Compare commits
29
Commits
main
...
71fc027134
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
71fc027134 | ||
|
|
ee7fdec541 | ||
|
|
32caa21308 | ||
|
|
684795a2de | ||
|
|
a4562b2b23 | ||
|
|
a47c6564ab | ||
|
|
98ea948ffa | ||
|
|
5d0e544878 | ||
|
|
c30cf7e457 | ||
|
|
adce82beaa | ||
|
|
ed47836c98 | ||
|
|
77a99e83ce | ||
|
|
bd478ce09c | ||
|
|
4c3b4d29c4 | ||
|
|
445738e830 | ||
|
|
352ba477b4 | ||
|
|
4d1639f7c5 | ||
|
|
26bacdb304 | ||
|
|
7fa02d16be | ||
|
|
f78c9dc6fd | ||
|
|
ae60cd68a2 | ||
|
|
0540bef07b | ||
|
|
59763c9af5 | ||
|
|
1069c727c8 | ||
|
|
53660adcce | ||
|
|
42376c6693 | ||
|
|
9761b40eb5 | ||
|
|
7255b8ec30 | ||
|
|
ca78f0a8e5 |
No files matched your search
@@ -19,7 +19,7 @@ The smallest module and route that shows it:
|
||||
## Environment
|
||||
|
||||
- green-tea version:
|
||||
- Runtime and version: <!-- Node 20.11 / Deno 2.1 / Bun 1.1 / Cloudflare Workers -->
|
||||
- Runtime and version: <!-- Node 22.12 / Deno 2.1 / Bun 1.1 / Cloudflare Workers -->
|
||||
- OS:
|
||||
|
||||
<!--
|
||||
|
||||
@@ -41,7 +41,7 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '18'
|
||||
node-version: '22'
|
||||
- run: npm ci
|
||||
- run: npm run lint
|
||||
- run: npm run format:check
|
||||
|
||||
@@ -21,6 +21,7 @@ coverage/
|
||||
|
||||
# Edge (Miniflare) test bundle artifact
|
||||
test/edge/_worker.mjs
|
||||
test/edge/_parity-worker.mjs
|
||||
|
||||
# Bun writes this on `bun install`, and nothing here consumes it: `npm run test:bun` runs
|
||||
# `bun test` against the node_modules npm installed, which package-lock.json already pins.
|
||||
|
||||
@@ -55,6 +55,20 @@ feature/* → develop → main → [promote.yml] → GitHub main
|
||||
|
||||
**Only `hotfix/*` can still cause real drift**, since it branches from and returns to `main`. That case genuinely needs a back-merge; nothing else does.
|
||||
|
||||
**`tea pr merge` cannot do the promotion.** The CLI offers `merge`, `rebase`, `squash` and `rebase-merge`, and every one of them births a commit on `main` — the drift this section exists to prevent. Gitea's API has the style the CLI lacks, so promote through it:
|
||||
|
||||
```bash
|
||||
curl -X POST -H "Authorization: token $TOKEN" -H 'Content-Type: application/json' \
|
||||
-d '{"Do":"fast-forward-only"}' \
|
||||
"$GITEA_URL/api/v1/repos/$REPO/pulls/<n>/merge"
|
||||
```
|
||||
|
||||
`$GITEA_URL` and `$REPO` are yours to fill in — this file is mirrored to a public repository, and
|
||||
the address of a private forge is not something to publish. `fast-forward-only` is the part that
|
||||
matters and is the part the CLI does not offer.
|
||||
|
||||
A `405 Not all required status checks successful` means the pull request's own CI has not finished — `main` is protected, and a promotion runs its own checks rather than inheriting `develop`'s. Wait for them; the call is the same afterwards.
|
||||
|
||||
**Delete the branch when the work lands.** Both sides, as the last step of merging rather than a chore left for later:
|
||||
|
||||
```bash
|
||||
|
||||
@@ -6,6 +6,104 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
green-tea uses calendar versioning: `YY.M.PATCH` — the month is not zero-padded, since
|
||||
npm treats versions as semver and semver forbids leading zeros.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Breaking
|
||||
|
||||
- **Node 18 and Node 20 are no longer supported; the minimum is Node 22.** Both are end-of-life
|
||||
and receive no security patches, so `engines.node` is now `>=22`, CI runs Node 22 only, and the
|
||||
build targets `node22`. Node 22 is the oldest line still maintained. The `node:crypto` fallback
|
||||
for Node 18's missing global `crypto` is removed with it.
|
||||
|
||||
- **Inbound WebSocket messages are capped at 1 MiB by default** (#107). Node used `ws`'s own
|
||||
default of 100 MiB, and Deno, Bun and the edge applied no cap of their own, so one client could
|
||||
make the server hold a message of any size the runtime would accept. A larger message now closes
|
||||
the connection with `1009` (`message too large`). Raise it with `limits.maxWsMessageBytes`.
|
||||
|
||||
- **A connection with 16 unread inbound messages is closed on the 17th** (#107), with `1013`
|
||||
(`inbound queue full`). The queue behind `inbound` was unbounded on every runtime, so a handler
|
||||
that read slowly — or never — let a client grow it without limit. This also reaches a `@Ws`
|
||||
handler that never reads `inbound` at all: on Node those frames used to be discarded, and they
|
||||
now count. Raise the bound with `limits.maxWsQueue`.
|
||||
|
||||
### Added
|
||||
|
||||
- **`limits.maxWsMessageBytes` and `limits.maxWsQueue`** (#107): per-connection bounds on inbound
|
||||
WebSocket messages, in bytes and in unread messages, server-wide on every runtime. `createApp`
|
||||
throws a `TypeError` for anything but a positive integer. Node and Bun refuse an oversized message
|
||||
before buffering it; Bun does so by dropping the connection, so its peer sees `1006` rather than
|
||||
`1009`. Deno and workerd expose no such option, so there the message is received in full and then
|
||||
refused, and its memory is bounded by the platform's own cap. Worst-case buffered inbound memory is
|
||||
about `maxConnections × maxWsQueue × maxWsMessageBytes`, ≈ 15.6 GiB at the Node defaults; Deno and
|
||||
Bun have no connection cap, so set one at the platform or proxy there.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **`static` no longer serves files outside its root through a symlink** (#106). The traversal guard
|
||||
compared paths lexically, and the file read then followed symlinks, so `public/leak -> /etc/hosts`
|
||||
was served. Containment now compares real paths: the requested file, and a directory's
|
||||
`index.html`, must resolve beneath the root's real path. Links that stay inside the root, and a
|
||||
root that is itself a symlink, keep working.
|
||||
|
||||
A link that resolves outside the root, or a dangling link, is a **404** — the same miss as a file
|
||||
that does not exist, rendered through `onError` like any other, and `405`/`204` where the path has
|
||||
routes. It is deliberately not a `403`, so a probe cannot tell "exists outside the root" from
|
||||
"does not exist". The content-type still follows the requested name, not the link target.
|
||||
|
||||
The root's real path is resolved on the first request and cached, so **re-pointing a root symlink
|
||||
while the app runs needs a restart** to take effect. A link swapped inside the root between the
|
||||
check and the read can still escape; exploiting that needs write access to the served directory.
|
||||
|
||||
- **A request that fails past the error renderer no longer takes the Node process down** (#108). The Node
|
||||
request listener was an `async` function, and `http.createServer` ignores the promise it returns,
|
||||
so anything that rejected outside the region where errors convert to a response — a custom static
|
||||
resolver, a handler header value Node refuses to write, a stream that fails before its first frame
|
||||
— became an unhandled rejection, which Node's default mode turns into an exit. The listener now
|
||||
catches it. While the response is still writable the client gets a fixed 500 with
|
||||
`connection: close`, written without calling `onError` again; once output has started the socket
|
||||
is destroyed instead. Either way the failure is logged through `logger.error`. No `request:end` is
|
||||
emitted for these requests. Deno, Bun and the edge were not affected: they receive `app.fetch`'s
|
||||
promise, and the runtime answers a rejection with a 500 itself.
|
||||
|
||||
- **A malformed WebSocket upgrade no longer takes a Node server down** (#104). The upgrade path never
|
||||
ran the request-path normalization HTTP runs, so a bad percent escape in a param segment
|
||||
(`/room/%E0%A4%A`) threw out of the `'upgrade'` listener as an uncaught exception, and one request
|
||||
was enough to end the process. Upgrades now go through the same normalization: a malformed escape
|
||||
or a repeated slash gets a `400`, an unknown route a written `404` instead of a silent disconnect,
|
||||
and anything else that throws in the listener a `500`. `//rt//echo` used to match `/rt/echo` on
|
||||
upgrade while HTTP refused it; both refuse it now. On Deno, Bun and the edge the same paths close
|
||||
with `1008 invalid request path` rather than `1011 internal error`, and on Deno a `1008` sent before
|
||||
the socket finished opening now reaches the client instead of leaving it hanging.
|
||||
|
||||
- **Deno, Bun and the edge enforce `maxBodyBytes` while reading the body, not after** (#105). The
|
||||
fetch adapter read every request through `request.arrayBuffer()` and compared the length once the
|
||||
whole body was in memory, so a 10 GB upload was buffered in full before it was refused. It now
|
||||
reads `request.body` chunk by chunk, stops at the chunk that crosses the limit and cancels the
|
||||
stream, so nothing further is pulled. A `content-length` that already declares more than the limit
|
||||
is refused before any of the body is read, on Node too, where the request used to wait for its
|
||||
first chunk. A malformed or absent `content-length` proves nothing and is ignored; the running
|
||||
count enforces the limit either way. The response is unchanged: the same `413 Payload Too Large`,
|
||||
through `onError`, with the same route-over-server precedence for `maxBodyBytes` and `maxParts`.
|
||||
|
||||
workerd may drop `content-length` from a chunked upload, so there an oversized body is refused by
|
||||
the count rather than up front. The status is the same; only how early it comes differs.
|
||||
|
||||
- **`serveDeno()` and `serveBun()` populate `ctx.ip` with the client's address** (#116). The fetch
|
||||
path had no way to learn the socket peer, so every HTTP request on Deno and Bun saw `ctx.ip` as
|
||||
`''`, and anything keyed on it put every client in one bucket — the rate-limit plugin, where one
|
||||
client could exhaust the limit for everyone, above all. Both adapters now hand the peer to
|
||||
`app.fetch`, and `ctx.ip` follows the same rule as Node's `listen()`: the first
|
||||
`x-forwarded-for` hop when `trustProxy` is on and the header is present, the socket peer
|
||||
otherwise. That includes `trustProxy` with no `x-forwarded-for`, which used to answer `''` on
|
||||
the fetch path and now falls back to the peer, as Node always has.
|
||||
|
||||
Addresses are passed through as each runtime reports them, so the IPv6 loopback is `::1` on all
|
||||
three but Node may report an IPv4 client as `::ffff:127.0.0.1`. A bare `app.fetch(request)` from
|
||||
your own code has no socket to report and still answers `''` (or the forwarded hop), and so does
|
||||
a `Request` copied from the one the adapter received. No signature changed. The edge adapter is
|
||||
unchanged: trusting `cf-connecting-ip` is only correct behind Cloudflare, and needs its own
|
||||
decision.
|
||||
|
||||
## [26.9.0-beta.2] - 2026-09-22
|
||||
|
||||
### Breaking
|
||||
|
||||
+1
-1
@@ -101,7 +101,7 @@ Follow [Conventional Commits](https://www.conventionalcommits.org/): `feat:`, `f
|
||||
|
||||
## Local setup
|
||||
|
||||
Node 18 or newer, which is what `engines` requires and what CI runs.
|
||||
Node 22 or newer, which is what `engines` requires and what CI runs. Node 18 and 20 are end-of-life and no longer supported.
|
||||
|
||||
```bash
|
||||
npm install
|
||||
|
||||
@@ -141,7 +141,7 @@ without growing the runtime dependency tree past `reflect-metadata`:
|
||||
- **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS.
|
||||
- **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response.
|
||||
- **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency.
|
||||
- **Resource ceilings, with safe defaults.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. `maxConcurrentRequests` is opt-in and applies per server or Fetch adapter instance; when set, excess in-flight requests receive `503` and `Retry-After: 1`. It bounds concurrently executing handlers, so a handler that never returns continues to hold its slot; on Node, a client disconnect releases that slot. Long-lived streams and WebSocket upgrades do not hold that request budget. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there.
|
||||
- **Resource ceilings, with safe defaults.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. `maxConcurrentRequests` is opt-in and applies per server or Fetch adapter instance; when set, excess in-flight requests receive `503` and `Retry-After: 1`. It bounds concurrently executing handlers, so a handler that never returns continues to hold its slot; on Node, a client disconnect releases that slot. Long-lived streams and WebSocket upgrades do not hold that request budget. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there. WebSocket connections are bounded too: `maxWsMessageBytes` (default 1 MiB) closes a connection whose message is larger with `1009`, and `maxWsQueue` (default `16`) closes one that has that many unread inbound messages and receives another with `1013`, rather than dropping anything. Both are server-wide and must be positive integers. Node and Bun refuse an oversized message before buffering it (Bun drops the connection, so its peer sees `1006`); Deno and the edge check it after the runtime has received it. Worst case, a server buffers about `maxConnections × maxWsQueue × maxWsMessageBytes` of inbound messages — ≈ 15.6 GiB at the Node defaults.
|
||||
- **Observability without an integration.** Every request carries an id and a trace id through every lifecycle event, each step reports its own duration, and `createApp({ logger })` accepts any logger — the default writes structured JSON. Nothing in core writes to `console`. Metrics and tracing exporters read the same stream from outside core.
|
||||
- **Graceful shutdown, with a deadline.** `app.close()` drains in-flight requests and closes live streams and mesh links, then warns and force-closes whatever is still open after 10 seconds — so a stuck handler cannot hold a deploy open forever. Change the number per call with `close({ timeoutMs })` or for the whole app with `createApp({ shutdownTimeoutMs })`. Connection *draining* is Node-only; on Deno and Bun the server `serveDeno()`/`serveBun()` returns carries the same `close({ timeoutMs })`.
|
||||
- **Shutdown is an extension point.** A provider that opened a pool closes it in `dispose()`; a plugin registers `onShutdown(...)`; an application that wants neither passes `createApp({ hooks: [{ onShutdown }] })`. All three land in one registry, run in reverse boot order — a `cache` that needs `db` closes first — and are *awaited*, unlike a `bus.on` listener. A failure is logged and the rest still run, because one broken teardown must not leave the process up. Everything happens inside `close()`'s deadline; `createApp({ teardownTimeoutMs })` reserves a slice of it when a connection must get its chance. *Not available on the edge* — workerd has no shutdown to hook.
|
||||
@@ -284,7 +284,7 @@ green-tea is **beta**, on the road to a release candidate. Express and Fastify h
|
||||
|
||||
**What is not here:** no metrics registry, and **no OpenTelemetry exporter in core** — that is a separate package, because core has one runtime dependency and intends to keep it. A `traceparent` header is carried through untouched for an exporter to interpret; core implements no propagation spec. If your definition of production-ready includes shipping traces on day one, you are writing the exporter, and the stream it needs is the part that now exists.
|
||||
|
||||
**Runtimes differ in what they can offer.** Node ≥ 18, Deno, and Bun run everything. On the edge (Cloudflare Workers) there is no `app.listen()`, no filesystem — so `@Html` file/template modes and `static` serving are unavailable — and mesh does not run there at all (the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which `nodejs_compat` doesn't provide). Workers also require the `nodejs_compat` flag.
|
||||
**Runtimes differ in what they can offer.** Node ≥ 22, Deno, and Bun run everything. On the edge (Cloudflare Workers) there is no `app.listen()`, no filesystem — so `@Html` file/template modes and `static` serving are unavailable — and mesh does not run there at all (the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which `nodejs_compat` doesn't provide). Workers also require the `nodejs_compat` flag.
|
||||
|
||||
**mesh is alpha.** Distributed DI works, but discovery, load-balancing, and failover are not built, and its API and wire protocol may change between releases. It is gated behind an explicit opt-in — `createApp({ mesh, experimental: true })` — and `createApp` throws if you configure `mesh` without it. Don't ship mesh to production yet.
|
||||
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
# Pre-radix router baseline — `ed47836`
|
||||
|
||||
The performance half of the CARD-08 parity corpus (FPRD-001, #109), captured before any CARD-07
|
||||
router change and immutable through CARD-07 review, like `test/router-parity/`. CARD-10 measures
|
||||
the radix index with the **same harness and defaults, on the same host, cpuset and image**, running
|
||||
`LOOKUP_ROUTERS="base=<ed47836 router>,head=src/http/router.ts"`. Do not re-run into this directory:
|
||||
a new capture goes in a new directory.
|
||||
|
||||
## Files
|
||||
|
||||
| File | What it is |
|
||||
|---|---|
|
||||
| `lookup-raw.json` | **The D4 baseline.** Interleaved `bench:lookup` with the live linear matcher as A and the byte-identical frozen oracle as B: environment, method, every sample of every round, and the summary. The live column gives the absolute baseline; the B/A ratios give the A/A noise floor. |
|
||||
| `lookup-summary.txt` | The tables that run printed. |
|
||||
| `load.txt` | `uptime` and running CI job containers, before and after. |
|
||||
| `battery-run/` | The superseded first capture (laptop on battery, sequential harness), kept for reference, including its `bench:compare` end-to-end req/s run. |
|
||||
|
||||
## Environment
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Host | jarvis (homelab), Ubuntu 24.04.3 LTS, kernel 6.8.0-138-generic, x86_64 |
|
||||
| CPU | AMD Ryzen 7 3700X, 8 cores / 16 threads, 2 × 16 MiB L3, governor `schedutil` (host default; not changed) |
|
||||
| Memory | 62.7 GiB |
|
||||
| Isolation | `docker run --rm --cpuset-cpus 6,7,14,15`: physical cores 6 and 7 plus their SMT siblings, both on the second CCX. All 16 CPUs were 0.0–0.8% busy in a 5 s sample beforehand. |
|
||||
| Container | `node:22` (`sha256:5647be70…`), Node v22.23.1, V8 12.4.254.21-node.56; Docker 29.1.3 |
|
||||
| Power | Not applicable (mains-powered server) |
|
||||
| Load | 1-minute load 0.27 before, 0.79 after; no CI job containers running (see `load.txt`). jarvis also runs long-lived services (payments-automation, open-webui, windmill, the Gitea act_runner, alloy, beszel), none of them pinned off these cores. |
|
||||
| Revision | Router at `ed47836c9820c47bf4ed5e902d91e019abdb110a`; harness `ee7fdec`, whose `src/` is byte-identical to `ed47836`. Copied with `git archive`, `npm ci --ignore-scripts` in the container. |
|
||||
| Env vars | Only `LOOKUP_*` (recorded in `meta.env`); no `NODE_OPTIONS`. |
|
||||
|
||||
## Method (`bench/lookup.ts` at `ee7fdec`, defaults)
|
||||
|
||||
- **Operation:** `resolveRoute(routes, method, path)`, and on `undefined`, `allowedMethods(routes, path)` — what `dispatch` does after `normalizeRequestPath`.
|
||||
- **Route counts:** 10, 100 and 500 **total registered HTTP routes**, from the recorded generator (`meta.method.routeGenerator`).
|
||||
- **Workloads:** static hit, late parameter hit, method miss, path miss; each answer is asserted before timing.
|
||||
- **Interleaving:** for each cell, every router is warmed for 250 ms (also calibrating ≈25 ms samples), then 21 rounds of one sample per router with the order alternating AB / BA.
|
||||
- **Repetitions:** 4 fresh processes, with module import order alternating per process → 84 paired rounds per cell. Every sample is kept.
|
||||
- **Statistics:** absolute = median ns per lookup over all 84 samples; ratio = median of the 84 per-round B/A ratios, with a percentile-bootstrap 95% CI (4000 resamples, seed 10908).
|
||||
|
||||
## Baseline: live linear matcher (median ns per lookup)
|
||||
|
||||
| Routes | Workload | live median ns | run medians (ns) | run spread |
|
||||
|---:|---|---:|---|---:|
|
||||
| 10 | static hit | 185.3 | 156.1 / 187.7 / 174.1 / 194.2 | 20.5% |
|
||||
| 10 | late param hit | 328.4 | 311.9 / 336.2 / 323.0 / 342.4 | 9.3% |
|
||||
| 10 | method miss | 800.4 | 762.6 / 801.2 / 798.6 / 804.4 | 5.2% |
|
||||
| 10 | path miss | 625.5 | 594.6 / 631.3 / 620.3 / 628.1 | 5.9% |
|
||||
| 100 | static hit | 201.2 | 202.2 / 200.8 / 197.6 / 207.2 | 4.8% |
|
||||
| 100 | late param hit | 878.0 | 861.1 / 857.0 / 907.3 / 880.5 | 5.7% |
|
||||
| 100 | method miss | 2,525 | 2,424 / 2,514 / 2,580 / 2,531 | 6.2% |
|
||||
| 100 | path miss | 3,054 | 2,965 / 3,024 / 3,114 / 3,071 | 4.9% |
|
||||
| 500 | static hit | 202.2 | 201.8 / 202.3 / 195.1 / 210.3 | 7.5% |
|
||||
| 500 | late param hit | 2,931 | 2,830 / 2,804 / 2,980 / 3,016 | 7.2% |
|
||||
| 500 | method miss | 11,904 | 11,635 / 11,518 / 11,946 / 12,031 | 4.3% |
|
||||
| 500 | path miss | 15,514 | 15,103 / 14,972 / 15,665 / 16,034 | 6.8% |
|
||||
|
||||
## A/A noise floor: identical code, oracle / live
|
||||
|
||||
| Routes | Workload | oracle / live median | 95% CI |
|
||||
|---:|---|---:|---|
|
||||
| 10 | static hit | 0.9507 (-4.9%) | -13.7% … +11.9% |
|
||||
| 10 | late param hit | 1.0415 (+4.1%) | -1.6% … +9.8% |
|
||||
| 10 | method miss | 0.9809 (-1.9%) | -4.4% … +0.8% |
|
||||
| 10 | path miss | 0.9919 (-0.8%) | -3.2% … +1.4% |
|
||||
| 100 | static hit | 1.0082 (+0.8%) | -1.9% … +4.5% |
|
||||
| 100 | late param hit | 1.0247 (+2.5%) | +1.9% … +2.9% |
|
||||
| 100 | method miss | 1.0055 (+0.6%) | +0.3% … +0.7% |
|
||||
| 100 | path miss | 1.0165 (+1.7%) | +1.2% … +1.9% |
|
||||
| 500 | static hit | 1.0107 (+1.1%) | -2.2% … +4.5% |
|
||||
| 500 | late param hit | 0.9838 (-1.6%) | -2.2% … +0.8% |
|
||||
| 500 | method miss | 1.0197 (+2.0%) | +1.6% … +2.3% |
|
||||
| 500 | path miss | 1.0161 (+1.6%) | +0.5% … +2.6% |
|
||||
|
||||
**For D4:**
|
||||
|
||||
- **Import order.** In-process, the module imported first is faster on the cheapest cell. At 10-route static hit (≈180 ns) the per-run medians swap by about 20% when the import order swaps (run 1: live 156, oracle 200 ns; run 2: live 188, oracle 162 ns). Alternating the import order removes that bias from the median, but it leaves that cell's 95% CI at −13.7 … +11.9%. A ≤5% regression limit cannot be resolved there with this method and sample size.
|
||||
- **Other 10-route cells.** The CIs are within about ±10% (late parameter hit −1.6 … +9.8%), and the misses are within ±4.4%.
|
||||
- **100 and 500 routes.** Identical code shows small but systematic offsets of up to +2.9%, with CIs that exclude 1. Treat anything inside ±3% as indistinguishable from no change.
|
||||
- **500 routes.** The ≥20% improvement target is far outside the noise in every cell.
|
||||
|
||||
The options for D4 are to apply the 10-route limit to the miss and late-parameter cells only, to require more rounds for the static cell, or to restate the limit relative to this measured floor. That decision belongs to the owner.
|
||||
@@ -0,0 +1,94 @@
|
||||
# Superseded: first baseline, laptop on battery — `ed47836`
|
||||
|
||||
> Kept for reference only. **The baseline is `../README.md`**, captured on jarvis with the
|
||||
> interleaved harness. This run used the earlier sequential harness (`98ea948`), one router per
|
||||
> process, on a laptop running on battery.
|
||||
|
||||
The performance half of the CARD-08 parity corpus (FPRD-001, #109). Captured before any CARD-07
|
||||
router change; immutable through CARD-07 review, like `test/router-parity/`. CARD-10 measures the
|
||||
radix index with the **same harness, same defaults, same machine class**, and compares against
|
||||
these files. Do not re-run into this directory: a new capture goes in a new directory.
|
||||
|
||||
## Files
|
||||
|
||||
| File | What it is |
|
||||
|---|---|
|
||||
| `lookup-raw.json` | **The D4 baseline.** `bench:lookup` on the live linear matcher: environment, method, every sample of every run, and the summary. |
|
||||
| `lookup-summary.txt` | The table `bench:lookup` printed for that run. |
|
||||
| `lookup-aa-raw.json`, `lookup-aa-summary.txt` | A/A noise check: the live router against the byte-identical frozen oracle (`test/router-parity/oracle.ts`), same alternating protocol. Any difference here is noise. |
|
||||
| `compare-e2e-raw.json`, `compare-e2e-summary.txt`, `compare-e2e-stderr.txt` | `npm run bench:compare`, run once with this tree as both base and head. **End-to-end req/s signal only**: 50/200 *filler* routes plus base routes, not 10/100/500 total, and not lookup time. It cannot decide D4. |
|
||||
| `load.txt` | `uptime` before and after each run. |
|
||||
|
||||
## Environment
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Hardware | Apple M4 Max (`Mac16,5`), 16 cores (12 performance + 4 efficiency), 64 GiB |
|
||||
| Power | **On battery** (84%, discharging) for every run. macOS may manage clocks differently on AC; run the CARD-10 comparison on the same power source, or re-capture both on AC. |
|
||||
| OS | macOS 27.0.1 (build 26A434), Darwin 27.0.0 arm64 |
|
||||
| Node | v22.22.2 (V8 12.4.254.21-node.39) |
|
||||
| Packages | `@green-tea/core@26.9.0-beta.2`; tsx 4.23.5, typescript 5.9.3, vitest 4.1.11, autocannon 8.0.0 (from `package-lock.json`) |
|
||||
| Core revision | Router source at `ed47836c9820c47bf4ed5e902d91e019abdb110a`. The harness ran from `98ea948` (this branch), whose `src/` is byte-identical to `ed47836` — the branch adds only tests and bench files. |
|
||||
| Env vars | `LOOKUP_OUT` only (and `LOOKUP_ROUTERS` for the A/A run); no `NODE_OPTIONS`. Recorded in each raw file under `meta.env`. |
|
||||
| Load | 1-minute load average 2.4–3.4 on 16 cores throughout (see `load.txt` and `meta.loadavgAtStart/End`). Foreground apps were a browser and the window server; nothing else CPU-bound. |
|
||||
|
||||
## Method (`bench/lookup.ts`, defaults)
|
||||
|
||||
- **Operation:** `resolveRoute(routes, method, path)`, and on `undefined`, `allowedMethods(routes, path)` — what `dispatch` does after `normalizeRequestPath`. Normalization is excluded.
|
||||
- **Route counts:** 10, 100 and 500 **total registered HTTP routes**.
|
||||
- **Generator:** N−2 fillers cycling `GET /res{k}/items`, `POST /res{k}/items`, `GET /res{k}/items/:id`, `PUT /res{k}/items/:id(\d+)`, `GET /res{k}/files/:path*` (k = ⌊i/5⌋), then `GET /static/target/leaf`, then `GET /late/:group/:id` declared last.
|
||||
- **Workloads:** static hit `GET /static/target/leaf`; late parameter hit `GET /late/g1/42`; method miss `DELETE /static/target/leaf` (Allow `GET, HEAD, OPTIONS`); path miss `GET /nowhere/at/all`. Each answer is asserted before timing.
|
||||
- **Order:** for each run, for each router (order alternates per run), for count 10 → 100 → 500, for the four workloads in the order above.
|
||||
- **Warm-up:** 250 ms per cell, time-boxed; it also calibrates iterations so one sample lasts ≈25 ms (iteration counts are stored per cell).
|
||||
- **Repetitions:** 5 runs, each a fresh child process; 21 samples per cell per run → 105 samples per cell. Every sample is kept.
|
||||
- **Statistic:** median ns per lookup over all 105 samples. Run spread = (max − min of the five per-run medians) / median.
|
||||
|
||||
## Baseline (median ns per lookup, `lookup-raw.json`)
|
||||
|
||||
| Routes | Static hit | Late param hit | Method miss | Path miss |
|
||||
|---:|---:|---:|---:|---:|
|
||||
| 10 | 61.3 (spread 17.5%) | 123.3 (6.2%) | 313.1 (4.6%) | 247.1 (6.8%) |
|
||||
| 100 | 67.6 (8.0%) | 343.4 (2.1%) | 1 263.7 (3.5%) | 1 463.3 (3.2%) |
|
||||
| 500 | 67.8 (7.5%) | 1 326.8 (16.5%) | 6 732.2 (6.5%) | 8 973.4 (2.0%) |
|
||||
|
||||
## Noise floor (A/A, `lookup-aa-raw.json`)
|
||||
|
||||
Identical matcher code under two labels, alternating order per run. Median difference
|
||||
(oracle − live) / live:
|
||||
|
||||
| Routes | Static hit | Late param hit | Method miss | Path miss |
|
||||
|---:|---:|---:|---:|---:|
|
||||
| 10 | +5.2% | 0.0% | +1.2% | +0.2% |
|
||||
| 100 | −0.1% | −0.8% | −0.1% | +0.1% |
|
||||
| 500 | −2.7% | +0.3% | −0.4% | +0.1% |
|
||||
|
||||
**For D4:** with no code difference at all, the 10-route static hit already moves 5.2% — the
|
||||
size of the proposed ≤5% regression limit — and per-run medians at 10 routes spread 4.5–17.5%.
|
||||
That cell is ~60 ns, where a few nanoseconds of timer and scheduling noise are a large fraction.
|
||||
The ≥20% improvement at 500 routes is well clear of the noise (≤2.7% A/A, ≤16.5% spread on a
|
||||
1.3–9 µs operation). Whether D4's 10-route limit applies per workload, to a mean across workloads,
|
||||
or needs more runs is an owner decision; this baseline does not make it.
|
||||
|
||||
## End-to-end signal (`bench:compare`, req/s — not lookup time)
|
||||
|
||||
Run once, A/A: `AB_BASE` pointed at this same tree, so base and head are identical code. Defaults:
|
||||
3 rounds × 10 s per case after a 10 s warm-up, 100 connections, alternating side order. Load
|
||||
average 2.8–3.3 throughout. A few short parity-test runs (seconds each) happened during this
|
||||
~22-minute run; the lookup runs above had nothing else running.
|
||||
|
||||
| Scenario | base req/s | head req/s | Δ |
|
||||
|---|---:|---:|---:|
|
||||
| hello | 88,212 | 88,236 | +0.0% |
|
||||
| param | 86,508 | 85,885 | −0.7% |
|
||||
| pipeline (3 steps) | 80,189 | 80,934 | +0.9% |
|
||||
| steps5 | 74,359 | 73,975 | −0.5% |
|
||||
| validate (POST) | 70,607 | 69,903 | −1.0% |
|
||||
| hello + security | 83,913 | 83,802 | −0.1% |
|
||||
| hello + cors predicate | 82,028 | 80,445 | −1.9% |
|
||||
| preflight + cors predicate | 114,377 | 114,010 | −0.3% |
|
||||
| param, 50 routes | 82,476 | 82,045 | −0.5% |
|
||||
| param, 200 routes | 72,957 | 73,306 | +0.5% |
|
||||
|
||||
Every row's sample ranges overlap. So with no code change, end-to-end throughput moves up to
|
||||
±1.9%; the route-width rows show that 200 filler routes already cost ~12% req/s against
|
||||
`param` with none.
|
||||
@@ -0,0 +1,207 @@
|
||||
{
|
||||
"rounds": 3,
|
||||
"duration": 10,
|
||||
"conns": 100,
|
||||
"rows": [
|
||||
{
|
||||
"name": "hello",
|
||||
"base": 88212.37,
|
||||
"head": 88235.64,
|
||||
"delta": 0.0263795202418936,
|
||||
"separated": false,
|
||||
"samples": {
|
||||
"base": [
|
||||
82493.1,
|
||||
88503.28,
|
||||
88212.37
|
||||
],
|
||||
"head": [
|
||||
88177.46,
|
||||
88235.64,
|
||||
92826.19
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "param",
|
||||
"base": 86507.64,
|
||||
"head": 85885.1,
|
||||
"delta": -0.7196358610638246,
|
||||
"separated": false,
|
||||
"samples": {
|
||||
"base": [
|
||||
81230.55,
|
||||
86757.82,
|
||||
86507.64
|
||||
],
|
||||
"head": [
|
||||
83412.37,
|
||||
86705.46,
|
||||
85885.1
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "pipeline (3 steps)",
|
||||
"base": 80189.1,
|
||||
"head": 80933.82,
|
||||
"delta": 0.9287047740902455,
|
||||
"separated": false,
|
||||
"samples": {
|
||||
"base": [
|
||||
76116.37,
|
||||
80189.1,
|
||||
80276.37
|
||||
],
|
||||
"head": [
|
||||
77035.64,
|
||||
80992,
|
||||
80933.82
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "steps5",
|
||||
"base": 74359.28,
|
||||
"head": 73975.28,
|
||||
"delta": -0.5164116704734096,
|
||||
"separated": false,
|
||||
"samples": {
|
||||
"base": [
|
||||
75272.73,
|
||||
74359.28,
|
||||
73928.73
|
||||
],
|
||||
"head": [
|
||||
72235.64,
|
||||
74813.1,
|
||||
73975.28
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "validate (POST)",
|
||||
"base": 70606.55,
|
||||
"head": 69902.55,
|
||||
"delta": -0.997074634010584,
|
||||
"separated": false,
|
||||
"samples": {
|
||||
"base": [
|
||||
70775.28,
|
||||
70606.55,
|
||||
69762.91
|
||||
],
|
||||
"head": [
|
||||
67138.91,
|
||||
74353.46,
|
||||
69902.55
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "hello + security",
|
||||
"base": 83912.73,
|
||||
"head": 83802.19,
|
||||
"delta": -0.13173209833596597,
|
||||
"separated": false,
|
||||
"samples": {
|
||||
"base": [
|
||||
81928.73,
|
||||
84709.82,
|
||||
83912.73
|
||||
],
|
||||
"head": [
|
||||
81742.55,
|
||||
83802.19,
|
||||
84512
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "hello + cors predicate",
|
||||
"base": 82027.64,
|
||||
"head": 80445.1,
|
||||
"delta": -1.9292765219138253,
|
||||
"separated": false,
|
||||
"samples": {
|
||||
"base": [
|
||||
82481.46,
|
||||
82027.64,
|
||||
81381.82
|
||||
],
|
||||
"head": [
|
||||
79368.73,
|
||||
82213.82,
|
||||
80445.1
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "preflight + cors predicate",
|
||||
"base": 114376.73,
|
||||
"head": 114010.19,
|
||||
"delta": -0.3204672838609686,
|
||||
"separated": false,
|
||||
"samples": {
|
||||
"base": [
|
||||
114580.37,
|
||||
114376.73,
|
||||
112322.91
|
||||
],
|
||||
"head": [
|
||||
109669.82,
|
||||
114813.1,
|
||||
114010.19
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "param, 50 routes",
|
||||
"base": 82475.64,
|
||||
"head": 82045.1,
|
||||
"delta": -0.5220208051734956,
|
||||
"separated": false,
|
||||
"samples": {
|
||||
"base": [
|
||||
82562.91,
|
||||
82475.64,
|
||||
82178.91
|
||||
],
|
||||
"head": [
|
||||
78891.64,
|
||||
82045.1,
|
||||
82388.37
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "param, 200 routes",
|
||||
"base": 72957.1,
|
||||
"head": 73306.19,
|
||||
"delta": 0.47848667230467834,
|
||||
"separated": false,
|
||||
"samples": {
|
||||
"base": [
|
||||
72986.19,
|
||||
72957.1,
|
||||
72194.91
|
||||
],
|
||||
"head": [
|
||||
72055.28,
|
||||
73306.19,
|
||||
73381.82
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"cors": {
|
||||
"base": {
|
||||
"get": 1,
|
||||
"preflight": 1
|
||||
},
|
||||
"head": {
|
||||
"get": 1,
|
||||
"preflight": 1
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
[compare] round 1 base hello 82,493 req/s
|
||||
[compare] round 1 base param 81,231 req/s
|
||||
[compare] round 1 base pipeline (3 steps) 76,116 req/s
|
||||
[compare] round 1 base steps5 75,273 req/s
|
||||
[compare] round 1 base validate (POST) 70,775 req/s
|
||||
[compare] round 1 base hello + security 81,929 req/s
|
||||
[compare] round 1 base hello + cors predicate 82,481 req/s
|
||||
[compare] round 1 base preflight + cors predicate 114,580 req/s
|
||||
[compare] round 1 base param, 50 routes 82,563 req/s
|
||||
[compare] round 1 base param, 200 routes 72,986 req/s
|
||||
[compare] round 1 head hello 88,177 req/s
|
||||
[compare] round 1 head param 83,412 req/s
|
||||
[compare] round 1 head pipeline (3 steps) 77,036 req/s
|
||||
[compare] round 1 head steps5 72,236 req/s
|
||||
[compare] round 1 head validate (POST) 67,139 req/s
|
||||
[compare] round 1 head hello + security 81,743 req/s
|
||||
[compare] round 1 head hello + cors predicate 79,369 req/s
|
||||
[compare] round 1 head preflight + cors predicate 109,670 req/s
|
||||
[compare] round 1 head param, 50 routes 78,892 req/s
|
||||
[compare] round 1 head param, 200 routes 72,055 req/s
|
||||
[compare] round 2 head hello 88,236 req/s
|
||||
[compare] round 2 head param 86,705 req/s
|
||||
[compare] round 2 head pipeline (3 steps) 80,992 req/s
|
||||
[compare] round 2 head steps5 74,813 req/s
|
||||
[compare] round 2 head validate (POST) 74,353 req/s
|
||||
[compare] round 2 head hello + security 83,802 req/s
|
||||
[compare] round 2 head hello + cors predicate 82,214 req/s
|
||||
[compare] round 2 head preflight + cors predicate 114,813 req/s
|
||||
[compare] round 2 head param, 50 routes 82,045 req/s
|
||||
[compare] round 2 head param, 200 routes 73,306 req/s
|
||||
[compare] round 2 base hello 88,503 req/s
|
||||
[compare] round 2 base param 86,758 req/s
|
||||
[compare] round 2 base pipeline (3 steps) 80,189 req/s
|
||||
[compare] round 2 base steps5 74,359 req/s
|
||||
[compare] round 2 base validate (POST) 70,607 req/s
|
||||
[compare] round 2 base hello + security 84,710 req/s
|
||||
[compare] round 2 base hello + cors predicate 82,028 req/s
|
||||
[compare] round 2 base preflight + cors predicate 114,377 req/s
|
||||
[compare] round 2 base param, 50 routes 82,476 req/s
|
||||
[compare] round 2 base param, 200 routes 72,957 req/s
|
||||
[compare] round 3 base hello 88,212 req/s
|
||||
[compare] round 3 base param 86,508 req/s
|
||||
[compare] round 3 base pipeline (3 steps) 80,276 req/s
|
||||
[compare] round 3 base steps5 73,929 req/s
|
||||
[compare] round 3 base validate (POST) 69,763 req/s
|
||||
[compare] round 3 base hello + security 83,913 req/s
|
||||
[compare] round 3 base hello + cors predicate 81,382 req/s
|
||||
[compare] round 3 base preflight + cors predicate 112,323 req/s
|
||||
[compare] round 3 base param, 50 routes 82,179 req/s
|
||||
[compare] round 3 base param, 200 routes 72,195 req/s
|
||||
[compare] round 3 head hello 92,826 req/s
|
||||
[compare] round 3 head param 85,885 req/s
|
||||
[compare] round 3 head pipeline (3 steps) 80,934 req/s
|
||||
[compare] round 3 head steps5 73,975 req/s
|
||||
[compare] round 3 head validate (POST) 69,903 req/s
|
||||
[compare] round 3 head hello + security 84,512 req/s
|
||||
[compare] round 3 head hello + cors predicate 80,445 req/s
|
||||
[compare] round 3 head preflight + cors predicate 114,010 req/s
|
||||
[compare] round 3 head param, 50 routes 82,388 req/s
|
||||
[compare] round 3 head param, 200 routes 73,382 req/s
|
||||
@@ -0,0 +1,21 @@
|
||||
|
||||
> @green-tea/core@26.9.0-beta.2 bench:compare
|
||||
> tsx bench/compare.ts
|
||||
|
||||
|
||||
| Scenario | base | head | Δ | |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| hello | 88,212 | 88,236 | +0.0% | overlaps |
|
||||
| param | 86,508 | 85,885 | -0.7% | overlaps |
|
||||
| pipeline (3 steps) | 80,189 | 80,934 | +0.9% | overlaps |
|
||||
| steps5 | 74,359 | 73,975 | -0.5% | overlaps |
|
||||
| validate (POST) | 70,607 | 69,903 | -1.0% | overlaps |
|
||||
| hello + security | 83,913 | 83,802 | -0.1% | overlaps |
|
||||
| hello + cors predicate | 82,028 | 80,445 | -1.9% | overlaps |
|
||||
| preflight + cors predicate | 114,377 | 114,010 | -0.3% | overlaps |
|
||||
| param, 50 routes | 82,476 | 82,045 | -0.5% | overlaps |
|
||||
| param, 200 routes | 72,957 | 73,306 | +0.5% | overlaps |
|
||||
|
||||
cors.origins calls — base: 1 per GET, 1 per preflight
|
||||
cors.origins calls — head: 1 per GET, 1 per preflight
|
||||
exit 0
|
||||
@@ -0,0 +1,6 @@
|
||||
uptime before: 17:01 up 9 days, 7:50, 1 user, load averages: 2.47 2.14 6.86
|
||||
uptime after: 17:02 up 9 days, 7:51, 1 user, load averages: 2.58 2.21 6.64
|
||||
A/A uptime before: 17:02 up 9 days, 7:51, 1 user, load averages: 3.42 2.40 6.66
|
||||
A/A uptime after: 17:03 up 9 days, 7:53, 1 user, load averages: 2.89 2.48 6.26
|
||||
bench:compare uptime before: 17:04 up 9 days, 7:53, 1 user, load averages: 2.98 2.51 6.25
|
||||
bench:compare uptime after: 17:26 up 9 days, 8:15, 1 user, load averages: 2.82 3.32 4.29
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,33 @@
|
||||
|
||||
> @green-tea/core@26.9.0-beta.2 bench:lookup
|
||||
> tsx bench/lookup.ts
|
||||
|
||||
| router | routes | workload | median ns/op | run medians (ns) | run spread |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| live | 10 | static hit | 62.0 | 57.9 / 65.8 / 60.3 / 62.7 / 61.8 | 12.7% |
|
||||
| live | 10 | late param hit | 123.8 | 124.0 / 120.4 / 122.1 / 124.3 / 128.4 | 6.4% |
|
||||
| live | 10 | method miss | 309.0 | 305.7 / 305.6 / 320.1 / 310.8 / 311.6 | 4.7% |
|
||||
| live | 10 | path miss | 248.4 | 242.7 / 242.5 / 253.7 / 251.0 / 248.7 | 4.5% |
|
||||
| live | 100 | static hit | 69.5 | 66.7 / 68.7 / 69.2 / 71.6 / 71.5 | 7.1% |
|
||||
| live | 100 | late param hit | 352.2 | 345.1 / 348.3 / 349.9 / 355.2 / 365.1 | 5.7% |
|
||||
| live | 100 | method miss | 1265.3 | 1273.8 / 1256.0 / 1254.2 / 1279.7 / 1267.1 | 2.0% |
|
||||
| live | 100 | path miss | 1464.9 | 1462.8 / 1451.3 / 1462.3 / 1485.2 / 1470.6 | 2.3% |
|
||||
| live | 500 | static hit | 67.8 | 67.2 / 66.9 / 68.1 / 69.3 / 67.7 | 3.4% |
|
||||
| live | 500 | late param hit | 1313.7 | 1362.0 / 1293.9 / 1309.7 / 1313.7 / 1316.9 | 5.2% |
|
||||
| live | 500 | method miss | 6778.2 | 7068.9 / 6783.2 / 6634.3 / 6816.4 / 6689.2 | 6.4% |
|
||||
| live | 500 | path miss | 9005.3 | 9445.9 / 9015.5 / 8965.0 / 9032.4 / 8834.1 | 6.8% |
|
||||
| oracle | 10 | static hit | 65.2 | 62.2 / 66.6 / 66.6 / 65.2 / 58.0 | 13.1% |
|
||||
| oracle | 10 | late param hit | 123.9 | 130.7 / 123.5 / 125.2 / 122.9 / 120.1 | 8.5% |
|
||||
| oracle | 10 | method miss | 312.7 | 311.4 / 314.2 / 312.2 / 316.8 / 309.1 | 2.4% |
|
||||
| oracle | 10 | path miss | 249.0 | 248.6 / 253.1 / 247.3 / 249.0 / 248.9 | 2.3% |
|
||||
| oracle | 100 | static hit | 69.4 | 69.5 / 71.1 / 69.8 / 67.5 / 66.7 | 6.4% |
|
||||
| oracle | 100 | late param hit | 349.3 | 347.5 / 352.5 / 349.6 / 347.2 / 354.0 | 1.9% |
|
||||
| oracle | 100 | method miss | 1263.6 | 1294.1 / 1243.1 / 1251.2 / 1286.5 / 1258.0 | 4.0% |
|
||||
| oracle | 100 | path miss | 1466.2 | 1511.6 / 1464.0 / 1459.5 / 1480.7 / 1449.1 | 4.3% |
|
||||
| oracle | 500 | static hit | 66.0 | 67.0 / 67.3 / 65.8 / 64.9 / 65.1 | 3.6% |
|
||||
| oracle | 500 | late param hit | 1317.6 | 1313.2 / 1310.2 / 1323.5 / 1294.5 / 1363.2 | 5.2% |
|
||||
| oracle | 500 | method miss | 6753.3 | 6717.3 / 6758.7 / 6666.4 / 6876.3 / 6750.7 | 3.1% |
|
||||
| oracle | 500 | path miss | 9015.3 | 8998.0 / 9021.6 / 8980.8 / 9100.7 / 8884.0 | 2.4% |
|
||||
|
||||
load average: start 3.42 2.40 6.66, end 2.89 2.48 6.26
|
||||
raw samples: bench/baseline/router-ed47836/lookup-aa-raw.json
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,21 @@
|
||||
|
||||
> @green-tea/core@26.9.0-beta.2 bench:lookup
|
||||
> tsx bench/lookup.ts
|
||||
|
||||
| router | routes | workload | median ns/op | run medians (ns) | run spread |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| live | 10 | static hit | 61.3 | 64.4 / 61.0 / 68.4 / 58.0 / 57.6 | 17.5% |
|
||||
| live | 10 | late param hit | 123.3 | 122.4 / 128.1 / 123.3 / 123.7 / 120.4 | 6.2% |
|
||||
| live | 10 | method miss | 313.1 | 303.2 / 314.0 / 317.6 / 317.2 / 304.7 | 4.6% |
|
||||
| live | 10 | path miss | 247.1 | 243.8 / 246.0 / 256.5 / 251.7 / 239.7 | 6.8% |
|
||||
| live | 100 | static hit | 67.6 | 67.6 / 70.3 / 71.7 / 66.9 / 66.3 | 8.0% |
|
||||
| live | 100 | late param hit | 343.4 | 339.7 / 345.5 / 346.8 / 343.0 / 341.0 | 2.1% |
|
||||
| live | 100 | method miss | 1263.7 | 1253.2 / 1236.5 / 1280.9 / 1261.0 / 1264.6 | 3.5% |
|
||||
| live | 100 | path miss | 1463.3 | 1444.6 / 1442.4 / 1489.2 / 1467.6 / 1467.1 | 3.2% |
|
||||
| live | 500 | static hit | 67.8 | 69.7 / 68.1 / 68.2 / 64.6 / 65.1 | 7.5% |
|
||||
| live | 500 | late param hit | 1326.8 | 1480.6 / 1262.0 / 1309.9 / 1328.9 / 1331.8 | 16.5% |
|
||||
| live | 500 | method miss | 6732.2 | 7072.0 / 6659.6 / 6796.0 / 6631.5 / 6699.6 | 6.5% |
|
||||
| live | 500 | path miss | 8973.4 | 8915.3 / 8994.7 / 9052.0 / 8876.0 / 8981.4 | 2.0% |
|
||||
|
||||
load average: start 2.47 2.14 6.86, end 2.58 2.21 6.64
|
||||
raw samples: bench/baseline/router-ed47836/lookup-raw.json
|
||||
@@ -0,0 +1,3 @@
|
||||
before: 2026-10-10T22:42:38Z 17:42:38 up 44 days, 17:31, 2 users, load average: 0.27, 0.11, 0.04
|
||||
ci job containers: 0
|
||||
after: 2026-10-10T22:43:54Z 17:43:54 up 44 days, 17:32, 2 users, load average: 0.79, 0.31, 0.12
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,44 @@
|
||||
| routes | workload | router | median ns/op | run medians (ns) | run spread |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 10 | static hit | live | 185.3 | 156.1 / 187.7 / 174.1 / 194.2 | 20.5% |
|
||||
| 10 | static hit | oracle | 176.8 | 199.9 / 161.9 / 195.0 / 162.5 | 21.5% |
|
||||
| 10 | late param hit | live | 328.4 | 311.9 / 336.2 / 323.0 / 342.4 | 9.3% |
|
||||
| 10 | late param hit | oracle | 337.6 | 343.0 / 329.2 / 356.3 / 324.3 | 9.5% |
|
||||
| 10 | method miss | live | 800.4 | 762.6 / 801.2 / 798.6 / 804.4 | 5.2% |
|
||||
| 10 | method miss | oracle | 768.8 | 770.0 / 764.6 / 833.1 / 762.5 | 9.2% |
|
||||
| 10 | path miss | live | 625.5 | 594.6 / 631.3 / 620.3 / 628.1 | 5.9% |
|
||||
| 10 | path miss | oracle | 606.6 | 603.8 / 610.1 / 657.9 / 591.5 | 10.9% |
|
||||
| 100 | static hit | live | 201.2 | 202.2 / 200.8 / 197.6 / 207.2 | 4.8% |
|
||||
| 100 | static hit | oracle | 206.9 | 211.7 / 196.6 / 213.9 / 201.7 | 8.4% |
|
||||
| 100 | late param hit | live | 878.0 | 861.1 / 857.0 / 907.3 / 880.5 | 5.7% |
|
||||
| 100 | late param hit | oracle | 893.0 | 888.7 / 869.0 / 942.1 / 895.2 | 8.2% |
|
||||
| 100 | method miss | live | 2524.8 | 2424.2 / 2513.7 / 2579.6 / 2531.5 | 6.2% |
|
||||
| 100 | method miss | oracle | 2515.2 | 2473.4 / 2527.3 / 2595.9 / 2509.5 | 4.9% |
|
||||
| 100 | path miss | live | 3054.2 | 2965.2 / 3023.7 / 3113.5 / 3070.6 | 4.9% |
|
||||
| 100 | path miss | oracle | 3075.6 | 3002.5 / 3087.9 / 3179.5 / 3064.3 | 5.8% |
|
||||
| 500 | static hit | live | 202.2 | 201.8 / 202.3 / 195.1 / 210.3 | 7.5% |
|
||||
| 500 | static hit | oracle | 206.3 | 212.1 / 197.8 / 213.2 / 201.1 | 7.5% |
|
||||
| 500 | late param hit | live | 2930.6 | 2829.6 / 2804.3 / 2980.0 / 3016.2 | 7.2% |
|
||||
| 500 | late param hit | oracle | 2878.8 | 2865.8 / 2832.6 / 2916.8 / 2881.2 | 2.9% |
|
||||
| 500 | method miss | live | 11903.6 | 11635.5 / 11518.4 / 11946.5 / 12031.2 | 4.3% |
|
||||
| 500 | method miss | oracle | 12101.5 | 11822.5 / 11856.4 / 12275.6 / 12190.0 | 3.7% |
|
||||
| 500 | path miss | live | 15513.7 | 15103.4 / 14971.6 / 15664.8 / 16034.1 | 6.8% |
|
||||
| 500 | path miss | oracle | 15719.6 | 15158.8 / 15479.0 / 16084.0 / 15885.7 | 5.9% |
|
||||
|
||||
| routes | workload | B / A | median ratio | 95% CI | rounds |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 10 | static hit | oracle / live | 0.9507 (-4.9%) | 0.8629 – 1.1186 (-13.7% … +11.9%) | 84 |
|
||||
| 10 | late param hit | oracle / live | 1.0415 (+4.1%) | 0.9840 – 1.0982 (-1.6% … +9.8%) | 84 |
|
||||
| 10 | method miss | oracle / live | 0.9809 (-1.9%) | 0.9563 – 1.0076 (-4.4% … +0.8%) | 84 |
|
||||
| 10 | path miss | oracle / live | 0.9919 (-0.8%) | 0.9676 – 1.0141 (-3.2% … +1.4%) | 84 |
|
||||
| 100 | static hit | oracle / live | 1.0082 (+0.8%) | 0.9808 – 1.0453 (-1.9% … +4.5%) | 84 |
|
||||
| 100 | late param hit | oracle / live | 1.0247 (+2.5%) | 1.0192 – 1.0292 (+1.9% … +2.9%) | 84 |
|
||||
| 100 | method miss | oracle / live | 1.0055 (+0.6%) | 1.0033 – 1.0072 (+0.3% … +0.7%) | 84 |
|
||||
| 100 | path miss | oracle / live | 1.0165 (+1.7%) | 1.0119 – 1.0185 (+1.2% … +1.9%) | 84 |
|
||||
| 500 | static hit | oracle / live | 1.0107 (+1.1%) | 0.9782 – 1.0453 (-2.2% … +4.5%) | 84 |
|
||||
| 500 | late param hit | oracle / live | 0.9838 (-1.6%) | 0.9784 – 1.0076 (-2.2% … +0.8%) | 84 |
|
||||
| 500 | method miss | oracle / live | 1.0197 (+2.0%) | 1.0161 – 1.0235 (+1.6% … +2.3%) | 84 |
|
||||
| 500 | path miss | oracle / live | 1.0161 (+1.6%) | 1.0047 – 1.0257 (+0.5% … +2.6%) | 84 |
|
||||
|
||||
load average: start 0.27 0.11 0.04, end 0.79 0.31 0.12; cpuset 6-7,14-15
|
||||
raw samples: out/lookup-raw.json
|
||||
+356
@@ -0,0 +1,356 @@
|
||||
/**
|
||||
* Focused route-lookup benchmark — the D4 instrument for the radix router (FPRD-001 CARD-08/10, #109).
|
||||
*
|
||||
* `bench:compare` measures req/s end to end, where lookup is a few percent of a request and drowns
|
||||
* in socket and pipeline noise. This measures the lookup alone: exactly what `dispatch` in
|
||||
* `src/http/core.ts` does with an already-normalized path — `resolveRoute`, and on a miss
|
||||
* `allowedMethods` for the 404/405 decision. Normalization is excluded: CARD-07 does not touch it.
|
||||
*
|
||||
* Usage:
|
||||
*
|
||||
* npm run bench:lookup
|
||||
* LOOKUP_ROUTERS="base=/tmp/base/src/http/router.ts,head=src/http/router.ts" npm run bench:lookup
|
||||
* LOOKUP_ROUTERS="live=src/http/router.ts,oracle=test/router-parity/oracle.ts" npm run bench:lookup # A/A
|
||||
*
|
||||
* Each router is a module exporting `resolveRoute` and `allowedMethods` with the `src/http/router.ts`
|
||||
* signatures. All routers are loaded into the same process and **interleaved**: per cell, every
|
||||
* router is warmed, then each round takes one sample from each router, alternating which goes first
|
||||
* (AB, BA, AB, ...). Every router after the first is reported against the first as the median of the
|
||||
* per-round B/A ratios, with a bootstrap 95% CI. Interleaving puts drift and background load on both
|
||||
* sides of each ratio instead of on whichever ran later. With one router it reports absolute numbers
|
||||
* only. Do not edit the generator, the workloads or the defaults between a baseline and its
|
||||
* comparison: they are the method.
|
||||
*
|
||||
* Env: `LOOKUP_ROUTERS` (label=path list, default `live=src/http/router.ts`), `LOOKUP_RUNS` (4 fresh
|
||||
* processes, import order alternating), `LOOKUP_ROUNDS` (21 per cell per run, minimum 15), `LOOKUP_SAMPLE_MS` (25),
|
||||
* `LOOKUP_WARMUP_MS` (250 per router per cell), `LOOKUP_OUT` (bench/lookup-results.json). Any other
|
||||
* `LOOKUP_*` variable (e.g. `LOOKUP_HOST`, `LOOKUP_CPUSET`) is copied into the record as a note.
|
||||
*/
|
||||
import { spawn, execFileSync } from 'child_process';
|
||||
import { writeFileSync, readFileSync } from 'fs';
|
||||
import os from 'os';
|
||||
import { dirname, resolve } from 'path';
|
||||
import { pathToFileURL } from 'url';
|
||||
|
||||
const ROUTE_COUNTS = [10, 100, 500];
|
||||
const RUNS = Number(process.env.LOOKUP_RUNS ?? 4);
|
||||
const ROUNDS = Math.max(15, Number(process.env.LOOKUP_ROUNDS ?? 21));
|
||||
const BOOTSTRAP = 4000;
|
||||
const SAMPLE_MS = Number(process.env.LOOKUP_SAMPLE_MS ?? 25);
|
||||
const WARMUP_MS = Number(process.env.LOOKUP_WARMUP_MS ?? 250);
|
||||
const OUT = process.env.LOOKUP_OUT ?? 'bench/lookup-results.json';
|
||||
|
||||
interface Route {
|
||||
method: string;
|
||||
pattern: string;
|
||||
transport: 'buffer';
|
||||
handler: () => Promise<{ status: number; headers: Record<string, string>; body: string }>;
|
||||
}
|
||||
|
||||
interface RouterModule {
|
||||
resolveRoute(routes: Route[], method: string, path: string): { def: Route } | undefined;
|
||||
allowedMethods(routes: Route[], path: string): string[];
|
||||
}
|
||||
|
||||
/** Five REST-shaped filler routes per resource, cycled, so every count has statics, params, constraints and catch-alls. */
|
||||
const FILLER: Array<(k: number) => [string, string]> = [
|
||||
(k) => ['GET', `/res${k}/items`],
|
||||
(k) => ['POST', `/res${k}/items`],
|
||||
(k) => ['GET', `/res${k}/items/:id`],
|
||||
(k) => ['PUT', `/res${k}/items/:id(\\d+)`],
|
||||
(k) => ['GET', `/res${k}/files/:path*`],
|
||||
];
|
||||
|
||||
export const ROUTE_GENERATOR =
|
||||
'N total HTTP routes: N-2 fillers (i = 0..N-3, shape FILLER[i % 5] with k = floor(i / 5): GET /res{k}/items, ' +
|
||||
'POST /res{k}/items, GET /res{k}/items/:id, PUT /res{k}/items/:id(\\d+), GET /res{k}/files/:path*), then ' +
|
||||
'GET /static/target/leaf, then GET /late/:group/:id declared last. All buffer transport.';
|
||||
|
||||
const handler = async () => ({ status: 200, headers: {}, body: '' });
|
||||
|
||||
export function buildRoutes(total: number): Route[] {
|
||||
const fillers = Array.from({ length: total - 2 }, (_, i): Route => {
|
||||
const [method, pattern] = FILLER[i % FILLER.length](Math.floor(i / FILLER.length));
|
||||
return { method, pattern, transport: 'buffer', handler };
|
||||
});
|
||||
return [
|
||||
...fillers,
|
||||
{ method: 'GET', pattern: '/static/target/leaf', transport: 'buffer', handler },
|
||||
{ method: 'GET', pattern: '/late/:group/:id', transport: 'buffer', handler },
|
||||
];
|
||||
}
|
||||
|
||||
interface Workload {
|
||||
name: string;
|
||||
method: string;
|
||||
path: string;
|
||||
/** What the lookup must answer; checked before timing, so a broken implementation cannot post a number. */
|
||||
expect: string;
|
||||
}
|
||||
|
||||
export const WORKLOADS: Workload[] = [
|
||||
{ name: 'static hit', method: 'GET', path: '/static/target/leaf', expect: 'hit /static/target/leaf' },
|
||||
{ name: 'late param hit', method: 'GET', path: '/late/g1/42', expect: 'hit /late/:group/:id' },
|
||||
{ name: 'method miss', method: 'DELETE', path: '/static/target/leaf', expect: 'allow GET,HEAD,OPTIONS' },
|
||||
{ name: 'path miss', method: 'GET', path: '/nowhere/at/all', expect: 'allow ' },
|
||||
];
|
||||
|
||||
/** One lookup, as `dispatch` performs it. Returns a value so the work cannot be optimised away. */
|
||||
function lookup(router: RouterModule, routes: Route[], w: Workload): string {
|
||||
const matched = router.resolveRoute(routes, w.method, w.path);
|
||||
if (matched) return `hit ${matched.def.pattern}`;
|
||||
return `allow ${router.allowedMethods(routes, w.path).join(',')}`;
|
||||
}
|
||||
|
||||
interface Cell {
|
||||
routes: number;
|
||||
workload: string;
|
||||
/** Calibrated per router; a sample is `iterations` lookups. */
|
||||
iterations: Record<string, number>;
|
||||
/** Round order, e.g. ['live', 'oracle'] then ['oracle', 'live']. */
|
||||
orders: string[][];
|
||||
/** One entry per router, one sample (ns per lookup) per round, in round order. */
|
||||
samplesNs: Record<string, number[]>;
|
||||
}
|
||||
|
||||
type Loaded = Array<{ label: string; router: RouterModule }>;
|
||||
|
||||
let sink = 0;
|
||||
|
||||
function warm(router: RouterModule, routes: Route[], w: Workload): number {
|
||||
const answer = lookup(router, routes, w);
|
||||
if (answer !== w.expect) throw new Error(`${w.name} @ ${routes.length}: expected '${w.expect}', got '${answer}'`);
|
||||
|
||||
// Time-boxed; it also calibrates how many iterations make one sample last SAMPLE_MS.
|
||||
let ops = 0;
|
||||
const warmStart = process.hrtime.bigint();
|
||||
const warmBudget = BigInt(WARMUP_MS * 1_000_000);
|
||||
while (process.hrtime.bigint() - warmStart < warmBudget) {
|
||||
for (let i = 0; i < 100; i++) sink += lookup(router, routes, w).length;
|
||||
ops += 100;
|
||||
}
|
||||
const nsPerOp = Number(process.hrtime.bigint() - warmStart) / ops;
|
||||
return Math.max(100, Math.round((SAMPLE_MS * 1e6) / nsPerOp));
|
||||
}
|
||||
|
||||
function sample(router: RouterModule, routes: Route[], w: Workload, iterations: number): number {
|
||||
const start = process.hrtime.bigint();
|
||||
for (let i = 0; i < iterations; i++) sink += lookup(router, routes, w).length;
|
||||
return Number(process.hrtime.bigint() - start) / iterations;
|
||||
}
|
||||
|
||||
function measureCell(loaded: Loaded, routes: Route[], w: Workload): Cell {
|
||||
const iterations: Record<string, number> = {};
|
||||
const samplesNs: Record<string, number[]> = {};
|
||||
const orders: string[][] = [];
|
||||
|
||||
for (const { label, router } of loaded) {
|
||||
iterations[label] = warm(router, routes, w);
|
||||
samplesNs[label] = [];
|
||||
}
|
||||
|
||||
for (let round = 0; round < ROUNDS; round++) {
|
||||
const order = round % 2 === 0 ? loaded : [...loaded].reverse();
|
||||
orders.push(order.map(({ label }) => label));
|
||||
for (const { label, router } of order) samplesNs[label].push(sample(router, routes, w, iterations[label]));
|
||||
}
|
||||
|
||||
return { routes: routes.length, workload: w.name, iterations, orders, samplesNs };
|
||||
}
|
||||
|
||||
async function child(routers: Array<[string, string]>): Promise<void> {
|
||||
// Import order alternates per run (LOOKUP_IMPORT_REVERSED): which copy V8 sees first can bias an
|
||||
// in-process comparison of otherwise identical code, and alternating spreads that over both sides.
|
||||
const imports = process.env.LOOKUP_IMPORT_REVERSED === '1' ? [...routers].reverse() : routers;
|
||||
const modules = new Map<string, RouterModule>();
|
||||
for (const [label, path] of imports)
|
||||
modules.set(label, (await import(pathToFileURL(resolve(path)).href)) as RouterModule);
|
||||
const loaded: Loaded = routers.map(([label]) => ({ label, router: modules.get(label)! }));
|
||||
|
||||
const cells: Cell[] = [];
|
||||
for (const count of ROUTE_COUNTS) {
|
||||
const routes = buildRoutes(count);
|
||||
for (const w of WORKLOADS) cells.push(measureCell(loaded, routes, w));
|
||||
}
|
||||
|
||||
if (sink === 42) process.stderr.write(''); // keeps `sink` observable
|
||||
process.stdout.write(`${JSON.stringify({ cells })}\n`);
|
||||
}
|
||||
|
||||
function runChild(spec: string, importReversed: boolean): Promise<{ cells: Cell[] }> {
|
||||
return new Promise((resolvePromise, reject) => {
|
||||
const proc = spawn(process.execPath, ['--import', 'tsx', 'bench/lookup.ts'], {
|
||||
env: { ...process.env, LOOKUP_CHILD: spec, LOOKUP_IMPORT_REVERSED: importReversed ? '1' : '0' },
|
||||
stdio: ['ignore', 'pipe', 'inherit'],
|
||||
});
|
||||
let out = '';
|
||||
proc.stdout.on('data', (d) => (out += d));
|
||||
proc.on('exit', (code) =>
|
||||
code === 0 ? resolvePromise(JSON.parse(out)) : reject(new Error(`child exited ${code}`)),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
const median = (xs: number[]): number => {
|
||||
const s = [...xs].sort((a, b) => a - b);
|
||||
const m = s.length >> 1;
|
||||
return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
|
||||
};
|
||||
|
||||
/** Deterministic PRNG for the bootstrap, so the same raw samples always give the same interval. */
|
||||
function mulberry32(seed: number): () => number {
|
||||
let state = seed >>> 0;
|
||||
return () => {
|
||||
state = (state + 0x6d2b79f5) >>> 0;
|
||||
let t = state;
|
||||
t = Math.imul(t ^ (t >>> 15), t | 1);
|
||||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
/** Percentile bootstrap 95% CI of the median of `xs`. */
|
||||
function bootstrapMedianCi(xs: number[]): [number, number] {
|
||||
const rng = mulberry32(10908);
|
||||
const medians: number[] = [];
|
||||
for (let b = 0; b < BOOTSTRAP; b++) medians.push(median(xs.map(() => xs[Math.floor(rng() * xs.length)])));
|
||||
medians.sort((a, b) => a - b);
|
||||
return [medians[Math.floor(BOOTSTRAP * 0.025)], medians[Math.ceil(BOOTSTRAP * 0.975) - 1]];
|
||||
}
|
||||
|
||||
function git(cwd: string, ...args: string[]): string {
|
||||
try {
|
||||
return execFileSync('git', ['-C', cwd, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
|
||||
} catch {
|
||||
return 'unavailable';
|
||||
}
|
||||
}
|
||||
|
||||
function cpuset(): string {
|
||||
for (const file of ['/sys/fs/cgroup/cpuset.cpus.effective', '/sys/fs/cgroup/cpuset/cpuset.effective_cpus']) {
|
||||
try {
|
||||
return readFileSync(file, 'utf8').trim();
|
||||
} catch {
|
||||
/* not Linux, or not this cgroup layout */
|
||||
}
|
||||
}
|
||||
return 'n/a';
|
||||
}
|
||||
|
||||
function environment(routers: Array<[string, string]>) {
|
||||
const pkg = JSON.parse(readFileSync('package.json', 'utf8')) as { name: string; version: string };
|
||||
return {
|
||||
startedAt: new Date().toISOString(),
|
||||
hostname: os.hostname(),
|
||||
node: process.version,
|
||||
v8: process.versions.v8,
|
||||
platform: `${os.platform()} ${os.release()} ${os.arch()}`,
|
||||
cpu: os.cpus()[0]?.model,
|
||||
cpus: os.cpus().length,
|
||||
cpuset: cpuset(),
|
||||
memoryBytes: os.totalmem(),
|
||||
loadavgAtStart: os.loadavg(),
|
||||
package: `${pkg.name}@${pkg.version}`,
|
||||
harnessCommit: process.env.LOOKUP_COMMIT ?? git('.', 'rev-parse', 'HEAD'),
|
||||
routers: routers.map(([label, path]) => ({ label, path })),
|
||||
env: Object.fromEntries(
|
||||
Object.entries(process.env).filter(([k]) => k.startsWith('LOOKUP_') || k === 'NODE_OPTIONS'),
|
||||
),
|
||||
method: {
|
||||
routeCounts: ROUTE_COUNTS,
|
||||
routeCountMeaning: 'total registered HTTP routes',
|
||||
routeGenerator: ROUTE_GENERATOR,
|
||||
workloads: WORKLOADS,
|
||||
workloadOrder:
|
||||
'for each run (fresh process; module import order reversed on even-numbered runs): for count in routeCounts: ' +
|
||||
'for workload in workloads: warm every router, ' +
|
||||
'then ROUNDS rounds of one sample per router, order alternating AB/BA per round',
|
||||
operation: 'resolveRoute(routes, method, path); on undefined, allowedMethods(routes, path)',
|
||||
runs: RUNS,
|
||||
roundsPerCellPerRun: ROUNDS,
|
||||
sampleMs: SAMPLE_MS,
|
||||
warmupMsPerRouterPerCell: WARMUP_MS,
|
||||
ratio: 'per round, sample(B) / sample(A) with A the first router; median over all rounds of all runs',
|
||||
ci: `percentile bootstrap of the median ratio, ${BOOTSTRAP} resamples, seed 10908`,
|
||||
unit: 'ns per lookup (sample time / iterations)',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function summarize(labels: string[], runs: Array<{ run: number; cells: Cell[] }>) {
|
||||
return ROUTE_COUNTS.flatMap((count) =>
|
||||
WORKLOADS.map((w) => {
|
||||
const cells = runs.map((r) => r.cells.find((c) => c.routes === count && c.workload === w.name)!);
|
||||
const routers = labels.map((label) => {
|
||||
const runMedians = cells.map((c) => median(c.samplesNs[label]));
|
||||
const med = median(cells.flatMap((c) => c.samplesNs[label]));
|
||||
return {
|
||||
router: label,
|
||||
medianNs: med,
|
||||
runMediansNs: runMedians,
|
||||
runSpreadPct: ((Math.max(...runMedians) - Math.min(...runMedians)) / med) * 100,
|
||||
};
|
||||
});
|
||||
const ratios = labels.slice(1).map((label) => {
|
||||
const paired = cells.flatMap((c) => c.samplesNs[label].map((b, i) => b / c.samplesNs[labels[0]][i]));
|
||||
const [low, high] = bootstrapMedianCi(paired);
|
||||
return { b: label, a: labels[0], medianRatio: median(paired), ci95: [low, high], rounds: paired.length };
|
||||
});
|
||||
return { routes: count, workload: w.name, routers, ratios };
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const pct = (ratio: number): string => `${ratio >= 1 ? '+' : ''}${((ratio - 1) * 100).toFixed(1)}%`;
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const spec = process.env.LOOKUP_CHILD
|
||||
? process.env.LOOKUP_CHILD
|
||||
: (process.env.LOOKUP_ROUTERS ?? 'live=src/http/router.ts');
|
||||
const routers = spec.split(',').map((entry) => entry.split('=') as [string, string]);
|
||||
if (process.env.LOOKUP_CHILD) return child(routers);
|
||||
|
||||
const labels = routers.map(([label]) => label);
|
||||
const meta = environment(routers);
|
||||
const runs: Array<{ run: number; importReversed: boolean; cells: Cell[] }> = [];
|
||||
|
||||
for (let run = 0; run < RUNS; run++) {
|
||||
runs.push({ run: run + 1, importReversed: run % 2 === 1, ...(await runChild(spec, run % 2 === 1)) });
|
||||
process.stderr.write(`[lookup] run ${run + 1}/${RUNS} done\n`);
|
||||
}
|
||||
|
||||
const summary = summarize(labels, runs);
|
||||
const loadavgAtEnd = os.loadavg();
|
||||
writeFileSync(OUT, `${JSON.stringify({ meta: { ...meta, loadavgAtEnd }, summary, runs }, null, 2)}\n`);
|
||||
|
||||
console.log('| routes | workload | router | median ns/op | run medians (ns) | run spread |');
|
||||
console.log('| --- | --- | --- | --- | --- | --- |');
|
||||
for (const cell of summary)
|
||||
for (const r of cell.routers)
|
||||
console.log(
|
||||
`| ${cell.routes} | ${cell.workload} | ${r.router} | ${r.medianNs.toFixed(1)} | ` +
|
||||
`${r.runMediansNs.map((n) => n.toFixed(1)).join(' / ')} | ${r.runSpreadPct.toFixed(1)}% |`,
|
||||
);
|
||||
|
||||
if (labels.length > 1) {
|
||||
console.log('\n| routes | workload | B / A | median ratio | 95% CI | rounds |');
|
||||
console.log('| --- | --- | --- | --- | --- | --- |');
|
||||
for (const cell of summary)
|
||||
for (const r of cell.ratios)
|
||||
console.log(
|
||||
`| ${cell.routes} | ${cell.workload} | ${r.b} / ${r.a} | ${r.medianRatio.toFixed(4)} (${pct(r.medianRatio)}) | ` +
|
||||
`${r.ci95.map((x) => x.toFixed(4)).join(' – ')} (${pct(r.ci95[0])} … ${pct(r.ci95[1])}) | ${r.rounds} |`,
|
||||
);
|
||||
}
|
||||
|
||||
console.log(
|
||||
`\nload average: start ${meta.loadavgAtStart.map((n) => n.toFixed(2)).join(' ')}, ` +
|
||||
`end ${loadavgAtEnd.map((n) => n.toFixed(2)).join(' ')}; cpuset ${meta.cpuset}`,
|
||||
);
|
||||
console.log(`raw samples: ${OUT}`);
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -27,7 +27,7 @@
|
||||
"npm:@types/autocannon@^7.12.7",
|
||||
"npm:@types/busboy@^1.5.4",
|
||||
"npm:@types/express@^5.0.6",
|
||||
"npm:@types/node@^18.19.0",
|
||||
"npm:@types/node@^22.20.5",
|
||||
"npm:@types/ws@^8.18.1",
|
||||
"npm:autocannon@8",
|
||||
"npm:busboy@^1.6.0",
|
||||
@@ -35,7 +35,7 @@
|
||||
"npm:esbuild@0.27.2",
|
||||
"npm:eslint@^9.39.5",
|
||||
"npm:express@^5.2.1",
|
||||
"npm:fastify@^5.11.0",
|
||||
"npm:fastify@^5.12.5",
|
||||
"npm:graphql@^16.9.0",
|
||||
"npm:miniflare@^4.20260730.0",
|
||||
"npm:prettier@^3.9.6",
|
||||
@@ -46,7 +46,7 @@
|
||||
"npm:typescript-eslint@^8.65.0",
|
||||
"npm:typescript@^5.5.0",
|
||||
"npm:vite@^6.4.3",
|
||||
"npm:vitest@^3.2.7",
|
||||
"npm:vitest@^4.1.11",
|
||||
"npm:ws@^8.21.1"
|
||||
],
|
||||
"overrides": {
|
||||
@@ -56,7 +56,9 @@
|
||||
"uuid": "11.1.1"
|
||||
}
|
||||
},
|
||||
"undici": "7.29.0"
|
||||
"undici": "7.29.1",
|
||||
"sharp": "0.35.5",
|
||||
"fastify": "$fastify"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+387
-525
File diff suppressed because it is too large.
Load diff
+9
-5
@@ -26,7 +26,7 @@
|
||||
"node"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
"node": ">=22"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
@@ -103,6 +103,8 @@
|
||||
"complexity:cyclomatic": "cyclomatic-complexity \"src/**/*.ts\" -tw 15 -te 25",
|
||||
"bench": "tsx bench/run.ts",
|
||||
"bench:compare": "tsx bench/compare.ts",
|
||||
"bench:lookup": "tsx bench/lookup.ts",
|
||||
"parity:mutants": "tsx test/router-parity/mutants.ts",
|
||||
"prepublishOnly": "npm run lint && npm run complexity:check && npm run typecheck && npm test && npm run build",
|
||||
"prepare": "git config core.hooksPath .githooks || true"
|
||||
},
|
||||
@@ -128,7 +130,9 @@
|
||||
"uuid": "11.1.1"
|
||||
}
|
||||
},
|
||||
"undici": "7.29.0"
|
||||
"undici": "7.29.1",
|
||||
"sharp": "0.35.5",
|
||||
"fastify": "$fastify"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.5",
|
||||
@@ -140,7 +144,7 @@
|
||||
"@types/autocannon": "^7.12.7",
|
||||
"@types/busboy": "^1.5.4",
|
||||
"@types/express": "^5.0.6",
|
||||
"@types/node": "^18.19.0",
|
||||
"@types/node": "^22.20.5",
|
||||
"@types/ws": "^8.18.1",
|
||||
"autocannon": "^8.0.0",
|
||||
"busboy": "^1.6.0",
|
||||
@@ -148,7 +152,7 @@
|
||||
"eslint": "^9.39.5",
|
||||
"esbuild": "0.27.2",
|
||||
"express": "^5.2.1",
|
||||
"fastify": "^5.11.0",
|
||||
"fastify": "^5.12.5",
|
||||
"graphql": "^16.9.0",
|
||||
"miniflare": "^4.20260730.0",
|
||||
"prettier": "^3.9.6",
|
||||
@@ -158,7 +162,7 @@
|
||||
"typescript": "^5.5.0",
|
||||
"typescript-eslint": "^8.65.0",
|
||||
"vite": "^6.4.3",
|
||||
"vitest": "^3.2.7",
|
||||
"vitest": "^4.1.11",
|
||||
"ws": "^8.21.1"
|
||||
}
|
||||
}
|
||||
+39
-15
@@ -8,7 +8,17 @@ import { runPipeline, runSteps, PipelineStep } from '../pipeline';
|
||||
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http';
|
||||
import type { HttpOptions } from '../http';
|
||||
import { buildFetch } from '../http/web';
|
||||
import { matchWsRoute, runWsConnection, trackUntil, type WsRequest, type WsSocket } from '../http/ws-core';
|
||||
import {
|
||||
boundInbound,
|
||||
validateWsLimits,
|
||||
WS_MAX_MESSAGE_BYTES,
|
||||
wsMessageBytes,
|
||||
matchWsRoute,
|
||||
runWsConnection,
|
||||
trackUntil,
|
||||
type WsRequest,
|
||||
type WsSocket,
|
||||
} from '../http/ws-core';
|
||||
import { isAsyncIterable } from '../channel';
|
||||
import { JsonTransformer, type ErrorRenderer } from '../transformers';
|
||||
import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin';
|
||||
@@ -39,7 +49,7 @@ import type { MeshControl } from '../http';
|
||||
import type { RequestEnvelope, RouteEntry } from '../mesh/protocol';
|
||||
import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types';
|
||||
import { inspectRoute, buildGraphView, explainRoute } from './introspect';
|
||||
import { compilePattern } from '../http/router';
|
||||
import { compilePattern, normalizeRequestPath } from '../http/router';
|
||||
|
||||
export type { App, InspectLine, ExplainNode, Explain, MeshConfig, Hooks } from './types';
|
||||
|
||||
@@ -195,6 +205,8 @@ export function createApp(opts: {
|
||||
);
|
||||
}
|
||||
|
||||
validateWsLimits(opts.limits);
|
||||
|
||||
const bus = new Bus();
|
||||
const logger = opts.logger ?? createDefaultLogger();
|
||||
if (opts.logRequests) logRequests(bus, logger);
|
||||
@@ -318,7 +330,7 @@ export function createApp(opts: {
|
||||
devRoutes,
|
||||
() => remoteRoutes,
|
||||
);
|
||||
const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl);
|
||||
const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl, opts.limits);
|
||||
|
||||
const listen = async (port: number): Promise<http.Server> => {
|
||||
const deps = pipelineDeps;
|
||||
@@ -387,7 +399,7 @@ export function createApp(opts: {
|
||||
return wrapped;
|
||||
};
|
||||
|
||||
return {
|
||||
const app: App = {
|
||||
listen,
|
||||
close,
|
||||
handleSignals,
|
||||
@@ -405,6 +417,10 @@ export function createApp(opts: {
|
||||
bus,
|
||||
logger,
|
||||
};
|
||||
|
||||
return Object.assign(app, {
|
||||
[WS_MAX_MESSAGE_BYTES]: wsMessageBytes(opts.limits),
|
||||
});
|
||||
}
|
||||
|
||||
/** Creates an empty {@link Registry} whose `setRunner` enforces globally-unique provider/step names. */
|
||||
@@ -1275,22 +1291,30 @@ function buildAppUpgrade(
|
||||
streams: Set<() => void>,
|
||||
ensureBooted: () => Promise<void>,
|
||||
getMeshControl: () => MeshControl | undefined,
|
||||
limits?: RequestLimits,
|
||||
): (request: WsRequest, socket: WsSocket) => Promise<void> {
|
||||
let wsRoutes: WsRouteDef[] | undefined;
|
||||
|
||||
return async (request: WsRequest, socket: WsSocket): Promise<void> => {
|
||||
// Subscribe to inbound BEFORE awaiting the boot. `channel` is fan-out: a frame pushed with no
|
||||
// subscriber is dropped, so anything the peer sends while providers are still booting would be
|
||||
// lost. For the mesh control channel that is the `hello` itself — the handshake would hang
|
||||
// until timeout against a teapot whose providers happened to boot slowly.
|
||||
const frames = socket.inbound[Symbol.asyncIterator]();
|
||||
const ready: WsSocket = Object.create(socket, {
|
||||
inbound: { value: { [Symbol.asyncIterator]: () => frames } },
|
||||
}) as WsSocket;
|
||||
// Bound and subscribe to inbound BEFORE awaiting the boot. `channel` is fan-out: a frame pushed
|
||||
// with no subscriber is dropped, so anything the peer sends while providers are still booting
|
||||
// would be lost. For the mesh control channel that is the `hello` itself — the handshake would
|
||||
// hang until timeout against a teapot whose providers happened to boot slowly.
|
||||
const ready = boundInbound(socket, limits);
|
||||
|
||||
await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted
|
||||
|
||||
const path = request.url.split('?')[0];
|
||||
let path: string;
|
||||
|
||||
// The same normalization HTTP and the Node upgrade listener run. A malformed escape would
|
||||
// otherwise reject out of the matcher and close with 1011, a server-error code for a client error.
|
||||
try {
|
||||
path = normalizeRequestPath(request.url.split('?')[0]);
|
||||
} catch {
|
||||
ready.close(1008, 'invalid request path');
|
||||
return;
|
||||
}
|
||||
|
||||
const meshControl = getMeshControl();
|
||||
|
||||
// The reserved mesh path, checked before route matching: this is what lets a teapot export
|
||||
@@ -1489,8 +1513,8 @@ function closeApp(
|
||||
timeoutMs,
|
||||
});
|
||||
|
||||
// closeAllConnections() requires Node >=18.2, same floor as closeIdleConnections()
|
||||
// below — `engines` in package.json only guarantees >=18, so this matters.
|
||||
// closeAllConnections() and closeIdleConnections() below both arrived in Node 18.2;
|
||||
// `engines` guarantees >=22, so both are always present.
|
||||
server.closeAllConnections();
|
||||
finish();
|
||||
}, drainBudget);
|
||||
|
||||
+11
-1
@@ -1,9 +1,10 @@
|
||||
import { channel } from './channel';
|
||||
import type { Channel } from './channel';
|
||||
import type { App } from './app/types';
|
||||
import type { WsSocket, WsRequest } from './http/ws-core';
|
||||
import { WS_MAX_MESSAGE_BYTES, DEFAULT_MAX_WS_MESSAGE_BYTES, type WsSocket, type WsRequest } from './http/ws-core';
|
||||
import { decodeMessage, neutralSocket, toWsRequest, upgradeSafely } from './http/ws-adapter';
|
||||
import { closeWithDeadline } from './http/shutdown';
|
||||
import { setPeer } from './http/peer';
|
||||
|
||||
// Minimal ambient for the Bun globals we use — avoids a @types/bun devDep.
|
||||
// Mirrors the real Bun.serve / server.upgrade / ServerWebSocket signatures we call.
|
||||
@@ -15,6 +16,7 @@ interface BunServerWebSocket {
|
||||
terminate?(): void;
|
||||
}
|
||||
interface BunWebSocketHandler {
|
||||
maxPayloadLength?: number;
|
||||
open?(ws: BunServerWebSocket): void;
|
||||
message(ws: BunServerWebSocket, message: string | Uint8Array): void;
|
||||
close?(ws: BunServerWebSocket, code: number, reason: string): void;
|
||||
@@ -100,9 +102,17 @@ export async function serveBun(app: App, options?: BunServeShortOptions): Promis
|
||||
return new Response('WebSocket upgrade failed', { status: 400 });
|
||||
}
|
||||
|
||||
// The same object goes to `app.fetch`, which is what lets it find the peer again.
|
||||
setPeer(request, server.requestIP(request)?.address ?? '');
|
||||
return app.fetch(request);
|
||||
},
|
||||
websocket: {
|
||||
// The pre-buffer half of `limits.maxWsMessageBytes`: Bun refuses an oversized frame before
|
||||
// assembling it. It drops the connection without a close frame, so the peer sees 1006 rather
|
||||
// than 1009 — verified on Bun 1.3, and the price of not buffering the message at all.
|
||||
// `app.upgrade` checks the same bound again on the decoded text.
|
||||
maxPayloadLength:
|
||||
(app as { [WS_MAX_MESSAGE_BYTES]?: number })[WS_MAX_MESSAGE_BYTES] ?? DEFAULT_MAX_WS_MESSAGE_BYTES,
|
||||
open(ws) {
|
||||
const { wsReq } = ws.data as BunConnData;
|
||||
|
||||
|
||||
+31
-2
@@ -14,6 +14,26 @@ export function isAsyncIterable(x: unknown): x is AsyncIterable<unknown> {
|
||||
return x != null && typeof (x as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === 'function';
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal: reads a channel synchronously, inside `push`, rather than through an async iterator
|
||||
* that only drains once the event loop yields. `boundInbound` needs it to bound a WebSocket burst
|
||||
* frame by frame, before anything is queued (#107). Not exported from the package; `Symbol.for`
|
||||
* because each tsup entry carries its own copy of this module.
|
||||
*/
|
||||
export const CHANNEL_TAP: unique symbol = Symbol.for('green-tea.channel-tap');
|
||||
|
||||
/** What {@link CHANNEL_TAP} calls, synchronously, for every push, close and fail. */
|
||||
export interface ChannelSink<T> {
|
||||
push(value: T): void;
|
||||
end(): void;
|
||||
fail(err: unknown): void;
|
||||
}
|
||||
|
||||
/** A channel that can be tapped; every channel built by {@link channel} is one. */
|
||||
export interface TappableChannel<T> extends Channel<T> {
|
||||
[CHANNEL_TAP](sink: ChannelSink<T>): () => void;
|
||||
}
|
||||
|
||||
interface Sub<T> {
|
||||
iterator: AsyncIterator<T>;
|
||||
push(value: T, cap: number): void;
|
||||
@@ -84,9 +104,9 @@ function newSub<T>(onReturn: () => void): Sub<T> {
|
||||
* Creates a fan-out {@link Channel}. Values pushed are delivered to every active subscriber.
|
||||
* @param opts.buffer Per-subscriber queue cap; drops oldest when exceeded (default: unbounded).
|
||||
*/
|
||||
export function channel<T>(opts: { buffer?: number } = {}): Channel<T> {
|
||||
export function channel<T>(opts: { buffer?: number } = {}): TappableChannel<T> {
|
||||
const cap = opts.buffer ?? Infinity;
|
||||
const subs = new Set<Sub<T>>();
|
||||
const subs = new Set<Omit<Sub<T>, 'iterator'>>();
|
||||
let done = false;
|
||||
let closedFlag = false;
|
||||
|
||||
@@ -117,5 +137,14 @@ export function channel<T>(opts: { buffer?: number } = {}): Channel<T> {
|
||||
subs.add(sub);
|
||||
return sub.iterator;
|
||||
},
|
||||
[CHANNEL_TAP](sink) {
|
||||
if (done) {
|
||||
sink.end();
|
||||
return () => {};
|
||||
}
|
||||
|
||||
subs.add(sink);
|
||||
return () => subs.delete(sink);
|
||||
},
|
||||
};
|
||||
}
|
||||
+6
-2
@@ -1,9 +1,10 @@
|
||||
import type { App } from './app/types';
|
||||
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
|
||||
import { closeWithDeadline } from './http/shutdown';
|
||||
import { setPeer } from './http/peer';
|
||||
|
||||
// The project tsconfig's `lib` doesn't include `DOM`, and the installed `@types/node` (18.x)
|
||||
// doesn't declare a global `WebSocket` either — so we ambient-declare just the shape we use.
|
||||
// The project tsconfig's `lib` doesn't include `DOM`, so we ambient-declare just the shape of
|
||||
// Deno's `WebSocket` we use rather than rely on whichever global `@types/node` happens to declare.
|
||||
interface WebSocket extends EventfulSocket {
|
||||
binaryType: string;
|
||||
}
|
||||
@@ -82,6 +83,9 @@ export async function serveDeno(app: App, options?: DenoServeOptions): Promise<D
|
||||
return response;
|
||||
}
|
||||
|
||||
// The same object goes to `app.fetch`, which is what lets it find the peer again. A unix socket
|
||||
// has no `hostname`, and records nothing.
|
||||
setPeer(request, info.remoteAddr.hostname);
|
||||
return app.fetch(request);
|
||||
});
|
||||
|
||||
|
||||
+14
-6
@@ -22,12 +22,11 @@ function isPromise<T>(value: MaybePromise<T>): value is Promise<T> {
|
||||
/**
|
||||
* Reads the raw request body, enforcing `limit`.
|
||||
*
|
||||
* The adapter owns this and nothing else about the body, because enforcement is the one place the
|
||||
* runtimes legitimately differ: Node checks the running total as chunks arrive and can abort a
|
||||
* 10 GB upload after 1 MB, while a fetch runtime has only `request.arrayBuffer()` and can check
|
||||
* `byteLength` after the fact. Passing the limit *in*, rather than measuring the returned buffer
|
||||
* here, is what keeps Node's incremental abort — measuring afterwards would force it to buffer
|
||||
* without bound first.
|
||||
* The adapter owns this and nothing else about the body, because getting the bytes is the one place
|
||||
* the runtimes legitimately differ: Node iterates the socket, a fetch runtime reads `request.body`.
|
||||
* Both check the running total as chunks arrive and abort a 10 GB upload after 1 MB. Passing the
|
||||
* limit *in*, rather than measuring the returned buffer here, is what makes that incremental abort
|
||||
* possible — measuring afterwards would force the reader to buffer without bound first.
|
||||
*
|
||||
* The failure branch is opaque on purpose: Node answers an over-limit request with
|
||||
* `connection: close`, so the rest of the upload does not keep arriving on a kept-alive socket.
|
||||
@@ -41,6 +40,15 @@ function isPromise<T>(value: MaybePromise<T>): value is Promise<T> {
|
||||
*/
|
||||
export type BodyReader = (source: unknown, limit: number) => MaybePromise<{ bytes: Buffer | undefined } | BodyFailure>;
|
||||
|
||||
/**
|
||||
* True when a `content-length` header declares more than `limit` bytes — the one case a reader can
|
||||
* refuse before consuming anything. A malformed or absent header answers false: it proves nothing,
|
||||
* and the running total still enforces the limit on whatever actually arrives.
|
||||
*/
|
||||
export function declaresOverLimit(contentLength: string | null | undefined, limit: number): boolean {
|
||||
return contentLength != null && /^\d+$/.test(contentLength) && Number(contentLength) > limit;
|
||||
}
|
||||
|
||||
/** Parse outcome: the decoded body, or an error message plus the status to send (400 unless set). */
|
||||
type ParseResult = { body: unknown } | { error: string; status?: number };
|
||||
|
||||
|
||||
+5
-21
@@ -9,31 +9,15 @@ import { acquireBody, type BodyReader } from './body';
|
||||
import type { RouteDef, HttpOptions } from './types';
|
||||
import type { StreamEncoder } from '../encoders';
|
||||
import type { Bus } from '../bus';
|
||||
import { nodeRequire } from '../node-require';
|
||||
|
||||
/**
|
||||
* `randomUUID`, from wherever this runtime keeps it. Resolved once, at import.
|
||||
* `randomUUID` from the web-standard global, which every supported runtime exposes without a flag:
|
||||
* Node (the `engines` floor is 22; the global arrived unflagged in 19), Deno, Bun and workerd.
|
||||
*
|
||||
* The web-standard global stays the primary path, and that is deliberate rather than stylistic:
|
||||
* this file is the runtime-neutral core, and Deno, Bun and workerd all expose `crypto` without a
|
||||
* compatibility flag, while `node:crypto` is unavailable to at least one of them.
|
||||
*
|
||||
* Node is the exception. The global arrived **unflagged in 19**, and `engines` promises `>=18`,
|
||||
* where it does not exist at all — so the previous `declare const crypto` compiled cleanly and then
|
||||
* threw `ReferenceError: crypto is not defined` on the first request of every Node 18 process. Only
|
||||
* CI's Node 18 job caught it; every newer Node and every other runtime hides it, which is exactly
|
||||
* why that job is pinned to the floor rather than to the current release.
|
||||
*
|
||||
* The fallback is reached only by a runtime that lacks the global, so workerd never evaluates it.
|
||||
* It goes through {@link nodeRequire} rather than a bare `require`, which is what makes it work on
|
||||
* every distribution of this package and not just the bundled ones.
|
||||
* Node 18 lacked it, and this used to fall back to `node:crypto` there. That fallback went with the
|
||||
* Node 18 floor.
|
||||
*/
|
||||
const randomUUID: () => string = (() => {
|
||||
const webCrypto = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;
|
||||
if (typeof webCrypto?.randomUUID === 'function') return () => webCrypto.randomUUID!();
|
||||
|
||||
return nodeRequire<{ randomUUID: () => string }>('node:crypto').randomUUID;
|
||||
})();
|
||||
const randomUUID = (): string => crypto.randomUUID();
|
||||
|
||||
/**
|
||||
* A runtime-neutral inbound request.
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
// src/http/peer.ts — the socket peer address, handed from the Deno and Bun adapters to `buildFetch`.
|
||||
// Internal: not exported from the package.
|
||||
//
|
||||
// Keyed by the `Request` object rather than carried on it. A header would be visible to handlers and
|
||||
// spoofable by any client that sent one with the same name; a second `fetch` parameter would be
|
||||
// public API. The adapters call `app.fetch` with the very object they record, so identity holds, and
|
||||
// the entry goes when the request does. A `Request` copied from it carries nothing, which is what a
|
||||
// bare `app.fetch` from user code has always seen.
|
||||
//
|
||||
// The map lives on `globalThis` under a registered symbol, not in this module, because this module
|
||||
// is not always one instance. The CommonJS build bundles `index`, `deno` and `bun` as separate files
|
||||
// with no shared chunk, so each carries its own copy of this one: a module-private map in
|
||||
// `@green-tea/core/bun` would record peers that `app.fetch` from `@green-tea/core` never sees. An app
|
||||
// that loads core both as ESM and as CommonJS has the same split.
|
||||
const KEY = Symbol.for('@green-tea/core:peer');
|
||||
const registry = globalThis as { [KEY]?: WeakMap<Request, string> };
|
||||
const peers = (registry[KEY] ??= new WeakMap<Request, string>());
|
||||
|
||||
/** Records `ip` as the peer of `request`. An empty address — a unix socket has none — is not recorded. */
|
||||
export function setPeer(request: Request, ip: string): void {
|
||||
if (ip) peers.set(request, ip);
|
||||
}
|
||||
|
||||
/** The peer an adapter recorded for `request`, or `''` when none did. */
|
||||
export function peerOf(request: Request): string {
|
||||
return peers.get(request) ?? '';
|
||||
}
|
||||
@@ -1,8 +1,13 @@
|
||||
import type http from 'http';
|
||||
import { HttpError } from '../signals';
|
||||
import { declaresOverLimit } from './body';
|
||||
|
||||
/** Reads the full request body, enforcing the max-bytes ceiling (throws 413 if exceeded). */
|
||||
export async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise<Buffer | undefined> {
|
||||
// A declared length over the limit is refused without waiting for the first chunk, which could
|
||||
// otherwise sit until the request timeout. The fetch adapter makes the same check.
|
||||
if (declaresOverLimit(req.headers['content-length'], maxBodyBytes)) throw new HttpError(413, 'Payload Too Large');
|
||||
|
||||
const chunks: Buffer[] = [];
|
||||
let total = 0;
|
||||
|
||||
|
||||
+43
-3
@@ -18,6 +18,7 @@ import {
|
||||
} from './core';
|
||||
import type { BodyFailure, BodyReader } from './body';
|
||||
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
|
||||
import type { Logger } from '../logger';
|
||||
import { nodeRequire } from '../node-require';
|
||||
|
||||
interface HandlerConfig {
|
||||
@@ -78,7 +79,7 @@ export function createHttpServer(
|
||||
server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000;
|
||||
server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000;
|
||||
server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000;
|
||||
attachWs(server, wsRoutes, bus, meshControl, opts?.streams);
|
||||
attachWs(server, wsRoutes, bus, meshControl, opts?.streams, opts?.limits);
|
||||
return server;
|
||||
}
|
||||
|
||||
@@ -96,7 +97,14 @@ function createRequestHandler(cfg: HandlerConfig) {
|
||||
const readBody: BodyReader = (source, limit) => readRequestBytes(source, limit, opts);
|
||||
const gate = createRequestGate(opts?.limits?.maxConcurrentRequests);
|
||||
|
||||
return async (req: http.IncomingMessage, res: http.ServerResponse): Promise<void> => {
|
||||
// `http.createServer` ignores the promise a listener returns, so a rejection that escapes `serve`
|
||||
// would be an `unhandledRejection` — and under Node's default mode, the end of the process.
|
||||
// Caught here, at the one place every request passes through (#108).
|
||||
return (req: http.IncomingMessage, res: http.ServerResponse): void => {
|
||||
serve(req, res).catch((err: unknown) => failSafe(res, err, opts?.logger));
|
||||
};
|
||||
|
||||
async function serve(req: http.IncomingMessage, res: http.ServerResponse): Promise<void> {
|
||||
// Install the security-header patch BEFORE any routing/response so every path
|
||||
// (200, 404, error, stream) writes headers through the same patched writeHead.
|
||||
const secure = deriveSecure(req, trustProxy);
|
||||
@@ -192,7 +200,39 @@ function createRequestHandler(cfg: HandlerConfig) {
|
||||
|
||||
res.writeHead(result.outcome.status, result.outcome.headers);
|
||||
res.end(result.outcome.body);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The last resort for a request whose handling rejected. Deliberately does not call `onError`: this
|
||||
* runs because something already failed past the point where errors convert to a response, and user
|
||||
* code that may be the thing failing is the wrong place to send it. Must never throw — nothing
|
||||
* catches it.
|
||||
*
|
||||
* Writable: a fixed 500 with `connection: close`, still through the patched `writeHead`, so the
|
||||
* security headers land. Output already started, or the client gone: there is no honest response
|
||||
* left to send, so the socket is destroyed and the client sees a truncated reply rather than a
|
||||
* complete-looking one. No `request:end` is emitted — observers do not alter the response, and the
|
||||
* core never completed this request.
|
||||
*/
|
||||
function failSafe(res: http.ServerResponse, err: unknown, logger: Logger | undefined): void {
|
||||
try {
|
||||
logger?.error('request listener failed', { err: err instanceof Error ? err.message : String(err) });
|
||||
} catch {
|
||||
/* a broken logger must not stop the response below */
|
||||
}
|
||||
|
||||
if (res.headersSent || res.destroyed || !res.writable) {
|
||||
res.destroy();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
res.writeHead(500, { 'content-type': 'application/json', connection: 'close' });
|
||||
res.end('{"error":"Internal Server Error"}');
|
||||
} catch {
|
||||
res.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -16,6 +16,31 @@ export interface RequestLimits {
|
||||
headersTimeoutMs?: number; // default 10_000
|
||||
keepAliveTimeoutMs?: number; // default 5_000
|
||||
maxParts?: number; // default 1000
|
||||
/**
|
||||
* Largest inbound WebSocket message, in bytes (UTF-8 bytes for text), per connection. Default
|
||||
* `1_048_576` (1 MiB). A larger message closes the connection with `1009` (`message too large`);
|
||||
* a fragmented message counts as a whole. Must be a positive integer, or `createApp` throws.
|
||||
*
|
||||
* Node and Bun refuse an oversized frame before buffering it (`ws`'s `maxPayload`, Bun's
|
||||
* `maxPayloadLength`). Bun then drops the connection without a close frame, so on Bun the peer
|
||||
* sees `1006` instead of `1009`. Deno and the edge offer no such option: there the runtime
|
||||
* receives the whole message first, so its memory is bounded by the platform's own cap, and this
|
||||
* limit is checked after receipt — the connection still closes `1009`.
|
||||
*
|
||||
* Server-level only; there is no per-route override.
|
||||
*/
|
||||
maxWsMessageBytes?: number;
|
||||
/**
|
||||
* Inbound WebSocket messages a connection may hold that the handler has not read yet. Default
|
||||
* `16`. One more closes the connection with `1013` (`inbound queue full`) rather than dropping
|
||||
* anything, so a handler that never reads `inbound` is closed once its peer sends 17 messages.
|
||||
* Must be a positive integer, or `createApp` throws. Applies on every runtime.
|
||||
*
|
||||
* Worst-case buffered inbound memory is about `maxConnections × maxWsQueue × maxWsMessageBytes`:
|
||||
* ≈ 15.6 GiB at the defaults on Node. Deno and Bun have no connection cap, so cap connections at
|
||||
* the platform or proxy there. Server-level only; there is no per-route override.
|
||||
*/
|
||||
maxWsQueue?: number;
|
||||
}
|
||||
|
||||
/** Options controlling server construction: limits, TLS, proxy trust, security headers, CORS, and body parsing. */
|
||||
|
||||
+73
-25
@@ -11,7 +11,8 @@ import {
|
||||
type Preflight,
|
||||
} from './core';
|
||||
import { mergeInjectedHeaders } from './headers';
|
||||
import type { BodyFailure, BodyReader, MaybePromise } from './body';
|
||||
import { peerOf } from './peer';
|
||||
import { declaresOverLimit, type BodyFailure, type BodyReader, type MaybePromise } from './body';
|
||||
import { HttpError } from '../signals';
|
||||
import { renderError, type ErrorRequest } from '../transformers';
|
||||
import type { RouteDef, HttpOptions } from './types';
|
||||
@@ -97,9 +98,9 @@ function headersToRecord(headers: Headers): Record<string, string> {
|
||||
/**
|
||||
* The fetch half of body acquisition: bytes out of the `Request`, and the over-limit answer.
|
||||
*
|
||||
* Unlike Node, there is no incremental read to abort — `arrayBuffer()` resolves with the whole body
|
||||
* or not at all, so the limit can only be checked once the bytes are already in memory. That
|
||||
* difference is exactly why the limit is passed in rather than applied by the shared core.
|
||||
* Read from `request.body` chunk by chunk rather than through `arrayBuffer()`, which resolves with
|
||||
* the whole body or not at all and so could only check the limit once every byte was in memory.
|
||||
* Deno, Bun, workerd and Node all expose `request.body` as a stream, so no runtime needs a branch.
|
||||
*/
|
||||
function readFetchBytes(
|
||||
source: unknown,
|
||||
@@ -110,21 +111,63 @@ function readFetchBytes(
|
||||
// Not `async`: a bodiless request answers without allocating a promise at all.
|
||||
if (!request.body) return { bytes: undefined };
|
||||
|
||||
return request.arrayBuffer().then((arrayBuffer) => {
|
||||
if (arrayBuffer.byteLength > limit) {
|
||||
// Rebuilt here rather than captured per request: only an over-limit body ever needs it, and
|
||||
// a `url`/`headers` pair captured up-front cost more than the work it saved.
|
||||
const url = new URL(request.url);
|
||||
const errReq: ErrorRequest = {
|
||||
method: request.method,
|
||||
url: url.pathname + url.search,
|
||||
headers: headersToRecord(request.headers),
|
||||
};
|
||||
return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError, opts?.logger) };
|
||||
// A declared length over the limit is refused before a single chunk is pulled. Cancelling is best
|
||||
// effort: it tells the runtime to stop the upload, and a refusal changes nothing about the answer.
|
||||
if (declaresOverLimit(request.headers.get('content-length'), limit)) {
|
||||
request.body.cancel().catch(() => {});
|
||||
return tooLarge(request, opts);
|
||||
}
|
||||
|
||||
// ponytail: one reader loop; a TransformStream byte-counter only if another consumer needs it
|
||||
return readBounded(request.body.getReader(), limit).then((bytes) =>
|
||||
bytes === null ? tooLarge(request, opts) : { bytes },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads until the stream ends, or until the running total crosses `limit` — then cancels the reader,
|
||||
* so no further chunk is pulled, and answers null. A rejected `read()` (the client went away)
|
||||
* propagates exactly as a rejected `arrayBuffer()` used to.
|
||||
*
|
||||
* workerd may strip `content-length` from a chunked upload, so there this count is the only check.
|
||||
* The answer is the same 413 either way; only how early it comes differs.
|
||||
*/
|
||||
async function readBounded(
|
||||
reader: ReadableStreamDefaultReader<Uint8Array>,
|
||||
limit: number,
|
||||
): Promise<Buffer | undefined | null> {
|
||||
const chunks: Uint8Array[] = [];
|
||||
let total = 0;
|
||||
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
|
||||
total += value.byteLength;
|
||||
|
||||
if (total > limit) {
|
||||
reader.cancel().catch(() => {});
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return { bytes: arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer) };
|
||||
});
|
||||
chunks.push(value);
|
||||
}
|
||||
|
||||
return total === 0 ? undefined : Buffer.concat(chunks, total);
|
||||
}
|
||||
|
||||
/** The over-limit answer, shared by the declared-length check and the stream count. */
|
||||
function tooLarge(request: Request, opts: HttpOptions | undefined): BodyFailure {
|
||||
// Rebuilt here rather than captured per request: only an over-limit body ever needs it, and
|
||||
// a `url`/`headers` pair captured up-front cost more than the work it saved.
|
||||
const url = new URL(request.url);
|
||||
const errReq: ErrorRequest = {
|
||||
method: request.method,
|
||||
url: url.pathname + url.search,
|
||||
headers: headersToRecord(request.headers),
|
||||
};
|
||||
return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError, opts?.logger) };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -176,6 +219,15 @@ function outcomeToResponse(result: HandleResult, bus?: Bus, correlation: Correla
|
||||
return new Response(body, { status: result.outcome.status, headers });
|
||||
}
|
||||
|
||||
/** The first `x-forwarded-for` hop when the proxy is trusted, else `''`. */
|
||||
function forwardedFor(headers: Record<string, string>, opts: HttpOptions | undefined): string {
|
||||
if (!opts?.trustProxy) return '';
|
||||
|
||||
return String(headers['x-forwarded-for'] ?? '')
|
||||
.split(',')[0]
|
||||
.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a Web-Standards `fetch(request)` handler over the same route table the Node adapter uses:
|
||||
* describes the request for the runtime-neutral {@link handle}, supplies the {@link BodyReader} it
|
||||
@@ -244,14 +296,10 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
|
||||
source: request,
|
||||
secure,
|
||||
// Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the
|
||||
// proxy is trusted, and take its first hop — an untrusted XFF is client-spoofable, and
|
||||
// there's no socket peer address to fall back to on the fetch path, so the untrusted case
|
||||
// is simply ''.
|
||||
ip: opts?.trustProxy
|
||||
? String(headers['x-forwarded-for'] ?? '')
|
||||
.split(',')[0]
|
||||
.trim()
|
||||
: '',
|
||||
// proxy is trusted, and take its first hop — an untrusted XFF is client-spoofable.
|
||||
// Otherwise the socket peer, which only the Deno and Bun adapters can supply; a bare
|
||||
// `app.fetch` has none, so there the answer is still ''.
|
||||
ip: forwardedFor(headers, opts) || peerOf(request),
|
||||
},
|
||||
// Already computed above for the shed-503 path; handing it down keeps `cors.origins` to
|
||||
// one call per request.
|
||||
|
||||
+19
-5
@@ -1,4 +1,4 @@
|
||||
import { channel } from '../channel';
|
||||
import { channel, type Channel } from '../channel';
|
||||
import type { App } from '../app/types';
|
||||
import type { WsRequest, WsSocket } from './ws-core';
|
||||
import { nodeRequire } from '../node-require';
|
||||
@@ -10,6 +10,7 @@ import { nodeRequire } from '../node-require';
|
||||
*/
|
||||
|
||||
const decoder = new TextDecoder();
|
||||
const CONNECTING = 0; // WebSocket.CONNECTING
|
||||
const OPEN = 1; // WebSocket.OPEN — same constant in every runtime; avoids a per-runtime ambient
|
||||
|
||||
/** Decodes a host `message` payload to the string the core expects (parity with Node's Buffer.toString()). */
|
||||
@@ -69,7 +70,18 @@ export function eventSocket(host: EventfulSocket): WsSocket {
|
||||
ac.abort();
|
||||
});
|
||||
|
||||
return neutralSocket(host, inbound, ac);
|
||||
const socket = neutralSocket(host, inbound, ac);
|
||||
const closeNow = socket.close;
|
||||
|
||||
// Deno hands the socket over still CONNECTING: its 101 has not gone out yet, and a close in
|
||||
// that state is a no-op, so a route that refuses straight away (1008) left the peer hanging.
|
||||
// Deferring to 'open' is what lets that close reach the client at all.
|
||||
return Object.assign(socket, {
|
||||
close: (code?: number, reason?: string) => {
|
||||
if (host.readyState === CONNECTING) host.addEventListener('open', () => closeNow(code, reason));
|
||||
else closeNow(code, reason);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -79,7 +91,7 @@ export function eventSocket(host: EventfulSocket): WsSocket {
|
||||
*/
|
||||
export function neutralSocket(
|
||||
host: Pick<EventfulSocket, 'readyState' | 'send' | 'close'> & { terminate?(): void },
|
||||
inbound: ReturnType<typeof channel<unknown>>,
|
||||
inbound: Channel<unknown>,
|
||||
ac: AbortController,
|
||||
): WsSocket {
|
||||
return {
|
||||
@@ -112,8 +124,10 @@ export function neutralSocket(
|
||||
export type SocketCtor = new (url: string) => EventfulSocket;
|
||||
|
||||
/**
|
||||
* The WebSocket client implementation: the platform global where it exists (Deno, Bun, and
|
||||
* Node >= 22), else the `ws` optional peer — Node 18-21, our declared floor, has no global.
|
||||
* The WebSocket client implementation: the platform global where it exists, else the `ws`
|
||||
* optional peer. Every supported runtime has the global — Deno, Bun, and Node from 22, the
|
||||
* declared floor — so the fallback is reached only when Node runs with the global switched off
|
||||
* (`--no-experimental-websocket`). `ws` is installed anyway for the server side.
|
||||
*
|
||||
* Both expose the same `addEventListener` API and deliver text frames as `event.data` strings,
|
||||
* so one bridge covers both. That is verified rather than assumed: `ws` implements the
|
||||
|
||||
+215
-1
@@ -1,8 +1,9 @@
|
||||
import { isHttpError } from '../signals';
|
||||
import { CHANNEL_TAP, type TappableChannel } from '../channel';
|
||||
import type { Bus } from '../bus';
|
||||
import { correlateRequest } from './core';
|
||||
import { matchPattern } from './router';
|
||||
import type { WsRouteDef } from './types';
|
||||
import type { WsRouteDef, RequestLimits } from './types';
|
||||
|
||||
/** Neutral, runtime-free WebSocket request context (replaces the raw Node req). */
|
||||
export interface WsRequest {
|
||||
@@ -22,6 +23,219 @@ export interface WsSocket {
|
||||
terminate(): void;
|
||||
}
|
||||
|
||||
/** Default for `limits.maxWsMessageBytes`: 1 MiB. */
|
||||
export const DEFAULT_MAX_WS_MESSAGE_BYTES = 1_048_576;
|
||||
/** Default for `limits.maxWsQueue`, in undelivered inbound messages per connection (D1). */
|
||||
export const DEFAULT_MAX_WS_QUEUE = 16;
|
||||
|
||||
/**
|
||||
* Where `createApp` leaves the resolved `maxWsMessageBytes` for `serveBun`, which needs it as
|
||||
* Bun's native `maxPayloadLength` and has no other path to the app's options. Internal, not part
|
||||
* of the public `App` type; `Symbol.for` because each tsup entry carries its own copy of this
|
||||
* module, and only the global registry resolves to one symbol across them.
|
||||
*/
|
||||
export const WS_MAX_MESSAGE_BYTES: unique symbol = Symbol.for('green-tea.ws-max-message-bytes');
|
||||
|
||||
/** The effective `limits.maxWsMessageBytes`. */
|
||||
export function wsMessageBytes(limits: Pick<RequestLimits, 'maxWsMessageBytes'> | undefined): number {
|
||||
return limits?.maxWsMessageBytes ?? DEFAULT_MAX_WS_MESSAGE_BYTES;
|
||||
}
|
||||
|
||||
/** Throws when a WebSocket limit is present but not a positive safe integer (#107). */
|
||||
export function validateWsLimits(limits: RequestLimits | undefined): void {
|
||||
for (const key of ['maxWsMessageBytes', 'maxWsQueue'] as const) {
|
||||
const value: unknown = limits?.[key];
|
||||
if (value === undefined || (Number.isSafeInteger(value) && (value as number) > 0)) continue;
|
||||
const shown = typeof value === 'string' ? `'${value}'` : String(value);
|
||||
throw new TypeError(`limits.${key} must be a positive integer, got ${shown}`);
|
||||
}
|
||||
}
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
/** True when `msg`'s UTF-8 encoding is longer than `max` bytes. */
|
||||
function exceedsBytes(msg: unknown, max: number): boolean {
|
||||
if (typeof msg !== 'string') return false; // every adapter delivers strings; nothing else to measure
|
||||
// A UTF-16 unit encodes to 1–3 UTF-8 bytes, so both bounds below are exact. Only a string in
|
||||
// between pays for the encode — which is never one of the short messages that dominate.
|
||||
if (msg.length * 3 <= max) return false;
|
||||
if (msg.length > max) return true;
|
||||
return encoder.encode(msg).byteLength > max;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bounds a socket's inbound side (#107): a frame over `maxWsMessageBytes` closes `1009`, and a
|
||||
* frame that arrives while `maxWsQueue` frames are still undelivered closes `1013`. Nothing is
|
||||
* dropped silently — the peer learns which bound it hit from the close code.
|
||||
*
|
||||
* Subscribes to `socket.inbound` immediately. `channel` is fan-out, so a frame pushed with no
|
||||
* subscriber is lost; subscribing here, before any boot or step runs, is what keeps the first
|
||||
* frames — for the mesh control channel, the `hello` itself. Those early frames go to the first
|
||||
* consumer. After that the returned `inbound` fans out like `channel`: each iterator gets every
|
||||
* frame from the moment it subscribes, through its own queue, and the bound applies to each queue.
|
||||
* Every other capability is the original socket's.
|
||||
*/
|
||||
export function boundInbound(
|
||||
socket: WsSocket,
|
||||
limits?: Pick<RequestLimits, 'maxWsMessageBytes' | 'maxWsQueue'>,
|
||||
): WsSocket {
|
||||
const fanout = new InboundFanout(socket, wsMessageBytes(limits), limits?.maxWsQueue ?? DEFAULT_MAX_WS_QUEUE);
|
||||
|
||||
const tap = (socket.inbound as Partial<TappableChannel<unknown>>)[CHANNEL_TAP];
|
||||
if (tap) fanout.tap(tap);
|
||||
else void fanout.pump();
|
||||
|
||||
return Object.create(socket, {
|
||||
inbound: { value: { [Symbol.asyncIterator]: () => fanout.subscribe() } },
|
||||
}) as WsSocket;
|
||||
}
|
||||
|
||||
/** The fan-out behind {@link boundInbound}: one bounded queue per consumer. */
|
||||
class InboundFanout {
|
||||
private readonly subs = new Set<InboundSub>();
|
||||
/** Holds the frames that arrive before anyone reads; handed to the first consumer. */
|
||||
private first: InboundSub | null;
|
||||
private ended = false;
|
||||
private failure: { err: unknown } | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly socket: WsSocket,
|
||||
private readonly maxBytes: number,
|
||||
private readonly maxQueue: number,
|
||||
) {
|
||||
this.first = this.add();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the adapter's channel inside its `push`. Runtimes emit a whole read's worth of frames
|
||||
* synchronously — `ws` does — so a bound checked after the event loop yields is checked after an
|
||||
* unbounded queue has already taken the burst. Here each frame is bounded before it is queued.
|
||||
*/
|
||||
tap(tap: TappableChannel<unknown>[typeof CHANNEL_TAP]): void {
|
||||
const untap = tap({
|
||||
push: (msg) => {
|
||||
if (this.ended || this.accept(msg)) return;
|
||||
untap();
|
||||
this.settle();
|
||||
},
|
||||
end: () => this.settle(),
|
||||
fail: (err) => this.settle({ err }),
|
||||
});
|
||||
}
|
||||
|
||||
// ponytail: only for an inbound that is not a channel (no adapter builds one); bounds late.
|
||||
async pump(): Promise<void> {
|
||||
try {
|
||||
for await (const msg of this.socket.inbound) {
|
||||
if (this.ended || !this.accept(msg)) break;
|
||||
}
|
||||
|
||||
this.settle();
|
||||
} catch (err) {
|
||||
this.settle({ err });
|
||||
}
|
||||
}
|
||||
|
||||
subscribe(): AsyncIterator<unknown> {
|
||||
const sub = this.first ?? this.add();
|
||||
this.first = null;
|
||||
return sub;
|
||||
}
|
||||
|
||||
private add(): InboundSub {
|
||||
const sub = new InboundSub(() => this.subs.delete(sub));
|
||||
if (this.ended) sub.settle(this.failure ?? undefined);
|
||||
else this.subs.add(sub);
|
||||
return sub;
|
||||
}
|
||||
|
||||
/** Delivers or queues one frame for every consumer; returns false once it has closed the socket. */
|
||||
private accept(msg: unknown): boolean {
|
||||
if (exceedsBytes(msg, this.maxBytes)) {
|
||||
this.socket.close(1009, 'message too large');
|
||||
return false;
|
||||
}
|
||||
|
||||
// Capacity first, for every consumer: a frame that overflows one queue reaches none, so a
|
||||
// rejected frame cannot run some handlers' side effects and not others'.
|
||||
for (const sub of this.subs) {
|
||||
if (sub.full(this.maxQueue)) {
|
||||
this.socket.close(1013, 'inbound queue full');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
for (const sub of this.subs) sub.offer(msg);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Ends every consumer once, cleanly or with a failure; whatever is still queued is delivered first. */
|
||||
private settle(failure?: { err: unknown }): void {
|
||||
if (this.ended) return;
|
||||
this.ended = true;
|
||||
this.failure = failure ?? null;
|
||||
for (const sub of this.subs) sub.settle(failure);
|
||||
this.subs.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/** One consumer's queue; it is its own async iterator. */
|
||||
class InboundSub implements AsyncIterator<unknown> {
|
||||
private readonly queue: unknown[] = [];
|
||||
private waiter: { resolve: (r: IteratorResult<unknown>) => void; reject: (e: unknown) => void } | null = null;
|
||||
private ended = false;
|
||||
private failure: { err: unknown } | null = null;
|
||||
|
||||
constructor(private readonly onReturn: () => void) {}
|
||||
|
||||
/** True when `max` frames are already waiting and no `next()` is there to take another. */
|
||||
full(max: number): boolean {
|
||||
return !this.waiter && this.queue.length >= max;
|
||||
}
|
||||
|
||||
/** Hands `msg` to a waiting `next()` or queues it; callers check {@link full} first. */
|
||||
offer(msg: unknown): void {
|
||||
const waiter = this.waiter;
|
||||
|
||||
if (waiter) {
|
||||
this.waiter = null;
|
||||
waiter.resolve({ value: msg, done: false });
|
||||
return;
|
||||
}
|
||||
|
||||
this.queue.push(msg);
|
||||
}
|
||||
|
||||
next(): Promise<IteratorResult<unknown>> {
|
||||
if (this.queue.length) return Promise.resolve({ value: this.queue.shift(), done: false });
|
||||
if (this.failure) return Promise.reject(this.failure.err);
|
||||
if (this.ended) return Promise.resolve({ value: undefined, done: true });
|
||||
return new Promise((resolve, reject) => {
|
||||
this.waiter = { resolve, reject };
|
||||
});
|
||||
}
|
||||
|
||||
// A consumer that stops reading has said it wants no more; queueing for it would only close
|
||||
// the connection for a bound it no longer cares about. Other consumers keep receiving.
|
||||
return(): Promise<IteratorResult<unknown>> {
|
||||
this.queue.length = 0;
|
||||
this.onReturn();
|
||||
this.settle();
|
||||
return Promise.resolve({ value: undefined, done: true });
|
||||
}
|
||||
|
||||
settle(failure?: { err: unknown }): void {
|
||||
if (this.ended) return;
|
||||
this.ended = true;
|
||||
this.failure = failure ?? null;
|
||||
const waiter = this.waiter;
|
||||
this.waiter = null;
|
||||
if (!waiter) return;
|
||||
if (failure) waiter.reject(failure.err);
|
||||
else waiter.resolve({ value: undefined, done: true });
|
||||
}
|
||||
}
|
||||
|
||||
/** Finds the first ws route whose pattern matches `path`, capturing its params. */
|
||||
export function matchWsRoute(
|
||||
wsRoutes: WsRouteDef[],
|
||||
|
||||
+73
-23
@@ -1,8 +1,17 @@
|
||||
import type http from 'http';
|
||||
import { channel } from '../channel';
|
||||
import type { Bus } from '../bus';
|
||||
import { runWsConnection, matchWsRoute, trackUntil, type WsSocket, type WsRequest } from './ws-core';
|
||||
import type { WsRouteDef, MeshControl } from './types';
|
||||
import {
|
||||
runWsConnection,
|
||||
matchWsRoute,
|
||||
trackUntil,
|
||||
boundInbound,
|
||||
wsMessageBytes,
|
||||
type WsSocket,
|
||||
type WsRequest,
|
||||
} from './ws-core';
|
||||
import type { WsRouteDef, MeshControl, RequestLimits } from './types';
|
||||
import { normalizeRequestPath } from './router';
|
||||
import { nodeRequire } from '../node-require';
|
||||
|
||||
/** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */
|
||||
@@ -16,9 +25,9 @@ function loadWss(): any | null {
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes a 501 Not Implemented status to the raw socket and destroys it. */
|
||||
function reject501(socket: any): void {
|
||||
socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n');
|
||||
/** Writes a bodyless HTTP status to the raw socket and destroys it. */
|
||||
function rejectUpgrade(socket: any, status: number, text: string): void {
|
||||
socket.write(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
|
||||
socket.destroy();
|
||||
}
|
||||
|
||||
@@ -31,11 +40,12 @@ function handleMeshUpgrade(
|
||||
socket: any,
|
||||
head: Buffer,
|
||||
streams?: Set<() => void>,
|
||||
limits?: RequestLimits,
|
||||
): boolean {
|
||||
if (path !== meshControl.path) return false;
|
||||
|
||||
if (!wss) {
|
||||
reject501(socket);
|
||||
rejectUpgrade(socket, 501, 'Not Implemented');
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -45,7 +55,7 @@ function handleMeshUpgrade(
|
||||
// an untracked control channel leaves the teapot's server.close() waiting on it forever.
|
||||
// serveFrames swallows its own failures, so the floating promise cannot reject.
|
||||
wss.handleUpgrade(req, socket, head, (ws: any) => {
|
||||
const neutral = nodeSocket(ws);
|
||||
const neutral = boundInbound(nodeSocket(ws), limits);
|
||||
|
||||
void trackUntil(neutral, meshControl.handle(neutral), streams);
|
||||
});
|
||||
@@ -97,29 +107,69 @@ export function attachWs(
|
||||
bus?: Bus,
|
||||
meshControl?: MeshControl,
|
||||
streams?: Set<() => void>,
|
||||
limits?: RequestLimits,
|
||||
): void {
|
||||
if (wsRoutes.length === 0 && !meshControl) return;
|
||||
const WebSocketServer = loadWss();
|
||||
const wss = WebSocketServer ? new WebSocketServer({ noServer: true }) : null;
|
||||
// `maxPayload` is the pre-buffer half of `maxWsMessageBytes`: `ws` refuses an oversized frame,
|
||||
// fragmented or not, before it is assembled, and closes 1009 itself. `boundInbound` repeats the
|
||||
// check on the decoded text, which is the only half Deno and the edge have.
|
||||
const wss = WebSocketServer ? new WebSocketServer({ noServer: true, maxPayload: wsMessageBytes(limits) }) : null;
|
||||
server.on('upgrade', (req, socket, head) => {
|
||||
const path = (req.url ?? '/').split('?')[0];
|
||||
// A peer that resets mid-rejection must not raise an unhandled 'error' on a socket nobody
|
||||
// else is listening to yet: that is as fatal as a throw.
|
||||
socket.on('error', () => {});
|
||||
|
||||
if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head, streams)) return;
|
||||
|
||||
const route = matchWsRoute(wsRoutes, path);
|
||||
|
||||
if (!route) {
|
||||
socket.destroy();
|
||||
return;
|
||||
// Nothing thrown in here may escape. This is a raw EventEmitter listener, so a throw is an
|
||||
// uncaught exception that takes the whole process down, not a 500 for one client.
|
||||
try {
|
||||
routeUpgrade({ wss, wsRoutes, bus, meshControl, streams, limits }, req, socket, head);
|
||||
} catch {
|
||||
if (socket.writable) rejectUpgrade(socket, 500, 'Internal Server Error');
|
||||
else socket.destroy();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (!wss) {
|
||||
reject501(socket);
|
||||
return;
|
||||
}
|
||||
/** What every upgrade on one server shares. */
|
||||
interface UpgradeEnv {
|
||||
wss: any;
|
||||
wsRoutes: WsRouteDef[];
|
||||
bus?: Bus;
|
||||
meshControl?: MeshControl;
|
||||
streams?: Set<() => void>;
|
||||
limits?: RequestLimits;
|
||||
}
|
||||
|
||||
wss.handleUpgrade(req, socket, head, (ws: any) => {
|
||||
void runWsConnection(nodeSocket(ws), nodeWsRequest(req), route, bus, streams);
|
||||
});
|
||||
/** Routes one upgrade: validates the path the way HTTP does, then mesh control, then the ws route table. */
|
||||
function routeUpgrade(env: UpgradeEnv, req: http.IncomingMessage, socket: any, head: Buffer): void {
|
||||
const { wss, wsRoutes, bus, meshControl, streams, limits } = env;
|
||||
let path: string;
|
||||
|
||||
// The same normalization the HTTP path runs (`dispatch` in core.ts). Without it a malformed
|
||||
// escape reaches `decodeURIComponent` in the matcher and throws, and `//` silently matches.
|
||||
try {
|
||||
path = normalizeRequestPath((req.url ?? '/').split('?')[0]);
|
||||
} catch {
|
||||
rejectUpgrade(socket, 400, 'Bad Request');
|
||||
return;
|
||||
}
|
||||
|
||||
if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head, streams, limits)) return;
|
||||
|
||||
const route = matchWsRoute(wsRoutes, path);
|
||||
|
||||
if (!route) {
|
||||
rejectUpgrade(socket, 404, 'Not Found');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!wss) {
|
||||
rejectUpgrade(socket, 501, 'Not Implemented');
|
||||
return;
|
||||
}
|
||||
|
||||
wss.handleUpgrade(req, socket, head, (ws: any) => {
|
||||
void runWsConnection(boundInbound(nodeSocket(ws), limits), nodeWsRequest(req), route, bus, streams);
|
||||
});
|
||||
}
|
||||
+49
-6
@@ -86,9 +86,40 @@ export interface StaticHit {
|
||||
/** Resolves a URL path to a static file under a fixed root, or `undefined` for a miss. */
|
||||
export type StaticResolver = (urlPath: string) => Promise<StaticHit | undefined>;
|
||||
|
||||
/** The real path of `path` when it is `root` or lies beneath it, else `undefined`. Rejects on ENOENT.
|
||||
* The separator suffix keeps a sibling such as `root-evil` out of `root`. */
|
||||
async function confine(fs: typeof import('node:fs'), sep: string, root: string, path: string) {
|
||||
const real = await fs.promises.realpath(path);
|
||||
return real === root || real.startsWith(root + sep) ? real : undefined;
|
||||
}
|
||||
|
||||
/** Reads `full` (or its `index.html` when a directory) if its real path stays inside the real `root`. */
|
||||
async function readConfined(
|
||||
fs: typeof import('node:fs'),
|
||||
nodePath: typeof import('node:path'),
|
||||
root: string,
|
||||
full: string,
|
||||
): Promise<StaticHit | undefined> {
|
||||
let real = await confine(fs, nodePath.sep, root, full);
|
||||
if (!real) return undefined;
|
||||
const isDir = (await fs.promises.stat(real)).isDirectory();
|
||||
// `index.html` is a second resolution and can itself be a link, so it is confined on its own.
|
||||
if (isDir) real = await confine(fs, nodePath.sep, root, nodePath.join(real, 'index.html'));
|
||||
if (!real) return undefined;
|
||||
// ponytail: a link swapped between `realpath` and `readFile` can still escape. Exploiting it needs
|
||||
// write access inside the served root, which already owns the app; closing it needs `O_NOFOLLOW`
|
||||
// on every path component, which Node, Deno and Bun do not offer portably.
|
||||
const body = await fs.promises.readFile(real);
|
||||
// The content-type follows the requested name, not the link target (`app.js -> app.3f2a.js`).
|
||||
const target = isDir ? nodePath.join(full, 'index.html') : full;
|
||||
return { body, contentType: contentTypeFor(nodePath.extname(target)) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a static-file resolver rooted at `root` (`true` → `./public`). Requires a filesystem: throws at
|
||||
* boot on a runtime without one (edge). Path-traversal-safe — a resolved path outside the root is a miss.
|
||||
* boot on a runtime without one (edge). Path-traversal-safe — a resolved path outside the root is a miss,
|
||||
* and so is a symlink whose real target lies outside the root's real path (#106). Escapes are misses
|
||||
* (404), not 403, so a probe cannot tell "exists outside the root" from "does not exist".
|
||||
*/
|
||||
export function buildStaticResolver(root: string | true): StaticResolver {
|
||||
let fs: typeof import('node:fs');
|
||||
@@ -105,6 +136,18 @@ export function buildStaticResolver(root: string | true): StaticResolver {
|
||||
|
||||
const abs = nodePath.resolve(process.cwd(), root === true ? 'public' : root);
|
||||
|
||||
// The root's real path, resolved once on the first request rather than at build time, so a missing
|
||||
// `public/` at boot is still not fatal — it just makes every request a miss, as before. Containment
|
||||
// compares real paths, so the root must be real too: a symlinked `public/` would otherwise fail every
|
||||
// check. Cached for the life of the app: re-pointing a root symlink at runtime needs a restart. A failed
|
||||
// lookup is not cached, so a root created after boot starts serving, as it did before.
|
||||
let realRoot: Promise<string | undefined> | undefined;
|
||||
const resolveRoot = () =>
|
||||
(realRoot ??= fs.promises.realpath(abs).catch(() => {
|
||||
realRoot = undefined;
|
||||
return undefined;
|
||||
}));
|
||||
|
||||
return async (urlPath) => {
|
||||
let rel: string;
|
||||
|
||||
@@ -118,13 +161,13 @@ export function buildStaticResolver(root: string | true): StaticResolver {
|
||||
const full = nodePath.resolve(abs, '.' + (rel.startsWith('/') ? rel : '/' + rel));
|
||||
if (full !== abs && !full.startsWith(abs + nodePath.sep)) return undefined; // traversal guard
|
||||
|
||||
const rootReal = await resolveRoot();
|
||||
if (!rootReal) return undefined;
|
||||
|
||||
try {
|
||||
const stat = await fs.promises.stat(full);
|
||||
const target = stat.isDirectory() ? nodePath.join(full, 'index.html') : full;
|
||||
const body = await fs.promises.readFile(target);
|
||||
return { body, contentType: contentTypeFor(nodePath.extname(target)) };
|
||||
return await readConfined(fs, nodePath, rootReal, full);
|
||||
} catch {
|
||||
return undefined;
|
||||
return undefined; // includes ENOENT from `realpath` on a dangling link: a miss, never a rejection
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -12,7 +12,16 @@ class Rt {
|
||||
})();
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Rt] })
|
||||
@Route('/room')
|
||||
class Room {
|
||||
@Ws('/:name')
|
||||
join(@ctx() { inbound }: any) {
|
||||
return (async function* () {
|
||||
for await (const msg of inbound) yield `room:${msg}`;
|
||||
})();
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Rt, Room] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
|
||||
@@ -96,4 +105,18 @@ describe('app.upgrade', () => {
|
||||
await app.upgrade(req, socket);
|
||||
expect(closedCode).toBe(1008);
|
||||
});
|
||||
|
||||
it.each(['/rt/%E0%A4%A', '/room/%E0%A4%A', '//rt//echo'])(
|
||||
'closes 1008 on the malformed path %s instead of rejecting (#104)',
|
||||
async (url) => {
|
||||
const { socket } = fakeSocket();
|
||||
let closed: [number | undefined, string | undefined] | undefined;
|
||||
socket.close = (c, r) => {
|
||||
closed = [c, r];
|
||||
};
|
||||
const req: WsRequest = { url, headers: {}, protocol: 'http', ip: '' };
|
||||
await app.upgrade(req, socket);
|
||||
expect(closed).toEqual([1008, 'invalid request path']);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
// #105 on the real Bun runtime: the request-body limit is enforced while the body is read, both on
|
||||
// `app.fetch` directly and through `serveBun`. The counting stream is what proves the read stopped —
|
||||
// a 413 looks the same whether the body was buffered first or not.
|
||||
//
|
||||
// Run with: npm run test:bun (or: bun test test/bun/)
|
||||
import 'reflect-metadata';
|
||||
import { test, expect } from 'bun:test';
|
||||
import { createApp, Route, Post, Module, body } from '../../src/index.ts';
|
||||
import { serveBun } from '../../src/bun.ts';
|
||||
import { countingStream } from '../helpers/counting-stream.ts';
|
||||
|
||||
const LIMIT = 1_000_000; // the server default
|
||||
const SMALL = 1000;
|
||||
|
||||
@Route('/')
|
||||
class Ctl {
|
||||
@Post('/echo') echo(@body() b: unknown) {
|
||||
return { length: String(b).length };
|
||||
}
|
||||
// Small for the socket tests, so every refused body fits in the socket buffer. A client still
|
||||
// writing a large body when the 413 lands can see a reset instead — the transport racing the
|
||||
// answer, not a different answer.
|
||||
@Post('/small', { maxBodyBytes: SMALL }) small(@body() b: unknown) {
|
||||
return { length: String(b).length };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
|
||||
const post = (url: string, body: BodyInit, headers: Record<string, string> = {}) =>
|
||||
new Request(url, { method: 'POST', body, headers, duplex: 'half' } as RequestInit);
|
||||
|
||||
test('T1 app.fetch: a declared content-length over the limit is refused unread', async () => {
|
||||
const app = createApp({ modules: [M] });
|
||||
const source = countingStream(10, 300_000);
|
||||
|
||||
const res = await app.fetch(post('http://x/echo', source.stream, { 'content-length': '2000000' }));
|
||||
|
||||
expect(res.status).toBe(413);
|
||||
expect(source.pulled).toBe(0);
|
||||
expect(source.cancelled).toBe(true);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
test('T3 app.fetch: a streamed body stops at the chunk that crosses the limit', async () => {
|
||||
const app = createApp({ modules: [M] });
|
||||
const source = countingStream(10, 300_000);
|
||||
|
||||
const res = await app.fetch(post('http://x/echo', source.stream));
|
||||
|
||||
expect(res.status).toBe(413);
|
||||
expect(source.pulled).toBeLessThanOrEqual(5);
|
||||
expect(source.cancelled).toBe(true);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
test('T5 app.fetch: exactly the limit is accepted, one byte over is refused', async () => {
|
||||
const app = createApp({ modules: [M] });
|
||||
|
||||
const at = await app.fetch(post('http://x/echo', 'x'.repeat(LIMIT), { 'content-type': 'text/plain' }));
|
||||
const over = await app.fetch(post('http://x/echo', 'x'.repeat(LIMIT + 1), { 'content-type': 'text/plain' }));
|
||||
|
||||
expect(at.status).toBe(200);
|
||||
expect(await at.json()).toEqual({ length: LIMIT });
|
||||
expect(over.status).toBe(413);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
test('T11 serveBun: the same statuses over a real socket', async () => {
|
||||
const server = await serveBun(createApp({ modules: [M] }), { port: 0 });
|
||||
const base = `http://127.0.0.1:${server.port}`;
|
||||
// A fresh connection per request. Bun's *client* reuses a kept-alive socket after a response that
|
||||
// arrived before the server read the request body, and its next request on that socket comes back
|
||||
// 400 or 431. Node's fetch against the same Bun server does not (Bun 1.3.14), so it is the client
|
||||
// that misbehaves, not `serveBun`.
|
||||
const send = (body: BodyInit, headers?: Record<string, string>) =>
|
||||
fetch(post(`${base}/small`, body, headers), { keepalive: false } as RequestInit);
|
||||
|
||||
try {
|
||||
expect((await send(new Uint8Array(2 * SMALL))).status).toBe(413);
|
||||
expect((await send(countingStream(10, 300).stream)).status).toBe(413);
|
||||
expect((await send('x'.repeat(SMALL), { 'content-type': 'text/plain' })).status).toBe(200);
|
||||
expect((await send('x'.repeat(SMALL + 1), { 'content-type': 'text/plain' })).status).toBe(413);
|
||||
} finally {
|
||||
await server.close({ timeoutMs: 1000 });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
// #116 on the real Bun runtime: `serveBun` hands the socket's peer address to `ctx.ip`, the way
|
||||
// Node's `listen()` always has. Without it every client shared `''`, so anything keyed on the
|
||||
// address — the rate-limit plugin above all — put the whole internet in one bucket.
|
||||
//
|
||||
// Run with: npm run test:bun (or: bun test test/bun/)
|
||||
import 'reflect-metadata';
|
||||
import { test, expect } from 'bun:test';
|
||||
import { createServer } from 'node:net';
|
||||
import { createApp, Route, Get, Module, ctx } from '../../src/index.ts';
|
||||
import { serveBun } from '../../src/bun.ts';
|
||||
|
||||
@Route('/')
|
||||
class Ctl {
|
||||
@Get('/ip') ip(@ctx() c: { ip: string }) {
|
||||
return { ip: c.ip };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
|
||||
async function ipVia(
|
||||
hostname: string,
|
||||
opts: { trustProxy?: boolean; headers?: Record<string, string> } = {},
|
||||
): Promise<string> {
|
||||
const server = await serveBun(createApp({ modules: [M], trustProxy: opts.trustProxy }), { hostname, port: 0 });
|
||||
const host = hostname.includes(':') ? `[${hostname}]` : hostname;
|
||||
|
||||
try {
|
||||
const res = await fetch(`http://${host}:${server.port}/ip`, { headers: opts.headers });
|
||||
return ((await res.json()) as { ip: string }).ip;
|
||||
} finally {
|
||||
await server.close({ timeoutMs: 1000 });
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether this host can bind the IPv6 loopback at all; CI containers often cannot. */
|
||||
const ipv6Available = await new Promise<boolean>((resolve) => {
|
||||
const probe = createServer();
|
||||
probe.once('error', () => resolve(false));
|
||||
probe.listen(0, '::1', () => probe.close(() => resolve(true)));
|
||||
});
|
||||
|
||||
test('T2 serveBun: ctx.ip is the socket peer address', async () => {
|
||||
expect(await ipVia('127.0.0.1')).toBe('127.0.0.1');
|
||||
});
|
||||
|
||||
// Skipped, not failed: the host has no IPv6 loopback to connect over.
|
||||
test.skipIf(!ipv6Available)('T3 serveBun: an IPv6 peer is passed through as Bun reports it', async () => {
|
||||
expect(await ipVia('::1')).toBe('::1');
|
||||
});
|
||||
|
||||
test('T4 serveBun: trustProxy takes the first x-forwarded-for hop', async () => {
|
||||
const ip = await ipVia('127.0.0.1', { trustProxy: true, headers: { 'x-forwarded-for': '203.0.113.7, 10.0.0.1' } });
|
||||
expect(ip).toBe('203.0.113.7');
|
||||
});
|
||||
|
||||
test('T5 serveBun: trustProxy without x-forwarded-for falls back to the peer', async () => {
|
||||
expect(await ipVia('127.0.0.1', { trustProxy: true })).toBe('127.0.0.1');
|
||||
});
|
||||
|
||||
test('T6 serveBun: without trustProxy a spoofed x-forwarded-for is ignored', async () => {
|
||||
expect(await ipVia('127.0.0.1', { headers: { 'x-forwarded-for': '1.2.3.4' } })).toBe('127.0.0.1');
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
// The frozen router-parity differential under the real Bun runtime: every matcher case (hand-picked,
|
||||
// owner, generated v1/v2, WS) through the oracle and the live router, and the app.fetch cases, all
|
||||
// against the same frozen files the Node suite uses. See test/router-parity/README.md.
|
||||
//
|
||||
// Run with: npm run test:bun
|
||||
import 'reflect-metadata';
|
||||
import { test, expect } from 'bun:test';
|
||||
import { runDifferential } from '../router-parity/differential.ts';
|
||||
import { runAppDifferential } from '../router-parity/app-fixture.ts';
|
||||
|
||||
const load = (name: string) => Bun.file(new URL(`../router-parity/frozen/${name}.json`, import.meta.url)).json();
|
||||
|
||||
test('router parity on Bun: frozen matcher differential, oracle and live', async () => {
|
||||
const report = await runDifferential(load);
|
||||
expect(report.mismatches).toEqual([]);
|
||||
expect(report.sets.length).toBe(5);
|
||||
});
|
||||
|
||||
test('router parity on Bun: app.fetch cases', async () => {
|
||||
const report = await runAppDifferential(load);
|
||||
expect(report.mismatches).toEqual([]);
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
// Static-file confinement (#106) under the real Bun runtime, which reaches `realpath` through its
|
||||
// `node:fs` compat — a third implementation of symlink resolution, so not something to assume from
|
||||
// the Node suite.
|
||||
//
|
||||
// Run with: npm run test:bun
|
||||
import 'reflect-metadata';
|
||||
import { test, expect } from 'bun:test';
|
||||
import { mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { createApp } from '../../src/index.ts';
|
||||
|
||||
const base = mkdtempSync(join(tmpdir(), 'gt-static-bun-'));
|
||||
const root = join(base, 'root');
|
||||
mkdirSync(join(root, 'sub'), { recursive: true });
|
||||
writeFileSync(join(root, 'a.txt'), 'in root');
|
||||
writeFileSync(join(root, 'sub', 'index.html'), '<h1>Sub</h1>');
|
||||
writeFileSync(join(base, 'secret.txt'), 'TOP SECRET');
|
||||
symlinkSync('a.txt', join(root, 'in-link'));
|
||||
symlinkSync('../secret.txt', join(root, 'out-link'));
|
||||
symlinkSync('../nope.txt', join(root, 'dangling'));
|
||||
symlinkSync('root', join(base, 'root-alias'));
|
||||
|
||||
const app = createApp({ modules: [], static: root });
|
||||
const get = (path: string) => app.fetch(new Request(`http://x${path}`));
|
||||
|
||||
test('static on Bun: a link to a file outside the root is a miss', async () => {
|
||||
const res = await get('/out-link');
|
||||
expect(res.status).toBe(404);
|
||||
expect(await res.text()).not.toContain('TOP SECRET');
|
||||
});
|
||||
|
||||
test('static on Bun: a link to a file inside the root is served', async () => {
|
||||
const res = await get('/in-link');
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.text()).toBe('in root');
|
||||
});
|
||||
|
||||
test('static on Bun: a dangling link is a 404, not a rejection', async () => {
|
||||
expect((await get('/dangling')).status).toBe(404);
|
||||
});
|
||||
|
||||
test('static on Bun: a root that is itself a symlink still serves its files', async () => {
|
||||
const aliased = createApp({ modules: [], static: join(base, 'root-alias') });
|
||||
const a = await aliased.fetch(new Request('http://x/a.txt'));
|
||||
expect(a.status).toBe(200);
|
||||
expect(await a.text()).toBe('in root');
|
||||
const sub = await aliased.fetch(new Request('http://x/sub/'));
|
||||
expect(sub.status).toBe(200);
|
||||
expect(await sub.text()).toBe('<h1>Sub</h1>');
|
||||
});
|
||||
@@ -20,6 +20,22 @@ class Rt {
|
||||
for await (const msg of inbound) yield `echo:${msg}`;
|
||||
})();
|
||||
}
|
||||
|
||||
// Never reads `inbound`, so every frame the client sends stays queued (#107).
|
||||
@Ws('/stall')
|
||||
stall() {
|
||||
return (async function* () {
|
||||
await new Promise<never>(() => {});
|
||||
yield '';
|
||||
})();
|
||||
}
|
||||
|
||||
@Ws('/room/:name')
|
||||
room(@ctx() { inbound }: any) {
|
||||
return (async function* () {
|
||||
for await (const msg of inbound) yield `room:${msg}`;
|
||||
})();
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Rt] })
|
||||
class M {}
|
||||
@@ -47,3 +63,77 @@ test('serveBun: HTTP + WebSocket round-trip', async () => {
|
||||
server.stop(true);
|
||||
}
|
||||
});
|
||||
|
||||
// #104: a malformed escape in a param segment used to reject out of the matcher and close 1011.
|
||||
test('serveBun: a malformed upgrade path closes 1008 and the server keeps serving', async () => {
|
||||
const app = createApp({ modules: [M] });
|
||||
const server = await serveBun(app, { port: 0 });
|
||||
const port = server.port;
|
||||
try {
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}/rt/room/%E0%A4%A`);
|
||||
const closed = await new Promise<{ code: number; reason: string }>((resolve) => {
|
||||
ws.onclose = (e) => resolve({ code: e.code, reason: e.reason });
|
||||
});
|
||||
expect(closed).toEqual({ code: 1008, reason: 'invalid request path' });
|
||||
|
||||
const httpRes = await fetch(`http://127.0.0.1:${port}/rt/hello`);
|
||||
expect(httpRes.status).toBe(200);
|
||||
} finally {
|
||||
server.stop(true);
|
||||
}
|
||||
});
|
||||
|
||||
/** Opens `path`, sends `frames` once open, and resolves with every reply and the close. */
|
||||
function exchange(port: number, path: string, frames: string[], until = 2000) {
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}${path}`);
|
||||
const replies: string[] = [];
|
||||
return new Promise<{ replies: string[]; close?: { code: number; reason: string } }>((resolve) => {
|
||||
const timer = setTimeout(() => {
|
||||
ws.close();
|
||||
resolve({ replies });
|
||||
}, until);
|
||||
ws.onopen = () => frames.forEach((f) => ws.send(f));
|
||||
ws.onmessage = (e) => replies.push(String(e.data));
|
||||
ws.onclose = (e) => {
|
||||
clearTimeout(timer);
|
||||
resolve({ replies, close: { code: e.code, reason: e.reason } });
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// #107: Bun refuses an oversized frame natively (`maxPayloadLength`), before buffering it. Its
|
||||
// uWebSockets core drops the TCP connection without a close frame, so the peer sees `1006`, not
|
||||
// the `1009` Node, Deno and the edge send. Asserted rather than papered over: it is the documented
|
||||
// Bun difference, and a Bun upgrade that starts sending 1009 should fail here and be noticed.
|
||||
test('serveBun: ws message size and inbound queue limits', async () => {
|
||||
const app = createApp({ modules: [M], limits: { maxWsMessageBytes: 1024, maxWsQueue: 4 } });
|
||||
const server = await serveBun(app, { port: 0 });
|
||||
const port = server.port;
|
||||
try {
|
||||
const atLimit = await exchange(port, '/rt/echo', ['a'.repeat(1024)], 300);
|
||||
expect(atLimit.replies).toEqual([`echo:${'a'.repeat(1024)}`]);
|
||||
|
||||
const over = await exchange(port, '/rt/echo', ['a'.repeat(1025)]);
|
||||
expect(over.close?.code).toBe(1006);
|
||||
|
||||
const full = await exchange(port, '/rt/stall', ['1', '2', '3', '4', '5']);
|
||||
expect(full.close).toEqual({ code: 1013, reason: 'inbound queue full' });
|
||||
} finally {
|
||||
server.stop(true);
|
||||
}
|
||||
});
|
||||
|
||||
test('serveBun: ws message size default is 1 MiB', async () => {
|
||||
const app = createApp({ modules: [M] });
|
||||
const server = await serveBun(app, { port: 0 });
|
||||
const port = server.port;
|
||||
try {
|
||||
const atLimit = await exchange(port, '/rt/echo', ['a'.repeat(1_048_576)], 500);
|
||||
expect(atLimit.replies.length).toBe(1);
|
||||
|
||||
const over = await exchange(port, '/rt/echo', ['a'.repeat(1_048_577)]);
|
||||
expect(over.close?.code).toBe(1006);
|
||||
} finally {
|
||||
server.stop(true);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
// #105 on the real Deno runtime: the request-body limit is enforced while the body is read, both on
|
||||
// `app.fetch` directly and through `serveDeno`. The counting stream is what proves the read stopped —
|
||||
// a 413 looks the same whether the body was buffered first or not.
|
||||
//
|
||||
// Run with: npm run test:deno
|
||||
import 'reflect-metadata';
|
||||
import { assertEquals } from 'jsr:@std/assert';
|
||||
import { createApp, Route, Post, Module, body } from '../../src/index.ts';
|
||||
import { serveDeno } from '../../src/deno.ts';
|
||||
import { countingStream } from '../helpers/counting-stream.ts';
|
||||
|
||||
const LIMIT = 1_000_000; // the server default
|
||||
const SMALL = 1000;
|
||||
|
||||
@Route('/')
|
||||
class Ctl {
|
||||
@Post('/echo') echo(@body() b: unknown) {
|
||||
return { length: String(b).length };
|
||||
}
|
||||
// Small for the socket tests, so every refused body fits in the socket buffer. A client still
|
||||
// writing a large body when the 413 lands can see a reset instead — the transport racing the
|
||||
// answer, not a different answer.
|
||||
@Post('/small', { maxBodyBytes: SMALL }) small(@body() b: unknown) {
|
||||
return { length: String(b).length };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
|
||||
const post = (url: string, body: BodyInit, headers: Record<string, string> = {}) =>
|
||||
new Request(url, { method: 'POST', body, headers, duplex: 'half' } as RequestInit);
|
||||
|
||||
Deno.test('T1 app.fetch: a declared content-length over the limit is refused unread', async () => {
|
||||
const app = createApp({ modules: [M] });
|
||||
const source = countingStream(10, 300_000);
|
||||
|
||||
const res = await app.fetch(post('http://x/echo', source.stream, { 'content-length': '2000000' }));
|
||||
|
||||
assertEquals(res.status, 413);
|
||||
assertEquals(source.pulled, 0);
|
||||
assertEquals(source.cancelled, true);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
Deno.test('T3 app.fetch: a streamed body stops at the chunk that crosses the limit', async () => {
|
||||
const app = createApp({ modules: [M] });
|
||||
const source = countingStream(10, 300_000);
|
||||
|
||||
const res = await app.fetch(post('http://x/echo', source.stream));
|
||||
|
||||
assertEquals(res.status, 413);
|
||||
if (source.pulled > 5) throw new Error(`pulled ${source.pulled} chunks — the read did not stop at the limit`);
|
||||
assertEquals(source.cancelled, true);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
Deno.test('T5 app.fetch: exactly the limit is accepted, one byte over is refused', async () => {
|
||||
const app = createApp({ modules: [M] });
|
||||
|
||||
const at = await app.fetch(post('http://x/echo', 'x'.repeat(LIMIT), { 'content-type': 'text/plain' }));
|
||||
const over = await app.fetch(post('http://x/echo', 'x'.repeat(LIMIT + 1), { 'content-type': 'text/plain' }));
|
||||
|
||||
assertEquals(at.status, 200);
|
||||
assertEquals(await at.json(), { length: LIMIT });
|
||||
assertEquals(over.status, 413);
|
||||
await over.body?.cancel();
|
||||
await app.close();
|
||||
});
|
||||
|
||||
Deno.test('T11 serveDeno: the same statuses over a real socket', async () => {
|
||||
const server = await serveDeno(createApp({ modules: [M] }), { port: 0, onListen: () => {} });
|
||||
const base = `http://127.0.0.1:${(server as unknown as { addr: { port: number } }).addr.port}`;
|
||||
|
||||
try {
|
||||
const send = (body: BodyInit, headers?: Record<string, string>) => fetch(post(`${base}/small`, body, headers));
|
||||
|
||||
const declared = await send(new Uint8Array(2 * SMALL));
|
||||
assertEquals(declared.status, 413);
|
||||
await declared.body?.cancel();
|
||||
|
||||
const streamed = await send(countingStream(10, 300).stream);
|
||||
assertEquals(streamed.status, 413);
|
||||
await streamed.body?.cancel();
|
||||
|
||||
const at = await send('x'.repeat(SMALL), { 'content-type': 'text/plain' });
|
||||
assertEquals(at.status, 200);
|
||||
await at.body?.cancel();
|
||||
|
||||
const over = await send('x'.repeat(SMALL + 1), { 'content-type': 'text/plain' });
|
||||
assertEquals(over.status, 413);
|
||||
await over.body?.cancel();
|
||||
} finally {
|
||||
await server.close({ timeoutMs: 1000 });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
// #116 on the real Deno runtime: `serveDeno` hands the socket's peer address to `ctx.ip`, the way
|
||||
// Node's `listen()` always has. Without it every client shared `''`, so anything keyed on the
|
||||
// address — the rate-limit plugin above all — put the whole internet in one bucket.
|
||||
//
|
||||
// Run with: npm run test:deno
|
||||
import 'reflect-metadata';
|
||||
import { assertEquals } from 'jsr:@std/assert';
|
||||
import { createApp, Route, Get, Module, ctx } from '../../src/index.ts';
|
||||
import { serveDeno } from '../../src/deno.ts';
|
||||
|
||||
@Route('/')
|
||||
class Ctl {
|
||||
@Get('/ip') ip(@ctx() c: { ip: string }) {
|
||||
return { ip: c.ip };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
|
||||
async function ipVia(
|
||||
hostname: string,
|
||||
opts: { trustProxy?: boolean; headers?: Record<string, string> } = {},
|
||||
): Promise<string> {
|
||||
const server = await serveDeno(createApp({ modules: [M], trustProxy: opts.trustProxy }), {
|
||||
hostname,
|
||||
port: 0,
|
||||
onListen: () => {},
|
||||
});
|
||||
const port = (server as unknown as { addr: { port: number } }).addr.port;
|
||||
const host = hostname.includes(':') ? `[${hostname}]` : hostname;
|
||||
|
||||
try {
|
||||
const res = await fetch(`http://${host}:${port}/ip`, { headers: opts.headers });
|
||||
return ((await res.json()) as { ip: string }).ip;
|
||||
} finally {
|
||||
await server.close({ timeoutMs: 1000 });
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether this host can bind the IPv6 loopback at all; CI containers often cannot. */
|
||||
function ipv6Available(): boolean {
|
||||
try {
|
||||
Deno.listen({ hostname: '::1', port: 0 }).close();
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Deno.test('T1 serveDeno: ctx.ip is the socket peer address', async () => {
|
||||
assertEquals(await ipVia('127.0.0.1'), '127.0.0.1');
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: 'T3 serveDeno: an IPv6 peer is passed through as Deno reports it',
|
||||
ignore: !ipv6Available(), // skipped, not failed: the host has no IPv6 loopback to connect over
|
||||
fn: async () => {
|
||||
assertEquals(await ipVia('::1'), '::1');
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test('T4 serveDeno: trustProxy takes the first x-forwarded-for hop', async () => {
|
||||
const ip = await ipVia('127.0.0.1', { trustProxy: true, headers: { 'x-forwarded-for': '203.0.113.7, 10.0.0.1' } });
|
||||
assertEquals(ip, '203.0.113.7');
|
||||
});
|
||||
|
||||
Deno.test('T5 serveDeno: trustProxy without x-forwarded-for falls back to the peer', async () => {
|
||||
assertEquals(await ipVia('127.0.0.1', { trustProxy: true }), '127.0.0.1');
|
||||
});
|
||||
|
||||
Deno.test('T6 serveDeno: without trustProxy a spoofed x-forwarded-for is ignored', async () => {
|
||||
assertEquals(await ipVia('127.0.0.1', { headers: { 'x-forwarded-for': '1.2.3.4' } }), '127.0.0.1');
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
// The frozen router-parity differential under the real Deno runtime: every matcher case (hand-picked,
|
||||
// owner, generated v1/v2, WS) through the oracle and the live router, and the app.fetch cases, all
|
||||
// against the same frozen files the Node suite uses. See test/router-parity/README.md.
|
||||
//
|
||||
// Run with: npm run test:deno
|
||||
import 'npm:reflect-metadata';
|
||||
import { assertEquals } from 'jsr:@std/assert';
|
||||
import { runDifferential } from '../router-parity/differential.ts';
|
||||
import { runAppDifferential } from '../router-parity/app-fixture.ts';
|
||||
|
||||
const load = async (name: string) =>
|
||||
JSON.parse(await Deno.readTextFile(new URL(`../router-parity/frozen/${name}.json`, import.meta.url)));
|
||||
|
||||
Deno.test('router parity on Deno: frozen matcher differential, oracle and live', async () => {
|
||||
const report = await runDifferential(load);
|
||||
assertEquals(report.mismatches, []);
|
||||
assertEquals(report.sets.length, 5);
|
||||
});
|
||||
|
||||
Deno.test('router parity on Deno: app.fetch cases', async () => {
|
||||
const report = await runAppDifferential(load);
|
||||
assertEquals(report.mismatches, []);
|
||||
});
|
||||
@@ -74,3 +74,40 @@ Deno.test('multipart resolves the busboy peer dependency instead of reporting it
|
||||
assertEquals(await res.json(), { name: 'joe', filename: 'p.png' });
|
||||
await app.close();
|
||||
});
|
||||
|
||||
// #106 on Deno, which reaches `realpath` through its `node:fs` compat. Committed symlinks rather than
|
||||
// a temp tree, for the same `--allow-write` reason as above; `secret.txt` sits beside the root.
|
||||
const linked = 'test/fixtures/static';
|
||||
|
||||
Deno.test('static: a link to a file outside the root is a miss', async () => {
|
||||
const app = createApp({ modules: [], static: `${linked}/root` });
|
||||
const res = await app.fetch(new Request('http://x/out-link'));
|
||||
assertEquals(res.status, 404);
|
||||
assertEquals((await res.text()).includes('TOP SECRET'), false);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
Deno.test('static: a link to a file inside the root is served', async () => {
|
||||
const app = createApp({ modules: [], static: `${linked}/root` });
|
||||
const res = await app.fetch(new Request('http://x/in-link'));
|
||||
assertEquals(res.status, 200);
|
||||
assertEquals(await res.text(), 'in root');
|
||||
await app.close();
|
||||
});
|
||||
|
||||
Deno.test('static: a dangling link is a 404, not a rejection', async () => {
|
||||
const app = createApp({ modules: [], static: `${linked}/root` });
|
||||
assertEquals((await app.fetch(new Request('http://x/dangling'))).status, 404);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
Deno.test('static: a root that is itself a symlink still serves its files', async () => {
|
||||
const app = createApp({ modules: [], static: `${linked}/root-alias` });
|
||||
const a = await app.fetch(new Request('http://x/a.txt'));
|
||||
assertEquals(a.status, 200);
|
||||
assertEquals(await a.text(), 'in root');
|
||||
const sub = await app.fetch(new Request('http://x/sub/'));
|
||||
assertEquals(sub.status, 200);
|
||||
assertEquals(await sub.text(), '<h1>Sub</h1>');
|
||||
await app.close();
|
||||
});
|
||||
@@ -28,6 +28,22 @@ class Rt {
|
||||
for await (const msg of inbound) yield `echo:${msg}`;
|
||||
})();
|
||||
}
|
||||
|
||||
// Never reads `inbound`, so every frame the client sends stays queued (#107).
|
||||
@Ws('/stall')
|
||||
stall() {
|
||||
return (async function* () {
|
||||
await new Promise<never>(() => {});
|
||||
yield '';
|
||||
})();
|
||||
}
|
||||
|
||||
@Ws('/room/:name')
|
||||
room(@ctx() { inbound }: any) {
|
||||
return (async function* () {
|
||||
for await (const msg of inbound) yield `room:${msg}`;
|
||||
})();
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/', controllers: [Rt] })
|
||||
@@ -69,3 +85,99 @@ Deno.test('serveDeno: HTTP + WebSocket round-trip through the graph', async () =
|
||||
await server.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
// #104: a malformed escape in a param segment used to reject out of the matcher and close 1011.
|
||||
Deno.test('serveDeno: a malformed upgrade path closes 1008 and the server keeps serving', async () => {
|
||||
const app = createApp({ modules: [M] });
|
||||
|
||||
let port = 0;
|
||||
const server = await serveDeno(app, {
|
||||
port: 0,
|
||||
onListen: (addr) => {
|
||||
port = addr.port;
|
||||
},
|
||||
});
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
|
||||
try {
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}/rt/room/%E0%A4%A`);
|
||||
const closed = await new Promise<{ code: number; reason: string }>((resolve) => {
|
||||
ws.onclose = (e) => resolve({ code: e.code, reason: e.reason });
|
||||
});
|
||||
assertEquals(closed, { code: 1008, reason: 'invalid request path' });
|
||||
|
||||
const httpRes = await fetch(`http://127.0.0.1:${port}/rt/hello`);
|
||||
assertEquals(httpRes.status, 200);
|
||||
await httpRes.body?.cancel();
|
||||
} finally {
|
||||
await server.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
/** Opens `path`, sends `frames` once open, and resolves with every reply and the close. */
|
||||
function exchange(port: number, path: string, frames: string[], until = 2000) {
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}${path}`);
|
||||
const replies: string[] = [];
|
||||
return new Promise<{ replies: string[]; close?: { code: number; reason: string } }>((resolve) => {
|
||||
const timer = setTimeout(() => {
|
||||
ws.close();
|
||||
resolve({ replies });
|
||||
}, until);
|
||||
ws.onopen = () => frames.forEach((f) => ws.send(f));
|
||||
ws.onmessage = (e) => replies.push(String(e.data));
|
||||
ws.onclose = (e) => {
|
||||
clearTimeout(timer);
|
||||
resolve({ replies, close: { code: e.code, reason: e.reason } });
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// #107: on Deno the runtime receives the whole message before user code sees it, so the size
|
||||
// bound is checked after receipt — the close code is the same as on Node and Bun.
|
||||
Deno.test('serveDeno: ws message size and inbound queue limits', async () => {
|
||||
const app = createApp({ modules: [M], limits: { maxWsMessageBytes: 1024, maxWsQueue: 4 } });
|
||||
let port = 0;
|
||||
const server = await serveDeno(app, {
|
||||
port: 0,
|
||||
onListen: (addr) => {
|
||||
port = addr.port;
|
||||
},
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
|
||||
try {
|
||||
const atLimit = await exchange(port, '/rt/echo', ['a'.repeat(1024)], 300);
|
||||
assertEquals(atLimit.replies, [`echo:${'a'.repeat(1024)}`]);
|
||||
|
||||
const over = await exchange(port, '/rt/echo', ['a'.repeat(1025)]);
|
||||
assertEquals(over.close, { code: 1009, reason: 'message too large' });
|
||||
|
||||
const full = await exchange(port, '/rt/stall', ['1', '2', '3', '4', '5']);
|
||||
assertEquals(full.close, { code: 1013, reason: 'inbound queue full' });
|
||||
} finally {
|
||||
await server.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
Deno.test('serveDeno: ws message size default is 1 MiB', async () => {
|
||||
const app = createApp({ modules: [M] });
|
||||
let port = 0;
|
||||
const server = await serveDeno(app, {
|
||||
port: 0,
|
||||
onListen: (addr) => {
|
||||
port = addr.port;
|
||||
},
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
|
||||
try {
|
||||
const atLimit = await exchange(port, '/rt/echo', ['a'.repeat(1_048_576)], 500);
|
||||
assertEquals(atLimit.replies.length, 1);
|
||||
|
||||
const over = await exchange(port, '/rt/echo', ['a'.repeat(1_048_577)]);
|
||||
assertEquals(over.close?.code, 1009);
|
||||
} finally {
|
||||
await server.shutdown();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
// Worker entry that runs the frozen router-parity differential inside workerd: every matcher case
|
||||
// through the oracle and the live router, and the app.fetch cases, against the same frozen files the
|
||||
// Node suite uses. The frozen JSON is bundled in, since a worker has no file system. Driven by
|
||||
// test/edge/run.ts; see test/router-parity/README.md.
|
||||
import { runDifferential } from '../router-parity/differential';
|
||||
import { runAppDifferential } from '../router-parity/app-fixture';
|
||||
import matcherHand from '../router-parity/frozen/matcher-hand.json';
|
||||
import matcherOwner from '../router-parity/frozen/matcher-owner.json';
|
||||
import matcherGenerated from '../router-parity/frozen/matcher-generated.json';
|
||||
import matcherGeneratedV2 from '../router-parity/frozen/matcher-generated-v2.json';
|
||||
import matcherWs from '../router-parity/frozen/matcher-ws.json';
|
||||
import appFetch from '../router-parity/frozen/app-fetch.json';
|
||||
import ownerAppAllow from '../router-parity/frozen/owner-app-allow.json';
|
||||
|
||||
const FROZEN: Record<string, unknown> = {
|
||||
'matcher-hand': matcherHand,
|
||||
'matcher-owner': matcherOwner,
|
||||
'matcher-generated': matcherGenerated,
|
||||
'matcher-generated-v2': matcherGeneratedV2,
|
||||
'matcher-ws': matcherWs,
|
||||
'app-fetch': appFetch,
|
||||
'owner-app-allow': ownerAppAllow,
|
||||
};
|
||||
|
||||
export default {
|
||||
fetch: async (): Promise<Response> => {
|
||||
const load = (name: string) => FROZEN[name];
|
||||
const matcher = await runDifferential(load);
|
||||
const app = await runAppDifferential(load);
|
||||
return Response.json({ matcher, app });
|
||||
},
|
||||
};
|
||||
+134
-5
@@ -66,6 +66,33 @@ async function main() {
|
||||
assert.equal(httpRes.status, 200);
|
||||
assert.deepEqual(await httpRes.json(), { ok: true });
|
||||
|
||||
// Body limits (#105): the same statuses as app.fetch, Deno and Bun. workerd may drop a
|
||||
// chunked upload's content-length, so the streamed case is enforced by the read count alone.
|
||||
const LIMIT = 1000; // the route's maxBodyBytes, see worker.ts
|
||||
const post = async (body: Uint8Array | string | ReadableStream<Uint8Array>): Promise<number> => {
|
||||
const res = await mf.dispatchFetch('http://localhost/rt/body', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'text/plain' },
|
||||
body,
|
||||
duplex: 'half',
|
||||
} as Parameters<typeof mf.dispatchFetch>[1]);
|
||||
await res.arrayBuffer();
|
||||
return res.status;
|
||||
};
|
||||
const chunks = (count: number, size: number): ReadableStream<Uint8Array> => {
|
||||
let sent = 0;
|
||||
return new ReadableStream({
|
||||
pull(controller) {
|
||||
if (sent++ === count) controller.close();
|
||||
else controller.enqueue(new Uint8Array(size).fill(0x61));
|
||||
},
|
||||
});
|
||||
};
|
||||
assert.equal(await post(new Uint8Array(2 * LIMIT)), 413, 'declared content-length over the limit');
|
||||
assert.equal(await post(chunks(10, 300)), 413, 'streamed body over the limit');
|
||||
assert.equal(await post('x'.repeat(LIMIT)), 200, 'exactly the limit');
|
||||
assert.equal(await post('x'.repeat(LIMIT + 1)), 413, 'one byte over the limit');
|
||||
|
||||
// WebSocket
|
||||
const wsRes = await mf.dispatchFetch('http://localhost/rt/echo', {
|
||||
headers: { Upgrade: 'websocket' },
|
||||
@@ -84,13 +111,115 @@ async function main() {
|
||||
});
|
||||
assert.equal(got, 'echo:hi');
|
||||
|
||||
console.log('edge (workerd via miniflare): HTTP 200 + WS echo:hi — PASS');
|
||||
// #104: a malformed escape in a param segment closes 1008 instead of 1011, and HTTP still serves.
|
||||
const badRes = await mf.dispatchFetch('http://localhost/rt/room/%E0%A4%A', {
|
||||
headers: { Upgrade: 'websocket' },
|
||||
});
|
||||
const bad = badRes.webSocket;
|
||||
assert.ok(bad, 'expected a client webSocket on the 101 response');
|
||||
const closed = new Promise<{ code: number; reason: string }>((resolve) =>
|
||||
bad.addEventListener('close', (e: { code: number; reason: string }) =>
|
||||
resolve({ code: e.code, reason: e.reason }),
|
||||
),
|
||||
);
|
||||
bad.accept();
|
||||
assert.deepEqual(await closed, { code: 1008, reason: 'invalid request path' });
|
||||
assert.equal((await mf.dispatchFetch('http://localhost/rt/hello')).status, 200);
|
||||
|
||||
// #107: workerd delivers the whole message before user code sees it, so the size bound is
|
||||
// checked after receipt; the close codes match Node and Deno.
|
||||
const limitedEcho = async (frames: string[]) => exchange(mf, 'http://limited/rt/echo', frames);
|
||||
assert.deepEqual((await limitedEcho(['a'.repeat(1024)])).replies, [`echo:${'a'.repeat(1024)}`]);
|
||||
assert.deepEqual((await limitedEcho(['a'.repeat(1025)])).close, { code: 1009, reason: 'message too large' });
|
||||
assert.deepEqual((await exchange(mf, 'http://limited/rt/stall', ['1', '2', '3', '4', '5'])).close, {
|
||||
code: 1013,
|
||||
reason: 'inbound queue full',
|
||||
});
|
||||
assert.equal((await exchange(mf, 'http://localhost/rt/echo', ['a'.repeat(1_048_576)])).replies.length, 1);
|
||||
assert.equal((await exchange(mf, 'http://localhost/rt/echo', ['a'.repeat(1_048_577)])).close?.code, 1009);
|
||||
|
||||
console.log('edge (workerd via miniflare): HTTP 200 + body limits 413/413/200/413 + WS echo:hi + ws limits — PASS');
|
||||
} finally {
|
||||
await mf.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
const PARITY_BUNDLE = 'test/edge/_parity-worker.mjs';
|
||||
|
||||
/**
|
||||
* The frozen router-parity differential inside workerd (test/router-parity/README.md). Same bundling
|
||||
* as the main worker; the worker runs every case itself and answers with its mismatch report.
|
||||
*/
|
||||
async function parity() {
|
||||
await build({
|
||||
entryPoints: ['test/edge/parity-worker.ts'],
|
||||
bundle: true,
|
||||
format: 'esm',
|
||||
outfile: PARITY_BUNDLE,
|
||||
platform: 'browser',
|
||||
target: 'esnext',
|
||||
external: ['node:*', 'http', 'https'],
|
||||
alias: {
|
||||
crypto: 'node:crypto',
|
||||
stream: 'node:stream',
|
||||
zlib: 'node:zlib',
|
||||
buffer: 'node:buffer',
|
||||
events: 'node:events',
|
||||
net: 'node:net',
|
||||
tls: 'node:tls',
|
||||
util: 'node:util',
|
||||
},
|
||||
});
|
||||
|
||||
const mf = new Miniflare({
|
||||
modules: true,
|
||||
scriptPath: PARITY_BUNDLE,
|
||||
compatibilityDate: '2024-11-01',
|
||||
compatibilityFlags: ['nodejs_compat'],
|
||||
});
|
||||
|
||||
try {
|
||||
const res = await mf.dispatchFetch('http://localhost/');
|
||||
const report = (await res.json()) as {
|
||||
matcher: { sets: Array<{ name: string; requests: number }>; mismatches: string[] };
|
||||
app: { requests: number; mismatches: string[] };
|
||||
};
|
||||
assert.deepEqual(report.matcher.mismatches, [], 'matcher differential mismatches under workerd');
|
||||
assert.deepEqual(report.app.mismatches, [], 'app.fetch parity mismatches under workerd');
|
||||
const requests = report.matcher.sets.reduce((sum, set) => sum + set.requests, 0);
|
||||
console.log(
|
||||
`edge (workerd): router parity — ${requests} matcher cases + ${report.app.requests} app.fetch cases — PASS`,
|
||||
);
|
||||
} finally {
|
||||
await mf.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/** Opens a ws on `url`, sends `frames`, and resolves with the replies and the close (or none within `ms`). */
|
||||
async function exchange(mf: Miniflare, url: string, frames: string[], ms = 1000) {
|
||||
const res = await mf.dispatchFetch(url, { headers: { Upgrade: 'websocket' } });
|
||||
const ws = res.webSocket;
|
||||
assert.ok(ws, `expected a client webSocket on the 101 response for ${url}`);
|
||||
const replies: string[] = [];
|
||||
const result = new Promise<{ replies: string[]; close?: { code: number; reason: string } }>((resolve) => {
|
||||
const timer = setTimeout(() => {
|
||||
ws.close();
|
||||
resolve({ replies });
|
||||
}, ms);
|
||||
ws.addEventListener('message', (e: { data: unknown }) => replies.push(String(e.data)));
|
||||
ws.addEventListener('close', (e: { code: number; reason: string }) => {
|
||||
clearTimeout(timer);
|
||||
resolve({ replies, close: { code: e.code, reason: e.reason } });
|
||||
});
|
||||
});
|
||||
ws.accept();
|
||||
for (const frame of frames) ws.send(frame);
|
||||
return result;
|
||||
}
|
||||
|
||||
main()
|
||||
.then(parity)
|
||||
.catch((err) => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
+32
-2
@@ -1,7 +1,7 @@
|
||||
// Worker entry for the real workerd (Miniflare) integration test.
|
||||
// Mirrors test/deno/ws.test.ts's graph so HTTP + WebSocket behavior is proven
|
||||
// identically across runtimes. Run via `npm run test:edge` (see test/edge/run.ts).
|
||||
import { createApp, Route, Get, Ws, ctx, Module } from '../../src/index';
|
||||
import { createApp, Route, Get, Post, Ws, body, ctx, Module } from '../../src/index';
|
||||
import { edgeHandler } from '../../src/edge';
|
||||
|
||||
@Route('/rt')
|
||||
@@ -11,17 +11,47 @@ class Rt {
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
// #105: the body limit, read from workerd's own request stream. Small, so every refused body still
|
||||
// fits in the socket buffer: a client that is mid-upload when the 413 lands can see ECONNRESET
|
||||
// instead, which is the transport racing the answer rather than a different answer.
|
||||
@Post('/body', { maxBodyBytes: 1000 })
|
||||
body(@body() b: unknown) {
|
||||
return { length: String(b).length };
|
||||
}
|
||||
|
||||
@Ws('/echo')
|
||||
echo(@ctx() { inbound }: any) {
|
||||
return (async function* () {
|
||||
for await (const msg of inbound) yield `echo:${msg}`;
|
||||
})();
|
||||
}
|
||||
|
||||
// Never reads `inbound`, so every frame the client sends stays queued (#107).
|
||||
@Ws('/stall')
|
||||
stall() {
|
||||
return (async function* () {
|
||||
await new Promise<never>(() => {});
|
||||
yield '';
|
||||
})();
|
||||
}
|
||||
|
||||
@Ws('/room/:name')
|
||||
room(@ctx() { inbound }: any) {
|
||||
return (async function* () {
|
||||
for await (const msg of inbound) yield `room:${msg}`;
|
||||
})();
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/', controllers: [Rt] })
|
||||
class M {}
|
||||
|
||||
const app = createApp({ modules: [M] });
|
||||
// #107: the same graph with tight ws limits, reached through the `limited` host.
|
||||
const limited = createApp({ modules: [M], limits: { maxWsMessageBytes: 1024, maxWsQueue: 4 } });
|
||||
const handlers = { default: edgeHandler(app), limited: edgeHandler(limited) };
|
||||
|
||||
export default { fetch: edgeHandler(app) };
|
||||
export default {
|
||||
fetch: (request: Request, env?: unknown, ctx?: Parameters<typeof handlers.default>[2]) =>
|
||||
(new URL(request.url).hostname === 'limited' ? handlers.limited : handlers.default)(request, env, ctx),
|
||||
};
|
||||
+155
-1
@@ -1,5 +1,7 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { createApp, Provider, Route, Get, Post, Module, needs, body, ctx } from '../src/index';
|
||||
import { countingStream } from './helpers/counting-stream';
|
||||
import { setPeer } from '../src/http/peer';
|
||||
|
||||
@Provider({ provides: 'store' })
|
||||
class Store {
|
||||
@@ -108,6 +110,57 @@ describe('app.fetch trustProxy gates x-forwarded-for', () => {
|
||||
);
|
||||
expect(await res.json()).toEqual({ ip: '' });
|
||||
});
|
||||
|
||||
// #116: the Deno and Bun adapters now hand `buildFetch` the socket peer. A bare `app.fetch` from
|
||||
// user code has none to hand, so it must keep answering exactly what it did before.
|
||||
it('T7: bare app.fetch without peer metadata is unchanged', async () => {
|
||||
const untrusting = createApp({ modules: [IpModule] });
|
||||
const trusting = createApp({ modules: [IpModule], trustProxy: true });
|
||||
|
||||
expect(await (await untrusting.fetch(new Request('http://x/ip/whoami'))).json()).toEqual({ ip: '' });
|
||||
expect(await (await trusting.fetch(new Request('http://x/ip/whoami'))).json()).toEqual({ ip: '' });
|
||||
expect(
|
||||
await (
|
||||
await trusting.fetch(new Request('http://x/ip/whoami', { headers: { 'x-forwarded-for': '9.9.9.9' } }))
|
||||
).json(),
|
||||
).toEqual({ ip: '9.9.9.9' });
|
||||
});
|
||||
|
||||
it('the peer an adapter recorded reaches ctx.ip, and trustProxy without XFF falls back to it', async () => {
|
||||
const untrusting = createApp({ modules: [IpModule] });
|
||||
const trusting = createApp({ modules: [IpModule], trustProxy: true });
|
||||
const spoofed = new Request('http://x/ip/whoami', { headers: { 'x-forwarded-for': '1.2.3.4' } });
|
||||
const plain = new Request('http://x/ip/whoami');
|
||||
setPeer(spoofed, '127.0.0.1');
|
||||
setPeer(plain, '::1');
|
||||
|
||||
expect(await (await untrusting.fetch(spoofed)).json()).toEqual({ ip: '127.0.0.1' });
|
||||
expect(await (await trusting.fetch(plain)).json()).toEqual({ ip: '::1' });
|
||||
});
|
||||
|
||||
// The published CommonJS build bundles `index`, `deno` and `bun` as separate files, each with its
|
||||
// own copy of every module they share, so `serveBun` from `@green-tea/core/bun` and `app.fetch`
|
||||
// from `@green-tea/core` do not run the same `peer.ts`. A store private to the module would be two
|
||||
// stores, and the peer recorded by one would never be found by the other.
|
||||
it('a second copy of the peer module sees the peer the first one recorded', async () => {
|
||||
const request = new Request('http://x/');
|
||||
setPeer(request, '192.0.2.1'); // through the copy this file imported
|
||||
|
||||
vi.resetModules();
|
||||
const copy = await import('../src/http/peer');
|
||||
|
||||
expect(copy.setPeer).not.toBe(setPeer); // really a second instance of the module
|
||||
expect(copy.peerOf(request)).toBe('192.0.2.1');
|
||||
});
|
||||
|
||||
it('T8: only the adapter\'s own Request carries the peer — a copy of it does not', async () => {
|
||||
const original = new Request('http://x/ip/whoami');
|
||||
setPeer(original, '127.0.0.1');
|
||||
|
||||
const res = await createApp({ modules: [IpModule] }).fetch(new Request(original));
|
||||
|
||||
expect(await res.json()).toEqual({ ip: '' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('app.fetch on a mesh app', () => {
|
||||
@@ -145,3 +198,104 @@ describe('app.fetch on a mesh app', () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// #105: the limit is enforced while the body is read, not after it has been buffered. A status code
|
||||
// cannot tell the two apart — both answer 413 — so the counting stream is what these assert on.
|
||||
@Route('/limits')
|
||||
class LimitsCtl {
|
||||
@Post('/echo') echo(@body() b: any) {
|
||||
return { got: b };
|
||||
}
|
||||
@Post('/small', { maxBodyBytes: 10 }) small(@body() b: any) {
|
||||
return { got: b };
|
||||
}
|
||||
@Post('/large', { maxBodyBytes: 2_000_000 }) large(@body() b: any) {
|
||||
return { length: String(b).length };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [LimitsCtl] })
|
||||
class LimitsModule {}
|
||||
|
||||
const post = (path: string, body: RequestInit['body'], headers: Record<string, string> = {}) =>
|
||||
new Request(`http://x${path}`, { method: 'POST', body, headers, duplex: 'half' } as RequestInit);
|
||||
|
||||
describe('app.fetch bounded body reads (#105)', () => {
|
||||
const limitsApp = createApp({ modules: [LimitsModule] }); // server limit: the 1 MB default
|
||||
|
||||
it('T1: a declared content-length over the limit is refused without reading the body', async () => {
|
||||
const body = countingStream(10, 300_000);
|
||||
|
||||
const res = await limitsApp.fetch(post('/limits/echo', body.stream, { 'content-length': '2000000' }));
|
||||
|
||||
expect(res.status).toBe(413);
|
||||
expect(body.pulled).toBe(0);
|
||||
expect(body.cancelled).toBe(true);
|
||||
});
|
||||
|
||||
it('T3: a streamed body stops at the chunk that crosses the limit, and the reader is cancelled', async () => {
|
||||
const body = countingStream(10, 300_000); // 3 MB, no content-length
|
||||
|
||||
const res = await limitsApp.fetch(post('/limits/echo', body.stream));
|
||||
|
||||
expect(res.status).toBe(413);
|
||||
// 4 read, the 4th crossing 1 MB, plus at most one the stream queued ahead of the reader.
|
||||
expect(body.pulled).toBeLessThanOrEqual(5);
|
||||
expect(body.cancelled).toBe(true);
|
||||
});
|
||||
|
||||
it('T4: a body of exactly the limit is accepted', async () => {
|
||||
const json = JSON.stringify({ s: 'x'.repeat(1_000_000 - 8) });
|
||||
expect(Buffer.byteLength(json)).toBe(1_000_000);
|
||||
|
||||
const res = await limitsApp.fetch(post('/limits/echo', json, { 'content-type': 'application/json' }));
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(((await res.json()) as any).got.s).toHaveLength(1_000_000 - 8);
|
||||
});
|
||||
|
||||
it('T5: one byte over the limit is refused', async () => {
|
||||
const json = JSON.stringify({ s: 'x'.repeat(1_000_000 - 7) });
|
||||
|
||||
const res = await limitsApp.fetch(post('/limits/echo', json, { 'content-type': 'application/json' }));
|
||||
|
||||
expect(res.status).toBe(413);
|
||||
});
|
||||
|
||||
it('T5: one byte over the limit is refused when streamed without a content-length', async () => {
|
||||
const body = countingStream(1, 1_000_001);
|
||||
|
||||
const res = await limitsApp.fetch(post('/limits/echo', body.stream));
|
||||
|
||||
expect(res.status).toBe(413);
|
||||
});
|
||||
|
||||
it('T8: a route limit below the server limit wins', async () => {
|
||||
const res = await limitsApp.fetch(post('/limits/small', 'x'.repeat(11), { 'content-type': 'text/plain' }));
|
||||
|
||||
expect(res.status).toBe(413);
|
||||
});
|
||||
|
||||
it('T9: a route limit above the server limit wins', async () => {
|
||||
const res = await limitsApp.fetch(
|
||||
post('/limits/large', 'x'.repeat(1_500_000), { 'content-type': 'text/plain' }),
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({ length: 1_500_000 });
|
||||
});
|
||||
|
||||
it('a malformed content-length is ignored, and the stream count enforces the limit', async () => {
|
||||
const body = countingStream(1, 20);
|
||||
|
||||
const res = await limitsApp.fetch(post('/limits/small', body.stream, { 'content-length': 'nope' }));
|
||||
|
||||
expect(res.status).toBe(413);
|
||||
});
|
||||
|
||||
it('T10: a bodiless request is answered without reading anything', async () => {
|
||||
const res = await limitsApp.fetch(new Request('http://x/limits/echo', { method: 'POST' }));
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({});
|
||||
});
|
||||
});
|
||||
+1
@@ -0,0 +1 @@
|
||||
root
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
in root
|
||||
+1
@@ -0,0 +1 @@
|
||||
../nope.txt
|
||||
+1
@@ -0,0 +1 @@
|
||||
a.txt
|
||||
+1
@@ -0,0 +1 @@
|
||||
../secret.txt
|
||||
+1
@@ -0,0 +1 @@
|
||||
<h1>Sub</h1>
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
TOP SECRET
|
||||
@@ -0,0 +1,44 @@
|
||||
// A request body that records how much of it was consumed. Web APIs only, so the Node, Deno and Bun
|
||||
// suites share it: the regression it guards (#105) is "read the whole body before checking the
|
||||
// limit", which no status code can show on its own — a 413 looks the same either way.
|
||||
|
||||
export interface CountingStream {
|
||||
stream: ReadableStream<Uint8Array>;
|
||||
/** Chunks the consumer has pulled so far. */
|
||||
readonly pulled: number;
|
||||
/** Whether the consumer cancelled the stream. */
|
||||
readonly cancelled: boolean;
|
||||
}
|
||||
|
||||
/** `count` chunks of `size` bytes each, handed out one per pull. */
|
||||
export function countingStream(count: number, size: number): CountingStream {
|
||||
let pulled = 0;
|
||||
let cancelled = false;
|
||||
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
// Pull-based, and only on demand: with a high-water mark of 0 the stream does not pre-fill its
|
||||
// queue, so `pulled` counts what the consumer asked for. The default of 1 pulls a chunk at
|
||||
// construction, before anyone reads, and would make "nothing was read" unprovable.
|
||||
pull(controller) {
|
||||
if (pulled === count) {
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
pulled++;
|
||||
controller.enqueue(new Uint8Array(size).fill(0x61));
|
||||
},
|
||||
cancel() {
|
||||
cancelled = true;
|
||||
},
|
||||
}, { highWaterMark: 0 });
|
||||
|
||||
return {
|
||||
stream,
|
||||
get pulled() {
|
||||
return pulled;
|
||||
},
|
||||
get cancelled() {
|
||||
return cancelled;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -123,6 +123,32 @@ describe('request hardening', () => {
|
||||
server.close();
|
||||
});
|
||||
|
||||
// #105: a declared length over the limit is answered before any of the body is sent. Without the
|
||||
// header check, the reader waits for a first chunk that this client never sends — and times out.
|
||||
it('T2: rejects a declared content-length over the limit before reading any body', async () => {
|
||||
let ran = false;
|
||||
const server = createHttpServer(
|
||||
[{ method: 'POST', pattern: '/echo', transport: 'buffer',
|
||||
handler: async () => { ran = true; return { status: 200, headers: {}, body: 'ok' }; } }],
|
||||
[], undefined, undefined, { limits: { maxBodyBytes: 16 } },
|
||||
);
|
||||
await new Promise<void>((r) => server.listen(0, r));
|
||||
const socket = net.connect((server.address() as any).port, '127.0.0.1');
|
||||
await once(socket, 'connect');
|
||||
socket.write('POST /echo HTTP/1.1\r\nHost: x\r\nContent-Length: 2000000\r\n\r\n'); // headers only
|
||||
|
||||
let raw = '';
|
||||
socket.setEncoding('utf8');
|
||||
socket.on('data', (chunk: string) => (raw += chunk));
|
||||
await once(socket, 'end');
|
||||
|
||||
expect(raw).toMatch(/^HTTP\/1\.1 413 /);
|
||||
expect(raw.toLowerCase()).toContain('connection: close');
|
||||
expect(ran).toBe(false);
|
||||
socket.destroy();
|
||||
server.close();
|
||||
}, 2000);
|
||||
|
||||
it('sets the configured server timeouts and connection limit', async () => {
|
||||
const server = createHttpServer([], [], undefined, undefined,
|
||||
{ limits: { maxConnections: 2468, requestTimeoutMs: 12345, headersTimeoutMs: 6789, keepAliveTimeoutMs: 4321 } });
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
|
||||
import http from 'node:http';
|
||||
import net from 'node:net';
|
||||
import { once } from 'node:events';
|
||||
import { Bus } from '../src/bus';
|
||||
import { createHttpServer } from '../src/http';
|
||||
import type { HttpOptions, RouteDef } from '../src/http/types';
|
||||
import type { Logger } from '../src/logger';
|
||||
|
||||
// #108: `http.createServer` ignores the promise its listener returns, so a rejection inside the
|
||||
// request listener used to be an `unhandledRejection` — fatal under Node's default mode. Every test
|
||||
// here goes through a real socket, because the boundary under test is the Node listener itself.
|
||||
|
||||
interface Reply {
|
||||
status?: number;
|
||||
headers?: http.IncomingHttpHeaders;
|
||||
body?: string;
|
||||
/** Set when the connection ended without a complete response. */
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/** A GET on a fresh connection (`agent: false`), bounded so a hung listener fails fast instead of at the 30 s request timeout. */
|
||||
function get(port: number, path: string, headers: Record<string, string> = {}): Promise<Reply> {
|
||||
return new Promise((resolve) => {
|
||||
const reply: Reply = {};
|
||||
const req = http.request({ host: '127.0.0.1', port, path, headers, agent: false }, (res) => {
|
||||
reply.status = res.statusCode;
|
||||
reply.headers = res.headers;
|
||||
let body = '';
|
||||
res.setEncoding('utf8');
|
||||
res.on('data', (chunk: string) => (body += chunk));
|
||||
res.on('end', () => resolve({ ...reply, body }));
|
||||
res.on('error', (err) => resolve({ ...reply, body, error: err.message }));
|
||||
res.on('aborted', () => resolve({ ...reply, body, error: 'aborted' }));
|
||||
});
|
||||
req.setTimeout(1_000, () => req.destroy(new Error('client timeout')));
|
||||
req.on('error', (err) => resolve({ ...reply, error: err.message }));
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
function spyLogger(): Logger & { error: Mock<(...args: unknown[]) => void> } {
|
||||
return { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() };
|
||||
}
|
||||
|
||||
const ok: RouteDef = {
|
||||
method: 'GET',
|
||||
pattern: '/ok',
|
||||
transport: 'buffer',
|
||||
handler: async () => ({ status: 200, headers: { 'content-type': 'text/plain' }, body: 'ok' }),
|
||||
};
|
||||
|
||||
const servers: http.Server[] = [];
|
||||
|
||||
async function start(routes: RouteDef[], opts: HttpOptions = {}, bus?: Bus): Promise<number> {
|
||||
const server = createHttpServer([ok, ...routes], [], bus, undefined, opts);
|
||||
servers.push(server);
|
||||
server.listen(0, '127.0.0.1');
|
||||
await once(server, 'listening');
|
||||
return (server.address() as net.AddressInfo).port;
|
||||
}
|
||||
|
||||
/** T10: after every injected failure, a normal request on a fresh connection still succeeds. */
|
||||
async function expectServerStillServes(port: number): Promise<void> {
|
||||
const next = await get(port, '/ok');
|
||||
expect(next.status).toBe(200);
|
||||
expect(next.body).toBe('ok');
|
||||
}
|
||||
|
||||
const settle = () => new Promise((r) => setTimeout(r, 20));
|
||||
|
||||
let unhandled: Mock<(...args: unknown[]) => void>;
|
||||
let uncaught: Mock<(...args: unknown[]) => void>;
|
||||
|
||||
beforeEach(() => {
|
||||
unhandled = vi.fn();
|
||||
uncaught = vi.fn();
|
||||
process.on('unhandledRejection', unhandled);
|
||||
process.on('uncaughtException', uncaught);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await settle();
|
||||
process.off('unhandledRejection', unhandled);
|
||||
process.off('uncaughtException', uncaught);
|
||||
|
||||
for (const server of servers.splice(0)) {
|
||||
server.closeAllConnections();
|
||||
server.close();
|
||||
}
|
||||
|
||||
expect(unhandled).not.toHaveBeenCalled();
|
||||
expect(uncaught).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
const rejectingStatic = (reason: unknown) => async () => {
|
||||
throw reason;
|
||||
};
|
||||
|
||||
describe('Node request-listener boundary (#108)', () => {
|
||||
it('T1: a rejected request operation while writable answers a minimal 500 and closes', async () => {
|
||||
const logger = spyLogger();
|
||||
const port = await start([], { static: rejectingStatic(new Error('boom')), logger });
|
||||
|
||||
const res = await get(port, '/missing');
|
||||
expect(res.status).toBe(500);
|
||||
expect(res.headers?.connection).toBe('close');
|
||||
expect(res.headers?.['content-type']).toBe('application/json');
|
||||
expect(JSON.parse(res.body!)).toEqual({ error: 'Internal Server Error' });
|
||||
// The security headers still land: the minimal path writes through the patched writeHead.
|
||||
expect(res.headers?.['x-content-type-options']).toBe('nosniff');
|
||||
expect(logger.error).toHaveBeenCalledTimes(1);
|
||||
expect(logger.error).toHaveBeenCalledWith('request listener failed', { err: 'boom' });
|
||||
|
||||
await expectServerStillServes(port);
|
||||
});
|
||||
|
||||
it.each([['boom'], [undefined]])('T2: a non-Error rejection (%s) answers 500 and logs String(err)', async (reason) => {
|
||||
const logger = spyLogger();
|
||||
const port = await start([], { static: rejectingStatic(reason), logger });
|
||||
|
||||
const res = await get(port, '/missing');
|
||||
expect(res.status).toBe(500);
|
||||
expect(logger.error).toHaveBeenCalledWith('request listener failed', { err: String(reason) });
|
||||
|
||||
await expectServerStillServes(port);
|
||||
});
|
||||
|
||||
// Deviation from the card: `originAllowed` already guards a throwing predicate and denies the origin
|
||||
// (src/security.ts), so this never reaches the listener boundary. Kept as a regression test.
|
||||
it('T3: a throwing cors.origins predicate denies the origin and serves the request', async () => {
|
||||
const logger = spyLogger();
|
||||
const port = await start([], {
|
||||
logger,
|
||||
cors: {
|
||||
origins: () => {
|
||||
throw new Error('allowlist down');
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await get(port, '/ok', { origin: 'https://a.example' });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers?.['access-control-allow-origin']).toBeUndefined();
|
||||
|
||||
await expectServerStillServes(port);
|
||||
});
|
||||
|
||||
it('T4: an invalid handler header value answers 500 through the minimal path', async () => {
|
||||
const logger = spyLogger();
|
||||
const port = await start(
|
||||
[
|
||||
{
|
||||
method: 'GET',
|
||||
pattern: '/bad-header',
|
||||
transport: 'buffer',
|
||||
handler: async () => ({ status: 200, headers: { 'x-bad': 'a\nb' }, body: 'nope' }),
|
||||
},
|
||||
],
|
||||
{ logger },
|
||||
);
|
||||
|
||||
const res = await get(port, '/bad-header');
|
||||
expect(res.status).toBe(500);
|
||||
expect(res.headers?.connection).toBe('close');
|
||||
expect(res.headers?.['x-bad']).toBeUndefined();
|
||||
expect(logger.error).toHaveBeenCalledTimes(1);
|
||||
|
||||
await expectServerStillServes(port);
|
||||
});
|
||||
|
||||
// The card's BigInt injection is caught inside `pipeStream`'s loop and becomes an error frame, so it
|
||||
// never reaches the boundary; kept as a regression test. The second case fails after the 200 headers
|
||||
// are flushed but before that loop, which is the "output already started" path.
|
||||
it('T5a: a stream encoder failure on the first frame ends the stream with an error frame', async () => {
|
||||
const port = await start([
|
||||
{
|
||||
method: 'GET',
|
||||
pattern: '/big',
|
||||
transport: 'ndjson',
|
||||
handler: async () => ({
|
||||
stream: (async function* () {
|
||||
yield { n: BigInt(1) };
|
||||
})(),
|
||||
}),
|
||||
},
|
||||
]);
|
||||
|
||||
const res = await get(port, '/big');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toContain('"error"');
|
||||
|
||||
await expectServerStillServes(port);
|
||||
});
|
||||
|
||||
it('T5b: a failure after the 200 headers were sent destroys the connection and is logged', async () => {
|
||||
const logger = spyLogger();
|
||||
const port = await start(
|
||||
[
|
||||
{
|
||||
method: 'GET',
|
||||
pattern: '/broken-stream',
|
||||
transport: 'ndjson',
|
||||
handler: async () => ({
|
||||
stream: {
|
||||
[Symbol.asyncIterator]() {
|
||||
throw new Error('iterator failed');
|
||||
},
|
||||
},
|
||||
}),
|
||||
},
|
||||
],
|
||||
{ logger },
|
||||
);
|
||||
|
||||
const res = await get(port, '/broken-stream');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.error).toBeDefined();
|
||||
expect(logger.error).toHaveBeenCalledWith('request listener failed', { err: 'iterator failed' });
|
||||
|
||||
await expectServerStillServes(port);
|
||||
});
|
||||
|
||||
it('T6: a throwing onError still sends the built-in 404', async () => {
|
||||
const logger = spyLogger();
|
||||
const port = await start([], {
|
||||
logger,
|
||||
onError: () => {
|
||||
throw new Error('renderer broke');
|
||||
},
|
||||
});
|
||||
|
||||
const res = await get(port, '/missing');
|
||||
expect(res.status).toBe(404);
|
||||
|
||||
await expectServerStillServes(port);
|
||||
});
|
||||
|
||||
it('T7: a throwing request:start observer does not alter the response', async () => {
|
||||
const bus = new Bus();
|
||||
bus.on('request:start', () => {
|
||||
throw new Error('observer broke');
|
||||
});
|
||||
const port = await start([], { bus }, bus);
|
||||
|
||||
await expectServerStillServes(port);
|
||||
await expectServerStillServes(port);
|
||||
});
|
||||
|
||||
it('T8: a client abort racing a rejection leaves no unhandled rejection and no write after close', async () => {
|
||||
const logger = spyLogger();
|
||||
let rejected!: () => void;
|
||||
const done = new Promise<void>((r) => (rejected = r));
|
||||
const port = await start([], {
|
||||
logger,
|
||||
static: async () => {
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
rejected();
|
||||
throw new Error('late');
|
||||
},
|
||||
});
|
||||
|
||||
const socket = net.connect(port, '127.0.0.1');
|
||||
await once(socket, 'connect');
|
||||
socket.write('GET /missing HTTP/1.1\r\nHost: x\r\n\r\n');
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
socket.destroy();
|
||||
await done;
|
||||
await settle();
|
||||
|
||||
expect(logger.error).toHaveBeenCalledWith('request listener failed', { err: 'late' });
|
||||
await expectServerStillServes(port);
|
||||
});
|
||||
|
||||
it('T9: a rejection releases its maxConcurrentRequests slot', async () => {
|
||||
const port = await start(
|
||||
[],
|
||||
{ static: rejectingStatic(new Error('boom')), limits: { maxConcurrentRequests: 1 }, logger: spyLogger() },
|
||||
);
|
||||
|
||||
expect((await get(port, '/missing')).status).toBe(500);
|
||||
await expectServerStillServes(port);
|
||||
await expectServerStillServes(port);
|
||||
});
|
||||
});
|
||||
@@ -56,11 +56,11 @@ function startSkewedTeapot() {
|
||||
|
||||
/**
|
||||
* Both client implementations, exercised on whatever Node runs the suite. `ws` is always in the
|
||||
* list: it is the Node 18-21 path, and on a modern CI the platform global would otherwise be the
|
||||
* only one ever covered — the fallback would rot unnoticed until someone ran the declared floor.
|
||||
* list: it is the fallback for a Node run with the global WebSocket switched off, and every
|
||||
* supported Node has the global, so it would otherwise never be covered and rot unnoticed.
|
||||
*/
|
||||
const platform = (globalThis as { WebSocket?: SocketCtor }).WebSocket;
|
||||
const CTORS: [string, SocketCtor][] = [['the ws package (Node < 22 path)', WS as unknown as SocketCtor]];
|
||||
const CTORS: [string, SocketCtor][] = [['the ws package (fallback path)', WS as unknown as SocketCtor]];
|
||||
if (platform) CTORS.push(['the platform global WebSocket', platform]);
|
||||
|
||||
describe('WebSocket client implementations', () => {
|
||||
|
||||
@@ -1,6 +1,20 @@
|
||||
import { describe, it, expect, afterEach } from 'vitest';
|
||||
import { describe, it, expect, afterEach, vi } from 'vitest';
|
||||
import { createApp, Route, Post, Module, body } from '../src';
|
||||
|
||||
// Counts calls into the multipart parser while still running the real one, so a test can prove
|
||||
// busboy was never reached rather than inferring it from the status code.
|
||||
const parsed = vi.hoisted(() => ({ calls: 0 }));
|
||||
vi.mock('../src/multipart', async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import('../src/multipart')>();
|
||||
return {
|
||||
...real,
|
||||
parseMultipart: (...args: Parameters<typeof real.parseMultipart>) => {
|
||||
parsed.calls++;
|
||||
return real.parseMultipart(...args);
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
let app: any;
|
||||
afterEach(async () => { await app?.close(); });
|
||||
|
||||
@@ -88,3 +102,63 @@ describe('bodyDuplicates', () => {
|
||||
expect(await post('/b')).toEqual({ x: ['1', '2'] });
|
||||
});
|
||||
});
|
||||
|
||||
// #105: multipart is parsed from the bytes the bounded reader returns, so the byte limit has to stop
|
||||
// a request before busboy ever sees it, and `maxParts` has to keep working on what gets through.
|
||||
describe('multipart limits on app.fetch (#105)', () => {
|
||||
const form = (fields: number, size = 1) => {
|
||||
const fd = new FormData();
|
||||
for (let i = 0; i < fields; i++) fd.set(`f${i}`, 'x'.repeat(size));
|
||||
return fd;
|
||||
};
|
||||
|
||||
it('T6: a multipart body over maxBodyBytes is 413 and never reaches the parser', async () => {
|
||||
@Route('/') class C { @Post('/u', { maxBodyBytes: 1000 }) u(@body() b: any) { return b; } }
|
||||
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
|
||||
app = createApp({ modules: [CMod] });
|
||||
parsed.calls = 0;
|
||||
|
||||
const r = await app.fetch(new Request('http://x/u', { method: 'POST', body: form(1, 5000) }));
|
||||
|
||||
expect(r.status).toBe(413);
|
||||
expect(parsed.calls).toBe(0);
|
||||
});
|
||||
|
||||
it('T6: the same holds when the multipart body arrives without a content-length', async () => {
|
||||
@Route('/') class C { @Post('/u', { maxBodyBytes: 1000 }) u(@body() b: any) { return b; } }
|
||||
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
|
||||
app = createApp({ modules: [CMod] });
|
||||
parsed.calls = 0;
|
||||
const encoded = new Request('http://x', { method: 'POST', body: form(1, 5000) });
|
||||
|
||||
const r = await app.fetch(new Request('http://x/u', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': encoded.headers.get('content-type')! },
|
||||
body: encoded.body,
|
||||
duplex: 'half',
|
||||
} as RequestInit));
|
||||
|
||||
expect(r.status).toBe(413);
|
||||
expect(parsed.calls).toBe(0);
|
||||
});
|
||||
|
||||
it('T7: under the byte limit but over maxParts is 400 Invalid multipart body', async () => {
|
||||
@Route('/') class C { @Post('/u', { maxParts: 2 }) u(@body() b: any) { return b; } }
|
||||
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
|
||||
app = createApp({ modules: [CMod] });
|
||||
|
||||
const r = await app.fetch(new Request('http://x/u', { method: 'POST', body: form(3) }));
|
||||
|
||||
expect(r.status).toBe(400);
|
||||
expect(await r.text()).toContain('Invalid multipart body');
|
||||
});
|
||||
|
||||
it('T7: the server-level maxParts applies when the route sets none', async () => {
|
||||
@Route('/') class C { @Post('/u') u(@body() b: any) { return b; } }
|
||||
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
|
||||
app = createApp({ modules: [CMod], limits: { maxParts: 2 } });
|
||||
|
||||
expect((await app.fetch(new Request('http://x/u', { method: 'POST', body: form(1) }))).status).toBe(200);
|
||||
expect((await app.fetch(new Request('http://x/u', { method: 'POST', body: form(3) }))).status).toBe(400);
|
||||
});
|
||||
});
|
||||
@@ -1,27 +0,0 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
// The `engines` floor is `>=18`, and the global `crypto` only arrived unflagged in Node 19. That gap
|
||||
// shipped once: `correlateRequest` compiled cleanly against an ambient declaration and then threw
|
||||
// `ReferenceError: crypto is not defined` on the first request of every Node 18 process.
|
||||
//
|
||||
// CI's Node 18 job is what caught it, and this test is what makes it catchable without one — every
|
||||
// developer machine and every other runtime has the global, so the bug is invisible where it is
|
||||
// written. Stubbing the global away reproduces the floor's condition on any Node.
|
||||
//
|
||||
// If the floor ever moves above 18, this test and the fallback it guards can both go.
|
||||
describe('correlateRequest without a global crypto (Node 18)', () => {
|
||||
it('falls back to node:crypto instead of throwing ReferenceError', async () => {
|
||||
vi.stubGlobal('crypto', undefined);
|
||||
vi.resetModules();
|
||||
|
||||
const { correlateRequest } = await import('../src/http/core');
|
||||
const a = correlateRequest({});
|
||||
const b = correlateRequest({});
|
||||
|
||||
expect(a.requestId).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/);
|
||||
expect(a.requestId).not.toBe(b.requestId);
|
||||
expect(correlateRequest({ 'x-request-id': 'from-gateway' }).requestId).toBe('from-gateway');
|
||||
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
# Router parity corpus (frozen)
|
||||
|
||||
The compatibility baseline for replacing the linear HTTP matcher with a radix index
|
||||
(FPRD-001 CARD-07/08/09/10, issue #109). Everything here was captured from
|
||||
`@green-tea/core` at **`ed47836c9820c47bf4ed5e902d91e019abdb110a`** (develop after #117 and #122).
|
||||
|
||||
## The rule
|
||||
|
||||
**The baseline is immutable through CARD-07 review.** If the router change makes a test here fail,
|
||||
the router changed behaviour. That is a compatibility failure, not a stale fixture.
|
||||
|
||||
A deliberate compatibility change needs its own maintainer approval, recorded on the card, and a
|
||||
reviewed edit to the specific frozen file, in a commit that says why. Do not edit a golden to make a
|
||||
test pass, do not edit `oracle.ts` to fit a new implementation, and do not delete a frozen file to
|
||||
let a capture run recreate it.
|
||||
|
||||
Nothing can regenerate the baseline by accident:
|
||||
|
||||
- `vitest -u` is refused with an error. These are plain JSON files, not vitest snapshots.
|
||||
- `ROUTER_PARITY_CAPTURE=1` only writes a frozen file that **does not exist**. It never
|
||||
overwrites. It is how the files were first captured, and how a new fixture gets added later.
|
||||
|
||||
## What is here
|
||||
|
||||
| File | What it freezes |
|
||||
|---|---|
|
||||
| `manifest.json` | Existing tests retained unchanged (ROUTER-CORPUS §1), with the verification result at the pinned revision. `manifest.test.ts` fails if a named file or test disappears. |
|
||||
| `oracle.ts` | Verbatim copy of the pre-radix `matchRoute`, `resolveRoute`, `allowedMethods`, `normalizeRequestPath`, `compilePattern` and `matchWsRoute`. Test-only; `src/` must never import it. |
|
||||
| `cases.ts`, `generator.ts` | Matcher inputs: 24 hand-picked scenarios (§2), 9 owner-requested scenarios (backtracking, cross-pattern `Allow`, encoded slashes, zero-segment catch-alls), and a fixed-seed generator in two versions, both seed `10908`: `router-parity-gen-v1`, and `router-parity-gen-v2`, which forces static/param/constrained/catch-all siblings under shared prefixes. |
|
||||
| `branches.ts` | Measures the share of generated requests that walk into sibling branches and backtrack; frozen with the v2 fixture. |
|
||||
| `frozen/matcher-*.json` | Captured matcher outputs: declaration ID, decoded params, `implicitHead`, ordered `Allow`, or the normalization error. The generated file also stores the seed, the generator rules and every generated input. |
|
||||
| `frozen/app-*.json` | Status, headers, `Allow` and body through `app.fetch` and through a Node socket, including HEAD body suppression. |
|
||||
| `frozen/ws-*.json` | WS upgrade selection through `app.upgrade` and the Node listener, plus HTTP requests at the WS paths. |
|
||||
| `frozen/owner-*.json` | Owner additions needing a running app: cross-pattern `Allow` through both adapters, and the mesh HTTP route table across a peer's lifetime (it is built once at boot and never changes — see `owner.test.ts`). |
|
||||
| `frozen/boot-*.json` | Boot-time rejections: pattern compilation, local ambiguity, mesh splicing. |
|
||||
| `frozen/golden-*.json` | `graph()`, `explain()`, `openapi({ title: 'Parity', version: '1' })`, and a mesh teacup before and after `ready()`. |
|
||||
|
||||
## How the comparison works
|
||||
|
||||
`matcher.test.ts` runs every scenario through the oracle **and** through the live
|
||||
`src/http/router` exports, and requires both to equal the frozen capture. Today the live router is
|
||||
the linear matcher, so this proves the oracle is a faithful copy. CARD-07 replaces the internals
|
||||
behind the same exports, and the same test then compares oracle against radix with no edit here.
|
||||
|
||||
Each run builds fresh `RouteDef` objects, so the two implementations never share a cached table, and
|
||||
the answering route is identified by declaration ID, never by pattern text.
|
||||
|
||||
Application-level, WS, boot and introspection files are compared against the live code only,
|
||||
because there is no second implementation of `app.fetch` to diff against; the frozen capture plays
|
||||
the oracle's role.
|
||||
|
||||
### On every runtime
|
||||
|
||||
`differential.ts` and `app-fixture.ts` hold the same comparison with no vitest and no file API, so
|
||||
it runs unchanged on Deno (`test/deno/router-parity.test.ts`), Bun (`test/bun/router-parity.test.ts`)
|
||||
and workerd (`test/edge/parity-worker.ts`, driven by `test/edge/run.ts`). Each runtime runs every frozen
|
||||
matcher case through both the oracle and the live router, plus the `app.fetch` cases from
|
||||
`app-fetch.json` and `owner-app-allow.json`. The Node-socket, WS-upgrade, boot and mesh files stay
|
||||
Node-only: they need `http.request`, the `ws` client, or a mesh peer listening on a port.
|
||||
|
||||
### Mutation check
|
||||
|
||||
`npm run parity:mutants` (not part of `npm test`) applies targeted mutants modelling likely radix
|
||||
bugs to a temporary copy of `src/`, runs this suite against each, and reports which were killed.
|
||||
`src/` itself is never modified.
|
||||
|
||||
The performance half of the baseline is in `bench/lookup.ts` and `bench/baseline/router-ed47836/`.
|
||||
@@ -0,0 +1,241 @@
|
||||
/**
|
||||
* The application-level fetch fixtures, free of vitest and of any runtime API, so the same app and
|
||||
* requests run through `app.fetch` on Node, Deno, Bun and workerd. `app.test.ts` and
|
||||
* `owner.test.ts` use them with the frozen files; the runtime runners call {@link runAppDifferential}.
|
||||
*/
|
||||
import 'reflect-metadata';
|
||||
import { createApp, Route, Get, Head, Post, Put, Patch, Delete, Options, Sse, Module, param } from '../../src/index';
|
||||
import type { App } from '../../src/app/types';
|
||||
import type { FrozenLoader } from './differential';
|
||||
|
||||
const reply = (id: string, params: Record<string, string>) => ({ id, params });
|
||||
|
||||
// Ordered on purpose: the overlapping declarations are registered least-specific first, so a
|
||||
// lookup that fell back to registration order would answer differently from one that ranks.
|
||||
@Route('/')
|
||||
class ParityHttp {
|
||||
@Get('/a/:rest*') aRest(@param() p: Record<string, string>) {
|
||||
return reply('aRest', p);
|
||||
}
|
||||
@Get('/a/:id') aId(@param() p: Record<string, string>) {
|
||||
return reply('aId', p);
|
||||
}
|
||||
@Get('/a/b') aB(@param() p: Record<string, string>) {
|
||||
return reply('aB', p);
|
||||
}
|
||||
@Get('/users/:value') usersValue(@param() p: Record<string, string>) {
|
||||
return reply('usersValue', p);
|
||||
}
|
||||
@Get('/users/:id(\\d+)') usersId(@param() p: Record<string, string>) {
|
||||
return reply('usersId', p);
|
||||
}
|
||||
@Get('/n/:num(\\d+)') nNum(@param() p: Record<string, string>) {
|
||||
return reply('nNum', p);
|
||||
}
|
||||
@Get('/n/:code([0-9a-f]+)') nCode(@param() p: Record<string, string>) {
|
||||
return reply('nCode', p);
|
||||
}
|
||||
@Get('/files') files(@param() p: Record<string, string>) {
|
||||
return reply('files', p);
|
||||
}
|
||||
@Get('/files/:rest*') filesRest(@param() p: Record<string, string>) {
|
||||
return reply('filesRest', p);
|
||||
}
|
||||
@Get('/m') mGet(@param() p: Record<string, string>) {
|
||||
return reply('mGet', p);
|
||||
}
|
||||
@Post('/m') mPost(@param() p: Record<string, string>) {
|
||||
return reply('mPost', p);
|
||||
}
|
||||
@Get('/h') hGet(@param() p: Record<string, string>) {
|
||||
return reply('hGet', p);
|
||||
}
|
||||
@Head('/h') hHead(@param() p: Record<string, string>) {
|
||||
return reply('hHead', p);
|
||||
}
|
||||
@Sse('/stream') stream() {
|
||||
return (async function* () {
|
||||
yield { id: 'stream' };
|
||||
})();
|
||||
}
|
||||
@Sse('/s/live') sLive() {
|
||||
return (async function* () {
|
||||
yield { id: 'sLive' };
|
||||
})();
|
||||
}
|
||||
@Get('/s/:id') sId(@param() p: Record<string, string>) {
|
||||
return reply('sId', p);
|
||||
}
|
||||
@Get('/Case') caseUpper(@param() p: Record<string, string>) {
|
||||
return reply('caseUpper', p);
|
||||
}
|
||||
@Get('/u/:name') uName(@param() p: Record<string, string>) {
|
||||
return reply('uName', p);
|
||||
}
|
||||
@Get('/admin') admin(@param() p: Record<string, string>) {
|
||||
return reply('admin', p);
|
||||
}
|
||||
@Get('/public/:file') publicFile(@param() p: Record<string, string>) {
|
||||
return reply('publicFile', p);
|
||||
}
|
||||
@Delete('/r') rDelete(@param() p: Record<string, string>) {
|
||||
return reply('rDelete', p);
|
||||
}
|
||||
@Patch('/r') rPatch(@param() p: Record<string, string>) {
|
||||
return reply('rPatch', p);
|
||||
}
|
||||
@Options('/r') rOptions(@param() p: Record<string, string>) {
|
||||
return reply('rOptions', p);
|
||||
}
|
||||
@Put('/r') rPut(@param() p: Record<string, string>) {
|
||||
return reply('rPut', p);
|
||||
}
|
||||
@Get('/') root(@param() p: Record<string, string>) {
|
||||
return reply('root', p);
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/', controllers: [ParityHttp] })
|
||||
export class ParityHttpModule {}
|
||||
|
||||
export type Req = [method: string, raw: string];
|
||||
|
||||
export const REQUESTS: Req[] = [
|
||||
['GET', '/a/b'],
|
||||
['GET', '/a/x'],
|
||||
['GET', '/a/x/y'],
|
||||
['GET', '/a'],
|
||||
['GET', '/users/42'],
|
||||
['GET', '/users/alice'],
|
||||
['GET', '/users/a%20b'],
|
||||
['GET', '/n/42'],
|
||||
['GET', '/n/ff'],
|
||||
['GET', '/files'],
|
||||
['GET', '/files/'],
|
||||
['GET', '/files/a%2Fb'],
|
||||
['GET', '/m'],
|
||||
['HEAD', '/m'],
|
||||
['OPTIONS', '/m'],
|
||||
['PUT', '/m'],
|
||||
['DELETE', '/m'],
|
||||
['POST', '/m'],
|
||||
['GET', '/h'],
|
||||
['HEAD', '/h'],
|
||||
['GET', '/stream'],
|
||||
['HEAD', '/stream'],
|
||||
['OPTIONS', '/stream'],
|
||||
['HEAD', '/s/live'],
|
||||
['HEAD', '/s/x'],
|
||||
['GET', '/absent'],
|
||||
['HEAD', '/absent'],
|
||||
['OPTIONS', '/absent'],
|
||||
['GET', '/users/%E0%A4%A'],
|
||||
['HEAD', '/users/%E0%A4%A'],
|
||||
['GET', '/a//b'],
|
||||
['GET', '/Case'],
|
||||
['GET', '/case'],
|
||||
['GET', '/caf%C3%A9'],
|
||||
['GET', '/u/caf%C3%A9'],
|
||||
['GET', '/public/../admin'],
|
||||
['GET', '/public/%2e%2e/admin'],
|
||||
['GET', '/public/..%2fadmin'],
|
||||
['GET', '/admin/'],
|
||||
['OPTIONS', '/r'],
|
||||
['HEAD', '/r'],
|
||||
['GET', '/r'],
|
||||
['PURGE', '/r'], // TRACE is a forbidden method for `new Request`
|
||||
['GET', '/'],
|
||||
['GET', '/?q=1'],
|
||||
];
|
||||
|
||||
/** Headers that vary per run or per connection rather than per route decision. */
|
||||
const VOLATILE = new Set(['date', 'connection', 'keep-alive', 'x-request-id']);
|
||||
|
||||
export function stableHeaders(entries: Iterable<[string, string]>): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
for (const [name, value] of [...entries].sort(([a], [b]) => a.localeCompare(b)))
|
||||
if (!VOLATILE.has(name)) out[name] = value;
|
||||
return out;
|
||||
}
|
||||
|
||||
export interface Observed {
|
||||
method: string;
|
||||
raw: string;
|
||||
status: number;
|
||||
headers: Record<string, string>;
|
||||
body: string;
|
||||
}
|
||||
|
||||
export async function viaFetch(app: App, [method, raw]: Req): Promise<Observed> {
|
||||
// `new Request` applies the URL parser first — exactly what Deno, Bun and workerd do.
|
||||
const res = await app.fetch(new Request(`http://parity.test${raw}`, { method }));
|
||||
return { method, raw, status: res.status, headers: stableHeaders(res.headers), body: await res.text() };
|
||||
}
|
||||
|
||||
// `/ca` is GET :id + POST b; `/cb` adds DELETE :rest*. Two prefixes because one app cannot hold both
|
||||
// variants at the same path.
|
||||
@Route('/')
|
||||
class CrossAllow {
|
||||
@Get('/ca/:id') caGet(@param() p: Record<string, string>) {
|
||||
return { id: 'caGet', p };
|
||||
}
|
||||
@Post('/ca/b') caPost() {
|
||||
return { id: 'caPost' };
|
||||
}
|
||||
@Get('/cb/:id') cbGet(@param() p: Record<string, string>) {
|
||||
return { id: 'cbGet', p };
|
||||
}
|
||||
@Post('/cb/b') cbPost() {
|
||||
return { id: 'cbPost' };
|
||||
}
|
||||
@Delete('/cb/:rest*') cbDelete(@param() p: Record<string, string>) {
|
||||
return { id: 'cbDelete', p };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [CrossAllow] })
|
||||
export class CrossAllowModule {}
|
||||
|
||||
export const ALLOW_REQUESTS: Array<[string, string]> = ['/ca', '/cb'].flatMap((base): Array<[string, string]> => [
|
||||
['PUT', `${base}/b`],
|
||||
['OPTIONS', `${base}/b`],
|
||||
['PUT', `${base}/x`],
|
||||
['HEAD', `${base}/b`],
|
||||
['PUT', `${base}/x/y`],
|
||||
]);
|
||||
|
||||
export interface Seen {
|
||||
method: string;
|
||||
path: string;
|
||||
status: number;
|
||||
allow: string | null;
|
||||
body: string;
|
||||
}
|
||||
|
||||
export async function fetchRequest(app: App, method: string, path: string): Promise<Seen> {
|
||||
const res = await app.fetch(new Request(`http://parity.test${path}`, { method }));
|
||||
return { method, path, status: res.status, allow: res.headers.get('allow'), body: await res.text() };
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the frozen `app.fetch` cases — `app-fetch.json` and the fetch rows of `owner-app-allow.json`
|
||||
* — on whatever runtime calls it, and returns every mismatch.
|
||||
*/
|
||||
export async function runAppDifferential(load: FrozenLoader): Promise<{ requests: number; mismatches: string[] }> {
|
||||
const mismatches: string[] = [];
|
||||
const parity = createApp({ modules: [ParityHttpModule] });
|
||||
const appFetch = ((await load('app-fetch')) as { data: Observed[] }).data;
|
||||
for (const [index, req] of REQUESTS.entries()) {
|
||||
const seen = await viaFetch(parity, req);
|
||||
if (JSON.stringify(seen) !== JSON.stringify(appFetch[index])) mismatches.push(`app-fetch ${req[0]} ${req[1]}`);
|
||||
}
|
||||
|
||||
const cross = createApp({ modules: [CrossAllowModule] });
|
||||
const allow = ((await load('owner-app-allow')) as { data: Array<Seen & { adapter: string }> }).data;
|
||||
const fetchRows = allow.filter((row) => row.adapter === 'fetch');
|
||||
for (const [index, [method, path]] of ALLOW_REQUESTS.entries()) {
|
||||
const seen = { adapter: 'fetch', ...(await fetchRequest(cross, method, path)) };
|
||||
if (JSON.stringify(seen) !== JSON.stringify(fetchRows[index])) mismatches.push(`owner-app-allow ${method} ${path}`);
|
||||
}
|
||||
|
||||
return { requests: REQUESTS.length + ALLOW_REQUESTS.length, mismatches };
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* Application-level router parity: what a client sees through `app.fetch` and through a real Node
|
||||
* socket — status, `Allow`, response headers, and HEAD body suppression. Matcher equality alone
|
||||
* cannot prove these: the 404/405/OPTIONS decisions, the 400 for a bad path and the HEAD body rule
|
||||
* live in `src/http/core.ts`, around the matcher.
|
||||
*/
|
||||
import http from 'http';
|
||||
import type { AddressInfo } from 'net';
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
import { createApp } from '../../src/index';
|
||||
import { readFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import {
|
||||
ParityHttpModule,
|
||||
REQUESTS,
|
||||
runAppDifferential,
|
||||
stableHeaders,
|
||||
viaFetch,
|
||||
type Observed,
|
||||
type Req,
|
||||
} from './app-fixture';
|
||||
import type { App } from '../../src/app/types';
|
||||
import { frozen, expectFrozenEqual } from './frozen';
|
||||
|
||||
function viaNode(port: number, [method, raw]: Req): Promise<Observed> {
|
||||
// `http.request` sends the path bytes as given, so the server sees the raw target.
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = http.request({ host: '127.0.0.1', port, method, path: raw, agent: false }, (res) => {
|
||||
let body = '';
|
||||
res.setEncoding('utf8');
|
||||
res.on('data', (chunk) => (body += chunk));
|
||||
res.on('end', () => {
|
||||
const headers = Object.entries(res.headers).map(([k, v]): [string, string] => [
|
||||
k,
|
||||
Array.isArray(v) ? v.join(', ') : String(v),
|
||||
]);
|
||||
resolve({ method, raw, status: res.statusCode ?? 0, headers: stableHeaders(headers), body });
|
||||
});
|
||||
});
|
||||
req.on('error', reject);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
describe('router parity: application-level HTTP outcomes', () => {
|
||||
let fetchApp: App;
|
||||
let nodeApp: App;
|
||||
let port: number;
|
||||
|
||||
beforeAll(async () => {
|
||||
fetchApp = createApp({ modules: [ParityHttpModule] });
|
||||
nodeApp = createApp({ modules: [ParityHttpModule] });
|
||||
const server = await nodeApp.listen(0);
|
||||
port = (server.address() as AddressInfo).port;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await nodeApp.close();
|
||||
});
|
||||
|
||||
it('app.fetch outcomes equal the frozen capture', async () => {
|
||||
const run = async () => {
|
||||
const out: Observed[] = [];
|
||||
for (const req of REQUESTS) out.push(await viaFetch(fetchApp, req));
|
||||
return out;
|
||||
};
|
||||
const expected = await frozen('app-fetch', run);
|
||||
expectFrozenEqual(await run(), expected, 'app.fetch');
|
||||
});
|
||||
|
||||
it('Node listener outcomes equal the frozen capture', async () => {
|
||||
const run = async () => {
|
||||
const out: Observed[] = [];
|
||||
for (const req of REQUESTS) out.push(await viaNode(port, req));
|
||||
return out;
|
||||
};
|
||||
const expected = await frozen('app-node', run);
|
||||
expectFrozenEqual(await run(), expected, 'node listener');
|
||||
});
|
||||
|
||||
it('the runtime-neutral app differential (the one Deno, Bun and workerd run) reports no mismatch', async () => {
|
||||
const dir = join(__dirname, 'frozen');
|
||||
const report = await runAppDifferential((name) => JSON.parse(readFileSync(join(dir, `${name}.json`), 'utf8')));
|
||||
expect(report.mismatches).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,315 @@
|
||||
/**
|
||||
* Boot-time rejection parity: invalid patterns, local ambiguity and mesh route splicing. These are
|
||||
* not inputs to the differential matcher — a pattern that fails here never reaches a lookup — so
|
||||
* they are frozen as their own expected-error fixture: the rejection point (pattern compile, app
|
||||
* construction, mesh `ready()`), the error class and the exact message.
|
||||
*/
|
||||
import 'reflect-metadata';
|
||||
import type { AddressInfo } from 'net';
|
||||
import { describe, it } from 'vitest';
|
||||
import { createApp, Route, Get, Post, Sse, Ws, Module, param } from '../../src/index';
|
||||
import type { RouteDecorator } from '../../src/metadata';
|
||||
import type { Logger } from '../../src/logger';
|
||||
import * as live from '../../src/http/router';
|
||||
import * as oracle from './oracle';
|
||||
import { errorOutcome, type ErrorOutcome } from './matcher';
|
||||
import { frozen, expectFrozenEqual } from './frozen';
|
||||
|
||||
const PATTERNS = [
|
||||
'/',
|
||||
'/users/:id',
|
||||
'/users/:id(\\d+)',
|
||||
'/files/:rest*',
|
||||
'/:rest*',
|
||||
'/t/',
|
||||
'/café',
|
||||
'/build/:version(\\d{2}\\.\\d{1,2})',
|
||||
'/x/:id/:id',
|
||||
'/x/:id/:rest*/tail',
|
||||
'/x/:rest*/:rest*',
|
||||
'/x/:',
|
||||
'/x/:1x',
|
||||
'/x//y',
|
||||
'x',
|
||||
'',
|
||||
'/x/:id((a+)+)',
|
||||
'/x/:id((?=a)a)',
|
||||
'/x/:id(\\1)',
|
||||
'/x/:id(a|b)',
|
||||
'/x/:id(\\d+\\w+)',
|
||||
'/x/:id(\\d{5,2})',
|
||||
'/x/:id(\\d{1,4096})',
|
||||
'/x/:id(\\d+',
|
||||
'/x/:id()',
|
||||
`/x/:id(${'a'.repeat(129)})`,
|
||||
];
|
||||
|
||||
type PatternOutcome = { pattern: string; shape: string } | { pattern: string; error: ErrorOutcome };
|
||||
|
||||
function compileAll(compile: (pattern: string) => { shape: string }): PatternOutcome[] {
|
||||
return PATTERNS.map((pattern) => {
|
||||
try {
|
||||
return { pattern, shape: compile(pattern).shape };
|
||||
} catch (error) {
|
||||
return { pattern, error: errorOutcome(error) };
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
type Decl = [decorator: RouteDecorator, path: string];
|
||||
|
||||
/** One controller per case, its handlers declared in the given order (decorators applied by hand). */
|
||||
function moduleWith(decls: Decl[]) {
|
||||
class ParityBoot {}
|
||||
decls.forEach(([decorator, path], index) => {
|
||||
const name = `h${index}`;
|
||||
Object.defineProperty(ParityBoot.prototype, name, {
|
||||
value: () => (async function* () {})(),
|
||||
configurable: true,
|
||||
});
|
||||
decorator(path)(ParityBoot.prototype, name, Object.getOwnPropertyDescriptor(ParityBoot.prototype, name)!);
|
||||
});
|
||||
Route('/')(ParityBoot);
|
||||
class ParityBootModule {}
|
||||
Module({ mountpoint: '/', controllers: [ParityBoot] })(ParityBootModule);
|
||||
return ParityBootModule;
|
||||
}
|
||||
|
||||
const APP_CASES: Array<{ id: string; decls: Decl[] }> = [
|
||||
{ id: 'B01-duplicate-param', decls: [[Get, '/x/:id/:id']] },
|
||||
{ id: 'B02-nonfinal-catch-all', decls: [[Get, '/x/:rest*/tail']] },
|
||||
{ id: 'B03-nested-quantifier', decls: [[Get, '/x/:id((a+)+)']] },
|
||||
{ id: 'B04-alternation', decls: [[Get, '/x/:id(a|b)']] },
|
||||
{ id: 'B05-adjacent-unbounded', decls: [[Get, '/x/:id(\\d+\\w+)']] },
|
||||
{ id: 'B06-inverted-quantifier', decls: [[Get, '/x/:id(\\d{5,2})']] },
|
||||
{ id: 'B07-invalid-param-name', decls: [[Get, '/x/:1x']] },
|
||||
{ id: 'B08-malformed-constraint', decls: [[Get, '/x/:id(\\d+']] },
|
||||
{
|
||||
id: 'B09-same-shape-plain',
|
||||
decls: [
|
||||
[Get, '/users/:id'],
|
||||
[Get, '/users/:name'],
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'B10-same-shape-constrained',
|
||||
decls: [
|
||||
[Get, '/c/:a(\\d+)'],
|
||||
[Get, '/c/:b(\\d+)'],
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'B11-trailing-slash-twin',
|
||||
decls: [
|
||||
[Get, '/t'],
|
||||
[Get, '/t/'],
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'B12-get-and-ws-same-path',
|
||||
decls: [
|
||||
[Get, '/live'],
|
||||
[Ws, '/live'],
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'B13-get-and-sse-same-path',
|
||||
decls: [
|
||||
[Get, '/feed'],
|
||||
[Sse, '/feed'],
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'B14-ws-same-shape',
|
||||
decls: [
|
||||
[Ws, '/w/:a'],
|
||||
[Ws, '/w/:b'],
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'B15-ok-same-shape-different-methods',
|
||||
decls: [
|
||||
[Get, '/users/:id'],
|
||||
[Post, '/users/:name'],
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'B16-ok-different-constraints',
|
||||
decls: [
|
||||
[Get, '/c/:a(\\d+)'],
|
||||
[Get, '/c/:b([a-z]+)'],
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'B17-ok-static-and-param',
|
||||
decls: [
|
||||
[Get, '/users/me'],
|
||||
[Get, '/users/:id'],
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'B18-ok-exact-and-catch-all',
|
||||
decls: [
|
||||
[Get, '/f'],
|
||||
[Get, '/f/:rest*'],
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const LABELS = new Map<RouteDecorator, string>([
|
||||
[Get, '@Get'],
|
||||
[Post, '@Post'],
|
||||
[Sse, '@Sse'],
|
||||
[Ws, '@Ws'],
|
||||
]);
|
||||
|
||||
function bootAll() {
|
||||
return APP_CASES.map(({ id, decls }) => {
|
||||
const declarations = decls.map(([decorator, path]) => `${LABELS.get(decorator)}('${path}')`);
|
||||
try {
|
||||
createApp({ modules: [moduleWith(decls)] });
|
||||
return { id, declarations, ok: true };
|
||||
} catch (error) {
|
||||
return { id, declarations, error: errorOutcome(error) };
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ── mesh ────────────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
const SECRET = 'parity-secret';
|
||||
|
||||
@Route('/dup')
|
||||
class DupCtl {
|
||||
@Get('/ping', { export: true }) ping() {
|
||||
return { from: 'teapot' };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [DupCtl] })
|
||||
class DupTeapotModule {}
|
||||
|
||||
@Route('/shape')
|
||||
class ShapeIdCtl {
|
||||
@Get('/:id', { export: true }) get(@param() p: Record<string, string>) {
|
||||
return { from: 'id', p };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [ShapeIdCtl] })
|
||||
class ShapeIdTeapotModule {}
|
||||
|
||||
@Route('/shape')
|
||||
class ShapeNameCtl {
|
||||
@Get('/:name', { export: true }) get(@param() p: Record<string, string>) {
|
||||
return { from: 'name', p };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [ShapeNameCtl] })
|
||||
class ShapeNameTeapotModule {}
|
||||
|
||||
// Same method and shape as the teapot's export: the local route wins, with a warning.
|
||||
@Route('/dup')
|
||||
class ShadowCtl {
|
||||
@Get('/ping') local() {
|
||||
return { from: 'local' };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [ShadowCtl] })
|
||||
class ShadowTeacupModule {}
|
||||
|
||||
// A different shape that overlaps the export: no warning, and lookup ranks across local and remote.
|
||||
@Route('/dup')
|
||||
class OverlapCtl {
|
||||
@Get('/:anything') local(@param() p: Record<string, string>) {
|
||||
return { from: 'local', p };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [OverlapCtl] })
|
||||
class OverlapTeacupModule {}
|
||||
|
||||
@Route('/c')
|
||||
class PlainCtl {
|
||||
@Get('/ok') ok() {
|
||||
return { from: 'teacup' };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [PlainCtl] })
|
||||
class PlainTeacupModule {}
|
||||
|
||||
type Ctor = new (...args: unknown[]) => unknown;
|
||||
|
||||
function recordingLogger(): { logger: Logger; warnings: string[] } {
|
||||
const warnings: string[] = [];
|
||||
const noop = () => {};
|
||||
return { logger: { debug: noop, info: noop, error: noop, warn: (m) => warnings.push(m) }, warnings };
|
||||
}
|
||||
|
||||
/** Starts one teapot per module and returns their control URLs plus a function that hides the ports. */
|
||||
async function teapots(modules: Ctor[]) {
|
||||
const apps = modules.map((module) => createApp({ modules: [module], experimental: true, mesh: { secret: SECRET } }));
|
||||
const servers = await Promise.all(apps.map((app) => app.listen(0)));
|
||||
const urls = servers.map((s) => `ws://127.0.0.1:${(s.address() as AddressInfo).port}/__mesh__/control`);
|
||||
const anonymize = (text: string) => urls.reduce((out, url, i) => out.split(url).join(`<teapot${i + 1}>`), text);
|
||||
const close = () => Promise.all(apps.map((app) => app.close()));
|
||||
return { urls, anonymize, close };
|
||||
}
|
||||
|
||||
async function meshCase(id: string, teacupModule: Ctor, teapotModules: Ctor[], requests: string[]) {
|
||||
const pots = await teapots(teapotModules);
|
||||
const { logger, warnings } = recordingLogger();
|
||||
const teacup = createApp({
|
||||
modules: [teacupModule],
|
||||
experimental: true,
|
||||
logger,
|
||||
mesh: { teapots: pots.urls.map((url) => ({ url, secret: SECRET })) },
|
||||
});
|
||||
|
||||
try {
|
||||
await teacup.ready();
|
||||
const responses = [];
|
||||
for (const path of requests) {
|
||||
const res = await teacup.fetch(new Request(`http://parity.test${path}`));
|
||||
responses.push({ path, status: res.status, body: await res.text() });
|
||||
}
|
||||
const routing = warnings.filter((w) => w.includes('precedence')).map(pots.anonymize);
|
||||
return { id, ok: true, warnings: routing, responses };
|
||||
} catch (error) {
|
||||
const { name, message } = errorOutcome(error);
|
||||
return { id, error: { name, message: pots.anonymize(message) } };
|
||||
} finally {
|
||||
await teacup.close();
|
||||
await pots.close();
|
||||
}
|
||||
}
|
||||
|
||||
async function meshAll() {
|
||||
return [
|
||||
await meshCase('M01-two-teapots-same-route', PlainTeacupModule, [DupTeapotModule, DupTeapotModule], []),
|
||||
await meshCase('M02-two-teapots-same-shape', PlainTeacupModule, [ShapeIdTeapotModule, ShapeNameTeapotModule], []),
|
||||
await meshCase('M03-local-same-shape-wins', ShadowTeacupModule, [DupTeapotModule], ['/api/dup/ping']),
|
||||
await meshCase('M04-unique-remote', PlainTeacupModule, [DupTeapotModule], ['/api/dup/ping', '/c/ok', '/api/nope']),
|
||||
await meshCase(
|
||||
'M05-remote-static-outranks-local-param',
|
||||
OverlapTeacupModule,
|
||||
[DupTeapotModule],
|
||||
['/api/dup/ping', '/api/dup/x'],
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
describe('router parity: boot-time rejection', () => {
|
||||
it('pattern compilation (oracle and live compilePattern) equals the frozen capture', async () => {
|
||||
const expected = await frozen('boot-patterns', () => compileAll(live.compilePattern));
|
||||
expectFrozenEqual(compileAll(oracle.compilePattern), expected, 'oracle compilePattern');
|
||||
expectFrozenEqual(compileAll(live.compilePattern), expected, 'live compilePattern');
|
||||
});
|
||||
|
||||
it('createApp route-table validation equals the frozen capture', async () => {
|
||||
const expected = await frozen('boot-app', bootAll);
|
||||
expectFrozenEqual(bootAll(), expected, 'createApp');
|
||||
});
|
||||
|
||||
it('mesh route splicing equals the frozen capture', async () => {
|
||||
const expected = await frozen('boot-mesh', meshAll);
|
||||
expectFrozenEqual(await meshAll(), expected, 'mesh splice');
|
||||
}, 30_000);
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* Measures how much of a corpus exercises sibling branches, so "the generator covers backtracking"
|
||||
* is a number rather than a hope. Method-agnostic: a tree is walked by path before a method is
|
||||
* chosen, so any declaration that shares the walk counts.
|
||||
*
|
||||
* - sibling hit: two declarations both match the request's leading segments through a segment
|
||||
* where their patterns differ — the lookup has two branches to choose between at that point.
|
||||
* - backtrack: a sibling hit where at least one of those declarations then fails to match the
|
||||
* whole path — a branch the lookup walks into and has to leave.
|
||||
*/
|
||||
import { compilePattern, normalizeRequestPath, type CompiledSegment } from './oracle';
|
||||
import type { Scenario } from './matcher';
|
||||
|
||||
function segmentMatches(segment: CompiledSegment, value: string): boolean {
|
||||
if (segment.kind === 'static') return segment.value === value;
|
||||
if (segment.kind === 'catchAll') return true;
|
||||
const decoded = value.includes('%') ? decodeURIComponent(value) : value;
|
||||
return !segment.constraint || segment.constraint.test(decoded);
|
||||
}
|
||||
|
||||
/** Leading segments matched, and whether the whole path matched. */
|
||||
function walk(pattern: string, segs: string[]): { depth: number; full: boolean } {
|
||||
const { segments } = compilePattern(pattern);
|
||||
for (let i = 0; i < segments.length; i++) {
|
||||
if (segments[i].kind === 'catchAll') return { depth: segments.length, full: true };
|
||||
if (i >= segs.length || !segmentMatches(segments[i], segs[i])) return { depth: i, full: false };
|
||||
}
|
||||
return { depth: segments.length, full: segments.length === segs.length };
|
||||
}
|
||||
|
||||
const sameSegment = (a: CompiledSegment, b: CompiledSegment): boolean =>
|
||||
JSON.stringify({ ...a, constraint: undefined }) === JSON.stringify({ ...b, constraint: undefined });
|
||||
|
||||
export interface BranchStats {
|
||||
requests: number;
|
||||
validPaths: number;
|
||||
siblingHits: number;
|
||||
backtracks: number;
|
||||
siblingShare: string;
|
||||
backtrackShare: string;
|
||||
}
|
||||
|
||||
export function branchStats(scenarios: Scenario[]): BranchStats {
|
||||
let requests = 0;
|
||||
let validPaths = 0;
|
||||
let siblingHits = 0;
|
||||
let backtracks = 0;
|
||||
|
||||
for (const scenario of scenarios) {
|
||||
const patterns = [...new Set(scenario.declarations.map((d) => d.pattern))];
|
||||
|
||||
for (const { raw } of scenario.requests) {
|
||||
requests++;
|
||||
let path: string;
|
||||
try {
|
||||
path = normalizeRequestPath(raw);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
validPaths++;
|
||||
|
||||
const segs = path.split('/').filter(Boolean);
|
||||
const walks = patterns.map((pattern) => ({ segments: compilePattern(pattern).segments, ...walk(pattern, segs) }));
|
||||
let sibling = false;
|
||||
let backtrack = false;
|
||||
|
||||
for (let i = 0; i < walks.length; i++) {
|
||||
for (let j = i + 1; j < walks.length; j++) {
|
||||
const [a, b] = [walks[i], walks[j]];
|
||||
const shared = Math.min(a.depth, b.depth, a.segments.length, b.segments.length);
|
||||
const diverge = Array.from({ length: shared }, (_, d) => d).find(
|
||||
(d) => !sameSegment(a.segments[d], b.segments[d]),
|
||||
);
|
||||
if (diverge === undefined) continue;
|
||||
sibling = true;
|
||||
if (!a.full || !b.full) backtrack = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (sibling) siblingHits++;
|
||||
if (backtrack) backtracks++;
|
||||
}
|
||||
}
|
||||
|
||||
const pct = (n: number) => `${((n / requests) * 100).toFixed(1)}%`;
|
||||
return {
|
||||
requests,
|
||||
validPaths,
|
||||
siblingHits,
|
||||
backtracks,
|
||||
siblingShare: pct(siblingHits),
|
||||
backtrackShare: pct(backtracks),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
/**
|
||||
* Hand-picked matcher scenarios (ROUTER-CORPUS §2). Declaration IDs are stable across a scenario
|
||||
* and its reversed twin, so a reversed run is compared by which declaration answered, not by which
|
||||
* pattern text happens to sit first.
|
||||
*
|
||||
* Inputs only. The expected outputs live in `frozen/matcher-hand.json`, captured from the pinned
|
||||
* revision; nothing in this file states what the answer should be.
|
||||
*/
|
||||
import type { Declaration, Request, Scenario, Transport } from './matcher';
|
||||
|
||||
type Decl = [id: string, method: string, pattern: string, transport?: Transport];
|
||||
type Req = [method: string, raw: string];
|
||||
|
||||
function scenario(id: string, note: string, decls: Decl[], reqs: Req[]): Scenario {
|
||||
const declarations = decls.map(([declId, method, pattern, transport = 'buffer']): Declaration => ({
|
||||
id: declId,
|
||||
method,
|
||||
pattern,
|
||||
transport,
|
||||
}));
|
||||
const requests = reqs.map(([method, raw]): Request => ({ method, raw }));
|
||||
return { id, note, declarations, requests };
|
||||
}
|
||||
|
||||
/** The same scenario with its declarations in reverse registration order. */
|
||||
function reversed(base: Scenario, id: string): Scenario {
|
||||
return { ...base, id, note: `${base.note} (declarations reversed)`, declarations: [...base.declarations].reverse() };
|
||||
}
|
||||
|
||||
const get = (...paths: string[]): Req[] => paths.map((path): Req => ['GET', path]);
|
||||
const methods = (path: string, ...verbs: string[]): Req[] => verbs.map((verb): Req => [verb, path]);
|
||||
|
||||
const rank = scenario(
|
||||
'H01-rank',
|
||||
'static beats plain param beats catch-all',
|
||||
[
|
||||
['catchAll', 'GET', '/a/:rest*'],
|
||||
['param', 'GET', '/a/:id'],
|
||||
['static', 'GET', '/a/b'],
|
||||
],
|
||||
[...get('/a/b', '/a/x', '/a/x/y', '/a', '/a/'), ['HEAD', '/a/x'], ['OPTIONS', '/a/b'], ['POST', '/a/b']],
|
||||
);
|
||||
|
||||
const constraint = scenario(
|
||||
'H03-constraint',
|
||||
'constrained param beats plain param; constraint tested against the decoded segment',
|
||||
[
|
||||
['plain', 'GET', '/users/:value'],
|
||||
['digits', 'GET', '/users/:id(\\d+)'],
|
||||
],
|
||||
get('/users/42', '/users/alice', '/users/42x', '/users/%34%32', '/users/'),
|
||||
);
|
||||
|
||||
const constraintTie = scenario(
|
||||
'H05-constraint-tie',
|
||||
'two overlapping constraints of equal rank: registration order decides',
|
||||
[
|
||||
['digits', 'GET', '/n/:num(\\d+)'],
|
||||
['hex', 'GET', '/n/:code([0-9a-f]+)'],
|
||||
],
|
||||
get('/n/42', '/n/ff', '/n/4f', '/n/zz'),
|
||||
);
|
||||
|
||||
const equalRank = scenario(
|
||||
'H08-equal-rank',
|
||||
'equal-specificity plain params: first registered wins',
|
||||
[
|
||||
['first', 'GET', '/t/:first'],
|
||||
['second', 'GET', '/t/:second'],
|
||||
],
|
||||
[...get('/t/x', '/t/x/y'), ['HEAD', '/t/x']],
|
||||
);
|
||||
|
||||
const samePattern = scenario(
|
||||
'H10-same-pattern',
|
||||
'identical pattern text under two declaration IDs (mesh local/remote twins reach the matcher this way)',
|
||||
[
|
||||
['one', 'GET', '/same'],
|
||||
['two', 'GET', '/same'],
|
||||
],
|
||||
[...get('/same'), ['HEAD', '/same'], ['OPTIONS', '/same']],
|
||||
);
|
||||
|
||||
export const HAND_SCENARIOS: Scenario[] = [
|
||||
rank,
|
||||
reversed(rank, 'H02-rank-reversed'),
|
||||
constraint,
|
||||
reversed(constraint, 'H04-constraint-reversed'),
|
||||
constraintTie,
|
||||
reversed(constraintTie, 'H06-constraint-tie-reversed'),
|
||||
scenario(
|
||||
'H07-exact-vs-catch-all',
|
||||
'exact route at /files, catch-all below it, decoded captures',
|
||||
[
|
||||
['exact', 'GET', '/files'],
|
||||
['rest', 'GET', '/files/:rest*'],
|
||||
],
|
||||
[...get('/files', '/files/', '/files/a%2Fb', '/files/a/b/c', '/files/a%20b/c%2Fd'), ['HEAD', '/files/x']],
|
||||
),
|
||||
equalRank,
|
||||
reversed(equalRank, 'H09-equal-rank-reversed'),
|
||||
samePattern,
|
||||
reversed(samePattern, 'H11-same-pattern-reversed'),
|
||||
scenario(
|
||||
'H12-method-implicit-head',
|
||||
'buffered GET supplies HEAD; OPTIONS and 405 share one canonical Allow',
|
||||
[
|
||||
['get', 'GET', '/m'],
|
||||
['post', 'POST', '/m'],
|
||||
],
|
||||
methods('/m', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT', 'DELETE', 'PATCH'),
|
||||
),
|
||||
scenario(
|
||||
'H13-method-explicit-head',
|
||||
'an explicit HEAD wins over the buffered-GET fallback',
|
||||
[
|
||||
['get', 'GET', '/m'],
|
||||
['post', 'POST', '/m'],
|
||||
['head', 'HEAD', '/m'],
|
||||
],
|
||||
methods('/m', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT', 'DELETE'),
|
||||
),
|
||||
scenario(
|
||||
'H14-streaming-head',
|
||||
'a streaming GET does not supply HEAD',
|
||||
[['stream', 'GET', '/stream', 'sse']],
|
||||
methods('/stream', 'GET', 'HEAD', 'OPTIONS', 'POST'),
|
||||
),
|
||||
scenario(
|
||||
'H15-streaming-outranks-buffered',
|
||||
'HEAD skips a higher-ranked streaming GET and falls back to a lower-ranked buffered GET',
|
||||
[
|
||||
['live', 'GET', '/s/live', 'sse'],
|
||||
['byId', 'GET', '/s/:id'],
|
||||
],
|
||||
[...methods('/s/live', 'GET', 'HEAD', 'OPTIONS'), ['HEAD', '/s/x']],
|
||||
),
|
||||
scenario(
|
||||
'H16-negotiate-and-ndjson-head',
|
||||
'negotiate and ndjson GETs are streaming transports for the HEAD rule',
|
||||
[
|
||||
['negotiate', 'GET', '/neg', 'negotiate'],
|
||||
['ndjson', 'GET', '/nd', 'ndjson'],
|
||||
],
|
||||
[...methods('/neg', 'GET', 'HEAD', 'OPTIONS'), ...methods('/nd', 'HEAD', 'OPTIONS')],
|
||||
),
|
||||
scenario(
|
||||
'H17-allow-order',
|
||||
'Allow is canonical regardless of declaration order; explicit OPTIONS is a normal route',
|
||||
[
|
||||
['delete', 'DELETE', '/r'],
|
||||
['patch', 'PATCH', '/r'],
|
||||
['options', 'OPTIONS', '/r'],
|
||||
['put', 'PUT', '/r'],
|
||||
['get', 'GET', '/r', 'sse'],
|
||||
['post', 'POST', '/r'],
|
||||
],
|
||||
methods('/r', 'OPTIONS', 'HEAD', 'GET', 'TRACE', 'POST'),
|
||||
),
|
||||
scenario(
|
||||
'H18-path-miss',
|
||||
'a path no pattern matches: no route and an empty Allow',
|
||||
[['a', 'GET', '/a']],
|
||||
[...get('/absent', '/a/extra', '/'), ['OPTIONS', '/absent'], ['HEAD', '/absent']],
|
||||
),
|
||||
scenario(
|
||||
'H19-encoding-case-unicode',
|
||||
'decoded params, malformed escapes, repeated slashes, exact case and Unicode literals',
|
||||
[
|
||||
['userId', 'GET', '/users/:id'],
|
||||
['upper', 'GET', '/Case'],
|
||||
['unicode', 'GET', '/café'],
|
||||
['unicodeParam', 'GET', '/u/:name'],
|
||||
],
|
||||
get(
|
||||
'/users/a%20b',
|
||||
'/users/a+b',
|
||||
'/users/%F0%9F%8D%B5',
|
||||
'/users/%E0%A4%A',
|
||||
'/users/%zz',
|
||||
'/a//b',
|
||||
'/users//x',
|
||||
'/Case',
|
||||
'/case',
|
||||
'/CASE',
|
||||
'/café',
|
||||
'/caf%C3%A9',
|
||||
'/u/caf%C3%A9',
|
||||
'/u/café',
|
||||
),
|
||||
),
|
||||
scenario(
|
||||
'H20-normalization',
|
||||
'one trailing slash removed; plain and encoded dot segments resolved before lookup',
|
||||
[
|
||||
['a', 'GET', '/a'],
|
||||
['admin', 'GET', '/admin'],
|
||||
['file', 'GET', '/public/:file'],
|
||||
],
|
||||
get(
|
||||
'/a/',
|
||||
'/a//',
|
||||
'/public/../admin',
|
||||
'/public/%2e%2e/admin',
|
||||
'/public/%2E%2E/admin',
|
||||
'/public/./x',
|
||||
'/a/.',
|
||||
'/public/..%2fadmin',
|
||||
'/..',
|
||||
'/a/b/../../admin',
|
||||
'',
|
||||
'a',
|
||||
),
|
||||
),
|
||||
scenario(
|
||||
'H21-root',
|
||||
'the root pattern and a root catch-all',
|
||||
[
|
||||
['any', 'GET', '/:rest*'],
|
||||
['root', 'GET', '/'],
|
||||
],
|
||||
get('/', '/x', '/x/y', '/x/'),
|
||||
),
|
||||
scenario(
|
||||
'H22-first-differing-segment',
|
||||
'ranking is decided at the first segment whose kind differs',
|
||||
[
|
||||
['paramStatic', 'GET', '/a/:x/c'],
|
||||
['staticParam', 'GET', '/a/b/:y'],
|
||||
['paramConstrained', 'GET', '/a/:x/:y(\\d+)'],
|
||||
],
|
||||
get('/a/b/c', '/a/z/c', '/a/z/5', '/a/b/5', '/a/z/q'),
|
||||
),
|
||||
scenario(
|
||||
'H23-per-position-decode',
|
||||
'a decoded value is the same for every candidate the scan reaches',
|
||||
[
|
||||
['zzz', 'GET', '/a/:x/zzz'],
|
||||
['b', 'GET', '/a/:y/b'],
|
||||
],
|
||||
get('/a/a%20b/b', '/a/a%20b/zzz'),
|
||||
),
|
||||
scenario(
|
||||
'H24-constrained-catch-all',
|
||||
'two catch-alls ranked by the segments before them',
|
||||
[
|
||||
['named', 'GET', '/v/:name/:rest*'],
|
||||
['versioned', 'GET', '/v/:ver(\\d+)/:rest*'],
|
||||
],
|
||||
get('/v/1/x', '/v/a/x', '/v/1', '/v'),
|
||||
),
|
||||
];
|
||||
|
||||
/**
|
||||
* Owner-requested additions (CARD-08 review), frozen separately in `frozen/matcher-owner.json` so the
|
||||
* first capture stays untouched. Inputs only, like everything above.
|
||||
*/
|
||||
export const OWNER_SCENARIOS: Scenario[] = [
|
||||
scenario(
|
||||
'O01-backtrack',
|
||||
'a static branch that fails one level down must fall back to a sibling param branch',
|
||||
[
|
||||
['static', 'GET', '/a/b/c'],
|
||||
['param', 'GET', '/a/:x/d'],
|
||||
],
|
||||
get('/a/b/d', '/a/b/c', '/a/z/d', '/a/b/x'),
|
||||
),
|
||||
scenario(
|
||||
'O02-backtrack-deep',
|
||||
'the static branch fails at depth 5 (and a param branch at depth 3), after walking four or two levels',
|
||||
[
|
||||
['static', 'GET', '/p/q/r/s/t'],
|
||||
['paramDepth2', 'GET', '/p/:x/r/s/u'],
|
||||
['paramDepth3', 'GET', '/p/q/:y/s/v'],
|
||||
],
|
||||
get('/p/q/r/s/u', '/p/q/r/s/t', '/p/z/r/s/u', '/p/q/r/s/v', '/p/q/z/s/v', '/p/q/r/s/w'),
|
||||
),
|
||||
scenario(
|
||||
'O03-backtrack-constrained',
|
||||
'the fallback branch is a constrained param',
|
||||
[
|
||||
['static', 'GET', '/k/1/c'],
|
||||
['digits', 'GET', '/k/:n(\\d+)/d'],
|
||||
],
|
||||
get('/k/1/d', '/k/1/c', '/k/2/d', '/k/x/d'),
|
||||
),
|
||||
scenario(
|
||||
'O04-cross-pattern-allow',
|
||||
'Allow is the union of methods across different patterns matching the same path',
|
||||
[
|
||||
['getParam', 'GET', '/a/:id'],
|
||||
['postStatic', 'POST', '/a/b'],
|
||||
],
|
||||
[
|
||||
['PUT', '/a/b'],
|
||||
['OPTIONS', '/a/b'],
|
||||
['PUT', '/a/x'],
|
||||
['HEAD', '/a/b'],
|
||||
['GET', '/a/b'],
|
||||
['POST', '/a/x'],
|
||||
],
|
||||
),
|
||||
scenario(
|
||||
'O05-cross-pattern-allow-catch-all',
|
||||
'the same, with a catch-all contributing a method',
|
||||
[
|
||||
['getParam', 'GET', '/a/:id'],
|
||||
['postStatic', 'POST', '/a/b'],
|
||||
['deleteRest', 'DELETE', '/a/:rest*'],
|
||||
],
|
||||
[
|
||||
['PUT', '/a/b'],
|
||||
['OPTIONS', '/a/b'],
|
||||
['PUT', '/a/x'],
|
||||
['HEAD', '/a/b'],
|
||||
['PUT', '/a/x/y'],
|
||||
['DELETE', '/a'],
|
||||
],
|
||||
),
|
||||
scenario(
|
||||
'O06-encoded-slash-plain',
|
||||
'an encoded slash inside one segment, plain param',
|
||||
[['userId', 'GET', '/users/:id']],
|
||||
get('/users/a%2Fb', '/users/a%2fb', '/users/%2F', '/users/a/b'),
|
||||
),
|
||||
scenario(
|
||||
'O07-encoded-slash-constrained',
|
||||
'an encoded slash against a word constraint and a non-space constraint (a / cannot appear inside a constraint: the pattern splits there)',
|
||||
[
|
||||
['word', 'GET', '/c/:id(\\w+)'],
|
||||
['nonSpace', 'GET', '/d/:id(\\S+)'],
|
||||
],
|
||||
get('/c/a%2Fb', '/c/ab', '/d/a%2Fb', '/d/a%2fb', '/d/%2F', '/d/a/b'),
|
||||
),
|
||||
scenario(
|
||||
'O08-zero-segment-catch-all',
|
||||
'a catch-all with no exact sibling route',
|
||||
[['rest', 'GET', '/files/:rest*']],
|
||||
[...get('/files', '/files/', '/files/a', '/filesx'), ['HEAD', '/files'], ['OPTIONS', '/files']],
|
||||
),
|
||||
scenario('O09-root-catch-all', 'a root catch-all alone', [['rest', 'GET', '/:rest*']], get('/', '/a', '/a/b/')),
|
||||
];
|
||||
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* The frozen matcher differential, free of vitest and of any runtime's file API, so the same
|
||||
* comparison runs on Node (vitest), Deno, Bun and workerd. Each runtime passes a loader that
|
||||
* returns a frozen file's parsed JSON.
|
||||
*
|
||||
* It compares exactly what `matcher.test.ts` compares — regenerated inputs, oracle outputs and live
|
||||
* outputs against the frozen capture, key and array order included — and returns mismatches instead
|
||||
* of throwing, so a runner can report them all.
|
||||
*/
|
||||
import * as live from '../../src/http/router';
|
||||
import { matchWsRoute as liveMatchWsRoute } from '../../src/http/ws-core';
|
||||
import type { WsRouteDef } from '../../src/http/types';
|
||||
import * as oracle from './oracle';
|
||||
import { runScenario, type MatcherImpl, type Outcome, type Scenario } from './matcher';
|
||||
import { HAND_SCENARIOS, OWNER_SCENARIOS } from './cases';
|
||||
import { generateScenarios, generateScenariosV2, GENERATOR_SEED } from './generator';
|
||||
|
||||
export type FrozenLoader = (name: string) => unknown | Promise<unknown>;
|
||||
|
||||
interface CapturedScenario extends Scenario {
|
||||
outcomes: Outcome[];
|
||||
}
|
||||
|
||||
// ── WebSocket matcher cases (first registered wins) ─────────────────────────────────────────────
|
||||
|
||||
type WsDecl = WsRouteDef & { id: string };
|
||||
export type WsMatcher = (
|
||||
routes: WsRouteDef[],
|
||||
path: string,
|
||||
) => { def: WsRouteDef; params: Record<string, string> | undefined } | undefined;
|
||||
|
||||
const ws = (id: string, pattern: string): WsDecl => ({ id, pattern, open: async () => (async function* () {})() });
|
||||
const overlap = [ws('param', '/ws/:id'), ws('static', '/ws/static'), ws('rest', '/ws/:rest*')];
|
||||
const WS_SCENARIOS = [
|
||||
{ id: 'W01-overlap', routes: overlap },
|
||||
{ id: 'W02-overlap-reversed', routes: [...overlap].reverse() },
|
||||
{ id: 'W03-catch-all-first', routes: [ws('rest', '/w/:rest*'), ws('exact', '/w')] },
|
||||
];
|
||||
// Fed already normalized, as both upgrade adapters do since #117.
|
||||
const WS_PATHS = ['/ws/static', '/ws/x', '/ws/a%20b', '/ws', '/ws/x/y', '/w', '/w/a%2Fb/c', '/nope'];
|
||||
|
||||
export function runWsMatcher(matchWs: WsMatcher) {
|
||||
return WS_SCENARIOS.map(({ id, routes }) => ({
|
||||
id,
|
||||
declarations: routes.map((route) => ({ id: route.id, pattern: route.pattern })),
|
||||
outcomes: WS_PATHS.map((path) => {
|
||||
const hit = matchWs(routes, path);
|
||||
return { path, route: hit ? { id: (hit.def as WsDecl).id, params: hit.params } : null };
|
||||
}),
|
||||
}));
|
||||
}
|
||||
|
||||
export const LIVE_WS_MATCHER: WsMatcher = liveMatchWsRoute;
|
||||
export const ORACLE_WS_MATCHER: WsMatcher = oracle.matchWsRoute;
|
||||
|
||||
// ── the comparison ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
const same = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b);
|
||||
const plain = (value: unknown): unknown => JSON.parse(JSON.stringify(value));
|
||||
|
||||
export interface DifferentialReport {
|
||||
sets: Array<{ name: string; scenarios: number; requests: number }>;
|
||||
mismatches: string[];
|
||||
}
|
||||
|
||||
const SETS: Array<{ name: string; scenarios: () => Scenario[]; inFile: (data: any) => CapturedScenario[] }> = [
|
||||
{ name: 'matcher-hand', scenarios: () => HAND_SCENARIOS, inFile: (data) => data },
|
||||
{ name: 'matcher-owner', scenarios: () => OWNER_SCENARIOS, inFile: (data) => data },
|
||||
{ name: 'matcher-generated', scenarios: () => generateScenarios(GENERATOR_SEED), inFile: (data) => data.scenarios },
|
||||
{
|
||||
name: 'matcher-generated-v2',
|
||||
scenarios: () => generateScenariosV2(GENERATOR_SEED),
|
||||
inFile: (data) => data.scenarios,
|
||||
},
|
||||
];
|
||||
|
||||
function compareSet(name: string, scenarios: Scenario[], expected: CapturedScenario[], mismatches: string[]): number {
|
||||
const byId = new Map(expected.map((scenario) => [scenario.id, scenario]));
|
||||
if (
|
||||
!same(
|
||||
expected.map((s) => s.id),
|
||||
scenarios.map((s) => s.id),
|
||||
)
|
||||
)
|
||||
mismatches.push(`${name}: scenario ids differ from the frozen file`);
|
||||
|
||||
let requests = 0;
|
||||
for (const scenario of scenarios) {
|
||||
const frozen = byId.get(scenario.id);
|
||||
if (!frozen) continue;
|
||||
const { outcomes, ...inputs } = frozen;
|
||||
requests += scenario.requests.length;
|
||||
if (!same(plain(scenario), inputs)) mismatches.push(`${name} ${scenario.id}: inputs`);
|
||||
const impls: Array<[string, MatcherImpl]> = [
|
||||
['oracle', oracle],
|
||||
['live', live],
|
||||
];
|
||||
for (const [label, impl] of impls)
|
||||
if (!same(plain(runScenario(impl, scenario)), outcomes)) mismatches.push(`${name} ${scenario.id}: ${label}`);
|
||||
}
|
||||
return requests;
|
||||
}
|
||||
|
||||
export async function runDifferential(load: FrozenLoader): Promise<DifferentialReport> {
|
||||
const mismatches: string[] = [];
|
||||
const sets: DifferentialReport['sets'] = [];
|
||||
|
||||
for (const set of SETS) {
|
||||
const scenarios = set.scenarios();
|
||||
const file = (await load(set.name)) as { data: unknown };
|
||||
const requests = compareSet(set.name, scenarios, set.inFile(file.data), mismatches);
|
||||
sets.push({ name: set.name, scenarios: scenarios.length, requests });
|
||||
}
|
||||
|
||||
const wsFile = (await load('matcher-ws')) as { data: unknown };
|
||||
for (const [label, matcher] of [
|
||||
['oracle', ORACLE_WS_MATCHER],
|
||||
['live', LIVE_WS_MATCHER],
|
||||
] as const)
|
||||
if (!same(plain(runWsMatcher(matcher)), wsFile.data)) mismatches.push(`matcher-ws: ${label}`);
|
||||
sets.push({ name: 'matcher-ws', scenarios: WS_SCENARIOS.length, requests: WS_SCENARIOS.length * WS_PATHS.length });
|
||||
|
||||
return { sets, mismatches };
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* Reads the frozen router-parity baseline. Read README.md in this directory before touching it.
|
||||
*
|
||||
* Every expected output under `frozen/` was captured from the pinned revision below, by running
|
||||
* these tests with `ROUTER_PARITY_CAPTURE=1` while the file did not exist yet. Nothing here ever
|
||||
* overwrites a file: a capture only fills a gap, and `vitest -u` is refused outright, because a
|
||||
* baseline that a flag can rewrite is a baseline a new implementation can quietly move.
|
||||
*/
|
||||
import { existsSync, readFileSync, writeFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import { expect } from 'vitest';
|
||||
|
||||
/** The `@green-tea/core` commit every frozen output was captured from (develop after #117 and #122). */
|
||||
export const PINNED_REVISION = 'ed47836c9820c47bf4ed5e902d91e019abdb110a';
|
||||
|
||||
const FROZEN_DIR = join(__dirname, 'frozen');
|
||||
|
||||
interface FrozenFile<T> {
|
||||
revision: string;
|
||||
data: T;
|
||||
}
|
||||
|
||||
function refuseSnapshotUpdate(name: string): void {
|
||||
// `_updateSnapshot` is vitest's private record of `-u` ('all') versus a normal run ('new'/'none').
|
||||
const state = expect.getState().snapshotState as unknown as { _updateSnapshot?: string } | undefined;
|
||||
if (state?._updateSnapshot !== 'all') return;
|
||||
|
||||
throw new Error(
|
||||
`router-parity: '${name}' is a frozen baseline captured at ${PINNED_REVISION} and is never ` +
|
||||
'rewritten by `vitest -u`. A behaviour difference against it is a compatibility failure. ' +
|
||||
'If the change is deliberate, it needs its own maintainer approval and a reviewed edit of ' +
|
||||
`test/router-parity/frozen/${name}.json — see test/router-parity/README.md.`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the frozen data for `name`. When the file is missing it fails, unless
|
||||
* `ROUTER_PARITY_CAPTURE=1` is set, in which case `capture()` runs against the current code and its
|
||||
* result is written. An existing file is never replaced.
|
||||
*/
|
||||
export async function frozen<T>(name: string, capture: () => T | Promise<T>): Promise<T> {
|
||||
refuseSnapshotUpdate(name);
|
||||
const file = join(FROZEN_DIR, `${name}.json`);
|
||||
|
||||
if (!existsSync(file)) {
|
||||
if (process.env.ROUTER_PARITY_CAPTURE !== '1')
|
||||
throw new Error(
|
||||
`router-parity: frozen file ${file} is missing — the baseline cannot be regenerated by a test run`,
|
||||
);
|
||||
const data = JSON.parse(JSON.stringify(await capture())) as T;
|
||||
const record: FrozenFile<T> = { revision: PINNED_REVISION, data };
|
||||
writeFileSync(file, `${JSON.stringify(record, null, 2)}\n`);
|
||||
return data;
|
||||
}
|
||||
|
||||
const record = JSON.parse(readFileSync(file, 'utf8')) as FrozenFile<T>;
|
||||
expect(record.revision, `${name}.json was captured from a different revision`).toBe(PINNED_REVISION);
|
||||
return record.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Structural equality that also holds array order and object key order. `toEqual` alone ignores key
|
||||
* order, which is observable in `openapi().paths` and in serialized introspection output.
|
||||
*/
|
||||
export function expectFrozenEqual(actual: unknown, expected: unknown, label: string): void {
|
||||
const plain = JSON.parse(JSON.stringify(actual));
|
||||
expect(plain, label).toEqual(expected);
|
||||
expect(JSON.stringify(plain), `${label} (key and array order)`).toBe(JSON.stringify(expected));
|
||||
}
|
||||
@@ -0,0 +1,597 @@
|
||||
{
|
||||
"revision": "ed47836c9820c47bf4ed5e902d91e019abdb110a",
|
||||
"data": [
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/a/b",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"aB\",\"params\":{}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/a/x",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"aId\",\"params\":{\"id\":\"x\"}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/a/x/y",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"aRest\",\"params\":{\"rest\":\"x/y\"}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/a",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"aRest\",\"params\":{\"rest\":\"\"}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/users/42",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"usersId\",\"params\":{\"id\":\"42\"}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/users/alice",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"usersValue\",\"params\":{\"value\":\"alice\"}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/users/a%20b",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"usersValue\",\"params\":{\"value\":\"a b\"}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/n/42",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"nNum\",\"params\":{\"num\":\"42\"}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/n/ff",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"nCode\",\"params\":{\"code\":\"ff\"}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/files",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"files\",\"params\":{}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/files/",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"files\",\"params\":{}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/files/a%2Fb",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"filesRest\",\"params\":{\"rest\":\"a/b\"}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/m",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"mGet\",\"params\":{}}"
|
||||
},
|
||||
{
|
||||
"method": "HEAD",
|
||||
"raw": "/m",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": ""
|
||||
},
|
||||
{
|
||||
"method": "OPTIONS",
|
||||
"raw": "/m",
|
||||
"status": 204,
|
||||
"headers": {
|
||||
"allow": "GET, HEAD, POST, OPTIONS",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": ""
|
||||
},
|
||||
{
|
||||
"method": "PUT",
|
||||
"raw": "/m",
|
||||
"status": 405,
|
||||
"headers": {
|
||||
"allow": "GET, HEAD, POST, OPTIONS",
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"error\":\"Method Not Allowed\"}"
|
||||
},
|
||||
{
|
||||
"method": "DELETE",
|
||||
"raw": "/m",
|
||||
"status": 405,
|
||||
"headers": {
|
||||
"allow": "GET, HEAD, POST, OPTIONS",
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"error\":\"Method Not Allowed\"}"
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"raw": "/m",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"mPost\",\"params\":{}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/h",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"hGet\",\"params\":{}}"
|
||||
},
|
||||
{
|
||||
"method": "HEAD",
|
||||
"raw": "/h",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": ""
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/stream",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"cache-control": "no-cache",
|
||||
"content-type": "text/event-stream",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "data: {\"id\":\"stream\"}\n\n"
|
||||
},
|
||||
{
|
||||
"method": "HEAD",
|
||||
"raw": "/stream",
|
||||
"status": 405,
|
||||
"headers": {
|
||||
"allow": "GET, OPTIONS",
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": ""
|
||||
},
|
||||
{
|
||||
"method": "OPTIONS",
|
||||
"raw": "/stream",
|
||||
"status": 204,
|
||||
"headers": {
|
||||
"allow": "GET, OPTIONS",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": ""
|
||||
},
|
||||
{
|
||||
"method": "HEAD",
|
||||
"raw": "/s/live",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": ""
|
||||
},
|
||||
{
|
||||
"method": "HEAD",
|
||||
"raw": "/s/x",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": ""
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/absent",
|
||||
"status": 404,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"error\":\"Not Found\"}"
|
||||
},
|
||||
{
|
||||
"method": "HEAD",
|
||||
"raw": "/absent",
|
||||
"status": 404,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": ""
|
||||
},
|
||||
{
|
||||
"method": "OPTIONS",
|
||||
"raw": "/absent",
|
||||
"status": 404,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"error\":\"Not Found\"}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/users/%E0%A4%A",
|
||||
"status": 400,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"error\":\"Bad Request\"}"
|
||||
},
|
||||
{
|
||||
"method": "HEAD",
|
||||
"raw": "/users/%E0%A4%A",
|
||||
"status": 400,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": ""
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/a//b",
|
||||
"status": 400,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"error\":\"Bad Request\"}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/Case",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"caseUpper\",\"params\":{}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/case",
|
||||
"status": 404,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"error\":\"Not Found\"}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/caf%C3%A9",
|
||||
"status": 404,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"error\":\"Not Found\"}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/u/caf%C3%A9",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"uName\",\"params\":{\"name\":\"café\"}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/public/../admin",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"admin\",\"params\":{}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/public/%2e%2e/admin",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"admin\",\"params\":{}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/public/..%2fadmin",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"publicFile\",\"params\":{\"file\":\"../admin\"}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/admin/",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"admin\",\"params\":{}}"
|
||||
},
|
||||
{
|
||||
"method": "OPTIONS",
|
||||
"raw": "/r",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"rOptions\",\"params\":{}}"
|
||||
},
|
||||
{
|
||||
"method": "HEAD",
|
||||
"raw": "/r",
|
||||
"status": 405,
|
||||
"headers": {
|
||||
"allow": "PUT, PATCH, DELETE, OPTIONS",
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": ""
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/r",
|
||||
"status": 405,
|
||||
"headers": {
|
||||
"allow": "PUT, PATCH, DELETE, OPTIONS",
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"error\":\"Method Not Allowed\"}"
|
||||
},
|
||||
{
|
||||
"method": "PURGE",
|
||||
"raw": "/r",
|
||||
"status": 405,
|
||||
"headers": {
|
||||
"allow": "PUT, PATCH, DELETE, OPTIONS",
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"error\":\"Method Not Allowed\"}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"root\",\"params\":{}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/?q=1",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"root\",\"params\":{}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,632 @@
|
||||
{
|
||||
"revision": "ed47836c9820c47bf4ed5e902d91e019abdb110a",
|
||||
"data": [
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/a/b",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"aB\",\"params\":{}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/a/x",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"aId\",\"params\":{\"id\":\"x\"}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/a/x/y",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"aRest\",\"params\":{\"rest\":\"x/y\"}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/a",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"aRest\",\"params\":{\"rest\":\"\"}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/users/42",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"usersId\",\"params\":{\"id\":\"42\"}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/users/alice",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"usersValue\",\"params\":{\"value\":\"alice\"}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/users/a%20b",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"usersValue\",\"params\":{\"value\":\"a b\"}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/n/42",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"nNum\",\"params\":{\"num\":\"42\"}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/n/ff",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"nCode\",\"params\":{\"code\":\"ff\"}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/files",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"files\",\"params\":{}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/files/",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"files\",\"params\":{}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/files/a%2Fb",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"filesRest\",\"params\":{\"rest\":\"a/b\"}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/m",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"mGet\",\"params\":{}}"
|
||||
},
|
||||
{
|
||||
"method": "HEAD",
|
||||
"raw": "/m",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": ""
|
||||
},
|
||||
{
|
||||
"method": "OPTIONS",
|
||||
"raw": "/m",
|
||||
"status": 204,
|
||||
"headers": {
|
||||
"allow": "GET, HEAD, POST, OPTIONS",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": ""
|
||||
},
|
||||
{
|
||||
"method": "PUT",
|
||||
"raw": "/m",
|
||||
"status": 405,
|
||||
"headers": {
|
||||
"allow": "GET, HEAD, POST, OPTIONS",
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"error\":\"Method Not Allowed\"}"
|
||||
},
|
||||
{
|
||||
"method": "DELETE",
|
||||
"raw": "/m",
|
||||
"status": 405,
|
||||
"headers": {
|
||||
"allow": "GET, HEAD, POST, OPTIONS",
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"error\":\"Method Not Allowed\"}"
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"raw": "/m",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"mPost\",\"params\":{}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/h",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"hGet\",\"params\":{}}"
|
||||
},
|
||||
{
|
||||
"method": "HEAD",
|
||||
"raw": "/h",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": ""
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/stream",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"cache-control": "no-cache",
|
||||
"content-type": "text/event-stream",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "data: {\"id\":\"stream\"}\n\n"
|
||||
},
|
||||
{
|
||||
"method": "HEAD",
|
||||
"raw": "/stream",
|
||||
"status": 405,
|
||||
"headers": {
|
||||
"allow": "GET, OPTIONS",
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": ""
|
||||
},
|
||||
{
|
||||
"method": "OPTIONS",
|
||||
"raw": "/stream",
|
||||
"status": 204,
|
||||
"headers": {
|
||||
"allow": "GET, OPTIONS",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": ""
|
||||
},
|
||||
{
|
||||
"method": "HEAD",
|
||||
"raw": "/s/live",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": ""
|
||||
},
|
||||
{
|
||||
"method": "HEAD",
|
||||
"raw": "/s/x",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": ""
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/absent",
|
||||
"status": 404,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"error\":\"Not Found\"}"
|
||||
},
|
||||
{
|
||||
"method": "HEAD",
|
||||
"raw": "/absent",
|
||||
"status": 404,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": ""
|
||||
},
|
||||
{
|
||||
"method": "OPTIONS",
|
||||
"raw": "/absent",
|
||||
"status": 404,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"error\":\"Not Found\"}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/users/%E0%A4%A",
|
||||
"status": 400,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"error\":\"Bad Request\"}"
|
||||
},
|
||||
{
|
||||
"method": "HEAD",
|
||||
"raw": "/users/%E0%A4%A",
|
||||
"status": 400,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": ""
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/a//b",
|
||||
"status": 400,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"error\":\"Bad Request\"}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/Case",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"caseUpper\",\"params\":{}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/case",
|
||||
"status": 404,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"error\":\"Not Found\"}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/caf%C3%A9",
|
||||
"status": 404,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"error\":\"Not Found\"}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/u/caf%C3%A9",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"uName\",\"params\":{\"name\":\"café\"}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/public/../admin",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"admin\",\"params\":{}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/public/%2e%2e/admin",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"admin\",\"params\":{}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/public/..%2fadmin",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"publicFile\",\"params\":{\"file\":\"../admin\"}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/admin/",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"admin\",\"params\":{}}"
|
||||
},
|
||||
{
|
||||
"method": "OPTIONS",
|
||||
"raw": "/r",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"rOptions\",\"params\":{}}"
|
||||
},
|
||||
{
|
||||
"method": "HEAD",
|
||||
"raw": "/r",
|
||||
"status": 405,
|
||||
"headers": {
|
||||
"allow": "PUT, PATCH, DELETE, OPTIONS",
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": ""
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/r",
|
||||
"status": 405,
|
||||
"headers": {
|
||||
"allow": "PUT, PATCH, DELETE, OPTIONS",
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"error\":\"Method Not Allowed\"}"
|
||||
},
|
||||
{
|
||||
"method": "PURGE",
|
||||
"raw": "/r",
|
||||
"status": 405,
|
||||
"headers": {
|
||||
"allow": "PUT, PATCH, DELETE, OPTIONS",
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"error\":\"Method Not Allowed\"}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"root\",\"params\":{}}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"raw": "/?q=1",
|
||||
"status": 200,
|
||||
"headers": {
|
||||
"content-type": "application/json",
|
||||
"referrer-policy": "no-referrer",
|
||||
"transfer-encoding": "chunked",
|
||||
"x-content-type-options": "nosniff",
|
||||
"x-dns-prefetch-control": "off",
|
||||
"x-frame-options": "SAMEORIGIN"
|
||||
},
|
||||
"body": "{\"id\":\"root\",\"params\":{}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
{
|
||||
"revision": "ed47836c9820c47bf4ed5e902d91e019abdb110a",
|
||||
"data": [
|
||||
{
|
||||
"id": "B01-duplicate-param",
|
||||
"declarations": [
|
||||
"@Get('/x/:id/:id')"
|
||||
],
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "invalid route pattern '/x/:id/:id': duplicate parameter 'id'"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "B02-nonfinal-catch-all",
|
||||
"declarations": [
|
||||
"@Get('/x/:rest*/tail')"
|
||||
],
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "invalid route pattern '/x/:rest*/tail': catch-all must be the final segment"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "B03-nested-quantifier",
|
||||
"declarations": [
|
||||
"@Get('/x/:id((a+)+)')"
|
||||
],
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "unsafe route constraint: unsupported expression '(a+)+'"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "B04-alternation",
|
||||
"declarations": [
|
||||
"@Get('/x/:id(a|b)')"
|
||||
],
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "unsafe route constraint: unsupported expression 'a|b'"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "B05-adjacent-unbounded",
|
||||
"declarations": [
|
||||
"@Get('/x/:id(\\d+\\w+)')"
|
||||
],
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "unsafe route constraint: adjacent unbounded quantifiers in '\\d+\\w+'"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "B06-inverted-quantifier",
|
||||
"declarations": [
|
||||
"@Get('/x/:id(\\d{5,2})')"
|
||||
],
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "unsafe route constraint: invalid quantifier '{5,2}'"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "B07-invalid-param-name",
|
||||
"declarations": [
|
||||
"@Get('/x/:1x')"
|
||||
],
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "invalid route pattern '/x/:1x': invalid parameter name '1x'"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "B08-malformed-constraint",
|
||||
"declarations": [
|
||||
"@Get('/x/:id(\\d+')"
|
||||
],
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "invalid route pattern '/x/:id(\\d+': malformed constraint"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "B09-same-shape-plain",
|
||||
"declarations": [
|
||||
"@Get('/users/:id')",
|
||||
"@Get('/users/:name')"
|
||||
],
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "ambiguous route GET /users/:name at ParityBoot.h1 conflicts with GET /users/:id at ParityBoot.h0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "B10-same-shape-constrained",
|
||||
"declarations": [
|
||||
"@Get('/c/:a(\\d+)')",
|
||||
"@Get('/c/:b(\\d+)')"
|
||||
],
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "ambiguous route GET /c/:b(\\d+) at ParityBoot.h1 conflicts with GET /c/:a(\\d+) at ParityBoot.h0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "B11-trailing-slash-twin",
|
||||
"declarations": [
|
||||
"@Get('/t')",
|
||||
"@Get('/t/')"
|
||||
],
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "ambiguous route GET /t/ at ParityBoot.h1 conflicts with GET /t at ParityBoot.h0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "B12-get-and-ws-same-path",
|
||||
"declarations": [
|
||||
"@Get('/live')",
|
||||
"@Ws('/live')"
|
||||
],
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "ambiguous route GET /live at ParityBoot.h1 conflicts with GET /live at ParityBoot.h0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "B13-get-and-sse-same-path",
|
||||
"declarations": [
|
||||
"@Get('/feed')",
|
||||
"@Sse('/feed')"
|
||||
],
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "ambiguous route GET /feed at ParityBoot.h1 conflicts with GET /feed at ParityBoot.h0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "B14-ws-same-shape",
|
||||
"declarations": [
|
||||
"@Ws('/w/:a')",
|
||||
"@Ws('/w/:b')"
|
||||
],
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "ambiguous route GET /w/:b at ParityBoot.h1 conflicts with GET /w/:a at ParityBoot.h0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "B15-ok-same-shape-different-methods",
|
||||
"declarations": [
|
||||
"@Get('/users/:id')",
|
||||
"@Post('/users/:name')"
|
||||
],
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"id": "B16-ok-different-constraints",
|
||||
"declarations": [
|
||||
"@Get('/c/:a(\\d+)')",
|
||||
"@Get('/c/:b([a-z]+)')"
|
||||
],
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"id": "B17-ok-static-and-param",
|
||||
"declarations": [
|
||||
"@Get('/users/me')",
|
||||
"@Get('/users/:id')"
|
||||
],
|
||||
"ok": true
|
||||
},
|
||||
{
|
||||
"id": "B18-ok-exact-and-catch-all",
|
||||
"declarations": [
|
||||
"@Get('/f')",
|
||||
"@Get('/f/:rest*')"
|
||||
],
|
||||
"ok": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
{
|
||||
"revision": "ed47836c9820c47bf4ed5e902d91e019abdb110a",
|
||||
"data": [
|
||||
{
|
||||
"id": "M01-two-teapots-same-route",
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "mesh: ambiguous remote route 'GET /api/dup/ping' from <teapot2> conflicts with 'GET /api/dup/ping' from <teapot1> — load balancing across teapots is not implemented yet, so green-tea will not choose one for you. Export it from a single teapot."
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "M02-two-teapots-same-shape",
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "mesh: ambiguous remote route 'GET /api/shape/:name' from <teapot2> conflicts with 'GET /api/shape/:id' from <teapot1> — load balancing across teapots is not implemented yet, so green-tea will not choose one for you. Export it from a single teapot."
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "M03-local-same-shape-wins",
|
||||
"ok": true,
|
||||
"warnings": [
|
||||
"mesh: route 'GET /api/dup/ping' is exported by teapot <teapot1> but also declared locally — the local route takes precedence and the remote one will not be reached. Remove one if that is not what you meant."
|
||||
],
|
||||
"responses": [
|
||||
{
|
||||
"path": "/api/dup/ping",
|
||||
"status": 200,
|
||||
"body": "{\"from\":\"local\"}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "M04-unique-remote",
|
||||
"ok": true,
|
||||
"warnings": [],
|
||||
"responses": [
|
||||
{
|
||||
"path": "/api/dup/ping",
|
||||
"status": 200,
|
||||
"body": "{\"from\":\"teapot\"}"
|
||||
},
|
||||
{
|
||||
"path": "/c/ok",
|
||||
"status": 200,
|
||||
"body": "{\"from\":\"teacup\"}"
|
||||
},
|
||||
{
|
||||
"path": "/api/nope",
|
||||
"status": 404,
|
||||
"body": "{\"error\":\"Not Found\"}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "M05-remote-static-outranks-local-param",
|
||||
"ok": true,
|
||||
"warnings": [],
|
||||
"responses": [
|
||||
{
|
||||
"path": "/api/dup/ping",
|
||||
"status": 200,
|
||||
"body": "{\"from\":\"teapot\"}"
|
||||
},
|
||||
{
|
||||
"path": "/api/dup/x",
|
||||
"status": 200,
|
||||
"body": "{\"from\":\"local\",\"p\":{\"anything\":\"x\"}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
{
|
||||
"revision": "ed47836c9820c47bf4ed5e902d91e019abdb110a",
|
||||
"data": [
|
||||
{
|
||||
"pattern": "/",
|
||||
"shape": ""
|
||||
},
|
||||
{
|
||||
"pattern": "/users/:id",
|
||||
"shape": "s:users/p"
|
||||
},
|
||||
{
|
||||
"pattern": "/users/:id(\\d+)",
|
||||
"shape": "s:users/r:\\d+"
|
||||
},
|
||||
{
|
||||
"pattern": "/files/:rest*",
|
||||
"shape": "s:files/c"
|
||||
},
|
||||
{
|
||||
"pattern": "/:rest*",
|
||||
"shape": "c"
|
||||
},
|
||||
{
|
||||
"pattern": "/t/",
|
||||
"shape": "s:t"
|
||||
},
|
||||
{
|
||||
"pattern": "/café",
|
||||
"shape": "s:café"
|
||||
},
|
||||
{
|
||||
"pattern": "/build/:version(\\d{2}\\.\\d{1,2})",
|
||||
"shape": "s:build/r:\\d{2}\\.\\d{1,2}"
|
||||
},
|
||||
{
|
||||
"pattern": "/x/:id/:id",
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "invalid route pattern '/x/:id/:id': duplicate parameter 'id'"
|
||||
}
|
||||
},
|
||||
{
|
||||
"pattern": "/x/:id/:rest*/tail",
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "invalid route pattern '/x/:id/:rest*/tail': catch-all must be the final segment"
|
||||
}
|
||||
},
|
||||
{
|
||||
"pattern": "/x/:rest*/:rest*",
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "invalid route pattern '/x/:rest*/:rest*': catch-all must be the final segment"
|
||||
}
|
||||
},
|
||||
{
|
||||
"pattern": "/x/:",
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "invalid route pattern '/x/:': invalid parameter name ''"
|
||||
}
|
||||
},
|
||||
{
|
||||
"pattern": "/x/:1x",
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "invalid route pattern '/x/:1x': invalid parameter name '1x'"
|
||||
}
|
||||
},
|
||||
{
|
||||
"pattern": "/x//y",
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "invalid route pattern '/x//y': repeated slash"
|
||||
}
|
||||
},
|
||||
{
|
||||
"pattern": "x",
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "invalid route pattern 'x': pattern must start with '/'"
|
||||
}
|
||||
},
|
||||
{
|
||||
"pattern": "",
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "invalid route pattern '': pattern must start with '/'"
|
||||
}
|
||||
},
|
||||
{
|
||||
"pattern": "/x/:id((a+)+)",
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "unsafe route constraint: unsupported expression '(a+)+'"
|
||||
}
|
||||
},
|
||||
{
|
||||
"pattern": "/x/:id((?=a)a)",
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "unsafe route constraint: unsupported expression '(?=a)a'"
|
||||
}
|
||||
},
|
||||
{
|
||||
"pattern": "/x/:id(\\1)",
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "unsafe route constraint: unsupported expression '\\1'"
|
||||
}
|
||||
},
|
||||
{
|
||||
"pattern": "/x/:id(a|b)",
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "unsafe route constraint: unsupported expression 'a|b'"
|
||||
}
|
||||
},
|
||||
{
|
||||
"pattern": "/x/:id(\\d+\\w+)",
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "unsafe route constraint: adjacent unbounded quantifiers in '\\d+\\w+'"
|
||||
}
|
||||
},
|
||||
{
|
||||
"pattern": "/x/:id(\\d{5,2})",
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "unsafe route constraint: invalid quantifier '{5,2}'"
|
||||
}
|
||||
},
|
||||
{
|
||||
"pattern": "/x/:id(\\d{1,4096})",
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "unsafe route constraint: invalid quantifier '{1,4096}'"
|
||||
}
|
||||
},
|
||||
{
|
||||
"pattern": "/x/:id(\\d+",
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "invalid route pattern '/x/:id(\\d+': malformed constraint"
|
||||
}
|
||||
},
|
||||
{
|
||||
"pattern": "/x/:id()",
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "unsafe route constraint: expression must contain 1-128 characters"
|
||||
}
|
||||
},
|
||||
{
|
||||
"pattern": "/x/:id(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)",
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "unsafe route constraint: expression must contain 1-128 characters"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
{
|
||||
"revision": "ed47836c9820c47bf4ed5e902d91e019abdb110a",
|
||||
"data": [
|
||||
{
|
||||
"pattern": "/api/items/:id(\\d+)",
|
||||
"explain": {
|
||||
"pattern": "/api/items/:id(\\d+)",
|
||||
"method": "GET",
|
||||
"transport": "buffer",
|
||||
"chain": [
|
||||
{
|
||||
"name": "get",
|
||||
"kind": "handler",
|
||||
"origin": "module:IntrospectionModule",
|
||||
"needs": [],
|
||||
"provides": []
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"pattern": "/api/items",
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "no route: /api/items"
|
||||
}
|
||||
},
|
||||
{
|
||||
"pattern": "/api/live/:room",
|
||||
"explain": {
|
||||
"pattern": "/api/live/:room",
|
||||
"method": "GET",
|
||||
"transport": "ws",
|
||||
"chain": [
|
||||
{
|
||||
"name": "db",
|
||||
"kind": "provider",
|
||||
"origin": "module:IntrospectionModule",
|
||||
"needs": [],
|
||||
"provides": [
|
||||
"db"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "user",
|
||||
"kind": "step",
|
||||
"origin": "module:IntrospectionModule",
|
||||
"needs": [
|
||||
"db"
|
||||
],
|
||||
"provides": [
|
||||
"user"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "live",
|
||||
"kind": "handler",
|
||||
"origin": "module:IntrospectionModule",
|
||||
"needs": [
|
||||
"user"
|
||||
],
|
||||
"provides": []
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"pattern": "/api/items/:id/files/:path*",
|
||||
"explain": {
|
||||
"pattern": "/api/items/:id/files/:path*",
|
||||
"method": "GET",
|
||||
"transport": "buffer",
|
||||
"chain": [
|
||||
{
|
||||
"name": "files",
|
||||
"kind": "handler",
|
||||
"origin": "module:IntrospectionModule",
|
||||
"needs": [],
|
||||
"provides": []
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"pattern": "/api/missing",
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "no route: /api/missing"
|
||||
}
|
||||
},
|
||||
{
|
||||
"pattern": "/api/items/42",
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "no route: /api/items/42"
|
||||
}
|
||||
},
|
||||
{
|
||||
"pattern": "/api/items/",
|
||||
"explain": {
|
||||
"pattern": "/api/items/",
|
||||
"method": "GET",
|
||||
"transport": "buffer",
|
||||
"chain": [
|
||||
{
|
||||
"name": "db",
|
||||
"kind": "provider",
|
||||
"origin": "module:IntrospectionModule",
|
||||
"needs": [],
|
||||
"provides": [
|
||||
"db"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "user",
|
||||
"kind": "step",
|
||||
"origin": "module:IntrospectionModule",
|
||||
"needs": [
|
||||
"db"
|
||||
],
|
||||
"provides": [
|
||||
"user"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "list",
|
||||
"kind": "handler",
|
||||
"origin": "module:IntrospectionModule",
|
||||
"needs": [
|
||||
"user"
|
||||
],
|
||||
"provides": []
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
{
|
||||
"revision": "ed47836c9820c47bf4ed5e902d91e019abdb110a",
|
||||
"data": {
|
||||
"nodes": [
|
||||
{
|
||||
"name": "db",
|
||||
"kind": "provider",
|
||||
"origin": "module:IntrospectionModule",
|
||||
"needs": [],
|
||||
"provides": [
|
||||
"db"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "logger",
|
||||
"kind": "provider",
|
||||
"origin": "builtin",
|
||||
"needs": [],
|
||||
"provides": [
|
||||
"logger"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "rooms",
|
||||
"kind": "provider",
|
||||
"origin": "builtin",
|
||||
"needs": [],
|
||||
"provides": [
|
||||
"rooms"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "events",
|
||||
"kind": "provider",
|
||||
"origin": "builtin",
|
||||
"needs": [],
|
||||
"provides": [
|
||||
"events"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "user",
|
||||
"kind": "step",
|
||||
"origin": "module:IntrospectionModule",
|
||||
"needs": [
|
||||
"db"
|
||||
],
|
||||
"provides": [
|
||||
"user"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "audit",
|
||||
"kind": "step",
|
||||
"origin": "module:IntrospectionModule",
|
||||
"needs": [],
|
||||
"provides": [
|
||||
"audit"
|
||||
]
|
||||
}
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"pattern": "/api/items/:id/files/:path*",
|
||||
"method": "GET",
|
||||
"transport": "buffer",
|
||||
"chain": [
|
||||
"files"
|
||||
]
|
||||
},
|
||||
{
|
||||
"pattern": "/api/items/",
|
||||
"method": "GET",
|
||||
"transport": "buffer",
|
||||
"chain": [
|
||||
"db",
|
||||
"user",
|
||||
"list"
|
||||
]
|
||||
},
|
||||
{
|
||||
"pattern": "/api/items/",
|
||||
"method": "POST",
|
||||
"transport": "buffer",
|
||||
"chain": [
|
||||
"db",
|
||||
"user",
|
||||
"create"
|
||||
]
|
||||
},
|
||||
{
|
||||
"pattern": "/api/items/:id(\\d+)",
|
||||
"method": "GET",
|
||||
"transport": "buffer",
|
||||
"chain": [
|
||||
"get"
|
||||
]
|
||||
},
|
||||
{
|
||||
"pattern": "/api/items/:id(\\d+)",
|
||||
"method": "HEAD",
|
||||
"transport": "buffer",
|
||||
"chain": [
|
||||
"head"
|
||||
]
|
||||
},
|
||||
{
|
||||
"pattern": "/api/items/:id(\\d+)",
|
||||
"method": "OPTIONS",
|
||||
"transport": "buffer",
|
||||
"chain": [
|
||||
"options"
|
||||
]
|
||||
},
|
||||
{
|
||||
"pattern": "/api/items/:id(\\d+)",
|
||||
"method": "DELETE",
|
||||
"transport": "buffer",
|
||||
"chain": [
|
||||
"audit",
|
||||
"remove"
|
||||
]
|
||||
},
|
||||
{
|
||||
"pattern": "/api/items/:slug([a-z0-9-]+)",
|
||||
"method": "PUT",
|
||||
"transport": "buffer",
|
||||
"chain": [
|
||||
"upsert"
|
||||
]
|
||||
},
|
||||
{
|
||||
"pattern": "/api/items/search",
|
||||
"method": "GET",
|
||||
"transport": "buffer",
|
||||
"chain": [
|
||||
"search"
|
||||
]
|
||||
},
|
||||
{
|
||||
"pattern": "/api/events",
|
||||
"method": "GET",
|
||||
"transport": "sse",
|
||||
"chain": [
|
||||
"events"
|
||||
]
|
||||
},
|
||||
{
|
||||
"pattern": "/api/feed",
|
||||
"method": "GET",
|
||||
"transport": "negotiate",
|
||||
"chain": [
|
||||
"feed"
|
||||
]
|
||||
},
|
||||
{
|
||||
"pattern": "/api/live/:room",
|
||||
"method": "GET",
|
||||
"transport": "ws",
|
||||
"chain": [
|
||||
"db",
|
||||
"user",
|
||||
"live"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
{
|
||||
"revision": "ed47836c9820c47bf4ed5e902d91e019abdb110a",
|
||||
"data": {
|
||||
"before": {
|
||||
"graph": {
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "graph() unavailable until a mesh app has booted: a mesh graph is not knowable until its teapots are asked. Call `await app.ready()` first — it is a no-op on a non-mesh app"
|
||||
}
|
||||
},
|
||||
"explain": {
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "explain() unavailable until a mesh app has booted: a mesh graph is not knowable until its teapots are asked. Call `await app.ready()` first — it is a no-op on a non-mesh app"
|
||||
}
|
||||
},
|
||||
"openapi": {
|
||||
"value": {
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "Parity",
|
||||
"version": "1"
|
||||
},
|
||||
"paths": {
|
||||
"/api/local/who": {
|
||||
"get": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {}
|
||||
}
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/local/{id}": {
|
||||
"get": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {}
|
||||
}
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error"
|
||||
}
|
||||
},
|
||||
"parameters": [
|
||||
{
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"after": {
|
||||
"graph": {
|
||||
"nodes": [
|
||||
{
|
||||
"name": "logger",
|
||||
"kind": "provider",
|
||||
"origin": "builtin",
|
||||
"needs": [],
|
||||
"provides": [
|
||||
"logger"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "rooms",
|
||||
"kind": "provider",
|
||||
"origin": "builtin",
|
||||
"needs": [],
|
||||
"provides": [
|
||||
"rooms"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "events",
|
||||
"kind": "provider",
|
||||
"origin": "builtin",
|
||||
"needs": [],
|
||||
"provides": [
|
||||
"events"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "config",
|
||||
"kind": "step",
|
||||
"origin": "mesh:<teapot>",
|
||||
"needs": [],
|
||||
"provides": [
|
||||
"config"
|
||||
]
|
||||
}
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"pattern": "/api/local/who",
|
||||
"method": "GET",
|
||||
"transport": "buffer",
|
||||
"chain": [
|
||||
"config",
|
||||
"who"
|
||||
]
|
||||
},
|
||||
{
|
||||
"pattern": "/api/local/:id",
|
||||
"method": "GET",
|
||||
"transport": "buffer",
|
||||
"chain": [
|
||||
"byId"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"explain": [
|
||||
{
|
||||
"pattern": "/api/missing",
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "no route: /api/missing"
|
||||
}
|
||||
}
|
||||
],
|
||||
"explainLocal": {
|
||||
"pattern": "/api/local/who",
|
||||
"method": "GET",
|
||||
"transport": "buffer",
|
||||
"chain": [
|
||||
{
|
||||
"name": "config",
|
||||
"kind": "step",
|
||||
"origin": "mesh:<teapot>",
|
||||
"needs": [],
|
||||
"provides": [
|
||||
"config"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "who",
|
||||
"kind": "handler",
|
||||
"origin": "module:TeacupModule",
|
||||
"needs": [
|
||||
"config"
|
||||
],
|
||||
"provides": []
|
||||
}
|
||||
]
|
||||
},
|
||||
"explainRemote": {
|
||||
"error": {
|
||||
"name": "Error",
|
||||
"message": "no route: /api/remote/ping"
|
||||
}
|
||||
},
|
||||
"openapi": {
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "Parity",
|
||||
"version": "1"
|
||||
},
|
||||
"paths": {
|
||||
"/api/local/who": {
|
||||
"get": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {}
|
||||
}
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/local/{id}": {
|
||||
"get": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {}
|
||||
}
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error"
|
||||
}
|
||||
},
|
||||
"parameters": [
|
||||
{
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"lookup": {
|
||||
"path": "/api/remote/ping",
|
||||
"status": 200,
|
||||
"body": "{\"from\":\"teapot\"}"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
{
|
||||
"revision": "ed47836c9820c47bf4ed5e902d91e019abdb110a",
|
||||
"data": {
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "Parity",
|
||||
"version": "1"
|
||||
},
|
||||
"paths": {
|
||||
"/api/items/{id}/files/{path}": {
|
||||
"get": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {}
|
||||
}
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error"
|
||||
}
|
||||
},
|
||||
"parameters": [
|
||||
{
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "path",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/items": {
|
||||
"get": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {}
|
||||
}
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error"
|
||||
}
|
||||
}
|
||||
},
|
||||
"post": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {}
|
||||
}
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error"
|
||||
}
|
||||
},
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/items/{id}": {
|
||||
"get": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {}
|
||||
}
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error"
|
||||
}
|
||||
},
|
||||
"parameters": [
|
||||
{
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"pattern": "\\d+"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "expand",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"head": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {}
|
||||
}
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error"
|
||||
}
|
||||
},
|
||||
"parameters": [
|
||||
{
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"pattern": "\\d+"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"options": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {}
|
||||
}
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error"
|
||||
}
|
||||
},
|
||||
"parameters": [
|
||||
{
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"pattern": "\\d+"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"delete": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {}
|
||||
}
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error"
|
||||
}
|
||||
},
|
||||
"parameters": [
|
||||
{
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"pattern": "\\d+"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/items/{slug}": {
|
||||
"put": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {}
|
||||
}
|
||||
}
|
||||
},
|
||||
"422": {
|
||||
"description": "Validation failed"
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error"
|
||||
}
|
||||
},
|
||||
"parameters": [
|
||||
{
|
||||
"name": "slug",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"pattern": "[a-z0-9-]+"
|
||||
}
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/items/search": {
|
||||
"get": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {}
|
||||
}
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/events": {
|
||||
"get": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Event stream",
|
||||
"content": {
|
||||
"text/event-stream": {}
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/feed": {
|
||||
"get": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Stream",
|
||||
"content": {
|
||||
"application/x-ndjson": {}
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,214 @@
|
||||
{
|
||||
"revision": "ed47836c9820c47bf4ed5e902d91e019abdb110a",
|
||||
"data": [
|
||||
{
|
||||
"id": "W01-overlap",
|
||||
"declarations": [
|
||||
{
|
||||
"id": "param",
|
||||
"pattern": "/ws/:id"
|
||||
},
|
||||
{
|
||||
"id": "static",
|
||||
"pattern": "/ws/static"
|
||||
},
|
||||
{
|
||||
"id": "rest",
|
||||
"pattern": "/ws/:rest*"
|
||||
}
|
||||
],
|
||||
"outcomes": [
|
||||
{
|
||||
"path": "/ws/static",
|
||||
"route": {
|
||||
"id": "param",
|
||||
"params": {
|
||||
"id": "static"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "/ws/x",
|
||||
"route": {
|
||||
"id": "param",
|
||||
"params": {
|
||||
"id": "x"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "/ws/a%20b",
|
||||
"route": {
|
||||
"id": "param",
|
||||
"params": {
|
||||
"id": "a b"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "/ws",
|
||||
"route": {
|
||||
"id": "rest",
|
||||
"params": {
|
||||
"rest": ""
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "/ws/x/y",
|
||||
"route": {
|
||||
"id": "rest",
|
||||
"params": {
|
||||
"rest": "x/y"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "/w",
|
||||
"route": null
|
||||
},
|
||||
{
|
||||
"path": "/w/a%2Fb/c",
|
||||
"route": null
|
||||
},
|
||||
{
|
||||
"path": "/nope",
|
||||
"route": null
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "W02-overlap-reversed",
|
||||
"declarations": [
|
||||
{
|
||||
"id": "rest",
|
||||
"pattern": "/ws/:rest*"
|
||||
},
|
||||
{
|
||||
"id": "static",
|
||||
"pattern": "/ws/static"
|
||||
},
|
||||
{
|
||||
"id": "param",
|
||||
"pattern": "/ws/:id"
|
||||
}
|
||||
],
|
||||
"outcomes": [
|
||||
{
|
||||
"path": "/ws/static",
|
||||
"route": {
|
||||
"id": "rest",
|
||||
"params": {
|
||||
"rest": "static"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "/ws/x",
|
||||
"route": {
|
||||
"id": "rest",
|
||||
"params": {
|
||||
"rest": "x"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "/ws/a%20b",
|
||||
"route": {
|
||||
"id": "rest",
|
||||
"params": {
|
||||
"rest": "a b"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "/ws",
|
||||
"route": {
|
||||
"id": "rest",
|
||||
"params": {
|
||||
"rest": ""
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "/ws/x/y",
|
||||
"route": {
|
||||
"id": "rest",
|
||||
"params": {
|
||||
"rest": "x/y"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "/w",
|
||||
"route": null
|
||||
},
|
||||
{
|
||||
"path": "/w/a%2Fb/c",
|
||||
"route": null
|
||||
},
|
||||
{
|
||||
"path": "/nope",
|
||||
"route": null
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "W03-catch-all-first",
|
||||
"declarations": [
|
||||
{
|
||||
"id": "rest",
|
||||
"pattern": "/w/:rest*"
|
||||
},
|
||||
{
|
||||
"id": "exact",
|
||||
"pattern": "/w"
|
||||
}
|
||||
],
|
||||
"outcomes": [
|
||||
{
|
||||
"path": "/ws/static",
|
||||
"route": null
|
||||
},
|
||||
{
|
||||
"path": "/ws/x",
|
||||
"route": null
|
||||
},
|
||||
{
|
||||
"path": "/ws/a%20b",
|
||||
"route": null
|
||||
},
|
||||
{
|
||||
"path": "/ws",
|
||||
"route": null
|
||||
},
|
||||
{
|
||||
"path": "/ws/x/y",
|
||||
"route": null
|
||||
},
|
||||
{
|
||||
"path": "/w",
|
||||
"route": {
|
||||
"id": "rest",
|
||||
"params": {
|
||||
"rest": ""
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "/w/a%2Fb/c",
|
||||
"route": {
|
||||
"id": "rest",
|
||||
"params": {
|
||||
"rest": "a/b/c"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "/nope",
|
||||
"route": null
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
{
|
||||
"revision": "ed47836c9820c47bf4ed5e902d91e019abdb110a",
|
||||
"data": [
|
||||
{
|
||||
"adapter": "fetch",
|
||||
"method": "PUT",
|
||||
"path": "/ca/b",
|
||||
"status": 405,
|
||||
"allow": "GET, HEAD, POST, OPTIONS",
|
||||
"body": "{\"error\":\"Method Not Allowed\"}"
|
||||
},
|
||||
{
|
||||
"adapter": "fetch",
|
||||
"method": "OPTIONS",
|
||||
"path": "/ca/b",
|
||||
"status": 204,
|
||||
"allow": "GET, HEAD, POST, OPTIONS",
|
||||
"body": ""
|
||||
},
|
||||
{
|
||||
"adapter": "fetch",
|
||||
"method": "PUT",
|
||||
"path": "/ca/x",
|
||||
"status": 405,
|
||||
"allow": "GET, HEAD, OPTIONS",
|
||||
"body": "{\"error\":\"Method Not Allowed\"}"
|
||||
},
|
||||
{
|
||||
"adapter": "fetch",
|
||||
"method": "HEAD",
|
||||
"path": "/ca/b",
|
||||
"status": 200,
|
||||
"allow": null,
|
||||
"body": ""
|
||||
},
|
||||
{
|
||||
"adapter": "fetch",
|
||||
"method": "PUT",
|
||||
"path": "/ca/x/y",
|
||||
"status": 404,
|
||||
"allow": null,
|
||||
"body": "{\"error\":\"Not Found\"}"
|
||||
},
|
||||
{
|
||||
"adapter": "fetch",
|
||||
"method": "PUT",
|
||||
"path": "/cb/b",
|
||||
"status": 405,
|
||||
"allow": "GET, HEAD, POST, DELETE, OPTIONS",
|
||||
"body": "{\"error\":\"Method Not Allowed\"}"
|
||||
},
|
||||
{
|
||||
"adapter": "fetch",
|
||||
"method": "OPTIONS",
|
||||
"path": "/cb/b",
|
||||
"status": 204,
|
||||
"allow": "GET, HEAD, POST, DELETE, OPTIONS",
|
||||
"body": ""
|
||||
},
|
||||
{
|
||||
"adapter": "fetch",
|
||||
"method": "PUT",
|
||||
"path": "/cb/x",
|
||||
"status": 405,
|
||||
"allow": "GET, HEAD, DELETE, OPTIONS",
|
||||
"body": "{\"error\":\"Method Not Allowed\"}"
|
||||
},
|
||||
{
|
||||
"adapter": "fetch",
|
||||
"method": "HEAD",
|
||||
"path": "/cb/b",
|
||||
"status": 200,
|
||||
"allow": null,
|
||||
"body": ""
|
||||
},
|
||||
{
|
||||
"adapter": "fetch",
|
||||
"method": "PUT",
|
||||
"path": "/cb/x/y",
|
||||
"status": 405,
|
||||
"allow": "DELETE, OPTIONS",
|
||||
"body": "{\"error\":\"Method Not Allowed\"}"
|
||||
},
|
||||
{
|
||||
"adapter": "node",
|
||||
"method": "PUT",
|
||||
"path": "/ca/b",
|
||||
"status": 405,
|
||||
"allow": "GET, HEAD, POST, OPTIONS",
|
||||
"body": "{\"error\":\"Method Not Allowed\"}"
|
||||
},
|
||||
{
|
||||
"adapter": "node",
|
||||
"method": "OPTIONS",
|
||||
"path": "/ca/b",
|
||||
"status": 204,
|
||||
"allow": "GET, HEAD, POST, OPTIONS",
|
||||
"body": ""
|
||||
},
|
||||
{
|
||||
"adapter": "node",
|
||||
"method": "PUT",
|
||||
"path": "/ca/x",
|
||||
"status": 405,
|
||||
"allow": "GET, HEAD, OPTIONS",
|
||||
"body": "{\"error\":\"Method Not Allowed\"}"
|
||||
},
|
||||
{
|
||||
"adapter": "node",
|
||||
"method": "HEAD",
|
||||
"path": "/ca/b",
|
||||
"status": 200,
|
||||
"allow": null,
|
||||
"body": ""
|
||||
},
|
||||
{
|
||||
"adapter": "node",
|
||||
"method": "PUT",
|
||||
"path": "/ca/x/y",
|
||||
"status": 404,
|
||||
"allow": null,
|
||||
"body": "{\"error\":\"Not Found\"}"
|
||||
},
|
||||
{
|
||||
"adapter": "node",
|
||||
"method": "PUT",
|
||||
"path": "/cb/b",
|
||||
"status": 405,
|
||||
"allow": "GET, HEAD, POST, DELETE, OPTIONS",
|
||||
"body": "{\"error\":\"Method Not Allowed\"}"
|
||||
},
|
||||
{
|
||||
"adapter": "node",
|
||||
"method": "OPTIONS",
|
||||
"path": "/cb/b",
|
||||
"status": 204,
|
||||
"allow": "GET, HEAD, POST, DELETE, OPTIONS",
|
||||
"body": ""
|
||||
},
|
||||
{
|
||||
"adapter": "node",
|
||||
"method": "PUT",
|
||||
"path": "/cb/x",
|
||||
"status": 405,
|
||||
"allow": "GET, HEAD, DELETE, OPTIONS",
|
||||
"body": "{\"error\":\"Method Not Allowed\"}"
|
||||
},
|
||||
{
|
||||
"adapter": "node",
|
||||
"method": "HEAD",
|
||||
"path": "/cb/b",
|
||||
"status": 200,
|
||||
"allow": null,
|
||||
"body": ""
|
||||
},
|
||||
{
|
||||
"adapter": "node",
|
||||
"method": "PUT",
|
||||
"path": "/cb/x/y",
|
||||
"status": 405,
|
||||
"allow": "DELETE, OPTIONS",
|
||||
"body": "{\"error\":\"Method Not Allowed\"}"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
{
|
||||
"revision": "ed47836c9820c47bf4ed5e902d91e019abdb110a",
|
||||
"data": [
|
||||
{
|
||||
"phase": "A1 teapot up at boot",
|
||||
"method": "GET",
|
||||
"path": "/api/remote/ping",
|
||||
"status": 200,
|
||||
"allow": null,
|
||||
"body": "{\"from\":\"teapot\"}"
|
||||
},
|
||||
{
|
||||
"phase": "A1 teapot up at boot",
|
||||
"method": "POST",
|
||||
"path": "/api/remote/ping",
|
||||
"status": 405,
|
||||
"allow": "GET, HEAD, OPTIONS",
|
||||
"body": "{\"error\":\"Method Not Allowed\"}"
|
||||
},
|
||||
{
|
||||
"phase": "A1 teapot up at boot",
|
||||
"method": "GET",
|
||||
"path": "/api/local/ok",
|
||||
"status": 200,
|
||||
"allow": null,
|
||||
"body": "{\"from\":\"teacup\"}"
|
||||
},
|
||||
{
|
||||
"phase": "A1 teapot up at boot",
|
||||
"method": "GET",
|
||||
"path": "/api/nope",
|
||||
"status": 404,
|
||||
"allow": null,
|
||||
"body": "{\"error\":\"Not Found\"}"
|
||||
},
|
||||
{
|
||||
"phase": "A2 teapot gone after boot",
|
||||
"method": "GET",
|
||||
"path": "/api/remote/ping",
|
||||
"status": 503,
|
||||
"allow": null,
|
||||
"body": "{\"error\":\"mesh link to <teapot>/__mesh__/control is down\"}"
|
||||
},
|
||||
{
|
||||
"phase": "A2 teapot gone after boot",
|
||||
"method": "POST",
|
||||
"path": "/api/remote/ping",
|
||||
"status": 405,
|
||||
"allow": "GET, HEAD, OPTIONS",
|
||||
"body": "{\"error\":\"Method Not Allowed\"}"
|
||||
},
|
||||
{
|
||||
"phase": "A2 teapot gone after boot",
|
||||
"method": "GET",
|
||||
"path": "/api/local/ok",
|
||||
"status": 200,
|
||||
"allow": null,
|
||||
"body": "{\"from\":\"teacup\"}"
|
||||
},
|
||||
{
|
||||
"phase": "A2 teapot gone after boot",
|
||||
"method": "GET",
|
||||
"path": "/api/nope",
|
||||
"status": 404,
|
||||
"allow": null,
|
||||
"body": "{\"error\":\"Not Found\"}"
|
||||
},
|
||||
{
|
||||
"phase": "B1 teapot absent at boot",
|
||||
"method": "GET",
|
||||
"path": "/api/remote/ping",
|
||||
"status": 404,
|
||||
"allow": null,
|
||||
"body": "{\"error\":\"Not Found\"}"
|
||||
},
|
||||
{
|
||||
"phase": "B1 teapot absent at boot",
|
||||
"method": "POST",
|
||||
"path": "/api/remote/ping",
|
||||
"status": 404,
|
||||
"allow": null,
|
||||
"body": "{\"error\":\"Not Found\"}"
|
||||
},
|
||||
{
|
||||
"phase": "B1 teapot absent at boot",
|
||||
"method": "GET",
|
||||
"path": "/api/local/ok",
|
||||
"status": 200,
|
||||
"allow": null,
|
||||
"body": "{\"from\":\"teacup\"}"
|
||||
},
|
||||
{
|
||||
"phase": "B1 teapot absent at boot",
|
||||
"method": "GET",
|
||||
"path": "/api/nope",
|
||||
"status": 404,
|
||||
"allow": null,
|
||||
"body": "{\"error\":\"Not Found\"}"
|
||||
},
|
||||
{
|
||||
"phase": "B2 teapot up after boot",
|
||||
"method": "GET",
|
||||
"path": "/api/remote/ping",
|
||||
"status": 404,
|
||||
"allow": null,
|
||||
"body": "{\"error\":\"Not Found\"}"
|
||||
},
|
||||
{
|
||||
"phase": "B2 teapot up after boot",
|
||||
"method": "POST",
|
||||
"path": "/api/remote/ping",
|
||||
"status": 404,
|
||||
"allow": null,
|
||||
"body": "{\"error\":\"Not Found\"}"
|
||||
},
|
||||
{
|
||||
"phase": "B2 teapot up after boot",
|
||||
"method": "GET",
|
||||
"path": "/api/local/ok",
|
||||
"status": 200,
|
||||
"allow": null,
|
||||
"body": "{\"from\":\"teacup\"}"
|
||||
},
|
||||
{
|
||||
"phase": "B2 teapot up after boot",
|
||||
"method": "GET",
|
||||
"path": "/api/nope",
|
||||
"status": 404,
|
||||
"allow": null,
|
||||
"body": "{\"error\":\"Not Found\"}"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
{
|
||||
"revision": "ed47836c9820c47bf4ed5e902d91e019abdb110a",
|
||||
"data": [
|
||||
{
|
||||
"path": "/live/lobby",
|
||||
"sent": [
|
||||
{
|
||||
"id": "liveRoom",
|
||||
"params": {
|
||||
"room": "lobby"
|
||||
}
|
||||
}
|
||||
],
|
||||
"closes": [
|
||||
{}
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "/live/kitchen",
|
||||
"sent": [
|
||||
{
|
||||
"id": "liveRoom",
|
||||
"params": {
|
||||
"room": "kitchen"
|
||||
}
|
||||
}
|
||||
],
|
||||
"closes": [
|
||||
{}
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "/live/lobby/",
|
||||
"sent": [
|
||||
{
|
||||
"id": "liveRoom",
|
||||
"params": {
|
||||
"room": "lobby"
|
||||
}
|
||||
}
|
||||
],
|
||||
"closes": [
|
||||
{}
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "/live/x/../lobby",
|
||||
"sent": [
|
||||
{
|
||||
"id": "liveRoom",
|
||||
"params": {
|
||||
"room": "lobby"
|
||||
}
|
||||
}
|
||||
],
|
||||
"closes": [
|
||||
{}
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "/live/a%20b",
|
||||
"sent": [
|
||||
{
|
||||
"id": "liveRoom",
|
||||
"params": {
|
||||
"room": "a b"
|
||||
}
|
||||
}
|
||||
],
|
||||
"closes": [
|
||||
{}
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "/live/lobby?x=1",
|
||||
"sent": [
|
||||
{
|
||||
"id": "liveRoom",
|
||||
"params": {
|
||||
"room": "lobby"
|
||||
}
|
||||
}
|
||||
],
|
||||
"closes": [
|
||||
{}
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "/live/%E0%A4%A",
|
||||
"sent": [],
|
||||
"closes": [
|
||||
{
|
||||
"code": 1008,
|
||||
"reason": "invalid request path"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "/live//lobby",
|
||||
"sent": [],
|
||||
"closes": [
|
||||
{
|
||||
"code": 1008,
|
||||
"reason": "invalid request path"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "/plain",
|
||||
"sent": [],
|
||||
"closes": [
|
||||
{
|
||||
"code": 1008,
|
||||
"reason": "no matching ws route"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "/nope",
|
||||
"sent": [],
|
||||
"closes": [
|
||||
{
|
||||
"code": 1008,
|
||||
"reason": "no matching ws route"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "/feed",
|
||||
"sent": [
|
||||
{
|
||||
"id": "feed",
|
||||
"params": {}
|
||||
}
|
||||
],
|
||||
"closes": [
|
||||
{}
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "/__mesh__/control",
|
||||
"sent": [],
|
||||
"closes": [
|
||||
{
|
||||
"code": 1008,
|
||||
"reason": "mesh control channel not enabled: this app exports nothing, or has no mesh.secret"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"revision": "ed47836c9820c47bf4ed5e902d91e019abdb110a",
|
||||
"data": [
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/live/lobby",
|
||||
"status": 405,
|
||||
"allow": "POST, OPTIONS",
|
||||
"body": "{\"error\":\"Method Not Allowed\"}"
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/live/lobby",
|
||||
"status": 200,
|
||||
"allow": null,
|
||||
"body": "{\"id\":\"httpLobby\"}"
|
||||
},
|
||||
{
|
||||
"method": "OPTIONS",
|
||||
"path": "/live/lobby",
|
||||
"status": 204,
|
||||
"allow": "POST, OPTIONS",
|
||||
"body": ""
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/live/kitchen",
|
||||
"status": 404,
|
||||
"allow": null,
|
||||
"body": "{\"error\":\"Not Found\"}"
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/feed",
|
||||
"status": 200,
|
||||
"allow": null,
|
||||
"body": "{\"id\":\"feed\",\"params\":{}}\n"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
{
|
||||
"revision": "ed47836c9820c47bf4ed5e902d91e019abdb110a",
|
||||
"data": [
|
||||
{
|
||||
"path": "/live/lobby",
|
||||
"status": 101,
|
||||
"sent": [
|
||||
{
|
||||
"id": "liveRoom",
|
||||
"params": {
|
||||
"room": "lobby"
|
||||
}
|
||||
}
|
||||
],
|
||||
"close": {
|
||||
"code": 1005,
|
||||
"reason": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "/live/kitchen",
|
||||
"status": 101,
|
||||
"sent": [
|
||||
{
|
||||
"id": "liveRoom",
|
||||
"params": {
|
||||
"room": "kitchen"
|
||||
}
|
||||
}
|
||||
],
|
||||
"close": {
|
||||
"code": 1005,
|
||||
"reason": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "/live/lobby/",
|
||||
"status": 101,
|
||||
"sent": [
|
||||
{
|
||||
"id": "liveRoom",
|
||||
"params": {
|
||||
"room": "lobby"
|
||||
}
|
||||
}
|
||||
],
|
||||
"close": {
|
||||
"code": 1005,
|
||||
"reason": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "/live/x/../lobby",
|
||||
"status": 101,
|
||||
"sent": [
|
||||
{
|
||||
"id": "liveRoom",
|
||||
"params": {
|
||||
"room": "lobby"
|
||||
}
|
||||
}
|
||||
],
|
||||
"close": {
|
||||
"code": 1005,
|
||||
"reason": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "/live/a%20b",
|
||||
"status": 101,
|
||||
"sent": [
|
||||
{
|
||||
"id": "liveRoom",
|
||||
"params": {
|
||||
"room": "a b"
|
||||
}
|
||||
}
|
||||
],
|
||||
"close": {
|
||||
"code": 1005,
|
||||
"reason": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "/live/lobby?x=1",
|
||||
"status": 101,
|
||||
"sent": [
|
||||
{
|
||||
"id": "liveRoom",
|
||||
"params": {
|
||||
"room": "lobby"
|
||||
}
|
||||
}
|
||||
],
|
||||
"close": {
|
||||
"code": 1005,
|
||||
"reason": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "/live/%E0%A4%A",
|
||||
"status": 400,
|
||||
"sent": []
|
||||
},
|
||||
{
|
||||
"path": "/live//lobby",
|
||||
"status": 400,
|
||||
"sent": []
|
||||
},
|
||||
{
|
||||
"path": "/plain",
|
||||
"status": 404,
|
||||
"sent": []
|
||||
},
|
||||
{
|
||||
"path": "/nope",
|
||||
"status": 404,
|
||||
"sent": []
|
||||
},
|
||||
{
|
||||
"path": "/feed",
|
||||
"status": 101,
|
||||
"sent": [
|
||||
{
|
||||
"id": "feed",
|
||||
"params": {}
|
||||
}
|
||||
],
|
||||
"close": {
|
||||
"code": 1005,
|
||||
"reason": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "/__mesh__/control",
|
||||
"status": 101,
|
||||
"sent": [
|
||||
{
|
||||
"id": "reserved",
|
||||
"params": {}
|
||||
}
|
||||
],
|
||||
"close": {
|
||||
"code": 1005,
|
||||
"reason": ""
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
/**
|
||||
* Fixed-seed route/path generator for the differential corpus.
|
||||
*
|
||||
* Its output is versioned with the fixture: `frozen/matcher-generated.json` stores the seed, the
|
||||
* rules below and every generated declaration and request. The test regenerates from the seed and
|
||||
* requires the result to equal the stored inputs, so a change to this file cannot quietly move the
|
||||
* baseline — it fails until someone deliberately starts a new generator version.
|
||||
*
|
||||
* Do not edit GENERATOR_V1. A new generator is a new version with its own frozen file.
|
||||
*/
|
||||
import { compilePattern } from './oracle';
|
||||
import type { Declaration, Request, Scenario, Transport } from './matcher';
|
||||
|
||||
export const GENERATOR_SEED = 10908;
|
||||
export const GENERATOR_VERSION = 'router-parity-gen-v1';
|
||||
|
||||
export const GENERATOR_RULES = [
|
||||
'PRNG: mulberry32(seed); every choice below draws from it in program order.',
|
||||
'40 scenarios; each has 2-10 declarations and 12 requests.',
|
||||
'Declaration: 0-3 segments, each static (a|b|c|x, p=0.5), plain param (p=0.25) or constrained param (p=0.25) ' +
|
||||
'using one of \\d+ | [a-c]+ | [0-9a-f]{2}; then a final catch-all with p=0.2. Param names are p<index>.',
|
||||
'Declaration method from GET x3, POST, PUT, DELETE, PATCH, HEAD, OPTIONS. A GET is buffer with p=0.7, else ' +
|
||||
'sse | ndjson | negotiate; every other method is buffer.',
|
||||
'Request path: p=0.6 instantiate a random declaration (static -> its literal, param -> value pool, catch-all -> ' +
|
||||
'0-2 pool values), else 0-4 random pool segments. Value pool: a b c x 7 42 ff 0a a%20b caf%C3%A9 %34%32.',
|
||||
'Request decoration: trailing slash p=0.15, a dot segment (/./ or /q/../) inserted p=0.1, a repeated slash p=0.05.',
|
||||
'Request method from GET x2, HEAD, POST, PUT, DELETE, PATCH, OPTIONS.',
|
||||
'Unsupported patterns are never produced: every generated pattern must pass compilePattern.',
|
||||
];
|
||||
|
||||
const STATICS = ['a', 'b', 'c', 'x'];
|
||||
const CONSTRAINTS = ['\\d+', '[a-c]+', '[0-9a-f]{2}'];
|
||||
const VALUES = ['a', 'b', 'c', 'x', '7', '42', 'ff', '0a', 'a%20b', 'caf%C3%A9', '%34%32'];
|
||||
const DECL_METHODS = ['GET', 'GET', 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];
|
||||
const STREAMING: Transport[] = ['sse', 'ndjson', 'negotiate'];
|
||||
const REQUEST_METHODS = ['GET', 'GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'];
|
||||
|
||||
type Rng = () => number;
|
||||
|
||||
function mulberry32(seed: number): Rng {
|
||||
let state = seed >>> 0;
|
||||
return () => {
|
||||
state = (state + 0x6d2b79f5) >>> 0;
|
||||
let t = state;
|
||||
t = Math.imul(t ^ (t >>> 15), t | 1);
|
||||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
const pick = <T>(rng: Rng, items: readonly T[]): T => items[Math.floor(rng() * items.length)];
|
||||
const int = (rng: Rng, min: number, max: number): number => min + Math.floor(rng() * (max - min + 1));
|
||||
|
||||
function patternSegment(rng: Rng, index: number): string {
|
||||
const roll = rng();
|
||||
if (roll < 0.5) return pick(rng, STATICS);
|
||||
if (roll < 0.75) return `:p${index}`;
|
||||
return `:p${index}(${pick(rng, CONSTRAINTS)})`;
|
||||
}
|
||||
|
||||
function declaration(rng: Rng, id: string): Declaration {
|
||||
const depth = int(rng, 0, 3);
|
||||
const segments = Array.from({ length: depth }, (_, index) => patternSegment(rng, index));
|
||||
if (rng() < 0.2) segments.push(`:p${depth}*`);
|
||||
|
||||
const method = pick(rng, DECL_METHODS);
|
||||
const transport: Transport = method === 'GET' && rng() >= 0.7 ? pick(rng, STREAMING) : 'buffer';
|
||||
const pattern = `/${segments.join('/')}`;
|
||||
compilePattern(pattern); // throws if a rule above ever produced an unsupported pattern
|
||||
return { id, method, pattern, transport };
|
||||
}
|
||||
|
||||
function instantiate(rng: Rng, decl: Declaration): string[] {
|
||||
const segments: string[] = [];
|
||||
|
||||
for (const segment of decl.pattern.split('/').slice(1)) {
|
||||
if (!segment) continue;
|
||||
if (segment.endsWith('*')) {
|
||||
const count = int(rng, 0, 2);
|
||||
for (let index = 0; index < count; index++) segments.push(pick(rng, VALUES));
|
||||
} else {
|
||||
segments.push(segment.startsWith(':') ? pick(rng, VALUES) : segment);
|
||||
}
|
||||
}
|
||||
|
||||
return segments;
|
||||
}
|
||||
|
||||
function decorate(rng: Rng, segments: string[]): string {
|
||||
let path = `/${segments.join('/')}`;
|
||||
if (rng() < 0.15 && path !== '/') path += '/';
|
||||
|
||||
if (rng() < 0.1) {
|
||||
const at = int(rng, 0, segments.length);
|
||||
const dots = rng() < 0.5 ? ['.'] : ['q', '..'];
|
||||
const withDots = [...segments.slice(0, at), ...dots, ...segments.slice(at)];
|
||||
path = `/${withDots.join('/')}`;
|
||||
}
|
||||
|
||||
if (rng() < 0.05) path = path.replace('/', '//');
|
||||
return path;
|
||||
}
|
||||
|
||||
function request(rng: Rng, declarations: Declaration[]): Request {
|
||||
const segments =
|
||||
rng() < 0.6
|
||||
? instantiate(rng, pick(rng, declarations))
|
||||
: Array.from({ length: int(rng, 0, 4) }, () => pick(rng, VALUES));
|
||||
return { method: pick(rng, REQUEST_METHODS), raw: decorate(rng, segments) };
|
||||
}
|
||||
|
||||
export function generateScenarios(seed: number = GENERATOR_SEED): Scenario[] {
|
||||
const rng = mulberry32(seed);
|
||||
|
||||
return Array.from({ length: 40 }, (_, index): Scenario => {
|
||||
const id = `G${String(index + 1).padStart(2, '0')}`;
|
||||
const declarations = Array.from({ length: int(rng, 2, 10) }, (_, d) => declaration(rng, `${id}.d${d + 1}`));
|
||||
const requests = Array.from({ length: 12 }, () => request(rng, declarations));
|
||||
return { id, note: `generated by ${GENERATOR_VERSION}, seed ${seed}`, declarations, requests };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Version 2: the same seed and helpers, plus rules that force shared prefixes, so a meaningful share
|
||||
* of cases puts static, param, constrained and catch-all siblings under one prefix and makes the
|
||||
* lookup leave a branch it has already walked into. Frozen in `frozen/matcher-generated-v2.json`;
|
||||
* v1 above and its frozen file are unchanged.
|
||||
*/
|
||||
export const GENERATOR_V2_VERSION = 'router-parity-gen-v2';
|
||||
|
||||
export const GENERATOR_V2_RULES = [
|
||||
'PRNG: mulberry32(seed), fresh for v2; every choice below draws from it in program order.',
|
||||
'40 scenarios; each has a shared static prefix of 0-3 segments (a|b|c|x), so siblings sit at depth 1-4.',
|
||||
'Each scenario has 3-6 sibling declarations: prefix + one sibling segment + a tail. The first sibling segment is ' +
|
||||
'static, the second a plain or constrained param; the rest are static (p=0.35), plain (p=0.25), constrained ' +
|
||||
'(p=0.25) or a final catch-all (p=0.15). Tails are 0-2 segments, static/plain/constrained, none after a catch-all.',
|
||||
'Then 0-3 unrelated declarations made by the v1 declaration rule.',
|
||||
'Methods and transports follow the v1 declaration rule.',
|
||||
'Requests (12): p=0.5 instantiate a sibling; p=0.25 cross two siblings (prefix and sibling segment of one, tail ' +
|
||||
'of another) to force a partial match; else prefix + 0-3 pool values. v1 decoration and request methods apply.',
|
||||
'Unsupported patterns are never produced: every generated pattern must pass compilePattern.',
|
||||
];
|
||||
|
||||
function siblingSegment(rng: Rng, depth: number, index: number): string {
|
||||
if (index === 0) return pick(rng, STATICS);
|
||||
if (index === 1) return rng() < 0.5 ? `:p${depth}` : `:p${depth}(${pick(rng, CONSTRAINTS)})`;
|
||||
const roll = rng();
|
||||
if (roll < 0.35) return pick(rng, STATICS);
|
||||
if (roll < 0.6) return `:p${depth}`;
|
||||
if (roll < 0.85) return `:p${depth}(${pick(rng, CONSTRAINTS)})`;
|
||||
return `:p${depth}*`;
|
||||
}
|
||||
|
||||
function siblingDeclaration(rng: Rng, id: string, prefix: string[], index: number): Declaration {
|
||||
const sibling = siblingSegment(rng, prefix.length, index);
|
||||
const segments = [...prefix, sibling];
|
||||
if (!sibling.endsWith('*')) {
|
||||
const tail = int(rng, 0, 2);
|
||||
for (let t = 0; t < tail; t++) {
|
||||
const depth = segments.length;
|
||||
const roll = rng();
|
||||
segments.push(
|
||||
roll < 0.5 ? pick(rng, STATICS) : roll < 0.75 ? `:p${depth}` : `:p${depth}(${pick(rng, CONSTRAINTS)})`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const method = pick(rng, DECL_METHODS);
|
||||
const transport: Transport = method === 'GET' && rng() >= 0.7 ? pick(rng, STREAMING) : 'buffer';
|
||||
const pattern = `/${segments.join('/')}`;
|
||||
compilePattern(pattern);
|
||||
return { id, method, pattern, transport };
|
||||
}
|
||||
|
||||
function siblingRequest(rng: Rng, prefixLength: number, siblings: Declaration[]): Request {
|
||||
const roll = rng();
|
||||
let segments: string[];
|
||||
|
||||
if (roll < 0.5) {
|
||||
segments = instantiate(rng, pick(rng, siblings));
|
||||
} else if (roll < 0.75) {
|
||||
const head = instantiate(rng, pick(rng, siblings)).slice(0, prefixLength + 1);
|
||||
const tail = instantiate(rng, pick(rng, siblings)).slice(prefixLength + 1);
|
||||
segments = [...head, ...tail];
|
||||
} else {
|
||||
const prefix = instantiate(rng, siblings[0]).slice(0, prefixLength);
|
||||
segments = [...prefix, ...Array.from({ length: int(rng, 0, 3) }, () => pick(rng, VALUES))];
|
||||
}
|
||||
|
||||
return { method: pick(rng, REQUEST_METHODS), raw: decorate(rng, segments) };
|
||||
}
|
||||
|
||||
export function generateScenariosV2(seed: number = GENERATOR_SEED): Scenario[] {
|
||||
const rng = mulberry32(seed);
|
||||
|
||||
return Array.from({ length: 40 }, (_, index): Scenario => {
|
||||
const id = `S${String(index + 1).padStart(2, '0')}`;
|
||||
const prefix = Array.from({ length: int(rng, 0, 3) }, () => pick(rng, STATICS));
|
||||
const siblings = Array.from({ length: int(rng, 3, 6) }, (_, s) =>
|
||||
siblingDeclaration(rng, `${id}.s${s + 1}`, prefix, s),
|
||||
);
|
||||
const unrelated = Array.from({ length: int(rng, 0, 3) }, (_, u) => declaration(rng, `${id}.u${u + 1}`));
|
||||
const requests = Array.from({ length: 12 }, () => siblingRequest(rng, prefix.length, siblings));
|
||||
return {
|
||||
id,
|
||||
note: `generated by ${GENERATOR_V2_VERSION}, seed ${seed}, shared prefix /${prefix.join('/')}`,
|
||||
declarations: [...siblings, ...unrelated],
|
||||
requests,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
/**
|
||||
* Introspection goldens (ROUTER-CORPUS §3, CARD-09). `graph()`, `explain()` and `openapi()` read
|
||||
* `routePlans` in declaration order and must never be derived from a lookup index. Compared as
|
||||
* parsed structures with array order and key order held — see `expectFrozenEqual`.
|
||||
*/
|
||||
import 'reflect-metadata';
|
||||
import type { AddressInfo } from 'net';
|
||||
import { describe, it } from 'vitest';
|
||||
import {
|
||||
createApp,
|
||||
Provider,
|
||||
Step,
|
||||
Route,
|
||||
Get,
|
||||
Head,
|
||||
Post,
|
||||
Put,
|
||||
Delete,
|
||||
Options,
|
||||
Sse,
|
||||
Stream,
|
||||
Ws,
|
||||
Module,
|
||||
needs,
|
||||
param,
|
||||
query,
|
||||
body,
|
||||
} from '../../src/index';
|
||||
import type { Logger } from '../../src/logger';
|
||||
import { errorOutcome } from './matcher';
|
||||
import { frozen, expectFrozenEqual } from './frozen';
|
||||
|
||||
const slugSchema = {
|
||||
'~standard': { version: 1 as const, vendor: 'parity', validate: (v: unknown) => ({ value: v }) },
|
||||
};
|
||||
|
||||
@Provider({ provides: 'db' })
|
||||
class Db {
|
||||
provide() {
|
||||
return { db: {} };
|
||||
}
|
||||
}
|
||||
|
||||
@Step({ provides: 'user', needs: ['db'] })
|
||||
class Auth {
|
||||
run() {
|
||||
return { user: {} };
|
||||
}
|
||||
}
|
||||
|
||||
@Step({ provides: 'audit', needs: [] })
|
||||
class Audit {
|
||||
run() {
|
||||
return { audit: {} };
|
||||
}
|
||||
}
|
||||
|
||||
// Declaration order is deliberately not specificity order, and paths repeat across methods, so
|
||||
// any traversal-ordered output would differ from this one.
|
||||
@Route('/items')
|
||||
class Items {
|
||||
@Get('/:id/files/:path*') files(@param('path') _p: string) {
|
||||
return {};
|
||||
}
|
||||
@Get('/') list(@needs('user') _u: unknown) {
|
||||
return [];
|
||||
}
|
||||
@Post('/') create(@body() _b: unknown, @needs('user') _u: unknown) {
|
||||
return {};
|
||||
}
|
||||
@Get('/:id(\\d+)') get(@param('id') _id: string, @query('expand') _e: string) {
|
||||
return {};
|
||||
}
|
||||
@Head('/:id(\\d+)') head() {
|
||||
return {};
|
||||
}
|
||||
@Options('/:id(\\d+)') options() {
|
||||
return {};
|
||||
}
|
||||
@Delete('/:id(\\d+)') remove(@needs('audit') _a: unknown) {
|
||||
return {};
|
||||
}
|
||||
@Put('/:slug([a-z0-9-]+)') upsert(@body(slugSchema) _b: unknown) {
|
||||
return {};
|
||||
}
|
||||
@Get('/search') search() {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
@Route('/')
|
||||
class Streams {
|
||||
@Sse('/events') events() {
|
||||
return (async function* () {})();
|
||||
}
|
||||
@Stream('/feed') feed() {
|
||||
return (async function* () {})();
|
||||
}
|
||||
@Ws('/live/:room') live(@needs('user') _u: unknown) {
|
||||
return (async function* () {})();
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/api', providers: [Db], steps: [Auth, Audit], controllers: [Items, Streams] })
|
||||
class IntrospectionModule {}
|
||||
|
||||
const EXPLAINED = ['/api/items/:id(\\d+)', '/api/items', '/api/live/:room', '/api/items/:id/files/:path*'];
|
||||
const NOT_DECLARED = ['/api/missing', '/api/items/42', '/api/items/'];
|
||||
|
||||
function explainAll(explain: (pattern: string) => unknown) {
|
||||
return [...EXPLAINED, ...NOT_DECLARED].map((pattern) => {
|
||||
try {
|
||||
return { pattern, explain: explain(pattern) };
|
||||
} catch (error) {
|
||||
return { pattern, error: errorOutcome(error) };
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function capture() {
|
||||
const app = createApp({ modules: [IntrospectionModule] });
|
||||
return {
|
||||
graph: app.graph(),
|
||||
explain: explainAll(app.explain),
|
||||
openapi: app.openapi({ title: 'Parity', version: '1' }),
|
||||
};
|
||||
}
|
||||
|
||||
// ── mesh ────────────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
const SECRET = 'parity-secret';
|
||||
|
||||
@Step({ provides: 'config', needs: [], export: true })
|
||||
class Config {
|
||||
run() {
|
||||
return { config: {} };
|
||||
}
|
||||
}
|
||||
|
||||
@Route('/remote')
|
||||
class RemoteCtl {
|
||||
@Get('/ping', { export: true }) ping() {
|
||||
return { from: 'teapot' };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', steps: [Config], controllers: [RemoteCtl] })
|
||||
class TeapotModule {}
|
||||
|
||||
@Route('/local')
|
||||
class LocalCtl {
|
||||
@Get('/who') who(@needs('config') _c: unknown) {
|
||||
return { from: 'teacup' };
|
||||
}
|
||||
@Get('/:id') byId() {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
|
||||
class TeacupModule {}
|
||||
|
||||
const quiet: Logger = { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} };
|
||||
|
||||
function attempt<T>(fn: () => T): { value: T } | { error: ReturnType<typeof errorOutcome> } {
|
||||
try {
|
||||
return { value: fn() };
|
||||
} catch (error) {
|
||||
return { error: errorOutcome(error) };
|
||||
}
|
||||
}
|
||||
|
||||
async function captureMesh() {
|
||||
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||
const server = await teapot.listen(0);
|
||||
const url = `ws://127.0.0.1:${(server.address() as AddressInfo).port}/__mesh__/control`;
|
||||
const anonymize = (value: unknown) => JSON.parse(JSON.stringify(value).split(url).join('<teapot>'));
|
||||
const teacup = createApp({
|
||||
modules: [TeacupModule],
|
||||
experimental: true,
|
||||
logger: quiet,
|
||||
mesh: { teapots: [{ url, secret: SECRET }] },
|
||||
});
|
||||
|
||||
try {
|
||||
const before = {
|
||||
graph: attempt(() => teacup.graph()),
|
||||
explain: attempt(() => teacup.explain('/api/local/who')),
|
||||
openapi: attempt(() => teacup.openapi({ title: 'Parity', version: '1' })),
|
||||
};
|
||||
await teacup.ready();
|
||||
const after = {
|
||||
graph: teacup.graph(),
|
||||
explain: explainAll(teacup.explain).filter(({ pattern }) => pattern === '/api/missing'),
|
||||
explainLocal: teacup.explain('/api/local/who'),
|
||||
explainRemote: attempt(() => teacup.explain('/api/remote/ping')),
|
||||
openapi: teacup.openapi({ title: 'Parity', version: '1' }),
|
||||
};
|
||||
// Remote routes are reachable for lookup even though they are absent from routePlans.
|
||||
const res = await teacup.fetch(new Request('http://parity.test/api/remote/ping'));
|
||||
const lookup = { path: '/api/remote/ping', status: res.status, body: await res.text() };
|
||||
return anonymize({ before, after, lookup });
|
||||
} finally {
|
||||
await teacup.close();
|
||||
await teapot.close();
|
||||
}
|
||||
}
|
||||
|
||||
describe('router parity: introspection goldens', () => {
|
||||
it('graph() equals the golden, routes in declaration order', async () => {
|
||||
const expected = await frozen('golden-graph', () => capture().graph);
|
||||
expectFrozenEqual(capture().graph, expected, 'graph()');
|
||||
});
|
||||
|
||||
it('explain() for declared patterns and the `no route:` error equals the golden', async () => {
|
||||
const expected = await frozen('golden-explain', () => capture().explain);
|
||||
expectFrozenEqual(capture().explain, expected, 'explain()');
|
||||
});
|
||||
|
||||
it("openapi({ title: 'Parity', version: '1' }) equals the golden", async () => {
|
||||
const expected = await frozen('golden-openapi', () => capture().openapi);
|
||||
expectFrozenEqual(capture().openapi, expected, 'openapi()');
|
||||
});
|
||||
|
||||
it('a mesh teacup before and after ready() equals the golden; remote routes stay out of routePlans', async () => {
|
||||
const expected = await frozen('golden-mesh', captureMesh);
|
||||
expectFrozenEqual(await captureMesh(), expected, 'mesh introspection');
|
||||
}, 30_000);
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
{
|
||||
"purpose": "Existing tests retained unchanged as the radix-router compatibility baseline (FPRD-001 CARD-08, ROUTER-CORPUS §1, #109).",
|
||||
"revision": "ed47836c9820c47bf4ed5e902d91e019abdb110a",
|
||||
"corpusRevision": "42376c6693c7e15fadbcfb544172cc571fcacef0",
|
||||
"verification": {
|
||||
"date": "2026-10-10",
|
||||
"revision": "ed47836c9820c47bf4ed5e902d91e019abdb110a",
|
||||
"command": "npx vitest run <every vitest file below> --reporter=json; npm run test:deno; npm run test:bun; npm run test:edge",
|
||||
"result": "Every file and every named test exists at the pinned revision and passes. No test was renamed or removed between 42376c6 and ed47836; src/http/router.ts is byte-identical between the two.",
|
||||
"renamed": []
|
||||
},
|
||||
"retained": [
|
||||
{
|
||||
"surface": "Pattern grammar, normalization, matching, Allow, HEAD",
|
||||
"file": "test/router.test.ts",
|
||||
"scope": "file"
|
||||
},
|
||||
{
|
||||
"surface": "HTTP adapter",
|
||||
"file": "test/http.test.ts",
|
||||
"scope": "tests",
|
||||
"tests": [
|
||||
"matches a static + :param route and extracts params",
|
||||
"http streaming > routes by method (non-GET no longer falls through)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"surface": "Fetch adapter",
|
||||
"file": "test/fetch.test.ts",
|
||||
"scope": "tests",
|
||||
"tests": [
|
||||
"app.fetch > handles GET and returns JSON 200",
|
||||
"app.fetch > 404s an unknown route",
|
||||
"app.fetch on a mesh app > serves without ever calling listen()",
|
||||
"app.fetch on a mesh app > does not re-boot when listen() follows a fetch"
|
||||
]
|
||||
},
|
||||
{
|
||||
"surface": "App declarations and introspection",
|
||||
"file": "test/app.test.ts",
|
||||
"scope": "tests",
|
||||
"tests": [
|
||||
"app.graph / explain > graph() returns nodes (with origin/needs/provides) and routes with their sliced chain",
|
||||
"app.graph / explain > explain() returns the rich chain with origin and a handler entry",
|
||||
"route table validation > rejects routes with the same method and effective pattern",
|
||||
"route table validation > allows the same effective pattern under different methods",
|
||||
"devGraph endpoint > serves /__graph__ as HTML when devGraph:true",
|
||||
"devGraph endpoint > does NOT mount /__graph__ without devGraph",
|
||||
"devGraph endpoint > serves /__graph__ and /__openapi__ over app.fetch too (runtime-agnostic dev tools)",
|
||||
"app streaming wiring > serves a @Ws route receiving @inbound and returning a channel"
|
||||
]
|
||||
},
|
||||
{
|
||||
"surface": "OpenAPI",
|
||||
"file": "test/openapi.test.ts",
|
||||
"scope": "file"
|
||||
},
|
||||
{
|
||||
"surface": "WebSocket selection",
|
||||
"file": "test/ws-core.test.ts",
|
||||
"scope": "tests",
|
||||
"tests": ["runWsConnection (neutral core) > matchWsRoute finds a pattern and captures params"]
|
||||
},
|
||||
{
|
||||
"surface": "Node WebSocket upgrade",
|
||||
"file": "test/ws.test.ts",
|
||||
"scope": "tests",
|
||||
"tests": [
|
||||
"ws upgrade > echoes inbound to outbound and aborts on close",
|
||||
"ws upgrade > closes with a 4000+status code when the WS open() throws an HttpError"
|
||||
]
|
||||
},
|
||||
{
|
||||
"surface": "Mesh route splicing",
|
||||
"file": "test/mesh/integration.test.ts",
|
||||
"scope": "tests",
|
||||
"tests": [
|
||||
"mesh skeleton integration > teapot still serves its own local route (regression)",
|
||||
"mesh skeleton integration > refuses to boot when two teapots export the same route, naming both",
|
||||
"mesh skeleton integration > refuses ambiguous remote routes that differ only by parameter name",
|
||||
"mesh skeleton integration > accepts the same route from a single teapot (regression: no false positive)",
|
||||
"mesh skeleton integration > gives a local route precedence over a remote one, and says so",
|
||||
"mesh skeleton integration > does not warn when a remote route has no local twin"
|
||||
]
|
||||
}
|
||||
],
|
||||
"runtimeSmoke": [
|
||||
{
|
||||
"file": "test/deno/ws.test.ts",
|
||||
"runner": "npm run test:deno",
|
||||
"tests": [
|
||||
"serveDeno: HTTP + WebSocket round-trip through the graph",
|
||||
"serveDeno: a malformed upgrade path closes 1008 and the server keeps serving"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "test/bun/ws.test.ts",
|
||||
"runner": "npm run test:bun",
|
||||
"tests": [
|
||||
"serveBun: HTTP + WebSocket round-trip",
|
||||
"serveBun: a malformed upgrade path closes 1008 and the server keeps serving"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "test/deno/mesh.test.ts",
|
||||
"runner": "npm run test:deno",
|
||||
"tests": [
|
||||
"mesh on Deno: teacup resolves a Deno teapot through the graph",
|
||||
"mesh on Deno: a teapot refuses a bad secret over its control channel"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "test/bun/mesh.test.ts",
|
||||
"runner": "npm run test:bun",
|
||||
"tests": [
|
||||
"mesh on Bun: teacup resolves a Bun teapot through the graph",
|
||||
"mesh on Bun: a teapot refuses a bad secret over its control channel"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "test/edge/run.ts",
|
||||
"runner": "npm run test:edge",
|
||||
"tests": []
|
||||
}
|
||||
],
|
||||
"supplementary": {
|
||||
"note": "Not in ROUTER-CORPUS §1. Proposed because #117 (merged after the corpus was written) moved WS upgrade paths through normalizeRequestPath and added the reserved-path refusal on app.upgrade. Pending D5 approval; they run in npm test either way.",
|
||||
"retained": [
|
||||
{
|
||||
"surface": "Node upgrade path normalization and rejection (#104)",
|
||||
"file": "test/ws-upgrade-reject.test.ts",
|
||||
"scope": "file"
|
||||
},
|
||||
{
|
||||
"surface": "Reserved mesh control path ahead of WS routes (Node)",
|
||||
"file": "test/mesh/control-upgrade.test.ts",
|
||||
"scope": "file"
|
||||
},
|
||||
{
|
||||
"surface": "Reserved mesh control path over app.upgrade",
|
||||
"file": "test/mesh/fetch-boot.test.ts",
|
||||
"scope": "tests",
|
||||
"tests": [
|
||||
"mesh control over app.upgrade (no listen) > serves the handshake to a peer that never touched a Node server",
|
||||
"mesh control over app.upgrade (no listen) > refuses the reserved path explicitly on an app that exports nothing"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"frozenFixtures": {
|
||||
"dir": "test/router-parity/frozen",
|
||||
"oracle": "test/router-parity/oracle.ts",
|
||||
"readme": "test/router-parity/README.md"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* Keeps the retained-test manifest honest: every file it names must exist and every test it names
|
||||
* must still be declared there. A rename or deletion during CARD-07 fails here instead of silently
|
||||
* shrinking the compatibility baseline. Whether those tests *pass* is `npm test` and the runtime
|
||||
* suites' job; this only proves they are still the tests the manifest says they are.
|
||||
*/
|
||||
import { existsSync, readFileSync, readdirSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { PINNED_REVISION } from './frozen';
|
||||
|
||||
interface Entry {
|
||||
file: string;
|
||||
scope?: 'file' | 'tests';
|
||||
tests?: string[];
|
||||
}
|
||||
|
||||
const ROOT = join(__dirname, '..', '..');
|
||||
const manifest = JSON.parse(readFileSync(join(__dirname, 'manifest.json'), 'utf8')) as {
|
||||
revision: string;
|
||||
retained: Entry[];
|
||||
runtimeSmoke: Entry[];
|
||||
supplementary: { retained: Entry[] };
|
||||
frozenFixtures: { oracle: string; readme: string };
|
||||
};
|
||||
|
||||
const entries: Entry[] = [...manifest.retained, ...manifest.runtimeSmoke, ...manifest.supplementary.retained];
|
||||
|
||||
describe('router parity: retained-test manifest', () => {
|
||||
it('is pinned to the same revision as the frozen fixtures', () => {
|
||||
expect(manifest.revision).toBe(PINNED_REVISION);
|
||||
});
|
||||
|
||||
for (const entry of entries) {
|
||||
it(`${entry.file} exists and declares every named test`, () => {
|
||||
const path = join(ROOT, entry.file);
|
||||
expect(existsSync(path), `${entry.file} is missing`).toBe(true);
|
||||
const source = readFileSync(path, 'utf8');
|
||||
|
||||
for (const name of entry.tests ?? []) {
|
||||
for (const part of name.split(' > ')) expect(source, `${entry.file}: '${name}'`).toContain(part);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
it('names an oracle and a README that exist', () => {
|
||||
for (const file of [manifest.frozenFixtures.oracle, manifest.frozenFixtures.readme])
|
||||
expect(existsSync(join(ROOT, file)), file).toBe(true);
|
||||
});
|
||||
|
||||
it('the oracle is not imported from src/', () => {
|
||||
// A frozen oracle the product can reach is no longer frozen: someone will "fix" it.
|
||||
const files = readdirSync(join(ROOT, 'src'), { recursive: true, encoding: 'utf8' }).filter((f) =>
|
||||
f.endsWith('.ts'),
|
||||
);
|
||||
const hits = files.filter((f) => readFileSync(join(ROOT, 'src', f), 'utf8').includes('router-parity'));
|
||||
expect(hits).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,156 @@
|
||||
/**
|
||||
* Differential matcher parity (CARD-08 → CARD-07, #109).
|
||||
*
|
||||
* Every scenario runs through the frozen oracle and through the live `src/http/router` exports, and
|
||||
* both must equal the outputs captured at the pinned revision. Today the live router *is* the
|
||||
* linear matcher, so this proves the oracle is a faithful copy; once CARD-07 swaps the internals
|
||||
* for a radix index behind the same exports, the same test compares oracle against radix with no
|
||||
* edit here.
|
||||
*/
|
||||
import { readFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import { describe, it, expect, beforeAll } from 'vitest';
|
||||
import * as live from '../../src/http/router';
|
||||
import * as oracle from './oracle';
|
||||
import { runScenario, type MatcherImpl, type Outcome, type Scenario } from './matcher';
|
||||
import { HAND_SCENARIOS, OWNER_SCENARIOS } from './cases';
|
||||
import { branchStats, type BranchStats } from './branches';
|
||||
import {
|
||||
generateScenarios,
|
||||
generateScenariosV2,
|
||||
GENERATOR_RULES,
|
||||
GENERATOR_SEED,
|
||||
GENERATOR_VERSION,
|
||||
GENERATOR_V2_RULES,
|
||||
GENERATOR_V2_VERSION,
|
||||
} from './generator';
|
||||
import { frozen, expectFrozenEqual } from './frozen';
|
||||
import { runDifferential, runWsMatcher, LIVE_WS_MATCHER, ORACLE_WS_MATCHER } from './differential';
|
||||
|
||||
const LIVE: MatcherImpl = live;
|
||||
const ORACLE: MatcherImpl = oracle;
|
||||
|
||||
interface CapturedScenario extends Scenario {
|
||||
outcomes: Outcome[];
|
||||
}
|
||||
|
||||
interface GeneratedFile {
|
||||
generator: string;
|
||||
seed: number;
|
||||
rules: string[];
|
||||
scenarios: CapturedScenario[];
|
||||
}
|
||||
|
||||
const capture = (scenarios: Scenario[]): CapturedScenario[] =>
|
||||
scenarios.map((scenario) => ({ ...scenario, outcomes: runScenario(LIVE, scenario) }));
|
||||
|
||||
function checkScenario(scenario: Scenario, expected: CapturedScenario | undefined): void {
|
||||
expect(expected, `${scenario.id} is missing from the frozen fixture`).toBeDefined();
|
||||
const { outcomes, ...inputs } = expected!;
|
||||
expectFrozenEqual(scenario, inputs, `${scenario.id} inputs`);
|
||||
expectFrozenEqual(runScenario(ORACLE, scenario), outcomes, `${scenario.id} oracle`);
|
||||
expectFrozenEqual(runScenario(LIVE, scenario), outcomes, `${scenario.id} live router`);
|
||||
}
|
||||
|
||||
describe('router parity: hand-picked matcher cases', () => {
|
||||
let expected: Map<string, CapturedScenario>;
|
||||
|
||||
beforeAll(async () => {
|
||||
const data = await frozen('matcher-hand', () => capture(HAND_SCENARIOS));
|
||||
expect(data.map((scenario) => scenario.id)).toEqual(HAND_SCENARIOS.map((scenario) => scenario.id));
|
||||
expected = new Map(data.map((scenario) => [scenario.id, scenario]));
|
||||
});
|
||||
|
||||
for (const scenario of HAND_SCENARIOS) {
|
||||
it(`${scenario.id}: ${scenario.note}`, () => checkScenario(scenario, expected.get(scenario.id)));
|
||||
}
|
||||
});
|
||||
|
||||
describe(`router parity: generated matcher cases (${GENERATOR_VERSION}, seed ${GENERATOR_SEED})`, () => {
|
||||
const generated = generateScenarios(GENERATOR_SEED);
|
||||
let expected: Map<string, CapturedScenario>;
|
||||
|
||||
beforeAll(async () => {
|
||||
const data = await frozen<GeneratedFile>('matcher-generated', () => ({
|
||||
generator: GENERATOR_VERSION,
|
||||
seed: GENERATOR_SEED,
|
||||
rules: GENERATOR_RULES,
|
||||
scenarios: capture(generated),
|
||||
}));
|
||||
expect({ generator: data.generator, seed: data.seed, rules: data.rules }).toEqual({
|
||||
generator: GENERATOR_VERSION,
|
||||
seed: GENERATOR_SEED,
|
||||
rules: GENERATOR_RULES,
|
||||
});
|
||||
expect(data.scenarios.map((scenario) => scenario.id)).toEqual(generated.map((scenario) => scenario.id));
|
||||
expected = new Map(data.scenarios.map((scenario) => [scenario.id, scenario]));
|
||||
});
|
||||
|
||||
for (const scenario of generated) {
|
||||
it(`${scenario.id}`, () => checkScenario(scenario, expected.get(scenario.id)));
|
||||
}
|
||||
});
|
||||
|
||||
describe('router parity: owner-requested matcher cases', () => {
|
||||
let expected: Map<string, CapturedScenario>;
|
||||
|
||||
beforeAll(async () => {
|
||||
const data = await frozen('matcher-owner', () => capture(OWNER_SCENARIOS));
|
||||
expect(data.map((scenario) => scenario.id)).toEqual(OWNER_SCENARIOS.map((scenario) => scenario.id));
|
||||
expected = new Map(data.map((scenario) => [scenario.id, scenario]));
|
||||
});
|
||||
|
||||
for (const scenario of OWNER_SCENARIOS) {
|
||||
it(`${scenario.id}: ${scenario.note}`, () => checkScenario(scenario, expected.get(scenario.id)));
|
||||
}
|
||||
});
|
||||
|
||||
interface GeneratedV2File extends GeneratedFile {
|
||||
/** Share of generated requests that walk into sibling branches; v1's share is kept for contrast. */
|
||||
branchStats: { v1: BranchStats; v2: BranchStats };
|
||||
}
|
||||
|
||||
describe(`router parity: generated shared-prefix cases (${GENERATOR_V2_VERSION}, seed ${GENERATOR_SEED})`, () => {
|
||||
const generated = generateScenariosV2(GENERATOR_SEED);
|
||||
const stats = () => ({ v1: branchStats(generateScenarios(GENERATOR_SEED)), v2: branchStats(generated) });
|
||||
let expected: Map<string, CapturedScenario>;
|
||||
|
||||
beforeAll(async () => {
|
||||
const data = await frozen<GeneratedV2File>('matcher-generated-v2', () => ({
|
||||
generator: GENERATOR_V2_VERSION,
|
||||
seed: GENERATOR_SEED,
|
||||
rules: GENERATOR_V2_RULES,
|
||||
branchStats: stats(),
|
||||
scenarios: capture(generated),
|
||||
}));
|
||||
expect({ generator: data.generator, seed: data.seed, rules: data.rules }).toEqual({
|
||||
generator: GENERATOR_V2_VERSION,
|
||||
seed: GENERATOR_SEED,
|
||||
rules: GENERATOR_V2_RULES,
|
||||
});
|
||||
expect(stats()).toEqual(data.branchStats);
|
||||
expect(data.scenarios.map((scenario) => scenario.id)).toEqual(generated.map((scenario) => scenario.id));
|
||||
expected = new Map(data.scenarios.map((scenario) => [scenario.id, scenario]));
|
||||
});
|
||||
|
||||
for (const scenario of generated) {
|
||||
it(`${scenario.id}`, () => checkScenario(scenario, expected.get(scenario.id)));
|
||||
}
|
||||
});
|
||||
|
||||
describe('router parity: WebSocket matcher (first registered wins)', () => {
|
||||
// WS selection is a separate contract from HTTP: no specificity ranking, registration order only.
|
||||
it('oracle and live matchWsRoute equal the frozen capture', async () => {
|
||||
const expected = await frozen('matcher-ws', () => runWsMatcher(LIVE_WS_MATCHER));
|
||||
expectFrozenEqual(runWsMatcher(ORACLE_WS_MATCHER), expected, 'ws oracle');
|
||||
expectFrozenEqual(runWsMatcher(LIVE_WS_MATCHER), expected, 'ws live');
|
||||
});
|
||||
});
|
||||
|
||||
describe('router parity: runtime-neutral differential (the one Deno, Bun and workerd run)', () => {
|
||||
it('reports no mismatch on Node', async () => {
|
||||
const dir = join(__dirname, 'frozen');
|
||||
const report = await runDifferential((name) => JSON.parse(readFileSync(join(dir, `${name}.json`), 'utf8')));
|
||||
expect(report.mismatches).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* The differential matcher harness: one ordered declaration array and one request list, run through
|
||||
* any implementation of the router's lookup functions, reduced to what a caller can observe —
|
||||
* which declaration answered (by stable ID, never by pattern text), its decoded params, whether HEAD
|
||||
* was implicit, the ordered `Allow` list, and the normalization error if the path never got that far.
|
||||
*/
|
||||
import type { RouteDef } from '../../src/http/types';
|
||||
|
||||
export type Transport = 'buffer' | 'sse' | 'ndjson' | 'negotiate';
|
||||
|
||||
export interface Declaration {
|
||||
id: string;
|
||||
method: string;
|
||||
pattern: string;
|
||||
transport: Transport;
|
||||
}
|
||||
|
||||
export interface Request {
|
||||
method: string;
|
||||
raw: string;
|
||||
}
|
||||
|
||||
export interface Scenario {
|
||||
id: string;
|
||||
note: string;
|
||||
declarations: Declaration[];
|
||||
requests: Request[];
|
||||
}
|
||||
|
||||
/** The lookup surface CARD-07 replaces. The live router and the frozen oracle both satisfy it. */
|
||||
export interface MatcherImpl {
|
||||
normalizeRequestPath(path: string): string;
|
||||
matchRoute(
|
||||
routes: RouteDef[],
|
||||
method: string,
|
||||
path: string,
|
||||
): { def: unknown; params: Record<string, string> } | undefined;
|
||||
resolveRoute(
|
||||
routes: RouteDef[],
|
||||
method: string,
|
||||
path: string,
|
||||
): { def: unknown; params: Record<string, string>; implicitHead: boolean } | undefined;
|
||||
allowedMethods(routes: RouteDef[], path: string): string[];
|
||||
}
|
||||
|
||||
export interface ErrorOutcome {
|
||||
name: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface Outcome {
|
||||
method: string;
|
||||
raw: string;
|
||||
normalized?: string;
|
||||
error?: ErrorOutcome;
|
||||
match?: { id: string; params: Record<string, string> } | null;
|
||||
resolve?: { id: string; params: Record<string, string>; implicitHead: boolean } | null;
|
||||
allow?: string[];
|
||||
}
|
||||
|
||||
export function errorOutcome(error: unknown): ErrorOutcome {
|
||||
const err = error as Error;
|
||||
return { name: err.name, message: err.message };
|
||||
}
|
||||
|
||||
/** Builds fresh `RouteDef` objects for one run, so no implementation can see another's cached table. */
|
||||
function buildRoutes(declarations: Declaration[]): { routes: RouteDef[]; idOf: Map<unknown, string> } {
|
||||
const idOf = new Map<unknown, string>();
|
||||
const routes = declarations.map((decl): RouteDef => {
|
||||
const def: RouteDef = {
|
||||
method: decl.method,
|
||||
pattern: decl.pattern,
|
||||
transport: decl.transport,
|
||||
handler: async () => ({ status: 200, headers: {}, body: decl.id }),
|
||||
};
|
||||
idOf.set(def, decl.id);
|
||||
return def;
|
||||
});
|
||||
return { routes, idOf };
|
||||
}
|
||||
|
||||
export function runScenario(impl: MatcherImpl, scenario: Scenario): Outcome[] {
|
||||
const { routes, idOf } = buildRoutes(scenario.declarations);
|
||||
const id = (def: unknown): string => idOf.get(def) ?? '<unknown declaration>';
|
||||
|
||||
return scenario.requests.map(({ method, raw }): Outcome => {
|
||||
let normalized: string;
|
||||
|
||||
try {
|
||||
normalized = impl.normalizeRequestPath(raw);
|
||||
} catch (error) {
|
||||
return { method, raw, error: errorOutcome(error) };
|
||||
}
|
||||
|
||||
const match = impl.matchRoute(routes, method, normalized);
|
||||
const resolved = impl.resolveRoute(routes, method, normalized);
|
||||
|
||||
return {
|
||||
method,
|
||||
raw,
|
||||
normalized,
|
||||
match: match ? { id: id(match.def), params: match.params } : null,
|
||||
resolve: resolved ? { id: id(resolved.def), params: resolved.params, implicitHead: resolved.implicitHead } : null,
|
||||
allow: impl.allowedMethods(routes, normalized),
|
||||
};
|
||||
});
|
||||
}
|
||||
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user