Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8b659d827f |
No files matched your search
@@ -1,22 +1,13 @@
|
|||||||
name: Promote → GitHub
|
name: Promote → GitHub
|
||||||
|
|
||||||
# Promotion. Runs on GITEA ONLY. Mirrors ONLY `main` to the public GitHub repo — develop and
|
# Promotion. Runs on GITEA ONLY. Mirrors ONLY `main` + version tags to the public GitHub
|
||||||
# feature branches stay Gitea-private (this is why we don't use Gitea's push-mirror, which
|
# repo — develop and feature branches stay Gitea-private (this is why we don't use Gitea's
|
||||||
# would expose every branch).
|
# push-mirror, which would expose every branch). A pushed tag lands on GitHub and triggers
|
||||||
#
|
# its release workflow (production publish).
|
||||||
# Tags are deliberately NOT mirrored. The same `v*` tag means two different things on the two
|
|
||||||
# forges: on Gitea it stages to Verdaccio (`stage.yml`), on GitHub it publishes to npm and
|
|
||||||
# JSR, and a JSR version can never be replaced or removed. Promoting the tag is therefore a
|
|
||||||
# decision a person takes after reading the staging run, not a side effect of creating it:
|
|
||||||
#
|
|
||||||
# git push gh v<version>
|
|
||||||
#
|
|
||||||
# `--tags` is left off the branch push for the same reason. It used to ride along here, which
|
|
||||||
# meant any tag sitting in the runner's clone could reach production as a side effect of
|
|
||||||
# promoting `main` — a publish nobody chose, of a commit nobody was looking at.
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [main]
|
branches: [main]
|
||||||
|
tags: ['v*']
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
push-github:
|
push-github:
|
||||||
@@ -25,10 +16,15 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0 # full history for a clean push
|
fetch-depth: 0 # full history + tags for a clean push
|
||||||
- name: Push main to GitHub
|
- name: Push main + tags to GitHub
|
||||||
env:
|
env:
|
||||||
GH_TOKEN: ${{ secrets.GH_PROMOTE_TOKEN }}
|
GH_TOKEN: ${{ secrets.GH_PROMOTE_TOKEN }}
|
||||||
run: |
|
run: |
|
||||||
git remote add github "https://x-access-token:${GH_TOKEN}@github.com/Expressive-Tea/green-tea.git"
|
git remote add github "https://x-access-token:${GH_TOKEN}@github.com/Expressive-Tea/green-tea.git"
|
||||||
|
if [ "${{ github.ref_type }}" = "tag" ]; then
|
||||||
|
git push github "refs/tags/${{ github.ref_name }}"
|
||||||
|
else
|
||||||
git push github "HEAD:refs/heads/main"
|
git push github "HEAD:refs/heads/main"
|
||||||
|
git push github --tags
|
||||||
|
fi
|
||||||
@@ -1,18 +1,12 @@
|
|||||||
name: Stage → Verdaccio
|
name: Stage → Verdaccio
|
||||||
|
|
||||||
# Staging publish. Runs on GITEA ONLY (the `if` guards against GitHub). Publishes to the
|
# Staging publish. Runs on GITEA ONLY (the `if` guards against GitHub) for release
|
||||||
# internal Verdaccio under the `stg` dist-tag, from a `release/**` branch or from a `v*` tag.
|
# branches. Publishes prereleases to the internal Verdaccio under the `stg` dist-tag.
|
||||||
# Staging versions are intentionally mutable: an existing prerelease is removed before
|
# Staging versions are intentionally mutable: an existing prerelease is removed before
|
||||||
# publishing the updated release candidate under the same version.
|
# publishing the updated release candidate under the same version.
|
||||||
#
|
|
||||||
# The tag trigger is what makes creating a tag on Gitea safe. It runs the real publish path —
|
|
||||||
# the same `prepublishOnly` gate, the same tarball, the same commit — against a registry we
|
|
||||||
# can overwrite, so the release is proven before the tag is promoted to GitHub, where npm
|
|
||||||
# allows 72 hours to unpublish and JSR allows nothing at all.
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: ['release/**']
|
branches: ['release/**']
|
||||||
tags: ['v*']
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
publish-stg:
|
publish-stg:
|
||||||
@@ -38,11 +32,6 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
npm config set //npm.svc.zoit.services/:_authToken "$NODE_AUTH_TOKEN"
|
npm config set //npm.svc.zoit.services/:_authToken "$NODE_AUTH_TOKEN"
|
||||||
VER=$(node -p "require('./package.json').version")
|
VER=$(node -p "require('./package.json').version")
|
||||||
# Staging overwrites the version it publishes, and a stable number that changes
|
|
||||||
# under an internal consumer is worse than no staging at all. This will need
|
|
||||||
# revisiting at the first stable release, which is exactly the one most worth
|
|
||||||
# staging: the answer is probably to stage it under a suffixed version rather
|
|
||||||
# than to drop the guard.
|
|
||||||
case "$VER" in
|
case "$VER" in
|
||||||
*-*) ;;
|
*-*) ;;
|
||||||
*) echo "Refusing to stage non-prerelease version: $VER" >&2; exit 1 ;;
|
*) echo "Refusing to stage non-prerelease version: $VER" >&2; exit 1 ;;
|
||||||
|
|||||||
@@ -29,19 +29,16 @@ Run the first four before proposing anything as finished. The runtime suites sta
|
|||||||
|
|
||||||
## Two forges
|
## Two forges
|
||||||
|
|
||||||
Development lives on a private Gitea instance. GitHub is a downstream mirror that receives `main` automatically and release tags only by hand.
|
Development lives on a private Gitea instance. GitHub is a downstream mirror that receives `main` and release tags, nothing else.
|
||||||
|
|
||||||
```
|
```
|
||||||
feature/* → develop → main → [promote.yml] → GitHub main
|
feature/* → develop → main → [promote.yml] → GitHub main
|
||||||
↑ │ ↓
|
↑ ↓
|
||||||
lead dev │ GitHub contrib ← external PRs
|
lead dev GitHub contrib ← external PRs
|
||||||
│
|
|
||||||
v* tag ────┴─── Gitea: [stage.yml] → Verdaccio
|
|
||||||
└─── GitHub (pushed by hand): [release.yml] → npm + JSR
|
|
||||||
```
|
```
|
||||||
|
|
||||||
- **Gitea `develop`** — active development.
|
- **Gitea `develop`** — active development.
|
||||||
- **Gitea `main`** — staging. Merging here publishes nothing. A `v*` tag here publishes to the internal Verdaccio, never to a public registry.
|
- **Gitea `main`** — staging. Merging here publishes nothing; only a `v*` tag publishes.
|
||||||
- **GitHub `main`** — production mirror. No human touches it. Protected against force-push and deletion, with no review requirement, because `promote.yml` pushes to it directly and a review rule would block that.
|
- **GitHub `main`** — production mirror. No human touches it. Protected against force-push and deletion, with no review requirement, because `promote.yml` pushes to it directly and a review rule would block that.
|
||||||
- **`contrib`** — exists on *both* forges. Where outside contributions land.
|
- **`contrib`** — exists on *both* forges. Where outside contributions land.
|
||||||
|
|
||||||
@@ -88,19 +85,6 @@ Bumping `package.json` and `deno.json` ahead of the tag is fine and necessary
|
|||||||
*next* publish will be called, and the docs repo's `verify:release` compares the tag against them.
|
*next* publish will be called, and the docs repo's `verify:release` compares the tag against them.
|
||||||
A version number is a plan; a changelog heading is a receipt.
|
A version number is a plan; a changelog heading is a receipt.
|
||||||
|
|
||||||
**A tag is created twice, on purpose.** Pushing `v*` to Gitea stages that exact commit to
|
|
||||||
Verdaccio through the real publish path; pushing the same tag to GitHub publishes it to npm and
|
|
||||||
JSR. Nothing promotes the tag for you — `promote.yml` mirrors `main` and only `main`, so the
|
|
||||||
second push is a decision made after reading the first run:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git push origin v<version> # Gitea → Verdaccio, reversible
|
|
||||||
git push gh v<version> # GitHub → npm + JSR, permanent on JSR
|
|
||||||
```
|
|
||||||
|
|
||||||
The split exists because a mistake caught on Verdaccio costs a re-tag, and the same mistake
|
|
||||||
caught on JSR costs the version number forever.
|
|
||||||
|
|
||||||
**After a beta release, move the channel tag by hand.** A publish sets exactly one dist-tag, and it
|
**After a beta release, move the channel tag by hand.** A publish sets exactly one dist-tag, and it
|
||||||
is the only npm write the release workflow can make — Trusted Publishing's OIDC exchange lives inside
|
is the only npm write the release workflow can make — Trusted Publishing's OIDC exchange lives inside
|
||||||
`npm publish`, so the token it hands back is rejected by `npm dist-tag` (`E401`, learned the hard way
|
`npm publish`, so the token it hands back is rejected by `npm dist-tag` (`E401`, learned the hard way
|
||||||
|
|||||||
+34
-161
@@ -4,14 +4,14 @@
|
|||||||
|
|
||||||
## Environment
|
## Environment
|
||||||
|
|
||||||
- **Date**: 2026-09-02
|
- **Date**: 2026-07-07
|
||||||
- **Commit**: 8c5855c
|
- **Commit**: fe1831a
|
||||||
- **Node**: v22.22.2
|
- **Node**: v22.22.2
|
||||||
- **OS**: darwin
|
- **OS**: darwin
|
||||||
- **CPU**: Apple M4 Max (16 cores)
|
- **CPU**: Apple M4 Max (16 cores)
|
||||||
- **RAM**: 69 GB
|
- **RAM**: 69 GB
|
||||||
- **Core-pinned**: no
|
- **Core-pinned**: no
|
||||||
- **autocannon config**: 100 connections, 10s duration, 5 runs (1 warmup discarded), pipelining 1
|
- **autocannon config**: 100 connections, 5s duration, 3 runs (1 warmup discarded), pipelining 1
|
||||||
|
|
||||||
> **A note on honesty: this is a single-box benchmark.** All frameworks were driven with autocannon over
|
> **A note on honesty: this is a single-box benchmark.** All frameworks were driven with autocannon over
|
||||||
> loopback on the same machine, sharing the same cores as the server processes they measured. That
|
> loopback on the same machine, sharing the same cores as the server processes they measured. That
|
||||||
@@ -29,74 +29,64 @@
|
|||||||
|
|
||||||
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
|
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
|
||||||
| --- | --- | --- | --- | --- | --- | --- |
|
| --- | --- | --- | --- | --- | --- | --- |
|
||||||
| raw-http | 119,357 | 0.00 | 1.00 | 1.00 | 0.4% | 118,560–120,067 |
|
| raw-http | 115,398 | 0.00 | 1.00 | 1.00 | 0.3% | 114,822–115,539 |
|
||||||
| nestjs-fastify | 98,039 | 0.00 | 1.00 | 2.00 | 1.2% | 96,073–99,680 |
|
| green-tea | 98,093 | 0.00 | 1.00 | 2.00 | 0.3% | 98,054–98,669 |
|
||||||
| fastify | 89,097 | 1.00 | 1.00 | 2.00 | 0.1% | 88,864–89,207 |
|
| nestjs-fastify | 95,034 | 1.00 | 1.00 | 2.00 | 0.5% | 94,240–95,264 |
|
||||||
| green-tea | 87,473 | 1.00 | 2.00 | 2.00 | 0.3% | 86,903–87,607 |
|
| fastify | 86,765 | 1.00 | 2.00 | 2.00 | 0.3% | 86,496–87,123 |
|
||||||
| express | 24,677 | 3.00 | 5.00 | 8.00 | 0.2% | 24,647–24,769 |
|
| express | 24,366 | 3.00 | 5.00 | 8.00 | 0.2% | 24,283–24,418 |
|
||||||
| nestjs-express | 21,879 | 4.00 | 6.00 | 9.00 | 0.2% | 21,845–21,953 |
|
| nestjs-express | 21,762 | 4.00 | 6.00 | 10.00 | 0.4% | 21,698–21,896 |
|
||||||
|
|
||||||
### Route param
|
### Route param
|
||||||
|
|
||||||
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
|
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
|
||||||
| --- | --- | --- | --- | --- | --- | --- |
|
| --- | --- | --- | --- | --- | --- | --- |
|
||||||
| raw-http | 120,905 | 0.00 | 1.00 | 1.00 | 0.5% | 119,927–121,713 |
|
| raw-http | 116,333 | 0.00 | 1.00 | 1.00 | 0.2% | 115,974–116,410 |
|
||||||
| nestjs-fastify | 91,849 | 1.00 | 1.00 | 2.00 | 0.3% | 91,825–92,599 |
|
| green-tea | 93,434 | 1.00 | 2.00 | 2.00 | 0.2% | 93,152–93,613 |
|
||||||
| fastify | 88,317 | 1.00 | 1.00 | 2.00 | 0.2% | 87,997–88,439 |
|
| nestjs-fastify | 89,312 | 1.00 | 2.00 | 2.00 | 0.1% | 89,235–89,530 |
|
||||||
| green-tea | 86,595 | 1.00 | 2.00 | 2.00 | 0.2% | 86,368–86,880 |
|
| fastify | 86,278 | 1.00 | 2.00 | 2.00 | 0.3% | 86,138–86,765 |
|
||||||
| express | 24,200 | 3.00 | 5.00 | 8.00 | 0.2% | 24,158–24,260 |
|
| express | 23,835 | 3.00 | 5.00 | 8.00 | 0.5% | 23,803–24,046 |
|
||||||
| nestjs-express | 21,182 | 4.00 | 6.00 | 9.00 | 0.7% | 21,150–21,518 |
|
| nestjs-express | 20,955 | 4.00 | 6.00 | 11.00 | 0.6% | 20,949–21,202 |
|
||||||
|
|
||||||
### Pipeline (3 steps) (approximation)
|
### Pipeline (3 steps) (approximation)
|
||||||
|
|
||||||
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
|
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
|
||||||
| --- | --- | --- | --- | --- | --- | --- |
|
| --- | --- | --- | --- | --- | --- | --- |
|
||||||
| raw-http | 118,996 | 0.00 | 1.00 | 1.00 | 0.3% | 118,583–119,584 |
|
| raw-http | 113,491 | 0.00 | 1.00 | 1.00 | 0.8% | 112,531–114,810 |
|
||||||
| nestjs-fastify | 89,527 | 1.00 | 2.00 | 2.00 | 1.0% | 87,572–90,028 |
|
| nestjs-fastify | 87,328 | 1.00 | 2.00 | 2.00 | 0.4% | 86,867–87,661 |
|
||||||
| fastify | 86,671 | 1.00 | 1.00 | 2.00 | 0.1% | 86,490–86,793 |
|
| fastify | 85,024 | 1.00 | 2.00 | 2.00 | 0.3% | 84,512–85,178 |
|
||||||
| green-tea | 80,079 | 1.00 | 2.00 | 2.00 | 0.2% | 80,026–80,375 |
|
| green-tea | 84,896 | 1.00 | 2.00 | 2.00 | 0.5% | 84,243–85,267 |
|
||||||
| express | 24,325 | 3.00 | 5.00 | 8.00 | 0.2% | 24,281–24,407 |
|
| express | 23,950 | 3.00 | 5.00 | 8.00 | 0.2% | 23,902–24,011 |
|
||||||
| nestjs-express | 20,872 | 4.00 | 6.00 | 9.00 | 0.2% | 20,801–20,940 |
|
| nestjs-express | 20,824 | 4.00 | 6.00 | 11.00 | 0.1% | 20,805–20,878 |
|
||||||
|
|
||||||
### POST JSON + validation
|
### POST JSON + validation
|
||||||
|
|
||||||
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
|
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
|
||||||
| --- | --- | --- | --- | --- | --- | --- |
|
| --- | --- | --- | --- | --- | --- | --- |
|
||||||
| raw-http | 104,288 | 0.00 | 1.00 | 1.00 | 0.4% | 103,776–104,916 |
|
| raw-http | 100,141 | 0.00 | 1.00 | 2.00 | 0.2% | 99,846–100,294 |
|
||||||
| green-tea | 70,298 | 1.00 | 2.00 | 3.00 | 1.0% | 68,972–70,607 |
|
| green-tea | 77,178 | 1.00 | 2.00 | 2.00 | 0.1% | 77,126–77,254 |
|
||||||
| fastify | 65,905 | 1.00 | 2.00 | 3.00 | 0.3% | 65,725–66,367 |
|
| fastify | 63,722 | 1.00 | 2.00 | 3.00 | 0.1% | 63,574–63,760 |
|
||||||
| nestjs-fastify | 63,318 | 1.00 | 2.00 | 3.00 | 0.9% | 62,454–63,747 |
|
| nestjs-fastify | 59,146 | 1.00 | 3.00 | 3.00 | 0.3% | 59,005–59,376 |
|
||||||
| express | 20,297 | 4.00 | 6.00 | 10.00 | 0.5% | 20,158–20,414 |
|
| express | 20,098 | 4.00 | 6.00 | 12.00 | 0.2% | 20,056–20,174 |
|
||||||
| nestjs-express | 18,788 | 5.00 | 7.00 | 10.00 | 0.3% | 18,684–18,862 |
|
| nestjs-express | 18,856 | 5.00 | 7.00 | 30.00 | 0.5% | 18,853–19,067 |
|
||||||
|
|
||||||
## Step-scaling (green-tea)
|
## Step-scaling (green-tea)
|
||||||
|
|
||||||
| Path | Steps | req/s |
|
| Path | Steps | req/s |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| /steps/0 | 0 | 88,108 |
|
| /steps/0 | 0 | 92,282 |
|
||||||
| /steps/3 | 3 | 79,951 |
|
| /steps/3 | 3 | 81,530 |
|
||||||
| /steps/5 | 5 | 74,127 |
|
| /steps/5 | 5 | 71,994 |
|
||||||
|
|
||||||
Each additional pipeline step costs roughly 2,796 req/s (-15.9% over 5 steps), on this box.
|
Each additional pipeline step costs roughly 4,058 req/s (-22.0% over 5 steps), on this box.
|
||||||
|
|
||||||
## green-tea across runtimes
|
|
||||||
|
|
||||||
| Scenario | node | deno | bun |
|
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| JSON hello (overhead) | 90,976 | 153,408 | 131,674 |
|
|
||||||
| Route param | 88,905 | 146,368 | 126,909 |
|
|
||||||
| Pipeline (3 steps) | 82,045 | 136,256 | 117,489 |
|
|
||||||
| POST JSON + validation | 72,236 | 106,662 | 95,124 |
|
|
||||||
|
|
||||||
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)
|
## Cost of secure-by-default (green-tea)
|
||||||
|
|
||||||
| Label | req/s |
|
| Label | req/s |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| security:false (parity) | 87,473 |
|
| security:false (parity) | 98,093 |
|
||||||
| security:true (default) | 83,773 |
|
| security:true (default) | 92,998 |
|
||||||
|
|
||||||
The real cost of running secure-by-default (rather than the parity-mode `security:false` used above) is ~4.2% req/s on this box.
|
The real cost of running secure-by-default (rather than the parity-mode `security:false` used above) is ~5.2% req/s on this box.
|
||||||
|
|
||||||
> Scope: this micro-bench currently measures the security-**headers** cost only (`security:false` vs
|
> Scope: this micro-bench currently measures the security-**headers** cost only (`security:false` vs
|
||||||
> `security:true` on `/hello`). The incremental cost of `@body` validation and CORS is not separately
|
> `security:true` on `/hello`). The incremental cost of `@body` validation and CORS is not separately
|
||||||
@@ -126,120 +116,3 @@ The real cost of running secure-by-default (rather than the parity-mode `securit
|
|||||||
`ValidationPipe` / class-validator is **not** used — `/validate` performs the same manual field check
|
`ValidationPipe` / class-validator is **not** used — `/validate` performs the same manual field check
|
||||||
as every other server (parity). The same parity controls apply: `etag` and `x-powered-by` are disabled
|
as every other server (parity). The same parity controls apply: `etag` and `x-powered-by` are disabled
|
||||||
on the underlying Express instance, and `keepAliveTimeout` is 5000 on both adapters.
|
on the underlying Express instance, and `keepAliveTimeout` is 5000 on both adapters.
|
||||||
|
|
||||||
<!-- keep-below: hand-written, survives `npm run bench` -->
|
|
||||||
|
|
||||||
## What moved between releases
|
|
||||||
|
|
||||||
These figures were measured per function and never per version. Every change on the request path
|
|
||||||
was benchmarked as it landed — the numbers are still in the code, cited below — but no one ran this
|
|
||||||
file between `26.7` and `26.9`, so nothing added them up. That is the gap this section and
|
|
||||||
`npm run bench:compare` exist to close.
|
|
||||||
|
|
||||||
### The release gate: `26.8.0-beta.1` → `26.9.0-beta.1`
|
|
||||||
|
|
||||||
Both trees measured on one box in one sitting, alternating which side ran first each round, sharing
|
|
||||||
one `node_modules` and one byte-identical server file. Medians of five rounds:
|
|
||||||
|
|
||||||
| Scenario | 26.8.0-beta.1 | 26.9.0-beta.1 | Δ |
|
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| hello | 91,343 | 90,371 | −1.1% |
|
|
||||||
| param | 88,113 | 87,921 | −0.2% |
|
|
||||||
| pipeline (3 steps) | 80,934 | 80,893 | −0.1% |
|
|
||||||
| validate (POST) | 72,340 | 72,241 | −0.1% |
|
|
||||||
| hello + security | 85,967 | 86,426 | +0.5% |
|
|
||||||
| hello + cors predicate | 82,609 | 83,401 | +1.0% |
|
|
||||||
| preflight + cors predicate | 112,055 | 115,069 | **+2.7%** |
|
|
||||||
|
|
||||||
Every row but the last overlaps between the two sides and is noise. The preflight row does not: the
|
|
||||||
new tree wins all three rounds, which is where a `cors.origins` predicate stopped being evaluated
|
|
||||||
three times per request.
|
|
||||||
|
|
||||||
That change is a call count, not a rate, and the benchmark's predicate is a `Set` lookup — so the
|
|
||||||
saving is invisible in req/s here and would be two or three network round trips in the lookup the
|
|
||||||
option exists for:
|
|
||||||
|
|
||||||
| | per cross-origin GET | per preflight |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| 26.8.0-beta.1 | 2 | 3 |
|
|
||||||
| 26.9.0-beta.1 | **1** | **1** |
|
|
||||||
|
|
||||||
### Against `26.7`, and why it is not a regression
|
|
||||||
|
|
||||||
The table this file carried until today was measured at `fe1831a`, before `26.8.0-beta.1`
|
|
||||||
shipped. Re-running
|
|
||||||
that tree today, under the same toolchain and dependencies, gives 94,403 req/s on `hello` and
|
|
||||||
93,361 on `param` against 89,527 and 85,839 for the current tree — roughly −5% and −8%. Against
|
|
||||||
`fastify` as a control, which moved +1.2% to +1.8% across the same scenarios, green-tea's ratio to
|
|
||||||
it fell 6.6% to 11.7%.
|
|
||||||
|
|
||||||
**That number is real and it is not a regression, because it is not the same program.** July matched
|
|
||||||
routes by splitting the path and comparing segments, returning on the first hit, in one flat file.
|
|
||||||
It had no route constraints, no specificity ranking, no per-request correlation, no lifecycle
|
|
||||||
stream, and one adapter. It was fast the way something is fast before it does anything.
|
|
||||||
|
|
||||||
What the interval bought, in the order it costs: a runtime-neutral request and response boundary,
|
|
||||||
which is what serves Deno, Bun and workerd from one core rather than one adapter; constraint and
|
|
||||||
specificity matching; a correlated event stream; and per-request identity.
|
|
||||||
|
|
||||||
The first of those is now measurable, because the runtimes table above did not exist either. The
|
|
||||||
same boundary that costs on Node is what puts the same application on Deno at 153,408 req/s and Bun
|
|
||||||
at 131,674 against Node's 90,976 — and above the 119,357 that Node's own `http` module manages with
|
|
||||||
no framework at all. Whether the trade is worth it is the reader's call. This file's job is to say
|
|
||||||
what it cost and what it bought.
|
|
||||||
|
|
||||||
### Figures recorded when each change landed
|
|
||||||
|
|
||||||
Measured at the time, in the code, against a microbenchmark rather than this harness:
|
|
||||||
|
|
||||||
| Where | Finding |
|
|
||||||
| --- | --- |
|
|
||||||
| `src/http/core.ts:63` | a per-request derivation that reached **45% of a whole request** before it was fixed |
|
|
||||||
| `src/http/core.ts:89` | six request-id generators compared; `crypto.randomUUID` at 76 ns was the fastest cross-runtime option, and the only alternatives that beat it are Node-only |
|
|
||||||
| `src/http/core.ts:229` | wrapping `dispatch` in a second async frame: 0.43 µs per request |
|
|
||||||
| `src/bus.ts:173` | spreading request identity into an event payload: ~197 ns on a two-step pipeline |
|
|
||||||
| `src/pipeline.ts:58` | one timestamp per step boundary instead of two: 25.2 ns against 45.3 ns per step |
|
|
||||||
| `src/http/headers.ts:30` | 146.4 ns against 55.9 ns for the same header answer |
|
|
||||||
| `src/http/body.ts:39` | 250 ns per request for a closure and the error context it captured |
|
|
||||||
| `src/http/router.ts:232` | per-segment decoding on a path nobody decodes: 95.8 ns for `/hello`, 342.7 ns for six segments |
|
|
||||||
|
|
||||||
**These do not add up to the release delta, and cannot.** They cite different baselines — 4.4 µs,
|
|
||||||
4.5 µs, 10.19 µs — because each was taken against whatever a request cost on the day. A dozen
|
|
||||||
findings in nanoseconds against inconsistent references is a discussion, not a total. A version-level
|
|
||||||
number measured against a fixed baseline is what was missing, not rigour.
|
|
||||||
|
|
||||||
### What is still unattributed
|
|
||||||
|
|
||||||
Three candidates for the `26.7` → `26.9` interval were measured and none of them account for it:
|
|
||||||
|
|
||||||
- **`crypto.randomUUID` per request** — removing it entirely lands within noise on every scenario,
|
|
||||||
and one row moves the wrong way. At 76 ns against a ~11 µs request it is ~0.7%, below what a load
|
|
||||||
test at this CV can resolve.
|
|
||||||
- **Specificity ranking in the matcher** — replacing it with July's first-match-wins is noise on all
|
|
||||||
four rows at this route-table size.
|
|
||||||
- **The bundle versus the TypeScript source** — every row overlaps, so the form the table loads does
|
|
||||||
not explain it either.
|
|
||||||
|
|
||||||
No single culprit was found. The remaining candidates are the neutral request and response objects
|
|
||||||
and the several small per-request allocations around them, which is a shape that resists a single
|
|
||||||
measurement.
|
|
||||||
|
|
||||||
## What this file does not measure
|
|
||||||
|
|
||||||
- **Route-table width was invisible until `26.9`.** Every matcher cost scales with how many
|
|
||||||
candidates a request walks past, and the cross-framework tables use six routes — so any matcher
|
|
||||||
change measures as noise there regardless of its size. `npm run bench:compare` carries 50- and
|
|
||||||
200-route cases for this reason. Settling route ranking when the table is built rather than per
|
|
||||||
request is worth nothing at six routes, +3.4% at fifty, and **+12% to +14.9% at two hundred**,
|
|
||||||
across twelve rounds without a crossing sample.
|
|
||||||
- **Boot time is absent.** Independent providers began booting concurrently in `26.9`: three
|
|
||||||
providers with no edges and 200 ms of work each went from 616 ms to 210 ms. No table here shows it.
|
|
||||||
- **Streaming is absent.** Every scenario is a buffered response. SSE framing, the encoder's
|
|
||||||
per-item work, and the stream lifecycle events are not exercised.
|
|
||||||
- **The cross-framework tables are Node-only**, and they load green-tea from `src/` through `tsx`
|
|
||||||
while the other frameworks load their published JavaScript. Measured today, that difference is
|
|
||||||
within noise — but it is a difference, and the runtimes table above avoids it by loading the built
|
|
||||||
bundle on all three.
|
|
||||||
- **The runtimes table compares each runtime's HTTP server, not its JavaScript engine.** `Deno.serve`
|
|
||||||
and `Bun.serve` are native stacks; Node's `http` is JavaScript. "green-tea on this runtime" is the
|
|
||||||
claim, and it is the one an application actually experiences.
|
|
||||||
+2
-220
@@ -6,225 +6,7 @@ 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
|
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.
|
npm treats versions as semver and semver forbids leading zeros.
|
||||||
|
|
||||||
## [26.9.0-beta.1] - 2026-09-04
|
## [Unreleased]
|
||||||
|
|
||||||
### Added
|
|
||||||
|
|
||||||
- **A request budget, not just a connection cap.** `createApp({ limits: { maxConcurrentRequests } })`
|
|
||||||
bounds how many handlers run at once, per server and per Fetch adapter instance; over the budget a
|
|
||||||
request gets `503` with `Retry-After: 1` instead of queueing behind the ones already running. It is
|
|
||||||
opt-in and unlimited by default, and it counts *executing handlers* rather than open connections —
|
|
||||||
the slot is released when routing and the handler finish, so a long-lived SSE stream or a WebSocket
|
|
||||||
upgrade does not hold one for its lifetime. On Node a client disconnect releases the slot early. A
|
|
||||||
handler that never returns keeps its slot, which is the honest behaviour for a budget of this shape.
|
|
||||||
Contributed by @hgshreyas.
|
|
||||||
|
|
||||||
Node's connection cap also stopped being silent: reaching `maxConnections` now logs a warning
|
|
||||||
naming the dropped peer, rate-limited to one a minute. Until now the socket was destroyed with no
|
|
||||||
HTTP response and nothing said so, which reads from the outside like a network fault.
|
|
||||||
|
|
||||||
- **`createApp({ handleSignals: true })` registers `SIGINT`/`SIGTERM` to close and exit.** Off by
|
|
||||||
default, and that is the design rather than caution: a library that installs process-wide handlers
|
|
||||||
behind your back is worse than one that installs none, because when the process exits is the
|
|
||||||
application's call. Both halves are supported — keep the handler, or hand it over. What is not
|
|
||||||
optional either way is that *something* calls `close()`; the teardown registry only runs from
|
|
||||||
there, so a container `SIGKILL`ed after its grace period skips every `dispose()` and reports
|
|
||||||
nothing.
|
|
||||||
|
|
||||||
Declared once and wired per runtime by whichever boot call runs — `listen()`, `serveDeno()` and
|
|
||||||
`serveBun()` each attach it to the closer that drains *their* server, so `process.on` on Node and
|
|
||||||
Bun and `Deno.addSignalListener` on Deno stop being the application's problem. `close()`
|
|
||||||
unregisters, which means a *second* signal falls through to the platform default and ends the
|
|
||||||
process at once: Ctrl-C twice is the way out of a teardown that is stuck.
|
|
||||||
|
|
||||||
- **The extension-point types are exported, not just the extension points.** `TransformerFn` — the
|
|
||||||
type of `@Transformer`'s only argument — could not be imported, so a custom transformer was
|
|
||||||
attached with its shape redeclared inline or borrowed off a value as `typeof JsonTransformer`.
|
|
||||||
Checking the barrel for the same oversight turned up four more, all now exported: `PluginApi`,
|
|
||||||
`ScopeApi` and `ScopeNode`, the chain reached through `api.scope.add`, without which a plugin split
|
|
||||||
into named functions cannot annotate what it receives; plus `Hooks` and `TeardownFn`. Types only —
|
|
||||||
nothing at runtime moved and no existing export changed.
|
|
||||||
|
|
||||||
- **The lifecycle stream has a contract now, not just events.** `request:end` is documented as
|
|
||||||
terminal and universal — it fires for every request shape and is the only one carrying the status
|
|
||||||
the client received, which makes it the request counter. `request:failed` means *handler code
|
|
||||||
threw*, which no status expresses on its own since a rendered `422` is also a throw, and
|
|
||||||
`route:unmatched` means *no route ran*. Both are **additional** to `request:end`, not alternatives
|
|
||||||
to it: one failing request emits three events and a 404 emits two, all sharing a `requestId`, and
|
|
||||||
an exporter that treats them as separate outcomes counts the same request twice. Silently — the
|
|
||||||
metrics just come out wrong.
|
|
||||||
|
|
||||||
`request:failed` now carries `status`, so an error counter can break down by status without
|
|
||||||
joining back through `requestId` for something the emitter already had. It is absent in exactly
|
|
||||||
one case: a custom `onError` that threw while producing it, where the framework does not know what
|
|
||||||
was sent and will not guess.
|
|
||||||
|
|
||||||
- **`@needs('events')` reaches the read-only half of the bus** — `{ on }`, the same narrowing
|
|
||||||
plugins already get, exported as the `Events` type. `app.bus` was public and a plugin could
|
|
||||||
subscribe, but the bus was not a graph token, so `@needs('bus')` failed at boot and nothing said
|
|
||||||
why. It still is not one, and that is the design: handing `emit` to every node turns a one-way
|
|
||||||
observation channel into something anything can forge events on. `@needs('bus')` now fails saying
|
|
||||||
exactly that, and pointing at the two things that do work.
|
|
||||||
|
|
||||||
A plugin remains the right home for observation, because it gets `on` and `onShutdown` *together*.
|
|
||||||
This token gives the subscribe half alone — `on()` returns its own unsubscribe for a `@Provider`
|
|
||||||
to release in `dispose()`, and a `@Step` should not subscribe at all, since it runs per request
|
|
||||||
and would add a listener each time.
|
|
||||||
|
|
||||||
- **`@Sse` can emit an `id:`, so an `EventSource` reconnect has something to resume from.**
|
|
||||||
`sse(data, { id, event, retry })` tags a stream item and the encoder writes the fields ahead of
|
|
||||||
`data:`; an app that never calls it produces byte-identical output. Until now the encoder wrote one
|
|
||||||
field, so the browser had nothing to put in `Last-Event-ID` and every automatic reconnect — the
|
|
||||||
reason to choose SSE over a raw WebSocket — rebuilt the route's iterable from its start and lost
|
|
||||||
the gap in silence. The other half already worked: the request envelope has always carried every
|
|
||||||
header, so a handler could already read `@header('last-event-id')`; it simply always arrived empty.
|
|
||||||
`event:` and `retry:` come along because the same envelope carries them, and neither was reachable
|
|
||||||
before.
|
|
||||||
|
|
||||||
**green-tea stores nothing** — no buffer, no retention window, no replay. It carries the marker in
|
|
||||||
both directions and the handler decides what the gap means, because only the source knows: a paged
|
|
||||||
log re-reads from an offset, a live sensor has no past worth delivering. An `id` containing a
|
|
||||||
newline is rejected rather than stripped, since the SSE format is line-based and an id is exactly
|
|
||||||
the value most likely to be built from a request — a cursor, a page token — so one newline would
|
|
||||||
let a caller append fields to somebody else's stream. On an `ndjson` or `negotiate`-to-ndjson route
|
|
||||||
the payload is unwrapped and the fields dropped. New exports: `sse`, `isSseEvent`, `SseEvent`,
|
|
||||||
`SseFields`.
|
|
||||||
|
|
||||||
### Changed
|
|
||||||
|
|
||||||
- **A request's security and CORS headers are computed once.** They were derived twice per request
|
|
||||||
and three times for a preflight — once in the adapter, to seed the headers a response written
|
|
||||||
before routing still has to carry, and again during dispatch. Nothing was incorrect, but
|
|
||||||
`cors.origins` is a predicate precisely so it can be a lookup: an allowlist in Redis, a tenant
|
|
||||||
query. Running it two or three times charged the caller's latency budget and their backend for an
|
|
||||||
answer whose inputs had not changed in between, and made a predicate with a counter in it count
|
|
||||||
double.
|
|
||||||
|
|
||||||
- **Every `request:end` is now preceded by a `request:start` carrying the same `requestId`.** The
|
|
||||||
pairing held by accident until `maxConcurrentRequests` arrived: `request:start` had a single
|
|
||||||
emitter, so nothing could break it, and a shed request emitted only the `request:end`. A consumer
|
|
||||||
that opens per-request state on the first and closes it on the second — an in-flight gauge, most
|
|
||||||
obviously — would have drifted under shedding, which is when an operator is reading it, and would
|
|
||||||
have done so by producing a plausible wrong number rather than an error. It is a guarantee now,
|
|
||||||
written next to `LifecycleEvent` and enforced by a test that enumerates every response shape.
|
|
||||||
|
|
||||||
- **An unmatched request carries a bounded `route`.** `route:unmatched` was the one terminal request
|
|
||||||
event with no `route`, so the only subject a consumer could reach was `name` — which on that event
|
|
||||||
is the concrete, caller-controlled path. A matched path is bounded by the route table; an
|
|
||||||
unmatched one is bounded by nothing, and a scanner walking `/aaa`, `/aab`, `/aac` is a memory leak
|
|
||||||
with a metrics backend attached. It and the `request:end` that follows now carry
|
|
||||||
`route: '<unmatched>'`, exported as `UNMATCHED_ROUTE`. Written down alongside it: `name` is
|
|
||||||
caller-controlled and must never be a metric label.
|
|
||||||
|
|
||||||
- **Framework token names are reserved.** `logger`, `rooms`, `events` and `bus` cannot be declared
|
|
||||||
by a module, plugin or mesh export; taking one is a boot error naming it. Built-ins used to be
|
|
||||||
registered only if the name was free, so a provider called `logger` silently replaced the
|
|
||||||
framework's own and every `@needs('logger')` in the app got something that was not the logger core
|
|
||||||
writes to — a divergence discovered from a log line that never appeared. `bus` is reserved without
|
|
||||||
being provided, so `@needs('bus')` cannot resolve to whatever a user happened to call `bus`.
|
|
||||||
|
|
||||||
**This can fail an app that boots today**, which is the point of it, and the fix is to rename.
|
|
||||||
|
|
||||||
- **No per-request bookkeeping when no request budget is set.** Every request registered a `close`
|
|
||||||
listener and set a flag for `maxConcurrentRequests`, which is opt-in and unlimited by default — so
|
|
||||||
most applications paid a closure and an `EventEmitter` registration per request, on the hot path,
|
|
||||||
for a feature that was off. Unchanged where a budget *is* configured: the listener is what
|
|
||||||
releases a slot when a client disconnects mid-handler.
|
|
||||||
|
|
||||||
- **Route ranking is settled when the route table is built, not on every request.** Matching scanned
|
|
||||||
every route registered under the request's method and ranked the candidates as it went, deriving
|
|
||||||
each pattern's specificity from its source string per comparison. Both the scan and the ranking
|
|
||||||
scale with the size of the route table, and neither can produce a different answer between two
|
|
||||||
requests — the table is assembled once, after the graph is prepared, and handed to the adapter
|
|
||||||
unchanged. Routes are now compiled, bucketed by method and ordered most-specific-first once, and
|
|
||||||
matching returns at the first route that matches.
|
|
||||||
|
|
||||||
Nothing about which route answers changes. Equal specificity still keeps registration order, which
|
|
||||||
the ordering carries through a stable sort rather than through a scan that declined to replace its
|
|
||||||
best on a tie. Two smaller savings ride along on the same path: a path segment holding no `%` skips
|
|
||||||
`decodeURIComponent` entirely, and decoding is memoized per request rather than repeated for every
|
|
||||||
candidate route that reaches the same parameter position.
|
|
||||||
|
|
||||||
Worth nothing on a small route table and worth a great deal on a large one, which is the shape of
|
|
||||||
the saving rather than a caveat on it: **no measurable change at 6 routes, +3.4% at 50, and +12% to
|
|
||||||
+14.9% at 200**. That is also why it went unnoticed for two releases — the benchmark had no
|
|
||||||
route-table-width dimension until this one, so every matcher change measured as noise regardless of
|
|
||||||
its size.
|
|
||||||
|
|
||||||
- **Independent providers boot concurrently.** Boot walked the topological order one node at a time,
|
|
||||||
so an application paid the *sum* of its providers' latencies rather than its longest chain — three
|
|
||||||
providers with no edges between them and 200ms of work each took 616ms for a graph whose critical
|
|
||||||
path is 200ms; it now takes 210ms. The graph already proved which nodes cannot constrain each
|
|
||||||
other, and flattening the sort was the only thing throwing that away: the ordered list is grouped
|
|
||||||
back into dependency levels and each level runs together, with level *N* fully registered and
|
|
||||||
warmed before *N+1* starts. Nothing the graph derives changes, and this is the second thing users
|
|
||||||
get for declaring `needs`/`provides` rather than ordering calls by hand — pruning was the first,
|
|
||||||
and neither is available to a middleware chain, where nothing declares what is independent.
|
|
||||||
|
|
||||||
Two consequences worth knowing. Teardown still runs in the exact reverse of boot: registration
|
|
||||||
follows level order rather than completion order, which is what keeps that a guarantee instead of
|
|
||||||
a race. And a required provider that fails no longer prevents its independent siblings from
|
|
||||||
starting — they are already in flight — so whatever they opened is registered for teardown before
|
|
||||||
the boot is aborted. On the bus, `boot:provider:start` no longer strictly alternates with `:ok`; a
|
|
||||||
level emits its starts together and then its results.
|
|
||||||
|
|
||||||
### Fixed
|
|
||||||
|
|
||||||
- **A `cors.origins` predicate that throws no longer takes the process down.** The predicate runs on
|
|
||||||
the request path, above the region where errors convert to a response, so a throw became a rejected
|
|
||||||
promise nobody awaited — and Node's default for that is to exit. One cross-origin request was
|
|
||||||
enough, `onError` never saw it, and the trigger is a browser: the predicate is only reached when an
|
|
||||||
`Origin` header is present, so no test that forgets the header can catch it. A predicate that throws
|
|
||||||
now **denies** the origin and the failure is logged. A lookup that failed has not said yes, and a
|
|
||||||
broken allowlist must never widen into an open one.
|
|
||||||
|
|
||||||
- **The JSR package works.** JSR serves `src/` rather than the tsup build, and the ESM build's
|
|
||||||
`createRequire` banner therefore never existed there — so every lazy `require()` in the source had
|
|
||||||
nothing to resolve. `@Html('file')` and template mode died at boot on Deno with `ReferenceError:
|
|
||||||
require is not defined`. Two other sites were worse than the crash because they answered
|
|
||||||
confidently and wrongly: `static` reported *"needs a filesystem and is unavailable on this runtime
|
|
||||||
(edge)"* while running on Deno, which has one, and multipart reported `busboy` as not installed
|
|
||||||
while it sat in `node_modules`. Both blamed the runtime for a packaging problem, and both named a
|
|
||||||
runtime the reader was not on.
|
|
||||||
|
|
||||||
Every call site now resolves through one helper that prefers the ambient `require` — so both npm
|
|
||||||
builds behave exactly as before — and otherwise rebuilds one from
|
|
||||||
`process.getBuiltinModule('node:module')`, which Node, Deno and Bun all expose synchronously. On
|
|
||||||
workerd, which offers neither, nothing changes and the guarded sites' "edge has no filesystem"
|
|
||||||
story is finally the true one.
|
|
||||||
|
|
||||||
- **A custom `onError` that throws no longer takes the process down.** `createApp({ onError })` is
|
|
||||||
the advertised way to render errors, it runs on the request path, and it ran with no boundary — a
|
|
||||||
renderer that threw exited the process, exit code 1. It is the same shape as the CORS predicate
|
|
||||||
crash above and easier to reach: not a cross-origin request, but *any* request that produces an
|
|
||||||
error. The renderer produces the 404 too, so an app with a custom renderer and no matching route
|
|
||||||
was one request away from exiting.
|
|
||||||
|
|
||||||
It was also the worst-timed crash there was, since the renderer only runs once something has
|
|
||||||
already gone wrong: an error occurs, the code written to report it fails, and instead of a
|
|
||||||
degraded report the server ends. A renderer that throws now falls back to the built-in rendering —
|
|
||||||
which is exactly what the option overrides — so the original error still gets its response, and
|
|
||||||
the renderer's own failure is logged separately, naming both.
|
|
||||||
|
|
||||||
- **A stream's lifecycle is reported on every runtime, and joins back to its request.** `stream:open`,
|
|
||||||
`stream:close` and `stream:error` were emitted only by the Node adapter. Every Fetch runtime — Deno,
|
|
||||||
Bun, workerd, and `app.fetch()` on Node — emitted none of them and broke the response with a
|
|
||||||
transport error instead of writing the encoder's error frame. Both halves were silent: a consumer
|
|
||||||
counting `stream:error` saw zero on three of the four runtimes while streams were failing normally,
|
|
||||||
and the client got a truncated body indistinguishable from a clean end of stream. The Fetch path now
|
|
||||||
emits all three and frames the error before closing cleanly, which is what the Node adapter always
|
|
||||||
did and the better answer for the client — an SSE consumer that received an `error` event knows what
|
|
||||||
happened, where a dropped connection tells it nothing.
|
|
||||||
|
|
||||||
All three events now also carry the opening request's `requestId` and `traceId`, plus a bounded
|
|
||||||
`route`. `src/http/core.ts` had documented them as carrying the id since the stream landed; they
|
|
||||||
never did. The split they exist for is deliberate — a route returning an `AsyncIterable` is done in
|
|
||||||
milliseconds while its connection may live for hours, so `request:end` fires at the handler's return
|
|
||||||
and hour-long connections stay out of the same latency distribution as 2ms replies — but it only
|
|
||||||
works if the two can be *joined*, and without the id an exporter could not say which request opened
|
|
||||||
the connection still holding a slot. A WebSocket upgrade correlates itself: it is an HTTP request
|
|
||||||
with headers like any other, so it adopts a gateway's `x-request-id` rather than opening a second
|
|
||||||
identity, and carries `transport: 'ws'`.
|
|
||||||
|
|
||||||
## [26.8.0-beta.1] - 2026-08-19
|
## [26.8.0-beta.1] - 2026-08-19
|
||||||
|
|
||||||
@@ -527,7 +309,7 @@ change before the stable release.
|
|||||||
- **Benchmarks** — reproducible `npm run bench` harness vs Express 5, Fastify 5,
|
- **Benchmarks** — reproducible `npm run bench` harness vs Express 5, Fastify 5,
|
||||||
NestJS, and raw `http`; results in [BENCHMARKS.md](./BENCHMARKS.md).
|
NestJS, and raw `http`; results in [BENCHMARKS.md](./BENCHMARKS.md).
|
||||||
|
|
||||||
[26.9.0-beta.1]: https://github.com/Expressive-Tea/green-tea/compare/v26.8.0-beta.1...v26.9.0-beta.1
|
[Unreleased]: https://github.com/Expressive-Tea/green-tea/compare/v26.8.0-beta.1...main
|
||||||
[26.8.0-beta.1]: https://github.com/Expressive-Tea/green-tea/compare/v26.8.0-beta.0...v26.8.0-beta.1
|
[26.8.0-beta.1]: https://github.com/Expressive-Tea/green-tea/compare/v26.8.0-beta.0...v26.8.0-beta.1
|
||||||
[26.8.0-beta.0]: https://github.com/Expressive-Tea/green-tea/compare/v26.7.0-beta.0...v26.8.0-beta.0
|
[26.8.0-beta.0]: https://github.com/Expressive-Tea/green-tea/compare/v26.7.0-beta.0...v26.8.0-beta.0
|
||||||
[26.7.0-beta.0]: https://github.com/Expressive-Tea/green-tea/releases/tag/v26.7.0-beta.0
|
[26.7.0-beta.0]: https://github.com/Expressive-Tea/green-tea/releases/tag/v26.7.0-beta.0
|
||||||
@@ -1,270 +0,0 @@
|
|||||||
/**
|
|
||||||
* Compares green-tea against an earlier green-tea, on one box, in one sitting.
|
|
||||||
*
|
|
||||||
* `BENCHMARKS.md` answers "how do we compare to Fastify". This answers the question a release
|
|
||||||
* actually has to pass: **did the last N commits cost anything.** It is a different measurement and
|
|
||||||
* it needs a different setup, because comparing today's numbers against a table generated weeks ago
|
|
||||||
* compares two machines-in-a-mood, not two versions.
|
|
||||||
*
|
|
||||||
* Usage:
|
|
||||||
*
|
|
||||||
* git worktree add /tmp/base v26.8.0-beta.1
|
|
||||||
* ln -s "$PWD/node_modules" /tmp/base/node_modules
|
|
||||||
* AB_BASE=/tmp/base npm run bench:compare
|
|
||||||
*
|
|
||||||
* The worktree shares this checkout's `node_modules`, which is only sound while `package.json` has
|
|
||||||
* not moved between the two revisions — check that first, or the comparison is measuring a
|
|
||||||
* dependency bump.
|
|
||||||
*
|
|
||||||
* Env: `AB_BASE` (required), `AB_DURATION` (10), `AB_ROUNDS` (3), `AB_CONNS` (100),
|
|
||||||
* `AB_ONLY` (comma-separated substrings of case names), `AB_OUT` (bench/compare-results.json).
|
|
||||||
*/
|
|
||||||
import autocannon from 'autocannon';
|
|
||||||
import { spawn } from 'child_process';
|
|
||||||
import { writeFileSync } from 'fs';
|
|
||||||
|
|
||||||
const DURATION = Number(process.env.AB_DURATION ?? 10);
|
|
||||||
const ROUNDS = Number(process.env.AB_ROUNDS ?? 3);
|
|
||||||
const CONNS = Number(process.env.AB_CONNS ?? 100);
|
|
||||||
|
|
||||||
const HEAD = process.cwd();
|
|
||||||
// Per side, so "the bundle we publish vs the source we test" is one run rather than two tables.
|
|
||||||
const BASE_SERVER = process.env.AB_BASE_SERVER ?? 'compare';
|
|
||||||
const HEAD_SERVER = process.env.AB_HEAD_SERVER ?? 'compare';
|
|
||||||
|
|
||||||
function requireBase(): string {
|
|
||||||
const base = process.env.AB_BASE;
|
|
||||||
if (base) return base;
|
|
||||||
console.error('AB_BASE must point at a worktree of the revision to compare against — see the header of this file.');
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
const BASE = requireBase();
|
|
||||||
|
|
||||||
interface Case {
|
|
||||||
name: string;
|
|
||||||
path: string;
|
|
||||||
method?: 'GET' | 'POST' | 'OPTIONS';
|
|
||||||
body?: unknown;
|
|
||||||
headers?: Record<string, string>;
|
|
||||||
env?: Record<string, string>;
|
|
||||||
}
|
|
||||||
|
|
||||||
const ORIGIN = { origin: 'http://bench.example' };
|
|
||||||
|
|
||||||
const CASES: Case[] = [
|
|
||||||
{ name: 'hello', path: '/hello' },
|
|
||||||
{ name: 'param', path: '/users/42' },
|
|
||||||
{ name: 'pipeline (3 steps)', path: '/pipeline' },
|
|
||||||
{ name: 'steps5', path: '/steps/5' },
|
|
||||||
{ name: 'validate (POST)', path: '/validate', method: 'POST', body: { email: 'bench@example.com' } },
|
|
||||||
{ name: 'hello + security', path: '/hello', env: { GT_SECURE: '1' } },
|
|
||||||
// The CORS predicate is only reached when a request carries an `Origin`, so a case that forgets
|
|
||||||
// the header measures the path around it rather than the path through it.
|
|
||||||
{ name: 'hello + cors predicate', path: '/hello', env: { GT_CORS: '1' }, headers: ORIGIN },
|
|
||||||
{
|
|
||||||
name: 'preflight + cors predicate',
|
|
||||||
path: '/hello',
|
|
||||||
method: 'OPTIONS',
|
|
||||||
env: { GT_CORS: '1' },
|
|
||||||
headers: { ...ORIGIN, 'access-control-request-method': 'GET' },
|
|
||||||
},
|
|
||||||
// Route-table width. Every matcher cost scales with the number of candidates a request walks
|
|
||||||
// past, and the cross-framework table has six routes — so a change that saves work per candidate
|
|
||||||
// measures as noise there no matter how real it is. `/users/:id` is registered last and is not
|
|
||||||
// all-static, so it takes the full scan rather than the early exit a literal path gets.
|
|
||||||
{ name: 'param, 50 routes', path: '/users/42', env: { GT_ROUTES: '50' } },
|
|
||||||
{ name: 'param, 200 routes', path: '/users/42', env: { GT_ROUTES: '200' } },
|
|
||||||
];
|
|
||||||
|
|
||||||
const ONLY = process.env.AB_ONLY;
|
|
||||||
const RUN_CASES = ONLY ? CASES.filter((c) => ONLY.split(',').some((k) => c.name.includes(k.trim()))) : CASES;
|
|
||||||
|
|
||||||
function log(m: string): void {
|
|
||||||
process.stderr.write(`[compare] ${m}\n`);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function boot(cwd: string, env: Record<string, string>, server = 'compare'): Promise<{ port: number; kill: () => Promise<void> }> {
|
|
||||||
const child = spawn(process.execPath, ['--import', 'tsx', `bench/servers/${server}.ts`], {
|
|
||||||
cwd,
|
|
||||||
env: { ...process.env, TSX_TSCONFIG_PATH: 'bench/tsconfig.json', ...env },
|
|
||||||
});
|
|
||||||
let stderr = '';
|
|
||||||
child.stderr.on('data', (d) => (stderr += d));
|
|
||||||
const port = await new Promise<number>((resolve, reject) => {
|
|
||||||
const t = setTimeout(() => {
|
|
||||||
child.kill('SIGKILL');
|
|
||||||
reject(new Error(`no READY in 15s:\n${stderr}`));
|
|
||||||
}, 15000);
|
|
||||||
let buf = '';
|
|
||||||
child.stdout.on('data', (d) => {
|
|
||||||
buf += d;
|
|
||||||
const m = /READY (\d+)/.exec(buf);
|
|
||||||
if (m) {
|
|
||||||
clearTimeout(t);
|
|
||||||
resolve(Number(m[1]));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
child.on('exit', (c) => {
|
|
||||||
clearTimeout(t);
|
|
||||||
reject(new Error(`exited ${c}:\n${stderr}`));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
const kill = (): Promise<void> =>
|
|
||||||
new Promise<void>((r) => {
|
|
||||||
child.on('exit', () => r());
|
|
||||||
child.kill('SIGTERM');
|
|
||||||
setTimeout(() => {
|
|
||||||
try {
|
|
||||||
child.kill('SIGKILL');
|
|
||||||
} catch {
|
|
||||||
/* already dead */
|
|
||||||
}
|
|
||||||
}, 2000);
|
|
||||||
});
|
|
||||||
return { port, kill };
|
|
||||||
}
|
|
||||||
|
|
||||||
async function hit(port: number, c: Case, warmup = false): Promise<number> {
|
|
||||||
const r = (await autocannon({
|
|
||||||
url: `http://127.0.0.1:${port}${c.path}`,
|
|
||||||
connections: CONNS,
|
|
||||||
duration: DURATION,
|
|
||||||
pipelining: 1,
|
|
||||||
method: (c.method ?? 'GET') as 'GET',
|
|
||||||
headers: { ...(c.body ? { 'content-type': 'application/json' } : {}), ...c.headers },
|
|
||||||
body: c.body ? JSON.stringify(c.body) : undefined,
|
|
||||||
})) as unknown as {
|
|
||||||
requests: { average: number };
|
|
||||||
non2xx?: number;
|
|
||||||
errors?: number;
|
|
||||||
timeouts?: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
// A case whose route 404s still posts a req/s number, and a run whose connections all errored
|
|
||||||
// posts one too — 0, which a median will quietly absorb. Assert the traffic was the traffic this
|
|
||||||
// case claims to send before believing any of it.
|
|
||||||
// Not on the warmup: a cold server drops a handful of connections from the opening burst, and
|
|
||||||
// absorbing exactly that is what the warmup is for. Asserting on it fails the run for the noise
|
|
||||||
// it exists to discard.
|
|
||||||
if (!warmup) {
|
|
||||||
const bad = (r.non2xx ?? 0) + (r.errors ?? 0) + (r.timeouts ?? 0);
|
|
||||||
if (bad > 0) throw new Error(`${c.name}: ${bad} non-2xx/error/timeout responses — not measuring what it claims`);
|
|
||||||
if (!(r.requests.average > 0)) throw new Error(`${c.name}: 0 req/s — the run produced no traffic`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return r.requests.average;
|
|
||||||
}
|
|
||||||
|
|
||||||
const median = (xs: number[]): number => {
|
|
||||||
const s = [...xs].sort((a, b) => a - b);
|
|
||||||
const m = s.length >> 1;
|
|
||||||
return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* True when the two sides' sample ranges do not overlap at all.
|
|
||||||
*
|
|
||||||
* A weak signal on its own and stated as such: with three samples a pair of overlapping
|
|
||||||
* distributions separates by chance often enough to fool you, which it did the first time this was
|
|
||||||
* run. Treat a flagged row as "measure it again with more rounds", never as a result.
|
|
||||||
*/
|
|
||||||
const separated = (a: number[], b: number[]): boolean => {
|
|
||||||
const [x, y] = [[...a].sort((p, q) => p - q), [...b].sort((p, q) => p - q)];
|
|
||||||
return x[0] > y[y.length - 1] || y[0] > x[x.length - 1];
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Counts `cors.origins` invocations for one cross-origin GET and one preflight.
|
|
||||||
*
|
|
||||||
* Deliberately a count rather than a rate: the benchmark's predicate is a `Set.has`, so calls saved
|
|
||||||
* are invisible in req/s — but the option takes a function so it can be a lookup, and there the
|
|
||||||
* same saving is a network round trip.
|
|
||||||
*/
|
|
||||||
async function corsCalls(cwd: string, server: string): Promise<{ get: number; preflight: number }> {
|
|
||||||
const { port, kill } = await boot(cwd, { GT_CORS: '1' }, server);
|
|
||||||
const base = `http://127.0.0.1:${port}`;
|
|
||||||
// The read carries no `Origin`, so asking cannot change the answer.
|
|
||||||
const read = async (): Promise<number> => ((await (await fetch(`${base}/cors-calls`)).json()) as { calls: number }).calls;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const before = await read();
|
|
||||||
await fetch(`${base}/hello`, { headers: ORIGIN });
|
|
||||||
const afterGet = await read();
|
|
||||||
await fetch(`${base}/hello`, { method: 'OPTIONS', headers: { ...ORIGIN, 'access-control-request-method': 'GET' } });
|
|
||||||
const afterPreflight = await read();
|
|
||||||
return { get: afterGet - before, preflight: afterPreflight - afterGet };
|
|
||||||
} finally {
|
|
||||||
await kill();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function main(): Promise<void> {
|
|
||||||
const samples: Record<string, { base: number[]; head: number[] }> = {};
|
|
||||||
for (const c of RUN_CASES) samples[c.name] = { base: [], head: [] };
|
|
||||||
|
|
||||||
for (let round = 0; round < ROUNDS; round++) {
|
|
||||||
// Alternate which side goes first. Thermal drift and background load over a half-hour run are
|
|
||||||
// real; alternating spreads them across both sides instead of charging them to whichever went
|
|
||||||
// second.
|
|
||||||
const order: Array<['base' | 'head', string]> =
|
|
||||||
round % 2 === 0
|
|
||||||
? [
|
|
||||||
['base', BASE],
|
|
||||||
['head', HEAD],
|
|
||||||
]
|
|
||||||
: [
|
|
||||||
['head', HEAD],
|
|
||||||
['base', BASE],
|
|
||||||
];
|
|
||||||
|
|
||||||
for (const [side, cwd] of order) {
|
|
||||||
for (const c of RUN_CASES) {
|
|
||||||
const { port, kill } = await boot(cwd, c.env ?? {}, side === 'base' ? BASE_SERVER : HEAD_SERVER);
|
|
||||||
try {
|
|
||||||
await hit(port, c, true); // warmup, discarded
|
|
||||||
const v = await hit(port, c);
|
|
||||||
samples[c.name][side].push(v);
|
|
||||||
log(`round ${round + 1} ${side.padEnd(4)} ${c.name.padEnd(28)} ${Math.round(v).toLocaleString()} req/s`);
|
|
||||||
} finally {
|
|
||||||
await kill();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const rows = RUN_CASES.map((c) => {
|
|
||||||
const b = median(samples[c.name].base);
|
|
||||||
const h = median(samples[c.name].head);
|
|
||||||
return {
|
|
||||||
name: c.name,
|
|
||||||
base: b,
|
|
||||||
head: h,
|
|
||||||
delta: ((h - b) / b) * 100,
|
|
||||||
separated: separated(samples[c.name].base, samples[c.name].head),
|
|
||||||
samples: samples[c.name],
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
const cors = { base: await corsCalls(BASE, BASE_SERVER), head: await corsCalls(HEAD, HEAD_SERVER) };
|
|
||||||
|
|
||||||
writeFileSync(
|
|
||||||
process.env.AB_OUT ?? 'bench/compare-results.json',
|
|
||||||
JSON.stringify({ rounds: ROUNDS, duration: DURATION, conns: CONNS, rows, cors }, null, 2),
|
|
||||||
);
|
|
||||||
|
|
||||||
const f = (n: number): string => Math.round(n).toLocaleString();
|
|
||||||
console.log('\n| Scenario | base | head | Δ | |');
|
|
||||||
console.log('| --- | --- | --- | --- | --- |');
|
|
||||||
for (const r of rows) {
|
|
||||||
const flag = r.separated ? 'ranges do not overlap — re-run with more rounds' : 'overlaps';
|
|
||||||
console.log(`| ${r.name} | ${f(r.base)} | ${f(r.head)} | ${r.delta >= 0 ? '+' : ''}${r.delta.toFixed(1)}% | ${flag} |`);
|
|
||||||
}
|
|
||||||
console.log(`\ncors.origins calls — base: ${cors.base.get} per GET, ${cors.base.preflight} per preflight`);
|
|
||||||
console.log(`cors.origins calls — head: ${cors.head.get} per GET, ${cors.head.preflight} per preflight`);
|
|
||||||
}
|
|
||||||
|
|
||||||
main().catch((e) => {
|
|
||||||
console.error(e);
|
|
||||||
process.exit(1);
|
|
||||||
});
|
|
||||||
+1
-31
@@ -37,8 +37,6 @@ export interface RenderData {
|
|||||||
scenarios: ScenarioBlock[];
|
scenarios: ScenarioBlock[];
|
||||||
stepScaling: { path: string; steps: number; reqSec: number }[];
|
stepScaling: { path: string; steps: number; reqSec: number }[];
|
||||||
secureCost: { label: string; reqSec: number }[];
|
secureCost: { label: string; reqSec: number }[];
|
||||||
/** Optional: results captured before the runtime matrix existed still render. */
|
|
||||||
runtimes?: { runtime: string; scenario: string; reqSec: number }[];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const fmtInt = (n: number): string => Math.round(n).toLocaleString('en-US');
|
const fmtInt = (n: number): string => Math.round(n).toLocaleString('en-US');
|
||||||
@@ -126,33 +124,6 @@ function renderStepScaling(stepScaling: RenderData['stepScaling']): string {
|
|||||||
return ['## Step-scaling (green-tea)', '', header, divider, ...lines, '', deltaNote, ''].join('\n');
|
return ['## Step-scaling (green-tea)', '', header, divider, ...lines, '', deltaNote, ''].join('\n');
|
||||||
}
|
}
|
||||||
|
|
||||||
/** green-tea on each runtime it supports, one column per runtime, all loading the built bundle. */
|
|
||||||
function renderRuntimes(runtimes: RenderData['runtimes']): string {
|
|
||||||
if (!runtimes?.length) return '';
|
|
||||||
|
|
||||||
const names = [...new Set(runtimes.map((row) => row.runtime))];
|
|
||||||
const scenarios = [...new Set(runtimes.map((row) => row.scenario))];
|
|
||||||
const at = (runtime: string, scenario: string): number | undefined =>
|
|
||||||
runtimes.find((row) => row.runtime === runtime && row.scenario === scenario)?.reqSec;
|
|
||||||
|
|
||||||
const header = `| Scenario | ${names.join(' | ')} |`;
|
|
||||||
const divider = `| --- | ${names.map(() => '---').join(' | ')} |`;
|
|
||||||
const lines = scenarios.map((scenario) => {
|
|
||||||
const cells = names.map((runtime) => {
|
|
||||||
const value = at(runtime, scenario);
|
|
||||||
return value === undefined ? '—' : fmtInt(value);
|
|
||||||
});
|
|
||||||
return `| ${scenario} | ${cells.join(' | ')} |`;
|
|
||||||
});
|
|
||||||
|
|
||||||
const note =
|
|
||||||
'Same application, same built bundle, same box — only the runtime differs. Read across a row, ' +
|
|
||||||
'never against the cross-framework tables above: those measure other frameworks on Node, and ' +
|
|
||||||
'nobody ran fastify on Bun here. A runtime that is not installed is absent rather than zero.';
|
|
||||||
|
|
||||||
return ['## green-tea across runtimes', '', header, divider, ...lines, '', note].join('\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderSecureCost(secureCost: RenderData['secureCost']): string {
|
function renderSecureCost(secureCost: RenderData['secureCost']): string {
|
||||||
const header = '| Label | req/s |';
|
const header = '| Label | req/s |';
|
||||||
const divider = '| --- | --- |';
|
const divider = '| --- | --- |';
|
||||||
@@ -225,7 +196,7 @@ function renderLeaderboard(scenarios: ScenarioBlock[]): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function renderMarkdown(data: RenderData): string {
|
export function renderMarkdown(data: RenderData): string {
|
||||||
const { env, config, scenarios, stepScaling, secureCost, runtimes } = data;
|
const { env, config, scenarios, stepScaling, secureCost } = data;
|
||||||
|
|
||||||
return [
|
return [
|
||||||
renderLeaderboard(scenarios),
|
renderLeaderboard(scenarios),
|
||||||
@@ -237,7 +208,6 @@ export function renderMarkdown(data: RenderData): string {
|
|||||||
'',
|
'',
|
||||||
renderScenarios(scenarios),
|
renderScenarios(scenarios),
|
||||||
renderStepScaling(stepScaling),
|
renderStepScaling(stepScaling),
|
||||||
renderRuntimes(runtimes),
|
|
||||||
renderSecureCost(secureCost),
|
renderSecureCost(secureCost),
|
||||||
renderMethodology(),
|
renderMethodology(),
|
||||||
].join('\n');
|
].join('\n');
|
||||||
|
|||||||
+144
-206
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"env": {
|
"env": {
|
||||||
"date": "2026-09-02",
|
"date": "2026-07-07",
|
||||||
"commit": "8c5855c",
|
"commit": "fe1831a",
|
||||||
"node": "v22.22.2",
|
"node": "v22.22.2",
|
||||||
"os": "darwin",
|
"os": "darwin",
|
||||||
"cpu": "Apple M4 Max (16 cores)",
|
"cpu": "Apple M4 Max (16 cores)",
|
||||||
@@ -10,8 +10,8 @@
|
|||||||
},
|
},
|
||||||
"config": {
|
"config": {
|
||||||
"conns": 100,
|
"conns": 100,
|
||||||
"duration": 10,
|
"duration": 5,
|
||||||
"runs": 5,
|
"runs": 3,
|
||||||
"warmup": 1,
|
"warmup": 1,
|
||||||
"pipelining": 1
|
"pipelining": 1
|
||||||
},
|
},
|
||||||
@@ -23,11 +23,11 @@
|
|||||||
{
|
{
|
||||||
"framework": "raw-http",
|
"framework": "raw-http",
|
||||||
"reqSec": {
|
"reqSec": {
|
||||||
"median": 119357.1,
|
"median": 115398.4,
|
||||||
"min": 118560,
|
"min": 114822.4,
|
||||||
"max": 120066.91,
|
"max": 115539.2,
|
||||||
"stddev": 484.9030139151553,
|
"stddev": 310.09010876768724,
|
||||||
"cv": 0.0040636145553490976
|
"cv": 0.0026905088104554075
|
||||||
},
|
},
|
||||||
"p50": 0,
|
"p50": 0,
|
||||||
"p99": 1,
|
"p99": 1,
|
||||||
@@ -36,24 +36,24 @@
|
|||||||
{
|
{
|
||||||
"framework": "fastify",
|
"framework": "fastify",
|
||||||
"reqSec": {
|
"reqSec": {
|
||||||
"median": 89096.73,
|
"median": 86764.8,
|
||||||
"min": 88864,
|
"min": 86496,
|
||||||
"max": 89207.28,
|
"max": 87123.2,
|
||||||
"stddev": 111.97759400880093,
|
"stddev": 256.9227813090051,
|
||||||
"cv": 0.001257219726589825
|
"cv": 0.002960121758353106
|
||||||
},
|
},
|
||||||
"p50": 1,
|
"p50": 1,
|
||||||
"p99": 1,
|
"p99": 2,
|
||||||
"p999": 2
|
"p999": 2
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"framework": "express",
|
"framework": "express",
|
||||||
"reqSec": {
|
"reqSec": {
|
||||||
"median": 24677.1,
|
"median": 24366.4,
|
||||||
"min": 24646.55,
|
"min": 24283.2,
|
||||||
"max": 24768.73,
|
"max": 24417.6,
|
||||||
"stddev": 43.02015834466458,
|
"stddev": 55.38455460585383,
|
||||||
"cv": 0.0017417832565876405
|
"cv": 0.002273984274990166
|
||||||
},
|
},
|
||||||
"p50": 3,
|
"p50": 3,
|
||||||
"p99": 5,
|
"p99": 5,
|
||||||
@@ -62,39 +62,39 @@
|
|||||||
{
|
{
|
||||||
"framework": "green-tea",
|
"framework": "green-tea",
|
||||||
"reqSec": {
|
"reqSec": {
|
||||||
"median": 87473.46,
|
"median": 98092.8,
|
||||||
"min": 86903.28,
|
"min": 98054.4,
|
||||||
"max": 87607.28,
|
"max": 98668.8,
|
||||||
"stddev": 280.84365746087286,
|
"stddev": 281.0175795212842,
|
||||||
"cv": 0.0032155347907296527
|
"cv": 0.002859589501804015
|
||||||
},
|
},
|
||||||
"p50": 1,
|
"p50": 0,
|
||||||
"p99": 2,
|
"p99": 1,
|
||||||
"p999": 2
|
"p999": 2
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"framework": "nestjs-express",
|
"framework": "nestjs-express",
|
||||||
"reqSec": {
|
"reqSec": {
|
||||||
"median": 21878.55,
|
"median": 21761.6,
|
||||||
"min": 21845.1,
|
"min": 21697.6,
|
||||||
"max": 21952.73,
|
"max": 21896,
|
||||||
"stddev": 41.00873789816055,
|
"stddev": 82.67870880032535,
|
||||||
"cv": 0.0018731606009975037
|
"cv": 0.0037952010918943873
|
||||||
},
|
},
|
||||||
"p50": 4,
|
"p50": 4,
|
||||||
"p99": 6,
|
"p99": 6,
|
||||||
"p999": 9
|
"p999": 10
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"framework": "nestjs-fastify",
|
"framework": "nestjs-fastify",
|
||||||
"reqSec": {
|
"reqSec": {
|
||||||
"median": 98039.28,
|
"median": 95033.6,
|
||||||
"min": 96072.73,
|
"min": 94240,
|
||||||
"max": 99680,
|
"max": 95264,
|
||||||
"stddev": 1215.4038343760499,
|
"stddev": 438.6166536839312,
|
||||||
"cv": 0.012396669934655963
|
"cv": 0.00462452048886261
|
||||||
},
|
},
|
||||||
"p50": 0,
|
"p50": 1,
|
||||||
"p99": 1,
|
"p99": 1,
|
||||||
"p999": 2
|
"p999": 2
|
||||||
}
|
}
|
||||||
@@ -107,11 +107,11 @@
|
|||||||
{
|
{
|
||||||
"framework": "raw-http",
|
"framework": "raw-http",
|
||||||
"reqSec": {
|
"reqSec": {
|
||||||
"median": 120904.73,
|
"median": 116332.8,
|
||||||
"min": 119927.28,
|
"min": 115974.4,
|
||||||
"max": 121713.46,
|
"max": 116409.6,
|
||||||
"stddev": 658.0250991747977,
|
"stddev": 189.66281191162406,
|
||||||
"cv": 0.005441723483024015
|
"cv": 0.001631663389130871
|
||||||
},
|
},
|
||||||
"p50": 0,
|
"p50": 0,
|
||||||
"p99": 1,
|
"p99": 1,
|
||||||
@@ -120,24 +120,24 @@
|
|||||||
{
|
{
|
||||||
"framework": "fastify",
|
"framework": "fastify",
|
||||||
"reqSec": {
|
"reqSec": {
|
||||||
"median": 88317.1,
|
"median": 86278.4,
|
||||||
"min": 87997.1,
|
"min": 86137.6,
|
||||||
"max": 88439.28,
|
"max": 86764.8,
|
||||||
"stddev": 182.99174422907566,
|
"stddev": 268.69839349476365,
|
||||||
"cv": 0.00207430857941761
|
"cv": 0.003110165492522174
|
||||||
},
|
},
|
||||||
"p50": 1,
|
"p50": 1,
|
||||||
"p99": 1,
|
"p99": 2,
|
||||||
"p999": 2
|
"p999": 2
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"framework": "express",
|
"framework": "express",
|
||||||
"reqSec": {
|
"reqSec": {
|
||||||
"median": 24200,
|
"median": 23835.2,
|
||||||
"min": 24157.82,
|
"min": 23803.2,
|
||||||
"max": 24259.64,
|
"max": 24046.4,
|
||||||
"stddev": 39.43298619176589,
|
"stddev": 107.89690552662897,
|
||||||
"cv": 0.0016290899720752198
|
"cv": 0.004515472130491916
|
||||||
},
|
},
|
||||||
"p50": 3,
|
"p50": 3,
|
||||||
"p99": 5,
|
"p99": 5,
|
||||||
@@ -146,11 +146,11 @@
|
|||||||
{
|
{
|
||||||
"framework": "green-tea",
|
"framework": "green-tea",
|
||||||
"reqSec": {
|
"reqSec": {
|
||||||
"median": 86594.91,
|
"median": 93433.6,
|
||||||
"min": 86368,
|
"min": 93152,
|
||||||
"max": 86880,
|
"max": 93612.8,
|
||||||
"stddev": 179.11650003279965,
|
"stddev": 189.6628119116206,
|
||||||
"cv": 0.002068552609808656
|
"cv": 0.002030662686635119
|
||||||
},
|
},
|
||||||
"p50": 1,
|
"p50": 1,
|
||||||
"p99": 2,
|
"p99": 2,
|
||||||
@@ -159,27 +159,27 @@
|
|||||||
{
|
{
|
||||||
"framework": "nestjs-express",
|
"framework": "nestjs-express",
|
||||||
"reqSec": {
|
"reqSec": {
|
||||||
"median": 21181.82,
|
"median": 20955.2,
|
||||||
"min": 21149.82,
|
"min": 20948.8,
|
||||||
"max": 21517.82,
|
"max": 21201.6,
|
||||||
"stddev": 139.0670808494951,
|
"stddev": 117.69157432317111,
|
||||||
"cv": 0.006540068168697097
|
"cv": 0.005594982425799189
|
||||||
},
|
},
|
||||||
"p50": 4,
|
"p50": 4,
|
||||||
"p99": 6,
|
"p99": 6,
|
||||||
"p999": 9
|
"p999": 11
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"framework": "nestjs-fastify",
|
"framework": "nestjs-fastify",
|
||||||
"reqSec": {
|
"reqSec": {
|
||||||
"median": 91848.73,
|
"median": 89312,
|
||||||
"min": 91825.46,
|
"min": 89235.2,
|
||||||
"max": 92599.28,
|
"max": 89529.6,
|
||||||
"stddev": 296.55679952413783,
|
"stddev": 124.68598780759793,
|
||||||
"cv": 0.00322222064035544
|
"cv": 0.001395338811201841
|
||||||
},
|
},
|
||||||
"p50": 1,
|
"p50": 1,
|
||||||
"p99": 1,
|
"p99": 2,
|
||||||
"p999": 2
|
"p999": 2
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
@@ -192,11 +192,11 @@
|
|||||||
{
|
{
|
||||||
"framework": "raw-http",
|
"framework": "raw-http",
|
||||||
"reqSec": {
|
"reqSec": {
|
||||||
"median": 118996.37,
|
"median": 113491.2,
|
||||||
"min": 118583.28,
|
"min": 112531.2,
|
||||||
"max": 119584,
|
"max": 114809.6,
|
||||||
"stddev": 341.82644850274596,
|
"stddev": 933.9810324031724,
|
||||||
"cv": 0.002872466494470492
|
"cv": 0.008220892102882115
|
||||||
},
|
},
|
||||||
"p50": 0,
|
"p50": 0,
|
||||||
"p99": 1,
|
"p99": 1,
|
||||||
@@ -205,24 +205,24 @@
|
|||||||
{
|
{
|
||||||
"framework": "fastify",
|
"framework": "fastify",
|
||||||
"reqSec": {
|
"reqSec": {
|
||||||
"median": 86670.55,
|
"median": 85024,
|
||||||
"min": 86490.19,
|
"min": 84512,
|
||||||
"max": 86792.73,
|
"max": 85177.6,
|
||||||
"stddev": 97.03476704769095,
|
"stddev": 284.55819947576623,
|
||||||
"cv": 0.0011197471063834074
|
"cv": 0.003351507726431956
|
||||||
},
|
},
|
||||||
"p50": 1,
|
"p50": 1,
|
||||||
"p99": 1,
|
"p99": 2,
|
||||||
"p999": 2
|
"p999": 2
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"framework": "express",
|
"framework": "express",
|
||||||
"reqSec": {
|
"reqSec": {
|
||||||
"median": 24325.1,
|
"median": 23950.4,
|
||||||
"min": 24281.46,
|
"min": 23902.4,
|
||||||
"max": 24406.55,
|
"max": 24011.2,
|
||||||
"stddev": 50.44878456414985,
|
"stddev": 44.519758410046,
|
||||||
"cv": 0.002073096921615235
|
"cv": 0.0018585004345727763
|
||||||
},
|
},
|
||||||
"p50": 3,
|
"p50": 3,
|
||||||
"p99": 5,
|
"p99": 5,
|
||||||
@@ -231,11 +231,11 @@
|
|||||||
{
|
{
|
||||||
"framework": "green-tea",
|
"framework": "green-tea",
|
||||||
"reqSec": {
|
"reqSec": {
|
||||||
"median": 80078.55,
|
"median": 84896,
|
||||||
"min": 80026.19,
|
"min": 84243.2,
|
||||||
"max": 80375.28,
|
"max": 85267.2,
|
||||||
"stddev": 126.5427427235537,
|
"stddev": 423.2825796347192,
|
||||||
"cv": 0.00157915416330658
|
"cv": 0.004991414284012342
|
||||||
},
|
},
|
||||||
"p50": 1,
|
"p50": 1,
|
||||||
"p99": 2,
|
"p99": 2,
|
||||||
@@ -244,24 +244,24 @@
|
|||||||
{
|
{
|
||||||
"framework": "nestjs-express",
|
"framework": "nestjs-express",
|
||||||
"reqSec": {
|
"reqSec": {
|
||||||
"median": 20872,
|
"median": 20824,
|
||||||
"min": 20800.73,
|
"min": 20804.8,
|
||||||
"max": 20940.37,
|
"max": 20878.41,
|
||||||
"stddev": 44.78034640330492,
|
"stddev": 31.17605954717337,
|
||||||
"cv": 0.0021458031999967474
|
"cv": 0.001496278247605678
|
||||||
},
|
},
|
||||||
"p50": 4,
|
"p50": 4,
|
||||||
"p99": 6,
|
"p99": 6,
|
||||||
"p999": 9
|
"p999": 11
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"framework": "nestjs-fastify",
|
"framework": "nestjs-fastify",
|
||||||
"reqSec": {
|
"reqSec": {
|
||||||
"median": 89527.28,
|
"median": 87328,
|
||||||
"min": 87572.37,
|
"min": 86867.2,
|
||||||
"max": 90027.64,
|
"max": 87660.8,
|
||||||
"stddev": 867.875358507201,
|
"stddev": 325.38753646827104,
|
||||||
"cv": 0.009726340137622384
|
"cv": 0.0037278603866430907
|
||||||
},
|
},
|
||||||
"p50": 1,
|
"p50": 1,
|
||||||
"p99": 2,
|
"p99": 2,
|
||||||
@@ -276,24 +276,24 @@
|
|||||||
{
|
{
|
||||||
"framework": "raw-http",
|
"framework": "raw-http",
|
||||||
"reqSec": {
|
"reqSec": {
|
||||||
"median": 104288,
|
"median": 100140.8,
|
||||||
"min": 103776,
|
"min": 99846.4,
|
||||||
"max": 104916.37,
|
"max": 100294.4,
|
||||||
"stddev": 371.6125197245094,
|
"stddev": 185.88177843875883,
|
||||||
"cv": 0.0035614220793380035
|
"cv": 0.0018570746103533369
|
||||||
},
|
},
|
||||||
"p50": 0,
|
"p50": 0,
|
||||||
"p99": 1,
|
"p99": 1,
|
||||||
"p999": 1
|
"p999": 2
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"framework": "fastify",
|
"framework": "fastify",
|
||||||
"reqSec": {
|
"reqSec": {
|
||||||
"median": 65905.46,
|
"median": 63721.6,
|
||||||
"min": 65725.1,
|
"min": 63574.4,
|
||||||
"max": 66366.55,
|
"max": 63760,
|
||||||
"stddev": 217.1439762369652,
|
"stddev": 79.99288857281053,
|
||||||
"cv": 0.0032914527300013986
|
"cv": 0.0012560645345785087
|
||||||
},
|
},
|
||||||
"p50": 1,
|
"p50": 1,
|
||||||
"p99": 2,
|
"p99": 2,
|
||||||
@@ -302,53 +302,53 @@
|
|||||||
{
|
{
|
||||||
"framework": "express",
|
"framework": "express",
|
||||||
"reqSec": {
|
"reqSec": {
|
||||||
"median": 20297.46,
|
"median": 20097.6,
|
||||||
"min": 20157.82,
|
"min": 20056,
|
||||||
"max": 20413.82,
|
"max": 20174.41,
|
||||||
"stddev": 99.50819415505447,
|
"stddev": 49.04789518646266,
|
||||||
"cv": 0.004902635960088364
|
"cv": 0.0024390608203285337
|
||||||
},
|
},
|
||||||
"p50": 4,
|
"p50": 4,
|
||||||
"p99": 6,
|
"p99": 6,
|
||||||
"p999": 10
|
"p999": 12
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"framework": "green-tea",
|
"framework": "green-tea",
|
||||||
"reqSec": {
|
"reqSec": {
|
||||||
"median": 70298.19,
|
"median": 77177.61,
|
||||||
"min": 68971.64,
|
"min": 77126.4,
|
||||||
"max": 70606.55,
|
"max": 77254.4,
|
||||||
"stddev": 704.8749988359651,
|
"stddev": 52.602458962379814,
|
||||||
"cv": 0.01008804689681251
|
"cv": 0.0006815013839797027
|
||||||
},
|
},
|
||||||
"p50": 1,
|
"p50": 1,
|
||||||
"p99": 2,
|
"p99": 2,
|
||||||
"p999": 3
|
"p999": 2
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"framework": "nestjs-express",
|
"framework": "nestjs-express",
|
||||||
"reqSec": {
|
"reqSec": {
|
||||||
"median": 18787.64,
|
"median": 18856,
|
||||||
"min": 18684.37,
|
"min": 18852.8,
|
||||||
"max": 18861.82,
|
"max": 19067.2,
|
||||||
"stddev": 57.13389375843402,
|
"stddev": 100.32338821143516,
|
||||||
"cv": 0.0030419312672842124
|
"cv": 0.005301010367660728
|
||||||
},
|
},
|
||||||
"p50": 5,
|
"p50": 5,
|
||||||
"p99": 7,
|
"p99": 7,
|
||||||
"p999": 10
|
"p999": 30
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"framework": "nestjs-fastify",
|
"framework": "nestjs-fastify",
|
||||||
"reqSec": {
|
"reqSec": {
|
||||||
"median": 63317.82,
|
"median": 59145.6,
|
||||||
"min": 62453.82,
|
"min": 59004.8,
|
||||||
"max": 63746.91,
|
"max": 59376,
|
||||||
"stddev": 543.811870536126,
|
"stddev": 153.00625985741647,
|
||||||
"cv": 0.00860786685722159
|
"cv": 0.002585636725423652
|
||||||
},
|
},
|
||||||
"p50": 1,
|
"p50": 1,
|
||||||
"p99": 2,
|
"p99": 3,
|
||||||
"p999": 3
|
"p999": 3
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
@@ -358,89 +358,27 @@
|
|||||||
{
|
{
|
||||||
"path": "/steps/0",
|
"path": "/steps/0",
|
||||||
"steps": 0,
|
"steps": 0,
|
||||||
"reqSec": 88107.64
|
"reqSec": 92281.6
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"path": "/steps/3",
|
"path": "/steps/3",
|
||||||
"steps": 3,
|
"steps": 3,
|
||||||
"reqSec": 79950.55
|
"reqSec": 81529.61
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"path": "/steps/5",
|
"path": "/steps/5",
|
||||||
"steps": 5,
|
"steps": 5,
|
||||||
"reqSec": 74126.55
|
"reqSec": 71993.61
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"secureCost": [
|
"secureCost": [
|
||||||
{
|
{
|
||||||
"label": "security:false (parity)",
|
"label": "security:false (parity)",
|
||||||
"reqSec": 87473.46
|
"reqSec": 98092.8
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"label": "security:true (default)",
|
"label": "security:true (default)",
|
||||||
"reqSec": 83773.1
|
"reqSec": 92998.4
|
||||||
}
|
|
||||||
],
|
|
||||||
"runtimes": [
|
|
||||||
{
|
|
||||||
"runtime": "node",
|
|
||||||
"scenario": "JSON hello (overhead)",
|
|
||||||
"reqSec": 90976
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"runtime": "node",
|
|
||||||
"scenario": "Route param",
|
|
||||||
"reqSec": 88904.73
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"runtime": "node",
|
|
||||||
"scenario": "Pipeline (3 steps)",
|
|
||||||
"reqSec": 82045.1
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"runtime": "node",
|
|
||||||
"scenario": "POST JSON + validation",
|
|
||||||
"reqSec": 72235.64
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"runtime": "deno",
|
|
||||||
"scenario": "JSON hello (overhead)",
|
|
||||||
"reqSec": 153408
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"runtime": "deno",
|
|
||||||
"scenario": "Route param",
|
|
||||||
"reqSec": 146368
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"runtime": "deno",
|
|
||||||
"scenario": "Pipeline (3 steps)",
|
|
||||||
"reqSec": 136256
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"runtime": "deno",
|
|
||||||
"scenario": "POST JSON + validation",
|
|
||||||
"reqSec": 106661.82
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"runtime": "bun",
|
|
||||||
"scenario": "JSON hello (overhead)",
|
|
||||||
"reqSec": 131674.19
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"runtime": "bun",
|
|
||||||
"scenario": "Route param",
|
|
||||||
"reqSec": 126909.1
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"runtime": "bun",
|
|
||||||
"scenario": "Pipeline (3 steps)",
|
|
||||||
"reqSec": 117489.46
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"runtime": "bun",
|
|
||||||
"scenario": "POST JSON + validation",
|
|
||||||
"reqSec": 95124.37
|
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
+3
-74
@@ -1,30 +1,17 @@
|
|||||||
import autocannon from 'autocannon';
|
import autocannon from 'autocannon';
|
||||||
import { spawn, execSync } from 'child_process';
|
import { spawn, execSync } from 'child_process';
|
||||||
import os from 'os';
|
import os from 'os';
|
||||||
import { existsSync, readFileSync, writeFileSync } from 'fs';
|
import { writeFileSync } from 'fs';
|
||||||
import { SCENARIOS, STEP_ROUTES } from './scenarios';
|
import { SCENARIOS, STEP_ROUTES } from './scenarios';
|
||||||
import { aggregate } from './stats';
|
import { aggregate } from './stats';
|
||||||
import { renderMarkdown, type RenderData, type Row, type ScenarioBlock } from './render';
|
import { renderMarkdown, type RenderData, type Row, type ScenarioBlock } from './render';
|
||||||
|
|
||||||
/** Hand-written notes start here and are carried across regenerations verbatim. */
|
|
||||||
const KEEP_BELOW = '<!-- keep-below: hand-written, survives `npm run bench` -->';
|
|
||||||
|
|
||||||
const SMOKE = process.env.BENCH_SMOKE === '1';
|
const SMOKE = process.env.BENCH_SMOKE === '1';
|
||||||
const CONNS = Number(process.env.BENCH_CONNS ?? 100);
|
const CONNS = Number(process.env.BENCH_CONNS ?? 100);
|
||||||
const DURATION = SMOKE ? 1 : Number(process.env.BENCH_DURATION ?? 10);
|
const DURATION = SMOKE ? 1 : Number(process.env.BENCH_DURATION ?? 10);
|
||||||
const RUNS = SMOKE ? 1 : Number(process.env.BENCH_RUNS ?? 5);
|
const RUNS = SMOKE ? 1 : Number(process.env.BENCH_RUNS ?? 5);
|
||||||
const WARMUP = SMOKE ? 0 : Number(process.env.BENCH_WARMUP ?? 1);
|
const WARMUP = SMOKE ? 0 : Number(process.env.BENCH_WARMUP ?? 1);
|
||||||
|
|
||||||
/** Whether a runtime is on PATH. */
|
|
||||||
function which(cmd: string): boolean {
|
|
||||||
try {
|
|
||||||
execSync(`command -v ${cmd}`, { stdio: 'ignore' });
|
|
||||||
return true;
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function log(msg: string): void {
|
function log(msg: string): void {
|
||||||
process.stderr.write(`[bench] ${msg}\n`);
|
process.stderr.write(`[bench] ${msg}\n`);
|
||||||
}
|
}
|
||||||
@@ -36,25 +23,11 @@ interface RunResult {
|
|||||||
p999: number;
|
p999: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* How each server is launched. Node servers are TypeScript run through tsx; the Deno and Bun ones
|
|
||||||
* are handed to their own runtime, which is the whole point of measuring them.
|
|
||||||
*/
|
|
||||||
const LAUNCHERS: Record<string, (file: string) => { cmd: string; args: string[] }> = {
|
|
||||||
node: (file) => ({ cmd: process.execPath, args: ['--import', 'tsx', file] }),
|
|
||||||
// `-A` rather than an enumerated permission set: this is a benchmark server on loopback, and a
|
|
||||||
// missing flag fails as a boot timeout that reads like a framework problem.
|
|
||||||
deno: (file) => ({ cmd: 'deno', args: ['run', '-A', file] }),
|
|
||||||
bun: (file) => ({ cmd: 'bun', args: [file] }),
|
|
||||||
};
|
|
||||||
|
|
||||||
async function spawnServer(
|
async function spawnServer(
|
||||||
name: string,
|
name: string,
|
||||||
extraEnv: Record<string, string> = {},
|
extraEnv: Record<string, string> = {},
|
||||||
runtime: 'node' | 'deno' | 'bun' = 'node',
|
|
||||||
): Promise<{ port: number; kill: () => Promise<void> }> {
|
): Promise<{ port: number; kill: () => Promise<void> }> {
|
||||||
const { cmd, args } = LAUNCHERS[runtime](`bench/servers/${name}.ts`);
|
const child = spawn(process.execPath, ['--import', 'tsx', `bench/servers/${name}.ts`], {
|
||||||
const child = spawn(cmd, args, {
|
|
||||||
env: { ...process.env, TSX_TSCONFIG_PATH: 'bench/tsconfig.json', ...extraEnv },
|
env: { ...process.env, TSX_TSCONFIG_PATH: 'bench/tsconfig.json', ...extraEnv },
|
||||||
});
|
});
|
||||||
let stderr = '';
|
let stderr = '';
|
||||||
@@ -123,7 +96,6 @@ async function main(): Promise<void> {
|
|||||||
}));
|
}));
|
||||||
const stepScaling: RenderData['stepScaling'] = [];
|
const stepScaling: RenderData['stepScaling'] = [];
|
||||||
const secureCost: RenderData['secureCost'] = [];
|
const secureCost: RenderData['secureCost'] = [];
|
||||||
const runtimes: RenderData['runtimes'] = [];
|
|
||||||
|
|
||||||
for (const fw of frameworks) {
|
for (const fw of frameworks) {
|
||||||
log(`booting ${fw}`);
|
log(`booting ${fw}`);
|
||||||
@@ -173,42 +145,6 @@ async function main(): Promise<void> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// green-tea on each runtime it supports. Kept out of the cross-framework tables above on purpose:
|
|
||||||
// those compare frameworks on one runtime, and a green-tea-on-Bun row sitting beside
|
|
||||||
// fastify-on-Node would read as a comparison nobody made.
|
|
||||||
//
|
|
||||||
// All three load `dist/`, so what varies is the runtime. Skipped rather than failed when a
|
|
||||||
// runtime is not installed — a contributor without Bun should still get every other table.
|
|
||||||
for (const { runtime, server } of [
|
|
||||||
{ runtime: 'node', server: 'green-tea-node' },
|
|
||||||
{ runtime: 'deno', server: 'green-tea-deno' },
|
|
||||||
{ runtime: 'bun', server: 'green-tea-bun' },
|
|
||||||
] as const) {
|
|
||||||
if (runtime !== 'node' && !which(runtime)) {
|
|
||||||
log(`skipping ${runtime}: not installed`);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
log(`booting green-tea on ${runtime}`);
|
|
||||||
|
|
||||||
try {
|
|
||||||
const { port, kill } = await spawnServer(server, {}, runtime);
|
|
||||||
|
|
||||||
try {
|
|
||||||
for (const s of SCENARIOS) {
|
|
||||||
const runs = await measure(port, s.path, s.method, s.body);
|
|
||||||
runtimes.push({ runtime, scenario: s.title, reqSec: aggregate(runs.map((r) => r.reqSec)).median });
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
await kill();
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
// A runtime that cannot boot the built bundle is worth reporting, not worth losing the rest
|
|
||||||
// of the run over.
|
|
||||||
log(`${runtime} failed to boot: ${(error as Error).message.split('\n')[0]}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const commit = execSync('git rev-parse --short HEAD').toString().trim();
|
const commit = execSync('git rev-parse --short HEAD').toString().trim();
|
||||||
const data: RenderData = {
|
const data: RenderData = {
|
||||||
env: {
|
env: {
|
||||||
@@ -224,15 +160,8 @@ async function main(): Promise<void> {
|
|||||||
scenarios: scenarioBlocks,
|
scenarios: scenarioBlocks,
|
||||||
stepScaling,
|
stepScaling,
|
||||||
secureCost,
|
secureCost,
|
||||||
runtimes,
|
|
||||||
};
|
};
|
||||||
// Everything below the marker is written by hand and survives a re-run. The generated tables
|
writeFileSync('BENCHMARKS.md', renderMarkdown(data));
|
||||||
// answer "how fast is it today"; the notes below them carry what a table cannot — which release
|
|
||||||
// moved a number, and what the move bought. Regenerating and silently deleting that is how the
|
|
||||||
// history this file exists to keep gets lost a second time.
|
|
||||||
const previous = existsSync('BENCHMARKS.md') ? readFileSync('BENCHMARKS.md', 'utf8') : '';
|
|
||||||
const kept = previous.includes(KEEP_BELOW) ? previous.slice(previous.indexOf(KEEP_BELOW)) : '';
|
|
||||||
writeFileSync('BENCHMARKS.md', renderMarkdown(data) + (kept ? `\n${kept}` : ''));
|
|
||||||
writeFileSync('bench/results.json', JSON.stringify(data, null, 2));
|
writeFileSync('bench/results.json', JSON.stringify(data, null, 2));
|
||||||
log('wrote BENCHMARKS.md + bench/results.json');
|
log('wrote BENCHMARKS.md + bench/results.json');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,61 +0,0 @@
|
|||||||
// A/B bench server. Identical file dropped into both trees, so each side compiles against its own
|
|
||||||
// `src/`. Adds the two paths the standard bench server does not exercise and this release changed:
|
|
||||||
// secure-by-default headers, and a `cors.origins` predicate.
|
|
||||||
import 'reflect-metadata';
|
|
||||||
import { createApp, Step, Route, Get, Post, Module, needs, param, body } from '../../dist/index.mjs';
|
|
||||||
|
|
||||||
const emailSchema = {
|
|
||||||
'~standard': { version: 1 as const, vendor: 'bench', validate: (v: any) =>
|
|
||||||
(v && typeof v.email === 'string' && v.email.includes('@')) ? { value: v } : { issues: [{ message: 'invalid email' }] } },
|
|
||||||
};
|
|
||||||
|
|
||||||
function makeStep(n: number) {
|
|
||||||
@Step({ provides: `s${n}`, needs: n > 1 ? [`s${n - 1}`] : [] })
|
|
||||||
class S { run() { return { [`s${n}`]: n }; } }
|
|
||||||
return S;
|
|
||||||
}
|
|
||||||
const steps = [1, 2, 3, 4, 5].map(makeStep);
|
|
||||||
|
|
||||||
@Route('/')
|
|
||||||
class Bench {
|
|
||||||
@Get('/hello') hello() { return { hello: 'world' }; }
|
|
||||||
@Get('/users/:id') user(@param('id') id: string) { return { id }; }
|
|
||||||
@Get('/pipeline') pipeline(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
|
|
||||||
@Post('/validate') validate(@body(emailSchema) b: any) { return { email: b.email }; }
|
|
||||||
@Get('/steps/5') steps5(@needs('s5') s5: number) { return { hello: 'world', s5 }; }
|
|
||||||
// Reads the counter without resetting it — the read itself carries no Origin, so it cannot
|
|
||||||
// change what it reports.
|
|
||||||
@Get('/cors-calls') corsCalls() { return { calls: corsCalls }; }
|
|
||||||
}
|
|
||||||
|
|
||||||
@Module({ mountpoint: '/', steps, controllers: [Bench] })
|
|
||||||
class BenchModule {}
|
|
||||||
|
|
||||||
// A predicate rather than a list: that is the shape `cors.origins` takes a function for, and the
|
|
||||||
// one this release stopped evaluating two and three times per request.
|
|
||||||
const ALLOWED = new Set(['http://bench.example']);
|
|
||||||
let corsCalls = 0;
|
|
||||||
const cors =
|
|
||||||
process.env.GT_CORS === '1'
|
|
||||||
? {
|
|
||||||
origins: (o: string) => {
|
|
||||||
corsCalls++;
|
|
||||||
return ALLOWED.has(o);
|
|
||||||
},
|
|
||||||
}
|
|
||||||
: undefined;
|
|
||||||
|
|
||||||
const app = createApp({
|
|
||||||
modules: [BenchModule],
|
|
||||||
security: process.env.GT_SECURE === '1',
|
|
||||||
...(cors ? { cors } : {}),
|
|
||||||
});
|
|
||||||
|
|
||||||
async function main() {
|
|
||||||
try { if (app.inspect('/hello').length === 0) throw new Error('empty'); }
|
|
||||||
catch { console.error('DECORATORS_NOT_APPLIED'); process.exit(1); }
|
|
||||||
const server = await app.listen(0);
|
|
||||||
server.keepAliveTimeout = 5000;
|
|
||||||
console.log(`READY ${(server.address() as any).port}`);
|
|
||||||
}
|
|
||||||
main().catch((e) => { console.error(e); process.exit(1); });
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
// A/B bench server. Identical file dropped into both trees, so each side compiles against its own
|
|
||||||
// `src/`. Adds the two paths the standard bench server does not exercise and this release changed:
|
|
||||||
// secure-by-default headers, and a `cors.origins` predicate.
|
|
||||||
import 'reflect-metadata';
|
|
||||||
import { createApp, Step, Route, Get, Post, Module, needs, param, body } from '../../src/index';
|
|
||||||
|
|
||||||
type Ctor = new (...args: any[]) => any;
|
|
||||||
|
|
||||||
const emailSchema = {
|
|
||||||
'~standard': { version: 1 as const, vendor: 'bench', validate: (v: any) =>
|
|
||||||
(v && typeof v.email === 'string' && v.email.includes('@')) ? { value: v } : { issues: [{ message: 'invalid email' }] } },
|
|
||||||
};
|
|
||||||
|
|
||||||
function makeStep(n: number) {
|
|
||||||
@Step({ provides: `s${n}`, needs: n > 1 ? [`s${n - 1}`] : [] })
|
|
||||||
class S { run() { return { [`s${n}`]: n }; } }
|
|
||||||
return S;
|
|
||||||
}
|
|
||||||
const steps = [1, 2, 3, 4, 5].map(makeStep);
|
|
||||||
|
|
||||||
@Route('/')
|
|
||||||
class Bench {
|
|
||||||
@Get('/hello') hello() { return { hello: 'world' }; }
|
|
||||||
@Get('/users/:id') user(@param('id') id: string) { return { id }; }
|
|
||||||
@Get('/pipeline') pipeline(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
|
|
||||||
@Post('/validate') validate(@body(emailSchema) b: any) { return { email: b.email }; }
|
|
||||||
@Get('/steps/5') steps5(@needs('s5') s5: number) { return { hello: 'world', s5 }; }
|
|
||||||
// Reads the counter without resetting it — the read itself carries no Origin, so it cannot
|
|
||||||
// change what it reports.
|
|
||||||
@Get('/cors-calls') corsCalls() { return { calls: corsCalls }; }
|
|
||||||
}
|
|
||||||
|
|
||||||
// Filler routes, so the width of the route table becomes a dimension the harness can see.
|
|
||||||
//
|
|
||||||
// Every matcher cost discussed for this file — the specificity scan, the per-candidate
|
|
||||||
// `decodeURIComponent`, the per-request `compilePattern` lookups — scales with how many candidate
|
|
||||||
// routes a request has to walk past. At the six routes the cross-framework table uses, all of them
|
|
||||||
// measure as noise, which says nothing about them and everything about the instrument. `/users/:id`
|
|
||||||
// is declared last so a request for it pays the full scan.
|
|
||||||
function fillerRoutes(count: number): Ctor[] {
|
|
||||||
return Array.from({ length: count }, (_, i) => {
|
|
||||||
@Route(`/filler${i}`)
|
|
||||||
class Filler {
|
|
||||||
@Get('/:a/:b') ab(@param('a') a: string) {
|
|
||||||
return { a };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return Filler as Ctor;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const EXTRA = Number(process.env.GT_ROUTES ?? 0);
|
|
||||||
|
|
||||||
@Module({ mountpoint: '/', steps, controllers: [...fillerRoutes(EXTRA), Bench] })
|
|
||||||
class BenchModule {}
|
|
||||||
|
|
||||||
// A predicate rather than a list: that is the shape `cors.origins` takes a function for, and the
|
|
||||||
// one this release stopped evaluating two and three times per request.
|
|
||||||
const ALLOWED = new Set(['http://bench.example']);
|
|
||||||
let corsCalls = 0;
|
|
||||||
const cors =
|
|
||||||
process.env.GT_CORS === '1'
|
|
||||||
? {
|
|
||||||
origins: (o: string) => {
|
|
||||||
corsCalls++;
|
|
||||||
return ALLOWED.has(o);
|
|
||||||
},
|
|
||||||
}
|
|
||||||
: undefined;
|
|
||||||
|
|
||||||
const app = createApp({
|
|
||||||
modules: [BenchModule],
|
|
||||||
security: process.env.GT_SECURE === '1',
|
|
||||||
...(cors ? { cors } : {}),
|
|
||||||
});
|
|
||||||
|
|
||||||
async function main() {
|
|
||||||
try { if (app.inspect('/hello').length === 0) throw new Error('empty'); }
|
|
||||||
catch { console.error('DECORATORS_NOT_APPLIED'); process.exit(1); }
|
|
||||||
const server = await app.listen(0);
|
|
||||||
server.keepAliveTimeout = 5000;
|
|
||||||
console.log(`READY ${(server.address() as any).port}`);
|
|
||||||
}
|
|
||||||
main().catch((e) => { console.error(e); process.exit(1); });
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
import 'reflect-metadata';
|
|
||||||
import { createApp, Step, Route, Get, Post, Module, needs, param, body } from '../../dist/index.mjs';
|
|
||||||
|
|
||||||
|
|
||||||
// Same BenchModule as green-tea.ts, but loaded from `dist/` rather than `src/`.
|
|
||||||
//
|
|
||||||
// The runtimes table exists to vary the runtime. The Deno and Bun servers import the built bundle
|
|
||||||
// because that is the only form those runtimes can load here, so a Node row reading `src/` through
|
|
||||||
// tsx would vary the load form at the same time and the table would answer neither question.
|
|
||||||
const emailSchema = {
|
|
||||||
'~standard': { version: 1 as const, vendor: 'bench', validate: (v: any) =>
|
|
||||||
(v && typeof v.email === 'string' && v.email.includes('@')) ? { value: v } : { issues: [{ message: 'invalid email' }] } },
|
|
||||||
};
|
|
||||||
|
|
||||||
function makeStep(n: number) {
|
|
||||||
@Step({ provides: `s${n}`, needs: n > 1 ? [`s${n - 1}`] : [] })
|
|
||||||
class S { run() { return { [`s${n}`]: n }; } }
|
|
||||||
return S;
|
|
||||||
}
|
|
||||||
const steps = [1, 2, 3, 4, 5].map(makeStep);
|
|
||||||
|
|
||||||
@Route('/')
|
|
||||||
class Bench {
|
|
||||||
@Get('/hello') hello() { return { hello: 'world' }; }
|
|
||||||
@Get('/users/:id') user(@param('id') id: string) { return { id }; }
|
|
||||||
@Get('/pipeline') pipeline(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
|
|
||||||
@Post('/validate') validate(@body(emailSchema) b: any) { return { email: b.email }; }
|
|
||||||
@Get('/steps/0') steps0() { return { hello: 'world' }; }
|
|
||||||
@Get('/steps/3') steps3(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
|
|
||||||
@Get('/steps/5') steps5(@needs('s5') s5: number) { return { hello: 'world', s5 }; }
|
|
||||||
}
|
|
||||||
|
|
||||||
@Module({ mountpoint: '/', steps, controllers: [Bench] })
|
|
||||||
class BenchModule {}
|
|
||||||
|
|
||||||
const app = createApp({ modules: [BenchModule], security: false });
|
|
||||||
|
|
||||||
async function main(): Promise<void> {
|
|
||||||
const server = await app.listen(0);
|
|
||||||
server.keepAliveTimeout = 5000; // parity value (all servers use 5000)
|
|
||||||
console.log(`READY ${(server.address() as { port: number }).port}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
main().catch((e) => {
|
|
||||||
console.error(e);
|
|
||||||
process.exit(1);
|
|
||||||
});
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@green-tea/core",
|
"name": "@green-tea/core",
|
||||||
"version": "26.9.0-beta.1",
|
"version": "26.8.0-beta.1",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
// JSR serves TypeScript source, not the tsup build, so these point at `src/` where npm's
|
// JSR serves TypeScript source, not the tsup build, so these point at `src/` where npm's
|
||||||
// `exports` point at `dist/`. Same four entry points on purpose: a docs example that imports
|
// `exports` point at `dist/`. Same four entry points on purpose: a docs example that imports
|
||||||
|
|||||||
+1
-2
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@green-tea/core",
|
"name": "@green-tea/core",
|
||||||
"version": "26.9.0-beta.1",
|
"version": "26.8.0-beta.1",
|
||||||
"description": "A zen, opinionated, type-safe framework \u2014 your API is a graph, not a middleware chain.",
|
"description": "A zen, opinionated, type-safe framework \u2014 your API is a graph, not a middleware chain.",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"author": "green-tea contributors <projects@expressive-tea.io>",
|
"author": "green-tea contributors <projects@expressive-tea.io>",
|
||||||
@@ -102,7 +102,6 @@
|
|||||||
"complexity:check": "node scripts/check-complexity.mjs",
|
"complexity:check": "node scripts/check-complexity.mjs",
|
||||||
"complexity:cyclomatic": "cyclomatic-complexity \"src/**/*.ts\" -tw 15 -te 25",
|
"complexity:cyclomatic": "cyclomatic-complexity \"src/**/*.ts\" -tw 15 -te 25",
|
||||||
"bench": "tsx bench/run.ts",
|
"bench": "tsx bench/run.ts",
|
||||||
"bench:compare": "tsx bench/compare.ts",
|
|
||||||
"prepublishOnly": "npm run lint && npm run complexity:check && npm run typecheck && npm test && npm run build",
|
"prepublishOnly": "npm run lint && npm run complexity:check && npm run typecheck && npm test && npm run build",
|
||||||
"prepare": "git config core.hooksPath .githooks || true"
|
"prepare": "git config core.hooksPath .githooks || true"
|
||||||
},
|
},
|
||||||
|
|||||||
+40
-120
@@ -1,8 +1,8 @@
|
|||||||
import type http from 'http';
|
import type http from 'http';
|
||||||
import { Bus, type Events } from '../bus';
|
import { Bus } from '../bus';
|
||||||
import { createDefaultLogger, logRequests, type Logger } from '../logger';
|
import { createDefaultLogger, logRequests, type Logger } from '../logger';
|
||||||
import { Container } from '../container';
|
import { Container } from '../container';
|
||||||
import { topoSort, topoLevels, subgraphFor, GraphNode, nearest } from '../graph';
|
import { topoSort, subgraphFor, GraphNode, nearest } from '../graph';
|
||||||
import { toMermaid, toDOT, graphHtml, type GraphView } from '../graph-viz';
|
import { toMermaid, toDOT, graphHtml, type GraphView } from '../graph-viz';
|
||||||
import { runPipeline, runSteps, PipelineStep } from '../pipeline';
|
import { runPipeline, runSteps, PipelineStep } from '../pipeline';
|
||||||
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http';
|
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http';
|
||||||
@@ -62,7 +62,7 @@ interface Registry {
|
|||||||
exportedProviders: string[];
|
exportedProviders: string[];
|
||||||
exportedSteps: string[];
|
exportedSteps: string[];
|
||||||
exportedRoutes: RouteEntry[];
|
exportedRoutes: RouteEntry[];
|
||||||
setRunner(name: string, runner: Runner, framework?: boolean): void;
|
setRunner(name: string, runner: Runner): void;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -86,8 +86,6 @@ interface PipelineDeps {
|
|||||||
planSteps(plan: RoutePlan): PipelineStep[];
|
planSteps(plan: RoutePlan): PipelineStep[];
|
||||||
bus: Bus;
|
bus: Bus;
|
||||||
onError?: ErrorRenderer;
|
onError?: ErrorRenderer;
|
||||||
/** Where a failing `onError` is reported — the renderer's error is not the request's. */
|
|
||||||
logger: Logger;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -210,7 +208,7 @@ export function createApp(opts: {
|
|||||||
const { providerNodes, stepNodes, runners, providerMeta, routePlans } = registry;
|
const { providerNodes, stepNodes, runners, providerMeta, routePlans } = registry;
|
||||||
const teardown = buildTeardownRegistry(opts.hooks, opts.teardownTimeoutMs, opts.shutdownTimeoutMs);
|
const teardown = buildTeardownRegistry(opts.hooks, opts.teardownTimeoutMs, opts.shutdownTimeoutMs);
|
||||||
mountPlugins(opts.plugins, bus, registry, teardown);
|
mountPlugins(opts.plugins, bus, registry, teardown);
|
||||||
provideBuiltins(registry, logger, bus);
|
provideBuiltins(registry, logger);
|
||||||
|
|
||||||
// For each route, resolve which providers/steps feed it via topo order.
|
// For each route, resolve which providers/steps feed it via topo order.
|
||||||
// MVP: every route depends on every declared step + provider in the app graph.
|
// MVP: every route depends on every declared step + provider in the app graph.
|
||||||
@@ -231,7 +229,7 @@ export function createApp(opts: {
|
|||||||
|
|
||||||
const providedSeed = (plan: RoutePlan) => seedProviders(container, plan);
|
const providedSeed = (plan: RoutePlan) => seedProviders(container, plan);
|
||||||
const planSteps = (plan: RoutePlan) => compilePlanSteps(runners, plan);
|
const planSteps = (plan: RoutePlan) => compilePlanSteps(runners, plan);
|
||||||
const pipelineDeps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError, logger };
|
const pipelineDeps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError };
|
||||||
let meshControl: MeshControl | undefined;
|
let meshControl: MeshControl | undefined;
|
||||||
|
|
||||||
// mesh teacup: connect remote teapots and splice their scopes/routes in, then finalize.
|
// mesh teacup: connect remote teapots and splice their scopes/routes in, then finalize.
|
||||||
@@ -308,7 +306,7 @@ export function createApp(opts: {
|
|||||||
};
|
};
|
||||||
const fetchFn = buildAppFetch(
|
const fetchFn = buildAppFetch(
|
||||||
routePlans,
|
routePlans,
|
||||||
{ providedSeed, planSteps, bus, onError: opts.onError, logger },
|
{ providedSeed, planSteps, bus, onError: opts.onError },
|
||||||
fetchOpts,
|
fetchOpts,
|
||||||
bootApp,
|
bootApp,
|
||||||
devRoutes,
|
devRoutes,
|
||||||
@@ -406,12 +404,7 @@ export function createApp(opts: {
|
|||||||
function emptyRegistry(): Registry {
|
function emptyRegistry(): Registry {
|
||||||
const runners = new Map<string, Runner>(); // node name -> runtime fn
|
const runners = new Map<string, Runner>(); // node name -> runtime fn
|
||||||
|
|
||||||
const setRunner = (name: string, runner: Runner, framework = false) => {
|
const setRunner = (name: string, runner: Runner) => {
|
||||||
if (!framework && RESERVED_TOKENS.has(name))
|
|
||||||
throw new Error(
|
|
||||||
`'${name}' is reserved by the framework and cannot be provided by a module, plugin or mesh export — ` +
|
|
||||||
`rename it. The framework's own '${name}' is what '@needs' resolves to.`,
|
|
||||||
);
|
|
||||||
if (runners.has(name))
|
if (runners.has(name))
|
||||||
throw new Error(`duplicate provider/step name '${name}' — names must be unique across modules and plugins`);
|
throw new Error(`duplicate provider/step name '${name}' — names must be unique across modules and plugins`);
|
||||||
runners.set(name, runner);
|
runners.set(name, runner);
|
||||||
@@ -600,46 +593,22 @@ function mountPlugins(plugins: Plugin[] | undefined, bus: Bus, registry: Registr
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Auto-provides a shared {@link Rooms} instance unless the user already declared a `rooms` provider. */
|
/** Auto-provides a shared {@link Rooms} instance unless the user already declared a `rooms` provider. */
|
||||||
/**
|
function provideBuiltins(registry: Registry, logger: Logger): void {
|
||||||
* Token names the framework owns. Declaring one is a boot error, not a silent override.
|
|
||||||
*
|
|
||||||
* Builtins used to be registered with `if (!runners.has(name))`, so a provider called `logger`
|
|
||||||
* quietly replaced the framework's own and every `@needs('logger')` in the app got something else.
|
|
||||||
* That is the kind of thing that is discovered from a log line that never appeared.
|
|
||||||
*
|
|
||||||
* `bus` is reserved without being provided, on purpose. It is not a graph token — putting the `Bus`
|
|
||||||
* itself in the graph would hand `emit` to every node and turn a one-way observation channel into
|
|
||||||
* something anything can forge events on. Reserving the name means `@needs('bus')` can say that,
|
|
||||||
* instead of resolving to whatever a user happened to call `bus` and being wrong in silence.
|
|
||||||
*/
|
|
||||||
const RESERVED_TOKENS = new Set(['logger', 'rooms', 'events', 'bus']);
|
|
||||||
|
|
||||||
function provideBuiltins(registry: Registry, logger: Logger, bus: Bus): void {
|
|
||||||
const builtin = (name: string, value: () => Record<string, unknown>): void => {
|
|
||||||
registry.providerNodes.push({ name, needs: [], provides: [name], origin: 'builtin' });
|
|
||||||
registry.providerMeta.set(name, { optional: false });
|
|
||||||
registry.setRunner(name, value, true);
|
|
||||||
};
|
|
||||||
|
|
||||||
// `logger` is registered as an ordinary provider *in addition to* being framework infrastructure,
|
// `logger` is registered as an ordinary provider *in addition to* being framework infrastructure,
|
||||||
// so a step or handler reaches it with `@needs('logger')` like any other dependency. It is the
|
// so a step or handler reaches it with `@needs('logger')` like any other dependency. It is the
|
||||||
// same object createApp holds, not a second one — core cannot depend on the graph for something
|
// same object createApp holds, not a second one — core cannot depend on the graph for something
|
||||||
// it must use while the graph is still resolving.
|
// it must use while the graph is still resolving.
|
||||||
builtin('logger', () => ({ logger }));
|
if (!registry.runners.has('logger')) {
|
||||||
|
registry.providerNodes.push({ name: 'logger', needs: [], provides: ['logger'], origin: 'builtin' });
|
||||||
|
registry.providerMeta.set('logger', { optional: false });
|
||||||
|
registry.setRunner('logger', () => ({ logger }));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (registry.runners.has('rooms')) return;
|
||||||
const roomsInstance = new Rooms();
|
const roomsInstance = new Rooms();
|
||||||
builtin('rooms', () => ({ rooms: roomsInstance }));
|
registry.providerNodes.push({ name: 'rooms', needs: [], provides: ['rooms'], origin: 'builtin' });
|
||||||
|
registry.providerMeta.set('rooms', { optional: false });
|
||||||
// The read-only half of the bus, and only the read-only half: `on`, never `emit`. The same
|
registry.setRunner('rooms', () => ({ rooms: roomsInstance })); // merge object -> ctx.rooms
|
||||||
// narrowing a plugin gets, for the same reason — an observation channel anything can write to is
|
|
||||||
// not one.
|
|
||||||
//
|
|
||||||
// A subscription is not like the other injectables, and the difference is the scope that reaches
|
|
||||||
// it. A `@Provider` runs once, so subscribing there is fine; a `@Step` runs *per request*, and a
|
|
||||||
// step that calls `on()` registers a listener on every one of them. `on()` returns its own
|
|
||||||
// unsubscribe for the provider that wants to clean up in `dispose()` — but a plugin, which gets
|
|
||||||
// `on` and `onShutdown` together, remains the right home for observation.
|
|
||||||
builtin('events', () => ({ events: { on: bus.on.bind(bus) } satisfies Events }));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Boot-time nudge: a route whose need-closure pulls this many steps is almost always a modeling
|
// Boot-time nudge: a route whose need-closure pulls this many steps is almost always a modeling
|
||||||
@@ -697,21 +666,6 @@ function assertNeedsSatisfiable(routePlans: RoutePlan[], providerNodes: GraphNod
|
|||||||
for (const plan of routePlans) {
|
for (const plan of routePlans) {
|
||||||
for (const need of plan.needs) {
|
for (const need of plan.needs) {
|
||||||
if (allowed.has(need)) continue;
|
if (allowed.has(need)) continue;
|
||||||
|
|
||||||
// The generic message plus a nearest-match is right for a typo and useless here: nothing is
|
|
||||||
// spelled nearly enough like `bus` to suggest, and the reader's mistake is not a typo but a
|
|
||||||
// reasonable guess about the shape. `@needs('logger')` teaches that framework things are
|
|
||||||
// graph tokens, so `@needs('bus')` is the next instinct — and the boot error is the first
|
|
||||||
// news that it is not the same shape. Say why, where they are.
|
|
||||||
if (need === 'bus') {
|
|
||||||
throw new Error(
|
|
||||||
`handler '${plan.handlerName}' needs 'bus' — the Bus is not a graph token, because a node ` +
|
|
||||||
`that could reach it could also emit, and an observation channel anything can write to ` +
|
|
||||||
`is not one. Use @needs('events') for the read-only half ({ on }), or write a plugin, ` +
|
|
||||||
`which gets on() and onShutdown() together and is the right home for observation.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const hint = nearest(need, allowed);
|
const hint = nearest(need, allowed);
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`handler '${plan.handlerName}' needs '${need}' but nothing (local or mesh) provides it${hint ? ` — did you mean '${hint}'?` : ''}`,
|
`handler '${plan.handlerName}' needs '${need}' but nothing (local or mesh) provides it${hint ? ` — did you mean '${hint}'?` : ''}`,
|
||||||
@@ -937,41 +891,8 @@ function applyOverrides(overrides: Record<string, unknown> | undefined, registry
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** What a provider's boot produced: nothing to say, or the error it failed with. */
|
|
||||||
interface BootOutcome {
|
|
||||||
node: GraphNode;
|
|
||||||
error?: Error;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Boots one provider and registers its value. Never rejects — the caller decides what a failure means. */
|
|
||||||
async function bootProvider(
|
|
||||||
node: GraphNode,
|
|
||||||
deps: { runners: Map<string, Runner>; container: Container; bus: Bus },
|
|
||||||
): Promise<BootOutcome> {
|
|
||||||
const { runners, container, bus } = deps;
|
|
||||||
bus.emit('boot:provider:start', { name: node.name, scope: node.origin });
|
|
||||||
|
|
||||||
try {
|
|
||||||
const value = await runners.get(node.name)!(await snapshot(container, node.needs));
|
|
||||||
container.register(node.name, 'app', () => value);
|
|
||||||
await container.resolve(node.name); // warm the cache
|
|
||||||
bus.emit('boot:provider:ok', { name: node.name });
|
|
||||||
return { node };
|
|
||||||
} catch (error) {
|
|
||||||
bus.emit('boot:provider:fail', { name: node.name, error });
|
|
||||||
return { node, error: error as Error };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Runs app-scoped providers level by level — concurrently within a level, sequentially between
|
* Runs app-scoped providers in topo order, caching each result; required failures abort, optional ones warn.
|
||||||
* them; required failures abort, optional ones warn.
|
|
||||||
*
|
|
||||||
* The topo sort already proved nothing in a level can order anything else in it, so serializing a
|
|
||||||
* level only ever bought latency: an app paid the sum of its providers' boot times instead of its
|
|
||||||
* longest chain. Concurrency is the second thing the graph earns its users, after pruning, and the
|
|
||||||
* one a middleware chain structurally cannot offer.
|
|
||||||
*
|
|
||||||
* @returns The names of optional providers that failed and are running degraded (unregistered).
|
* @returns The names of optional providers that failed and are running degraded (unregistered).
|
||||||
*/
|
*/
|
||||||
async function bootProviders(
|
async function bootProviders(
|
||||||
@@ -986,39 +907,40 @@ async function bootProviders(
|
|||||||
logger: Logger;
|
logger: Logger;
|
||||||
},
|
},
|
||||||
): Promise<string[]> {
|
): Promise<string[]> {
|
||||||
const { providerMeta, providerInstances, teardown, logger } = deps;
|
const { runners, container, providerMeta, providerInstances, teardown, bus, logger } = deps;
|
||||||
const degraded: string[] = [];
|
const degraded: string[] = [];
|
||||||
|
|
||||||
for (const level of topoLevels(orderedProviders)) {
|
for (const node of orderedProviders) {
|
||||||
// Outcomes rather than rejections: a sibling that throws must not strand the ones that
|
bus.emit('boot:provider:start', { name: node.name, scope: node.origin });
|
||||||
// succeeded, or a provider that opened a pool would never get its dispose() registered.
|
|
||||||
const outcomes = await Promise.all(level.map((node) => bootProvider(node, deps)));
|
|
||||||
|
|
||||||
// Teardown in level order, not completion order. `orderedProviders` is topologically sorted and
|
try {
|
||||||
// the registry runs in reverse, which is what gives dependants teardown before their
|
const value = await runners.get(node.name)!(await snapshot(container, node.needs));
|
||||||
// dependencies for free — a guarantee that would have become luck if this followed whichever
|
container.register(node.name, 'app', () => value);
|
||||||
// provider happened to settle first. Registered before the failure pass so a level that aborts
|
await container.resolve(node.name); // warm the cache
|
||||||
// the boot still leaves its successful siblings closeable.
|
// Registered here, as it boots, rather than where it was collected. `orderedProviders` is
|
||||||
|
// topologically sorted, so registration order *is* boot order — and the registry running in
|
||||||
|
// reverse then gives dependants teardown before their dependencies for free, with no second
|
||||||
|
// sort to keep in step with this one.
|
||||||
//
|
//
|
||||||
// Skipped for a failure on purpose: a provider that threw never provided anything, and calling
|
// Inside the try on purpose: a provider that threw never provided anything, and calling
|
||||||
// dispose() on a half-constructed one is how a teardown finds a null connection.
|
// dispose() on a half-constructed one is how a teardown finds a null connection.
|
||||||
for (const { node, error } of outcomes) {
|
|
||||||
if (error) continue;
|
|
||||||
const instance = providerInstances.get(node.name);
|
const instance = providerInstances.get(node.name);
|
||||||
if (instance?.dispose) teardown.add(() => instance.dispose!());
|
if (instance?.dispose) teardown.add(() => instance.dispose!());
|
||||||
}
|
bus.emit('boot:provider:ok', { name: node.name });
|
||||||
|
} catch (error) {
|
||||||
for (const { node, error } of outcomes) {
|
bus.emit('boot:provider:fail', { name: node.name, error });
|
||||||
if (!error) continue;
|
|
||||||
|
|
||||||
if (!providerMeta.get(node.name)?.optional) {
|
if (!providerMeta.get(node.name)?.optional) {
|
||||||
throw new Error(`provider '${node.name}' failed: ${error.message}`);
|
throw new Error(`provider '${node.name}' failed: ${(error as Error).message}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// optional: warn, leave it unregistered; routes needing it fail at request time
|
// optional: warn, leave it unregistered; routes needing it fail at request time
|
||||||
// ponytail: full partial-degradation is out of scope (spec §10); warn is enough here
|
// ponytail: full partial-degradation is out of scope (spec §10); warn is enough here
|
||||||
degraded.push(node.name);
|
degraded.push(node.name);
|
||||||
logger.warn(`optional provider '${node.name}' failed: ${error.message}`, { provider: node.name, error });
|
logger.warn(`optional provider '${node.name}' failed: ${(error as Error).message}`, {
|
||||||
|
provider: node.name,
|
||||||
|
error,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1084,7 +1006,7 @@ function buildMeshControl(
|
|||||||
|
|
||||||
if (!mesh?.secret || !hasExports) return undefined;
|
if (!mesh?.secret || !hasExports) return undefined;
|
||||||
const { container, orderedProviders, orderedSteps } = deps;
|
const { container, orderedProviders, orderedSteps } = deps;
|
||||||
const { bus, providedSeed, planSteps, onError, logger } = deps.deps;
|
const { bus, providedSeed, planSteps, onError } = deps.deps;
|
||||||
const manifest = buildManifest({ providers: exportedProviders, steps: exportedSteps, routes: exportedRoutes });
|
const manifest = buildManifest({ providers: exportedProviders, steps: exportedSteps, routes: exportedRoutes });
|
||||||
|
|
||||||
const resolveScope = async (name: string, env: RequestEnvelope): Promise<unknown> => {
|
const resolveScope = async (name: string, env: RequestEnvelope): Promise<unknown> => {
|
||||||
@@ -1123,7 +1045,6 @@ function buildMeshControl(
|
|||||||
transformer: plan.transformer,
|
transformer: plan.transformer,
|
||||||
bus,
|
bus,
|
||||||
onError,
|
onError,
|
||||||
logger,
|
|
||||||
transport: plan.transport,
|
transport: plan.transport,
|
||||||
correlation: {
|
correlation: {
|
||||||
requestId: env.correlation?.requestId,
|
requestId: env.correlation?.requestId,
|
||||||
@@ -1149,7 +1070,7 @@ function buildMeshControl(
|
|||||||
|
|
||||||
/** Compiles every non-ws route plan into an HTTP route that seeds and runs the pipeline, plus any remote routes. */
|
/** Compiles every non-ws route plan into an HTTP route that seeds and runs the pipeline, plus any remote routes. */
|
||||||
function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps: PipelineDeps): RouteDef[] {
|
function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps: PipelineDeps): RouteDef[] {
|
||||||
const { providedSeed, planSteps, bus, onError, logger } = deps;
|
const { providedSeed, planSteps, bus, onError } = deps;
|
||||||
|
|
||||||
const local = routePlans
|
const local = routePlans
|
||||||
.filter((plan) => plan.transport !== 'ws') // buffer | sse | ndjson | negotiate
|
.filter((plan) => plan.transport !== 'ws') // buffer | sse | ndjson | negotiate
|
||||||
@@ -1168,7 +1089,6 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps
|
|||||||
transformer: plan.transformer,
|
transformer: plan.transformer,
|
||||||
bus,
|
bus,
|
||||||
onError,
|
onError,
|
||||||
logger,
|
|
||||||
transport: plan.transport,
|
transport: plan.transport,
|
||||||
// `route` is the pattern, never req.url — a metrics consumer labelling on concrete
|
// `route` is the pattern, never req.url — a metrics consumer labelling on concrete
|
||||||
// paths gets one label per distinct URL, and that takes down the metrics backend.
|
// paths gets one label per distinct URL, and that takes down the metrics backend.
|
||||||
|
|||||||
+3
-98
@@ -1,28 +1,4 @@
|
|||||||
/**
|
/** Names of every lifecycle event the framework emits over the {@link Bus}. */
|
||||||
* Names of every lifecycle event the framework emits over the {@link Bus}.
|
|
||||||
*
|
|
||||||
* ### The request pair is a guarantee
|
|
||||||
*
|
|
||||||
* **Every `request:end` is preceded by a `request:start` carrying the same `requestId`.** A
|
|
||||||
* consumer may open per-request state on the first and close it on the second without checking
|
|
||||||
* whether the request got as far as a route — a shed `503` emits the pair as surely as a `200`
|
|
||||||
* does.
|
|
||||||
*
|
|
||||||
* This is a promise to emitters as much as to subscribers: a terminal path that emits one must
|
|
||||||
* emit the other, in that order. It held by accident until `maxConcurrentRequests` added the first
|
|
||||||
* terminal path that does not reach the router, and `test/lifecycle-pairing.test.ts` enumerates
|
|
||||||
* every response shape so that the next one cannot break it quietly. The alternative — documenting
|
|
||||||
* `request:end` as standalone — was rejected because it makes the obvious consumer wrong: an
|
|
||||||
* in-flight gauge counting `start` up and `end` down would drift negative under shedding, which is
|
|
||||||
* exactly when an operator is reading it.
|
|
||||||
*
|
|
||||||
* ### `request:end` is terminal and universal; the others are additional
|
|
||||||
*
|
|
||||||
* `request:end` fires for every dispatched request — handled, thrown and unmatched alike — and is
|
|
||||||
* the only one of these carrying the real status. **Count it, and nothing else.**
|
|
||||||
* `request:failed` and `route:unmatched` describe the *same* request and fire in addition to it, so
|
|
||||||
* a consumer that counts them as separate outcomes counts one request twice. See `EventPayload`.
|
|
||||||
*/
|
|
||||||
export type LifecycleEvent =
|
export type LifecycleEvent =
|
||||||
| 'boot:provider:start'
|
| 'boot:provider:start'
|
||||||
| 'boot:provider:ok'
|
| 'boot:provider:ok'
|
||||||
@@ -30,11 +6,6 @@ export type LifecycleEvent =
|
|||||||
| 'request:step:enter'
|
| 'request:step:enter'
|
||||||
| 'request:step:leave'
|
| 'request:step:leave'
|
||||||
| 'request:step:error'
|
| 'request:step:error'
|
||||||
// A streaming connection — SSE, NDJSON or a WebSocket — from established to gone. Deliberately
|
|
||||||
// *not* the request span: a route returning an `AsyncIterable` is done in milliseconds while its
|
|
||||||
// connection may live for hours, so `request:end` fires at the handler's return and these three
|
|
||||||
// describe what outlives it. They carry the opening request's `requestId` and `traceId`, which is
|
|
||||||
// what lets a consumer join the two rather than watch them as unrelated streams of events.
|
|
||||||
| 'stream:open'
|
| 'stream:open'
|
||||||
| 'stream:close'
|
| 'stream:close'
|
||||||
| 'stream:error'
|
| 'stream:error'
|
||||||
@@ -46,18 +17,12 @@ export type LifecycleEvent =
|
|||||||
// came up, and a deploy watching for trouble wants to tell those apart.
|
// came up, and a deploy watching for trouble wants to tell those apart.
|
||||||
| 'mesh:boot:retry'
|
| 'mesh:boot:retry'
|
||||||
| 'plugin:mounted'
|
| 'plugin:mounted'
|
||||||
// Paired: see the guarantee above. `request:start` has no status and no duration — it says a
|
|
||||||
// request arrived, not that it routed.
|
|
||||||
| 'request:start'
|
| 'request:start'
|
||||||
| 'request:end'
|
| 'request:end'
|
||||||
// "handler code threw", and *additional* to the `request:end` that follows it — a rendered 422 is
|
|
||||||
// also a throw, which is a thing a status alone cannot express.
|
|
||||||
| 'request:failed'
|
| 'request:failed'
|
||||||
| 'route:matched'
|
| 'route:matched'
|
||||||
// Covers a 404 *and* a 405 — the report's `route.not_found` names one outcome and would
|
// Covers a 404 *and* a 405 — the report's `route.not_found` names one outcome and would
|
||||||
// misreport the other, and "no route ran" is the fact a consumer actually wants. It is also not
|
// misreport the other, and "no route ran" is the fact a consumer actually wants.
|
||||||
// a synonym for "the request failed": a static file served from `createApp({ static })` matched
|
|
||||||
// no route either, and answers 200. Read the status from the `request:end` that follows.
|
|
||||||
| 'route:unmatched';
|
| 'route:unmatched';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -66,39 +31,8 @@ export type LifecycleEvent =
|
|||||||
*
|
*
|
||||||
* Everything past `name` is optional and stays that way. Boot and mesh events have no request to
|
* Everything past `name` is optional and stays that way. Boot and mesh events have no request to
|
||||||
* name, and requiring a shape they cannot fill would only mean inventing values for it.
|
* name, and requiring a shape they cannot fill would only mean inventing values for it.
|
||||||
*
|
|
||||||
* ### One failed request produces three events
|
|
||||||
*
|
|
||||||
* A single request that throws emits `request:start`, then `request:failed`, then `request:end`.
|
|
||||||
* All three carry the same `requestId`, and the first implementation anyone writes counts the
|
|
||||||
* failure twice — once from `request:failed` and once from the `request:end` that follows it,
|
|
||||||
* under whatever status it invents for the one that had none. `route:unmatched` overlaps the same
|
|
||||||
* way: it fires *in addition to* the `request:end` that follows, so a 404 is two events and one
|
|
||||||
* outcome.
|
|
||||||
*
|
|
||||||
* The division of labour, which is the thing to build against:
|
|
||||||
*
|
|
||||||
* - **`request:end`** — terminal, universal, and the only one carrying the status the client
|
|
||||||
* received. This is the request counter and the latency histogram.
|
|
||||||
* - **`request:failed`** — *handler code threw*, which no status can express on its own: a
|
|
||||||
* rendered `422` is also a throw. This is a separate error counter, not a second request
|
|
||||||
* counter.
|
|
||||||
* - **`route:unmatched`** — *no route ran*, covering 404 and 405 alike. Also additional.
|
|
||||||
*
|
|
||||||
* `logRequests` gets this right and is worth reading as a reference (`src/logger.ts`): it takes
|
|
||||||
* the outcome from `request:end` and only the message from `request:failed`.
|
|
||||||
*/
|
*/
|
||||||
export interface EventPayload {
|
export interface EventPayload {
|
||||||
/**
|
|
||||||
* What the event is about, for a human reading a log line.
|
|
||||||
*
|
|
||||||
* **Never use this as a metric label.** On the request events it is caller-controlled: for a
|
|
||||||
* matched request it is the route pattern, but on `request:start` and `route:unmatched` it is
|
|
||||||
* built from the path that arrived. A matched path is bounded by the route table; an unmatched
|
|
||||||
* one is bounded by nothing at all, and a scanner walking `/aaa`, `/aab`, `/aac` becomes one
|
|
||||||
* label per distinct URL — a memory leak with a metrics backend attached. Label on {@link route},
|
|
||||||
* which is bounded by construction.
|
|
||||||
*/
|
|
||||||
name: string;
|
name: string;
|
||||||
scope?: string;
|
scope?: string;
|
||||||
error?: unknown;
|
error?: unknown;
|
||||||
@@ -107,23 +41,10 @@ export interface EventPayload {
|
|||||||
requestId?: string;
|
requestId?: string;
|
||||||
/** A `traceparent` header carried verbatim. Core parses nothing — that is the exporter's job. */
|
/** A `traceparent` header carried verbatim. Core parses nothing — that is the exporter's job. */
|
||||||
traceId?: string;
|
traceId?: string;
|
||||||
/**
|
/** The matched *pattern* (`/users/:id`), never the concrete path — see {@link Correlation}. */
|
||||||
* The matched *pattern* (`/users/:id`), never the concrete path — see {@link Correlation}.
|
|
||||||
*
|
|
||||||
* Bounded by the route table, which is what makes it the field to label a metric on. When nothing
|
|
||||||
* matched it is `'<unmatched>'` rather than absent, on `route:unmatched` and on the `request:end`
|
|
||||||
* that follows it: a single series for every path that was never a route, instead of a fallback
|
|
||||||
* each consumer invents and some get wrong. It cannot collide with a real pattern, which always
|
|
||||||
* starts with `/`.
|
|
||||||
*/
|
|
||||||
route?: string;
|
route?: string;
|
||||||
method?: string;
|
method?: string;
|
||||||
transport?: string;
|
transport?: string;
|
||||||
/**
|
|
||||||
* The status the client received. Present on `request:end` always, and on `request:failed`
|
|
||||||
* except when a custom `onError` renderer threw while producing it — the one case where the
|
|
||||||
* framework does not know what was sent, and will not guess.
|
|
||||||
*/
|
|
||||||
status?: number;
|
status?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -137,22 +58,6 @@ export interface EventPayload {
|
|||||||
*/
|
*/
|
||||||
export type Correlation = Pick<EventPayload, 'requestId' | 'traceId' | 'route' | 'method' | 'transport'>;
|
export type Correlation = Pick<EventPayload, 'requestId' | 'traceId' | 'route' | 'method' | 'transport'>;
|
||||||
|
|
||||||
/**
|
|
||||||
* The read-only half of the {@link Bus}, as `@needs('events')` hands it over.
|
|
||||||
*
|
|
||||||
* `on` and deliberately not `emit`: a channel anything can write to is not an observation channel,
|
|
||||||
* and the framework's own events would stop being trustworthy the moment a node could forge one.
|
|
||||||
* Plugins get exactly this same narrowing.
|
|
||||||
*
|
|
||||||
* `on` returns its own unsubscribe. Use it — a `@Provider` that subscribes should release in
|
|
||||||
* `dispose()`, and a `@Step` should not subscribe at all, since it runs once per request and would
|
|
||||||
* add a listener each time. A plugin, which gets `on` and `onShutdown` together, is the home this
|
|
||||||
* token exists to point at rather than replace.
|
|
||||||
*/
|
|
||||||
export interface Events {
|
|
||||||
on: Bus['on'];
|
|
||||||
}
|
|
||||||
|
|
||||||
/** In-process pub/sub for framework lifecycle events; observer failures are swallowed so they never break the pipeline. */
|
/** In-process pub/sub for framework lifecycle events; observer failures are swallowed so they never break the pipeline. */
|
||||||
export class Bus {
|
export class Bus {
|
||||||
private readonly listeners = new Map<LifecycleEvent, Set<(p: EventPayload) => void>>();
|
private readonly listeners = new Map<LifecycleEvent, Set<(p: EventPayload) => void>>();
|
||||||
|
|||||||
+2
-100
@@ -11,106 +11,10 @@ export interface StreamEncoder {
|
|||||||
|
|
||||||
const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error));
|
const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error));
|
||||||
|
|
||||||
// Registered globally rather than module-local: this package ships twice — a bundle on npm and raw
|
|
||||||
// source on JSR — so two copies in one dependency tree is a real shape, and a marker that stopped
|
|
||||||
// being recognised across them would silently degrade back to an id-less `data:` frame.
|
|
||||||
const SSE_EVENT = Symbol.for('green-tea.sse-event');
|
|
||||||
|
|
||||||
/** Optional SSE fields carried alongside a payload. See {@link sse}. */
|
|
||||||
export interface SseFields {
|
|
||||||
/**
|
|
||||||
* The event's id, written as `id:`. The browser echoes the last one it saw back as the
|
|
||||||
* `Last-Event-ID` request header when `EventSource` reconnects — read it with
|
|
||||||
* `@header('last-event-id')` and resume from there.
|
|
||||||
*/
|
|
||||||
id?: string;
|
|
||||||
/** Event name, written as `event:`. Dispatched to `addEventListener(name)` instead of `onmessage`. */
|
|
||||||
event?: string;
|
|
||||||
/** Reconnection delay in whole milliseconds, written as `retry:`. Applies to the connection, not the event. */
|
|
||||||
retry?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A stream item carrying SSE fields as well as a payload. Build one with {@link sse}. */
|
|
||||||
export interface SseEvent<T = unknown> extends SseFields {
|
|
||||||
readonly [SSE_EVENT]: true;
|
|
||||||
data: T;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Type guard: true when a stream item was built by {@link sse}. */
|
|
||||||
export function isSseEvent(item: unknown): item is SseEvent {
|
|
||||||
return typeof item === 'object' && item !== null && (item as Record<symbol, unknown>)[SSE_EVENT] === true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// The SSE wire format is line-based, so a newline inside a field value ends the field — and a
|
|
||||||
// value that reaches `id:` from a request (a cursor, a page token) would let a caller append
|
|
||||||
// arbitrary fields, or whole events, to somebody else's stream. Rejected rather than stripped:
|
|
||||||
// a silently-shortened id is echoed back as `Last-Event-ID` and resumes from the wrong place,
|
|
||||||
// which is the same invisible gap this feature exists to close. `pipeStream` catches this, emits
|
|
||||||
// `stream:error` and writes an `error` frame, so the failure is loud and lands on the first event.
|
|
||||||
function assertFieldSafe(field: string, value: string): void {
|
|
||||||
if (!/[\r\n\0]/.test(value)) return;
|
|
||||||
|
|
||||||
throw new Error(
|
|
||||||
`sse(): '${field}' may not contain a newline or a NUL — the SSE wire format is line-based, so ` +
|
|
||||||
'one would end the field and let the rest of the value be read as further SSE fields. ' +
|
|
||||||
`Received ${JSON.stringify(value)}.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Tags a stream item with SSE fields, so an `@Sse` route can emit `id:`, `event:` and `retry:`
|
|
||||||
* instead of a bare `data:` frame.
|
|
||||||
*
|
|
||||||
* The `id` is what makes an `EventSource` reconnect resumable: the browser sends the last id it
|
|
||||||
* saw back as `Last-Event-ID`, and the handler decides what to do with it. green-tea carries the
|
|
||||||
* marker in both directions and stores nothing — a source that can resume, resumes; one that
|
|
||||||
* cannot keeps streaming from now, which is the honest behaviour for a live feed.
|
|
||||||
*
|
|
||||||
* On an `ndjson` or `negotiate`-to-ndjson route the payload is unwrapped and the SSE fields are
|
|
||||||
* dropped, because NDJSON has no frame to carry them and no resumption protocol to use them.
|
|
||||||
*
|
|
||||||
* @example
|
|
||||||
* ```ts
|
|
||||||
* @Sse('/feed')
|
|
||||||
* feed(@header('last-event-id') from: string) {
|
|
||||||
* return (async function* () {
|
|
||||||
* for await (const row of rows({ after: from })) yield sse(row, { id: row.seq });
|
|
||||||
* })();
|
|
||||||
* }
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export function sse<T>(data: T, fields: SseFields = {}): SseEvent<T> {
|
|
||||||
if (fields.id !== undefined) assertFieldSafe('id', fields.id);
|
|
||||||
if (fields.event !== undefined) assertFieldSafe('event', fields.event);
|
|
||||||
|
|
||||||
// Browsers ignore a `retry:` that is not a base-10 integer, so a float would silently leave the
|
|
||||||
// reconnection delay at the default rather than at the value the app asked for.
|
|
||||||
if (fields.retry !== undefined && !Number.isInteger(fields.retry)) {
|
|
||||||
throw new Error(`sse(): 'retry' must be a whole number of milliseconds, received ${fields.retry}.`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return { [SSE_EVENT]: true, data, ...fields };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Frames one item as an SSE event. Fields precede `data:` and `data:` closes the event.
|
|
||||||
* `JSON.stringify` escapes newlines inside the payload, so the data line is single by construction.
|
|
||||||
*/
|
|
||||||
function sseFrame(item: unknown): string {
|
|
||||||
if (!isSseEvent(item)) return `data: ${JSON.stringify(item)}\n\n`;
|
|
||||||
let frame = '';
|
|
||||||
|
|
||||||
if (item.retry !== undefined) frame += `retry: ${item.retry}\n`;
|
|
||||||
if (item.event !== undefined) frame += `event: ${item.event}\n`;
|
|
||||||
if (item.id !== undefined) frame += `id: ${item.id}\n`;
|
|
||||||
|
|
||||||
return `${frame}data: ${JSON.stringify(item.data)}\n\n`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Server-Sent Events encoder: one JSON payload per `data:` event, with comment-line pings. */
|
/** Server-Sent Events encoder: one JSON payload per `data:` event, with comment-line pings. */
|
||||||
export const sseEncoder: StreamEncoder = {
|
export const sseEncoder: StreamEncoder = {
|
||||||
headers: { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' },
|
headers: { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' },
|
||||||
encode: sseFrame,
|
encode: (item) => `data: ${JSON.stringify(item)}\n\n`,
|
||||||
encodeError: (err) => `event: error\ndata: ${JSON.stringify({ error: messageOf(err) })}\n\n`,
|
encodeError: (err) => `event: error\ndata: ${JSON.stringify({ error: messageOf(err) })}\n\n`,
|
||||||
ping: () => ': ping\n\n',
|
ping: () => ': ping\n\n',
|
||||||
};
|
};
|
||||||
@@ -118,8 +22,6 @@ export const sseEncoder: StreamEncoder = {
|
|||||||
/** Newline-delimited JSON encoder: one JSON object per line. */
|
/** Newline-delimited JSON encoder: one JSON object per line. */
|
||||||
export const ndjsonEncoder: StreamEncoder = {
|
export const ndjsonEncoder: StreamEncoder = {
|
||||||
headers: { 'content-type': 'application/x-ndjson' },
|
headers: { 'content-type': 'application/x-ndjson' },
|
||||||
// Unwrapped rather than serialized as-is: a `negotiate` route yields the same items to both
|
encode: (item) => `${JSON.stringify(item)}\n`,
|
||||||
// encoders, and an ndjson client asked for the payload, not green-tea's SSE envelope around it.
|
|
||||||
encode: (item) => `${JSON.stringify(isSseEvent(item) ? item.data : item)}\n`,
|
|
||||||
encodeError: (err) => `${JSON.stringify({ error: messageOf(err) })}\n`,
|
encodeError: (err) => `${JSON.stringify({ error: messageOf(err) })}\n`,
|
||||||
};
|
};
|
||||||
@@ -78,35 +78,6 @@ export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] {
|
|||||||
return ordered;
|
return ordered;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Groups an already topo-sorted list into dependency levels: nothing in a level can constrain
|
|
||||||
* anything else in it, and a level depends only on the levels before it — so a level can run
|
|
||||||
* concurrently. Needs produced by nothing in `ordered` (seeds, filtered-out kinds) constrain
|
|
||||||
* nothing and are ignored.
|
|
||||||
*/
|
|
||||||
export function topoLevels(ordered: GraphNode[]): GraphNode[][] {
|
|
||||||
const producedBy = new Map<string, GraphNode>();
|
|
||||||
for (const node of ordered) for (const key of node.provides) producedBy.set(key, node);
|
|
||||||
const depthOf = new Map<GraphNode, number>();
|
|
||||||
const levels: GraphNode[][] = [];
|
|
||||||
|
|
||||||
// One forward pass is enough: `ordered` is topologically sorted, so every producer of a node's
|
|
||||||
// needs already has its depth by the time the node is reached.
|
|
||||||
for (const node of ordered) {
|
|
||||||
let depth = 0;
|
|
||||||
|
|
||||||
for (const key of node.needs) {
|
|
||||||
const producer = producedBy.get(key);
|
|
||||||
if (producer && producer !== node) depth = Math.max(depth, (depthOf.get(producer) ?? 0) + 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
depthOf.set(node, depth);
|
|
||||||
(levels[depth] ??= []).push(node);
|
|
||||||
}
|
|
||||||
|
|
||||||
return levels;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Filters `ordered` down to the transitive closure of producers reachable from `needs`. */
|
/** Filters `ordered` down to the transitive closure of producers reachable from `needs`. */
|
||||||
export function subgraphFor(needs: string[], ordered: GraphNode[]): GraphNode[] {
|
export function subgraphFor(needs: string[], ordered: GraphNode[]): GraphNode[] {
|
||||||
const producedBy = new Map<string, GraphNode>();
|
const producedBy = new Map<string, GraphNode>();
|
||||||
|
|||||||
+1
-1
@@ -129,7 +129,7 @@ function parseAcquired(
|
|||||||
|
|
||||||
return parseRequestBody(acquired.bytes, contentType, duplicates, maxParts).then((parsed) =>
|
return parseRequestBody(acquired.bytes, contentType, duplicates, maxParts).then((parsed) =>
|
||||||
'error' in parsed
|
'error' in parsed
|
||||||
? { fail: renderError(new HttpError(parsed.status ?? 400, parsed.error), req, opts?.onError, opts?.logger) }
|
? { fail: renderError(new HttpError(parsed.status ?? 400, parsed.error), req, opts?.onError) }
|
||||||
: { body: parsed.body },
|
: { body: parsed.body },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
+7
-74
@@ -144,7 +144,7 @@ function errorOutcome(
|
|||||||
opts: HttpOptions | undefined,
|
opts: HttpOptions | undefined,
|
||||||
headers: Record<string, string> = {},
|
headers: Record<string, string> = {},
|
||||||
): HandleResult {
|
): HandleResult {
|
||||||
const rendered = renderError(error, req, opts?.onError, opts?.logger);
|
const rendered = renderError(error, req, opts?.onError);
|
||||||
return {
|
return {
|
||||||
injected,
|
injected,
|
||||||
outcome: {
|
outcome: {
|
||||||
@@ -192,15 +192,6 @@ async function unmatchedOutcome(
|
|||||||
return errorOutcome(error, req, injected, opts, allow.length ? { allow: allow.join(', ') } : {});
|
return errorOutcome(error, req, injected, opts, allow.length ? { allow: allow.join(', ') } : {});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* The `route` reported for a request no route matched.
|
|
||||||
*
|
|
||||||
* A bounded value rather than an empty field, and deliberately unlike any pattern a user can
|
|
||||||
* declare — a route pattern starts with `/`, so this cannot collide with one. It aggregates as a
|
|
||||||
* single series where the concrete path would produce one per distinct URL.
|
|
||||||
*/
|
|
||||||
export const UNMATCHED_ROUTE = '<unmatched>';
|
|
||||||
|
|
||||||
/** What `dispatch` learned along the way that `handle` needs in order to describe the request afterwards. */
|
/** What `dispatch` learned along the way that `handle` needs in order to describe the request afterwards. */
|
||||||
interface Trace {
|
interface Trace {
|
||||||
route?: string;
|
route?: string;
|
||||||
@@ -221,7 +212,6 @@ export function handle(
|
|||||||
routes: RouteDef[],
|
routes: RouteDef[],
|
||||||
opts: HttpOptions | undefined,
|
opts: HttpOptions | undefined,
|
||||||
req: NeutralRequest,
|
req: NeutralRequest,
|
||||||
injected?: Record<string, string>,
|
|
||||||
): Promise<HandleResult | Preflight> {
|
): Promise<HandleResult | Preflight> {
|
||||||
const bus = opts?.bus;
|
const bus = opts?.bus;
|
||||||
|
|
||||||
@@ -237,52 +227,10 @@ export function handle(
|
|||||||
bus.hasListeners('route:unmatched')
|
bus.hasListeners('route:unmatched')
|
||||||
)
|
)
|
||||||
) {
|
) {
|
||||||
return dispatch(routes, opts, req, undefined, undefined, injected);
|
return dispatch(routes, opts, req, undefined, undefined);
|
||||||
}
|
}
|
||||||
|
|
||||||
return observedDispatch(routes, opts, req, bus, injected);
|
return observedDispatch(routes, opts, req, bus);
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Whether anything is listening for the request pair — the one check both adapters need before
|
|
||||||
* paying for a `performance.now()` on a request they are about to refuse.
|
|
||||||
*/
|
|
||||||
export function watchingRequests(bus: Bus | undefined): bus is Bus {
|
|
||||||
return bus !== undefined && (bus.hasListeners('request:start') || bus.hasListeners('request:end'));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Emits the lifecycle pair for a request shed before routing.
|
|
||||||
*
|
|
||||||
* A shed request never reaches {@link handle}, so `observedDispatch` — the emitter every other
|
|
||||||
* terminal path goes through — never sees it, and an adapter that emitted only `request:end` would
|
|
||||||
* be the first thing in the tree to break the pairing {@link LifecycleEvent} guarantees. Both
|
|
||||||
* events are emitted here, in order, so a consumer that opens per-`requestId` state on
|
|
||||||
* `request:start` and closes it on `request:end` does not start leaking half-open entries the first
|
|
||||||
* time a server sheds — under load, which is when it can least afford them.
|
|
||||||
*
|
|
||||||
* Each event keeps its own listener guard: the pairing is a promise to a subscriber of *both*, and
|
|
||||||
* costs nothing for a subscriber of one.
|
|
||||||
*/
|
|
||||||
export function emitShedPair(
|
|
||||||
bus: Bus,
|
|
||||||
req: { method: string; url: string; requestId?: string; traceId?: string },
|
|
||||||
startedAt: number,
|
|
||||||
): void {
|
|
||||||
const name = `${req.method} ${req.url}`;
|
|
||||||
|
|
||||||
if (bus.hasListeners('request:start'))
|
|
||||||
bus.emit('request:start', { name, method: req.method, requestId: req.requestId, traceId: req.traceId });
|
|
||||||
|
|
||||||
if (bus.hasListeners('request:end'))
|
|
||||||
bus.emit('request:end', {
|
|
||||||
name,
|
|
||||||
method: req.method,
|
|
||||||
status: 503,
|
|
||||||
durationMs: performance.now() - startedAt,
|
|
||||||
requestId: req.requestId,
|
|
||||||
traceId: req.traceId,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function observedDispatch(
|
async function observedDispatch(
|
||||||
@@ -290,7 +238,6 @@ async function observedDispatch(
|
|||||||
opts: HttpOptions | undefined,
|
opts: HttpOptions | undefined,
|
||||||
req: NeutralRequest,
|
req: NeutralRequest,
|
||||||
bus: Bus,
|
bus: Bus,
|
||||||
injected?: Record<string, string>,
|
|
||||||
): Promise<HandleResult | Preflight> {
|
): Promise<HandleResult | Preflight> {
|
||||||
const watchingEnd = bus.hasListeners('request:end');
|
const watchingEnd = bus.hasListeners('request:end');
|
||||||
const startedAt = watchingEnd ? performance.now() : 0;
|
const startedAt = watchingEnd ? performance.now() : 0;
|
||||||
@@ -304,7 +251,7 @@ async function observedDispatch(
|
|||||||
traceId: req.traceId,
|
traceId: req.traceId,
|
||||||
});
|
});
|
||||||
|
|
||||||
const result = await dispatch(routes, opts, req, bus, trace, injected);
|
const result = await dispatch(routes, opts, req, bus, trace);
|
||||||
|
|
||||||
if (watchingEnd) {
|
if (watchingEnd) {
|
||||||
// A preflight is a 204 the router never routed; a stream has no status of its own and is a 200
|
// A preflight is a 204 the router never routed; a stream has no status of its own and is a 200
|
||||||
@@ -330,13 +277,8 @@ async function dispatch(
|
|||||||
req: NeutralRequest,
|
req: NeutralRequest,
|
||||||
bus: Bus | undefined,
|
bus: Bus | undefined,
|
||||||
trace: Trace | undefined,
|
trace: Trace | undefined,
|
||||||
precomputed?: Record<string, string>,
|
|
||||||
): Promise<HandleResult | Preflight> {
|
): Promise<HandleResult | Preflight> {
|
||||||
// Both adapters compute this before routing, because a response written above `handle()` — a
|
const injected = computeInjected(opts, req);
|
||||||
// shed 503, a 413 from the body reader — has to carry the same headers as one written below it.
|
|
||||||
// Recomputing here would run `security` and, worse, the `origins` predicate a second time for
|
|
||||||
// one request. `computeInjected` stays as the fallback for callers that have nothing yet.
|
|
||||||
const injected = precomputed ?? computeInjected(opts, req);
|
|
||||||
let path: string;
|
let path: string;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -346,24 +288,15 @@ async function dispatch(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) {
|
if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) {
|
||||||
return { preflight: corsPreflightHeaders(opts.cors, req, injected) };
|
return { preflight: corsPreflightHeaders(opts.cors, req, opts.logger) };
|
||||||
}
|
}
|
||||||
|
|
||||||
const matched = resolveRoute(routes, req.method, path);
|
const matched = resolveRoute(routes, req.method, path);
|
||||||
|
|
||||||
if (!matched) {
|
if (!matched) {
|
||||||
// `name` here is the path that arrived, and it is the one value in this payload that must never
|
|
||||||
// become a metric label: a matched route's path is bounded by the route table, an unmatched one
|
|
||||||
// is bounded by nothing at all, and a scanner walking /aaa, /aab, /aac is a memory leak with a
|
|
||||||
// metrics backend attached. So the event carries a bounded `route` as well, and so does the
|
|
||||||
// `request:end` that follows it, rather than leaving every consumer to invent the same fallback
|
|
||||||
// and some of them to get it wrong.
|
|
||||||
if (trace) trace.route = UNMATCHED_ROUTE;
|
|
||||||
|
|
||||||
if (bus?.hasListeners('route:unmatched'))
|
if (bus?.hasListeners('route:unmatched'))
|
||||||
bus.emit('route:unmatched', {
|
bus.emit('route:unmatched', {
|
||||||
name: `${req.method} ${path}`,
|
name: `${req.method} ${path}`,
|
||||||
route: UNMATCHED_ROUTE,
|
|
||||||
method: req.method,
|
method: req.method,
|
||||||
requestId: req.requestId,
|
requestId: req.requestId,
|
||||||
traceId: req.traceId,
|
traceId: req.traceId,
|
||||||
@@ -410,7 +343,7 @@ async function dispatch(
|
|||||||
traceId: req.traceId,
|
traceId: req.traceId,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
result = renderError(error, req, opts?.onError, opts?.logger);
|
result = renderError(error, req, opts?.onError);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isStreamResult(result)) {
|
if (isStreamResult(result)) {
|
||||||
|
|||||||
@@ -5,16 +5,6 @@
|
|||||||
* handler execution finishes; a returned stream does not hold the slot for the stream's lifetime.
|
* handler execution finishes; a returned stream does not hold the slot for the stream's lifetime.
|
||||||
*/
|
*/
|
||||||
export interface RequestGate {
|
export interface RequestGate {
|
||||||
/**
|
|
||||||
* Whether a budget is actually configured.
|
|
||||||
*
|
|
||||||
* Exposed rather than left for each adapter to re-derive from `opts`, because the gate is what
|
|
||||||
* knows: `acquire()` returns `true` unconditionally when there is no limit, so a caller reading
|
|
||||||
* only its result cannot tell "admitted" from "not counting", and pays for the bookkeeping either
|
|
||||||
* way. `maxConcurrentRequests` is opt-in, so for most applications this is `false` and every
|
|
||||||
* per-request cost behind it should be skipped entirely.
|
|
||||||
*/
|
|
||||||
limited: boolean;
|
|
||||||
acquire(): boolean;
|
acquire(): boolean;
|
||||||
release(): void;
|
release(): void;
|
||||||
}
|
}
|
||||||
@@ -22,11 +12,8 @@ export interface RequestGate {
|
|||||||
/** Creates an unlimited gate when `limit` is undefined or non-positive. */
|
/** Creates an unlimited gate when `limit` is undefined or non-positive. */
|
||||||
export function createRequestGate(limit: number | undefined): RequestGate {
|
export function createRequestGate(limit: number | undefined): RequestGate {
|
||||||
let active = 0;
|
let active = 0;
|
||||||
const limited = limit !== undefined && limit > 0;
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
limited,
|
|
||||||
|
|
||||||
acquire(): boolean {
|
acquire(): boolean {
|
||||||
if (limit === undefined || limit <= 0) return true;
|
if (limit === undefined || limit <= 0) return true;
|
||||||
if (active >= limit) return false;
|
if (active >= limit) return false;
|
||||||
|
|||||||
+34
-80
@@ -13,6 +13,8 @@ export interface CompiledPattern {
|
|||||||
segments: CompiledSegment[];
|
segments: CompiledSegment[];
|
||||||
kinds: number[];
|
kinds: number[];
|
||||||
catchAll: boolean;
|
catchAll: boolean;
|
||||||
|
/** Every segment is a literal, so this pattern scores the maximum specificity and cannot be outranked. */
|
||||||
|
allStatic: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const compiledCache = new Map<string, CompiledPattern>();
|
const compiledCache = new Map<string, CompiledPattern>();
|
||||||
@@ -158,6 +160,7 @@ export function compilePattern(pattern: string): CompiledPattern {
|
|||||||
.filter((segment) => segment.kind !== 'catchAll')
|
.filter((segment) => segment.kind !== 'catchAll')
|
||||||
.map((segment) => (segment.kind === 'static' ? 3 : segment.constraint ? 2 : 1)),
|
.map((segment) => (segment.kind === 'static' ? 3 : segment.constraint ? 2 : 1)),
|
||||||
catchAll: segments.at(-1)?.kind === 'catchAll',
|
catchAll: segments.at(-1)?.kind === 'catchAll',
|
||||||
|
allStatic: segments.every((segment) => segment.kind === 'static'),
|
||||||
};
|
};
|
||||||
compiledCache.set(pattern, compiled);
|
compiledCache.set(pattern, compiled);
|
||||||
return compiled;
|
return compiled;
|
||||||
@@ -245,10 +248,7 @@ export function normalizeRequestPath(path: string): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function decodeSegment(value: string): string {
|
function decodeSegment(value: string): string {
|
||||||
// Same gate `normalizeRequestPath` uses on the whole path, for the same reason: a segment with no
|
return decodeURIComponent(value);
|
||||||
// `%` decodes to itself, so the call only ever proves that. Most segments have no `%`, and this
|
|
||||||
// runs for every param segment of every candidate route the scan reaches.
|
|
||||||
return value.includes('%') ? decodeURIComponent(value) : value;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -262,18 +262,7 @@ function splitPath(path: string): string[] {
|
|||||||
return path.split('/').filter(Boolean);
|
return path.split('/').filter(Boolean);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
function matchCompiled(compiled: CompiledPattern, pathSegs: string[]): Record<string, string> | undefined {
|
||||||
* Matches one compiled pattern against a request's segments.
|
|
||||||
*
|
|
||||||
* `decoded` memoizes per request, not per candidate: a scan reaching the same parameter position on
|
|
||||||
* several routes decoded the same string once per route. Position is all decoding depends on, so one
|
|
||||||
* array shared across the scan is the same answer for less work.
|
|
||||||
*/
|
|
||||||
function matchCompiled(
|
|
||||||
compiled: CompiledPattern,
|
|
||||||
pathSegs: string[],
|
|
||||||
decoded?: Array<string | undefined>,
|
|
||||||
): Record<string, string> | undefined {
|
|
||||||
const params: Record<string, string> = {};
|
const params: Record<string, string> = {};
|
||||||
|
|
||||||
for (let index = 0; index < compiled.segments.length; index++) {
|
for (let index = 0; index < compiled.segments.length; index++) {
|
||||||
@@ -291,7 +280,7 @@ function matchCompiled(
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
const value = decoded ? (decoded[index] ??= decodeSegment(pathSegs[index])) : decodeSegment(pathSegs[index]);
|
const value = decodeSegment(pathSegs[index]);
|
||||||
if (segment.constraint && !segment.constraint.test(value)) return undefined;
|
if (segment.constraint && !segment.constraint.test(value)) return undefined;
|
||||||
params[segment.name] = value;
|
params[segment.name] = value;
|
||||||
}
|
}
|
||||||
@@ -304,15 +293,10 @@ export function matchPattern(pattern: string, path: string): Record<string, stri
|
|||||||
return matchCompiled(compilePattern(pattern), splitPath(path));
|
return matchCompiled(compilePattern(pattern), splitPath(path));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Orders matching patterns by exactness, then static/constrained/plain segment specificity. */
|
||||||
* Orders patterns by exactness, then static/constrained/plain segment specificity.
|
function moreSpecific(a: string, b: string): number {
|
||||||
*
|
const scoreA = compilePattern(a);
|
||||||
* Takes compiled patterns rather than their source strings: it used to re-derive both through
|
const scoreB = compilePattern(b);
|
||||||
* `compilePattern`, which is a `Map` lookup each, on every comparison of every request.
|
|
||||||
*/
|
|
||||||
function moreSpecific(a: CompiledPattern, b: CompiledPattern): number {
|
|
||||||
const scoreA = a;
|
|
||||||
const scoreB = b;
|
|
||||||
if (scoreA.catchAll !== scoreB.catchAll) return scoreA.catchAll ? -1 : 1;
|
if (scoreA.catchAll !== scoreB.catchAll) return scoreA.catchAll ? -1 : 1;
|
||||||
const length = Math.max(scoreA.kinds.length, scoreB.kinds.length);
|
const length = Math.max(scoreA.kinds.length, scoreB.kinds.length);
|
||||||
|
|
||||||
@@ -325,65 +309,35 @@ function moreSpecific(a: CompiledPattern, b: CompiledPattern): number {
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** One route with its pattern already compiled. Built once per table, ordered within its method. */
|
/** Finds the most specific route matching both method and path; ties keep registration order. */
|
||||||
interface IndexedRoute {
|
|
||||||
def: RouteDef;
|
|
||||||
compiled: CompiledPattern;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Compiled, method-bucketed, specificity-ordered route tables, keyed by the identity of the array
|
|
||||||
* they were built from.
|
|
||||||
*
|
|
||||||
* A server hands the same array to every request, so this is built once and collected with the
|
|
||||||
* table it describes. A table assembled fresh — mesh splicing a teapot's exports in at boot — is a
|
|
||||||
* different array and gets its own index, so nothing has to remember to invalidate anything.
|
|
||||||
*/
|
|
||||||
const routeIndexCache = new WeakMap<RouteDef[], Map<string, IndexedRoute[]>>();
|
|
||||||
|
|
||||||
function routeIndex(routes: RouteDef[]): Map<string, IndexedRoute[]> {
|
|
||||||
const cached = routeIndexCache.get(routes);
|
|
||||||
if (cached) return cached;
|
|
||||||
|
|
||||||
const byMethod = new Map<string, IndexedRoute[]>();
|
|
||||||
|
|
||||||
for (const def of routes) {
|
|
||||||
const entry: IndexedRoute = { def, compiled: compilePattern(def.pattern) };
|
|
||||||
const bucket = byMethod.get(def.method);
|
|
||||||
if (bucket) bucket.push(entry);
|
|
||||||
else byMethod.set(def.method, [entry]);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Most specific first, so the first match *is* the answer. `sort` is stable, so equal patterns
|
|
||||||
// keep registration order — which is exactly what the old scan did by refusing to replace its
|
|
||||||
// best on a tie.
|
|
||||||
for (const bucket of byMethod.values()) bucket.sort((a, b) => moreSpecific(b.compiled, a.compiled));
|
|
||||||
|
|
||||||
routeIndexCache.set(routes, byMethod);
|
|
||||||
return byMethod;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Finds the most specific route matching both method and path; ties keep registration order.
|
|
||||||
*
|
|
||||||
* The ranking is settled when the table is built, not per request: the answer cannot change between
|
|
||||||
* requests, and re-deriving it charged every request for a scan to the end plus a `moreSpecific`
|
|
||||||
* call — two `compilePattern` lookups each — per candidate. Both scaled with the size of the route
|
|
||||||
* table. What is left here is a walk that stops at the first match.
|
|
||||||
*/
|
|
||||||
export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined {
|
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 pathSegs = splitPath(path);
|
||||||
const decoded: Array<string | undefined> = new Array(pathSegs.length);
|
let best: MatchedRoute | undefined;
|
||||||
|
let bestPattern = '';
|
||||||
|
|
||||||
for (const { def, compiled } of candidates) {
|
for (const route of routes) {
|
||||||
const params = matchCompiled(compiled, pathSegs, decoded);
|
if (route.method !== method) continue;
|
||||||
if (params) return { params, def };
|
const compiled = compilePattern(route.pattern);
|
||||||
|
const params = matchCompiled(compiled, pathSegs);
|
||||||
|
if (!params) continue;
|
||||||
|
|
||||||
|
// An all-static match ends the scan. Specificity ranks a literal segment above every other
|
||||||
|
// kind, so no pattern that also matches this path can outrank one made only of literals — and
|
||||||
|
// an equal rank keeps registration order, which is this route. Finishing the scan would
|
||||||
|
// re-derive the answer already in hand.
|
||||||
|
//
|
||||||
|
// The scan used to run to the end regardless: `/hello` cost the same whether it was declared
|
||||||
|
// first or last among 32 routes, 1227 ns against 1237 ns. That is ~38 ns of scanning per
|
||||||
|
// registered route on every request, and it grows with the route table.
|
||||||
|
if (compiled.allStatic) return { params, def: route };
|
||||||
|
|
||||||
|
if (!best || moreSpecific(route.pattern, bestPattern) > 0) {
|
||||||
|
best = { params, def: route };
|
||||||
|
bestPattern = route.pattern;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return undefined;
|
return best;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Route resolution adds the one HTTP fallback the matcher supports: buffered GET serves HEAD. */
|
/** Route resolution adds the one HTTP fallback the matcher supports: buffered GET serves HEAD. */
|
||||||
|
|||||||
+23
-47
@@ -3,19 +3,12 @@ import type https from 'https';
|
|||||||
import { createRequestGate } from './request-gate';
|
import { createRequestGate } from './request-gate';
|
||||||
import { renderError, type ErrorRequest } from '../transformers';
|
import { renderError, type ErrorRequest } from '../transformers';
|
||||||
import type { Bus } from '../bus';
|
import type { Bus } from '../bus';
|
||||||
|
import { buildSecurityHeaders, resolveCors } from '../security';
|
||||||
import { readBody as readBodyBytes, deriveSecure, deriveIp } from './request';
|
import { readBody as readBodyBytes, deriveSecure, deriveIp } from './request';
|
||||||
import { pipeStream } from './stream';
|
import { pipeStream } from './stream';
|
||||||
import { attachWs } from './ws';
|
import { attachWs } from './ws';
|
||||||
import { mergeInjectedHeaders } from './headers';
|
import { mergeInjectedHeaders } from './headers';
|
||||||
import {
|
import { handle, correlateRequest, type HandleResult, type Preflight } from './core';
|
||||||
handle,
|
|
||||||
correlateRequest,
|
|
||||||
computeInjected,
|
|
||||||
emitShedPair,
|
|
||||||
watchingRequests,
|
|
||||||
type HandleResult,
|
|
||||||
type Preflight,
|
|
||||||
} from './core';
|
|
||||||
import type { BodyFailure, BodyReader } from './body';
|
import type { BodyFailure, BodyReader } from './body';
|
||||||
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
|
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
|
||||||
import { nodeRequire } from '../node-require';
|
import { nodeRequire } from '../node-require';
|
||||||
@@ -102,30 +95,32 @@ function createRequestHandler(cfg: HandlerConfig) {
|
|||||||
const secure = deriveSecure(req, trustProxy);
|
const secure = deriveSecure(req, trustProxy);
|
||||||
// Derived before the body is read, so a 413 rejected below still carries an identity.
|
// Derived before the body is read, so a 413 rejected below still carries an identity.
|
||||||
const correlation = correlateRequest(req.headers);
|
const correlation = correlateRequest(req.headers);
|
||||||
// One computation for the whole request: this object is patched into every response below, and
|
const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, secure) };
|
||||||
// handed to `handle()` so routing does not derive it a second time — `security` is pure, but
|
|
||||||
// `cors.origins` may be a predicate with a network call in it.
|
|
||||||
const injected = computeInjected(opts, { secure, headers: req.headers });
|
|
||||||
patchResponseHeaders(res, injected);
|
patchResponseHeaders(res, injected);
|
||||||
|
|
||||||
|
// CORS is added to `injected` AFTER the patch is installed — the patch reads it lazily
|
||||||
|
// by reference at writeHead time, so keys added here still land on every response.
|
||||||
|
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req, opts?.logger));
|
||||||
|
|
||||||
let result: HandleResult | Preflight;
|
let result: HandleResult | Preflight;
|
||||||
let acquired = false;
|
let acquired = false;
|
||||||
const watching = watchingRequests(bus);
|
const watchingEnd = bus?.hasListeners('request:end') ?? false;
|
||||||
const startedAt = watching ? performance.now() : 0;
|
const startedAt = watchingEnd ? performance.now() : 0;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (!gate.acquire()) {
|
if (!gate.acquire()) {
|
||||||
if (watching)
|
if (watchingEnd) {
|
||||||
emitShedPair(
|
const method = req.method ?? 'GET';
|
||||||
bus,
|
const url = req.url ?? '/';
|
||||||
{
|
bus!.emit('request:end', {
|
||||||
method: req.method ?? 'GET',
|
name: `${method} ${url}`,
|
||||||
url: req.url ?? '/',
|
method,
|
||||||
|
status: 503,
|
||||||
|
durationMs: performance.now() - startedAt,
|
||||||
requestId: correlation.requestId,
|
requestId: correlation.requestId,
|
||||||
traceId: correlation.traceId,
|
traceId: correlation.traceId,
|
||||||
},
|
});
|
||||||
startedAt,
|
}
|
||||||
);
|
|
||||||
|
|
||||||
res.writeHead(503, {
|
res.writeHead(503, {
|
||||||
'content-type': 'application/json',
|
'content-type': 'application/json',
|
||||||
@@ -136,23 +131,14 @@ function createRequestHandler(cfg: HandlerConfig) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Both the flag and the listener are skipped when no budget is configured, which is most
|
|
||||||
// applications: `maxConcurrentRequests` is opt-in and unlimited by default. A closure and an
|
|
||||||
// EventEmitter registration per request, on the hot path, for a feature that is off is a cost
|
|
||||||
// with nothing on the other side of it.
|
|
||||||
if (gate.limited) {
|
|
||||||
acquired = true;
|
acquired = true;
|
||||||
res.once('close', () => {
|
res.once('close', () => {
|
||||||
if (!acquired) return;
|
if (!acquired) return;
|
||||||
acquired = false;
|
acquired = false;
|
||||||
gate.release();
|
gate.release();
|
||||||
});
|
});
|
||||||
}
|
|
||||||
|
|
||||||
result = await handle(
|
result = await handle(routes, opts, {
|
||||||
routes,
|
|
||||||
opts,
|
|
||||||
{
|
|
||||||
...correlation,
|
...correlation,
|
||||||
method: req.method ?? 'GET',
|
method: req.method ?? 'GET',
|
||||||
url: req.url ?? '/',
|
url: req.url ?? '/',
|
||||||
@@ -161,9 +147,7 @@ function createRequestHandler(cfg: HandlerConfig) {
|
|||||||
source: req,
|
source: req,
|
||||||
secure,
|
secure,
|
||||||
ip: deriveIp(req, trustProxy),
|
ip: deriveIp(req, trustProxy),
|
||||||
},
|
});
|
||||||
injected,
|
|
||||||
);
|
|
||||||
} finally {
|
} finally {
|
||||||
if (acquired) {
|
if (acquired) {
|
||||||
acquired = false;
|
acquired = false;
|
||||||
@@ -178,15 +162,7 @@ function createRequestHandler(cfg: HandlerConfig) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (result.outcome.kind === 'stream') {
|
if (result.outcome.kind === 'stream') {
|
||||||
await pipeStream(
|
await pipeStream(res, result.outcome.stream, result.outcome.encoder, bus, result.outcome.route, opts?.streams);
|
||||||
res,
|
|
||||||
result.outcome.stream,
|
|
||||||
result.outcome.encoder,
|
|
||||||
bus,
|
|
||||||
result.outcome.route,
|
|
||||||
opts?.streams,
|
|
||||||
correlation,
|
|
||||||
);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -212,7 +188,7 @@ function readRequestBytes(
|
|||||||
return readBodyBytes(req, limit).then(
|
return readBodyBytes(req, limit).then(
|
||||||
(bytes) => ({ bytes }),
|
(bytes) => ({ bytes }),
|
||||||
(error: unknown) => {
|
(error: unknown) => {
|
||||||
const rendered = renderError(error, errorRequest(req), opts?.onError, opts?.logger);
|
const rendered = renderError(error, errorRequest(req), opts?.onError);
|
||||||
return { fail: { ...rendered, headers: { ...rendered.headers, connection: 'close' } } };
|
return { fail: { ...rendered, headers: { ...rendered.headers, connection: 'close' } } };
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
+4
-10
@@ -2,7 +2,7 @@ import type http from 'http';
|
|||||||
import { once } from 'events';
|
import { once } from 'events';
|
||||||
import { sseEncoder, ndjsonEncoder, StreamEncoder } from '../encoders';
|
import { sseEncoder, ndjsonEncoder, StreamEncoder } from '../encoders';
|
||||||
import type { Transport } from '../metadata';
|
import type { Transport } from '../metadata';
|
||||||
import type { Bus, Correlation } from '../bus';
|
import type { Bus } from '../bus';
|
||||||
|
|
||||||
const PING_MS = 15_000;
|
const PING_MS = 15_000;
|
||||||
|
|
||||||
@@ -35,16 +35,10 @@ export async function pipeStream(
|
|||||||
bus?: Bus,
|
bus?: Bus,
|
||||||
name = '',
|
name = '',
|
||||||
streams?: Set<() => void>,
|
streams?: Set<() => void>,
|
||||||
correlation: Correlation = {},
|
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
// `route` duplicates `name` here rather than being passed separately: on a stream event `name`
|
|
||||||
// is always the route pattern, never the concrete path the request events can carry — but a
|
|
||||||
// consumer following the documented contract labels on `route` and would otherwise find it
|
|
||||||
// absent on the longest-lived thing the server does. See `EventPayload.name`.
|
|
||||||
const trace = { name, route: name, ...correlation };
|
|
||||||
res.writeHead(200, encoder.headers);
|
res.writeHead(200, encoder.headers);
|
||||||
res.flushHeaders(); // establish the stream immediately so idle-until-event sources (e.g. subscriptions) don't deadlock clients awaiting 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);
|
bus?.emit('stream:open', { name });
|
||||||
const iterator = stream[Symbol.asyncIterator]();
|
const iterator = stream[Symbol.asyncIterator]();
|
||||||
let ping: ReturnType<typeof setInterval> | undefined;
|
let ping: ReturnType<typeof setInterval> | undefined;
|
||||||
|
|
||||||
@@ -82,13 +76,13 @@ export async function pipeStream(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
bus?.emit('stream:error', { ...trace, error: err });
|
bus?.emit('stream:error', { name, error: err });
|
||||||
const frame = encoder.encodeError(err);
|
const frame = encoder.encodeError(err);
|
||||||
if (frame && !res.writableEnded) res.write(frame);
|
if (frame && !res.writableEnded) res.write(frame);
|
||||||
} finally {
|
} finally {
|
||||||
if (ping) clearInterval(ping);
|
if (ping) clearInterval(ping);
|
||||||
streams?.delete(closer);
|
streams?.delete(closer);
|
||||||
if (!res.writableEnded && !res.destroyed) res.end();
|
if (!res.writableEnded && !res.destroyed) res.end();
|
||||||
bus?.emit('stream:close', trace);
|
bus?.emit('stream:close', { name });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+25
-92
@@ -1,85 +1,34 @@
|
|||||||
import type { StreamEncoder } from '../encoders';
|
import type { StreamEncoder } from '../encoders';
|
||||||
import type { Bus, Correlation } from '../bus';
|
|
||||||
import { createRequestGate } from './request-gate';
|
import { createRequestGate } from './request-gate';
|
||||||
import {
|
import { handle, computeInjected, correlateRequest, type HandleResult, type Preflight } from './core';
|
||||||
handle,
|
|
||||||
computeInjected,
|
|
||||||
correlateRequest,
|
|
||||||
emitShedPair,
|
|
||||||
watchingRequests,
|
|
||||||
type HandleResult,
|
|
||||||
type Preflight,
|
|
||||||
} from './core';
|
|
||||||
import { mergeInjectedHeaders } from './headers';
|
import { mergeInjectedHeaders } from './headers';
|
||||||
import type { BodyFailure, BodyReader, MaybePromise } from './body';
|
import type { BodyFailure, BodyReader, MaybePromise } from './body';
|
||||||
import { HttpError } from '../signals';
|
import { HttpError } from '../signals';
|
||||||
import { renderError, type ErrorRequest } from '../transformers';
|
import { renderError, type ErrorRequest } from '../transformers';
|
||||||
import type { RouteDef, HttpOptions } from './types';
|
import type { RouteDef, HttpOptions } from './types';
|
||||||
|
|
||||||
/**
|
/** Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream cancel. */
|
||||||
* Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream
|
export function asReadableStream(source: AsyncIterable<unknown>, encoder: StreamEncoder): ReadableStream<Uint8Array> {
|
||||||
* cancel, and reports the connection on the bus exactly as {@link pipeStream} does for Node — the
|
|
||||||
* lifecycle of a stream must not depend on which adapter is serving it.
|
|
||||||
*/
|
|
||||||
export function asReadableStream(
|
|
||||||
source: AsyncIterable<unknown>,
|
|
||||||
encoder: StreamEncoder,
|
|
||||||
bus?: Bus,
|
|
||||||
name = '',
|
|
||||||
correlation: Correlation = {},
|
|
||||||
): ReadableStream<Uint8Array> {
|
|
||||||
const iterator = source[Symbol.asyncIterator]();
|
const iterator = source[Symbol.asyncIterator]();
|
||||||
const te = new TextEncoder();
|
const te = new TextEncoder();
|
||||||
// See the same line in `pipeStream`: `name` is the pattern on a stream event, but the contract
|
|
||||||
// says label on `route`, so both are carried.
|
|
||||||
const trace = { name, route: name, ...correlation };
|
|
||||||
const frame = (chunk: string | Buffer): Uint8Array => (typeof chunk === 'string' ? te.encode(chunk) : chunk);
|
|
||||||
// `cancel` can land after the body has already ended, and an errored stream still unwinds through
|
|
||||||
// its own path — so the close is latched rather than emitted from each of the three exits.
|
|
||||||
let closed = false;
|
|
||||||
|
|
||||||
const close = (): void => {
|
|
||||||
if (closed) return;
|
|
||||||
closed = true;
|
|
||||||
bus?.emit('stream:close', trace);
|
|
||||||
};
|
|
||||||
|
|
||||||
return new ReadableStream<Uint8Array>({
|
return new ReadableStream<Uint8Array>({
|
||||||
start() {
|
|
||||||
bus?.emit('stream:open', trace);
|
|
||||||
},
|
|
||||||
async pull(controller) {
|
async pull(controller) {
|
||||||
try {
|
try {
|
||||||
const { value, done } = await iterator.next();
|
const { value, done } = await iterator.next();
|
||||||
|
|
||||||
if (done) {
|
if (done) {
|
||||||
close();
|
|
||||||
controller.close();
|
controller.close();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
controller.enqueue(frame(encoder.encode(value)));
|
const encoded = encoder.encode(value);
|
||||||
|
const bytes = typeof encoded === 'string' ? te.encode(encoded) : encoded;
|
||||||
|
controller.enqueue(bytes);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
bus?.emit('stream:error', { ...trace, error: err });
|
|
||||||
const errorFrame = encoder.encodeError(err);
|
|
||||||
close();
|
|
||||||
|
|
||||||
// Framed and closed cleanly, which is what the Node adapter does and the better answer for
|
|
||||||
// the client: an SSE consumer that received an `error` event knows what happened, where a
|
|
||||||
// transport-level failure is indistinguishable from the connection simply dropping.
|
|
||||||
// `controller.error` is kept for the encoder that has no error frame to offer, because
|
|
||||||
// then breaking the stream is the only signal left.
|
|
||||||
if (errorFrame === null) {
|
|
||||||
controller.error(err);
|
controller.error(err);
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
controller.enqueue(frame(errorFrame));
|
|
||||||
controller.close();
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
async cancel() {
|
async cancel() {
|
||||||
close();
|
|
||||||
await iterator.return?.();
|
await iterator.return?.();
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -120,7 +69,7 @@ function readFetchBytes(
|
|||||||
url: url.pathname + url.search,
|
url: url.pathname + url.search,
|
||||||
headers: headersToRecord(request.headers),
|
headers: headersToRecord(request.headers),
|
||||||
};
|
};
|
||||||
return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError, opts?.logger) };
|
return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError) };
|
||||||
}
|
}
|
||||||
|
|
||||||
return { bytes: arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer) };
|
return { bytes: arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer) };
|
||||||
@@ -158,18 +107,11 @@ export function toBodyInit(body: string | Buffer): ResponseBody {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Converts a {@link HandleResult}'s outcome into a web `Response`, buffered or streamed. */
|
/** Converts a {@link HandleResult}'s outcome into a web `Response`, buffered or streamed. */
|
||||||
function outcomeToResponse(result: HandleResult, bus?: Bus, correlation: Correlation = {}): Response {
|
function outcomeToResponse(result: HandleResult): Response {
|
||||||
const headers = mergeInjectedHeaders(result.outcome.headers, result.injected) as Record<string, string>;
|
const headers = mergeInjectedHeaders(result.outcome.headers, result.injected) as Record<string, string>;
|
||||||
|
|
||||||
if (result.outcome.kind === 'stream') {
|
if (result.outcome.kind === 'stream') {
|
||||||
const body = asReadableStream(
|
return new Response(asReadableStream(result.outcome.stream, result.outcome.encoder), { headers });
|
||||||
result.outcome.stream,
|
|
||||||
result.outcome.encoder,
|
|
||||||
bus,
|
|
||||||
result.outcome.route,
|
|
||||||
correlation,
|
|
||||||
);
|
|
||||||
return new Response(body, { headers });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const body = [204, 205, 304].includes(result.outcome.status) ? null : toBodyInit(result.outcome.body);
|
const body = [204, 205, 304].includes(result.outcome.status) ? null : toBodyInit(result.outcome.body);
|
||||||
@@ -201,22 +143,21 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
|
|||||||
|
|
||||||
let result: HandleResult | Preflight;
|
let result: HandleResult | Preflight;
|
||||||
let acquired = false;
|
let acquired = false;
|
||||||
const watching = watchingRequests(opts?.bus);
|
const watchingEnd = opts?.bus?.hasListeners('request:end') ?? false;
|
||||||
const startedAt = watching ? performance.now() : 0;
|
const startedAt = watchingEnd ? performance.now() : 0;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (!gate.acquire()) {
|
if (!gate.acquire()) {
|
||||||
if (watching)
|
if (watchingEnd) {
|
||||||
emitShedPair(
|
opts!.bus!.emit('request:end', {
|
||||||
opts!.bus!,
|
name: `${request.method} ${path}`,
|
||||||
{
|
|
||||||
method: request.method,
|
method: request.method,
|
||||||
url: path,
|
status: 503,
|
||||||
|
durationMs: performance.now() - startedAt,
|
||||||
requestId: correlation.requestId,
|
requestId: correlation.requestId,
|
||||||
traceId: correlation.traceId,
|
traceId: correlation.traceId,
|
||||||
},
|
});
|
||||||
startedAt,
|
}
|
||||||
);
|
|
||||||
|
|
||||||
return new Response(JSON.stringify({ error: 'Service Unavailable' }), {
|
return new Response(JSON.stringify({ error: 'Service Unavailable' }), {
|
||||||
status: 503,
|
status: 503,
|
||||||
@@ -230,12 +171,9 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
acquired = gate.limited;
|
acquired = true;
|
||||||
|
|
||||||
result = await handle(
|
result = await handle(routes, opts, {
|
||||||
routes,
|
|
||||||
opts,
|
|
||||||
{
|
|
||||||
...correlation,
|
...correlation,
|
||||||
method: request.method,
|
method: request.method,
|
||||||
url: path,
|
url: path,
|
||||||
@@ -243,20 +181,15 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
|
|||||||
readBody,
|
readBody,
|
||||||
source: request,
|
source: request,
|
||||||
secure,
|
secure,
|
||||||
// Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the
|
// Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the proxy is
|
||||||
// proxy is trusted, and take its first hop — an untrusted XFF is client-spoofable, and
|
// trusted, and take its first hop — an untrusted XFF is client-spoofable, and there's no socket
|
||||||
// there's no socket peer address to fall back to on the fetch path, so the untrusted case
|
// peer address to fall back to on the fetch path, so the untrusted case is simply ''.
|
||||||
// is simply ''.
|
|
||||||
ip: opts?.trustProxy
|
ip: opts?.trustProxy
|
||||||
? String(headers['x-forwarded-for'] ?? '')
|
? String(headers['x-forwarded-for'] ?? '')
|
||||||
.split(',')[0]
|
.split(',')[0]
|
||||||
.trim()
|
.trim()
|
||||||
: '',
|
: '',
|
||||||
},
|
});
|
||||||
// Already computed above for the shed-503 path; handing it down keeps `cors.origins` to
|
|
||||||
// one call per request.
|
|
||||||
injected,
|
|
||||||
);
|
|
||||||
} finally {
|
} finally {
|
||||||
// Release when routing/handling finishes, not when a returned stream finishes.
|
// Release when routing/handling finishes, not when a returned stream finishes.
|
||||||
// Long-lived streams therefore do not permanently consume the request budget.
|
// Long-lived streams therefore do not permanently consume the request budget.
|
||||||
@@ -272,6 +205,6 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return outcomeToResponse(result, opts?.bus, correlation);
|
return outcomeToResponse(result);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
+3
-9
@@ -1,6 +1,5 @@
|
|||||||
import { isHttpError } from '../signals';
|
import { isHttpError } from '../signals';
|
||||||
import type { Bus } from '../bus';
|
import type { Bus } from '../bus';
|
||||||
import { correlateRequest } from './core';
|
|
||||||
import { matchPattern } from './router';
|
import { matchPattern } from './router';
|
||||||
import type { WsRouteDef } from './types';
|
import type { WsRouteDef } from './types';
|
||||||
|
|
||||||
@@ -110,11 +109,6 @@ export async function runWsConnection(
|
|||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const { closer } = trackConnection(socket, streams);
|
const { closer } = trackConnection(socket, streams);
|
||||||
const name = route.def.pattern;
|
const name = route.def.pattern;
|
||||||
// Derived here rather than handed down: an upgrade is an HTTP request with headers like any
|
|
||||||
// other, so it adopts an `x-request-id` from a gateway and carries `traceparent` through by the
|
|
||||||
// same rule. `runWsConnection` is the only place a ws connection is correlated, which is what
|
|
||||||
// keeps one identity per connection instead of one per emitter.
|
|
||||||
const trace = { name, route: name, transport: 'ws', ...correlateRequest(request.headers) };
|
|
||||||
let iterator: AsyncIterator<unknown> | undefined;
|
let iterator: AsyncIterator<unknown> | undefined;
|
||||||
|
|
||||||
const onAbort = () => {
|
const onAbort = () => {
|
||||||
@@ -123,7 +117,7 @@ export async function runWsConnection(
|
|||||||
};
|
};
|
||||||
|
|
||||||
socket.abort.addEventListener('abort', onAbort, { once: true });
|
socket.abort.addEventListener('abort', onAbort, { once: true });
|
||||||
bus?.emit('stream:open', trace);
|
bus?.emit('stream:open', { name });
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const outbound = await route.def.open({
|
const outbound = await route.def.open({
|
||||||
@@ -135,9 +129,9 @@ export async function runWsConnection(
|
|||||||
iterator = outbound[Symbol.asyncIterator]();
|
iterator = outbound[Symbol.asyncIterator]();
|
||||||
await pumpOutbound(socket, iterator);
|
await pumpOutbound(socket, iterator);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
bus?.emit('stream:error', { ...trace, error: err });
|
bus?.emit('stream:error', { name, error: err });
|
||||||
closeOnError(socket, err);
|
closeOnError(socket, err);
|
||||||
} finally {
|
} finally {
|
||||||
bus?.emit('stream:close', trace);
|
bus?.emit('stream:close', { name });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+3
-4
@@ -60,7 +60,7 @@ export {
|
|||||||
|
|
||||||
// Bus & flow
|
// Bus & flow
|
||||||
export { Bus } from './bus';
|
export { Bus } from './bus';
|
||||||
export type { LifecycleEvent, EventPayload, Correlation, Events } from './bus';
|
export type { LifecycleEvent, EventPayload, Correlation } from './bus';
|
||||||
export { flow, Flow } from './flow';
|
export { flow, Flow } from './flow';
|
||||||
export type { StepFn, CompiledFlow } from './flow';
|
export type { StepFn, CompiledFlow } from './flow';
|
||||||
|
|
||||||
@@ -76,12 +76,11 @@ export type { Logger, LogLevel, LogFields } from './logger';
|
|||||||
export { channel, isAsyncIterable } from './channel';
|
export { channel, isAsyncIterable } from './channel';
|
||||||
export type { Channel } from './channel';
|
export type { Channel } from './channel';
|
||||||
export { Rooms } from './rooms';
|
export { Rooms } from './rooms';
|
||||||
export { sse, isSseEvent, sseEncoder, ndjsonEncoder } from './encoders';
|
export { sseEncoder, ndjsonEncoder } from './encoders';
|
||||||
export type { StreamEncoder, SseEvent, SseFields } from './encoders';
|
export type { StreamEncoder } from './encoders';
|
||||||
|
|
||||||
// HTTP, security & validation
|
// HTTP, security & validation
|
||||||
export type { RequestLimits } from './http';
|
export type { RequestLimits } from './http';
|
||||||
export { UNMATCHED_ROUTE } from './http/core';
|
|
||||||
export type { TlsOptions, CorsOptions, SecurityOptions } from './security';
|
export type { TlsOptions, CorsOptions, SecurityOptions } from './security';
|
||||||
export type { UploadedFile, MultipartBody } from './multipart';
|
export type { UploadedFile, MultipartBody } from './multipart';
|
||||||
export type { StandardSchemaV1 } from './standard-schema';
|
export type { StandardSchemaV1 } from './standard-schema';
|
||||||
|
|||||||
+8
-27
@@ -3,7 +3,6 @@ import { renderError, type ErrorRenderer } from './transformers';
|
|||||||
import { isAsyncIterable } from './channel';
|
import { isAsyncIterable } from './channel';
|
||||||
import type { TransformerFn, Transport } from './metadata';
|
import type { TransformerFn, Transport } from './metadata';
|
||||||
import { TransportMismatchError } from './signals';
|
import { TransportMismatchError } from './signals';
|
||||||
import type { Logger } from './logger';
|
|
||||||
|
|
||||||
/** A single step in a request pipeline: a named unit whose `run` merges its output into the shared context. */
|
/** A single step in a request pipeline: a named unit whose `run` merges its output into the shared context. */
|
||||||
export interface PipelineStep {
|
export interface PipelineStep {
|
||||||
@@ -114,10 +113,9 @@ export async function runPipeline(args: {
|
|||||||
bus: Bus;
|
bus: Bus;
|
||||||
transport: Transport;
|
transport: Transport;
|
||||||
onError?: ErrorRenderer;
|
onError?: ErrorRenderer;
|
||||||
logger?: Logger;
|
|
||||||
correlation?: Correlation;
|
correlation?: Correlation;
|
||||||
}): Promise<PipelineResult> {
|
}): Promise<PipelineResult> {
|
||||||
const { steps, handler, transformer, seed, bus, transport, onError, logger, correlation = {} } = args;
|
const { steps, handler, transformer, seed, bus, transport, onError, correlation = {} } = args;
|
||||||
// context is intentionally `any`: each step merges arbitrary keys into the accumulator
|
// context is intentionally `any`: each step merges arbitrary keys into the accumulator
|
||||||
let context: any = { ...seed };
|
let context: any = { ...seed };
|
||||||
|
|
||||||
@@ -139,33 +137,16 @@ export async function runPipeline(args: {
|
|||||||
const transformed = transformer(result);
|
const transformed = transformer(result);
|
||||||
return { status: transformed.status ?? 200, headers: transformed.headers ?? {}, body: transformed.body };
|
return { status: transformed.status ?? 200, headers: transformed.headers ?? {}, body: transformed.body };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const req = (context.req ?? {}) as { method?: string; url?: string; headers?: Record<string, unknown> };
|
|
||||||
let status: number | undefined;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const rendered = renderError(
|
|
||||||
error,
|
|
||||||
{ method: req.method ?? '', url: req.url ?? '', headers: (context.headers ?? req.headers ?? {}) as never },
|
|
||||||
onError,
|
|
||||||
logger,
|
|
||||||
);
|
|
||||||
status = rendered.status;
|
|
||||||
return rendered;
|
|
||||||
} finally {
|
|
||||||
// Both fire for a failing step, deliberately: `request:step:error` above marks the span,
|
// Both fire for a failing step, deliberately: `request:step:error` above marks the span,
|
||||||
// this marks the trace. A tracing exporter needs each, and only emitting the outer one is
|
// this marks the trace. A tracing exporter needs each, and only emitting the outer one is
|
||||||
// what produces a trace that says a request failed without saying where.
|
// what produces a trace that says a request failed without saying where.
|
||||||
//
|
|
||||||
// Emitted after the render rather than before it, because the status is only decided there:
|
|
||||||
// `onError` may turn any throw into any status, so deriving one from the error would be a
|
|
||||||
// guess that a custom renderer makes wrong.
|
|
||||||
//
|
|
||||||
// In `finally` rather than after the call, so that nothing between here and the emit can cost
|
|
||||||
// us the only record that a request failed. `renderError` already contains a throwing
|
|
||||||
// `onError` and degrades to the built-in rendering, so this is a second line rather than the
|
|
||||||
// first — but a failure whose reporting is what broke is the worst one to lose.
|
|
||||||
if (bus.hasListeners('request:failed'))
|
if (bus.hasListeners('request:failed'))
|
||||||
bus.emit('request:failed', { name: correlation.route ?? 'pipeline', error, status, ...correlation });
|
bus.emit('request:failed', { name: correlation.route ?? 'pipeline', error, ...correlation });
|
||||||
}
|
const req = (context.req ?? {}) as { method?: string; url?: string; headers?: Record<string, unknown> };
|
||||||
|
return renderError(
|
||||||
|
error,
|
||||||
|
{ method: req.method ?? '', url: req.url ?? '', headers: (context.headers ?? req.headers ?? {}) as never },
|
||||||
|
onError,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+1
-12
@@ -14,18 +14,7 @@ export interface ScopeNode {
|
|||||||
export interface ScopeApi {
|
export interface ScopeApi {
|
||||||
add(node: ScopeNode): void;
|
add(node: ScopeNode): void;
|
||||||
}
|
}
|
||||||
/**
|
/** The capabilities handed to a plugin: event subscription, node registration, and teardown. */
|
||||||
* The capabilities handed to a plugin: event subscription, node registration, and teardown.
|
|
||||||
*
|
|
||||||
* This is the home for observation, and the reason is the pairing: `bus.on` arrives next to
|
|
||||||
* `onShutdown`, so whatever a plugin subscribes to it can also release. A graph node can reach the
|
|
||||||
* same read-only slice through `@needs('events')`, but it gets the subscribe half without the
|
|
||||||
* unsubscribe half — and a `@Step` reaching it would register a listener per request.
|
|
||||||
*
|
|
||||||
* The `Bus` itself is deliberately not here and is not a graph token either: handing over `emit`
|
|
||||||
* would turn a one-way observation channel into something any node can forge events on.
|
|
||||||
* `@needs('bus')` fails at boot and says so.
|
|
||||||
*/
|
|
||||||
export interface PluginApi {
|
export interface PluginApi {
|
||||||
bus: { on: Bus['on'] };
|
bus: { on: Bus['on'] };
|
||||||
scope: ScopeApi;
|
scope: ScopeApi;
|
||||||
|
|||||||
+2
-6
@@ -128,13 +128,9 @@ export function resolveCors(
|
|||||||
export function corsPreflightHeaders(
|
export function corsPreflightHeaders(
|
||||||
opts: CorsOptions,
|
opts: CorsOptions,
|
||||||
req: { headers: Record<string, string | string[] | undefined> },
|
req: { headers: Record<string, string | string[] | undefined> },
|
||||||
resolved?: Headers,
|
logger?: Logger,
|
||||||
): Headers {
|
): Headers {
|
||||||
// The caller has almost always resolved CORS already, one layer up, to seed the headers every
|
const headers = resolveCors(opts, req, logger);
|
||||||
// response carries. Re-deriving here would consult `origins` a second time for the same request —
|
|
||||||
// and `origins` may be a predicate doing a network lookup. Copied rather than used in place: the
|
|
||||||
// preflight-only keys below belong to this 204, not to the shared object.
|
|
||||||
const headers: Headers = { ...resolved };
|
|
||||||
if (!headers['access-control-allow-origin']) return headers; // origin not allowed → bare 204
|
if (!headers['access-control-allow-origin']) return headers; // origin not allowed → bare 204
|
||||||
headers['access-control-allow-methods'] = (opts.methods ?? ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']).join(
|
headers['access-control-allow-methods'] = (opts.methods ?? ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']).join(
|
||||||
', ',
|
', ',
|
||||||
|
|||||||
+2
-29
@@ -1,7 +1,6 @@
|
|||||||
import { isHttpError, ValidationError } from './signals';
|
import { isHttpError, ValidationError } from './signals';
|
||||||
import type { TransformerFn } from './metadata';
|
import type { TransformerFn } from './metadata';
|
||||||
import { flattenPath } from './standard-schema';
|
import { flattenPath } from './standard-schema';
|
||||||
import type { Logger } from './logger';
|
|
||||||
|
|
||||||
/** A ready-to-send HTTP response. */
|
/** A ready-to-send HTTP response. */
|
||||||
export interface ErrorResponse {
|
export interface ErrorResponse {
|
||||||
@@ -61,32 +60,6 @@ export function errorToResponse(error: unknown): ErrorResponse {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Render an error through the optional user {@link ErrorRenderer}, falling back to {@link errorToResponse}. */
|
/** Render an error through the optional user {@link ErrorRenderer}, falling back to {@link errorToResponse}. */
|
||||||
export function renderError(
|
export function renderError(error: unknown, req: ErrorRequest, onError?: ErrorRenderer): ErrorResponse {
|
||||||
error: unknown,
|
return onError?.(error, req) ?? errorToResponse(error);
|
||||||
req: ErrorRequest,
|
|
||||||
onError?: ErrorRenderer,
|
|
||||||
logger?: Logger,
|
|
||||||
): ErrorResponse {
|
|
||||||
if (!onError) return errorToResponse(error);
|
|
||||||
|
|
||||||
// `onError` is user code, it runs on the request path, and it runs *after something already went
|
|
||||||
// wrong* — which makes an unguarded throw here the worst-timed crash in the framework: the error
|
|
||||||
// occurs, the code written to report it fails, and the process ends instead of degrading.
|
|
||||||
//
|
|
||||||
// It is also easy to reach. This renders the 404 too, not just a thrown handler, so an app with a
|
|
||||||
// custom renderer and no matching route is one request away from exiting.
|
|
||||||
//
|
|
||||||
// A renderer that throws falls back to the built-in rendering, which is exactly what the option
|
|
||||||
// overrides and therefore the honest thing to fall back to: the original error still gets its
|
|
||||||
// response. The renderer's own failure is reported separately, because it is a different error
|
|
||||||
// from the request's and a reader chasing the wrong one loses an afternoon.
|
|
||||||
try {
|
|
||||||
return onError(error, req) ?? errorToResponse(error);
|
|
||||||
} catch (rendererError) {
|
|
||||||
logger?.error('createApp({ onError }) threw while rendering — falling back to the built-in renderer', {
|
|
||||||
err: rendererError instanceof Error ? rendererError.message : String(rendererError),
|
|
||||||
rendering: error instanceof Error ? error.message : String(error),
|
|
||||||
});
|
|
||||||
return errorToResponse(error);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
+2
-6
@@ -603,11 +603,7 @@ describe('rooms auto-provide', () => {
|
|||||||
expect(await fetch(`http://127.0.0.1:${port}/api/r/x`).then((r) => r.json())).toEqual({ ok: true });
|
expect(await fetch(`http://127.0.0.1:${port}/api/r/x`).then((r) => r.json())).toEqual({ ok: true });
|
||||||
s.close();
|
s.close();
|
||||||
});
|
});
|
||||||
// This used to be allowed, and the user's provider silently replaced the framework's. The same
|
it('a user-declared rooms provider wins (no duplicate-name throw)', () => {
|
||||||
// held for `logger`, where every `@needs('logger')` in the app then got something that was not
|
|
||||||
// the logger core writes to — a divergence discovered from a log line that never appeared.
|
|
||||||
// Framework token names are reserved now, and taking one is a boot error.
|
|
||||||
it('refuses a user-declared rooms provider instead of silently replacing the built-in', () => {
|
|
||||||
@Provider({ provides: 'rooms' })
|
@Provider({ provides: 'rooms' })
|
||||||
class MyRooms {
|
class MyRooms {
|
||||||
provide() {
|
provide() {
|
||||||
@@ -622,7 +618,7 @@ describe('rooms auto-provide', () => {
|
|||||||
}
|
}
|
||||||
@Module({ mountpoint: '/api', providers: [MyRooms], controllers: [Ctl] })
|
@Module({ mountpoint: '/api', providers: [MyRooms], controllers: [Ctl] })
|
||||||
class M {}
|
class M {}
|
||||||
expect(() => createApp({ modules: [M] })).toThrow(/'rooms' is reserved by the framework/);
|
expect(() => createApp({ modules: [M] })).not.toThrow();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -76,46 +76,3 @@ describe('renderMarkdown', () => {
|
|||||||
expect(md.indexOf('fastify')).toBeLessThan(md.indexOf('green-tea')); // fastify (50k) before green-tea (42k)
|
expect(md.indexOf('fastify')).toBeLessThan(md.indexOf('green-tea')); // fastify (50k) before green-tea (42k)
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('renderMarkdown runtime matrix', () => {
|
|
||||||
const base = {
|
|
||||||
env: { date: '2026-09-01', commit: 'abc1234', node: 'v22', os: 'darwin', cpu: 'M4', ram: '69 GB', pinned: false },
|
|
||||||
config: { conns: 100, duration: 10, runs: 5, warmup: 1, pipelining: 1 },
|
|
||||||
scenarios: [],
|
|
||||||
stepScaling: [],
|
|
||||||
secureCost: [],
|
|
||||||
};
|
|
||||||
|
|
||||||
it('renders one column per runtime and one row per scenario', () => {
|
|
||||||
const md = renderMarkdown({
|
|
||||||
...base,
|
|
||||||
runtimes: [
|
|
||||||
{ runtime: 'node', scenario: 'JSON hello', reqSec: 90_000 },
|
|
||||||
{ runtime: 'bun', scenario: 'JSON hello', reqSec: 120_000 },
|
|
||||||
],
|
|
||||||
} as never);
|
|
||||||
|
|
||||||
expect(md).toContain('## green-tea across runtimes');
|
|
||||||
expect(md).toContain('| Scenario | node | bun |');
|
|
||||||
expect(md).toContain('| JSON hello | 90,000 | 120,000 |');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('marks a runtime that produced no number rather than printing a zero', () => {
|
|
||||||
// A skipped runtime must not read as "it ran and scored nothing".
|
|
||||||
const md = renderMarkdown({
|
|
||||||
...base,
|
|
||||||
runtimes: [
|
|
||||||
{ runtime: 'node', scenario: 'JSON hello', reqSec: 90_000 },
|
|
||||||
{ runtime: 'deno', scenario: 'Route param', reqSec: 80_000 },
|
|
||||||
],
|
|
||||||
} as never);
|
|
||||||
|
|
||||||
expect(md).toContain('| JSON hello | 90,000 | — |');
|
|
||||||
expect(md).toContain('| Route param | — | 80,000 |');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('omits the section entirely when no runtime was measured', () => {
|
|
||||||
expect(renderMarkdown({ ...base, runtimes: [] } as never)).not.toContain('across runtimes');
|
|
||||||
expect(renderMarkdown(base as never)).not.toContain('across runtimes');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,205 +0,0 @@
|
|||||||
// Independent providers boot concurrently; dependent ones still wait.
|
|
||||||
//
|
|
||||||
// The graph already proved which providers cannot constrain each other — that is what the topo
|
|
||||||
// sort *is*. Booting them one at a time charged every app the sum of its providers' latencies
|
|
||||||
// instead of its longest chain, for no ordering anyone declared.
|
|
||||||
//
|
|
||||||
// Timing is asserted structurally rather than by clock: "all three entered before any left" is
|
|
||||||
// the same claim as "they overlapped" and does not get flaky on a loaded CI box.
|
|
||||||
import 'reflect-metadata';
|
|
||||||
import { describe, expect, it, vi } from 'vitest';
|
|
||||||
import { Get, Module, Provider, Route, type Ctor } from '../src/metadata';
|
|
||||||
import { createApp } from '../src/app';
|
|
||||||
import type { Logger } from '../src/logger';
|
|
||||||
|
|
||||||
const silentLogger = (): Logger => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() });
|
|
||||||
const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
|
|
||||||
|
|
||||||
@Route('/')
|
|
||||||
class Ctl {
|
|
||||||
@Get('/ping') ping() {
|
|
||||||
return { ok: true };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Boots the app by serving one request — providers are lazy until something is actually served. */
|
|
||||||
async function boot(module: Ctor, logger = silentLogger()): Promise<void> {
|
|
||||||
const app = createApp({ modules: [module], logger });
|
|
||||||
await app.fetch(new Request('http://x/ping'));
|
|
||||||
await app.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('provider boot concurrency', () => {
|
|
||||||
it('overlaps providers that do not depend on each other', async () => {
|
|
||||||
const log: string[] = [];
|
|
||||||
|
|
||||||
const independent = (name: string): Ctor => {
|
|
||||||
@Provider({ provides: name })
|
|
||||||
class P {
|
|
||||||
async provide() {
|
|
||||||
log.push(`${name}:in`);
|
|
||||||
await sleep(10);
|
|
||||||
log.push(`${name}:out`);
|
|
||||||
return { [name]: name };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return P;
|
|
||||||
};
|
|
||||||
|
|
||||||
@Module({ mountpoint: '/', controllers: [Ctl], providers: [independent('a'), independent('b'), independent('c')] })
|
|
||||||
class M {}
|
|
||||||
await boot(M);
|
|
||||||
|
|
||||||
// Serial boot gives a:in a:out b:in … — every entry preceded by the previous exit.
|
|
||||||
expect(log.slice(0, 3)).toEqual(['a:in', 'b:in', 'c:in']);
|
|
||||||
expect(log).toHaveLength(6);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('still waits for a provider its dependant needs', async () => {
|
|
||||||
const log: string[] = [];
|
|
||||||
|
|
||||||
@Provider({ provides: 'base' })
|
|
||||||
class Base {
|
|
||||||
async provide() {
|
|
||||||
log.push('base:in');
|
|
||||||
await sleep(10);
|
|
||||||
log.push('base:out');
|
|
||||||
return { base: 1 };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Provider({ provides: 'derived', needs: ['base'] })
|
|
||||||
class Derived {
|
|
||||||
provide(ctx: { base: number }) {
|
|
||||||
log.push('derived:in');
|
|
||||||
return { derived: ctx.base + 1 };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Declared out of order on purpose: the wait is the graph's doing, not the array's.
|
|
||||||
@Module({ mountpoint: '/', controllers: [Ctl], providers: [Derived, Base] })
|
|
||||||
class M {}
|
|
||||||
await boot(M);
|
|
||||||
|
|
||||||
expect(log).toEqual(['base:in', 'base:out', 'derived:in']);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('gives a dependant every value from its level, not just the one that finished first', async () => {
|
|
||||||
@Provider({ provides: 'slow' })
|
|
||||||
class Slow {
|
|
||||||
async provide() {
|
|
||||||
await sleep(15);
|
|
||||||
return { slow: 'slow' };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Provider({ provides: 'fast' })
|
|
||||||
class Fast {
|
|
||||||
provide() {
|
|
||||||
return { fast: 'fast' };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let seen: Record<string, unknown> = {};
|
|
||||||
@Provider({ provides: 'joined', needs: ['slow', 'fast'] })
|
|
||||||
class Joined {
|
|
||||||
provide(ctx: Record<string, unknown>) {
|
|
||||||
seen = { slow: ctx.slow, fast: ctx.fast };
|
|
||||||
return { joined: true };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Module({ mountpoint: '/', controllers: [Ctl], providers: [Slow, Fast, Joined] })
|
|
||||||
class M {}
|
|
||||||
await boot(M);
|
|
||||||
|
|
||||||
expect(seen).toEqual({ slow: 'slow', fast: 'fast' });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('tears down in reverse boot order even though boot is concurrent', async () => {
|
|
||||||
const disposed: string[] = [];
|
|
||||||
|
|
||||||
const independent = (name: string, delay: number): Ctor => {
|
|
||||||
@Provider({ provides: name })
|
|
||||||
class P {
|
|
||||||
async provide() {
|
|
||||||
await sleep(delay);
|
|
||||||
return { [name]: name };
|
|
||||||
}
|
|
||||||
dispose() {
|
|
||||||
disposed.push(name);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return P;
|
|
||||||
};
|
|
||||||
|
|
||||||
// `c` finishes first and `a` last — completion order is the reverse of declaration order, so a
|
|
||||||
// teardown registered as each one lands would come out in a different order than this.
|
|
||||||
@Module({
|
|
||||||
mountpoint: '/',
|
|
||||||
controllers: [Ctl],
|
|
||||||
providers: [independent('a', 20), independent('b', 10), independent('c', 1)],
|
|
||||||
})
|
|
||||||
class M {}
|
|
||||||
await boot(M);
|
|
||||||
|
|
||||||
expect(disposed).toEqual(['c', 'b', 'a']);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('fails the boot on a required provider, and still registers its siblings for teardown', async () => {
|
|
||||||
const disposed: string[] = [];
|
|
||||||
|
|
||||||
@Provider({ provides: 'ok' })
|
|
||||||
class Ok {
|
|
||||||
async provide() {
|
|
||||||
await sleep(10); // still in flight when its sibling rejects
|
|
||||||
return { ok: true };
|
|
||||||
}
|
|
||||||
dispose() {
|
|
||||||
disposed.push('ok');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Provider({ provides: 'broken' })
|
|
||||||
class Broken {
|
|
||||||
provide(): never {
|
|
||||||
throw new Error('no pool');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Module({ mountpoint: '/', controllers: [Ctl], providers: [Ok, Broken] })
|
|
||||||
class M {}
|
|
||||||
const app = createApp({ modules: [M], logger: silentLogger() });
|
|
||||||
|
|
||||||
await expect(app.fetch(new Request('http://x/ping'))).rejects.toThrow("provider 'broken' failed: no pool");
|
|
||||||
// The sibling booted — it was already in flight — so whatever it opened has to be closeable.
|
|
||||||
await app.close();
|
|
||||||
expect(disposed).toEqual(['ok']);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('degrades an optional provider without taking its level down', async () => {
|
|
||||||
const logger = silentLogger();
|
|
||||||
|
|
||||||
@Provider({ provides: 'flaky', optional: true })
|
|
||||||
class Flaky {
|
|
||||||
provide(): never {
|
|
||||||
throw new Error('nope');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Provider({ provides: 'solid' })
|
|
||||||
class Solid {
|
|
||||||
provide() {
|
|
||||||
return { solid: true };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Module({ mountpoint: '/', controllers: [Ctl], providers: [Flaky, Solid] })
|
|
||||||
class M {}
|
|
||||||
const app = createApp({ modules: [M], logger });
|
|
||||||
await app.fetch(new Request('http://x/ping'));
|
|
||||||
|
|
||||||
expect(app.degraded()).toEqual(['flaky']);
|
|
||||||
await app.close();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
// The three legitimate ways to reach the bus, exercised together in one app.
|
|
||||||
//
|
|
||||||
// `bus` became a reserved name and the `Bus` itself is still not a graph token, so this file's job
|
|
||||||
// is to prove that what closed is only the wrong door: observation from outside, from a plugin and
|
|
||||||
// from inside the graph all still work, and only `emit` stays where it was.
|
|
||||||
import 'reflect-metadata';
|
|
||||||
import { describe, it, expect } from 'vitest';
|
|
||||||
import { createApp, Route, Get, Module, needs } from '../src/index';
|
|
||||||
import type { Events, Plugin } from '../src/index';
|
|
||||||
|
|
||||||
@Route('/b')
|
|
||||||
class Ctl {
|
|
||||||
@Get('/x') x(@needs('events') events: Events) {
|
|
||||||
// Reaching it per request is allowed; *subscribing* per request is the thing the docs warn
|
|
||||||
// about, and nothing here does that.
|
|
||||||
return { hasOn: typeof events.on === 'function' };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('reaching the bus', () => {
|
|
||||||
it('works from outside, from a plugin and from the graph, all at once', async () => {
|
|
||||||
const fromOutside: string[] = [];
|
|
||||||
const fromPlugin: string[] = [];
|
|
||||||
|
|
||||||
const observer: Plugin = (api) => {
|
|
||||||
api.bus.on('request:end', (e) => fromPlugin.push(e.route ?? ''));
|
|
||||||
};
|
|
||||||
|
|
||||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
|
||||||
class M {}
|
|
||||||
|
|
||||||
const app = createApp({ modules: [M], plugins: [observer] });
|
|
||||||
// 1. from outside: the public `app.bus`, which keeps `emit` too.
|
|
||||||
app.bus.on('request:end', (e) => fromOutside.push(e.route ?? ''));
|
|
||||||
|
|
||||||
// 3. from the graph: the handler receives `events` and reports its shape.
|
|
||||||
const res = await app.fetch(new Request('http://x/b/x'));
|
|
||||||
|
|
||||||
expect(await res.json()).toEqual({ hasOn: true });
|
|
||||||
expect(fromOutside).toEqual(['/b/x']);
|
|
||||||
expect(fromPlugin).toEqual(['/b/x']);
|
|
||||||
|
|
||||||
await app.close();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('keeps emit outside the graph and outside plugins, and only there', async () => {
|
|
||||||
let injected: Events | undefined;
|
|
||||||
const seen: string[] = [];
|
|
||||||
|
|
||||||
@Route('/e')
|
|
||||||
class Grab {
|
|
||||||
@Get('/x') x(@needs('events') events: Events) {
|
|
||||||
injected = events;
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@Module({ mountpoint: '/', controllers: [Grab] })
|
|
||||||
class M {}
|
|
||||||
|
|
||||||
const app = createApp({ modules: [M] });
|
|
||||||
await app.fetch(new Request('http://x/e/x'));
|
|
||||||
|
|
||||||
// The graph's slice cannot forge an event...
|
|
||||||
expect((injected as unknown as { emit?: unknown }).emit).toBeUndefined();
|
|
||||||
|
|
||||||
// ...while the application that owns the app still can, which is what `app.bus` is for.
|
|
||||||
app.bus.on('plugin:mounted', (e) => seen.push(e.name));
|
|
||||||
app.bus.emit('plugin:mounted', { name: 'from the owner' });
|
|
||||||
expect(seen).toEqual(['from the owner']);
|
|
||||||
|
|
||||||
await app.close();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -80,76 +80,3 @@ describe('HttpError body', () => {
|
|||||||
server.close();
|
server.close();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// `onError` is user code, on the request path, running *after something already went wrong*. An
|
|
||||||
// unguarded throw here was the worst-timed crash in the framework: the error occurs, the code
|
|
||||||
// written to report it fails, and the process ends instead of degrading. It was also easy to
|
|
||||||
// reach — the renderer produces the 404 too, so an app with a custom renderer and no matching
|
|
||||||
// route was one request away from exiting.
|
|
||||||
describe('an onError that throws', () => {
|
|
||||||
const exploding: ErrorRenderer = () => {
|
|
||||||
throw new Error('renderer exploded');
|
|
||||||
};
|
|
||||||
|
|
||||||
@Route('/x')
|
|
||||||
class Boom {
|
|
||||||
@Get('/boom') boom() {
|
|
||||||
throw new HttpError(503, 'Service Unavailable');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Module({ mountpoint: '/', controllers: [Boom] })
|
|
||||||
class BoomModule {}
|
|
||||||
|
|
||||||
it('falls back to the built-in rendering rather than losing the response', async () => {
|
|
||||||
const app = createApp({ modules: [BoomModule], onError: exploding });
|
|
||||||
const res = await app.fetch(new Request('http://x/x/boom'));
|
|
||||||
|
|
||||||
// The original error still gets its answer: the fallback is the rendering `onError` overrides.
|
|
||||||
expect(res.status).toBe(503);
|
|
||||||
expect(await res.json()).toEqual({ error: 'Service Unavailable' });
|
|
||||||
});
|
|
||||||
|
|
||||||
// The path that needed no thrown handler at all.
|
|
||||||
it('survives a 404, which the renderer also produces', async () => {
|
|
||||||
const app = createApp({ modules: [BoomModule], onError: exploding });
|
|
||||||
const res = await app.fetch(new Request('http://x/nothing-here'));
|
|
||||||
|
|
||||||
expect(res.status).toBe(404);
|
|
||||||
expect(await res.json()).toEqual({ error: 'Not Found' });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('reports the renderer as the thing that failed, not the request', async () => {
|
|
||||||
const logged: Array<{ msg: string; fields?: Record<string, unknown> }> = [];
|
|
||||||
const logger = {
|
|
||||||
debug() {},
|
|
||||||
info() {},
|
|
||||||
warn() {},
|
|
||||||
error(msg: string, fields?: Record<string, unknown>) {
|
|
||||||
logged.push({ msg, fields });
|
|
||||||
},
|
|
||||||
};
|
|
||||||
const app = createApp({ modules: [BoomModule], onError: exploding, logger });
|
|
||||||
|
|
||||||
await app.fetch(new Request('http://x/x/boom'));
|
|
||||||
|
|
||||||
expect(logged).toHaveLength(1);
|
|
||||||
expect(logged[0].msg).toMatch(/onError/);
|
|
||||||
// Both errors named, because a reader chasing the wrong one loses an afternoon.
|
|
||||||
expect(logged[0].fields?.err).toBe('renderer exploded');
|
|
||||||
expect(logged[0].fields?.rendering).toBe('Service Unavailable');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('answers over a real Node server instead of exiting the process', async () => {
|
|
||||||
const app = createApp({ modules: [BoomModule], onError: exploding });
|
|
||||||
const server = await app.listen(0);
|
|
||||||
const port = (server.address() as { port: number }).port;
|
|
||||||
|
|
||||||
const res = await fetch(`http://127.0.0.1:${port}/x/boom`);
|
|
||||||
expect(res.status).toBe(503);
|
|
||||||
// Still serving — the point of the whole test.
|
|
||||||
expect((await fetch(`http://127.0.0.1:${port}/nope`)).status).toBe(404);
|
|
||||||
|
|
||||||
await app.close();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
+1
-29
@@ -1,5 +1,5 @@
|
|||||||
import { describe, expect, it, test } from 'vitest';
|
import { describe, expect, it, test } from 'vitest';
|
||||||
import { topoSort, topoLevels, GraphNode, subgraphFor, nearest } from '../src/graph';
|
import { topoSort, GraphNode, subgraphFor, nearest } from '../src/graph';
|
||||||
|
|
||||||
const node = (name: string, needs: string[], provides: string[]): GraphNode =>
|
const node = (name: string, needs: string[], provides: string[]): GraphNode =>
|
||||||
({ name, needs, provides, origin: 'test' });
|
({ name, needs, provides, origin: 'test' });
|
||||||
@@ -42,34 +42,6 @@ describe('subgraphFor', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('topoLevels', () => {
|
|
||||||
const levels = (ordered: GraphNode[]): string[][] => topoLevels(ordered).map((l) => l.map((n) => n.name));
|
|
||||||
|
|
||||||
it('puts nodes that cannot constrain each other in the same level', () => {
|
|
||||||
expect(levels([N('a'), N('b'), N('c')])).toEqual([['a', 'b', 'c']]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('pushes a node past every producer it needs, not just its first', () => {
|
|
||||||
// `late` needs a depth-0 and a depth-1 node, so it belongs at 2 — taking the max, not the first.
|
|
||||||
const ordered = [N('config'), N('db', ['config']), N('late', ['config', 'db'])];
|
|
||||||
expect(levels(ordered)).toEqual([['config'], ['db'], ['late']]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('ignores needs nothing here produces, so a seed does not push a node down a level', () => {
|
|
||||||
expect(levels([N('a'), N('user', ['req', 'params'])])).toEqual([['a', 'user']]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('leaves no gaps, so every level has something to run', () => {
|
|
||||||
const ordered = topoSort([N('c', ['b']), N('a'), N('b', ['a']), N('solo')], []);
|
|
||||||
expect(topoLevels(ordered).every((level) => level.length > 0)).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('keeps every node exactly once', () => {
|
|
||||||
const ordered = topoSort([N('c', ['b']), N('a'), N('b', ['a']), N('solo')], []);
|
|
||||||
expect(topoLevels(ordered).flat().map((n) => n.name).sort()).toEqual(['a', 'b', 'c', 'solo']);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('nearest', () => {
|
describe('nearest', () => {
|
||||||
it('suggests a close candidate (edit distance <= 2)', () => {
|
it('suggests a close candidate (edit distance <= 2)', () => {
|
||||||
expect(nearest('usr', ['user', 'config', 'db'])).toBe('user');
|
expect(nearest('usr', ['user', 'config', 'db'])).toBe('user');
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { describe, expect, it, test, vi } from 'vitest';
|
import { describe, expect, it, test, vi } from 'vitest';
|
||||||
import * as net from 'node:net';
|
import * as net from 'node:net';
|
||||||
import { ServerResponse } from 'node:http';
|
|
||||||
import { once } from 'node:events';
|
import { once } from 'node:events';
|
||||||
import { Bus } from '../src/bus';
|
import { Bus } from '../src/bus';
|
||||||
import { matchRoute, parseQuery, createHttpServer } from '../src/http';
|
import { matchRoute, parseQuery, createHttpServer } from '../src/http';
|
||||||
@@ -385,80 +384,4 @@ describe('request hardening', () => {
|
|||||||
server.close();
|
server.close();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
// `origins` is a predicate because the shapes it exists for are lookups — an allowlist in Redis, a
|
|
||||||
// tenant query. Running one twice for a GET and three times for a preflight charges the caller's
|
|
||||||
// latency budget and their backend for an answer whose inputs did not change in between.
|
|
||||||
it('consults a cors.origins predicate once per request, not once per header computation', async () => {
|
|
||||||
let calls = 0;
|
|
||||||
const server = createHttpServer(
|
|
||||||
[{ method: 'GET', pattern: '/ping', transport: 'buffer', handler }],
|
|
||||||
[], undefined, undefined,
|
|
||||||
{ cors: { origins: () => { calls++; return true; } } },
|
|
||||||
);
|
|
||||||
await new Promise<void>((r) => server.listen(0, r));
|
|
||||||
const origin = { origin: 'https://a.com' };
|
|
||||||
|
|
||||||
const plain = await fetch(`${getUrl(server)}/ping`, { headers: origin });
|
|
||||||
expect(plain.headers.get('access-control-allow-origin')).toBe('https://a.com');
|
|
||||||
expect(calls).toBe(1);
|
|
||||||
|
|
||||||
calls = 0;
|
|
||||||
const preflight = await fetch(`${getUrl(server)}/ping`, {
|
|
||||||
method: 'OPTIONS', headers: { ...origin, 'access-control-request-method': 'GET' },
|
|
||||||
});
|
|
||||||
expect(preflight.status).toBe(204);
|
|
||||||
expect(preflight.headers.get('access-control-allow-methods')).toContain('GET');
|
|
||||||
expect(preflight.headers.get('access-control-allow-origin')).toBe('https://a.com');
|
|
||||||
expect(calls).toBe(1);
|
|
||||||
|
|
||||||
// No Origin header never reaches the predicate at all — that part was already right.
|
|
||||||
calls = 0;
|
|
||||||
await fetch(`${getUrl(server)}/ping`);
|
|
||||||
expect(calls).toBe(0);
|
|
||||||
|
|
||||||
server.close();
|
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
// `maxConcurrentRequests` is opt-in and unlimited by default, so the overwhelming majority of
|
|
||||||
// apps used to pay a closure and an EventEmitter registration per request for a feature that is
|
|
||||||
// off. Small in absolute terms, and on the hot path, which is why it is asserted rather than
|
|
||||||
// trusted: a `res.once('close')` is exactly the kind of line that comes back.
|
|
||||||
it('registers no per-request close listener when no request budget is configured', async () => {
|
|
||||||
const closeListeners: string[] = [];
|
|
||||||
// Typed loosely on purpose: `once` is an overloaded EventEmitter signature and the spy only
|
|
||||||
// needs to see the event name before handing the call straight back to the real one.
|
|
||||||
const proto = ServerResponse.prototype as unknown as {
|
|
||||||
once(event: string | symbol, listener: (...args: unknown[]) => void): unknown;
|
|
||||||
};
|
|
||||||
const realOnce = proto.once;
|
|
||||||
const spy = vi.spyOn(proto, 'once').mockImplementation(function (this: unknown, event, listener) {
|
|
||||||
if (event === 'close') closeListeners.push('close');
|
|
||||||
return realOnce.call(this, event, listener);
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
|
||||||
const unlimited = createHttpServer([{ method: 'GET', pattern: '/ping', transport: 'buffer', handler }]);
|
|
||||||
await new Promise<void>((r) => unlimited.listen(0, r));
|
|
||||||
expect((await fetch(`${getUrl(unlimited)}/ping`)).status).toBe(200);
|
|
||||||
expect(closeListeners).toHaveLength(0);
|
|
||||||
unlimited.close();
|
|
||||||
|
|
||||||
// With a budget set, the listener is what releases the slot on a client disconnect, so it
|
|
||||||
// has to come back — the guard is about the unset case, not about dropping the feature.
|
|
||||||
const limited = createHttpServer(
|
|
||||||
[{ method: 'GET', pattern: '/ping', transport: 'buffer', handler }],
|
|
||||||
[], undefined, undefined,
|
|
||||||
{ limits: { maxConcurrentRequests: 4 } },
|
|
||||||
);
|
|
||||||
await new Promise<void>((r) => limited.listen(0, r));
|
|
||||||
expect((await fetch(`${getUrl(limited)}/ping`)).status).toBe(200);
|
|
||||||
expect(closeListeners.length).toBeGreaterThan(0);
|
|
||||||
limited.close();
|
|
||||||
} finally {
|
|
||||||
spy.mockRestore();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
});
|
||||||
@@ -1,185 +0,0 @@
|
|||||||
// The `request:start` / `request:end` pairing, asserted across every terminal path there is.
|
|
||||||
//
|
|
||||||
// The guarantee held by accident until `maxConcurrentRequests` arrived: `request:start` had a
|
|
||||||
// single emitter, so nothing could break it. It has more than one now, and a guarantee upheld by
|
|
||||||
// there being only one place to get it wrong is not a guarantee — it is a coincidence with good
|
|
||||||
// timing. This file is what makes the next terminal path fail loudly instead of quietly.
|
|
||||||
//
|
|
||||||
// Adding a response shape? Add a row. That is the whole maintenance contract.
|
|
||||||
import { describe, expect, it } from 'vitest';
|
|
||||||
import { Bus } from '../src/bus';
|
|
||||||
import { createHttpServer } from '../src/http';
|
|
||||||
import { buildFetch } from '../src/http/web';
|
|
||||||
|
|
||||||
interface Seen {
|
|
||||||
starts: string[];
|
|
||||||
ends: Array<{ requestId?: string; status?: number }>;
|
|
||||||
}
|
|
||||||
|
|
||||||
function watch(bus: Bus): Seen {
|
|
||||||
const seen: Seen = { starts: [], ends: [] };
|
|
||||||
bus.on('request:start', (e) => seen.starts.push(e.requestId ?? ''));
|
|
||||||
bus.on('request:end', (e) => seen.ends.push({ requestId: e.requestId, status: e.status }));
|
|
||||||
return seen;
|
|
||||||
}
|
|
||||||
|
|
||||||
const ok = async () => ({ status: 200, headers: {}, body: 'ok' });
|
|
||||||
const boom = async () => {
|
|
||||||
throw new Error('kaboom');
|
|
||||||
};
|
|
||||||
|
|
||||||
/** Every shape of request the framework can answer, and how to provoke it. */
|
|
||||||
const SHAPES: Array<{
|
|
||||||
name: string;
|
|
||||||
status: number;
|
|
||||||
routes: Parameters<typeof buildFetch>[0];
|
|
||||||
opts?: Parameters<typeof buildFetch>[1];
|
|
||||||
request: () => Request;
|
|
||||||
}> = [
|
|
||||||
{
|
|
||||||
name: 'matched handler',
|
|
||||||
status: 200,
|
|
||||||
routes: [{ method: 'GET', pattern: '/ok', transport: 'buffer', handler: ok }],
|
|
||||||
request: () => new Request('http://x/ok'),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'unmatched route',
|
|
||||||
status: 404,
|
|
||||||
routes: [{ method: 'GET', pattern: '/ok', transport: 'buffer', handler: ok }],
|
|
||||||
request: () => new Request('http://x/nope'),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'handler throws',
|
|
||||||
status: 500,
|
|
||||||
routes: [{ method: 'GET', pattern: '/boom', transport: 'buffer', handler: boom }],
|
|
||||||
request: () => new Request('http://x/boom'),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'body over maxBodyBytes',
|
|
||||||
status: 413,
|
|
||||||
routes: [{ method: 'POST', pattern: '/echo', transport: 'buffer', handler: ok }],
|
|
||||||
opts: { limits: { maxBodyBytes: 8 } },
|
|
||||||
request: () => new Request('http://x/echo', { method: 'POST', body: 'x'.repeat(500) }),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'CORS preflight',
|
|
||||||
status: 204,
|
|
||||||
routes: [{ method: 'GET', pattern: '/ok', transport: 'buffer', handler: ok }],
|
|
||||||
opts: { cors: { origins: '*' } },
|
|
||||||
request: () =>
|
|
||||||
new Request('http://x/ok', {
|
|
||||||
method: 'OPTIONS',
|
|
||||||
headers: { origin: 'https://a.com', 'access-control-request-method': 'GET' },
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
describe('every terminal path emits request:start before request:end', () => {
|
|
||||||
for (const shape of SHAPES) {
|
|
||||||
it(`${shape.name} → ${shape.status}`, async () => {
|
|
||||||
const bus = new Bus();
|
|
||||||
const seen = watch(bus);
|
|
||||||
const fetchHandler = buildFetch(shape.routes, { ...shape.opts, bus });
|
|
||||||
|
|
||||||
const res = await fetchHandler(shape.request());
|
|
||||||
|
|
||||||
expect(res.status).toBe(shape.status);
|
|
||||||
expect(seen.starts).toHaveLength(1);
|
|
||||||
expect(seen.ends).toHaveLength(1);
|
|
||||||
// Same request, not two that happened to arrive together — the id is what a consumer keys on.
|
|
||||||
expect(seen.ends[0].requestId).toBe(seen.starts[0]);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// The path that broke the pairing, and the reason this file exists. It never reaches `handle()`,
|
|
||||||
// so the emitter every row above goes through never sees it.
|
|
||||||
it('shed over maxConcurrentRequests → 503', async () => {
|
|
||||||
const bus = new Bus();
|
|
||||||
const seen = watch(bus);
|
|
||||||
let release!: () => void;
|
|
||||||
const blocked = new Promise<void>((r) => (release = r));
|
|
||||||
|
|
||||||
const fetchHandler = buildFetch(
|
|
||||||
[{ method: 'GET', pattern: '/slow', transport: 'buffer', handler: async () => (await blocked, ok()) }],
|
|
||||||
{ bus, limits: { maxConcurrentRequests: 1 } },
|
|
||||||
);
|
|
||||||
|
|
||||||
const first = fetchHandler(new Request('http://x/slow'));
|
|
||||||
const shed = await fetchHandler(new Request('http://x/slow'));
|
|
||||||
|
|
||||||
expect(shed.status).toBe(503);
|
|
||||||
release();
|
|
||||||
await first;
|
|
||||||
|
|
||||||
const shedPair = seen.ends.find((e) => e.status === 503)!;
|
|
||||||
expect(shedPair).toBeDefined();
|
|
||||||
expect(seen.starts).toContain(shedPair.requestId);
|
|
||||||
});
|
|
||||||
|
|
||||||
// The Node adapter sheds through its own code path, so passing on `buildFetch` proves nothing
|
|
||||||
// about it — the two were separate emitters before they shared one.
|
|
||||||
it('shed over maxConcurrentRequests → 503, on the Node adapter', async () => {
|
|
||||||
const bus = new Bus();
|
|
||||||
const seen = watch(bus);
|
|
||||||
let release!: () => void;
|
|
||||||
let started!: () => void;
|
|
||||||
const blocked = new Promise<void>((r) => (release = r));
|
|
||||||
const firstStarted = new Promise<void>((r) => (started = r));
|
|
||||||
|
|
||||||
const server = createHttpServer(
|
|
||||||
[
|
|
||||||
{
|
|
||||||
method: 'GET',
|
|
||||||
pattern: '/slow',
|
|
||||||
transport: 'buffer',
|
|
||||||
handler: async () => {
|
|
||||||
started();
|
|
||||||
await blocked;
|
|
||||||
return { status: 200, headers: {}, body: 'ok' };
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
[],
|
|
||||||
bus,
|
|
||||||
undefined,
|
|
||||||
{ limits: { maxConcurrentRequests: 1 } },
|
|
||||||
);
|
|
||||||
await new Promise<void>((r) => server.listen(0, r));
|
|
||||||
const url = `http://127.0.0.1:${(server.address() as { port: number }).port}/slow`;
|
|
||||||
|
|
||||||
const first = fetch(url);
|
|
||||||
await firstStarted;
|
|
||||||
const shed = await fetch(url);
|
|
||||||
|
|
||||||
expect(shed.status).toBe(503);
|
|
||||||
release();
|
|
||||||
await first;
|
|
||||||
|
|
||||||
const shedPair = seen.ends.find((e) => e.status === 503)!;
|
|
||||||
expect(shedPair).toBeDefined();
|
|
||||||
expect(seen.starts).toContain(shedPair.requestId);
|
|
||||||
server.close();
|
|
||||||
});
|
|
||||||
|
|
||||||
// The invariant stated as a count rather than per row. Scoped to the enumerated shapes on
|
|
||||||
// purpose — the two shed paths have their own tests above, because they are the ones that need
|
|
||||||
// a blocked handler to provoke and the ones that broke it in the first place.
|
|
||||||
it('leaves no enumerated shape with an end whose start is missing', async () => {
|
|
||||||
const bus = new Bus();
|
|
||||||
const seen = watch(bus);
|
|
||||||
const fetchHandler = buildFetch(
|
|
||||||
[{ method: 'GET', pattern: '/ok', transport: 'buffer', handler: ok }],
|
|
||||||
{ bus, cors: { origins: '*' } },
|
|
||||||
);
|
|
||||||
|
|
||||||
for (const shape of SHAPES) {
|
|
||||||
const h = buildFetch(shape.routes, { ...shape.opts, bus });
|
|
||||||
await h(shape.request());
|
|
||||||
}
|
|
||||||
await fetchHandler(new Request('http://x/ok'));
|
|
||||||
|
|
||||||
expect(seen.ends).not.toHaveLength(0);
|
|
||||||
for (const end of seen.ends) expect(seen.starts).toContain(end.requestId);
|
|
||||||
expect(seen.starts).toHaveLength(seen.ends.length);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
import { describe, it, expect } from 'vitest';
|
import { describe, it, expect } from 'vitest';
|
||||||
import { createApp, Provider, Step, Route, Get, Module, needs } from '../src/index';
|
import { createApp, Provider, Step, Route, Get, Module, needs } from '../src/index';
|
||||||
import type { EventPayload } from '../src/bus';
|
import type { EventPayload } from '../src/bus';
|
||||||
import { UNMATCHED_ROUTE } from '../src/index';
|
|
||||||
|
|
||||||
@Provider({ provides: 'db' })
|
@Provider({ provides: 'db' })
|
||||||
class Db {
|
class Db {
|
||||||
@@ -176,100 +175,6 @@ describe('failure reporting', () => {
|
|||||||
expect(requestFailures).toHaveLength(1);
|
expect(requestFailures).toHaveLength(1);
|
||||||
expect(requestFailures[0].route).toBe('/bad/go');
|
expect(requestFailures[0].route).toBe('/bad/go');
|
||||||
expect(requestFailures[0].requestId).toBe(stepErrors[0].requestId);
|
expect(requestFailures[0].requestId).toBe(stepErrors[0].requestId);
|
||||||
// Carries what was actually sent, so an error counter can break down by status without
|
|
||||||
// joining back to the `request:end` that follows it.
|
|
||||||
expect(requestFailures[0].status).toBe(500);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// The cardinality trap: `name` carries the path that arrived, which is bounded by nothing at all.
|
|
||||||
// A consumer labelling on `route` gets one bounded series for every path that was never a route;
|
|
||||||
// one labelling on `name` gets a series per scanner probe.
|
|
||||||
it('labels an unmatched request with a bounded route, on both events', async () => {
|
|
||||||
const app = createApp({ modules: [BadModule] });
|
|
||||||
const unmatched: EventPayload[] = [];
|
|
||||||
const ends: EventPayload[] = [];
|
|
||||||
app.bus.on('route:unmatched', (p) => unmatched.push(p));
|
|
||||||
app.bus.on('request:end', (p) => ends.push(p));
|
|
||||||
|
|
||||||
for (const probe of ['/aaa', '/aab', '/aac']) await app.fetch(new Request(`http://x${probe}`));
|
|
||||||
|
|
||||||
expect(unmatched).toHaveLength(3);
|
|
||||||
expect(ends).toHaveLength(3);
|
|
||||||
// Three distinct paths, one series.
|
|
||||||
expect(new Set(unmatched.map((e) => e.route))).toEqual(new Set([UNMATCHED_ROUTE]));
|
|
||||||
expect(new Set(ends.map((e) => e.route))).toEqual(new Set([UNMATCHED_ROUTE]));
|
|
||||||
// `name` still carries the concrete path, which is what makes it useful in a log and unusable
|
|
||||||
// as a label.
|
|
||||||
expect(new Set(unmatched.map((e) => e.name)).size).toBe(3);
|
|
||||||
// It cannot collide with a pattern a user can declare.
|
|
||||||
expect(UNMATCHED_ROUTE.startsWith('/')).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('leaves a matched route labelled with its pattern, not the marker', async () => {
|
|
||||||
const app = createApp({ modules: [BadModule] });
|
|
||||||
const ends: EventPayload[] = [];
|
|
||||||
app.bus.on('request:end', (p) => ends.push(p));
|
|
||||||
|
|
||||||
await app.fetch(new Request('http://x/bad/go'));
|
|
||||||
|
|
||||||
expect(ends[0].route).toBe('/bad/go');
|
|
||||||
});
|
|
||||||
|
|
||||||
// The three-event overlap, asserted rather than described: one failing request, three events,
|
|
||||||
// one requestId. A consumer that counts `request:failed` and `request:end` as separate outcomes
|
|
||||||
// counts this request twice — which is the mistake the payload docs now name.
|
|
||||||
it('emits start, failed and end for one failing request, all sharing a requestId', async () => {
|
|
||||||
const app = createApp({ modules: [BadModule] });
|
|
||||||
const seen: Array<{ event: string; payload: EventPayload }> = [];
|
|
||||||
for (const event of ['request:start', 'request:failed', 'request:end'] as const)
|
|
||||||
app.bus.on(event, (payload) => seen.push({ event, payload }));
|
|
||||||
|
|
||||||
await app.fetch(new Request('http://x/bad/go'));
|
|
||||||
|
|
||||||
expect(seen.map((s) => s.event)).toEqual(['request:start', 'request:failed', 'request:end']);
|
|
||||||
expect(new Set(seen.map((s) => s.payload.requestId)).size).toBe(1);
|
|
||||||
// `request:end` is the terminal one and the only one that fires for every request shape; it is
|
|
||||||
// what a request counter counts.
|
|
||||||
expect(seen[2].payload.status).toBe(500);
|
|
||||||
});
|
|
||||||
|
|
||||||
// `onError` may turn any throw into any status, so a status derived from the error rather than
|
|
||||||
// from the render would be a guess that a custom renderer makes wrong.
|
|
||||||
it('reports the status a custom onError produced, not the one the error implied', async () => {
|
|
||||||
const app = createApp({
|
|
||||||
modules: [BadModule],
|
|
||||||
onError: () => ({ status: 418, headers: {}, body: 'teapot' }),
|
|
||||||
});
|
|
||||||
const failures: EventPayload[] = [];
|
|
||||||
app.bus.on('request:failed', (p) => failures.push(p));
|
|
||||||
|
|
||||||
const res = await app.fetch(new Request('http://x/bad/go'));
|
|
||||||
|
|
||||||
expect(res.status).toBe(418);
|
|
||||||
expect(failures).toHaveLength(1);
|
|
||||||
expect(failures[0].status).toBe(418);
|
|
||||||
});
|
|
||||||
|
|
||||||
// A renderer that throws must not swallow the event — the failure still happened, and losing the
|
|
||||||
// only record of it because the reporting of it broke is the worst possible trade. The status is
|
|
||||||
// the built-in renderer's, since that is what the request actually got.
|
|
||||||
it('still reports the failure when onError itself throws', async () => {
|
|
||||||
const app = createApp({
|
|
||||||
modules: [BadModule],
|
|
||||||
onError: () => {
|
|
||||||
throw new Error('renderer exploded');
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const failures: EventPayload[] = [];
|
|
||||||
app.bus.on('request:failed', (p) => failures.push(p));
|
|
||||||
|
|
||||||
const res = await app.fetch(new Request('http://x/bad/go'));
|
|
||||||
|
|
||||||
expect(res.status).toBe(500);
|
|
||||||
expect(failures).toHaveLength(1);
|
|
||||||
expect(failures[0].status).toBe(500);
|
|
||||||
// The request's error, not the renderer's — they are different errors and the event names the
|
|
||||||
// one the request suffered.
|
|
||||||
expect((failures[0].error as Error).message).toBe('step exploded');
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
@@ -1,141 +0,0 @@
|
|||||||
// Framework token names, and the read-only slice of the bus that `@needs` can reach.
|
|
||||||
//
|
|
||||||
// Two halves of one decision. The bus is not a graph token — a node that could reach it could also
|
|
||||||
// `emit`, and an observation channel anything can write to is not one — but `@needs('logger')`
|
|
||||||
// teaches that framework things *are* graph tokens, so reaching for `@needs('bus')` is the natural
|
|
||||||
// next move. Documenting that it does not work only reaches a reader; the boot error reaches the
|
|
||||||
// person writing it. And reserving the names stops a user's own `logger` from quietly becoming the
|
|
||||||
// one the whole app injects.
|
|
||||||
import 'reflect-metadata';
|
|
||||||
import { describe, it, expect } from 'vitest';
|
|
||||||
import { createApp, Provider, Step, Route, Get, Module, needs } from '../src/index';
|
|
||||||
import type { Events } from '../src/index';
|
|
||||||
|
|
||||||
@Route('/r')
|
|
||||||
class Ctl {
|
|
||||||
@Get('/x') x() {
|
|
||||||
return { ok: true };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('reserved framework tokens', () => {
|
|
||||||
for (const token of ['logger', 'rooms', 'events']) {
|
|
||||||
it(`refuses a provider that declares '${token}'`, () => {
|
|
||||||
@Provider({ provides: token })
|
|
||||||
class Shadow {
|
|
||||||
provide() {
|
|
||||||
return { [token]: { mine: true } };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@Module({ mountpoint: '/', providers: [Shadow], controllers: [Ctl] })
|
|
||||||
class M {}
|
|
||||||
|
|
||||||
expect(() => createApp({ modules: [M] })).toThrow(
|
|
||||||
new RegExp(`'${token}' is reserved by the framework`),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
it("refuses a step that declares 'bus', a name the framework reserves without providing", () => {
|
|
||||||
@Step({ provides: 'bus' })
|
|
||||||
class Shadow {
|
|
||||||
run() {
|
|
||||||
return { bus: { mine: true } };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@Module({ mountpoint: '/', steps: [Shadow], controllers: [Ctl] })
|
|
||||||
class M {}
|
|
||||||
|
|
||||||
expect(() => createApp({ modules: [M] })).toThrow(/'bus' is reserved by the framework/);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('leaves every other name alone', () => {
|
|
||||||
@Provider({ provides: 'buses' })
|
|
||||||
class Fine {
|
|
||||||
provide() {
|
|
||||||
return { buses: 1 };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@Module({ mountpoint: '/', providers: [Fine], controllers: [Ctl] })
|
|
||||||
class M {}
|
|
||||||
|
|
||||||
expect(() => createApp({ modules: [M] })).not.toThrow();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("@needs('bus')", () => {
|
|
||||||
it('fails at boot naming the read-only token and the plugin, not a nearest match', () => {
|
|
||||||
@Route('/b')
|
|
||||||
class Bad {
|
|
||||||
@Get('/x') x(@needs('bus') _bus: unknown) {
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@Module({ mountpoint: '/', controllers: [Bad] })
|
|
||||||
class M {}
|
|
||||||
|
|
||||||
expect(() => createApp({ modules: [M] })).toThrow(/the Bus is not a graph token/);
|
|
||||||
expect(() => createApp({ modules: [M] })).toThrow(/@needs\('events'\)/);
|
|
||||||
expect(() => createApp({ modules: [M] })).toThrow(/plugin/);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("@needs('events')", () => {
|
|
||||||
it('hands over on() and nothing else — no emit to forge events with', async () => {
|
|
||||||
let injected: Events | undefined;
|
|
||||||
|
|
||||||
@Route('/e')
|
|
||||||
class Observer {
|
|
||||||
@Get('/x') x(@needs('events') events: Events) {
|
|
||||||
injected = events;
|
|
||||||
return { ok: true };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@Module({ mountpoint: '/', controllers: [Observer] })
|
|
||||||
class M {}
|
|
||||||
|
|
||||||
const app = createApp({ modules: [M] });
|
|
||||||
await app.fetch(new Request('http://x/e/x'));
|
|
||||||
|
|
||||||
expect(typeof injected?.on).toBe('function');
|
|
||||||
expect(Object.keys(injected!)).toEqual(['on']);
|
|
||||||
expect((injected as unknown as { emit?: unknown }).emit).toBeUndefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('subscribes to the same bus the framework emits on, and hands back an unsubscribe', async () => {
|
|
||||||
const seen: string[] = [];
|
|
||||||
|
|
||||||
@Provider({ provides: 'watcher', needs: ['events'] })
|
|
||||||
class Watcher {
|
|
||||||
#off?: () => void;
|
|
||||||
provide(ctx: { events: Events }) {
|
|
||||||
this.#off = ctx.events.on('request:end', (e) => seen.push(e.route ?? ''));
|
|
||||||
return { watcher: true };
|
|
||||||
}
|
|
||||||
dispose() {
|
|
||||||
this.#off?.();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@Route('/e')
|
|
||||||
class Observed {
|
|
||||||
@Get('/y') y(@needs('watcher') _w: unknown) {
|
|
||||||
return { ok: true };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@Module({ mountpoint: '/', providers: [Watcher], controllers: [Observed] })
|
|
||||||
class M {}
|
|
||||||
|
|
||||||
const app = createApp({ modules: [M] });
|
|
||||||
await app.fetch(new Request('http://x/e/y'));
|
|
||||||
|
|
||||||
expect(seen).toEqual(['/e/y']);
|
|
||||||
|
|
||||||
// dispose() releases it, which is the half a plugin gets for free with onShutdown. Asserted by
|
|
||||||
// emitting after close and watching nothing arrive — clearing the array and finding it empty
|
|
||||||
// would prove only that clearing works.
|
|
||||||
await app.close();
|
|
||||||
seen.length = 0;
|
|
||||||
app.bus.emit('request:end', { name: 'after close', route: '/after' });
|
|
||||||
expect(seen).toEqual([]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -119,23 +119,6 @@ describe('matchRoute precedence', () => {
|
|||||||
expect(matchRoute(routes, 'GET', '/users/diego')?.def.pattern).toBe('/users/:value');
|
expect(matchRoute(routes, 'GET', '/users/diego')?.def.pattern).toBe('/users/:value');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('keeps registration order between patterns of equal specificity', () => {
|
|
||||||
// The tie-break the ordering rests on. Ranking is settled once when the table is built, and the
|
|
||||||
// sort that settles it is stable — which is what preserves the behaviour the scan used to get
|
|
||||||
// by refusing to replace its best on an equal rank. A sort that reordered equals would change
|
|
||||||
// which of two same-shape routes answers, silently and only for the ones that collide.
|
|
||||||
const routes = [route('GET', '/a/:first'), route('GET', '/a/:second')];
|
|
||||||
expect(matchRoute(routes, 'GET', '/a/x')?.def.pattern).toBe('/a/:first');
|
|
||||||
expect(matchRoute([...routes].reverse(), 'GET', '/a/x')?.def.pattern).toBe('/a/:second');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('decodes a parameter once per position, however many candidates the scan walks', () => {
|
|
||||||
// Not an optimisation detail: the decoded value each candidate sees must be the same one, so
|
|
||||||
// memoising per request cannot change which route matches or what it receives.
|
|
||||||
const routes = [route('GET', '/a/:x/zzz'), route('GET', '/a/:y/b')];
|
|
||||||
expect(matchRoute(routes, 'GET', '/a/a%20b/b')?.params).toEqual({ y: 'a b' });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns undefined when no pattern matches the path', () => {
|
it('returns undefined when no pattern matches the path', () => {
|
||||||
expect(matchRoute([route('GET', '/a')], 'GET', '/b')).toBeUndefined();
|
expect(matchRoute([route('GET', '/a')], 'GET', '/b')).toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,146 +0,0 @@
|
|||||||
// `id:` on the wire, and the `Last-Event-ID` round-trip it exists to enable.
|
|
||||||
//
|
|
||||||
// `EventSource` reconnects on its own — that is the reason to pick SSE over a raw WebSocket. Until
|
|
||||||
// an `id:` was written the browser had nothing to send back, so every reconnect restarted the
|
|
||||||
// iterable from its beginning and lost the gap in silence. green-tea carries the marker both ways
|
|
||||||
// and stores nothing: what the gap means is the handler's call, because only the source knows
|
|
||||||
// whether it is replayable.
|
|
||||||
import 'reflect-metadata';
|
|
||||||
import { describe, expect, it } from 'vitest';
|
|
||||||
import { ndjsonEncoder, sse, sseEncoder } from '../src/encoders';
|
|
||||||
import { Module, Route, Sse } from '../src/metadata';
|
|
||||||
import { header } from '../src/params';
|
|
||||||
import { createApp } from '../src/app';
|
|
||||||
|
|
||||||
const frame = (item: unknown): string => String(sseEncoder.encode(item));
|
|
||||||
|
|
||||||
describe('sse() framing', () => {
|
|
||||||
it('writes id: before data:', () => {
|
|
||||||
expect(frame(sse({ t: 1 }, { id: '7' }))).toBe('id: 7\ndata: {"t":1}\n\n');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('writes every field it was given, fields before data', () => {
|
|
||||||
expect(frame(sse({ t: 1 }, { id: '7', event: 'tick', retry: 5000 }))).toBe(
|
|
||||||
'retry: 5000\nevent: tick\nid: 7\ndata: {"t":1}\n\n',
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('leaves a plain item exactly as it was', () => {
|
|
||||||
// The whole point of the marker: an app that never calls sse() sees no change on the wire.
|
|
||||||
expect(frame({ t: 1 })).toBe('data: {"t":1}\n\n');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('keeps an empty id, which is how the spec resets the client s last event id', () => {
|
|
||||||
expect(frame(sse({ t: 1 }, { id: '' }))).toBe('id: \ndata: {"t":1}\n\n');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('cannot be talked into extra fields by a newline in the payload', () => {
|
|
||||||
// JSON.stringify escapes the newline, so the data line stays single by construction.
|
|
||||||
expect(frame({ note: 'a\nid: 99' })).toBe('data: {"note":"a\\nid: 99"}\n\n');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('sse() rejects a field that would break the frame', () => {
|
|
||||||
// An id is exactly the value most likely to come from a request — a cursor, a page token — so
|
|
||||||
// this is a boundary, not a formatting nicety. Stripping would resume from the wrong place
|
|
||||||
// silently, which is the bug this feature exists to close.
|
|
||||||
for (const [label, id] of [
|
|
||||||
['newline', 'a\nid: 99'],
|
|
||||||
['carriage return', 'a\rid: 99'],
|
|
||||||
['NUL', 'a\0b'],
|
|
||||||
] as const) {
|
|
||||||
it(`throws on a ${label} in id`, () => {
|
|
||||||
expect(() => sse({ t: 1 }, { id })).toThrow(/may not contain a newline or a NUL/);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
it('throws on a newline in event', () => {
|
|
||||||
expect(() => sse({ t: 1 }, { event: 'a\ndata: fake' })).toThrow(/'event' may not contain/);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('throws on a fractional retry, which a browser would ignore', () => {
|
|
||||||
expect(() => sse({ t: 1 }, { retry: 1.5 })).toThrow(/whole number of milliseconds/);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('ndjson', () => {
|
|
||||||
it('unwraps the payload and drops the SSE fields', () => {
|
|
||||||
// A `negotiate` route yields the same items to both encoders. NDJSON has no frame to carry
|
|
||||||
// id/event/retry and no resumption protocol to use them, so the client gets what it asked for.
|
|
||||||
expect(String(ndjsonEncoder.encode(sse({ t: 1 }, { id: '7' })))).toBe('{"t":1}\n');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('leaves a plain item alone', () => {
|
|
||||||
expect(String(ndjsonEncoder.encode({ t: 1 }))).toBe('{"t":1}\n');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('the Last-Event-ID round trip', () => {
|
|
||||||
const app = (): ReturnType<typeof createApp> => {
|
|
||||||
@Route('/')
|
|
||||||
class Ctl {
|
|
||||||
// Reading the header needs nothing new — the envelope has always carried it. What was
|
|
||||||
// missing was the `id:` that gives the browser something to put in it.
|
|
||||||
@Sse('/feed') feed(@header('last-event-id') from: string) {
|
|
||||||
const start = from ? Number(from) + 1 : 1;
|
|
||||||
return (async function* () {
|
|
||||||
for (let n = start; n < start + 2; n++) yield sse({ n }, { id: String(n) });
|
|
||||||
})();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
|
||||||
class M {}
|
|
||||||
return createApp({ modules: [M] });
|
|
||||||
};
|
|
||||||
|
|
||||||
it('serves ids, and resumes from the one the client sends back', async () => {
|
|
||||||
const feed = app();
|
|
||||||
|
|
||||||
const first = await (await feed.fetch(new Request('http://x/feed'))).text();
|
|
||||||
expect(first).toBe('id: 1\ndata: {"n":1}\n\nid: 2\ndata: {"n":2}\n\n');
|
|
||||||
|
|
||||||
// What EventSource does by itself on reconnect, spelled out.
|
|
||||||
const resumed = await (
|
|
||||||
await feed.fetch(new Request('http://x/feed', { headers: { 'last-event-id': '2' } }))
|
|
||||||
).text();
|
|
||||||
expect(resumed).toBe('id: 3\ndata: {"n":3}\n\nid: 4\ndata: {"n":4}\n\n');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('serves the same bytes over the Node adapter', async () => {
|
|
||||||
// A different write path — `pipeStream` to a socket rather than a web ReadableStream — so
|
|
||||||
// passing on `fetch` proves nothing about the runtime most apps deploy on.
|
|
||||||
const feed = app();
|
|
||||||
const server = await feed.listen(0);
|
|
||||||
const { port } = server.address() as import('net').AddressInfo;
|
|
||||||
|
|
||||||
const res = await fetch(`http://127.0.0.1:${port}/feed`, { headers: { 'last-event-id': '9' } });
|
|
||||||
expect(res.headers.get('content-type')).toBe('text/event-stream');
|
|
||||||
expect(await res.text()).toBe('id: 10\ndata: {"n":10}\n\nid: 11\ndata: {"n":11}\n\n');
|
|
||||||
|
|
||||||
await feed.close();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('refuses an id that would inject fields, rather than writing it', async () => {
|
|
||||||
@Route('/')
|
|
||||||
class Ctl {
|
|
||||||
@Sse('/bad') bad() {
|
|
||||||
return (async function* () {
|
|
||||||
yield sse({ t: 1 }, { id: 'cursor\ndata: injected' });
|
|
||||||
})();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
|
||||||
class M {}
|
|
||||||
const broken = createApp({ modules: [M] });
|
|
||||||
const errors: unknown[] = [];
|
|
||||||
broken.bus.on('stream:error', (e) => errors.push(e.error));
|
|
||||||
|
|
||||||
const body = await (await broken.fetch(new Request('http://x/bad'))).text();
|
|
||||||
|
|
||||||
// Not `toContain`: the rejection quotes the offending value, so the text appears inside the
|
|
||||||
// error payload — escaped, on one line. The claim is that no *field* was injected.
|
|
||||||
expect(body.split('\n')).not.toContain('data: injected');
|
|
||||||
expect(body).toContain('event: error');
|
|
||||||
expect(errors).toHaveLength(1);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,161 +0,0 @@
|
|||||||
// A stream's lifecycle must not depend on which adapter is serving it.
|
|
||||||
//
|
|
||||||
// `pipeStream` (Node) emitted `stream:open`/`:close`/`:error` and wrote the encoder's error frame.
|
|
||||||
// `asReadableStream` — the path every Fetch runtime takes, so Deno, Bun, workerd and `app.fetch()`
|
|
||||||
// on Node — emitted nothing and called `controller.error`. A consumer counting `stream:error` saw
|
|
||||||
// zero on three of the four runtimes, and the client got a truncated body indistinguishable from a
|
|
||||||
// clean end. Both halves are silent, which is what made it worth its own issue.
|
|
||||||
//
|
|
||||||
// Both adapters are driven from the same route table here on purpose: a table asserting one and
|
|
||||||
// then the other is how the two drift again.
|
|
||||||
import 'reflect-metadata';
|
|
||||||
import { describe, expect, it } from 'vitest';
|
|
||||||
import { Bus } from '../src/bus';
|
|
||||||
import { createHttpServer } from '../src/http';
|
|
||||||
import { buildFetch } from '../src/http/web';
|
|
||||||
import type { RouteDef } from '../src/http/types';
|
|
||||||
|
|
||||||
const events = (bus: Bus): string[] => {
|
|
||||||
const seen: string[] = [];
|
|
||||||
for (const name of ['stream:open', 'stream:close', 'stream:error'] as const)
|
|
||||||
bus.on(name, () => seen.push(name));
|
|
||||||
return seen;
|
|
||||||
};
|
|
||||||
|
|
||||||
const route = (handler: () => AsyncIterable<unknown>): RouteDef[] => [
|
|
||||||
{ method: 'GET', pattern: '/feed', transport: 'sse', handler: async () => ({ stream: handler() }) },
|
|
||||||
];
|
|
||||||
|
|
||||||
const clean = route(async function* () {
|
|
||||||
yield { t: 1 };
|
|
||||||
});
|
|
||||||
const broken = route(async function* () {
|
|
||||||
yield { t: 1 };
|
|
||||||
throw new Error('source died');
|
|
||||||
});
|
|
||||||
|
|
||||||
/** Serves one request through the Node adapter and returns the body it wrote. */
|
|
||||||
async function overNode(routes: RouteDef[], bus: Bus): Promise<string> {
|
|
||||||
const server = createHttpServer(routes, [], bus, undefined, {});
|
|
||||||
await new Promise<void>((r) => server.listen(0, r));
|
|
||||||
const { port } = server.address() as { port: number };
|
|
||||||
|
|
||||||
try {
|
|
||||||
return await (await fetch(`http://127.0.0.1:${port}/feed`)).text();
|
|
||||||
} finally {
|
|
||||||
server.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Serves one request through the Fetch adapter and returns the body it wrote. */
|
|
||||||
async function overFetch(routes: RouteDef[], bus: Bus): Promise<string> {
|
|
||||||
return await (await buildFetch(routes, { bus })(new Request('http://x/feed'))).text();
|
|
||||||
}
|
|
||||||
|
|
||||||
const ADAPTERS = [
|
|
||||||
{ name: 'node', serve: overNode },
|
|
||||||
{ name: 'fetch', serve: overFetch },
|
|
||||||
] as const;
|
|
||||||
|
|
||||||
describe('stream lifecycle events, on every adapter', () => {
|
|
||||||
for (const adapter of ADAPTERS) {
|
|
||||||
it(`${adapter.name}: opens and closes a stream that ends normally`, async () => {
|
|
||||||
const bus = new Bus();
|
|
||||||
const seen = events(bus);
|
|
||||||
|
|
||||||
expect(await adapter.serve(clean, bus)).toBe('data: {"t":1}\n\n');
|
|
||||||
expect(seen).toEqual(['stream:open', 'stream:close']);
|
|
||||||
});
|
|
||||||
|
|
||||||
it(`${adapter.name}: reports a source that throws, and frames it for the client`, async () => {
|
|
||||||
const bus = new Bus();
|
|
||||||
const seen = events(bus);
|
|
||||||
const errors: unknown[] = [];
|
|
||||||
bus.on('stream:error', (e) => errors.push(e.error));
|
|
||||||
|
|
||||||
const body = await adapter.serve(broken, bus);
|
|
||||||
|
|
||||||
// Framed rather than dropped: an SSE consumer can see this, where a truncated body is
|
|
||||||
// indistinguishable from the connection dropping.
|
|
||||||
expect(body).toContain('data: {"t":1}\n\n');
|
|
||||||
expect(body).toContain('event: error');
|
|
||||||
expect(body).toContain('source died');
|
|
||||||
|
|
||||||
expect(seen).toEqual(['stream:open', 'stream:error', 'stream:close']);
|
|
||||||
expect((errors[0] as Error).message).toBe('source died');
|
|
||||||
});
|
|
||||||
|
|
||||||
it(`${adapter.name}: names the route pattern, not the path that arrived`, async () => {
|
|
||||||
const bus = new Bus();
|
|
||||||
const names: string[] = [];
|
|
||||||
bus.on('stream:open', (e) => names.push(e.name));
|
|
||||||
|
|
||||||
await adapter.serve(clean, bus);
|
|
||||||
expect(names).toEqual(['/feed']);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const adapter of ADAPTERS) {
|
|
||||||
it(`${adapter.name}: correlates every stream event with the request that opened it`, async () => {
|
|
||||||
// The split is deliberate — `request:end` fires when the handler returns, not when the
|
|
||||||
// stream it produced finishes, so an hour-long SSE connection and a 2ms reply never share a
|
|
||||||
// latency distribution. That only works if the two can be joined, and this is the join key.
|
|
||||||
const bus = new Bus();
|
|
||||||
const ids = new Set<string | undefined>();
|
|
||||||
const traces = new Set<string | undefined>();
|
|
||||||
const routes = new Set<string | undefined>();
|
|
||||||
|
|
||||||
for (const name of ['stream:open', 'stream:close'] as const)
|
|
||||||
bus.on(name, (e) => {
|
|
||||||
ids.add(e.requestId);
|
|
||||||
traces.add(e.traceId);
|
|
||||||
routes.add(e.route);
|
|
||||||
});
|
|
||||||
|
|
||||||
await adapter.serve(clean, bus);
|
|
||||||
|
|
||||||
expect([...ids]).toHaveLength(1);
|
|
||||||
expect([...ids][0]).toMatch(/^[0-9a-f-]{36}$/); // one id, and it is the request's
|
|
||||||
// Bounded by the route table, which is what makes it the field to label a metric on.
|
|
||||||
expect([...routes]).toEqual(['/feed']);
|
|
||||||
expect([...traces]).toEqual([undefined]); // absent, not invented, when no traceparent arrived
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
it('fetch: adopts the gateway s x-request-id rather than opening a second identity', async () => {
|
|
||||||
const bus = new Bus();
|
|
||||||
const ids: Array<string | undefined> = [];
|
|
||||||
bus.on('stream:open', (e) => ids.push(e.requestId));
|
|
||||||
bus.on('stream:close', (e) => ids.push(e.requestId));
|
|
||||||
|
|
||||||
await (
|
|
||||||
await buildFetch(clean, { bus })(
|
|
||||||
new Request('http://x/feed', { headers: { 'x-request-id': 'from-the-gateway', traceparent: 'tp-1' } }),
|
|
||||||
)
|
|
||||||
).text();
|
|
||||||
|
|
||||||
expect(ids).toEqual(['from-the-gateway', 'from-the-gateway']);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('fetch: closes once when the client cancels mid-stream', async () => {
|
|
||||||
// The exit `pipeStream` gets from `res.on('close')` and the ReadableStream gets from `cancel`.
|
|
||||||
// Latched, because a cancel can also land after the body has already ended.
|
|
||||||
const bus = new Bus();
|
|
||||||
const seen = events(bus);
|
|
||||||
let released!: () => void;
|
|
||||||
const blocked = new Promise<void>((r) => (released = r));
|
|
||||||
|
|
||||||
const endless = route(async function* () {
|
|
||||||
yield { t: 1 };
|
|
||||||
await blocked;
|
|
||||||
});
|
|
||||||
|
|
||||||
const res = await buildFetch(endless, { bus })(new Request('http://x/feed'));
|
|
||||||
const reader = res.body!.getReader();
|
|
||||||
await reader.read();
|
|
||||||
await reader.cancel();
|
|
||||||
released();
|
|
||||||
|
|
||||||
expect(seen).toEqual(['stream:open', 'stream:close']);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -51,17 +51,13 @@ const hooks: Hooks[] = [{ onShutdown: flush }];
|
|||||||
// The two neighbouring extension points, already exported. Here so a future barrel edit that drops
|
// The two neighbouring extension points, already exported. Here so a future barrel edit that drops
|
||||||
// one is caught by the same test rather than by a user.
|
// one is caught by the same test rather than by a user.
|
||||||
const renderError: ErrorRenderer = () => ({ status: 500, headers: {}, body: 'boom' });
|
const renderError: ErrorRenderer = () => ({ status: 500, headers: {}, body: 'boom' });
|
||||||
const encoder: StreamEncoder = {
|
const encoder: StreamEncoder = { headers: {}, encode: (item) => String(item) };
|
||||||
headers: {},
|
|
||||||
encode: (item) => String(item),
|
|
||||||
encodeError: (err) => String(err),
|
|
||||||
};
|
|
||||||
|
|
||||||
test('every extension point is typeable from the package barrel', () => {
|
test('every extension point is typeable from the package barrel', () => {
|
||||||
expect(prometheusText('x').body).toBe('x');
|
expect(prometheusText('x').body).toBe('x');
|
||||||
expect(typeof metricsPlugin).toBe('function');
|
expect(typeof metricsPlugin).toBe('function');
|
||||||
expect(hooks).toHaveLength(1);
|
expect(hooks).toHaveLength(1);
|
||||||
expect(renderError(new Error('boom'), {} as never)?.status).toBe(500);
|
expect(renderError(new Error('boom'), {} as never).status).toBe(500);
|
||||||
expect(encoder.encode(1)).toBe('1');
|
expect(encoder.encode(1)).toBe('1');
|
||||||
// The workaround the missing export forced, kept as a reminder of what it replaced.
|
// The workaround the missing export forced, kept as a reminder of what it replaced.
|
||||||
expect(typeof JsonTransformer).toBe('function');
|
expect(typeof JsonTransformer).toBe('function');
|
||||||
|
|||||||
@@ -19,24 +19,6 @@ class Views {
|
|||||||
class M {}
|
class M {}
|
||||||
const app = createApp({ modules: [M], views: dir });
|
const app = createApp({ modules: [M], views: dir });
|
||||||
|
|
||||||
// Checked alongside the `onError` guard: `viewEngine` is the other user callback on a render path,
|
|
||||||
// and whether it had a boundary was not something to assume. It does — the pipeline's own catch
|
|
||||||
// covers it, so a broken engine is a 500 rather than a dead process. Asserted so it stays that way.
|
|
||||||
describe('a viewEngine that throws', () => {
|
|
||||||
it('renders a 500 instead of escaping the request', async () => {
|
|
||||||
const broken = createApp({
|
|
||||||
modules: [M],
|
|
||||||
views: dir,
|
|
||||||
viewEngine: () => {
|
|
||||||
throw new Error('engine exploded');
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const res = await broken.fetch(new Request('http://x/user'));
|
|
||||||
expect(res.status).toBe(500);
|
|
||||||
expect(await res.json()).toEqual({ error: 'Internal Server Error' });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('@Html modes', () => {
|
describe('@Html modes', () => {
|
||||||
it('string mode sends the handler return as text/html', async () => {
|
it('string mode sends the handler return as text/html', async () => {
|
||||||
const res = await app.fetch(new Request('http://x/str'));
|
const res = await app.fetch(new Request('http://x/str'));
|
||||||
|
|||||||
@@ -166,28 +166,6 @@ describe('buildFetch request gate', () => {
|
|||||||
const afterRelease = await fetchHandler(new Request('http://localhost/slow'));
|
const afterRelease = await fetchHandler(new Request('http://localhost/slow'));
|
||||||
expect(afterRelease.status).toBe(200);
|
expect(afterRelease.status).toBe(200);
|
||||||
});
|
});
|
||||||
it('consults a cors.origins predicate once per request on the fetch path too', async () => {
|
|
||||||
let calls = 0;
|
|
||||||
const fetchHandler = buildFetch(
|
|
||||||
[{ method: 'GET', pattern: '/ok', transport: 'buffer',
|
|
||||||
handler: async () => ({ status: 200, headers: {}, body: 'ok' }) }],
|
|
||||||
{ cors: { origins: () => { calls++; return true; } } },
|
|
||||||
);
|
|
||||||
|
|
||||||
const res = await fetchHandler(new Request('http://localhost/ok', { headers: { origin: 'https://a.com' } }));
|
|
||||||
expect(res.headers.get('access-control-allow-origin')).toBe('https://a.com');
|
|
||||||
expect(calls).toBe(1);
|
|
||||||
|
|
||||||
calls = 0;
|
|
||||||
const preflight = await fetchHandler(new Request('http://localhost/ok', {
|
|
||||||
method: 'OPTIONS',
|
|
||||||
headers: { origin: 'https://a.com', 'access-control-request-method': 'GET' },
|
|
||||||
}));
|
|
||||||
expect(preflight.status).toBe(204);
|
|
||||||
expect(preflight.headers.get('access-control-allow-methods')).toContain('GET');
|
|
||||||
expect(calls).toBe(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('releases the slot when a streaming handler returns', async () => {
|
it('releases the slot when a streaming handler returns', async () => {
|
||||||
async function* stream() {
|
async function* stream() {
|
||||||
yield { n: 1 };
|
yield { n: 1 };
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { describe, it, expect } from 'vitest';
|
|||||||
import { runWsConnection, matchWsRoute, type WsSocket, type WsRequest } from '../src/http/ws-core';
|
import { runWsConnection, matchWsRoute, type WsSocket, type WsRequest } from '../src/http/ws-core';
|
||||||
import { channel } from '../src/channel';
|
import { channel } from '../src/channel';
|
||||||
import { HttpError } from '../src/signals';
|
import { HttpError } from '../src/signals';
|
||||||
import { Bus } from '../src/bus';
|
|
||||||
import type { WsRouteDef } from '../src/http/types';
|
import type { WsRouteDef } from '../src/http/types';
|
||||||
|
|
||||||
/** A controllable fake WsSocket that records sends and closes. */
|
/** A controllable fake WsSocket that records sends and closes. */
|
||||||
@@ -111,44 +110,3 @@ describe('runWsConnection (neutral core)', () => {
|
|||||||
expect(matchWsRoute(routes, '/nope')).toBeUndefined();
|
expect(matchWsRoute(routes, '/nope')).toBeUndefined();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('runWsConnection correlation', () => {
|
|
||||||
const def: WsRouteDef = {
|
|
||||||
pattern: '/ws',
|
|
||||||
open: async () =>
|
|
||||||
(async function* () {
|
|
||||||
yield 'hi';
|
|
||||||
})(),
|
|
||||||
};
|
|
||||||
|
|
||||||
const opened = async (headers: WsRequest['headers']): Promise<Record<string, unknown>[]> => {
|
|
||||||
const bus = new Bus();
|
|
||||||
const seen: Record<string, unknown>[] = [];
|
|
||||||
for (const name of ['stream:open', 'stream:close'] as const)
|
|
||||||
bus.on(name, (e) => seen.push({ ...e }));
|
|
||||||
const { socket } = fakeSocket();
|
|
||||||
await runWsConnection(socket, { ...req, headers }, { def, params: {} }, bus);
|
|
||||||
return seen;
|
|
||||||
};
|
|
||||||
|
|
||||||
it('gives the connection one identity, not one per emitter', async () => {
|
|
||||||
const seen = await opened({});
|
|
||||||
expect(seen).toHaveLength(2);
|
|
||||||
expect(seen[0].requestId).toMatch(/^[0-9a-f-]{36}$/);
|
|
||||||
expect(seen[1].requestId).toBe(seen[0].requestId);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('adopts a gateway s x-request-id and carries traceparent through', async () => {
|
|
||||||
// An upgrade is an HTTP request with headers like any other: a service behind a proxy must not
|
|
||||||
// open a second identity for a connection that already has one.
|
|
||||||
const seen = await opened({ 'x-request-id': 'gw-1', traceparent: 'tp-1' });
|
|
||||||
expect(seen.map((e) => e.requestId)).toEqual(['gw-1', 'gw-1']);
|
|
||||||
expect(seen.map((e) => e.traceId)).toEqual(['tp-1', 'tp-1']);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('labels the route pattern and names the transport', async () => {
|
|
||||||
const [open] = await opened({});
|
|
||||||
expect(open.route).toBe('/ws');
|
|
||||||
expect(open.transport).toBe('ws');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
Reference in new issue
Block a user