Compare commits
169
Commits
main
...
ff63fc7c87
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ff63fc7c87 | ||
|
|
582f6278c1 | ||
|
|
5c6ee7d68f | ||
|
|
56ee10cc23 | ||
|
|
085e3c01d1 | ||
|
|
18270779fc | ||
|
|
46cfa744a1 | ||
|
|
ff7001f4be | ||
|
|
870cdb25e9 | ||
|
|
0261da6fd6 | ||
|
|
7c1efa5adc | ||
|
|
21fcf45fab | ||
|
|
4566f319b5 | ||
|
|
fe4827ccb3 | ||
|
|
e8842e6e06 | ||
|
|
1935e8e047 | ||
|
|
d51ff3bee4 | ||
|
|
068614ef11 | ||
|
|
02f0473bfc | ||
|
|
4e4553cdc8 | ||
|
|
b86cd605c4 | ||
|
|
109297ca4c | ||
|
|
133af8dfe5 | ||
|
|
5b2143fcb7 | ||
|
|
9648a9d1ed | ||
|
|
d626fadbfd | ||
|
|
88be9b1cb2 | ||
|
|
704622cf65 | ||
|
|
8b67b1a46c | ||
|
|
74faa55f41 | ||
|
|
b7a852ac92 | ||
|
|
dd3a74afcd | ||
|
|
40702aef2a | ||
|
|
3fc43eb7ad | ||
|
|
bc04330a27 | ||
|
|
cf5df70c62 | ||
|
|
5536093894 | ||
|
|
87b6e7a4b0 | ||
|
|
235e483bfb | ||
|
|
e7f08052f4 | ||
|
|
0ba15b7862 | ||
|
|
b005d6a44a | ||
|
|
08d3dd061b | ||
|
|
510e9c4863 | ||
|
|
ebb828a495 | ||
|
|
dae052f400 | ||
|
|
32bd4f6e4a | ||
|
|
1daa4f3cd1 | ||
|
|
1a24d4e1b6 | ||
|
|
51fa7c1a88 | ||
|
|
c7558ccbeb | ||
|
|
212d2fa5c4 | ||
|
|
d90e7ca2b0 | ||
|
|
79925595b5 | ||
|
|
e303cb3a4b | ||
|
|
6fc6e9e3c5 | ||
|
|
7c2454fe43 | ||
|
|
9f6f916063 | ||
|
|
dc88fdef10 | ||
|
|
1e2d55f158 | ||
|
|
f494fc283d | ||
|
|
9de0027ddc | ||
|
|
92d54dcc45 | ||
|
|
b1392db7af | ||
|
|
411c7ef3f5 | ||
|
|
19d6db7064 | ||
|
|
1ae4c6f865 | ||
|
|
8333a46497 | ||
|
|
2fc7bab78a | ||
|
|
439f37d68f | ||
|
|
bca6fd09eb | ||
|
|
1611ec0bfe | ||
|
|
b23b4e4161 | ||
|
|
4e02cdc351 | ||
|
|
07d9b7441c | ||
|
|
bb3d759f3a | ||
|
|
d1abc4951a | ||
|
|
0017093626 | ||
|
|
3efe049bb5 | ||
|
|
74dbbe0b1a | ||
|
|
cdef95ffcb | ||
|
|
a9a4f6c6ef | ||
|
|
567b5e134f | ||
|
|
8f73779a21 | ||
|
|
e98d5d33eb | ||
|
|
cad81223e5 | ||
|
|
713122d53a | ||
|
|
bfa4c1464a | ||
|
|
3296189093 | ||
|
|
c22c37e0b3 | ||
|
|
d32fc9f8d7 | ||
|
|
50010da88d | ||
|
|
7f9a0eef0f | ||
|
|
037e695a31 | ||
|
|
9ea1365b66 | ||
|
|
6bbd78fc8e | ||
|
|
c9e76fde2d | ||
|
|
ae9e5529e8 | ||
|
|
5783212377 | ||
|
|
1da6bf2f99 | ||
|
|
f0530b15bb | ||
|
|
09251496c0 | ||
|
|
9977d14605 | ||
|
|
2c00cc3407 | ||
|
|
444910b6f0 | ||
|
|
56f953f0bb | ||
|
|
a9e0555516 | ||
|
|
88cbe41f72 | ||
|
|
89ac955072 | ||
|
|
8bf54ec168 | ||
|
|
e565b1d4c9 | ||
|
|
e112819f64 | ||
|
|
f4d29d8ee8 | ||
|
|
69bdc8adec | ||
|
|
169ffe6b88 | ||
|
|
7bc402a1fb | ||
|
|
539f287a67 | ||
|
|
84e6f0752e | ||
|
|
63f60134ea | ||
|
|
e41d9560ba | ||
|
|
c2db4f69c6 | ||
|
|
2e2c68de07 | ||
|
|
ed19f16c70 | ||
|
|
a64f514db2 | ||
|
|
7a9932f095 | ||
|
|
72f591dd21 | ||
|
|
d07d6add04 | ||
|
|
1b30f15c02 | ||
|
|
fcee6892bf | ||
|
|
cb123e3774 | ||
|
|
a2b71e2472 | ||
|
|
4de9f32e31 | ||
|
|
5e0ae94ba2 | ||
|
|
996fb3f7a5 | ||
|
|
55a4e282ad | ||
|
|
d76afd7f25 | ||
|
|
815f76116f | ||
|
|
7ee7ab7ec5 | ||
|
|
fdd762b081 | ||
|
|
71fc027134 | ||
|
|
ee7fdec541 | ||
|
|
32caa21308 | ||
|
|
684795a2de | ||
|
|
a4562b2b23 | ||
|
|
a47c6564ab | ||
|
|
98ea948ffa | ||
|
|
5d0e544878 | ||
|
|
c30cf7e457 | ||
|
|
adce82beaa | ||
|
|
ed47836c98 | ||
|
|
77a99e83ce | ||
|
|
bd478ce09c | ||
|
|
4c3b4d29c4 | ||
|
|
445738e830 | ||
|
|
352ba477b4 | ||
|
|
4d1639f7c5 | ||
|
|
26bacdb304 | ||
|
|
7fa02d16be | ||
|
|
f78c9dc6fd | ||
|
|
ae60cd68a2 | ||
|
|
0540bef07b | ||
|
|
59763c9af5 | ||
|
|
1069c727c8 | ||
|
|
53660adcce | ||
|
|
42376c6693 | ||
|
|
9761b40eb5 | ||
|
|
7255b8ec30 | ||
|
|
ca78f0a8e5 | ||
|
|
aaef6cf5b7 |
No files matched your search
@@ -19,7 +19,7 @@ The smallest module and route that shows it:
|
||||
## Environment
|
||||
|
||||
- green-tea version:
|
||||
- Runtime and version: <!-- Node 20.11 / Deno 2.1 / Bun 1.1 / Cloudflare Workers -->
|
||||
- Runtime and version: <!-- e.g. Node 22.20 / Deno 2.5 / Bun 1.3 / Cloudflare Workers -->
|
||||
- OS:
|
||||
|
||||
<!--
|
||||
|
||||
@@ -11,6 +11,7 @@ Closes #
|
||||
- [ ] 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
|
||||
- [ ] The runtime suites this change touches pass locally (`npm run test:deno`, `test:bun`, `test:edge`, or `test:all`), and they are named here
|
||||
- [ ] 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
|
||||
@@ -13,7 +13,7 @@ jobs:
|
||||
if: github.event_name == 'pull_request'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Every commit needs a Signed-off-by
|
||||
@@ -38,10 +38,10 @@ jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: '18'
|
||||
node-version: '22'
|
||||
- run: npm ci
|
||||
- run: npm run lint
|
||||
- run: npm run format:check
|
||||
@@ -49,6 +49,10 @@ jobs:
|
||||
- run: npm run typecheck
|
||||
- run: npm test
|
||||
- run: npm run build
|
||||
# The committed reports in api/ are the frozen surface (CARD-22, D20). A PR that changes a
|
||||
# public type fails here until it regenerates them with `npm run api`, so the change shows up
|
||||
# in the diff a reviewer reads instead of only in the published declarations.
|
||||
- run: npm run api:check
|
||||
# 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
|
||||
@@ -73,8 +77,8 @@ jobs:
|
||||
matrix:
|
||||
runtime: [deno, bun, edge]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: '22'
|
||||
# All three need the dependency tree: the edge suite drives workerd from a Node process, and
|
||||
|
||||
@@ -31,7 +31,7 @@ jobs:
|
||||
if: ${{ github.server_url != 'https://github.com' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0 # full history for a clean push
|
||||
- name: Push to GitHub
|
||||
|
||||
@@ -18,8 +18,8 @@ jobs:
|
||||
id-token: write # OIDC for Trusted Publishing (also enables provenance)
|
||||
contents: write # create the GitHub release for this tag
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: '22'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
|
||||
@@ -19,8 +19,8 @@ jobs:
|
||||
if: ${{ github.server_url != 'https://github.com' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: '22'
|
||||
- run: npm ci
|
||||
|
||||
@@ -21,6 +21,9 @@ coverage/
|
||||
|
||||
# Edge (Miniflare) test bundle artifact
|
||||
test/edge/_worker.mjs
|
||||
test/edge/_parity-worker.mjs
|
||||
test/edge/_compression-worker.mjs
|
||||
test/edge/_dist-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.
|
||||
|
||||
@@ -55,6 +55,20 @@ feature/* → develop → main → [promote.yml] → GitHub main
|
||||
|
||||
**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.
|
||||
|
||||
**`tea pr merge` cannot do the promotion.** The CLI offers `merge`, `rebase`, `squash` and `rebase-merge`, and every one of them births a commit on `main` — the drift this section exists to prevent. Gitea's API has the style the CLI lacks, so promote through it:
|
||||
|
||||
```bash
|
||||
curl -X POST -H "Authorization: token $TOKEN" -H 'Content-Type: application/json' \
|
||||
-d '{"Do":"fast-forward-only"}' \
|
||||
"$GITEA_URL/api/v1/repos/$REPO/pulls/<n>/merge"
|
||||
```
|
||||
|
||||
`$GITEA_URL` and `$REPO` are yours to fill in — this file is mirrored to a public repository, and
|
||||
the address of a private forge is not something to publish. `fast-forward-only` is the part that
|
||||
matters and is the part the CLI does not offer.
|
||||
|
||||
A `405 Not all required status checks successful` means the pull request's own CI has not finished — `main` is protected, and a promotion runs its own checks rather than inheriting `develop`'s. Wait for them; the call is the same afterwards.
|
||||
|
||||
**Delete the branch when the work lands.** Both sides, as the last step of merging rather than a chore left for later:
|
||||
|
||||
```bash
|
||||
|
||||
+118
-37
@@ -4,9 +4,9 @@
|
||||
|
||||
## Environment
|
||||
|
||||
- **Date**: 2026-09-22
|
||||
- **Commit**: daf0fed
|
||||
- **Node**: v22.22.2
|
||||
- **Date**: 2026-10-29
|
||||
- **Commit**: 4566f31
|
||||
- **Node**: v22.23.1
|
||||
- **OS**: linux
|
||||
- **CPU**: AMD Ryzen 7 3700X 8-Core Processor (16 cores)
|
||||
- **RAM**: 67 GB
|
||||
@@ -29,72 +29,72 @@
|
||||
|
||||
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| raw-http | 41,631 | 2.00 | 3.00 | 4.00 | 0.6% | 41,343–41,974 |
|
||||
| nestjs-fastify | 32,419 | 3.00 | 4.00 | 6.00 | 0.5% | 32,103–32,583 |
|
||||
| fastify | 32,170 | 3.00 | 3.00 | 5.00 | 1.3% | 31,236–32,356 |
|
||||
| green-tea | 29,777 | 3.00 | 6.00 | 7.00 | 0.4% | 29,557–29,873 |
|
||||
| express | 10,546 | 8.00 | 13.00 | 18.00 | 0.4% | 10,480–10,625 |
|
||||
| nestjs-express | 9,680 | 9.00 | 15.00 | 21.00 | 0.6% | 9,567–9,739 |
|
||||
| raw-http | 47,469 | 2.00 | 3.00 | 4.00 | 0.6% | 47,193–48,004 |
|
||||
| green-tea | 37,599 | 2.00 | 3.00 | 5.00 | 0.5% | 37,162–37,654 |
|
||||
| fastify | 36,740 | 2.00 | 3.00 | 4.00 | 0.6% | 36,641–37,244 |
|
||||
| nestjs-fastify | 36,205 | 2.00 | 3.00 | 4.00 | 0.7% | 35,969–36,627 |
|
||||
| express | 11,099 | 8.00 | 12.00 | 14.00 | 0.6% | 11,000–11,183 |
|
||||
| nestjs-express | 10,067 | 9.00 | 13.00 | 16.00 | 0.5% | 9,991–10,122 |
|
||||
|
||||
### Route param
|
||||
|
||||
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| raw-http | 41,756 | 2.00 | 3.00 | 4.00 | 1.1% | 40,953–42,017 |
|
||||
| fastify | 31,708 | 3.00 | 4.00 | 5.00 | 0.5% | 31,359–31,847 |
|
||||
| nestjs-fastify | 29,880 | 3.00 | 4.00 | 6.00 | 0.3% | 29,745–29,961 |
|
||||
| green-tea | 28,706 | 3.00 | 6.00 | 7.00 | 0.6% | 28,562–29,051 |
|
||||
| express | 10,376 | 9.00 | 12.00 | 17.00 | 0.4% | 10,364–10,453 |
|
||||
| nestjs-express | 9,257 | 10.00 | 15.00 | 21.00 | 0.2% | 9,244–9,285 |
|
||||
| raw-http | 47,661 | 2.00 | 3.00 | 4.00 | 0.7% | 47,062–48,028 |
|
||||
| fastify | 36,135 | 2.00 | 3.00 | 4.00 | 0.5% | 35,868–36,391 |
|
||||
| green-tea | 35,001 | 2.00 | 4.00 | 5.00 | 0.2% | 34,879–35,088 |
|
||||
| nestjs-fastify | 33,253 | 3.00 | 3.00 | 4.00 | 0.8% | 32,969–33,756 |
|
||||
| express | 10,889 | 8.00 | 12.00 | 14.00 | 0.2% | 10,872–10,925 |
|
||||
| nestjs-express | 9,589 | 10.00 | 14.00 | 16.00 | 0.5% | 9,535–9,676 |
|
||||
|
||||
### Pipeline (3 steps) (approximation)
|
||||
|
||||
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| raw-http | 39,897 | 2.00 | 3.00 | 5.00 | 0.6% | 39,847–40,441 |
|
||||
| fastify | 31,436 | 3.00 | 4.00 | 6.00 | 0.6% | 31,079–31,563 |
|
||||
| nestjs-fastify | 29,403 | 3.00 | 4.00 | 6.00 | 0.6% | 29,151–29,689 |
|
||||
| green-tea | 26,839 | 3.00 | 6.00 | 8.00 | 0.1% | 26,783–26,872 |
|
||||
| express | 10,365 | 9.00 | 12.00 | 18.00 | 1.3% | 10,171–10,542 |
|
||||
| nestjs-express | 9,256 | 10.00 | 15.00 | 22.00 | 0.5% | 9,187–9,302 |
|
||||
| raw-http | 46,361 | 2.00 | 3.00 | 4.00 | 0.2% | 46,192–46,509 |
|
||||
| fastify | 35,329 | 2.00 | 3.00 | 5.00 | 0.5% | 35,027–35,536 |
|
||||
| green-tea | 33,375 | 2.00 | 3.00 | 5.00 | 0.5% | 33,092–33,569 |
|
||||
| nestjs-fastify | 32,767 | 3.00 | 3.00 | 4.00 | 0.5% | 32,559–32,995 |
|
||||
| express | 10,936 | 8.00 | 13.00 | 14.00 | 0.8% | 10,755–11,024 |
|
||||
| nestjs-express | 9,605 | 10.00 | 14.00 | 17.00 | 0.7% | 9,485–9,652 |
|
||||
|
||||
### POST JSON + validation
|
||||
|
||||
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| raw-http | 31,783 | 3.00 | 5.00 | 6.00 | 0.4% | 31,517–31,825 |
|
||||
| green-tea | 22,005 | 4.00 | 7.00 | 9.00 | 0.7% | 21,736–22,187 |
|
||||
| fastify | 20,430 | 4.00 | 8.00 | 9.00 | 0.4% | 20,398–20,601 |
|
||||
| nestjs-fastify | 18,597 | 4.00 | 8.00 | 11.00 | 0.2% | 18,540–18,658 |
|
||||
| express | 8,440 | 11.00 | 16.00 | 24.00 | 0.3% | 8,408–8,492 |
|
||||
| nestjs-express | 7,666 | 12.00 | 18.00 | 26.00 | 0.3% | 7,645–7,703 |
|
||||
| raw-http | 34,945 | 2.00 | 3.00 | 5.00 | 0.4% | 34,637–35,079 |
|
||||
| fastify | 28,345 | 3.00 | 4.00 | 6.00 | 0.4% | 28,239–28,537 |
|
||||
| green-tea | 24,495 | 4.00 | 5.00 | 7.00 | 0.5% | 24,379–24,745 |
|
||||
| nestjs-fastify | 24,103 | 4.00 | 6.00 | 7.00 | 0.8% | 23,729–24,164 |
|
||||
| express | 9,019 | 10.00 | 14.00 | 22.00 | 0.4% | 8,985–9,084 |
|
||||
| nestjs-express | 8,107 | 11.00 | 17.00 | 26.00 | 0.4% | 8,078–8,166 |
|
||||
|
||||
## Step-scaling (green-tea)
|
||||
|
||||
| Path | Steps | req/s |
|
||||
| --- | --- | --- |
|
||||
| /steps/0 | 0 | 29,196 |
|
||||
| /steps/3 | 3 | 26,564 |
|
||||
| /steps/5 | 5 | 25,314 |
|
||||
| /steps/0 | 0 | 36,423 |
|
||||
| /steps/3 | 3 | 32,436 |
|
||||
| /steps/5 | 5 | 30,549 |
|
||||
|
||||
Each additional pipeline step costs roughly 776 req/s (-13.3% over 5 steps), on this box.
|
||||
Each additional pipeline step costs roughly 1,175 req/s (-16.1% over 5 steps), on this box.
|
||||
|
||||
## green-tea across runtimes
|
||||
|
||||
| Scenario | node | deno | bun |
|
||||
| --- | --- | --- | --- |
|
||||
| JSON hello (overhead) | 30,379 | 51,888 | 46,300 |
|
||||
| Route param | 29,204 | 51,786 | 42,788 |
|
||||
| Pipeline (3 steps) | 27,208 | 50,692 | 39,644 |
|
||||
| POST JSON + validation | 22,609 | 35,743 | 31,960 |
|
||||
| JSON hello (overhead) | 38,119 | 61,792 | 54,428 |
|
||||
| Route param | 35,335 | 61,919 | 48,444 |
|
||||
| Pipeline (3 steps) | 33,776 | 59,521 | 44,956 |
|
||||
| POST JSON + validation | 24,759 | 38,561 | 35,268 |
|
||||
|
||||
Same application, same built bundle, same box — only the runtime differs. Read across a row, never against the cross-framework tables above: those measure other frameworks on Node, and nobody ran fastify on Bun here. A runtime that is not installed is absent rather than zero.
|
||||
## Cost of secure-by-default (green-tea)
|
||||
|
||||
| Label | req/s |
|
||||
| --- | --- |
|
||||
| security:false (parity) | 29,777 |
|
||||
| security:true (default) | 28,919 |
|
||||
| security:false (parity) | 37,599 |
|
||||
| security:true (default) | 36,508 |
|
||||
|
||||
The real cost of running secure-by-default (rather than the parity-mode `security:false` used above) is ~2.9% req/s on this box.
|
||||
|
||||
@@ -136,6 +136,87 @@ was benchmarked as it landed — the numbers are still in the code, cited below
|
||||
file between `26.7` and `26.9`, so nothing added them up. That is the gap this section and
|
||||
`npm run bench:compare` exist to close.
|
||||
|
||||
### The release gate: `26.9.0-beta.2` → RC.1 (`4566f31`)
|
||||
|
||||
Fifteen cases on all three runtimes this time, because the previous gate measured Node alone and
|
||||
Deno was the runtime that drifted. Both trees ran on one box in one sitting. Each round alternated
|
||||
which side went first, and both sides shared one `node_modules`. The runs used a `node:22` container
|
||||
pinned to four cores (`--cpuset-cpus 6,7,14,15`), so the absolute numbers are not comparable with
|
||||
the gates below. Only the Δ carries over. Medians of four rounds; an A/A run on the same setup moves
|
||||
within ±4%. A Δ marked † has overlapping ranges and says nothing:
|
||||
|
||||
| Scenario | Node | Deno | Bun |
|
||||
| --- | --- | --- | --- |
|
||||
| hello | +15.0% | −4.1% † | −0.6% † |
|
||||
| param | +7.7% | −8.2% | −4.3% |
|
||||
| pipeline (3 steps) | +14.2% | −3.4% † | −2.9% † |
|
||||
| steps5 | +13.6% | −3.4% | −2.8% † |
|
||||
| validate (POST) | −2.5% † | −6.1% | −2.3% |
|
||||
| hello + security | +12.6% | −5.7% | −1.9% † |
|
||||
| hello + cors predicate | +14.8% | −3.7% † | −2.5% † |
|
||||
| preflight + cors predicate | −3.2% | −7.5% | −0.9% |
|
||||
| param, 50 routes | +14.4% | −5.2% | +0.8% † |
|
||||
| param, 200 routes | **+21.4%** | **+13.9%** | **+23.6%** |
|
||||
| json 8KB uncompressed | +1.6% | −2.4% † | −0.9% † |
|
||||
|
||||
Node got faster almost everywhere. The Node path stopped doing per-request work it did not need,
|
||||
and the radix router replaced a matcher that walked past every candidate. Bun is flat apart from
|
||||
`param`. Deno lost 3% to 8% on the small cases. These figures are the remainder after the changes
|
||||
below:
|
||||
|
||||
- **The router is about 5% of it, and it was accepted on purpose.** The radix index costs Deno
|
||||
roughly 5% on a parameterised route in a small table, and it is the reason every runtime gains
|
||||
14% to 24% at two hundred routes. The router's gate allowed up to +5% at ten routes, and this cost
|
||||
is within it.
|
||||
- **Two added features cost Deno more than they had to, and both were fixed before this run.** The
|
||||
health probes made `app.fetch` await the boot on every request, which cost 6% on Deno. Cookie
|
||||
support had also added per-request work to the fetch adapter. Both fixes are in this tree.
|
||||
- **`ctx.ip` resolution became lazy.** The first attempt at it used getters on an object literal.
|
||||
V8 and JavaScriptCore both treat that as a slow object, and it cost Node and Deno 15% to 24%. The
|
||||
getters moved onto a class prototype before the change merged, and the merged version measures
|
||||
flat.
|
||||
- **What remains on Deno is not pinned to a single change.** It is the per-request work that came
|
||||
with this release's features, such as cookies, ETags and the reserved mesh route, spread thinly
|
||||
enough that no one removal recovers it.
|
||||
|
||||
#### Compression is new, so there is no `beta.2` number to compare it with
|
||||
|
||||
`26.9.0-beta.2` has no compression. On these rows the base side served the same 8 KB body
|
||||
uncompressed, so the Δ is what turning compression on costs rather than a regression:
|
||||
|
||||
| Scenario | Node | Deno | Bun |
|
||||
| --- | --- | --- | --- |
|
||||
| hello + compression | +4.9% † | −2.2% † | −3.5% |
|
||||
| json 8KB + compression, identity | −5.3% | −10.7% | −5.0% |
|
||||
| json 8KB + gzip | −36.3% | −59.3% | −42.4% |
|
||||
| json 8KB + br | −51.4% | −75.5% | −39.9% |
|
||||
|
||||
A body under the threshold costs nothing measurable, because no `Vary` is set on it any more.
|
||||
Before that change, Deno lost 25% on `hello + compression`. An identity response above the
|
||||
threshold still carries `Vary: Accept-Encoding`, as RFC 9110 requires. That header costs Deno about
|
||||
10% of a small request and Bun about 3%. Encoding 8 KB on every request is the price of the smaller
|
||||
response. These are loopback numbers, so the bandwidth the encoding saves does not appear in them.
|
||||
|
||||
#### Against the field
|
||||
|
||||
The cross-framework tables above were regenerated on the same box as September's, and that run was
|
||||
unpinned like September's. This box measured faster across the board this time: `raw-http` rose 10%
|
||||
to 16%. So the ratio to `raw-http` is the honest comparison, not the req/s:
|
||||
|
||||
| Scenario | green-tea, Sep | green-tea, now | fastify, Sep | fastify, now |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| JSON hello | 71.5% | **79.2%** | 77.3% | 77.4% |
|
||||
| Route param | 68.7% | **73.4%** | 75.9% | 75.8% |
|
||||
| Pipeline (3 steps) | 67.3% | **72.0%** | 78.8% | 76.2% |
|
||||
| POST JSON + validation | 69.2% | 70.1% | 64.3% | **81.1%** |
|
||||
|
||||
The previous gate described a shape: green-tea behind Fastify on `hello`, `param` and `pipeline`,
|
||||
and ahead of it on `validate`. That shape has now flipped at both ends. On `hello`, green-tea is
|
||||
ahead of Fastify on this box, by 2.3%. The gap on `param` and `pipeline` narrowed from 7-15% to
|
||||
3-6%. On `validate`, green-tea's own ratio barely moved. Fastify's rose 17 points between `5.11.0`
|
||||
and `5.12.7`, the version the lockfile now pins, and this file has not looked into which Fastify
|
||||
change did it. green-tea did not get slower at validation; Fastify got faster.
|
||||
|
||||
### The release gate: `26.9.0-beta.1` → `26.9.0-beta.2`
|
||||
|
||||
Ten cases, both trees on one box in one sitting, alternating which side ran first each round, sharing
|
||||
|
||||
+558
-2
@@ -6,6 +6,562 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
green-tea uses calendar versioning: `YY.M.PATCH` — the month is not zero-padded, since
|
||||
npm treats versions as semver and semver forbids leading zeros.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Breaking
|
||||
|
||||
- **Response header values are `string | string[]`** (#113, D11). `TransformerFn`, `ErrorResponse.headers`,
|
||||
`HttpError.headers` / `HttpErrorLike.headers` and the pipeline's `ResponseShape.headers` widen from
|
||||
`Record<string, string>`, so a response can carry several `Set-Cookie` lines. Code that *produces*
|
||||
headers is unaffected; code that *reads* `headers[k]` from one of these types as a `string` stops
|
||||
compiling and must handle the array. A `set-cookie` array is sent as one header line per element
|
||||
on Node, Deno, Bun and the edge — before, the fetch adapters stringified it into one broken
|
||||
`a,b` cookie. Any other array is sent as one line joined with `, `. Injected security and CORS
|
||||
headers stay authoritative, and a handler's `vary` array is merged with the injected one.
|
||||
|
||||
- **Node 18 and Node 20 are no longer supported; the minimum is Node 22.** Both are end-of-life
|
||||
and receive no security patches, so `engines.node` is now `>=22`, CI runs Node 22 only, and the
|
||||
build targets `node22`. Node 22 is the oldest line still maintained. The `node:crypto` fallback
|
||||
for Node 18's missing global `crypto` is removed with it.
|
||||
|
||||
- **Inbound WebSocket messages are capped at 1 MiB by default** (#107). Node used `ws`'s own
|
||||
default of 100 MiB, and Deno, Bun and the edge applied no cap of their own, so one client could
|
||||
make the server hold a message of any size the runtime would accept. A larger message now closes
|
||||
the connection with `1009` (`message too large`). Raise it with `limits.maxWsMessageBytes`.
|
||||
|
||||
- **A connection with 16 unread inbound messages is closed on the 17th** (#107), with `1013`
|
||||
(`inbound queue full`). The queue behind `inbound` was unbounded on every runtime, so a handler
|
||||
that read slowly — or never — let a client grow it without limit. This also reaches a `@Ws`
|
||||
handler that never reads `inbound` at all: on Node those frames used to be discarded, and they
|
||||
now count. Raise the bound with `limits.maxWsQueue`.
|
||||
|
||||
- **A constrained route param that ties with a sibling, or makes one unreachable, now fails boot**
|
||||
(#127). Before, the router picked by registration order, and nothing reported it.
|
||||
Two routes of the same method that branch at the same segment under the same prefix fail
|
||||
`createApp` when:
|
||||
|
||||
- both are constrained, their constraints accept a common segment, and the rest of both patterns
|
||||
can match one request. The error names both declarations and a witness:
|
||||
`/u/:id(\d+)` + `/u/:n(\d{1,3})` → `both match '0' (GET /u/0)`. Different spellings of one
|
||||
language (`\d+` and `[0-9]+`) count. `/u/:id(\d+)/a` + `/u/:n(\d{1,3})/b` share digits but
|
||||
no request, so they still boot.
|
||||
- a plain param is next to a constraint that accepts every segment (`[^]*`, `[\s\S]+`) and
|
||||
outranks it. The error names the dead route and the one that wins.
|
||||
|
||||
A plain param next to a constraint that leaves some segments over is the fallback pattern and
|
||||
still boots: `/u/:id(\d+)` + `/u/:slug` routes digits to `:id` and everything else to `:slug`. An
|
||||
unescaped `.` does not match line terminators, so `/algo/:a(.*)` leaves `/algo/%0A` to a plain
|
||||
sibling, and that pair boots too.
|
||||
|
||||
WebSocket routes are checked under their own precedence, which is declaration order. So a plain
|
||||
WS param declared before a constrained one now fails as unreachable. A `@Stream` route sits in
|
||||
both tables and is checked under both. Mesh routes exported by different teapots are checked
|
||||
against each other. A local route against a remote one keeps the deliberate local override and
|
||||
its warning.
|
||||
|
||||
To fix a pair that now fails, make the router's choice explicit. Make the two constraints
|
||||
disjoint (`\d{1,3}` and `\d{4,}`), keep one route and branch inside its handler, or move one
|
||||
under a static segment of its own (`/u/:id(\d+)` and `/u/short/:n(\d{1,3})`). A plain param
|
||||
reported as unreachable never answered a request: delete it, or narrow the constraint that
|
||||
shadows it so some segments are left over. For a WebSocket pair, declare the constrained route
|
||||
first.
|
||||
|
||||
The check is exact. The safe subset makes every constraint a sequence of (character set, min,
|
||||
max) blocks, and the check walks the product of two such sequences. It costs
|
||||
O(|A|·|B|·(|A|+|B|)·K) per pair, with K ≤ 2048. Measured at under 0.1 ms for `\d{0,2048}`
|
||||
against `[0-9]{0,2048}`, and about 90 ms for the largest product the 128-character limit allows.
|
||||
It runs once at boot, and lookup is unchanged. One case is not compared yet: two *different*
|
||||
constraints at a later segment of an otherwise unreachable route. The route then boots, as
|
||||
before.
|
||||
|
||||
- **Edge WebSocket upgrades no longer trust `cf-connecting-ip` by default** (#119). `edgeHandler`
|
||||
copied the header into `ctx.ip` on every upgrade, so any client that sent it chose its own
|
||||
address. It now counts only under `trustProxy: true`, the same rule HTTP follows. Without it,
|
||||
`ctx.ip` on an edge WebSocket is `''`, as it already was on edge HTTP: workerd exposes no peer
|
||||
address. An app behind Cloudflare that keys anything on the WebSocket IP needs
|
||||
`createApp({ trustProxy: true })`.
|
||||
- **A token has one producer: a second one fails `createApp`** (GitHub #35). The graph kept the
|
||||
last node registered for a token, and plugin nodes are registered after module nodes, so a
|
||||
plugin whose `scope.add` provided `user` silently replaced the app's own `@Provider({ provides:
|
||||
'user' })` for every route that needed it. Boot now fails instead, naming both nodes and where
|
||||
they came from: `token 'user' is provided twice: by 'user' (module:AppModule) and by 'shadow'
|
||||
(plugin)`. The rule covers the whole graph (modules, plugins, mesh steps spliced at boot, and
|
||||
the built-ins `logger`, `rooms` and `events`), so a plugin node that provides `logger` under
|
||||
another name fails as well, whatever order things are registered in. `overrides` keep working:
|
||||
they replace the runner of an existing token and add no producer. Observer steps that provide
|
||||
nothing are unaffected. The official plugins already follow name = node name = token.
|
||||
- **`/__mesh__/control` is reserved in every app, mesh or not** (#126). A `@Ws`, `@Stream` or HTTP
|
||||
route that claims it — `@Ws('/__mesh__/control')`, `@Get('/__mesh__/control')`,
|
||||
`@Ws('/__mesh__/:x')`, `/__mesh__/:rest*`, or a mountpoint that adds up to one of these — now
|
||||
fails `createApp`, naming the declaration and the reserved path. A route exported by a teapot is
|
||||
checked the same way, and fails the teacup's boot. Before, the Node listener served a user route
|
||||
there whenever no mesh control channel was configured, while `app.upgrade` (Deno, Bun, the edge)
|
||||
always refused it, so the same route worked on one runtime and not the others. A pattern whose
|
||||
first segment is not the literal `__mesh__` (`/:org/:repo`, `/:rest*`) still boots; the reserved
|
||||
path is answered ahead of the route table on every runtime, so such a route never sees it.
|
||||
To migrate, move the route to another path, for example `/mesh/control`. Nothing replaces
|
||||
`/__mesh__/control` itself: it never reached the route on Deno, Bun or the edge.
|
||||
|
||||
An upgrade to `/__mesh__/control` on an app with no control channel is now refused identically
|
||||
everywhere: the Node listener accepts it and closes `1008` with
|
||||
`mesh control channel not enabled: this app exports nothing, or has no mesh.secret`, as
|
||||
`app.upgrade` already did. An app with no `@Ws`/`@Stream` routes and no mesh attaches no upgrade
|
||||
listener on Node, as before, so there the request still reaches the HTTP route table.
|
||||
|
||||
- **Static files are revalidated, not re-downloaded** (#114, D12). Every static hit carries a weak
|
||||
`ETag` (`W/"<size>-<mtime>"`), `Last-Modified` and `Cache-Control: no-cache`. A matching
|
||||
`If-None-Match`, or `If-Modified-Since` when there is no `If-None-Match`, answers `304` from the
|
||||
file's `stat` without reading it. A `HEAD` no longer reads the file either. `no-cache` stops
|
||||
browsers from reusing a file for a lifetime they guessed from `Last-Modified`. To keep the old
|
||||
behaviour, set `static: { cacheControl }` to whatever your proxy expects.
|
||||
|
||||
- **A node that needs the token it provides fails `createApp`** (GitHub #43). The graph check
|
||||
skipped a dependency whose producer was the node itself, so a step with `needs: ['user']` and
|
||||
`provides: ['user']` booted, and at request time read a value nobody had written. It now fails
|
||||
as the cycle it is, naming the token and the fix: `cycle detected: auth -> auth (it needs 'user',
|
||||
which only it provides). Remove 'user' from its needs, or move the work that produces 'user' into
|
||||
a step it needs.` Since a token has one producer (GitHub #35), no other node can supply it; only a seeded
|
||||
token (`req`, `params`) still satisfies a node's own need, because the node reads the seed.
|
||||
`overrides` do not exempt the node: they replace its runner after the graph is checked. To
|
||||
migrate, remove the token from the node's `needs`, or move the work that produces it into a
|
||||
separate provider or step the node needs.
|
||||
|
||||
- **A handler that returns `undefined` answers `204 No Content`** (GitHub #38). The default JSON
|
||||
transformer passed the value to `JSON.stringify`, which returns `undefined` rather than a string:
|
||||
the Node server sent an empty `200` with `content-type: application/json`, and the fetch adapter
|
||||
threw a `TypeError`, so Deno, Bun and the edge answered `500` for a handler that did nothing
|
||||
wrong. Every runtime now sends `204` with no body and no `content-type`. A handler that returns
|
||||
`null` still gets `200` with `null`. A client that checked for `200` after a handler with no
|
||||
`return` sees `204` instead; return a value to keep a `200`. A route with its own `@Transformer`
|
||||
is not affected.
|
||||
|
||||
- **`serveDeno()` and `serveBun()` reject an app created with `tls`.** Only Node's `listen()` ever
|
||||
read `tls`; Deno and Bun serve through their runtime's own listener, so the same app came up as
|
||||
plain HTTP there, without a word, for someone who had asked for HTTPS. Both adapters now reject
|
||||
before they boot or bind. Migrate by dropping `tls` from `createApp` and configuring TLS on the
|
||||
runtime's server, or terminating it at a proxy. An app without `tls` is unaffected.
|
||||
|
||||
### Added
|
||||
|
||||
- **Every type a public signature uses can now be imported.** These were already in the
|
||||
declarations, but nothing exported them, so code could call the API and could not name what it
|
||||
passed or got back. From the root: `ModuleOptions`, `Ctor`, `BusLike`, `ArgSource`,
|
||||
`GraphNodeView`, `GraphRouteView`, `StandardIssue`, `StandardResult`, and, for the experimental
|
||||
mesh (tagged `@experimental`, outside the freeze), `Link`, `ReconnectOptions`, `ManifestPolicy`, `SocketCtor`, `EventfulSocket`, `RouteEntry`,
|
||||
`RemoteScopeNode`, `RemoteRoute`, `MeshControlDeps` and `ResponseShape`. From `/deno`:
|
||||
`DenoServeOptions` and `DenoHttpServer`. From `/bun`: `BunServeOptions` and `BunServer`. From
|
||||
`/edge`: `EdgeCtx`. All of them are additions, and nothing was renamed.
|
||||
|
||||
- **Health probes: `createApp({ health: true })`** (#115). Off by default. `GET`/`HEAD /__live__`
|
||||
answers `200 {"status":"ok"}` whenever the process answers. `/__ready__` answers
|
||||
`503 {"status":"booting"}` until `boot()` resolves, then `200 {"status":"ok"}` or
|
||||
`200 {"status":"degraded","degraded":[…]}` (from `app.degraded()`), and
|
||||
`503 {"status":"draining"}` from the moment `close()` starts: Node `app.close()`, and the
|
||||
`close()` that `serveDeno()`/`serveBun()` return. Probes are answered by the adapter, ahead of
|
||||
`maxConcurrentRequests` and the route table, so they are never shed and run no step, provider,
|
||||
plugin or `onError`, and emit no lifecycle event (`logRequests` and metrics plugins do not see
|
||||
them). Security headers still apply, plus `cache-control: no-store`; other methods get `405` with
|
||||
`Allow: GET, HEAD`. While `health` is on, a route at either path fails the boot, local or spliced
|
||||
from a teapot. A probe through `app.fetch` before the boot starts the boot without waiting for it.
|
||||
|
||||
`health: { drainDelayMs }` (default 0) keeps the listener open that long after `close()` starts,
|
||||
with `/__ready__` already answering `503`, before connections drain. Without it Node closes idle
|
||||
keep-alive connections at once, so a probe usually sees a refused connection rather than a `503`.
|
||||
The window is spent out of the shutdown budget; `createApp` throws when `drainDelayMs` plus
|
||||
`teardownTimeoutMs` exceeds `shutdownTimeoutMs`, and on any `health` value other than `true`,
|
||||
`false` or `{ drainDelayMs?: number }`. On the edge there is no `close()`, so `/__ready__` never
|
||||
reports `draining` there.
|
||||
|
||||
- **`createApp({ compression })`** (#112, D13): response compression, off by default. `true`, or
|
||||
`{ threshold?, encodings? }` (default `1024` bytes and `['br', 'gzip']`, in preference order).
|
||||
`Accept-Encoding` is negotiated with q-values, `identity`, `*` and `q=0`, and ties go to server
|
||||
preference. Text, JSON, JavaScript, ndjson, SVG, XML and wasm are compressed. A response that
|
||||
already has `Content-Encoding` or `Content-Range`, has no `Content-Type`, or says
|
||||
`Cache-Control: no-transform` is left alone. `Vary: Accept-Encoding` is added wherever the request
|
||||
decided the outcome: identity clients, `HEAD` and every `304`. A body under the threshold gets
|
||||
none: it is sent identity whatever the client accepts, and Deno pays about 10% of a small request
|
||||
for the header (about 3% on Bun). On the edge, where Cloudflare encodes, every compressible
|
||||
response keeps `Vary`.
|
||||
`Content-Length` is dropped from an encoded body. SSE and ndjson streams are compressed too,
|
||||
flushed after every event, error frame and ping, so each event decodes when it arrives.
|
||||
Per runtime:
|
||||
- **Node and Bun:** async `node:zlib`, br at quality 4.
|
||||
- **Deno:** the same code, but Deno 2.9 runs zlib's async API on the main thread, so compression
|
||||
costs event-loop time there (about 4× slower than Node for a 51 KB gzip under load).
|
||||
- **Edge:** core never encodes and sets only `Vary`; Cloudflare applies the encoding. Edge is
|
||||
recognised through `edgeHandler` or by detecting workerd at `createApp`.
|
||||
|
||||
ETags (`etag: true`) are taken before encoding and stay the same across codings. No dependency;
|
||||
invalid options throw.
|
||||
|
||||
- **`createApp({ etag: true })`** (#114, D12): weak ETags for buffered `200` responses to `GET` and
|
||||
`HEAD`, from a 32-bit FNV-1a hash of the body plus its length. A matching `If-None-Match` (weak
|
||||
comparison, lists, `*`) gets a `304` with no body. A handler that sets its own `etag` keeps it, and
|
||||
that tag drives the comparison. Streams, non-200 responses and other methods are never tagged.
|
||||
The handler still runs. Off by default; anything but a boolean throws at `createApp`.
|
||||
- **`static: { dir?, cacheControl? }`** (#114): the object form of `static` sets the
|
||||
`Cache-Control` sent with static files and their `304`s (for example
|
||||
`'public, max-age=31536000, immutable'` for hashed assets). `static: true` and `static: '<dir>'`
|
||||
keep working. An unknown key, or a `cacheControl` with CR/LF, throws at `createApp`.
|
||||
|
||||
- **`@cookie('name')` / `@cookies()` argument decorators and `setCookie()`** (#113). Cookies are
|
||||
parsed from the request's `Cookie` header on first use per request (RFC 6265: first value wins,
|
||||
`%`-sequences decoded, malformed pairs skipped rather than answered with a 400), on HTTP and
|
||||
WebSocket routes; `@needs('cookies')` gives the same map. OpenAPI lists a cookie argument as an
|
||||
`in: cookie` parameter. `setCookie(name, value, options?)` returns a `Set-Cookie` value with
|
||||
`HttpOnly`, `SameSite=Lax`, `Path=/` and `Secure` by default (D10; `secure: false` opts out), and
|
||||
throws, naming the field, on a name outside the token set, a value with CR, LF, `;`, `,`,
|
||||
whitespace or a control character, an attribute with CR/LF, `;` or a control character, and on
|
||||
`sameSite: 'none'` or `partitioned` without `secure`. `parseCookies()` and `CookieOptions` are
|
||||
exported too. No dependency: signing and sessions stay out of core.
|
||||
|
||||
- **`limits.maxWsMessageBytes` and `limits.maxWsQueue`** (#107): per-connection bounds on inbound
|
||||
WebSocket messages, in bytes and in unread messages, server-wide on every runtime. `createApp`
|
||||
throws a `TypeError` for anything but a positive integer. Node and Bun refuse an oversized message
|
||||
before buffering it; Bun before 1.4 does so by dropping the connection, so its peer sees `1006`
|
||||
rather than `1009` (Bun 1.4 and later send `1009`). Deno and workerd expose no such option, so there the message is received in full and then
|
||||
refused, and its memory is bounded by the platform's own cap. Worst-case buffered inbound memory is
|
||||
about `maxConnections × maxWsQueue × maxWsMessageBytes`, ≈ 15.6 GiB at the Node defaults; Deno and
|
||||
Bun have no connection cap, so set one at the platform or proxy there.
|
||||
|
||||
- **`WsSocket.drained()`** (#41): an optional method an adapter's socket provides so the outbound
|
||||
pump can wait for its send buffer. It resolves once the buffer is at or below the adapter's
|
||||
high-water mark, or the socket has closed, and at once when it already is. The built-in adapters
|
||||
all provide it. A socket built without it is never waited on, as before.
|
||||
|
||||
- **Types you could see but not name are now exported** (D19): `AppOptions` (the options object of
|
||||
`createApp`, until now an inline type, so `const opts: AppOptions = …` works), `ExplainNode`
|
||||
(one entry of `Explain.chain`), and `WsRequest` / `WsSocket` (the arguments of `app.upgrade`).
|
||||
|
||||
- **`RequestHeaders`** (D19): the type of the incoming request headers, under a name that does not
|
||||
shadow the Fetch `Headers` global. `Headers` remains as a deprecated alias.
|
||||
|
||||
### Changed
|
||||
|
||||
- **The mesh's exports are marked `@experimental`** (D19): `connectLink`, `buildRemote`,
|
||||
`envelopeFrom`, `buildManifest`, `createMeshControl`, `MESH_CONTROL_PATH`, `Manifest`,
|
||||
`RequestEnvelope`, `Frame` and `MeshConfig`. They stay exported, unchanged. The mesh already needs
|
||||
`createApp({ experimental: true })`; the tag says the same thing in the types: these are outside
|
||||
the API freeze and may change in a minor release.
|
||||
- **Every `304` is bodiless** (#114). A `304` has no body and no `content-*` headers on any adapter,
|
||||
including one from `throw new NotModified()`, which used to go out with the default JSON
|
||||
envelope's `content-type`.
|
||||
|
||||
- **HTTP route lookup uses a radix index** (#109). The router used to scan a specificity-sorted
|
||||
list per method, and on every 404 and 405 it recompiled and matched every route to build `Allow`.
|
||||
It now walks a tree per method, built once from the route table, with mesh routes from teapots
|
||||
in a tree of their own. This is internal and changes no behaviour: the same route wins, with the
|
||||
same params, `Allow`, implicit `HEAD` and 404/405, checked against the frozen parity corpus.
|
||||
`graph()`, `explain()` and `openapi()` still read the declared routes, not the tree. Median lookup
|
||||
time against the old matcher (jarvis, `bench:lookup`): at 500 routes, static hit −54%, late
|
||||
param hit −88%, method miss −94%, path miss −96%; at 10 routes, every cell is within noise or
|
||||
faster (late param hit +3.4%, 95% CI −5.0…+12.6%).
|
||||
|
||||
- **A query string keeps every `?` after the first** (GitHub #48). `parseQuery` took the text
|
||||
between the first and second `?`, so `/search?q=what?now` gave `q: 'what'` and dropped the rest.
|
||||
RFC 3986 §3.4 allows `?` inside a query, so the query string is now everything after the first
|
||||
`?` and before `#`, if there is one: `q: 'what?now'`, and `/search?a=1&b=?` gives `b: '?'`. URLs
|
||||
with a single `?` parse as before. Path extraction is unchanged.
|
||||
|
||||
- **Mesh (alpha): a teacup's remote routes follow which teapots are connected** (#124, D15). The
|
||||
route table used to be built once at boot: a teapot that started late was never served, and a
|
||||
teapot that was gone for good stayed advertised. Now:
|
||||
|
||||
- A teapot that missed `bootTimeoutMs` is retried in the background with the `reconnect` backoff.
|
||||
When it connects, its routes are served, with no restart. Its steps are not added, because the
|
||||
graph was validated at boot without them. With `reconnect: false` it is not retried.
|
||||
- While a link is reconnecting, its routes stay and answer `503`, now with `retry-after` (the
|
||||
seconds until the next attempt). `Allow` keeps them.
|
||||
- A link that gives up for good has its routes removed: they answer `404` and leave `Allow`. That
|
||||
is a link dropped with `reconnect: false`, or one refused permanently (a wrong secret, a protocol
|
||||
mismatch) while reconnecting. A refused reconnect used to retry forever. It now stops.
|
||||
- A returning teapot's routes replace its old ones: a route it added is served, one it dropped
|
||||
answers `404`. A returning manifest is still refused for a missing **step**
|
||||
(`onManifestChange: 'refuse'`), but no longer for a missing route.
|
||||
- A late route that conflicts with another teapot's (same shape, or a CARD-13 sibling conflict)
|
||||
is refused and logged, and the rest keep serving. At boot the same conflict still fails boot.
|
||||
- A late or returning route on a reserved path (`/__mesh__/control`, and `/__live__`/`/__ready__`
|
||||
with `health` on) is refused and logged the same way. At boot it still fails boot.
|
||||
- Every change emits `mesh:routes` with `{ url, added, removed }` (new `EventPayload` fields).
|
||||
|
||||
Membership changes publish a new table. A request in flight routes against the old one or the
|
||||
new one, never a mix. Only the remote route trees are rebuilt. `listen()` now reads the same
|
||||
table as `app.fetch`, and `createHttpServer` accepts a getter as well as an array. Dev
|
||||
introspection routes (`devGraph`, `devOpenapi`) now sit before remote routes in that table, so
|
||||
in the one case where a teapot exports the same path at the same specificity, the dev route wins.
|
||||
|
||||
- **`ctx.ip` is resolved when it is read, not on every request.** The client address is now
|
||||
worked out the first time a step, a handler or a plugin such as rate-limit reads `ctx.ip`, and
|
||||
kept for the rest of the request. A route that never reads it pays nothing. The rules are
|
||||
unchanged: the first `x-forwarded-for` hop under `trustProxy`, otherwise the socket peer. What
|
||||
the address costs to resolve depends on the runtime:
|
||||
|
||||
| Runtime | Where the address comes from | Cost when read |
|
||||
| --- | --- | --- |
|
||||
| Node | `req.socket.remoteAddress`, cached by Node per connection | negligible |
|
||||
| Deno | `info.remoteAddr`, handed over by `Deno.serve` | negligible |
|
||||
| Bun | `server.requestIP()`, a native call per request | 7–11% of a small request |
|
||||
| edge | the `cf-connecting-ip` header, under `trustProxy` | negligible |
|
||||
|
||||
The Bun figure is what reading the address costs on every request. Before this change every Bun
|
||||
request paid it, whether anything read `ctx.ip` or not. Behind a proxy that sets
|
||||
`x-forwarded-for`, `trustProxy: true` takes the address from the header on every runtime and
|
||||
never asks the socket.
|
||||
|
||||
Measured against the previous commit, on a Ryzen 3700X with 4 pinned cores, 15 cases including
|
||||
gzip and brotli: Bun is 3–11% faster on every case that never reads `ctx.ip`; a `POST` gains
|
||||
about 1%, because the body read dominates it. Node and Deno are unchanged, within ±4%.
|
||||
|
||||
**Inside a stream body `ctx.ip` is `''`** unless a step or the handler read it before returning
|
||||
the stream. The body runs after the response has started, when the socket the address would come
|
||||
from may already be gone. A route that needs the address in a stream reads it first, as
|
||||
rate-limit already does.
|
||||
|
||||
- **The Node request path does less per request.** A request without a body (no
|
||||
`Transfer-Encoding`, no or a zero `Content-Length`, RFC 9112 §6.3), which is every `GET`, no
|
||||
longer touches the request stream at all. A JSON `POST` reads its body with stream
|
||||
listeners instead of `for await`, which cost a promise and a microtask per chunk; the response is
|
||||
written without an `async` wrapper when nothing needs awaiting, and without building the
|
||||
compression request when compression is off; the `content-length` limit check runs its shape test
|
||||
only for a body that would be refused. Behaviour is unchanged: the same `413`s, the same
|
||||
rejection when a client goes away mid-body.
|
||||
|
||||
- **The fetch adapter (Deno, Bun, workerd) regains what two earlier changes in this release cost.**
|
||||
Response headers that are all plain strings, which is nearly every response, now go to
|
||||
`new Response` as the record they already are, not copied into a `Headers` one by one. That copy,
|
||||
added with `set-cookie` arrays, cost 5–8% on every Deno request. A body with a well-formed
|
||||
`Content-Length` inside the limit is read with `arrayBuffer()`, not chunk by chunk. The runtime
|
||||
frames the body by that header, so the bounded read is kept only for chunked uploads. The chunked
|
||||
read, added for the incremental `413`, had cut a Bun JSON `POST` by more than half. Behaviour is
|
||||
unchanged: the same `413`s, and `set-cookie` arrays still reach the client one line per cookie.
|
||||
|
||||
- **`app.fetch` stops awaiting the boot once it has finished.** Since the health probes, every
|
||||
request went through an `async` wrapper around the memoized boot, which cost a promise and
|
||||
microtask hops even after the app was up. The first request still waits for the boot, and a boot
|
||||
that failed still fails every request.
|
||||
|
||||
### Deprecated
|
||||
|
||||
- **The `Headers` type** (D19). Import `RequestHeaders` instead: same type, a name that does not
|
||||
shadow the Fetch `Headers` global in the files that import it. `Headers` stays as an alias, so
|
||||
nothing breaks.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **A `@Module` without a `mountpoint` names itself at boot** (GitHub #31). The type
|
||||
requires it, but JavaScript or transpile-only code could still omit it, and `createApp` failed
|
||||
with `Cannot read properties of undefined (reading 'replace')` from inside the path helper. It now
|
||||
fails with `<Module> @Module metadata is missing mountpoint`. `mountpoint: ''` still mounts at the
|
||||
root.
|
||||
|
||||
- **The body parser is chosen by the media type** (GitHub #36). It was chosen by a substring of
|
||||
the raw `Content-Type` header, case-sensitively, so `Content-Type: Application/JSON` reached the
|
||||
handler as a string while `text/plain; x=application/json` was parsed as JSON. The same applied
|
||||
to urlencoded and multipart bodies. The parser now compares the media type, the part before any
|
||||
`;`, trimmed and lowercased, exactly. Any `+json` type (RFC 6839) is parsed as JSON too:
|
||||
`application/problem+json` and `application/vnd.api+json`, which used to arrive as text, now
|
||||
arrive parsed, and `application/json-patch+json`, which matched the old substring, still does.
|
||||
|
||||
- **Two concurrent `close()` calls both wait for teardown** (GitHub #45). The teardown registry
|
||||
marked itself drained and returned at once to any second caller, so a `close()` from a signal
|
||||
handler and another from a test hook ran teardown once, but only the first waited for it: the
|
||||
second resolved while a database could still be open. Every caller now gets the promise of the
|
||||
teardown already in flight, and it still runs once.
|
||||
|
||||
- **A graceful close that throws synchronously no longer rejects `close()`** (GitHub #47). On Deno
|
||||
and Bun, `closeWithDeadline` called the graceful path directly, so a throw before it returned a
|
||||
promise escaped as a rejection of `close()`, while the deadline timer stayed armed and later
|
||||
forced the server and logged a timeout nobody was waiting for. A synchronous throw is now handled
|
||||
like a rejection: `close()` resolves, and the timer is cleared.
|
||||
|
||||
- **A client leaving an idle stream ends it at once** (GitHub #40). Both stream adapters waited for
|
||||
the source's pending `next()` after the client had gone, so an SSE feed with nothing to send kept
|
||||
its connection alive: on Node, `stream:close` never fired and the stream stayed registered for
|
||||
graceful shutdown; through `app.fetch`, cancelling the body did not settle. The pull is now raced
|
||||
against the disconnect, and the source's `return()` is called without being waited on, so one
|
||||
that hangs or throws can no longer hold up or break the cleanup. Compressed streams included.
|
||||
|
||||
- **Decorating a subclass no longer changes its base class** (GitHub #44). The argument
|
||||
decorators (`@query`, `@param`, `@needs`, …) and the route decorators (`@Get`, `@Ws`, …) read
|
||||
their metadata with `Reflect.getMetadata`, which walks the prototype chain, and then pushed into
|
||||
what came back. On a subclass that was the base class's own map or array, so a `@query` on
|
||||
`Child.list` also appeared in `getArgs(Base, 'list')`, and a route declared on `Child` was served
|
||||
by `Base` too. Each decorator now writes a copy onto the class it decorates. The subclass still
|
||||
starts from what it inherits.
|
||||
|
||||
- **An app-scoped binding runs its factory once, however many resolve it at once** (GitHub #46).
|
||||
The internal container cached the value only after the factory settled, so two resolutions that
|
||||
started before then each ran it. It now caches the pending promise. A rejection is still not
|
||||
cached: the next resolution retries, as before, and the callers already waiting share that one
|
||||
rejection. `createApp` was not affected in practice, because it runs each provider once during
|
||||
the memoized boot and registers the finished value, but the container no longer depends on that.
|
||||
|
||||
- **A multipart text field over 1 MiB is no longer cut short** (GitHub #39). busboy applies its
|
||||
own 1 MiB `fieldSize` default unless told otherwise, so with `maxBodyBytes` raised above that a
|
||||
1,100,000-character field reached the handler as its first 1,048,576, and nothing said it had
|
||||
been cut. A field is now bounded by the route's body limit, the same one the whole body is held
|
||||
to. If busboy still reports a field as truncated, the request fails with `413` rather than
|
||||
handing the handler partial data. The Node server and `app.fetch` parse multipart through the
|
||||
same path, so the fix applies to both.
|
||||
|
||||
- **`maxParts: N` accepts exactly N parts** (#118). busboy signals its parts limit once the count
|
||||
reaches it, so a body of exactly `maxParts` parts was rejected with `400 Invalid multipart body`
|
||||
and only N−1 got through. busboy now gets one part of headroom, the same way `fieldSize` does:
|
||||
N parts are accepted and N+1 are rejected, as the option's name says. Both the route-level and
|
||||
the server-level `maxParts` were affected, on the Node server and `app.fetch` alike.
|
||||
- **`@header('Content-Type')` finds the header** (GitHub #37). Every adapter stores request
|
||||
header names lower-cased, and `@header`/`@headers` looked the name up as written, so any name
|
||||
with a capital letter reached the handler as `undefined`. The name is now matched without case.
|
||||
`@headers(['X-Trace'])` keeps the names as written in the bag it hands over, so the handler reads
|
||||
`X-Trace` back; `@headers()` with no argument still returns the lower-cased bag. Node, Deno, Bun
|
||||
and the edge share this path.
|
||||
- **The npm ESM build loads on Cloudflare Workers** (#93). tsup gives every ESM file a
|
||||
`createRequire(import.meta.url)` banner so the lazy `require('ws')`/`require('busboy')` work, and
|
||||
it ran at module scope. On workerd `import.meta.url` is not a file URL, so `createRequire` threw
|
||||
and the whole worker failed to load: `@green-tea/core/edge` from npm could not be used at all.
|
||||
The edge suite never noticed because it bundles `src/`. The call is now guarded; where it fails,
|
||||
`require` is left undefined and the existing fallback takes over. `npm run test:edge` now also
|
||||
builds and boots the published `dist/` on workerd. Node, Deno, Bun and JSR are unchanged.
|
||||
|
||||
- **`listen()` rejects when the port is taken** (#138). A bind failure such as `EADDRINUSE` or
|
||||
`EACCES` arrives as the server's `error` event, which `listen()` did not handle: the promise
|
||||
never settled, and the error surfaced as an unhandled one. It now rejects with that error. The
|
||||
app counts as never having listened, so `close()` resolves and a second `listen()` can try
|
||||
another port.
|
||||
|
||||
- **WebSocket outbound respects backpressure** (#41). A `@Ws` handler's async iterator was pulled
|
||||
as fast as it could yield, whatever the peer read, so a fast producer and a slow client grew the
|
||||
send buffer without limit: 10,000 frames of 64 KiB put 640 MiB in memory at once. The pump now
|
||||
waits before each pull while the socket's buffer is over 1 MiB, an internal mark rather than an
|
||||
option, so a slow peer holds at most about that plus one frame. A peer that keeps up never makes
|
||||
it wait. If the peer goes away while the pump waits, the wait ends and the iterator's `return()`
|
||||
runs, as on any other close. Each runtime signals in its own way: Node uses `ws`'s
|
||||
`bufferedAmount` and send callback, Bun uses `getBufferedAmount()` and its `drain` callback, and
|
||||
Deno polls `bufferedAmount`, since its `WebSocket` has no drain event. **workerd reports no
|
||||
buffered amount**, so on the edge the pump never waits and buffering is left to the platform.
|
||||
|
||||
- **On Deno, a `@Ws` handler that yields at once no longer loses the connection.** Deno hands the
|
||||
socket over before it is open. A value yielded in that window was pulled, the pump found the
|
||||
socket not open, and it gave up: the client got no frame and a close without a code (`1005`).
|
||||
The pump now waits for the socket to open, as part of the same backpressure wait.
|
||||
|
||||
- **A mesh RPC whose body is within `maxBodyBytes` reaches the teapot again** (#120). The 1 MiB
|
||||
WebSocket cap from #107 also bounded the mesh control channel, so a request body that fit the
|
||||
HTTP limit could still exceed it once the teacup wrapped it in an RPC frame. A text body near
|
||||
1 MB was enough, because JSON escaping doubles every `"` and backslash, and any body limit raised
|
||||
above 1 MiB was capped at 1 MiB on the channel. Either way the teapot closed the whole channel
|
||||
with `1009`, and every request through that link failed with `503` until it reconnected.
|
||||
|
||||
The control channel is now bounded by the teapot's `limits.maxBodyBytes`: six times the body
|
||||
limit, the most JSON escaping can grow a body (a control character becomes `\u0001`), plus 1 MiB
|
||||
for headers and the rest of the envelope. That is 7,048,576 bytes at the 1 MB default, up from
|
||||
the frame parser's former fixed 4,000,000. `limits.maxWsMessageBytes` still governs every user
|
||||
`@Ws` route, unchanged. On Bun, which takes one native payload limit for all sockets, a teapot
|
||||
raises that limit to the control channel's bound, so an oversized frame on a user route is
|
||||
refused by the framework instead: still `1009`, on every Bun version, where Bun before 1.4
|
||||
refused natively by dropping the connection (`1006`).
|
||||
|
||||
The larger bound applies only once the peer's `hello` is accepted. Until then the channel takes
|
||||
hello-sized frames (64 KiB), and on Node a peer that sends more than that before its hello is
|
||||
dropped before `ws` assembles the frame. Bun and Deno have no per-socket limit for the framework
|
||||
to hold that to, so there an unauthenticated peer can still make the teapot receive one frame up
|
||||
to the channel's bound before refusing it. If untrusted peers can reach a Bun or Deno teapot's
|
||||
`/__mesh__/control`, limit frame size at the proxy in front of it.
|
||||
|
||||
- **More than 16 mesh RPCs in flight on one link no longer drop the control channel** (#148). The
|
||||
16-frame inbound queue from #107 (`limits.maxWsQueue`) also applied to the control channel. On
|
||||
Node, `ws` delivers every frame of one socket read at once, so a teacup sending a burst of RPCs
|
||||
got the channel closed with `1013`, and every pending request failed with `503`. The control
|
||||
channel now has its own queue bound of 4,096 frames, or `maxWsQueue` if that is larger, which is
|
||||
more than one socket read can carry. User `@Ws` routes keep closing `1013` at `maxWsQueue`. Deno
|
||||
and Bun deliver frames one at a time and did not hit this, but they now share the same bound.
|
||||
|
||||
Both larger bounds, this one and the frame size from #120, **apply only once the peer's `hello`
|
||||
is accepted**. Until then the control channel takes frames of at most 64 KiB and queues at most
|
||||
16, and closes with `1009` or `1013` past that. An unauthenticated peer can therefore make a
|
||||
teapot hold about 1 MiB per connection, including while `app.upgrade` waits for a slow boot,
|
||||
instead of thousands of multi-megabyte frames.
|
||||
|
||||
- **Edge HTTP fills `ctx.ip` from `cf-connecting-ip` under `trustProxy`** (#119). `edgeHandler`
|
||||
never read the header for HTTP, so IP-keyed plugins such as rate-limit saw `''`, one bucket for
|
||||
every client. Under `trustProxy: true` the header now sets `ctx.ip`, and it wins over
|
||||
`x-forwarded-for`, because Cloudflare sets it itself while XFF can carry hops the client supplied.
|
||||
Without `trustProxy` it is ignored. Only `edgeHandler` reads it: the Node, Deno and Bun adapters, and a
|
||||
bare `app.fetch`, ignore it as before.
|
||||
|
||||
- **Mesh (alpha): `HEAD` on a remote `GET` route now works** (#125). The teacup resolved `HEAD` to
|
||||
the remote `GET` and `OPTIONS` advertised `HEAD`, but the request went to the teapot as `HEAD`,
|
||||
which has no `HEAD` plan, so it answered `404`. The teacup now forwards it as a `GET` and drops
|
||||
the body, so it answers like a local route: the `GET`'s status and headers, no body, and a
|
||||
`404`/`500` from the route keeps its status. An explicit remote `HEAD` route still takes
|
||||
precedence. The teapot is unchanged, so a new teacup works against an older teapot during a
|
||||
rolling deploy.
|
||||
|
||||
- **`static` no longer serves files outside its root through a symlink** (#106). The traversal guard
|
||||
compared paths lexically, and the file read then followed symlinks, so `public/leak -> /etc/hosts`
|
||||
was served. Containment now compares real paths: the requested file, and a directory's
|
||||
`index.html`, must resolve beneath the root's real path. Links that stay inside the root, and a
|
||||
root that is itself a symlink, keep working.
|
||||
|
||||
A link that resolves outside the root, or a dangling link, is a **404** — the same miss as a file
|
||||
that does not exist, rendered through `onError` like any other, and `405`/`204` where the path has
|
||||
routes. It is deliberately not a `403`, so a probe cannot tell "exists outside the root" from
|
||||
"does not exist". The content-type still follows the requested name, not the link target.
|
||||
|
||||
The root's real path is resolved on the first request and cached, so **re-pointing a root symlink
|
||||
while the app runs needs a restart** to take effect. A link swapped inside the root between the
|
||||
check and the read can still escape; exploiting that needs write access to the served directory.
|
||||
|
||||
- **A request that fails past the error renderer no longer takes the Node process down** (#108). The Node
|
||||
request listener was an `async` function, and `http.createServer` ignores the promise it returns,
|
||||
so anything that rejected outside the region where errors convert to a response — a custom static
|
||||
resolver, a handler header value Node refuses to write, a stream that fails before its first frame
|
||||
— became an unhandled rejection, which Node's default mode turns into an exit. The listener now
|
||||
catches it. While the response is still writable the client gets a fixed 500 with
|
||||
`connection: close`, written without calling `onError` again; once output has started the socket
|
||||
is destroyed instead. Either way the failure is logged through `logger.error`. No `request:end` is
|
||||
emitted for these requests. Deno, Bun and the edge were not affected: they receive `app.fetch`'s
|
||||
promise, and the runtime answers a rejection with a 500 itself.
|
||||
|
||||
- **A malformed WebSocket upgrade no longer takes a Node server down** (#104). The upgrade path never
|
||||
ran the request-path normalization HTTP runs, so a bad percent escape in a param segment
|
||||
(`/room/%E0%A4%A`) threw out of the `'upgrade'` listener as an uncaught exception, and one request
|
||||
was enough to end the process. Upgrades now go through the same normalization: a malformed escape
|
||||
or a repeated slash gets a `400`, an unknown route a written `404` instead of a silent disconnect,
|
||||
and anything else that throws in the listener a `500`. `//rt//echo` used to match `/rt/echo` on
|
||||
upgrade while HTTP refused it; both refuse it now. On Deno, Bun and the edge the same paths close
|
||||
with `1008 invalid request path` rather than `1011 internal error`, and on Deno a `1008` sent before
|
||||
the socket finished opening now reaches the client instead of leaving it hanging.
|
||||
|
||||
- **Deno, Bun and the edge enforce `maxBodyBytes` while reading the body, not after** (#105). The
|
||||
fetch adapter read every request through `request.arrayBuffer()` and compared the length once the
|
||||
whole body was in memory, so a 10 GB upload was buffered in full before it was refused. It now
|
||||
reads `request.body` chunk by chunk, stops at the chunk that crosses the limit and cancels the
|
||||
stream, so nothing further is pulled. A `content-length` that already declares more than the limit
|
||||
is refused before any of the body is read, on Node too, where the request used to wait for its
|
||||
first chunk. A malformed or absent `content-length` proves nothing and is ignored; the running
|
||||
count enforces the limit either way. The response is unchanged: the same `413 Payload Too Large`,
|
||||
through `onError`, with the same route-over-server precedence for `maxBodyBytes` and `maxParts`.
|
||||
|
||||
workerd may drop `content-length` from a chunked upload, so there an oversized body is refused by
|
||||
the count rather than up front. The status is the same; only how early it comes differs.
|
||||
|
||||
- **`serveDeno()` and `serveBun()` populate `ctx.ip` with the client's address** (#116). The fetch
|
||||
path had no way to learn the socket peer, so every HTTP request on Deno and Bun saw `ctx.ip` as
|
||||
`''`, and anything keyed on it put every client in one bucket — the rate-limit plugin, where one
|
||||
client could exhaust the limit for everyone, above all. Both adapters now hand the peer to
|
||||
`app.fetch`, and `ctx.ip` follows the same rule as Node's `listen()`: the first
|
||||
`x-forwarded-for` hop when `trustProxy` is on and the header is present, the socket peer
|
||||
otherwise. That includes `trustProxy` with no `x-forwarded-for`, which used to answer `''` on
|
||||
the fetch path and now falls back to the peer, as Node always has.
|
||||
|
||||
Addresses are passed through as each runtime reports them, so the IPv6 loopback is `::1` on all
|
||||
three but Node may report an IPv4 client as `::ffff:127.0.0.1`. A bare `app.fetch(request)` from
|
||||
your own code has no socket to report and still answers `''` (or the forwarded hop), and so does
|
||||
a `Request` copied from the one the adapter received. No signature changed. The edge adapter is
|
||||
unchanged: trusting `cf-connecting-ip` is only correct behind Cloudflare, and needs its own
|
||||
decision.
|
||||
|
||||
## [26.9.0-beta.2] - 2026-09-22
|
||||
|
||||
### Breaking
|
||||
@@ -113,8 +669,8 @@ npm treats versions as semver and semver forbids leading zeros.
|
||||
So the change is for the teacup that does *not* depend on that teapot: it starts, rather than
|
||||
refusing over a dependency it never had. It is not graceful degradation of the dependency, and
|
||||
cannot be — answering `503` for an absent teapot's tokens means knowing what it *would* have
|
||||
exported, and only a declaration can say. That declaration is the `expects` list in
|
||||
`docs/plans/2026-08-18-mesh-degrade-plan.md`, which is planned and not built. Two things are
|
||||
exported, and only a declaration can say. That declaration is a per-teapot `expects` list,
|
||||
which is planned and not built. Two things are
|
||||
unchanged: a **permanent refusal** — a wrong secret, a protocol mismatch — still fails the boot
|
||||
without spending the grace, because it is the teapot's decision rather than the network's and will
|
||||
be the same decision in thirty seconds; and the missing-token error, which now says "local or
|
||||
|
||||
+14
-5
@@ -74,7 +74,7 @@ So go through the diff the way you would go through a stranger's, because that i
|
||||
**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 write for Node and assume the rest follows. It doesn't — green-tea also runs on Deno, Bun and the edge, and `npm test` is the Node suite only. CI runs the other three, and `npm run test:all` runs them locally.
|
||||
- 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.
|
||||
|
||||
@@ -101,7 +101,7 @@ Follow [Conventional Commits](https://www.conventionalcommits.org/): `feat:`, `f
|
||||
|
||||
## Local setup
|
||||
|
||||
Node 18 or newer, which is what `engines` requires and what CI runs.
|
||||
Node 22 or newer, which is what `engines` requires and what CI runs. Node 18 and 20 are end-of-life and no longer supported.
|
||||
|
||||
```bash
|
||||
npm install
|
||||
@@ -120,16 +120,19 @@ If it prints nothing, run `git config core.hooksPath .githooks` yourself. If you
|
||||
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:
|
||||
and their own toolchains:
|
||||
|
||||
```bash
|
||||
npm run test:deno # needs deno
|
||||
npm run test:bun # needs bun
|
||||
npm run test:edge # Miniflare
|
||||
npm run test:all # all four, plus the JSR gate (deno publish --dry-run)
|
||||
```
|
||||
|
||||
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.
|
||||
CI runs all three on every push and pull request, in the `runtimes` job, and each one gates a
|
||||
merge just as the Node suite does. 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,
|
||||
so a red Bun job is not the first time anyone hears about it.
|
||||
|
||||
## Before you open a pull request
|
||||
|
||||
@@ -142,11 +145,17 @@ npm run typecheck # must be clean — this includes the compile-time-guarantee t
|
||||
npm test # all tests must pass
|
||||
npm run complexity:check
|
||||
npm run build
|
||||
npm run api:check # the committed API reports in api/ still match the build
|
||||
npm audit --omit=dev # only what ships blocks; CI reports the rest
|
||||
```
|
||||
|
||||
plus the runtime suite for whatever your change touches (see *Local setup* above). CI runs Deno,
|
||||
Bun and the edge in its `runtimes` job.
|
||||
|
||||
- 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`.
|
||||
- **The public API is frozen from RC.1, and `api/` is its record.** `api/*.api.md` holds one report per export-map entry, and `npm run api:check` fails when the build declares something they do not. If you meant to change the API, run `npm run build && npm run api` and commit the regenerated report with your change, so the reviewer reads the API change as a diff rather than finding it after release. From RC.1 to stable, releases are fixes only, so a pull request that changes a report needs the owner to reopen the freeze first. The policy is in the README under [API stability](./README.md#api-stability). The check also fails when a public signature names a type its entry point does not export, because a user would have no way to name it. Mesh is `@experimental` and outside the freeze, but it is still in the report, so a mesh change shows up there too.
|
||||
- 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.
|
||||
|
||||
@@ -43,6 +43,8 @@ Less to hold in your head. That's the tea.
|
||||
npm install @green-tea/core@beta reflect-metadata
|
||||
```
|
||||
|
||||
Requires Node 22 or newer. Node 18 and 20 are end-of-life and are not supported. Deno, Bun and Cloudflare Workers run the same code.
|
||||
|
||||
`@green-tea/core` — **beta**, RC-track. One runtime dependency: `reflect-metadata`. Two optional peers you install only if you use them:
|
||||
|
||||
```bash
|
||||
@@ -140,10 +142,11 @@ without growing the runtime dependency tree past `reflect-metadata`:
|
||||
- **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 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.
|
||||
- **Resource ceilings, with safe defaults.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. `maxConcurrentRequests` is opt-in and applies per server or Fetch adapter instance; when set, excess in-flight requests receive `503` and `Retry-After: 1`. It bounds concurrently executing handlers, so a handler that never returns continues to hold its slot; on Node, a client disconnect releases that slot. Long-lived streams and WebSocket upgrades do not hold that request budget. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there.
|
||||
- **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. Static files carry a weak `ETag`, `Last-Modified` and `Cache-Control: no-cache` (change it with `static: { dir, cacheControl }`), and a conditional request gets a `304` without the file being read. `createApp({ etag: true })` does the same for buffered `GET`/`HEAD` handler responses, and `createApp({ compression: true })` compresses text responses and event streams with gzip or br. It uses `node:zlib` on Node, Deno and Bun, and leaves encoding to the platform on the edge.
|
||||
- **Resource ceilings, with safe defaults.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. `maxConcurrentRequests` is opt-in and applies per server or Fetch adapter instance; when set, excess in-flight requests receive `503` and `Retry-After: 1`. It bounds concurrently executing handlers, so a handler that never returns continues to hold its slot; on Node, a client disconnect releases that slot. Long-lived streams and WebSocket upgrades do not hold that request budget. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there. WebSocket connections are bounded too: `maxWsMessageBytes` (default 1 MiB) closes a connection whose message is larger with `1009`, and `maxWsQueue` (default `16`) closes one that has that many unread inbound messages and receives another with `1013`, rather than dropping anything. Both are server-wide and must be positive integers. Node and Bun refuse an oversized message before buffering it (Bun before 1.4 drops the connection, so its peer sees `1006`; Bun 1.4 and later send `1009`); Deno and the edge check it after the runtime has received it. Worst case, a server buffers about `maxConnections × maxWsQueue × maxWsMessageBytes` of inbound messages — ≈ 15.6 GiB at the Node defaults.
|
||||
- **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 })`.
|
||||
- **Liveness and readiness probes.** `createApp({ health: true })` serves `/__live__` and `/__ready__`. Readiness reports `booting`, `ok`, `degraded` (optional providers that failed) or `draining` (from the moment `close()` starts). Probes are answered ahead of the pipeline: they are never shed and never show up in lifecycle events or request logs. `health: { drainDelayMs }` keeps the listener open for that window after `close()` starts, so a load balancer reads the `503` before connections drain. The edge never reports `draining`, because it has no `close()`.
|
||||
- **Shutdown is an extension point.** A provider that opened a pool closes it in `dispose()`; a plugin registers `onShutdown(...)`; an application that wants neither passes `createApp({ hooks: [{ onShutdown }] })`. All three land in one registry, run in reverse boot order — a `cache` that needs `db` closes first — and are *awaited*, unlike a `bus.on` listener. A failure is logged and the rest still run, because one broken teardown must not leave the process up. Everything happens inside `close()`'s deadline; `createApp({ teardownTimeoutMs })` reserves a slice of it when a connection must get its chance. *Not available on the edge* — workerd has no shutdown to hook.
|
||||
- **The `SIGTERM` handler is yours to keep or to hand over.** All of the above runs from `close()`, and something has to call it — a container `SIGKILL`ed after its grace period skips every `dispose()` and reports nothing. Write the handler yourself and keep the control, or set `createApp({ handleSignals: true })` and the framework registers `SIGINT`/`SIGTERM` to close and exit for you. Off by default, because a library that installs process-wide handlers behind your back is worse than one that installs none. Turning it on also absorbs the last runtime difference an app has: `process.on` on Node and Bun, `Deno.addSignalListener` on Deno, and the matching `exit` for each — `listen()`, `serveDeno()` and `serveBun()` each wire it to the closer that drains *their* server. `close()` unregisters, so a second Ctrl-C ends a teardown that is stuck.
|
||||
- **Testable by construction.** `createApp({ overrides: { db: fakeDb } })` swaps any node in one line.
|
||||
@@ -151,13 +154,22 @@ without growing the runtime dependency tree past `reflect-metadata`:
|
||||
|
||||
## Benchmarks
|
||||
|
||||
We built a reproducible [autocannon harness](./BENCHMARKS.md) comparing green-tea to Express 5, Fastify 5, NestJS (on both Express and Fastify), and raw Node `http` — and we wrote it to be **hard on ourselves**, not flattering.
|
||||
green-tea keeps a reproducible [autocannon](https://github.com/mcollina/autocannon) harness in
|
||||
`bench/`, and it is written to be hard on green-tea rather than flattering. It answers two
|
||||
different questions, and they need different setups:
|
||||
|
||||
On that harness green-tea is in the same class as Fastify and NestJS-on-Fastify, roughly 2.8× ahead of Express, and behind raw `http` with no framework at all. Within that class the shape reproduces on two very different machines: green-tea is **behind** Fastify on the JSON, routing and pipeline scenarios, and **ahead** of it on POST-plus-validation. How far behind is a property of the box rather than a constant — 2-8% on a laptop M4 Max, 7-15% on an idle desktop Ryzen — which is why the table carries its hardware and its date, and why a percentage quoted without them says little. Read [BENCHMARKS.md](./BENCHMARKS.md) rather than a sentence here: a ranking written into prose once is a claim nobody re-measures.
|
||||
- **How does green-tea compare to other frameworks?** `npm run bench` runs green-tea, Express 5,
|
||||
Fastify 5, NestJS on Express and on Fastify, and raw Node `http` through the same scenarios on
|
||||
one box, then writes [BENCHMARKS.md](./BENCHMARKS.md).
|
||||
- **Did the last N commits cost anything?** `npm run bench:compare` runs two versions of green-tea
|
||||
on one box in one sitting, alternating sides, so the difference is the code rather than the
|
||||
machine's mood that day.
|
||||
|
||||
The question a release actually has to pass is the other one — *did the last N commits cost anything* — and comparing today's numbers against a table generated weeks ago answers it with two machines in a mood rather than two versions. `npm run bench:compare` runs both trees on one box in one sitting, alternating sides; `26.9.0-beta.1 → 26.9.0-beta.2` came out flat on every case.
|
||||
|
||||
Read the honest caveats in [BENCHMARKS.md](./BENCHMARKS.md): the numbers are single-box + loopback (absolute throughput is overstated and differences compressed — trust the *ratios*), the cross-framework table runs green-tea with `security:false` for header parity, and the real cost of secure-by-default is measured separately. Regenerate any time with `npm run bench`.
|
||||
This section carries no numbers on purpose. A ranking written into prose is a claim nobody
|
||||
re-measures, and it goes stale with the next release. The figures, the hardware and date they
|
||||
were taken on, and the caveats live in [BENCHMARKS.md](./BENCHMARKS.md). The caveats include
|
||||
single-box loopback, trusting the ratios over the absolute numbers, and green-tea running with
|
||||
`security: false` for header parity, with the cost of secure-by-default measured separately.
|
||||
|
||||
## How it compares
|
||||
|
||||
@@ -243,6 +255,10 @@ The handler signature declares exactly what it wants — in any order, nothing m
|
||||
| `@body(...)` | parsed body (JSON / urlencoded / multipart) | `()` · `('field')` · `(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)` |
|
||||
| `@cookies(...)` | request cookies, parsed from `Cookie` (whole map or picked) | `()` · `('sid')` · `(['a','b'])` · `(schema)` |
|
||||
| `@cookie('name')` | one request cookie (singular alias of `@cookies`) | `('sid')` · `('sid', schema)` |
|
||||
|
||||
To send cookies, `setCookie(name, value, options?)` returns a `Set-Cookie` value with safe defaults (`HttpOnly`, `SameSite=Lax`, `Path=/`, `Secure`) and throws on anything that could inject a header. Response header values are `string | string[]`: a `set-cookie` array is sent as one line per cookie on every runtime, any other array as one line joined with `, `. Pass `secure: false` where the browser will not keep a `Secure` cookie over plain HTTP (Safari, a LAN IP). Signing and sessions are not in core.
|
||||
|
||||
`@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.
|
||||
|
||||
@@ -259,7 +275,14 @@ Patterns match by segment: static, constrained params such as `:id(\d+)`, plain
|
||||
|
||||
`@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.
|
||||
Because that subset is linear, constraints are also compared at boot. Two routes that branch at the same segment, under the same prefix and method, fail `createApp`:
|
||||
|
||||
- **ambiguous**: two constrained params accept a common segment and the rest of both patterns can match one request. The error names both routes and a segment both accept, such as `/u/:id(\d+)` + `/u/:n(\d{1,3})`, which both match `'0'`. Different spellings of one language (`\d+`, `[0-9]+`) count.
|
||||
- **unreachable**: a plain `:param` whose constrained sibling accepts every segment, such as `[^]*`, and wins every request the plain one could take.
|
||||
|
||||
A constraint next to a plain param is still the fallback pattern: with `/u/:id(\d+)` + `/u/:slug`, digits go to `:id` and everything else goes to `:slug`. An unescaped `.` does not match a line terminator, so `(.*)` does not cover every segment. WebSocket routes follow the same rules, except that they match in declaration order, so a plain WS param declared before a constrained one makes the constrained one unreachable. Mesh routes exported by different teapots are checked against each other; a local route still overrides a remote one, with a warning.
|
||||
|
||||
Lookup uses a radix tree per method, built once from the final route table, so a request only walks the branches its path can follow. Precedence is the same as above, and so are `Allow`, 405 and OPTIONS.
|
||||
|
||||
## Two layers
|
||||
|
||||
@@ -284,13 +307,13 @@ green-tea is **beta**, on the road to a release candidate. Express and Fastify h
|
||||
|
||||
**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.
|
||||
**Runtimes differ in what they can offer.** Node ≥ 22, 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. Native TLS (`createApp({ tls })`) is Node's `listen()` only: `serveDeno()` and `serveBun()` reject an app that sets it rather than serve it as plain HTTP, so configure TLS on that runtime's server or at a proxy, as you would on the edge. With `compression`, core never encodes on the edge (Cloudflare does), and on Deno it runs zlib on the main thread, where Deno's own `automaticCompression` is the faster gzip.
|
||||
|
||||
**mesh is alpha.** Distributed DI works, but discovery, load-balancing, and failover are not built, and its API and wire protocol may change between releases. It is gated behind an explicit opt-in — `createApp({ mesh, experimental: true })` — and `createApp` throws if you configure `mesh` without it. Don't ship mesh to production yet.
|
||||
|
||||
**What a teapot exports: steps and routes, and nothing else.** A `@Provider` marked `export: true` fails the boot with an error that says why — a provider's value *is* the object it builds, a pool or a client or a `db`, and the mesh moves data, not objects. Export a `@Step` instead: it runs on the teapot, per request, and its result is what comes back. That is also what lets a teacup boot without its teapot: a remote step holds nothing between requests, so a teacup whose teapot never answers still starts once the `bootTimeoutMs` grace runs out — it warns and carries on. Be precise about what that means, because it is narrower than it sounds. A teapot that never connected sent no manifest, so nothing of it reached the graph: its routes **404** rather than `503`, since nothing was registered to match, and a local step that `@needs` one of its tokens **still fails the boot**, naming the teapot that did not connect. That failure is deliberate — it is the check that catches a typo in a token name, which no amount of waiting will fix. `503` is what you get from a teapot that connected and *later* died, where the link and its exports do exist. So what the change buys is the teacup that does *not* depend on that teapot starting anyway, rather than refusing over a dependency it never had. Keeping a *needed* token serving while its teapot is legitimately away is a known gap, not an oversight: the intended answer is the `expects` list in [the mesh degrade plan](./docs/plans/2026-08-18-mesh-degrade-plan.md), which is planned and not built.
|
||||
**What a teapot exports: steps and routes, and nothing else.** A `@Provider` marked `export: true` fails the boot with an error that says why — a provider's value *is* the object it builds, a pool or a client or a `db`, and the mesh moves data, not objects. Export a `@Step` instead: it runs on the teapot, per request, and its result is what comes back. That is also what lets a teacup boot without its teapot: a remote step holds nothing between requests, so a teacup whose teapot never answers still starts once the `bootTimeoutMs` grace runs out — it warns and carries on. Be precise about what that means, because it is narrower than it sounds. A teapot that never connected sent no manifest, so nothing of it reached the graph: its routes **404** rather than `503`, since nothing was registered to match, and a local step that `@needs` one of its tokens **still fails the boot**, naming the teapot that did not connect. That failure is deliberate — it is the check that catches a typo in a token name, which no amount of waiting will fix. `503` is what you get from a teapot that connected and *later* died, where the link and its exports do exist. So what the change buys is the teacup that does *not* depend on that teapot starting anyway, rather than refusing over a dependency it never had. Keeping a *needed* token serving while its teapot is legitimately away is a known gap, not an oversight: the intended answer is a per-teapot `expects` list that declares what a teapot would export, which is planned and not built.
|
||||
|
||||
**What is settled, and what is still moving.** Present state, not a roadmap and not the API freeze — this is spare-time work by one person, and a schedule it cannot keep would cost more than it earns. The **graph is the settled part**: `needs`/`provides`, the order derived from them, and the boot-time failure when nothing provides a key have not changed since the beta hardening on 7 July, and `@Provider`, `@Step`, `@Route` and handler shapes still mean what they meant then — the decorator *set* has grown (`@Head`, `@Options`, `@Html`), which only ever adds. **Still moving:** the plugin API, which became `{ name, mount }` and gained `onShutdown`; the runtime entry points, where `serveDeno()` and `serveBun()` became async so they boot before they bind; `createApp`'s options, which gain fields most months; and the pipeline context, which in July became one object mutated in place rather than copied per step — so a step that captured it now sees later steps' writes. **Alpha:** mesh, above. Legacy decorators are a standing *external* risk rather than a green-tea one — see [Why legacy decorators](#why-legacy-decorators). The [matcha](https://github.com/Expressive-Tea/matcha) CLI ships from its own repository on its own version line, so nothing here speaks for it.
|
||||
**What is settled, and what is frozen.** From RC.1 the public surface of the four entry points (`@green-tea/core`, `/deno`, `/bun`, `/edge`) is frozen. Between RC.1 and the first stable release, releases are fixes only: nothing is added, removed, renamed or narrowed. Nothing published in `26.9.0-beta.2` was removed to reach the freeze. [API stability](#api-stability) has the full policy. That covers the graph (`needs`/`provides`, the order derived from them, and the boot-time failure when nothing provides a key), the decorators and handler shapes, the plugin API (`{ name, mount }` with `onShutdown`), the runtime entry points (`serveDeno()` and `serveBun()` are async so they boot before they bind), `createApp`'s options, and the pipeline context, which is one object mutated in place, so a step sees what earlier steps wrote. **Outside the freeze:** mesh, marked `@experimental` and described 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
|
||||
|
||||
@@ -333,13 +356,23 @@ consumer would have received.
|
||||
- ✅ **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.
|
||||
- ✅ **radix-tree matcher** — route lookup by index rather than a walk past every candidate, so a 200-route table costs about what a 10-route one does.
|
||||
- **next** — first stable release, mesh sub-specs (discovery, load-balancing, failover), and official plugins.
|
||||
|
||||
## Versioning
|
||||
|
||||
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.
|
||||
**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. Release candidates (`-rc.N`) publish the same way.
|
||||
|
||||
### API stability
|
||||
|
||||
**From the first release candidate (RC.1) the public API is frozen.** The public API is everything exported from the four entry points: `@green-tea/core`, `/deno`, `/bun` and `/edge`.
|
||||
|
||||
- **RC.1 to stable: fixes only.** No release in that window adds, removes, renames or narrows a public API. It also deprecates nothing. If a fix needs an API change, the freeze is reopened, and the change is called out under `### Breaking` in the CHANGELOG.
|
||||
- **After stable, deprecations come before removals.** A deprecated API keeps working for at least two monthly releases. It carries JSDoc `@deprecated` naming its replacement. Where it has a runtime path, it warns once per process through `app.logger`, never `console`. It is removed only in a release whose CHANGELOG lists the removal under `### Breaking`.
|
||||
- **Every API change shows up in review.** [`api/`](./api) holds the committed API report for each entry point, and CI fails when the build no longer matches it. A deliberate change regenerates the report in the same pull request.
|
||||
- **Mesh is outside the promise.** It is `@experimental` and gated behind `createApp({ experimental: true })`, so it may change in any release. Its exports still appear in the reports, so those changes still show up in review.
|
||||
|
||||
## License
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
## API Report File for "@green-tea/core"
|
||||
|
||||
> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).
|
||||
|
||||
```ts
|
||||
|
||||
import http from 'http';
|
||||
|
||||
// @public
|
||||
export interface BunServeOptions {
|
||||
// (undocumented)
|
||||
hostname?: string;
|
||||
// (undocumented)
|
||||
port?: number;
|
||||
}
|
||||
|
||||
// @public
|
||||
export interface BunServer {
|
||||
// (undocumented)
|
||||
port: number;
|
||||
// (undocumented)
|
||||
requestIP(request: Request): {
|
||||
address: string;
|
||||
family: string;
|
||||
port: number;
|
||||
} | null;
|
||||
// (undocumented)
|
||||
stop(closeActiveConnections?: boolean): Promise<void>;
|
||||
// (undocumented)
|
||||
upgrade(request: Request, options?: {
|
||||
data?: unknown;
|
||||
headers?: Record<string, string>;
|
||||
}): boolean;
|
||||
}
|
||||
|
||||
// @public
|
||||
export interface BunServeResult extends BunServer {
|
||||
close(options?: {
|
||||
timeoutMs?: number;
|
||||
}): Promise<void>;
|
||||
}
|
||||
|
||||
// @public
|
||||
export function serveBun(app: App, options?: BunServeOptions): Promise<BunServeResult>;
|
||||
|
||||
// (No @packageDocumentation comment for this package)
|
||||
|
||||
```
|
||||
@@ -0,0 +1,44 @@
|
||||
## API Report File for "@green-tea/core"
|
||||
|
||||
> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).
|
||||
|
||||
```ts
|
||||
|
||||
import http from 'http';
|
||||
|
||||
// @public
|
||||
export interface DenoHttpServer {
|
||||
// (undocumented)
|
||||
finished: Promise<void>;
|
||||
// (undocumented)
|
||||
shutdown(): Promise<void>;
|
||||
}
|
||||
|
||||
// @public
|
||||
export interface DenoServeOptions {
|
||||
// (undocumented)
|
||||
hostname?: string;
|
||||
// (undocumented)
|
||||
onListen?: (addr: {
|
||||
hostname: string;
|
||||
port: number;
|
||||
}) => void;
|
||||
// (undocumented)
|
||||
port?: number;
|
||||
// (undocumented)
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
// @public
|
||||
export interface DenoServer extends DenoHttpServer {
|
||||
close(options?: {
|
||||
timeoutMs?: number;
|
||||
}): Promise<void>;
|
||||
}
|
||||
|
||||
// @public
|
||||
export function serveDeno(app: App, options?: DenoServeOptions): Promise<DenoServer>;
|
||||
|
||||
// (No @packageDocumentation comment for this package)
|
||||
|
||||
```
|
||||
@@ -0,0 +1,20 @@
|
||||
## API Report File for "@green-tea/core"
|
||||
|
||||
> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).
|
||||
|
||||
```ts
|
||||
|
||||
import http from 'http';
|
||||
|
||||
// @public
|
||||
export interface EdgeCtx {
|
||||
// (undocumented)
|
||||
waitUntil(promise: Promise<unknown>): void;
|
||||
}
|
||||
|
||||
// @public
|
||||
export function edgeHandler(app: App): (request: Request, env?: unknown, ctx?: EdgeCtx) => Response | Promise<Response>;
|
||||
|
||||
// (No @packageDocumentation comment for this package)
|
||||
|
||||
```
|
||||
+1081
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,82 @@
|
||||
# Pre-radix router baseline — `ed47836`
|
||||
|
||||
The performance half of the CARD-08 parity corpus (FPRD-001, #109), captured before any CARD-07
|
||||
router change and immutable through CARD-07 review, like `test/router-parity/`. CARD-10 measures
|
||||
the radix index with the **same harness and defaults, on the same host, cpuset and image**, running
|
||||
`LOOKUP_ROUTERS="base=<ed47836 router>,head=src/http/router.ts"`. Do not re-run into this directory:
|
||||
a new capture goes in a new directory.
|
||||
|
||||
## Files
|
||||
|
||||
| File | What it is |
|
||||
|---|---|
|
||||
| `lookup-raw.json` | **The D4 baseline.** Interleaved `bench:lookup` with the live linear matcher as A and the byte-identical frozen oracle as B: environment, method, every sample of every round, and the summary. The live column gives the absolute baseline; the B/A ratios give the A/A noise floor. |
|
||||
| `lookup-summary.txt` | The tables that run printed. |
|
||||
| `load.txt` | `uptime` and running CI job containers, before and after. |
|
||||
| `battery-run/` | The superseded first capture (laptop on battery, sequential harness), kept for reference, including its `bench:compare` end-to-end req/s run. |
|
||||
|
||||
## Environment
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Host | jarvis (homelab), Ubuntu 24.04.3 LTS, kernel 6.8.0-138-generic, x86_64 |
|
||||
| CPU | AMD Ryzen 7 3700X, 8 cores / 16 threads, 2 × 16 MiB L3, governor `schedutil` (host default; not changed) |
|
||||
| Memory | 62.7 GiB |
|
||||
| Isolation | `docker run --rm --cpuset-cpus 6,7,14,15`: physical cores 6 and 7 plus their SMT siblings, both on the second CCX. All 16 CPUs were 0.0–0.8% busy in a 5 s sample beforehand. |
|
||||
| Container | `node:22` (`sha256:5647be70…`), Node v22.23.1, V8 12.4.254.21-node.56; Docker 29.1.3 |
|
||||
| Power | Not applicable (mains-powered server) |
|
||||
| Load | 1-minute load 0.27 before, 0.79 after; no CI job containers running (see `load.txt`). jarvis also runs long-lived services (payments-automation, open-webui, windmill, the Gitea act_runner, alloy, beszel), none of them pinned off these cores. |
|
||||
| Revision | Router at `ed47836c9820c47bf4ed5e902d91e019abdb110a`; harness `ee7fdec`, whose `src/` is byte-identical to `ed47836`. Copied with `git archive`, `npm ci --ignore-scripts` in the container. |
|
||||
| Env vars | Only `LOOKUP_*` (recorded in `meta.env`); no `NODE_OPTIONS`. |
|
||||
|
||||
## Method (`bench/lookup.ts` at `ee7fdec`, defaults)
|
||||
|
||||
- **Operation:** `resolveRoute(routes, method, path)`, and on `undefined`, `allowedMethods(routes, path)` — what `dispatch` does after `normalizeRequestPath`.
|
||||
- **Route counts:** 10, 100 and 500 **total registered HTTP routes**, from the recorded generator (`meta.method.routeGenerator`).
|
||||
- **Workloads:** static hit, late parameter hit, method miss, path miss; each answer is asserted before timing.
|
||||
- **Interleaving:** for each cell, every router is warmed for 250 ms (also calibrating ≈25 ms samples), then 21 rounds of one sample per router with the order alternating AB / BA.
|
||||
- **Repetitions:** 4 fresh processes, with module import order alternating per process → 84 paired rounds per cell. Every sample is kept.
|
||||
- **Statistics:** absolute = median ns per lookup over all 84 samples; ratio = median of the 84 per-round B/A ratios, with a percentile-bootstrap 95% CI (4000 resamples, seed 10908).
|
||||
|
||||
## Baseline: live linear matcher (median ns per lookup)
|
||||
|
||||
| Routes | Workload | live median ns | run medians (ns) | run spread |
|
||||
|---:|---|---:|---|---:|
|
||||
| 10 | static hit | 185.3 | 156.1 / 187.7 / 174.1 / 194.2 | 20.5% |
|
||||
| 10 | late param hit | 328.4 | 311.9 / 336.2 / 323.0 / 342.4 | 9.3% |
|
||||
| 10 | method miss | 800.4 | 762.6 / 801.2 / 798.6 / 804.4 | 5.2% |
|
||||
| 10 | path miss | 625.5 | 594.6 / 631.3 / 620.3 / 628.1 | 5.9% |
|
||||
| 100 | static hit | 201.2 | 202.2 / 200.8 / 197.6 / 207.2 | 4.8% |
|
||||
| 100 | late param hit | 878.0 | 861.1 / 857.0 / 907.3 / 880.5 | 5.7% |
|
||||
| 100 | method miss | 2,525 | 2,424 / 2,514 / 2,580 / 2,531 | 6.2% |
|
||||
| 100 | path miss | 3,054 | 2,965 / 3,024 / 3,114 / 3,071 | 4.9% |
|
||||
| 500 | static hit | 202.2 | 201.8 / 202.3 / 195.1 / 210.3 | 7.5% |
|
||||
| 500 | late param hit | 2,931 | 2,830 / 2,804 / 2,980 / 3,016 | 7.2% |
|
||||
| 500 | method miss | 11,904 | 11,635 / 11,518 / 11,946 / 12,031 | 4.3% |
|
||||
| 500 | path miss | 15,514 | 15,103 / 14,972 / 15,665 / 16,034 | 6.8% |
|
||||
|
||||
## A/A noise floor: identical code, oracle / live
|
||||
|
||||
| Routes | Workload | oracle / live median | 95% CI |
|
||||
|---:|---|---:|---|
|
||||
| 10 | static hit | 0.9507 (-4.9%) | -13.7% … +11.9% |
|
||||
| 10 | late param hit | 1.0415 (+4.1%) | -1.6% … +9.8% |
|
||||
| 10 | method miss | 0.9809 (-1.9%) | -4.4% … +0.8% |
|
||||
| 10 | path miss | 0.9919 (-0.8%) | -3.2% … +1.4% |
|
||||
| 100 | static hit | 1.0082 (+0.8%) | -1.9% … +4.5% |
|
||||
| 100 | late param hit | 1.0247 (+2.5%) | +1.9% … +2.9% |
|
||||
| 100 | method miss | 1.0055 (+0.6%) | +0.3% … +0.7% |
|
||||
| 100 | path miss | 1.0165 (+1.7%) | +1.2% … +1.9% |
|
||||
| 500 | static hit | 1.0107 (+1.1%) | -2.2% … +4.5% |
|
||||
| 500 | late param hit | 0.9838 (-1.6%) | -2.2% … +0.8% |
|
||||
| 500 | method miss | 1.0197 (+2.0%) | +1.6% … +2.3% |
|
||||
| 500 | path miss | 1.0161 (+1.6%) | +0.5% … +2.6% |
|
||||
|
||||
**For D4:**
|
||||
|
||||
- **Import order.** In-process, the module imported first is faster on the cheapest cell. At 10-route static hit (≈180 ns) the per-run medians swap by about 20% when the import order swaps (run 1: live 156, oracle 200 ns; run 2: live 188, oracle 162 ns). Alternating the import order removes that bias from the median, but it leaves that cell's 95% CI at −13.7 … +11.9%. A ≤5% regression limit cannot be resolved there with this method and sample size.
|
||||
- **Other 10-route cells.** The CIs are within about ±10% (late parameter hit −1.6 … +9.8%), and the misses are within ±4.4%.
|
||||
- **100 and 500 routes.** Identical code shows small but systematic offsets of up to +2.9%, with CIs that exclude 1. Treat anything inside ±3% as indistinguishable from no change.
|
||||
- **500 routes.** The ≥20% improvement target is far outside the noise in every cell.
|
||||
|
||||
The options for D4 are to apply the 10-route limit to the miss and late-parameter cells only, to require more rounds for the static cell, or to restate the limit relative to this measured floor. That decision belongs to the owner.
|
||||
@@ -0,0 +1,94 @@
|
||||
# Superseded: first baseline, laptop on battery — `ed47836`
|
||||
|
||||
> Kept for reference only. **The baseline is `../README.md`**, captured on jarvis with the
|
||||
> interleaved harness. This run used the earlier sequential harness (`98ea948`), one router per
|
||||
> process, on a laptop running on battery.
|
||||
|
||||
The performance half of the CARD-08 parity corpus (FPRD-001, #109). Captured before any CARD-07
|
||||
router change; immutable through CARD-07 review, like `test/router-parity/`. CARD-10 measures the
|
||||
radix index with the **same harness, same defaults, same machine class**, and compares against
|
||||
these files. Do not re-run into this directory: a new capture goes in a new directory.
|
||||
|
||||
## Files
|
||||
|
||||
| File | What it is |
|
||||
|---|---|
|
||||
| `lookup-raw.json` | **The D4 baseline.** `bench:lookup` on the live linear matcher: environment, method, every sample of every run, and the summary. |
|
||||
| `lookup-summary.txt` | The table `bench:lookup` printed for that run. |
|
||||
| `lookup-aa-raw.json`, `lookup-aa-summary.txt` | A/A noise check: the live router against the byte-identical frozen oracle (`test/router-parity/oracle.ts`), same alternating protocol. Any difference here is noise. |
|
||||
| `compare-e2e-raw.json`, `compare-e2e-summary.txt`, `compare-e2e-stderr.txt` | `npm run bench:compare`, run once with this tree as both base and head. **End-to-end req/s signal only**: 50/200 *filler* routes plus base routes, not 10/100/500 total, and not lookup time. It cannot decide D4. |
|
||||
| `load.txt` | `uptime` before and after each run. |
|
||||
|
||||
## Environment
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Hardware | Apple M4 Max (`Mac16,5`), 16 cores (12 performance + 4 efficiency), 64 GiB |
|
||||
| Power | **On battery** (84%, discharging) for every run. macOS may manage clocks differently on AC; run the CARD-10 comparison on the same power source, or re-capture both on AC. |
|
||||
| OS | macOS 27.0.1 (build 26A434), Darwin 27.0.0 arm64 |
|
||||
| Node | v22.22.2 (V8 12.4.254.21-node.39) |
|
||||
| Packages | `@green-tea/core@26.9.0-beta.2`; tsx 4.23.5, typescript 5.9.3, vitest 4.1.11, autocannon 8.0.0 (from `package-lock.json`) |
|
||||
| Core revision | Router source at `ed47836c9820c47bf4ed5e902d91e019abdb110a`. The harness ran from `98ea948` (this branch), whose `src/` is byte-identical to `ed47836` — the branch adds only tests and bench files. |
|
||||
| Env vars | `LOOKUP_OUT` only (and `LOOKUP_ROUTERS` for the A/A run); no `NODE_OPTIONS`. Recorded in each raw file under `meta.env`. |
|
||||
| Load | 1-minute load average 2.4–3.4 on 16 cores throughout (see `load.txt` and `meta.loadavgAtStart/End`). Foreground apps were a browser and the window server; nothing else CPU-bound. |
|
||||
|
||||
## Method (`bench/lookup.ts`, defaults)
|
||||
|
||||
- **Operation:** `resolveRoute(routes, method, path)`, and on `undefined`, `allowedMethods(routes, path)` — what `dispatch` does after `normalizeRequestPath`. Normalization is excluded.
|
||||
- **Route counts:** 10, 100 and 500 **total registered HTTP routes**.
|
||||
- **Generator:** N−2 fillers cycling `GET /res{k}/items`, `POST /res{k}/items`, `GET /res{k}/items/:id`, `PUT /res{k}/items/:id(\d+)`, `GET /res{k}/files/:path*` (k = ⌊i/5⌋), then `GET /static/target/leaf`, then `GET /late/:group/:id` declared last.
|
||||
- **Workloads:** static hit `GET /static/target/leaf`; late parameter hit `GET /late/g1/42`; method miss `DELETE /static/target/leaf` (Allow `GET, HEAD, OPTIONS`); path miss `GET /nowhere/at/all`. Each answer is asserted before timing.
|
||||
- **Order:** for each run, for each router (order alternates per run), for count 10 → 100 → 500, for the four workloads in the order above.
|
||||
- **Warm-up:** 250 ms per cell, time-boxed; it also calibrates iterations so one sample lasts ≈25 ms (iteration counts are stored per cell).
|
||||
- **Repetitions:** 5 runs, each a fresh child process; 21 samples per cell per run → 105 samples per cell. Every sample is kept.
|
||||
- **Statistic:** median ns per lookup over all 105 samples. Run spread = (max − min of the five per-run medians) / median.
|
||||
|
||||
## Baseline (median ns per lookup, `lookup-raw.json`)
|
||||
|
||||
| Routes | Static hit | Late param hit | Method miss | Path miss |
|
||||
|---:|---:|---:|---:|---:|
|
||||
| 10 | 61.3 (spread 17.5%) | 123.3 (6.2%) | 313.1 (4.6%) | 247.1 (6.8%) |
|
||||
| 100 | 67.6 (8.0%) | 343.4 (2.1%) | 1 263.7 (3.5%) | 1 463.3 (3.2%) |
|
||||
| 500 | 67.8 (7.5%) | 1 326.8 (16.5%) | 6 732.2 (6.5%) | 8 973.4 (2.0%) |
|
||||
|
||||
## Noise floor (A/A, `lookup-aa-raw.json`)
|
||||
|
||||
Identical matcher code under two labels, alternating order per run. Median difference
|
||||
(oracle − live) / live:
|
||||
|
||||
| Routes | Static hit | Late param hit | Method miss | Path miss |
|
||||
|---:|---:|---:|---:|---:|
|
||||
| 10 | +5.2% | 0.0% | +1.2% | +0.2% |
|
||||
| 100 | −0.1% | −0.8% | −0.1% | +0.1% |
|
||||
| 500 | −2.7% | +0.3% | −0.4% | +0.1% |
|
||||
|
||||
**For D4:** with no code difference at all, the 10-route static hit already moves 5.2% — the
|
||||
size of the proposed ≤5% regression limit — and per-run medians at 10 routes spread 4.5–17.5%.
|
||||
That cell is ~60 ns, where a few nanoseconds of timer and scheduling noise are a large fraction.
|
||||
The ≥20% improvement at 500 routes is well clear of the noise (≤2.7% A/A, ≤16.5% spread on a
|
||||
1.3–9 µs operation). Whether D4's 10-route limit applies per workload, to a mean across workloads,
|
||||
or needs more runs is an owner decision; this baseline does not make it.
|
||||
|
||||
## End-to-end signal (`bench:compare`, req/s — not lookup time)
|
||||
|
||||
Run once, A/A: `AB_BASE` pointed at this same tree, so base and head are identical code. Defaults:
|
||||
3 rounds × 10 s per case after a 10 s warm-up, 100 connections, alternating side order. Load
|
||||
average 2.8–3.3 throughout. A few short parity-test runs (seconds each) happened during this
|
||||
~22-minute run; the lookup runs above had nothing else running.
|
||||
|
||||
| Scenario | base req/s | head req/s | Δ |
|
||||
|---|---:|---:|---:|
|
||||
| hello | 88,212 | 88,236 | +0.0% |
|
||||
| param | 86,508 | 85,885 | −0.7% |
|
||||
| pipeline (3 steps) | 80,189 | 80,934 | +0.9% |
|
||||
| steps5 | 74,359 | 73,975 | −0.5% |
|
||||
| validate (POST) | 70,607 | 69,903 | −1.0% |
|
||||
| hello + security | 83,913 | 83,802 | −0.1% |
|
||||
| hello + cors predicate | 82,028 | 80,445 | −1.9% |
|
||||
| preflight + cors predicate | 114,377 | 114,010 | −0.3% |
|
||||
| param, 50 routes | 82,476 | 82,045 | −0.5% |
|
||||
| param, 200 routes | 72,957 | 73,306 | +0.5% |
|
||||
|
||||
Every row's sample ranges overlap. So with no code change, end-to-end throughput moves up to
|
||||
±1.9%; the route-width rows show that 200 filler routes already cost ~12% req/s against
|
||||
`param` with none.
|
||||
@@ -0,0 +1,207 @@
|
||||
{
|
||||
"rounds": 3,
|
||||
"duration": 10,
|
||||
"conns": 100,
|
||||
"rows": [
|
||||
{
|
||||
"name": "hello",
|
||||
"base": 88212.37,
|
||||
"head": 88235.64,
|
||||
"delta": 0.0263795202418936,
|
||||
"separated": false,
|
||||
"samples": {
|
||||
"base": [
|
||||
82493.1,
|
||||
88503.28,
|
||||
88212.37
|
||||
],
|
||||
"head": [
|
||||
88177.46,
|
||||
88235.64,
|
||||
92826.19
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "param",
|
||||
"base": 86507.64,
|
||||
"head": 85885.1,
|
||||
"delta": -0.7196358610638246,
|
||||
"separated": false,
|
||||
"samples": {
|
||||
"base": [
|
||||
81230.55,
|
||||
86757.82,
|
||||
86507.64
|
||||
],
|
||||
"head": [
|
||||
83412.37,
|
||||
86705.46,
|
||||
85885.1
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "pipeline (3 steps)",
|
||||
"base": 80189.1,
|
||||
"head": 80933.82,
|
||||
"delta": 0.9287047740902455,
|
||||
"separated": false,
|
||||
"samples": {
|
||||
"base": [
|
||||
76116.37,
|
||||
80189.1,
|
||||
80276.37
|
||||
],
|
||||
"head": [
|
||||
77035.64,
|
||||
80992,
|
||||
80933.82
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "steps5",
|
||||
"base": 74359.28,
|
||||
"head": 73975.28,
|
||||
"delta": -0.5164116704734096,
|
||||
"separated": false,
|
||||
"samples": {
|
||||
"base": [
|
||||
75272.73,
|
||||
74359.28,
|
||||
73928.73
|
||||
],
|
||||
"head": [
|
||||
72235.64,
|
||||
74813.1,
|
||||
73975.28
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "validate (POST)",
|
||||
"base": 70606.55,
|
||||
"head": 69902.55,
|
||||
"delta": -0.997074634010584,
|
||||
"separated": false,
|
||||
"samples": {
|
||||
"base": [
|
||||
70775.28,
|
||||
70606.55,
|
||||
69762.91
|
||||
],
|
||||
"head": [
|
||||
67138.91,
|
||||
74353.46,
|
||||
69902.55
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "hello + security",
|
||||
"base": 83912.73,
|
||||
"head": 83802.19,
|
||||
"delta": -0.13173209833596597,
|
||||
"separated": false,
|
||||
"samples": {
|
||||
"base": [
|
||||
81928.73,
|
||||
84709.82,
|
||||
83912.73
|
||||
],
|
||||
"head": [
|
||||
81742.55,
|
||||
83802.19,
|
||||
84512
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "hello + cors predicate",
|
||||
"base": 82027.64,
|
||||
"head": 80445.1,
|
||||
"delta": -1.9292765219138253,
|
||||
"separated": false,
|
||||
"samples": {
|
||||
"base": [
|
||||
82481.46,
|
||||
82027.64,
|
||||
81381.82
|
||||
],
|
||||
"head": [
|
||||
79368.73,
|
||||
82213.82,
|
||||
80445.1
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "preflight + cors predicate",
|
||||
"base": 114376.73,
|
||||
"head": 114010.19,
|
||||
"delta": -0.3204672838609686,
|
||||
"separated": false,
|
||||
"samples": {
|
||||
"base": [
|
||||
114580.37,
|
||||
114376.73,
|
||||
112322.91
|
||||
],
|
||||
"head": [
|
||||
109669.82,
|
||||
114813.1,
|
||||
114010.19
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "param, 50 routes",
|
||||
"base": 82475.64,
|
||||
"head": 82045.1,
|
||||
"delta": -0.5220208051734956,
|
||||
"separated": false,
|
||||
"samples": {
|
||||
"base": [
|
||||
82562.91,
|
||||
82475.64,
|
||||
82178.91
|
||||
],
|
||||
"head": [
|
||||
78891.64,
|
||||
82045.1,
|
||||
82388.37
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "param, 200 routes",
|
||||
"base": 72957.1,
|
||||
"head": 73306.19,
|
||||
"delta": 0.47848667230467834,
|
||||
"separated": false,
|
||||
"samples": {
|
||||
"base": [
|
||||
72986.19,
|
||||
72957.1,
|
||||
72194.91
|
||||
],
|
||||
"head": [
|
||||
72055.28,
|
||||
73306.19,
|
||||
73381.82
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"cors": {
|
||||
"base": {
|
||||
"get": 1,
|
||||
"preflight": 1
|
||||
},
|
||||
"head": {
|
||||
"get": 1,
|
||||
"preflight": 1
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
[compare] round 1 base hello 82,493 req/s
|
||||
[compare] round 1 base param 81,231 req/s
|
||||
[compare] round 1 base pipeline (3 steps) 76,116 req/s
|
||||
[compare] round 1 base steps5 75,273 req/s
|
||||
[compare] round 1 base validate (POST) 70,775 req/s
|
||||
[compare] round 1 base hello + security 81,929 req/s
|
||||
[compare] round 1 base hello + cors predicate 82,481 req/s
|
||||
[compare] round 1 base preflight + cors predicate 114,580 req/s
|
||||
[compare] round 1 base param, 50 routes 82,563 req/s
|
||||
[compare] round 1 base param, 200 routes 72,986 req/s
|
||||
[compare] round 1 head hello 88,177 req/s
|
||||
[compare] round 1 head param 83,412 req/s
|
||||
[compare] round 1 head pipeline (3 steps) 77,036 req/s
|
||||
[compare] round 1 head steps5 72,236 req/s
|
||||
[compare] round 1 head validate (POST) 67,139 req/s
|
||||
[compare] round 1 head hello + security 81,743 req/s
|
||||
[compare] round 1 head hello + cors predicate 79,369 req/s
|
||||
[compare] round 1 head preflight + cors predicate 109,670 req/s
|
||||
[compare] round 1 head param, 50 routes 78,892 req/s
|
||||
[compare] round 1 head param, 200 routes 72,055 req/s
|
||||
[compare] round 2 head hello 88,236 req/s
|
||||
[compare] round 2 head param 86,705 req/s
|
||||
[compare] round 2 head pipeline (3 steps) 80,992 req/s
|
||||
[compare] round 2 head steps5 74,813 req/s
|
||||
[compare] round 2 head validate (POST) 74,353 req/s
|
||||
[compare] round 2 head hello + security 83,802 req/s
|
||||
[compare] round 2 head hello + cors predicate 82,214 req/s
|
||||
[compare] round 2 head preflight + cors predicate 114,813 req/s
|
||||
[compare] round 2 head param, 50 routes 82,045 req/s
|
||||
[compare] round 2 head param, 200 routes 73,306 req/s
|
||||
[compare] round 2 base hello 88,503 req/s
|
||||
[compare] round 2 base param 86,758 req/s
|
||||
[compare] round 2 base pipeline (3 steps) 80,189 req/s
|
||||
[compare] round 2 base steps5 74,359 req/s
|
||||
[compare] round 2 base validate (POST) 70,607 req/s
|
||||
[compare] round 2 base hello + security 84,710 req/s
|
||||
[compare] round 2 base hello + cors predicate 82,028 req/s
|
||||
[compare] round 2 base preflight + cors predicate 114,377 req/s
|
||||
[compare] round 2 base param, 50 routes 82,476 req/s
|
||||
[compare] round 2 base param, 200 routes 72,957 req/s
|
||||
[compare] round 3 base hello 88,212 req/s
|
||||
[compare] round 3 base param 86,508 req/s
|
||||
[compare] round 3 base pipeline (3 steps) 80,276 req/s
|
||||
[compare] round 3 base steps5 73,929 req/s
|
||||
[compare] round 3 base validate (POST) 69,763 req/s
|
||||
[compare] round 3 base hello + security 83,913 req/s
|
||||
[compare] round 3 base hello + cors predicate 81,382 req/s
|
||||
[compare] round 3 base preflight + cors predicate 112,323 req/s
|
||||
[compare] round 3 base param, 50 routes 82,179 req/s
|
||||
[compare] round 3 base param, 200 routes 72,195 req/s
|
||||
[compare] round 3 head hello 92,826 req/s
|
||||
[compare] round 3 head param 85,885 req/s
|
||||
[compare] round 3 head pipeline (3 steps) 80,934 req/s
|
||||
[compare] round 3 head steps5 73,975 req/s
|
||||
[compare] round 3 head validate (POST) 69,903 req/s
|
||||
[compare] round 3 head hello + security 84,512 req/s
|
||||
[compare] round 3 head hello + cors predicate 80,445 req/s
|
||||
[compare] round 3 head preflight + cors predicate 114,010 req/s
|
||||
[compare] round 3 head param, 50 routes 82,388 req/s
|
||||
[compare] round 3 head param, 200 routes 73,382 req/s
|
||||
@@ -0,0 +1,21 @@
|
||||
|
||||
> @green-tea/core@26.9.0-beta.2 bench:compare
|
||||
> tsx bench/compare.ts
|
||||
|
||||
|
||||
| Scenario | base | head | Δ | |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| hello | 88,212 | 88,236 | +0.0% | overlaps |
|
||||
| param | 86,508 | 85,885 | -0.7% | overlaps |
|
||||
| pipeline (3 steps) | 80,189 | 80,934 | +0.9% | overlaps |
|
||||
| steps5 | 74,359 | 73,975 | -0.5% | overlaps |
|
||||
| validate (POST) | 70,607 | 69,903 | -1.0% | overlaps |
|
||||
| hello + security | 83,913 | 83,802 | -0.1% | overlaps |
|
||||
| hello + cors predicate | 82,028 | 80,445 | -1.9% | overlaps |
|
||||
| preflight + cors predicate | 114,377 | 114,010 | -0.3% | overlaps |
|
||||
| param, 50 routes | 82,476 | 82,045 | -0.5% | overlaps |
|
||||
| param, 200 routes | 72,957 | 73,306 | +0.5% | overlaps |
|
||||
|
||||
cors.origins calls — base: 1 per GET, 1 per preflight
|
||||
cors.origins calls — head: 1 per GET, 1 per preflight
|
||||
exit 0
|
||||
@@ -0,0 +1,6 @@
|
||||
uptime before: 17:01 up 9 days, 7:50, 1 user, load averages: 2.47 2.14 6.86
|
||||
uptime after: 17:02 up 9 days, 7:51, 1 user, load averages: 2.58 2.21 6.64
|
||||
A/A uptime before: 17:02 up 9 days, 7:51, 1 user, load averages: 3.42 2.40 6.66
|
||||
A/A uptime after: 17:03 up 9 days, 7:53, 1 user, load averages: 2.89 2.48 6.26
|
||||
bench:compare uptime before: 17:04 up 9 days, 7:53, 1 user, load averages: 2.98 2.51 6.25
|
||||
bench:compare uptime after: 17:26 up 9 days, 8:15, 1 user, load averages: 2.82 3.32 4.29
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,33 @@
|
||||
|
||||
> @green-tea/core@26.9.0-beta.2 bench:lookup
|
||||
> tsx bench/lookup.ts
|
||||
|
||||
| router | routes | workload | median ns/op | run medians (ns) | run spread |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| live | 10 | static hit | 62.0 | 57.9 / 65.8 / 60.3 / 62.7 / 61.8 | 12.7% |
|
||||
| live | 10 | late param hit | 123.8 | 124.0 / 120.4 / 122.1 / 124.3 / 128.4 | 6.4% |
|
||||
| live | 10 | method miss | 309.0 | 305.7 / 305.6 / 320.1 / 310.8 / 311.6 | 4.7% |
|
||||
| live | 10 | path miss | 248.4 | 242.7 / 242.5 / 253.7 / 251.0 / 248.7 | 4.5% |
|
||||
| live | 100 | static hit | 69.5 | 66.7 / 68.7 / 69.2 / 71.6 / 71.5 | 7.1% |
|
||||
| live | 100 | late param hit | 352.2 | 345.1 / 348.3 / 349.9 / 355.2 / 365.1 | 5.7% |
|
||||
| live | 100 | method miss | 1265.3 | 1273.8 / 1256.0 / 1254.2 / 1279.7 / 1267.1 | 2.0% |
|
||||
| live | 100 | path miss | 1464.9 | 1462.8 / 1451.3 / 1462.3 / 1485.2 / 1470.6 | 2.3% |
|
||||
| live | 500 | static hit | 67.8 | 67.2 / 66.9 / 68.1 / 69.3 / 67.7 | 3.4% |
|
||||
| live | 500 | late param hit | 1313.7 | 1362.0 / 1293.9 / 1309.7 / 1313.7 / 1316.9 | 5.2% |
|
||||
| live | 500 | method miss | 6778.2 | 7068.9 / 6783.2 / 6634.3 / 6816.4 / 6689.2 | 6.4% |
|
||||
| live | 500 | path miss | 9005.3 | 9445.9 / 9015.5 / 8965.0 / 9032.4 / 8834.1 | 6.8% |
|
||||
| oracle | 10 | static hit | 65.2 | 62.2 / 66.6 / 66.6 / 65.2 / 58.0 | 13.1% |
|
||||
| oracle | 10 | late param hit | 123.9 | 130.7 / 123.5 / 125.2 / 122.9 / 120.1 | 8.5% |
|
||||
| oracle | 10 | method miss | 312.7 | 311.4 / 314.2 / 312.2 / 316.8 / 309.1 | 2.4% |
|
||||
| oracle | 10 | path miss | 249.0 | 248.6 / 253.1 / 247.3 / 249.0 / 248.9 | 2.3% |
|
||||
| oracle | 100 | static hit | 69.4 | 69.5 / 71.1 / 69.8 / 67.5 / 66.7 | 6.4% |
|
||||
| oracle | 100 | late param hit | 349.3 | 347.5 / 352.5 / 349.6 / 347.2 / 354.0 | 1.9% |
|
||||
| oracle | 100 | method miss | 1263.6 | 1294.1 / 1243.1 / 1251.2 / 1286.5 / 1258.0 | 4.0% |
|
||||
| oracle | 100 | path miss | 1466.2 | 1511.6 / 1464.0 / 1459.5 / 1480.7 / 1449.1 | 4.3% |
|
||||
| oracle | 500 | static hit | 66.0 | 67.0 / 67.3 / 65.8 / 64.9 / 65.1 | 3.6% |
|
||||
| oracle | 500 | late param hit | 1317.6 | 1313.2 / 1310.2 / 1323.5 / 1294.5 / 1363.2 | 5.2% |
|
||||
| oracle | 500 | method miss | 6753.3 | 6717.3 / 6758.7 / 6666.4 / 6876.3 / 6750.7 | 3.1% |
|
||||
| oracle | 500 | path miss | 9015.3 | 8998.0 / 9021.6 / 8980.8 / 9100.7 / 8884.0 | 2.4% |
|
||||
|
||||
load average: start 3.42 2.40 6.66, end 2.89 2.48 6.26
|
||||
raw samples: bench/baseline/router-ed47836/lookup-aa-raw.json
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,21 @@
|
||||
|
||||
> @green-tea/core@26.9.0-beta.2 bench:lookup
|
||||
> tsx bench/lookup.ts
|
||||
|
||||
| router | routes | workload | median ns/op | run medians (ns) | run spread |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| live | 10 | static hit | 61.3 | 64.4 / 61.0 / 68.4 / 58.0 / 57.6 | 17.5% |
|
||||
| live | 10 | late param hit | 123.3 | 122.4 / 128.1 / 123.3 / 123.7 / 120.4 | 6.2% |
|
||||
| live | 10 | method miss | 313.1 | 303.2 / 314.0 / 317.6 / 317.2 / 304.7 | 4.6% |
|
||||
| live | 10 | path miss | 247.1 | 243.8 / 246.0 / 256.5 / 251.7 / 239.7 | 6.8% |
|
||||
| live | 100 | static hit | 67.6 | 67.6 / 70.3 / 71.7 / 66.9 / 66.3 | 8.0% |
|
||||
| live | 100 | late param hit | 343.4 | 339.7 / 345.5 / 346.8 / 343.0 / 341.0 | 2.1% |
|
||||
| live | 100 | method miss | 1263.7 | 1253.2 / 1236.5 / 1280.9 / 1261.0 / 1264.6 | 3.5% |
|
||||
| live | 100 | path miss | 1463.3 | 1444.6 / 1442.4 / 1489.2 / 1467.6 / 1467.1 | 3.2% |
|
||||
| live | 500 | static hit | 67.8 | 69.7 / 68.1 / 68.2 / 64.6 / 65.1 | 7.5% |
|
||||
| live | 500 | late param hit | 1326.8 | 1480.6 / 1262.0 / 1309.9 / 1328.9 / 1331.8 | 16.5% |
|
||||
| live | 500 | method miss | 6732.2 | 7072.0 / 6659.6 / 6796.0 / 6631.5 / 6699.6 | 6.5% |
|
||||
| live | 500 | path miss | 8973.4 | 8915.3 / 8994.7 / 9052.0 / 8876.0 / 8981.4 | 2.0% |
|
||||
|
||||
load average: start 2.47 2.14 6.86, end 2.58 2.21 6.64
|
||||
raw samples: bench/baseline/router-ed47836/lookup-raw.json
|
||||
@@ -0,0 +1,3 @@
|
||||
before: 2026-10-10T22:42:38Z 17:42:38 up 44 days, 17:31, 2 users, load average: 0.27, 0.11, 0.04
|
||||
ci job containers: 0
|
||||
after: 2026-10-10T22:43:54Z 17:43:54 up 44 days, 17:32, 2 users, load average: 0.79, 0.31, 0.12
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,44 @@
|
||||
| routes | workload | router | median ns/op | run medians (ns) | run spread |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 10 | static hit | live | 185.3 | 156.1 / 187.7 / 174.1 / 194.2 | 20.5% |
|
||||
| 10 | static hit | oracle | 176.8 | 199.9 / 161.9 / 195.0 / 162.5 | 21.5% |
|
||||
| 10 | late param hit | live | 328.4 | 311.9 / 336.2 / 323.0 / 342.4 | 9.3% |
|
||||
| 10 | late param hit | oracle | 337.6 | 343.0 / 329.2 / 356.3 / 324.3 | 9.5% |
|
||||
| 10 | method miss | live | 800.4 | 762.6 / 801.2 / 798.6 / 804.4 | 5.2% |
|
||||
| 10 | method miss | oracle | 768.8 | 770.0 / 764.6 / 833.1 / 762.5 | 9.2% |
|
||||
| 10 | path miss | live | 625.5 | 594.6 / 631.3 / 620.3 / 628.1 | 5.9% |
|
||||
| 10 | path miss | oracle | 606.6 | 603.8 / 610.1 / 657.9 / 591.5 | 10.9% |
|
||||
| 100 | static hit | live | 201.2 | 202.2 / 200.8 / 197.6 / 207.2 | 4.8% |
|
||||
| 100 | static hit | oracle | 206.9 | 211.7 / 196.6 / 213.9 / 201.7 | 8.4% |
|
||||
| 100 | late param hit | live | 878.0 | 861.1 / 857.0 / 907.3 / 880.5 | 5.7% |
|
||||
| 100 | late param hit | oracle | 893.0 | 888.7 / 869.0 / 942.1 / 895.2 | 8.2% |
|
||||
| 100 | method miss | live | 2524.8 | 2424.2 / 2513.7 / 2579.6 / 2531.5 | 6.2% |
|
||||
| 100 | method miss | oracle | 2515.2 | 2473.4 / 2527.3 / 2595.9 / 2509.5 | 4.9% |
|
||||
| 100 | path miss | live | 3054.2 | 2965.2 / 3023.7 / 3113.5 / 3070.6 | 4.9% |
|
||||
| 100 | path miss | oracle | 3075.6 | 3002.5 / 3087.9 / 3179.5 / 3064.3 | 5.8% |
|
||||
| 500 | static hit | live | 202.2 | 201.8 / 202.3 / 195.1 / 210.3 | 7.5% |
|
||||
| 500 | static hit | oracle | 206.3 | 212.1 / 197.8 / 213.2 / 201.1 | 7.5% |
|
||||
| 500 | late param hit | live | 2930.6 | 2829.6 / 2804.3 / 2980.0 / 3016.2 | 7.2% |
|
||||
| 500 | late param hit | oracle | 2878.8 | 2865.8 / 2832.6 / 2916.8 / 2881.2 | 2.9% |
|
||||
| 500 | method miss | live | 11903.6 | 11635.5 / 11518.4 / 11946.5 / 12031.2 | 4.3% |
|
||||
| 500 | method miss | oracle | 12101.5 | 11822.5 / 11856.4 / 12275.6 / 12190.0 | 3.7% |
|
||||
| 500 | path miss | live | 15513.7 | 15103.4 / 14971.6 / 15664.8 / 16034.1 | 6.8% |
|
||||
| 500 | path miss | oracle | 15719.6 | 15158.8 / 15479.0 / 16084.0 / 15885.7 | 5.9% |
|
||||
|
||||
| routes | workload | B / A | median ratio | 95% CI | rounds |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 10 | static hit | oracle / live | 0.9507 (-4.9%) | 0.8629 – 1.1186 (-13.7% … +11.9%) | 84 |
|
||||
| 10 | late param hit | oracle / live | 1.0415 (+4.1%) | 0.9840 – 1.0982 (-1.6% … +9.8%) | 84 |
|
||||
| 10 | method miss | oracle / live | 0.9809 (-1.9%) | 0.9563 – 1.0076 (-4.4% … +0.8%) | 84 |
|
||||
| 10 | path miss | oracle / live | 0.9919 (-0.8%) | 0.9676 – 1.0141 (-3.2% … +1.4%) | 84 |
|
||||
| 100 | static hit | oracle / live | 1.0082 (+0.8%) | 0.9808 – 1.0453 (-1.9% … +4.5%) | 84 |
|
||||
| 100 | late param hit | oracle / live | 1.0247 (+2.5%) | 1.0192 – 1.0292 (+1.9% … +2.9%) | 84 |
|
||||
| 100 | method miss | oracle / live | 1.0055 (+0.6%) | 1.0033 – 1.0072 (+0.3% … +0.7%) | 84 |
|
||||
| 100 | path miss | oracle / live | 1.0165 (+1.7%) | 1.0119 – 1.0185 (+1.2% … +1.9%) | 84 |
|
||||
| 500 | static hit | oracle / live | 1.0107 (+1.1%) | 0.9782 – 1.0453 (-2.2% … +4.5%) | 84 |
|
||||
| 500 | late param hit | oracle / live | 0.9838 (-1.6%) | 0.9784 – 1.0076 (-2.2% … +0.8%) | 84 |
|
||||
| 500 | method miss | oracle / live | 1.0197 (+2.0%) | 1.0161 – 1.0235 (+1.6% … +2.3%) | 84 |
|
||||
| 500 | path miss | oracle / live | 1.0161 (+1.6%) | 1.0047 – 1.0257 (+0.5% … +2.6%) | 84 |
|
||||
|
||||
load average: start 0.27 0.11 0.04, end 0.79 0.31 0.12; cpuset 6-7,14-15
|
||||
raw samples: out/lookup-raw.json
|
||||
@@ -75,6 +75,15 @@ const CASES: Case[] = [
|
||||
// all-static, so it takes the full scan rather than the early exit a literal path gets.
|
||||
{ name: 'param, 50 routes', path: '/users/42', env: { GT_ROUTES: '50' } },
|
||||
{ name: 'param, 200 routes', path: '/users/42', env: { GT_ROUTES: '200' } },
|
||||
// Compression (CARD-16). `json 8KB uncompressed` is the same response uncompressed, so each compressed case
|
||||
// has its own baseline in the table. `hello + compression` sits under the threshold: the cost of
|
||||
// deciding not to encode, which is what most small responses pay once compression is on. Without
|
||||
// `accept-encoding`, the 8 KB case measures negotiation alone.
|
||||
{ name: 'json 8KB uncompressed', path: '/big' },
|
||||
{ name: 'hello + compression', path: '/hello', env: { GT_COMPRESS: '1' }, headers: { 'accept-encoding': 'gzip, br' } },
|
||||
{ name: 'json 8KB + compression, identity', path: '/big', env: { GT_COMPRESS: '1' } },
|
||||
{ name: 'json 8KB + gzip', path: '/big', env: { GT_COMPRESS: '1' }, headers: { 'accept-encoding': 'gzip' } },
|
||||
{ name: 'json 8KB + br', path: '/big', env: { GT_COMPRESS: '1' }, headers: { 'accept-encoding': 'br' } },
|
||||
];
|
||||
|
||||
const ONLY = process.env.AB_ONLY;
|
||||
|
||||
+358
@@ -0,0 +1,358 @@
|
||||
/**
|
||||
* Focused route-lookup benchmark — the D4 instrument for the radix router (FPRD-001 CARD-08/10, #109).
|
||||
*
|
||||
* `bench:compare` measures req/s end to end, where lookup is a few percent of a request and drowns
|
||||
* in socket and pipeline noise. This measures the lookup alone: exactly what `dispatch` in
|
||||
* `src/http/core.ts` does with an already-normalized path — `resolveRoute`, and on a miss
|
||||
* `allowedMethods` for the 404/405 decision. Normalization is excluded: CARD-07 does not touch it.
|
||||
*
|
||||
* Usage:
|
||||
*
|
||||
* npm run bench:lookup
|
||||
* LOOKUP_ROUTERS="base=/tmp/base/src/http/router.ts,head=src/http/router.ts" npm run bench:lookup
|
||||
* LOOKUP_ROUTERS="live=src/http/router.ts,oracle=test/router-parity/oracle.ts" npm run bench:lookup # A/A
|
||||
*
|
||||
* Each router is a module exporting `resolveRoute` and `allowedMethods` with the `src/http/router.ts`
|
||||
* signatures. All routers are loaded into the same process and **interleaved**: per cell, every
|
||||
* router is warmed, then each round takes one sample from each router, alternating which goes first
|
||||
* (AB, BA, AB, ...). Fresh processes alternate the whole router order, warm-up included. Every router after the first is reported against the first as the median of the
|
||||
* per-round B/A ratios, with a bootstrap 95% CI. Interleaving puts drift and background load on both
|
||||
* sides of each ratio instead of on whichever ran later. With one router it reports absolute numbers
|
||||
* only. Do not edit the generator, the workloads or the defaults between a baseline and its
|
||||
* comparison: they are the method.
|
||||
*
|
||||
* Env: `LOOKUP_ROUTERS` (label=path list, default `live=src/http/router.ts`), `LOOKUP_RUNS` (4 fresh
|
||||
* processes, router order alternating), `LOOKUP_ROUNDS` (21 per cell per run, minimum 15), `LOOKUP_SAMPLE_MS` (25),
|
||||
* `LOOKUP_WARMUP_MS` (250 per router per cell), `LOOKUP_OUT` (bench/lookup-results.json). Any other
|
||||
* `LOOKUP_*` variable (e.g. `LOOKUP_HOST`, `LOOKUP_CPUSET`) is copied into the record as a note.
|
||||
*/
|
||||
import { spawn, execFileSync } from 'child_process';
|
||||
import { writeFileSync, readFileSync } from 'fs';
|
||||
import os from 'os';
|
||||
import { dirname, resolve } from 'path';
|
||||
import { pathToFileURL } from 'url';
|
||||
|
||||
const ROUTE_COUNTS = [10, 100, 500];
|
||||
const RUNS = Number(process.env.LOOKUP_RUNS ?? 4);
|
||||
const ROUNDS = Math.max(15, Number(process.env.LOOKUP_ROUNDS ?? 21));
|
||||
const BOOTSTRAP = 4000;
|
||||
const SAMPLE_MS = Number(process.env.LOOKUP_SAMPLE_MS ?? 25);
|
||||
const WARMUP_MS = Number(process.env.LOOKUP_WARMUP_MS ?? 250);
|
||||
const OUT = process.env.LOOKUP_OUT ?? 'bench/lookup-results.json';
|
||||
|
||||
interface Route {
|
||||
method: string;
|
||||
pattern: string;
|
||||
transport: 'buffer';
|
||||
handler: () => Promise<{ status: number; headers: Record<string, string>; body: string }>;
|
||||
}
|
||||
|
||||
interface RouterModule {
|
||||
resolveRoute(routes: Route[], method: string, path: string): { def: Route } | undefined;
|
||||
allowedMethods(routes: Route[], path: string): string[];
|
||||
}
|
||||
|
||||
/** Five REST-shaped filler routes per resource, cycled, so every count has statics, params, constraints and catch-alls. */
|
||||
const FILLER: Array<(k: number) => [string, string]> = [
|
||||
(k) => ['GET', `/res${k}/items`],
|
||||
(k) => ['POST', `/res${k}/items`],
|
||||
(k) => ['GET', `/res${k}/items/:id`],
|
||||
(k) => ['PUT', `/res${k}/items/:id(\\d+)`],
|
||||
(k) => ['GET', `/res${k}/files/:path*`],
|
||||
];
|
||||
|
||||
export const ROUTE_GENERATOR =
|
||||
'N total HTTP routes: N-2 fillers (i = 0..N-3, shape FILLER[i % 5] with k = floor(i / 5): GET /res{k}/items, ' +
|
||||
'POST /res{k}/items, GET /res{k}/items/:id, PUT /res{k}/items/:id(\\d+), GET /res{k}/files/:path*), then ' +
|
||||
'GET /static/target/leaf, then GET /late/:group/:id declared last. All buffer transport.';
|
||||
|
||||
const handler = async () => ({ status: 200, headers: {}, body: '' });
|
||||
|
||||
export function buildRoutes(total: number): Route[] {
|
||||
const fillers = Array.from({ length: total - 2 }, (_, i): Route => {
|
||||
const [method, pattern] = FILLER[i % FILLER.length](Math.floor(i / FILLER.length));
|
||||
return { method, pattern, transport: 'buffer', handler };
|
||||
});
|
||||
return [
|
||||
...fillers,
|
||||
{ method: 'GET', pattern: '/static/target/leaf', transport: 'buffer', handler },
|
||||
{ method: 'GET', pattern: '/late/:group/:id', transport: 'buffer', handler },
|
||||
];
|
||||
}
|
||||
|
||||
interface Workload {
|
||||
name: string;
|
||||
method: string;
|
||||
path: string;
|
||||
/** What the lookup must answer; checked before timing, so a broken implementation cannot post a number. */
|
||||
expect: string;
|
||||
}
|
||||
|
||||
export const WORKLOADS: Workload[] = [
|
||||
{ name: 'static hit', method: 'GET', path: '/static/target/leaf', expect: 'hit /static/target/leaf' },
|
||||
{ name: 'late param hit', method: 'GET', path: '/late/g1/42', expect: 'hit /late/:group/:id' },
|
||||
{ name: 'method miss', method: 'DELETE', path: '/static/target/leaf', expect: 'allow GET,HEAD,OPTIONS' },
|
||||
{ name: 'path miss', method: 'GET', path: '/nowhere/at/all', expect: 'allow ' },
|
||||
];
|
||||
|
||||
/** One lookup, as `dispatch` performs it. Returns a value so the work cannot be optimised away. */
|
||||
function lookup(router: RouterModule, routes: Route[], w: Workload): string {
|
||||
const matched = router.resolveRoute(routes, w.method, w.path);
|
||||
if (matched) return `hit ${matched.def.pattern}`;
|
||||
return `allow ${router.allowedMethods(routes, w.path).join(',')}`;
|
||||
}
|
||||
|
||||
interface Cell {
|
||||
routes: number;
|
||||
workload: string;
|
||||
/** Calibrated per router; a sample is `iterations` lookups. */
|
||||
iterations: Record<string, number>;
|
||||
/** Round order, e.g. ['live', 'oracle'] then ['oracle', 'live']. */
|
||||
orders: string[][];
|
||||
/** One entry per router, one sample (ns per lookup) per round, in round order. */
|
||||
samplesNs: Record<string, number[]>;
|
||||
}
|
||||
|
||||
type Loaded = Array<{ label: string; router: RouterModule }>;
|
||||
|
||||
let sink = 0;
|
||||
|
||||
function warm(router: RouterModule, routes: Route[], w: Workload): number {
|
||||
const answer = lookup(router, routes, w);
|
||||
if (answer !== w.expect) throw new Error(`${w.name} @ ${routes.length}: expected '${w.expect}', got '${answer}'`);
|
||||
|
||||
// Time-boxed; it also calibrates how many iterations make one sample last SAMPLE_MS.
|
||||
let ops = 0;
|
||||
const warmStart = process.hrtime.bigint();
|
||||
const warmBudget = BigInt(WARMUP_MS * 1_000_000);
|
||||
while (process.hrtime.bigint() - warmStart < warmBudget) {
|
||||
for (let i = 0; i < 100; i++) sink += lookup(router, routes, w).length;
|
||||
ops += 100;
|
||||
}
|
||||
const nsPerOp = Number(process.hrtime.bigint() - warmStart) / ops;
|
||||
return Math.max(100, Math.round((SAMPLE_MS * 1e6) / nsPerOp));
|
||||
}
|
||||
|
||||
function sample(router: RouterModule, routes: Route[], w: Workload, iterations: number): number {
|
||||
const start = process.hrtime.bigint();
|
||||
for (let i = 0; i < iterations; i++) sink += lookup(router, routes, w).length;
|
||||
return Number(process.hrtime.bigint() - start) / iterations;
|
||||
}
|
||||
|
||||
function measureCell(loaded: Loaded, routes: Route[], w: Workload): Cell {
|
||||
const iterations: Record<string, number> = {};
|
||||
const samplesNs: Record<string, number[]> = {};
|
||||
const orders: string[][] = [];
|
||||
|
||||
for (const { label, router } of loaded) {
|
||||
iterations[label] = warm(router, routes, w);
|
||||
samplesNs[label] = [];
|
||||
}
|
||||
|
||||
for (let round = 0; round < ROUNDS; round++) {
|
||||
const order = round % 2 === 0 ? loaded : [...loaded].reverse();
|
||||
orders.push(order.map(({ label }) => label));
|
||||
for (const { label, router } of order) samplesNs[label].push(sample(router, routes, w, iterations[label]));
|
||||
}
|
||||
|
||||
return { routes: routes.length, workload: w.name, iterations, orders, samplesNs };
|
||||
}
|
||||
|
||||
async function child(routers: Array<[string, string]>): Promise<void> {
|
||||
// Router order alternates per run (LOOKUP_IMPORT_REVERSED): import order, warm-up order and which
|
||||
// router opens each cell's first round. Whichever router V8 sees first, in import or in the shared
|
||||
// `lookup` call site, can bias an in-process comparison of otherwise identical code; alternating
|
||||
// all of it spreads that over both sides. Reversing only the import order left an A/A bias of up
|
||||
// to +8% on the second-listed router (CARD-10).
|
||||
const ordered = process.env.LOOKUP_IMPORT_REVERSED === '1' ? [...routers].reverse() : routers;
|
||||
const loaded: Loaded = [];
|
||||
for (const [label, path] of ordered)
|
||||
loaded.push({ label, router: (await import(pathToFileURL(resolve(path)).href)) as RouterModule });
|
||||
|
||||
const cells: Cell[] = [];
|
||||
for (const count of ROUTE_COUNTS) {
|
||||
const routes = buildRoutes(count);
|
||||
for (const w of WORKLOADS) cells.push(measureCell(loaded, routes, w));
|
||||
}
|
||||
|
||||
if (sink === 42) process.stderr.write(''); // keeps `sink` observable
|
||||
process.stdout.write(`${JSON.stringify({ cells })}\n`);
|
||||
}
|
||||
|
||||
function runChild(spec: string, importReversed: boolean): Promise<{ cells: Cell[] }> {
|
||||
return new Promise((resolvePromise, reject) => {
|
||||
const proc = spawn(process.execPath, ['--import', 'tsx', 'bench/lookup.ts'], {
|
||||
env: { ...process.env, LOOKUP_CHILD: spec, LOOKUP_IMPORT_REVERSED: importReversed ? '1' : '0' },
|
||||
stdio: ['ignore', 'pipe', 'inherit'],
|
||||
});
|
||||
let out = '';
|
||||
proc.stdout.on('data', (d) => (out += d));
|
||||
proc.on('exit', (code) =>
|
||||
code === 0 ? resolvePromise(JSON.parse(out)) : reject(new Error(`child exited ${code}`)),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
const median = (xs: number[]): number => {
|
||||
const s = [...xs].sort((a, b) => a - b);
|
||||
const m = s.length >> 1;
|
||||
return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
|
||||
};
|
||||
|
||||
/** Deterministic PRNG for the bootstrap, so the same raw samples always give the same interval. */
|
||||
function mulberry32(seed: number): () => number {
|
||||
let state = seed >>> 0;
|
||||
return () => {
|
||||
state = (state + 0x6d2b79f5) >>> 0;
|
||||
let t = state;
|
||||
t = Math.imul(t ^ (t >>> 15), t | 1);
|
||||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
/** Percentile bootstrap 95% CI of the median of `xs`. */
|
||||
function bootstrapMedianCi(xs: number[]): [number, number] {
|
||||
const rng = mulberry32(10908);
|
||||
const medians: number[] = [];
|
||||
for (let b = 0; b < BOOTSTRAP; b++) medians.push(median(xs.map(() => xs[Math.floor(rng() * xs.length)])));
|
||||
medians.sort((a, b) => a - b);
|
||||
return [medians[Math.floor(BOOTSTRAP * 0.025)], medians[Math.ceil(BOOTSTRAP * 0.975) - 1]];
|
||||
}
|
||||
|
||||
function git(cwd: string, ...args: string[]): string {
|
||||
try {
|
||||
return execFileSync('git', ['-C', cwd, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
|
||||
} catch {
|
||||
return 'unavailable';
|
||||
}
|
||||
}
|
||||
|
||||
function cpuset(): string {
|
||||
for (const file of ['/sys/fs/cgroup/cpuset.cpus.effective', '/sys/fs/cgroup/cpuset/cpuset.effective_cpus']) {
|
||||
try {
|
||||
return readFileSync(file, 'utf8').trim();
|
||||
} catch {
|
||||
/* not Linux, or not this cgroup layout */
|
||||
}
|
||||
}
|
||||
return 'n/a';
|
||||
}
|
||||
|
||||
function environment(routers: Array<[string, string]>) {
|
||||
const pkg = JSON.parse(readFileSync('package.json', 'utf8')) as { name: string; version: string };
|
||||
return {
|
||||
startedAt: new Date().toISOString(),
|
||||
hostname: os.hostname(),
|
||||
node: process.version,
|
||||
v8: process.versions.v8,
|
||||
platform: `${os.platform()} ${os.release()} ${os.arch()}`,
|
||||
cpu: os.cpus()[0]?.model,
|
||||
cpus: os.cpus().length,
|
||||
cpuset: cpuset(),
|
||||
memoryBytes: os.totalmem(),
|
||||
loadavgAtStart: os.loadavg(),
|
||||
package: `${pkg.name}@${pkg.version}`,
|
||||
harnessCommit: process.env.LOOKUP_COMMIT ?? git('.', 'rev-parse', 'HEAD'),
|
||||
routers: routers.map(([label, path]) => ({ label, path })),
|
||||
env: Object.fromEntries(
|
||||
Object.entries(process.env).filter(([k]) => k.startsWith('LOOKUP_') || k === 'NODE_OPTIONS'),
|
||||
),
|
||||
method: {
|
||||
routeCounts: ROUTE_COUNTS,
|
||||
routeCountMeaning: 'total registered HTTP routes',
|
||||
routeGenerator: ROUTE_GENERATOR,
|
||||
workloads: WORKLOADS,
|
||||
workloadOrder:
|
||||
'for each run (fresh process; module import order reversed on even-numbered runs): for count in routeCounts: ' +
|
||||
'for workload in workloads: warm every router, ' +
|
||||
'then ROUNDS rounds of one sample per router, order alternating AB/BA per round',
|
||||
operation: 'resolveRoute(routes, method, path); on undefined, allowedMethods(routes, path)',
|
||||
runs: RUNS,
|
||||
roundsPerCellPerRun: ROUNDS,
|
||||
sampleMs: SAMPLE_MS,
|
||||
warmupMsPerRouterPerCell: WARMUP_MS,
|
||||
ratio: 'per round, sample(B) / sample(A) with A the first router; median over all rounds of all runs',
|
||||
ci: `percentile bootstrap of the median ratio, ${BOOTSTRAP} resamples, seed 10908`,
|
||||
unit: 'ns per lookup (sample time / iterations)',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function summarize(labels: string[], runs: Array<{ run: number; cells: Cell[] }>) {
|
||||
return ROUTE_COUNTS.flatMap((count) =>
|
||||
WORKLOADS.map((w) => {
|
||||
const cells = runs.map((r) => r.cells.find((c) => c.routes === count && c.workload === w.name)!);
|
||||
const routers = labels.map((label) => {
|
||||
const runMedians = cells.map((c) => median(c.samplesNs[label]));
|
||||
const med = median(cells.flatMap((c) => c.samplesNs[label]));
|
||||
return {
|
||||
router: label,
|
||||
medianNs: med,
|
||||
runMediansNs: runMedians,
|
||||
runSpreadPct: ((Math.max(...runMedians) - Math.min(...runMedians)) / med) * 100,
|
||||
};
|
||||
});
|
||||
const ratios = labels.slice(1).map((label) => {
|
||||
const paired = cells.flatMap((c) => c.samplesNs[label].map((b, i) => b / c.samplesNs[labels[0]][i]));
|
||||
const [low, high] = bootstrapMedianCi(paired);
|
||||
return { b: label, a: labels[0], medianRatio: median(paired), ci95: [low, high], rounds: paired.length };
|
||||
});
|
||||
return { routes: count, workload: w.name, routers, ratios };
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const pct = (ratio: number): string => `${ratio >= 1 ? '+' : ''}${((ratio - 1) * 100).toFixed(1)}%`;
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const spec = process.env.LOOKUP_CHILD
|
||||
? process.env.LOOKUP_CHILD
|
||||
: (process.env.LOOKUP_ROUTERS ?? 'live=src/http/router.ts');
|
||||
const routers = spec.split(',').map((entry) => entry.split('=') as [string, string]);
|
||||
if (process.env.LOOKUP_CHILD) return child(routers);
|
||||
|
||||
const labels = routers.map(([label]) => label);
|
||||
const meta = environment(routers);
|
||||
const runs: Array<{ run: number; importReversed: boolean; cells: Cell[] }> = [];
|
||||
|
||||
for (let run = 0; run < RUNS; run++) {
|
||||
runs.push({ run: run + 1, importReversed: run % 2 === 1, ...(await runChild(spec, run % 2 === 1)) });
|
||||
process.stderr.write(`[lookup] run ${run + 1}/${RUNS} done\n`);
|
||||
}
|
||||
|
||||
const summary = summarize(labels, runs);
|
||||
const loadavgAtEnd = os.loadavg();
|
||||
writeFileSync(OUT, `${JSON.stringify({ meta: { ...meta, loadavgAtEnd }, summary, runs }, null, 2)}\n`);
|
||||
|
||||
console.log('| routes | workload | router | median ns/op | run medians (ns) | run spread |');
|
||||
console.log('| --- | --- | --- | --- | --- | --- |');
|
||||
for (const cell of summary)
|
||||
for (const r of cell.routers)
|
||||
console.log(
|
||||
`| ${cell.routes} | ${cell.workload} | ${r.router} | ${r.medianNs.toFixed(1)} | ` +
|
||||
`${r.runMediansNs.map((n) => n.toFixed(1)).join(' / ')} | ${r.runSpreadPct.toFixed(1)}% |`,
|
||||
);
|
||||
|
||||
if (labels.length > 1) {
|
||||
console.log('\n| routes | workload | B / A | median ratio | 95% CI | rounds |');
|
||||
console.log('| --- | --- | --- | --- | --- | --- |');
|
||||
for (const cell of summary)
|
||||
for (const r of cell.ratios)
|
||||
console.log(
|
||||
`| ${cell.routes} | ${cell.workload} | ${r.b} / ${r.a} | ${r.medianRatio.toFixed(4)} (${pct(r.medianRatio)}) | ` +
|
||||
`${r.ci95.map((x) => x.toFixed(4)).join(' – ')} (${pct(r.ci95[0])} … ${pct(r.ci95[1])}) | ${r.rounds} |`,
|
||||
);
|
||||
}
|
||||
|
||||
console.log(
|
||||
`\nload average: start ${meta.loadavgAtStart.map((n) => n.toFixed(2)).join(' ')}, ` +
|
||||
`end ${loadavgAtEnd.map((n) => n.toFixed(2)).join(' ')}; cpuset ${meta.cpuset}`,
|
||||
);
|
||||
console.log(`raw samples: ${OUT}`);
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
});
|
||||
+197
-197
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"env": {
|
||||
"date": "2026-09-22",
|
||||
"commit": "daf0fed",
|
||||
"node": "v22.22.2",
|
||||
"date": "2026-10-29",
|
||||
"commit": "4566f31",
|
||||
"node": "v22.23.1",
|
||||
"os": "linux",
|
||||
"cpu": "AMD Ryzen 7 3700X 8-Core Processor (16 cores)",
|
||||
"ram": "67 GB",
|
||||
@@ -23,11 +23,11 @@
|
||||
{
|
||||
"framework": "raw-http",
|
||||
"reqSec": {
|
||||
"median": 41630.55,
|
||||
"min": 41342.55,
|
||||
"max": 41973.82,
|
||||
"stddev": 232.79156158245826,
|
||||
"cv": 0.0055977118567263305
|
||||
"median": 47469.1,
|
||||
"min": 47192.73,
|
||||
"max": 48004.37,
|
||||
"stddev": 269.02890451399486,
|
||||
"cv": 0.0056617632193964144
|
||||
},
|
||||
"p50": 2,
|
||||
"p99": 3,
|
||||
@@ -36,67 +36,67 @@
|
||||
{
|
||||
"framework": "fastify",
|
||||
"reqSec": {
|
||||
"median": 32170.19,
|
||||
"min": 31235.64,
|
||||
"max": 32355.64,
|
||||
"stddev": 403.36620390905324,
|
||||
"cv": 0.012593571579786219
|
||||
"median": 36740.37,
|
||||
"min": 36641.46,
|
||||
"max": 37243.64,
|
||||
"stddev": 214.65425409248226,
|
||||
"cv": 0.005826132913876785
|
||||
},
|
||||
"p50": 3,
|
||||
"p50": 2,
|
||||
"p99": 3,
|
||||
"p999": 5
|
||||
"p999": 4
|
||||
},
|
||||
{
|
||||
"framework": "express",
|
||||
"reqSec": {
|
||||
"median": 10545.82,
|
||||
"min": 10480.37,
|
||||
"max": 10625.1,
|
||||
"stddev": 47.02831087759791,
|
||||
"cv": 0.004456044641032285
|
||||
"median": 11098.55,
|
||||
"min": 11000.37,
|
||||
"max": 11182.91,
|
||||
"stddev": 66.7811100836154,
|
||||
"cv": 0.006025867495164444
|
||||
},
|
||||
"p50": 8,
|
||||
"p99": 13,
|
||||
"p999": 18
|
||||
"p99": 12,
|
||||
"p999": 14
|
||||
},
|
||||
{
|
||||
"framework": "green-tea",
|
||||
"reqSec": {
|
||||
"median": 29776.73,
|
||||
"min": 29557.1,
|
||||
"max": 29872.73,
|
||||
"stddev": 120.92248317000461,
|
||||
"cv": 0.004066812850878315
|
||||
"median": 37598.55,
|
||||
"min": 37162.19,
|
||||
"max": 37653.82,
|
||||
"stddev": 180.19629658791482,
|
||||
"cv": 0.004804609848274523
|
||||
},
|
||||
"p50": 3,
|
||||
"p99": 6,
|
||||
"p999": 7
|
||||
"p50": 2,
|
||||
"p99": 3,
|
||||
"p999": 5
|
||||
},
|
||||
{
|
||||
"framework": "nestjs-express",
|
||||
"reqSec": {
|
||||
"median": 9679.64,
|
||||
"min": 9566.91,
|
||||
"max": 9738.55,
|
||||
"stddev": 58.2951632985104,
|
||||
"cv": 0.006025529205104781
|
||||
"median": 10066.55,
|
||||
"min": 9990.91,
|
||||
"max": 10121.6,
|
||||
"stddev": 49.181765970733586,
|
||||
"cv": 0.0048902075440459426
|
||||
},
|
||||
"p50": 9,
|
||||
"p99": 15,
|
||||
"p999": 21
|
||||
"p99": 13,
|
||||
"p999": 16
|
||||
},
|
||||
{
|
||||
"framework": "nestjs-fastify",
|
||||
"reqSec": {
|
||||
"median": 32418.91,
|
||||
"min": 32103.28,
|
||||
"max": 32582.55,
|
||||
"stddev": 159.574135748874,
|
||||
"cv": 0.004929287112917938
|
||||
"median": 36205.1,
|
||||
"min": 35969.46,
|
||||
"max": 36626.91,
|
||||
"stddev": 239.33000477165558,
|
||||
"cv": 0.006602437612625466
|
||||
},
|
||||
"p50": 3,
|
||||
"p99": 4,
|
||||
"p999": 6
|
||||
"p50": 2,
|
||||
"p99": 3,
|
||||
"p999": 4
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -107,11 +107,11 @@
|
||||
{
|
||||
"framework": "raw-http",
|
||||
"reqSec": {
|
||||
"median": 41755.64,
|
||||
"min": 40952.73,
|
||||
"max": 42017.46,
|
||||
"stddev": 439.72294183496837,
|
||||
"cv": 0.010587809774433589
|
||||
"median": 47661.1,
|
||||
"min": 47061.82,
|
||||
"max": 48027.64,
|
||||
"stddev": 334.1152775914324,
|
||||
"cv": 0.007027904143674679
|
||||
},
|
||||
"p50": 2,
|
||||
"p99": 3,
|
||||
@@ -120,67 +120,67 @@
|
||||
{
|
||||
"framework": "fastify",
|
||||
"reqSec": {
|
||||
"median": 31708.37,
|
||||
"min": 31359.28,
|
||||
"max": 31846.55,
|
||||
"stddev": 168.73300179869975,
|
||||
"cv": 0.005328784944282288
|
||||
"median": 36135.28,
|
||||
"min": 35867.64,
|
||||
"max": 36391.28,
|
||||
"stddev": 184.11967651503156,
|
||||
"cv": 0.005092910836977374
|
||||
},
|
||||
"p50": 3,
|
||||
"p99": 4,
|
||||
"p999": 5
|
||||
"p50": 2,
|
||||
"p99": 3,
|
||||
"p999": 4
|
||||
},
|
||||
{
|
||||
"framework": "express",
|
||||
"reqSec": {
|
||||
"median": 10375.64,
|
||||
"min": 10364,
|
||||
"max": 10452.73,
|
||||
"stddev": 37.668132419858544,
|
||||
"cv": 0.003621859193349617
|
||||
"median": 10889.1,
|
||||
"min": 10872.37,
|
||||
"max": 10924.73,
|
||||
"stddev": 18.709325375330668,
|
||||
"cv": 0.0017176428734098992
|
||||
},
|
||||
"p50": 9,
|
||||
"p50": 8,
|
||||
"p99": 12,
|
||||
"p999": 17
|
||||
"p999": 14
|
||||
},
|
||||
{
|
||||
"framework": "green-tea",
|
||||
"reqSec": {
|
||||
"median": 28706.19,
|
||||
"min": 28562.19,
|
||||
"max": 29050.91,
|
||||
"stddev": 166.92265315408858,
|
||||
"cv": 0.005803163694455583
|
||||
"median": 35000.73,
|
||||
"min": 34878.55,
|
||||
"max": 35088,
|
||||
"stddev": 69.54965035138484,
|
||||
"cv": 0.001987752137162527
|
||||
},
|
||||
"p50": 3,
|
||||
"p99": 6,
|
||||
"p999": 7
|
||||
"p50": 2,
|
||||
"p99": 4,
|
||||
"p999": 5
|
||||
},
|
||||
{
|
||||
"framework": "nestjs-express",
|
||||
"reqSec": {
|
||||
"median": 9257.1,
|
||||
"min": 9244,
|
||||
"max": 9285.46,
|
||||
"stddev": 16.97885461390117,
|
||||
"cv": 0.0018327336012062287
|
||||
"median": 9589.46,
|
||||
"min": 9534.91,
|
||||
"max": 9676,
|
||||
"stddev": 49.39604299941435,
|
||||
"cv": 0.0051436658697942604
|
||||
},
|
||||
"p50": 10,
|
||||
"p99": 15,
|
||||
"p999": 21
|
||||
"p99": 14,
|
||||
"p999": 16
|
||||
},
|
||||
{
|
||||
"framework": "nestjs-fastify",
|
||||
"reqSec": {
|
||||
"median": 29880,
|
||||
"min": 29744.73,
|
||||
"max": 29961.46,
|
||||
"stddev": 90.38256681462417,
|
||||
"cv": 0.003027383166346
|
||||
"median": 33253.1,
|
||||
"min": 32969.46,
|
||||
"max": 33756,
|
||||
"stddev": 254.90284160048154,
|
||||
"cv": 0.007652733271277979
|
||||
},
|
||||
"p50": 3,
|
||||
"p99": 4,
|
||||
"p999": 6
|
||||
"p99": 3,
|
||||
"p999": 4
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -192,80 +192,80 @@
|
||||
{
|
||||
"framework": "raw-http",
|
||||
"reqSec": {
|
||||
"median": 39896.73,
|
||||
"min": 39847.28,
|
||||
"max": 40440.73,
|
||||
"stddev": 235.6558649726337,
|
||||
"cv": 0.0058846766178520865
|
||||
"median": 46360.73,
|
||||
"min": 46192,
|
||||
"max": 46509.1,
|
||||
"stddev": 111.17974682467946,
|
||||
"cv": 0.002398415644709733
|
||||
},
|
||||
"p50": 2,
|
||||
"p99": 3,
|
||||
"p999": 4
|
||||
},
|
||||
{
|
||||
"framework": "fastify",
|
||||
"reqSec": {
|
||||
"median": 35329.46,
|
||||
"min": 35026.91,
|
||||
"max": 35536,
|
||||
"stddev": 189.35963174868976,
|
||||
"cv": 0.0053689295267283325
|
||||
},
|
||||
"p50": 2,
|
||||
"p99": 3,
|
||||
"p999": 5
|
||||
},
|
||||
{
|
||||
"framework": "fastify",
|
||||
"reqSec": {
|
||||
"median": 31436.37,
|
||||
"min": 31078.55,
|
||||
"max": 31562.91,
|
||||
"stddev": 185.21052212010017,
|
||||
"cv": 0.005909263441314207
|
||||
},
|
||||
"p50": 3,
|
||||
"p99": 4,
|
||||
"p999": 6
|
||||
},
|
||||
{
|
||||
"framework": "express",
|
||||
"reqSec": {
|
||||
"median": 10365.46,
|
||||
"min": 10170.55,
|
||||
"max": 10542.19,
|
||||
"stddev": 129.83340146510884,
|
||||
"cv": 0.01252603707960138
|
||||
"median": 10935.64,
|
||||
"min": 10754.55,
|
||||
"max": 11023.64,
|
||||
"stddev": 90.09481170411546,
|
||||
"cv": 0.008251152407480157
|
||||
},
|
||||
"p50": 9,
|
||||
"p99": 12,
|
||||
"p999": 18
|
||||
"p50": 8,
|
||||
"p99": 13,
|
||||
"p999": 14
|
||||
},
|
||||
{
|
||||
"framework": "green-tea",
|
||||
"reqSec": {
|
||||
"median": 26838.55,
|
||||
"min": 26783.28,
|
||||
"max": 26872,
|
||||
"stddev": 35.930271582608675,
|
||||
"cv": 0.0013390899572667937
|
||||
"median": 33374.55,
|
||||
"min": 33092.37,
|
||||
"max": 33568.73,
|
||||
"stddev": 154.68541992056046,
|
||||
"cv": 0.004639644133664113
|
||||
},
|
||||
"p50": 3,
|
||||
"p99": 6,
|
||||
"p999": 8
|
||||
"p50": 2,
|
||||
"p99": 3,
|
||||
"p999": 5
|
||||
},
|
||||
{
|
||||
"framework": "nestjs-express",
|
||||
"reqSec": {
|
||||
"median": 9256.37,
|
||||
"min": 9187.28,
|
||||
"max": 9302.19,
|
||||
"stddev": 42.180541200890175,
|
||||
"cv": 0.0045584972844857205
|
||||
"median": 9605.46,
|
||||
"min": 9484.73,
|
||||
"max": 9652,
|
||||
"stddev": 62.41935917646065,
|
||||
"cv": 0.006518360010616271
|
||||
},
|
||||
"p50": 10,
|
||||
"p99": 15,
|
||||
"p999": 22
|
||||
"p99": 14,
|
||||
"p999": 17
|
||||
},
|
||||
{
|
||||
"framework": "nestjs-fastify",
|
||||
"reqSec": {
|
||||
"median": 29402.91,
|
||||
"min": 29151.28,
|
||||
"max": 29689.46,
|
||||
"stddev": 189.99449229911926,
|
||||
"cv": 0.006460862473261261
|
||||
"median": 32767.28,
|
||||
"min": 32559.28,
|
||||
"max": 32994.91,
|
||||
"stddev": 150.4312969298629,
|
||||
"cv": 0.004587519776661802
|
||||
},
|
||||
"p50": 3,
|
||||
"p99": 4,
|
||||
"p999": 6
|
||||
"p99": 3,
|
||||
"p999": 4
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -276,80 +276,80 @@
|
||||
{
|
||||
"framework": "raw-http",
|
||||
"reqSec": {
|
||||
"median": 31783.28,
|
||||
"min": 31517.1,
|
||||
"max": 31824.73,
|
||||
"stddev": 111.5598838292694,
|
||||
"cv": 0.003516116881358333
|
||||
"median": 34945.46,
|
||||
"min": 34637.1,
|
||||
"max": 35079.28,
|
||||
"stddev": 147.87762107905314,
|
||||
"cv": 0.004238372721839537
|
||||
},
|
||||
"p50": 3,
|
||||
"p99": 5,
|
||||
"p999": 6
|
||||
"p50": 2,
|
||||
"p99": 3,
|
||||
"p999": 5
|
||||
},
|
||||
{
|
||||
"framework": "fastify",
|
||||
"reqSec": {
|
||||
"median": 20429.82,
|
||||
"min": 20397.82,
|
||||
"max": 20601.46,
|
||||
"stddev": 73.12471046096515,
|
||||
"cv": 0.0035727493036941836
|
||||
"median": 28345.46,
|
||||
"min": 28239.28,
|
||||
"max": 28537.46,
|
||||
"stddev": 104.51947619463081,
|
||||
"cv": 0.0036825069822342044
|
||||
},
|
||||
"p50": 4,
|
||||
"p99": 8,
|
||||
"p999": 9
|
||||
"p50": 3,
|
||||
"p99": 4,
|
||||
"p999": 6
|
||||
},
|
||||
{
|
||||
"framework": "express",
|
||||
"reqSec": {
|
||||
"median": 8440.37,
|
||||
"min": 8407.64,
|
||||
"max": 8492,
|
||||
"stddev": 29.52737333390846,
|
||||
"cv": 0.003496408589959768
|
||||
"median": 9019.28,
|
||||
"min": 8984.91,
|
||||
"max": 9084,
|
||||
"stddev": 32.592512391652114,
|
||||
"cv": 0.003611277084889395
|
||||
},
|
||||
"p50": 11,
|
||||
"p99": 16,
|
||||
"p999": 24
|
||||
"p50": 10,
|
||||
"p99": 14,
|
||||
"p999": 22
|
||||
},
|
||||
{
|
||||
"framework": "green-tea",
|
||||
"reqSec": {
|
||||
"median": 22005.1,
|
||||
"min": 21736,
|
||||
"max": 22186.91,
|
||||
"stddev": 149.1731413626461,
|
||||
"cv": 0.006790967759795645
|
||||
"median": 24495.28,
|
||||
"min": 24378.91,
|
||||
"max": 24745.46,
|
||||
"stddev": 131.18982628237575,
|
||||
"cv": 0.005350572306127685
|
||||
},
|
||||
"p50": 4,
|
||||
"p99": 7,
|
||||
"p999": 9
|
||||
"p99": 5,
|
||||
"p999": 7
|
||||
},
|
||||
{
|
||||
"framework": "nestjs-express",
|
||||
"reqSec": {
|
||||
"median": 7666.37,
|
||||
"min": 7645.28,
|
||||
"max": 7703.46,
|
||||
"stddev": 20.418688106732038,
|
||||
"cv": 0.002662071942974812
|
||||
"median": 8107.1,
|
||||
"min": 8077.82,
|
||||
"max": 8165.64,
|
||||
"stddev": 33.73639957079006,
|
||||
"cv": 0.004157687523312779
|
||||
},
|
||||
"p50": 12,
|
||||
"p99": 18,
|
||||
"p50": 11,
|
||||
"p99": 17,
|
||||
"p999": 26
|
||||
},
|
||||
{
|
||||
"framework": "nestjs-fastify",
|
||||
"reqSec": {
|
||||
"median": 18596.8,
|
||||
"min": 18540.37,
|
||||
"max": 18658.19,
|
||||
"stddev": 37.943211988443956,
|
||||
"cv": 0.0020404741150848267
|
||||
"median": 24102.55,
|
||||
"min": 23728.73,
|
||||
"max": 24163.64,
|
||||
"stddev": 190.77768416667587,
|
||||
"cv": 0.007957219028998775
|
||||
},
|
||||
"p50": 4,
|
||||
"p99": 8,
|
||||
"p999": 11
|
||||
"p99": 6,
|
||||
"p999": 7
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -358,89 +358,89 @@
|
||||
{
|
||||
"path": "/steps/0",
|
||||
"steps": 0,
|
||||
"reqSec": 29196.37
|
||||
"reqSec": 36423.28
|
||||
},
|
||||
{
|
||||
"path": "/steps/3",
|
||||
"steps": 3,
|
||||
"reqSec": 26563.64
|
||||
"reqSec": 32436.37
|
||||
},
|
||||
{
|
||||
"path": "/steps/5",
|
||||
"steps": 5,
|
||||
"reqSec": 25314.19
|
||||
"reqSec": 30549.1
|
||||
}
|
||||
],
|
||||
"secureCost": [
|
||||
{
|
||||
"label": "security:false (parity)",
|
||||
"reqSec": 29776.73
|
||||
"reqSec": 37598.55
|
||||
},
|
||||
{
|
||||
"label": "security:true (default)",
|
||||
"reqSec": 28918.55
|
||||
"reqSec": 36507.64
|
||||
}
|
||||
],
|
||||
"runtimes": [
|
||||
{
|
||||
"runtime": "node",
|
||||
"scenario": "JSON hello (overhead)",
|
||||
"reqSec": 30378.91
|
||||
"reqSec": 38119.28
|
||||
},
|
||||
{
|
||||
"runtime": "node",
|
||||
"scenario": "Route param",
|
||||
"reqSec": 29203.64
|
||||
"reqSec": 35335.28
|
||||
},
|
||||
{
|
||||
"runtime": "node",
|
||||
"scenario": "Pipeline (3 steps)",
|
||||
"reqSec": 27208
|
||||
"reqSec": 33776
|
||||
},
|
||||
{
|
||||
"runtime": "node",
|
||||
"scenario": "POST JSON + validation",
|
||||
"reqSec": 22608.73
|
||||
"reqSec": 24758.55
|
||||
},
|
||||
{
|
||||
"runtime": "deno",
|
||||
"scenario": "JSON hello (overhead)",
|
||||
"reqSec": 51888
|
||||
"reqSec": 61792
|
||||
},
|
||||
{
|
||||
"runtime": "deno",
|
||||
"scenario": "Route param",
|
||||
"reqSec": 51785.6
|
||||
"reqSec": 61918.55
|
||||
},
|
||||
{
|
||||
"runtime": "deno",
|
||||
"scenario": "Pipeline (3 steps)",
|
||||
"reqSec": 50692.37
|
||||
"reqSec": 59521.46
|
||||
},
|
||||
{
|
||||
"runtime": "deno",
|
||||
"scenario": "POST JSON + validation",
|
||||
"reqSec": 35742.55
|
||||
"reqSec": 38561.46
|
||||
},
|
||||
{
|
||||
"runtime": "bun",
|
||||
"scenario": "JSON hello (overhead)",
|
||||
"reqSec": 46299.64
|
||||
"reqSec": 54427.64
|
||||
},
|
||||
{
|
||||
"runtime": "bun",
|
||||
"scenario": "Route param",
|
||||
"reqSec": 42788.37
|
||||
"reqSec": 48443.64
|
||||
},
|
||||
{
|
||||
"runtime": "bun",
|
||||
"scenario": "Pipeline (3 steps)",
|
||||
"reqSec": 39643.64
|
||||
"reqSec": 44955.64
|
||||
},
|
||||
{
|
||||
"runtime": "bun",
|
||||
"scenario": "POST JSON + validation",
|
||||
"reqSec": 31960
|
||||
"reqSec": 35268.37
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
# Radix router lookup evidence — `b128139` (CARD-10, D4)
|
||||
|
||||
> **Superseded by `../router-ed19f16/`.** This run found the 10-route regression from `a2b71e2`, which #131 fixed, and the A/A order bias, which `ed19f16` fixed in `bench/lookup.ts`. It is kept as the record of both.
|
||||
|
||||
The formal D4 comparison for the radix index (FPRD-001 CARD-10, #109): the radix router at
|
||||
`b128139` against the frozen pre-radix linear matcher, with the harness, host, cpuset and image of
|
||||
the baseline in `bench/baseline/router-ed47836/`. `b128139` is `develop` at `cb123e3` (CARD-07,
|
||||
PR #128) plus the internal seam counters added for the no-recompilation test; the attribution run
|
||||
below shows those counters do not move the numbers.
|
||||
|
||||
**Verdict: D4 fails at 10 routes** (late param hit, method miss, path miss). 100 and 500 routes pass.
|
||||
The cause is localized below to one CARD-07 commit. Per the card, no threshold was relaxed and no
|
||||
`src/` change was made to recover it; this is evidence for an owner decision.
|
||||
|
||||
## Files
|
||||
|
||||
| File | What it is |
|
||||
|---|---|
|
||||
| `lookup-raw.json` | **The D4 run.** A = `oracle` (`test/router-parity/oracle.ts`, the pre-radix linear matcher), B = `radix` (`src/http/router.ts` at `b128139`). Environment, method, every sample of every round, and the summary. |
|
||||
| `lookup-summary.txt` | The tables that run printed. |
|
||||
| `aa-raw.json`, `aa-summary.txt` | A/A noise band, same settings: `oracle` against `oracle-copy`, a byte-identical copy of the oracle at another path (sha256 `8875ec12…`, same as the original), so V8 sees two separate modules. |
|
||||
| `attrib-raw.json`, `attrib-summary.txt` | Diagnostic only, not part of the D4 verdict: oracle against the radix router at `5e0ae94`, `cb123e3` and `b128139` in the same process. |
|
||||
| `load.txt` | `uptime` and running CI job containers before and after each run. |
|
||||
|
||||
## Environment
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Host | jarvis (homelab), Ubuntu 24.04, kernel 6.8.0-138-generic, x86_64, AMD Ryzen 7 3700X, 62.7 GiB — same host as the baseline |
|
||||
| Isolation | `docker run --rm --cpuset-cpus 6,7,14,15 --user 1000:1000` (cpuset reported inside the container: `6-7,14-15`) |
|
||||
| Container | `node:22`, image id `sha256:5647be709086c696ff32edaaf1c70cd26d1da6ab2b39c32f3c7b4c4a31957e37` — the baseline's image; Node v22.23.1, V8 12.4.254.21-node.56; Docker 29.1.3 |
|
||||
| Revision | `b128139e2f4447af52b6b6d1a0d60d92664e40f8`, copied with `git archive`; `npm ci --ignore-scripts` inside the container |
|
||||
| Load (1/5/15 min) | D4 run: 0.24 0.25 0.11 before, 1.92 1.40 0.66 after. A/A: 1.92 1.40 0.66 before, 1.62 1.50 0.92 after. No CI job containers at any point. The rise is the benchmark itself (16 consecutive processes) plus jarvis's long-lived services; see `load.txt`. |
|
||||
| Env vars | Only `LOOKUP_*` (recorded in `meta.env`); no `NODE_OPTIONS` |
|
||||
|
||||
## Method
|
||||
|
||||
`bench/lookup.ts` unchanged from the baseline (defaults: 250 ms warm-up per router per cell, ≈25 ms
|
||||
samples, rounds alternating AB/BA, import order alternating per process, bootstrap 95% CI of the
|
||||
median paired ratio, 4000 resamples, seed 10908). The one difference is more repetitions, as the
|
||||
owner asked, to narrow the CIs: **16 fresh processes × 21 rounds = 336 paired rounds per cell**
|
||||
(baseline: 4 × 21 = 84).
|
||||
|
||||
```sh
|
||||
docker run --rm --cpuset-cpus 6,7,14,15 --user 1000:1000 -e HOME=/tmp -v "$PWD":/w -w /w \
|
||||
-e LOOKUP_ROUTERS="oracle=test/router-parity/oracle.ts,radix=src/http/router.ts" \
|
||||
-e LOOKUP_RUNS=16 -e LOOKUP_ROUNDS=21 -e LOOKUP_OUT=out/lookup-raw.json \
|
||||
-e LOOKUP_COMMIT=b128139e2f4447af52b6b6d1a0d60d92664e40f8 -e LOOKUP_HOST=jarvis -e LOOKUP_CPUSET=6,7,14,15 \
|
||||
-e LOOKUP_DOCKER="$(docker --version)" -e LOOKUP_KERNEL="$(uname -r)" \
|
||||
-e LOOKUP_IMAGE="$(docker image inspect node:22 --format '{{.Id}}')" \
|
||||
node:22 node --import tsx bench/lookup.ts
|
||||
```
|
||||
|
||||
The A/A run is the same command with `LOOKUP_ROUTERS="oracle=test/router-parity/oracle.ts,oracle-copy=aa/oracle-copy.ts"`
|
||||
and `LOOKUP_OUT=out/aa-raw.json`, started immediately after.
|
||||
|
||||
## D4 rule (accepted by the owner, 2026-10-10)
|
||||
|
||||
Per cell, B/A = median lookup time ratio radix / oracle with its bootstrap 95% CI.
|
||||
|
||||
- No regression anywhere: a cell **fails** only if its CI **lower** bound is above +5%.
|
||||
- At 500 routes, late param hit, method miss and path miss must also have a CI **upper** bound ≤ −20%. Static hit at 500: no regression only.
|
||||
|
||||
## D4 verdict — radix / oracle, 336 paired rounds per cell
|
||||
|
||||
| Routes | Workload | oracle ns | radix ns | radix / oracle | 95% CI | Rule | Verdict |
|
||||
|---:|---|---:|---:|---:|---|---|---|
|
||||
| 10 | static hit | 189.3 | 79.9 | 0.4198 (−58.0%) | −59.5% … −56.5% | lower ≤ +5% | PASS |
|
||||
| 10 | late param hit | 335.8 | 495.8 | 1.5253 (+52.5%) | +51.6% … +53.0% | lower ≤ +5% | **FAIL** |
|
||||
| 10 | method miss | 774.2 | 1,032.5 | 1.3181 (+31.8%) | +31.3% … +32.3% | lower ≤ +5% | **FAIL** |
|
||||
| 10 | path miss | 605.2 | 1,216.1 | 2.0192 (+101.9%) | +100.6% … +102.9% | lower ≤ +5% | **FAIL** |
|
||||
| 100 | static hit | 203.1 | 94.4 | 0.4632 (−53.7%) | −53.9% … −53.4% | lower ≤ +5% | PASS |
|
||||
| 100 | late param hit | 880.6 | 499.1 | 0.5726 (−42.7%) | −42.9% … −42.6% | lower ≤ +5% | PASS |
|
||||
| 100 | method miss | 2,515.1 | 1,048.2 | 0.4193 (−58.1%) | −58.3% … −57.8% | lower ≤ +5% | PASS |
|
||||
| 100 | path miss | 3,042.8 | 1,218.2 | 0.4042 (−59.6%) | −59.9% … −59.4% | lower ≤ +5% | PASS |
|
||||
| 500 | static hit | 203.9 | 96.3 | 0.4673 (−53.3%) | −53.5% … −53.2% | lower ≤ +5% | PASS |
|
||||
| 500 | late param hit | 2,825.2 | 498.6 | 0.1751 (−82.5%) | −82.6% … −82.4% | upper ≤ −20% | PASS |
|
||||
| 500 | method miss | 11,838.0 | 1,052.0 | 0.0887 (−91.1%) | −91.2% … −91.1% | upper ≤ −20% | PASS |
|
||||
| 500 | path miss | 15,335.4 | 1,218.9 | 0.0786 (−92.1%) | −92.2% … −92.1% | upper ≤ −20% | PASS |
|
||||
|
||||
The oracle's absolute medians match the baseline's live linear matcher within a few percent in every
|
||||
cell (e.g. 10-route late param 335.8 vs 328.4 ns, 500-route path miss 15,335 vs 15,514 ns), so the
|
||||
host and setup are comparable with the baseline capture.
|
||||
|
||||
## A/A noise band — oracle-copy / oracle, same settings
|
||||
|
||||
| Routes | Workload | ratio | 95% CI |
|
||||
|---:|---|---:|---|
|
||||
| 10 | static hit | 1.0421 (+4.2%) | +2.1% … +5.7% |
|
||||
| 10 | late param hit | 1.0829 (+8.3%) | +7.1% … +9.1% |
|
||||
| 10 | method miss | 0.9862 (−1.4%) | −2.0% … +0.2% |
|
||||
| 10 | path miss | 0.9988 (−0.1%) | −0.7% … +0.1% |
|
||||
| 100 | static hit | 1.0384 (+3.8%) | +2.4% … +5.4% |
|
||||
| 100 | late param hit | 1.0285 (+2.9%) | +2.6% … +3.0% |
|
||||
| 100 | method miss | 0.9971 (−0.3%) | −0.5% … −0.0% |
|
||||
| 100 | path miss | 1.0100 (+1.0%) | +0.7% … +1.2% |
|
||||
| 500 | static hit | 1.0374 (+3.7%) | +2.7% … +4.9% |
|
||||
| 500 | late param hit | 1.0113 (+1.1%) | +0.9% … +1.4% |
|
||||
| 500 | method miss | 1.0107 (+1.1%) | +0.8% … +1.3% |
|
||||
| 500 | path miss | 1.0155 (+1.5%) | +1.3% … +1.9% |
|
||||
|
||||
With 336 rounds the CIs are narrow, so identical code now shows **systematic** offsets that exclude
|
||||
1: up to +8.3% (CI +7.1 … +9.1%) at 10-route late param hit, and +3.7 … +4.2% on the static hits.
|
||||
The baseline's A/A had the same sign at that cell (+4.1%, CI −1.6 … +9.8%). The harness therefore
|
||||
carries an in-process bias of up to ≈9% against the second-listed router on the cheapest cells,
|
||||
which the 5% rule does not account for. It does not change this verdict: the three failing cells
|
||||
are 30–100% slower, far outside the band.
|
||||
|
||||
## Attribution (diagnostic, not part of the verdict)
|
||||
|
||||
Same image, cpuset and harness, 8 processes × 21 rounds, four routers in one process. The two
|
||||
older revisions are `git show <sha>:src/http/router.ts` (sha256 checked against git).
|
||||
|
||||
| 10 routes | `5e0ae94` (before the last CARD-07 fix) | `cb123e3` (merged CARD-07) | `b128139` (this commit) |
|
||||
|---|---|---|---|
|
||||
| late param hit | +5.3% (+4.1 … +9.4%) | +44.9% (+42.9 … +52.6%) | +45.5% (+44.1 … +51.2%) |
|
||||
| method miss | −2.6% (−2.8 … −2.1%) | +34.4% (+33.9 … +35.2%) | +34.4% (+33.3 … +35.1%) |
|
||||
| path miss | +1.2% (+1.0 … +1.4%) | +105.9% (+104.7 … +106.3%) | +103.4% (+102.5 … +103.9%) |
|
||||
|
||||
- The regression arrived with `a2b71e2` (*fix(router): drop pending walk frames when a segment
|
||||
fails to decode*), the only router change between `5e0ae94` and `cb123e3`. It wraps the walk
|
||||
loop in `try … finally` and resets `stackNodes.length` / `stackDepths.length` on every walk.
|
||||
It costs a roughly constant 130–650 ns per lookup, depending on how many walks a lookup makes,
|
||||
at every route count. Static hits, which take the `exactPaths` shortcut and never walk, are unaffected.
|
||||
- `b128139` matches `cb123e3` within noise in every cell, so the seam counters added by this change
|
||||
do not affect lookup time.
|
||||
- At `5e0ae94`, the 10-route cells were within D4 (late param lower bound +4.1%) and the 100- and
|
||||
500-route improvements were larger (e.g. 500-route path miss −95.9% vs −91.8% now).
|
||||
|
||||
No optimization was attempted here; restoring the walk's cost without losing the `a2b71e2` fix is a
|
||||
`src/` change for the owner to decide on.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,44 @@
|
||||
| routes | workload | router | median ns/op | run medians (ns) | run spread |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 10 | static hit | oracle | 185.3 | 171.6 / 186.8 / 175.1 / 192.6 / 170.0 / 205.3 / 171.4 / 199.3 / 171.1 / 193.4 / 177.1 / 189.5 / 169.8 / 184.8 / 185.4 / 195.5 | 19.2% |
|
||||
| 10 | static hit | oracle-copy | 192.0 | 196.0 / 153.5 / 200.2 / 172.0 / 197.0 / 177.6 / 197.1 / 176.1 / 203.6 / 174.9 / 200.2 / 178.6 / 198.1 / 191.5 / 194.9 / 165.3 | 26.1% |
|
||||
| 10 | late param hit | oracle | 331.9 | 320.2 / 341.3 / 317.8 / 338.3 / 324.5 / 340.3 / 317.4 / 351.5 / 317.5 / 347.3 / 329.1 / 340.9 / 315.2 / 336.1 / 322.1 / 350.8 | 11.0% |
|
||||
| 10 | late param hit | oracle-copy | 351.3 | 355.6 / 320.9 / 352.7 / 326.7 / 353.3 / 337.1 / 349.3 / 326.9 / 359.6 / 330.6 / 361.0 / 339.1 / 353.3 / 362.1 / 353.6 / 342.2 | 11.7% |
|
||||
| 10 | method miss | oracle | 779.3 | 777.8 / 784.3 / 763.9 / 777.0 / 755.4 / 772.9 / 763.4 / 886.9 / 765.3 / 786.1 / 785.6 / 802.9 / 747.7 / 777.0 / 799.4 / 799.2 | 17.9% |
|
||||
| 10 | method miss | oracle-copy | 777.0 | 798.4 / 753.2 / 777.7 / 765.1 / 780.7 / 737.3 / 793.9 / 766.2 / 796.8 / 754.9 / 803.9 / 783.0 / 764.9 / 745.1 / 797.6 / 780.6 | 8.6% |
|
||||
| 10 | path miss | oracle | 609.3 | 584.8 / 616.8 / 592.5 / 609.0 / 597.2 / 611.6 / 595.4 / 644.2 / 596.9 / 602.2 / 629.0 / 624.6 / 602.9 / 611.7 / 613.7 / 617.7 | 9.8% |
|
||||
| 10 | path miss | oracle-copy | 608.0 | 614.9 / 582.4 / 611.4 / 601.2 / 615.8 / 588.2 / 624.8 / 595.1 / 625.1 / 590.1 / 626.7 / 590.9 / 604.0 / 581.9 / 620.0 / 617.8 | 7.4% |
|
||||
| 100 | static hit | oracle | 205.5 | 194.9 / 206.9 / 189.7 / 214.3 / 188.1 / 217.3 / 186.0 / 229.0 / 190.8 / 213.4 / 202.8 / 209.4 / 201.7 / 209.7 / 194.9 / 215.3 | 20.9% |
|
||||
| 100 | static hit | oracle-copy | 210.5 | 207.8 / 193.9 / 218.3 / 194.5 / 213.6 / 205.8 / 213.3 / 206.2 / 211.8 / 197.6 / 217.5 / 216.4 / 211.0 / 195.7 / 211.3 / 210.2 | 11.6% |
|
||||
| 100 | late param hit | oracle | 875.3 | 902.1 / 855.1 / 852.7 / 852.9 / 906.6 / 882.9 / 873.6 / 905.3 / 877.5 / 866.5 / 896.0 / 875.3 / 860.6 / 866.4 / 874.7 / 886.1 | 6.2% |
|
||||
| 100 | late param hit | oracle-copy | 895.3 | 913.2 / 889.1 / 889.9 / 876.3 / 890.4 / 887.5 / 896.3 / 910.0 / 907.8 / 897.7 / 916.0 / 892.1 / 889.4 / 888.0 / 897.7 / 951.7 | 8.4% |
|
||||
| 100 | method miss | oracle | 2509.1 | 2589.9 / 2498.9 / 2487.7 / 2509.2 / 2487.4 / 2496.7 / 2473.1 / 2589.6 / 2516.7 / 2519.8 / 2455.1 / 2588.2 / 2405.1 / 2509.1 / 2499.6 / 2547.7 | 7.4% |
|
||||
| 100 | method miss | oracle-copy | 2502.4 | 2620.9 / 2470.5 / 2491.5 / 2484.1 / 2487.6 / 2436.2 / 2562.5 / 2523.3 / 2559.0 / 2508.5 / 2491.9 / 2572.8 / 2473.1 / 2460.1 / 2480.1 / 2540.1 | 7.4% |
|
||||
| 100 | path miss | oracle | 3032.2 | 3123.1 / 3002.5 / 3029.2 / 3027.7 / 3035.2 / 3023.8 / 2984.2 / 3115.4 / 3057.8 / 3042.8 / 2996.6 / 3089.9 / 2916.3 / 3028.2 / 2983.7 / 3066.3 | 6.8% |
|
||||
| 100 | path miss | oracle-copy | 3069.0 | 3164.6 / 3009.8 / 3072.4 / 3041.6 / 3033.8 / 3027.1 / 3080.2 / 3077.8 / 3115.3 / 3083.6 / 3050.5 / 3099.1 / 2989.7 / 3019.5 / 3018.2 / 3075.3 | 5.7% |
|
||||
| 500 | static hit | oracle | 206.7 | 197.8 / 209.1 / 193.0 / 215.8 / 193.8 / 219.8 / 186.2 / 230.4 / 196.6 / 216.2 / 202.7 / 208.8 / 195.3 / 208.2 / 197.6 / 216.7 | 21.4% |
|
||||
| 500 | static hit | oracle-copy | 209.7 | 207.7 / 195.5 / 218.7 / 196.3 / 217.5 / 207.7 / 211.3 / 205.7 / 214.9 / 198.0 / 217.5 / 215.3 / 208.1 / 194.0 / 212.9 / 210.4 | 11.8% |
|
||||
| 500 | late param hit | oracle | 2851.6 | 3013.2 / 2800.0 / 2822.0 / 2822.6 / 2985.7 / 2976.5 / 2853.5 / 2841.9 / 2938.3 / 2842.8 / 2903.9 / 2847.2 / 2789.9 / 2833.2 / 2813.1 / 2967.4 | 7.8% |
|
||||
| 500 | late param hit | oracle-copy | 2904.5 | 2898.8 / 2832.6 / 2904.8 / 2849.5 / 2917.2 / 2922.2 / 2839.8 / 2955.2 / 2986.3 / 2964.2 / 2966.0 / 2863.6 / 2850.6 / 2874.6 / 2853.0 / 2965.1 | 5.3% |
|
||||
| 500 | method miss | oracle | 11893.2 | 11982.2 / 11618.7 / 11522.3 / 11528.5 / 12093.8 / 12866.2 / 11749.3 / 11991.5 / 11895.6 / 11915.7 / 11763.2 / 11896.4 / 11793.6 / 12613.8 / 11668.1 / 12156.8 | 11.3% |
|
||||
| 500 | method miss | oracle-copy | 12004.6 | 12046.9 / 11880.8 / 11572.6 / 11957.2 / 12294.5 / 12289.2 / 11975.8 / 12018.3 / 11969.8 / 11802.4 / 12070.3 / 12118.1 / 11893.5 / 12437.1 / 11771.9 / 12685.4 | 9.3% |
|
||||
| 500 | path miss | oracle | 15411.0 | 15690.0 / 15020.4 / 14830.8 / 14986.3 / 15701.3 / 16217.0 / 15500.7 / 15373.9 / 15740.1 / 15391.9 / 15109.0 / 15411.0 / 15122.5 / 16445.6 / 15265.1 / 15824.8 | 10.5% |
|
||||
| 500 | path miss | oracle-copy | 15727.3 | 15736.8 / 15428.6 / 15278.9 / 15690.0 / 15853.1 / 16234.6 / 15623.0 / 15809.2 / 15772.1 / 15577.8 / 15765.7 / 15756.7 / 15389.3 / 16351.2 / 15500.3 / 16250.8 | 6.8% |
|
||||
|
||||
| routes | workload | B / A | median ratio | 95% CI | rounds |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 10 | static hit | oracle-copy / oracle | 1.0421 (+4.2%) | 1.0207 – 1.0565 (+2.1% … +5.7%) | 336 |
|
||||
| 10 | late param hit | oracle-copy / oracle | 1.0829 (+8.3%) | 1.0707 – 1.0909 (+7.1% … +9.1%) | 336 |
|
||||
| 10 | method miss | oracle-copy / oracle | 0.9862 (-1.4%) | 0.9797 – 1.0016 (-2.0% … +0.2%) | 336 |
|
||||
| 10 | path miss | oracle-copy / oracle | 0.9988 (-0.1%) | 0.9927 – 1.0010 (-0.7% … +0.1%) | 336 |
|
||||
| 100 | static hit | oracle-copy / oracle | 1.0384 (+3.8%) | 1.0244 – 1.0536 (+2.4% … +5.4%) | 336 |
|
||||
| 100 | late param hit | oracle-copy / oracle | 1.0285 (+2.9%) | 1.0259 – 1.0301 (+2.6% … +3.0%) | 336 |
|
||||
| 100 | method miss | oracle-copy / oracle | 0.9971 (-0.3%) | 0.9952 – 0.9997 (-0.5% … -0.0%) | 336 |
|
||||
| 100 | path miss | oracle-copy / oracle | 1.0100 (+1.0%) | 1.0071 – 1.0122 (+0.7% … +1.2%) | 336 |
|
||||
| 500 | static hit | oracle-copy / oracle | 1.0374 (+3.7%) | 1.0272 – 1.0495 (+2.7% … +4.9%) | 336 |
|
||||
| 500 | late param hit | oracle-copy / oracle | 1.0113 (+1.1%) | 1.0091 – 1.0135 (+0.9% … +1.4%) | 336 |
|
||||
| 500 | method miss | oracle-copy / oracle | 1.0107 (+1.1%) | 1.0082 – 1.0128 (+0.8% … +1.3%) | 336 |
|
||||
| 500 | path miss | oracle-copy / oracle | 1.0155 (+1.5%) | 1.0125 – 1.0186 (+1.3% … +1.9%) | 336 |
|
||||
|
||||
load average: start 1.92 1.40 0.66, end 1.62 1.50 0.92; cpuset 6-7,14-15
|
||||
raw samples: out/aa-raw.json
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,92 @@
|
||||
| routes | workload | router | median ns/op | run medians (ns) | run spread |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 10 | static hit | oracle | 187.8 | 168.5 / 200.6 / 175.3 / 190.2 / 170.3 / 190.5 / 168.8 / 192.4 | 17.1% |
|
||||
| 10 | static hit | radix-5e0ae94 | 84.9 | 85.7 / 86.0 / 79.7 / 83.5 / 88.2 / 78.5 / 89.3 / 77.6 | 13.8% |
|
||||
| 10 | static hit | radix-cb123e3 | 84.5 | 81.1 / 83.5 / 76.5 / 89.7 / 87.8 / 85.3 / 92.9 / 81.1 | 19.4% |
|
||||
| 10 | static hit | radix-b128139 | 80.1 | 80.8 / 78.3 / 80.9 / 79.2 / 81.0 / 73.2 / 88.3 / 72.2 | 20.2% |
|
||||
| 10 | late param hit | oracle | 336.6 | 324.5 / 385.9 / 322.3 / 352.3 / 326.7 / 343.0 / 322.4 / 357.0 | 18.9% |
|
||||
| 10 | late param hit | radix-5e0ae94 | 365.3 | 368.2 / 370.1 / 360.7 / 366.8 / 356.6 / 350.2 / 369.3 / 363.5 | 5.5% |
|
||||
| 10 | late param hit | radix-cb123e3 | 500.4 | 503.7 / 495.1 / 514.9 / 502.3 / 498.4 / 481.8 / 538.7 / 498.7 | 11.4% |
|
||||
| 10 | late param hit | radix-b128139 | 496.0 | 507.8 / 488.5 / 489.6 / 508.8 / 494.4 / 480.8 / 507.1 / 496.2 | 5.6% |
|
||||
| 10 | method miss | oracle | 772.3 | 764.9 / 783.0 / 768.7 / 775.2 / 773.0 / 761.1 / 757.6 / 777.4 | 3.3% |
|
||||
| 10 | method miss | radix-5e0ae94 | 755.9 | 770.1 / 759.0 / 745.2 / 760.1 / 771.6 / 727.2 / 750.8 / 747.0 | 5.9% |
|
||||
| 10 | method miss | radix-cb123e3 | 1043.5 | 1060.9 / 1043.9 / 1063.5 / 1040.5 / 1029.8 / 1007.2 / 1032.6 / 1050.8 | 5.4% |
|
||||
| 10 | method miss | radix-b128139 | 1038.4 | 1056.8 / 1027.2 / 1043.0 / 1050.4 / 1010.3 / 1010.0 / 1034.4 / 1042.8 | 4.5% |
|
||||
| 10 | path miss | oracle | 600.9 | 578.0 / 631.4 / 604.8 / 603.2 / 599.0 / 589.4 / 594.2 / 612.4 | 8.9% |
|
||||
| 10 | path miss | radix-5e0ae94 | 611.0 | 622.1 / 628.3 / 601.6 / 610.3 / 608.1 / 596.6 / 611.3 / 617.3 | 5.2% |
|
||||
| 10 | path miss | radix-cb123e3 | 1246.5 | 1304.5 / 1261.4 / 1252.0 / 1262.0 / 1199.2 / 1218.0 / 1216.0 / 1235.3 | 8.5% |
|
||||
| 10 | path miss | radix-b128139 | 1225.0 | 1250.3 / 1211.7 / 1240.8 / 1253.4 / 1215.2 / 1198.9 / 1197.2 / 1227.9 | 4.6% |
|
||||
| 100 | static hit | oracle | 206.6 | 204.8 / 211.1 / 197.2 / 210.7 / 203.8 / 211.6 / 200.2 / 207.8 | 7.0% |
|
||||
| 100 | static hit | radix-5e0ae94 | 99.0 | 99.4 / 97.9 / 95.0 / 106.8 / 101.9 / 92.1 / 105.6 / 98.7 | 14.8% |
|
||||
| 100 | static hit | radix-cb123e3 | 99.5 | 104.8 / 91.4 / 94.3 / 103.2 / 95.7 / 101.8 / 104.3 / 96.0 | 13.4% |
|
||||
| 100 | static hit | radix-b128139 | 95.4 | 92.5 / 96.5 / 92.0 / 105.7 / 102.1 / 84.9 / 102.2 / 88.7 | 21.8% |
|
||||
| 100 | late param hit | oracle | 868.9 | 885.4 / 862.0 / 869.3 / 871.4 / 864.4 / 855.0 / 868.9 / 879.3 | 3.5% |
|
||||
| 100 | late param hit | radix-5e0ae94 | 369.7 | 386.9 / 362.5 / 360.3 / 373.0 / 367.5 / 353.6 / 375.6 / 372.1 | 9.0% |
|
||||
| 100 | late param hit | radix-cb123e3 | 501.6 | 508.1 / 496.2 / 502.9 / 500.3 / 503.1 / 508.5 / 497.4 / 500.1 | 2.5% |
|
||||
| 100 | late param hit | radix-b128139 | 493.5 | 518.8 / 482.0 / 496.6 / 483.9 / 499.6 / 489.7 / 504.7 / 488.8 | 7.5% |
|
||||
| 100 | method miss | oracle | 2502.9 | 2533.9 / 2508.3 / 2493.5 / 2481.1 / 2577.2 / 2450.9 / 2466.6 / 2510.1 | 5.0% |
|
||||
| 100 | method miss | radix-5e0ae94 | 774.7 | 792.1 / 772.2 / 775.9 / 784.0 / 761.3 / 757.2 / 754.8 / 779.7 | 4.8% |
|
||||
| 100 | method miss | radix-cb123e3 | 1051.3 | 1105.3 / 1040.9 / 1083.8 / 1052.1 / 1050.8 / 1033.5 / 1027.5 / 1067.1 | 7.4% |
|
||||
| 100 | method miss | radix-b128139 | 1060.1 | 1088.1 / 1031.5 / 1068.2 / 1060.7 / 1093.0 / 1033.6 / 1040.2 / 1059.6 | 5.8% |
|
||||
| 100 | path miss | oracle | 3026.9 | 3035.0 / 3106.5 / 3057.6 / 2989.9 / 3054.9 / 2927.9 / 2987.3 / 3023.6 | 5.9% |
|
||||
| 100 | path miss | radix-5e0ae94 | 615.7 | 639.5 / 619.8 / 612.0 / 592.7 / 622.4 / 588.0 / 600.1 / 619.4 | 8.4% |
|
||||
| 100 | path miss | radix-cb123e3 | 1231.5 | 1266.1 / 1255.0 / 1264.9 / 1215.8 / 1209.3 / 1186.0 / 1212.1 / 1240.5 | 6.5% |
|
||||
| 100 | path miss | radix-b128139 | 1230.0 | 1261.6 / 1233.2 / 1246.0 / 1213.0 / 1222.2 / 1169.2 / 1216.9 / 1237.5 | 7.5% |
|
||||
| 500 | static hit | oracle | 208.6 | 204.7 / 216.8 / 201.3 / 208.9 / 205.4 / 223.7 / 203.9 / 217.7 | 10.7% |
|
||||
| 500 | static hit | radix-5e0ae94 | 107.7 | 104.2 / 112.1 / 104.8 / 105.5 / 109.4 / 109.4 / 108.3 / 114.2 | 9.3% |
|
||||
| 500 | static hit | radix-cb123e3 | 104.5 | 106.1 / 110.9 / 103.8 / 100.2 / 106.0 / 112.5 / 104.6 / 100.3 | 11.8% |
|
||||
| 500 | static hit | radix-b128139 | 103.1 | 98.2 / 102.2 / 102.9 / 104.6 / 104.0 / 102.4 / 104.6 / 104.0 | 6.2% |
|
||||
| 500 | late param hit | oracle | 2845.6 | 2835.8 / 2802.4 / 2823.4 / 2840.5 / 2866.8 / 2913.6 / 2810.5 / 2883.0 | 3.9% |
|
||||
| 500 | late param hit | radix-5e0ae94 | 378.2 | 383.9 / 373.7 / 367.4 / 380.3 / 389.5 / 374.5 / 375.7 / 379.7 | 5.8% |
|
||||
| 500 | late param hit | radix-cb123e3 | 508.5 | 511.6 / 503.5 / 496.2 / 504.9 / 522.1 / 527.9 / 504.4 / 513.9 | 6.2% |
|
||||
| 500 | late param hit | radix-b128139 | 502.5 | 515.2 / 494.4 / 487.7 / 492.1 / 516.9 / 503.8 / 505.7 / 500.6 | 5.8% |
|
||||
| 500 | method miss | oracle | 11778.4 | 11628.2 / 11388.0 / 11702.2 / 11567.8 / 11866.3 / 12532.8 / 11933.9 / 11949.8 | 9.7% |
|
||||
| 500 | method miss | radix-5e0ae94 | 794.6 | 804.2 / 786.3 / 768.6 / 801.9 / 797.1 / 791.5 / 785.1 / 796.6 | 4.5% |
|
||||
| 500 | method miss | radix-cb123e3 | 1082.2 | 1110.1 / 1063.7 / 1078.1 / 1062.3 / 1089.6 / 1075.3 / 1127.6 / 1080.6 | 6.0% |
|
||||
| 500 | method miss | radix-b128139 | 1079.5 | 1083.6 / 1050.3 / 1079.0 / 1065.1 / 1124.2 / 1092.1 / 1098.9 / 1067.3 | 6.8% |
|
||||
| 500 | path miss | oracle | 15341.3 | 15106.1 / 14850.3 / 15080.7 / 15327.4 / 15495.3 / 16139.2 / 15346.2 / 15630.0 | 8.4% |
|
||||
| 500 | path miss | radix-5e0ae94 | 629.5 | 658.3 / 646.1 / 620.1 / 626.6 / 666.2 / 631.3 / 610.1 / 615.6 | 8.9% |
|
||||
| 500 | path miss | radix-cb123e3 | 1249.6 | 1285.0 / 1252.6 / 1250.4 / 1243.2 / 1280.2 / 1250.4 / 1214.4 / 1235.9 | 5.6% |
|
||||
| 500 | path miss | radix-b128139 | 1235.2 | 1272.1 / 1228.4 / 1243.8 / 1236.2 / 1278.3 / 1226.9 / 1216.5 / 1226.1 | 5.0% |
|
||||
|
||||
| routes | workload | B / A | median ratio | 95% CI | rounds |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 10 | static hit | radix-5e0ae94 / oracle | 0.4484 (-55.2%) | 0.4386 – 0.4553 (-56.1% … -54.5%) | 168 |
|
||||
| 10 | static hit | radix-cb123e3 / oracle | 0.4496 (-55.0%) | 0.4462 – 0.4731 (-55.4% … -52.7%) | 168 |
|
||||
| 10 | static hit | radix-b128139 / oracle | 0.4312 (-56.9%) | 0.4158 – 0.4608 (-58.4% … -53.9%) | 168 |
|
||||
| 10 | late param hit | radix-5e0ae94 / oracle | 1.0535 (+5.3%) | 1.0415 – 1.0937 (+4.1% … +9.4%) | 168 |
|
||||
| 10 | late param hit | radix-cb123e3 / oracle | 1.4493 (+44.9%) | 1.4291 – 1.5261 (+42.9% … +52.6%) | 168 |
|
||||
| 10 | late param hit | radix-b128139 / oracle | 1.4549 (+45.5%) | 1.4414 – 1.5117 (+44.1% … +51.2%) | 168 |
|
||||
| 10 | method miss | radix-5e0ae94 / oracle | 0.9744 (-2.6%) | 0.9724 – 0.9790 (-2.8% … -2.1%) | 168 |
|
||||
| 10 | method miss | radix-cb123e3 / oracle | 1.3441 (+34.4%) | 1.3387 – 1.3520 (+33.9% … +35.2%) | 168 |
|
||||
| 10 | method miss | radix-b128139 / oracle | 1.3437 (+34.4%) | 1.3329 – 1.3510 (+33.3% … +35.1%) | 168 |
|
||||
| 10 | path miss | radix-5e0ae94 / oracle | 1.0124 (+1.2%) | 1.0105 – 1.0143 (+1.0% … +1.4%) | 168 |
|
||||
| 10 | path miss | radix-cb123e3 / oracle | 2.0590 (+105.9%) | 2.0473 – 2.0628 (+104.7% … +106.3%) | 168 |
|
||||
| 10 | path miss | radix-b128139 / oracle | 2.0340 (+103.4%) | 2.0254 – 2.0387 (+102.5% … +103.9%) | 168 |
|
||||
| 100 | static hit | radix-5e0ae94 / oracle | 0.4836 (-51.6%) | 0.4813 – 0.4878 (-51.9% … -51.2%) | 168 |
|
||||
| 100 | static hit | radix-cb123e3 / oracle | 0.4800 (-52.0%) | 0.4746 – 0.4834 (-52.5% … -51.7%) | 168 |
|
||||
| 100 | static hit | radix-b128139 / oracle | 0.4597 (-54.0%) | 0.4569 – 0.4677 (-54.3% … -53.2%) | 168 |
|
||||
| 100 | late param hit | radix-5e0ae94 / oracle | 0.4236 (-57.6%) | 0.4226 – 0.4252 (-57.7% … -57.5%) | 168 |
|
||||
| 100 | late param hit | radix-cb123e3 / oracle | 0.5754 (-42.5%) | 0.5744 – 0.5768 (-42.6% … -42.3%) | 168 |
|
||||
| 100 | late param hit | radix-b128139 / oracle | 0.5709 (-42.9%) | 0.5680 – 0.5726 (-43.2% … -42.7%) | 168 |
|
||||
| 100 | method miss | radix-5e0ae94 / oracle | 0.3095 (-69.0%) | 0.3088 – 0.3107 (-69.1% … -68.9%) | 168 |
|
||||
| 100 | method miss | radix-cb123e3 / oracle | 0.4225 (-57.8%) | 0.4213 – 0.4241 (-57.9% … -57.6%) | 168 |
|
||||
| 100 | method miss | radix-b128139 / oracle | 0.4235 (-57.6%) | 0.4228 – 0.4249 (-57.7% … -57.5%) | 168 |
|
||||
| 100 | path miss | radix-5e0ae94 / oracle | 0.2012 (-79.9%) | 0.2006 – 0.2020 (-79.9% … -79.8%) | 168 |
|
||||
| 100 | path miss | radix-cb123e3 / oracle | 0.4068 (-59.3%) | 0.4058 – 0.4075 (-59.4% … -59.2%) | 168 |
|
||||
| 100 | path miss | radix-b128139 / oracle | 0.4055 (-59.4%) | 0.4035 – 0.4065 (-59.6% … -59.3%) | 168 |
|
||||
| 500 | static hit | radix-5e0ae94 / oracle | 0.5144 (-48.6%) | 0.5106 – 0.5169 (-48.9% … -48.3%) | 168 |
|
||||
| 500 | static hit | radix-cb123e3 / oracle | 0.5066 (-49.3%) | 0.5014 – 0.5089 (-49.9% … -49.1%) | 168 |
|
||||
| 500 | static hit | radix-b128139 / oracle | 0.4860 (-51.4%) | 0.4820 – 0.4998 (-51.8% … -50.0%) | 168 |
|
||||
| 500 | late param hit | radix-5e0ae94 / oracle | 0.1332 (-86.7%) | 0.1328 – 0.1336 (-86.7% … -86.6%) | 168 |
|
||||
| 500 | late param hit | radix-cb123e3 / oracle | 0.1793 (-82.1%) | 0.1788 – 0.1797 (-82.1% … -82.0%) | 168 |
|
||||
| 500 | late param hit | radix-b128139 / oracle | 0.1754 (-82.5%) | 0.1739 – 0.1763 (-82.6% … -82.4%) | 168 |
|
||||
| 500 | method miss | radix-5e0ae94 / oracle | 0.0670 (-93.3%) | 0.0667 – 0.0675 (-93.3% … -93.2%) | 168 |
|
||||
| 500 | method miss | radix-cb123e3 / oracle | 0.0922 (-90.8%) | 0.0918 – 0.0925 (-90.8% … -90.7%) | 168 |
|
||||
| 500 | method miss | radix-b128139 / oracle | 0.0922 (-90.8%) | 0.0917 – 0.0924 (-90.8% … -90.8%) | 168 |
|
||||
| 500 | path miss | radix-5e0ae94 / oracle | 0.0409 (-95.9%) | 0.0406 – 0.0412 (-95.9% … -95.9%) | 168 |
|
||||
| 500 | path miss | radix-cb123e3 / oracle | 0.0818 (-91.8%) | 0.0808 – 0.0824 (-91.9% … -91.8%) | 168 |
|
||||
| 500 | path miss | radix-b128139 / oracle | 0.0815 (-91.8%) | 0.0806 – 0.0821 (-91.9% … -91.8%) | 168 |
|
||||
|
||||
load average: start 0.74 1.27 0.87, end 1.09 1.16 0.95; cpuset 6-7,14-15
|
||||
raw samples: out/attrib-raw.json
|
||||
@@ -0,0 +1,8 @@
|
||||
d4 before: 2026-10-12T18:58:39Z 13:58:39 up 46 days, 13:47, 2 users, load average: 0.24, 0.25, 0.11
|
||||
ci job containers: 0
|
||||
d4 after / aa before: 2026-10-12T19:03:38Z 14:03:38 up 46 days, 13:52, 3 users, load average: 1.92, 1.40, 0.66
|
||||
ci job containers: 0
|
||||
aa after: 2026-10-12T19:08:38Z 14:08:38 up 46 days, 13:57, 3 users, load average: 1.62, 1.50, 0.92
|
||||
ci job containers: 0
|
||||
attrib before: 2026-10-12T19:09:34Z 14:09:34 up 46 days, 13:58, 2 users, load average: 0.74, 1.27, 0.87
|
||||
attrib after: 2026-10-12T19:14:33Z 14:14:33 up 46 days, 14:03, 3 users, load average: 1.09, 1.16, 0.95
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,44 @@
|
||||
| routes | workload | router | median ns/op | run medians (ns) | run spread |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 10 | static hit | oracle | 189.3 | 181.1 / 193.3 / 189.0 / 189.8 / 173.8 / 193.6 / 179.5 / 290.1 / 170.8 / 196.3 / 164.7 / 202.2 / 172.3 / 207.0 / 186.1 / 198.5 | 66.2% |
|
||||
| 10 | static hit | radix | 79.9 | 80.5 / 76.3 / 80.4 / 76.0 / 81.0 / 78.8 / 78.8 / 95.0 / 89.6 / 71.2 / 80.6 / 71.0 / 87.4 / 70.2 / 85.5 / 76.3 | 31.2% |
|
||||
| 10 | late param hit | oracle | 335.8 | 318.2 / 339.1 / 315.3 / 342.1 / 324.1 / 366.1 / 324.7 / 527.3 / 323.3 / 341.9 / 324.4 / 338.6 / 317.1 / 341.9 / 327.3 / 344.9 | 63.1% |
|
||||
| 10 | late param hit | radix | 495.8 | 492.0 / 487.5 / 495.8 / 494.7 / 496.8 / 489.9 / 497.5 / 801.9 / 495.5 / 485.1 / 504.0 / 504.2 / 497.0 / 581.5 / 497.9 / 487.1 | 63.9% |
|
||||
| 10 | method miss | oracle | 774.2 | 759.1 / 774.4 / 745.0 / 773.2 / 771.5 / 797.9 / 774.8 / 797.8 / 764.1 / 768.2 / 767.2 / 795.5 / 761.3 / 777.9 / 784.2 / 789.1 | 6.8% |
|
||||
| 10 | method miss | radix | 1032.5 | 1009.5 / 1003.8 / 1039.7 / 1015.7 / 1056.1 / 1033.4 / 1069.7 / 1028.3 / 1059.3 / 1002.3 / 1047.3 / 1017.9 / 1048.7 / 1022.2 / 1033.2 / 1028.6 | 6.5% |
|
||||
| 10 | path miss | oracle | 605.2 | 594.3 / 607.6 / 583.3 / 609.8 / 600.0 / 626.6 / 607.2 / 629.6 / 605.1 / 591.5 / 595.6 / 713.2 / 583.0 / 600.3 / 607.1 / 614.0 | 21.5% |
|
||||
| 10 | path miss | radix | 1216.1 | 1183.5 / 1193.5 / 1238.1 / 1205.4 / 1282.2 / 1214.5 / 1272.6 / 1211.0 / 1271.8 / 1193.4 / 1218.9 / 1215.2 / 1224.3 / 1209.3 / 1242.6 / 1174.7 | 8.8% |
|
||||
| 100 | static hit | oracle | 203.1 | 182.3 / 210.0 / 203.7 / 212.3 / 203.4 / 201.1 / 209.6 / 212.6 / 209.2 / 208.9 / 199.2 / 195.9 / 195.4 / 202.1 / 186.2 / 201.9 | 14.9% |
|
||||
| 100 | static hit | radix | 94.4 | 90.2 / 96.5 / 102.2 / 92.3 / 98.8 / 95.2 / 96.5 / 83.3 / 96.8 / 80.8 / 97.0 / 90.3 / 91.6 / 91.0 / 100.8 / 88.5 | 22.7% |
|
||||
| 100 | late param hit | oracle | 880.6 | 853.2 / 862.3 / 885.2 / 870.7 / 861.9 / 891.0 / 885.0 / 896.1 / 886.1 / 865.7 / 876.4 / 892.3 / 851.3 / 880.6 / 889.4 / 883.5 | 5.1% |
|
||||
| 100 | late param hit | radix | 499.1 | 491.3 / 494.4 / 519.6 / 493.9 / 504.8 / 509.3 / 518.2 / 516.4 / 496.7 / 496.9 / 521.4 / 490.0 / 494.4 / 495.6 / 505.0 / 480.1 | 8.3% |
|
||||
| 100 | method miss | oracle | 2515.1 | 2509.2 / 2535.9 / 2510.3 / 2525.3 / 2490.2 / 2561.8 / 2525.3 / 2494.8 / 2439.7 / 2423.0 / 2499.4 / 2511.6 / 2385.6 / 2579.1 / 2519.5 / 2545.4 | 7.7% |
|
||||
| 100 | method miss | radix | 1048.2 | 1018.7 / 1035.6 / 1075.5 / 1016.9 / 1066.9 / 1042.7 / 1079.9 / 1052.9 / 1073.1 / 1026.8 / 1059.7 / 1042.4 / 1039.5 / 1060.1 / 1054.8 / 1033.0 | 6.0% |
|
||||
| 100 | path miss | oracle | 3042.8 | 3018.3 / 3084.7 / 3030.3 / 3092.0 / 2983.1 / 3092.1 / 3035.8 / 3017.4 / 2997.3 / 2928.0 / 3051.5 / 3049.1 / 2878.8 / 3112.3 / 3047.9 / 3086.6 | 7.7% |
|
||||
| 100 | path miss | radix | 1218.2 | 1195.4 / 1204.1 / 1240.3 / 1211.8 / 1227.2 / 1218.4 / 1243.9 / 1242.6 / 1220.0 / 1198.2 / 1228.8 / 1218.2 / 1185.0 / 1203.0 / 1273.6 / 1212.9 | 7.3% |
|
||||
| 500 | static hit | oracle | 203.9 | 185.0 / 212.4 / 203.2 / 213.1 / 203.7 / 203.9 / 208.0 / 209.0 / 209.4 / 209.9 / 202.5 / 193.9 / 196.4 / 200.1 / 186.2 / 203.9 | 13.8% |
|
||||
| 500 | static hit | radix | 96.3 | 91.7 / 95.8 / 94.2 / 99.5 / 100.5 / 98.6 / 97.1 / 82.1 / 97.7 / 85.0 / 97.7 / 90.3 / 105.0 / 89.6 / 103.2 / 85.4 | 23.9% |
|
||||
| 500 | late param hit | oracle | 2825.2 | 2782.7 / 2787.9 / 2800.5 / 2832.6 / 2832.2 / 3098.7 / 2786.3 / 2839.1 / 2896.6 / 2805.7 / 2793.9 / 2896.0 / 2838.7 / 2754.0 / 2917.6 / 2790.8 | 12.2% |
|
||||
| 500 | late param hit | radix | 498.6 | 490.6 / 498.8 / 513.9 / 488.6 / 513.6 / 502.6 / 504.4 / 495.1 / 499.6 / 498.7 / 513.2 / 488.8 / 501.8 / 480.6 / 496.4 / 480.6 | 6.7% |
|
||||
| 500 | method miss | oracle | 11838.0 | 11627.9 / 11728.6 / 11904.6 / 11696.5 / 11752.0 / 12264.6 / 13500.6 / 12268.7 / 11613.4 / 11893.1 / 11864.7 / 11897.3 / 12343.2 / 11508.1 / 11541.6 / 11492.7 | 17.0% |
|
||||
| 500 | method miss | radix | 1052.0 | 1039.0 / 1017.2 / 1056.4 / 1027.9 / 1068.6 / 1077.4 / 1239.0 / 1052.4 / 1048.1 / 1032.9 / 1055.6 / 1056.9 / 1056.9 / 1020.8 / 1056.6 / 1034.0 | 21.1% |
|
||||
| 500 | path miss | oracle | 15335.4 | 15129.6 / 15295.6 / 15401.4 / 15353.4 / 15333.0 / 16553.2 / 16364.6 / 16945.0 / 15275.6 / 15335.0 / 15342.4 / 15630.5 / 15379.6 / 15051.5 / 15119.7 / 15143.7 | 12.3% |
|
||||
| 500 | path miss | radix | 1218.9 | 1222.0 / 1211.4 / 1216.4 / 1226.8 / 1232.7 / 1260.1 / 1269.4 / 1221.6 / 1195.9 / 1181.8 / 1210.2 / 1211.3 / 1229.7 / 1167.4 / 1240.5 / 1210.2 | 8.4% |
|
||||
|
||||
| routes | workload | B / A | median ratio | 95% CI | rounds |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 10 | static hit | radix / oracle | 0.4198 (-58.0%) | 0.4051 – 0.4352 (-59.5% … -56.5%) | 336 |
|
||||
| 10 | late param hit | radix / oracle | 1.5253 (+52.5%) | 1.5161 – 1.5300 (+51.6% … +53.0%) | 336 |
|
||||
| 10 | method miss | radix / oracle | 1.3181 (+31.8%) | 1.3130 – 1.3228 (+31.3% … +32.3%) | 336 |
|
||||
| 10 | path miss | radix / oracle | 2.0192 (+101.9%) | 2.0063 – 2.0291 (+100.6% … +102.9%) | 336 |
|
||||
| 100 | static hit | radix / oracle | 0.4632 (-53.7%) | 0.4610 – 0.4662 (-53.9% … -53.4%) | 336 |
|
||||
| 100 | late param hit | radix / oracle | 0.5726 (-42.7%) | 0.5711 – 0.5741 (-42.9% … -42.6%) | 336 |
|
||||
| 100 | method miss | radix / oracle | 0.4193 (-58.1%) | 0.4173 – 0.4215 (-58.3% … -57.8%) | 336 |
|
||||
| 100 | path miss | radix / oracle | 0.4042 (-59.6%) | 0.4013 – 0.4064 (-59.9% … -59.4%) | 336 |
|
||||
| 500 | static hit | radix / oracle | 0.4673 (-53.3%) | 0.4653 – 0.4683 (-53.5% … -53.2%) | 336 |
|
||||
| 500 | late param hit | radix / oracle | 0.1751 (-82.5%) | 0.1744 – 0.1763 (-82.6% … -82.4%) | 336 |
|
||||
| 500 | method miss | radix / oracle | 0.0887 (-91.1%) | 0.0885 – 0.0889 (-91.2% … -91.1%) | 336 |
|
||||
| 500 | path miss | radix / oracle | 0.0786 (-92.1%) | 0.0784 – 0.0790 (-92.2% … -92.1%) | 336 |
|
||||
|
||||
load average: start 0.24 0.25 0.11, end 1.92 1.40 0.66; cpuset 6-7,14-15
|
||||
raw samples: out/lookup-raw.json
|
||||
@@ -0,0 +1,67 @@
|
||||
# Radix router lookup evidence: `ed19f16` (CARD-10, D4)
|
||||
|
||||
This is the formal D4 comparison for the radix index (FPRD-001 CARD-10, #109). It supersedes `../router-b128139/`.
|
||||
|
||||
The radix router (`src/http/router.ts`) runs against the frozen pre-radix linear matcher (`test/router-parity/oracle.ts`). `ed19f16` contains:
|
||||
|
||||
- `develop` at `72f591d`, which includes:
|
||||
- CARD-07 (#128);
|
||||
- the walk-stack fix (#131);
|
||||
- CARD-09 (#129);
|
||||
- the no-recompilation seam counters;
|
||||
- the harness order fix described below.
|
||||
|
||||
**Verdict: D4 passes.** Every cell passes. The 10-route late param hit passes by 0.1 point: its CI lower bound is +4.9% and the limit is +5%.
|
||||
|
||||
## Method
|
||||
|
||||
The harness, host, cpuset and image are the same as in `bench/baseline/router-ed47836/`, with two differences:
|
||||
|
||||
- 16 processes × 21 rounds give 336 paired rounds per cell. The owner asked for more rounds to narrow the CI on the borderline cell.
|
||||
- In `bench/lookup.ts` (`ed19f16`), each process now reverses the **whole** router order: import, warm-up, and which router opens each cell's first round. Before, only the import order alternated. The A/A in `../router-b128139/` showed a steady bias of up to +8.3% against the second-listed router at 10 routes, and with this change the same A/A centres on 0. The owner approved this method change on 2026-10-12.
|
||||
|
||||
Run details:
|
||||
|
||||
- **Host and container:** jarvis, `docker run --rm --cpuset-cpus 6,7,14,15 --user 1000:1000 node:22`.
|
||||
- **Image:** `sha256:5647be70…`, the same as the baseline.
|
||||
- **Command:** in `run.sh`. It ran on a `git archive` of `ed19f16`, installed with `npm ci --ignore-scripts`.
|
||||
- **Load:** see `load.txt`. The 1-minute load was about 1 throughout.
|
||||
|
||||
## D4 verdict (radix / oracle, median of per-round ratios, bootstrap 95% CI)
|
||||
|
||||
| routes | workload | ratio | 95% CI | D4 rule | verdict |
|
||||
| -----: | -------------- | -----: | --------------- | ------------------ | -------------------- |
|
||||
| 10 | static hit | −57.7% | −58.8% … −55.9% | lower bound ≤ +5% | pass |
|
||||
| 10 | late param hit | +5.6% | +4.9% … +6.6% | lower bound ≤ +5% | pass (margin 0.1 pt) |
|
||||
| 10 | method miss | −6.1% | −6.9% … −5.2% | lower bound ≤ +5% | pass |
|
||||
| 10 | path miss | −2.5% | −3.2% … −2.0% | lower bound ≤ +5% | pass |
|
||||
| 100 | static hit | −55.4% | −55.8% … −55.2% | lower bound ≤ +5% | pass |
|
||||
| 100 | late param hit | −57.9% | −58.1% … −57.7% | lower bound ≤ +5% | pass |
|
||||
| 100 | method miss | −70.6% | −70.7% … −70.6% | lower bound ≤ +5% | pass |
|
||||
| 100 | path miss | −80.1% | −80.2% … −80.1% | lower bound ≤ +5% | pass |
|
||||
| 500 | static hit | −54.2% | −54.7% … −53.8% | lower bound ≤ +5% | pass |
|
||||
| 500 | late param hit | −87.3% | −87.4% … −87.3% | upper bound ≤ −20% | pass |
|
||||
| 500 | method miss | −93.8% | −93.8% … −93.8% | upper bound ≤ −20% | pass |
|
||||
| 500 | path miss | −96.1% | −96.1% … −96.1% | upper bound ≤ −20% | pass |
|
||||
|
||||
## A/A noise band (oracle vs `oracle-copy`, same settings)
|
||||
|
||||
`oracle-copy` is a byte-identical copy of the oracle at another path (sha256 `8875ec12…`), so V8 sees two separate modules. It is not committed.
|
||||
|
||||
| routes | static hit | late param hit | method miss | path miss |
|
||||
| -----: | -------------------- | ------------------- | ------------------- | ------------------- |
|
||||
| 10 | +7.9% (+5.2 … +14.1) | −0.6% (−6.4 … +5.4) | −0.7% (−1.9 … +0.9) | −0.6% (−1.1 … −0.0) |
|
||||
| 100 | −2.4% (−3.0 … −2.0) | −0.4% (−1.5 … +1.3) | +0.2% (−0.5 … +0.6) | +0.0% (−0.3 … +0.5) |
|
||||
| 500 | −2.1% (−2.7 … −0.9) | −0.0% (−0.4 … +0.3) | +0.5% (+0.0 … +1.0) | +0.1% (−0.1 … +0.7) |
|
||||
|
||||
- **Late param hit at 10 routes:** the old harness had a +8.3% bias here, and it is gone.
|
||||
- **Static hit at 10 routes:** this cell still varies by several percent. It is the cheapest cell, about 80 ns per radix lookup. Radix is −58% on it, so this does not affect the verdict.
|
||||
|
||||
## Files
|
||||
|
||||
| File | What it is |
|
||||
| --------------------------------------- | ------------------------------------------------------------------------------------- |
|
||||
| `lookup-raw.json`, `lookup-summary.txt` | The D4 run: environment, method, every sample of every round, and the summary tables. |
|
||||
| `aa-raw.json`, `aa-summary.txt` | The A/A run. |
|
||||
| `load.txt` | Load average before and after each run. |
|
||||
| `run.sh` | The exact script run on jarvis. |
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,44 @@
|
||||
| routes | workload | router | median ns/op | run medians (ns) | run spread |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 10 | static hit | oracle | 184.9 | 161.5 / 191.2 / 171.2 / 197.5 / 177.1 / 188.6 / 160.5 / 198.9 / 170.6 / 197.6 / 169.9 / 199.4 / 157.8 / 185.4 / 173.3 / 193.4 | 22.5% |
|
||||
| 10 | static hit | oracle-copy | 193.0 | 201.2 / 164.3 / 204.2 / 177.6 / 207.4 / 158.2 / 192.9 / 159.0 / 194.1 / 162.4 / 202.0 / 210.2 / 193.6 / 158.7 / 205.0 / 152.7 | 29.8% |
|
||||
| 10 | late param hit | oracle | 338.6 | 313.5 / 352.1 / 322.0 / 348.0 / 328.9 / 341.3 / 318.8 / 345.6 / 337.1 / 353.2 / 325.0 / 351.8 / 315.3 / 341.8 / 323.6 / 357.5 | 13.0% |
|
||||
| 10 | late param hit | oracle-copy | 335.9 | 363.8 / 326.6 / 352.0 / 321.1 / 357.7 / 320.7 / 358.3 / 303.6 / 352.0 / 328.2 / 357.7 / 320.6 / 341.9 / 317.9 / 369.6 / 317.1 | 19.7% |
|
||||
| 10 | method miss | oracle | 778.0 | 754.3 / 784.9 / 782.6 / 789.8 / 781.1 / 774.3 / 771.4 / 765.4 / 767.2 / 801.7 / 778.0 / 785.8 / 762.0 / 777.7 / 780.3 / 775.2 | 6.1% |
|
||||
| 10 | method miss | oracle-copy | 770.3 | 768.7 / 767.8 / 805.3 / 757.9 / 796.7 / 759.9 / 804.6 / 743.0 / 796.8 / 759.1 / 799.6 / 764.3 / 777.8 / 745.2 / 784.3 / 752.3 | 8.1% |
|
||||
| 10 | path miss | oracle | 611.4 | 575.6 / 616.4 / 603.4 / 618.0 / 647.3 / 615.9 / 595.0 / 596.9 / 601.3 / 625.8 / 616.0 / 620.5 / 583.5 / 602.3 / 616.6 / 593.0 | 11.7% |
|
||||
| 10 | path miss | oracle-copy | 609.4 | 619.1 / 595.4 / 613.5 / 591.6 / 642.4 / 583.6 / 628.4 / 575.4 / 611.3 / 601.3 / 628.2 / 610.0 / 609.6 / 583.7 / 635.8 / 589.3 | 11.0% |
|
||||
| 100 | static hit | oracle | 208.7 | 207.7 / 210.4 / 207.8 / 210.4 / 221.5 / 199.1 / 206.7 / 211.5 / 201.0 / 217.3 / 204.9 / 213.8 / 203.7 / 206.4 / 208.5 / 210.1 | 10.7% |
|
||||
| 100 | static hit | oracle-copy | 205.8 | 208.9 / 196.3 / 212.2 / 203.7 / 217.6 / 194.6 / 213.2 / 202.2 / 208.2 / 205.8 / 215.3 / 206.1 / 214.3 / 197.2 / 202.9 / 195.2 | 11.2% |
|
||||
| 100 | late param hit | oracle | 877.6 | 863.1 / 894.9 / 864.3 / 876.5 / 872.4 / 875.8 / 876.0 / 878.3 / 871.3 / 903.5 / 878.7 / 906.6 / 857.8 / 886.7 / 876.3 / 883.0 | 5.6% |
|
||||
| 100 | late param hit | oracle-copy | 876.0 | 873.7 / 878.7 / 894.7 / 863.0 / 907.0 / 850.4 / 907.8 / 855.8 / 884.5 / 873.4 / 901.1 / 869.7 / 875.8 / 854.7 / 940.3 / 854.8 | 10.3% |
|
||||
| 100 | method miss | oracle | 2516.5 | 2453.3 / 2483.4 / 2487.6 / 2558.5 / 2523.3 / 2540.6 / 2488.3 / 2511.2 / 2525.1 / 2558.0 / 2516.4 / 2500.7 / 2417.7 / 2536.5 / 2524.2 / 2465.4 | 5.6% |
|
||||
| 100 | method miss | oracle-copy | 2502.9 | 2471.0 / 2451.7 / 2510.4 / 2516.7 / 2542.0 / 2508.5 / 2552.8 / 2465.8 / 2594.2 / 2495.7 / 2545.8 / 2462.7 / 2485.8 / 2452.2 / 2616.0 / 2448.2 | 6.7% |
|
||||
| 100 | path miss | oracle | 3037.3 | 2978.5 / 3022.9 / 3006.6 / 3103.8 / 3101.2 / 3046.5 / 2979.6 / 3040.1 / 3049.6 / 3118.8 / 3025.8 / 3011.0 / 2935.2 / 3071.9 / 3099.1 / 2965.5 | 6.0% |
|
||||
| 100 | path miss | oracle-copy | 3037.9 | 3041.2 / 2996.5 / 3028.4 / 3045.4 / 3096.7 / 2975.0 / 3079.9 / 2962.1 / 3136.0 / 3026.7 / 3094.9 / 2984.3 / 3048.0 / 2955.6 / 3244.1 / 2972.6 | 9.5% |
|
||||
| 500 | static hit | oracle | 209.3 | 211.9 / 210.6 / 208.7 / 215.4 / 215.7 / 200.7 / 206.6 / 209.7 / 203.8 / 214.9 / 203.8 / 214.2 / 202.2 / 206.1 / 209.9 / 208.0 | 7.2% |
|
||||
| 500 | static hit | oracle-copy | 208.2 | 212.9 / 195.6 / 214.1 / 208.4 / 212.5 / 194.1 / 210.6 / 201.8 / 209.8 / 207.9 / 216.0 / 208.0 / 205.3 / 197.4 / 209.5 / 196.0 | 10.5% |
|
||||
| 500 | late param hit | oracle | 2892.8 | 2922.3 / 2909.8 / 2907.3 / 2869.4 / 2896.2 / 2838.4 / 3127.0 / 2843.3 / 2856.8 / 2899.0 / 2850.2 / 2986.6 / 2834.3 / 2949.8 / 2921.4 / 2805.8 | 11.1% |
|
||||
| 500 | late param hit | oracle-copy | 2875.6 | 2954.7 / 2820.6 / 2892.0 / 2910.9 / 2838.5 / 2846.3 / 3085.2 / 2805.9 / 2875.2 / 2907.8 / 2915.2 / 2838.5 / 2831.3 / 2821.6 / 3177.4 / 2860.3 | 12.9% |
|
||||
| 500 | method miss | oracle | 11983.6 | 11847.4 / 12882.7 / 12017.7 / 12459.0 / 11847.8 / 11892.0 / 11939.7 / 12016.0 / 12380.8 / 12269.0 / 11950.3 / 12261.1 / 11912.2 / 11840.5 / 11665.5 / 11457.1 | 11.9% |
|
||||
| 500 | method miss | oracle-copy | 12159.0 | 11968.8 / 12588.8 / 12425.4 / 12422.9 / 11777.1 / 11917.7 / 12422.4 / 11747.1 / 12906.7 / 12187.0 / 12176.6 / 11921.2 / 11987.1 / 11776.4 / 12248.0 / 11684.3 | 10.1% |
|
||||
| 500 | path miss | oracle | 15652.9 | 15474.0 / 15789.1 / 15842.1 / 16100.5 / 16618.4 / 15582.3 / 15494.8 / 15694.0 / 15182.6 / 15975.5 / 15348.8 / 16286.0 / 15438.4 / 16749.9 / 15374.9 / 15001.2 | 11.2% |
|
||||
| 500 | path miss | oracle-copy | 15838.8 | 15516.0 / 15429.6 / 16192.3 / 16110.5 / 16422.0 / 15446.7 / 16269.8 / 15092.8 / 15859.0 / 15826.1 / 15883.9 / 15583.2 / 15528.5 / 16004.2 / 16248.8 / 15284.5 | 8.4% |
|
||||
|
||||
| routes | workload | B / A | median ratio | 95% CI | rounds |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 10 | static hit | oracle-copy / oracle | 1.0793 (+7.9%) | 1.0522 – 1.1409 (+5.2% … +14.1%) | 336 |
|
||||
| 10 | late param hit | oracle-copy / oracle | 0.9945 (-0.6%) | 0.9364 – 1.0536 (-6.4% … +5.4%) | 336 |
|
||||
| 10 | method miss | oracle-copy / oracle | 0.9933 (-0.7%) | 0.9813 – 1.0087 (-1.9% … +0.9%) | 336 |
|
||||
| 10 | path miss | oracle-copy / oracle | 0.9941 (-0.6%) | 0.9890 – 1.0000 (-1.1% … -0.0%) | 336 |
|
||||
| 100 | static hit | oracle-copy / oracle | 0.9757 (-2.4%) | 0.9702 – 0.9803 (-3.0% … -2.0%) | 336 |
|
||||
| 100 | late param hit | oracle-copy / oracle | 0.9955 (-0.4%) | 0.9846 – 1.0128 (-1.5% … +1.3%) | 336 |
|
||||
| 100 | method miss | oracle-copy / oracle | 1.0023 (+0.2%) | 0.9951 – 1.0057 (-0.5% … +0.6%) | 336 |
|
||||
| 100 | path miss | oracle-copy / oracle | 1.0001 (+0.0%) | 0.9966 – 1.0049 (-0.3% … +0.5%) | 336 |
|
||||
| 500 | static hit | oracle-copy / oracle | 0.9786 (-2.1%) | 0.9727 – 0.9915 (-2.7% … -0.9%) | 336 |
|
||||
| 500 | late param hit | oracle-copy / oracle | 0.9998 (-0.0%) | 0.9957 – 1.0028 (-0.4% … +0.3%) | 336 |
|
||||
| 500 | method miss | oracle-copy / oracle | 1.0051 (+0.5%) | 1.0004 – 1.0104 (+0.0% … +1.0%) | 336 |
|
||||
| 500 | path miss | oracle-copy / oracle | 1.0010 (+0.1%) | 0.9987 – 1.0074 (-0.1% … +0.7%) | 336 |
|
||||
|
||||
load average: start 1.02 0.97 0.62, end 1.07 1.03 0.75; cpuset 6-7,14-15
|
||||
raw samples: out/aa-raw.json
|
||||
@@ -0,0 +1,3 @@
|
||||
d4 before: 2026-10-12T20:16:20Z 15:16:20 up 46 days, 15:05, 2 users, load average: 0.89, 0.83, 0.44
|
||||
d4 after / aa before: 2026-10-12T20:21:20Z 15:21:20 up 46 days, 15:10, 2 users, load average: 1.02, 0.97, 0.62
|
||||
aa after: 2026-10-12T20:26:20Z 15:26:20 up 46 days, 15:15, 2 users, load average: 1.07, 1.03, 0.75
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,44 @@
|
||||
| routes | workload | router | median ns/op | run medians (ns) | run spread |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 10 | static hit | oracle | 183.5 | 170.9 / 196.0 / 159.6 / 207.7 / 162.1 / 212.6 / 165.0 / 190.8 / 163.7 / 185.1 / 164.6 / 199.1 / 155.7 / 192.8 / 164.1 / 195.6 | 31.0% |
|
||||
| 10 | static hit | radix | 77.7 | 74.8 / 75.8 / 79.8 / 75.6 / 81.1 / 78.2 / 91.4 / 74.7 / 80.8 / 76.5 / 81.8 / 79.1 / 81.1 / 72.6 / 77.2 / 71.4 | 25.7% |
|
||||
| 10 | late param hit | oracle | 344.2 | 343.1 / 352.8 / 313.5 / 373.3 / 321.1 / 377.3 / 326.4 / 349.7 / 317.4 / 355.7 / 320.6 / 357.8 / 312.4 / 346.3 / 316.1 / 364.3 | 18.9% |
|
||||
| 10 | late param hit | radix | 364.0 | 353.5 / 360.3 / 365.2 / 355.0 / 361.4 / 380.8 / 371.1 / 369.5 / 367.3 / 361.5 / 375.1 / 362.1 / 372.5 / 365.1 / 361.5 / 357.7 | 7.5% |
|
||||
| 10 | method miss | oracle | 773.0 | 746.5 / 785.3 / 758.8 / 759.6 / 765.0 / 820.1 / 768.3 / 780.1 / 765.4 / 780.6 / 761.5 / 775.7 / 773.2 / 782.9 / 744.8 / 796.6 | 9.8% |
|
||||
| 10 | method miss | radix | 723.0 | 734.2 / 714.1 / 698.9 / 716.7 / 763.9 / 723.3 / 814.9 / 709.9 / 733.4 / 696.8 / 751.3 / 722.2 / 715.6 / 755.9 / 723.8 / 719.0 | 16.3% |
|
||||
| 10 | path miss | oracle | 607.3 | 596.1 / 616.6 / 573.2 / 603.4 / 591.4 / 645.9 / 593.2 / 614.0 / 587.3 / 624.1 / 589.8 / 612.6 / 607.9 / 621.6 / 574.2 / 640.0 | 12.0% |
|
||||
| 10 | path miss | radix | 593.5 | 584.4 / 603.9 / 593.1 / 581.4 / 603.8 / 592.6 / 602.8 / 582.1 / 596.8 / 589.9 / 611.5 / 594.9 / 571.5 / 590.5 / 605.0 / 584.4 | 6.7% |
|
||||
| 100 | static hit | oracle | 206.6 | 213.9 / 206.7 / 196.7 / 217.4 / 199.7 / 213.5 / 225.5 / 205.7 / 194.3 / 208.8 / 203.9 / 216.4 / 197.6 / 204.8 / 204.0 / 211.0 | 15.1% |
|
||||
| 100 | static hit | radix | 92.4 | 91.2 / 92.3 / 93.3 / 87.3 / 89.0 / 90.9 / 101.9 / 92.4 / 98.0 / 85.6 / 100.2 / 93.9 / 98.8 / 81.5 / 97.7 / 87.1 | 22.1% |
|
||||
| 100 | late param hit | oracle | 889.6 | 866.4 / 897.8 / 852.5 / 888.2 / 887.2 / 902.6 / 896.5 / 914.7 / 861.6 / 879.4 / 869.5 / 905.6 / 870.3 / 906.5 / 855.8 / 910.7 | 7.0% |
|
||||
| 100 | late param hit | radix | 370.2 | 368.5 / 355.8 / 369.2 / 371.2 / 363.5 / 386.8 / 384.7 / 355.4 / 371.7 / 366.8 / 386.6 / 363.3 / 385.2 / 382.4 / 359.7 / 381.2 | 8.5% |
|
||||
| 100 | method miss | oracle | 2523.3 | 2478.4 / 2543.4 / 2454.7 / 2465.9 / 2556.8 / 2556.0 / 2572.0 / 2518.0 / 2506.3 / 2527.4 / 2491.5 / 2507.7 / 2529.7 / 2588.4 / 2437.8 / 2635.8 | 7.8% |
|
||||
| 100 | method miss | radix | 742.6 | 752.0 / 724.4 / 736.4 / 724.1 / 755.3 / 737.5 / 747.6 / 738.0 / 761.9 / 723.8 / 773.0 / 738.3 / 743.8 / 727.2 / 748.1 / 746.0 | 6.6% |
|
||||
| 100 | path miss | oracle | 3064.0 | 2996.5 / 3098.5 / 2949.4 / 2992.4 / 3066.7 / 3109.7 / 3092.9 / 3104.7 / 3033.1 / 3054.4 / 3007.8 / 3073.7 / 3033.7 / 3154.8 / 2945.8 / 3178.4 | 7.6% |
|
||||
| 100 | path miss | radix | 601.4 | 593.1 / 594.2 / 597.1 / 601.0 / 630.5 / 591.5 / 624.1 / 617.2 / 578.7 / 611.0 / 622.7 / 599.9 / 603.3 / 555.5 / 604.3 / 602.1 | 12.5% |
|
||||
| 500 | static hit | oracle | 208.9 | 214.7 / 208.6 / 195.7 / 217.1 / 198.1 / 210.1 / 222.5 / 207.1 / 194.3 / 209.3 / 200.2 / 216.9 / 195.1 / 200.3 / 209.6 / 211.9 | 13.5% |
|
||||
| 500 | static hit | radix | 94.3 | 91.4 / 97.9 / 89.9 / 89.5 / 86.3 / 89.1 / 104.5 / 100.4 / 100.1 / 86.5 / 97.5 / 98.9 / 97.3 / 77.8 / 102.6 / 89.5 | 28.4% |
|
||||
| 500 | late param hit | oracle | 2888.2 | 2786.7 / 2872.4 / 2767.8 / 2860.5 / 2993.3 / 2794.6 / 2875.9 / 2952.6 / 2916.0 / 2898.9 / 2798.5 / 2896.8 / 2814.6 / 2907.4 / 2931.7 / 2967.0 | 7.8% |
|
||||
| 500 | late param hit | radix | 366.8 | 356.9 / 356.5 / 359.8 / 363.2 / 367.0 / 368.5 / 385.1 / 359.3 / 370.1 / 359.1 / 371.8 / 363.8 / 374.1 / 374.1 / 366.4 / 372.0 | 7.8% |
|
||||
| 500 | method miss | oracle | 11874.2 | 11413.6 / 11968.3 / 11607.4 / 11878.7 / 11790.1 / 11980.8 / 11864.2 / 12272.0 / 12594.5 / 11869.7 / 11764.9 / 11698.0 / 11665.0 / 11709.8 / 11844.9 / 12182.7 | 9.9% |
|
||||
| 500 | method miss | radix | 742.6 | 745.3 / 732.5 / 723.4 / 729.2 / 751.7 / 720.7 / 751.0 / 755.4 / 745.2 / 731.5 / 751.2 / 741.4 / 740.2 / 709.8 / 763.6 / 755.6 | 7.2% |
|
||||
| 500 | path miss | oracle | 15410.9 | 14864.1 / 15496.8 / 14872.3 / 15422.0 / 15357.7 / 15515.3 / 15290.8 / 15967.8 / 16266.8 / 15399.2 / 15008.4 / 15404.7 / 15121.7 / 15493.3 / 15280.0 / 16059.3 | 9.1% |
|
||||
| 500 | path miss | radix | 597.3 | 597.3 / 576.9 / 596.6 / 592.0 / 605.6 / 589.7 / 620.5 / 628.8 / 598.2 / 596.8 / 586.1 / 589.7 / 625.4 / 595.5 / 644.3 / 612.2 | 11.3% |
|
||||
|
||||
| routes | workload | B / A | median ratio | 95% CI | rounds |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 10 | static hit | radix / oracle | 0.4230 (-57.7%) | 0.4115 – 0.4410 (-58.8% … -55.9%) | 336 |
|
||||
| 10 | late param hit | radix / oracle | 1.0562 (+5.6%) | 1.0490 – 1.0656 (+4.9% … +6.6%) | 336 |
|
||||
| 10 | method miss | radix / oracle | 0.9389 (-6.1%) | 0.9306 – 0.9483 (-6.9% … -5.2%) | 336 |
|
||||
| 10 | path miss | radix / oracle | 0.9749 (-2.5%) | 0.9678 – 0.9796 (-3.2% … -2.0%) | 336 |
|
||||
| 100 | static hit | radix / oracle | 0.4456 (-55.4%) | 0.4420 – 0.4480 (-55.8% … -55.2%) | 336 |
|
||||
| 100 | late param hit | radix / oracle | 0.4209 (-57.9%) | 0.4190 – 0.4226 (-58.1% … -57.7%) | 336 |
|
||||
| 100 | method miss | radix / oracle | 0.2939 (-70.6%) | 0.2928 – 0.2944 (-70.7% … -70.6%) | 336 |
|
||||
| 100 | path miss | radix / oracle | 0.1986 (-80.1%) | 0.1979 – 0.1992 (-80.2% … -80.1%) | 336 |
|
||||
| 500 | static hit | radix / oracle | 0.4585 (-54.2%) | 0.4530 – 0.4620 (-54.7% … -53.8%) | 336 |
|
||||
| 500 | late param hit | radix / oracle | 0.1267 (-87.3%) | 0.1261 – 0.1273 (-87.4% … -87.3%) | 336 |
|
||||
| 500 | method miss | radix / oracle | 0.0620 (-93.8%) | 0.0617 – 0.0622 (-93.8% … -93.8%) | 336 |
|
||||
| 500 | path miss | radix / oracle | 0.0388 (-96.1%) | 0.0386 – 0.0390 (-96.1% … -96.1%) | 336 |
|
||||
|
||||
load average: start 0.89 0.83 0.44, end 1.02 0.97 0.62; cpuset 6-7,14-15
|
||||
raw samples: out/lookup-raw.json
|
||||
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
cd "$(dirname "$0")"
|
||||
run() { docker run --rm --cpuset-cpus 6,7,14,15 --user 1000:1000 -e HOME=/tmp -v "$PWD":/w -w /w -e LOOKUP_ROUTERS="$2" -e LOOKUP_RUNS=16 -e LOOKUP_ROUNDS=21 -e LOOKUP_OUT="$1" -e LOOKUP_COMMIT=ed19f16c70bcc70bd762c627d8d2dd78645a6c4d -e LOOKUP_HOST=jarvis -e LOOKUP_CPUSET=6,7,14,15 -e LOOKUP_IMAGE="$(docker image inspect node:22 --format '{{.Id}}')" node:22 node --import tsx bench/lookup.ts; }
|
||||
echo "d4 before: $(date -u +%FT%TZ) $(uptime)" > out/load.txt
|
||||
run out/lookup-raw.json oracle=test/router-parity/oracle.ts,radix=src/http/router.ts > out/lookup-summary.txt 2> out/lookup-stderr.txt
|
||||
echo "d4 after / aa before: $(date -u +%FT%TZ) $(uptime)" >> out/load.txt
|
||||
run out/aa-raw.json oracle=test/router-parity/oracle.ts,oracle-copy=test/router-parity/oracle-copy.ts > out/aa-summary.txt 2> out/aa-stderr.txt
|
||||
echo "aa after: $(date -u +%FT%TZ) $(uptime)" >> out/load.txt
|
||||
@@ -18,12 +18,17 @@ function makeStep(n: number) {
|
||||
}
|
||||
const steps = [1, 2, 3, 4, 5].map(makeStep);
|
||||
|
||||
// ~8 KB of JSON: well over the 1024-byte compression threshold, and repetitive the way list
|
||||
// responses are, so the encoders do real work rather than bailing out on incompressible input.
|
||||
const BIG = Array.from({ length: 120 }, (_, i) => ({ id: i, name: `user ${i}`, email: `user${i}@example.com`, active: i % 2 === 0 }));
|
||||
|
||||
@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('/big') big() { return BIG; }
|
||||
@Get('/steps/5') steps5(@needs('s5') s5: number) { return { hello: 'world', s5 }; }
|
||||
// Reads the counter without resetting it — the read itself carries no Origin, so it cannot
|
||||
// change what it reports.
|
||||
@@ -68,10 +73,12 @@ const cors =
|
||||
}
|
||||
: undefined;
|
||||
|
||||
// Only passed when asked for, so the file still boots against a revision without compression.
|
||||
const app = createApp({
|
||||
modules: [BenchModule],
|
||||
security: process.env.GT_SECURE === '1',
|
||||
...(cors ? { cors } : {}),
|
||||
...(process.env.GT_COMPRESS === '1' ? { compression: true } : {}),
|
||||
});
|
||||
|
||||
async function main() {
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
"packageJson": {
|
||||
"dependencies": [
|
||||
"npm:@eslint/js@^9.39.5",
|
||||
"npm:@microsoft/api-extractor@^7.59.4",
|
||||
"npm:@nestjs/common@^11.1.28",
|
||||
"npm:@nestjs/core@^11.1.28",
|
||||
"npm:@nestjs/platform-express@^11.1.28",
|
||||
@@ -27,7 +28,7 @@
|
||||
"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/node@^22.20.5",
|
||||
"npm:@types/ws@^8.18.1",
|
||||
"npm:autocannon@8",
|
||||
"npm:busboy@^1.6.0",
|
||||
@@ -35,7 +36,7 @@
|
||||
"npm:esbuild@0.27.2",
|
||||
"npm:eslint@^9.39.5",
|
||||
"npm:express@^5.2.1",
|
||||
"npm:fastify@^5.11.0",
|
||||
"npm:fastify@^5.12.5",
|
||||
"npm:graphql@^16.9.0",
|
||||
"npm:miniflare@^4.20260730.0",
|
||||
"npm:prettier@^3.9.6",
|
||||
@@ -46,7 +47,7 @@
|
||||
"npm:typescript-eslint@^8.65.0",
|
||||
"npm:typescript@^5.5.0",
|
||||
"npm:vite@^6.4.3",
|
||||
"npm:vitest@^3.2.7",
|
||||
"npm:vitest@^4.1.11",
|
||||
"npm:ws@^8.21.1"
|
||||
],
|
||||
"overrides": {
|
||||
@@ -56,7 +57,10 @@
|
||||
"uuid": "11.1.1"
|
||||
}
|
||||
},
|
||||
"undici": "7.29.0"
|
||||
"undici": "7.30.1",
|
||||
"sharp": "0.35.5",
|
||||
"fastify": "$fastify",
|
||||
"multer": "2.5.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,170 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,679 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,166 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,166 +0,0 @@
|
||||
# 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
|
||||
```
|
||||
@@ -1,350 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,211 +0,0 @@
|
||||
# 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`.
|
||||
@@ -1,141 +0,0 @@
|
||||
# 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`.
|
||||
@@ -1,89 +0,0 @@
|
||||
# A teapot that may be absent, declared per teapot
|
||||
|
||||
**Status:** planned, 2026-08-18
|
||||
**Depends on:** the boot grace (`bootTimeoutMs`) and the reconnect/refuse work already merged
|
||||
**Mesh stays alpha.**
|
||||
|
||||
## The decision
|
||||
|
||||
Strictness is a property of the *teapot*, not of the app. Diego: *"es mejor que los teapots definan
|
||||
esa estrategia … 503 suena mejor para billing que para authorization."* A payment provider being
|
||||
away is a degraded checkout; an authorization provider being away is not a degraded anything.
|
||||
|
||||
```ts
|
||||
mesh: {
|
||||
teapots: [
|
||||
{ url: billingUrl, secret, expects: ['billing'], onUnreachable: 'degrade' },
|
||||
{ url: authUrl, secret }, // 'fail' — the default
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
## Why `expects` is required for `'degrade'`, and not inferred
|
||||
|
||||
A teapot that never answered never sent a manifest, so **we do not know what it exported**. Without
|
||||
that list there is nothing to put in the graph, `@needs('billing')` has no provider, and graph
|
||||
validation fails the boot anyway — degrading would fail identically, just later.
|
||||
|
||||
The tempting shortcut is to placeholder *every unresolved token*. That must not happen: it would
|
||||
turn a misspelled `needs` into a runtime 503 instead of a boot error, and destroy the property the
|
||||
framework leads with. `expects` keeps the placeholder set exact, so a typo anywhere else still fails
|
||||
loudly.
|
||||
|
||||
It also pushes the developer to state what a service depends on, which is the same discipline the
|
||||
graph asks for everywhere else. `createApp` throws when `'degrade'` is set without a non-empty
|
||||
`expects`, naming the teapot.
|
||||
|
||||
## Decisions
|
||||
|
||||
**D1 — Placeholders are request-scope, never app-scope.** An app-scope placeholder resolves once at
|
||||
boot, and throwing there is the very failure we are avoiding. A request-scope node runs per request
|
||||
and throws `503`, naming the token and the teapot it belongs to.
|
||||
|
||||
**D2 — `expects` covers scope tokens only, not routes.** A degraded teapot's exported *routes*
|
||||
simply do not exist locally, because a route needs a method and a pattern we were never told. A
|
||||
request for one 404s, which is what an unregistered route does everywhere else. Documented, not
|
||||
silent.
|
||||
|
||||
**D3 — Degraded tokens surface through `app.degraded()`**, the API that already reports optional
|
||||
providers that failed to boot. A teapot that came up degraded is the same idea, not a parallel one,
|
||||
and a consumer that already checks `degraded()` before reporting healthy gets this for free. Plus a
|
||||
boot-time `logger.warn` and a `mesh:boot:degraded` event, for the same reason retries are both
|
||||
logged and emitted.
|
||||
|
||||
**D4 — A degraded link keeps trying in the background.** Reconnection today only covers links that
|
||||
handshook at least once; this one never did, so it needs its own attempt loop. Without it a degraded
|
||||
teapot stays degraded until the process restarts, which is the bug this plan exists to avoid, moved.
|
||||
|
||||
**D5 — Adoption is the refuse rule again.** When a degraded teapot finally answers, its manifest
|
||||
must contain everything in `expects`; if it does not, the connection is refused and the placeholders
|
||||
stay. Same policy, same reason, and it reuses `missingFromManifest` with `expects` as the baseline
|
||||
instead of a boot manifest.
|
||||
|
||||
**D6 — Swapping placeholders for real runners reuses the rebind seam** added for reconnection
|
||||
(`invalidateRemoteBindings`). If that seam turns out not to fit, that is a signal the seam was
|
||||
wrong, not a reason to write a second one.
|
||||
|
||||
**Note, 2026-09-06: that seam is gone.** `invalidateRemoteBindings`, the `rebind` array and the
|
||||
`onReconnect` callback were removed along with the remote app-scope binding when the mesh stopped
|
||||
exporting providers — with nothing cached between requests, there is nothing left to invalidate.
|
||||
This does not block D6, and it is not the "seam was wrong" case either: a degraded token swaps the
|
||||
*runner* behind a step node, which is a graph mutation, not a container rebind. It never needed the
|
||||
seam. Whatever the swap is written on, it is still one mechanism, decided when the work starts.
|
||||
|
||||
## Tasks
|
||||
|
||||
1. `expects` and `onUnreachable` on the teapot entry; `createApp` throws for `'degrade'` without
|
||||
`expects`.
|
||||
2. Placeholder step nodes per D1, registered when the boot grace runs out under `'degrade'`.
|
||||
3. `degraded()` reporting per D3, plus the warn and the event.
|
||||
4. Background attempt loop per D4, and adoption per D5/D6.
|
||||
5. Tests, on all three server runtimes: boots degraded, the token 503s with a message naming it,
|
||||
the teapot arrives late and the same request then succeeds, a manifest missing `expects` is
|
||||
refused, and `'degrade'` without `expects` fails at `createApp`.
|
||||
6. Docs: the mesh guide, `app.degraded()` in the reference, and the event table.
|
||||
|
||||
## Size
|
||||
|
||||
Comparable to the reconnection work — a background loop, a graph mutation and a runtime swap, on
|
||||
three runtimes. Not a follow-up to squeeze into another change.
|
||||
@@ -1,108 +0,0 @@
|
||||
# Mesh reconnection, with a refusing manifest policy
|
||||
|
||||
**Status:** planned, 2026-08-18
|
||||
**Scope:** `src/mesh/link.ts`, `src/app/index.ts`, `src/container.ts`, mesh tests, `guides/mesh.md`
|
||||
**Mesh stays alpha.** It remains behind `experimental: true`. This closes the gap that makes mesh
|
||||
unusable in production; it does not move the label, because the label is a statement about how much
|
||||
we know, and we will know more once this runs somewhere real.
|
||||
|
||||
## The problem
|
||||
|
||||
There is no reconnection anywhere in `src/`. Combined with `spliceRemoteScopes` connecting teapots
|
||||
serially and throwing on any failure (`src/app/index.ts:631`):
|
||||
|
||||
- a teapot down at boot → the teacup does not start;
|
||||
- a teapot that dies afterwards → that link is dead for the life of the process, 503 on every RPC.
|
||||
|
||||
**Deploying a teapot therefore forces a restart of every teacup**, and boot order becomes
|
||||
load-bearing. That is a worse operational property than any gap currently written in the docs.
|
||||
|
||||
## Vocabulary
|
||||
|
||||
**Reconnect** is returning to the *same* teapot when it comes back. **Failover** — switching to a
|
||||
different teapot exporting the same thing — needs load balancing and stays out of scope. The two
|
||||
words must not be used interchangeably in code, CHANGELOG or docs.
|
||||
|
||||
## Decisions
|
||||
|
||||
**D1 — The `Link` object must survive the reconnect.** `buildRemote` captures `link.rpc` into the
|
||||
registry's runners at boot, and the graph holds those closures. A reconnect that produced a new
|
||||
`Link` would leave the graph pointing at the dead one. So `Link` owns a *swappable* socket, and
|
||||
`connectLink` becomes "establish, then keep established".
|
||||
|
||||
**D2 — Reconnection covers links that handshook at least once.** A boot-time failure still fails
|
||||
boot, unchanged. Boot retry is a separate piece of work; mixing them would blur "this app cannot be
|
||||
configured" with "this dependency is temporarily away".
|
||||
|
||||
**D3 — Exponential backoff with jitter**, 500 ms initial, 30 s cap, timer `unref`'d — matching the
|
||||
heartbeat, so reconnection never holds a process open on its own.
|
||||
|
||||
**D4 — The refuse rule.** On reconnect, the new manifest must still contain **everything this link
|
||||
contributed at boot**: every scope token, with the same `app`/`request` lifetime, and every route by
|
||||
method plus *effective shape* (the same comparison `spliceRemoteScopes` already uses for ambiguity,
|
||||
so `/:id` and `/:name` are the same shape). Anything missing → refuse the connection.
|
||||
|
||||
Rationale: the graph was validated at boot against the old manifest and is already running. A token
|
||||
that vanished cannot be validated away after the fact, and serving requests against a manifest that
|
||||
no longer backs the graph is how you get a 500 that looks like application code.
|
||||
|
||||
**D5 — Extra exports in a returned manifest are ignored.** The graph is fixed at boot; new tokens are
|
||||
not spliced in. Documented, not silent.
|
||||
|
||||
**D6 — A refused reconnect keeps retrying, but logs once per distinct manifest fingerprint.** A
|
||||
rollback can restore the missing token, so giving up permanently would turn a recoverable state into
|
||||
an outage. Logging every attempt at the 30 s cap would be 2,880 identical lines a day.
|
||||
|
||||
**D7 — The policy is a named strategy from day one**: `mesh: { onManifestChange: 'refuse' }`, and
|
||||
`'refuse'` is the default. Reconciliation is a future version and lands as `'reconcile'`, additively.
|
||||
If refusal shipped as implicit behaviour instead, adding reconciliation later would change the
|
||||
meaning of an existing default across processes on separate deploy cadences — breaking, in the worst
|
||||
place to be breaking.
|
||||
|
||||
**D8 — App-scope invalidation is lazy, and re-registers rather than clears.** A remote app-scope
|
||||
provider is resolved once at boot and frozen into the container as `() => value`
|
||||
(`src/app/index.ts:744`). Invalidation re-registers the binding with a factory that re-runs the RPC
|
||||
and resets `resolved`, so the *next* resolve pays for it. Eager re-resolution would put a network
|
||||
call on the reconnect path, where its failure has nowhere to go. This closes the documented
|
||||
"app-scope export survives its teapot with a stale value" gap.
|
||||
|
||||
The invalidation is written as **"invalidate the remote bindings of link X"**, a named function, not
|
||||
inline in the reconnect handler — that function is what reconciliation will reuse.
|
||||
|
||||
**D9 — `close()` is terminal.** `closeLinks` runs on shutdown; a link closed by the application must
|
||||
never reconnect. This is the trap worth naming: without it, `app.close()` leaves a process that
|
||||
cannot exit.
|
||||
|
||||
**D10 — RPCs during the down window are unchanged**: immediate 503 from the existing `isOpen` guard,
|
||||
not a wait for `timeoutMs`.
|
||||
|
||||
## Tasks
|
||||
|
||||
1. **`Link` owns its socket.** Extract the handshake into something callable more than once; `Link`
|
||||
holds `current: WsSocket | undefined`, and `rpc` reads it. `isOpen` false → the existing 503.
|
||||
2. **Reconnect loop** on `abort`, unless closed by D9. Backoff per D3, `mesh:disconnect` on drop and
|
||||
`mesh:connect` on success (existing events; no new bus contract in alpha).
|
||||
3. **Manifest comparison.** Capture the contributed set at boot, compare per D4, reuse
|
||||
`compilePattern(...).shape` for routes. Refusal logs the missing token or route by name.
|
||||
4. **`invalidateRemoteBindings(link)`** per D8, called on successful reconnect.
|
||||
|
||||
**Note, 2026-09-06:** this no longer exists. When the mesh stopped exporting providers, the
|
||||
remote app-scope binding went with it, and `invalidateRemoteBindings`, the `rebind` array and the
|
||||
`onReconnect` callback went with that — there is no cached value left to invalidate, so a
|
||||
reconnected link is simply usable again on the next RPC. The rest of this plan shipped as
|
||||
written; only this step has no counterpart in the code.
|
||||
5. **Config**: `mesh: { reconnect?: boolean | { initialDelayMs?, maxDelayMs? }, onManifestChange?: 'refuse' }`.
|
||||
Reconnect defaults **on**. Validate at boot like the other mesh options.
|
||||
6. **Tests.** Reconnect after the teapot returns; refuse when a token disappears, with the message
|
||||
naming it; `close()` stops reconnection (assert no timer keeps the process alive); an app-scope
|
||||
value re-resolves after reconnect; a heartbeat-triggered close reconnects. Deno and Bun get the
|
||||
reconnect case — the platform `WebSocket` is a different client implementation, which is exactly
|
||||
where a swappable socket can break.
|
||||
7. **Docs.** `guides/mesh.md`: mesh stays alpha, the gap list loses the stale-value entry and gains
|
||||
"extra exports are not spliced". CHANGELOG under `Fixed`, because from the operator's side this is
|
||||
a defect, not a feature.
|
||||
|
||||
## Not in this plan
|
||||
|
||||
Boot retry, correlation across the mesh (and the `mesh:rpc:error` name/id bug), the teapot handshake
|
||||
deadline, the frame size cap, `req.url` in the envelope. All queued, none blocked by this.
|
||||
@@ -1,710 +0,0 @@
|
||||
# A mesh that exports steps, not providers
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: use `superpowers:subagent-driven-development` or
|
||||
> `superpowers:executing-plans` to work through this task by task. Steps use `- [ ]` for tracking.
|
||||
|
||||
**Status:** planned, 2026-09-06
|
||||
**Scope:** `src/mesh/protocol.ts`, `src/mesh/teapot.ts`, `src/mesh/teacup.ts`, `src/app/index.ts`,
|
||||
mesh tests on all runtimes, `README.md`, `CHANGELOG.md`
|
||||
**Mesh stays alpha.** It remains behind `experimental: true`, and the wire changes without a
|
||||
protocol bump because of it.
|
||||
|
||||
**Goal:** A teapot exports **steps and routes only**. Exporting a `@Provider` becomes a boot error,
|
||||
and a teapot that is unreachable at boot no longer stops the teacup from starting.
|
||||
|
||||
## The problem
|
||||
|
||||
`@Provider` is a factory whose value *is* the object — `db`, a client, a pool. That object cannot
|
||||
cross a wire, and the mesh already knows it: `untransportable` (`src/mesh/protocol.ts:145`) refuses
|
||||
any class instance, so an exported provider can only ever return plain data. What survives is the
|
||||
worst half of the idea — `src/app/index.ts:854` registers the remote provider as an **app-scope**
|
||||
binding, so the teacup resolves it once at boot and answers from that snapshot for the life of the
|
||||
process. It is a cache the teapot no longer stands behind, wearing the word "provider".
|
||||
|
||||
A step is the shape that actually works across the mesh. It runs per request, the teacup sends the
|
||||
envelope, the teapot resolves its own graph and sends back the result, and the teacup binds it to
|
||||
the token. Transparent to the caller, and nothing is held.
|
||||
|
||||
Two things follow from that, and they are the whole of this plan:
|
||||
|
||||
1. **Exporting a provider is not a feature to fix, it is a thing to forbid.** The alternative
|
||||
already exists and is spelled `@Step({ export: true })`.
|
||||
2. **The boot no longer needs to block on a teapot.** Blocking existed because an app-scope value
|
||||
has to be resolved *at boot* — there is no later. A step has nothing but later. A teapot that is
|
||||
away costs a `503` on the requests that need it, and the app starts.
|
||||
|
||||
## Decisions
|
||||
|
||||
**D1 — `export: true` on a `@Provider` is a boot error, not a silent no-op.** Turning it into a
|
||||
warning would leave a running app whose token resolves locally and looks exported. The error names
|
||||
the replacement, so the message is a fix and not a complaint.
|
||||
|
||||
**D2 — No protocol bump.** Removing `ScopeEntry.scope` is a field removal, which the rule in
|
||||
`src/mesh/protocol.ts:11` would normally make a bump. Mesh is alpha and behind `experimental: true`,
|
||||
both peers ship from this repo, and a bump would spend the number on a version nobody deployed.
|
||||
`MESH_PROTOCOL_VERSION` stays `1`.
|
||||
|
||||
**D3 — Keep `connectUntilDeadline`; delete only its `throw`.** *This corrects what was said in the
|
||||
design conversation.* The retry loop is not the boot blocker — the `throw` at the end of it is. The
|
||||
loop is the co-deploy grace: a teacup that starts two seconds ahead of its teapot waits, gets the
|
||||
manifest, and has its steps for the process lifetime. Delete the loop and that teacup instead boots
|
||||
into a graph with no `authorization` node, which is strictly worse than today. So the budget stays;
|
||||
exhausting it now warns and contributes nothing, instead of failing the boot.
|
||||
|
||||
**D4 — A permanent refusal still fails the boot.** `isPermanentRefusal` covers a wrong secret and a
|
||||
protocol mismatch. Those are configuration errors — the same class as a typo in a token name — and
|
||||
they will be the same errors in thirty seconds. Failing at boot with the reason beats a `503` at
|
||||
3am that says nothing about a secret. Only *unreachable* becomes non-fatal.
|
||||
|
||||
**D5 — A missing token still fails the boot, through the ordinary validator.** If a teapot is away
|
||||
and a local step declares `needs: ['authorization']`, `topoSort` throws
|
||||
`missing dependency: authorization needed by …` (`src/graph.ts:54`). That is not a mesh step to
|
||||
remove: it is what catches a typo, and tolerating it would let a misspelled token boot clean and
|
||||
`503` forever. The message gains the teapots that did not connect, so the cause is on the screen.
|
||||
|
||||
**D6 — The `expects` / degrade plan survives; its D6 does not.**
|
||||
`docs/plans/2026-08-18-mesh-degrade-plan.md` is still the right answer for "this teapot may
|
||||
legitimately be absent", and it is already steps-only. But its D6 reuses
|
||||
`invalidateRemoteBindings`, which this plan deletes. That seam was app-scope-specific; a degraded
|
||||
step swaps a runner, not a container binding. Note it there rather than leave a dangling reference.
|
||||
|
||||
## File structure
|
||||
|
||||
| File | Change |
|
||||
| --- | --- |
|
||||
| `src/mesh/protocol.ts` | `Manifest` → `{ steps: string[]; routes: RouteEntry[] }`; drop `ScopeEntry`; update the `manifest` frame and its `SHAPE` row |
|
||||
| `src/mesh/teapot.ts` | `buildManifest({ steps, routes })` |
|
||||
| `src/mesh/teacup.ts` | `buildRemote` → `{ steps, routes }` |
|
||||
| `src/graph.ts` | `topoSort` takes an optional note appended to the missing-dependency error |
|
||||
| `src/app/index.ts` | forbid provider export; drop the remote-provider loop, `rebind`, `invalidateRemoteBindings`, `exportedProviders`; `connectUntilDeadline` exhaustion becomes non-fatal |
|
||||
| tests | `test/mesh/*`, `test/deno/mesh*`, `test/bun/mesh*`, `test/interop/_node-peer.ts`, `test/edge/_worker.mjs` |
|
||||
| docs | `README.md` mesh section, `CHANGELOG.md`, the degrade plan's D6 |
|
||||
|
||||
## A note on the line numbers
|
||||
|
||||
Every `file:line` below is accurate as of `85b6c70` and drifts as tasks land. Locate code by symbol —
|
||||
`collectProviders`, `spliceRemoteScopes`, `connectUntilDeadline`, `buildMeshControl`, `finalizeGraph`
|
||||
— and treat the numbers as hints.
|
||||
|
||||
---
|
||||
|
||||
## Task 1: Forbid exporting a provider
|
||||
|
||||
The prohibition lands first and alone, because every later task assumes it. Nothing on the wire
|
||||
changes yet.
|
||||
|
||||
**Files**
|
||||
- Modify: `src/app/index.ts:440` (`collectProviders`)
|
||||
- Test: `test/mesh/failure.test.ts`
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```ts
|
||||
// test/mesh/failure.test.ts
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { createApp, Provider, Module } from '../../src/index';
|
||||
|
||||
describe('provider export', () => {
|
||||
it('refuses to boot when a provider is exported over the mesh', async () => {
|
||||
@Provider({ provides: 'db', needs: [], export: true } as any)
|
||||
class Db {
|
||||
provide() {
|
||||
return { db: { query: () => [] } };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', providers: [Db] })
|
||||
class AppModule {}
|
||||
|
||||
expect(() => createApp({ modules: [AppModule], mesh: { secret: 's' } })).toThrow(
|
||||
/provider 'db' cannot be exported/i,
|
||||
);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run it and watch it fail**
|
||||
|
||||
```bash
|
||||
npx vitest run test/mesh/failure.test.ts -t 'refuses to boot'
|
||||
```
|
||||
|
||||
Expected: FAIL — no error is thrown, the app builds.
|
||||
|
||||
- [ ] **Step 3: Throw in `collectProviders`**
|
||||
|
||||
Replace `src/app/index.ts:440`:
|
||||
|
||||
```ts
|
||||
if (meta.export) registry.exportedProviders.push(meta.provides);
|
||||
```
|
||||
|
||||
with:
|
||||
|
||||
```ts
|
||||
// A provider's value IS the object it builds — a pool, a client, a `db`. That cannot cross a
|
||||
// wire, and the half of it that could (plain data) arrived as an app-scope binding the teacup
|
||||
// resolved once and cached for the life of the process. A step is the shape that travels:
|
||||
// it runs per request, on the teapot, and only its result comes back.
|
||||
if (meta.export)
|
||||
throw new Error(
|
||||
`mesh: provider '${meta.provides}' cannot be exported — a provider is a factory whose value ` +
|
||||
'is the object itself, and the mesh transports data, not objects. ' +
|
||||
'Export a @Step instead, which runs on the teapot per request and returns its result.',
|
||||
);
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run it and watch it pass**
|
||||
|
||||
```bash
|
||||
npx vitest run test/mesh/failure.test.ts -t 'refuses to boot'
|
||||
```
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 5: Fix every test that exported a provider**
|
||||
|
||||
```bash
|
||||
npx vitest run test/mesh/
|
||||
```
|
||||
|
||||
Convert any `@Provider({ ..., export: true })` in a fixture to `@Step({ ..., export: true })`.
|
||||
Check `test/mesh/integration.test.ts`, `test/mesh/envelope.test.ts`, `test/mesh/transport.test.ts`,
|
||||
`test/mesh/fetch-boot.test.ts`, `test/interop/_node-peer.ts`, `test/edge/_worker.mjs`.
|
||||
|
||||
- [ ] **Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add src/app/index.ts test/
|
||||
git commit -m "feat(mesh)!: refuse to export a provider
|
||||
|
||||
A provider's value is the object it builds, which cannot cross a JSON wire.
|
||||
What did cross became an app-scope binding the teacup resolved once at boot
|
||||
and served from a cache the teapot no longer stood behind. A step is the
|
||||
shape that travels; the error says so."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 2: A manifest of steps and routes
|
||||
|
||||
**Files**
|
||||
- Modify: `src/mesh/protocol.ts` (`ScopeEntry`, `Manifest`, `Frame`, `SHAPE.manifest`)
|
||||
- Modify: `src/mesh/teapot.ts` (`buildManifest`, and wherever the manifest frame is sent)
|
||||
- Modify: `src/mesh/teacup.ts` (`buildRemote`)
|
||||
- Modify: `src/mesh/link.ts` (manifest handling and the refuse-policy comparison)
|
||||
- Test: `test/mesh/protocol.test.ts`, `test/mesh/teapot.test.ts`, `test/mesh/teacup.test.ts`
|
||||
|
||||
**Interfaces**
|
||||
- Produces: `interface Manifest { steps: string[]; routes: RouteEntry[] }`
|
||||
- Produces: `buildManifest(args: { steps: string[]; routes: RouteEntry[] }): Manifest`
|
||||
- Produces: `buildRemote(link: Link): { steps: RemoteScopeNode[]; routes: RemoteRoute[] }`
|
||||
- Gone: `ScopeEntry`, and the `scopes` field of the `manifest` frame
|
||||
|
||||
- [ ] **Step 1: Write the failing tests**
|
||||
|
||||
```ts
|
||||
// test/mesh/protocol.test.ts
|
||||
it('encodes a manifest of step names', () => {
|
||||
const frame = decode(encode({ type: 'manifest', v: 1, steps: ['auth'], routes: [] }));
|
||||
expect(frame).toEqual({ type: 'manifest', v: 1, steps: ['auth'], routes: [] });
|
||||
});
|
||||
|
||||
it('rejects a manifest whose steps are not an array', () => {
|
||||
expect(() => decode(JSON.stringify({ type: 'manifest', v: 1, steps: 'auth', routes: [] }))).toThrow(
|
||||
/steps and routes must be arrays/,
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// test/mesh/teapot.test.ts
|
||||
it('builds a manifest from step tokens and routes', () => {
|
||||
expect(buildManifest({ steps: ['auth'], routes: [{ method: 'GET', pattern: '/u/:id' }] })).toEqual({
|
||||
steps: ['auth'],
|
||||
routes: [{ method: 'GET', pattern: '/u/:id' }],
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// test/mesh/teacup.test.ts
|
||||
it('turns every manifest step into a lazy remote node', async () => {
|
||||
const link = { manifest: { steps: ['auth'], routes: [] }, rpc: async () => ({ ok: true }) } as any;
|
||||
const { steps, routes } = buildRemote(link);
|
||||
|
||||
expect(routes).toEqual([]);
|
||||
expect(steps.map((s: any) => s.name)).toEqual(['auth']);
|
||||
expect(await steps[0].run({})).toEqual({ auth: { ok: true } });
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run them and watch them fail**
|
||||
|
||||
```bash
|
||||
npx vitest run test/mesh/protocol.test.ts test/mesh/teapot.test.ts test/mesh/teacup.test.ts
|
||||
```
|
||||
|
||||
Expected: FAIL — `steps` is not a field, `buildManifest` still wants `providers`.
|
||||
|
||||
- [ ] **Step 3: Change the protocol**
|
||||
|
||||
In `src/mesh/protocol.ts`, delete `ScopeEntry` (`:45-49`) and replace the `Manifest` interface:
|
||||
|
||||
```ts
|
||||
/**
|
||||
* A mesh server's advertised steps and routes.
|
||||
*
|
||||
* Steps only: a provider's value is the object it builds, which cannot cross a JSON wire, so
|
||||
* exporting one is refused at boot (`collectProviders`). Every entry here is request-scope and
|
||||
* lazy — the token exists in the teacup's graph, and running it is an RPC.
|
||||
*/
|
||||
export interface Manifest {
|
||||
steps: string[];
|
||||
routes: RouteEntry[];
|
||||
}
|
||||
```
|
||||
|
||||
In the `Frame` union, replace the `manifest` member:
|
||||
|
||||
```ts
|
||||
| { type: 'manifest'; v: number; steps: string[]; routes: RouteEntry[] }
|
||||
```
|
||||
|
||||
And its `SHAPE` row:
|
||||
|
||||
```ts
|
||||
manifest: (frame, bad) => {
|
||||
if (!isNumber(frame.v)) bad('missing protocol version');
|
||||
if (!Array.isArray(frame.steps) || !Array.isArray(frame.routes)) bad('steps and routes must be arrays');
|
||||
},
|
||||
```
|
||||
|
||||
Leave `MESH_PROTOCOL_VERSION` at `1` (D2). Leave `untransportable` alone — a step result can still
|
||||
carry a `Date` or a `Map`.
|
||||
|
||||
- [ ] **Step 4: Change `buildManifest`**
|
||||
|
||||
In `src/mesh/teapot.ts`, replace the function at `:43-56`:
|
||||
|
||||
```ts
|
||||
/** Assemble a {@link Manifest} from exported step tokens and buffered routes. */
|
||||
export function buildManifest(args: { steps: string[]; routes: RouteEntry[] }): Manifest {
|
||||
return { steps: [...args.steps], routes: args.routes };
|
||||
}
|
||||
```
|
||||
|
||||
Then follow the type errors: wherever the teapot sends the `manifest` frame it now sends
|
||||
`steps: manifest.steps` in place of `scopes: manifest.scopes`.
|
||||
|
||||
The only other caller is `buildMeshControl` (`src/app/index.ts:1088`). Update it here, not in Task 3
|
||||
— a task must leave the tree typechecking, and splitting a signature from its only call site across
|
||||
two commits leaves a broken commit in history:
|
||||
|
||||
```ts
|
||||
const manifest = buildManifest({ steps: exportedSteps, routes: exportedRoutes });
|
||||
```
|
||||
|
||||
`exportedProviders` is still destructured on the line above; leave it, Task 3 removes the field.
|
||||
|
||||
- [ ] **Step 5: Change `buildRemote`**
|
||||
|
||||
In `src/mesh/teacup.ts`, replace the scope loop (`:44-54`):
|
||||
|
||||
```ts
|
||||
/** Turn a link's manifest into local proxy nodes: lazy request-scope steps, and routes. */
|
||||
export function buildRemote(link: Link): { steps: RemoteScopeNode[]; routes: RemoteRoute[] } {
|
||||
const steps: RemoteScopeNode[] = link.manifest.steps.map((token) => ({
|
||||
name: token,
|
||||
run: async (ctx: any) => ({ [token]: await link.rpc('scope', token, envelopeFrom(ctx)) }),
|
||||
}));
|
||||
|
||||
const routes: RemoteRoute[] = link.manifest.routes.map((route) => ({
|
||||
method: route.method,
|
||||
pattern: route.pattern,
|
||||
handler: async (req: RequestEnvelope) => (await link.rpc('route', route.pattern, req)) as ResponseShape,
|
||||
}));
|
||||
|
||||
return { steps, routes };
|
||||
}
|
||||
```
|
||||
|
||||
The RPC `kind` stays `'scope'` — renaming it to `'step'` is a wire change with no benefit, and
|
||||
`resolveScope` on the teapot side resolves both the same way.
|
||||
|
||||
- [ ] **Step 6: Update the refuse policy in `link.ts`**
|
||||
|
||||
Find the manifest comparison used by `onManifestChange: 'refuse'` and drop the lifetime half of it:
|
||||
a returned manifest must still contain every step token the link contributed at boot, and every
|
||||
route by method plus effective shape. There is no `scope` field left to compare (D6 of the reconnect
|
||||
plan).
|
||||
|
||||
- [ ] **Step 7: Typecheck, then run the mesh suite**
|
||||
|
||||
```bash
|
||||
npm run typecheck && npx vitest run test/mesh/
|
||||
```
|
||||
|
||||
Expected: PASS both. A typecheck failure here means a `manifest` frame send or the `buildMeshControl`
|
||||
call site was missed.
|
||||
|
||||
- [ ] **Step 8: Commit**
|
||||
|
||||
```bash
|
||||
git add src/mesh/ test/mesh/
|
||||
git commit -m "refactor(mesh)!: a manifest carries step names, not scoped tokens
|
||||
|
||||
Every exported token is request-scope now, so the lifetime field had one
|
||||
value and told a reader nothing. No protocol bump: mesh is alpha, both
|
||||
peers ship from this repo, and the number should mean incompatibility
|
||||
between deployed versions."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 3: The teacup stops splicing providers
|
||||
|
||||
**Files**
|
||||
- Modify: `src/app/index.ts:62,427` (`Registry.exportedProviders`)
|
||||
- Modify: `src/app/index.ts:808` (delete `invalidateRemoteBindings`)
|
||||
- Modify: `src/app/index.ts:813-856` (`spliceRemoteScopes`)
|
||||
- Modify: `src/app/index.ts:1078-1088` (`buildMeshControl`)
|
||||
- Test: `test/mesh/integration.test.ts`
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
This file's teapot fixture opens with `@Provider({ provides: 'config', export: true })`
|
||||
(`test/mesh/integration.test.ts:6`), and `LocalCtl` declares `@needs('config')`. Task 1 already made
|
||||
that fixture fail at boot, so converting it is not optional — and converting it is the regression
|
||||
guard, because a step re-runs where the provider was cached:
|
||||
|
||||
```ts
|
||||
// test/mesh/integration.test.ts — replaces the @Provider fixture at :6
|
||||
let configCalls = 0;
|
||||
@Step({ provides: 'config', needs: [], export: true })
|
||||
class Config {
|
||||
run() {
|
||||
configCalls += 1;
|
||||
return { config: { region: 'mx', call: configCalls } };
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
and add, alongside the existing `/local/who` assertion:
|
||||
|
||||
```ts
|
||||
it('re-runs the RPC on every request rather than caching a boot value', async () => {
|
||||
// same teapot/teacup pair the '/local/who' test stands up
|
||||
expect((await hit('/api/local/who')).config.call).toBe(1);
|
||||
expect((await hit('/api/local/who')).config.call).toBe(2);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run it — it should already pass, and that is the point**
|
||||
|
||||
```bash
|
||||
npx vitest run test/mesh/integration.test.ts -t 're-runs the RPC'
|
||||
```
|
||||
|
||||
Expected: PASS. This is a regression guard, not a red test. The caching bug was only reachable
|
||||
through provider export, which Task 1 made impossible — once `config` is a step it lands in the
|
||||
request-scope bucket and already re-runs. The guard exists so that removing the splice in the next
|
||||
steps cannot quietly reintroduce a cached remote value. Do not manufacture a red state for it.
|
||||
|
||||
- [ ] **Step 3: Delete `exportedProviders`**
|
||||
|
||||
Remove the field from the `Registry` interface (`:62`) and its initializer (`:427`). In
|
||||
`buildMeshControl` (`:1078-1088`):
|
||||
|
||||
```ts
|
||||
const { exportedSteps, exportedRoutes, routePlans, runners } = registry;
|
||||
const hasExports = exportedSteps.length || exportedRoutes.length;
|
||||
// ...
|
||||
const manifest = buildManifest({ steps: exportedSteps, routes: exportedRoutes });
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Delete the remote-provider splice**
|
||||
|
||||
In `spliceRemoteScopes`, delete the `rebind` array (`:829`), the `onReconnect` callback that calls
|
||||
`invalidateRemoteBindings` (`:838`), and the whole `for (const provider of providers)` block
|
||||
(`:846-856`). Destructure only what is left:
|
||||
|
||||
```ts
|
||||
const { steps, routes } = buildRemote(link);
|
||||
```
|
||||
|
||||
Then delete `invalidateRemoteBindings` (`:808-810`) and drop the now-unused `container` parameter
|
||||
from `spliceRemoteScopes` (`:818`) and its call site (`:242`) — `container` was used at `:854` and
|
||||
nowhere else in the function.
|
||||
|
||||
The reconnect handler no longer needs an `onReconnect`. A remote step holds no state between
|
||||
requests, so a reconnected link is simply usable again on the next RPC.
|
||||
|
||||
- [ ] **Step 5: Run the full suite and the typechecker**
|
||||
|
||||
```bash
|
||||
npm run typecheck && npx vitest run test/mesh/
|
||||
```
|
||||
|
||||
Expected: PASS, and no unused-symbol errors.
|
||||
|
||||
- [ ] **Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add src/app/index.ts test/mesh/
|
||||
git commit -m "refactor(mesh): drop the remote app-scope binding and its rebind seam
|
||||
|
||||
A remote provider was registered app-scope, resolved once, and cached for
|
||||
the process lifetime; invalidateRemoteBindings existed only to un-cache it
|
||||
on reconnect. With providers gone from the manifest, both go, and a remote
|
||||
step needs nothing on reconnect because it holds nothing between requests."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 4: An unreachable teapot does not stop the boot
|
||||
|
||||
**Files**
|
||||
- Modify: `src/app/index.ts:736-776` (`connectUntilDeadline`)
|
||||
- Modify: `src/app/index.ts:824-843` (the `try` in `spliceRemoteScopes`)
|
||||
- Modify: `src/graph.ts:54` (the missing-dependency message)
|
||||
- Test: `test/mesh/boot-retry.test.ts`
|
||||
|
||||
- [ ] **Step 1: Write the failing tests**
|
||||
|
||||
```ts
|
||||
// test/mesh/boot-retry.test.ts
|
||||
it('boots when a teapot is unreachable and nothing local needs it', async () => {
|
||||
const app = createApp({
|
||||
modules: [LocalOnlyModule], // declares no needs on a remote token
|
||||
mesh: { secret: 's', teapots: [{ url: 'ws://127.0.0.1:9/x', secret: 's' }], bootTimeoutMs: 300 },
|
||||
});
|
||||
|
||||
await expect(app.ready()).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('still fails the boot when a local step needs a token the absent teapot owned', async () => {
|
||||
const app = createApp({
|
||||
modules: [NeedsAuthModule], // a step with needs: ['auth']
|
||||
mesh: { secret: 's', teapots: [{ url: 'ws://127.0.0.1:9/x', secret: 's' }], bootTimeoutMs: 300 },
|
||||
});
|
||||
|
||||
await expect(app.ready()).rejects.toThrow(/missing dependency: auth[\s\S]*did not connect/i);
|
||||
});
|
||||
|
||||
it('still fails the boot when the teapot refuses the secret', async () => {
|
||||
// stand up a teapot with secret 'right', connect with 'wrong'
|
||||
await expect(app.ready()).rejects.toThrow(/refused/i);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run them and watch the first two fail**
|
||||
|
||||
```bash
|
||||
npx vitest run test/mesh/boot-retry.test.ts
|
||||
```
|
||||
|
||||
Expected: the first fails (boot throws on an unreachable teapot), the second fails on the message
|
||||
(it says `missing dependency: auth` with no mention of the teapot), the third passes already.
|
||||
|
||||
- [ ] **Step 3: Make budget exhaustion non-fatal**
|
||||
|
||||
In `connectUntilDeadline`, keep the loop, the backoff, the `mesh:boot:retry` event and the
|
||||
permanent-refusal `throw` (D4). Change the return type to `Promise<Link | undefined>` and replace
|
||||
the exhaustion branch:
|
||||
|
||||
```ts
|
||||
// The budget is a grace for a co-deploy, not a requirement. Every export is a lazy step or a
|
||||
// proxied route now, so an absent teapot costs a 503 on the requests that need it — and a
|
||||
// teacup that refuses to start takes down the half of itself that never needed the teapot.
|
||||
if (remaining <= 0) {
|
||||
logger.warn(
|
||||
`mesh: teapot unreachable after ${attempts} attempt(s) over ${budgetMs}ms ` +
|
||||
`(${(error as Error).message}) — starting without it; its steps and routes will 503`,
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
```
|
||||
|
||||
In `spliceRemoteScopes`, skip a link that came back `undefined`, and record its url:
|
||||
|
||||
```ts
|
||||
const link = await connectUntilDeadline(/* … */);
|
||||
if (!link) {
|
||||
absent.push(teapot.url);
|
||||
continue;
|
||||
}
|
||||
```
|
||||
|
||||
Return `absent` alongside `remoteRoutes` and `meshLinks`.
|
||||
|
||||
- [ ] **Step 4: Name the absent teapots in the missing-dependency error**
|
||||
|
||||
`topoSort` (`src/graph.ts:46`) is generic and must stay that way. Give it an optional trailing note
|
||||
instead of mesh knowledge — note the capital S, and that `seedKeys` stays second:
|
||||
|
||||
```ts
|
||||
// src/graph.ts:46
|
||||
export function topoSort(nodes: GraphNode[], seedKeys: string[], note?: (key: string) => string): GraphNode[] {
|
||||
```
|
||||
|
||||
and at the throw (`src/graph.ts:54`):
|
||||
|
||||
```ts
|
||||
throw new Error(`missing dependency: ${key} needed by ${node.name}${note?.(key) ?? ''}`);
|
||||
```
|
||||
|
||||
The only call site is `finalizeGraph` (`src/app/index.ts:660`), so thread the note through its
|
||||
signature rather than reaching for a module-level variable:
|
||||
|
||||
```ts
|
||||
// src/app/index.ts:654 — finalizeGraph gains a trailing optional param
|
||||
function finalizeGraph(
|
||||
registry: Registry,
|
||||
logger: Logger,
|
||||
warnDepth: number | false = DEEP_GRAPH_WARN,
|
||||
missingNote?: (key: string) => string,
|
||||
): { orderedProviders: GraphNode[]; orderedSteps: GraphNode[] } {
|
||||
const { providerNodes, stepNodes, routePlans } = registry;
|
||||
const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params'], missingNote);
|
||||
```
|
||||
|
||||
`finalize` in `createApp` is the closure that calls it; give it the note built from `absent`:
|
||||
|
||||
```ts
|
||||
// Without this the error is `missing dependency: auth needed by getUser` and says nothing about
|
||||
// the teapot that was away — which is the actual cause every time it is the cause.
|
||||
const meshNote = absent.length
|
||||
? () => ` — these teapots did not connect, so their exports are absent: ${absent.join(', ')}`
|
||||
: undefined;
|
||||
```
|
||||
|
||||
The note is unconditional on the key rather than per-token on purpose: the teacup does not know
|
||||
which teapot *would* have owned a token it never received a manifest for, and guessing would put a
|
||||
wrong url in an error. Listing the ones that were away is true and enough.
|
||||
|
||||
- [ ] **Step 5: Run them and watch them pass**
|
||||
|
||||
```bash
|
||||
npx vitest run test/mesh/boot-retry.test.ts
|
||||
```
|
||||
|
||||
Expected: PASS, all three.
|
||||
|
||||
- [ ] **Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add src/app/index.ts src/graph.ts test/mesh/boot-retry.test.ts
|
||||
git commit -m "feat(mesh): an unreachable teapot no longer stops the teacup from booting
|
||||
|
||||
Blocking existed for app-scope exports, which have to resolve at boot
|
||||
because there is no later. Steps and proxied routes are all later. The
|
||||
grace budget stays -- a co-deploy still waits -- but exhausting it now
|
||||
warns instead of throwing. A missing token still fails the boot, and the
|
||||
error now names the teapots that were away."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 5: The other runtimes
|
||||
|
||||
`npm test` does not cover Deno, Bun or the edge, and this change touches `src/mesh/` and
|
||||
`src/app/index.ts` — exactly the code AGENTS.md says to run them for.
|
||||
|
||||
**Files**
|
||||
- Modify: `test/deno/mesh.test.ts`, `test/deno/mesh-hardening.test.ts`, `test/deno/mesh-interop.test.ts`,
|
||||
`test/deno/mesh-reconnect.test.ts`, `test/bun/mesh.test.ts`, `test/bun/mesh-reconnect.test.ts`
|
||||
- Modify: `test/interop/_node-peer.ts`, `test/edge/_worker.mjs`
|
||||
|
||||
- [ ] **Step 1: Convert every exported provider in the runtime fixtures to a step**
|
||||
|
||||
```bash
|
||||
grep -rn "export: true" test/deno test/bun test/interop test/edge
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run each runtime suite**
|
||||
|
||||
```bash
|
||||
npm run test:deno
|
||||
npm run test:bun
|
||||
npm run test:edge
|
||||
```
|
||||
|
||||
Expected: PASS on all three. The interop peer and the worker both speak the new manifest, so a
|
||||
mismatch here means one side was missed.
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add test/
|
||||
git commit -m "test(mesh): steps-only exports across Deno, Bun and the edge"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 6: Say it in the docs
|
||||
|
||||
**Files**
|
||||
- Modify: `README.md` (mesh section)
|
||||
- Modify: `CHANGELOG.md` (`[Unreleased]`)
|
||||
- Modify: `docs/plans/2026-08-18-mesh-degrade-plan.md` (D6)
|
||||
|
||||
- [ ] **Step 1: README**
|
||||
|
||||
In the mesh section: only `@Step` and routes are exportable; `@Provider` with `export: true` fails
|
||||
at boot and why; an unreachable teapot no longer blocks the boot, and its steps and routes `503`;
|
||||
a missing token still fails the boot, and that is deliberate.
|
||||
|
||||
- [ ] **Step 2: CHANGELOG**
|
||||
|
||||
Under `[Unreleased]`, with no date and no version heading — the heading is written the day the tag
|
||||
ships, never earlier.
|
||||
|
||||
```markdown
|
||||
### Changed
|
||||
|
||||
- **Mesh (alpha): only steps and routes can be exported.** `@Provider({ export: true })` now fails
|
||||
at boot. A provider's value is the object it builds, which cannot cross a JSON wire; what did
|
||||
cross became an app-scope binding the teacup resolved once and cached for the life of the
|
||||
process. Export a `@Step` instead — it runs on the teapot per request and returns its result.
|
||||
- **Mesh (alpha): an unreachable teapot no longer stops a teacup from booting.** The
|
||||
`bootTimeoutMs` grace still waits for a co-deploy; exhausting it now warns and starts without
|
||||
that teapot, whose steps and routes answer `503`. A local step that *needs* an absent token still
|
||||
fails the boot, and the error names the teapots that did not connect.
|
||||
- **Mesh (alpha): the manifest carries step names.** The wire changed without a protocol bump,
|
||||
which alpha permits and a stable version would not.
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Note the broken seam in the degrade plan**
|
||||
|
||||
Add one line under its D6: `invalidateRemoteBindings` no longer exists — a degraded step swaps a
|
||||
runner, not a container binding.
|
||||
|
||||
- [ ] **Step 4: The full gate**
|
||||
|
||||
```bash
|
||||
npm run lint && npm run format:check && npm run typecheck && npm test && npm run complexity:check
|
||||
npm run test:deno && npm run test:bun && npm run test:edge
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add README.md CHANGELOG.md docs/plans/
|
||||
git commit -m "docs(mesh): steps and routes are what a teapot exports"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Size
|
||||
|
||||
Smaller than the reconnect work, and mostly subtraction: roughly 120 lines out, 20 in. No new
|
||||
subsystem, no new configuration, no background loop. The risk is not in the code but in the wire —
|
||||
both peers change at once, which alpha allows and which the runtime suites are there to prove.
|
||||
|
||||
## Branch
|
||||
|
||||
From `develop`, per AGENTS.md — `develop` and `main` refuse direct pushes.
|
||||
|
||||
```bash
|
||||
git fetch origin && git checkout -b feat/mesh-steps-only origin/develop
|
||||
```
|
||||
+14
-7
@@ -1,11 +1,18 @@
|
||||
````markdown
|
||||
# green-tea example
|
||||
# green-tea examples
|
||||
|
||||
Each file is a runnable app. Run one with `tsx`, which is already a dev dependency:
|
||||
|
||||
```bash
|
||||
npx ts-node example/server.ts # or: npm run build && node dist/example/server.js
|
||||
curl -H 'x-token: u1' http://localhost:3000/api/users/9
|
||||
npx tsx example/server.ts # the tour, below
|
||||
npx tsx example/crud.ts # a CRUD API over an in-memory store, on :3300
|
||||
npx tsx example/chat.ts # WebSocket rooms, on ws://localhost:4100/chat/:room?token=...
|
||||
npx tsx example/graphql.ts # GraphQL queries and subscriptions over SSE, on :4200/graphql
|
||||
```
|
||||
|
||||
Demonstrates: typed context contract, graph-derived order, `app.inspect()`,
|
||||
and a logger plugin that observes the bus without touching the chain.
|
||||
````
|
||||
`server.ts` demonstrates the typed context contract, graph-derived order, `app.inspect()`, a
|
||||
logger plugin that observes the bus without touching the chain, streams, and a mesh teapot and
|
||||
teacup. Try it with:
|
||||
|
||||
```bash
|
||||
curl -H 'x-token: u1' http://localhost:3000/api/users/9
|
||||
```
|
||||
@@ -122,6 +122,7 @@ if (require.main === module) {
|
||||
console.log('teapot on http://localhost:3002');
|
||||
const teacupApp = createApp({
|
||||
modules: [TeacupModule],
|
||||
experimental: true,
|
||||
mesh: { teapots: [{ url: `ws://127.0.0.1:3002${MESH_CONTROL_PATH}`, secret: 'demo-secret' }] },
|
||||
});
|
||||
teacupApp.listen(3003).then(() => console.log('teacup on http://localhost:3003'));
|
||||
|
||||
Generated
+821
-534
File diff suppressed because it is too large.
Load diff
+16
-8
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@green-tea/core",
|
||||
"version": "26.9.0-beta.2",
|
||||
"description": "A zen, opinionated, type-safe framework \u2014 your API is a graph, not a middleware chain.",
|
||||
"description": "A zen, opinionated, type-safe framework — your API is a graph, not a middleware chain.",
|
||||
"license": "MIT",
|
||||
"author": "green-tea contributors <projects@expressive-tea.io>",
|
||||
"repository": {
|
||||
@@ -26,7 +26,7 @@
|
||||
"node"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
"node": ">=22"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
@@ -86,11 +86,13 @@
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsup",
|
||||
"api": "node scripts/api-report.mjs",
|
||||
"api:check": "node scripts/api-report.mjs --check",
|
||||
"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:edge": "tsx test/edge/run.ts && tsx test/edge/compression.ts && npm run build && tsx test/edge/dist.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",
|
||||
@@ -103,6 +105,8 @@
|
||||
"complexity:cyclomatic": "cyclomatic-complexity \"src/**/*.ts\" -tw 15 -te 25",
|
||||
"bench": "tsx bench/run.ts",
|
||||
"bench:compare": "tsx bench/compare.ts",
|
||||
"bench:lookup": "tsx bench/lookup.ts",
|
||||
"parity:mutants": "tsx test/router-parity/mutants.ts",
|
||||
"prepublishOnly": "npm run lint && npm run complexity:check && npm run typecheck && npm test && npm run build",
|
||||
"prepare": "git config core.hooksPath .githooks || true"
|
||||
},
|
||||
@@ -128,10 +132,14 @@
|
||||
"uuid": "11.1.1"
|
||||
}
|
||||
},
|
||||
"undici": "7.29.0"
|
||||
"undici": "7.30.1",
|
||||
"sharp": "0.35.5",
|
||||
"fastify": "$fastify",
|
||||
"multer": "2.5.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.5",
|
||||
"@microsoft/api-extractor": "^7.59.4",
|
||||
"@nestjs/common": "^11.1.28",
|
||||
"@nestjs/core": "^11.1.28",
|
||||
"@nestjs/platform-express": "^11.1.28",
|
||||
@@ -140,15 +148,15 @@
|
||||
"@types/autocannon": "^7.12.7",
|
||||
"@types/busboy": "^1.5.4",
|
||||
"@types/express": "^5.0.6",
|
||||
"@types/node": "^18.19.0",
|
||||
"@types/node": "^22.20.5",
|
||||
"@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",
|
||||
"eslint": "^9.39.5",
|
||||
"express": "^5.2.1",
|
||||
"fastify": "^5.11.0",
|
||||
"fastify": "^5.12.5",
|
||||
"graphql": "^16.9.0",
|
||||
"miniflare": "^4.20260730.0",
|
||||
"prettier": "^3.9.6",
|
||||
@@ -158,7 +166,7 @@
|
||||
"typescript": "^5.5.0",
|
||||
"typescript-eslint": "^8.65.0",
|
||||
"vite": "^6.4.3",
|
||||
"vitest": "^3.2.7",
|
||||
"vitest": "^4.1.11",
|
||||
"ws": "^8.21.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
// API report per export-map entry (CARD-22, D20). Reads the `.d.ts` that `tsup` emits, so run
|
||||
// `npm run build` first. `npm run api:check` fails when a report in `api/` differs from what the
|
||||
// build declares; `npm run api` rewrites them. A deliberate API change is a regenerated report in
|
||||
// the same PR, which is what makes the change visible to a reviewer at all.
|
||||
import { Extractor, ExtractorConfig } from '@microsoft/api-extractor';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
const check = process.argv.includes('--check');
|
||||
const root = resolve(import.meta.dirname, '..');
|
||||
const entries = ['index', 'deno', 'bun', 'edge'];
|
||||
let failed = false;
|
||||
|
||||
// An adapter's signatures name root types (`App`, `Logger`, …) that its own entry does not
|
||||
// re-export. Those are nameable from `@green-tea/core`, so they pass; anything else still fails.
|
||||
const rootExports = new Set(
|
||||
[...readFileSync(resolve(root, 'dist/index.d.ts'), 'utf8').matchAll(/export \{([^}]*)\}/g)]
|
||||
.flatMap((m) => m[1].split(','))
|
||||
.map((name) => name.trim().replace(/^type /, '').split(' as ').pop()),
|
||||
);
|
||||
const exportedByRoot = (message) =>
|
||||
message.messageId === 'ae-forgotten-export' && rootExports.has(/The symbol "([^"]+)"/.exec(message.text)?.[1]);
|
||||
|
||||
for (const entry of entries) {
|
||||
const config = ExtractorConfig.prepare({
|
||||
configObject: {
|
||||
projectFolder: root,
|
||||
mainEntryPointFilePath: `<projectFolder>/dist/${entry}.d.ts`,
|
||||
compiler: { tsconfigFilePath: '<projectFolder>/tsconfig.json' },
|
||||
apiReport: {
|
||||
enabled: true,
|
||||
reportFileName: `${entry}.api.md`,
|
||||
reportFolder: '<projectFolder>/api/',
|
||||
reportTempFolder: '<projectFolder>/node_modules/.cache/api-extractor/',
|
||||
},
|
||||
docModel: { enabled: false },
|
||||
dtsRollup: { enabled: false },
|
||||
tsdocMetadata: { enabled: false },
|
||||
messages: {
|
||||
// The report records the surface; it is not a TSDoc linter. The one message that fails the
|
||||
// run is a public signature naming a type the entry does not export (D19).
|
||||
compilerMessageReporting: { default: { logLevel: 'warning' } },
|
||||
extractorMessageReporting: {
|
||||
default: { logLevel: 'none' },
|
||||
'ae-forgotten-export': { logLevel: 'error', addToApiReportFile: false },
|
||||
},
|
||||
tsdocMessageReporting: { default: { logLevel: 'none' } },
|
||||
},
|
||||
},
|
||||
configObjectFullPath: resolve(root, 'api-extractor.json'),
|
||||
packageJsonFullPath: resolve(root, 'package.json'),
|
||||
});
|
||||
|
||||
const result = Extractor.invoke(config, {
|
||||
localBuild: !check,
|
||||
messageCallback: (message) => {
|
||||
if (entry !== 'index' && exportedByRoot(message)) message.logLevel = 'none';
|
||||
},
|
||||
});
|
||||
if (!result.succeeded) {
|
||||
failed = true;
|
||||
console.error(
|
||||
check && result.apiReportChanged
|
||||
? `api/${entry}.api.md is out of date: run \`npm run build && npm run api\` and commit the report.`
|
||||
: `api report for ${entry} failed (${result.errorCount} error(s)).`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
process.exit(failed ? 1 : 0);
|
||||
+778
-150
File diff suppressed because it is too large.
Load diff
+29
-1
@@ -37,6 +37,15 @@ export interface Explain {
|
||||
/** A running application instance with lifecycle, introspection and graph-export methods. */
|
||||
export interface App {
|
||||
listen(port: number): Promise<http.Server>;
|
||||
/**
|
||||
* Drains in-flight work, closes the server and mesh links, then runs teardown, all within
|
||||
* `timeoutMs` (default `shutdownTimeoutMs`, else 10s).
|
||||
*
|
||||
* With `createApp({ health })` on, `/__ready__` answers `503 {"status":"draining"}` from the first
|
||||
* line of this call, and the listener stays open for `health.drainDelayMs` before draining starts.
|
||||
* That window is part of `timeoutMs`. On Deno and Bun the same happens in the `close()` that
|
||||
* `serveDeno()`/`serveBun()` return.
|
||||
*/
|
||||
close(options?: { timeoutMs?: number }): Promise<void>;
|
||||
/**
|
||||
* Wires `SIGINT`/`SIGTERM` to `closer` and returns a close that also unregisters them — or
|
||||
@@ -116,7 +125,12 @@ export interface RoutePlan {
|
||||
args: ArgSpec[];
|
||||
}
|
||||
|
||||
/** Mesh networking options: a secret to gate this node's exports and/or remote teapots to connect to. */
|
||||
/**
|
||||
* Mesh networking options: a secret to gate this node's exports and/or remote teapots to connect to.
|
||||
*
|
||||
* @experimental Part of the mesh, which needs `createApp({ experimental: true })`: outside the
|
||||
* API freeze, so it may change in a minor release.
|
||||
*/
|
||||
export interface MeshConfig {
|
||||
secret?: string;
|
||||
teapots?: Array<{ url: string; secret: string }>;
|
||||
@@ -135,6 +149,13 @@ export interface MeshConfig {
|
||||
* `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.
|
||||
*
|
||||
* It also decides what a dropped teapot's routes do (D15). While a link is reconnecting its routes
|
||||
* stay in the table and answer `503` with `retry-after`, and `Allow` keeps them. A link that gives
|
||||
* up for good — dropped with `reconnect: false`, or refused permanently (a wrong secret, a
|
||||
* protocol mismatch) while reconnecting — has its routes removed: they answer `404` and leave
|
||||
* `Allow`. Each change emits `mesh:routes` with `{ url, added, removed }`. A teapot that missed
|
||||
* `bootTimeoutMs` is retried in the background with this backoff, unless it is `false`.
|
||||
*/
|
||||
reconnect?: boolean | { initialDelayMs?: number; maxDelayMs?: number };
|
||||
/**
|
||||
@@ -145,6 +166,9 @@ export interface MeshConfig {
|
||||
* 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.
|
||||
*
|
||||
* Only steps count. Routes are not part of the graph, so a returning teapot's routes replace its
|
||||
* old ones: a route it added is served, one it dropped answers `404` (D15).
|
||||
*/
|
||||
onManifestChange?: 'refuse';
|
||||
/**
|
||||
@@ -161,6 +185,10 @@ export interface MeshConfig {
|
||||
* one of its tokens still fails the boot, naming it. A permanent refusal — a wrong secret, a
|
||||
* protocol mismatch — fails at once without spending the grace.
|
||||
*
|
||||
* After boot, such a teapot keeps being retried in the background with the `reconnect` backoff
|
||||
* (not with `reconnect: false`). When it connects, its routes are added to the table and served;
|
||||
* its steps are not, because the graph was validated at boot without them (D15).
|
||||
*
|
||||
* `0` means one attempt and no grace. That is the attempt count boot used to have, and nothing
|
||||
* more: exhausting it no longer fails the boot, so a single unreachable teapot still warns and
|
||||
* starts. To make a teapot's absence fatal, have something local `@needs` one of its tokens.
|
||||
|
||||
+64
-10
@@ -1,9 +1,18 @@
|
||||
import { channel } from './channel';
|
||||
import type { Channel } from './channel';
|
||||
import type { App } from './app/types';
|
||||
import type { WsSocket, WsRequest } from './http/ws-core';
|
||||
import { refuseTls } from './security';
|
||||
import {
|
||||
WS_MAX_MESSAGE_BYTES,
|
||||
DEFAULT_MAX_WS_MESSAGE_BYTES,
|
||||
WS_HIGH_WATER_MARK,
|
||||
type WsSocket,
|
||||
type WsRequest,
|
||||
} from './http/ws-core';
|
||||
import { beginDrain } from './http/health';
|
||||
import { decodeMessage, neutralSocket, toWsRequest, upgradeSafely } from './http/ws-adapter';
|
||||
import { closeWithDeadline } from './http/shutdown';
|
||||
import { setPeer } from './http/peer';
|
||||
|
||||
// Minimal ambient for the Bun globals we use — avoids a @types/bun devDep.
|
||||
// Mirrors the real Bun.serve / server.upgrade / ServerWebSocket signatures we call.
|
||||
@@ -13,14 +22,19 @@ interface BunServerWebSocket {
|
||||
send(data: string): number;
|
||||
close(code?: number, reason?: string): void;
|
||||
terminate?(): void;
|
||||
/** Bytes queued and not yet written; Bun's counterpart to `WebSocket.bufferedAmount`. */
|
||||
getBufferedAmount?(): number;
|
||||
}
|
||||
interface BunWebSocketHandler {
|
||||
maxPayloadLength?: number;
|
||||
open?(ws: BunServerWebSocket): void;
|
||||
message(ws: BunServerWebSocket, message: string | Uint8Array): void;
|
||||
close?(ws: BunServerWebSocket, code: number, reason: string): void;
|
||||
drain?(ws: BunServerWebSocket): void;
|
||||
error?(ws: BunServerWebSocket, error?: unknown): void;
|
||||
}
|
||||
interface BunServer {
|
||||
/** The part of the server `Bun.serve` returns that {@link BunServeResult} builds on. */
|
||||
export 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.
|
||||
@@ -41,20 +55,31 @@ export interface BunServeResult extends BunServer {
|
||||
*/
|
||||
close(options?: { timeoutMs?: number }): Promise<void>;
|
||||
}
|
||||
interface BunServeOptions {
|
||||
interface BunNativeServeOptions {
|
||||
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 };
|
||||
/** Options for {@link serveBun}; passed through to `Bun.serve`. */
|
||||
export interface BunServeOptions {
|
||||
port?: number;
|
||||
hostname?: string;
|
||||
}
|
||||
declare const Bun: { serve(options: BunNativeServeOptions): 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;
|
||||
/** `drained` callers waiting for Bun's `drain` callback or the close (#41). */
|
||||
drainWaiters: Array<() => void>;
|
||||
}
|
||||
|
||||
/** Wakes every `drained` caller; each rechecks the buffer and waits again if it is still over. */
|
||||
function releaseDrain(ws: BunServerWebSocket): void {
|
||||
(ws.data as BunConnData).drainWaiters.splice(0).forEach((resolve) => resolve());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -63,9 +88,17 @@ interface BunConnData {
|
||||
* 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;
|
||||
const { inbound, ac, drainWaiters } = ws.data as BunConnData;
|
||||
|
||||
return neutralSocket(ws, inbound, ac);
|
||||
// Bun has no `bufferedAmount` property, so the generic poll would never wait. It has better: a
|
||||
// `getBufferedAmount()` to read and a server-level `drain` callback to wait on, no timer needed.
|
||||
const drained = async (): Promise<void> => {
|
||||
while (!ac.signal.aborted && (ws.getBufferedAmount?.() ?? 0) > WS_HIGH_WATER_MARK) {
|
||||
await new Promise<void>((resolve) => drainWaiters.push(resolve));
|
||||
}
|
||||
};
|
||||
|
||||
return Object.assign(neutralSocket(ws, inbound, ac), { drained });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -77,7 +110,7 @@ function bunSocket(ws: BunServerWebSocket): WsSocket {
|
||||
*
|
||||
* **Boots before it binds**, which is why it is async — see the `await app.boot()` below.
|
||||
*/
|
||||
export async function serveBun(app: App, options?: BunServeShortOptions): Promise<BunServeResult> {
|
||||
export async function serveBun(app: App, options?: BunServeOptions): Promise<BunServeResult> {
|
||||
// The same gate `listen()` runs before it binds a socket, and for the same reason: resolve the
|
||||
// graph and run the provider factories here, so a missing key or an unreachable pool is a startup
|
||||
// failure rather than a 500 on every request.
|
||||
@@ -86,6 +119,7 @@ export async function serveBun(app: App, options?: BunServeShortOptions): Promis
|
||||
// the first request would fix the failure in place and the runtime would answer from it forever,
|
||||
// without ever reaching `onError`. This was documented as something the caller should remember to
|
||||
// do, which made the correct use of a core helper depend on reading a README.
|
||||
refuseTls(app, 'serveBun');
|
||||
await app.boot();
|
||||
|
||||
const server = Bun.serve({
|
||||
@@ -95,14 +129,25 @@ export async function serveBun(app: App, options?: BunServeShortOptions): Promis
|
||||
const inbound = channel();
|
||||
const ac = new AbortController();
|
||||
const wsReq = toWsRequest(request, server.requestIP(request)?.address ?? '');
|
||||
const data: BunConnData = { wsReq, inbound, ac };
|
||||
const data: BunConnData = { wsReq, inbound, ac, drainWaiters: [] };
|
||||
if (server.upgrade(request, { data })) return undefined;
|
||||
return new Response('WebSocket upgrade failed', { status: 400 });
|
||||
}
|
||||
|
||||
// The same object goes to `app.fetch`, which is what lets it find the peer again. The server,
|
||||
// not its answer: `requestIP` runs only if something reads `ctx.ip` (see `peer.ts`).
|
||||
setPeer(request, server);
|
||||
return app.fetch(request);
|
||||
},
|
||||
websocket: {
|
||||
// The pre-buffer half of `limits.maxWsMessageBytes`: Bun refuses an oversized frame before
|
||||
// assembling it. Up to Bun 1.3 it dropped the connection without a close frame, so the peer
|
||||
// saw 1006 rather than 1009 — the price of not buffering the message at all. Bun 1.4 sends 1009.
|
||||
// `app.upgrade` checks the same bound again on the decoded text.
|
||||
// On a teapot the value is the mesh control channel's larger bound (#120), and `app.upgrade`
|
||||
// alone holds user routes to `maxWsMessageBytes`, closing 1009 on every Bun version.
|
||||
maxPayloadLength:
|
||||
(app as { [WS_MAX_MESSAGE_BYTES]?: number })[WS_MAX_MESSAGE_BYTES] ?? DEFAULT_MAX_WS_MESSAGE_BYTES,
|
||||
open(ws) {
|
||||
const { wsReq } = ws.data as BunConnData;
|
||||
|
||||
@@ -113,15 +158,20 @@ export async function serveBun(app: App, options?: BunServeShortOptions): Promis
|
||||
|
||||
inbound.push(decodeMessage(message));
|
||||
},
|
||||
drain(ws) {
|
||||
releaseDrain(ws);
|
||||
},
|
||||
close(ws) {
|
||||
const { inbound, ac } = ws.data as BunConnData;
|
||||
inbound.close();
|
||||
ac.abort();
|
||||
releaseDrain(ws);
|
||||
},
|
||||
error(ws) {
|
||||
const { inbound, ac } = ws.data as BunConnData;
|
||||
inbound.fail(new Error('websocket error'));
|
||||
ac.abort();
|
||||
releaseDrain(ws);
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -139,7 +189,11 @@ export async function serveBun(app: App, options?: BunServeShortOptions): Promis
|
||||
// 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()),
|
||||
// The drain window first: `/__ready__` answers 503 while the listener is still open (D14).
|
||||
() =>
|
||||
beginDrain(app)
|
||||
.then(() => server.stop(false))
|
||||
.then(() => app.close()),
|
||||
() => void server.stop(true),
|
||||
closeOptions.timeoutMs ?? 10_000,
|
||||
(ms) =>
|
||||
|
||||
@@ -45,6 +45,9 @@ export type LifecycleEvent =
|
||||
// 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'
|
||||
// A teacup's remote routes changed after boot (D15): a late teapot connected, a returning one
|
||||
// exported a different set, or a link gave up for good. Carries `url`, `added` and `removed`.
|
||||
| 'mesh:routes'
|
||||
| 'plugin:mounted'
|
||||
// Paired: see the guarantee above. `request:start` has no status and no duration — it says a
|
||||
// request arrived, not that it routed.
|
||||
@@ -125,6 +128,12 @@ export interface EventPayload {
|
||||
* framework does not know what was sent, and will not guess.
|
||||
*/
|
||||
status?: number;
|
||||
/** `mesh:routes`: the teapot whose routes changed. */
|
||||
url?: string;
|
||||
/** `mesh:routes`: routes added to the remote table, as `'METHOD /pattern'`. */
|
||||
added?: string[];
|
||||
/** `mesh:routes`: routes removed from the remote table, as `'METHOD /pattern'`. */
|
||||
removed?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+48
-2
@@ -14,6 +14,40 @@ export function isAsyncIterable(x: unknown): x is AsyncIterable<unknown> {
|
||||
return x != null && typeof (x as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === 'function';
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal: tells a source its consumer has gone, without waiting for it to finish. An async
|
||||
* generator runs `return()` only once its pending `next()` settles, which for an idle source may be
|
||||
* never, and a `return()` may also throw or reject. None of that may hold up or break the cleanup
|
||||
* that calls this (GitHub #40). Not exported from the package.
|
||||
*/
|
||||
export function releaseIterator(iterator: AsyncIterator<unknown> | undefined): void {
|
||||
try {
|
||||
void Promise.resolve(iterator?.return?.()).catch(() => {});
|
||||
} catch {
|
||||
/* a return() that throws synchronously */
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal: reads a channel synchronously, inside `push`, rather than through an async iterator
|
||||
* that only drains once the event loop yields. `boundInbound` needs it to bound a WebSocket burst
|
||||
* frame by frame, before anything is queued (#107). Not exported from the package; `Symbol.for`
|
||||
* because each tsup entry carries its own copy of this module.
|
||||
*/
|
||||
export const CHANNEL_TAP: unique symbol = Symbol.for('green-tea.channel-tap');
|
||||
|
||||
/** What {@link CHANNEL_TAP} calls, synchronously, for every push, close and fail. */
|
||||
export interface ChannelSink<T> {
|
||||
push(value: T): void;
|
||||
end(): void;
|
||||
fail(err: unknown): void;
|
||||
}
|
||||
|
||||
/** A channel that can be tapped; every channel built by {@link channel} is one. */
|
||||
export interface TappableChannel<T> extends Channel<T> {
|
||||
[CHANNEL_TAP](sink: ChannelSink<T>): () => void;
|
||||
}
|
||||
|
||||
interface Sub<T> {
|
||||
iterator: AsyncIterator<T>;
|
||||
push(value: T, cap: number): void;
|
||||
@@ -86,11 +120,13 @@ function newSub<T>(onReturn: () => void): Sub<T> {
|
||||
*/
|
||||
export function channel<T>(opts: { buffer?: number } = {}): Channel<T> {
|
||||
const cap = opts.buffer ?? Infinity;
|
||||
const subs = new Set<Sub<T>>();
|
||||
const subs = new Set<Omit<Sub<T>, 'iterator'>>();
|
||||
let done = false;
|
||||
let closedFlag = false;
|
||||
|
||||
return {
|
||||
// Public type stays `Channel<T>` (as in beta.2): the tap is internal plumbing, found by `ws-core`
|
||||
// through the symbol rather than through this signature.
|
||||
const ch: TappableChannel<T> = {
|
||||
get closed() {
|
||||
return closedFlag;
|
||||
},
|
||||
@@ -117,5 +153,15 @@ export function channel<T>(opts: { buffer?: number } = {}): Channel<T> {
|
||||
subs.add(sub);
|
||||
return sub.iterator;
|
||||
},
|
||||
[CHANNEL_TAP](sink) {
|
||||
if (done) {
|
||||
sink.end();
|
||||
return () => {};
|
||||
}
|
||||
|
||||
subs.add(sink);
|
||||
return () => subs.delete(sink);
|
||||
},
|
||||
};
|
||||
return ch;
|
||||
}
|
||||
+14
-10
@@ -6,8 +6,8 @@ export type Factory = (ctx: Record<string, unknown>) => unknown | Promise<unknow
|
||||
interface Binding {
|
||||
scope: Scope;
|
||||
factory: Factory;
|
||||
cached?: unknown;
|
||||
resolved?: boolean;
|
||||
/** The app-scoped value, cached as a promise from the moment the factory starts. */
|
||||
cached?: Promise<unknown>;
|
||||
}
|
||||
|
||||
/** Minimal token-keyed dependency container with app-scoped memoization and async, mesh-ready resolution. */
|
||||
@@ -30,14 +30,18 @@ export class Container {
|
||||
async resolve(token: string, ctx: Record<string, unknown> = {}): Promise<unknown> {
|
||||
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 === 'request') return binding.factory(ctx);
|
||||
if (binding.cached) return binding.cached;
|
||||
|
||||
if (binding.scope === 'app') {
|
||||
binding.cached = value;
|
||||
binding.resolved = true;
|
||||
}
|
||||
|
||||
return value;
|
||||
// The pending promise is cached, not the settled value (GitHub #46): a resolve that starts
|
||||
// while the factory is still running must wait for it, or it runs the factory a second time.
|
||||
// A rejection is not kept — it clears the cache, so the next resolve retries, as it did when
|
||||
// only successes were cached. The async wrapper turns a synchronous throw into that rejection.
|
||||
const pending = (async () => binding.factory(ctx))();
|
||||
binding.cached = pending;
|
||||
pending.catch(() => {
|
||||
if (binding.cached === pending) binding.cached = undefined;
|
||||
});
|
||||
return pending;
|
||||
}
|
||||
}
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
// src/cookies.ts — request cookie parsing and `Set-Cookie` serialisation (RFC 6265), dependency-free.
|
||||
|
||||
/**
|
||||
* Options for {@link setCookie}. Every attribute is optional; the defaults are the safe ones
|
||||
* (`httpOnly: true`, `sameSite: 'lax'`, `path: '/'`, `secure: true`).
|
||||
*/
|
||||
export interface CookieOptions {
|
||||
/** `Max-Age` in seconds. An integer; `0` or a negative value tells the browser to drop the cookie. */
|
||||
maxAge?: number;
|
||||
/** `Expires`, written as an HTTP date. `maxAge` wins in browsers when both are set. */
|
||||
expires?: Date;
|
||||
/** `Path`. Default `'/'`. */
|
||||
path?: string;
|
||||
/** `Domain`. Omitted by default, which scopes the cookie to the exact host that set it. */
|
||||
domain?: string;
|
||||
/**
|
||||
* `Secure`. Default `true`: Chrome, Edge and Firefox accept a `Secure` cookie on
|
||||
* `http://localhost`. Safari, a LAN IP or a plain-HTTP dev hostname do not — pass `false` there
|
||||
* (for example `secure: !isDev`).
|
||||
*/
|
||||
secure?: boolean;
|
||||
/** `HttpOnly`. Default `true`, so page scripts cannot read the cookie. */
|
||||
httpOnly?: boolean;
|
||||
/** `SameSite`. Default `'lax'`. `'none'` requires `secure`. */
|
||||
sameSite?: 'strict' | 'lax' | 'none';
|
||||
/** `Partitioned` (CHIPS). Requires `secure`. */
|
||||
partitioned?: boolean;
|
||||
}
|
||||
|
||||
/** RFC 6265 §4.1.1 cookie-name: an RFC 7230 token. */
|
||||
const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
||||
/** What a cookie value may not contain: CR, LF, `;`, `,`, whitespace and every control character. */
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const BAD_VALUE = /[\u0000- ;,\u007f]/;
|
||||
/**
|
||||
* What an attribute value may not contain. CR/LF is the header-injection case the card names; `;`
|
||||
* and the other control characters are refused too, because a `;` inside `Path` would start a new
|
||||
* attribute and change what the cookie means without breaking the header.
|
||||
*/
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const BAD_ATTRIBUTE = /[\u0000-\u001f;\u007f]/;
|
||||
|
||||
const SAME_SITE = { strict: 'Strict', lax: 'Lax', none: 'None' } as const;
|
||||
|
||||
/**
|
||||
* Serialises one `Set-Cookie` header value.
|
||||
*
|
||||
* Throws, naming the field, rather than producing a header that would split or reshape the
|
||||
* response: a name outside the RFC 6265 token set, a value carrying CR, LF, `;`, `,`, whitespace or a
|
||||
* control character, an attribute carrying CR/LF, `;` or a control character, a non-integer
|
||||
* `maxAge`, an invalid `expires`, and `sameSite: 'none'` or `partitioned` without `secure`.
|
||||
*
|
||||
* The value is written as given. Encode it yourself (`encodeURIComponent`) if it can hold any of the
|
||||
* refused characters; the cookie decorators decode `%`-sequences on the way back in.
|
||||
*
|
||||
* Several cookies on one response go in an array: `headers: { 'set-cookie': [a, b] }`, and each
|
||||
* element is sent as its own `Set-Cookie` line on every adapter.
|
||||
*
|
||||
* @example
|
||||
* setCookie('session', id, { maxAge: 3600 })
|
||||
* // 'session=<id>; Max-Age=3600; Path=/; Secure; HttpOnly; SameSite=Lax'
|
||||
*/
|
||||
export function setCookie(name: string, value: string, options: CookieOptions = {}): string {
|
||||
if (typeof name !== 'string' || !TOKEN.test(name))
|
||||
throw new TypeError(`setCookie: name ${JSON.stringify(name)} is not a valid cookie name (RFC 6265 token)`);
|
||||
|
||||
if (typeof value !== 'string' || BAD_VALUE.test(value))
|
||||
throw new TypeError(
|
||||
`setCookie: value for '${name}' contains a character a cookie value cannot carry (CR, LF, ';', ',', whitespace or a control character)`,
|
||||
);
|
||||
|
||||
const secure = options.secure ?? true;
|
||||
const sameSite = options.sameSite ?? 'lax';
|
||||
const parts = [`${name}=${value}`];
|
||||
|
||||
if (options.maxAge !== undefined) {
|
||||
if (!Number.isInteger(options.maxAge)) throw new TypeError(`setCookie: maxAge for '${name}' must be an integer`);
|
||||
parts.push(`Max-Age=${options.maxAge}`);
|
||||
}
|
||||
|
||||
if (options.expires !== undefined) {
|
||||
if (!(options.expires instanceof Date) || Number.isNaN(options.expires.getTime()))
|
||||
throw new TypeError(`setCookie: expires for '${name}' must be a valid Date`);
|
||||
parts.push(`Expires=${options.expires.toUTCString()}`);
|
||||
}
|
||||
|
||||
if (options.domain !== undefined) parts.push(`Domain=${attribute(name, 'domain', options.domain)}`);
|
||||
parts.push(`Path=${attribute(name, 'path', options.path ?? '/')}`);
|
||||
if (secure) parts.push('Secure');
|
||||
if (options.httpOnly ?? true) parts.push('HttpOnly');
|
||||
|
||||
if (!Object.prototype.hasOwnProperty.call(SAME_SITE, sameSite))
|
||||
throw new TypeError(`setCookie: sameSite for '${name}' must be 'strict', 'lax' or 'none'`);
|
||||
|
||||
if (sameSite === 'none' && !secure)
|
||||
throw new TypeError(`setCookie: sameSite 'none' for '${name}' requires secure (browsers reject it otherwise)`);
|
||||
parts.push(`SameSite=${SAME_SITE[sameSite]}`);
|
||||
|
||||
if (options.partitioned) {
|
||||
if (!secure) throw new TypeError(`setCookie: partitioned for '${name}' requires secure`);
|
||||
parts.push('Partitioned');
|
||||
}
|
||||
|
||||
return parts.join('; ');
|
||||
}
|
||||
|
||||
function attribute(name: string, field: string, value: string): string {
|
||||
if (typeof value !== 'string' || value === '' || BAD_ATTRIBUTE.test(value))
|
||||
throw new TypeError(
|
||||
`setCookie: ${field} for '${name}' must be a non-empty string without CR, LF, ';' or control characters`,
|
||||
);
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a request `Cookie` header into a name → value map (RFC 6265 §5.2 / §4.2).
|
||||
*
|
||||
* - The first value wins for a repeated name — the browser sends the most specific cookie first.
|
||||
* - `%`-sequences are decoded; a value that fails to decode is kept raw rather than rejected.
|
||||
* - A malformed pair (no `=`, or an empty name) is skipped. A broken cookie never becomes a 400:
|
||||
* the header is client state the server did not choose and the request may not even need it.
|
||||
* - Several `cookie` lines (HTTP/2, some proxies) arrive as an array and are joined with `; `.
|
||||
*
|
||||
* The map has no prototype, so a cookie named `__proto__` or `constructor` is just a key.
|
||||
*/
|
||||
export function parseCookies(header: string | string[] | undefined): Record<string, string> {
|
||||
const out: Record<string, string> = Object.create(null);
|
||||
if (header === undefined) return out;
|
||||
const raw = Array.isArray(header) ? header.join('; ') : header;
|
||||
|
||||
for (const pair of raw.split(';')) {
|
||||
const eq = pair.indexOf('=');
|
||||
if (eq === -1) continue;
|
||||
const key = pair.slice(0, eq).trim();
|
||||
if (key === '' || key in out) continue;
|
||||
out[key] = decode(pair.slice(eq + 1).trim());
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
function decode(value: string): string {
|
||||
if (!value.includes('%')) return value;
|
||||
|
||||
try {
|
||||
return decodeURIComponent(value);
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
+18
-5
@@ -1,16 +1,20 @@
|
||||
import type { App } from './app/types';
|
||||
import { refuseTls } from './security';
|
||||
import { beginDrain } from './http/health';
|
||||
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
|
||||
import { closeWithDeadline } from './http/shutdown';
|
||||
import { setPeer } from './http/peer';
|
||||
|
||||
// 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.
|
||||
// The project tsconfig's `lib` doesn't include `DOM`, so we ambient-declare just the shape of
|
||||
// Deno's `WebSocket` we use rather than rely on whichever global `@types/node` happens to declare.
|
||||
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 {
|
||||
/** Options for {@link serveDeno}; passed through to `Deno.serve`. */
|
||||
export interface DenoServeOptions {
|
||||
port?: number;
|
||||
hostname?: string;
|
||||
signal?: AbortSignal;
|
||||
@@ -19,7 +23,8 @@ interface DenoServeOptions {
|
||||
interface DenoServeHandlerInfo {
|
||||
remoteAddr: { hostname: string; port: number; transport: string };
|
||||
}
|
||||
interface DenoHttpServer {
|
||||
/** The part of the server `Deno.serve` returns that {@link DenoServer} builds on. */
|
||||
export interface DenoHttpServer {
|
||||
finished: Promise<void>;
|
||||
shutdown(): Promise<void>;
|
||||
}
|
||||
@@ -63,6 +68,7 @@ export async function serveDeno(app: App, options?: DenoServeOptions): Promise<D
|
||||
// the first request would fix the failure in place and the runtime would answer from it forever,
|
||||
// without ever reaching `onError`. This was documented as something the caller should remember to
|
||||
// do, which made the correct use of a core helper depend on reading a README.
|
||||
refuseTls(app, 'serveDeno');
|
||||
await app.boot();
|
||||
|
||||
// Deno's only force-close lever is the abort signal it was served with, so the adapter has to
|
||||
@@ -82,6 +88,9 @@ export async function serveDeno(app: App, options?: DenoServeOptions): Promise<D
|
||||
return response;
|
||||
}
|
||||
|
||||
// The same object goes to `app.fetch`, which is what lets it find the peer again. A unix socket
|
||||
// has no `hostname`, and records nothing.
|
||||
setPeer(request, info.remoteAddr.hostname);
|
||||
return app.fetch(request);
|
||||
});
|
||||
|
||||
@@ -98,7 +107,11 @@ export async function serveDeno(app: App, options?: DenoServeOptions): Promise<D
|
||||
// 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()),
|
||||
// The drain window first: `/__ready__` answers 503 while the listener is still open (D14).
|
||||
() =>
|
||||
beginDrain(app)
|
||||
.then(() => 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
|
||||
|
||||
+24
-2
@@ -1,12 +1,15 @@
|
||||
import type { App } from './app/types';
|
||||
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
|
||||
import { setProxyClient } from './http/peer';
|
||||
import { MARK_EDGE } from './http/compression';
|
||||
|
||||
// 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 {
|
||||
/** The Workers execution context {@link edgeHandler} receives as its third argument. */
|
||||
export interface EdgeCtx {
|
||||
waitUntil(promise: Promise<unknown>): void;
|
||||
}
|
||||
declare const WebSocketPair: { new (): { 0: EdgeWebSocket; 1: EdgeWebSocket } };
|
||||
@@ -22,15 +25,22 @@ declare const WebSocketPair: { new (): { 0: EdgeWebSocket; 1: EdgeWebSocket } };
|
||||
* 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.
|
||||
*
|
||||
* **`compression` never encodes here.** Cloudflare compresses in front of the Worker, so core sets
|
||||
* only `Vary: Accept-Encoding`; wrapping the app in `edgeHandler` marks it as edge explicitly.
|
||||
*/
|
||||
export function edgeHandler(
|
||||
app: App,
|
||||
): (request: Request, env?: unknown, ctx?: EdgeCtx) => Response | Promise<Response> {
|
||||
(app as { [MARK_EDGE]?: () => void })[MARK_EDGE]?.();
|
||||
|
||||
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') ?? '');
|
||||
// No peer address on the edge, so `ip` starts empty; the header only fills it under `trustProxy`.
|
||||
const wsReq = toWsRequest(request, '');
|
||||
recordClient(wsReq, request);
|
||||
const lifecycle = upgradeSafely(app, wsReq, eventSocket(server));
|
||||
if (ctx?.waitUntil) ctx.waitUntil(lifecycle);
|
||||
else void lifecycle;
|
||||
@@ -38,6 +48,18 @@ export function edgeHandler(
|
||||
return new Response(null, { status: 101, webSocket: client } as ResponseInit & { webSocket: EdgeWebSocket });
|
||||
}
|
||||
|
||||
recordClient(request, request);
|
||||
return app.fetch(request);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Hands the app the `cf-connecting-ip` header for `source`, the object the app will be given for this
|
||||
* request. The app — not this adapter — decides whether it counts, since `trustProxy` is an app
|
||||
* option; HTTP and WebSocket both go through here and through the same check on the app side.
|
||||
* Without `trustProxy` the header is ignored and `ctx.ip` stays `''`: workerd exposes no peer address,
|
||||
* and an untrusted header is whatever the client chose to send.
|
||||
*/
|
||||
function recordClient(source: object, request: Request): void {
|
||||
setProxyClient(source, request.headers.get('cf-connecting-ip') ?? '');
|
||||
}
|
||||
+50
-5
@@ -42,16 +42,61 @@ 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[], note = ''): GraphNode[] {
|
||||
/**
|
||||
* Maps every token to the one node that produces it; throws when a second node provides a token.
|
||||
*
|
||||
* One producer per token, across modules, plugins, mesh steps and built-ins alike (GitHub #35, D9).
|
||||
* This used to be `producedBy.set(key, node)`, last one wins: plugin nodes are registered after
|
||||
* module nodes, so a plugin's `scope.add` that provided `user` silently replaced the app's own `user`
|
||||
* for every route that needed it. Checking here, on the whole graph, rather than at each place a node
|
||||
* is registered, is what covers every path — current and future — and makes the built-in tokens
|
||||
* (`logger`, `rooms`, `events`) safe by rule instead of by registration order.
|
||||
*/
|
||||
function producers(nodes: GraphNode[]): Map<string, GraphNode> {
|
||||
const producedBy = new Map<string, GraphNode>();
|
||||
for (const node of nodes) for (const key of node.provides) producedBy.set(key, node);
|
||||
|
||||
for (const node of nodes) {
|
||||
for (const key of node.provides) {
|
||||
const prior = producedBy.get(key);
|
||||
|
||||
if (prior && prior !== node) {
|
||||
throw new Error(
|
||||
`token '${key}' is provided twice: by '${prior.name}' (${prior.origin}) and by '${node.name}' (${node.origin}) — ` +
|
||||
'a token has exactly one producer; rename one of them, or use `overrides` to replace a runner',
|
||||
);
|
||||
}
|
||||
|
||||
producedBy.set(key, node);
|
||||
}
|
||||
}
|
||||
|
||||
return producedBy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Orders nodes so every dependency precedes its dependents; throws on a token with two producers,
|
||||
* missing keys or cycles.
|
||||
*/
|
||||
export function topoSort(nodes: GraphNode[], seedKeys: string[], note = ''): GraphNode[] {
|
||||
const producedBy = producers(nodes);
|
||||
|
||||
// validate dependencies exist
|
||||
for (const node of nodes) {
|
||||
for (const key of node.needs) {
|
||||
if (!seedKeys.includes(key) && !producedBy.has(key)) {
|
||||
throw new Error(`missing dependency: ${key} needed by ${node.name}${note}`);
|
||||
if (seedKeys.includes(key)) continue;
|
||||
const producer = producedBy.get(key);
|
||||
|
||||
if (!producer) throw new Error(`missing dependency: ${key} needed by ${node.name}${note}`);
|
||||
|
||||
// A node that needs its own token is a cycle of one (GitHub #43): it would read a value nobody
|
||||
// wrote yet. `producers` already allows one producer per token, so no other node can supply
|
||||
// it; only a seed makes the need real, and the seed case continued above. Same wording as the
|
||||
// cycle check below, so both read as the one error they are.
|
||||
if (producer === node) {
|
||||
throw new Error(
|
||||
`cycle detected: ${node.name} -> ${node.name} (it needs '${key}', which only it provides)${note}. ` +
|
||||
`Remove '${key}' from its needs, or move the work that produces '${key}' into a step it needs.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+44
-15
@@ -8,7 +8,7 @@ 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 };
|
||||
fail: { status: number; headers: Record<string, string | string[]>; body: string };
|
||||
}
|
||||
|
||||
/** A value, or a promise of one. Readers that have nothing to await return the value directly. */
|
||||
@@ -22,12 +22,11 @@ function isPromise<T>(value: MaybePromise<T>): value is Promise<T> {
|
||||
/**
|
||||
* 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 adapter owns this and nothing else about the body, because getting the bytes is the one place
|
||||
* the runtimes legitimately differ: Node iterates the socket, a fetch runtime reads `request.body`.
|
||||
* Both check the running total as chunks arrive and abort a 10 GB upload after 1 MB. Passing the
|
||||
* limit *in*, rather than measuring the returned buffer here, is what makes that incremental abort
|
||||
* possible — measuring afterwards would force the reader 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.
|
||||
@@ -41,6 +40,27 @@ function isPromise<T>(value: MaybePromise<T>): value is Promise<T> {
|
||||
*/
|
||||
export type BodyReader = (source: unknown, limit: number) => MaybePromise<{ bytes: Buffer | undefined } | BodyFailure>;
|
||||
|
||||
/**
|
||||
* True when a `content-length` header declares more than `limit` bytes — the one case a reader can
|
||||
* refuse before consuming anything. A malformed or absent header answers false: it proves nothing,
|
||||
* and the running total still enforces the limit on whatever actually arrives.
|
||||
*/
|
||||
export function declaresOverLimit(contentLength: string | null | undefined, limit: number): boolean {
|
||||
// The numeric test first: nearly every request is under the limit, so the shape check below runs
|
||||
// only for the rare one that would be refused.
|
||||
return contentLength != null && Number(contentLength) > limit && /^\d+$/.test(contentLength);
|
||||
}
|
||||
|
||||
/**
|
||||
* The media type of a Content-Type value: the part before any parameters, trimmed and lowercased,
|
||||
* since media types are case-insensitive (RFC 9110 §8.3.1). Matching a substring of the raw header
|
||||
* instead let a parameter choose the parser: `text/plain; x=application/json` was parsed as JSON.
|
||||
*/
|
||||
function mediaType(contentType: string): string {
|
||||
const semi = contentType.indexOf(';');
|
||||
return (semi === -1 ? contentType : contentType.slice(0, semi)).trim().toLowerCase();
|
||||
}
|
||||
|
||||
/** 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 };
|
||||
|
||||
@@ -53,8 +73,13 @@ export async function parseRequestBody(
|
||||
contentType: string,
|
||||
duplicates: 'array' | 'last',
|
||||
maxParts: number,
|
||||
maxFieldBytes?: number,
|
||||
): Promise<ParseResult> {
|
||||
if (buf !== undefined && contentType.includes('application/json')) {
|
||||
const type = mediaType(contentType);
|
||||
|
||||
// `+json` is the structured-syntax suffix for JSON (RFC 6839): `application/problem+json`,
|
||||
// `application/vnd.api+json` and `application/json-patch+json` are JSON documents too.
|
||||
if (buf !== undefined && (type === 'application/json' || type.endsWith('+json'))) {
|
||||
try {
|
||||
return { body: JSON.parse(buf.toString('utf8')) };
|
||||
} catch {
|
||||
@@ -62,18 +87,19 @@ export async function parseRequestBody(
|
||||
}
|
||||
}
|
||||
|
||||
if (buf !== undefined && contentType.includes('application/x-www-form-urlencoded')) {
|
||||
if (buf !== undefined && type === 'application/x-www-form-urlencoded') {
|
||||
return { body: collapseDuplicates(new URLSearchParams(buf.toString('utf8')), duplicates) };
|
||||
}
|
||||
|
||||
if (buf !== undefined && contentType.includes('multipart/form-data')) {
|
||||
if (buf !== undefined && type === 'multipart/form-data') {
|
||||
const boundary = extractBoundary(contentType);
|
||||
if (!boundary) return { error: 'Invalid multipart body' };
|
||||
|
||||
try {
|
||||
return { body: await parseMultipart(buf, boundary, { maxParts, duplicates }) };
|
||||
return { body: await parseMultipart(buf, boundary, { maxParts, duplicates, maxFieldBytes }) };
|
||||
} catch (error) {
|
||||
// HttpError = the busboy peer dep is missing (501); anything else = malformed input (400).
|
||||
// HttpError = the busboy peer dep is missing (501) or a field is over the limit (413);
|
||||
// anything else = malformed input (400).
|
||||
if (isHttpError(error)) return { error: error.message, status: error.status };
|
||||
return { error: 'Invalid multipart body' };
|
||||
}
|
||||
@@ -106,12 +132,13 @@ export function acquireBody(
|
||||
// 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);
|
||||
? acquired.then((settled) => parseAcquired(settled, limit, matched, opts, req))
|
||||
: parseAcquired(acquired, limit, matched, opts, req);
|
||||
}
|
||||
|
||||
function parseAcquired(
|
||||
acquired: { bytes: Buffer | undefined } | BodyFailure,
|
||||
limit: number,
|
||||
matched: MatchedRoute,
|
||||
opts: HttpOptions | undefined,
|
||||
req: ErrorRequest,
|
||||
@@ -127,7 +154,9 @@ function parseAcquired(
|
||||
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) =>
|
||||
// A field is bounded by the body limit alone. busboy's own 1 MiB default would otherwise cut any
|
||||
// larger field that `maxBodyBytes` was raised to admit.
|
||||
return parseRequestBody(acquired.bytes, contentType, duplicates, maxParts, limit).then((parsed) =>
|
||||
'error' in parsed
|
||||
? { fail: renderError(new HttpError(parsed.status ?? 400, parsed.error), req, opts?.onError, opts?.logger) }
|
||||
: { body: parsed.body },
|
||||
|
||||
@@ -0,0 +1,441 @@
|
||||
// src/http/compression.ts — response compression (CARD-16, #112, D13 strategy B).
|
||||
//
|
||||
// The per-runtime contract, as measured in SPIKE-COMPRESSION.md and SPIKE-COMPRESSION-B.md:
|
||||
// - Node, Deno, Bun: `node:zlib` only, loaded lazily. Buffered bodies always go through the async
|
||||
// API: at 32 connections the sync API stalled the event loop for 9–13 ms even below 64 KiB, and
|
||||
// async gave 4× (Node) to 8× (Bun) the throughput. Streams go through createGzip /
|
||||
// createBrotliCompress, flushed after every frame, error frame and ping, so each event is
|
||||
// decodable the moment it arrives. br quality is fixed at 4 (zlib's default 11 stalls 6–33 ms).
|
||||
// - Deno runs `node:zlib`'s async API on the main thread (2.9.7), so there core compression is
|
||||
// CPU work on the event loop. That is documented, not worked around: no Deno branch here.
|
||||
// - Edge (workerd): core never encodes. Cloudflare compresses in front of the Worker, an encoded
|
||||
// body plus `Content-Encoding` is encoded a second time, and a bundled Worker cannot even
|
||||
// `require('node:zlib')`. Core sets `Vary` and nothing else.
|
||||
// - No `CompressionStream` anywhere: it cannot flush, so it would hold SSE frames back.
|
||||
import { mergeVary } from '../security';
|
||||
import { nodeRequire } from '../node-require';
|
||||
import { findHeader } from './conditional';
|
||||
import type { NeutralOutcome } from './core';
|
||||
|
||||
/** A content-coding core can produce. */
|
||||
export type Encoding = 'br' | 'gzip';
|
||||
|
||||
/** The public `createApp({ compression })` object form. */
|
||||
export interface CompressionOptions {
|
||||
/** Smallest buffered body, in bytes, worth encoding. Default `1024`. Streams ignore it. */
|
||||
threshold?: number;
|
||||
/** Encodings core may produce, in server preference order. Default `['br', 'gzip']`. */
|
||||
encodings?: Array<'br' | 'gzip'>;
|
||||
}
|
||||
|
||||
/** Resolved, validated configuration. `encode: false` is the edge mode: `Vary` only. */
|
||||
export interface CompressionConfig {
|
||||
threshold: number;
|
||||
encodings: Encoding[];
|
||||
encode: boolean;
|
||||
}
|
||||
|
||||
/** Fixed brotli quality. See the module comment. */
|
||||
export const BR_QUALITY = 4;
|
||||
|
||||
const KNOWN: readonly Encoding[] = ['br', 'gzip'];
|
||||
|
||||
/**
|
||||
* Marks an app as running on the edge, so core never encodes for it. `edgeHandler` calls it: that
|
||||
* covers the official adapter whatever the Worker's compat flags, including the case detection
|
||||
* cannot see (an old compat date without `navigator`, unbundled so `node:zlib` loads). A property
|
||||
* on the app rather than on the public `App` type, and `Symbol.for` because each tsup entry carries
|
||||
* its own copy of this module — the same arrangement as `WS_MAX_MESSAGE_BYTES`.
|
||||
*/
|
||||
export const MARK_EDGE: unique symbol = Symbol.for('green-tea.mark-edge');
|
||||
|
||||
/** The `[MARK_EDGE]` hook for an app: turns encoding off for good. A no-op when compression is off. */
|
||||
export function edgeMarker(cfg: CompressionConfig | undefined): () => void {
|
||||
return () => {
|
||||
if (cfg) cfg.encode = false;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this process is a Cloudflare Workers isolate. workerd sets `navigator.userAgent` to
|
||||
* exactly this string under the `global_navigator` compat flag, on by default since 2022-03-21.
|
||||
* Detected in `createApp` so `export default { fetch: app.fetch }`, which never passes through
|
||||
* `edgeHandler`, is covered too.
|
||||
*/
|
||||
export function isWorkerd(): boolean {
|
||||
const nav = (globalThis as { navigator?: { userAgent?: string } }).navigator;
|
||||
return nav?.userAgent === 'Cloudflare-Workers';
|
||||
}
|
||||
|
||||
interface ZlibStream {
|
||||
write(chunk: Uint8Array | string): boolean;
|
||||
flush(kind: number, cb: () => void): void;
|
||||
end(): void;
|
||||
destroy(): void;
|
||||
on(event: string, fn: (...args: never[]) => void): this;
|
||||
once(event: string, fn: (...args: never[]) => void): this;
|
||||
pipe<T>(dest: T): T;
|
||||
}
|
||||
|
||||
interface Zlib {
|
||||
gzip(b: Uint8Array, cb: (e: Error | null, r: Buffer) => void): void;
|
||||
brotliCompress(b: Uint8Array, o: object, cb: (e: Error | null, r: Buffer) => void): void;
|
||||
createGzip(): ZlibStream;
|
||||
createBrotliCompress(o: object): ZlibStream;
|
||||
constants: Record<string, number>;
|
||||
}
|
||||
|
||||
let zlibModule: Zlib | undefined;
|
||||
/** Lazy, so the edge bundle never evaluates `node:zlib`. */
|
||||
const zlib = (): Zlib => (zlibModule ??= nodeRequire<Zlib>('node:zlib'));
|
||||
|
||||
/**
|
||||
* Encode only off workerd, and only where `node:zlib` actually loads. In a bundled Worker
|
||||
* `nodeRequire` throws, and without this probe every compressible edge response was a 500
|
||||
* (SPIKE-COMPRESSION-B §6.1). Evaluated once, at `createApp`.
|
||||
*/
|
||||
function canEncode(): boolean {
|
||||
if (isWorkerd()) return false;
|
||||
|
||||
try {
|
||||
return typeof zlib().gzip === 'function';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Validates `createApp({ compression })`. Returns `undefined` when compression is off. */
|
||||
export function resolveCompression(
|
||||
option: boolean | CompressionOptions | undefined,
|
||||
encode: () => boolean = canEncode,
|
||||
): CompressionConfig | undefined {
|
||||
if (option === undefined || option === false) return undefined;
|
||||
|
||||
if (option !== true && (typeof option !== 'object' || option === null))
|
||||
throw new TypeError('createApp({ compression }): expected a boolean or { threshold?, encodings? }');
|
||||
|
||||
const opts: CompressionOptions = option === true ? {} : option;
|
||||
const threshold = opts.threshold ?? 1024;
|
||||
|
||||
if (!Number.isInteger(threshold) || threshold < 0)
|
||||
throw new TypeError(
|
||||
`createApp({ compression }): threshold must be a non-negative integer, got ${String(threshold)}`,
|
||||
);
|
||||
|
||||
const encodings = opts.encodings ?? ['br', 'gzip'];
|
||||
|
||||
if (!Array.isArray(encodings) || encodings.length === 0)
|
||||
throw new TypeError('createApp({ compression }): encodings must be a non-empty array');
|
||||
|
||||
for (const e of encodings)
|
||||
if (!KNOWN.includes(e))
|
||||
throw new TypeError(`createApp({ compression }): unknown encoding '${String(e)}' — expected 'br' or 'gzip'`);
|
||||
|
||||
return { threshold, encodings: [...new Set(encodings)], encode: encode() };
|
||||
}
|
||||
|
||||
/**
|
||||
* The qvalue grammar of RFC 9110 §12.4.2: `0` with up to three decimals, or `1` with up to three
|
||||
* zeros. `Number()` alone would admit `2`, `1e0` or `-1`, and a `q=2` would outrank the server's
|
||||
* preference.
|
||||
*/
|
||||
const QVALUE = /^(0(\.\d{0,3})?|1(\.0{0,3})?)$/;
|
||||
|
||||
/** `q` of one `Accept-Encoding` member, or 1 when absent. A malformed or out-of-range `q` excludes it. */
|
||||
function weightOf(params: string[]): number {
|
||||
for (const param of params) {
|
||||
const eq = param.indexOf('=');
|
||||
|
||||
if (eq !== -1 && param.slice(0, eq).trim().toLowerCase() === 'q') {
|
||||
const raw = param.slice(eq + 1).trim();
|
||||
return QVALUE.test(raw) ? Number(raw) : 0;
|
||||
}
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* `Accept-Encoding` negotiation (RFC 9110 §12.5.3). Returns the encoding to use, or `undefined` for
|
||||
* identity. Highest `q` wins; a tie goes to server preference, the order of `encodings`. `*` covers
|
||||
* every encoding not named explicitly, and `q=0` excludes. An absent header means identity:
|
||||
* §12.5.3 allows any coding then, but an absent header is overwhelmingly a client that would not
|
||||
* decode one.
|
||||
*/
|
||||
export function negotiate(accept: string | undefined, encodings: Encoding[]): Encoding | undefined {
|
||||
if (!accept) return undefined;
|
||||
const q = new Map<string, number>();
|
||||
|
||||
for (const part of accept.split(',')) {
|
||||
const [rawName, ...params] = part.split(';');
|
||||
const name = rawName.trim().toLowerCase();
|
||||
if (name) q.set(name, weightOf(params));
|
||||
}
|
||||
|
||||
let best: Encoding | undefined;
|
||||
let bestQ = 0;
|
||||
|
||||
for (const e of encodings) {
|
||||
const weight = q.get(e) ?? q.get('*') ?? 0;
|
||||
|
||||
if (weight > bestQ) {
|
||||
best = e;
|
||||
bestQ = weight;
|
||||
}
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
|
||||
const COMPRESSIBLE =
|
||||
/^\s*(text\/|application\/(json|javascript|xml|wasm|x-ndjson)\s*(;|$)|image\/svg\+xml\s*(;|$)|application\/[^;\s]+\+(json|xml)\s*(;|$))/i;
|
||||
|
||||
type Headers = Record<string, string | string[]>;
|
||||
|
||||
/**
|
||||
* Whether the response's representation could vary by `Accept-Encoding` at all. When it cannot —
|
||||
* already encoded, a range, no or an incompressible type, `no-transform` — core neither encodes
|
||||
* nor adds `Vary`. A buffered body under the threshold is the same case, decided in
|
||||
* {@link compressBuffered} once the size is known. Request-side reasons (HEAD, the client's header) do not appear here: those
|
||||
* responses still get `Vary`, so a shared cache keys them correctly.
|
||||
*/
|
||||
function eligible(headers: Headers): boolean {
|
||||
// One pass over the keys rather than one `read` per header: every response with compression on
|
||||
// comes through here, and four case-insensitive scans plus two regexes cost ~8% of a small Deno
|
||||
// request. The first key of each name wins, as `findHeader` would pick it.
|
||||
let type: string | undefined;
|
||||
let cacheControl: string | undefined;
|
||||
|
||||
for (const key of Object.keys(headers)) {
|
||||
const value = headers[key];
|
||||
if (value === undefined) continue;
|
||||
const lower = key.toLowerCase();
|
||||
if (lower === 'content-encoding' || lower === 'content-range') return false;
|
||||
if (lower === 'content-type') type ??= Array.isArray(value) ? value.join(', ') : value;
|
||||
else if (lower === 'cache-control') cacheControl ??= Array.isArray(value) ? value.join(', ') : value;
|
||||
}
|
||||
|
||||
if (!type || !compressibleType(type)) return false;
|
||||
return cacheControl === undefined || !NO_TRANSFORM.test(cacheControl);
|
||||
}
|
||||
|
||||
const NO_TRANSFORM = /(^|[\s,])no-transform\s*(,|$)/i;
|
||||
|
||||
// ponytail: a one-entry memo, since an app answers nearly every response with the same type or two;
|
||||
// a bounded map if a mix of types ever measures.
|
||||
let lastType: string | undefined;
|
||||
let lastCompressible = false;
|
||||
|
||||
function compressibleType(type: string): boolean {
|
||||
if (type !== lastType) {
|
||||
lastType = type;
|
||||
lastCompressible = COMPRESSIBLE.test(type);
|
||||
}
|
||||
|
||||
return lastCompressible;
|
||||
}
|
||||
|
||||
function withVary(headers: Headers): Headers {
|
||||
const key = findHeader(headers, 'vary');
|
||||
const out = { ...headers };
|
||||
let existing: string | undefined;
|
||||
|
||||
if (key !== undefined) {
|
||||
const value = out[key];
|
||||
existing = Array.isArray(value) ? value.join(', ') : value;
|
||||
delete out[key];
|
||||
}
|
||||
|
||||
out.vary = mergeVary(existing, 'Accept-Encoding');
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Headers for an encoded body: `Vary` merged, `Content-Encoding` set, `Content-Length` dropped (it described the identity body). */
|
||||
function encodedHeaders(headers: Headers, encoding: Encoding): Headers {
|
||||
const out = withVary(headers);
|
||||
const length = findHeader(out, 'content-length');
|
||||
if (length !== undefined) delete out[length];
|
||||
out['content-encoding'] = encoding;
|
||||
return out;
|
||||
}
|
||||
|
||||
const brParams = (size?: number) => {
|
||||
const c = zlib().constants;
|
||||
const params: Record<number, number> = { [c.BROTLI_PARAM_QUALITY]: BR_QUALITY };
|
||||
if (size !== undefined) params[c.BROTLI_PARAM_SIZE_HINT] = size;
|
||||
return { params };
|
||||
};
|
||||
|
||||
/** Encodes one buffered body with the async zlib API — never the sync one (see the module comment). */
|
||||
function encodeBody(body: Uint8Array, encoding: Encoding): Promise<Buffer> {
|
||||
const z = zlib();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const done = (err: Error | null, out: Buffer) => (err ? reject(err) : resolve(out));
|
||||
if (encoding === 'br') z.brotliCompress(body, brParams(body.byteLength), done);
|
||||
else z.gzip(body, done);
|
||||
});
|
||||
}
|
||||
|
||||
/** A fresh compressing stream plus the flush mode that makes it emit everything written so far. */
|
||||
function createEncoderStream(encoding: Encoding): { stream: ZlibStream; flushKind: number } {
|
||||
const z = zlib();
|
||||
|
||||
if (encoding === 'br')
|
||||
return { stream: z.createBrotliCompress(brParams()), flushKind: z.constants.BROTLI_OPERATION_FLUSH };
|
||||
|
||||
return { stream: z.createGzip(), flushKind: z.constants.Z_SYNC_FLUSH };
|
||||
}
|
||||
|
||||
/** The request facts compression needs. */
|
||||
export interface CompressionRequest {
|
||||
method: string;
|
||||
headers: Record<string, string | string[] | undefined>;
|
||||
}
|
||||
|
||||
const acceptOf = (req: CompressionRequest): string | undefined => {
|
||||
const v = req.headers['accept-encoding'];
|
||||
return Array.isArray(v) ? v.join(', ') : v;
|
||||
};
|
||||
|
||||
type Buffered = Extract<NeutralOutcome, { kind: 'buffered' }>;
|
||||
type Streamed = Extract<NeutralOutcome, { kind: 'stream' }>;
|
||||
|
||||
/** Decides a buffered outcome. Returns it untouched, with `Vary` only, or encoded. */
|
||||
function compressBuffered(
|
||||
cfg: CompressionConfig,
|
||||
req: CompressionRequest,
|
||||
outcome: Buffered,
|
||||
): Buffered | Promise<Buffered> {
|
||||
const { status, headers, body } = outcome;
|
||||
// A 304 carries `Vary` whatever else it has: it usually has no `Content-Type`, so the
|
||||
// eligibility test would drop it, and a cache needs the same key it stored the 200 under.
|
||||
if (status === 304) return { ...outcome, headers: withVary(headers) };
|
||||
if (status === 204 || !eligible(headers)) return outcome;
|
||||
|
||||
const vary = (): Buffered => ({ ...outcome, headers: withVary(headers) });
|
||||
if (status < 200 || req.method === 'HEAD' || !cfg.encode) return vary();
|
||||
|
||||
// Under the threshold the body is sent identity whatever the client accepts, so `Accept-Encoding`
|
||||
// played no part and there is no `Vary` to send (RFC 9110 §12.5.5). A cache that stores this
|
||||
// response for everyone is right to: every client accepts identity. Skipping it matters on Deno,
|
||||
// which pays ~10% of a small request for a `Vary` header. Measured without allocating the bytes.
|
||||
const size = typeof body === 'string' ? Buffer.byteLength(body) : body.byteLength;
|
||||
if (size < cfg.threshold) return outcome;
|
||||
|
||||
const encoding = negotiate(acceptOf(req), cfg.encodings);
|
||||
if (!encoding) return vary();
|
||||
|
||||
const bytes = typeof body === 'string' ? Buffer.from(body) : body;
|
||||
return encodeBody(bytes, encoding).then((encoded) => ({
|
||||
...outcome,
|
||||
headers: encodedHeaders(headers, encoding),
|
||||
body: encoded,
|
||||
}));
|
||||
}
|
||||
|
||||
/** Decides a stream: its headers, and the encoding the adapter applies frame by frame. `threshold` does not apply. */
|
||||
function compressStream(cfg: CompressionConfig, req: CompressionRequest, outcome: Streamed): Streamed {
|
||||
if (!eligible(outcome.headers)) return outcome;
|
||||
if (req.method === 'HEAD' || !cfg.encode) return { ...outcome, headers: withVary(outcome.headers) };
|
||||
const encoding = negotiate(acceptOf(req), cfg.encodings);
|
||||
if (!encoding) return { ...outcome, headers: withVary(outcome.headers) };
|
||||
return { ...outcome, headers: encodedHeaders(outcome.headers, encoding), encoding };
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies `createApp({ compression })` to an outcome, after `handle()` and before the adapter
|
||||
* writes it. One function for both adapters, so Node and the fetch runtimes cannot diverge. The
|
||||
* ETag (CARD-15) was taken in `dispatch` on the identity body and is not touched: it is weak, so
|
||||
* one tag describes every coding.
|
||||
*/
|
||||
export function compressOutcome(
|
||||
cfg: CompressionConfig | undefined,
|
||||
req: CompressionRequest,
|
||||
outcome: NeutralOutcome,
|
||||
): NeutralOutcome | Promise<NeutralOutcome> {
|
||||
if (!cfg) return outcome;
|
||||
return outcome.kind === 'stream' ? compressStream(cfg, req, outcome) : compressBuffered(cfg, req, outcome);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps a web byte stream so every chunk is compressed and flushed on its own: one SSE frame in,
|
||||
* one decodable compressed chunk out. This is the thing `CompressionStream` cannot do.
|
||||
*/
|
||||
export function compressWebStream(source: ReadableStream<Uint8Array>, encoding: Encoding): ReadableStream<Uint8Array> {
|
||||
const { stream: z, flushKind } = createEncoderStream(encoding);
|
||||
const reader = source.getReader();
|
||||
let pending: Uint8Array[] = [];
|
||||
let failure: unknown;
|
||||
z.on('data', (c: Uint8Array) => pending.push(c));
|
||||
// Without a listener a zlib error is an uncaught exception that takes the process down.
|
||||
z.on('error', (err: unknown) => (failure ??= err));
|
||||
|
||||
const take = (): Uint8Array | undefined => {
|
||||
if (pending.length === 0) return undefined;
|
||||
const chunk = pending.length === 1 ? pending[0] : Buffer.concat(pending);
|
||||
pending = [];
|
||||
return new Uint8Array(chunk.buffer as ArrayBuffer, chunk.byteOffset, chunk.byteLength);
|
||||
};
|
||||
|
||||
return new ReadableStream<Uint8Array>({
|
||||
async pull(controller) {
|
||||
const { value, done } = await reader.read();
|
||||
|
||||
if (done) {
|
||||
await new Promise<void>((resolve) => {
|
||||
z.once('end', resolve);
|
||||
z.once('error', () => resolve());
|
||||
z.end();
|
||||
});
|
||||
} else {
|
||||
z.write(value);
|
||||
await new Promise<void>((resolve) => z.flush(flushKind, resolve));
|
||||
}
|
||||
|
||||
if (failure !== undefined) {
|
||||
controller.error(failure);
|
||||
await reader.cancel(failure).catch(() => {});
|
||||
return;
|
||||
}
|
||||
|
||||
const out = take();
|
||||
if (out) controller.enqueue(out);
|
||||
if (done) controller.close();
|
||||
},
|
||||
async cancel(reason) {
|
||||
z.destroy();
|
||||
await reader.cancel(reason);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Where `pipeStream` writes frames: `res` itself, or a flushing compressor piped into it. */
|
||||
export interface FrameSink {
|
||||
write(chunk: string | Buffer): boolean;
|
||||
/** The emitter whose `drain` ends a backpressure wait. */
|
||||
drains: NodeJS.EventEmitter;
|
||||
end(): void;
|
||||
destroy(): void;
|
||||
}
|
||||
|
||||
/** The Node stream path's sink. Without an encoding it is `res`, unchanged. */
|
||||
export function frameSink(res: NodeJS.WritableStream & { destroy(): void }, encoding?: Encoding): FrameSink {
|
||||
if (!encoding) return { write: (c) => res.write(c), drains: res, end: () => void res.end(), destroy: () => {} };
|
||||
|
||||
const { stream: zs, flushKind } = createEncoderStream(encoding);
|
||||
zs.on('error', () => res.destroy());
|
||||
zs.pipe(res);
|
||||
|
||||
return {
|
||||
write(chunk) {
|
||||
const ok = zs.write(chunk);
|
||||
// Flushed per frame: the point of an event stream is that each event arrives when it happens.
|
||||
zs.flush(flushKind, () => {});
|
||||
return ok;
|
||||
},
|
||||
drains: zs as unknown as NodeJS.EventEmitter,
|
||||
end: () => zs.end(), // `pipe` ends `res` once the compressor has drained
|
||||
destroy: () => zs.destroy(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
// src/http/conditional.ts — ETags and conditional GET (RFC 9110 §8.8.3, §13.1.2, §13.1.3, §15.4.5).
|
||||
|
||||
type HeaderBag = Record<string, string | string[] | undefined>;
|
||||
|
||||
/** The first value of a request header, or `undefined`. */
|
||||
function single(value: string | string[] | undefined): string | undefined {
|
||||
return Array.isArray(value) ? value.join(', ') : value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits an `If-None-Match` list on the commas that sit outside quotes. An entity-tag may legally
|
||||
* contain a comma inside its quotes (`"a,b"`), so a plain `split(',')` would cut one tag in two.
|
||||
*/
|
||||
function splitTags(header: string): string[] {
|
||||
const tags: string[] = [];
|
||||
let start = 0;
|
||||
let quoted = false;
|
||||
|
||||
for (let i = 0; i < header.length; i++) {
|
||||
const ch = header[i];
|
||||
|
||||
if (ch === '"') quoted = !quoted;
|
||||
else if (ch === ',' && !quoted) {
|
||||
tags.push(header.slice(start, i).trim());
|
||||
start = i + 1;
|
||||
}
|
||||
}
|
||||
|
||||
tags.push(header.slice(start).trim());
|
||||
return tags.filter(Boolean);
|
||||
}
|
||||
|
||||
/** The opaque part of an entity-tag: `W/"x"` and `"x"` both become `"x"` (weak comparison). */
|
||||
const opaque = (tag: string): string => (tag.startsWith('W/') ? tag.slice(2) : tag);
|
||||
|
||||
/**
|
||||
* Whether `If-None-Match` matches `etag` under the weak comparison GET and HEAD use
|
||||
* (RFC 9110 §13.1.2): `W/"x"` matches `"x"`, and `*` matches any current representation.
|
||||
*/
|
||||
export function ifNoneMatchMatches(header: string, etag: string): boolean {
|
||||
const own = opaque(etag.trim());
|
||||
|
||||
for (const tag of splitTags(header)) if (tag === '*' || opaque(tag) === own) return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a resource last modified at `mtimeMs` is unchanged since an `If-Modified-Since` date.
|
||||
* HTTP dates have one-second resolution, so the modification time is truncated to the second first;
|
||||
* otherwise a file written at 12:00:00.400 would never match the `Last-Modified` it was served with.
|
||||
* An unparseable date is ignored, as RFC 9110 §13.1.3 requires.
|
||||
*/
|
||||
export function notModifiedSince(header: string, mtimeMs: number): boolean {
|
||||
const since = Date.parse(header);
|
||||
if (Number.isNaN(since)) return false;
|
||||
return Math.floor(mtimeMs / 1000) * 1000 <= since;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decides a conditional GET/HEAD: `If-None-Match` when present, else `If-Modified-Since` when the
|
||||
* caller has a modification time to compare (static files only — handler responses have none).
|
||||
*/
|
||||
export function isNotModified(headers: HeaderBag, etag: string, mtimeMs?: number): boolean {
|
||||
const inm = single(headers['if-none-match']);
|
||||
if (inm !== undefined) return ifNoneMatchMatches(inm, etag);
|
||||
|
||||
const ims = single(headers['if-modified-since']);
|
||||
return ims !== undefined && mtimeMs !== undefined && notModifiedSince(ims, mtimeMs);
|
||||
}
|
||||
|
||||
/** Weak validator for a static file, from the `stat` the resolver already does: `W/"<size>-<mtimeMs base36>"`. */
|
||||
export function staticEtag(size: number, mtimeMs: number): string {
|
||||
return `W/"${size}-${Math.floor(mtimeMs).toString(36)}"`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Weak validator for a buffered body: its byte length plus a 32-bit FNV-1a hash of its bytes, in
|
||||
* base 36. FNV rather than `crypto.subtle.digest`: it is synchronous and dependency-free, where
|
||||
* `subtle` costs a promise per response. It is not collision-resistant and need not be — an ETag
|
||||
* detects change, it does not authenticate. The length narrows a collision to equal-length bodies.
|
||||
*
|
||||
* Weak, so one tag can describe every content-coding of the same body (CARD-16 hashes before it
|
||||
* encodes). Strings are hashed as UTF-8, so the tag matches what goes on the wire.
|
||||
*/
|
||||
export function bodyEtag(body: string | Uint8Array): string {
|
||||
const bytes = typeof body === 'string' ? Buffer.from(body, 'utf8') : body;
|
||||
let hash = 0x811c9dc5;
|
||||
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
hash ^= bytes[i];
|
||||
hash = Math.imul(hash, 0x01000193);
|
||||
}
|
||||
|
||||
return `W/"${bytes.length.toString(36)}-${(hash >>> 0).toString(36)}"`;
|
||||
}
|
||||
|
||||
/** The key under which `headers` holds `name`, case-insensitively, or `undefined`. */
|
||||
export function findHeader(headers: Record<string, unknown>, name: string): string | undefined {
|
||||
for (const key of Object.keys(headers)) if (key.toLowerCase() === name) return key;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* The headers of a `304` built from the `200` it stands for: everything but the `content-*`
|
||||
* headers that describe a body (`content-type`, `content-length`, `content-encoding`, …), plus
|
||||
* `transfer-encoding`. `content-location` is kept: §15.4.5 lists it among the fields a 304 sends. `ETag`, `Vary`, `Cache-Control`, `Last-Modified` and anything else a cache
|
||||
* would update stay (RFC 9110 §15.4.5). Injected security headers are merged later by the adapter,
|
||||
* exactly as on a `200`.
|
||||
*/
|
||||
export function notModifiedHeaders(headers: Record<string, string | string[]>): Record<string, string | string[]> {
|
||||
const out: Record<string, string | string[]> = {};
|
||||
|
||||
for (const key of Object.keys(headers)) {
|
||||
const lower = key.toLowerCase();
|
||||
if ((lower.startsWith('content-') && lower !== 'content-location') || lower === 'transfer-encoding') continue;
|
||||
out[key] = headers[key];
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
+154
-60
@@ -6,34 +6,21 @@ import { buildSecurityHeaders, resolveCors, corsPreflightHeaders } from '../secu
|
||||
import { resolveRoute, allowedMethods, normalizeRequestPath, parseQuery } from './router';
|
||||
import { pickEncoder } from './stream';
|
||||
import { acquireBody, type BodyReader } from './body';
|
||||
import type { RouteDef, HttpOptions } from './types';
|
||||
import { bodyEtag, findHeader, isNotModified, notModifiedHeaders, staticEtag } from './conditional';
|
||||
import type { StaticHit } from '../views';
|
||||
import type { Encoding } from './compression';
|
||||
import type { RouteDef, HttpOptions, MatchedRoute } from './types';
|
||||
import type { StreamEncoder } from '../encoders';
|
||||
import type { Bus } from '../bus';
|
||||
import { nodeRequire } from '../node-require';
|
||||
|
||||
/**
|
||||
* `randomUUID`, from wherever this runtime keeps it. Resolved once, at import.
|
||||
* `randomUUID` from the web-standard global, which every supported runtime exposes without a flag:
|
||||
* Node (the `engines` floor is 22; the global arrived unflagged in 19), Deno, Bun and workerd.
|
||||
*
|
||||
* The web-standard global stays the primary path, and that is deliberate rather than stylistic:
|
||||
* this file is the runtime-neutral core, and Deno, Bun and workerd all expose `crypto` without a
|
||||
* compatibility flag, while `node:crypto` is unavailable to at least one of them.
|
||||
*
|
||||
* Node is the exception. The global arrived **unflagged in 19**, and `engines` promises `>=18`,
|
||||
* where it does not exist at all — so the previous `declare const crypto` compiled cleanly and then
|
||||
* threw `ReferenceError: crypto is not defined` on the first request of every Node 18 process. Only
|
||||
* CI's Node 18 job caught it; every newer Node and every other runtime hides it, which is exactly
|
||||
* why that job is pinned to the floor rather than to the current release.
|
||||
*
|
||||
* The fallback is reached only by a runtime that lacks the global, so workerd never evaluates it.
|
||||
* It goes through {@link nodeRequire} rather than a bare `require`, which is what makes it work on
|
||||
* every distribution of this package and not just the bundled ones.
|
||||
* Node 18 lacked it, and this used to fall back to `node:crypto` there. That fallback went with the
|
||||
* Node 18 floor.
|
||||
*/
|
||||
const randomUUID: () => string = (() => {
|
||||
const webCrypto = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;
|
||||
if (typeof webCrypto?.randomUUID === 'function') return () => webCrypto.randomUUID!();
|
||||
|
||||
return nodeRequire<{ randomUUID: () => string }>('node:crypto').randomUUID;
|
||||
})();
|
||||
const randomUUID = (): string => crypto.randomUUID();
|
||||
|
||||
/**
|
||||
* A runtime-neutral inbound request.
|
||||
@@ -54,7 +41,11 @@ export interface NeutralRequest {
|
||||
/** The runtime's own request object, passed back to {@link readBody} untouched and never inspected here. */
|
||||
source: unknown;
|
||||
secure: boolean;
|
||||
ip: string;
|
||||
/**
|
||||
* The client address, resolved only when something reads `ctx.ip`. A function of `source` rather
|
||||
* than a closure, so an adapter passes one module-level function and allocates nothing per request.
|
||||
*/
|
||||
resolveIp: (source: unknown, opts: HttpOptions | undefined) => string;
|
||||
requestId: string;
|
||||
traceId?: string;
|
||||
}
|
||||
@@ -101,14 +92,16 @@ export function correlateRequest(headers: Record<string, string | string[] | und
|
||||
|
||||
/** 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: 'buffered'; status: number; headers: Record<string, string | string[]>; body: string | Buffer }
|
||||
| {
|
||||
kind: 'stream';
|
||||
headers: Record<string, string>;
|
||||
headers: Record<string, string | string[]>;
|
||||
stream: AsyncIterable<unknown>;
|
||||
encoder: StreamEncoder;
|
||||
/** The matched route's pattern, for naming the stream lifecycle events. */
|
||||
route: string;
|
||||
/** Set by `compressOutcome`: the adapter encodes each frame with it and flushes. */
|
||||
encoding?: Encoding;
|
||||
};
|
||||
|
||||
/** {@link handle}'s result for a normal (non-preflight) request. */
|
||||
@@ -142,20 +135,76 @@ function errorOutcome(
|
||||
req: NeutralRequest,
|
||||
injected: Record<string, string>,
|
||||
opts: HttpOptions | undefined,
|
||||
headers: Record<string, string> = {},
|
||||
headers: Record<string, string | string[]> = {},
|
||||
): HandleResult {
|
||||
const rendered = renderError(error, req, opts?.onError, opts?.logger);
|
||||
return {
|
||||
injected,
|
||||
outcome: {
|
||||
outcome: bodyless({
|
||||
kind: 'buffered',
|
||||
status: rendered.status,
|
||||
headers: { ...rendered.headers, ...headers },
|
||||
body: req.method === 'HEAD' ? '' : rendered.body,
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
type Buffered = Extract<NeutralOutcome, { kind: 'buffered' }>;
|
||||
|
||||
/**
|
||||
* A `304` has no body on any adapter, and none of the headers that describe one. This is the one
|
||||
* place every buffered outcome passes through on its way out, so a handler that throws
|
||||
* `NotModified` — rendered by the default renderer as a JSON envelope — answers the same bodiless
|
||||
* `304` the ETag path does. Node would drop the body of a 304 by itself; the fetch adapters already
|
||||
* null it; the `content-type` would still have gone out on both.
|
||||
*/
|
||||
function bodyless(outcome: Buffered): Buffered {
|
||||
if (outcome.status !== 304) return outcome;
|
||||
return { kind: 'buffered', status: 304, headers: notModifiedHeaders(outcome.headers), body: '' };
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers a static hit: `ETag` + `Last-Modified` from the resolver's `stat`, `Cache-Control` from the
|
||||
* `static` option, and a `304` — decided before the file is read, so a revalidation costs a `stat`
|
||||
* and nothing more. HEAD never reads either.
|
||||
*/
|
||||
async function staticOutcome(hit: StaticHit, req: NeutralRequest): Promise<Buffered> {
|
||||
const etag = staticEtag(hit.size, hit.mtimeMs);
|
||||
const headers: Record<string, string> = {
|
||||
'content-type': hit.contentType,
|
||||
etag,
|
||||
'last-modified': new Date(hit.mtimeMs).toUTCString(),
|
||||
'cache-control': hit.cacheControl,
|
||||
};
|
||||
|
||||
if (isNotModified(req.headers, etag, hit.mtimeMs))
|
||||
return bodyless({ kind: 'buffered', status: 304, headers, body: '' });
|
||||
|
||||
return { kind: 'buffered', status: 200, headers, body: req.method === 'HEAD' ? '' : await hit.read() };
|
||||
}
|
||||
|
||||
/**
|
||||
* `createApp({ etag: true })` for a handler response: a buffered `200` to GET/HEAD gets a weak ETag
|
||||
* from its body — computed before HEAD blanks the body, so HEAD and GET carry the same tag — unless
|
||||
* the handler set one, which is kept and only compared. A match becomes a bodiless `304`. The
|
||||
* handler has already run: this saves bandwidth, not work.
|
||||
*/
|
||||
function tagged(
|
||||
result: { status: number; headers: Record<string, string | string[]>; body: string },
|
||||
req: NeutralRequest,
|
||||
): Buffered {
|
||||
const key = findHeader(result.headers, 'etag');
|
||||
const existing = key === undefined ? undefined : result.headers[key];
|
||||
// ETag is single-valued: from an array, the last value wins, as a repeated `setHeader` would.
|
||||
const own = Array.isArray(existing) ? existing[existing.length - 1] : existing;
|
||||
const etag = own ?? bodyEtag(result.body);
|
||||
const headers = { ...result.headers, [key ?? 'etag']: etag };
|
||||
|
||||
if (isNotModified(req.headers, etag)) return bodyless({ kind: 'buffered', status: 304, headers, body: '' });
|
||||
|
||||
return { kind: 'buffered', status: 200, headers, body: req.method === 'HEAD' ? '' : result.body };
|
||||
}
|
||||
|
||||
async function unmatchedOutcome(
|
||||
routes: RouteDef[],
|
||||
opts: HttpOptions | undefined,
|
||||
@@ -165,18 +214,7 @@ async function unmatchedOutcome(
|
||||
): 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,
|
||||
},
|
||||
};
|
||||
}
|
||||
if (hit) return { injected, outcome: await staticOutcome(hit, req) };
|
||||
}
|
||||
|
||||
const allow = allowedMethods(routes, path);
|
||||
@@ -324,6 +362,76 @@ async function observedDispatch(
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* The request a route handler receives.
|
||||
*
|
||||
* `ip` is resolved on its first read and kept. Most routes never read it, and on Bun resolving it
|
||||
* is a native call. A step may assign it, as it may any key. The accessor is on the prototype rather
|
||||
* than in an object literal: a literal with an accessor is a slow object in V8 and JSC, and every
|
||||
* read of every key paid for it, which cost Node and Deno 15-24%.
|
||||
*/
|
||||
class RouteRequest {
|
||||
method: string;
|
||||
url: string;
|
||||
headers: NeutralRequest['headers'];
|
||||
query: Record<string, string>;
|
||||
protocol: 'http' | 'https';
|
||||
requestId: string;
|
||||
traceId: string | undefined;
|
||||
private resolved: string | undefined = undefined;
|
||||
|
||||
constructor(
|
||||
private readonly req: NeutralRequest,
|
||||
private readonly opts: HttpOptions | undefined,
|
||||
public params: Record<string, string>,
|
||||
public body: unknown,
|
||||
) {
|
||||
this.method = req.method;
|
||||
this.url = req.url;
|
||||
this.headers = req.headers;
|
||||
this.query = parseQuery(req.url);
|
||||
this.protocol = req.secure ? 'https' : 'http';
|
||||
this.requestId = req.requestId;
|
||||
this.traceId = req.traceId;
|
||||
}
|
||||
|
||||
get ip(): string {
|
||||
return (this.resolved ??= this.req.resolveIp(this.req.source, this.opts));
|
||||
}
|
||||
|
||||
set ip(value: string) {
|
||||
this.resolved = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* A stream body runs after the response has started, when the socket the address would come
|
||||
* from may already be gone, so once a stream is returned an address nothing has read yet is `''`.
|
||||
*/
|
||||
seal(): void {
|
||||
this.resolved ??= '';
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs the matched route's handler, turning a throw into the standard error envelope. */
|
||||
async function runHandler(
|
||||
matched: MatchedRoute,
|
||||
req: NeutralRequest,
|
||||
body: unknown,
|
||||
opts: HttpOptions | undefined,
|
||||
): Promise<PipelineResult> {
|
||||
const request = new RouteRequest(req, opts, matched.params, body);
|
||||
let result: PipelineResult;
|
||||
|
||||
try {
|
||||
result = await matched.def.handler(request);
|
||||
} catch (error) {
|
||||
result = renderError(error, req, opts?.onError, opts?.logger);
|
||||
}
|
||||
|
||||
if (isStreamResult(result)) request.seal();
|
||||
return result;
|
||||
}
|
||||
|
||||
async function dispatch(
|
||||
routes: RouteDef[],
|
||||
opts: HttpOptions | undefined,
|
||||
@@ -394,24 +502,7 @@ async function dispatch(
|
||||
// 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, opts?.logger);
|
||||
}
|
||||
const result = await runHandler(matched, req, acquired.body, opts);
|
||||
|
||||
if (isStreamResult(result)) {
|
||||
const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? ''));
|
||||
@@ -427,13 +518,16 @@ async function dispatch(
|
||||
};
|
||||
}
|
||||
|
||||
if (opts?.etag && result.status === 200 && (req.method === 'GET' || req.method === 'HEAD'))
|
||||
return { injected, outcome: tagged(result, req) };
|
||||
|
||||
return {
|
||||
injected,
|
||||
outcome: {
|
||||
outcome: bodyless({
|
||||
kind: 'buffered',
|
||||
status: result.status,
|
||||
headers: result.headers,
|
||||
body: req.method === 'HEAD' ? '' : result.body,
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
+52
-1
@@ -19,7 +19,10 @@ export function mergeInjectedHeaders(
|
||||
const lowerKey = key.toLowerCase();
|
||||
|
||||
if (lowerKey === 'vary') {
|
||||
handlerVary = handlerHeaders[key];
|
||||
// A header value may be an array (D11). `mergeVary` splits on commas, so joining first keeps
|
||||
// every token a handler listed instead of stringifying the array by accident.
|
||||
const value = handlerHeaders[key];
|
||||
handlerVary = Array.isArray(value) ? value.join(', ') : value;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -40,3 +43,51 @@ export function mergeInjectedHeaders(
|
||||
else if (handlerVary !== undefined) merged['vary'] = handlerVary;
|
||||
return merged;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares merged headers for Node's `writeHead`, which writes one header line per array element
|
||||
* for *any* header. That is right for `set-cookie`, the one header whose values cannot be
|
||||
* comma-joined (an `Expires` date carries a comma), and wrong for every other: RFC 9110 §5.3 makes a
|
||||
* list header's repeated lines equivalent to one comma-joined line, and joining keeps all four
|
||||
* adapters sending the same bytes. So every other array is joined with `, ` here, before
|
||||
* `writeHead`. Returns the input untouched when it holds no array, which is nearly every response.
|
||||
*/
|
||||
export function joinListHeaders<T extends Record<string, unknown>>(headers: T): T {
|
||||
let out: Record<string, unknown> | undefined;
|
||||
|
||||
for (const key of Object.keys(headers)) {
|
||||
const value = headers[key];
|
||||
if (!Array.isArray(value) || key.toLowerCase() === 'set-cookie') continue;
|
||||
out ??= { ...headers };
|
||||
out[key] = value.join(', ');
|
||||
}
|
||||
|
||||
return (out as T | undefined) ?? headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a web `Headers` from merged headers. A plain record cannot be handed to `new Response`:
|
||||
* the Fetch spec stringifies an array value to `a,b`, which for `set-cookie` is one broken cookie.
|
||||
* `set-cookie` elements are appended one by one, so each reaches the client as its own line;
|
||||
* every other array is joined with `, `, exactly as {@link joinListHeaders} does for Node.
|
||||
*
|
||||
* A record of plain strings, which is nearly every response, is returned untouched: Deno and Bun
|
||||
* build their native headers from a record directly, and filling a `Headers` from JS instead measured
|
||||
* 5–8% on every Deno request.
|
||||
*/
|
||||
export function toWebHeaders(headers: Record<string, unknown>): Headers | Record<string, string> {
|
||||
if (Object.values(headers).every((value) => typeof value === 'string')) return headers as Record<string, string>;
|
||||
|
||||
const out = new Headers();
|
||||
|
||||
for (const key of Object.keys(headers)) {
|
||||
const value = headers[key];
|
||||
if (value === undefined) continue;
|
||||
|
||||
if (!Array.isArray(value)) out.set(key, String(value));
|
||||
else if (key.toLowerCase() === 'set-cookie') for (const cookie of value) out.append(key, String(cookie));
|
||||
else out.set(key, value.join(', '));
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
import type { ReservedPath } from './reserved-paths';
|
||||
|
||||
/** Liveness probe path: `200` whenever the process answers. */
|
||||
export const LIVE_PATH = '/__live__';
|
||||
/** Readiness probe path: `503` while booting or draining, `200` otherwise. */
|
||||
export const READY_PATH = '/__ready__';
|
||||
|
||||
/** The probe paths, as reserved-path entries for the boot check (only while `health` is on). */
|
||||
export const HEALTH_RESERVED: readonly ReservedPath[] = [
|
||||
{ path: LIVE_PATH, purpose: 'the liveness probe, health: true' },
|
||||
{ path: READY_PATH, purpose: 'the readiness probe, health: true' },
|
||||
];
|
||||
|
||||
/**
|
||||
* Where an app is in its life, as `/__ready__` reports it.
|
||||
*
|
||||
* `booting` until `boot()` resolves, `ready` after, `draining` from the moment `close()` starts.
|
||||
* Moves forward only: a boot that finishes while draining does not make the app ready again.
|
||||
*/
|
||||
export type HealthPhase = 'booting' | 'ready' | 'draining';
|
||||
|
||||
/** What the adapters read to answer a probe. Lives on {@link HttpOptions}; absent when `health` is off. */
|
||||
export interface HealthProbe {
|
||||
phase(): HealthPhase;
|
||||
/** Optional providers that failed to boot, as `app.degraded()` reports them. */
|
||||
degraded(): string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Close-time hook on the app object for the adapters that own the server (`serveDeno`, `serveBun`):
|
||||
* marks the app draining and resolves after `drainDelayMs`, so the listener stays open while
|
||||
* `/__ready__` answers `503`. Idempotent — later calls share the first window. Symbol-keyed because it
|
||||
* is adapter plumbing, not public API.
|
||||
*/
|
||||
export const HEALTH_DRAIN: unique symbol = Symbol.for('green-tea.health-drain');
|
||||
|
||||
/** Starts the drain window on `app` (see {@link HEALTH_DRAIN}); resolves at once when health is off. */
|
||||
export function beginDrain(app: object): Promise<void> {
|
||||
return (app as { [HEALTH_DRAIN]?: () => Promise<void> })[HEALTH_DRAIN]?.() ?? Promise.resolve();
|
||||
}
|
||||
|
||||
/** A probe response, before the adapter merges in the injected security headers. */
|
||||
export interface ProbeAnswer {
|
||||
status: number;
|
||||
headers: Record<string, string>;
|
||||
body: string;
|
||||
}
|
||||
|
||||
const JSON_NO_STORE = { 'content-type': 'application/json', 'cache-control': 'no-store' };
|
||||
|
||||
/** The readiness body and status for the current phase. */
|
||||
function readiness(probe: HealthProbe): { status: number; body: object } {
|
||||
const phase = probe.phase();
|
||||
if (phase === 'booting') return { status: 503, body: { status: 'booting' } };
|
||||
if (phase === 'draining') return { status: 503, body: { status: 'draining' } };
|
||||
|
||||
const degraded = probe.degraded();
|
||||
return degraded.length
|
||||
? { status: 200, body: { status: 'degraded', degraded } }
|
||||
: { status: 200, body: { status: 'ok' } };
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers `/__live__` or `/__ready__`, or returns `undefined` for any other path.
|
||||
*
|
||||
* Called by each adapter before the request gate and before `handle()`, so a probe runs no step,
|
||||
* provider, plugin or `onError`, emits no lifecycle event, and is never shed by
|
||||
* `maxConcurrentRequests`. `url` may carry a query string; only the exact path is a probe.
|
||||
*/
|
||||
export function answerProbe(method: string, url: string, probe: HealthProbe): ProbeAnswer | undefined {
|
||||
const query = url.indexOf('?');
|
||||
const path = query === -1 ? url : url.slice(0, query);
|
||||
if (path !== LIVE_PATH && path !== READY_PATH) return undefined;
|
||||
|
||||
if (method !== 'GET' && method !== 'HEAD') {
|
||||
return {
|
||||
status: 405,
|
||||
headers: { ...JSON_NO_STORE, allow: 'GET, HEAD' },
|
||||
body: JSON.stringify({ error: 'Method Not Allowed' }),
|
||||
};
|
||||
}
|
||||
|
||||
const { status, body } = path === LIVE_PATH ? { status: 200, body: { status: 'ok' } } : readiness(probe);
|
||||
return { status, headers: { ...JSON_NO_STORE }, body: method === 'HEAD' ? '' : JSON.stringify(body) };
|
||||
}
|
||||
|
||||
/** `createApp({ health })`, normalised. `undefined` when health is off. */
|
||||
export interface HealthConfig {
|
||||
drainDelayMs: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates `createApp({ health })` and normalises it. Throws on anything but `true`, `false`,
|
||||
* `undefined` or `{ drainDelayMs?: number }`, and on a `drainDelayMs` that does not fit in the shutdown
|
||||
* budget next to the teardown reservation.
|
||||
*/
|
||||
export function resolveHealth(
|
||||
health: unknown,
|
||||
shutdownTimeoutMs: number | undefined,
|
||||
teardownTimeoutMs: number | undefined,
|
||||
): HealthConfig | undefined {
|
||||
if (health === undefined || health === false) return undefined;
|
||||
if (health === true) return { drainDelayMs: 0 };
|
||||
|
||||
if (typeof health !== 'object' || health === null || Array.isArray(health)) {
|
||||
throw new Error(`health must be true, false or { drainDelayMs?: number } — got ${JSON.stringify(health)}`);
|
||||
}
|
||||
|
||||
const unknown = Object.keys(health).filter((key) => key !== 'drainDelayMs');
|
||||
|
||||
if (unknown.length) {
|
||||
throw new Error(
|
||||
`health: unknown option ${unknown.map((key) => `'${key}'`).join(', ')} — only drainDelayMs is supported`,
|
||||
);
|
||||
}
|
||||
|
||||
const drainDelayMs = (health as { drainDelayMs?: unknown }).drainDelayMs ?? 0;
|
||||
|
||||
if (typeof drainDelayMs !== 'number' || !Number.isFinite(drainDelayMs) || drainDelayMs < 0) {
|
||||
throw new Error(`health.drainDelayMs must be a non-negative number of milliseconds — got ${String(drainDelayMs)}`);
|
||||
}
|
||||
|
||||
const budget = shutdownTimeoutMs ?? 10_000;
|
||||
const reserved = teardownTimeoutMs ?? 0;
|
||||
|
||||
if (drainDelayMs + reserved > budget) {
|
||||
throw new Error(
|
||||
`health.drainDelayMs (${drainDelayMs}) plus teardownTimeoutMs (${reserved}) cannot exceed ` +
|
||||
`shutdownTimeoutMs (${budget}) — the drain window is spent out of the shutdown budget, ` +
|
||||
'so close() would have no time left to drain connections or run teardown.',
|
||||
);
|
||||
}
|
||||
|
||||
return { drainDelayMs };
|
||||
}
|
||||
|
||||
/**
|
||||
* The health state machine for one app: wraps `bootGraph` so a resolved boot marks it ready, and
|
||||
* offers the drain that `close()` (and `serveDeno`/`serveBun` through {@link HEALTH_DRAIN}) starts.
|
||||
* With health off the probe is absent and the drain resolves at once.
|
||||
*/
|
||||
export function trackHealth(
|
||||
health: HealthConfig | undefined,
|
||||
bootGraph: () => Promise<void>,
|
||||
degraded: () => string[],
|
||||
): { bootApp: () => Promise<void>; healthProbe: HealthProbe | undefined; drain: () => Promise<void> } {
|
||||
// Forward only: a boot that resolves after close() started stays draining.
|
||||
let phase: HealthPhase = 'booting';
|
||||
// Shared by every drain call. Left referenced on purpose: the process must stay up for the window.
|
||||
let drainWindow: Promise<void> | undefined;
|
||||
|
||||
const bootApp = async (): Promise<void> => {
|
||||
await bootGraph();
|
||||
if (phase === 'booting') phase = 'ready';
|
||||
};
|
||||
|
||||
const drain = (): Promise<void> => {
|
||||
if (!health) return Promise.resolve();
|
||||
|
||||
if (!drainWindow) {
|
||||
phase = 'draining';
|
||||
const ms = health.drainDelayMs;
|
||||
drainWindow = ms > 0 ? new Promise((resolve) => setTimeout(resolve, ms)) : Promise.resolve();
|
||||
}
|
||||
|
||||
return drainWindow;
|
||||
};
|
||||
|
||||
return { bootApp, healthProbe: health ? { phase: () => phase, degraded } : undefined, drain };
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// src/http/peer.ts — the socket peer address, handed from the Deno and Bun adapters to `buildFetch`.
|
||||
// Internal: not exported from the package.
|
||||
//
|
||||
// Keyed by the `Request` object rather than carried on it. A header would be visible to handlers and
|
||||
// spoofable by any client that sent one with the same name; a second `fetch` parameter would be
|
||||
// public API. The adapters call `app.fetch` with the very object they record, so identity holds, and
|
||||
// the entry goes when the request does. A `Request` copied from it carries nothing, which is what a
|
||||
// bare `app.fetch` from user code has always seen.
|
||||
//
|
||||
// The map lives on `globalThis` under a registered symbol, not in this module, because this module
|
||||
// is not always one instance. The CommonJS build bundles `index`, `deno` and `bun` as separate files
|
||||
// with no shared chunk, so each carries its own copy of this one: a module-private map in
|
||||
// `@green-tea/core/bun` would record peers that `app.fetch` from `@green-tea/core` never sees. An app
|
||||
// that loads core both as ESM and as CommonJS has the same split.
|
||||
//
|
||||
// Bun records its server rather than an address. `server.requestIP()` is a native call that builds
|
||||
// an object, and making it on every request measured 7–11% on Bun; recording the server is free, and
|
||||
// the address is asked for only when something reads `ctx.ip`. Deno hands the address over already
|
||||
// resolved, so it records the string.
|
||||
const KEY = Symbol.for('@green-tea/core:peer');
|
||||
|
||||
/** Names a request's socket peer on demand: Bun's server. */
|
||||
export interface PeerSource {
|
||||
requestIP(request: Request): { address: string } | null;
|
||||
}
|
||||
|
||||
const registry = globalThis as { [KEY]?: WeakMap<Request, string | PeerSource> };
|
||||
const peers = (registry[KEY] ??= new WeakMap<Request, string | PeerSource>());
|
||||
|
||||
/** Records the peer of `request`. An empty address — a unix socket has none — is not recorded. */
|
||||
export function setPeer(request: Request, peer: string | PeerSource): void {
|
||||
if (peer) peers.set(request, peer);
|
||||
}
|
||||
|
||||
/** The peer an adapter recorded for `request`, or `''` when none did. */
|
||||
export function peerOf(request: Request): string {
|
||||
const peer = peers.get(request);
|
||||
return typeof peer === 'object' ? (peer.requestIP(request)?.address ?? '') : (peer ?? '');
|
||||
}
|
||||
|
||||
// The client address a runtime adapter read from a header its platform's proxy sets — today only the
|
||||
// edge adapter, from `cf-connecting-ip`. Unlike the socket peer above, a header is client-supplied
|
||||
// unless a proxy in front overwrites it, so it only counts under `trustProxy`; the adapter cannot
|
||||
// decide that, because the option lives on the app, so it records the value and the app decides.
|
||||
// Keyed by the `Request` (HTTP) or the `WsRequest` (WebSocket upgrade) the adapter hands the app, for
|
||||
// the same reasons as the peer: no handler-visible header, no extra public parameter. Same
|
||||
// `globalThis` registration, because `@green-tea/core/edge` is a separate bundle too.
|
||||
const PROXY_KEY = Symbol.for('@green-tea/core:proxy-client');
|
||||
const proxyRegistry = globalThis as { [PROXY_KEY]?: WeakMap<object, string> };
|
||||
const proxyClients = (proxyRegistry[PROXY_KEY] ??= new WeakMap<object, string>());
|
||||
|
||||
/** Records `ip` as the client address a proxy header named for `source`. An empty value is not recorded. */
|
||||
export function setProxyClient(source: object, ip: string): void {
|
||||
if (ip) proxyClients.set(source, ip);
|
||||
}
|
||||
|
||||
/**
|
||||
* The client address an adapter recorded for `source` from a proxy header, when `trustProxy` is on;
|
||||
* `''` otherwise. The one check both `app.fetch` and `app.upgrade` run, so HTTP and WebSocket cannot
|
||||
* disagree about whether the header counts.
|
||||
*/
|
||||
export function trustedProxyClient(source: object, trustProxy: boolean | undefined): string {
|
||||
return trustProxy ? (proxyClients.get(source) ?? '') : '';
|
||||
}
|
||||
+57
-6
@@ -1,18 +1,69 @@
|
||||
import type http from 'http';
|
||||
import { HttpError } from '../signals';
|
||||
import { declaresOverLimit } from './body';
|
||||
|
||||
/** 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> {
|
||||
export function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise<Buffer | undefined> {
|
||||
// A declared length over the limit is refused without waiting for the first chunk, which could
|
||||
// otherwise sit until the request timeout. The fetch adapter makes the same check.
|
||||
const contentLength = req.headers['content-length'];
|
||||
if (declaresOverLimit(contentLength, maxBodyBytes)) return Promise.reject(new HttpError(413, 'Payload Too Large'));
|
||||
|
||||
// No `Transfer-Encoding` and no (or a zero) `Content-Length` is a request without a body (RFC 9112
|
||||
// §6.3) — every GET. Node's parser has already finished it, so there is nothing to wait for, and
|
||||
// subscribing to the stream anyway measured ~4% on an 8 KB GET response. Node drains the unread
|
||||
// request itself when the response ends.
|
||||
if (req.headers['transfer-encoding'] === undefined && (contentLength === undefined || contentLength === '0'))
|
||||
return Promise.resolve(undefined);
|
||||
|
||||
// Listeners rather than `for await`: the async iterator costs a promise and a microtask per chunk,
|
||||
// which a JSON POST pays on every request. The semantics are the iterator's: the running total
|
||||
// still enforces the limit, an over-limit body destroys the request as leaving the loop did, and a
|
||||
// stream that errors or closes before `end` rejects.
|
||||
return new Promise<Buffer | undefined>((resolve, reject) => {
|
||||
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);
|
||||
const settle = (): void => {
|
||||
req.off('data', onData);
|
||||
req.off('end', onEnd);
|
||||
req.off('error', onError);
|
||||
req.off('close', onClose);
|
||||
};
|
||||
|
||||
const onData = (chunk: Buffer): void => {
|
||||
total += chunk.length;
|
||||
|
||||
if (total <= maxBodyBytes) {
|
||||
chunks.push(chunk);
|
||||
return;
|
||||
}
|
||||
|
||||
return chunks.length === 0 ? undefined : Buffer.concat(chunks);
|
||||
settle();
|
||||
req.destroy();
|
||||
reject(new HttpError(413, 'Payload Too Large'));
|
||||
};
|
||||
|
||||
const onEnd = (): void => {
|
||||
settle();
|
||||
resolve(chunks.length === 0 ? undefined : chunks.length === 1 ? chunks[0] : Buffer.concat(chunks));
|
||||
};
|
||||
|
||||
const onError = (err: Error): void => {
|
||||
settle();
|
||||
reject(err);
|
||||
};
|
||||
|
||||
const onClose = (): void => {
|
||||
settle();
|
||||
reject(Object.assign(new Error('Premature close'), { code: 'ERR_STREAM_PREMATURE_CLOSE' }));
|
||||
};
|
||||
|
||||
req.on('data', onData);
|
||||
req.on('end', onEnd);
|
||||
req.on('error', onError);
|
||||
req.on('close', onClose);
|
||||
});
|
||||
}
|
||||
|
||||
/** Returns the first comma-separated token of a header value (handles array-valued headers). */
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { compilePattern, matchPattern } from './router';
|
||||
|
||||
/**
|
||||
* A path the framework answers itself, ahead of the route table, so no declared route may claim it.
|
||||
*
|
||||
* Each adapter intercepts these before route matching. A user route that could also match one would
|
||||
* be served on some code paths and shadowed on others, which is exactly the "works on Node, refused
|
||||
* on Deno" split a reserved path exists to prevent, so the boot refuses it instead.
|
||||
*/
|
||||
export interface ReservedPath {
|
||||
/** The concrete request path, e.g. `/__mesh__/control`. */
|
||||
path: string;
|
||||
/** What the framework serves there, for the error message (e.g. `the mesh control channel`). */
|
||||
purpose: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the reserved path `pattern` would claim, or `undefined` when it claims none.
|
||||
*
|
||||
* A pattern claims a reserved path when it matches it *and* its first segment is the reserved path's
|
||||
* own first segment, spelled literally. The literal-prefix half is deliberate: `/:org/:repo` or a
|
||||
* `/:rest*` fallback also match `/__mesh__/control`, but they never ask for it — the adapter intercepts
|
||||
* the reserved path before matching, so such a route simply never sees that one path, the same way
|
||||
* on every runtime. Refusing them would fail the boot of ordinary apps for a path they never named.
|
||||
* A literal pattern is therefore checked by equality and a parameterised one (`/__mesh__/:x`,
|
||||
* `/__mesh__/:rest*`) by matching the reserved path against it.
|
||||
*/
|
||||
export function claimedReservedPath(pattern: string, reserved: readonly ReservedPath[]): ReservedPath | undefined {
|
||||
const first = compilePattern(pattern).segments[0];
|
||||
if (first?.kind !== 'static') return undefined;
|
||||
|
||||
return reserved.find(
|
||||
(entry) => entry.path.split('/')[1] === first.value && matchPattern(pattern, entry.path) !== undefined,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Throws when `pattern` claims a reserved path. `subject` names the declaration for the message,
|
||||
* e.g. `route GET /__mesh__/control at Chat.control`.
|
||||
*/
|
||||
export function assertNotReserved(pattern: string, subject: string, reserved: readonly ReservedPath[]): void {
|
||||
const claimed = claimedReservedPath(pattern, reserved);
|
||||
if (!claimed) return;
|
||||
|
||||
throw new Error(
|
||||
`${subject} uses the reserved path ${claimed.path} (${claimed.purpose}) — ` +
|
||||
'green-tea answers that path itself on every runtime, so no route may declare it. Move the route.',
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,814 @@
|
||||
/**
|
||||
* Boot-time detection of route params that can never be reached, or that tie with a sibling
|
||||
* (FPRD-001 CARD-13, #127).
|
||||
*
|
||||
* `assertSafeConstraint` admits only a linear, group-free regex subset, so every constraint reads back
|
||||
* as a sequence of blocks — (set of characters, min, max). Intersection and the "accepts every segment"
|
||||
* question are then decided exactly, from the sets and counts, with no pattern lists and no sampling:
|
||||
*
|
||||
* - {@link intersectionWitness} walks the product of two block sequences and returns a segment both
|
||||
* accept, or proves there is none.
|
||||
* - {@link acceptsEverySegment} is a closed-form test on the blocks; the proof is in its comment.
|
||||
*
|
||||
* The universe is what the router can actually hand a param: a *decoded*, non-empty path segment —
|
||||
* any Unicode scalar value, `/` included (from `%2F`) — except `.` and `..`, which normalization
|
||||
* resolves away before matching. Everything here is measured against that universe, so a witness is a
|
||||
* segment a real request can carry.
|
||||
*
|
||||
* Nothing here runs per request. The lookup path does not import this module.
|
||||
*/
|
||||
import { CONSTRAINT_ATOM, CONSTRAINT_QUANTIFIER } from './router';
|
||||
import type { CompiledPattern, CompiledSegment } from './router';
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Character sets: sorted, disjoint, non-adjacent inclusive ranges, flattened [lo0, hi0, lo1, hi1, …].
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/** A set of Unicode scalar values. */
|
||||
export type CharSet = readonly number[];
|
||||
|
||||
const MAX_CODE_POINT = 0x10ffff;
|
||||
const DOT = 0x2e;
|
||||
|
||||
/** Every Unicode scalar value: what a decoded segment can contain. Lone surrogates fail `decodeURIComponent`. */
|
||||
const SIGMA: CharSet = [0, 0xd7ff, 0xe000, MAX_CODE_POINT];
|
||||
|
||||
function fromRanges(ranges: Array<[number, number]>): CharSet {
|
||||
const sorted = ranges.filter(([lo, hi]) => lo <= hi).sort((a, b) => a[0] - b[0]);
|
||||
const out: number[] = [];
|
||||
|
||||
for (const [lo, hi] of sorted) {
|
||||
const last = out.length - 1;
|
||||
if (last > 0 && lo <= out[last] + 1) out[last] = Math.max(out[last], hi);
|
||||
else out.push(lo, hi);
|
||||
}
|
||||
|
||||
return intersect(out, SIGMA);
|
||||
}
|
||||
|
||||
function intersect(a: CharSet, b: CharSet): CharSet {
|
||||
const out: number[] = [];
|
||||
let i = 0;
|
||||
let j = 0;
|
||||
|
||||
while (i < a.length && j < b.length) {
|
||||
const lo = Math.max(a[i], b[j]);
|
||||
const hi = Math.min(a[i + 1], b[j + 1]);
|
||||
if (lo <= hi) out.push(lo, hi);
|
||||
if (a[i + 1] < b[j + 1]) i += 2;
|
||||
else j += 2;
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Σ minus `set`. */
|
||||
function complement(set: CharSet): CharSet {
|
||||
const out: number[] = [];
|
||||
let next = 0;
|
||||
|
||||
for (let i = 0; i < set.length; i += 2) {
|
||||
if (set[i] > next) out.push(next, set[i] - 1);
|
||||
next = set[i + 1] + 1;
|
||||
}
|
||||
|
||||
if (next <= MAX_CODE_POINT) out.push(next, MAX_CODE_POINT);
|
||||
return intersect(out, SIGMA);
|
||||
}
|
||||
|
||||
function has(set: CharSet, cp: number): boolean {
|
||||
for (let i = 0; i < set.length; i += 2) if (cp >= set[i] && cp <= set[i + 1]) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
const isEmptySet = (set: CharSet): boolean => set.length === 0;
|
||||
const isSigma = (set: CharSet): boolean => set.length === SIGMA.length && set.every((v, i) => v === SIGMA[i]);
|
||||
|
||||
/** Readable witness characters first: digits, lowercase, uppercase, then printable ASCII. */
|
||||
const PREFERRED: Array<[number, number]> = [
|
||||
[0x30, 0x39],
|
||||
[0x61, 0x7a],
|
||||
[0x41, 0x5a],
|
||||
[0x21, 0x7e],
|
||||
];
|
||||
|
||||
/** Picks one member of a non-empty set, preferring a character a person can read in an error message. */
|
||||
function pick(set: CharSet): number {
|
||||
for (const [lo, hi] of PREFERRED) {
|
||||
const within = intersect(set, [lo, hi]);
|
||||
if (within.length) return within[0];
|
||||
}
|
||||
|
||||
return set[0];
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Atoms → character sets, with the semantics of a `u`-flag RegExp (no `i`, no `s`).
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
const DIGIT: CharSet = [0x30, 0x39];
|
||||
const WORD: CharSet = [0x30, 0x39, 0x41, 0x5a, 0x5f, 0x5f, 0x61, 0x7a];
|
||||
/** ECMAScript WhiteSpace ∪ LineTerminator, which is what `\s` matches. */
|
||||
const SPACE: CharSet = fromRanges([
|
||||
[0x09, 0x0d],
|
||||
[0x20, 0x20],
|
||||
[0xa0, 0xa0],
|
||||
[0x1680, 0x1680],
|
||||
[0x2000, 0x200a],
|
||||
[0x2028, 0x2029],
|
||||
[0x202f, 0x202f],
|
||||
[0x205f, 0x205f],
|
||||
[0x3000, 0x3000],
|
||||
[0xfeff, 0xfeff],
|
||||
]);
|
||||
/** Unescaped `.` without the `s` flag: anything but a line terminator. */
|
||||
const ANY_BUT_LINE_TERMINATOR: CharSet = complement(
|
||||
fromRanges([
|
||||
[0x0a, 0x0a],
|
||||
[0x0d, 0x0d],
|
||||
[0x2028, 0x2029],
|
||||
]),
|
||||
);
|
||||
|
||||
const CLASS_ESCAPES: Record<string, CharSet> = {
|
||||
d: DIGIT,
|
||||
D: complement(DIGIT),
|
||||
w: WORD,
|
||||
W: complement(WORD),
|
||||
s: SPACE,
|
||||
S: complement(SPACE),
|
||||
};
|
||||
|
||||
const CONTROL_ESCAPES: Record<string, number> = { b: 0x08, f: 0x0c, n: 0x0a, r: 0x0d, t: 0x09, v: 0x0b };
|
||||
const IDENTITY_ESCAPES = new Set('^$\\.*+?()[]{}|/-');
|
||||
|
||||
/** One parsed class atom: a single code point (a valid range end) or a class escape such as `\d`. */
|
||||
type ClassAtom = { cp: number; end: number } | { set: CharSet; end: number };
|
||||
|
||||
/** Signals a construct this reader does not model; the caller then asks the RegExp engine directly. */
|
||||
class Unmodelled extends Error {}
|
||||
|
||||
function hexAt(source: string, start: number, length: number): number {
|
||||
const text = source.slice(start, start + length);
|
||||
if (!/^[0-9a-fA-F]+$/.test(text) || text.length !== length) throw new Unmodelled();
|
||||
return parseInt(text, 16);
|
||||
}
|
||||
|
||||
/** Reads `\u…` (four hex digits, a surrogate pair of two, or `\u{…}`) starting after the `u`. */
|
||||
function unicodeEscape(source: string, at: number): { cp: number; end: number } {
|
||||
if (source[at] === '{') {
|
||||
const close = source.indexOf('}', at);
|
||||
if (close < 0) throw new Unmodelled();
|
||||
return { cp: hexAt(source, at + 1, close - at - 1), end: close + 1 };
|
||||
}
|
||||
|
||||
const cp = hexAt(source, at, 4);
|
||||
const isLead = cp >= 0xd800 && cp <= 0xdbff;
|
||||
|
||||
if (isLead && source.startsWith('\\u', at + 4)) {
|
||||
const trail = hexAt(source, at + 6, 4);
|
||||
if (trail >= 0xdc00 && trail <= 0xdfff)
|
||||
return { cp: (cp - 0xd800) * 0x400 + (trail - 0xdc00) + 0x10000, end: at + 10 };
|
||||
}
|
||||
|
||||
return { cp, end: at + 4 };
|
||||
}
|
||||
|
||||
/** Reads the escape whose backslash is at `at - 1`, inside a class. */
|
||||
function classEscape(source: string, at: number): ClassAtom {
|
||||
const c = source[at];
|
||||
if (CLASS_ESCAPES[c]) return { set: CLASS_ESCAPES[c], end: at + 1 };
|
||||
if (c in CONTROL_ESCAPES) return { cp: CONTROL_ESCAPES[c], end: at + 1 };
|
||||
if (IDENTITY_ESCAPES.has(c)) return { cp: c.charCodeAt(0), end: at + 1 };
|
||||
if (c === '0' && !/[0-9]/.test(source[at + 1] ?? '')) return { cp: 0, end: at + 1 };
|
||||
if (c === 'c' && /[A-Za-z]/.test(source[at + 1] ?? '')) return { cp: source.charCodeAt(at + 1) % 32, end: at + 2 };
|
||||
if (c === 'x') return { cp: hexAt(source, at + 1, 2), end: at + 3 };
|
||||
if (c === 'u') return unicodeEscape(source, at + 1);
|
||||
// `\p{…}` / `\P{…}` need Unicode property tables; anything else would not have compiled.
|
||||
throw new Unmodelled();
|
||||
}
|
||||
|
||||
function classAtom(source: string, at: number): ClassAtom {
|
||||
if (source[at] === '\\') return classEscape(source, at + 1);
|
||||
const cp = source.codePointAt(at)!;
|
||||
return { cp, end: at + (cp > 0xffff ? 2 : 1) };
|
||||
}
|
||||
|
||||
/** Parses the body of a `[...]` class (between the brackets) in `u` mode. */
|
||||
function classSet(body: string): CharSet {
|
||||
const negated = body.startsWith('^');
|
||||
const ranges: Array<[number, number]> = [];
|
||||
const sets: CharSet[] = [];
|
||||
let at = negated ? 1 : 0;
|
||||
|
||||
while (at < body.length) {
|
||||
const first = classAtom(body, at);
|
||||
at = first.end;
|
||||
|
||||
// `a-z`: a dash between two single characters. A dash first, last, or next to a class escape is
|
||||
// literal — and in `u` mode a class escape next to a range dash does not compile at all.
|
||||
if (body[at] === '-' && at + 1 < body.length && 'cp' in first) {
|
||||
const last = classAtom(body, at + 1);
|
||||
if (!('cp' in last)) throw new Unmodelled();
|
||||
ranges.push([first.cp, last.cp]);
|
||||
at = last.end;
|
||||
continue;
|
||||
}
|
||||
|
||||
if ('cp' in first) ranges.push([first.cp, first.cp]);
|
||||
else sets.push(first.set);
|
||||
}
|
||||
|
||||
const union = fromRanges([...ranges, ...sets.flatMap((set) => pairs(set))]);
|
||||
return negated ? complement(union) : union;
|
||||
}
|
||||
|
||||
function pairs(set: CharSet): Array<[number, number]> {
|
||||
const out: Array<[number, number]> = [];
|
||||
for (let i = 0; i < set.length; i += 2) out.push([set[i], set[i + 1]]);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The engine's own answer, one code point at a time. Only for constructs {@link classSet} does not model. */
|
||||
function enumerateSet(atom: string): CharSet {
|
||||
const test = new RegExp(`^${atom}$`, 'u');
|
||||
const ranges: Array<[number, number]> = [];
|
||||
let start = -1;
|
||||
|
||||
for (let cp = 0; cp <= MAX_CODE_POINT + 1; cp++) {
|
||||
const inside = cp <= MAX_CODE_POINT && (cp < 0xd800 || cp > 0xdfff) && test.test(String.fromCodePoint(cp));
|
||||
if (inside && start < 0) start = cp;
|
||||
|
||||
if (!inside && start >= 0) {
|
||||
ranges.push([start, cp - 1]);
|
||||
start = -1;
|
||||
}
|
||||
}
|
||||
|
||||
return fromRanges(ranges);
|
||||
}
|
||||
|
||||
/** The set of characters one atom of the safe subset matches. */
|
||||
export function atomSet(atom: string): CharSet {
|
||||
if (atom === '.') return ANY_BUT_LINE_TERMINATOR;
|
||||
if (atom.length === 1) return [atom.charCodeAt(0), atom.charCodeAt(0)];
|
||||
if (atom[0] === '\\' && CLASS_ESCAPES[atom[1]]) return CLASS_ESCAPES[atom[1]];
|
||||
if (atom[0] === '\\') return [atom.charCodeAt(1), atom.charCodeAt(1)];
|
||||
|
||||
try {
|
||||
return classSet(atom.slice(1, -1));
|
||||
} catch (error) {
|
||||
if (!(error instanceof Unmodelled)) throw error;
|
||||
return enumerateSet(atom);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Constraints → block sequences.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/** `set` repeated between `min` and `max` times; `max` is `Infinity` for `+`, `*` and `{n,}`. */
|
||||
export interface Block {
|
||||
set: CharSet;
|
||||
min: number;
|
||||
max: number;
|
||||
}
|
||||
|
||||
function bounds(quantifier: string): { min: number; max: number } {
|
||||
if (quantifier === '') return { min: 1, max: 1 };
|
||||
if (quantifier === '?') return { min: 0, max: 1 };
|
||||
if (quantifier === '*') return { min: 0, max: Infinity };
|
||||
if (quantifier === '+') return { min: 1, max: Infinity };
|
||||
const [minText, maxText] = quantifier.slice(1, -1).split(',');
|
||||
const min = Number(minText);
|
||||
if (maxText === undefined) return { min, max: min };
|
||||
return { min, max: maxText === '' ? Infinity : Number(maxText) };
|
||||
}
|
||||
|
||||
const chainCache = new Map<string, Block[]>();
|
||||
|
||||
/** Reads a constraint that `compilePattern` already accepted back as its sequence of blocks. */
|
||||
export function constraintBlocks(source: string): Block[] {
|
||||
const cached = chainCache.get(source);
|
||||
if (cached) return cached;
|
||||
|
||||
const blocks: Block[] = [];
|
||||
let offset = 0;
|
||||
|
||||
while (offset < source.length) {
|
||||
const rest = source.slice(offset);
|
||||
const atom = CONSTRAINT_ATOM.exec(rest)![0];
|
||||
const quantifier = CONSTRAINT_QUANTIFIER.exec(rest.slice(atom.length))?.[0] ?? '';
|
||||
blocks.push({ set: atomSet(atom), ...bounds(quantifier) });
|
||||
offset += atom.length + quantifier.length;
|
||||
}
|
||||
|
||||
chainCache.set(source, blocks);
|
||||
return blocks;
|
||||
}
|
||||
|
||||
/** What a plain `:param` accepts: any non-empty segment. */
|
||||
const ANY_SEGMENT: Block[] = [{ set: SIGMA, min: 1, max: Infinity }];
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Universality.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Whether a block sequence accepts every segment a request can carry.
|
||||
*
|
||||
* True exactly when (1) some block is Σ with no upper bound, (2) every block with `min ≥ 1` is Σ, and
|
||||
* (3) the mins add up to at most 1. Sufficient: skip every optional block, and the unbounded Σ block
|
||||
* takes whatever the mandatory ones leave over. Necessary, each against a segment in the universe:
|
||||
* (3) fails on `a`, too short; (2) fails on `zzz…`, with `z` outside the mandatory block's set; and
|
||||
* without (1), take `zⱼ` outside each unbounded block's set and repeat the round `z₁…zₜ` more times
|
||||
* than the bounded blocks' total capacity plus `t`. Blocks are consumed in order, so some round
|
||||
* lands wholly inside one unbounded block, which cannot hold its own `zⱼ`.
|
||||
*
|
||||
* Excluding `.` and `..` from the universe changes nothing: every counterexample above is longer or
|
||||
* is `a`.
|
||||
*/
|
||||
export function acceptsEverySegment(blocks: Block[]): boolean {
|
||||
const unboundedSigma = blocks.some((block) => block.max === Infinity && isSigma(block.set));
|
||||
const mandatoryAreSigma = blocks.every((block) => block.min === 0 || isSigma(block.set));
|
||||
const minLength = blocks.reduce((sum, block) => sum + block.min, 0);
|
||||
return unboundedSigma && mandatoryAreSigma && minLength <= 1;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Intersection with a witness.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/** Entry `i`: every block after block `i` is optional, so the sequence may stop once block `i` is done. */
|
||||
function endsAfter(blocks: Block[]): boolean[] {
|
||||
const out = new Array<boolean>(blocks.length);
|
||||
let optionalTail = true;
|
||||
|
||||
for (let i = blocks.length - 1; i >= 0; i--) {
|
||||
out[i] = optionalTail;
|
||||
optionalTail &&= blocks[i].min === 0;
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The reachable configurations on entry to one pair of blocks (`a` in sequence A, `b` in sequence B).
|
||||
*
|
||||
* `fresh` names the side that has just entered its block and has consumed nothing in it yet; the
|
||||
* other side, the carry, has already consumed `value` characters of its block. Both fresh is `fresh
|
||||
* = 'a'` with `value = 0`. Unbounded blocks clamp the counter at their `min`, since every count past
|
||||
* it behaves the same, so `value` never exceeds the carry block's `max`, or its `min` when unbounded.
|
||||
*
|
||||
* `dotsOnly` stays true while every character so far is `.`: a witness must not be `.` or `..`.
|
||||
*/
|
||||
interface EntryState {
|
||||
a: number;
|
||||
b: number;
|
||||
fresh: 'a' | 'b';
|
||||
dotsOnly: boolean;
|
||||
reached: Uint8Array;
|
||||
/** Union-find "next unreached value", so each value is filled once however many predecessors reach it. */
|
||||
free: Int32Array;
|
||||
prev: Array<EntryState | undefined>;
|
||||
prevValue: Int32Array;
|
||||
runChar: Int32Array;
|
||||
runLength: Int32Array;
|
||||
}
|
||||
|
||||
/** How a state was reached: from `(from, value)` by a run of `char`, at least `tLo` long. */
|
||||
interface Run {
|
||||
from: EntryState | undefined;
|
||||
value: number;
|
||||
char: number;
|
||||
tLo: number;
|
||||
}
|
||||
|
||||
/** Who is fresh in the next state: both sides, the same side as now, or the side that was the carry. */
|
||||
type NextFresh = 'both' | 'same' | 'flip';
|
||||
|
||||
const counterCap = (block: Block): number => (block.max === Infinity ? block.min : block.max);
|
||||
const clampTo = (block: Block, count: number): number => (block.max === Infinity ? Math.min(count, block.min) : count);
|
||||
|
||||
function findFree(state: EntryState, x: number): number {
|
||||
while (state.free[x] !== x) x = state.free[x] = state.free[state.free[x]];
|
||||
return x;
|
||||
}
|
||||
|
||||
class ProductWalk {
|
||||
private readonly states = new Map<string, EntryState>();
|
||||
private readonly endA: boolean[];
|
||||
private readonly endB: boolean[];
|
||||
|
||||
constructor(
|
||||
private readonly A: Block[],
|
||||
private readonly B: Block[],
|
||||
) {
|
||||
this.endA = endsAfter(A);
|
||||
this.endB = endsAfter(B);
|
||||
}
|
||||
|
||||
/** Returns a non-empty string in both languages that is neither `.` nor `..`, or `undefined` if none exists. */
|
||||
witness(): string | undefined {
|
||||
this.fill(this.state(0, 0, 'a', true), 0, 0, { from: undefined, value: 0, char: 0, tLo: 0 }, 0);
|
||||
|
||||
// Every transition moves to a later `a`, or to the same `a` and a later `b`, so visiting pairs in
|
||||
// that order sees each state after everything that reaches it.
|
||||
for (let a = 0; a < this.A.length; a++)
|
||||
for (let b = 0; b < this.B.length; b++)
|
||||
for (const key of [`${a},${b},a,1`, `${a},${b},a,0`, `${a},${b},b,1`, `${a},${b},b,0`]) {
|
||||
const state = this.states.get(key);
|
||||
const found = state && this.expand(state);
|
||||
if (found !== undefined) return found;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private state(a: number, b: number, fresh: 'a' | 'b', dotsOnly: boolean): EntryState {
|
||||
const key = `${a},${b},${fresh},${dotsOnly ? 1 : 0}`;
|
||||
let state = this.states.get(key);
|
||||
|
||||
if (!state) {
|
||||
const size = counterCap(fresh === 'a' ? this.B[b] : this.A[a]) + 1;
|
||||
state = {
|
||||
a,
|
||||
b,
|
||||
fresh,
|
||||
dotsOnly,
|
||||
reached: new Uint8Array(size),
|
||||
free: new Int32Array(size + 1).map((_, i) => i),
|
||||
prev: new Array(size),
|
||||
prevValue: new Int32Array(size),
|
||||
runChar: new Int32Array(size),
|
||||
runLength: new Int32Array(size),
|
||||
};
|
||||
this.states.set(key, state);
|
||||
}
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
/** Marks `[lo, hi]` reached in `target`; value `w` came by a run of length `max(tLo, w - offset)`. */
|
||||
private fill(target: EntryState, lo: number, hi: number, run: Run, offset: number): void {
|
||||
for (let w = findFree(target, lo); w <= hi; w = findFree(target, w + 1)) {
|
||||
target.reached[w] = 1;
|
||||
target.prev[w] = run.from;
|
||||
target.prevValue[w] = run.value;
|
||||
target.runChar[w] = run.char;
|
||||
target.runLength[w] = Math.max(run.tLo, w - offset);
|
||||
target.free[w] = w + 1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The state after one or both sides move to their next block, from the current fresh side's point
|
||||
* of view: `freshAt` is the fresh side's block index, `carryAt` the carry side's. `undefined` when
|
||||
* a side would run past its last block.
|
||||
*/
|
||||
private next(state: EntryState, freshAt: number, carryAt: number, mode: NextFresh, dotsOnly: boolean) {
|
||||
const freshIsA = state.fresh === 'a';
|
||||
const [a, b] = freshIsA ? [freshAt, carryAt] : [carryAt, freshAt];
|
||||
if (a >= this.A.length || b >= this.B.length) return undefined;
|
||||
const nextFreshIsA = mode === 'both' || (mode === 'same' ? freshIsA : !freshIsA);
|
||||
return this.state(a, b, nextFreshIsA ? 'a' : 'b', dotsOnly);
|
||||
}
|
||||
|
||||
/** Follows every move out of one entry state. Returns a witness as soon as one completes. */
|
||||
private expand(state: EntryState): string | undefined {
|
||||
this.skip(state);
|
||||
const shared = intersect(this.A[state.a].set, this.B[state.b].set);
|
||||
if (isEmptySet(shared)) return undefined;
|
||||
|
||||
const notDot = intersect(shared, complement([DOT, DOT]));
|
||||
const char = isEmptySet(notDot) ? DOT : pick(notDot);
|
||||
const dotsOnly = state.dotsOnly && char === DOT;
|
||||
|
||||
for (let value = 0; value < state.reached.length; value++) {
|
||||
if (!state.reached[value]) continue;
|
||||
const found = this.runFrom(state, value, char, dotsOnly);
|
||||
if (found !== undefined) return found;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zero-length moves past optional blocks. The fresh side may skip a `min = 0` block it has not
|
||||
* started, keeping the carry's count; a carry still at 0 in a `min = 0` block may skip it too.
|
||||
* Skipping one block at a time keeps every value's moves O(1); runs of optional blocks chain.
|
||||
*/
|
||||
private skip(state: EntryState): void {
|
||||
const freshIsA = state.fresh === 'a';
|
||||
const [freshAt, carryAt] = freshIsA ? [state.a, state.b] : [state.b, state.a];
|
||||
const fresh = freshIsA ? this.A[state.a] : this.B[state.b];
|
||||
const carry = freshIsA ? this.B[state.b] : this.A[state.a];
|
||||
const keep = (value: number): Run => ({ from: state, value, char: 0, tLo: 0 });
|
||||
const freshSkip = fresh.min === 0 ? this.next(state, freshAt + 1, carryAt, 'same', state.dotsOnly) : undefined;
|
||||
|
||||
for (let value = 0; freshSkip && value < state.reached.length; value++)
|
||||
if (state.reached[value]) this.fill(freshSkip, value, value, keep(value), value);
|
||||
|
||||
const carrySkip =
|
||||
carry.min === 0 && state.reached[0] && this.next(state, freshAt, carryAt + 1, 'same', state.dotsOnly);
|
||||
if (carrySkip) this.fill(carrySkip, 0, 0, keep(0), 0);
|
||||
}
|
||||
|
||||
/** A run of `t ≥ 1` copies of `char` in the current pair, then one or both sides leave their block. */
|
||||
private runFrom(state: EntryState, value: number, char: number, dotsOnly: boolean): string | undefined {
|
||||
const freshIsA = state.fresh === 'a';
|
||||
const [freshAt, carryAt] = freshIsA ? [state.a, state.b] : [state.b, state.a];
|
||||
const fresh = freshIsA ? this.A[state.a] : this.B[state.b];
|
||||
const carry = freshIsA ? this.B[state.b] : this.A[state.a];
|
||||
const tHi = Math.min(fresh.max, carry.max - value);
|
||||
if (tHi < 1) return undefined;
|
||||
|
||||
// Both leave: the run completes both blocks at once — and may complete the whole string.
|
||||
const bothLo = Math.max(1, fresh.min, carry.min - value);
|
||||
|
||||
if (bothLo <= tHi) {
|
||||
if (!dotsOnly && this.endA[state.a] && this.endB[state.b]) return this.trace(state, value, char, bothLo);
|
||||
const target = this.next(state, freshAt + 1, carryAt + 1, 'both', dotsOnly);
|
||||
if (target) this.fill(target, 0, 0, { from: state, value, char, tLo: bothLo }, 0);
|
||||
}
|
||||
|
||||
// The fresh side leaves; the carry stays in its block, `t` characters further on.
|
||||
const freshLo = Math.max(1, fresh.min);
|
||||
const same = freshLo <= tHi && this.next(state, freshAt + 1, carryAt, 'same', dotsOnly);
|
||||
if (same)
|
||||
this.fill(
|
||||
same,
|
||||
clampTo(carry, value + freshLo),
|
||||
clampTo(carry, value + tHi),
|
||||
{ from: state, value, char, tLo: freshLo },
|
||||
value,
|
||||
);
|
||||
|
||||
// The carry leaves; the fresh side stays, `t` characters in, and becomes the carry.
|
||||
const carryLo = Math.max(1, carry.min - value);
|
||||
const flip = carryLo <= tHi && this.next(state, freshAt, carryAt + 1, 'flip', dotsOnly);
|
||||
if (flip)
|
||||
this.fill(flip, clampTo(fresh, carryLo), clampTo(fresh, tHi), { from: state, value, char, tLo: carryLo }, 0);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Rebuilds the witness by following predecessors back to the start. */
|
||||
private trace(state: EntryState, value: number, char: number, length: number): string {
|
||||
const runs: string[] = [String.fromCodePoint(char).repeat(length)];
|
||||
let at: EntryState | undefined = state;
|
||||
let v = value;
|
||||
|
||||
while (at) {
|
||||
if (at.runLength[v]) runs.push(String.fromCodePoint(at.runChar[v]).repeat(at.runLength[v]));
|
||||
const prev: EntryState | undefined = at.prev[v];
|
||||
v = at.prevValue[v];
|
||||
at = prev;
|
||||
}
|
||||
|
||||
return runs.reverse().join('');
|
||||
}
|
||||
}
|
||||
|
||||
/** The lengths of the all-dot strings a sequence accepts: an interval, since a sum of intervals is one. */
|
||||
function dotLengths(blocks: Block[]): [number, number] | undefined {
|
||||
let lo = 0;
|
||||
let hi = 0;
|
||||
|
||||
for (const block of blocks) {
|
||||
const dot = has(block.set, DOT);
|
||||
if (!dot && block.min > 0) return undefined;
|
||||
lo += block.min;
|
||||
if (dot) hi += block.max;
|
||||
}
|
||||
|
||||
return [lo, hi];
|
||||
}
|
||||
|
||||
/**
|
||||
* A segment both block sequences accept, or `undefined` when their languages share none.
|
||||
*
|
||||
* Exact over the decoded-segment universe. The product walk finds any common string containing a
|
||||
* character other than `.`; the all-dot strings are an interval of lengths per side, and a common one
|
||||
* of length 3 or more is `...`, a segment normalization keeps.
|
||||
*
|
||||
* Cost: at most 4·|A|·|B| entry states, each holding at most K + 1 counter values (K ≤ 2048, the
|
||||
* largest quantifier bound the subset allows), each value expanded into at most |A| + |B| successor
|
||||
* fills that union-find keeps linear. O(|A|·|B|·(|A| + |B|)·K), with |A|, |B| ≤ 128 blocks.
|
||||
*/
|
||||
export function intersectionWitness(A: Block[], B: Block[]): string | undefined {
|
||||
const found = new ProductWalk(A, B).witness();
|
||||
if (found !== undefined) return found;
|
||||
|
||||
const dotsA = dotLengths(A);
|
||||
const dotsB = dotLengths(B);
|
||||
if (!dotsA || !dotsB) return undefined;
|
||||
const length = Math.max(3, dotsA[0], dotsB[0]);
|
||||
return length <= Math.min(dotsA[1], dotsB[1]) ? '.'.repeat(length) : undefined;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Route patterns.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* How a table picks between two routes that match the same request.
|
||||
*
|
||||
* `specificity` is the HTTP router: static > constrained > plain at the first differing segment,
|
||||
* registration order on a tie. `registration` is the WebSocket matcher, which takes the first route
|
||||
* declared that matches (frozen as observed by the parity corpus, `matcher-ws.json`).
|
||||
*/
|
||||
export type Precedence = 'specificity' | 'registration';
|
||||
|
||||
export type RouteConflict =
|
||||
/** Two constrained siblings accept a common segment: `segment` decoded, `path` a request both match. */
|
||||
| { kind: 'ambiguous'; segment: string; path: string }
|
||||
/** The route at `loser` (0 = first argument, 1 = second) can never be selected: the other wins every request it matches. */
|
||||
| { kind: 'unreachable'; loser: 0 | 1 };
|
||||
|
||||
type Param = Extract<CompiledSegment, { kind: 'param' }>;
|
||||
|
||||
const blocksOf = (segment: Param): Block[] =>
|
||||
segment.constraintSource ? constraintBlocks(segment.constraintSource) : ANY_SEGMENT;
|
||||
|
||||
function decodedStatic(value: string): string | undefined {
|
||||
try {
|
||||
const decoded = decodeURIComponent(value);
|
||||
// A request segment spelling `.` or `..` is resolved away before matching, so no request reaches it.
|
||||
return decoded === '.' || decoded === '..' ? undefined : decoded;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** A raw request segment that `segment` alone accepts, or `undefined` if it accepts none. */
|
||||
function segmentWitness(segment: CompiledSegment): string | undefined {
|
||||
if (segment.kind === 'static') return decodedStatic(segment.value) === undefined ? undefined : segment.value;
|
||||
if (segment.kind === 'catchAll') return undefined;
|
||||
const value = intersectionWitness(blocksOf(segment), ANY_SEGMENT);
|
||||
return value === undefined ? undefined : encodeURIComponent(value);
|
||||
}
|
||||
|
||||
/** A raw request segment both accept, or `undefined`. */
|
||||
function overlapWitness(x: CompiledSegment, y: CompiledSegment): string | undefined {
|
||||
if (x.kind === 'static' && y.kind === 'static') return x.value === y.value ? segmentWitness(x) : undefined;
|
||||
|
||||
if (x.kind === 'static' || y.kind === 'static') {
|
||||
const [fixed, param] = (x.kind === 'static' ? [x, y] : [y, x]) as [
|
||||
Extract<CompiledSegment, { kind: 'static' }>,
|
||||
Param,
|
||||
];
|
||||
const decoded = decodedStatic(fixed.value);
|
||||
return decoded !== undefined && (!param.constraint || param.constraint.test(decoded)) ? fixed.value : undefined;
|
||||
}
|
||||
|
||||
const value = intersectionWitness(blocksOf(x as Param), blocksOf(y as Param));
|
||||
return value === undefined ? undefined : encodeURIComponent(value);
|
||||
}
|
||||
|
||||
/** Witness segments for every fixed segment from `from` on, or `undefined` if one accepts nothing. */
|
||||
function restWitness(segments: CompiledSegment[], from: number): string[] | undefined {
|
||||
const out: string[] = [];
|
||||
|
||||
for (const segment of segments.slice(from)) {
|
||||
if (segment.kind === 'catchAll') break;
|
||||
const witness = segmentWitness(segment);
|
||||
if (witness === undefined) return undefined;
|
||||
out.push(witness);
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Raw segments of a request both patterns match from position `from` on, or `undefined` if none exists. */
|
||||
function overlapFrom(a: CompiledPattern, b: CompiledPattern, from: number): string[] | undefined {
|
||||
const out: string[] = [];
|
||||
|
||||
for (let m = from; ; m++) {
|
||||
const x = a.segments[m];
|
||||
const y = b.segments[m];
|
||||
// A catch-all takes zero or more segments, so it absorbs whatever the other side still needs.
|
||||
if (x?.kind === 'catchAll') return concat(out, restWitness(b.segments, m));
|
||||
if (y?.kind === 'catchAll') return concat(out, restWitness(a.segments, m));
|
||||
if (!x || !y) return x || y ? undefined : out;
|
||||
const witness = overlapWitness(x, y);
|
||||
if (witness === undefined) return undefined;
|
||||
out.push(witness);
|
||||
}
|
||||
}
|
||||
|
||||
const concat = (head: string[], tail: string[] | undefined): string[] | undefined => tail && [...head, ...tail];
|
||||
|
||||
/** Whether every segment `lower` accepts, `higher` accepts too. Two different constraints are not compared. */
|
||||
function segmentIncluded(lower: CompiledSegment, higher: CompiledSegment): boolean {
|
||||
if (higher.kind === 'static') return lower.kind === 'static' && lower.value === higher.value;
|
||||
if (higher.kind === 'catchAll' || lower.kind === 'catchAll') return false;
|
||||
if (!higher.constraintSource) return true;
|
||||
|
||||
if (lower.kind === 'static') {
|
||||
const decoded = decodedStatic(lower.value);
|
||||
return decoded === undefined || higher.constraint!.test(decoded);
|
||||
}
|
||||
|
||||
return lower.constraintSource === higher.constraintSource || acceptsEverySegment(blocksOf(higher));
|
||||
}
|
||||
|
||||
/** Whether `higher` matches every request `lower` matches, from position `from` on. */
|
||||
function includedFrom(lower: CompiledPattern, higher: CompiledPattern, from: number): boolean {
|
||||
for (let m = from; ; m++) {
|
||||
const l = lower.segments[m];
|
||||
const h = higher.segments[m];
|
||||
if (h?.kind === 'catchAll') return true;
|
||||
if (!l || !h) return !l && !h;
|
||||
if (!segmentIncluded(l, h)) return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** The position of the first segment whose shape differs — the radix node where the two routes branch. */
|
||||
function branchPoint(a: CompiledPattern, b: CompiledPattern): number {
|
||||
const length = Math.max(a.segments.length, b.segments.length);
|
||||
|
||||
for (let k = 0; k < length; k++) {
|
||||
const x = a.segments[k];
|
||||
const y = b.segments[k];
|
||||
if (!x || !y || shapeOf(x) !== shapeOf(y)) return k;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `first` beats `second` on a request both match, given that they branch at a constrained
|
||||
* param against a plain one. `firstConstrained` says which side holds the constraint.
|
||||
*
|
||||
* Under `specificity` this is the router's own ranking: an exact route beats a catch-all route
|
||||
* outright, and otherwise the constrained param beats the plain one at the branch, since every
|
||||
* segment before it has the same kind. Under `registration` the earlier declaration wins.
|
||||
*/
|
||||
function winsBranch(
|
||||
first: CompiledPattern,
|
||||
second: CompiledPattern,
|
||||
firstConstrained: boolean,
|
||||
precedence: Precedence,
|
||||
) {
|
||||
if (precedence === 'registration') return true;
|
||||
if (first.catchAll !== second.catchAll) return !first.catchAll;
|
||||
return firstConstrained;
|
||||
}
|
||||
|
||||
function shapeOf(segment: CompiledSegment): string {
|
||||
if (segment.kind === 'static') return `s:${segment.value}`;
|
||||
if (segment.kind === 'catchAll') return 'c';
|
||||
return segment.constraintSource ? `r:${segment.constraintSource}` : 'p';
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether two routes of the same method, in the same table, conflict. `first` was declared before
|
||||
* `second`.
|
||||
*
|
||||
* **Siblings.** Two routes are siblings at position `k` when their segments before `k` have the same
|
||||
* shape — they share a node of the radix tree — and both segments at `k` are params, at least one of
|
||||
* them constrained. Statics and catch-alls are not sibling params: a static wins on the raw segment
|
||||
* (a constrained twin is still reachable through a percent-encoded spelling), and a catch-all ranks
|
||||
* below every exact route. Equal shapes everywhere is the duplicate-shape error, checked elsewhere.
|
||||
*
|
||||
* **Ambiguous** (both constrained): the two constraints accept a common segment, *and* the full
|
||||
* patterns can match one request — every later position pair overlaps, a catch-all absorbing the
|
||||
* rest. `/u/:id(\d+)/a` and `/u/:n(\d{1,3})/b` share digits at the branch but no request, so they do
|
||||
* not conflict. The witness is the common segment at the branch, plus a whole request path.
|
||||
*
|
||||
* **Unreachable** (one constrained, one plain): the route that loses the branch can never be chosen
|
||||
* when the winner also matches everything it matches. The winner is the constrained one under
|
||||
* `specificity`, which then needs a constraint that accepts every segment; under `registration` it is
|
||||
* whichever was declared first. (An exact route beats a catch-all one under `specificity` whatever
|
||||
* the branch holds, and no exact route can include a catch-all.) Later positions must be included
|
||||
* segment by segment. Inclusion
|
||||
* between two *different* constraints at a later position is not attempted — it is not known to be
|
||||
* polynomial for this grammar — and counts as not included, so such a route boots.
|
||||
*/
|
||||
export function routeConflict(
|
||||
first: CompiledPattern,
|
||||
second: CompiledPattern,
|
||||
precedence: Precedence,
|
||||
): RouteConflict | undefined {
|
||||
const k = branchPoint(first, second);
|
||||
const x = first.segments[k];
|
||||
const y = second.segments[k];
|
||||
if (k < 0 || x?.kind !== 'param' || y?.kind !== 'param') return undefined;
|
||||
if (!x.constraintSource && !y.constraintSource) return undefined;
|
||||
|
||||
const prefix = restWitness(first.segments.slice(0, k), 0);
|
||||
if (!prefix) return undefined;
|
||||
|
||||
if (x.constraintSource && y.constraintSource) {
|
||||
const segment = intersectionWitness(blocksOf(x), blocksOf(y));
|
||||
const rest = segment === undefined ? undefined : overlapFrom(first, second, k + 1);
|
||||
if (segment === undefined || !rest) return undefined;
|
||||
return { kind: 'ambiguous', segment, path: `/${[...prefix, encodeURIComponent(segment), ...rest].join('/')}` };
|
||||
}
|
||||
|
||||
const firstWins = winsBranch(first, second, Boolean(x.constraintSource), precedence);
|
||||
const [winner, loser] = firstWins ? [first, second] : [second, first];
|
||||
const winnerParam = firstWins ? x : y;
|
||||
if (winnerParam.constraintSource && !acceptsEverySegment(blocksOf(winnerParam))) return undefined;
|
||||
return includedFrom(loser, winner, k + 1) ? { kind: 'unreachable', loser: firstWins ? 1 : 0 } : undefined;
|
||||
}
|
||||
+420
-66
@@ -1,4 +1,4 @@
|
||||
import type { RouteDef, MatchedRoute } from './types';
|
||||
import type { RouteDef, RouteTable, MatchedRoute } from './types';
|
||||
|
||||
export type CompiledSegment =
|
||||
| { kind: 'static'; value: string }
|
||||
@@ -33,13 +33,21 @@ interface ConstraintToken {
|
||||
separator: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* One atom of the safe constraint subset, and the quantifier that may follow it. Shared with
|
||||
* `route-conflicts.ts`, which reads accepted constraints back as (character set, min, max) blocks, so
|
||||
* the two cannot disagree about what an atom is.
|
||||
*/
|
||||
export const CONSTRAINT_ATOM = /^(?:\\[dDsSwW]|\\[.\-_/]|[A-Za-z0-9_.-]|\[(?:\\.|[^\]\\])+\])/u;
|
||||
export const CONSTRAINT_QUANTIFIER = /^(?:[+*?]|\{\d+(?:,\d*)?\})/u;
|
||||
|
||||
/** 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];
|
||||
const atom = CONSTRAINT_ATOM.exec(source)?.[0];
|
||||
if (!atom) return undefined;
|
||||
|
||||
const rest = source.slice(atom.length);
|
||||
const quantifier = /^(?:[+*?]|\{\d+(?:,\d*)?\})/u.exec(rest)?.[0] ?? '';
|
||||
const quantifier = CONSTRAINT_QUANTIFIER.exec(rest)?.[0] ?? '';
|
||||
if (quantifier.startsWith('{')) assertBoundedQuantifier(quantifier);
|
||||
|
||||
return {
|
||||
@@ -139,8 +147,19 @@ function segmentShape(segment: CompiledSegment): string {
|
||||
return segment.constraintSource ? `r:${segment.constraintSource}` : 'p';
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls into the compile and index-build seams. `compilePattern` is called inside this module, where a
|
||||
* spy on the export cannot see it, so the counts are kept here; they let a test prove that misses
|
||||
* after the index is built recompile nothing and rebuild nothing (FPRD-001 CARD-10).
|
||||
*/
|
||||
const seamCounts = { compilePattern: 0, indexBuilds: 0, localTreeBuilds: 0 };
|
||||
|
||||
/** @internal Calls so far to `compilePattern` (cache hits included), route-index builds and local-tree builds. For tests. */
|
||||
export const routerSeamCounts = (): Readonly<typeof seamCounts> => ({ ...seamCounts });
|
||||
|
||||
/** Compiles and validates one route pattern. Results are cached by source string. */
|
||||
export function compilePattern(pattern: string): CompiledPattern {
|
||||
seamCounts.compilePattern++;
|
||||
const cached = compiledCache.get(pattern);
|
||||
if (cached) return cached;
|
||||
if (!pattern.startsWith('/')) throw new Error(`invalid route pattern '${pattern}': pattern must start with '/'`);
|
||||
@@ -325,65 +344,387 @@ function moreSpecific(a: CompiledPattern, b: CompiledPattern): number {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** One route with its pattern already compiled. Built once per table, ordered within its method. */
|
||||
interface IndexedRoute {
|
||||
/**
|
||||
* One route at a terminal of the index.
|
||||
*
|
||||
* `rank` is the route's place in its method's specificity order — exactly the order the linear
|
||||
* matcher sorted its bucket into: `moreSpecific` first, declaration order on ties. Lower wins. The
|
||||
* tree only decides which routes *can* match; this number alone decides which one *does*, so the
|
||||
* shape of the tree can never override the global ranking (two overlapping constraints, a catch-all
|
||||
* at one depth against a param at another, an equal-rank tie).
|
||||
*/
|
||||
interface Terminal {
|
||||
def: RouteDef;
|
||||
compiled: CompiledPattern;
|
||||
rank: number;
|
||||
/** Position in the route array the index was built from. Breaks a tie between the two trees. */
|
||||
order: number;
|
||||
/** Every segment static: the route has no params to collect. */
|
||||
allStatic: boolean;
|
||||
}
|
||||
|
||||
/** A `:param` edge. Plain params share one edge; constrained ones share an edge per constraint source. */
|
||||
interface ParamEdge {
|
||||
constraintSource: string | undefined;
|
||||
constraint: RegExp | undefined;
|
||||
node: RadixNode;
|
||||
}
|
||||
|
||||
// ponytail: a segment trie — one edge per whole path segment, no compression of single-child static
|
||||
// chains. Lookup cost already follows path depth, not route count; compressing would save a few map
|
||||
// hops on long static prefixes and costs a split/merge routine nobody has measured a need for.
|
||||
interface RadixNode {
|
||||
statics: Map<string, RadixNode>;
|
||||
params: ParamEdge[];
|
||||
/** Routes whose last segment ends at this node, by rank. */
|
||||
exact: Terminal[];
|
||||
/** Catch-all routes whose fixed prefix ends at this node, by rank. They match zero or more segments. */
|
||||
catchAll: Terminal[];
|
||||
/** Lowest rank anywhere below this node: a branch that cannot beat the best match so far is skipped. */
|
||||
min: number;
|
||||
}
|
||||
|
||||
/** One method's routes: the tree, plus its all-static routes by exact path. */
|
||||
interface MethodTree {
|
||||
root: RadixNode;
|
||||
/**
|
||||
* All-static routes keyed by their normalized pattern, by rank. A hit here is the tree's best
|
||||
* match for that path: any other non-catch-all route matching it has as many segments, none of
|
||||
* them more specific than static, and every catch-all ranks below every exact route. So a static
|
||||
* request is answered without splitting the path. A miss proves nothing and falls through to the
|
||||
* walk, as does a path spelled differently from its pattern (`/a/`, `/a//b` on a direct call).
|
||||
*/
|
||||
exactPaths: Map<string, Terminal[]>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compiled, method-bucketed, specificity-ordered route tables, keyed by the identity of the array
|
||||
* they were built from.
|
||||
* The lookup index for one route array: a tree per HTTP method, local and remote kept apart.
|
||||
*
|
||||
* Mesh-spliced remote routes get their own trees so they can later be rebuilt alone when peers come
|
||||
* and go. Precedence stays the single list's: both trees answer, the more specific match wins, and
|
||||
* a tie goes to the earlier declaration — a local one, since local routes come first.
|
||||
*/
|
||||
interface RouteIndex {
|
||||
/** Length of the array at build time; a cached index for an array that has since grown or shrunk is rebuilt. */
|
||||
size: number;
|
||||
local: Map<string, MethodTree>;
|
||||
/** Absent for an app without mesh routes, which then does a single lookup. */
|
||||
remote: Map<string, MethodTree> | undefined;
|
||||
/** Every method with at least one route, in either tree. */
|
||||
methods: string[];
|
||||
}
|
||||
|
||||
/** The routes a mesh teacup spliced in from its teapots. Identity-keyed, so a route is remote wherever it travels. */
|
||||
const remoteRouteDefs = new WeakSet<RouteDef>();
|
||||
|
||||
/** The array a {@link RouteTable} holds right now. Servers call it once per request. */
|
||||
export function currentRoutes(table: RouteTable): RouteDef[] {
|
||||
return typeof table === 'function' ? table() : table;
|
||||
}
|
||||
|
||||
/** Marks a route as spliced in from a mesh teapot, so the index files it in the remote tree. */
|
||||
export function markRemoteRoute<T extends RouteDef>(def: T): T {
|
||||
remoteRouteDefs.add(def);
|
||||
return def;
|
||||
}
|
||||
|
||||
/**
|
||||
* Route indexes keyed by the identity of the array they were built from.
|
||||
*
|
||||
* A server hands the same array to every request, so this is built once and collected with the
|
||||
* table it describes. A table assembled fresh — mesh splicing a teapot's exports in at boot — is a
|
||||
* different array and gets its own index, so nothing has to remember to invalidate anything.
|
||||
* table it describes. Both callers (`buildAppFetch` and `listen()`) assemble that array after boot,
|
||||
* from local, remote and dev routes, and never touch it again. A table assembled fresh is a
|
||||
* different array and gets its own index.
|
||||
*/
|
||||
const routeIndexCache = new WeakMap<RouteDef[], Map<string, IndexedRoute[]>>();
|
||||
const routeIndexCache = new WeakMap<RouteDef[], RouteIndex>();
|
||||
|
||||
function routeIndex(routes: RouteDef[]): Map<string, IndexedRoute[]> {
|
||||
const cached = routeIndexCache.get(routes);
|
||||
if (cached) return cached;
|
||||
function newNode(): RadixNode {
|
||||
return { statics: new Map(), params: [], exact: [], catchAll: [], min: Infinity };
|
||||
}
|
||||
|
||||
const byMethod = new Map<string, IndexedRoute[]>();
|
||||
|
||||
for (const def of routes) {
|
||||
const entry: IndexedRoute = { def, compiled: compilePattern(def.pattern) };
|
||||
const bucket = byMethod.get(def.method);
|
||||
if (bucket) bucket.push(entry);
|
||||
else byMethod.set(def.method, [entry]);
|
||||
function childFor(node: RadixNode, segment: Exclude<CompiledSegment, { kind: 'catchAll' }>): RadixNode {
|
||||
if (segment.kind === 'static') {
|
||||
let next = node.statics.get(segment.value);
|
||||
if (!next) node.statics.set(segment.value, (next = newNode()));
|
||||
return next;
|
||||
}
|
||||
|
||||
// Most specific first, so the first match *is* the answer. `sort` is stable, so equal patterns
|
||||
// keep registration order — which is exactly what the old scan did by refusing to replace its
|
||||
// best on a tie.
|
||||
for (const bucket of byMethod.values()) bucket.sort((a, b) => moreSpecific(b.compiled, a.compiled));
|
||||
let edge = node.params.find((candidate) => candidate.constraintSource === segment.constraintSource);
|
||||
|
||||
routeIndexCache.set(routes, byMethod);
|
||||
return byMethod;
|
||||
if (!edge) {
|
||||
edge = { constraintSource: segment.constraintSource, constraint: segment.constraint, node: newNode() };
|
||||
node.params.push(edge);
|
||||
}
|
||||
|
||||
return edge.node;
|
||||
}
|
||||
|
||||
/** Files one terminal. Insertion runs in rank order, so every list stays sorted and `min` is set once. */
|
||||
function insert(tree: MethodTree, terminal: Terminal): void {
|
||||
let node = tree.root;
|
||||
if (node.min === Infinity) node.min = terminal.rank;
|
||||
|
||||
for (const segment of terminal.compiled.segments) {
|
||||
if (segment.kind === 'catchAll') {
|
||||
node.catchAll.push(terminal);
|
||||
return;
|
||||
}
|
||||
|
||||
node = childFor(node, segment);
|
||||
if (node.min === Infinity) node.min = terminal.rank;
|
||||
}
|
||||
|
||||
node.exact.push(terminal);
|
||||
|
||||
if (terminal.allStatic) {
|
||||
const key = terminal.compiled.normalized;
|
||||
const same = tree.exactPaths.get(key);
|
||||
if (same) same.push(terminal);
|
||||
else tree.exactPaths.set(key, [terminal]);
|
||||
}
|
||||
}
|
||||
|
||||
/** Builds one tree per method from `(route, array position)` pairs, ranked as the linear matcher sorted them. */
|
||||
function buildTrees(entries: Array<{ def: RouteDef; order: number }>): Map<string, MethodTree> {
|
||||
const byMethod = new Map<string, Terminal[]>();
|
||||
|
||||
for (const { def, order } of entries) {
|
||||
const compiled = compilePattern(def.pattern);
|
||||
const allStatic = compiled.segments.every((segment) => segment.kind === 'static');
|
||||
const terminal: Terminal = { def, compiled, rank: 0, order, allStatic };
|
||||
const bucket = byMethod.get(def.method);
|
||||
if (bucket) bucket.push(terminal);
|
||||
else byMethod.set(def.method, [terminal]);
|
||||
}
|
||||
|
||||
const trees = new Map<string, MethodTree>();
|
||||
|
||||
for (const [method, bucket] of byMethod) {
|
||||
// `sort` is stable, so equal patterns keep registration order.
|
||||
bucket.sort((a, b) => moreSpecific(b.compiled, a.compiled));
|
||||
const tree: MethodTree = { root: newNode(), exactPaths: new Map() };
|
||||
bucket.forEach((terminal, rank) => insert(tree, Object.assign(terminal, { rank })));
|
||||
trees.set(method, tree);
|
||||
}
|
||||
|
||||
return trees;
|
||||
}
|
||||
|
||||
/**
|
||||
* The last local trees built, and the `(def, position)` entries they were built from.
|
||||
*
|
||||
* When mesh membership changes, the app publishes a new array whose local entries are the same
|
||||
* objects at the same positions, with only the remote tail different (CARD-19, D15). Reusing the
|
||||
* local trees then means a peer coming or going rebuilds the remote trees alone. Keyed by the
|
||||
* first local def, so it is collected with the table that owns it.
|
||||
*/
|
||||
const localTreeCache = new WeakMap<
|
||||
RouteDef,
|
||||
{ entries: Array<{ def: RouteDef; order: number }>; trees: Map<string, MethodTree> }
|
||||
>();
|
||||
|
||||
function sameEntries(a: Array<{ def: RouteDef; order: number }>, b: Array<{ def: RouteDef; order: number }>): boolean {
|
||||
return a.length === b.length && a.every((entry, i) => entry.def === b[i].def && entry.order === b[i].order);
|
||||
}
|
||||
|
||||
function localTrees(local: Array<{ def: RouteDef; order: number }>): Map<string, MethodTree> {
|
||||
if (!local.length) return buildTrees(local);
|
||||
const cached = localTreeCache.get(local[0].def);
|
||||
if (cached && sameEntries(cached.entries, local)) return cached.trees;
|
||||
|
||||
seamCounts.localTreeBuilds++;
|
||||
const trees = buildTrees(local);
|
||||
localTreeCache.set(local[0].def, { entries: local, trees });
|
||||
return trees;
|
||||
}
|
||||
|
||||
function routeIndex(routes: RouteDef[]): RouteIndex {
|
||||
const cached = routeIndexCache.get(routes);
|
||||
if (cached?.size === routes.length) return cached;
|
||||
|
||||
seamCounts.indexBuilds++;
|
||||
const local: Array<{ def: RouteDef; order: number }> = [];
|
||||
const remote: Array<{ def: RouteDef; order: number }> = [];
|
||||
routes.forEach((def, order) => (remoteRouteDefs.has(def) ? remote : local).push({ def, order }));
|
||||
|
||||
const index: RouteIndex = {
|
||||
size: routes.length,
|
||||
local: localTrees(local),
|
||||
remote: remote.length ? buildTrees(remote) : undefined,
|
||||
methods: [...new Set(routes.map((route) => route.method))],
|
||||
};
|
||||
routeIndexCache.set(routes, index);
|
||||
return index;
|
||||
}
|
||||
|
||||
/**
|
||||
* One request's lookup state, shared by every tree it searches: the path, its segments (split only
|
||||
* if a walk needs them), decoded values memoized by position, and the current search's filter and
|
||||
* best terminal. One object per call rather than one per tree keeps the small-table cost down.
|
||||
*/
|
||||
interface Search {
|
||||
path: string;
|
||||
segs: string[] | undefined;
|
||||
decoded: Array<string | undefined>;
|
||||
accept: ((def: RouteDef) => boolean) | undefined;
|
||||
best: Terminal | undefined;
|
||||
}
|
||||
|
||||
/** Placeholder until a walk splits the path; nothing reads or writes it before then. */
|
||||
const NO_DECODED: Array<string | undefined> = [];
|
||||
|
||||
function newSearch(path: string): Search {
|
||||
return { path, segs: undefined, decoded: NO_DECODED, accept: undefined, best: undefined };
|
||||
}
|
||||
|
||||
function segmentsOf(search: Search): string[] {
|
||||
if (search.segs) return search.segs;
|
||||
const segs = splitPath(search.path);
|
||||
search.segs = segs;
|
||||
search.decoded = new Array(segs.length);
|
||||
return segs;
|
||||
}
|
||||
|
||||
/** Takes the best-ranked acceptable terminal of a rank-ordered list, if it beats the best so far. */
|
||||
function offer(search: Search, terminals: Terminal[]): void {
|
||||
for (let i = 0; i < terminals.length; i++) {
|
||||
const terminal = terminals[i];
|
||||
if (search.best && terminal.rank >= search.best.rank) return;
|
||||
if (search.accept && !search.accept(terminal.def)) continue;
|
||||
search.best = terminal;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pending walk frames, shared by every lookup. A frame is a node and its depth; `POST` marks the
|
||||
* frame that offers a node's catch-alls once its children are done. The walk is synchronous and
|
||||
* calls no user code, and each call pops only what it pushed, so sharing is safe.
|
||||
*/
|
||||
const stackNodes: RadixNode[] = [];
|
||||
const stackDepths: number[] = [];
|
||||
const POST = -1;
|
||||
|
||||
/** @internal Pending frames left on the shared walk stack; zero between lookups. For tests. */
|
||||
export const walkStackSize = (): number => stackNodes.length;
|
||||
|
||||
/**
|
||||
* Depth-first walk with backtracking: a static branch that dead-ends deeper falls back to its param,
|
||||
* constrained and catch-all siblings. Params are decoded after splitting, so `%2F` stays inside one
|
||||
* segment. Every branch that could still hold a better rank is visited; `min` prunes the rest.
|
||||
*
|
||||
* It runs on an explicit stack, not recursion, so a deep path that the linear matcher accepts cannot
|
||||
* overflow the call stack. Frames pop in the order the recursive walk visited them: static child,
|
||||
* then params in insertion order, then the node's catch-alls.
|
||||
*
|
||||
* The indexed loops and the empty-collection guards are measured, not style: at 10 routes the old
|
||||
* linear scan is a handful of string compares, and these keep the walk within D4 of it (FPRD-001).
|
||||
*/
|
||||
function walk(root: RadixNode, search: Search, segs: string[]): void {
|
||||
const base = stackNodes.length;
|
||||
stackNodes.push(root);
|
||||
stackDepths.push(0);
|
||||
|
||||
try {
|
||||
while (stackNodes.length > base) {
|
||||
const node = stackNodes.pop()!;
|
||||
const depth = stackDepths.pop()!;
|
||||
|
||||
if (depth === POST) {
|
||||
offer(search, node.catchAll);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (search.best && node.min >= search.best.rank) continue;
|
||||
|
||||
if (node.catchAll.length) {
|
||||
stackNodes.push(node);
|
||||
stackDepths.push(POST);
|
||||
}
|
||||
|
||||
if (depth === segs.length) {
|
||||
if (node.exact.length) offer(search, node.exact);
|
||||
continue;
|
||||
}
|
||||
|
||||
const segment = segs[depth];
|
||||
const params = node.params;
|
||||
|
||||
for (let i = params.length - 1; i >= 0; i--) {
|
||||
const edge = params[i];
|
||||
const value = (search.decoded[depth] ??= decodeSegment(segment));
|
||||
if (edge.constraint && !edge.constraint.test(value)) continue;
|
||||
stackNodes.push(edge.node);
|
||||
stackDepths.push(depth + 1);
|
||||
}
|
||||
|
||||
const next = node.statics.size ? node.statics.get(segment) : undefined;
|
||||
|
||||
if (next) {
|
||||
stackNodes.push(next);
|
||||
stackDepths.push(depth + 1);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// A malformed `%` escape throws out of `decodeSegment` with frames still pending; drop them.
|
||||
// Not in a `finally`: a normal walk already ends at `base`, and writing `length` on every lookup
|
||||
// drops the arrays' storage, which cost D4 at 10 routes (FPRD-001 CARD-10).
|
||||
stackNodes.length = base;
|
||||
stackDepths.length = base;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function searchTree(
|
||||
tree: MethodTree | undefined,
|
||||
search: Search,
|
||||
accept: ((def: RouteDef) => boolean) | undefined,
|
||||
): Terminal | undefined {
|
||||
if (!tree) return undefined;
|
||||
search.accept = accept;
|
||||
search.best = undefined;
|
||||
|
||||
const exact = tree.exactPaths.get(search.path);
|
||||
if (exact) offer(search, exact);
|
||||
if (!search.best) walk(tree.root, search, segmentsOf(search));
|
||||
return search.best;
|
||||
}
|
||||
|
||||
/** Looks a method up in both trees. The more specific match wins; an equal one goes to the earlier declaration. */
|
||||
function findRoute(
|
||||
index: RouteIndex,
|
||||
method: string,
|
||||
search: Search,
|
||||
accept?: (def: RouteDef) => boolean,
|
||||
): Terminal | undefined {
|
||||
const local = searchTree(index.local.get(method), search, accept);
|
||||
if (!index.remote) return local;
|
||||
|
||||
const remote = searchTree(index.remote.get(method), search, accept);
|
||||
if (!local || !remote) return local ?? remote;
|
||||
|
||||
const order = moreSpecific(local.compiled, remote.compiled);
|
||||
if (order !== 0) return order > 0 ? local : remote;
|
||||
return local.order < remote.order ? local : remote;
|
||||
}
|
||||
|
||||
/** Collects the winning route's own param names and values. The walk already proved it matches. */
|
||||
function paramsOf(terminal: Terminal, search: Search): Record<string, string> {
|
||||
return terminal.allStatic ? {} : matchCompiled(terminal.compiled, segmentsOf(search), search.decoded)!;
|
||||
}
|
||||
|
||||
const isBuffered = (def: RouteDef): boolean => def.transport === 'buffer';
|
||||
|
||||
/**
|
||||
* Finds the most specific route matching both method and path; ties keep registration order.
|
||||
*
|
||||
* The ranking is settled when the table is built, not per request: the answer cannot change between
|
||||
* requests, and re-deriving it charged every request for a scan to the end plus a `moreSpecific`
|
||||
* call — two `compilePattern` lookups each — per candidate. Both scaled with the size of the route
|
||||
* table. What is left here is a walk that stops at the first match.
|
||||
* The ranking is settled when the index is built, not per request. What is left here is a walk down
|
||||
* the method's tree that visits only the branches the path can follow.
|
||||
*/
|
||||
export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined {
|
||||
const candidates = routeIndex(routes).get(method);
|
||||
if (!candidates) return undefined;
|
||||
|
||||
const pathSegs = splitPath(path);
|
||||
const decoded: Array<string | undefined> = new Array(pathSegs.length);
|
||||
|
||||
for (const { def, compiled } of candidates) {
|
||||
const params = matchCompiled(compiled, pathSegs, decoded);
|
||||
if (params) return { params, def };
|
||||
}
|
||||
|
||||
return undefined;
|
||||
const search = newSearch(path);
|
||||
const hit = findRoute(routeIndex(routes), method, search);
|
||||
return hit && { params: paramsOf(hit, search), def: hit.def };
|
||||
}
|
||||
|
||||
/** Route resolution adds the one HTTP fallback the matcher supports: buffered GET serves HEAD. */
|
||||
@@ -392,29 +733,37 @@ export interface ResolvedRoute extends MatchedRoute {
|
||||
}
|
||||
|
||||
export function resolveRoute(routes: RouteDef[], method: string, path: string): ResolvedRoute | undefined {
|
||||
const explicit = matchRoute(routes, method, path);
|
||||
if (explicit) return { ...explicit, implicitHead: false };
|
||||
const index = routeIndex(routes);
|
||||
const search = newSearch(path);
|
||||
|
||||
const explicit = findRoute(index, method, search);
|
||||
if (explicit) return { params: paramsOf(explicit, search), def: explicit.def, implicitHead: false };
|
||||
if (method !== 'HEAD') return undefined;
|
||||
|
||||
const fallback = matchRoute(
|
||||
routes.filter((route) => route.transport === 'buffer'),
|
||||
'GET',
|
||||
path,
|
||||
);
|
||||
return fallback ? { ...fallback, implicitHead: true } : undefined;
|
||||
// Only a buffered GET can answer HEAD. The filter applies inside the ranking, so a higher-ranked
|
||||
// streaming GET is passed over for a lower-ranked buffered one rather than ending the search.
|
||||
const fallback = findRoute(index, 'GET', search, isBuffered);
|
||||
return fallback ? { params: paramsOf(fallback, search), def: fallback.def, 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. */
|
||||
/**
|
||||
* Lists the distinct HTTP methods whose pattern matches the path — used to build a 405 `Allow` header.
|
||||
*
|
||||
* One lookup per registered method over the union of both trees. Nothing is recompiled or rescanned
|
||||
* on a miss.
|
||||
*/
|
||||
export function allowedMethods(routes: RouteDef[], path: string): string[] {
|
||||
const pathSegs = splitPath(path);
|
||||
const index = routeIndex(routes);
|
||||
const search = newSearch(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');
|
||||
for (const method of index.methods) {
|
||||
// A buffered GET answers both GET and HEAD, so it is looked for first; only a GET path served
|
||||
// by streaming routes alone needs the second lookup.
|
||||
if (method === 'GET' && findRoute(index, method, search, isBuffered)) methods.add('GET').add('HEAD');
|
||||
else if (findRoute(index, method, search)) methods.add(method);
|
||||
}
|
||||
|
||||
if (methods.size) methods.add('OPTIONS');
|
||||
@@ -427,18 +776,23 @@ export function allowedMethods(routes: RouteDef[], path: string): string[] {
|
||||
});
|
||||
}
|
||||
|
||||
/** Parses a URL's query string into a flat string map (last value wins for repeated keys). */
|
||||
/**
|
||||
* Parses a URL's query string into a flat string map (last value wins for repeated keys).
|
||||
*
|
||||
* The query string is everything after the **first** `?` and before a `#`, if one is present.
|
||||
* A `?` inside the query is a legal character (RFC 3986 §3.4), so `/search?q=what?now` gives
|
||||
* `{ q: 'what?now' }`.
|
||||
*/
|
||||
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 {};
|
||||
// Most requests carry no query string, and the work below is not free for them:
|
||||
// `new URLSearchParams('')` builds an object and the loop runs zero times, to arrive at `{}`.
|
||||
// Measured at 92.3 ns against 18.6 ns for this check.
|
||||
const start = url.indexOf('?');
|
||||
if (start < 0) return {};
|
||||
|
||||
const queryString = url.split('?')[1] ?? '';
|
||||
// `split('?')[1]` used to stop at a second `?` and drop the rest of the value (GitHub #48).
|
||||
const hash = url.indexOf('#', start + 1);
|
||||
const queryString = hash < 0 ? url.slice(start + 1) : url.slice(start + 1, hash);
|
||||
const out: Record<string, string> = {};
|
||||
for (const [key, value] of new URLSearchParams(queryString)) out[key] = value;
|
||||
return out;
|
||||
|
||||
+114
-26
@@ -2,11 +2,11 @@ import type http from 'http';
|
||||
import type https from 'https';
|
||||
import { createRequestGate } from './request-gate';
|
||||
import { renderError, type ErrorRequest } from '../transformers';
|
||||
import type { Bus } from '../bus';
|
||||
import type { Bus, Correlation } from '../bus';
|
||||
import { readBody as readBodyBytes, deriveSecure, deriveIp } from './request';
|
||||
import { pipeStream } from './stream';
|
||||
import { attachWs } from './ws';
|
||||
import { mergeInjectedHeaders } from './headers';
|
||||
import { mergeInjectedHeaders, joinListHeaders } from './headers';
|
||||
import {
|
||||
handle,
|
||||
correlateRequest,
|
||||
@@ -15,13 +15,18 @@ import {
|
||||
watchingRequests,
|
||||
type HandleResult,
|
||||
type Preflight,
|
||||
type NeutralOutcome,
|
||||
} from './core';
|
||||
import type { BodyFailure, BodyReader } from './body';
|
||||
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
|
||||
import type { RouteTable, WsRouteDef, MeshControl, HttpOptions } from './types';
|
||||
import { currentRoutes } from './router';
|
||||
import type { Logger } from '../logger';
|
||||
import { nodeRequire } from '../node-require';
|
||||
import { answerProbe } from './health';
|
||||
import { compressOutcome } from './compression';
|
||||
|
||||
interface HandlerConfig {
|
||||
routes: RouteDef[];
|
||||
routes: RouteTable;
|
||||
bus?: Bus;
|
||||
opts?: HttpOptions;
|
||||
trustProxy: boolean;
|
||||
@@ -34,14 +39,19 @@ function errorRequest(req: http.IncomingMessage): ErrorRequest {
|
||||
|
||||
/**
|
||||
* Builds an HTTP/HTTPS server that routes requests, parses bodies, streams results, and handles WebSocket upgrades.
|
||||
* @param routes HTTP route definitions.
|
||||
* @param routes HTTP route definitions, or a getter read once per request (a mesh teacup's table changes as peers come and go).
|
||||
* @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.
|
||||
*/
|
||||
/** `ctx.ip` on Node, for `NeutralRequest.resolveIp`: the forwarded hop under `trustProxy`, else the socket peer. */
|
||||
function nodeIp(source: unknown, opts: HttpOptions | undefined): string {
|
||||
return deriveIp(source as http.IncomingMessage, opts?.trustProxy ?? false);
|
||||
}
|
||||
|
||||
export function createHttpServer(
|
||||
routes: RouteDef[],
|
||||
routes: RouteTable,
|
||||
wsRoutes: WsRouteDef[] = [],
|
||||
bus?: Bus,
|
||||
meshControl?: MeshControl,
|
||||
@@ -78,7 +88,7 @@ export function createHttpServer(
|
||||
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);
|
||||
attachWs(server, wsRoutes, bus, meshControl, opts?.streams, opts?.limits);
|
||||
return server;
|
||||
}
|
||||
|
||||
@@ -96,7 +106,14 @@ function createRequestHandler(cfg: HandlerConfig) {
|
||||
const readBody: BodyReader = (source, limit) => readRequestBytes(source, limit, opts);
|
||||
const gate = createRequestGate(opts?.limits?.maxConcurrentRequests);
|
||||
|
||||
return async (req: http.IncomingMessage, res: http.ServerResponse): Promise<void> => {
|
||||
// `http.createServer` ignores the promise a listener returns, so a rejection that escapes `serve`
|
||||
// would be an `unhandledRejection` — and under Node's default mode, the end of the process.
|
||||
// Caught here, at the one place every request passes through (#108).
|
||||
return (req: http.IncomingMessage, res: http.ServerResponse): void => {
|
||||
serve(req, res).catch((err: unknown) => failSafe(res, err, opts?.logger));
|
||||
};
|
||||
|
||||
async function serve(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);
|
||||
@@ -108,6 +125,8 @@ function createRequestHandler(cfg: HandlerConfig) {
|
||||
const injected = computeInjected(opts, { secure, headers: req.headers });
|
||||
patchResponseHeaders(res, injected);
|
||||
|
||||
if (writeProbe(req, res, opts)) return;
|
||||
|
||||
let result: HandleResult | Preflight;
|
||||
let acquired = false;
|
||||
const watching = watchingRequests(bus);
|
||||
@@ -150,7 +169,7 @@ function createRequestHandler(cfg: HandlerConfig) {
|
||||
}
|
||||
|
||||
result = await handle(
|
||||
routes,
|
||||
currentRoutes(routes), // once per request, see buildFetch
|
||||
opts,
|
||||
{
|
||||
...correlation,
|
||||
@@ -160,7 +179,7 @@ function createRequestHandler(cfg: HandlerConfig) {
|
||||
readBody,
|
||||
source: req,
|
||||
secure,
|
||||
ip: deriveIp(req, trustProxy),
|
||||
resolveIp: nodeIp,
|
||||
},
|
||||
injected,
|
||||
);
|
||||
@@ -171,28 +190,97 @@ function createRequestHandler(cfg: HandlerConfig) {
|
||||
}
|
||||
}
|
||||
|
||||
const written = writeResult(req, res, result, { opts, bus, correlation });
|
||||
if (written) await written;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes what `handle()` produced: a preflight, or an outcome after `compressOutcome` (CARD-16).
|
||||
* Module scope rather than inside `serve`, whose closure would charge every branch here again.
|
||||
*
|
||||
* Deliberately not `async`, like `handle()`: a buffered response without compression is written
|
||||
* synchronously and returns nothing to await, so the common request allocates no promise here.
|
||||
* Only a stream, or a compressed body, returns one.
|
||||
*/
|
||||
function writeResult(
|
||||
req: http.IncomingMessage,
|
||||
res: http.ServerResponse,
|
||||
result: HandleResult | Preflight,
|
||||
ctx: { opts: HttpOptions | undefined; bus: Bus | undefined; correlation: Correlation },
|
||||
): Promise<void> | undefined {
|
||||
if ('preflight' in result) {
|
||||
res.writeHead(204, result.preflight);
|
||||
res.end();
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const compression = ctx.opts?.compression;
|
||||
if (!compression) return writeOutcome(res, result.outcome, ctx);
|
||||
|
||||
const decided = compressOutcome(compression, { method: req.method ?? 'GET', headers: req.headers }, result.outcome);
|
||||
return decided instanceof Promise
|
||||
? decided.then((outcome) => writeOutcome(res, outcome, ctx))
|
||||
: writeOutcome(res, decided, ctx);
|
||||
}
|
||||
|
||||
/** Pipes a stream (returning its promise) or writes a buffered outcome in one go (returning nothing). */
|
||||
function writeOutcome(
|
||||
res: http.ServerResponse,
|
||||
outcome: NeutralOutcome,
|
||||
ctx: { opts: HttpOptions | undefined; bus: Bus | undefined; correlation: Correlation },
|
||||
): Promise<void> | undefined {
|
||||
if (outcome.kind === 'stream') return pipeStream(res, outcome, ctx.bus, ctx.opts?.streams, ctx.correlation);
|
||||
|
||||
res.writeHead(outcome.status, outcome.headers);
|
||||
res.end(outcome.body);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers a health probe and returns true, or returns false for any other request. Runs before the
|
||||
* gate, so shedding never refuses a probe, and before `handle()`, so no step, plugin or lifecycle
|
||||
* event sees one. Written through the patched writeHead, so the security headers still land.
|
||||
*/
|
||||
function writeProbe(req: http.IncomingMessage, res: http.ServerResponse, opts: HttpOptions | undefined): boolean {
|
||||
const probe = opts?.health && answerProbe(req.method ?? 'GET', req.url ?? '/', opts.health);
|
||||
if (!probe) return false;
|
||||
|
||||
res.writeHead(probe.status, probe.headers);
|
||||
res.end(probe.body);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* The last resort for a request whose handling rejected. Deliberately does not call `onError`: this
|
||||
* runs because something already failed past the point where errors convert to a response, and user
|
||||
* code that may be the thing failing is the wrong place to send it. Must never throw — nothing
|
||||
* catches it.
|
||||
*
|
||||
* Writable: a fixed 500 with `connection: close`, still through the patched `writeHead`, so the
|
||||
* security headers land. Output already started, or the client gone: there is no honest response
|
||||
* left to send, so the socket is destroyed and the client sees a truncated reply rather than a
|
||||
* complete-looking one. No `request:end` is emitted — observers do not alter the response, and the
|
||||
* core never completed this request.
|
||||
*/
|
||||
function failSafe(res: http.ServerResponse, err: unknown, logger: Logger | undefined): void {
|
||||
try {
|
||||
logger?.error('request listener failed', { err: err instanceof Error ? err.message : String(err) });
|
||||
} catch {
|
||||
/* a broken logger must not stop the response below */
|
||||
}
|
||||
|
||||
if (res.headersSent || res.destroyed || !res.writable) {
|
||||
res.destroy();
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.outcome.kind === 'stream') {
|
||||
await pipeStream(
|
||||
res,
|
||||
result.outcome.stream,
|
||||
result.outcome.encoder,
|
||||
bus,
|
||||
result.outcome.route,
|
||||
opts?.streams,
|
||||
correlation,
|
||||
);
|
||||
return;
|
||||
try {
|
||||
res.writeHead(500, { 'content-type': 'application/json', connection: 'close' });
|
||||
res.end('{"error":"Internal Server Error"}');
|
||||
} catch {
|
||||
res.destroy();
|
||||
}
|
||||
|
||||
res.writeHead(result.outcome.status, result.outcome.headers);
|
||||
res.end(result.outcome.body);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -228,7 +316,7 @@ function patchResponseHeaders(res: http.ServerResponse, injected: Record<string,
|
||||
|
||||
(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);
|
||||
const merged = joinListHeaders(mergeInjectedHeaders(handlerHeaders, injected));
|
||||
return typeof arg2 === 'string' ? origWriteHead(status, arg2, merged) : origWriteHead(status, merged);
|
||||
};
|
||||
}
|
||||
@@ -44,7 +44,9 @@ export function closeWithDeadline(
|
||||
};
|
||||
|
||||
// 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);
|
||||
// close, not a broken one, and leaving close() pending forever is the worse failure. Called
|
||||
// inside `then` so a graceful path that throws before returning its promise counts as a
|
||||
// rejection too, rather than rejecting close() and leaving the timer to force a closed server.
|
||||
void Promise.resolve().then(graceful).then(finish, finish);
|
||||
});
|
||||
}
|
||||
+26
-13
@@ -3,6 +3,9 @@ import { once } from 'events';
|
||||
import { sseEncoder, ndjsonEncoder, StreamEncoder } from '../encoders';
|
||||
import type { Transport } from '../metadata';
|
||||
import type { Bus, Correlation } from '../bus';
|
||||
import type { NeutralOutcome } from './core';
|
||||
import { frameSink } from './compression';
|
||||
import { releaseIterator } from '../channel';
|
||||
|
||||
const PING_MS = 15_000;
|
||||
|
||||
@@ -27,35 +30,41 @@ export function pickEncoder(transport: Transport, accept: string): StreamEncoder
|
||||
return pick(accept);
|
||||
}
|
||||
|
||||
/** Pipes an async-iterable result to the response as an HTTP stream, with keep-alive pings and backpressure handling. */
|
||||
/**
|
||||
* Pipes a stream outcome to the response, with keep-alive pings and backpressure handling. With
|
||||
* `outcome.encoding` set (CARD-16), frames go through a `node:zlib` stream piped into `res`, flushed
|
||||
* after every frame, error frame and ping, so each event is decodable on arrival.
|
||||
*/
|
||||
export async function pipeStream(
|
||||
res: http.ServerResponse,
|
||||
stream: AsyncIterable<unknown>,
|
||||
encoder: StreamEncoder,
|
||||
outcome: Extract<NeutralOutcome, { kind: 'stream' }>,
|
||||
bus?: Bus,
|
||||
name = '',
|
||||
streams?: Set<() => void>,
|
||||
correlation: Correlation = {},
|
||||
): Promise<void> {
|
||||
const { stream, encoder, route: name } = outcome;
|
||||
// `route` duplicates `name` here rather than being passed separately: on a stream event `name`
|
||||
// is always the route pattern, never the concrete path the request events can carry — but a
|
||||
// consumer following the documented contract labels on `route` and would otherwise find it
|
||||
// absent on the longest-lived thing the server does. See `EventPayload.name`.
|
||||
const trace = { name, route: name, ...correlation };
|
||||
res.writeHead(200, encoder.headers);
|
||||
res.writeHead(200, outcome.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', trace);
|
||||
const sink = frameSink(res, outcome.encoding);
|
||||
const iterator = stream[Symbol.asyncIterator]();
|
||||
let ping: ReturnType<typeof setInterval> | undefined;
|
||||
|
||||
if (encoder.ping) {
|
||||
ping = setInterval(() => res.write(encoder.ping!()), PING_MS);
|
||||
ping = setInterval(() => sink.write(encoder.ping!()), PING_MS);
|
||||
ping.unref?.();
|
||||
}
|
||||
|
||||
const stop = () => {
|
||||
if (ping) clearInterval(ping);
|
||||
void Promise.resolve(iterator.return?.()).catch(() => {});
|
||||
// A client gone mid-stream: the compressor holds zlib memory outside the JS heap until destroyed.
|
||||
sink.destroy();
|
||||
releaseIterator(iterator);
|
||||
};
|
||||
|
||||
res.on('close', stop);
|
||||
@@ -70,25 +79,29 @@ export async function pipeStream(
|
||||
|
||||
streams?.add(closer);
|
||||
const onClose = once(res, 'close');
|
||||
// `next()` is raced against the disconnect (GitHub #40): an idle source's may never settle, and
|
||||
// waiting on it kept this loop and its closer alive long after the client had gone.
|
||||
const gone = onClose.then(() => undefined);
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const { value, done } = await iterator.next();
|
||||
if (done) break;
|
||||
const step = await Promise.race([iterator.next(), gone]);
|
||||
if (!step || step.done) break;
|
||||
const { value } = step;
|
||||
|
||||
if (!res.write(encoder.encode(value))) {
|
||||
await Promise.race([once(res, 'drain'), onClose]);
|
||||
if (!sink.write(encoder.encode(value))) {
|
||||
await Promise.race([once(sink.drains, 'drain'), onClose]);
|
||||
if (res.destroyed) break; // let finally clean up
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
bus?.emit('stream:error', { ...trace, error: err });
|
||||
const frame = encoder.encodeError(err);
|
||||
if (frame && !res.writableEnded) res.write(frame);
|
||||
if (frame && !res.writableEnded) sink.write(frame);
|
||||
} finally {
|
||||
if (ping) clearInterval(ping);
|
||||
streams?.delete(closer);
|
||||
if (!res.writableEnded && !res.destroyed) res.end();
|
||||
if (!res.writableEnded && !res.destroyed) sink.end();
|
||||
bus?.emit('stream:close', trace);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { Transport } from '../metadata';
|
||||
import type { HealthProbe } from './health';
|
||||
import type { PipelineResult } from '../pipeline';
|
||||
import type { ErrorRenderer } from '../transformers';
|
||||
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
|
||||
@@ -6,6 +7,7 @@ import type { WsRequest, WsSocket } from './ws-core';
|
||||
import type { StaticResolver } from '../views';
|
||||
import type { Bus } from '../bus';
|
||||
import type { Logger } from '../logger';
|
||||
import type { CompressionConfig } from './compression';
|
||||
|
||||
/** Per-request and per-server resource ceilings applied by the server. */
|
||||
export interface RequestLimits {
|
||||
@@ -16,6 +18,31 @@ export interface RequestLimits {
|
||||
headersTimeoutMs?: number; // default 10_000
|
||||
keepAliveTimeoutMs?: number; // default 5_000
|
||||
maxParts?: number; // default 1000
|
||||
/**
|
||||
* Largest inbound WebSocket message, in bytes (UTF-8 bytes for text), per connection. Default
|
||||
* `1_048_576` (1 MiB). A larger message closes the connection with `1009` (`message too large`);
|
||||
* a fragmented message counts as a whole. Must be a positive integer, or `createApp` throws.
|
||||
*
|
||||
* Node and Bun refuse an oversized frame before buffering it (`ws`'s `maxPayload`, Bun's
|
||||
* `maxPayloadLength`). Before Bun 1.4, Bun then drops the connection without a close frame, so
|
||||
* the peer sees `1006` instead of `1009`; Bun 1.4 and later send `1009`. Deno and the edge offer no such option: there the runtime
|
||||
* receives the whole message first, so its memory is bounded by the platform's own cap, and this
|
||||
* limit is checked after receipt — the connection still closes `1009`.
|
||||
*
|
||||
* Server-level only; there is no per-route override.
|
||||
*/
|
||||
maxWsMessageBytes?: number;
|
||||
/**
|
||||
* Inbound WebSocket messages a connection may hold that the handler has not read yet. Default
|
||||
* `16`. One more closes the connection with `1013` (`inbound queue full`) rather than dropping
|
||||
* anything, so a handler that never reads `inbound` is closed once its peer sends 17 messages.
|
||||
* Must be a positive integer, or `createApp` throws. Applies on every runtime.
|
||||
*
|
||||
* Worst-case buffered inbound memory is about `maxConnections × maxWsQueue × maxWsMessageBytes`:
|
||||
* ≈ 15.6 GiB at the defaults on Node. Deno and Bun have no connection cap, so cap connections at
|
||||
* the platform or proxy there. Server-level only; there is no per-route override.
|
||||
*/
|
||||
maxWsQueue?: number;
|
||||
}
|
||||
|
||||
/** Options controlling server construction: limits, TLS, proxy trust, security headers, CORS, and body parsing. */
|
||||
@@ -37,6 +64,15 @@ export interface HttpOptions {
|
||||
bodyDuplicates?: 'array' | 'last';
|
||||
onError?: ErrorRenderer;
|
||||
static?: StaticResolver;
|
||||
/**
|
||||
* Answers `/__live__` and `/__ready__` ahead of the gate and the route table (`createApp({ health })`).
|
||||
* Absent when health is off, so no path is intercepted.
|
||||
*/
|
||||
health?: HealthProbe;
|
||||
/** Weak ETags + `304` for buffered `200` GET/HEAD handler responses (`createApp({ etag })`). */
|
||||
etag?: boolean;
|
||||
/** Resolved `createApp({ compression })`; absent when compression is off. */
|
||||
compression?: CompressionConfig;
|
||||
}
|
||||
|
||||
/** Handler for a matched HTTP route; receives a normalized request and resolves to a pipeline result. */
|
||||
@@ -66,6 +102,13 @@ export interface RouteDef {
|
||||
maxParts?: number; // per-route override of the server's multipart maxParts
|
||||
}
|
||||
|
||||
/**
|
||||
* A route table: a fixed array, or a getter the server reads once per request. A mesh teacup passes
|
||||
* a getter, because its remote routes change as teapots come and go (CARD-19); each change publishes
|
||||
* a new array, so a request sees the whole old table or the whole new one.
|
||||
*/
|
||||
export type RouteTable = RouteDef[] | (() => RouteDef[]);
|
||||
|
||||
/** Result of matching a request path against a route: extracted params plus the matched definition. */
|
||||
export interface MatchedRoute {
|
||||
params: Record<string, string>;
|
||||
@@ -89,6 +132,12 @@ export interface WsRouteDef {
|
||||
/** Hook for a mesh gateway to take over WebSocket upgrades on a fixed path. */
|
||||
export interface MeshControl {
|
||||
path: string;
|
||||
/**
|
||||
* Inbound bound for this channel's socket, in bytes, used in place of
|
||||
* `limits.maxWsMessageBytes` when larger (#120): an RPC carries a whole request body, which
|
||||
* `maxBodyBytes` bounds, not the WebSocket message limit.
|
||||
*/
|
||||
maxFrameBytes?: number;
|
||||
/**
|
||||
* 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.
|
||||
|
||||
+153
-43
@@ -10,11 +10,17 @@ import {
|
||||
type HandleResult,
|
||||
type Preflight,
|
||||
} from './core';
|
||||
import { mergeInjectedHeaders } from './headers';
|
||||
import type { BodyFailure, BodyReader, MaybePromise } from './body';
|
||||
import { mergeInjectedHeaders, toWebHeaders } from './headers';
|
||||
import { peerOf, trustedProxyClient } from './peer';
|
||||
import { declaresOverLimit, type BodyFailure, type BodyReader, type MaybePromise } from './body';
|
||||
import { HttpError } from '../signals';
|
||||
import { renderError, type ErrorRequest } from '../transformers';
|
||||
import type { RouteDef, HttpOptions } from './types';
|
||||
import type { RouteTable, HttpOptions } from './types';
|
||||
import { answerProbe } from './health';
|
||||
import { currentRoutes } from './router';
|
||||
import { compressOutcome, compressWebStream } from './compression';
|
||||
import type { NeutralOutcome } from './core';
|
||||
import { releaseIterator } from '../channel';
|
||||
|
||||
/**
|
||||
* Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream
|
||||
@@ -37,6 +43,9 @@ export function asReadableStream(
|
||||
// `cancel` can land after the body has already ended, and an errored stream still unwinds through
|
||||
// its own path — so the close is latched rather than emitted from each of the three exits.
|
||||
let closed = false;
|
||||
// Settles on `cancel`, so a `pull` waiting on an idle source's `next()` stops waiting (GitHub #40).
|
||||
let cancelled!: (step: undefined) => void;
|
||||
const gone = new Promise<undefined>((resolve) => (cancelled = resolve));
|
||||
|
||||
const close = (): void => {
|
||||
if (closed) return;
|
||||
@@ -50,7 +59,9 @@ export function asReadableStream(
|
||||
},
|
||||
async pull(controller) {
|
||||
try {
|
||||
const { value, done } = await iterator.next();
|
||||
const step = await Promise.race([iterator.next(), gone]);
|
||||
if (!step) return;
|
||||
const { value, done } = step;
|
||||
|
||||
if (done) {
|
||||
close();
|
||||
@@ -78,9 +89,11 @@ export function asReadableStream(
|
||||
controller.close();
|
||||
}
|
||||
},
|
||||
async cancel() {
|
||||
// Not awaited: `return()` on a generator still waiting in `next()` would hold the cancel open.
|
||||
cancel() {
|
||||
close();
|
||||
await iterator.return?.();
|
||||
cancelled(undefined);
|
||||
releaseIterator(iterator);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -97,9 +110,9 @@ function headersToRecord(headers: Headers): Record<string, string> {
|
||||
/**
|
||||
* 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.
|
||||
* Read from `request.body` chunk by chunk rather than through `arrayBuffer()`, which resolves with
|
||||
* the whole body or not at all and so could only check the limit once every byte was in memory.
|
||||
* Deno, Bun, workerd and Node all expose `request.body` as a stream, so no runtime needs a branch.
|
||||
*/
|
||||
function readFetchBytes(
|
||||
source: unknown,
|
||||
@@ -110,8 +123,68 @@ function readFetchBytes(
|
||||
// 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) {
|
||||
// A declared length over the limit is refused before a single chunk is pulled. Cancelling is best
|
||||
// effort: it tells the runtime to stop the upload, and a refusal changes nothing about the answer.
|
||||
if (declaresOverLimit(request.headers.get('content-length'), limit)) {
|
||||
request.body.cancel().catch(() => {});
|
||||
return tooLarge(request, opts);
|
||||
}
|
||||
|
||||
// A well-formed declared length within the limit bounds the body already: the runtime's HTTP parser
|
||||
// frames it by that header, so `arrayBuffer()`, native in Bun, Deno and workerd, cannot overrun.
|
||||
// The reader loop below measured 4x slower on a Bun JSON POST. `byteLength` is still checked, for
|
||||
// a `Request` built in user code whose header and body disagree.
|
||||
if (/^\d+$/.test(request.headers.get('content-length') ?? '')) {
|
||||
return request
|
||||
.arrayBuffer()
|
||||
.then((buffer) =>
|
||||
buffer.byteLength > limit
|
||||
? tooLarge(request, opts)
|
||||
: { bytes: buffer.byteLength === 0 ? undefined : Buffer.from(buffer) },
|
||||
);
|
||||
}
|
||||
|
||||
// ponytail: one reader loop; a TransformStream byte-counter only if another consumer needs it
|
||||
return readBounded(request.body.getReader(), limit).then((bytes) =>
|
||||
bytes === null ? tooLarge(request, opts) : { bytes },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads until the stream ends, or until the running total crosses `limit` — then cancels the reader,
|
||||
* so no further chunk is pulled, and answers null. A rejected `read()` (the client went away)
|
||||
* propagates exactly as a rejected `arrayBuffer()` used to.
|
||||
*
|
||||
* workerd may strip `content-length` from a chunked upload, so there this count is the only check.
|
||||
* The answer is the same 413 either way; only how early it comes differs.
|
||||
*/
|
||||
async function readBounded(
|
||||
reader: ReadableStreamDefaultReader<Uint8Array>,
|
||||
limit: number,
|
||||
): Promise<Buffer | undefined | null> {
|
||||
const chunks: Uint8Array[] = [];
|
||||
let total = 0;
|
||||
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
|
||||
total += value.byteLength;
|
||||
|
||||
if (total > limit) {
|
||||
reader.cancel().catch(() => {});
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
chunks.push(value);
|
||||
}
|
||||
|
||||
return total === 0 ? undefined : Buffer.concat(chunks, total);
|
||||
}
|
||||
|
||||
/** The over-limit answer, shared by the declared-length check and the stream count. */
|
||||
function tooLarge(request: Request, opts: HttpOptions | undefined): BodyFailure {
|
||||
// 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);
|
||||
@@ -121,10 +194,6 @@ function readFetchBytes(
|
||||
headers: headersToRecord(request.headers),
|
||||
};
|
||||
return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError, opts?.logger) };
|
||||
}
|
||||
|
||||
return { bytes: arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer) };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -157,23 +226,43 @@ export function toBodyInit(body: string | Buffer): ResponseBody {
|
||||
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, bus?: Bus, correlation: Correlation = {}): Response {
|
||||
const headers = mergeInjectedHeaders(result.outcome.headers, result.injected) as Record<string, string>;
|
||||
/** Converts an outcome (already through `compressOutcome`) into a web `Response`, buffered or streamed. */
|
||||
function outcomeToResponse(
|
||||
outcome: NeutralOutcome,
|
||||
injected: Record<string, string>,
|
||||
bus?: Bus,
|
||||
correlation: Correlation = {},
|
||||
): Response {
|
||||
const headers = toWebHeaders(mergeInjectedHeaders(outcome.headers, injected));
|
||||
|
||||
if (result.outcome.kind === 'stream') {
|
||||
const body = asReadableStream(
|
||||
result.outcome.stream,
|
||||
result.outcome.encoder,
|
||||
bus,
|
||||
result.outcome.route,
|
||||
correlation,
|
||||
);
|
||||
return new Response(body, { headers });
|
||||
if (outcome.kind === 'stream') {
|
||||
const frames = asReadableStream(outcome.stream, outcome.encoder, bus, outcome.route, correlation);
|
||||
return new Response(outcome.encoding ? compressWebStream(frames, outcome.encoding) : frames, { headers });
|
||||
}
|
||||
|
||||
const body = [204, 205, 304].includes(result.outcome.status) ? null : toBodyInit(result.outcome.body);
|
||||
return new Response(body, { status: result.outcome.status, headers });
|
||||
const body = [204, 205, 304].includes(outcome.status) ? null : toBodyInit(outcome.body);
|
||||
return new Response(body, { status: outcome.status, headers });
|
||||
}
|
||||
|
||||
/** The first `x-forwarded-for` hop when the proxy is trusted, else `''`. */
|
||||
function forwardedFor(request: Request, opts: HttpOptions | undefined): string {
|
||||
if (!opts?.trustProxy) return '';
|
||||
|
||||
return (request.headers.get('x-forwarded-for') ?? '').split(',')[0].trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* `ctx.ip` on the fetch path, for `NeutralRequest.resolveIp`. Mirrors Node's `deriveIp`
|
||||
* (src/http/request.ts): only trust `x-forwarded-for` when the proxy is trusted, and take its first
|
||||
* hop, because an untrusted XFF is client-spoofable. Otherwise the socket peer, which only the Deno
|
||||
* and Bun adapters can supply; a bare `app.fetch` has none, so there the answer is still ''. Ahead of
|
||||
* both, under `trustProxy` only: the address the edge adapter read from `cf-connecting-ip`.
|
||||
* Cloudflare sets that header itself, while XFF can carry hops the client supplied, so on the edge
|
||||
* it wins (CARD-23).
|
||||
*/
|
||||
function fetchIp(source: unknown, opts: HttpOptions | undefined): string {
|
||||
const request = source as Request;
|
||||
return trustedProxyClient(request, opts?.trustProxy) || forwardedFor(request, opts) || peerOf(request);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -183,7 +272,7 @@ function outcomeToResponse(result: HandleResult, bus?: Bus, correlation: Correla
|
||||
* 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) {
|
||||
export function buildFetch(routes: RouteTable, opts: HttpOptions | undefined) {
|
||||
// Built once per server, not once per request — see `BodyReader`.
|
||||
const readBody: BodyReader = (source, limit) => readFetchBytes(source, limit, opts);
|
||||
const gate = createRequestGate(opts?.limits?.maxConcurrentRequests);
|
||||
@@ -220,20 +309,24 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
|
||||
|
||||
return new Response(JSON.stringify({ error: 'Service Unavailable' }), {
|
||||
status: 503,
|
||||
headers: mergeInjectedHeaders(
|
||||
headers: toWebHeaders(
|
||||
mergeInjectedHeaders(
|
||||
{
|
||||
'content-type': 'application/json',
|
||||
'retry-after': '1',
|
||||
},
|
||||
injected,
|
||||
),
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
acquired = gate.limited;
|
||||
|
||||
result = await handle(
|
||||
routes,
|
||||
// Read once per request: a mesh teacup swaps its table when peers come and go, and one
|
||||
// request must route and build `Allow` against the same table (CARD-19).
|
||||
currentRoutes(routes),
|
||||
opts,
|
||||
{
|
||||
...correlation,
|
||||
@@ -243,15 +336,7 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
|
||||
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()
|
||||
: '',
|
||||
resolveIp: fetchIp,
|
||||
},
|
||||
// Already computed above for the shed-503 path; handing it down keeps `cors.origins` to
|
||||
// one call per request.
|
||||
@@ -268,10 +353,35 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
|
||||
if ('preflight' in result) {
|
||||
return new Response(null, {
|
||||
status: 204,
|
||||
headers: mergeInjectedHeaders(result.preflight, injected),
|
||||
headers: toWebHeaders(mergeInjectedHeaders(result.preflight, injected)),
|
||||
});
|
||||
}
|
||||
|
||||
return outcomeToResponse(result, opts?.bus, correlation);
|
||||
const decided = compressOutcome(opts?.compression, { method: request.method, headers }, result.outcome);
|
||||
return decided instanceof Promise
|
||||
? decided.then((outcome) => outcomeToResponse(outcome, injected, opts?.bus, correlation))
|
||||
: outcomeToResponse(decided, injected, opts?.bus, correlation);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers a health probe through the Fetch API, or returns `undefined` for any other request (or when
|
||||
* `health` is off). `app.fetch` calls this before awaiting the boot, which is what lets `/__ready__`
|
||||
* report `booting` at all, and before the gate and `handle()`, for the same reasons as the Node adapter.
|
||||
*/
|
||||
export function answerFetchProbe(request: Request, opts: HttpOptions | undefined): Response | undefined {
|
||||
if (!opts?.health) return undefined;
|
||||
|
||||
const url = new URL(request.url);
|
||||
const probe = answerProbe(request.method, url.pathname + url.search, opts.health);
|
||||
if (!probe) return undefined;
|
||||
|
||||
const injected = computeInjected(opts, {
|
||||
secure: url.protocol === 'https:',
|
||||
headers: headersToRecord(request.headers),
|
||||
});
|
||||
return new Response(probe.body || null, {
|
||||
status: probe.status,
|
||||
headers: mergeInjectedHeaders(probe.headers, injected) as Record<string, string>,
|
||||
});
|
||||
}
|
||||
+66
-9
@@ -1,6 +1,6 @@
|
||||
import { channel } from '../channel';
|
||||
import { channel, type Channel } from '../channel';
|
||||
import type { App } from '../app/types';
|
||||
import type { WsRequest, WsSocket } from './ws-core';
|
||||
import { WS_HIGH_WATER_MARK, type WsRequest, type WsSocket } from './ws-core';
|
||||
import { nodeRequire } from '../node-require';
|
||||
|
||||
/**
|
||||
@@ -10,6 +10,7 @@ import { nodeRequire } from '../node-require';
|
||||
*/
|
||||
|
||||
const decoder = new TextDecoder();
|
||||
const CONNECTING = 0; // WebSocket.CONNECTING
|
||||
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()). */
|
||||
@@ -36,9 +37,16 @@ export function toWsRequest(request: Request, ip: string): WsRequest {
|
||||
};
|
||||
}
|
||||
|
||||
/** The subset of a host WebSocket that {@link eventSocket} drives (Deno's WebSocket and workerd's both satisfy it). */
|
||||
/**
|
||||
* The subset of a host WebSocket that {@link eventSocket} drives (Deno's WebSocket and workerd's both satisfy it).
|
||||
*
|
||||
* @experimental Part of the mesh, which needs `createApp({ experimental: true })`: outside the
|
||||
* API freeze, so it may change in a minor release.
|
||||
*/
|
||||
export interface EventfulSocket {
|
||||
readonly readyState: number;
|
||||
/** Bytes queued by `send` and not yet written. Deno reports it; a host without it is never waited on. */
|
||||
readonly bufferedAmount?: number;
|
||||
send(data: string): void;
|
||||
close(code?: number, reason?: string): void;
|
||||
addEventListener(
|
||||
@@ -69,7 +77,18 @@ export function eventSocket(host: EventfulSocket): WsSocket {
|
||||
ac.abort();
|
||||
});
|
||||
|
||||
return neutralSocket(host, inbound, ac);
|
||||
const socket = neutralSocket(host, inbound, ac);
|
||||
const closeNow = socket.close;
|
||||
|
||||
// Deno hands the socket over still CONNECTING: its 101 has not gone out yet, and a close in
|
||||
// that state is a no-op, so a route that refuses straight away (1008) left the peer hanging.
|
||||
// Deferring to 'open' is what lets that close reach the client at all.
|
||||
return Object.assign(socket, {
|
||||
close: (code?: number, reason?: string) => {
|
||||
if (host.readyState === CONNECTING) host.addEventListener('open', () => closeNow(code, reason));
|
||||
else closeNow(code, reason);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -78,8 +97,8 @@ export function eventSocket(host: EventfulSocket): WsSocket {
|
||||
* 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>>,
|
||||
host: Pick<EventfulSocket, 'readyState' | 'send' | 'close' | 'bufferedAmount'> & { terminate?(): void },
|
||||
inbound: Channel<unknown>,
|
||||
ac: AbortController,
|
||||
): WsSocket {
|
||||
return {
|
||||
@@ -91,6 +110,7 @@ export function neutralSocket(
|
||||
send: (data) => {
|
||||
host.send(data);
|
||||
},
|
||||
drained: () => pollDrained(host, ac.signal),
|
||||
close: (code, reason) => {
|
||||
try {
|
||||
host.close(code, reason);
|
||||
@@ -108,12 +128,49 @@ export function neutralSocket(
|
||||
};
|
||||
}
|
||||
|
||||
/** Constructs a host WebSocket *client*. Both the platform global and the `ws` package satisfy it. */
|
||||
/** How often {@link pollDrained} rereads `bufferedAmount` while a socket is backed up. */
|
||||
const DRAIN_POLL_MS = 10;
|
||||
|
||||
/**
|
||||
* {@link WsSocket.drained} for a host that reports `bufferedAmount` but fires no drain event —
|
||||
* the Web `WebSocket` API has none. Polls only while the socket is over the mark, so a socket that
|
||||
* keeps up never starts a timer; the close (`signal`) ends the wait at once.
|
||||
*
|
||||
* A socket still CONNECTING is not writable either, and waits too. Deno hands its socket over in
|
||||
* that state, and a route that yielded at once had its first frame pulled, found the socket not
|
||||
* open, and the pump gave up on the connection.
|
||||
*/
|
||||
async function pollDrained(host: Pick<EventfulSocket, 'readyState' | 'bufferedAmount'>, signal: AbortSignal) {
|
||||
const backedUp = () =>
|
||||
host.readyState === CONNECTING || (host.readyState === OPEN && (host.bufferedAmount ?? 0) > WS_HIGH_WATER_MARK);
|
||||
|
||||
while (!signal.aborted && backedUp()) {
|
||||
await new Promise<void>((resolve) => {
|
||||
const done = () => {
|
||||
clearTimeout(timer);
|
||||
signal.removeEventListener('abort', done);
|
||||
resolve();
|
||||
};
|
||||
|
||||
const timer = setTimeout(done, DRAIN_POLL_MS);
|
||||
signal.addEventListener('abort', done, { once: true });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a host WebSocket *client*. Both the platform global and the `ws` package satisfy it.
|
||||
*
|
||||
* @experimental Part of the mesh, which needs `createApp({ experimental: true })`: outside the
|
||||
* API freeze, so it may change in a minor release.
|
||||
*/
|
||||
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.
|
||||
* The WebSocket client implementation: the platform global where it exists, else the `ws`
|
||||
* optional peer. Every supported runtime has the global — Deno, Bun, and Node from 22, the
|
||||
* declared floor — so the fallback is reached only when Node runs with the global switched off
|
||||
* (`--no-experimental-websocket`). `ws` is installed anyway for the server side.
|
||||
*
|
||||
* 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
|
||||
|
||||
+344
-3
@@ -1,8 +1,9 @@
|
||||
import { isHttpError } from '../signals';
|
||||
import { CHANNEL_TAP, releaseIterator, type TappableChannel } from '../channel';
|
||||
import type { Bus } from '../bus';
|
||||
import { correlateRequest } from './core';
|
||||
import { matchPattern } from './router';
|
||||
import type { WsRouteDef } from './types';
|
||||
import type { WsRouteDef, RequestLimits } from './types';
|
||||
|
||||
/** Neutral, runtime-free WebSocket request context (replaces the raw Node req). */
|
||||
export interface WsRequest {
|
||||
@@ -20,6 +21,337 @@ export interface WsSocket {
|
||||
send(data: string): void;
|
||||
close(code?: number, reason?: string): void;
|
||||
terminate(): void;
|
||||
/**
|
||||
* Resolves once the socket's send buffer is at or below the adapter's high-water mark, or the
|
||||
* socket has closed — at once when it already is (#41). The outbound pump awaits it before
|
||||
* pulling the next value, so a fast producer cannot grow the buffer without limit.
|
||||
*
|
||||
* Optional: a socket without it is never waited on, which is how every socket behaved before.
|
||||
* The mark is the adapter's; {@link WS_HIGH_WATER_MARK} is what the built-in adapters use.
|
||||
*/
|
||||
drained?(): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send-buffer level, in bytes, above which the built-in adapters report a socket as backed up
|
||||
* (#41). Internal, not an option: it bounds what one slow peer can make the process hold, and
|
||||
* a frame is sent whole, so the buffer peaks at this plus one frame.
|
||||
*/
|
||||
export const WS_HIGH_WATER_MARK = 1_048_576;
|
||||
|
||||
/** The tail of each socket's {@link sendWhenDrained} queue. */
|
||||
const sendQueues = new WeakMap<WsSocket, Promise<void>>();
|
||||
|
||||
/**
|
||||
* Sends on `socket` in call order, each frame only once {@link WsSocket.drained} lets it (#41).
|
||||
* For senders outside the outbound pump, such as concurrent mesh RPCs. Waiting one at a time is
|
||||
* the point: callers that each waited on their own would all be released by the same drain and
|
||||
* all send, putting one frame per caller over the mark. Queued, the buffer peaks at the mark plus
|
||||
* one frame, however many callers wait.
|
||||
*
|
||||
* `frame` runs at send time, so a caller that settled while queued (a timeout) returns
|
||||
* `undefined` and sends nothing. Nothing is sent once the socket has closed.
|
||||
*/
|
||||
export function sendWhenDrained(socket: WsSocket, frame: () => string | undefined): Promise<void> {
|
||||
const sent = (sendQueues.get(socket) ?? Promise.resolve()).then(async () => {
|
||||
if (socket.drained) await socket.drained();
|
||||
if (socket.abort.aborted) return;
|
||||
const data = frame();
|
||||
if (data !== undefined) socket.send(data);
|
||||
});
|
||||
sendQueues.set(
|
||||
socket,
|
||||
sent.catch(() => {}),
|
||||
);
|
||||
return sent;
|
||||
}
|
||||
|
||||
/** Default for `limits.maxWsMessageBytes`: 1 MiB. */
|
||||
export const DEFAULT_MAX_WS_MESSAGE_BYTES = 1_048_576;
|
||||
/** Default for `limits.maxWsQueue`, in undelivered inbound messages per connection (D1). */
|
||||
export const DEFAULT_MAX_WS_QUEUE = 16;
|
||||
|
||||
/**
|
||||
* Where `createApp` leaves the resolved `maxWsMessageBytes` for `serveBun`, which needs it as
|
||||
* Bun's native `maxPayloadLength` and has no other path to the app's options. Internal, not part
|
||||
* of the public `App` type; `Symbol.for` because each tsup entry carries its own copy of this
|
||||
* module, and only the global registry resolves to one symbol across them.
|
||||
*/
|
||||
export const WS_MAX_MESSAGE_BYTES: unique symbol = Symbol.for('green-tea.ws-max-message-bytes');
|
||||
|
||||
/** The effective `limits.maxWsMessageBytes`. */
|
||||
export function wsMessageBytes(limits: Pick<RequestLimits, 'maxWsMessageBytes'> | undefined): number {
|
||||
return limits?.maxWsMessageBytes ?? DEFAULT_MAX_WS_MESSAGE_BYTES;
|
||||
}
|
||||
|
||||
/**
|
||||
* Undelivered inbound frames the mesh control channel may hold once its peer is authenticated
|
||||
* (#148), in place of `limits.maxWsQueue` when larger. Its consumer, the teapot's frame loop, never
|
||||
* awaits between frames, so its queue only ever holds one delivery burst: `ws` emits every frame of
|
||||
* one socket read synchronously, and a read is at most 64 KiB, under 4,096 of the smallest control
|
||||
* frame (`{"type":"ping"}`). A teacup with many RPCs in flight sends exactly such bursts, which the
|
||||
* 16-frame user default closed with 1013.
|
||||
*/
|
||||
const CONTROL_QUEUE = 4096;
|
||||
|
||||
/**
|
||||
* Largest frame the mesh control channel accepts before its peer's `hello` is accepted. A hello
|
||||
* is a version and a secret; nothing larger has a reason to arrive first.
|
||||
*/
|
||||
export const HELLO_FRAME_BYTES = 65_536;
|
||||
|
||||
/** Inbound bounds for one socket, as {@link boundInbound} takes them. */
|
||||
type InboundLimits = { maxWsMessageBytes: number; maxWsQueue: number };
|
||||
|
||||
/**
|
||||
* The bounds of the mesh control channel's socket, in two phases.
|
||||
*
|
||||
* - `preAuth`, until the peer's `hello` is accepted: hello-sized frames and the default 16-frame
|
||||
* queue, so an unauthenticated peer can make the process hold about 1 MiB at most — including
|
||||
* while `app.upgrade` waits for a slow boot, before anything reads the queue.
|
||||
* - `authed`, after: `maxWsMessageBytes` raised to the channel's frame bound (#120) and `maxWsQueue`
|
||||
* to {@link CONTROL_QUEUE} (#148), each only when larger. The peer holds the mesh secret by then.
|
||||
*
|
||||
* A user route never goes through this, so it keeps both limits as configured.
|
||||
*/
|
||||
export function controlBounds(
|
||||
limits: Pick<RequestLimits, 'maxWsMessageBytes' | 'maxWsQueue'> | undefined,
|
||||
maxFrameBytes: number | undefined,
|
||||
): { preAuth: InboundLimits; authed: InboundLimits } {
|
||||
return {
|
||||
preAuth: { maxWsMessageBytes: HELLO_FRAME_BYTES, maxWsQueue: DEFAULT_MAX_WS_QUEUE },
|
||||
authed: {
|
||||
maxWsMessageBytes: Math.max(wsMessageBytes(limits), maxFrameBytes ?? 0),
|
||||
maxWsQueue: Math.max(limits?.maxWsQueue ?? DEFAULT_MAX_WS_QUEUE, CONTROL_QUEUE),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Where a socket bounded with a second phase keeps the switch to it; `Symbol.for`, as above. */
|
||||
const WIDEN_INBOUND: unique symbol = Symbol.for('green-tea.widen-inbound');
|
||||
|
||||
/**
|
||||
* Switches a socket from {@link boundInbound}'s first bounds to the `widened` ones it was given —
|
||||
* for the mesh control channel, once the peer has authenticated. A no-op on any other socket.
|
||||
* Frames already queued stay; the new bounds apply to the frames that arrive next.
|
||||
*/
|
||||
export function widenInbound(socket: WsSocket): void {
|
||||
(socket as { [WIDEN_INBOUND]?: () => void })[WIDEN_INBOUND]?.();
|
||||
}
|
||||
|
||||
/** Throws when a WebSocket limit is present but not a positive safe integer (#107). */
|
||||
export function validateWsLimits(limits: RequestLimits | undefined): void {
|
||||
for (const key of ['maxWsMessageBytes', 'maxWsQueue'] as const) {
|
||||
const value: unknown = limits?.[key];
|
||||
if (value === undefined || (Number.isSafeInteger(value) && (value as number) > 0)) continue;
|
||||
const shown = typeof value === 'string' ? `'${value}'` : String(value);
|
||||
throw new TypeError(`limits.${key} must be a positive integer, got ${shown}`);
|
||||
}
|
||||
}
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
/** True when `msg`'s UTF-8 encoding is longer than `max` bytes. */
|
||||
function exceedsBytes(msg: unknown, max: number): boolean {
|
||||
if (typeof msg !== 'string') return false; // every adapter delivers strings; nothing else to measure
|
||||
// A UTF-16 unit encodes to 1–3 UTF-8 bytes, so both bounds below are exact. Only a string in
|
||||
// between pays for the encode — which is never one of the short messages that dominate.
|
||||
if (msg.length * 3 <= max) return false;
|
||||
if (msg.length > max) return true;
|
||||
return encoder.encode(msg).byteLength > max;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bounds a socket's inbound side (#107): a frame over `maxWsMessageBytes` closes `1009`, and a
|
||||
* frame that arrives while `maxWsQueue` frames are still undelivered closes `1013`. Nothing is
|
||||
* dropped silently — the peer learns which bound it hit from the close code.
|
||||
*
|
||||
* Subscribes to `socket.inbound` immediately. `channel` is fan-out, so a frame pushed with no
|
||||
* subscriber is lost; subscribing here, before any boot or step runs, is what keeps the first
|
||||
* frames — for the mesh control channel, the `hello` itself. Those early frames go to the first
|
||||
* consumer. After that the returned `inbound` fans out like `channel`: each iterator gets every
|
||||
* frame from the moment it subscribes, through its own queue, and the bound applies to each queue.
|
||||
* Every other capability is the original socket's.
|
||||
*
|
||||
* `widened`, when given, is a second set of bounds that {@link widenInbound} switches to later: the
|
||||
* mesh control channel starts at hello size and widens once its peer authenticates. `onWiden` runs
|
||||
* then too, for an adapter that holds a bound of its own until that point.
|
||||
*/
|
||||
export function boundInbound(
|
||||
socket: WsSocket,
|
||||
limits?: Pick<RequestLimits, 'maxWsMessageBytes' | 'maxWsQueue'>,
|
||||
widened?: InboundLimits,
|
||||
onWiden?: () => void,
|
||||
): WsSocket {
|
||||
const fanout = new InboundFanout(socket, wsMessageBytes(limits), limits?.maxWsQueue ?? DEFAULT_MAX_WS_QUEUE);
|
||||
|
||||
const tap = (socket.inbound as Partial<TappableChannel<unknown>>)[CHANNEL_TAP];
|
||||
if (tap) fanout.tap(tap);
|
||||
else void fanout.pump();
|
||||
|
||||
return Object.create(socket, {
|
||||
inbound: { value: { [Symbol.asyncIterator]: () => fanout.subscribe() } },
|
||||
...(widened && {
|
||||
[WIDEN_INBOUND]: {
|
||||
value: () => {
|
||||
fanout.widen(widened);
|
||||
onWiden?.();
|
||||
},
|
||||
},
|
||||
}),
|
||||
}) as WsSocket;
|
||||
}
|
||||
|
||||
/** The fan-out behind {@link boundInbound}: one bounded queue per consumer. */
|
||||
class InboundFanout {
|
||||
private readonly subs = new Set<InboundSub>();
|
||||
/** Holds the frames that arrive before anyone reads; handed to the first consumer. */
|
||||
private first: InboundSub | null;
|
||||
private ended = false;
|
||||
private failure: { err: unknown } | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly socket: WsSocket,
|
||||
private maxBytes: number,
|
||||
private maxQueue: number,
|
||||
) {
|
||||
this.first = this.add();
|
||||
}
|
||||
|
||||
/** Applies the second phase's bounds; see {@link widenInbound}. */
|
||||
widen(limits: InboundLimits): void {
|
||||
this.maxBytes = limits.maxWsMessageBytes;
|
||||
this.maxQueue = limits.maxWsQueue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the adapter's channel inside its `push`. Runtimes emit a whole read's worth of frames
|
||||
* synchronously — `ws` does — so a bound checked after the event loop yields is checked after an
|
||||
* unbounded queue has already taken the burst. Here each frame is bounded before it is queued.
|
||||
*/
|
||||
tap(tap: TappableChannel<unknown>[typeof CHANNEL_TAP]): void {
|
||||
const untap = tap({
|
||||
push: (msg) => {
|
||||
if (this.ended || this.accept(msg)) return;
|
||||
untap();
|
||||
this.settle();
|
||||
},
|
||||
end: () => this.settle(),
|
||||
fail: (err) => this.settle({ err }),
|
||||
});
|
||||
}
|
||||
|
||||
// ponytail: only for an inbound that is not a channel (no adapter builds one); bounds late.
|
||||
async pump(): Promise<void> {
|
||||
try {
|
||||
for await (const msg of this.socket.inbound) {
|
||||
if (this.ended || !this.accept(msg)) break;
|
||||
}
|
||||
|
||||
this.settle();
|
||||
} catch (err) {
|
||||
this.settle({ err });
|
||||
}
|
||||
}
|
||||
|
||||
subscribe(): AsyncIterator<unknown> {
|
||||
const sub = this.first ?? this.add();
|
||||
this.first = null;
|
||||
return sub;
|
||||
}
|
||||
|
||||
private add(): InboundSub {
|
||||
const sub = new InboundSub(() => this.subs.delete(sub));
|
||||
if (this.ended) sub.settle(this.failure ?? undefined);
|
||||
else this.subs.add(sub);
|
||||
return sub;
|
||||
}
|
||||
|
||||
/** Delivers or queues one frame for every consumer; returns false once it has closed the socket. */
|
||||
private accept(msg: unknown): boolean {
|
||||
if (exceedsBytes(msg, this.maxBytes)) {
|
||||
this.socket.close(1009, 'message too large');
|
||||
return false;
|
||||
}
|
||||
|
||||
// Capacity first, for every consumer: a frame that overflows one queue reaches none, so a
|
||||
// rejected frame cannot run some handlers' side effects and not others'.
|
||||
for (const sub of this.subs) {
|
||||
if (sub.full(this.maxQueue)) {
|
||||
this.socket.close(1013, 'inbound queue full');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
for (const sub of this.subs) sub.offer(msg);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Ends every consumer once, cleanly or with a failure; whatever is still queued is delivered first. */
|
||||
private settle(failure?: { err: unknown }): void {
|
||||
if (this.ended) return;
|
||||
this.ended = true;
|
||||
this.failure = failure ?? null;
|
||||
for (const sub of this.subs) sub.settle(failure);
|
||||
this.subs.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/** One consumer's queue; it is its own async iterator. */
|
||||
class InboundSub implements AsyncIterator<unknown> {
|
||||
private readonly queue: unknown[] = [];
|
||||
private waiter: { resolve: (r: IteratorResult<unknown>) => void; reject: (e: unknown) => void } | null = null;
|
||||
private ended = false;
|
||||
private failure: { err: unknown } | null = null;
|
||||
|
||||
constructor(private readonly onReturn: () => void) {}
|
||||
|
||||
/** True when `max` frames are already waiting and no `next()` is there to take another. */
|
||||
full(max: number): boolean {
|
||||
return !this.waiter && this.queue.length >= max;
|
||||
}
|
||||
|
||||
/** Hands `msg` to a waiting `next()` or queues it; callers check {@link full} first. */
|
||||
offer(msg: unknown): void {
|
||||
const waiter = this.waiter;
|
||||
|
||||
if (waiter) {
|
||||
this.waiter = null;
|
||||
waiter.resolve({ value: msg, done: false });
|
||||
return;
|
||||
}
|
||||
|
||||
this.queue.push(msg);
|
||||
}
|
||||
|
||||
next(): Promise<IteratorResult<unknown>> {
|
||||
if (this.queue.length) return Promise.resolve({ value: this.queue.shift(), done: false });
|
||||
if (this.failure) return Promise.reject(this.failure.err);
|
||||
if (this.ended) return Promise.resolve({ value: undefined, done: true });
|
||||
return new Promise((resolve, reject) => {
|
||||
this.waiter = { resolve, reject };
|
||||
});
|
||||
}
|
||||
|
||||
// A consumer that stops reading has said it wants no more; queueing for it would only close
|
||||
// the connection for a bound it no longer cares about. Other consumers keep receiving.
|
||||
return(): Promise<IteratorResult<unknown>> {
|
||||
this.queue.length = 0;
|
||||
this.onReturn();
|
||||
this.settle();
|
||||
return Promise.resolve({ value: undefined, done: true });
|
||||
}
|
||||
|
||||
settle(failure?: { err: unknown }): void {
|
||||
if (this.ended) return;
|
||||
this.ended = true;
|
||||
this.failure = failure ?? null;
|
||||
const waiter = this.waiter;
|
||||
this.waiter = null;
|
||||
if (!waiter) return;
|
||||
if (failure) waiter.reject(failure.err);
|
||||
else waiter.resolve({ value: undefined, done: true });
|
||||
}
|
||||
}
|
||||
|
||||
/** Finds the first ws route whose pattern matches `path`, capturing its params. */
|
||||
@@ -65,9 +397,18 @@ function trackConnection(socket: WsSocket, streams?: Set<() => void>): { closer:
|
||||
return { closer };
|
||||
}
|
||||
|
||||
/** Drives the outbound async iterator, sending each yielded value until done or the socket closes. */
|
||||
/**
|
||||
* Drives the outbound async iterator, sending each yielded value until done or the socket closes.
|
||||
* Waits for {@link WsSocket.drained} before each pull (#41): a value pulled while the peer is
|
||||
* backed up has nowhere to go but the send buffer, so it is not pulled until there is room.
|
||||
*/
|
||||
async function pumpOutbound(socket: WsSocket, iterator: AsyncIterator<unknown>): Promise<void> {
|
||||
while (true) {
|
||||
if (socket.drained) await socket.drained();
|
||||
// Closed while waiting: stop before pulling a value nobody can receive. The abort listener in
|
||||
// `runWsConnection` has already called the iterator's `return()`. `abort`, not `isOpen`: Deno
|
||||
// hands a socket over still CONNECTING, which is not open yet and not closed either.
|
||||
if (socket.abort.aborted) break;
|
||||
const { value, done } = await iterator.next();
|
||||
if (done) break;
|
||||
if (!socket.isOpen) break;
|
||||
@@ -119,7 +460,7 @@ export async function runWsConnection(
|
||||
|
||||
const onAbort = () => {
|
||||
streams?.delete(closer);
|
||||
void Promise.resolve(iterator?.return?.()).catch(() => {});
|
||||
releaseIterator(iterator);
|
||||
};
|
||||
|
||||
socket.abort.addEventListener('abort', onAbort, { once: true });
|
||||
|
||||
+152
-15
@@ -1,9 +1,22 @@
|
||||
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';
|
||||
import {
|
||||
runWsConnection,
|
||||
matchWsRoute,
|
||||
trackUntil,
|
||||
boundInbound,
|
||||
controlBounds,
|
||||
wsMessageBytes,
|
||||
HELLO_FRAME_BYTES,
|
||||
WS_HIGH_WATER_MARK,
|
||||
type WsSocket,
|
||||
type WsRequest,
|
||||
} from './ws-core';
|
||||
import type { WsRouteDef, MeshControl, RequestLimits } from './types';
|
||||
import { normalizeRequestPath } from './router';
|
||||
import { nodeRequire } from '../node-require';
|
||||
import { MESH_CONTROL_DISABLED_REASON, MESH_CONTROL_PATH } from '../mesh/teapot';
|
||||
|
||||
/** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */
|
||||
function loadWss(): any | null {
|
||||
@@ -16,9 +29,9 @@ function loadWss(): any | 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');
|
||||
/** Writes a bodyless HTTP status to the raw socket and destroys it. */
|
||||
function rejectUpgrade(socket: any, status: number, text: string): void {
|
||||
socket.write(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
|
||||
socket.destroy();
|
||||
}
|
||||
|
||||
@@ -31,27 +44,81 @@ function handleMeshUpgrade(
|
||||
socket: any,
|
||||
head: Buffer,
|
||||
streams?: Set<() => void>,
|
||||
limits?: RequestLimits,
|
||||
): boolean {
|
||||
if (path !== meshControl.path) return false;
|
||||
|
||||
if (!wss) {
|
||||
reject501(socket);
|
||||
rejectUpgrade(socket, 501, 'Not Implemented');
|
||||
return true;
|
||||
}
|
||||
|
||||
// An RPC carries a whole request body, so once the peer authenticates the channel is bounded by
|
||||
// the teapot's body limit rather than `maxWsMessageBytes` (#120). `wss` is built with that bound
|
||||
// as `maxPayload`; until the hello is accepted, `boundInbound` holds the peer to hello size, and
|
||||
// `capPreAuthBytes` keeps `ws` from assembling anything larger first.
|
||||
const bounds = controlBounds(limits, meshControl.maxFrameBytes);
|
||||
|
||||
// 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);
|
||||
const lift = capPreAuthBytes(ws, socket, head);
|
||||
const neutral = boundInbound(nodeSocket(ws), bounds.preAuth, bounds.authed, lift);
|
||||
|
||||
void trackUntil(neutral, meshControl.handle(neutral), streams);
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Bytes an unauthenticated control peer may send: one hello-sized frame plus headers and a close frame. */
|
||||
const PRE_AUTH_WIRE_BYTES = HELLO_FRAME_BYTES + 1024;
|
||||
|
||||
/**
|
||||
* Closes a control peer that sends more than a hello's worth of bytes before its hello is accepted.
|
||||
* `maxPayload` is set once per `WebSocketServer`, and the control channel's must fit an
|
||||
* authenticated RPC (about 7 MB at the defaults), so without this an unauthenticated peer could
|
||||
* make `ws` assemble a frame that size before `boundInbound` sees it and refuses it. This counts
|
||||
* raw socket bytes instead, so the peer is closed `1009` about 64 KiB in. Returns the function that
|
||||
* stops counting, for when the peer authenticates.
|
||||
*
|
||||
* Installed in the `handleUpgrade` callback, after `ws` has attached its own `data` listener: a
|
||||
* listener added earlier would switch the socket to flowing mode and lose chunks `ws` never saw.
|
||||
*/
|
||||
function capPreAuthBytes(ws: any, socket: any, head: Buffer): () => void {
|
||||
let received = head.length;
|
||||
|
||||
const count = (chunk: Buffer) => {
|
||||
received += chunk.length;
|
||||
|
||||
if (received > PRE_AUTH_WIRE_BYTES) {
|
||||
socket.off('data', count);
|
||||
// 1009, as every other runtime closes an oversized frame. Paused, so `ws` reads nothing more
|
||||
// of it; `end` still flushes the close frame. `ws` destroys the socket at its close timeout.
|
||||
ws.close(1009, 'message too big');
|
||||
socket.pause();
|
||||
socket.end();
|
||||
}
|
||||
};
|
||||
|
||||
socket.on('data', count);
|
||||
return () => socket.off('data', count);
|
||||
}
|
||||
|
||||
/** Accepts an upgrade to the reserved mesh path on an app without a control channel, then closes it 1008. */
|
||||
function refuseMeshUpgrade(wss: any, req: http.IncomingMessage, socket: any, head: Buffer): void {
|
||||
if (!wss) {
|
||||
rejectUpgrade(socket, 501, 'Not Implemented');
|
||||
return;
|
||||
}
|
||||
|
||||
wss.handleUpgrade(req, socket, head, (ws: { close(code: number, reason: string): void }) =>
|
||||
ws.close(1008, MESH_CONTROL_DISABLED_REASON),
|
||||
);
|
||||
}
|
||||
|
||||
/** 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 {
|
||||
@@ -66,10 +133,21 @@ function nodeWsRequest(req: http.IncomingMessage): WsRequest {
|
||||
function nodeSocket(ws: any): WsSocket {
|
||||
const inbound = channel<unknown>();
|
||||
const ac = new AbortController();
|
||||
// `drained` callers waiting for the send buffer to fall to the mark (#41). Released by a send
|
||||
// callback, which `ws` runs once that frame is written to the TCP socket, or by the close.
|
||||
const waiters: Array<() => void> = [];
|
||||
const release = () => waiters.splice(0).forEach((resolve) => resolve());
|
||||
const backedUp = () => ws.readyState === 1 && ws.bufferedAmount > WS_HIGH_WATER_MARK;
|
||||
|
||||
const written = () => {
|
||||
if (!backedUp()) release();
|
||||
};
|
||||
|
||||
ws.on('message', (data: Buffer) => inbound.push(data.toString()));
|
||||
ws.on('close', () => {
|
||||
inbound.close();
|
||||
ac.abort();
|
||||
release();
|
||||
});
|
||||
ws.on('error', (err: unknown) => inbound.fail(err));
|
||||
return {
|
||||
@@ -78,7 +156,8 @@ function nodeSocket(ws: any): WsSocket {
|
||||
get isOpen() {
|
||||
return ws.readyState === 1; // 1 = OPEN
|
||||
},
|
||||
send: (data) => ws.send(data),
|
||||
send: (data) => ws.send(data, written),
|
||||
drained: () => (backedUp() ? new Promise<void>((resolve) => waiters.push(resolve)) : Promise.resolve()),
|
||||
close: (code, reason) => {
|
||||
try {
|
||||
ws.close(code, reason);
|
||||
@@ -97,29 +176,87 @@ export function attachWs(
|
||||
bus?: Bus,
|
||||
meshControl?: MeshControl,
|
||||
streams?: Set<() => void>,
|
||||
limits?: RequestLimits,
|
||||
): void {
|
||||
if (wsRoutes.length === 0 && !meshControl) return;
|
||||
const WebSocketServer = loadWss();
|
||||
const wss = WebSocketServer ? new WebSocketServer({ noServer: true }) : null;
|
||||
// `maxPayload` is the pre-buffer half of `maxWsMessageBytes`: `ws` refuses an oversized frame,
|
||||
// fragmented or not, before it is assembled, and closes 1009 itself. `boundInbound` repeats the
|
||||
// check on the decoded text, which is the only half Deno and the edge have.
|
||||
const wss = WebSocketServer ? new WebSocketServer({ noServer: true, maxPayload: wsMessageBytes(limits) }) : null;
|
||||
// The control channel's own server, so its larger bound (#120) never reaches a user route.
|
||||
const meshWss =
|
||||
WebSocketServer && meshControl
|
||||
? new WebSocketServer({
|
||||
noServer: true,
|
||||
maxPayload: controlBounds(limits, meshControl.maxFrameBytes).authed.maxWsMessageBytes,
|
||||
})
|
||||
: null;
|
||||
server.on('upgrade', (req, socket, head) => {
|
||||
const path = (req.url ?? '/').split('?')[0];
|
||||
// A peer that resets mid-rejection must not raise an unhandled 'error' on a socket nobody
|
||||
// else is listening to yet: that is as fatal as a throw.
|
||||
socket.on('error', () => {});
|
||||
|
||||
if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head, streams)) return;
|
||||
// Nothing thrown in here may escape. This is a raw EventEmitter listener, so a throw is an
|
||||
// uncaught exception that takes the whole process down, not a 500 for one client.
|
||||
try {
|
||||
routeUpgrade({ wss, meshWss, wsRoutes, bus, meshControl, streams, limits }, req, socket, head);
|
||||
} catch {
|
||||
if (socket.writable) rejectUpgrade(socket, 500, 'Internal Server Error');
|
||||
else socket.destroy();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** What every upgrade on one server shares. */
|
||||
interface UpgradeEnv {
|
||||
wss: any;
|
||||
/** The mesh control channel's server, bounded by its own frame limit (#120). */
|
||||
meshWss: any;
|
||||
wsRoutes: WsRouteDef[];
|
||||
bus?: Bus;
|
||||
meshControl?: MeshControl;
|
||||
streams?: Set<() => void>;
|
||||
limits?: RequestLimits;
|
||||
}
|
||||
|
||||
/** Routes one upgrade: validates the path the way HTTP does, then mesh control, then the ws route table. */
|
||||
function routeUpgrade(env: UpgradeEnv, req: http.IncomingMessage, socket: any, head: Buffer): void {
|
||||
const { wss, meshWss, wsRoutes, bus, meshControl, streams, limits } = env;
|
||||
let path: string;
|
||||
|
||||
// The same normalization the HTTP path runs (`dispatch` in core.ts). Without it a malformed
|
||||
// escape reaches `decodeURIComponent` in the matcher and throws, and `//` silently matches.
|
||||
try {
|
||||
path = normalizeRequestPath((req.url ?? '/').split('?')[0]);
|
||||
} catch {
|
||||
rejectUpgrade(socket, 400, 'Bad Request');
|
||||
return;
|
||||
}
|
||||
|
||||
if (meshControl && handleMeshUpgrade(meshWss, meshControl, path, req, socket, head, streams, limits)) return;
|
||||
|
||||
// The reserved path with no control channel: refused exactly as `app.upgrade` refuses it on Deno,
|
||||
// Bun and the edge — accept, then close 1008 with the same reason (D17). Never falls through to the
|
||||
// ws route table: the boot already refuses any route that claims this path.
|
||||
if (path === MESH_CONTROL_PATH) {
|
||||
refuseMeshUpgrade(wss, req, socket, head);
|
||||
return;
|
||||
}
|
||||
|
||||
const route = matchWsRoute(wsRoutes, path);
|
||||
|
||||
if (!route) {
|
||||
socket.destroy();
|
||||
rejectUpgrade(socket, 404, 'Not Found');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!wss) {
|
||||
reject501(socket);
|
||||
rejectUpgrade(socket, 501, 'Not Implemented');
|
||||
return;
|
||||
}
|
||||
|
||||
wss.handleUpgrade(req, socket, head, (ws: any) => {
|
||||
void runWsConnection(nodeSocket(ws), nodeWsRequest(req), route, bus, streams);
|
||||
});
|
||||
void runWsConnection(boundInbound(nodeSocket(ws), limits), nodeWsRequest(req), route, bus, streams);
|
||||
});
|
||||
}
|
||||
+20
-9
@@ -18,11 +18,11 @@ export const VERSION = '26.9.0-beta.2';
|
||||
|
||||
// Application
|
||||
export { createApp } from './app';
|
||||
export type { App, InspectLine, Explain, MeshConfig } from './app';
|
||||
export type { App, AppOptions, InspectLine, Explain, ExplainNode, MeshConfig } from './app';
|
||||
|
||||
// Graph visualization
|
||||
export { toMermaid, toDOT } from './graph-viz';
|
||||
export type { GraphView } from './graph-viz';
|
||||
export type { GraphView, GraphNodeView, GraphRouteView } from './graph-viz';
|
||||
export { buildOpenApi } from './openapi';
|
||||
export type { OpenApiDoc, OpenApiInfo, OpenApiRoute } from './openapi';
|
||||
|
||||
@@ -48,7 +48,7 @@ export {
|
||||
Options,
|
||||
Html,
|
||||
} from './metadata';
|
||||
export type { Transport, HttpMethod, RouteDecorator, TransformerFn } from './metadata';
|
||||
export type { Transport, HttpMethod, RouteDecorator, TransformerFn, ModuleOptions, Ctor } from './metadata';
|
||||
export type { Plugin, PluginApi, ScopeApi, ScopeNode } from './plugin';
|
||||
export type { Hooks } from './app';
|
||||
export type { TeardownFn } from './lifecycle';
|
||||
@@ -78,12 +78,16 @@ export { flow, Flow } from './flow';
|
||||
export type { StepFn, CompiledFlow } from './flow';
|
||||
|
||||
// Parameter decorators
|
||||
export { needs, ctx, param, query, body, headers, header, inbound, abort } from './params';
|
||||
export type { Query, Headers, Context, ArgSpec, ArgDecorator } from './params';
|
||||
export { needs, ctx, param, query, body, headers, header, cookies, cookie, inbound, abort } from './params';
|
||||
export type { Query, RequestHeaders, Headers, Context, ArgSpec, ArgSource, ArgDecorator } from './params';
|
||||
|
||||
// Cookies
|
||||
export { setCookie, parseCookies } from './cookies';
|
||||
export type { CookieOptions } from './cookies';
|
||||
|
||||
// Observability
|
||||
export { createDefaultLogger, logRequests, withConsoleFallback } from './logger';
|
||||
export type { Logger, LogLevel, LogFields } from './logger';
|
||||
export type { Logger, LogLevel, LogFields, BusLike } from './logger';
|
||||
|
||||
// Streaming
|
||||
export { channel, isAsyncIterable } from './channel';
|
||||
@@ -94,13 +98,20 @@ export type { StreamEncoder, SseEvent, SseFields } from './encoders';
|
||||
|
||||
// HTTP, security & validation
|
||||
export type { RequestLimits } from './http';
|
||||
export type { WsRequest, WsSocket } from './http/ws-core';
|
||||
export type { CompressionOptions } from './http/compression';
|
||||
export { UNMATCHED_ROUTE } from './http/core';
|
||||
export type { TlsOptions, CorsOptions, SecurityOptions } from './security';
|
||||
export type { UploadedFile, MultipartBody } from './multipart';
|
||||
export type { StandardSchemaV1 } from './standard-schema';
|
||||
export type { StandardSchemaV1, StandardIssue, StandardResult } from './standard-schema';
|
||||
|
||||
// Mesh
|
||||
// Mesh — experimental (`createApp({ experimental: true })`): outside the API freeze, may change in a minor.
|
||||
export { connectLink } from './mesh/link';
|
||||
export { buildRemote, envelopeFrom } from './mesh/teacup';
|
||||
export { buildManifest, createMeshControl, MESH_CONTROL_PATH } from './mesh/teapot';
|
||||
export type { Manifest, RequestEnvelope, Frame } from './mesh/protocol';
|
||||
export type { Manifest, RequestEnvelope, Frame, RouteEntry } from './mesh/protocol';
|
||||
export type { Link, ManifestPolicy, ReconnectOptions } from './mesh/link';
|
||||
export type { SocketCtor, EventfulSocket } from './http/ws-adapter';
|
||||
export type { RemoteScopeNode, RemoteRoute } from './mesh/teacup';
|
||||
export type { MeshControlDeps } from './mesh/teapot';
|
||||
export type { ResponseShape } from './pipeline';
|
||||
+9
-5
@@ -25,7 +25,7 @@ export type TeardownFn = () => void | Promise<void>;
|
||||
*/
|
||||
export class TeardownRegistry {
|
||||
private readonly callbacks: TeardownFn[] = [];
|
||||
private drained = false;
|
||||
private running: Promise<void> | undefined;
|
||||
|
||||
/** Register `fn` to run on shutdown. Later registrations run first — see {@link run}. */
|
||||
add(fn: TeardownFn): void {
|
||||
@@ -53,12 +53,16 @@ export class TeardownRegistry {
|
||||
* 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.
|
||||
* anyone expects, and a second call must not re-close what the first one closed. A second call
|
||||
* made while the first is still running gets the same promise rather than an early return: a
|
||||
* caller that awaits `close()` must not move on with a connection the first call has yet to close.
|
||||
*/
|
||||
async run(logger: Logger): Promise<void> {
|
||||
if (this.drained) return;
|
||||
this.drained = true;
|
||||
run(logger: Logger): Promise<void> {
|
||||
this.running ??= this.drain(logger);
|
||||
return this.running;
|
||||
}
|
||||
|
||||
private async drain(logger: Logger): Promise<void> {
|
||||
for (let index = this.callbacks.length - 1; index >= 0; index--) {
|
||||
try {
|
||||
await this.callbacks[index]();
|
||||
|
||||
+2
-1
@@ -129,7 +129,8 @@ export function logRequests(bus: BusLike, logger: Logger): () => void {
|
||||
}
|
||||
|
||||
/** The slice of {@link Bus} request logging needs — `on` only, matching what a plugin is handed. */
|
||||
interface BusLike {
|
||||
/** The part of a {@link Bus} that {@link logRequests} subscribes to. */
|
||||
export interface BusLike {
|
||||
on(event: 'request:end' | 'request:failed', listener: (payload: EventPayload) => void): () => void;
|
||||
}
|
||||
|
||||
|
||||
+159
-51
@@ -2,18 +2,27 @@ import type { Bus } from '../bus';
|
||||
import type { Logger } from '../logger';
|
||||
import { HttpError } from '../signals';
|
||||
import { connectSocket, type SocketCtor } from '../http/ws-adapter';
|
||||
import { compilePattern } from '../http/router';
|
||||
import type { WsSocket } from '../http/ws-core';
|
||||
import { sendWhenDrained, 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(). */
|
||||
/**
|
||||
* Client handle to a remote mesh server: its manifest, an RPC caller, and a close().
|
||||
*
|
||||
* @experimental Part of the mesh, which needs `createApp({ experimental: true })`: outside the
|
||||
* API freeze, so it may change in a minor release.
|
||||
*/
|
||||
export interface Link {
|
||||
manifest: Manifest;
|
||||
rpc(kind: 'scope' | 'route', name: string, ctx: RequestEnvelope): Promise<unknown>;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
/** Backoff bounds for reconnection. `false` disables reconnecting entirely. */
|
||||
/**
|
||||
* Backoff bounds for reconnection. `false` disables reconnecting entirely.
|
||||
*
|
||||
* @experimental Part of the mesh, which needs `createApp({ experimental: true })`: outside the
|
||||
* API freeze, so it may change in a minor release.
|
||||
*/
|
||||
export interface ReconnectOptions {
|
||||
/** Delay before the first retry; doubles from here (default: 500ms). */
|
||||
initialDelayMs?: number;
|
||||
@@ -27,6 +36,9 @@ export interface ReconnectOptions {
|
||||
* 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.
|
||||
*
|
||||
* @experimental Part of the mesh, which needs `createApp({ experimental: true })`: outside the
|
||||
* API freeze, so it may change in a minor release.
|
||||
*/
|
||||
export type ManifestPolicy = 'refuse';
|
||||
|
||||
@@ -64,6 +76,8 @@ interface LinkState {
|
||||
socket: WsSocket | undefined;
|
||||
closed: boolean;
|
||||
retry: ReturnType<typeof setTimeout> | undefined;
|
||||
/** When the scheduled reconnect attempt fires (epoch ms), for the `retry-after` a 503 carries. */
|
||||
retryAt: number | undefined;
|
||||
}
|
||||
|
||||
/** One established connection: its socket, the manifest it announced, and its heartbeat. */
|
||||
@@ -81,10 +95,10 @@ const DEFAULT_MAX_DELAY_MS = 30_000;
|
||||
* 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 {
|
||||
function rejectAllPending(pending: Map<string, PendingEntry>, reason: string, headers?: Record<string, string>): void {
|
||||
for (const [, entry] of pending) {
|
||||
clearTimeout(entry.timer);
|
||||
entry.reject(new HttpError(503, reason));
|
||||
entry.reject(new HttpError(503, reason, undefined, headers));
|
||||
}
|
||||
|
||||
pending.clear();
|
||||
@@ -99,13 +113,14 @@ function sendRpc(
|
||||
name: string,
|
||||
ctx: RequestEnvelope,
|
||||
timeoutMs: number,
|
||||
downHeaders?: Record<string, string>,
|
||||
): 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 Promise.reject(new HttpError(503, `mesh link is down: cannot resolve '${name}'`, undefined, downHeaders));
|
||||
}
|
||||
|
||||
return new Promise((resolveCall, rejectCall) => {
|
||||
@@ -117,7 +132,11 @@ function sendRpc(
|
||||
}, timeoutMs);
|
||||
|
||||
pending.set(id, { name, resolve: resolveCall, reject: rejectCall, timer });
|
||||
socket.send(encode({ type: 'rpc-req', id, kind, name, ctx }));
|
||||
// Not before the socket has room (#41); the timeout already runs, so a teapot that stops
|
||||
// reading still answers 504. Settled while waiting (timeout, close): nothing left to send.
|
||||
void sendWhenDrained(socket, () =>
|
||||
pending.has(id) ? encode({ type: 'rpc-req', id, kind, name, ctx }) : undefined,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -329,37 +348,109 @@ function stepKeys(manifest: Manifest): Set<string> {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 steps 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.
|
||||
* The graph was validated at boot against the first manifest and is already serving. A step token
|
||||
* that vanished cannot be validated away after the fact, so a manifest missing one is refused
|
||||
* rather than accepted — see `ManifestPolicy`. Extra steps are ignored: the graph is fixed at boot
|
||||
* and nothing new is spliced into it.
|
||||
*
|
||||
* Routes are not compared. They are not part of the graph, so a returning teapot's routes replace
|
||||
* the old ones instead (D15): a route it added is served, one it dropped is removed.
|
||||
*/
|
||||
export function missingFromManifest(booted: Manifest, returned: Manifest): string[] {
|
||||
const steps = stepKeys(returned);
|
||||
const routes = routeKeys(returned);
|
||||
const missing: string[] = [];
|
||||
|
||||
for (const step of booted.steps) {
|
||||
if (!steps.has(step)) missing.push(`step '${step}'`);
|
||||
}
|
||||
|
||||
for (const route of booted.routes) {
|
||||
if (!routes.has(`${route.method} ${compilePattern(route.pattern).shape}`)) {
|
||||
missing.push(`route '${route.method} ${route.pattern}'`);
|
||||
}
|
||||
return missing;
|
||||
}
|
||||
|
||||
/**
|
||||
* `retry-after` for a 503 while the link is down and will try again: the seconds until the next
|
||||
* attempt, at least 1. Nothing when it will not try again, so a client is not told to come back to
|
||||
* a link that has given up.
|
||||
*/
|
||||
function retryAfter(state: LinkState, reconnects: boolean): Record<string, string> | undefined {
|
||||
if (state.closed || !reconnects) return undefined;
|
||||
const waitMs = state.retryAt === undefined ? 0 : state.retryAt - Date.now();
|
||||
|
||||
return { 'retry-after': String(Math.max(1, Math.ceil(waitMs / 1000))) };
|
||||
}
|
||||
|
||||
/** A session dropped with reconnection off: the link is gone for good, if it was ever up. */
|
||||
function dropWithoutReconnect(adopted: boolean, giveUp: () => void): void {
|
||||
if (adopted) giveUp();
|
||||
}
|
||||
|
||||
/** Stop a link for good and say so: a drop with reconnection off, or a permanent refusal (D15). */
|
||||
function stopForGood(state: LinkState, onGone: (() => void) | undefined): void {
|
||||
if (state.closed) return;
|
||||
state.closed = true;
|
||||
clearTimeout(state.retry);
|
||||
state.retry = undefined;
|
||||
onGone?.();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a failed reconnect attempt was the teapot refusing this peer on purpose, in which case the
|
||||
* link gives up. Retrying reaches the same answer forever, so the link stops and its routes go (D15),
|
||||
* the same verdict boot gives a refusal.
|
||||
*/
|
||||
function refusedWhileReconnecting(
|
||||
url: string,
|
||||
error: unknown,
|
||||
logger: Logger | undefined,
|
||||
giveUp: () => void,
|
||||
): boolean {
|
||||
if (!isPermanentRefusal(error)) return false;
|
||||
logger?.warn(`mesh: ${url} refused this peer while reconnecting (${(error as Error).message}) — giving up on it.`);
|
||||
giveUp();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hang up on a session whose manifest no longer backs the graph, and return the fingerprint now logged.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
function refuseSession(
|
||||
session: Session,
|
||||
missing: string[],
|
||||
logged: string,
|
||||
url: string,
|
||||
logger: Logger | undefined,
|
||||
): string {
|
||||
session.heartbeat.stop();
|
||||
session.socket.close();
|
||||
const fingerprint = missing.join('|');
|
||||
|
||||
if (fingerprint !== logged) {
|
||||
logger?.warn(
|
||||
`mesh: refusing to reconnect to ${url} — its manifest no longer exports ${missing.join(', ')}, ` +
|
||||
'which the graph was validated against at boot. Retrying in case this is a partial deploy.',
|
||||
);
|
||||
}
|
||||
|
||||
return missing;
|
||||
return fingerprint;
|
||||
}
|
||||
|
||||
/** A session was adopted. When it is a returning one: keep the boot steps, take its routes (D15), and tell the caller. */
|
||||
function reconnected(
|
||||
returning: boolean,
|
||||
link: Link,
|
||||
returned: Manifest,
|
||||
onReconnect: ((manifest: Manifest) => void) | undefined,
|
||||
): void {
|
||||
if (!returning) return;
|
||||
link.manifest = { steps: link.manifest.steps, routes: returned.routes };
|
||||
onReconnect?.(link.manifest);
|
||||
}
|
||||
|
||||
/** Resolved backoff bounds, or `undefined` when the caller turned reconnection off. */
|
||||
@@ -381,6 +472,9 @@ function backoffBounds(
|
||||
* identity — the graph captured `rpc` at boot — and reconnects underneath it.
|
||||
*
|
||||
* `Ctor` is injectable to exercise both client implementations on a single runtime.
|
||||
*
|
||||
* @experimental Part of the mesh, which needs `createApp({ experimental: true })`: outside the
|
||||
* API freeze, so it may change in a minor release.
|
||||
*/
|
||||
export function connectLink(args: {
|
||||
url: string;
|
||||
@@ -394,19 +488,36 @@ export function connectLink(args: {
|
||||
/** What to do when a returning teapot's manifest no longer backs the graph (default: `'refuse'`). */
|
||||
onManifestChange?: ManifestPolicy;
|
||||
logger?: Logger;
|
||||
/**
|
||||
* Called each time a dropped link reconnects and its session is adopted, after `link.manifest`
|
||||
* has taken the returning manifest's routes. Not called for the first connection: the caller
|
||||
* has the link, and its manifest, when the returned promise resolves.
|
||||
*/
|
||||
onReconnect?: (manifest: Manifest) => void;
|
||||
/**
|
||||
* Called once when the link gives up for good: its session dropped with `reconnect: false`, or a
|
||||
* reconnect attempt was refused permanently (a wrong secret, a protocol mismatch). Not called by
|
||||
* `close()`, which is the application hanging up, not the teapot going away.
|
||||
*/
|
||||
onGone?: () => void;
|
||||
}): Promise<Link> {
|
||||
const timeoutMs = args.timeoutMs ?? 30_000;
|
||||
const heartbeatMs = args.heartbeatMs ?? HEARTBEAT_MS;
|
||||
const bounds = backoffBounds(args.reconnect);
|
||||
const pending = new Map<string, PendingEntry>();
|
||||
const state: LinkState = { socket: undefined, closed: false, retry: undefined };
|
||||
const state: LinkState = { socket: undefined, closed: false, retry: undefined, retryAt: undefined };
|
||||
let refusalLogged = '';
|
||||
let adopted = false; // a session was adopted at least once, so the link has something to lose
|
||||
|
||||
const downHeaders = (): Record<string, string> | undefined => retryAfter(state, bounds !== undefined);
|
||||
const giveUp = (): void => stopForGood(state, args.onGone);
|
||||
|
||||
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.
|
||||
// replaced with the real manifest before this object escapes. A reconnect keeps the boot
|
||||
// manifest's steps, because the graph is fixed at boot, and takes the returning one's routes.
|
||||
manifest: { steps: [], routes: [] },
|
||||
rpc: (kind, name, ctx) => sendRpc(state.socket, pending, String(counter++), kind, name, ctx, timeoutMs),
|
||||
rpc: (kind, name, ctx) =>
|
||||
sendRpc(state.socket, pending, String(counter++), kind, name, ctx, timeoutMs, downHeaders()),
|
||||
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.
|
||||
@@ -438,6 +549,8 @@ export function connectLink(args: {
|
||||
// the teapot the moment it returns.
|
||||
const delay = Math.round(capped / 2 + Math.random() * (capped / 2));
|
||||
|
||||
clearTimeout(state.retry);
|
||||
state.retryAt = Date.now() + delay;
|
||||
state.retry = setTimeout(() => void attemptReconnect(attempt + 1), delay);
|
||||
state.retry.unref?.();
|
||||
};
|
||||
@@ -446,8 +559,12 @@ export function connectLink(args: {
|
||||
const endSession = (attempt: number): void => {
|
||||
state.socket = undefined;
|
||||
args.bus?.emit('mesh:disconnect', { name: args.url });
|
||||
rejectAllPending(pending, `mesh link to ${args.url} is down`);
|
||||
// Scheduled before the rejection, so the 503s carry the real wait in `retry-after`.
|
||||
scheduleRetry(attempt);
|
||||
rejectAllPending(pending, `mesh link to ${args.url} is down`, downHeaders());
|
||||
// With reconnection off, a link that was up and dropped is gone for good (D15). `adopted`
|
||||
// keeps a first connect that never succeeded out of this: that link never escaped.
|
||||
if (!bounds) dropWithoutReconnect(adopted, giveUp);
|
||||
};
|
||||
|
||||
/** Adopt an established session, or refuse it when its manifest no longer backs the graph. */
|
||||
@@ -455,27 +572,16 @@ export function connectLink(args: {
|
||||
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.',
|
||||
);
|
||||
}
|
||||
|
||||
refusalLogged = refuseSession(session, missing, refusalLogged, args.url, args.logger);
|
||||
return false;
|
||||
}
|
||||
|
||||
refusalLogged = '';
|
||||
state.socket = session.socket;
|
||||
const returning = adopted;
|
||||
adopted = true;
|
||||
args.bus?.emit('mesh:connect', { name: args.url });
|
||||
reconnected(returning, link, session.manifest, args.onReconnect);
|
||||
|
||||
return true;
|
||||
};
|
||||
@@ -492,10 +598,12 @@ export function connectLink(args: {
|
||||
}
|
||||
|
||||
if (!adopt(session)) scheduleRetry(attempt);
|
||||
} catch {
|
||||
// openSession's own abort listener already scheduled the retry through `onEnd`; a rejection
|
||||
// that never opened a socket (a bad URL, DNS) needs one scheduled here instead.
|
||||
if (!state.socket && !state.retry) scheduleRetry(attempt);
|
||||
} catch (error) {
|
||||
// A permanent refusal ends the link. Otherwise: 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 (!refusedWhileReconnecting(args.url, error, args.logger, giveUp) && !state.socket && !state.retry)
|
||||
scheduleRetry(attempt);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
+15
-1
@@ -34,6 +34,9 @@ export const MESH_PROTOCOL_VERSION = 1;
|
||||
*
|
||||
* `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.
|
||||
*
|
||||
* @experimental Part of the mesh, which needs `createApp({ experimental: true })`: outside the
|
||||
* API freeze, so it may change in a minor release.
|
||||
*/
|
||||
export interface RequestEnvelope {
|
||||
method: string;
|
||||
@@ -51,7 +54,12 @@ export interface RequestEnvelope {
|
||||
correlation?: { requestId?: string; traceId?: string };
|
||||
}
|
||||
|
||||
/** Manifest entry for an exported route. */
|
||||
/**
|
||||
* Manifest entry for an exported route.
|
||||
*
|
||||
* @experimental Part of the mesh, which needs `createApp({ experimental: true })`: outside the
|
||||
* API freeze, so it may change in a minor release.
|
||||
*/
|
||||
export interface RouteEntry {
|
||||
method: string;
|
||||
pattern: string;
|
||||
@@ -63,6 +71,9 @@ export interface RouteEntry {
|
||||
* Steps only: a provider's value is the object it builds, which cannot cross a JSON wire, so
|
||||
* exporting one is refused at boot (`collectProviders`). Every entry here is request-scope and
|
||||
* lazy — the token exists in the teacup's graph, and running it is an RPC.
|
||||
*
|
||||
* @experimental Part of the mesh, which needs `createApp({ experimental: true })`: outside the
|
||||
* API freeze, so it may change in a minor release.
|
||||
*/
|
||||
export interface Manifest {
|
||||
steps: string[];
|
||||
@@ -75,6 +86,9 @@ export interface Manifest {
|
||||
* `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.
|
||||
*
|
||||
* @experimental Part of the mesh, which needs `createApp({ experimental: true })`: outside the
|
||||
* API freeze, so it may change in a minor release.
|
||||
*/
|
||||
export type Frame =
|
||||
| { type: 'hello'; v: number; secret: string }
|
||||
|
||||
+21
-3
@@ -2,12 +2,22 @@ import type { Link } from './link';
|
||||
import type { RequestEnvelope } from './protocol';
|
||||
import type { ResponseShape } from '../pipeline';
|
||||
|
||||
/** Local proxy for a remote scope: runs the RPC and returns its token→value binding. */
|
||||
/**
|
||||
* Local proxy for a remote scope: runs the RPC and returns its token→value binding.
|
||||
*
|
||||
* @experimental Part of the mesh, which needs `createApp({ experimental: true })`: outside the
|
||||
* API freeze, so it may change in a minor release.
|
||||
*/
|
||||
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. */
|
||||
/**
|
||||
* Local proxy for a remote route: forwards the request envelope over the link.
|
||||
*
|
||||
* @experimental Part of the mesh, which needs `createApp({ experimental: true })`: outside the
|
||||
* API freeze, so it may change in a minor release.
|
||||
*/
|
||||
export interface RemoteRoute {
|
||||
method: string;
|
||||
pattern: string;
|
||||
@@ -20,6 +30,9 @@ export interface RemoteRoute {
|
||||
* `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.
|
||||
*
|
||||
* @experimental Part of the mesh, which needs `createApp({ experimental: true })`: outside the
|
||||
* API freeze, so it may change in a minor release.
|
||||
*/
|
||||
export function envelopeFrom(ctx: any): RequestEnvelope {
|
||||
const req = ctx?.req;
|
||||
@@ -37,7 +50,12 @@ export function envelopeFrom(ctx: any): RequestEnvelope {
|
||||
};
|
||||
}
|
||||
|
||||
/** Turn a link's manifest into local proxy nodes: lazy request-scope steps, and routes. */
|
||||
/**
|
||||
* Turn a link's manifest into local proxy nodes: lazy request-scope steps, and routes.
|
||||
*
|
||||
* @experimental Part of the mesh, which needs `createApp({ experimental: true })`: outside the
|
||||
* API freeze, so it may change in a minor release.
|
||||
*/
|
||||
export function buildRemote(link: Link): { steps: RemoteScopeNode[]; routes: RemoteRoute[] } {
|
||||
const steps: RemoteScopeNode[] = link.manifest.steps.map((token) => ({
|
||||
name: token,
|
||||
|
||||
+95
-22
@@ -3,7 +3,7 @@
|
||||
// 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 { HELLO_FRAME_BYTES, sendWhenDrained, widenInbound, type WsSocket } from '../http/ws-core';
|
||||
import type { ResponseShape } from '../pipeline';
|
||||
import { isHttpError } from '../signals';
|
||||
import {
|
||||
@@ -17,9 +17,24 @@ import {
|
||||
type Frame,
|
||||
} from './protocol';
|
||||
|
||||
/** WebSocket path where a teapot exposes its mesh control channel. */
|
||||
/**
|
||||
* WebSocket path where a teapot exposes its mesh control channel.
|
||||
*
|
||||
* Reserved in every app, mesh or not (D17): `createApp` refuses a route that claims it, and an upgrade
|
||||
* to it on an app without a control channel closes `1008` on every adapter.
|
||||
*
|
||||
* @experimental Part of the mesh, which needs `createApp({ experimental: true })`: outside the
|
||||
* API freeze, so it may change in a minor release.
|
||||
*/
|
||||
export const MESH_CONTROL_PATH = '/__mesh__/control';
|
||||
|
||||
/**
|
||||
* Close reason for an upgrade to {@link MESH_CONTROL_PATH} on an app with no control channel. One
|
||||
* string shared by `app.upgrade` and the Node listener, so every adapter refuses it identically (D17).
|
||||
*/
|
||||
export const MESH_CONTROL_DISABLED_REASON =
|
||||
'mesh control channel not enabled: this app exports nothing, or has no mesh.secret';
|
||||
|
||||
/**
|
||||
* How long an unauthenticated peer may hold the control channel open before it is hung up on.
|
||||
*
|
||||
@@ -29,20 +44,41 @@ export const MESH_CONTROL_PATH = '/__mesh__/control';
|
||||
*/
|
||||
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;
|
||||
/** `limits.maxBodyBytes`'s default, which a teapot without one is sized for. */
|
||||
const DEFAULT_MAX_BODY_BYTES = 1_000_000;
|
||||
|
||||
/** Assemble a {@link Manifest} from exported step tokens and buffered routes. */
|
||||
/**
|
||||
* The most a body byte can grow inside an `rpc-req` envelope. The envelope is JSON, and a text
|
||||
* body travels as a JSON string, so a control character (`\u0001`) becomes the six characters of its
|
||||
* escape. Nothing a body can hold grows more: a `"` or backslash doubles, a JSON number such as
|
||||
* `1e20` re-encodes to about five times its length, a multipart `Buffer` to at most four, and
|
||||
* non-ASCII text is not escaped at all.
|
||||
*/
|
||||
const WORST_ESCAPE = 6;
|
||||
|
||||
/** Room in a frame for everything but the body: headers, params, query, url and the envelope. */
|
||||
const ENVELOPE_HEADROOM = 1_048_576;
|
||||
|
||||
/**
|
||||
* Largest control frame a teapot accepts, in characters, when the largest body it may be sent is
|
||||
* `maxBodyBytes` (#120): the body at its worst escaping plus {@link ENVELOPE_HEADROOM}, so any body
|
||||
* within the limit fits. 7,048,576 at the 1 MB default.
|
||||
*
|
||||
* `decode` runs `JSON.parse` on peer-controlled input, so the parse is capped by this figure — and
|
||||
* an unauthenticated peer never gets near it: until its `hello` is accepted, the channel takes only
|
||||
* hello-sized frames (`HELLO_FRAME_BYTES`, `controlBounds` in `ws-core`). Applies to the control
|
||||
* channel only: user WebSocket routes keep `limits.maxWsMessageBytes`.
|
||||
*/
|
||||
export function controlFrameLimit(maxBodyBytes = DEFAULT_MAX_BODY_BYTES): number {
|
||||
return WORST_ESCAPE * maxBodyBytes + ENVELOPE_HEADROOM;
|
||||
}
|
||||
|
||||
/**
|
||||
* Assemble a {@link Manifest} from exported step tokens and buffered routes.
|
||||
*
|
||||
* @experimental Part of the mesh, which needs `createApp({ experimental: true })`: outside the
|
||||
* API freeze, so it may change in a minor release.
|
||||
*/
|
||||
export function buildManifest(args: { steps: string[]; routes: RouteEntry[] }): Manifest {
|
||||
return { steps: [...args.steps], routes: args.routes };
|
||||
}
|
||||
@@ -54,13 +90,23 @@ function safeEqual(left: string, right: string): boolean {
|
||||
return crypto.timingSafeEqual(leftBuf, rightBuf);
|
||||
}
|
||||
|
||||
/** Dependencies for the mesh control handler: shared secret, manifest, and scope/route resolvers. */
|
||||
/**
|
||||
* Dependencies for the mesh control handler: shared secret, manifest, and scope/route resolvers.
|
||||
*
|
||||
* @experimental Part of the mesh, which needs `createApp({ experimental: true })`: outside the
|
||||
* API freeze, so it may change in a minor release.
|
||||
*/
|
||||
export interface MeshControlDeps {
|
||||
secret: string;
|
||||
manifest: Manifest;
|
||||
resolveScope: (name: string, env: RequestEnvelope) => Promise<unknown>;
|
||||
resolveRoute: (name: string, env: RequestEnvelope) => Promise<ResponseShape>;
|
||||
bus?: Bus;
|
||||
/**
|
||||
* The largest request body this teapot accepts, which sizes the control frames it parses
|
||||
* ({@link controlFrameLimit}). Defaults to the 1 MB body default.
|
||||
*/
|
||||
maxBodyBytes?: number;
|
||||
}
|
||||
|
||||
/** The rpc-req member of the {@link Frame} union. */
|
||||
@@ -101,6 +147,9 @@ function handleHandshake(socket: WsSocket, frame: Frame, deps: MeshControlDeps):
|
||||
return false;
|
||||
}
|
||||
|
||||
// The peer holds the secret now: lift the hello-sized bounds its socket was given to the ones
|
||||
// that carry RPC bodies (#120, #148). A socket bounded without a second phase is left as it is.
|
||||
widenInbound(socket);
|
||||
socket.send(
|
||||
encode({
|
||||
type: 'manifest',
|
||||
@@ -134,6 +183,14 @@ function resolveRpc(
|
||||
return deps.resolveRoute(name, ctx);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends one frame once the socket has room (#41): RPCs are served concurrently, so without the wait
|
||||
* a peer that stops reading grows the send buffer by one response per request it keeps sending.
|
||||
*/
|
||||
function reply(socket: WsSocket, frame: Frame): Promise<void> {
|
||||
return sendWhenDrained(socket, () => encode(frame));
|
||||
}
|
||||
|
||||
/** Serve one authenticated rpc-req: resolve it and frame the ok/error response back to the peer. */
|
||||
async function handleRpc(
|
||||
socket: WsSocket,
|
||||
@@ -160,12 +217,12 @@ async function handleRpc(
|
||||
throw error;
|
||||
}
|
||||
|
||||
socket.send(encode({ type: 'rpc-res', id, ok: true, result }));
|
||||
await reply(socket, { 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 } }));
|
||||
await reply(socket, { type: 'rpc-res', id, ok: false, error: { message: (err as Error).message, status } });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,6 +232,7 @@ async function serveFrames(
|
||||
deps: MeshControlDeps,
|
||||
exportedScopes: Set<string>,
|
||||
exportedRoutes: Set<string>,
|
||||
maxFrameChars: number,
|
||||
): Promise<void> {
|
||||
let authed = false;
|
||||
// Armed before the loop, and cleared by the handshake. An unauthenticated peer that simply
|
||||
@@ -188,8 +246,9 @@ async function serveFrames(
|
||||
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) {
|
||||
// Checked before `decode`, because decoding is the expensive part being defended. Until the
|
||||
// handshake, nothing larger than a hello is parsed, whatever the socket in front allowed.
|
||||
if (raw.length > (authed ? maxFrameChars : HELLO_FRAME_BYTES)) {
|
||||
socket.close(1009, 'mesh frame too large');
|
||||
break;
|
||||
}
|
||||
@@ -229,16 +288,30 @@ async function serveFrames(
|
||||
}
|
||||
}
|
||||
|
||||
/** Build a control handler that authenticates peers and serves scope/route RPCs from the manifest. */
|
||||
/**
|
||||
* Build a control handler that authenticates peers and serves scope/route RPCs from the manifest.
|
||||
*
|
||||
* @experimental Part of the mesh, which needs `createApp({ experimental: true })`: outside the
|
||||
* API freeze, so it may change in a minor release.
|
||||
*/
|
||||
export function createMeshControl(deps: MeshControlDeps): {
|
||||
path: string;
|
||||
maxFrameBytes: number;
|
||||
handle: (socket: WsSocket) => Promise<void>;
|
||||
} {
|
||||
const exportedScopes = new Set(deps.manifest.steps);
|
||||
const exportedRoutes = new Set(deps.manifest.routes.map((route) => `${route.method} ${route.pattern}`));
|
||||
const maxFrameChars = controlFrameLimit(deps.maxBodyBytes);
|
||||
|
||||
return {
|
||||
path: MESH_CONTROL_PATH,
|
||||
/**
|
||||
* The inbound bound a server puts on this channel's WebSocket in place of
|
||||
* `limits.maxWsMessageBytes` (#120). The same figure as the character check below: the two agree
|
||||
* on ASCII, and on other text the byte bound is the one that binds — a body measured in bytes by
|
||||
* `maxBodyBytes` stays about that many bytes inside the envelope, so it still fits.
|
||||
*/
|
||||
maxFrameBytes: maxFrameChars,
|
||||
/**
|
||||
* 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.
|
||||
@@ -246,7 +319,7 @@ export function createMeshControl(deps: MeshControlDeps): {
|
||||
* does synchronously, so the loop is live before any frame can arrive.
|
||||
*/
|
||||
handle(socket: WsSocket): Promise<void> {
|
||||
return serveFrames(socket, deps, exportedScopes, exportedRoutes);
|
||||
return serveFrames(socket, deps, exportedScopes, exportedRoutes, maxFrameChars);
|
||||
},
|
||||
};
|
||||
}
|
||||
Loaded 100 of 245 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user