Compare commits
25
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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
|
## Environment
|
||||||
|
|
||||||
- green-tea version:
|
- 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:
|
- OS:
|
||||||
|
|
||||||
<!--
|
<!--
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ jobs:
|
|||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- uses: actions/setup-node@v4
|
- uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: '18'
|
node-version: '22'
|
||||||
- run: npm ci
|
- run: npm ci
|
||||||
- run: npm run lint
|
- run: npm run lint
|
||||||
- run: npm run format:check
|
- run: npm run format:check
|
||||||
|
|||||||
@@ -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.
|
**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:
|
**Delete the branch when the work lands.** Both sides, as the last step of merging rather than a chore left for later:
|
||||||
|
|
||||||
```bash
|
```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
|
green-tea uses calendar versioning: `YY.M.PATCH` — the month is not zero-padded, since
|
||||||
npm treats versions as semver and semver forbids leading zeros.
|
npm treats versions as semver and semver forbids leading zeros.
|
||||||
|
|
||||||
|
## [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
|
## [26.9.0-beta.2] - 2026-09-22
|
||||||
|
|
||||||
### Breaking
|
### Breaking
|
||||||
|
|||||||
+1
-1
@@ -101,7 +101,7 @@ Follow [Conventional Commits](https://www.conventionalcommits.org/): `feat:`, `f
|
|||||||
|
|
||||||
## Local setup
|
## 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
|
```bash
|
||||||
npm install
|
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.
|
- **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.
|
- **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.
|
- **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.
|
- **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 })`.
|
- **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.
|
- **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.
|
**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.
|
**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,90 @@
|
|||||||
|
# Pre-radix router baseline — `ed47836`
|
||||||
|
|
||||||
|
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
|
||||||
+273
@@ -0,0 +1,273 @@
|
|||||||
|
/**
|
||||||
|
* 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
|
||||||
|
*
|
||||||
|
* Each implementation is a module exporting `resolveRoute` and `allowedMethods` with the
|
||||||
|
* `src/http/router.ts` signatures. With several, every run measures all of them in separate child
|
||||||
|
* processes, alternating which goes first, on the same generated tables. Do not edit the generator,
|
||||||
|
* the workloads or the defaults below between a baseline and its comparison — they are the method.
|
||||||
|
*
|
||||||
|
* Env: `LOOKUP_ROUTERS` (label=path list, default `live=src/http/router.ts`), `LOOKUP_RUNS` (5),
|
||||||
|
* `LOOKUP_SAMPLES` (21 per cell per run), `LOOKUP_SAMPLE_MS` (25), `LOOKUP_WARMUP_MS` (250),
|
||||||
|
* `LOOKUP_OUT` (bench/lookup-results.json).
|
||||||
|
*/
|
||||||
|
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 ?? 5);
|
||||||
|
const SAMPLES = Number(process.env.LOOKUP_SAMPLES ?? 21);
|
||||||
|
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;
|
||||||
|
iterations: number;
|
||||||
|
samplesNs: number[];
|
||||||
|
}
|
||||||
|
|
||||||
|
function measure(router: RouterModule, routes: Route[], w: Workload): { iterations: number; samplesNs: number[] } {
|
||||||
|
const answer = lookup(router, routes, w);
|
||||||
|
if (answer !== w.expect) throw new Error(`${w.name} @ ${routes.length}: expected '${w.expect}', got '${answer}'`);
|
||||||
|
|
||||||
|
// Warm-up, time-boxed; it also calibrates how many iterations make one sample last SAMPLE_MS.
|
||||||
|
let sink = 0;
|
||||||
|
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;
|
||||||
|
const iterations = Math.max(100, Math.round((SAMPLE_MS * 1e6) / nsPerOp));
|
||||||
|
|
||||||
|
const samplesNs: number[] = [];
|
||||||
|
for (let s = 0; s < SAMPLES; s++) {
|
||||||
|
const start = process.hrtime.bigint();
|
||||||
|
for (let i = 0; i < iterations; i++) sink += lookup(router, routes, w).length;
|
||||||
|
samplesNs.push(Number(process.hrtime.bigint() - start) / iterations);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sink === 42) process.stderr.write(''); // keeps `sink` observable
|
||||||
|
return { iterations, samplesNs };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function child(label: string, path: string): Promise<void> {
|
||||||
|
const router = (await import(pathToFileURL(resolve(path)).href)) as RouterModule;
|
||||||
|
const cells: Cell[] = [];
|
||||||
|
|
||||||
|
for (const count of ROUTE_COUNTS) {
|
||||||
|
const routes = buildRoutes(count);
|
||||||
|
for (const w of WORKLOADS) cells.push({ routes: count, workload: w.name, ...measure(router, routes, w) });
|
||||||
|
}
|
||||||
|
|
||||||
|
process.stdout.write(`${JSON.stringify({ label, cells })}\n`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function runChild(label: string, path: string): Promise<{ label: string; cells: Cell[] }> {
|
||||||
|
return new Promise((resolvePromise, reject) => {
|
||||||
|
const proc = spawn(process.execPath, ['--import', 'tsx', 'bench/lookup.ts'], {
|
||||||
|
env: { ...process.env, LOOKUP_CHILD: `${label}=${path}` },
|
||||||
|
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(`${label} 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;
|
||||||
|
};
|
||||||
|
|
||||||
|
function git(cwd: string, ...args: string[]): string {
|
||||||
|
try {
|
||||||
|
return execFileSync('git', ['-C', cwd, ...args], { encoding: 'utf8' }).trim();
|
||||||
|
} catch {
|
||||||
|
return 'unavailable';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function environment(routers: Array<[string, string]>) {
|
||||||
|
const pkg = JSON.parse(readFileSync('package.json', 'utf8')) as { name: string; version: string };
|
||||||
|
return {
|
||||||
|
startedAt: new Date().toISOString(),
|
||||||
|
node: process.version,
|
||||||
|
v8: process.versions.v8,
|
||||||
|
platform: `${os.platform()} ${os.release()} ${os.arch()}`,
|
||||||
|
cpu: os.cpus()[0]?.model,
|
||||||
|
cpus: os.cpus().length,
|
||||||
|
memoryBytes: os.totalmem(),
|
||||||
|
loadavgAtStart: os.loadavg(),
|
||||||
|
package: `${pkg.name}@${pkg.version}`,
|
||||||
|
harnessCommit: git('.', 'rev-parse', 'HEAD'),
|
||||||
|
routers: routers.map(([label, path]) => ({
|
||||||
|
label,
|
||||||
|
path,
|
||||||
|
commit: git(dirname(resolve(path)), 'rev-parse', 'HEAD'),
|
||||||
|
dirty: git(dirname(resolve(path)), 'status', '--porcelain', '--', resolve(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: for each router (order alternates per run): for count in routeCounts: for workload in workloads',
|
||||||
|
operation: 'resolveRoute(routes, method, path); on undefined, allowedMethods(routes, path)',
|
||||||
|
runs: RUNS,
|
||||||
|
samplesPerCellPerRun: SAMPLES,
|
||||||
|
sampleMs: SAMPLE_MS,
|
||||||
|
warmupMsPerCell: WARMUP_MS,
|
||||||
|
unit: 'ns per lookup (sample time / iterations)',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main(): Promise<void> {
|
||||||
|
if (process.env.LOOKUP_CHILD) {
|
||||||
|
const [label, path] = process.env.LOOKUP_CHILD.split('=');
|
||||||
|
return child(label, path);
|
||||||
|
}
|
||||||
|
|
||||||
|
const routers = (process.env.LOOKUP_ROUTERS ?? 'live=src/http/router.ts')
|
||||||
|
.split(',')
|
||||||
|
.map((entry) => entry.split('=') as [string, string]);
|
||||||
|
const meta = environment(routers);
|
||||||
|
const runs: Array<{ run: number; order: string[]; label: string; cells: Cell[] }> = [];
|
||||||
|
|
||||||
|
for (let run = 0; run < RUNS; run++) {
|
||||||
|
const order = run % 2 === 0 ? routers : [...routers].reverse();
|
||||||
|
for (const [label, path] of order) {
|
||||||
|
const result = await runChild(label, path);
|
||||||
|
runs.push({ run: run + 1, order: order.map(([l]) => l), ...result });
|
||||||
|
process.stderr.write(`[lookup] run ${run + 1}/${RUNS} ${label} done\n`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const summary = routers.flatMap(([label]) =>
|
||||||
|
ROUTE_COUNTS.flatMap((count) =>
|
||||||
|
WORKLOADS.map((w) => {
|
||||||
|
const cells = runs
|
||||||
|
.filter((r) => r.label === label)
|
||||||
|
.map((r) => r.cells.find((c) => c.routes === count && c.workload === w.name)!);
|
||||||
|
const runMedians = cells.map((c) => median(c.samplesNs));
|
||||||
|
const all = cells.flatMap((c) => c.samplesNs);
|
||||||
|
const med = median(all);
|
||||||
|
return {
|
||||||
|
router: label,
|
||||||
|
routes: count,
|
||||||
|
workload: w.name,
|
||||||
|
medianNs: med,
|
||||||
|
runMediansNs: runMedians,
|
||||||
|
runSpreadPct: ((Math.max(...runMedians) - Math.min(...runMedians)) / med) * 100,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const loadavgAtEnd = os.loadavg();
|
||||||
|
writeFileSync(OUT, `${JSON.stringify({ meta: { ...meta, loadavgAtEnd }, summary, runs }, null, 2)}\n`);
|
||||||
|
|
||||||
|
console.log('| router | routes | workload | median ns/op | run medians (ns) | run spread |');
|
||||||
|
console.log('| --- | --- | --- | --- | --- | --- |');
|
||||||
|
for (const row of summary) {
|
||||||
|
const runsText = row.runMediansNs.map((n) => n.toFixed(1)).join(' / ');
|
||||||
|
console.log(
|
||||||
|
`| ${row.router} | ${row.routes} | ${row.workload} | ${row.medianNs.toFixed(1)} | ${runsText} | ${row.runSpreadPct.toFixed(1)}% |`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
console.log(
|
||||||
|
`\nload average: start ${meta.loadavgAtStart.map((n) => n.toFixed(2)).join(' ')}, end ${loadavgAtEnd.map((n) => n.toFixed(2)).join(' ')}`,
|
||||||
|
);
|
||||||
|
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/autocannon@^7.12.7",
|
||||||
"npm:@types/busboy@^1.5.4",
|
"npm:@types/busboy@^1.5.4",
|
||||||
"npm:@types/express@^5.0.6",
|
"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:@types/ws@^8.18.1",
|
||||||
"npm:autocannon@8",
|
"npm:autocannon@8",
|
||||||
"npm:busboy@^1.6.0",
|
"npm:busboy@^1.6.0",
|
||||||
@@ -35,7 +35,7 @@
|
|||||||
"npm:esbuild@0.27.2",
|
"npm:esbuild@0.27.2",
|
||||||
"npm:eslint@^9.39.5",
|
"npm:eslint@^9.39.5",
|
||||||
"npm:express@^5.2.1",
|
"npm:express@^5.2.1",
|
||||||
"npm:fastify@^5.11.0",
|
"npm:fastify@^5.12.5",
|
||||||
"npm:graphql@^16.9.0",
|
"npm:graphql@^16.9.0",
|
||||||
"npm:miniflare@^4.20260730.0",
|
"npm:miniflare@^4.20260730.0",
|
||||||
"npm:prettier@^3.9.6",
|
"npm:prettier@^3.9.6",
|
||||||
@@ -46,7 +46,7 @@
|
|||||||
"npm:typescript-eslint@^8.65.0",
|
"npm:typescript-eslint@^8.65.0",
|
||||||
"npm:typescript@^5.5.0",
|
"npm:typescript@^5.5.0",
|
||||||
"npm:vite@^6.4.3",
|
"npm:vite@^6.4.3",
|
||||||
"npm:vitest@^3.2.7",
|
"npm:vitest@^4.1.11",
|
||||||
"npm:ws@^8.21.1"
|
"npm:ws@^8.21.1"
|
||||||
],
|
],
|
||||||
"overrides": {
|
"overrides": {
|
||||||
@@ -56,7 +56,9 @@
|
|||||||
"uuid": "11.1.1"
|
"uuid": "11.1.1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"undici": "7.29.0"
|
"undici": "7.29.1",
|
||||||
|
"sharp": "0.35.5",
|
||||||
|
"fastify": "$fastify"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Generated
+389
-527
File diff suppressed because it is too large.
Load diff
+8
-5
@@ -26,7 +26,7 @@
|
|||||||
"node"
|
"node"
|
||||||
],
|
],
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=18"
|
"node": ">=22"
|
||||||
},
|
},
|
||||||
"publishConfig": {
|
"publishConfig": {
|
||||||
"access": "public"
|
"access": "public"
|
||||||
@@ -103,6 +103,7 @@
|
|||||||
"complexity:cyclomatic": "cyclomatic-complexity \"src/**/*.ts\" -tw 15 -te 25",
|
"complexity:cyclomatic": "cyclomatic-complexity \"src/**/*.ts\" -tw 15 -te 25",
|
||||||
"bench": "tsx bench/run.ts",
|
"bench": "tsx bench/run.ts",
|
||||||
"bench:compare": "tsx bench/compare.ts",
|
"bench:compare": "tsx bench/compare.ts",
|
||||||
|
"bench:lookup": "tsx bench/lookup.ts",
|
||||||
"prepublishOnly": "npm run lint && npm run complexity:check && npm run typecheck && npm test && npm run build",
|
"prepublishOnly": "npm run lint && npm run complexity:check && npm run typecheck && npm test && npm run build",
|
||||||
"prepare": "git config core.hooksPath .githooks || true"
|
"prepare": "git config core.hooksPath .githooks || true"
|
||||||
},
|
},
|
||||||
@@ -128,7 +129,9 @@
|
|||||||
"uuid": "11.1.1"
|
"uuid": "11.1.1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"undici": "7.29.0"
|
"undici": "7.29.1",
|
||||||
|
"sharp": "0.35.5",
|
||||||
|
"fastify": "$fastify"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.39.5",
|
"@eslint/js": "^9.39.5",
|
||||||
@@ -140,7 +143,7 @@
|
|||||||
"@types/autocannon": "^7.12.7",
|
"@types/autocannon": "^7.12.7",
|
||||||
"@types/busboy": "^1.5.4",
|
"@types/busboy": "^1.5.4",
|
||||||
"@types/express": "^5.0.6",
|
"@types/express": "^5.0.6",
|
||||||
"@types/node": "^18.19.0",
|
"@types/node": "^22.20.5",
|
||||||
"@types/ws": "^8.18.1",
|
"@types/ws": "^8.18.1",
|
||||||
"autocannon": "^8.0.0",
|
"autocannon": "^8.0.0",
|
||||||
"busboy": "^1.6.0",
|
"busboy": "^1.6.0",
|
||||||
@@ -148,7 +151,7 @@
|
|||||||
"eslint": "^9.39.5",
|
"eslint": "^9.39.5",
|
||||||
"esbuild": "0.27.2",
|
"esbuild": "0.27.2",
|
||||||
"express": "^5.2.1",
|
"express": "^5.2.1",
|
||||||
"fastify": "^5.11.0",
|
"fastify": "^5.12.5",
|
||||||
"graphql": "^16.9.0",
|
"graphql": "^16.9.0",
|
||||||
"miniflare": "^4.20260730.0",
|
"miniflare": "^4.20260730.0",
|
||||||
"prettier": "^3.9.6",
|
"prettier": "^3.9.6",
|
||||||
@@ -158,7 +161,7 @@
|
|||||||
"typescript": "^5.5.0",
|
"typescript": "^5.5.0",
|
||||||
"typescript-eslint": "^8.65.0",
|
"typescript-eslint": "^8.65.0",
|
||||||
"vite": "^6.4.3",
|
"vite": "^6.4.3",
|
||||||
"vitest": "^3.2.7",
|
"vitest": "^4.1.11",
|
||||||
"ws": "^8.21.1"
|
"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 { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http';
|
||||||
import type { HttpOptions } from '../http';
|
import type { HttpOptions } from '../http';
|
||||||
import { buildFetch } from '../http/web';
|
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 { isAsyncIterable } from '../channel';
|
||||||
import { JsonTransformer, type ErrorRenderer } from '../transformers';
|
import { JsonTransformer, type ErrorRenderer } from '../transformers';
|
||||||
import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin';
|
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 { RequestEnvelope, RouteEntry } from '../mesh/protocol';
|
||||||
import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types';
|
import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types';
|
||||||
import { inspectRoute, buildGraphView, explainRoute } from './introspect';
|
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';
|
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 bus = new Bus();
|
||||||
const logger = opts.logger ?? createDefaultLogger();
|
const logger = opts.logger ?? createDefaultLogger();
|
||||||
if (opts.logRequests) logRequests(bus, logger);
|
if (opts.logRequests) logRequests(bus, logger);
|
||||||
@@ -318,7 +330,7 @@ export function createApp(opts: {
|
|||||||
devRoutes,
|
devRoutes,
|
||||||
() => remoteRoutes,
|
() => 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 listen = async (port: number): Promise<http.Server> => {
|
||||||
const deps = pipelineDeps;
|
const deps = pipelineDeps;
|
||||||
@@ -387,7 +399,7 @@ export function createApp(opts: {
|
|||||||
return wrapped;
|
return wrapped;
|
||||||
};
|
};
|
||||||
|
|
||||||
return {
|
const app: App = {
|
||||||
listen,
|
listen,
|
||||||
close,
|
close,
|
||||||
handleSignals,
|
handleSignals,
|
||||||
@@ -405,6 +417,10 @@ export function createApp(opts: {
|
|||||||
bus,
|
bus,
|
||||||
logger,
|
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. */
|
/** Creates an empty {@link Registry} whose `setRunner` enforces globally-unique provider/step names. */
|
||||||
@@ -1275,22 +1291,30 @@ function buildAppUpgrade(
|
|||||||
streams: Set<() => void>,
|
streams: Set<() => void>,
|
||||||
ensureBooted: () => Promise<void>,
|
ensureBooted: () => Promise<void>,
|
||||||
getMeshControl: () => MeshControl | undefined,
|
getMeshControl: () => MeshControl | undefined,
|
||||||
|
limits?: RequestLimits,
|
||||||
): (request: WsRequest, socket: WsSocket) => Promise<void> {
|
): (request: WsRequest, socket: WsSocket) => Promise<void> {
|
||||||
let wsRoutes: WsRouteDef[] | undefined;
|
let wsRoutes: WsRouteDef[] | undefined;
|
||||||
|
|
||||||
return async (request: WsRequest, socket: WsSocket): Promise<void> => {
|
return async (request: WsRequest, socket: WsSocket): Promise<void> => {
|
||||||
// Subscribe to inbound BEFORE awaiting the boot. `channel` is fan-out: a frame pushed with no
|
// Bound and subscribe to inbound BEFORE awaiting the boot. `channel` is fan-out: a frame pushed
|
||||||
// subscriber is dropped, so anything the peer sends while providers are still booting would be
|
// with no subscriber is dropped, so anything the peer sends while providers are still booting
|
||||||
// lost. For the mesh control channel that is the `hello` itself — the handshake would hang
|
// would be lost. For the mesh control channel that is the `hello` itself — the handshake would
|
||||||
// until timeout against a teapot whose providers happened to boot slowly.
|
// hang until timeout against a teapot whose providers happened to boot slowly.
|
||||||
const frames = socket.inbound[Symbol.asyncIterator]();
|
const ready = boundInbound(socket, limits);
|
||||||
const ready: WsSocket = Object.create(socket, {
|
|
||||||
inbound: { value: { [Symbol.asyncIterator]: () => frames } },
|
|
||||||
}) as WsSocket;
|
|
||||||
|
|
||||||
await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted
|
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();
|
const meshControl = getMeshControl();
|
||||||
|
|
||||||
// The reserved mesh path, checked before route matching: this is what lets a teapot export
|
// The reserved mesh path, checked before route matching: this is what lets a teapot export
|
||||||
@@ -1489,8 +1513,8 @@ function closeApp(
|
|||||||
timeoutMs,
|
timeoutMs,
|
||||||
});
|
});
|
||||||
|
|
||||||
// closeAllConnections() requires Node >=18.2, same floor as closeIdleConnections()
|
// closeAllConnections() and closeIdleConnections() below both arrived in Node 18.2;
|
||||||
// below — `engines` in package.json only guarantees >=18, so this matters.
|
// `engines` guarantees >=22, so both are always present.
|
||||||
server.closeAllConnections();
|
server.closeAllConnections();
|
||||||
finish();
|
finish();
|
||||||
}, drainBudget);
|
}, drainBudget);
|
||||||
|
|||||||
+11
-1
@@ -1,9 +1,10 @@
|
|||||||
import { channel } from './channel';
|
import { channel } from './channel';
|
||||||
import type { Channel } from './channel';
|
import type { Channel } from './channel';
|
||||||
import type { App } from './app/types';
|
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 { decodeMessage, neutralSocket, toWsRequest, upgradeSafely } from './http/ws-adapter';
|
||||||
import { closeWithDeadline } from './http/shutdown';
|
import { closeWithDeadline } from './http/shutdown';
|
||||||
|
import { setPeer } from './http/peer';
|
||||||
|
|
||||||
// Minimal ambient for the Bun globals we use — avoids a @types/bun devDep.
|
// Minimal ambient for the Bun globals we use — avoids a @types/bun devDep.
|
||||||
// Mirrors the real Bun.serve / server.upgrade / ServerWebSocket signatures we call.
|
// Mirrors the real Bun.serve / server.upgrade / ServerWebSocket signatures we call.
|
||||||
@@ -15,6 +16,7 @@ interface BunServerWebSocket {
|
|||||||
terminate?(): void;
|
terminate?(): void;
|
||||||
}
|
}
|
||||||
interface BunWebSocketHandler {
|
interface BunWebSocketHandler {
|
||||||
|
maxPayloadLength?: number;
|
||||||
open?(ws: BunServerWebSocket): void;
|
open?(ws: BunServerWebSocket): void;
|
||||||
message(ws: BunServerWebSocket, message: string | Uint8Array): void;
|
message(ws: BunServerWebSocket, message: string | Uint8Array): void;
|
||||||
close?(ws: BunServerWebSocket, code: number, reason: string): 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 });
|
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);
|
return app.fetch(request);
|
||||||
},
|
},
|
||||||
websocket: {
|
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) {
|
open(ws) {
|
||||||
const { wsReq } = ws.data as BunConnData;
|
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';
|
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> {
|
interface Sub<T> {
|
||||||
iterator: AsyncIterator<T>;
|
iterator: AsyncIterator<T>;
|
||||||
push(value: T, cap: number): void;
|
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.
|
* 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).
|
* @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 cap = opts.buffer ?? Infinity;
|
||||||
const subs = new Set<Sub<T>>();
|
const subs = new Set<Omit<Sub<T>, 'iterator'>>();
|
||||||
let done = false;
|
let done = false;
|
||||||
let closedFlag = false;
|
let closedFlag = false;
|
||||||
|
|
||||||
@@ -117,5 +137,14 @@ export function channel<T>(opts: { buffer?: number } = {}): Channel<T> {
|
|||||||
subs.add(sub);
|
subs.add(sub);
|
||||||
return sub.iterator;
|
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 type { App } from './app/types';
|
||||||
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
|
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
|
||||||
import { closeWithDeadline } from './http/shutdown';
|
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)
|
// The project tsconfig's `lib` doesn't include `DOM`, so we ambient-declare just the shape of
|
||||||
// doesn't declare a global `WebSocket` either — so we ambient-declare just the shape we use.
|
// Deno's `WebSocket` we use rather than rely on whichever global `@types/node` happens to declare.
|
||||||
interface WebSocket extends EventfulSocket {
|
interface WebSocket extends EventfulSocket {
|
||||||
binaryType: string;
|
binaryType: string;
|
||||||
}
|
}
|
||||||
@@ -82,6 +83,9 @@ export async function serveDeno(app: App, options?: DenoServeOptions): Promise<D
|
|||||||
return response;
|
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);
|
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`.
|
* Reads the raw request body, enforcing `limit`.
|
||||||
*
|
*
|
||||||
* The adapter owns this and nothing else about the body, because enforcement is the one place the
|
* The adapter owns this and nothing else about the body, because getting the bytes is the one place
|
||||||
* runtimes legitimately differ: Node checks the running total as chunks arrive and can abort a
|
* the runtimes legitimately differ: Node iterates the socket, a fetch runtime reads `request.body`.
|
||||||
* 10 GB upload after 1 MB, while a fetch runtime has only `request.arrayBuffer()` and can check
|
* Both check the running total as chunks arrive and abort a 10 GB upload after 1 MB. Passing the
|
||||||
* `byteLength` after the fact. Passing the limit *in*, rather than measuring the returned buffer
|
* limit *in*, rather than measuring the returned buffer here, is what makes that incremental abort
|
||||||
* here, is what keeps Node's incremental abort — measuring afterwards would force it to buffer
|
* possible — measuring afterwards would force the reader to buffer without bound first.
|
||||||
* without bound first.
|
|
||||||
*
|
*
|
||||||
* The failure branch is opaque on purpose: Node answers an over-limit request with
|
* 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.
|
* `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>;
|
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). */
|
/** 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 };
|
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 { RouteDef, HttpOptions } from './types';
|
||||||
import type { StreamEncoder } from '../encoders';
|
import type { StreamEncoder } from '../encoders';
|
||||||
import type { Bus } from '../bus';
|
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:
|
* Node 18 lacked it, and this used to fall back to `node:crypto` there. That fallback went with the
|
||||||
* this file is the runtime-neutral core, and Deno, Bun and workerd all expose `crypto` without a
|
* Node 18 floor.
|
||||||
* compatibility flag, while `node:crypto` is unavailable to at least one of them.
|
|
||||||
*
|
|
||||||
* Node is the exception. The global arrived **unflagged in 19**, and `engines` promises `>=18`,
|
|
||||||
* where it does not exist at all — so the previous `declare const crypto` compiled cleanly and then
|
|
||||||
* threw `ReferenceError: crypto is not defined` on the first request of every Node 18 process. Only
|
|
||||||
* CI's Node 18 job caught it; every newer Node and every other runtime hides it, which is exactly
|
|
||||||
* why that job is pinned to the floor rather than to the current release.
|
|
||||||
*
|
|
||||||
* The fallback is reached only by a runtime that lacks the global, so workerd never evaluates it.
|
|
||||||
* It goes through {@link nodeRequire} rather than a bare `require`, which is what makes it work on
|
|
||||||
* every distribution of this package and not just the bundled ones.
|
|
||||||
*/
|
*/
|
||||||
const randomUUID: () => string = (() => {
|
const randomUUID = (): string => crypto.randomUUID();
|
||||||
const webCrypto = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;
|
|
||||||
if (typeof webCrypto?.randomUUID === 'function') return () => webCrypto.randomUUID!();
|
|
||||||
|
|
||||||
return nodeRequire<{ randomUUID: () => string }>('node:crypto').randomUUID;
|
|
||||||
})();
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A runtime-neutral inbound request.
|
* 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 type http from 'http';
|
||||||
import { HttpError } from '../signals';
|
import { HttpError } from '../signals';
|
||||||
|
import { declaresOverLimit } from './body';
|
||||||
|
|
||||||
/** Reads the full request body, enforcing the max-bytes ceiling (throws 413 if exceeded). */
|
/** Reads the full request body, enforcing the max-bytes ceiling (throws 413 if exceeded). */
|
||||||
export async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise<Buffer | undefined> {
|
export 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[] = [];
|
const chunks: Buffer[] = [];
|
||||||
let total = 0;
|
let total = 0;
|
||||||
|
|
||||||
|
|||||||
+43
-3
@@ -18,6 +18,7 @@ import {
|
|||||||
} from './core';
|
} from './core';
|
||||||
import type { BodyFailure, BodyReader } from './body';
|
import type { BodyFailure, BodyReader } from './body';
|
||||||
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
|
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
|
||||||
|
import type { Logger } from '../logger';
|
||||||
import { nodeRequire } from '../node-require';
|
import { nodeRequire } from '../node-require';
|
||||||
|
|
||||||
interface HandlerConfig {
|
interface HandlerConfig {
|
||||||
@@ -78,7 +79,7 @@ export function createHttpServer(
|
|||||||
server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000;
|
server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000;
|
||||||
server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000;
|
server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000;
|
||||||
server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_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;
|
return server;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,7 +97,14 @@ function createRequestHandler(cfg: HandlerConfig) {
|
|||||||
const readBody: BodyReader = (source, limit) => readRequestBytes(source, limit, opts);
|
const readBody: BodyReader = (source, limit) => readRequestBytes(source, limit, opts);
|
||||||
const gate = createRequestGate(opts?.limits?.maxConcurrentRequests);
|
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
|
// Install the security-header patch BEFORE any routing/response so every path
|
||||||
// (200, 404, error, stream) writes headers through the same patched writeHead.
|
// (200, 404, error, stream) writes headers through the same patched writeHead.
|
||||||
const secure = deriveSecure(req, trustProxy);
|
const secure = deriveSecure(req, trustProxy);
|
||||||
@@ -192,7 +200,39 @@ function createRequestHandler(cfg: HandlerConfig) {
|
|||||||
|
|
||||||
res.writeHead(result.outcome.status, result.outcome.headers);
|
res.writeHead(result.outcome.status, result.outcome.headers);
|
||||||
res.end(result.outcome.body);
|
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
|
headersTimeoutMs?: number; // default 10_000
|
||||||
keepAliveTimeoutMs?: number; // default 5_000
|
keepAliveTimeoutMs?: number; // default 5_000
|
||||||
maxParts?: number; // default 1000
|
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. */
|
/** Options controlling server construction: limits, TLS, proxy trust, security headers, CORS, and body parsing. */
|
||||||
|
|||||||
+66
-18
@@ -11,7 +11,8 @@ import {
|
|||||||
type Preflight,
|
type Preflight,
|
||||||
} from './core';
|
} from './core';
|
||||||
import { mergeInjectedHeaders } from './headers';
|
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 { HttpError } from '../signals';
|
||||||
import { renderError, type ErrorRequest } from '../transformers';
|
import { renderError, type ErrorRequest } from '../transformers';
|
||||||
import type { RouteDef, HttpOptions } from './types';
|
import type { RouteDef, HttpOptions } from './types';
|
||||||
@@ -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.
|
* 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
|
* Read from `request.body` chunk by chunk rather than through `arrayBuffer()`, which resolves with
|
||||||
* or not at all, so the limit can only be checked once the bytes are already in memory. That
|
* the whole body or not at all and so could only check the limit once every byte was in memory.
|
||||||
* difference is exactly why the limit is passed in rather than applied by the shared core.
|
* Deno, Bun, workerd and Node all expose `request.body` as a stream, so no runtime needs a branch.
|
||||||
*/
|
*/
|
||||||
function readFetchBytes(
|
function readFetchBytes(
|
||||||
source: unknown,
|
source: unknown,
|
||||||
@@ -110,8 +111,54 @@ function readFetchBytes(
|
|||||||
// Not `async`: a bodiless request answers without allocating a promise at all.
|
// Not `async`: a bodiless request answers without allocating a promise at all.
|
||||||
if (!request.body) return { bytes: undefined };
|
if (!request.body) return { bytes: undefined };
|
||||||
|
|
||||||
return request.arrayBuffer().then((arrayBuffer) => {
|
// A declared length over the limit is refused before a single chunk is pulled. Cancelling is best
|
||||||
if (arrayBuffer.byteLength > limit) {
|
// 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
// 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.
|
// a `url`/`headers` pair captured up-front cost more than the work it saved.
|
||||||
const url = new URL(request.url);
|
const url = new URL(request.url);
|
||||||
@@ -123,10 +170,6 @@ function readFetchBytes(
|
|||||||
return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError, opts?.logger) };
|
return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError, opts?.logger) };
|
||||||
}
|
}
|
||||||
|
|
||||||
return { bytes: arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer) };
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Whatever the host runtime's `Response` accepts as a body. Derived from the constructor rather
|
* Whatever the host runtime's `Response` accepts as a body. Derived from the constructor rather
|
||||||
* than written as `BodyInit`, because that name is not global under this `lib` (`es2020` plus
|
* than written as `BodyInit`, because that name is not global under this `lib` (`es2020` plus
|
||||||
@@ -176,6 +219,15 @@ function outcomeToResponse(result: HandleResult, bus?: Bus, correlation: Correla
|
|||||||
return new Response(body, { status: result.outcome.status, headers });
|
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:
|
* 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
|
* 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,
|
source: request,
|
||||||
secure,
|
secure,
|
||||||
// Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the
|
// Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the
|
||||||
// proxy is trusted, and take its first hop — an untrusted XFF is client-spoofable, and
|
// proxy is trusted, and take its first hop — an untrusted XFF is client-spoofable.
|
||||||
// there's no socket peer address to fall back to on the fetch path, so the untrusted case
|
// Otherwise the socket peer, which only the Deno and Bun adapters can supply; a bare
|
||||||
// is simply ''.
|
// `app.fetch` has none, so there the answer is still ''.
|
||||||
ip: opts?.trustProxy
|
ip: forwardedFor(headers, opts) || peerOf(request),
|
||||||
? String(headers['x-forwarded-for'] ?? '')
|
|
||||||
.split(',')[0]
|
|
||||||
.trim()
|
|
||||||
: '',
|
|
||||||
},
|
},
|
||||||
// Already computed above for the shed-503 path; handing it down keeps `cors.origins` to
|
// Already computed above for the shed-503 path; handing it down keeps `cors.origins` to
|
||||||
// one call per request.
|
// 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 { App } from '../app/types';
|
||||||
import type { WsRequest, WsSocket } from './ws-core';
|
import type { WsRequest, WsSocket } from './ws-core';
|
||||||
import { nodeRequire } from '../node-require';
|
import { nodeRequire } from '../node-require';
|
||||||
@@ -10,6 +10,7 @@ import { nodeRequire } from '../node-require';
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
const decoder = new TextDecoder();
|
const decoder = new TextDecoder();
|
||||||
|
const CONNECTING = 0; // WebSocket.CONNECTING
|
||||||
const OPEN = 1; // WebSocket.OPEN — same constant in every runtime; avoids a per-runtime ambient
|
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()). */
|
/** 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();
|
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(
|
export function neutralSocket(
|
||||||
host: Pick<EventfulSocket, 'readyState' | 'send' | 'close'> & { terminate?(): void },
|
host: Pick<EventfulSocket, 'readyState' | 'send' | 'close'> & { terminate?(): void },
|
||||||
inbound: ReturnType<typeof channel<unknown>>,
|
inbound: Channel<unknown>,
|
||||||
ac: AbortController,
|
ac: AbortController,
|
||||||
): WsSocket {
|
): WsSocket {
|
||||||
return {
|
return {
|
||||||
@@ -112,8 +124,10 @@ export function neutralSocket(
|
|||||||
export type SocketCtor = new (url: string) => EventfulSocket;
|
export type SocketCtor = new (url: string) => EventfulSocket;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The WebSocket client implementation: the platform global where it exists (Deno, Bun, and
|
* The WebSocket client implementation: the platform global where it exists, else the `ws`
|
||||||
* Node >= 22), else the `ws` optional peer — Node 18-21, our declared floor, has no global.
|
* 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,
|
* 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
|
* 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 { isHttpError } from '../signals';
|
||||||
|
import { CHANNEL_TAP, type TappableChannel } from '../channel';
|
||||||
import type { Bus } from '../bus';
|
import type { Bus } from '../bus';
|
||||||
import { correlateRequest } from './core';
|
import { correlateRequest } from './core';
|
||||||
import { matchPattern } from './router';
|
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). */
|
/** Neutral, runtime-free WebSocket request context (replaces the raw Node req). */
|
||||||
export interface WsRequest {
|
export interface WsRequest {
|
||||||
@@ -22,6 +23,219 @@ export interface WsSocket {
|
|||||||
terminate(): void;
|
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. */
|
/** Finds the first ws route whose pattern matches `path`, capturing its params. */
|
||||||
export function matchWsRoute(
|
export function matchWsRoute(
|
||||||
wsRoutes: WsRouteDef[],
|
wsRoutes: WsRouteDef[],
|
||||||
|
|||||||
+64
-14
@@ -1,8 +1,17 @@
|
|||||||
import type http from 'http';
|
import type http from 'http';
|
||||||
import { channel } from '../channel';
|
import { channel } from '../channel';
|
||||||
import type { Bus } from '../bus';
|
import type { Bus } from '../bus';
|
||||||
import { runWsConnection, matchWsRoute, trackUntil, type WsSocket, type WsRequest } from './ws-core';
|
import {
|
||||||
import type { WsRouteDef, MeshControl } from './types';
|
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';
|
import { nodeRequire } from '../node-require';
|
||||||
|
|
||||||
/** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */
|
/** 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. */
|
/** Writes a bodyless HTTP status to the raw socket and destroys it. */
|
||||||
function reject501(socket: any): void {
|
function rejectUpgrade(socket: any, status: number, text: string): void {
|
||||||
socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n');
|
socket.write(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
|
||||||
socket.destroy();
|
socket.destroy();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -31,11 +40,12 @@ function handleMeshUpgrade(
|
|||||||
socket: any,
|
socket: any,
|
||||||
head: Buffer,
|
head: Buffer,
|
||||||
streams?: Set<() => void>,
|
streams?: Set<() => void>,
|
||||||
|
limits?: RequestLimits,
|
||||||
): boolean {
|
): boolean {
|
||||||
if (path !== meshControl.path) return false;
|
if (path !== meshControl.path) return false;
|
||||||
|
|
||||||
if (!wss) {
|
if (!wss) {
|
||||||
reject501(socket);
|
rejectUpgrade(socket, 501, 'Not Implemented');
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -45,7 +55,7 @@ function handleMeshUpgrade(
|
|||||||
// an untracked control channel leaves the teapot's server.close() waiting on it forever.
|
// 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.
|
// serveFrames swallows its own failures, so the floating promise cannot reject.
|
||||||
wss.handleUpgrade(req, socket, head, (ws: any) => {
|
wss.handleUpgrade(req, socket, head, (ws: any) => {
|
||||||
const neutral = nodeSocket(ws);
|
const neutral = boundInbound(nodeSocket(ws), limits);
|
||||||
|
|
||||||
void trackUntil(neutral, meshControl.handle(neutral), streams);
|
void trackUntil(neutral, meshControl.handle(neutral), streams);
|
||||||
});
|
});
|
||||||
@@ -97,29 +107,69 @@ export function attachWs(
|
|||||||
bus?: Bus,
|
bus?: Bus,
|
||||||
meshControl?: MeshControl,
|
meshControl?: MeshControl,
|
||||||
streams?: Set<() => void>,
|
streams?: Set<() => void>,
|
||||||
|
limits?: RequestLimits,
|
||||||
): void {
|
): void {
|
||||||
if (wsRoutes.length === 0 && !meshControl) return;
|
if (wsRoutes.length === 0 && !meshControl) return;
|
||||||
const WebSocketServer = loadWss();
|
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) => {
|
server.on('upgrade', (req, socket, head) => {
|
||||||
const path = (req.url ?? '/').split('?')[0];
|
// A peer that resets mid-rejection must not raise an unhandled 'error' on a socket nobody
|
||||||
|
// else is listening to yet: that is as fatal as a throw.
|
||||||
|
socket.on('error', () => {});
|
||||||
|
|
||||||
if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head, streams)) return;
|
// Nothing thrown in here may escape. This is a raw EventEmitter listener, so a throw is an
|
||||||
|
// uncaught exception that takes the whole process down, not a 500 for one client.
|
||||||
|
try {
|
||||||
|
routeUpgrade({ wss, wsRoutes, bus, meshControl, streams, limits }, req, socket, head);
|
||||||
|
} catch {
|
||||||
|
if (socket.writable) rejectUpgrade(socket, 500, 'Internal Server Error');
|
||||||
|
else socket.destroy();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What every upgrade on one server shares. */
|
||||||
|
interface UpgradeEnv {
|
||||||
|
wss: any;
|
||||||
|
wsRoutes: WsRouteDef[];
|
||||||
|
bus?: Bus;
|
||||||
|
meshControl?: MeshControl;
|
||||||
|
streams?: Set<() => void>;
|
||||||
|
limits?: RequestLimits;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Routes one upgrade: validates the path the way HTTP does, then mesh control, then the ws route table. */
|
||||||
|
function routeUpgrade(env: UpgradeEnv, req: http.IncomingMessage, socket: any, head: Buffer): void {
|
||||||
|
const { wss, 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);
|
const route = matchWsRoute(wsRoutes, path);
|
||||||
|
|
||||||
if (!route) {
|
if (!route) {
|
||||||
socket.destroy();
|
rejectUpgrade(socket, 404, 'Not Found');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!wss) {
|
if (!wss) {
|
||||||
reject501(socket);
|
rejectUpgrade(socket, 501, 'Not Implemented');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
wss.handleUpgrade(req, socket, head, (ws: any) => {
|
wss.handleUpgrade(req, socket, head, (ws: any) => {
|
||||||
void runWsConnection(nodeSocket(ws), nodeWsRequest(req), route, bus, streams);
|
void runWsConnection(boundInbound(nodeSocket(ws), limits), nodeWsRequest(req), route, bus, streams);
|
||||||
});
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
+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. */
|
/** 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>;
|
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
|
* 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 {
|
export function buildStaticResolver(root: string | true): StaticResolver {
|
||||||
let fs: typeof import('node:fs');
|
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);
|
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) => {
|
return async (urlPath) => {
|
||||||
let rel: string;
|
let rel: string;
|
||||||
|
|
||||||
@@ -118,13 +161,13 @@ export function buildStaticResolver(root: string | true): StaticResolver {
|
|||||||
const full = nodePath.resolve(abs, '.' + (rel.startsWith('/') ? rel : '/' + rel));
|
const full = nodePath.resolve(abs, '.' + (rel.startsWith('/') ? rel : '/' + rel));
|
||||||
if (full !== abs && !full.startsWith(abs + nodePath.sep)) return undefined; // traversal guard
|
if (full !== abs && !full.startsWith(abs + nodePath.sep)) return undefined; // traversal guard
|
||||||
|
|
||||||
|
const rootReal = await resolveRoot();
|
||||||
|
if (!rootReal) return undefined;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const stat = await fs.promises.stat(full);
|
return await readConfined(fs, nodePath, rootReal, full);
|
||||||
const target = stat.isDirectory() ? nodePath.join(full, 'index.html') : full;
|
|
||||||
const body = await fs.promises.readFile(target);
|
|
||||||
return { body, contentType: contentTypeFor(nodePath.extname(target)) };
|
|
||||||
} catch {
|
} 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 {}
|
class M {}
|
||||||
const app = createApp({ modules: [M] });
|
const app = createApp({ modules: [M] });
|
||||||
|
|
||||||
@@ -96,4 +105,18 @@ describe('app.upgrade', () => {
|
|||||||
await app.upgrade(req, socket);
|
await app.upgrade(req, socket);
|
||||||
expect(closedCode).toBe(1008);
|
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,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}`;
|
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] })
|
@Module({ mountpoint: '/', controllers: [Rt] })
|
||||||
class M {}
|
class M {}
|
||||||
@@ -47,3 +63,77 @@ test('serveBun: HTTP + WebSocket round-trip', async () => {
|
|||||||
server.stop(true);
|
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');
|
||||||
|
});
|
||||||
@@ -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' });
|
assertEquals(await res.json(), { name: 'joe', filename: 'p.png' });
|
||||||
await app.close();
|
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}`;
|
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] })
|
@Module({ mountpoint: '/', controllers: [Rt] })
|
||||||
@@ -69,3 +85,99 @@ Deno.test('serveDeno: HTTP + WebSocket round-trip through the graph', async () =
|
|||||||
await server.shutdown();
|
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();
|
||||||
|
}
|
||||||
|
});
|
||||||
+75
-1
@@ -66,6 +66,33 @@ async function main() {
|
|||||||
assert.equal(httpRes.status, 200);
|
assert.equal(httpRes.status, 200);
|
||||||
assert.deepEqual(await httpRes.json(), { ok: true });
|
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
|
// WebSocket
|
||||||
const wsRes = await mf.dispatchFetch('http://localhost/rt/echo', {
|
const wsRes = await mf.dispatchFetch('http://localhost/rt/echo', {
|
||||||
headers: { Upgrade: 'websocket' },
|
headers: { Upgrade: 'websocket' },
|
||||||
@@ -84,12 +111,59 @@ async function main() {
|
|||||||
});
|
});
|
||||||
assert.equal(got, 'echo:hi');
|
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 {
|
} finally {
|
||||||
await mf.dispose();
|
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().catch((err) => {
|
main().catch((err) => {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
|
|||||||
+32
-2
@@ -1,7 +1,7 @@
|
|||||||
// Worker entry for the real workerd (Miniflare) integration test.
|
// Worker entry for the real workerd (Miniflare) integration test.
|
||||||
// Mirrors test/deno/ws.test.ts's graph so HTTP + WebSocket behavior is proven
|
// 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).
|
// 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';
|
import { edgeHandler } from '../../src/edge';
|
||||||
|
|
||||||
@Route('/rt')
|
@Route('/rt')
|
||||||
@@ -11,17 +11,47 @@ class Rt {
|
|||||||
return { ok: true };
|
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')
|
@Ws('/echo')
|
||||||
echo(@ctx() { inbound }: any) {
|
echo(@ctx() { inbound }: any) {
|
||||||
return (async function* () {
|
return (async function* () {
|
||||||
for await (const msg of inbound) yield `echo:${msg}`;
|
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] })
|
@Module({ mountpoint: '/', controllers: [Rt] })
|
||||||
class M {}
|
class M {}
|
||||||
|
|
||||||
const app = createApp({ modules: [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 { 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' })
|
@Provider({ provides: 'store' })
|
||||||
class Store {
|
class Store {
|
||||||
@@ -108,6 +110,57 @@ describe('app.fetch trustProxy gates x-forwarded-for', () => {
|
|||||||
);
|
);
|
||||||
expect(await res.json()).toEqual({ ip: '' });
|
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', () => {
|
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();
|
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 () => {
|
it('sets the configured server timeouts and connection limit', async () => {
|
||||||
const server = createHttpServer([], [], undefined, undefined,
|
const server = createHttpServer([], [], undefined, undefined,
|
||||||
{ limits: { maxConnections: 2468, requestTimeoutMs: 12345, headersTimeoutMs: 6789, keepAliveTimeoutMs: 4321 } });
|
{ 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
|
* 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
|
* list: it is the fallback for a Node run with the global WebSocket switched off, and every
|
||||||
* only one ever covered — the fallback would rot unnoticed until someone ran the declared floor.
|
* supported Node has the global, so it would otherwise never be covered and rot unnoticed.
|
||||||
*/
|
*/
|
||||||
const platform = (globalThis as { WebSocket?: SocketCtor }).WebSocket;
|
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]);
|
if (platform) CTORS.push(['the platform global WebSocket', platform]);
|
||||||
|
|
||||||
describe('WebSocket client implementations', () => {
|
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';
|
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;
|
let app: any;
|
||||||
afterEach(async () => { await app?.close(); });
|
afterEach(async () => { await app?.close(); });
|
||||||
|
|
||||||
@@ -88,3 +102,63 @@ describe('bodyDuplicates', () => {
|
|||||||
expect(await post('/b')).toEqual({ x: ['1', '2'] });
|
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,52 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
|
The performance half of the baseline is in `bench/lookup.ts` and `bench/baseline/router-ed47836/`.
|
||||||
@@ -0,0 +1,234 @@
|
|||||||
|
/**
|
||||||
|
* 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 'reflect-metadata';
|
||||||
|
import http from 'http';
|
||||||
|
import type { AddressInfo } from 'net';
|
||||||
|
import { describe, it, beforeAll, afterAll } from 'vitest';
|
||||||
|
import { createApp, Route, Get, Head, Post, Put, Patch, Delete, Options, Sse, Module, param } from '../../src/index';
|
||||||
|
import type { App } from '../../src/app/types';
|
||||||
|
import { frozen, expectFrozenEqual } from './frozen';
|
||||||
|
|
||||||
|
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] })
|
||||||
|
class ParityHttpModule {}
|
||||||
|
|
||||||
|
type Req = [method: string, raw: string];
|
||||||
|
|
||||||
|
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']);
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Observed {
|
||||||
|
method: string;
|
||||||
|
raw: string;
|
||||||
|
status: number;
|
||||||
|
headers: Record<string, string>;
|
||||||
|
body: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
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() };
|
||||||
|
}
|
||||||
|
|
||||||
|
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');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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,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,172 @@
|
|||||||
|
/**
|
||||||
|
* 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 { describe, it, expect, beforeAll } from 'vitest';
|
||||||
|
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 { 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';
|
||||||
|
|
||||||
|
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.
|
||||||
|
// Paths are fed already normalized, as both upgrade adapters do since #117.
|
||||||
|
type WsDecl = WsRouteDef & { id: string };
|
||||||
|
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 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')] },
|
||||||
|
];
|
||||||
|
const paths = ['/ws/static', '/ws/x', '/ws/a%20b', '/ws', '/ws/x/y', '/w', '/w/a%2Fb/c', '/nope'];
|
||||||
|
|
||||||
|
const run = (matchWs: WsMatcher) =>
|
||||||
|
scenarios.map(({ id, routes }) => ({
|
||||||
|
id,
|
||||||
|
declarations: routes.map((route) => ({ id: route.id, pattern: route.pattern })),
|
||||||
|
outcomes: paths.map((path) => {
|
||||||
|
const hit = matchWs(routes, path);
|
||||||
|
return { path, route: hit ? { id: (hit.def as WsDecl).id, params: hit.params } : null };
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
it('oracle and live matchWsRoute equal the frozen capture', async () => {
|
||||||
|
const expected = await frozen('matcher-ws', () => run(liveMatchWsRoute));
|
||||||
|
expectFrozenEqual(run(oracle.matchWsRoute), expected, 'ws oracle');
|
||||||
|
expectFrozenEqual(run(liveMatchWsRoute), expected, 'ws live');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,472 @@
|
|||||||
|
/**
|
||||||
|
* FROZEN ORACLE — the pre-radix HTTP and WebSocket matcher, copied verbatim from `@green-tea/core`
|
||||||
|
* at ed47836c9820c47bf4ed5e902d91e019abdb110a (`src/http/router.ts`, minus `parseQuery`, plus
|
||||||
|
* `matchWsRoute` from `src/http/ws-core.ts`).
|
||||||
|
*
|
||||||
|
* DO NOT EDIT THIS FILE TO FIT A NEW IMPLEMENTATION. It is the reference the radix index (CARD-07,
|
||||||
|
* #109) is judged against: if the live matcher disagrees with it, the live matcher is what changed.
|
||||||
|
* A deliberate compatibility change needs its own maintainer approval and a new pinned oracle,
|
||||||
|
* never an edit here. Test-only: nothing under `src/` may import it.
|
||||||
|
*
|
||||||
|
* The only departures from the source are mechanical: the route types are declared locally (so a
|
||||||
|
* later change to `src/http/types.ts` cannot alter what this file compiles to), and the module-level
|
||||||
|
* caches are this file's own, so the oracle never shares compiled state with the live matcher.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** The fields of `RouteDef` the matcher reads. A live `RouteDef` is assignable to it. */
|
||||||
|
export interface OracleRoute {
|
||||||
|
method: string;
|
||||||
|
pattern: string;
|
||||||
|
transport: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The fields of `WsRouteDef` the WS matcher reads. */
|
||||||
|
export interface OracleWsRoute {
|
||||||
|
pattern: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MatchedRoute {
|
||||||
|
params: Record<string, string>;
|
||||||
|
def: OracleRoute;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CompiledSegment =
|
||||||
|
| { kind: 'static'; value: string }
|
||||||
|
| { kind: 'param'; name: string; constraint?: RegExp; constraintSource?: string }
|
||||||
|
| { kind: 'catchAll'; name: string };
|
||||||
|
|
||||||
|
/** Parsed route pattern reused by matching, specificity, ambiguity checks, and OpenAPI projection. */
|
||||||
|
export interface CompiledPattern {
|
||||||
|
source: string;
|
||||||
|
normalized: string;
|
||||||
|
shape: string;
|
||||||
|
segments: CompiledSegment[];
|
||||||
|
kinds: number[];
|
||||||
|
catchAll: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const compiledCache = new Map<string, CompiledPattern>();
|
||||||
|
const PARAM_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
||||||
|
const MAX_CONSTRAINT_LENGTH = 128;
|
||||||
|
|
||||||
|
/** Request-path syntax error. Adapters translate this to the standard 400 response envelope. */
|
||||||
|
export class InvalidRequestPathError extends Error {
|
||||||
|
constructor(message: string) {
|
||||||
|
super(message);
|
||||||
|
this.name = 'InvalidRequestPathError';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ConstraintToken {
|
||||||
|
length: number;
|
||||||
|
unbounded: boolean;
|
||||||
|
separator: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reads one atom plus its optional quantifier from the deliberately small safe-regex subset. */
|
||||||
|
function readConstraintToken(source: string): ConstraintToken | undefined {
|
||||||
|
const atom = /^(?:\\[dDsSwW]|\\[.\-_/]|[A-Za-z0-9_.-]|\[(?:\\.|[^\]\\])+\])/u.exec(source)?.[0];
|
||||||
|
if (!atom) return undefined;
|
||||||
|
|
||||||
|
const rest = source.slice(atom.length);
|
||||||
|
const quantifier = /^(?:[+*?]|\{\d+(?:,\d*)?\})/u.exec(rest)?.[0] ?? '';
|
||||||
|
if (quantifier.startsWith('{')) assertBoundedQuantifier(quantifier);
|
||||||
|
|
||||||
|
return {
|
||||||
|
length: atom.length + quantifier.length,
|
||||||
|
unbounded: quantifier === '+' || quantifier === '*' || quantifier.endsWith(',}'),
|
||||||
|
separator: quantifier === '' && /^(?:\\[.\-_/]|[._-])$/u.test(atom),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Rejects nonsensical or excessively large counted quantifiers before RegExp compilation. */
|
||||||
|
function assertBoundedQuantifier(quantifier: string): void {
|
||||||
|
const [minText, maxText] = quantifier.slice(1, -1).split(',');
|
||||||
|
const min = Number(minText);
|
||||||
|
const max = maxText === undefined || maxText === '' ? min : Number(maxText);
|
||||||
|
if (min > max || max > 2048) throw new Error(`unsafe route constraint: invalid quantifier '${quantifier}'`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Accepts only a linear, group-free regex subset to keep attacker-controlled segments ReDoS-safe. */
|
||||||
|
function assertSafeConstraint(source: string): void {
|
||||||
|
if (!source || source.length > MAX_CONSTRAINT_LENGTH)
|
||||||
|
throw new Error('unsafe route constraint: expression must contain 1-128 characters');
|
||||||
|
|
||||||
|
let offset = 0;
|
||||||
|
let previousUnbounded = false;
|
||||||
|
|
||||||
|
while (offset < source.length) {
|
||||||
|
const token = readConstraintToken(source.slice(offset));
|
||||||
|
if (!token) throw new Error(`unsafe route constraint: unsupported expression '${source}'`);
|
||||||
|
if (previousUnbounded && token.unbounded)
|
||||||
|
throw new Error(`unsafe route constraint: adjacent unbounded quantifiers in '${source}'`);
|
||||||
|
previousUnbounded = token.separator ? false : token.unbounded;
|
||||||
|
offset += token.length;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertParamName(name: string, pattern: string): void {
|
||||||
|
if (!PARAM_NAME.test(name)) throw new Error(`invalid route pattern '${pattern}': invalid parameter name '${name}'`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function compileParam(segment: string, pattern: string): Extract<CompiledSegment, { kind: 'param' }> {
|
||||||
|
const constraintStart = segment.indexOf('(');
|
||||||
|
|
||||||
|
if (constraintStart < 0) {
|
||||||
|
const name = segment.slice(1);
|
||||||
|
assertParamName(name, pattern);
|
||||||
|
return { kind: 'param', name };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!segment.endsWith(')')) throw new Error(`invalid route pattern '${pattern}': malformed constraint`);
|
||||||
|
const name = segment.slice(1, constraintStart);
|
||||||
|
const constraintSource = segment.slice(constraintStart + 1, -1);
|
||||||
|
assertParamName(name, pattern);
|
||||||
|
assertSafeConstraint(constraintSource);
|
||||||
|
return {
|
||||||
|
kind: 'param',
|
||||||
|
name,
|
||||||
|
constraintSource,
|
||||||
|
constraint: new RegExp(`^(?:${constraintSource})$`, 'u'),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function compileSegments(pattern: string, rawSegments: string[]): CompiledSegment[] {
|
||||||
|
const names = new Set<string>();
|
||||||
|
const compiled: CompiledSegment[] = [];
|
||||||
|
|
||||||
|
for (let index = 0; index < rawSegments.length; index++) {
|
||||||
|
const raw = rawSegments[index];
|
||||||
|
let segment: CompiledSegment;
|
||||||
|
|
||||||
|
if (raw.startsWith(':') && raw.endsWith('*')) {
|
||||||
|
const name = raw.slice(1, -1);
|
||||||
|
assertParamName(name, pattern);
|
||||||
|
if (index !== rawSegments.length - 1)
|
||||||
|
throw new Error(`invalid route pattern '${pattern}': catch-all must be the final segment`);
|
||||||
|
segment = { kind: 'catchAll', name };
|
||||||
|
} else if (raw.startsWith(':')) {
|
||||||
|
segment = compileParam(raw, pattern);
|
||||||
|
} else {
|
||||||
|
segment = { kind: 'static', value: raw };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (segment.kind !== 'static') {
|
||||||
|
if (names.has(segment.name))
|
||||||
|
throw new Error(`invalid route pattern '${pattern}': duplicate parameter '${segment.name}'`);
|
||||||
|
names.add(segment.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
compiled.push(segment);
|
||||||
|
}
|
||||||
|
|
||||||
|
return compiled;
|
||||||
|
}
|
||||||
|
|
||||||
|
function segmentShape(segment: CompiledSegment): string {
|
||||||
|
if (segment.kind === 'static') return `s:${segment.value}`;
|
||||||
|
if (segment.kind === 'catchAll') return 'c';
|
||||||
|
return segment.constraintSource ? `r:${segment.constraintSource}` : 'p';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Compiles and validates one route pattern. Results are cached by source string. */
|
||||||
|
export function compilePattern(pattern: string): CompiledPattern {
|
||||||
|
const cached = compiledCache.get(pattern);
|
||||||
|
if (cached) return cached;
|
||||||
|
if (!pattern.startsWith('/')) throw new Error(`invalid route pattern '${pattern}': pattern must start with '/'`);
|
||||||
|
if (pattern.includes('//')) throw new Error(`invalid route pattern '${pattern}': repeated slash`);
|
||||||
|
|
||||||
|
const normalized = pattern.length > 1 && pattern.endsWith('/') ? pattern.slice(0, -1) : pattern;
|
||||||
|
const rawSegments = normalized === '/' ? [] : normalized.split('/').slice(1);
|
||||||
|
const segments = compileSegments(pattern, rawSegments);
|
||||||
|
const compiled: CompiledPattern = {
|
||||||
|
source: pattern,
|
||||||
|
normalized,
|
||||||
|
shape: segments.map(segmentShape).join('/'),
|
||||||
|
segments,
|
||||||
|
kinds: segments
|
||||||
|
.filter((segment) => segment.kind !== 'catchAll')
|
||||||
|
.map((segment) => (segment.kind === 'static' ? 3 : segment.constraint ? 2 : 1)),
|
||||||
|
catchAll: segments.at(-1)?.kind === 'catchAll',
|
||||||
|
};
|
||||||
|
compiledCache.set(pattern, compiled);
|
||||||
|
return compiled;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Matches a `.` or `..` segment, percent-encoded or not, sitting alone between separators. */
|
||||||
|
const DOT_SEGMENT = /(?:^|\/)(?:\.|%2e){1,2}(?:\/|$)/i;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Classifies one path segment as `.`, `..`, or neither.
|
||||||
|
*
|
||||||
|
* `%2e` is a dot as far as the URL spec is concerned, so `/a/%2e%2e/b` and `/a/../b` are the same
|
||||||
|
* path. Skipping the encoded spelling would leave the encoded form as a way to reach a route the
|
||||||
|
* plain form resolves away from.
|
||||||
|
*/
|
||||||
|
function dotSegment(segment: string): '.' | '..' | undefined {
|
||||||
|
if (segment === '.' || segment === '..') return segment;
|
||||||
|
if (segment.length > 6 || !segment.includes('%')) return undefined;
|
||||||
|
const decoded = segment.toLowerCase().replace(/%2e/g, '.');
|
||||||
|
return decoded === '.' || decoded === '..' ? decoded : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves `.` and `..` segments, the way RFC 3986 §5.2.4 and the WHATWG URL parser both do.
|
||||||
|
*
|
||||||
|
* This runs for the *Node* adapter's benefit. Every fetch-based runtime — Deno, Bun, workerd —
|
||||||
|
* resolves dot segments inside the `Request` constructor, before green-tea is handed anything:
|
||||||
|
* `new Request('http://x/public/../admin').url` is already `http://x/admin`. The raw target is
|
||||||
|
* simply not recoverable there, so rejecting dot segments outright — which is what this module
|
||||||
|
* does for `//`, and would be the stricter policy — cannot be implemented on three of the four
|
||||||
|
* runtimes. Resolving is the only rule all four can agree on.
|
||||||
|
*
|
||||||
|
* Before this, the same bytes on the wire routed differently per runtime: `GET /public/../admin`
|
||||||
|
* reached a `/admin` route under Deno/Bun/edge and 404'd under Node.
|
||||||
|
*/
|
||||||
|
function resolveDotSegments(path: string): string {
|
||||||
|
const out: string[] = [];
|
||||||
|
|
||||||
|
for (const segment of path.split('/').slice(1)) {
|
||||||
|
const dots = dotSegment(segment);
|
||||||
|
if (dots === '.') continue;
|
||||||
|
|
||||||
|
if (dots === '..') {
|
||||||
|
out.pop();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
out.push(segment);
|
||||||
|
}
|
||||||
|
|
||||||
|
return `/${out.join('/')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Applies the public trailing-slash policy and validates every segment's percent encoding. */
|
||||||
|
export function normalizeRequestPath(path: string): string {
|
||||||
|
if (!path.startsWith('/')) throw new InvalidRequestPathError('invalid request path: path must start with slash');
|
||||||
|
if (path.includes('//')) throw new InvalidRequestPathError('invalid request path: repeated slash');
|
||||||
|
|
||||||
|
// Two `indexOf` scans gate the regex, and the regex gates the split. A path with no `.` and no
|
||||||
|
// `%` at all — which is most of them — pays only the scans.
|
||||||
|
const resolved =
|
||||||
|
(path.includes('.') || path.includes('%')) && DOT_SEGMENT.test(path) ? resolveDotSegments(path) : path;
|
||||||
|
const normalized = resolved.length > 1 && resolved.endsWith('/') ? resolved.slice(0, -1) : resolved;
|
||||||
|
|
||||||
|
// Validation only — the decoded value is deliberately discarded, matching is done on the raw
|
||||||
|
// path. So the work is skipped entirely unless there is something to validate.
|
||||||
|
//
|
||||||
|
// This used to split the path and call `decodeURIComponent` per segment, on every request, and
|
||||||
|
// throw all of it away. Measured on this path: 95.8 ns for `/hello`, 342.7 ns for a six-segment
|
||||||
|
// route — around 8% of a whole request, spent proving that a string nobody decodes could be
|
||||||
|
// decoded. The guard below is 15.7 ns and 6.7 ns for the same two paths.
|
||||||
|
//
|
||||||
|
// One call on the whole string rather than per segment is the same check: `decodeURIComponent`
|
||||||
|
// throws on the first malformed `%` sequence wherever it appears, and a `%2F` inside a segment
|
||||||
|
// decodes fine either way. Only the throw matters here, never the result.
|
||||||
|
if (normalized.includes('%')) {
|
||||||
|
try {
|
||||||
|
decodeURIComponent(normalized);
|
||||||
|
} catch {
|
||||||
|
throw new InvalidRequestPathError('invalid request path: malformed path encoding');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return normalized;
|
||||||
|
}
|
||||||
|
|
||||||
|
function decodeSegment(value: string): string {
|
||||||
|
// Same gate `normalizeRequestPath` uses on the whole path, for the same reason: a segment with no
|
||||||
|
// `%` decodes to itself, so the call only ever proves that. Most segments have no `%`, and this
|
||||||
|
// runs for every param segment of every candidate route the scan reaches.
|
||||||
|
return value.includes('%') ? decodeURIComponent(value) : value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Splits a request path into its non-empty segments.
|
||||||
|
*
|
||||||
|
* Called once per request by the scanning functions below, not once per candidate route. It used to
|
||||||
|
* live inside {@link matchCompiled}, which meant `split` + `filter` — two allocations — ran for every
|
||||||
|
* registered route on every request, always producing the same array.
|
||||||
|
*/
|
||||||
|
function splitPath(path: string): string[] {
|
||||||
|
return path.split('/').filter(Boolean);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Matches one compiled pattern against a request's segments.
|
||||||
|
*
|
||||||
|
* `decoded` memoizes per request, not per candidate: a scan reaching the same parameter position on
|
||||||
|
* several routes decoded the same string once per route. Position is all decoding depends on, so one
|
||||||
|
* array shared across the scan is the same answer for less work.
|
||||||
|
*/
|
||||||
|
function matchCompiled(
|
||||||
|
compiled: CompiledPattern,
|
||||||
|
pathSegs: string[],
|
||||||
|
decoded?: Array<string | undefined>,
|
||||||
|
): Record<string, string> | undefined {
|
||||||
|
const params: Record<string, string> = {};
|
||||||
|
|
||||||
|
for (let index = 0; index < compiled.segments.length; index++) {
|
||||||
|
const segment = compiled.segments[index];
|
||||||
|
|
||||||
|
if (segment.kind === 'catchAll') {
|
||||||
|
params[segment.name] = pathSegs.slice(index).map(decodeSegment).join('/');
|
||||||
|
return params;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (index >= pathSegs.length) return undefined;
|
||||||
|
|
||||||
|
if (segment.kind === 'static') {
|
||||||
|
if (segment.value !== pathSegs[index]) return undefined;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const value = decoded ? (decoded[index] ??= decodeSegment(pathSegs[index])) : decodeSegment(pathSegs[index]);
|
||||||
|
if (segment.constraint && !segment.constraint.test(value)) return undefined;
|
||||||
|
params[segment.name] = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
return compiled.segments.length === pathSegs.length ? params : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Matches a compiled segment pattern and returns its decoded parameters. */
|
||||||
|
export function matchPattern(pattern: string, path: string): Record<string, string> | undefined {
|
||||||
|
return matchCompiled(compilePattern(pattern), splitPath(path));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Orders patterns by exactness, then static/constrained/plain segment specificity.
|
||||||
|
*
|
||||||
|
* Takes compiled patterns rather than their source strings: it used to re-derive both through
|
||||||
|
* `compilePattern`, which is a `Map` lookup each, on every comparison of every request.
|
||||||
|
*/
|
||||||
|
function moreSpecific(a: CompiledPattern, b: CompiledPattern): number {
|
||||||
|
const scoreA = a;
|
||||||
|
const scoreB = b;
|
||||||
|
if (scoreA.catchAll !== scoreB.catchAll) return scoreA.catchAll ? -1 : 1;
|
||||||
|
const length = Math.max(scoreA.kinds.length, scoreB.kinds.length);
|
||||||
|
|
||||||
|
for (let index = 0; index < length; index++) {
|
||||||
|
const kindA = scoreA.kinds[index] ?? -1;
|
||||||
|
const kindB = scoreB.kinds[index] ?? -1;
|
||||||
|
if (kindA !== kindB) return kindA - kindB;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One route with its pattern already compiled. Built once per table, ordered within its method. */
|
||||||
|
interface IndexedRoute {
|
||||||
|
def: OracleRoute;
|
||||||
|
compiled: CompiledPattern;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compiled, method-bucketed, specificity-ordered route tables, keyed by the identity of the array
|
||||||
|
* they were built from.
|
||||||
|
*
|
||||||
|
* A server hands the same array to every request, so this is built once and collected with the
|
||||||
|
* table it describes. A table assembled fresh — mesh splicing a teapot's exports in at boot — is a
|
||||||
|
* different array and gets its own index, so nothing has to remember to invalidate anything.
|
||||||
|
*/
|
||||||
|
const routeIndexCache = new WeakMap<OracleRoute[], Map<string, IndexedRoute[]>>();
|
||||||
|
|
||||||
|
function routeIndex(routes: OracleRoute[]): Map<string, IndexedRoute[]> {
|
||||||
|
const cached = routeIndexCache.get(routes);
|
||||||
|
if (cached) return cached;
|
||||||
|
|
||||||
|
const byMethod = new Map<string, IndexedRoute[]>();
|
||||||
|
|
||||||
|
for (const def of routes) {
|
||||||
|
const entry: IndexedRoute = { def, compiled: compilePattern(def.pattern) };
|
||||||
|
const bucket = byMethod.get(def.method);
|
||||||
|
if (bucket) bucket.push(entry);
|
||||||
|
else byMethod.set(def.method, [entry]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Most specific first, so the first match *is* the answer. `sort` is stable, so equal patterns
|
||||||
|
// keep registration order — which is exactly what the old scan did by refusing to replace its
|
||||||
|
// best on a tie.
|
||||||
|
for (const bucket of byMethod.values()) bucket.sort((a, b) => moreSpecific(b.compiled, a.compiled));
|
||||||
|
|
||||||
|
routeIndexCache.set(routes, byMethod);
|
||||||
|
return byMethod;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Finds the most specific route matching both method and path; ties keep registration order.
|
||||||
|
*
|
||||||
|
* The ranking is settled when the table is built, not per request: the answer cannot change between
|
||||||
|
* requests, and re-deriving it charged every request for a scan to the end plus a `moreSpecific`
|
||||||
|
* call — two `compilePattern` lookups each — per candidate. Both scaled with the size of the route
|
||||||
|
* table. What is left here is a walk that stops at the first match.
|
||||||
|
*/
|
||||||
|
export function matchRoute(routes: OracleRoute[], method: string, path: string): MatchedRoute | undefined {
|
||||||
|
const candidates = routeIndex(routes).get(method);
|
||||||
|
if (!candidates) return undefined;
|
||||||
|
|
||||||
|
const pathSegs = splitPath(path);
|
||||||
|
const decoded: Array<string | undefined> = new Array(pathSegs.length);
|
||||||
|
|
||||||
|
for (const { def, compiled } of candidates) {
|
||||||
|
const params = matchCompiled(compiled, pathSegs, decoded);
|
||||||
|
if (params) return { params, def };
|
||||||
|
}
|
||||||
|
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Route resolution adds the one HTTP fallback the matcher supports: buffered GET serves HEAD. */
|
||||||
|
export interface ResolvedRoute extends MatchedRoute {
|
||||||
|
implicitHead: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveRoute(routes: OracleRoute[], method: string, path: string): ResolvedRoute | undefined {
|
||||||
|
const explicit = matchRoute(routes, method, path);
|
||||||
|
if (explicit) return { ...explicit, implicitHead: false };
|
||||||
|
if (method !== 'HEAD') return undefined;
|
||||||
|
|
||||||
|
const fallback = matchRoute(
|
||||||
|
routes.filter((route) => route.transport === 'buffer'),
|
||||||
|
'GET',
|
||||||
|
path,
|
||||||
|
);
|
||||||
|
return fallback ? { ...fallback, implicitHead: true } : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const METHOD_ORDER = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];
|
||||||
|
|
||||||
|
/** Lists the distinct HTTP methods whose pattern matches the path — used to build a 405 `Allow` header. */
|
||||||
|
export function allowedMethods(routes: OracleRoute[], path: string): string[] {
|
||||||
|
const pathSegs = splitPath(path);
|
||||||
|
const methods = new Set<string>();
|
||||||
|
|
||||||
|
for (const route of routes) {
|
||||||
|
if (!matchCompiled(compilePattern(route.pattern), pathSegs)) continue;
|
||||||
|
methods.add(route.method);
|
||||||
|
if (route.method === 'GET' && route.transport === 'buffer') methods.add('HEAD');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (methods.size) methods.add('OPTIONS');
|
||||||
|
return [...methods].sort((a, b) => {
|
||||||
|
const indexA = METHOD_ORDER.indexOf(a);
|
||||||
|
const indexB = METHOD_ORDER.indexOf(b);
|
||||||
|
return (
|
||||||
|
(indexA < 0 ? METHOD_ORDER.length : indexA) - (indexB < 0 ? METHOD_ORDER.length : indexB) || a.localeCompare(b)
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Selects the first registered WS declaration whose pattern matches — no specificity ranking.
|
||||||
|
* Copied from `src/http/ws-core.ts`; both adapters hand it a path already through
|
||||||
|
* `normalizeRequestPath` (Node `routeUpgrade`, and `buildAppUpgrade` for app.upgrade).
|
||||||
|
*/
|
||||||
|
export function matchWsRoute<W extends OracleWsRoute>(
|
||||||
|
wsRoutes: W[],
|
||||||
|
path: string,
|
||||||
|
): { def: W; params: Record<string, string> | undefined } | undefined {
|
||||||
|
return wsRoutes
|
||||||
|
.map((candidate) => ({ def: candidate, params: matchPattern(candidate.pattern, path) }))
|
||||||
|
.find((entry) => entry.params);
|
||||||
|
}
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
/**
|
||||||
|
* Owner-requested additions (CARD-08 review) that need a running app: cross-pattern `Allow` through
|
||||||
|
* both adapters, and the HTTP route table across a mesh peer's lifetime.
|
||||||
|
*/
|
||||||
|
import 'reflect-metadata';
|
||||||
|
import http from 'http';
|
||||||
|
import net from 'net';
|
||||||
|
import type { AddressInfo } from 'net';
|
||||||
|
import { describe, it, afterAll, beforeAll } from 'vitest';
|
||||||
|
import { createApp, Route, Get, Post, Delete, Module, param } from '../../src/index';
|
||||||
|
import type { App } from '../../src/app/types';
|
||||||
|
import type { Logger } from '../../src/logger';
|
||||||
|
import { frozen, expectFrozenEqual } from './frozen';
|
||||||
|
|
||||||
|
// `/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] })
|
||||||
|
class CrossAllowModule {}
|
||||||
|
|
||||||
|
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`],
|
||||||
|
]);
|
||||||
|
|
||||||
|
interface Seen {
|
||||||
|
method: string;
|
||||||
|
path: string;
|
||||||
|
status: number;
|
||||||
|
allow: string | null;
|
||||||
|
body: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function nodeRequest(port: number, method: string, path: string): Promise<Seen> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const req = http.request({ host: '127.0.0.1', port, method, path, agent: false }, (res) => {
|
||||||
|
let body = '';
|
||||||
|
res.setEncoding('utf8');
|
||||||
|
res.on('data', (chunk) => (body += chunk));
|
||||||
|
res.on('end', () =>
|
||||||
|
resolve({ method, path, status: res.statusCode ?? 0, allow: (res.headers.allow as string) ?? null, body }),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
req.on('error', reject);
|
||||||
|
req.end();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
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() };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── mesh: the HTTP route table across a peer's lifetime ─────────────────────────────────────────
|
||||||
|
|
||||||
|
const SECRET = 'parity-secret';
|
||||||
|
|
||||||
|
@Route('/remote')
|
||||||
|
class RemoteCtl {
|
||||||
|
@Get('/ping', { export: true }) ping() {
|
||||||
|
return { from: 'teapot' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/api', controllers: [RemoteCtl] })
|
||||||
|
class TeapotModule {}
|
||||||
|
|
||||||
|
@Route('/local')
|
||||||
|
class LocalCtl {
|
||||||
|
@Get('/ok') ok() {
|
||||||
|
return { from: 'teacup' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
|
||||||
|
class TeacupModule {}
|
||||||
|
|
||||||
|
const quiet: Logger = { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} };
|
||||||
|
|
||||||
|
/** A port nothing is listening on, that a teapot can take later. */
|
||||||
|
async function freePort(): Promise<number> {
|
||||||
|
const server = net.createServer();
|
||||||
|
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||||
|
const { port } = server.address() as AddressInfo;
|
||||||
|
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||||
|
return port;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Same probes at every phase: the remote hit, its method miss, a local hit and a path miss.
|
||||||
|
const PROBES: Array<[string, string]> = [
|
||||||
|
['GET', '/api/remote/ping'],
|
||||||
|
['POST', '/api/remote/ping'],
|
||||||
|
['GET', '/api/local/ok'],
|
||||||
|
['GET', '/api/nope'],
|
||||||
|
];
|
||||||
|
|
||||||
|
async function probe(app: App, phase: string) {
|
||||||
|
const out = [];
|
||||||
|
for (const [method, path] of PROBES) {
|
||||||
|
const { status, allow, body } = await fetchRequest(app, method, path);
|
||||||
|
// The teapot's ephemeral port appears in the 503 body; the port is not routing behaviour.
|
||||||
|
out.push({ phase, method, path, status, allow, body: body.replace(/ws:\/\/127\.0\.0\.1:\d+/g, '<teapot>') });
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
const teacupFor = (port: number) =>
|
||||||
|
createApp({
|
||||||
|
modules: [TeacupModule],
|
||||||
|
experimental: true,
|
||||||
|
logger: quiet,
|
||||||
|
mesh: {
|
||||||
|
teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: SECRET }],
|
||||||
|
bootTimeoutMs: 300,
|
||||||
|
timeoutMs: 500,
|
||||||
|
reconnect: false,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Two lifetimes. A: the teapot is up at boot, then goes away. B: the teapot is absent at boot and
|
||||||
|
* comes up afterwards. The current code builds the HTTP table once, at boot, and never changes it:
|
||||||
|
* routes spliced at boot stay in the table after their peer leaves, and a peer that arrives late
|
||||||
|
* is never spliced in. CARD-10 can reuse this to assert the index is not rebuilt per request.
|
||||||
|
*/
|
||||||
|
async function meshLifetimes() {
|
||||||
|
const results = [];
|
||||||
|
|
||||||
|
const portA = await freePort();
|
||||||
|
const teapotA = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||||
|
await teapotA.listen(portA);
|
||||||
|
const teacupA = teacupFor(portA);
|
||||||
|
try {
|
||||||
|
results.push(...(await probe(teacupA, 'A1 teapot up at boot')));
|
||||||
|
await teapotA.close();
|
||||||
|
results.push(...(await probe(teacupA, 'A2 teapot gone after boot')));
|
||||||
|
} finally {
|
||||||
|
await teacupA.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
const portB = await freePort();
|
||||||
|
const teacupB = teacupFor(portB);
|
||||||
|
const teapotB = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||||
|
try {
|
||||||
|
results.push(...(await probe(teacupB, 'B1 teapot absent at boot')));
|
||||||
|
await teapotB.listen(portB);
|
||||||
|
results.push(...(await probe(teacupB, 'B2 teapot up after boot')));
|
||||||
|
} finally {
|
||||||
|
await teacupB.close();
|
||||||
|
await teapotB.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('router parity: owner-requested application cases', () => {
|
||||||
|
let fetchApp: App;
|
||||||
|
let nodeApp: App;
|
||||||
|
let port: number;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
fetchApp = createApp({ modules: [CrossAllowModule] });
|
||||||
|
nodeApp = createApp({ modules: [CrossAllowModule] });
|
||||||
|
port = ((await nodeApp.listen(0)).address() as AddressInfo).port;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(() => nodeApp.close());
|
||||||
|
|
||||||
|
it('cross-pattern Allow through app.fetch and Node equals the frozen capture', async () => {
|
||||||
|
const run = async () => {
|
||||||
|
const out: Array<Seen & { adapter: string }> = [];
|
||||||
|
for (const [method, path] of ALLOW_REQUESTS)
|
||||||
|
out.push({ adapter: 'fetch', ...(await fetchRequest(fetchApp, method, path)) });
|
||||||
|
for (const [method, path] of ALLOW_REQUESTS)
|
||||||
|
out.push({ adapter: 'node', ...(await nodeRequest(port, method, path)) });
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
const expected = await frozen('owner-app-allow', run);
|
||||||
|
expectFrozenEqual(await run(), expected, 'cross-pattern Allow');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('the mesh HTTP route table across a peer lifetime equals the frozen capture', async () => {
|
||||||
|
const expected = await frozen('owner-mesh-lifetime', meshLifetimes);
|
||||||
|
expectFrozenEqual(await meshLifetimes(), expected, 'mesh lifetime');
|
||||||
|
}, 30_000);
|
||||||
|
});
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
/**
|
||||||
|
* WebSocket upgrade parity, kept apart from HTTP on purpose: WS selection is first-registered-wins
|
||||||
|
* with no specificity ranking, an HTTP route at the same path never takes the upgrade, and the mesh
|
||||||
|
* control path is checked before WS route matching. Captured through both upgrade entry points —
|
||||||
|
* `app.upgrade` (Deno/Bun/edge) and the Node `server.on('upgrade')` listener — because they are
|
||||||
|
* separate code paths and do not agree on everything (see the reserved-path rows in the fixture).
|
||||||
|
*/
|
||||||
|
import 'reflect-metadata';
|
||||||
|
import type { AddressInfo } from 'net';
|
||||||
|
import WebSocket from 'ws';
|
||||||
|
import { describe, it, beforeAll, afterAll } from 'vitest';
|
||||||
|
import { createApp, Route, Get, Post, Ws, Stream, Module, param } from '../../src/index';
|
||||||
|
import { channel } from '../../src/channel';
|
||||||
|
import type { App } from '../../src/app/types';
|
||||||
|
import type { WsRequest, WsSocket } from '../../src/http/ws-core';
|
||||||
|
import { frozen, expectFrozenEqual } from './frozen';
|
||||||
|
|
||||||
|
const announce = (id: string, params: Record<string, string>) =>
|
||||||
|
(async function* () {
|
||||||
|
yield { id, params };
|
||||||
|
})();
|
||||||
|
|
||||||
|
@Route('/')
|
||||||
|
class ParityWs {
|
||||||
|
// Registered before the static twin: WS does not rank, so this one answers /live/lobby.
|
||||||
|
@Ws('/live/:room') liveRoom(@param() p: Record<string, string>) {
|
||||||
|
return announce('liveRoom', p);
|
||||||
|
}
|
||||||
|
@Ws('/live/lobby') liveLobby(@param() p: Record<string, string>) {
|
||||||
|
return announce('liveLobby', p);
|
||||||
|
}
|
||||||
|
// Same path as the WS routes, different method, so the boot accepts it; it must not take upgrades.
|
||||||
|
@Post('/live/lobby') httpLobby() {
|
||||||
|
return { id: 'httpLobby' };
|
||||||
|
}
|
||||||
|
@Get('/plain') plain() {
|
||||||
|
return { id: 'plain' };
|
||||||
|
}
|
||||||
|
// `negotiate` routes are registered for both HTTP and WS.
|
||||||
|
@Stream('/feed') feed() {
|
||||||
|
return announce('feed', {});
|
||||||
|
}
|
||||||
|
// A user route on the reserved mesh path, on an app with no mesh: the two adapters disagree here.
|
||||||
|
@Ws('/__mesh__/control') reserved(@param() p: Record<string, string>) {
|
||||||
|
return announce('reserved', p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Module({ mountpoint: '/', controllers: [ParityWs] })
|
||||||
|
class ParityWsModule {}
|
||||||
|
|
||||||
|
// The `ws` client runs its URL through the URL parser, so on the Node rows dot segments are already
|
||||||
|
// resolved before the server sees them; `app.upgrade` receives each path exactly as written here.
|
||||||
|
const UPGRADE_PATHS = [
|
||||||
|
'/live/lobby',
|
||||||
|
'/live/kitchen',
|
||||||
|
'/live/lobby/',
|
||||||
|
'/live/x/../lobby',
|
||||||
|
'/live/a%20b',
|
||||||
|
'/live/lobby?x=1',
|
||||||
|
'/live/%E0%A4%A',
|
||||||
|
'/live//lobby',
|
||||||
|
'/plain',
|
||||||
|
'/nope',
|
||||||
|
'/feed',
|
||||||
|
'/__mesh__/control',
|
||||||
|
];
|
||||||
|
|
||||||
|
const HTTP_REQUESTS: Array<[string, string]> = [
|
||||||
|
['GET', '/live/lobby'],
|
||||||
|
['POST', '/live/lobby'],
|
||||||
|
['OPTIONS', '/live/lobby'],
|
||||||
|
['GET', '/live/kitchen'],
|
||||||
|
['GET', '/feed'],
|
||||||
|
];
|
||||||
|
|
||||||
|
interface UpgradeOutcome {
|
||||||
|
path: string;
|
||||||
|
sent: unknown[];
|
||||||
|
closes: Array<{ code?: number; reason?: string }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function viaAppUpgrade(app: App, path: string): Promise<UpgradeOutcome> {
|
||||||
|
const inbound = channel<unknown>();
|
||||||
|
const ac = new AbortController();
|
||||||
|
const sent: unknown[] = [];
|
||||||
|
const closes: Array<{ code?: number; reason?: string }> = [];
|
||||||
|
let open = true;
|
||||||
|
const socket: WsSocket = {
|
||||||
|
inbound,
|
||||||
|
abort: ac.signal,
|
||||||
|
get isOpen() {
|
||||||
|
return open;
|
||||||
|
},
|
||||||
|
send: (data) => sent.push(JSON.parse(data)),
|
||||||
|
close: (code, reason) => {
|
||||||
|
open = false;
|
||||||
|
closes.push({ code, reason });
|
||||||
|
ac.abort();
|
||||||
|
},
|
||||||
|
terminate: () => {
|
||||||
|
open = false;
|
||||||
|
ac.abort();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const request: WsRequest = { url: path, headers: {}, protocol: 'http', ip: '127.0.0.1' };
|
||||||
|
await app.upgrade(request, socket);
|
||||||
|
return { path, sent, closes };
|
||||||
|
}
|
||||||
|
|
||||||
|
interface NodeUpgradeOutcome {
|
||||||
|
path: string;
|
||||||
|
status?: number;
|
||||||
|
sent: unknown[];
|
||||||
|
close?: { code: number; reason: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
function viaNodeUpgrade(port: number, path: string): Promise<NodeUpgradeOutcome> {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const sent: unknown[] = [];
|
||||||
|
const client = new WebSocket(`ws://127.0.0.1:${port}${path}`);
|
||||||
|
client.on('unexpected-response', (_req, res) => {
|
||||||
|
resolve({ path, status: res.statusCode, sent });
|
||||||
|
res.resume();
|
||||||
|
client.terminate();
|
||||||
|
});
|
||||||
|
client.on('message', (data) => sent.push(JSON.parse(String(data))));
|
||||||
|
client.on('close', (code, reason) => resolve({ path, status: 101, sent, close: { code, reason: String(reason) } }));
|
||||||
|
client.on('error', () => {
|
||||||
|
/* reported through unexpected-response or close */
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('router parity: WebSocket upgrade outcomes', () => {
|
||||||
|
let app: App;
|
||||||
|
let nodeApp: App;
|
||||||
|
let port: number;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
app = createApp({ modules: [ParityWsModule] });
|
||||||
|
nodeApp = createApp({ modules: [ParityWsModule] });
|
||||||
|
const server = await nodeApp.listen(0);
|
||||||
|
port = (server.address() as AddressInfo).port;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await nodeApp.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('app.upgrade outcomes equal the frozen capture', async () => {
|
||||||
|
const run = async () => {
|
||||||
|
const out: UpgradeOutcome[] = [];
|
||||||
|
for (const path of UPGRADE_PATHS) out.push(await viaAppUpgrade(app, path));
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
const expected = await frozen('ws-app-upgrade', run);
|
||||||
|
expectFrozenEqual(await run(), expected, 'app.upgrade');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('Node upgrade listener outcomes equal the frozen capture', async () => {
|
||||||
|
const run = async () => {
|
||||||
|
const out: NodeUpgradeOutcome[] = [];
|
||||||
|
for (const path of UPGRADE_PATHS) out.push(await viaNodeUpgrade(port, path));
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
const expected = await frozen('ws-node-upgrade', run);
|
||||||
|
expectFrozenEqual(await run(), expected, 'node upgrade');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('plain HTTP requests at the WS paths equal the frozen capture', async () => {
|
||||||
|
const run = async () => {
|
||||||
|
const out: Array<{ method: string; path: string; status: number; allow: string | null; body: string }> = [];
|
||||||
|
for (const [method, path] of HTTP_REQUESTS) {
|
||||||
|
const res = await app.fetch(new Request(`http://parity.test${path}`, { method }));
|
||||||
|
out.push({ method, path, status: res.status, allow: res.headers.get('allow'), body: await res.text() });
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
const expected = await frozen('ws-http-same-path', run);
|
||||||
|
expectFrozenEqual(await run(), expected, 'http at ws paths');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -46,7 +46,7 @@ function runHarness(signal: NodeJS.Signals, env: NodeJS.ProcessEnv = {}, sendTwi
|
|||||||
// `process.execPath -r tsx/cjs`, not `npx tsx`: a wrapper puts the app one process further
|
// `process.execPath -r tsx/cjs`, not `npx tsx`: a wrapper puts the app one process further
|
||||||
// down, and on Linux the signal then lands on the wrapper while the app never hears it — which
|
// down, and on Linux the signal then lands on the wrapper while the app never hears it — which
|
||||||
// is exactly how this passed locally and failed in CI. `-r` rather than `--import`/`--loader`
|
// is exactly how this passed locally and failed in CI. `-r` rather than `--import`/`--loader`
|
||||||
// because it is the one form that works on both the Node 18 floor CI builds against and the
|
// because it is the one form that works on both the Node 22 floor CI builds against and the
|
||||||
// current release.
|
// current release.
|
||||||
const proc = spawn(process.execPath, ['-r', 'tsx/cjs', 'test/interop/_signal-app.ts'], {
|
const proc = spawn(process.execPath, ['-r', 'tsx/cjs', 'test/interop/_signal-app.ts'], {
|
||||||
env: { ...process.env, ...env },
|
env: { ...process.env, ...env },
|
||||||
|
|||||||
+108
-1
@@ -1,9 +1,11 @@
|
|||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
import { writeFileSync, mkdirSync } from 'node:fs';
|
import { writeFileSync, mkdirSync, mkdtempSync, symlinkSync } from 'node:fs';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
import { tmpdir } from 'node:os';
|
import { tmpdir } from 'node:os';
|
||||||
import { createApp, Route, Get, Module } from '../src/index';
|
import { createApp, Route, Get, Module } from '../src/index';
|
||||||
import { buildStaticResolver } from '../src/views';
|
import { buildStaticResolver } from '../src/views';
|
||||||
|
import { isHttpError } from '../src/signals';
|
||||||
|
import type { ErrorRenderer } from '../src/transformers';
|
||||||
|
|
||||||
const root = join(tmpdir(), 'gt-static-test');
|
const root = join(tmpdir(), 'gt-static-test');
|
||||||
mkdirSync(root, { recursive: true });
|
mkdirSync(root, { recursive: true });
|
||||||
@@ -67,3 +69,108 @@ describe('static serving', () => {
|
|||||||
expect(await resolve('/%2e%2e/gt-secret.txt')).toBeUndefined();
|
expect(await resolve('/%2e%2e/gt-secret.txt')).toBeUndefined();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// #106: the traversal guard above is lexical, and `stat`/`readFile` follow symlinks, so a link
|
||||||
|
// inside the root could serve a file outside it. Confinement has to compare real paths. On macOS
|
||||||
|
// `tmpdir()` is itself behind a symlink (`/var` → `/private/var`), so every case below also
|
||||||
|
// exercises a root whose lexical and real paths differ.
|
||||||
|
describe('static serving confined to the real root (#106)', () => {
|
||||||
|
const base = mkdtempSync(join(tmpdir(), 'gt-static-real-'));
|
||||||
|
const sroot = join(base, 'root');
|
||||||
|
mkdirSync(join(sroot, 'sub'), { recursive: true });
|
||||||
|
mkdirSync(join(sroot, 'idx'));
|
||||||
|
mkdirSync(join(base, 'root-evil'));
|
||||||
|
mkdirSync(join(base, 'outside'));
|
||||||
|
writeFileSync(join(sroot, 'a.txt'), 'in root');
|
||||||
|
writeFileSync(join(sroot, 'sub', 'index.html'), '<h1>Sub</h1>');
|
||||||
|
writeFileSync(join(base, 'root-evil', 'x.txt'), 'SIBLING');
|
||||||
|
writeFileSync(join(base, 'secret.txt'), 'TOP SECRET');
|
||||||
|
writeFileSync(join(base, 'outside', 's.txt'), 'OUTSIDE');
|
||||||
|
|
||||||
|
// Windows without the symlink privilege refuses to create links; the cases that need them skip
|
||||||
|
// there rather than pass vacuously.
|
||||||
|
let symlinks = true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
symlinkSync('a.txt', join(sroot, 'in-link'));
|
||||||
|
symlinkSync('../secret.txt', join(sroot, 'out-link'));
|
||||||
|
symlinkSync('../outside', join(sroot, 'dir-link'));
|
||||||
|
symlinkSync('../nope.txt', join(sroot, 'dangling'));
|
||||||
|
symlinkSync('../root-evil/x.txt', join(sroot, 'evil-link'));
|
||||||
|
symlinkSync('../../secret.txt', join(sroot, 'idx', 'index.html'));
|
||||||
|
symlinkSync('root', join(base, 'root-alias'));
|
||||||
|
} catch (err) {
|
||||||
|
if ((err as NodeJS.ErrnoException).code !== 'EPERM') throw err;
|
||||||
|
symlinks = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const withLinks = it.skipIf(!symlinks);
|
||||||
|
|
||||||
|
const app = createApp({ modules: [], static: sroot });
|
||||||
|
const get = (path: string) => app.fetch(new Request(`http://x${path}`));
|
||||||
|
|
||||||
|
withLinks('T1: does not serve a link to a file outside the root', async () => {
|
||||||
|
const res = await get('/out-link');
|
||||||
|
expect(res.status).toBe(404);
|
||||||
|
expect(await res.text()).not.toContain('TOP SECRET');
|
||||||
|
});
|
||||||
|
withLinks('T2: serves a link to a file inside the root', async () => {
|
||||||
|
const res = await get('/in-link');
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(await res.text()).toBe('in root');
|
||||||
|
});
|
||||||
|
withLinks('T3: a symlinked directory cannot expose an out-of-root file', async () => {
|
||||||
|
expect((await get('/dir-link/s.txt')).status).toBe(404);
|
||||||
|
});
|
||||||
|
it('T4: a sibling-prefix directory is not reachable by traversal', async () => {
|
||||||
|
expect((await get('/../root-evil/x.txt')).status).toBe(404);
|
||||||
|
expect((await get('/%2e%2e/root-evil/x.txt')).status).toBe(404);
|
||||||
|
});
|
||||||
|
withLinks('T5: a real path in a sibling-prefix directory is outside the root', async () => {
|
||||||
|
const resolve = buildStaticResolver(sroot);
|
||||||
|
expect(await resolve('/../root-evil/x.txt')).toBeUndefined();
|
||||||
|
// Passes the lexical guard, then really lands in `root-evil` — only the `root + sep` rule on the
|
||||||
|
// real path stops it.
|
||||||
|
expect(await resolve('/evil-link')).toBeUndefined();
|
||||||
|
});
|
||||||
|
withLinks('T6: a dangling link is a miss, not a rejection', async () => {
|
||||||
|
await expect(buildStaticResolver(sroot)('/dangling')).resolves.toBeUndefined();
|
||||||
|
expect((await get('/dangling')).status).toBe(404);
|
||||||
|
});
|
||||||
|
withLinks('T7: a directory index that links outside the root is a miss', async () => {
|
||||||
|
const res = await get('/idx/');
|
||||||
|
expect(res.status).toBe(404);
|
||||||
|
expect(await res.text()).not.toContain('TOP SECRET');
|
||||||
|
});
|
||||||
|
withLinks('T8: 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>');
|
||||||
|
});
|
||||||
|
withLinks('T10: an escape renders through onError exactly like a plain miss', async () => {
|
||||||
|
const onError: ErrorRenderer = (error) => ({
|
||||||
|
status: isHttpError(error) ? error.status : 500,
|
||||||
|
headers: { 'content-type': 'text/html' },
|
||||||
|
body: `<h1>${isHttpError(error) ? error.status : 500}</h1>`,
|
||||||
|
});
|
||||||
|
const custom = createApp({ modules: [], static: sroot, onError });
|
||||||
|
const escape = await custom.fetch(new Request('http://x/out-link'));
|
||||||
|
const miss = await custom.fetch(new Request('http://x/nope.txt'));
|
||||||
|
expect(escape.status).toBe(404);
|
||||||
|
expect(escape.headers.get('content-type')).toBe('text/html');
|
||||||
|
expect(await escape.text()).toBe(await miss.text());
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a root created after the first request starts serving without a restart', async () => {
|
||||||
|
const late = join(mkdtempSync(join(tmpdir(), 'gt-static-late-')), 'public');
|
||||||
|
const resolve = buildStaticResolver(late);
|
||||||
|
expect(await resolve('/a.txt')).toBeUndefined();
|
||||||
|
mkdirSync(late);
|
||||||
|
writeFileSync(join(late, 'a.txt'), 'late');
|
||||||
|
expect((await resolve('/a.txt'))?.body.toString()).toBe('late');
|
||||||
|
});
|
||||||
@@ -0,0 +1,379 @@
|
|||||||
|
import { describe, it, expect, afterEach } from 'vitest';
|
||||||
|
import type http from 'http';
|
||||||
|
import WebSocket from 'ws';
|
||||||
|
import { createApp, Route, Ws, Module, ctx } from '../src/index';
|
||||||
|
import type { RequestLimits } from '../src/index';
|
||||||
|
import { channel } from '../src/channel';
|
||||||
|
import { boundInbound, type WsSocket } from '../src/http/ws-core';
|
||||||
|
|
||||||
|
// #107 / D1: per-connection bounds on inbound WebSocket messages. Node runs the real `ws` server
|
||||||
|
// behind `listen(0)`; the other runtimes are covered in test/deno, test/bun and test/edge.
|
||||||
|
|
||||||
|
const never = new Promise<never>(() => {});
|
||||||
|
|
||||||
|
@Route('/rt')
|
||||||
|
class Rt {
|
||||||
|
@Ws('/echo')
|
||||||
|
echo(@ctx() { inbound }: any) {
|
||||||
|
return (async function* () {
|
||||||
|
for await (const msg of inbound) yield `echo:${(msg as string).length}`;
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Never reads `inbound`: every frame the client sends stays queued.
|
||||||
|
@Ws('/stall')
|
||||||
|
stall() {
|
||||||
|
return (async function* () {
|
||||||
|
await never;
|
||||||
|
yield '';
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reads exactly one frame, acknowledges it, then stalls.
|
||||||
|
@Ws('/one')
|
||||||
|
one(@ctx() { inbound }: any) {
|
||||||
|
return (async function* () {
|
||||||
|
const it = (inbound as AsyncIterable<unknown>)[Symbol.asyncIterator]();
|
||||||
|
await it.next();
|
||||||
|
yield 'took-one';
|
||||||
|
await never;
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', controllers: [Rt] })
|
||||||
|
class M {}
|
||||||
|
|
||||||
|
const servers: http.Server[] = [];
|
||||||
|
const clients: WebSocket[] = [];
|
||||||
|
afterEach(async () => {
|
||||||
|
clients.splice(0).forEach((c) => c.terminate());
|
||||||
|
await Promise.all(servers.splice(0).map((s) => new Promise((r) => s.close(r))));
|
||||||
|
});
|
||||||
|
|
||||||
|
async function serve(limits?: RequestLimits): Promise<number> {
|
||||||
|
const server = await createApp({ modules: [M], limits }).listen(0);
|
||||||
|
servers.push(server);
|
||||||
|
return (server.address() as { port: number }).port;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function connect(port: number, path: string) {
|
||||||
|
const client = new WebSocket(`ws://127.0.0.1:${port}${path}`);
|
||||||
|
clients.push(client);
|
||||||
|
const messages: string[] = [];
|
||||||
|
client.on('message', (d) => messages.push(d.toString()));
|
||||||
|
const closed = new Promise<{ code: number; reason: string }>((r) =>
|
||||||
|
client.on('close', (code, reason) => r({ code, reason: reason.toString() })),
|
||||||
|
);
|
||||||
|
await new Promise((r) => client.on('open', r));
|
||||||
|
return { client, messages, closed };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Resolves with the close if it happens within `ms`, else 'open'. */
|
||||||
|
const closedWithin = (closed: Promise<{ code: number; reason: string }>, ms = 150) =>
|
||||||
|
Promise.race([closed, new Promise<'open'>((r) => setTimeout(() => r('open'), ms))]);
|
||||||
|
|
||||||
|
const until = async (cond: () => boolean) => {
|
||||||
|
for (let i = 0; i < 100 && !cond(); i++) await new Promise((r) => setTimeout(r, 10));
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Binary payload of `n` bytes that is valid UTF-8 (ASCII), so its decoded size equals its wire size. */
|
||||||
|
const binary = (n: number) => Buffer.alloc(n, 0x62);
|
||||||
|
|
||||||
|
describe('limits.maxWsMessageBytes on Node (#107)', () => {
|
||||||
|
const limits = { maxWsMessageBytes: 1024 };
|
||||||
|
|
||||||
|
it('T1: a text message of exactly the limit is delivered', async () => {
|
||||||
|
const { client, messages } = await connect(await serve(limits), '/rt/echo');
|
||||||
|
client.send('a'.repeat(1024));
|
||||||
|
await until(() => messages.length > 0);
|
||||||
|
expect(messages).toEqual(['echo:1024']);
|
||||||
|
client.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T2: a binary message of exactly the limit is delivered', async () => {
|
||||||
|
const { client, messages } = await connect(await serve(limits), '/rt/echo');
|
||||||
|
client.send(binary(1024));
|
||||||
|
await until(() => messages.length > 0);
|
||||||
|
expect(messages).toEqual(['echo:1024']);
|
||||||
|
client.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T3: one byte of text over the limit closes 1009', async () => {
|
||||||
|
const { client, closed } = await connect(await serve(limits), '/rt/echo');
|
||||||
|
client.send('a'.repeat(1025));
|
||||||
|
expect((await closed).code).toBe(1009);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T4: one byte of binary over the limit closes 1009', async () => {
|
||||||
|
const { client, closed } = await connect(await serve(limits), '/rt/echo');
|
||||||
|
client.send(binary(1025));
|
||||||
|
expect((await closed).code).toBe(1009);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T5: the limit counts UTF-8 bytes, not characters', async () => {
|
||||||
|
const { client, closed } = await connect(await serve(limits), '/rt/echo');
|
||||||
|
client.send('€'.repeat(342)); // 342 UTF-16 units, 1026 UTF-8 bytes
|
||||||
|
expect((await closed).code).toBe(1009);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T6: a fragmented message is measured whole', async () => {
|
||||||
|
const { client, closed } = await connect(await serve(limits), '/rt/echo');
|
||||||
|
client.send('a'.repeat(400), { fin: false });
|
||||||
|
client.send('a'.repeat(400), { fin: false });
|
||||||
|
client.send('a'.repeat(400), { fin: true });
|
||||||
|
expect((await closed).code).toBe(1009);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('limits.maxWsQueue on Node (#107)', () => {
|
||||||
|
const limits = { maxWsQueue: 4 };
|
||||||
|
|
||||||
|
it('T7: a stalled consumer with the queue exactly full stays open', async () => {
|
||||||
|
const { client, closed } = await connect(await serve(limits), '/rt/stall');
|
||||||
|
for (let i = 0; i < 4; i++) client.send(`m${i}`);
|
||||||
|
expect(await closedWithin(closed)).toBe('open');
|
||||||
|
client.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T8: one more frame than the queue holds closes 1013, inbound queue full', async () => {
|
||||||
|
const { client, closed } = await connect(await serve(limits), '/rt/stall');
|
||||||
|
for (let i = 0; i < 5; i++) client.send(`m${i}`);
|
||||||
|
expect(await closed).toEqual({ code: 1013, reason: 'inbound queue full' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T9: the bound counts undelivered frames, so a delivered one frees a slot', async () => {
|
||||||
|
const { client, messages, closed } = await connect(await serve(limits), '/rt/one');
|
||||||
|
for (let i = 0; i < 4; i++) client.send(`m${i}`);
|
||||||
|
await until(() => messages.length > 0);
|
||||||
|
expect(messages).toEqual(['took-one']);
|
||||||
|
client.send('m4'); // 3 left queued + this one = 4
|
||||||
|
expect(await closedWithin(closed)).toBe('open');
|
||||||
|
client.close();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ws limit defaults on Node (#107)', () => {
|
||||||
|
it('T10: 1 MiB is accepted and 1 MiB + 1 closes 1009', async () => {
|
||||||
|
const port = await serve();
|
||||||
|
const ok = await connect(port, '/rt/echo');
|
||||||
|
ok.client.send('a'.repeat(1_048_576));
|
||||||
|
await until(() => ok.messages.length > 0);
|
||||||
|
expect(ok.messages).toEqual(['echo:1048576']);
|
||||||
|
ok.client.close();
|
||||||
|
|
||||||
|
const over = await connect(port, '/rt/echo');
|
||||||
|
over.client.send('a'.repeat(1_048_577));
|
||||||
|
expect((await over.closed).code).toBe(1009);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T10: 16 queued frames are held and the 17th closes 1013', async () => {
|
||||||
|
const port = await serve();
|
||||||
|
const held = await connect(port, '/rt/stall');
|
||||||
|
for (let i = 0; i < 16; i++) held.client.send(`m${i}`);
|
||||||
|
expect(await closedWithin(held.closed)).toBe('open');
|
||||||
|
held.client.close();
|
||||||
|
|
||||||
|
const over = await connect(port, '/rt/stall');
|
||||||
|
for (let i = 0; i < 17; i++) over.client.send(`m${i}`);
|
||||||
|
expect((await over.closed).code).toBe(1013);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ws limit validation (#107)', () => {
|
||||||
|
it.each([
|
||||||
|
['maxWsQueue', 0],
|
||||||
|
['maxWsQueue', -1],
|
||||||
|
['maxWsQueue', 1.5],
|
||||||
|
['maxWsQueue', '16'],
|
||||||
|
['maxWsQueue', NaN],
|
||||||
|
['maxWsMessageBytes', 0],
|
||||||
|
['maxWsMessageBytes', -1],
|
||||||
|
['maxWsMessageBytes', 1.5],
|
||||||
|
['maxWsMessageBytes', '16'],
|
||||||
|
['maxWsMessageBytes', Infinity],
|
||||||
|
])('T11: limits.%s = %s fails createApp with a TypeError naming the key', (key, value) => {
|
||||||
|
expect(() => createApp({ modules: [M], limits: { [key]: value } as RequestLimits })).toThrow(
|
||||||
|
new RegExp(`^limits\\.${key} must be a positive integer`),
|
||||||
|
);
|
||||||
|
expect(() => createApp({ modules: [M], limits: { [key]: value } as RequestLimits })).toThrow(TypeError);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accepts positive integers and absent keys', () => {
|
||||||
|
expect(() => createApp({ modules: [M], limits: { maxWsQueue: 1, maxWsMessageBytes: 1 } })).not.toThrow();
|
||||||
|
expect(() => createApp({ modules: [M], limits: {} })).not.toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
/** A WsSocket over a channel that records closes. */
|
||||||
|
function fakeSocket() {
|
||||||
|
const inbound = channel<unknown>();
|
||||||
|
const closes: Array<[number | undefined, string | undefined]> = [];
|
||||||
|
const socket: WsSocket = {
|
||||||
|
inbound,
|
||||||
|
abort: new AbortController().signal,
|
||||||
|
isOpen: true,
|
||||||
|
send: () => {},
|
||||||
|
close: (code, reason) => closes.push([code, reason]),
|
||||||
|
terminate: () => {},
|
||||||
|
};
|
||||||
|
return { socket, inbound, closes };
|
||||||
|
}
|
||||||
|
|
||||||
|
const tick = () => new Promise((r) => setTimeout(r, 0));
|
||||||
|
|
||||||
|
describe('boundInbound (#107)', () => {
|
||||||
|
it('T15: delivers frames in order to a waiting consumer and to a late one', async () => {
|
||||||
|
const { socket, inbound } = fakeSocket();
|
||||||
|
const bounded = boundInbound(socket, { maxWsQueue: 4 });
|
||||||
|
const it = bounded.inbound[Symbol.asyncIterator]();
|
||||||
|
const first = it.next();
|
||||||
|
inbound.push('a');
|
||||||
|
expect(await first).toEqual({ value: 'a', done: false });
|
||||||
|
inbound.push('b');
|
||||||
|
inbound.push('c');
|
||||||
|
await tick();
|
||||||
|
expect(await it.next()).toEqual({ value: 'b', done: false });
|
||||||
|
expect(await it.next()).toEqual({ value: 'c', done: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T15: subscribes immediately, so frames sent before the consumer arrives are kept', async () => {
|
||||||
|
const { socket, inbound } = fakeSocket();
|
||||||
|
const bounded = boundInbound(socket);
|
||||||
|
await tick();
|
||||||
|
inbound.push('early');
|
||||||
|
await tick();
|
||||||
|
expect(await bounded.inbound[Symbol.asyncIterator]().next()).toEqual({ value: 'early', done: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T15: closes 1009 on an oversized frame and never delivers it', async () => {
|
||||||
|
const { socket, inbound, closes } = fakeSocket();
|
||||||
|
const bounded = boundInbound(socket, { maxWsMessageBytes: 3 });
|
||||||
|
await tick();
|
||||||
|
inbound.push('€'); // 3 bytes: fits
|
||||||
|
inbound.push('€a'); // 4 bytes
|
||||||
|
await tick();
|
||||||
|
expect(closes).toEqual([[1009, 'message too large']]);
|
||||||
|
const it = bounded.inbound[Symbol.asyncIterator]();
|
||||||
|
expect(await it.next()).toEqual({ value: '€', done: false });
|
||||||
|
expect((await it.next()).done).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T15: closes 1013 on overflow, delivers what was queued, then ends', async () => {
|
||||||
|
const { socket, inbound, closes } = fakeSocket();
|
||||||
|
const bounded = boundInbound(socket, { maxWsQueue: 2 });
|
||||||
|
await tick();
|
||||||
|
for (const m of ['a', 'b', 'c']) inbound.push(m);
|
||||||
|
await tick();
|
||||||
|
expect(closes).toEqual([[1013, 'inbound queue full']]);
|
||||||
|
const got: unknown[] = [];
|
||||||
|
for await (const m of bounded.inbound) got.push(m);
|
||||||
|
expect(got).toEqual(['a', 'b']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T15: ends when the socket inbound ends', async () => {
|
||||||
|
const { socket, inbound } = fakeSocket();
|
||||||
|
const bounded = boundInbound(socket);
|
||||||
|
const it = bounded.inbound[Symbol.asyncIterator]();
|
||||||
|
const pending = it.next();
|
||||||
|
inbound.close();
|
||||||
|
expect((await pending).done).toBe(true);
|
||||||
|
expect((await it.next()).done).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T15: propagates a socket failure to a waiting and a later consumer', async () => {
|
||||||
|
const { socket, inbound } = fakeSocket();
|
||||||
|
const bounded = boundInbound(socket);
|
||||||
|
const it = bounded.inbound[Symbol.asyncIterator]();
|
||||||
|
const pending = it.next();
|
||||||
|
const boom = new Error('boom');
|
||||||
|
inbound.fail(boom);
|
||||||
|
await expect(pending).rejects.toBe(boom);
|
||||||
|
await expect(it.next()).rejects.toBe(boom);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T15: a consumer that returns stops queueing, so it is never closed for not reading', async () => {
|
||||||
|
const { socket, inbound, closes } = fakeSocket();
|
||||||
|
const bounded = boundInbound(socket, { maxWsQueue: 1 });
|
||||||
|
const it = bounded.inbound[Symbol.asyncIterator]();
|
||||||
|
await it.return?.();
|
||||||
|
for (const m of ['a', 'b', 'c']) inbound.push(m);
|
||||||
|
await tick();
|
||||||
|
expect(closes).toEqual([]);
|
||||||
|
expect((await it.next()).done).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fans out: two consumers waiting at once both receive the frame', async () => {
|
||||||
|
const { socket, inbound } = fakeSocket();
|
||||||
|
const bounded = boundInbound(socket);
|
||||||
|
const a = bounded.inbound[Symbol.asyncIterator]();
|
||||||
|
const b = bounded.inbound[Symbol.asyncIterator]();
|
||||||
|
const [nextA, nextB] = [a.next(), b.next()];
|
||||||
|
inbound.push('x');
|
||||||
|
expect(await nextA).toEqual({ value: 'x', done: false });
|
||||||
|
expect(await nextB).toEqual({ value: 'x', done: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fans out: a consumer that returns does not end the next one', async () => {
|
||||||
|
const { socket, inbound } = fakeSocket();
|
||||||
|
const bounded = boundInbound(socket);
|
||||||
|
const first = bounded.inbound[Symbol.asyncIterator]();
|
||||||
|
const firstNext = first.next();
|
||||||
|
inbound.push('a');
|
||||||
|
expect(await firstNext).toEqual({ value: 'a', done: false });
|
||||||
|
await first.return?.();
|
||||||
|
const second = bounded.inbound[Symbol.asyncIterator]();
|
||||||
|
const secondNext = second.next();
|
||||||
|
inbound.push('b');
|
||||||
|
expect(await secondNext).toEqual({ value: 'b', done: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fans out: the bound applies to each consumer, so one stalled reader closes 1013', async () => {
|
||||||
|
const { socket, inbound, closes } = fakeSocket();
|
||||||
|
const bounded = boundInbound(socket, { maxWsQueue: 2 });
|
||||||
|
const reader = bounded.inbound[Symbol.asyncIterator]();
|
||||||
|
bounded.inbound[Symbol.asyncIterator](); // subscribed, never reads
|
||||||
|
for (const m of ['a', 'b', 'c']) {
|
||||||
|
const got = reader.next();
|
||||||
|
inbound.push(m);
|
||||||
|
await got;
|
||||||
|
}
|
||||||
|
expect(closes).toEqual([[1013, 'inbound queue full']]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fans out: a frame that overflows any queue reaches no consumer', async () => {
|
||||||
|
const { socket, inbound, closes } = fakeSocket();
|
||||||
|
const bounded = boundInbound(socket, { maxWsQueue: 1 });
|
||||||
|
const fast = bounded.inbound[Symbol.asyncIterator]();
|
||||||
|
bounded.inbound[Symbol.asyncIterator](); // stalled
|
||||||
|
const first = fast.next();
|
||||||
|
inbound.push('a'); // fast takes it, stalled queues it: 1/1
|
||||||
|
expect(await first).toEqual({ value: 'a', done: false });
|
||||||
|
const second = fast.next();
|
||||||
|
inbound.push('b'); // stalled is full: rejected for everyone
|
||||||
|
expect(closes).toEqual([[1013, 'inbound queue full']]);
|
||||||
|
expect(await second).toEqual({ value: undefined, done: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('enforces the queue bound inside a synchronous burst, before the event loop yields', () => {
|
||||||
|
const { socket, inbound, closes } = fakeSocket();
|
||||||
|
const bounded = boundInbound(socket, { maxWsQueue: 2 });
|
||||||
|
bounded.inbound[Symbol.asyncIterator](); // stalled
|
||||||
|
for (let i = 0; i < 100_000; i++) inbound.push(String(i)); // what `ws` does with one TCP read
|
||||||
|
expect(closes).toEqual([[1013, 'inbound queue full']]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('enforces the size bound synchronously too', () => {
|
||||||
|
const { socket, inbound, closes } = fakeSocket();
|
||||||
|
boundInbound(socket, { maxWsMessageBytes: 3 });
|
||||||
|
inbound.push('abcd');
|
||||||
|
expect(closes).toEqual([[1009, 'message too large']]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T15: keeps the socket capabilities other than inbound', () => {
|
||||||
|
const { socket } = fakeSocket();
|
||||||
|
const bounded = boundInbound(socket);
|
||||||
|
expect(bounded.isOpen).toBe(true);
|
||||||
|
expect(bounded.abort).toBe(socket.abort);
|
||||||
|
bounded.close(1000, 'bye');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
import { describe, it, expect, beforeAll, afterAll, afterEach } from 'vitest';
|
||||||
|
import net from 'net';
|
||||||
|
import type http from 'http';
|
||||||
|
import WebSocket from 'ws';
|
||||||
|
import { createApp, Route, Get, Ws, Module, ctx } from '../src/index';
|
||||||
|
|
||||||
|
// Regression for #104: these drive the real Node `'upgrade'` listener through a `listen(0)` server,
|
||||||
|
// not `app.upgrade`. The requests are written by hand over a raw socket because a WebSocket client
|
||||||
|
// refuses or re-encodes the malformed URLs this is about.
|
||||||
|
|
||||||
|
@Route('/rt')
|
||||||
|
class Rt {
|
||||||
|
@Ws('/echo')
|
||||||
|
echo(@ctx() { inbound }: any) {
|
||||||
|
return (async function* () {
|
||||||
|
for await (const msg of inbound) yield `echo:${msg}`;
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
|
||||||
|
// A param route is what makes the bad escape fatal: only param segments are decoded on match.
|
||||||
|
@Ws('/room/:name')
|
||||||
|
room(@ctx() { inbound }: any) {
|
||||||
|
return (async function* () {
|
||||||
|
for await (const msg of inbound) yield `room:${msg}`;
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Route('/health')
|
||||||
|
class Health {
|
||||||
|
@Get('/')
|
||||||
|
ok() {
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', controllers: [Rt, Health] })
|
||||||
|
class M {}
|
||||||
|
|
||||||
|
/** Writes a raw upgrade request for `path` and resolves with everything the server sent before closing. */
|
||||||
|
function rawUpgrade(port: number, path: string): Promise<string> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const socket = net.connect(port, '127.0.0.1');
|
||||||
|
let data = '';
|
||||||
|
socket.on('connect', () =>
|
||||||
|
socket.write(
|
||||||
|
`GET ${path} HTTP/1.1\r\nHost: 127.0.0.1\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n` +
|
||||||
|
'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
socket.on('data', (chunk) => (data += chunk.toString()));
|
||||||
|
socket.on('close', () => resolve(data));
|
||||||
|
socket.on('error', reject);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('Node upgrade listener rejects malformed upgrades (#104)', () => {
|
||||||
|
let server: http.Server;
|
||||||
|
let port: number;
|
||||||
|
const uncaught: unknown[] = [];
|
||||||
|
const onUncaught = (err: unknown) => uncaught.push(err);
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
process.on('uncaughtException', onUncaught);
|
||||||
|
process.on('unhandledRejection', onUncaught);
|
||||||
|
const app = createApp({ modules: [M] });
|
||||||
|
server = await app.listen(0);
|
||||||
|
port = (server.address() as { port: number }).port;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
process.off('uncaughtException', onUncaught);
|
||||||
|
process.off('unhandledRejection', onUncaught);
|
||||||
|
await new Promise((r) => server.close(r));
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(async () => {
|
||||||
|
// T6: a normal request on a new connection succeeds after every rejected upgrade.
|
||||||
|
const res = await fetch(`http://127.0.0.1:${port}/health`);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(uncaught).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T1: malformed percent-encoding gets a 400 and the socket closes', async () => {
|
||||||
|
expect(await rawUpgrade(port, '/rt/%E0%A4%A')).toMatch(/^HTTP\/1\.1 400 /);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T1: malformed percent-encoding in a param segment gets a 400 instead of crashing', async () => {
|
||||||
|
expect(await rawUpgrade(port, '/rt/room/%E0%A4%A')).toMatch(/^HTTP\/1\.1 400 /);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T2: invalid hex in a percent escape gets a 400', async () => {
|
||||||
|
expect(await rawUpgrade(port, '/rt/room/%ZZ')).toMatch(/^HTTP\/1\.1 400 /);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T3: a repeated slash gets a 400 instead of matching /rt/echo', async () => {
|
||||||
|
expect(await rawUpgrade(port, '//rt//echo')).toMatch(/^HTTP\/1\.1 400 /);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T4: a long path below the header limit takes the normal miss path (404)', async () => {
|
||||||
|
expect(await rawUpgrade(port, `/rt/${'a'.repeat(8 * 1024)}`)).toMatch(/^HTTP\/1\.1 404 /);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T5: an unknown ws route gets a written 404, then close', async () => {
|
||||||
|
expect(await rawUpgrade(port, '/nope')).toMatch(/^HTTP\/1\.1 404 /);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T7: a valid upgrade still echoes', async () => {
|
||||||
|
const client = new WebSocket(`ws://127.0.0.1:${port}/rt/echo`);
|
||||||
|
await new Promise((r) => client.on('open', r));
|
||||||
|
const got = new Promise<string>((r) => client.on('message', (d) => r(d.toString())));
|
||||||
|
client.send('hi');
|
||||||
|
expect(await got).toBe('echo:hi');
|
||||||
|
client.close();
|
||||||
|
});
|
||||||
|
});
|
||||||
+1
-1
@@ -9,7 +9,7 @@ export default defineConfig({
|
|||||||
dts: true,
|
dts: true,
|
||||||
clean: true,
|
clean: true,
|
||||||
sourcemap: true,
|
sourcemap: true,
|
||||||
target: 'node18',
|
target: 'node22',
|
||||||
// Give the ESM output a real `require` (via createRequire) so the lazy require('ws') / require('busboy')
|
// Give the ESM output a real `require` (via createRequire) so the lazy require('ws') / require('busboy')
|
||||||
// (optional peer deps) resolve instead of hitting esbuild's "Dynamic require not supported" stub.
|
// (optional peer deps) resolve instead of hitting esbuild's "Dynamic require not supported" stub.
|
||||||
esbuildOptions(options, context) {
|
esbuildOptions(options, context) {
|
||||||
|
|||||||
Reference in new issue
Block a user