11 Commits
Author SHA1 Message Date
chrnx 3296189093 feat(http): response compression with gzip and br (CARD-16, #112)
CI / runtimes (edge) (pull_request) Successful in 19s
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 17s
CI / build (pull_request) Successful in 28s
CI / runtimes (deno) (pull_request) Successful in 23s
Text responses went out uncompressed unless a proxy sat in front of every
runtime. createApp({ compression: true | { threshold, encodings } }), off
by default, implements D13 strategy B as accepted on 2026-10-22.

- One function, compressOutcome, runs after handle() and before either
  adapter writes, so Node and the fetch runtimes cannot diverge.
- Accept-Encoding negotiation with q-values, identity, * and q=0; ties go
  to server preference (br before gzip). Vary: Accept-Encoding is merged
  wherever the request decided the outcome, including every 304. Skips:
  existing Content-Encoding or Content-Range, no or an incompressible
  Content-Type (ndjson is compressible), Cache-Control: no-transform.
  HEAD and bodies under threshold keep Vary; 204 gets none.
- Node, Deno, Bun: node:zlib only, loaded lazily through nodeRequire.
  Buffered bodies use the async API, never the sync one; br at quality 4.
  Content-Length is dropped from an encoded body.
- Streams (SSE, ndjson): a zlib stream flushed after every frame, error
  frame and ping, piped into res on Node and wrapped around the
  ReadableStream on fetch runtimes. Backpressure follows the compressor;
  a client leaving destroys it.
- Edge: core never encodes and sets Vary only. Edge is recognised by
  edgeHandler, which marks the app through an internal symbol, and by
  createApp detecting workerd (navigator.userAgent, or node:zlib failing
  to load), which covers a bare app.fetch export.
- ETags from CARD-15 are taken on the identity body and stay weak, so the
  tag does not change with the coding.

Deno runs zlib's async API on the main thread; that is documented and
pinned by a test, not worked around.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:12:48 -05:00
chrnx c22c37e0b3 Merge pull request 'feat(http): ETag and 304 for static files and buffered responses (CARD-15, #114)' (#144) from feature/fprd-001c-etag into develop
CI / runtimes (bun) (push) Successful in 16s
CI / build (push) Successful in 28s
CI / runtimes (deno) (push) Successful in 21s
Promote → GitHub / push-github (push) Successful in 5s
CI / runtimes (edge) (push) Successful in 14s
CI / dco (push) Has been skipped
2026-10-23 06:11:40 +00:00
chrnx d32fc9f8d7 feat(http): ETag and 304 for static files and buffered responses (CARD-15, #114)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / runtimes (deno) (pull_request) Successful in 21s
CI / runtimes (edge) (pull_request) Successful in 13s
CI / build (pull_request) Successful in 27s
Conditional GETs were never answered: every revalidation re-downloaded
the file or response.

- Static (D12, always on): a hit carries W/"<size>-<mtimeMs base36>",
  Last-Modified and Cache-Control from the stat the resolver already did.
  A matching If-None-Match, or If-Modified-Since when If-None-Match is
  absent, answers 304 before the file is read. StaticHit now carries the
  stat and a read() for the bytes, and HEAD no longer reads either.
- static: { dir?, cacheControl? } (rule 1a): Cache-Control defaults to
  no-cache so browsers revalidate rather than reuse a file for a lifetime
  guessed from Last-Modified. An unknown key or CR/LF throws at boot.
- createApp({ etag: true }) (off by default, boolean only): a buffered 200
  to GET/HEAD gets a weak tag from a 32-bit FNV-1a hash of its UTF-8 bytes
  plus its length, computed before HEAD blanks the body. A handler-set
  etag is kept and only compared. Weak comparison, lists split outside
  quotes, and * are supported.
- Every buffered 304 leaves dispatch bodiless, with its content-* headers
  dropped, so NotModified matches the ETag path on every adapter.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:09:54 -05:00
chrnx 50010da88d Merge pull request 'feat(http)!: cookie decorators, setCookie, and string | string[] response headers (CARD-14, #113)' (#140) from feature/fprd-001c-cookies into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 15s
CI / build (push) Successful in 27s
CI / runtimes (deno) (push) Successful in 21s
CI / runtimes (edge) (push) Successful in 14s
Promote → GitHub / push-github (push) Successful in 6s
2026-10-23 06:09:50 +00:00
chrnx 7f9a0eef0f feat(http)!: cookie decorators, setCookie, and string | string[] response headers (CARD-14, #113)
CI / runtimes (edge) (pull_request) Successful in 14s
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 27s
CI / runtimes (deno) (pull_request) Successful in 20s
Reading a cookie meant parsing the Cookie header by hand, and a response
could not carry more than one Set-Cookie: response header values were
Record<string, string>, and the fetch adapters would have stringified an
array into one broken "a,b" cookie anyway.

- @cookie('name') / @cookies() sit next to @header/@headers as a new
  'cookies' arg source. The header is parsed on first use per request and
  cached on the context, so a route without a cookie argument never parses
  it. RFC 6265: first value wins, %-sequences decoded, malformed pairs
  skipped (never a 400), undecodable values kept raw. Several cookie lines
  are joined with "; ". The map has no prototype. @needs('cookies') reads
  the same map, and 'cookies' joins the seed-key allow-list.
- setCookie(name, value, options) serialises one Set-Cookie value with
  HttpOnly, SameSite=Lax, Path=/ and Secure by default (D10), and throws,
  naming the field, on anything that could inject a header or that browsers
  reject (sameSite none / partitioned without secure).
- Response header values widen to string | string[] (D11) across
  TransformerFn, ErrorResponse, HttpError(Like).headers, ResponseShape and
  the neutral outcome. Node writes a set-cookie array as one line per
  element and joins every other array with ", " before writeHead; the
  fetch adapters build a Headers and append each set-cookie element.
  mergeInjectedHeaders keeps arrays by reference and joins a vary array
  before merging it.
- OpenAPI maps a cookie argument to an in: cookie parameter.

BREAKING CHANGE: code that reads a header value from TransformerFn,
ErrorResponse, HttpError or ResponseShape as a string must handle string[].

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:08:24 -05:00
chrnx 037e695a31 Merge pull request 'feat(mesh): remote routes follow teapot membership (CARD-19, #124)' (#146) from feature/fprd-001c-mesh-membership into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 16s
CI / build (push) Successful in 28s
CI / runtimes (deno) (push) Successful in 20s
CI / runtimes (edge) (push) Successful in 14s
Promote → GitHub / push-github (push) Successful in 6s
2026-10-23 06:08:09 +00:00
chrnx 9ea1365b66 test(router-parity): a late teapot is served after it connects for CARD-19 (owner approval required)
CI / runtimes (bun) (pull_request) Successful in 16s
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 26s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 14s
owner-mesh-lifetime.json froze phase B2 (teapot absent at boot, then up)
at 404 for GET and POST /api/remote/ping. The table was built once at
boot, so a late teapot was never spliced in. CARD-19 (#124, D15) changes
that. B2 now answers GET 200 {"from":"teapot"} and POST 405 with
Allow: GET, HEAD, OPTIONS, the same as A1.

Only those two entries change. A1, A2 and B1 are identical.

The fixture's teacup goes from reconnect: false to reconnect with a fast
backoff (20-60ms). Under D15, reconnect: false makes a dropped teapot
"gone" (404), and an absent one is not retried. The card's phases
describe the reconnecting teacup: A2 stays 503 and B2 becomes 200. B2
now waits for the mesh:routes event before probing. The fixture comment
and the corpus README line describing "built once at boot" are updated.

Owner approval required (CARD-08 rule): this edits a frozen file and the
fixture under test/router-parity/.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:04:40 -05:00
chrnx 6bbd78fc8e feat(mesh): remote routes follow teapot membership (CARD-19, #124)
The teacup built its route table once at boot. A teapot that started
late was never served, and one that was gone for good stayed advertised.
Implement D15 (accepted 2026-10-18):

- A teapot that missed bootTimeoutMs is retried in the background with
  the reconnect backoff (not with reconnect: false). On connect its
  routes join the remote table. Its steps do not, because the graph
  was validated at boot without them.
- While a link is reconnecting, its routes stay and answer 503, now
  with retry-after (seconds until the next attempt).
- A link that gives up for good (dropped with reconnect: false, or a
  permanent refusal while reconnecting) has its routes removed: 404,
  and Allow drops its methods. A refused reconnect no longer retries
  forever.
- A returning manifest replaces the teapot's routes. missingFromManifest
  now checks steps only, so a dropped route is removed instead of
  refusing the reconnect.
- A late route that conflicts with another teapot's is refused and
  logged. The table keeps serving. At boot the same conflict still
  fails boot.
- Each change emits mesh:routes with { url, added, removed }.
- The reserved-path check from CARD-21/CARD-17 (#141, #145) runs in
  the table for every remote route: at boot a route on /__mesh__/control
  (or /__live__ and /__ready__ with health on) fails boot as before. A
  late or returning one is refused and logged, and the teapot's other
  routes are served.

Mechanics: the remote table publishes a new array per change
(copy-on-write). app.fetch and listen() share one table through a
getter, and buildFetch/createHttpServer read it once per request, so a
request sees the old table or the new one, never a mix. The router
reuses local trees when the local entries are identical, so a
membership change rebuilds only the remote trees. Dev routes now sit
before remote ones in the table to keep the local positions stable.

Tests cover T1-T8 on Node (test/mesh/membership.test.ts), plus the
local-tree build counter and late reserved-path routes, and T1/T2 on
Deno and Bun.

The frozen owner-mesh-lifetime.json capture changes in the next commit.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:04:39 -05:00
chrnx c9e76fde2d Merge pull request 'fix(mesh): answer HEAD on a remote GET route (CARD-20, #125)' (#137) from feature/fprd-001c-mesh-remote-head into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 16s
CI / build (push) Successful in 27s
CI / runtimes (deno) (push) Successful in 21s
CI / runtimes (edge) (push) Successful in 14s
Promote → GitHub / push-github (push) Successful in 6s
2026-10-23 06:04:35 +00:00
chrnx ae9e5529e8 test(router-parity): HEAD on a remote GET answers 200 for CARD-20 (owner approval required)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 26s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / runtimes (deno) (pull_request) Successful in 20s
owner-mesh-allow.json froze HEAD /api/x at 404 on both adapters: the
teacup forwarded HEAD to the teapot, which has no HEAD plan for the
route. CARD-20 (#125, D16) fixes that, so HEAD now answers 200 with the
GET's headers and an empty body, like a local route.

Only those two entries change (fetch and node), status 404 -> 200.
Headers and the empty body are identical. The fixture comment in
owner.test.ts that described the old behaviour is updated to match.

Owner approval required (CARD-08 rule): this edits a frozen file under
test/router-parity/.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:59:56 -05:00
chrnx 5783212377 fix(mesh): answer HEAD on a remote GET route (CARD-20, #125)
The teacup's router resolves HEAD to a remote buffered GET through the
implicit-HEAD fallback, and OPTIONS advertises HEAD. But the remote
route handler forwarded req.method, so the teapot got a HEAD envelope,
found no HEAD plan in resolveRoute, and answered 404.

Forward a HEAD that matched a remote GET as GET. dispatch already drops
the body for HEAD, so the client gets the GET's status and headers and
no body, the same as a local route. An explicit remote HEAD route is
matched first and is still forwarded as HEAD.

The fix is teacup-side (D16, accepted 2026-10-22): the teapot and the
wire protocol are unchanged, so a new teacup works against an older
teapot during a rolling deploy.

Tests cover app.fetch and the Node listener (200 + GET headers + empty
body, OPTIONS, explicit HEAD precedence, 404/500 kept with no body, the
teapot handler called once as GET) and Deno and Bun.

The frozen owner-mesh-allow.json capture changes in the next commit.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:59:56 -05:00
59 changed files with 4476 additions and 309 deletions

No files matched your search

+1
View File
@@ -22,6 +22,7 @@ coverage/
# Edge (Miniflare) test bundle artifact
test/edge/_worker.mjs
test/edge/_parity-worker.mjs
test/edge/_compression-worker.mjs
# Bun writes this on `bun install`, and nothing here consumes it: `npm run test:bun` runs
# `bun test` against the node_modules npm installed, which package-lock.json already pins.
+94
View File
@@ -10,6 +10,15 @@ npm treats versions as semver and semver forbids leading zeros.
### Breaking
- **Response header values are `string | string[]`** (#113, D11). `TransformerFn`, `ErrorResponse.headers`,
`HttpError.headers` / `HttpErrorLike.headers` and the pipeline's `ResponseShape.headers` widen from
`Record<string, string>`, so a response can carry several `Set-Cookie` lines. Code that *produces*
headers is unaffected; code that *reads* `headers[k]` from one of these types as a `string` stops
compiling and must handle the array. A `set-cookie` array is sent as one header line per element
on Node, Deno, Bun and the edge — before, the fetch adapters stringified it into one broken
`a,b` cookie. Any other array is sent as one line joined with `, `. Injected security and CORS
headers stay authoritative, and a handler's `vary` array is merged with the injected one.
- **Node 18 and Node 20 are no longer supported; the minimum is Node 22.** Both are end-of-life
and receive no security patches, so `engines.node` is now `>=22`, CI runs Node 22 only, and the
build targets `node22`. Node 22 is the oldest line still maintained. The `node:crypto` fallback
@@ -112,6 +121,46 @@ npm treats versions as semver and semver forbids leading zeros.
`false` or `{ drainDelayMs?: number }`. On the edge there is no `close()`, so `/__ready__` never
reports `draining` there.
- **`createApp({ compression })`** (#112, D13): response compression, off by default. `true`, or
`{ threshold?, encodings? }` (default `1024` bytes and `['br', 'gzip']`, in preference order).
`Accept-Encoding` is negotiated with q-values, `identity`, `*` and `q=0`, and ties go to server
preference. Text, JSON, JavaScript, ndjson, SVG, XML and wasm are compressed. A response that
already has `Content-Encoding` or `Content-Range`, has no `Content-Type`, or says
`Cache-Control: no-transform` is left alone. `Vary: Accept-Encoding` is added wherever the request
decided the outcome: identity clients, `HEAD`, bodies under the threshold and every `304`.
`Content-Length` is dropped from an encoded body. SSE and ndjson streams are compressed too,
flushed after every event, error frame and ping, so each event decodes when it arrives.
Per runtime:
- **Node and Bun:** async `node:zlib`, br at quality 4.
- **Deno:** the same code, but Deno 2.9 runs zlib's async API on the main thread, so compression
costs event-loop time there (about 4× slower than Node for a 51 KB gzip under load).
- **Edge:** core never encodes and sets only `Vary`; Cloudflare applies the encoding. Edge is
recognised through `edgeHandler` or by detecting workerd at `createApp`.
ETags (`etag: true`) are taken before encoding and stay the same across codings. No dependency;
invalid options throw.
- **`createApp({ etag: true })`** (#114, D12): weak ETags for buffered `200` responses to `GET` and
`HEAD`, from a 32-bit FNV-1a hash of the body plus its length. A matching `If-None-Match` (weak
comparison, lists, `*`) gets a `304` with no body. A handler that sets its own `etag` keeps it, and
that tag drives the comparison. Streams, non-200 responses and other methods are never tagged.
The handler still runs. Off by default; anything but a boolean throws at `createApp`.
- **`static: { dir?, cacheControl? }`** (#114): the object form of `static` sets the
`Cache-Control` sent with static files and their `304`s (for example
`'public, max-age=31536000, immutable'` for hashed assets). `static: true` and `static: '<dir>'`
keep working. An unknown key, or a `cacheControl` with CR/LF, throws at `createApp`.
- **`@cookie('name')` / `@cookies()` argument decorators and `setCookie()`** (#113). Cookies are
parsed from the request's `Cookie` header on first use per request (RFC 6265: first value wins,
`%`-sequences decoded, malformed pairs skipped rather than answered with a 400), on HTTP and
WebSocket routes; `@needs('cookies')` gives the same map. OpenAPI lists a cookie argument as an
`in: cookie` parameter. `setCookie(name, value, options?)` returns a `Set-Cookie` value with
`HttpOnly`, `SameSite=Lax`, `Path=/` and `Secure` by default (D10; `secure: false` opts out), and
throws, naming the field, on a name outside the token set, a value with CR, LF, `;`, `,`,
whitespace or a control character, an attribute with CR/LF, `;` or a control character, and on
`sameSite: 'none'` or `partitioned` without `secure`. `parseCookies()` and `CookieOptions` are
exported too. No dependency: signing and sessions stay out of core.
- **`limits.maxWsMessageBytes` and `limits.maxWsQueue`** (#107): per-connection bounds on inbound
WebSocket messages, in bytes and in unread messages, server-wide on every runtime. `createApp`
throws a `TypeError` for anything but a positive integer. Node and Bun refuse an oversized message
@@ -123,6 +172,16 @@ npm treats versions as semver and semver forbids leading zeros.
### Changed
- **Static files are revalidated, not re-downloaded** (#114, D12). Every static hit carries a weak
`ETag` (`W/"<size>-<mtime>"`), `Last-Modified` and `Cache-Control: no-cache`. A matching
`If-None-Match`, or `If-Modified-Since` when there is no `If-None-Match`, answers `304` from the
file's `stat` without reading it. A `HEAD` no longer reads the file either. `no-cache` stops
browsers from reusing a file for a lifetime they guessed from `Last-Modified`. To keep the old
behaviour, set `static: { cacheControl }` to whatever your proxy expects.
- **Every `304` is bodiless** (#114). A `304` has no body and no `content-*` headers on any adapter,
including one from `throw new NotModified()`, which used to go out with the default JSON
envelope's `content-type`.
- **HTTP route lookup uses a radix index** (#109). The router used to scan a specificity-sorted
list per method, and on every 404 and 405 it recompiled and matched every route to build `Allow`.
It now walks a tree per method, built once from the route table, with mesh routes from teapots
@@ -139,6 +198,33 @@ npm treats versions as semver and semver forbids leading zeros.
`?` and before `#`, if there is one: `q: 'what?now'`, and `/search?a=1&b=?` gives `b: '?'`. URLs
with a single `?` parse as before. Path extraction is unchanged.
- **Mesh (alpha): a teacup's remote routes follow which teapots are connected** (#124, D15). The
route table used to be built once at boot: a teapot that started late was never served, and a
teapot that was gone for good stayed advertised. Now:
- A teapot that missed `bootTimeoutMs` is retried in the background with the `reconnect` backoff.
When it connects, its routes are served, with no restart. Its steps are not added, because the
graph was validated at boot without them. With `reconnect: false` it is not retried.
- While a link is reconnecting, its routes stay and answer `503`, now with `retry-after` (the
seconds until the next attempt). `Allow` keeps them.
- A link that gives up for good has its routes removed: they answer `404` and leave `Allow`. That
is a link dropped with `reconnect: false`, or one refused permanently (a wrong secret, a protocol
mismatch) while reconnecting. A refused reconnect used to retry forever. It now stops.
- A returning teapot's routes replace its old ones: a route it added is served, one it dropped
answers `404`. A returning manifest is still refused for a missing **step**
(`onManifestChange: 'refuse'`), but no longer for a missing route.
- A late route that conflicts with another teapot's (same shape, or a CARD-13 sibling conflict)
is refused and logged, and the rest keep serving. At boot the same conflict still fails boot.
- A late or returning route on a reserved path (`/__mesh__/control`, and `/__live__`/`/__ready__`
with `health` on) is refused and logged the same way. At boot it still fails boot.
- Every change emits `mesh:routes` with `{ url, added, removed }` (new `EventPayload` fields).
Membership changes publish a new table. A request in flight routes against the old one or the
new one, never a mix. Only the remote route trees are rebuilt. `listen()` now reads the same
table as `app.fetch`, and `createHttpServer` accepts a getter as well as an array. Dev
introspection routes (`devGraph`, `devOpenapi`) now sit before remote routes in that table, so
in the one case where a teapot exports the same path at the same specificity, the dev route wins.
### Fixed
- **Edge HTTP fills `ctx.ip` from `cf-connecting-ip` under `trustProxy`** (#119). `edgeHandler`
@@ -148,6 +234,14 @@ npm treats versions as semver and semver forbids leading zeros.
Without `trustProxy` it is ignored. Only `edgeHandler` reads it: the Node, Deno and Bun adapters, and a
bare `app.fetch`, ignore it as before.
- **Mesh (alpha): `HEAD` on a remote `GET` route now works** (#125). The teacup resolved `HEAD` to
the remote `GET` and `OPTIONS` advertised `HEAD`, but the request went to the teapot as `HEAD`,
which has no `HEAD` plan, so it answered `404`. The teacup now forwards it as a `GET` and drops
the body, so it answers like a local route: the `GET`'s status and headers, no body, and a
`404`/`500` from the route keeps its status. An explicit remote `HEAD` route still takes
precedence. The teapot is unchanged, so a new teacup works against an older teapot during a
rolling deploy.
- **`static` no longer serves files outside its root through a symlink** (#106). The traversal guard
compared paths lexically, and the file read then followed symlinks, so `public/leak -> /etc/hosts`
was served. Containment now compares real paths: the requested file, and a directory's
+6 -2
View File
@@ -140,7 +140,7 @@ without growing the runtime dependency tree past `reflect-metadata`:
- **Validation via [Standard Schema](https://standardschema.dev).** `@body(schema)` accepts zod, valibot, or arktype — you bring the validator, the core stays zero-dep. Invalid input → `422` with per-field issues; the parsed value reaches your handler typed.
- **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS.
- **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response.
- **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency.
- **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency. Static files carry a weak `ETag`, `Last-Modified` and `Cache-Control: no-cache` (change it with `static: { dir, cacheControl }`), and a conditional request gets a `304` without the file being read. `createApp({ etag: true })` does the same for buffered `GET`/`HEAD` handler responses, and `createApp({ compression: true })` compresses text responses and event streams with gzip or br. It uses `node:zlib` on Node, Deno and Bun, and leaves encoding to the platform on the edge.
- **Resource ceilings, with safe defaults.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. `maxConcurrentRequests` is opt-in and applies per server or Fetch adapter instance; when set, excess in-flight requests receive `503` and `Retry-After: 1`. It bounds concurrently executing handlers, so a handler that never returns continues to hold its slot; on Node, a client disconnect releases that slot. Long-lived streams and WebSocket upgrades do not hold that request budget. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there. WebSocket connections are bounded too: `maxWsMessageBytes` (default 1 MiB) closes a connection whose message is larger with `1009`, and `maxWsQueue` (default `16`) closes one that has that many unread inbound messages and receives another with `1013`, rather than dropping anything. Both are server-wide and must be positive integers. Node and Bun refuse an oversized message before buffering it (Bun before 1.4 drops the connection, so its peer sees `1006`; Bun 1.4 and later send `1009`); Deno and the edge check it after the runtime has received it. Worst case, a server buffers about `maxConnections × maxWsQueue × maxWsMessageBytes` of inbound messages — ≈ 15.6 GiB at the Node defaults.
- **Observability without an integration.** Every request carries an id and a trace id through every lifecycle event, each step reports its own duration, and `createApp({ logger })` accepts any logger — the default writes structured JSON. Nothing in core writes to `console`. Metrics and tracing exporters read the same stream from outside core.
- **Graceful shutdown, with a deadline.** `app.close()` drains in-flight requests and closes live streams and mesh links, then warns and force-closes whatever is still open after 10 seconds — so a stuck handler cannot hold a deploy open forever. Change the number per call with `close({ timeoutMs })` or for the whole app with `createApp({ shutdownTimeoutMs })`. Connection *draining* is Node-only; on Deno and Bun the server `serveDeno()`/`serveBun()` returns carries the same `close({ timeoutMs })`.
@@ -244,6 +244,10 @@ The handler signature declares exactly what it wants — in any order, nothing m
| `@body(...)` | parsed body (JSON / urlencoded / multipart) | `()` · `('field')` · `(schema)` |
| `@headers(...)` | request headers (whole bag or picked) | `()` · `('authorization')` · `(['a','b'])` · `(schema)` |
| `@header('name')` | one request header (singular alias of `@headers`) | `('x-trace')` · `('x-count', schema)` |
| `@cookies(...)` | request cookies, parsed from `Cookie` (whole map or picked) | `()` · `('sid')` · `(['a','b'])` · `(schema)` |
| `@cookie('name')` | one request cookie (singular alias of `@cookies`) | `('sid')` · `('sid', schema)` |
To send cookies, `setCookie(name, value, options?)` returns a `Set-Cookie` value with safe defaults (`HttpOnly`, `SameSite=Lax`, `Path=/`, `Secure`) and throws on anything that could inject a header. Response header values are `string | string[]`: a `set-cookie` array is sent as one line per cookie on every runtime, any other array as one line joined with `, `. Pass `secure: false` where the browser will not keep a `Secure` cookie over plain HTTP (Safari, a LAN IP). Signing and sessions are not in core.
`@needs` keys are validated at boot: nothing provides the key → `createApp` throws with a clear error instead of serving `undefined`. Pass a Standard Schema (`@body(User)`) and the value is validated, coerced, and typed before your handler sees it.
@@ -292,7 +296,7 @@ green-tea is **beta**, on the road to a release candidate. Express and Fastify h
**What is not here:** no metrics registry, and **no OpenTelemetry exporter in core** — that is a separate package, because core has one runtime dependency and intends to keep it. A `traceparent` header is carried through untouched for an exporter to interpret; core implements no propagation spec. If your definition of production-ready includes shipping traces on day one, you are writing the exporter, and the stream it needs is the part that now exists.
**Runtimes differ in what they can offer.** Node ≥ 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.
**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. With `compression`, core never encodes on the edge (Cloudflare does), and on Deno it runs zlib on the main thread, where Deno's own `automaticCompression` is the faster gzip.
**mesh is alpha.** Distributed DI works, but discovery, load-balancing, and failover are not built, and its API and wire protocol may change between releases. It is gated behind an explicit opt-in — `createApp({ mesh, experimental: true })` — and `createApp` throws if you configure `mesh` without it. Don't ship mesh to production yet.
+1 -1
View File
@@ -90,7 +90,7 @@
"test:dev": "vitest",
"test:deno": "deno test --allow-net --allow-read --allow-run --allow-env --no-check test/deno/",
"test:bun": "bun test test/bun/",
"test:edge": "tsx test/edge/run.ts",
"test:edge": "tsx test/edge/run.ts && tsx test/edge/compression.ts",
"test:all": "npm test && npm run test:deno && npm run test:bun && npm run test:edge && deno publish --dry-run --allow-dirty",
"typecheck": "tsc --noEmit -p tsconfig.json",
"typecheck:bench": "tsc --noEmit -p bench/tsconfig.json",
+404 -119
View File
@@ -9,6 +9,7 @@ import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } fro
import type { HttpOptions } from '../http';
import { trustedProxyClient } from '../http/peer';
import { answerFetchProbe, buildFetch } from '../http/web';
import { resolveCompression, edgeMarker, MARK_EDGE, type CompressionOptions } from '../http/compression';
import {
boundInbound,
validateWsLimits,
@@ -38,13 +39,13 @@ import {
type RouteMeta,
type TransformerFn,
} from '../metadata';
import { buildHtmlTransformer, buildStaticResolver, type ViewsContext } from '../views';
import { buildHtmlTransformer, buildStaticResolver, normalizeStatic, type ViewsContext } from '../views';
import { getArgs, getHandlerNeeds, resolveArgs } from '../params';
import { buildOpenApi, type OpenApiInfo } from '../openapi';
import { connectLink, isPermanentRefusal, type Link } from '../mesh/link';
import { Rooms } from '../rooms';
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
import { buildRemote } from '../mesh/teacup';
import { buildRemote, type RemoteRoute as TeacupRemoteRoute } from '../mesh/teacup';
import { buildManifest, createMeshControl, MESH_CONTROL_DISABLED_REASON, MESH_CONTROL_PATH } from '../mesh/teapot';
import type { MeshControl } from '../http';
import type { RequestEnvelope, RouteEntry } from '../mesh/protocol';
@@ -59,6 +60,9 @@ export type { App, InspectLine, ExplainNode, Explain, MeshConfig, Hooks } from '
type Runner = (ctx: any) => any;
/** Something shutdown closes: a mesh link, or the retry loop of a teapot that missed boot. */
type Closable = Pick<Link, 'close'>;
/** Mutable graph state assembled from modules/plugins and later spliced with remote mesh scopes. */
interface Registry {
providerNodes: GraphNode[];
@@ -156,8 +160,53 @@ export function createApp(opts: {
views?: string;
/** Bring-your-own template engine for `@Html(..., { template: true })`; defaults to the built-in `render`. */
viewEngine?: (source: string, data: unknown) => string;
/** Serve a static directory as a GET/HEAD fallback (after declared routes, before 404). `true` → `./public`. */
static?: boolean | string;
/**
* Serve a static directory as a GET/HEAD fallback (after declared routes, before 404). `true` →
* `./public`; a string is the directory; `{ dir?, cacheControl? }` also sets `Cache-Control`.
*
* Every hit carries a weak `ETag` and `Last-Modified` from the file's `stat`, and a matching
* `If-None-Match` (or `If-Modified-Since` when there is no `If-None-Match`) answers `304` without
* reading the file. `Cache-Control` is `no-cache` unless `cacheControl` says otherwise, so browsers
* revalidate instead of guessing a lifetime from `Last-Modified`; use
* `'public, max-age=31536000, immutable'` for content-hashed assets. An unknown key, or a
* `cacheControl` with CR/LF, throws here. Unavailable on the edge (no filesystem).
*/
static?: boolean | string | { dir?: string; cacheControl?: string };
/**
* Weak ETags for handler responses (default: off). A buffered `200` to GET or HEAD gets
* `ETag: W/"<length>-<hash>"` computed from its body, and a request whose `If-None-Match` matches
* gets a bodiless `304`. A handler that sets its own `etag` header keeps it, and that tag drives the
* comparison. Streams, non-200 responses and other methods are never tagged. The handler still
* runs: this saves bandwidth, not work. Static files are tagged regardless of this option.
* Anything but a boolean throws.
*/
etag?: boolean;
/**
* Response compression (default: off). `true`, or `{ threshold?, encodings? }`: `threshold` is
* the smallest buffered body worth encoding (default `1024` bytes; streams ignore it) and
* `encodings` the codings core may produce, in preference order (default `['br', 'gzip']`).
*
* Negotiated on `Accept-Encoding` (q-values, `identity`, `*`, `q=0`). Text, JSON, JavaScript,
* ndjson, SVG, XML and wasm are compressed; a response that already has `Content-Encoding` or
* `Content-Range`, has no `Content-Type`, or says `Cache-Control: no-transform` is left alone.
* `Vary: Accept-Encoding` is added wherever the choice depended on the request, including every
* `304`. SSE and ndjson streams are compressed too, flushed after every event.
*
* Per runtime:
* - **Node, Bun:** `node:zlib`, async (off the event loop), br at quality 4.
* - **Deno:** the same code, but Deno runs `node:zlib`'s async API on the main thread, so core
* compression costs event-loop time there — about 4× slower than Node for a 51 KB gzip under
* load. Deno's own `automaticCompression` gzip is about 3× faster than core's, but slower for br,
* and it weakens strong ETags on what it encodes.
* - **Edge (Cloudflare Workers):** core never encodes; it sets `Vary` and Cloudflare chooses and
* applies the encoding. Detected through `edgeHandler`, or at `createApp` from
* `navigator.userAgent`. A bare `export default { fetch: app.fetch }` on a Worker with a compat
* date before 2022-03-21 (no `navigator`) is detected only if `node:zlib` fails to load there.
*
* ETags (`etag: true`) are taken on the identity body and are weak, so one tag covers every coding.
* An invalid `threshold` or `encodings` throws.
*/
compression?: boolean | CompressionOptions;
/**
* How long `close()` gives in-flight work before forcing remaining connections shut, in ms
* (default: 10s). `close({ timeoutMs })` still wins per call. Set it here when `close()` is
@@ -232,6 +281,7 @@ export function createApp(opts: {
validateWsLimits(opts.limits);
const health = resolveHealth(opts.health, opts.shutdownTimeoutMs, opts.teardownTimeoutMs);
assertEtagOption(opts.etag);
const bus = new Bus();
const logger = opts.logger ?? createDefaultLogger();
@@ -258,8 +308,7 @@ export function createApp(opts: {
let orderedProviders: GraphNode[] = [];
let orderedSteps: GraphNode[] = [];
let booted = false;
let remoteRoutes: RouteDef[] = [];
const meshLinks: Link[] = [];
const meshLinks: Closable[] = [];
const finalize = (missingNote?: string): void => {
({ orderedProviders, orderedSteps } = finalizeGraph(registry, logger, opts.warnGraphDepth, missingNote));
@@ -278,8 +327,7 @@ export function createApp(opts: {
// can only be built here, after finalize(), and never at construction time.
const prepareGraph = async (): Promise<void> => {
if (opts.mesh && !booted) {
const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger, reserved);
remoteRoutes = spliced.remoteRoutes;
const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger, reserved, publishRemote);
meshLinks.push(...spliced.meshLinks);
// Without this the error is `missing dependency: auth needed by getUser` and says nothing
// about the teapot that was away — which is the actual cause every time it is the cause.
@@ -325,6 +373,11 @@ export function createApp(opts: {
return routes;
};
// The one HTTP route table, shared by app.fetch and listen() — see createRouteTable.
const table = createRouteTable(() => [...buildHttpRoutes(routePlans, pipelineDeps), ...devRoutes()]);
const currentTable = table.current;
const publishRemote = table.publish;
// Boots exactly once, however first triggered (app.fetch, app.upgrade or listen()); calling
// several never double-boots (which would re-run provider factories and their side effects).
const bootGraph = makeAppBooter(
@@ -338,9 +391,12 @@ export function createApp(opts: {
const { bootApp, healthProbe, drain } = trackHealth(health, bootGraph, () => [...degradedProviders]);
const staticResolver = opts.static ? buildStaticResolver(opts.static) : undefined;
const staticConfig = normalizeStatic(opts.static);
const staticResolver = staticConfig ? buildStaticResolver(staticConfig.root, staticConfig.cacheControl) : undefined;
const compression = resolveCompression(opts.compression);
const fetchOpts: HttpOptions = {
compression,
bus,
logger,
limits: opts.limits,
@@ -352,15 +408,9 @@ export function createApp(opts: {
onError: opts.onError,
static: staticResolver,
health: healthProbe,
etag: opts.etag,
};
const fetchFn = buildAppFetch(
routePlans,
{ providedSeed, planSteps, bus, onError: opts.onError, logger },
fetchOpts,
bootApp,
devRoutes,
() => remoteRoutes,
);
const fetchFn = buildAppFetch(fetchOpts, bootApp, currentTable);
const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl, {
limits: opts.limits,
trustProxy: opts.trustProxy,
@@ -373,10 +423,11 @@ export function createApp(opts: {
// and builds the mesh control channel — so Node and Deno/Bun serve an identical graph
await bootApp();
const httpRoutes = [...buildHttpRoutes(routePlans, remoteRoutes, deps), ...devRoutes()];
const wsRoutes = buildWsRoutes(routePlans, deps);
server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, {
// A getter, not an array: mesh membership can change the table after this server starts.
server = createHttpServer(currentTable, wsRoutes, bus, meshControl, {
compression,
bus,
logger,
limits: opts.limits,
@@ -389,6 +440,7 @@ export function createApp(opts: {
onError: opts.onError,
static: staticResolver,
health: healthProbe,
etag: opts.etag,
});
server.on('close', () => closeLinks(meshLinks));
await new Promise<void>((resolve) => server!.listen(port, resolve));
@@ -459,6 +511,9 @@ export function createApp(opts: {
return Object.assign(app, {
[WS_MAX_MESSAGE_BYTES]: wsMessageBytes(opts.limits),
[HEALTH_DRAIN]: drain,
// `edgeHandler` calls this: on the edge core never encodes, whatever detection concluded.
[MARK_EDGE]: edgeMarker(compression),
});
}
@@ -884,7 +939,17 @@ function assertNeedsSatisfiable(
...providerNodes.flatMap((node) => node.provides),
...stepNodes.flatMap((node) => node.provides),
]);
const allowed = new Set<string>([...producedKeys, 'req', 'params', 'query', 'body', 'headers', 'inbound', 'abort']);
const allowed = new Set<string>([
...producedKeys,
'req',
'params',
'query',
'body',
'headers',
'cookies',
'inbound',
'abort',
]);
for (const plan of routePlans) {
for (const need of plan.needs) {
@@ -1046,41 +1111,295 @@ function assertNoRemoteSiblingConflict(accepted: RemoteRoute[], route: RemoteRou
}
}
/** Connects the configured teapots, splices their remote steps into the registry, and returns their routes. */
/** A teapot route the remote table serves: its export, its owner, and the def the router files. */
interface ServedRemote extends RemoteRoute {
def: RouteDef;
}
/**
* The teacup's remote routes, by teapot, published as a fresh array on every change (D15).
*
* Never mutated in place: the router caches an index by array identity, and a request that is
* already routing keeps the array it read, so it sees the whole old table or the whole new one.
*/
interface RemoteTable {
/**
* Replaces one teapot's routes and publishes the table. With `strict` (boot) a conflicting route
* fails the boot; after boot it is refused and logged, and everything else keeps serving.
*/
set(url: string, routes: TeacupRemoteRoute[], strict: boolean): { added: string[]; removed: string[] };
}
const showRoute = (route: { method: string; pattern: string }): string => `${route.method} ${route.pattern}`;
/**
* Throws when `route` cannot join the remote routes already accepted: the same effective shape and
* method as one of them, or a sibling conflict (CARD-13). Route matching keeps the first of two
* identical patterns, so the loser would be silently dead — and callers could come to depend on
* "first teapot wins", which would make adding balancing later a breaking change.
*/
function assertRemoteRouteFits(accepted: RemoteRoute[], route: RemoteRoute): void {
const shape = compilePattern(route.pattern).shape;
const owner = accepted.find(
(prior) => prior.method === route.method && compilePattern(prior.pattern).shape === shape,
);
if (owner) {
throw new Error(
`mesh: ambiguous remote route '${showRoute(route)}' from ${route.url} conflicts with ` +
`'${showRoute(owner)}' from ${owner.url} — ` +
'load balancing across teapots is not implemented yet, so green-tea will not choose one for you. ' +
'Export it from a single teapot.',
);
}
assertNoRemoteSiblingConflict(accepted, route);
}
/**
* Local routes are merged ahead of remote ones (see the route table), so a local twin wins. That
* precedence is deliberate — your own code beats an imported one, and it is how you override a
* teapot — but silently shadowing an export looks exactly like a broken teapot from the outside.
* Warn and let the developer decide.
*/
function warnIfShadowed(registry: Registry, route: RemoteRoute, logger: Logger): void {
const shape = compilePattern(route.pattern).shape;
if (!registry.routePlans.some((plan) => plan.method === route.method && compilePattern(plan.pattern).shape === shape))
return;
logger.warn(
`mesh: route '${showRoute(route)}' is exported by teapot ${route.url} 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.',
);
}
/** The route the router files for a teapot's export: marked remote, and forwarding a built envelope. */
function remoteRouteDef(route: TeacupRemoteRoute): RouteDef {
// Marked so the router files it in the remote tree; precedence is unchanged by the split.
return markRemoteRoute({
method: route.method,
pattern: route.pattern,
transport: 'buffer',
// Built explicitly rather than cast from the handler argument. The cast put the whole
// internal request on the wire — `ip` and `protocol` included — and sent fields the
// protocol never declared, so a teapot could come to rely on something we never promised.
handler: async (req) =>
route.handler({
// HEAD reaches a remote GET through the implicit-HEAD fallback, and the teapot looks
// its plan up by method, so a forwarded HEAD finds none and answers 404. Send it as the
// GET it resolved to; dispatch drops the body for HEAD. Fixed teacup-side (D16) so an
// unchanged, older teapot still answers it during a rolling deploy.
method: req.method === 'HEAD' && route.method === 'GET' ? 'GET' : req.method,
params: req.params,
query: req.query,
body: req.body,
headers: req.headers,
url: req.url,
correlation: { requestId: req.requestId, traceId: req.traceId },
}),
});
}
/** Builds the remote table over the configured teapots, in configuration order. */
function createRemoteTable(
urls: string[],
registry: Registry,
logger: Logger,
reserved: readonly ReservedPath[],
publish: (routes: RouteDef[]) => void,
): RemoteTable {
const byUrl = new Map<string, ServedRemote[]>();
return {
set(url, routes, strict) {
const others = urls.filter((other) => other !== url).flatMap((other) => byUrl.get(other) ?? []);
const before = new Set((byUrl.get(url) ?? []).map(showRoute));
const next: ServedRemote[] = [];
for (const route of routes) {
const candidate: RemoteRoute = { method: route.method, pattern: route.pattern, url };
try {
// A teapot's own boot refuses a reserved path, but the manifest is whatever arrives on the
// wire: an older or foreign teapot could still advertise one, at boot or later, and the
// teacup must not splice it (CARD-21/CARD-17).
assertNotReserved(route.pattern, `mesh: remote route '${showRoute(route)}' from ${url}`, reserved);
assertRemoteRouteFits([...others, ...next], candidate);
} catch (error) {
if (strict) throw error;
// Refused for this teapot only; the table that is serving stays as it was (D15, rule 5).
// The same goes for a reserved path: that one route is skipped, the rest are served.
logger.warn(`mesh: not serving a route from ${url} — ${(error as Error).message}`);
continue;
}
if (!before.has(showRoute(candidate))) warnIfShadowed(registry, candidate, logger);
next.push({ ...candidate, def: remoteRouteDef(route) });
}
byUrl.set(url, next);
publish(urls.flatMap((other) => (byUrl.get(other) ?? []).map((served) => served.def)));
const after = new Set(next.map(showRoute));
return {
added: [...after].filter((key) => !before.has(key)),
removed: [...before].filter((key) => !after.has(key)),
};
},
};
}
/** What a teapot's link needs to report membership back to the remote table after boot. */
interface MembershipContext {
mesh: MeshConfig;
bus: Bus;
logger: Logger;
table: RemoteTable;
}
/** Applies one teapot's routes after boot and emits `mesh:routes` when the table actually changed. */
function applyMembership(ctx: MembershipContext, url: string, routes: TeacupRemoteRoute[]): void {
const { added, removed } = ctx.table.set(url, routes, false);
if (!added.length && !removed.length) return;
ctx.bus.emit('mesh:routes', { name: url, url, added, removed });
}
/**
* Opens a link to one teapot, wired so a returning manifest updates its routes and a link that
* gives up for good removes them (D15). `holder.link` is filled in once the link exists, because
* the callbacks need the link to rebuild its route proxies.
*/
function connectTeapot(
ctx: MembershipContext,
teapot: { url: string; secret: string },
holder: { link?: Link },
): Promise<Link> {
const { mesh, bus, logger } = ctx;
return connectLink({
url: teapot.url,
secret: teapot.secret,
timeoutMs: mesh.timeoutMs,
heartbeatMs: mesh.heartbeatMs,
reconnect: mesh.reconnect,
onManifestChange: mesh.onManifestChange,
logger,
bus,
onReconnect: () => {
if (holder.link) applyMembership(ctx, teapot.url, buildRemote(holder.link).routes);
},
onGone: () => {
logger.warn(`mesh: teapot ${teapot.url} is gone for good — its routes are removed and now answer 404.`);
applyMembership(ctx, teapot.url, []);
},
});
}
/** Backoff bounds for retrying a late teapot: the reconnect ones, or nothing when reconnect is off. */
function lateBounds(mesh: MeshConfig): { initial: number; max: number } | undefined {
if (mesh.reconnect === false) return undefined;
const opts = typeof mesh.reconnect === 'object' ? mesh.reconnect : {};
return { initial: opts.initialDelayMs ?? 500, max: opts.maxDelayMs ?? 30_000 };
}
/**
* Keeps trying a teapot that missed the boot budget, with the reconnect backoff (D15, rule 1). When
* it connects, its routes join the remote table; its steps do not, because the graph was validated
* at boot without them. A permanent refusal stops the retries. The handle's `close()` stops them too,
* and closes the link if one came up, so shutdown never leaves a retry behind.
*/
function retryLateTeapot(
ctx: MembershipContext,
teapot: { url: string; secret: string },
bounds: { initial: number; max: number },
): { close: () => void } {
const holder: { link?: Link } = {};
let stopped = false;
let attempt = 0;
let timer: ReturnType<typeof setTimeout> | undefined;
const schedule = (): void => {
const capped = Math.min(bounds.initial * 2 ** attempt++, bounds.max);
timer = setTimeout(() => void tryOnce(), Math.round(capped / 2 + Math.random() * (capped / 2)));
timer.unref?.();
};
const tryOnce = async (): Promise<void> => {
try {
const link = await connectTeapot(ctx, teapot, holder);
if (stopped) return link.close();
holder.link = link;
const { steps, routes } = buildRemote(link);
if (steps.length)
ctx.logger.warn(
`mesh: teapot ${teapot.url} connected after boot — its routes are served now, but its steps ` +
`(${steps.map((step) => step.name).join(', ')}) are not: the graph was fixed at boot without them.`,
);
applyMembership(ctx, teapot.url, routes);
} catch (error) {
if (stopped) return;
if (isPermanentRefusal(error)) {
ctx.logger.error(
`mesh: teapot ${teapot.url} refused this peer — no longer retrying it (${(error as Error).message})`,
);
return;
}
schedule();
}
};
schedule();
return {
close: () => {
stopped = true;
clearTimeout(timer);
holder.link?.close();
},
};
}
/**
* Connects the configured teapots, splices their remote steps into the registry, and publishes their
* routes through `publish`, now and whenever membership changes after boot (D15).
*/
async function spliceRemoteScopes(
mesh: MeshConfig,
bus: Bus,
registry: Registry,
logger: Logger,
reserved: readonly ReservedPath[],
): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[]; absent: string[] }> {
const remoteRoutes: RouteDef[] = [];
const meshLinks: Link[] = [];
publish: (routes: RouteDef[]) => void,
): Promise<{ meshLinks: Closable[]; absent: string[] }> {
const meshLinks: Closable[] = [];
const absent: string[] = []; // urls of teapots that never connected within the boot budget
const routeOwners = new Map<string, { url: string; pattern: string }>(); // "METHOD effective-shape" -> owner
const remoteAccepted: RemoteRoute[] = []; // every remote route spliced so far, in teapot order
const teapots = mesh.teapots ?? [];
const table = createRemoteTable(
teapots.map((teapot) => teapot.url),
registry,
logger,
reserved,
publish,
);
const ctx: MembershipContext = { mesh, bus, logger, table };
try {
for (const teapot of mesh.teapots ?? []) {
for (const teapot of teapots) {
warnIfCleartext(teapot.url, logger);
const link = await connectUntilDeadline(mesh, bus, logger, teapot.url, () =>
connectLink({
url: teapot.url,
secret: teapot.secret,
timeoutMs: mesh.timeoutMs,
heartbeatMs: mesh.heartbeatMs,
reconnect: mesh.reconnect,
onManifestChange: mesh.onManifestChange,
logger,
bus,
}),
);
const holder: { link?: Link } = {};
const link = await connectUntilDeadline(mesh, bus, logger, teapot.url, () => connectTeapot(ctx, teapot, holder));
if (!link) {
absent.push(teapot.url);
const bounds = lateBounds(mesh);
if (bounds) meshLinks.push(retryLateTeapot(ctx, teapot, bounds));
continue;
}
holder.link = link;
meshLinks.push(link);
const { steps, routes } = buildRemote(link);
const origin = `mesh:${teapot.url}`;
@@ -1090,82 +1409,14 @@ async function spliceRemoteScopes(
registry.setRunner(step.name, step.run);
}
for (const route of routes) {
const display = `${route.method} ${route.pattern}`;
// A teapot's own boot refuses such a route, but the manifest is whatever arrives on the wire:
// an older or foreign teapot could still advertise one, and the teacup must not splice it.
assertNotReserved(route.pattern, `mesh: remote route '${display}' from ${teapot.url}`, reserved);
const key = `${route.method} ${compilePattern(route.pattern).shape}`;
const owner = routeOwners.get(key);
// Fail the boot rather than pick one. Route matching keeps the first of two identical
// patterns, so the loser would be silently dead — and callers could come to depend on
// "first teapot wins", which would make adding balancing later a breaking change.
// Scope tokens already fail this way in setRunner; routes now match.
if (owner) {
throw new Error(
`mesh: ambiguous remote route '${display}' from ${teapot.url} conflicts with ` +
`'${route.method} ${owner.pattern}' from ${owner.url} — ` +
'load balancing across teapots is not implemented yet, so green-tea will not choose one for you. ' +
'Export it from a single teapot.',
);
}
routeOwners.set(key, { url: teapot.url, pattern: route.pattern });
assertNoRemoteSiblingConflict(remoteAccepted, {
method: route.method,
pattern: route.pattern,
url: teapot.url,
});
remoteAccepted.push({ method: route.method, pattern: route.pattern, url: teapot.url });
// Local routes are merged ahead of remote ones (see buildHttpRoutes), so a local twin
// wins. That precedence is deliberate — your own code beats an imported one, and it is
// how you override a teapot — but silently shadowing an export looks exactly like a
// broken teapot from the outside. Warn and let the developer decide.
if (
registry.routePlans.some(
(plan) =>
plan.method === route.method &&
compilePattern(plan.pattern).shape === compilePattern(route.pattern).shape,
)
) {
logger.warn(
`mesh: route '${display}' is exported by teapot ${teapot.url} 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.',
);
}
// Marked so the router files it in the remote tree; precedence is unchanged by the split.
remoteRoutes.push(
markRemoteRoute({
method: route.method,
pattern: route.pattern,
transport: 'buffer',
// Built explicitly rather than cast from the handler argument. The cast put the whole
// internal request on the wire — `ip` and `protocol` included — and sent fields the
// protocol never declared, so a teapot could come to rely on something we never promised.
handler: async (req) =>
route.handler({
method: req.method,
params: req.params,
query: req.query,
body: req.body,
headers: req.headers,
url: req.url,
correlation: { requestId: req.requestId, traceId: req.traceId },
}),
}),
);
}
table.set(teapot.url, routes, true);
}
} catch (err) {
closeLinks(meshLinks);
throw err;
}
return { remoteRoutes, meshLinks, absent };
return { meshLinks, absent };
}
/** Swaps provider/step runners by token — a value replaces the runner, a function becomes it. */
@@ -1390,8 +1641,39 @@ function buildMeshControl(
return createMeshControl({ secret: mesh.secret, manifest, resolveScope, resolveRoute, bus });
}
/** Compiles every non-ws route plan into an HTTP route that seeds and runs the pipeline, plus any remote routes. */
function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps: PipelineDeps): RouteDef[] {
/**
* The one HTTP route table, shared by app.fetch and listen(): local and dev routes, then remote ones.
* Built after boot, on first use. A mesh membership change publishes a new array with the same local
* head (D15), so the router reuses its local trees and rebuilds only the remote ones, and a request in
* flight keeps the array it read. Dev routes sit before the remote ones so their positions, and with
* them the local trees, do not move when remote routes come and go.
*/
function createRouteTable(buildLocal: () => RouteDef[]): {
current: () => RouteDef[];
publish: (remote: RouteDef[]) => void;
} {
let remote: RouteDef[] = [];
let local: RouteDef[] | undefined;
let table: RouteDef[] | undefined;
return {
current: () => {
if (!table) {
local = buildLocal();
table = [...local, ...remote];
}
return table;
},
publish: (next) => {
remote = next;
if (local) table = [...local, ...next];
},
};
}
/** Compiles every non-ws route plan into an HTTP route that seeds and runs the pipeline. */
function buildHttpRoutes(routePlans: RoutePlan[], deps: PipelineDeps): RouteDef[] {
const { providedSeed, planSteps, bus, onError, logger } = deps;
const local = routePlans
@@ -1436,7 +1718,7 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps
},
}));
return [...local, ...remoteRoutes];
return local;
}
/**
@@ -1447,12 +1729,9 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps
* costs one flag check per request after the first.
*/
function buildAppFetch(
routePlans: RoutePlan[],
deps: PipelineDeps,
fetchOpts: HttpOptions,
ensureBooted: () => Promise<void>,
devRoutes: () => RouteDef[],
getRemoteRoutes: () => RouteDef[],
getRoutes: () => RouteDef[],
): (request: Request) => Promise<Response> {
let handler: ((request: Request) => Promise<Response>) | undefined;
@@ -1471,7 +1750,7 @@ function buildAppFetch(
await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted
if (!handler) {
handler = buildFetch([...buildHttpRoutes(routePlans, getRemoteRoutes(), deps), ...devRoutes()], fetchOpts);
handler = buildFetch(getRoutes, fetchOpts);
}
return handler(request);
@@ -1665,7 +1944,7 @@ function runTeardown(teardown: TeardownRegistry, logger: Logger, budgetMs: numbe
function closeApp(
server: http.Server | undefined,
meshLinks: Link[],
meshLinks: Closable[],
streams: Set<() => void>,
options: { timeoutMs?: number },
defaultTimeoutMs: number | undefined,
@@ -1750,7 +2029,7 @@ function closeApp(
}
/** Best-effort close of every mesh link, ignoring individual failures. */
function closeLinks(links: Link[]): void {
function closeLinks(links: Closable[]): void {
for (const link of links) {
try {
link.close();
@@ -1760,6 +2039,12 @@ function closeLinks(links: Link[]): void {
}
}
/** `createApp({ etag })` is a boolean or absent; a truthy string doing something would be silent partial behaviour. */
function assertEtagOption(etag: unknown): void {
if (etag !== undefined && typeof etag !== 'boolean')
throw new TypeError(`createApp({ etag }): expected a boolean, got ${typeof etag}`);
}
/** Merges every app-scope provider bound to a route into a request seed (skips unresolved providers). */
async function seedProviders(container: Container, plan: RoutePlan): Promise<Record<string, unknown>> {
const provided: Record<string, unknown> = {};
+14
View File
@@ -144,6 +144,13 @@ export interface MeshConfig {
* `false` restores that fail-once behaviour. An object tunes the backoff, which doubles from
* `initialDelayMs` (500ms) up to `maxDelayMs` (30s) with jitter, so teacups that went down
* together do not come back in lockstep.
*
* It also decides what a dropped teapot's routes do (D15). While a link is reconnecting its routes
* stay in the table and answer `503` with `retry-after`, and `Allow` keeps them. A link that gives
* up for good — dropped with `reconnect: false`, or refused permanently (a wrong secret, a
* protocol mismatch) while reconnecting — has its routes removed: they answer `404` and leave
* `Allow`. Each change emits `mesh:routes` with `{ url, added, removed }`. A teapot that missed
* `bootTimeoutMs` is retried in the background with this backoff, unless it is `false`.
*/
reconnect?: boolean | { initialDelayMs?: number; maxDelayMs?: number };
/**
@@ -154,6 +161,9 @@ export interface MeshConfig {
* Serving against a manifest that no longer backs the graph would surface as a 500 that looks
* like application code. A future `'reconcile'` will rebuild the graph instead; it is named here
* rather than left implicit so that arriving is additive rather than a change of default.
*
* Only steps count. Routes are not part of the graph, so a returning teapot's routes replace its
* old ones: a route it added is served, one it dropped answers `404` (D15).
*/
onManifestChange?: 'refuse';
/**
@@ -170,6 +180,10 @@ export interface MeshConfig {
* one of its tokens still fails the boot, naming it. A permanent refusal — a wrong secret, a
* protocol mismatch — fails at once without spending the grace.
*
* After boot, such a teapot keeps being retried in the background with the `reconnect` backoff
* (not with `reconnect: false`). When it connects, its routes are added to the table and served;
* its steps are not, because the graph was validated at boot without them (D15).
*
* `0` means one attempt and no grace. That is the attempt count boot used to have, and nothing
* more: exhausting it no longer fails the boot, so a single unreachable teapot still warns and
* starts. To make a teapot's absence fatal, have something local `@needs` one of its tokens.
+9
View File
@@ -45,6 +45,9 @@ export type LifecycleEvent =
// Separate from `mesh:disconnect`, which is a link that was up and went away — this one never
// came up, and a deploy watching for trouble wants to tell those apart.
| 'mesh:boot:retry'
// A teacup's remote routes changed after boot (D15): a late teapot connected, a returning one
// exported a different set, or a link gave up for good. Carries `url`, `added` and `removed`.
| 'mesh:routes'
| 'plugin:mounted'
// Paired: see the guarantee above. `request:start` has no status and no duration — it says a
// request arrived, not that it routed.
@@ -125,6 +128,12 @@ export interface EventPayload {
* framework does not know what was sent, and will not guess.
*/
status?: number;
/** `mesh:routes`: the teapot whose routes changed. */
url?: string;
/** `mesh:routes`: routes added to the remote table, as `'METHOD /pattern'`. */
added?: string[];
/** `mesh:routes`: routes removed from the remote table, as `'METHOD /pattern'`. */
removed?: string[];
}
/**
+150
View File
@@ -0,0 +1,150 @@
// src/cookies.ts — request cookie parsing and `Set-Cookie` serialisation (RFC 6265), dependency-free.
/**
* Options for {@link setCookie}. Every attribute is optional; the defaults are the safe ones
* (`httpOnly: true`, `sameSite: 'lax'`, `path: '/'`, `secure: true`).
*/
export interface CookieOptions {
/** `Max-Age` in seconds. An integer; `0` or a negative value tells the browser to drop the cookie. */
maxAge?: number;
/** `Expires`, written as an HTTP date. `maxAge` wins in browsers when both are set. */
expires?: Date;
/** `Path`. Default `'/'`. */
path?: string;
/** `Domain`. Omitted by default, which scopes the cookie to the exact host that set it. */
domain?: string;
/**
* `Secure`. Default `true`: Chrome, Edge and Firefox accept a `Secure` cookie on
* `http://localhost`. Safari, a LAN IP or a plain-HTTP dev hostname do not — pass `false` there
* (for example `secure: !isDev`).
*/
secure?: boolean;
/** `HttpOnly`. Default `true`, so page scripts cannot read the cookie. */
httpOnly?: boolean;
/** `SameSite`. Default `'lax'`. `'none'` requires `secure`. */
sameSite?: 'strict' | 'lax' | 'none';
/** `Partitioned` (CHIPS). Requires `secure`. */
partitioned?: boolean;
}
/** RFC 6265 §4.1.1 cookie-name: an RFC 7230 token. */
const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
/** What a cookie value may not contain: CR, LF, `;`, `,`, whitespace and every control character. */
// eslint-disable-next-line no-control-regex
const BAD_VALUE = /[\u0000- ;,\u007f]/;
/**
* What an attribute value may not contain. CR/LF is the header-injection case the card names; `;`
* and the other control characters are refused too, because a `;` inside `Path` would start a new
* attribute and change what the cookie means without breaking the header.
*/
// eslint-disable-next-line no-control-regex
const BAD_ATTRIBUTE = /[\u0000-\u001f;\u007f]/;
const SAME_SITE = { strict: 'Strict', lax: 'Lax', none: 'None' } as const;
/**
* Serialises one `Set-Cookie` header value.
*
* Throws, naming the field, rather than producing a header that would split or reshape the
* response: a name outside the RFC 6265 token set, a value carrying CR, LF, `;`, `,`, whitespace or a
* control character, an attribute carrying CR/LF, `;` or a control character, a non-integer
* `maxAge`, an invalid `expires`, and `sameSite: 'none'` or `partitioned` without `secure`.
*
* The value is written as given. Encode it yourself (`encodeURIComponent`) if it can hold any of the
* refused characters; the cookie decorators decode `%`-sequences on the way back in.
*
* Several cookies on one response go in an array: `headers: { 'set-cookie': [a, b] }`, and each
* element is sent as its own `Set-Cookie` line on every adapter.
*
* @example
* setCookie('session', id, { maxAge: 3600 })
* // 'session=<id>; Max-Age=3600; Path=/; Secure; HttpOnly; SameSite=Lax'
*/
export function setCookie(name: string, value: string, options: CookieOptions = {}): string {
if (typeof name !== 'string' || !TOKEN.test(name))
throw new TypeError(`setCookie: name ${JSON.stringify(name)} is not a valid cookie name (RFC 6265 token)`);
if (typeof value !== 'string' || BAD_VALUE.test(value))
throw new TypeError(
`setCookie: value for '${name}' contains a character a cookie value cannot carry (CR, LF, ';', ',', whitespace or a control character)`,
);
const secure = options.secure ?? true;
const sameSite = options.sameSite ?? 'lax';
const parts = [`${name}=${value}`];
if (options.maxAge !== undefined) {
if (!Number.isInteger(options.maxAge)) throw new TypeError(`setCookie: maxAge for '${name}' must be an integer`);
parts.push(`Max-Age=${options.maxAge}`);
}
if (options.expires !== undefined) {
if (!(options.expires instanceof Date) || Number.isNaN(options.expires.getTime()))
throw new TypeError(`setCookie: expires for '${name}' must be a valid Date`);
parts.push(`Expires=${options.expires.toUTCString()}`);
}
if (options.domain !== undefined) parts.push(`Domain=${attribute(name, 'domain', options.domain)}`);
parts.push(`Path=${attribute(name, 'path', options.path ?? '/')}`);
if (secure) parts.push('Secure');
if (options.httpOnly ?? true) parts.push('HttpOnly');
if (!Object.prototype.hasOwnProperty.call(SAME_SITE, sameSite))
throw new TypeError(`setCookie: sameSite for '${name}' must be 'strict', 'lax' or 'none'`);
if (sameSite === 'none' && !secure)
throw new TypeError(`setCookie: sameSite 'none' for '${name}' requires secure (browsers reject it otherwise)`);
parts.push(`SameSite=${SAME_SITE[sameSite]}`);
if (options.partitioned) {
if (!secure) throw new TypeError(`setCookie: partitioned for '${name}' requires secure`);
parts.push('Partitioned');
}
return parts.join('; ');
}
function attribute(name: string, field: string, value: string): string {
if (typeof value !== 'string' || value === '' || BAD_ATTRIBUTE.test(value))
throw new TypeError(
`setCookie: ${field} for '${name}' must be a non-empty string without CR, LF, ';' or control characters`,
);
return value;
}
/**
* Parses a request `Cookie` header into a name → value map (RFC 6265 §5.2 / §4.2).
*
* - The first value wins for a repeated name — the browser sends the most specific cookie first.
* - `%`-sequences are decoded; a value that fails to decode is kept raw rather than rejected.
* - A malformed pair (no `=`, or an empty name) is skipped. A broken cookie never becomes a 400:
* the header is client state the server did not choose and the request may not even need it.
* - Several `cookie` lines (HTTP/2, some proxies) arrive as an array and are joined with `; `.
*
* The map has no prototype, so a cookie named `__proto__` or `constructor` is just a key.
*/
export function parseCookies(header: string | string[] | undefined): Record<string, string> {
const out: Record<string, string> = Object.create(null);
if (header === undefined) return out;
const raw = Array.isArray(header) ? header.join('; ') : header;
for (const pair of raw.split(';')) {
const eq = pair.indexOf('=');
if (eq === -1) continue;
const key = pair.slice(0, eq).trim();
if (key === '' || key in out) continue;
out[key] = decode(pair.slice(eq + 1).trim());
}
return out;
}
function decode(value: string): string {
if (!value.includes('%')) return value;
try {
return decodeURIComponent(value);
} catch {
return value;
}
}
+6
View File
@@ -1,6 +1,7 @@
import type { App } from './app/types';
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
import { setProxyClient } from './http/peer';
import { MARK_EDGE } from './http/compression';
// Minimal ambient for the Cloudflare Workers globals we use — avoids @cloudflare/workers-types.
// Declares only what we call; mirrors the real workerd signatures.
@@ -23,10 +24,15 @@ declare const WebSocketPair: { new (): { 0: EdgeWebSocket; 1: EdgeWebSocket } };
* to release something is therefore *silently* inert on the edge, which is why this says so rather
* than a best-effort call on an event that does not exist. Anything that must be released belongs in
* the request that acquired it, or in a platform binding that manages its own lifetime.
*
* **`compression` never encodes here.** Cloudflare compresses in front of the Worker, so core sets
* only `Vary: Accept-Encoding`; wrapping the app in `edgeHandler` marks it as edge explicitly.
*/
export function edgeHandler(
app: App,
): (request: Request, env?: unknown, ctx?: EdgeCtx) => Response | Promise<Response> {
(app as { [MARK_EDGE]?: () => void })[MARK_EDGE]?.();
return (request, _env, ctx) => {
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
const [client, server] = Object.values(new WebSocketPair()) as [EdgeWebSocket, EdgeWebSocket];
+1 -1
View File
@@ -8,7 +8,7 @@ import type { MatchedRoute, HttpOptions } from './types';
/** A ready-to-send error response produced while acquiring the request body. */
export interface BodyFailure {
fail: { status: number; headers: Record<string, string>; body: string };
fail: { status: number; headers: Record<string, string | string[]>; body: string };
}
/** A value, or a promise of one. Readers that have nothing to await return the value directly. */
+414
View File
@@ -0,0 +1,414 @@
// src/http/compression.ts — response compression (CARD-16, #112, D13 strategy B).
//
// The per-runtime contract, as measured in SPIKE-COMPRESSION.md and SPIKE-COMPRESSION-B.md:
// - Node, Deno, Bun: `node:zlib` only, loaded lazily. Buffered bodies always go through the async
// API: at 32 connections the sync API stalled the event loop for 9–13 ms even below 64 KiB, and
// async gave 4× (Node) to 8× (Bun) the throughput. Streams go through createGzip /
// createBrotliCompress, flushed after every frame, error frame and ping, so each event is
// decodable the moment it arrives. br quality is fixed at 4 (zlib's default 11 stalls 6–33 ms).
// - Deno runs `node:zlib`'s async API on the main thread (2.9.7), so there core compression is
// CPU work on the event loop. That is documented, not worked around: no Deno branch here.
// - Edge (workerd): core never encodes. Cloudflare compresses in front of the Worker, an encoded
// body plus `Content-Encoding` is encoded a second time, and a bundled Worker cannot even
// `require('node:zlib')`. Core sets `Vary` and nothing else.
// - No `CompressionStream` anywhere: it cannot flush, so it would hold SSE frames back.
import { mergeVary } from '../security';
import { nodeRequire } from '../node-require';
import { findHeader } from './conditional';
import type { NeutralOutcome } from './core';
/** A content-coding core can produce. */
export type Encoding = 'br' | 'gzip';
/** The public `createApp({ compression })` object form. */
export interface CompressionOptions {
/** Smallest buffered body, in bytes, worth encoding. Default `1024`. Streams ignore it. */
threshold?: number;
/** Encodings core may produce, in server preference order. Default `['br', 'gzip']`. */
encodings?: Array<'br' | 'gzip'>;
}
/** Resolved, validated configuration. `encode: false` is the edge mode: `Vary` only. */
export interface CompressionConfig {
threshold: number;
encodings: Encoding[];
encode: boolean;
}
/** Fixed brotli quality. See the module comment. */
export const BR_QUALITY = 4;
const KNOWN: readonly Encoding[] = ['br', 'gzip'];
/**
* Marks an app as running on the edge, so core never encodes for it. `edgeHandler` calls it: that
* covers the official adapter whatever the Worker's compat flags, including the case detection
* cannot see (an old compat date without `navigator`, unbundled so `node:zlib` loads). A property
* on the app rather than on the public `App` type, and `Symbol.for` because each tsup entry carries
* its own copy of this module — the same arrangement as `WS_MAX_MESSAGE_BYTES`.
*/
export const MARK_EDGE: unique symbol = Symbol.for('green-tea.mark-edge');
/** The `[MARK_EDGE]` hook for an app: turns encoding off for good. A no-op when compression is off. */
export function edgeMarker(cfg: CompressionConfig | undefined): () => void {
return () => {
if (cfg) cfg.encode = false;
};
}
/**
* Whether this process is a Cloudflare Workers isolate. workerd sets `navigator.userAgent` to
* exactly this string under the `global_navigator` compat flag, on by default since 2022-03-21.
* Detected in `createApp` so `export default { fetch: app.fetch }`, which never passes through
* `edgeHandler`, is covered too.
*/
export function isWorkerd(): boolean {
const nav = (globalThis as { navigator?: { userAgent?: string } }).navigator;
return nav?.userAgent === 'Cloudflare-Workers';
}
interface ZlibStream {
write(chunk: Uint8Array | string): boolean;
flush(kind: number, cb: () => void): void;
end(): void;
destroy(): void;
on(event: string, fn: (...args: never[]) => void): this;
once(event: string, fn: (...args: never[]) => void): this;
pipe<T>(dest: T): T;
}
interface Zlib {
gzip(b: Uint8Array, cb: (e: Error | null, r: Buffer) => void): void;
brotliCompress(b: Uint8Array, o: object, cb: (e: Error | null, r: Buffer) => void): void;
createGzip(): ZlibStream;
createBrotliCompress(o: object): ZlibStream;
constants: Record<string, number>;
}
let zlibModule: Zlib | undefined;
/** Lazy, so the edge bundle never evaluates `node:zlib`. */
const zlib = (): Zlib => (zlibModule ??= nodeRequire<Zlib>('node:zlib'));
/**
* Encode only off workerd, and only where `node:zlib` actually loads. In a bundled Worker
* `nodeRequire` throws, and without this probe every compressible edge response was a 500
* (SPIKE-COMPRESSION-B §6.1). Evaluated once, at `createApp`.
*/
function canEncode(): boolean {
if (isWorkerd()) return false;
try {
return typeof zlib().gzip === 'function';
} catch {
return false;
}
}
/** Validates `createApp({ compression })`. Returns `undefined` when compression is off. */
export function resolveCompression(
option: boolean | CompressionOptions | undefined,
encode: () => boolean = canEncode,
): CompressionConfig | undefined {
if (option === undefined || option === false) return undefined;
if (option !== true && (typeof option !== 'object' || option === null))
throw new TypeError('createApp({ compression }): expected a boolean or { threshold?, encodings? }');
const opts: CompressionOptions = option === true ? {} : option;
const threshold = opts.threshold ?? 1024;
if (!Number.isInteger(threshold) || threshold < 0)
throw new TypeError(
`createApp({ compression }): threshold must be a non-negative integer, got ${String(threshold)}`,
);
const encodings = opts.encodings ?? ['br', 'gzip'];
if (!Array.isArray(encodings) || encodings.length === 0)
throw new TypeError('createApp({ compression }): encodings must be a non-empty array');
for (const e of encodings)
if (!KNOWN.includes(e))
throw new TypeError(`createApp({ compression }): unknown encoding '${String(e)}' — expected 'br' or 'gzip'`);
return { threshold, encodings: [...new Set(encodings)], encode: encode() };
}
/**
* The qvalue grammar of RFC 9110 §12.4.2: `0` with up to three decimals, or `1` with up to three
* zeros. `Number()` alone would admit `2`, `1e0` or `-1`, and a `q=2` would outrank the server's
* preference.
*/
const QVALUE = /^(0(\.\d{0,3})?|1(\.0{0,3})?)$/;
/** `q` of one `Accept-Encoding` member, or 1 when absent. A malformed or out-of-range `q` excludes it. */
function weightOf(params: string[]): number {
for (const param of params) {
const eq = param.indexOf('=');
if (eq !== -1 && param.slice(0, eq).trim().toLowerCase() === 'q') {
const raw = param.slice(eq + 1).trim();
return QVALUE.test(raw) ? Number(raw) : 0;
}
}
return 1;
}
/**
* `Accept-Encoding` negotiation (RFC 9110 §12.5.3). Returns the encoding to use, or `undefined` for
* identity. Highest `q` wins; a tie goes to server preference, the order of `encodings`. `*` covers
* every encoding not named explicitly, and `q=0` excludes. An absent header means identity:
* §12.5.3 allows any coding then, but an absent header is overwhelmingly a client that would not
* decode one.
*/
export function negotiate(accept: string | undefined, encodings: Encoding[]): Encoding | undefined {
if (!accept) return undefined;
const q = new Map<string, number>();
for (const part of accept.split(',')) {
const [rawName, ...params] = part.split(';');
const name = rawName.trim().toLowerCase();
if (name) q.set(name, weightOf(params));
}
let best: Encoding | undefined;
let bestQ = 0;
for (const e of encodings) {
const weight = q.get(e) ?? q.get('*') ?? 0;
if (weight > bestQ) {
best = e;
bestQ = weight;
}
}
return best;
}
const COMPRESSIBLE =
/^\s*(text\/|application\/(json|javascript|xml|wasm|x-ndjson)\s*(;|$)|image\/svg\+xml\s*(;|$)|application\/[^;\s]+\+(json|xml)\s*(;|$))/i;
type Headers = Record<string, string | string[]>;
/** A header's value as one string, case-insensitively, or `undefined`. */
function read(headers: Headers, name: string): string | undefined {
const key = findHeader(headers, name);
if (key === undefined) return undefined;
const value = headers[key];
return Array.isArray(value) ? value.join(', ') : value;
}
/**
* Whether the response's representation could vary by `Accept-Encoding` at all. When it cannot —
* already encoded, a range, no or an incompressible type, `no-transform` — core neither encodes
* nor adds `Vary`. Request-side reasons (HEAD, the client's header) do not appear here: those
* responses still get `Vary`, so a shared cache keys them correctly.
*/
function eligible(headers: Headers): boolean {
if (read(headers, 'content-encoding') !== undefined || read(headers, 'content-range') !== undefined) return false;
const type = read(headers, 'content-type');
if (!type || !COMPRESSIBLE.test(type)) return false;
return !/(^|[\s,])no-transform\s*(,|$)/i.test(read(headers, 'cache-control') ?? '');
}
function withVary(headers: Headers): Headers {
const key = findHeader(headers, 'vary');
const out = { ...headers };
let existing: string | undefined;
if (key !== undefined) {
const value = out[key];
existing = Array.isArray(value) ? value.join(', ') : value;
delete out[key];
}
out.vary = mergeVary(existing, 'Accept-Encoding');
return out;
}
/** Headers for an encoded body: `Vary` merged, `Content-Encoding` set, `Content-Length` dropped (it described the identity body). */
function encodedHeaders(headers: Headers, encoding: Encoding): Headers {
const out = withVary(headers);
const length = findHeader(out, 'content-length');
if (length !== undefined) delete out[length];
out['content-encoding'] = encoding;
return out;
}
const brParams = (size?: number) => {
const c = zlib().constants;
const params: Record<number, number> = { [c.BROTLI_PARAM_QUALITY]: BR_QUALITY };
if (size !== undefined) params[c.BROTLI_PARAM_SIZE_HINT] = size;
return { params };
};
/** Encodes one buffered body with the async zlib API — never the sync one (see the module comment). */
function encodeBody(body: Uint8Array, encoding: Encoding): Promise<Buffer> {
const z = zlib();
return new Promise((resolve, reject) => {
const done = (err: Error | null, out: Buffer) => (err ? reject(err) : resolve(out));
if (encoding === 'br') z.brotliCompress(body, brParams(body.byteLength), done);
else z.gzip(body, done);
});
}
/** A fresh compressing stream plus the flush mode that makes it emit everything written so far. */
function createEncoderStream(encoding: Encoding): { stream: ZlibStream; flushKind: number } {
const z = zlib();
if (encoding === 'br')
return { stream: z.createBrotliCompress(brParams()), flushKind: z.constants.BROTLI_OPERATION_FLUSH };
return { stream: z.createGzip(), flushKind: z.constants.Z_SYNC_FLUSH };
}
/** The request facts compression needs. */
export interface CompressionRequest {
method: string;
headers: Record<string, string | string[] | undefined>;
}
const acceptOf = (req: CompressionRequest): string | undefined => {
const v = req.headers['accept-encoding'];
return Array.isArray(v) ? v.join(', ') : v;
};
type Buffered = Extract<NeutralOutcome, { kind: 'buffered' }>;
type Streamed = Extract<NeutralOutcome, { kind: 'stream' }>;
/** Decides a buffered outcome. Returns it untouched, with `Vary` only, or encoded. */
function compressBuffered(
cfg: CompressionConfig,
req: CompressionRequest,
outcome: Buffered,
): Buffered | Promise<Buffered> {
const { status, headers, body } = outcome;
// A 304 carries `Vary` whatever else it has: it usually has no `Content-Type`, so the
// eligibility test would drop it, and a cache needs the same key it stored the 200 under.
if (status === 304) return { ...outcome, headers: withVary(headers) };
if (status === 204 || !eligible(headers)) return outcome;
const vary = { ...outcome, headers: withVary(headers) };
if (status < 200 || req.method === 'HEAD' || !cfg.encode) return vary;
const bytes = typeof body === 'string' ? Buffer.from(body) : body;
if (bytes.byteLength < cfg.threshold) return vary;
const encoding = negotiate(acceptOf(req), cfg.encodings);
if (!encoding) return vary;
return encodeBody(bytes, encoding).then((encoded) => ({
...outcome,
headers: encodedHeaders(headers, encoding),
body: encoded,
}));
}
/** Decides a stream: its headers, and the encoding the adapter applies frame by frame. `threshold` does not apply. */
function compressStream(cfg: CompressionConfig, req: CompressionRequest, outcome: Streamed): Streamed {
if (!eligible(outcome.headers)) return outcome;
if (req.method === 'HEAD' || !cfg.encode) return { ...outcome, headers: withVary(outcome.headers) };
const encoding = negotiate(acceptOf(req), cfg.encodings);
if (!encoding) return { ...outcome, headers: withVary(outcome.headers) };
return { ...outcome, headers: encodedHeaders(outcome.headers, encoding), encoding };
}
/**
* Applies `createApp({ compression })` to an outcome, after `handle()` and before the adapter
* writes it. One function for both adapters, so Node and the fetch runtimes cannot diverge. The
* ETag (CARD-15) was taken in `dispatch` on the identity body and is not touched: it is weak, so
* one tag describes every coding.
*/
export function compressOutcome(
cfg: CompressionConfig | undefined,
req: CompressionRequest,
outcome: NeutralOutcome,
): NeutralOutcome | Promise<NeutralOutcome> {
if (!cfg) return outcome;
return outcome.kind === 'stream' ? compressStream(cfg, req, outcome) : compressBuffered(cfg, req, outcome);
}
/**
* Wraps a web byte stream so every chunk is compressed and flushed on its own: one SSE frame in,
* one decodable compressed chunk out. This is the thing `CompressionStream` cannot do.
*/
export function compressWebStream(source: ReadableStream<Uint8Array>, encoding: Encoding): ReadableStream<Uint8Array> {
const { stream: z, flushKind } = createEncoderStream(encoding);
const reader = source.getReader();
let pending: Uint8Array[] = [];
let failure: unknown;
z.on('data', (c: Uint8Array) => pending.push(c));
// Without a listener a zlib error is an uncaught exception that takes the process down.
z.on('error', (err: unknown) => (failure ??= err));
const take = (): Uint8Array | undefined => {
if (pending.length === 0) return undefined;
const chunk = pending.length === 1 ? pending[0] : Buffer.concat(pending);
pending = [];
return new Uint8Array(chunk.buffer as ArrayBuffer, chunk.byteOffset, chunk.byteLength);
};
return new ReadableStream<Uint8Array>({
async pull(controller) {
const { value, done } = await reader.read();
if (done) {
await new Promise<void>((resolve) => {
z.once('end', resolve);
z.once('error', () => resolve());
z.end();
});
} else {
z.write(value);
await new Promise<void>((resolve) => z.flush(flushKind, resolve));
}
if (failure !== undefined) {
controller.error(failure);
await reader.cancel(failure).catch(() => {});
return;
}
const out = take();
if (out) controller.enqueue(out);
if (done) controller.close();
},
async cancel(reason) {
z.destroy();
await reader.cancel(reason);
},
});
}
/** Where `pipeStream` writes frames: `res` itself, or a flushing compressor piped into it. */
export interface FrameSink {
write(chunk: string | Buffer): boolean;
/** The emitter whose `drain` ends a backpressure wait. */
drains: NodeJS.EventEmitter;
end(): void;
destroy(): void;
}
/** The Node stream path's sink. Without an encoding it is `res`, unchanged. */
export function frameSink(res: NodeJS.WritableStream & { destroy(): void }, encoding?: Encoding): FrameSink {
if (!encoding) return { write: (c) => res.write(c), drains: res, end: () => void res.end(), destroy: () => {} };
const { stream: zs, flushKind } = createEncoderStream(encoding);
zs.on('error', () => res.destroy());
zs.pipe(res);
return {
write(chunk) {
const ok = zs.write(chunk);
// Flushed per frame: the point of an event stream is that each event arrives when it happens.
zs.flush(flushKind, () => {});
return ok;
},
drains: zs as unknown as NodeJS.EventEmitter,
end: () => zs.end(), // `pipe` ends `res` once the compressor has drained
destroy: () => zs.destroy(),
};
}
+121
View File
@@ -0,0 +1,121 @@
// src/http/conditional.ts — ETags and conditional GET (RFC 9110 §8.8.3, §13.1.2, §13.1.3, §15.4.5).
type HeaderBag = Record<string, string | string[] | undefined>;
/** The first value of a request header, or `undefined`. */
function single(value: string | string[] | undefined): string | undefined {
return Array.isArray(value) ? value.join(', ') : value;
}
/**
* Splits an `If-None-Match` list on the commas that sit outside quotes. An entity-tag may legally
* contain a comma inside its quotes (`"a,b"`), so a plain `split(',')` would cut one tag in two.
*/
function splitTags(header: string): string[] {
const tags: string[] = [];
let start = 0;
let quoted = false;
for (let i = 0; i < header.length; i++) {
const ch = header[i];
if (ch === '"') quoted = !quoted;
else if (ch === ',' && !quoted) {
tags.push(header.slice(start, i).trim());
start = i + 1;
}
}
tags.push(header.slice(start).trim());
return tags.filter(Boolean);
}
/** The opaque part of an entity-tag: `W/"x"` and `"x"` both become `"x"` (weak comparison). */
const opaque = (tag: string): string => (tag.startsWith('W/') ? tag.slice(2) : tag);
/**
* Whether `If-None-Match` matches `etag` under the weak comparison GET and HEAD use
* (RFC 9110 §13.1.2): `W/"x"` matches `"x"`, and `*` matches any current representation.
*/
export function ifNoneMatchMatches(header: string, etag: string): boolean {
const own = opaque(etag.trim());
for (const tag of splitTags(header)) if (tag === '*' || opaque(tag) === own) return true;
return false;
}
/**
* Whether a resource last modified at `mtimeMs` is unchanged since an `If-Modified-Since` date.
* HTTP dates have one-second resolution, so the modification time is truncated to the second first;
* otherwise a file written at 12:00:00.400 would never match the `Last-Modified` it was served with.
* An unparseable date is ignored, as RFC 9110 §13.1.3 requires.
*/
export function notModifiedSince(header: string, mtimeMs: number): boolean {
const since = Date.parse(header);
if (Number.isNaN(since)) return false;
return Math.floor(mtimeMs / 1000) * 1000 <= since;
}
/**
* Decides a conditional GET/HEAD: `If-None-Match` when present, else `If-Modified-Since` when the
* caller has a modification time to compare (static files only — handler responses have none).
*/
export function isNotModified(headers: HeaderBag, etag: string, mtimeMs?: number): boolean {
const inm = single(headers['if-none-match']);
if (inm !== undefined) return ifNoneMatchMatches(inm, etag);
const ims = single(headers['if-modified-since']);
return ims !== undefined && mtimeMs !== undefined && notModifiedSince(ims, mtimeMs);
}
/** Weak validator for a static file, from the `stat` the resolver already does: `W/"<size>-<mtimeMs base36>"`. */
export function staticEtag(size: number, mtimeMs: number): string {
return `W/"${size}-${Math.floor(mtimeMs).toString(36)}"`;
}
/**
* Weak validator for a buffered body: its byte length plus a 32-bit FNV-1a hash of its bytes, in
* base 36. FNV rather than `crypto.subtle.digest`: it is synchronous and dependency-free, where
* `subtle` costs a promise per response. It is not collision-resistant and need not be — an ETag
* detects change, it does not authenticate. The length narrows a collision to equal-length bodies.
*
* Weak, so one tag can describe every content-coding of the same body (CARD-16 hashes before it
* encodes). Strings are hashed as UTF-8, so the tag matches what goes on the wire.
*/
export function bodyEtag(body: string | Uint8Array): string {
const bytes = typeof body === 'string' ? Buffer.from(body, 'utf8') : body;
let hash = 0x811c9dc5;
for (let i = 0; i < bytes.length; i++) {
hash ^= bytes[i];
hash = Math.imul(hash, 0x01000193);
}
return `W/"${bytes.length.toString(36)}-${(hash >>> 0).toString(36)}"`;
}
/** The key under which `headers` holds `name`, case-insensitively, or `undefined`. */
export function findHeader(headers: Record<string, unknown>, name: string): string | undefined {
for (const key of Object.keys(headers)) if (key.toLowerCase() === name) return key;
return undefined;
}
/**
* The headers of a `304` built from the `200` it stands for: everything but the `content-*`
* headers that describe a body (`content-type`, `content-length`, `content-encoding`, …), plus
* `transfer-encoding`. `content-location` is kept: §15.4.5 lists it among the fields a 304 sends. `ETag`, `Vary`, `Cache-Control`, `Last-Modified` and anything else a cache
* would update stay (RFC 9110 §15.4.5). Injected security headers are merged later by the adapter,
* exactly as on a `200`.
*/
export function notModifiedHeaders(headers: Record<string, string | string[]>): Record<string, string | string[]> {
const out: Record<string, string | string[]> = {};
for (const key of Object.keys(headers)) {
const lower = key.toLowerCase();
if ((lower.startsWith('content-') && lower !== 'content-location') || lower === 'transfer-encoding') continue;
out[key] = headers[key];
}
return out;
}
+70 -19
View File
@@ -6,6 +6,9 @@ import { buildSecurityHeaders, resolveCors, corsPreflightHeaders } from '../secu
import { resolveRoute, allowedMethods, normalizeRequestPath, parseQuery } from './router';
import { pickEncoder } from './stream';
import { acquireBody, type BodyReader } from './body';
import { bodyEtag, findHeader, isNotModified, notModifiedHeaders, staticEtag } from './conditional';
import type { StaticHit } from '../views';
import type { Encoding } from './compression';
import type { RouteDef, HttpOptions } from './types';
import type { StreamEncoder } from '../encoders';
import type { Bus } from '../bus';
@@ -85,14 +88,16 @@ export function correlateRequest(headers: Record<string, string | string[] | und
/** The neutral shape of a response: a fully buffered body, or a stream to pipe frame-by-frame. */
export type NeutralOutcome =
| { kind: 'buffered'; status: number; headers: Record<string, string>; body: string | Buffer }
| { kind: 'buffered'; status: number; headers: Record<string, string | string[]>; body: string | Buffer }
| {
kind: 'stream';
headers: Record<string, string>;
headers: Record<string, string | string[]>;
stream: AsyncIterable<unknown>;
encoder: StreamEncoder;
/** The matched route's pattern, for naming the stream lifecycle events. */
route: string;
/** Set by `compressOutcome`: the adapter encodes each frame with it and flushes. */
encoding?: Encoding;
};
/** {@link handle}'s result for a normal (non-preflight) request. */
@@ -126,20 +131,74 @@ function errorOutcome(
req: NeutralRequest,
injected: Record<string, string>,
opts: HttpOptions | undefined,
headers: Record<string, string> = {},
headers: Record<string, string | string[]> = {},
): HandleResult {
const rendered = renderError(error, req, opts?.onError, opts?.logger);
return {
injected,
outcome: {
outcome: bodyless({
kind: 'buffered',
status: rendered.status,
headers: { ...rendered.headers, ...headers },
body: req.method === 'HEAD' ? '' : rendered.body,
},
}),
};
}
type Buffered = Extract<NeutralOutcome, { kind: 'buffered' }>;
/**
* A `304` has no body on any adapter, and none of the headers that describe one. This is the one
* place every buffered outcome passes through on its way out, so a handler that throws
* `NotModified` — rendered by the default renderer as a JSON envelope — answers the same bodiless
* `304` the ETag path does. Node would drop the body of a 304 by itself; the fetch adapters already
* null it; the `content-type` would still have gone out on both.
*/
function bodyless(outcome: Buffered): Buffered {
if (outcome.status !== 304) return outcome;
return { kind: 'buffered', status: 304, headers: notModifiedHeaders(outcome.headers), body: '' };
}
/**
* Answers a static hit: `ETag` + `Last-Modified` from the resolver's `stat`, `Cache-Control` from the
* `static` option, and a `304` — decided before the file is read, so a revalidation costs a `stat`
* and nothing more. HEAD never reads either.
*/
async function staticOutcome(hit: StaticHit, req: NeutralRequest): Promise<Buffered> {
const etag = staticEtag(hit.size, hit.mtimeMs);
const headers: Record<string, string> = {
'content-type': hit.contentType,
etag,
'last-modified': new Date(hit.mtimeMs).toUTCString(),
'cache-control': hit.cacheControl,
};
if (isNotModified(req.headers, etag, hit.mtimeMs))
return bodyless({ kind: 'buffered', status: 304, headers, body: '' });
return { kind: 'buffered', status: 200, headers, body: req.method === 'HEAD' ? '' : await hit.read() };
}
/**
* `createApp({ etag: true })` for a handler response: a buffered `200` to GET/HEAD gets a weak ETag
* from its body — computed before HEAD blanks the body, so HEAD and GET carry the same tag — unless
* the handler set one, which is kept and only compared. A match becomes a bodiless `304`. The
* handler has already run: this saves bandwidth, not work.
*/
function tagged(
result: { status: number; headers: Record<string, string | string[]>; body: string },
req: NeutralRequest,
): Buffered {
const key = findHeader(result.headers, 'etag');
const existing = key === undefined ? undefined : result.headers[key];
const etag = typeof existing === 'string' ? existing : bodyEtag(result.body);
const headers = key === undefined ? { ...result.headers, etag } : result.headers;
if (isNotModified(req.headers, etag)) return bodyless({ kind: 'buffered', status: 304, headers, body: '' });
return { kind: 'buffered', status: 200, headers, body: req.method === 'HEAD' ? '' : result.body };
}
async function unmatchedOutcome(
routes: RouteDef[],
opts: HttpOptions | undefined,
@@ -149,18 +208,7 @@ async function unmatchedOutcome(
): Promise<HandleResult> {
if ((req.method === 'GET' || req.method === 'HEAD') && opts?.static) {
const hit = await opts.static(path);
if (hit) {
return {
injected,
outcome: {
kind: 'buffered',
status: 200,
headers: { 'content-type': hit.contentType },
body: req.method === 'HEAD' ? '' : hit.body,
},
};
}
if (hit) return { injected, outcome: await staticOutcome(hit, req) };
}
const allow = allowedMethods(routes, path);
@@ -411,13 +459,16 @@ async function dispatch(
};
}
if (opts?.etag && result.status === 200 && (req.method === 'GET' || req.method === 'HEAD'))
return { injected, outcome: tagged(result, req) };
return {
injected,
outcome: {
outcome: bodyless({
kind: 'buffered',
status: result.status,
headers: result.headers,
body: req.method === 'HEAD' ? '' : result.body,
},
}),
};
}
+46 -1
View File
@@ -19,7 +19,10 @@ export function mergeInjectedHeaders(
const lowerKey = key.toLowerCase();
if (lowerKey === 'vary') {
handlerVary = handlerHeaders[key];
// A header value may be an array (D11). `mergeVary` splits on commas, so joining first keeps
// every token a handler listed instead of stringifying the array by accident.
const value = handlerHeaders[key];
handlerVary = Array.isArray(value) ? value.join(', ') : value;
continue;
}
@@ -40,3 +43,45 @@ export function mergeInjectedHeaders(
else if (handlerVary !== undefined) merged['vary'] = handlerVary;
return merged;
}
/**
* Prepares merged headers for Node's `writeHead`, which writes one header line per array element
* for *any* header. That is right for `set-cookie`, the one header whose values cannot be
* comma-joined (an `Expires` date carries a comma), and wrong for every other: RFC 9110 §5.3 makes a
* list header's repeated lines equivalent to one comma-joined line, and joining keeps all four
* adapters sending the same bytes. So every other array is joined with `, ` here, before
* `writeHead`. Returns the input untouched when it holds no array, which is nearly every response.
*/
export function joinListHeaders<T extends Record<string, unknown>>(headers: T): T {
let out: Record<string, unknown> | undefined;
for (const key of Object.keys(headers)) {
const value = headers[key];
if (!Array.isArray(value) || key.toLowerCase() === 'set-cookie') continue;
out ??= { ...headers };
out[key] = value.join(', ');
}
return (out as T | undefined) ?? headers;
}
/**
* Builds a web `Headers` from merged headers. A plain record cannot be handed to `new Response`:
* the Fetch spec stringifies an array value to `a,b`, which for `set-cookie` is one broken cookie.
* `set-cookie` elements are appended one by one, so each reaches the client as its own line;
* every other array is joined with `, `, exactly as {@link joinListHeaders} does for Node.
*/
export function toWebHeaders(headers: Record<string, unknown>): Headers {
const out = new Headers();
for (const key of Object.keys(headers)) {
const value = headers[key];
if (value === undefined) continue;
if (!Array.isArray(value)) out.set(key, String(value));
else if (key.toLowerCase() === 'set-cookie') for (const cookie of value) out.append(key, String(cookie));
else out.set(key, value.join(', '));
}
return out;
}
+37 -4
View File
@@ -1,4 +1,4 @@
import type { RouteDef, MatchedRoute } from './types';
import type { RouteDef, RouteTable, MatchedRoute } from './types';
export type CompiledSegment =
| { kind: 'static'; value: string }
@@ -152,9 +152,9 @@ function segmentShape(segment: CompiledSegment): string {
* spy on the export cannot see it, so the counts are kept here; they let a test prove that misses
* after the index is built recompile nothing and rebuild nothing (FPRD-001 CARD-10).
*/
const seamCounts = { compilePattern: 0, indexBuilds: 0 };
const seamCounts = { compilePattern: 0, indexBuilds: 0, localTreeBuilds: 0 };
/** @internal Calls so far to `compilePattern` (cache hits included) and route-index builds. For tests. */
/** @internal Calls so far to `compilePattern` (cache hits included), route-index builds and local-tree builds. For tests. */
export const routerSeamCounts = (): Readonly<typeof seamCounts> => ({ ...seamCounts });
/** Compiles and validates one route pattern. Results are cached by source string. */
@@ -417,6 +417,11 @@ interface RouteIndex {
/** The routes a mesh teacup spliced in from its teapots. Identity-keyed, so a route is remote wherever it travels. */
const remoteRouteDefs = new WeakSet<RouteDef>();
/** The array a {@link RouteTable} holds right now. Servers call it once per request. */
export function currentRoutes(table: RouteTable): RouteDef[] {
return typeof table === 'function' ? table() : table;
}
/** Marks a route as spliced in from a mesh teapot, so the index files it in the remote tree. */
export function markRemoteRoute<T extends RouteDef>(def: T): T {
remoteRouteDefs.add(def);
@@ -505,6 +510,34 @@ function buildTrees(entries: Array<{ def: RouteDef; order: number }>): Map<strin
return trees;
}
/**
* The last local trees built, and the `(def, position)` entries they were built from.
*
* When mesh membership changes, the app publishes a new array whose local entries are the same
* objects at the same positions, with only the remote tail different (CARD-19, D15). Reusing the
* local trees then means a peer coming or going rebuilds the remote trees alone. Keyed by the
* first local def, so it is collected with the table that owns it.
*/
const localTreeCache = new WeakMap<
RouteDef,
{ entries: Array<{ def: RouteDef; order: number }>; trees: Map<string, MethodTree> }
>();
function sameEntries(a: Array<{ def: RouteDef; order: number }>, b: Array<{ def: RouteDef; order: number }>): boolean {
return a.length === b.length && a.every((entry, i) => entry.def === b[i].def && entry.order === b[i].order);
}
function localTrees(local: Array<{ def: RouteDef; order: number }>): Map<string, MethodTree> {
if (!local.length) return buildTrees(local);
const cached = localTreeCache.get(local[0].def);
if (cached && sameEntries(cached.entries, local)) return cached.trees;
seamCounts.localTreeBuilds++;
const trees = buildTrees(local);
localTreeCache.set(local[0].def, { entries: local, trees });
return trees;
}
function routeIndex(routes: RouteDef[]): RouteIndex {
const cached = routeIndexCache.get(routes);
if (cached?.size === routes.length) return cached;
@@ -516,7 +549,7 @@ function routeIndex(routes: RouteDef[]): RouteIndex {
const index: RouteIndex = {
size: routes.length,
local: buildTrees(local),
local: localTrees(local),
remote: remote.length ? buildTrees(remote) : undefined,
methods: [...new Set(routes.map((route) => route.method))],
};
+47 -29
View File
@@ -2,11 +2,11 @@ import type http from 'http';
import type https from 'https';
import { createRequestGate } from './request-gate';
import { renderError, type ErrorRequest } from '../transformers';
import type { Bus } from '../bus';
import type { Bus, Correlation } from '../bus';
import { readBody as readBodyBytes, deriveSecure, deriveIp } from './request';
import { pipeStream } from './stream';
import { attachWs } from './ws';
import { mergeInjectedHeaders } from './headers';
import { mergeInjectedHeaders, joinListHeaders } from './headers';
import {
handle,
correlateRequest,
@@ -17,13 +17,15 @@ import {
type Preflight,
} from './core';
import type { BodyFailure, BodyReader } from './body';
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
import type { RouteTable, WsRouteDef, MeshControl, HttpOptions } from './types';
import { currentRoutes } from './router';
import type { Logger } from '../logger';
import { nodeRequire } from '../node-require';
import { answerProbe } from './health';
import { compressOutcome } from './compression';
interface HandlerConfig {
routes: RouteDef[];
routes: RouteTable;
bus?: Bus;
opts?: HttpOptions;
trustProxy: boolean;
@@ -36,14 +38,14 @@ function errorRequest(req: http.IncomingMessage): ErrorRequest {
/**
* Builds an HTTP/HTTPS server that routes requests, parses bodies, streams results, and handles WebSocket upgrades.
* @param routes HTTP route definitions.
* @param routes HTTP route definitions, or a getter read once per request (a mesh teacup's table changes as peers come and go).
* @param wsRoutes WebSocket route definitions (requires the optional `ws` peer dependency).
* @param bus Optional event bus for stream lifecycle events.
* @param meshControl Optional mesh gateway hook for a reserved upgrade path.
* @param opts Limits, TLS, security, CORS, and body-parsing options.
*/
export function createHttpServer(
routes: RouteDef[],
routes: RouteTable,
wsRoutes: WsRouteDef[] = [],
bus?: Bus,
meshControl?: MeshControl,
@@ -161,7 +163,7 @@ function createRequestHandler(cfg: HandlerConfig) {
}
result = await handle(
routes,
currentRoutes(routes), // once per request, see buildFetch
opts,
{
...correlation,
@@ -182,30 +184,46 @@ function createRequestHandler(cfg: HandlerConfig) {
}
}
if ('preflight' in result) {
res.writeHead(204, result.preflight);
res.end();
return;
}
if (result.outcome.kind === 'stream') {
await pipeStream(
res,
result.outcome.stream,
result.outcome.encoder,
bus,
result.outcome.route,
opts?.streams,
correlation,
);
return;
}
res.writeHead(result.outcome.status, result.outcome.headers);
res.end(result.outcome.body);
await writeResult(req, res, result, { opts, bus, correlation });
}
}
/**
* Writes what `handle()` produced: a preflight, or an outcome after `compressOutcome` (CARD-16).
* Module scope rather than inside `serve`, whose closure would charge every branch here again.
*/
async function writeResult(
req: http.IncomingMessage,
res: http.ServerResponse,
result: HandleResult | Preflight,
ctx: { opts: HttpOptions | undefined; bus: Bus | undefined; correlation: Correlation },
): Promise<void> {
const { opts, bus, correlation } = ctx;
if ('preflight' in result) {
res.writeHead(204, result.preflight);
res.end();
return;
}
// Not awaited unless compression actually returned a promise: an app without it keeps the
// synchronous write it had.
const decided = compressOutcome(
opts?.compression,
{ method: req.method ?? 'GET', headers: req.headers },
result.outcome,
);
const outcome = decided instanceof Promise ? await decided : decided;
if (outcome.kind === 'stream') {
await pipeStream(res, outcome, bus, opts?.streams, correlation);
return;
}
res.writeHead(outcome.status, outcome.headers);
res.end(outcome.body);
}
/**
* Answers a health probe and returns true, or returns false for any other request. Runs before the
* gate, so shedding never refuses a probe, and before `handle()`, so no step, plugin or lifecycle
@@ -285,7 +303,7 @@ function patchResponseHeaders(res: http.ServerResponse, injected: Record<string,
(res as any).writeHead = (status: number, arg2?: any, arg3?: any) => {
const handlerHeaders = (typeof arg2 === 'string' ? arg3 : arg2) as Record<string, any> | undefined;
const merged = mergeInjectedHeaders(handlerHeaders, injected);
const merged = joinListHeaders(mergeInjectedHeaders(handlerHeaders, injected));
return typeof arg2 === 'string' ? origWriteHead(status, arg2, merged) : origWriteHead(status, merged);
};
}
+18 -10
View File
@@ -3,6 +3,8 @@ import { once } from 'events';
import { sseEncoder, ndjsonEncoder, StreamEncoder } from '../encoders';
import type { Transport } from '../metadata';
import type { Bus, Correlation } from '../bus';
import type { NeutralOutcome } from './core';
import { frameSink } from './compression';
const PING_MS = 15_000;
@@ -27,34 +29,40 @@ export function pickEncoder(transport: Transport, accept: string): StreamEncoder
return pick(accept);
}
/** Pipes an async-iterable result to the response as an HTTP stream, with keep-alive pings and backpressure handling. */
/**
* Pipes a stream outcome to the response, with keep-alive pings and backpressure handling. With
* `outcome.encoding` set (CARD-16), frames go through a `node:zlib` stream piped into `res`, flushed
* after every frame, error frame and ping, so each event is decodable on arrival.
*/
export async function pipeStream(
res: http.ServerResponse,
stream: AsyncIterable<unknown>,
encoder: StreamEncoder,
outcome: Extract<NeutralOutcome, { kind: 'stream' }>,
bus?: Bus,
name = '',
streams?: Set<() => void>,
correlation: Correlation = {},
): Promise<void> {
const { stream, encoder, route: name } = outcome;
// `route` duplicates `name` here rather than being passed separately: on a stream event `name`
// is always the route pattern, never the concrete path the request events can carry — but a
// consumer following the documented contract labels on `route` and would otherwise find it
// absent on the longest-lived thing the server does. See `EventPayload.name`.
const trace = { name, route: name, ...correlation };
res.writeHead(200, encoder.headers);
res.writeHead(200, outcome.headers);
res.flushHeaders(); // establish the stream immediately so idle-until-event sources (e.g. subscriptions) don't deadlock clients awaiting headers
bus?.emit('stream:open', trace);
const sink = frameSink(res, outcome.encoding);
const iterator = stream[Symbol.asyncIterator]();
let ping: ReturnType<typeof setInterval> | undefined;
if (encoder.ping) {
ping = setInterval(() => res.write(encoder.ping!()), PING_MS);
ping = setInterval(() => sink.write(encoder.ping!()), PING_MS);
ping.unref?.();
}
const stop = () => {
if (ping) clearInterval(ping);
// A client gone mid-stream: the compressor holds zlib memory outside the JS heap until destroyed.
sink.destroy();
void Promise.resolve(iterator.return?.()).catch(() => {});
};
@@ -76,19 +84,19 @@ export async function pipeStream(
const { value, done } = await iterator.next();
if (done) break;
if (!res.write(encoder.encode(value))) {
await Promise.race([once(res, 'drain'), onClose]);
if (!sink.write(encoder.encode(value))) {
await Promise.race([once(sink.drains, 'drain'), onClose]);
if (res.destroyed) break; // let finally clean up
}
}
} catch (err) {
bus?.emit('stream:error', { ...trace, error: err });
const frame = encoder.encodeError(err);
if (frame && !res.writableEnded) res.write(frame);
if (frame && !res.writableEnded) sink.write(frame);
} finally {
if (ping) clearInterval(ping);
streams?.delete(closer);
if (!res.writableEnded && !res.destroyed) res.end();
if (!res.writableEnded && !res.destroyed) sink.end();
bus?.emit('stream:close', trace);
}
}
+12
View File
@@ -7,6 +7,7 @@ import type { WsRequest, WsSocket } from './ws-core';
import type { StaticResolver } from '../views';
import type { Bus } from '../bus';
import type { Logger } from '../logger';
import type { CompressionConfig } from './compression';
/** Per-request and per-server resource ceilings applied by the server. */
export interface RequestLimits {
@@ -68,6 +69,10 @@ export interface HttpOptions {
* Absent when health is off, so no path is intercepted.
*/
health?: HealthProbe;
/** Weak ETags + `304` for buffered `200` GET/HEAD handler responses (`createApp({ etag })`). */
etag?: boolean;
/** Resolved `createApp({ compression })`; absent when compression is off. */
compression?: CompressionConfig;
}
/** Handler for a matched HTTP route; receives a normalized request and resolves to a pipeline result. */
@@ -97,6 +102,13 @@ export interface RouteDef {
maxParts?: number; // per-route override of the server's multipart maxParts
}
/**
* A route table: a fixed array, or a getter the server reads once per request. A mesh teacup passes
* a getter, because its remote routes change as teapots come and go (CARD-19); each change publishes
* a new array, so a request sees the whole old table or the whole new one.
*/
export type RouteTable = RouteDef[] | (() => RouteDef[]);
/** Result of matching a request path against a route: extracted params plus the matched definition. */
export interface MatchedRoute {
params: Record<string, string>;
+35 -26
View File
@@ -10,13 +10,16 @@ import {
type HandleResult,
type Preflight,
} from './core';
import { mergeInjectedHeaders } from './headers';
import { mergeInjectedHeaders, toWebHeaders } from './headers';
import { peerOf, trustedProxyClient } from './peer';
import { declaresOverLimit, type BodyFailure, type BodyReader, type MaybePromise } from './body';
import { HttpError } from '../signals';
import { renderError, type ErrorRequest } from '../transformers';
import type { RouteDef, HttpOptions } from './types';
import type { RouteTable, HttpOptions } from './types';
import { answerProbe } from './health';
import { currentRoutes } from './router';
import { compressOutcome, compressWebStream } from './compression';
import type { NeutralOutcome } from './core';
/**
* Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream
@@ -201,23 +204,22 @@ export function toBodyInit(body: string | Buffer): ResponseBody {
return new Uint8Array(body.buffer as ArrayBuffer, body.byteOffset, body.byteLength);
}
/** Converts a {@link HandleResult}'s outcome into a web `Response`, buffered or streamed. */
function outcomeToResponse(result: HandleResult, bus?: Bus, correlation: Correlation = {}): Response {
const headers = mergeInjectedHeaders(result.outcome.headers, result.injected) as Record<string, string>;
/** Converts an outcome (already through `compressOutcome`) into a web `Response`, buffered or streamed. */
function outcomeToResponse(
outcome: NeutralOutcome,
injected: Record<string, string>,
bus?: Bus,
correlation: Correlation = {},
): Response {
const headers = toWebHeaders(mergeInjectedHeaders(outcome.headers, injected));
if (result.outcome.kind === 'stream') {
const body = asReadableStream(
result.outcome.stream,
result.outcome.encoder,
bus,
result.outcome.route,
correlation,
);
return new Response(body, { headers });
if (outcome.kind === 'stream') {
const frames = asReadableStream(outcome.stream, outcome.encoder, bus, outcome.route, correlation);
return new Response(outcome.encoding ? compressWebStream(frames, outcome.encoding) : frames, { headers });
}
const body = [204, 205, 304].includes(result.outcome.status) ? null : toBodyInit(result.outcome.body);
return new Response(body, { status: result.outcome.status, headers });
const body = [204, 205, 304].includes(outcome.status) ? null : toBodyInit(outcome.body);
return new Response(body, { status: outcome.status, headers });
}
/** The first `x-forwarded-for` hop when the proxy is trusted, else `''`. */
@@ -236,7 +238,7 @@ function forwardedFor(headers: Record<string, string>, opts: HttpOptions | undef
* Routing, body parsing, limits and error rendering all live in the core; this file is the part
* that knows how to get bytes out of a `Request` and how to put them into a `Response`.
*/
export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
export function buildFetch(routes: RouteTable, opts: HttpOptions | undefined) {
// Built once per server, not once per request — see `BodyReader`.
const readBody: BodyReader = (source, limit) => readFetchBytes(source, limit, opts);
const gate = createRequestGate(opts?.limits?.maxConcurrentRequests);
@@ -273,12 +275,14 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
return new Response(JSON.stringify({ error: 'Service Unavailable' }), {
status: 503,
headers: mergeInjectedHeaders(
{
'content-type': 'application/json',
'retry-after': '1',
},
injected,
headers: toWebHeaders(
mergeInjectedHeaders(
{
'content-type': 'application/json',
'retry-after': '1',
},
injected,
),
),
});
}
@@ -286,7 +290,9 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
acquired = gate.limited;
result = await handle(
routes,
// Read once per request: a mesh teacup swaps its table when peers come and go, and one
// request must route and build `Allow` against the same table (CARD-19).
currentRoutes(routes),
opts,
{
...correlation,
@@ -320,11 +326,14 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
if ('preflight' in result) {
return new Response(null, {
status: 204,
headers: mergeInjectedHeaders(result.preflight, injected),
headers: toWebHeaders(mergeInjectedHeaders(result.preflight, injected)),
});
}
return outcomeToResponse(result, opts?.bus, correlation);
const decided = compressOutcome(opts?.compression, { method: request.method, headers }, result.outcome);
return decided instanceof Promise
? decided.then((outcome) => outcomeToResponse(outcome, injected, opts?.bus, correlation))
: outcomeToResponse(decided, injected, opts?.bus, correlation);
};
}
+6 -1
View File
@@ -78,9 +78,13 @@ export { flow, Flow } from './flow';
export type { StepFn, CompiledFlow } from './flow';
// Parameter decorators
export { needs, ctx, param, query, body, headers, header, inbound, abort } from './params';
export { needs, ctx, param, query, body, headers, header, cookies, cookie, inbound, abort } from './params';
export type { Query, Headers, Context, ArgSpec, ArgDecorator } from './params';
// Cookies
export { setCookie, parseCookies } from './cookies';
export type { CookieOptions } from './cookies';
// Observability
export { createDefaultLogger, logRequests, withConsoleFallback } from './logger';
export type { Logger, LogLevel, LogFields } from './logger';
@@ -94,6 +98,7 @@ export type { StreamEncoder, SseEvent, SseFields } from './encoders';
// HTTP, security & validation
export type { RequestLimits } from './http';
export type { CompressionOptions } from './http/compression';
export { UNMATCHED_ROUTE } from './http/core';
export type { TlsOptions, CorsOptions, SecurityOptions } from './security';
export type { UploadedFile, MultipartBody } from './multipart';
+135 -47
View File
@@ -2,7 +2,6 @@ import type { Bus } from '../bus';
import type { Logger } from '../logger';
import { HttpError } from '../signals';
import { connectSocket, type SocketCtor } from '../http/ws-adapter';
import { compilePattern } from '../http/router';
import type { WsSocket } from '../http/ws-core';
import { encode, decode, MESH_PROTOCOL_VERSION, type Manifest, type RequestEnvelope, type Frame } from './protocol';
@@ -64,6 +63,8 @@ interface LinkState {
socket: WsSocket | undefined;
closed: boolean;
retry: ReturnType<typeof setTimeout> | undefined;
/** When the scheduled reconnect attempt fires (epoch ms), for the `retry-after` a 503 carries. */
retryAt: number | undefined;
}
/** One established connection: its socket, the manifest it announced, and its heartbeat. */
@@ -81,10 +82,10 @@ const DEFAULT_MAX_DELAY_MS = 30_000;
* 503, not a bare Error: a dead upstream is not "this service broke", and the status is what
* tells a caller it may retry and an operator where to look. A bare Error renders as a 500.
*/
function rejectAllPending(pending: Map<string, PendingEntry>, reason: string): void {
function rejectAllPending(pending: Map<string, PendingEntry>, reason: string, headers?: Record<string, string>): void {
for (const [, entry] of pending) {
clearTimeout(entry.timer);
entry.reject(new HttpError(503, reason));
entry.reject(new HttpError(503, reason, undefined, headers));
}
pending.clear();
@@ -99,13 +100,14 @@ function sendRpc(
name: string,
ctx: RequestEnvelope,
timeoutMs: number,
downHeaders?: Record<string, string>,
): Promise<unknown> {
// Answer now rather than in timeoutMs. A closed socket cannot deliver the frame, so waiting
// would make every request to a downed teapot hang for the full timeout (30s by default)
// before failing anyway — the caller pays for a verdict already known. This is also the
// window a reconnecting link sits in: down, and answering immediately.
if (!socket?.isOpen) {
return Promise.reject(new HttpError(503, `mesh link is down: cannot resolve '${name}'`));
return Promise.reject(new HttpError(503, `mesh link is down: cannot resolve '${name}'`, undefined, downHeaders));
}
return new Promise((resolveCall, rejectCall) => {
@@ -329,37 +331,109 @@ function stepKeys(manifest: Manifest): Set<string> {
}
/**
* Route keys by method plus *effective shape*, the same comparison `spliceRemoteScopes` uses to
* detect ambiguity — so `/:id` renamed to `/:name` is the same route and does not trip the refusal.
*/
function routeKeys(manifest: Manifest): Set<string> {
return new Set(manifest.routes.map((route) => `${route.method} ${compilePattern(route.pattern).shape}`));
}
/**
* What the boot manifest had that a returning one does not.
* The steps the boot manifest had that a returning one does not.
*
* The graph was validated at boot against the first manifest and is already serving. A token that
* vanished cannot be validated away after the fact, so a manifest missing anything this link
* contributed is refused rather than accepted — see `ManifestPolicy`. Extra exports are *not*
* missing and are ignored: the graph is fixed at boot and nothing new is spliced into it.
* The graph was validated at boot against the first manifest and is already serving. A step token
* that vanished cannot be validated away after the fact, so a manifest missing one is refused
* rather than accepted — see `ManifestPolicy`. Extra steps are ignored: the graph is fixed at boot
* and nothing new is spliced into it.
*
* Routes are not compared. They are not part of the graph, so a returning teapot's routes replace
* the old ones instead (D15): a route it added is served, one it dropped is removed.
*/
export function missingFromManifest(booted: Manifest, returned: Manifest): string[] {
const steps = stepKeys(returned);
const routes = routeKeys(returned);
const missing: string[] = [];
for (const step of booted.steps) {
if (!steps.has(step)) missing.push(`step '${step}'`);
}
for (const route of booted.routes) {
if (!routes.has(`${route.method} ${compilePattern(route.pattern).shape}`)) {
missing.push(`route '${route.method} ${route.pattern}'`);
}
return missing;
}
/**
* `retry-after` for a 503 while the link is down and will try again: the seconds until the next
* attempt, at least 1. Nothing when it will not try again, so a client is not told to come back to
* a link that has given up.
*/
function retryAfter(state: LinkState, reconnects: boolean): Record<string, string> | undefined {
if (state.closed || !reconnects) return undefined;
const waitMs = state.retryAt === undefined ? 0 : state.retryAt - Date.now();
return { 'retry-after': String(Math.max(1, Math.ceil(waitMs / 1000))) };
}
/** A session dropped with reconnection off: the link is gone for good, if it was ever up. */
function dropWithoutReconnect(adopted: boolean, giveUp: () => void): void {
if (adopted) giveUp();
}
/** Stop a link for good and say so: a drop with reconnection off, or a permanent refusal (D15). */
function stopForGood(state: LinkState, onGone: (() => void) | undefined): void {
if (state.closed) return;
state.closed = true;
clearTimeout(state.retry);
state.retry = undefined;
onGone?.();
}
/**
* Whether a failed reconnect attempt was the teapot refusing this peer on purpose, in which case the
* link gives up. Retrying reaches the same answer forever, so the link stops and its routes go (D15),
* the same verdict boot gives a refusal.
*/
function refusedWhileReconnecting(
url: string,
error: unknown,
logger: Logger | undefined,
giveUp: () => void,
): boolean {
if (!isPermanentRefusal(error)) return false;
logger?.warn(`mesh: ${url} refused this peer while reconnecting (${(error as Error).message}) — giving up on it.`);
giveUp();
return true;
}
/**
* Hang up on a session whose manifest no longer backs the graph, and return the fingerprint now logged.
*
* Logged once per distinct manifest, not once per attempt: at the 30s ceiling this would otherwise be
* ~2,880 identical lines a day. A rollback can still fix it, which is why the link keeps retrying
* rather than giving up.
*/
function refuseSession(
session: Session,
missing: string[],
logged: string,
url: string,
logger: Logger | undefined,
): string {
session.heartbeat.stop();
session.socket.close();
const fingerprint = missing.join('|');
if (fingerprint !== logged) {
logger?.warn(
`mesh: refusing to reconnect to ${url} — its manifest no longer exports ${missing.join(', ')}, ` +
'which the graph was validated against at boot. Retrying in case this is a partial deploy.',
);
}
return missing;
return fingerprint;
}
/** A session was adopted. When it is a returning one: keep the boot steps, take its routes (D15), and tell the caller. */
function reconnected(
returning: boolean,
link: Link,
returned: Manifest,
onReconnect: ((manifest: Manifest) => void) | undefined,
): void {
if (!returning) return;
link.manifest = { steps: link.manifest.steps, routes: returned.routes };
onReconnect?.(link.manifest);
}
/** Resolved backoff bounds, or `undefined` when the caller turned reconnection off. */
@@ -394,19 +468,36 @@ export function connectLink(args: {
/** What to do when a returning teapot's manifest no longer backs the graph (default: `'refuse'`). */
onManifestChange?: ManifestPolicy;
logger?: Logger;
/**
* Called each time a dropped link reconnects and its session is adopted, after `link.manifest`
* has taken the returning manifest's routes. Not called for the first connection: the caller
* has the link, and its manifest, when the returned promise resolves.
*/
onReconnect?: (manifest: Manifest) => void;
/**
* Called once when the link gives up for good: its session dropped with `reconnect: false`, or a
* reconnect attempt was refused permanently (a wrong secret, a protocol mismatch). Not called by
* `close()`, which is the application hanging up, not the teapot going away.
*/
onGone?: () => void;
}): Promise<Link> {
const timeoutMs = args.timeoutMs ?? 30_000;
const heartbeatMs = args.heartbeatMs ?? HEARTBEAT_MS;
const bounds = backoffBounds(args.reconnect);
const pending = new Map<string, PendingEntry>();
const state: LinkState = { socket: undefined, closed: false, retry: undefined };
const state: LinkState = { socket: undefined, closed: false, retry: undefined, retryAt: undefined };
let refusalLogged = '';
let adopted = false; // a session was adopted at least once, so the link has something to lose
const downHeaders = (): Record<string, string> | undefined => retryAfter(state, bounds !== undefined);
const giveUp = (): void => stopForGood(state, args.onGone);
const link: Link = {
// replaced with the real manifest before this object escapes; a reconnect never changes it,
// because the graph is fixed at boot and only the *boot* manifest describes what it holds.
// replaced with the real manifest before this object escapes. A reconnect keeps the boot
// manifest's steps, because the graph is fixed at boot, and takes the returning one's routes.
manifest: { steps: [], routes: [] },
rpc: (kind, name, ctx) => sendRpc(state.socket, pending, String(counter++), kind, name, ctx, timeoutMs),
rpc: (kind, name, ctx) =>
sendRpc(state.socket, pending, String(counter++), kind, name, ctx, timeoutMs, downHeaders()),
close: () => {
// Terminal, by contract. `closeLinks` runs on shutdown, and a link that reconnected after
// the application hung up would leave a process that cannot exit.
@@ -438,6 +529,8 @@ export function connectLink(args: {
// the teapot the moment it returns.
const delay = Math.round(capped / 2 + Math.random() * (capped / 2));
clearTimeout(state.retry);
state.retryAt = Date.now() + delay;
state.retry = setTimeout(() => void attemptReconnect(attempt + 1), delay);
state.retry.unref?.();
};
@@ -446,8 +539,12 @@ export function connectLink(args: {
const endSession = (attempt: number): void => {
state.socket = undefined;
args.bus?.emit('mesh:disconnect', { name: args.url });
rejectAllPending(pending, `mesh link to ${args.url} is down`);
// Scheduled before the rejection, so the 503s carry the real wait in `retry-after`.
scheduleRetry(attempt);
rejectAllPending(pending, `mesh link to ${args.url} is down`, downHeaders());
// With reconnection off, a link that was up and dropped is gone for good (D15). `adopted`
// keeps a first connect that never succeeded out of this: that link never escaped.
if (!bounds) dropWithoutReconnect(adopted, giveUp);
};
/** Adopt an established session, or refuse it when its manifest no longer backs the graph. */
@@ -455,27 +552,16 @@ export function connectLink(args: {
const missing = missingFromManifest(link.manifest, session.manifest);
if (missing.length > 0) {
session.heartbeat.stop();
session.socket.close();
// Logged once per distinct manifest, not once per attempt: at the 30s ceiling this would
// otherwise be ~2,880 identical lines a day. A rollback can still fix it, which is why the
// link keeps retrying rather than giving up.
const fingerprint = missing.join('|');
if (fingerprint !== refusalLogged) {
refusalLogged = fingerprint;
args.logger?.warn(
`mesh: refusing to reconnect to ${args.url} — its manifest no longer exports ${missing.join(', ')}, ` +
'which the graph was validated against at boot. Retrying in case this is a partial deploy.',
);
}
refusalLogged = refuseSession(session, missing, refusalLogged, args.url, args.logger);
return false;
}
refusalLogged = '';
state.socket = session.socket;
const returning = adopted;
adopted = true;
args.bus?.emit('mesh:connect', { name: args.url });
reconnected(returning, link, session.manifest, args.onReconnect);
return true;
};
@@ -492,10 +578,12 @@ export function connectLink(args: {
}
if (!adopt(session)) scheduleRetry(attempt);
} catch {
// openSession's own abort listener already scheduled the retry through `onEnd`; a rejection
// that never opened a socket (a bad URL, DNS) needs one scheduled here instead.
if (!state.socket && !state.retry) scheduleRetry(attempt);
} catch (error) {
// A permanent refusal ends the link. Otherwise: openSession's own abort listener already
// scheduled the retry through `onEnd`; a rejection that never opened a socket (a bad URL,
// DNS) needs one scheduled here instead.
if (!refusedWhileReconnecting(args.url, error, args.logger, giveUp) && !state.socket && !state.retry)
scheduleRetry(attempt);
}
};
+5 -1
View File
@@ -3,7 +3,11 @@ import 'reflect-metadata';
/** Any class constructor. Kept `any` because decorators must accept every target shape. */
export type Ctor = new (...args: any[]) => any;
/** Serializes a handler's return value into an HTTP response envelope. */
export type TransformerFn = (value: unknown) => { status?: number; headers?: Record<string, string>; body: string };
export type TransformerFn = (value: unknown) => {
status?: number;
headers?: Record<string, string | string[]>;
body: string;
};
/** Metadata attached by `@Html`: optional file path and whether it is a template. */
export interface HtmlMeta {
+11 -4
View File
@@ -26,7 +26,7 @@ export interface OpenApiDoc {
type Parameter = {
name: string;
in: 'path' | 'query' | 'header';
in: 'path' | 'query' | 'header' | 'cookie';
required: boolean;
schema: { type: 'string'; pattern?: string };
};
@@ -57,13 +57,20 @@ function pathParams(pattern: string): Parameter[] {
});
}
/** Query and header parameters declared by the handler's `@query` / `@headers` / `@header` argument decorators. */
/** Where each argument source sits in an OpenAPI parameter list; sources absent here are not parameters. */
const ARG_LOCATION: Partial<Record<ArgSpec['source'], Parameter['in']>> = {
query: 'query',
headers: 'header',
cookies: 'cookie',
};
/** Query, header and cookie parameters declared by `@query` / `@headers` / `@header` / `@cookies` / `@cookie`. */
function argParams(args: ArgSpec[]): Parameter[] {
const params: Parameter[] = [];
for (const arg of args) {
if (arg.source !== 'query' && arg.source !== 'headers') continue;
const location = arg.source === 'query' ? 'query' : 'header';
const location = ARG_LOCATION[arg.source];
if (!location) continue;
const names = arg.keys ?? (arg.key ? [arg.key] : []);
for (const name of names) params.push({ name, in: location, required: false, schema: { type: 'string' } });
}
+27 -3
View File
@@ -2,6 +2,7 @@ import 'reflect-metadata';
import type { Ctor } from './metadata';
import { isStandardSchema, type StandardSchemaV1 } from './standard-schema';
import { ValidationError } from './signals';
import { parseCookies } from './cookies';
/** Parsed URL query string as flat key/value pairs. */
export type Query = Record<string, string>;
@@ -10,7 +11,7 @@ export type Headers = Record<string, string | string[] | undefined>;
/** Per-request bag that accumulates values produced by steps and providers. */
export type Context = Record<string, unknown>;
type ArgSource = 'ctx' | 'needs' | 'params' | 'query' | 'body' | 'headers' | 'inbound' | 'abort';
type ArgSource = 'ctx' | 'needs' | 'params' | 'query' | 'body' | 'headers' | 'cookies' | 'inbound' | 'abort';
/** Describes how a single handler parameter is sourced and (optionally) validated. */
export interface ArgSpec {
index: number;
@@ -71,6 +72,14 @@ export const body: ArgDecorator = envelope('body');
export const headers: ArgDecorator = envelope('headers');
/** Inject a single request header by name (singular alias of {@link headers}); accepts a schema to validate it. */
export const header: ArgDecorator = envelope('headers');
/**
* Inject request cookies, parsed from the `Cookie` header: no arg for the whole map (`{}` when the
* request has none), a key to pick one, an array to pick several. Accepts a schema to validate.
* First value wins for a repeated name, `%`-sequences are decoded, malformed pairs are skipped.
*/
export const cookies: ArgDecorator = envelope('cookies');
/** Inject a single request cookie by name (singular alias of {@link cookies}); `undefined` when absent. */
export const cookie: ArgDecorator = envelope('cookies');
/** Inject a value produced upstream by a step or provider, addressed by key. */
export function needs(key: string): ParameterDecorator {
@@ -126,10 +135,11 @@ export async function resolveArgs(specs: ArgSpec[], context: Context): Promise<u
function resolveOne(spec: ArgSpec, context: Context): unknown {
if (spec.source === 'ctx') return context;
if (spec.source === 'needs') return context[spec.key as string];
// `cookies` is a seed token like `headers`, but parsed on demand rather than seeded on every request.
if (spec.source === 'needs') return spec.key === 'cookies' ? cookiesOf(context) : context[spec.key as string];
if (spec.source === 'inbound') return context.inbound;
if (spec.source === 'abort') return context.abort;
const bag = context[spec.source];
const bag = spec.source === 'cookies' ? cookiesOf(context) : context[spec.source];
if (typeof bag !== 'object' || bag === null) return bag; // can't pick from a non-object; return as-is
const values = bag as Record<string, unknown>;
@@ -142,3 +152,17 @@ function resolveOne(spec: ArgSpec, context: Context): unknown {
if (spec.key !== undefined) return values[spec.key];
return values;
}
/**
* The request's cookie map, parsed on first use and cached on the context, so a route that never
* declares a cookie argument never parses the header and one that declares several parses it once.
* Serves `@cookie`, `@cookies` and `@needs('cookies')` alike.
*/
function cookiesOf(context: Context): unknown {
if (context.cookies === undefined) {
const headers = context.headers as Headers | undefined;
context.cookies = parseCookies(headers?.cookie);
}
return context.cookies;
}
+2 -1
View File
@@ -14,7 +14,8 @@ export interface PipelineStep {
/** A fully materialized HTTP response produced by a transformer. */
export interface ResponseShape {
status: number;
headers: Record<string, string>;
/** A value may be an array: `set-cookie` arrays are sent one line per element, others joined with `, `. */
headers: Record<string, string | string[]>;
body: string;
}
/** A streaming response; the async iterable is written to the socket and bypasses the transformer. */
+2 -2
View File
@@ -20,7 +20,7 @@ export interface HttpErrorLike {
status: number;
message: string;
body?: unknown;
headers?: Record<string, string>;
headers?: Record<string, string | string[]>;
}
/**
@@ -35,7 +35,7 @@ export class HttpError extends Error {
readonly status: number,
message?: string,
readonly body?: unknown,
readonly headers?: Record<string, string>,
readonly headers?: Record<string, string | string[]>,
) {
super(message ?? `HTTP ${status}`);
this.name = new.target.name;
+2 -1
View File
@@ -6,7 +6,8 @@ import type { Logger } from './logger';
/** A ready-to-send HTTP response. */
export interface ErrorResponse {
status: number;
headers: Record<string, string>;
/** A value may be an array: `set-cookie` arrays are sent one line per element, others joined with `, `. */
headers: Record<string, string | string[]>;
body: string;
}
+75 -14
View File
@@ -77,15 +77,63 @@ function readViewFile(views: string | undefined, path: string): string {
}
}
/** A static-file hit: the raw bytes and the content-type to send. */
/**
* A static-file hit: what the `stat` already knows, and a `read()` for the bytes.
*
* The bytes are behind a function so the caller can answer a conditional request from `size` and
* `mtimeMs` alone: a `304` never reads the file (CARD-15). `read()` reads the confined real path the
* resolver checked, so deferring it does not reopen the path to a different target.
*/
export interface StaticHit {
body: Buffer;
contentType: string;
size: number;
mtimeMs: number;
/** `Cache-Control` for this hit (and its `304`): `no-cache` unless `static.cacheControl` says otherwise. */
cacheControl: string;
read(): Promise<Buffer>;
}
/** Resolves a URL path to a static file under a fixed root, or `undefined` for a miss. */
export type StaticResolver = (urlPath: string) => Promise<StaticHit | undefined>;
/**
* The public `static` option: `true` (→ `./public`), a directory, or `{ dir?, cacheControl? }`.
* `cacheControl` defaults to `'no-cache'`, so a browser always revalidates — cheap, since a match is a
* `304` that never reads the file — and never reuses a file heuristically from `Last-Modified`
* (RFC 9111 §4.2.2). Hashed assets can opt into `'public, max-age=31536000, immutable'`.
*/
export type StaticOption = boolean | string | { dir?: string; cacheControl?: string };
const STATIC_KEYS = new Set(['dir', 'cacheControl']);
/**
* Validates and normalises the `static` option at boot. Throws on an unknown key in the object form
* (a misspelt `cachecontrol` silently doing nothing is the bug this prevents), on a non-string
* `dir`/`cacheControl`, and on a `cacheControl` carrying CR or LF (header injection).
*/
export function normalizeStatic(
option: StaticOption | undefined,
): { root: string | true; cacheControl: string } | undefined {
if (option === undefined || option === false) return undefined;
if (option === true || typeof option === 'string') return { root: option, cacheControl: 'no-cache' };
if (typeof option !== 'object' || option === null)
throw new TypeError('createApp({ static }): expected a boolean, a directory string or { dir?, cacheControl? }');
for (const key of Object.keys(option))
if (!STATIC_KEYS.has(key))
throw new TypeError(`createApp({ static }): unknown key '${key}' — expected 'dir' and/or 'cacheControl'`);
const { dir, cacheControl = 'no-cache' } = option;
if (dir !== undefined && typeof dir !== 'string')
throw new TypeError('createApp({ static: { dir } }): expected a string');
if (typeof cacheControl !== 'string' || /[\r\n]/.test(cacheControl))
throw new TypeError('createApp({ static: { cacheControl } }): expected a string without CR or LF');
return { root: dir ?? true, cacheControl };
}
/** 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) {
@@ -93,26 +141,39 @@ async function confine(fs: typeof import('node:fs'), sep: string, root: string,
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(
/** Stats `full` (or its `index.html` when a directory) if its real path stays inside the real `root`. */
async function statConfined(
fs: typeof import('node:fs'),
nodePath: typeof import('node:path'),
root: string,
full: string,
cacheControl: 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();
let stat = await fs.promises.stat(real);
const isDir = stat.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);
if (isDir) {
real = await confine(fs, nodePath.sep, root, nodePath.join(real, 'index.html'));
if (!real) return undefined;
stat = await fs.promises.stat(real);
}
const path = 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)) };
return {
contentType: contentTypeFor(nodePath.extname(target)),
size: stat.size,
mtimeMs: stat.mtimeMs,
cacheControl,
// 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.
read: () => fs.promises.readFile(path),
};
}
/**
@@ -121,7 +182,7 @@ async function readConfined(
* 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, cacheControl = 'no-cache'): StaticResolver {
let fs: typeof import('node:fs');
let nodePath: typeof import('node:path');
@@ -165,7 +226,7 @@ export function buildStaticResolver(root: string | true): StaticResolver {
if (!rootReal) return undefined;
try {
return await readConfined(fs, nodePath, rootReal, full);
return await statConfined(fs, nodePath, rootReal, full, cacheControl);
} catch {
return undefined; // includes ENOENT from `realpath` on a dangling link: a miss, never a rejection
}
+36
View File
@@ -0,0 +1,36 @@
// CARD-16 (#112) under the real Bun runtime: `Bun.serve` does not compress by itself, so every
// encoding here is core's, through `node:zlib`. Run with: npm run test:bun
import 'reflect-metadata';
import { test } from 'bun:test';
import { serveBun } from '../../src/bun.ts';
import { compressionApp } from '../fixtures/compression-app.ts';
import { checks, serverDoesNotCompress, ticksDuringGzip } from '../fixtures/compression-checks.ts';
for (const [name, run] of Object.entries(checks)) {
test(`compression on Bun.serve: ${name}`, async () => {
const server = await serveBun(compressionApp({ compression: true, etag: true }), { hostname: '127.0.0.1', port: 0 });
try {
await run(server.port);
} finally {
await server.close({ timeoutMs: 1000 });
}
});
}
// The documented Bun facts (CARD-16; `guides/runtimes.md`).
test('documented: Bun.serve does not compress by itself (core compression off → identity)', async () => {
const server = await serveBun(compressionApp(), { hostname: '127.0.0.1', port: 0 });
try {
await serverDoesNotCompress(server.port);
} finally {
await server.close({ timeoutMs: 1000 });
}
});
test("documented: node:zlib's async gzip is off the main thread on Bun", async () => {
const { ms, ticks } = await ticksDuringGzip();
if (ms < 50) throw new Error(`gzip took ${Math.round(ms)} ms — too fast to tell; enlarge the input`);
if (ticks < ms / 4) throw new Error(`only ${ticks} ticks in ${Math.round(ms)} ms: Bun blocked the loop — update the docs`);
});
+29
View File
@@ -0,0 +1,29 @@
// CARD-14 (#113) under the real Bun runtime: Set-Cookie arrays leave `Bun.serve` as separate
// lines, and @cookie reads the request header. Run with: npm run test:bun
import 'reflect-metadata';
import { test, expect } from 'bun:test';
import { createApp } from '../../src/index.ts';
import { serveBun } from '../../src/bun.ts';
import { CookieModule, C1, C2 } from '../fixtures/cookie-app.ts';
test('T7/T8/T11 on Bun.serve: two Set-Cookie lines, other arrays joined, @cookie decoded', async () => {
const server = await serveBun(createApp({ modules: [CookieModule] }), { hostname: '127.0.0.1', port: 0 });
try {
const base = `http://127.0.0.1:${server.port}`;
const two = await fetch(`${base}/c/two`);
await two.arrayBuffer();
expect(two.headers.getSetCookie()).toEqual([C1, C2]);
expect(two.headers.get('x-custom')).toBe('a, b');
const error = await fetch(`${base}/c/error`);
await error.arrayBuffer();
expect(error.status).toBe(401);
expect(error.headers.getSetCookie()).toEqual([C1, C2]);
const one = await fetch(`${base}/c/one`, { headers: { cookie: 'a=1; a=2; b=%41' } });
expect(await one.json()).toEqual({ a: '1', b: 'A' });
} finally {
await server.close({ timeoutMs: 1000 });
}
});
+37
View File
@@ -0,0 +1,37 @@
// CARD-15 (#114) under the real Bun runtime: static 304 without reading the file (T1), and a
// handler ETag round-trip under `etag: true` (T5). Run with: npm run test:bun
import 'reflect-metadata';
import fs from 'node:fs';
import { test, expect, spyOn } from 'bun:test';
import { createApp } from '../../src/index.ts';
import { serveBun } from '../../src/bun.ts';
import { EtagModule, STATIC_DIR } from '../fixtures/etag-app.ts';
test('T1/T5 on Bun.serve: static and handler 304s, readFile once', async () => {
const readFile = spyOn(fs.promises, 'readFile');
const server = await serveBun(createApp({ modules: [EtagModule], etag: true, static: STATIC_DIR }), {
hostname: '127.0.0.1',
port: 0,
});
const base = `http://127.0.0.1:${server.port}`;
try {
const s1 = await fetch(`${base}/asset.txt`);
expect(await s1.text()).toBe('served');
const etag = s1.headers.get('etag')!;
expect(etag).toMatch(/^W\/"\d+-[0-9a-z]+"$/);
expect(s1.headers.get('cache-control')).toBe('no-cache');
const s2 = await fetch(`${base}/asset.txt`, { headers: { 'if-none-match': etag } });
expect([s2.status, await s2.text(), s2.headers.get('etag'), s2.headers.get('content-type')]).toEqual([304, '', etag, null]);
expect(readFile).toHaveBeenCalledTimes(1);
const h1 = await fetch(`${base}/h/json`);
await h1.text();
const tag = h1.headers.get('etag')!;
const h2 = await fetch(`${base}/h/json`, { headers: { 'if-none-match': tag } });
expect([h2.status, await h2.text(), h2.headers.get('etag')]).toEqual([304, '', tag]);
} finally {
readFile.mockRestore();
await server.close({ timeoutMs: 1000 });
}
});
+88
View File
@@ -99,3 +99,91 @@ test('mesh on Bun: a teacup reconnects to a teapot that came back', async () =>
await teapot.stop();
}
});
// CARD-19 (#124, D15): remote routes follow teapot membership on Bun too.
@Route('/remote')
class PingCtl {
@Get('/ping', { export: true })
ping() {
return { from: 'teapot' };
}
}
@Module({ mountpoint: '/api', controllers: [PingCtl] })
class PingTeapotModule {}
@Module({ mountpoint: '/api', controllers: [] })
class BareTeacupModule {}
async function startPingTeapot(port: number) {
const app = createApp({ modules: [PingTeapotModule], experimental: true, mesh: { secret: SECRET } });
const server = await serveBun(app, { port });
return {
stop: async () => {
server.stop(true);
await app.close();
},
};
}
/** Polls `GET path` until it answers `status`, or fails after `ms`. */
async function untilStatus(app: ReturnType<typeof createApp>, path: string, status: number, ms = 3000) {
const deadline = Date.now() + ms;
let last = 0;
while (Date.now() < deadline) {
const res = await app.fetch(new Request(`http://x${path}`));
await res.text();
last = res.status;
if (last === status) return;
await settle(25);
}
throw new Error(`${path} answered ${last}, expected ${status}`);
}
const pingTeacup = (port: number) =>
createApp({
modules: [BareTeacupModule],
experimental: true,
mesh: {
teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: SECRET }],
reconnect: { initialDelayMs: 20, maxDelayMs: 60 },
bootTimeoutMs: 100,
heartbeatMs: 50,
timeoutMs: 2000,
},
});
test('mesh on Bun: a teapot absent at boot has its routes served once it connects (CARD-19 T1)', async () => {
const port = freePort();
const teacup = pingTeacup(port);
let teapot: Awaited<ReturnType<typeof startPingTeapot>> | undefined;
try {
expect((await teacup.fetch(new Request('http://x/api/remote/ping'))).status).toBe(404);
teapot = await startPingTeapot(port);
await untilStatus(teacup, '/api/remote/ping', 200);
} finally {
await teacup.close();
await teapot?.stop();
}
});
test('mesh on Bun: a reconnecting teapot keeps its routes with 503 + retry-after (CARD-19 T2)', async () => {
const port = freePort();
const teapot = await startPingTeapot(port);
const teacup = pingTeacup(port);
try {
await untilStatus(teacup, '/api/remote/ping', 200);
await teapot.stop();
await untilStatus(teacup, '/api/remote/ping', 503);
const down = await teacup.fetch(new Request('http://x/api/remote/ping'));
expect(down.status).toBe(503);
expect(Number(down.headers.get('retry-after'))).toBeGreaterThanOrEqual(1);
const options = await teacup.fetch(new Request('http://x/api/remote/ping', { method: 'OPTIONS' }));
expect(options.headers.get('allow')).toBe('GET, HEAD, OPTIONS');
} finally {
await teacup.close();
}
});
+36
View File
@@ -112,3 +112,39 @@ test('mesh on Bun: a remote step colliding with a local token fails the splice',
tServer.stop(true);
}
});
// CARD-20 (#125, D16): HEAD on a remote GET answers like HEAD on a local one.
@Route('/remote')
class RemoteHeadCtl {
@Get('/x', { export: true })
x() {
return { a: 1 };
}
}
@Module({ mountpoint: '/api', controllers: [RemoteHeadCtl] })
class RemoteHeadTeapotModule {}
@Module({ mountpoint: '/api', controllers: [] })
class EmptyTeacupModule {}
test('mesh on Bun: HEAD on a remote GET answers 200 with the GET headers and no body', async () => {
const teapot = createApp({ modules: [RemoteHeadTeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await serveBun(teapot, { port: 0 });
const teacup = createApp({
modules: [EmptyTeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(tServer.port), secret: SECRET }], reconnect: false },
});
const cServer = await serveBun(teacup, { port: 0 });
try {
const res = await fetch(`http://127.0.0.1:${cServer.port}/api/remote/x`, { method: 'HEAD' });
expect(res.status).toBe(200);
expect(res.headers.get('content-type') ?? '').toContain('application/json');
expect(await res.text()).toBe('');
} finally {
await teacup.close();
cServer.stop(true);
tServer.stop(true);
}
});
+377
View File
@@ -0,0 +1,377 @@
// CARD-16 (#112, D13): response compression on the Node adapter (`listen()`) and `app.fetch`.
// Negotiation T1–T6, skips T7/T8/T11, round trip T12, ETag interplay T10, 304 T15, ndjson T14, SSE
// per event T9, the edge rule through both signals (detection and `edgeHandler`), validation, and
// a client leaving mid-stream. Deno, Bun and workerd repeat what applies to them in their suites.
import 'reflect-metadata';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import * as http from 'node:http';
import * as zlib from 'node:zlib';
import type { AddressInfo } from 'node:net';
import { compressionApp, flood, JSON_BODY, HTML_BODY, BIG_BODY, SSE_EVENTS, SSE_GAP_MS } from './fixtures/compression-app';
import { negotiate, resolveCompression } from '../src/http/compression';
import { ticksDuringGzip } from './fixtures/compression-checks';
import { edgeHandler } from '../src/edge';
interface Raw {
status: number;
headers: http.IncomingHttpHeaders;
bytes: Buffer;
}
/** Raw bytes off the socket: no client-side decoding, so a double encoding cannot hide. */
function get(port: number, path: string, headers: Record<string, string> = {}, method = 'GET'): Promise<Raw> {
return new Promise((resolve, reject) => {
const req = http.request({ port, path, method, headers }, (res) => {
const chunks: Buffer[] = [];
res.on('data', (c) => chunks.push(c));
res.on('end', () => resolve({ status: res.statusCode!, headers: res.headers, bytes: Buffer.concat(chunks) }));
});
req.on('error', reject);
req.end();
});
}
const decode = (bytes: Buffer, ce: string | undefined): string =>
(ce === 'br' ? zlib.brotliDecompressSync(bytes) : ce === 'gzip' ? zlib.gunzipSync(bytes) : bytes).toString('utf8');
const ae = (value?: string): Record<string, string> => (value === undefined ? {} : { 'accept-encoding': value });
describe('negotiate() (RFC 9110 §12.5.3)', () => {
const both = ['br', 'gzip'] as ('br' | 'gzip')[];
it.each([
['gzip, br', 'br'], // T1: tie → server preference
['br;q=0, gzip', 'gzip'], // T2
['identity', undefined], // T3
[undefined, undefined], // T3 (absent)
['*;q=0', undefined], // T4
['*', 'br'], // T5: first configured
['gzip;q=1, br;q=0.5', 'gzip'],
['gzip;q=0.5, *', 'br'],
['br;q=bogus, gzip', 'gzip'],
// RFC 9110 §12.4.2 qvalues only: a malformed or out-of-range q excludes the member.
['gzip;q=2, br;q=1', 'br'],
['gzip;q=1e0', undefined],
['gzip;q=0.5000', undefined],
['gzip;q=-1', undefined],
['gzip;q=0.500, br;q=0.4', 'gzip'],
['gzip;q=1.000, br;q=1.', 'br'],
['GZIP', 'gzip'],
])('%s → %s', (header, expected) => {
expect(negotiate(header, both)).toBe(expected);
});
it('T6: encodings [gzip], client accepts only br → identity', () => {
expect(negotiate('br', ['gzip'])).toBeUndefined();
});
});
describe('option validation (at createApp)', () => {
it.each([
{ threshold: -1 },
{ threshold: 1.5 },
{ threshold: '1' },
{ encodings: [] },
{ encodings: ['zstd'] },
{ encodings: 'gzip' },
])('%j throws', (o) => {
expect(() => compressionApp({ compression: o as never })).toThrow(TypeError);
});
it('a non-object throws; off by default', () => {
expect(() => compressionApp({ compression: 'yes' as never })).toThrow(TypeError);
expect(resolveCompression(undefined)).toBeUndefined();
expect(resolveCompression(false)).toBeUndefined();
expect(resolveCompression(true, () => true)).toEqual({ threshold: 1024, encodings: ['br', 'gzip'], encode: true });
});
});
for (const adapter of ['node', 'fetch'] as const) {
describe(`${adapter} adapter, compression: true`, () => {
let close: () => Promise<void> = async () => {};
let call: (path: string, headers?: Record<string, string>, method?: string) => Promise<Raw>;
beforeAll(async () => {
const app = compressionApp({ compression: true, etag: true });
if (adapter === 'node') {
const server = await app.listen(0);
const port = (server.address() as AddressInfo).port;
close = () => app.close();
call = (p, h, m) => get(port, p, h, m);
} else {
call = async (p, h = {}, method = 'GET') => {
const res = await app.fetch(new Request(`http://x${p}`, { method, headers: h }));
const headers: http.IncomingHttpHeaders = {};
res.headers.forEach((v, k) => (headers[k] = v));
return { status: res.status, headers, bytes: Buffer.from(await res.arrayBuffer()) };
};
}
});
afterAll(() => close());
it.each([
['/c/json', 'gzip, br', 'br', JSON_BODY],
['/c/json', 'br;q=0, gzip', 'gzip', JSON_BODY],
['/c/json', '*', 'br', JSON_BODY],
['/c/html', 'gzip', 'gzip', HTML_BODY],
['/c/html', 'br', 'br', HTML_BODY],
['/c/big', 'gzip', 'gzip', BIG_BODY],
['/c/big', 'br', 'br', BIG_BODY],
])('T1/T2/T5/T12 %s with %s → %s, decodes to the original bytes', async (path, accept, ce, original) => {
const r = await call(path, ae(accept));
expect(r.headers['content-encoding']).toBe(ce);
expect(r.headers.vary).toMatch(/Accept-Encoding/i);
expect(r.headers['content-length'] === undefined || Number(r.headers['content-length']) === r.bytes.length).toBe(
true,
);
expect(decode(r.bytes, ce)).toBe(original); // one layer only: a second would not decode to this
});
it.each([['identity'], [undefined], ['*;q=0']])('T3/T4 Accept-Encoding %s → identity + Vary', async (accept) => {
const r = await call('/c/json', ae(accept));
expect(r.headers['content-encoding']).toBeUndefined();
expect(r.headers.vary).toMatch(/Accept-Encoding/i);
expect(r.bytes.toString()).toBe(JSON_BODY);
});
it.each([
['/c/small', 'T7 under threshold', true],
['/c/png', 'T8 image/png', false],
['/c/notype', 'T8 missing content-type', false],
['/c/range', 'T8 content-range', false],
['/c/notransform', 'T11 no-transform', false],
])('%s (%s) is sent identity', async (path, _why, vary) => {
const r = await call(path, ae('gzip, br'));
expect(r.headers['content-encoding']).toBeUndefined();
expect(/accept-encoding/i.test(String(r.headers.vary ?? ''))).toBe(vary);
});
it('T8 handler-set content-encoding is passed through untouched (no double encoding)', async () => {
const r = await call('/c/pre', ae('gzip, br'));
expect(r.headers['content-encoding']).toBe('gzip');
expect(r.bytes.toString()).toBe('y'.repeat(4096));
});
it('T8 HEAD and 204 are not encoded; HEAD keeps Vary, 204 gets none', async () => {
const head = await call('/c/json', ae('gzip'), 'HEAD');
expect(head.headers['content-encoding']).toBeUndefined();
expect(head.headers.vary).toMatch(/Accept-Encoding/i);
const empty = await call('/c/empty', ae('gzip'));
expect(empty.status).toBe(204);
expect(empty.headers['content-encoding']).toBeUndefined();
expect(empty.headers.vary).toBeUndefined();
});
it('merges Vary with a handler Vary', async () => {
const r = await call('/c/vary', ae('gzip'));
expect(r.headers.vary).toBe('Origin, Accept-Encoding');
});
it('T15: a 304 (NotModified) carries Vary, no Content-Type and no body', async () => {
const r = await call('/c/304', ae('gzip'));
expect(r.status).toBe(304);
expect(r.headers.vary).toMatch(/Accept-Encoding/i);
expect(r.headers['content-type']).toBeUndefined();
expect(r.headers['content-encoding']).toBeUndefined();
expect(r.bytes.length).toBe(0);
});
it('T10: etag + gzip → the same ETag as identity; the 304 carries Vary', async () => {
const identity = await call('/c/plainjson', ae('identity'));
const gz = await call('/c/plainjson', ae('gzip'));
expect(gz.headers['content-encoding']).toBe('gzip');
expect(gz.headers.etag).toMatch(/^W\//);
expect(gz.headers.etag).toBe(identity.headers.etag);
const nm = await call('/c/plainjson', { ...ae('gzip'), 'if-none-match': String(gz.headers.etag) });
expect(nm.status).toBe(304);
expect(nm.headers.vary).toMatch(/Accept-Encoding/i);
expect(nm.headers.etag).toBe(gz.headers.etag);
expect(nm.bytes.length).toBe(0);
});
it('a handler strong ETag stays strong on the encoded variant', async () => {
const r = await call('/c/etag', ae('gzip'));
expect(r.headers['content-encoding']).toBe('gzip');
expect(r.headers.etag).toBe('"v1"');
});
it.each(['gzip', 'br'])('T14 ndjson stream is encoded with %s and decodes to the same lines', async (ce) => {
const r = await call('/c/ndjson', ae(ce));
expect(r.headers['content-encoding']).toBe(ce);
expect(r.headers.vary).toMatch(/Accept-Encoding/i);
expect(decode(r.bytes, ce)).toBe('{"n":0}\n{"n":1}\n{"n":2}\n');
});
it('a stream to an identity client gets Vary and is not encoded', async () => {
const r = await call('/c/ndjson', ae('identity'));
expect(r.headers['content-encoding']).toBeUndefined();
expect(r.headers.vary).toMatch(/Accept-Encoding/i);
expect(r.bytes.toString()).toBe('{"n":0}\n{"n":1}\n{"n":2}\n');
});
});
}
describe('custom options', () => {
it('T6 encodings [gzip] with a br-only client → identity; threshold lowers the floor', async () => {
const app = compressionApp({ compression: { encodings: ['gzip'], threshold: 0 } });
const br = await app.fetch(new Request('http://x/c/small', { headers: ae('br') }));
expect(br.headers.get('content-encoding')).toBeNull();
const gz = await app.fetch(new Request('http://x/c/small', { headers: ae('gzip') }));
expect(gz.headers.get('content-encoding')).toBe('gzip');
});
});
describe('edge: core never encodes, Vary only', () => {
const identityWithVary = async (app: ReturnType<typeof compressionApp>) => {
for (const path of ['/c/json', '/c/ndjson']) {
const res = await app.fetch(new Request(`http://x${path}`, { headers: ae('gzip, br') }));
expect(res.headers.get('content-encoding'), path).toBeNull();
expect(res.headers.get('vary'), path).toMatch(/Accept-Encoding/i);
await res.arrayBuffer();
}
};
it('detected at createApp from navigator.userAgent (bare app.fetch)', async () => {
vi.stubGlobal('navigator', { userAgent: 'Cloudflare-Workers' });
try {
await identityWithVary(compressionApp({ compression: true }));
} finally {
vi.unstubAllGlobals();
}
});
it('marked by edgeHandler even when detection sees nothing', async () => {
const app = compressionApp({ compression: true });
edgeHandler(app);
await identityWithVary(app);
});
it('edgeHandler on an app without compression is harmless', async () => {
const app = compressionApp();
const res = await edgeHandler(app)(new Request('http://x/c/json', { headers: ae('gzip') }));
expect(res.headers.get('content-encoding')).toBeNull();
expect(res.headers.get('vary')).toBeNull();
});
});
describe('T9 SSE per-event delivery with compression (Node listen())', () => {
it.each(['gzip', 'br'])('%s: event n is readable before event n+1 is produced', async (ce) => {
const app = compressionApp({ compression: true });
const server = await app.listen(0);
const port = (server.address() as AddressInfo).port;
try {
const lags = await new Promise<number[]>((resolve, reject) => {
http
.get({ port, path: '/c/sse', headers: { 'accept-encoding': ce, accept: 'text/event-stream' } }, (res) => {
expect(res.headers['content-encoding']).toBe(ce);
const dec = ce === 'br' ? zlib.createBrotliDecompress() : zlib.createGunzip();
const out: number[] = [];
let buf = '';
dec.on('data', (d: Buffer) => {
buf += d.toString();
let i;
while ((i = buf.indexOf('\n\n')) >= 0) {
const m = buf.slice(0, i).match(/data: (\{.*\})/);
buf = buf.slice(i + 2);
if (m) out.push(Date.now() - JSON.parse(m[1]).t);
}
});
res.pipe(dec);
dec.on('end', () => resolve(out));
dec.on('error', reject);
})
.on('error', reject);
});
expect(lags).toHaveLength(SSE_EVENTS);
// Each event decodes well inside the gap before the next one is even produced.
for (const lag of lags) expect(lag).toBeLessThan(SSE_GAP_MS / 2);
} finally {
await app.close();
}
});
});
describe('client disconnect mid-stream', () => {
it.each(['gzip', 'br'])('Node %s: the stream closes and the compressor is torn down', async (ce) => {
const app = compressionApp({ compression: true });
const closed = new Promise<void>((resolve) => app.bus.on('stream:close', () => resolve()));
const server = await app.listen(0);
const port = (server.address() as AddressInfo).port;
try {
await new Promise<void>((resolve, reject) => {
const req = http.get({ port, path: '/c/forever', headers: { 'accept-encoding': ce } }, (res) => {
expect(res.headers['content-encoding']).toBe(ce);
res.once('data', () => {
req.destroy();
resolve();
});
});
req.on('error', () => {});
setTimeout(() => reject(new Error('no data')), 2000);
});
await closed;
} finally {
await app.close();
}
});
it.each(['gzip', 'br'])('app.fetch %s: cancelling the body cancels the source', async (ce) => {
const app = compressionApp({ compression: true });
const closed = new Promise<void>((resolve) => app.bus.on('stream:close', () => resolve()));
const res = await app.fetch(new Request('http://x/c/forever', { headers: ae(ce) }));
expect(res.headers.get('content-encoding')).toBe(ce);
const reader = res.body!.getReader();
const first = await reader.read();
expect(first.done).toBe(false);
await reader.cancel();
await closed;
});
});
describe('slow client backpressure (Node)', () => {
it.each(['gzip', 'br'])('%s: a client that stops reading stops the producer', async (ce) => {
const app = compressionApp({ compression: true });
const server = await app.listen(0);
const port = (server.address() as AddressInfo).port;
try {
const req = http.get({ port, path: '/c/flood', headers: { 'accept-encoding': ce } }, (res) => {
expect(res.headers['content-encoding']).toBe(ce);
res.pause(); // never read
});
req.on('error', () => {});
// Each frame is ~28 KB of nearly incompressible text. Without backpressure the generator never
// stops; with it, it stops once the socket, the response and the compressor's buffers are full.
// How many frames that takes depends on the kernel's socket buffers (Linux auto-tunes them to
// several MB), so wait for production to stall rather than for a fixed time.
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
let previous = -1;
for (let waited = 0; flood.produced !== previous; waited += 200) {
expect(waited, `still producing after ${waited} ms: ${flood.produced} frames`).toBeLessThan(10_000);
previous = flood.produced;
await sleep(200);
}
const stalled = flood.produced;
await sleep(500);
expect(flood.produced - stalled).toBeLessThanOrEqual(1);
expect(stalled).toBeLessThan(2000);
req.destroy();
} finally {
flood.produced = 0;
await app.close();
}
}, 20_000);
});
describe('documented runtime behaviour (Node)', () => {
it("node:zlib's async gzip runs off the main thread, so the loop keeps ticking", async () => {
const { ms, ticks } = await ticksDuringGzip();
expect(ms).toBeGreaterThan(50);
expect(ticks).toBeGreaterThan(ms / 4);
});
});
+306
View File
@@ -0,0 +1,306 @@
// CARD-14 (#113): reading cookies with @cookie/@cookies, writing them with setCookie, and more than
// one Set-Cookie line per response on the Node adapter and app.fetch. Deno, Bun and edge repeat the
// two-line cases in test/deno/cookies.test.ts, test/bun/cookies.test.ts and test/edge/run.ts.
import 'reflect-metadata';
import http from 'node:http';
import type { AddressInfo } from 'node:net';
import WebSocket from 'ws';
import { describe, expect, it, afterAll } from 'vitest';
import {
createApp,
Route,
Get,
Ws,
Module,
Transformer,
HttpError,
needs,
cookie,
cookies,
setCookie,
parseCookies,
type TransformerFn,
} from '../src/index';
const C1 = setCookie('a', '1');
const C2 = setCookie('b', '2', { maxAge: 60 });
const twoCookies: TransformerFn = (value) => ({
status: 200,
headers: { 'content-type': 'application/json', 'set-cookie': [C1, C2] },
body: JSON.stringify(value),
});
@Route('/c')
class CookieCtl {
@Get('/one')
one(@cookie('a') a: string | undefined, @cookie('b') b: string | undefined) {
return { a: a ?? null, b: b ?? null };
}
@Get('/all')
all(@cookies() all: Record<string, string>) {
return { all, keys: Object.keys(all) };
}
@Get('/pick')
pick(@cookies(['d', 'e']) picked: Record<string, string>) {
return picked;
}
@Get('/needs')
viaNeeds(@needs('cookies') jar: Record<string, string>) {
return { sid: jar.sid ?? null };
}
@Get('/transformer')
@Transformer(twoCookies)
transformer() {
return { ok: true };
}
@Get('/error')
error() {
throw new HttpError(401, 'nope', undefined, { 'set-cookie': [C1, C2] });
}
@Get('/custom')
@Transformer((v) => ({ headers: { 'x-custom': ['a', 'b'], vary: ['Accept', 'Accept-Language'] }, body: String(v) }))
custom() {
return 'x';
}
@Get('/renderer')
renderer() {
throw new Error('render me');
}
@Ws('/ws')
ws(@cookie('a') a: string | undefined) {
return (async function* () {
yield `a=${a}`;
})();
}
}
@Module({ mountpoint: '/', controllers: [CookieCtl] })
class M {}
const app = createApp({
modules: [M],
cors: { origins: ['http://ok.test'] },
onError: (error) =>
error instanceof Error && error.message === 'render me'
? { status: 418, headers: { 'content-type': 'text/plain', 'set-cookie': [C1, C2] }, body: 'teapot' }
: undefined,
});
let server: http.Server;
let port: number;
afterAll(() => server?.close());
async function boot(): Promise<void> {
if (server) return;
server = await app.listen(0);
port = (server.address() as AddressInfo).port;
}
/** A raw request, so repeated header lines are visible as they came off the socket. */
async function raw(
path: string,
headers: Record<string, string> = {},
): Promise<{ status: number; lines: [string, string][]; body: string }> {
await boot();
return new Promise((resolve, reject) => {
http
.get({ host: '127.0.0.1', port, path, headers }, (res) => {
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk) => (body += chunk));
res.on('end', () => {
const lines: [string, string][] = [];
for (let i = 0; i < res.rawHeaders.length; i += 2)
lines.push([res.rawHeaders[i].toLowerCase(), res.rawHeaders[i + 1]]);
resolve({ status: res.statusCode!, lines, body });
});
})
.on('error', reject);
});
}
const valuesOf = (lines: [string, string][], name: string) => lines.filter(([k]) => k === name).map(([, v]) => v);
const fetchVia = (path: string, headers: Record<string, string> = {}) =>
app.fetch(new Request(`http://x${path}`, { headers }));
describe('parseCookies', () => {
it('T1: first value wins, %-sequences decode', () => {
expect(parseCookies('a=1; a=2; b=%41')).toEqual({ a: '1', b: 'A' });
});
it('T2: malformed pairs are skipped, an undecodable value is kept raw', () => {
expect({ ...parseCookies('=x; c; d=%ZZ; e=5') }).toEqual({ d: '%ZZ', e: '5' });
});
it('T3: no header is an empty map', () => {
expect({ ...parseCookies(undefined) }).toEqual({});
});
it('joins several cookie lines (HTTP/2, proxies) with "; "', () => {
expect({ ...parseCookies(['a=1', 'b=2; a=3']) }).toEqual({ a: '1', b: '2' });
});
it('treats __proto__ as an ordinary key, never a prototype write', () => {
const map = parseCookies('__proto__=x; constructor=y');
expect(map['__proto__']).toBe('x');
expect(map['constructor']).toBe('y');
expect(({} as any).x).toBeUndefined();
});
});
describe('setCookie', () => {
it('T4: documented defaults, Secure per D10', () => {
expect(setCookie('s', 'v')).toBe('s=v; Path=/; Secure; HttpOnly; SameSite=Lax');
});
it('serialises every option', () => {
const expires = new Date(Date.UTC(2030, 0, 1));
expect(
setCookie('s', 'v', {
maxAge: 10,
expires,
domain: 'example.com',
path: '/app',
httpOnly: false,
sameSite: 'none',
partitioned: true,
}),
).toBe(
's=v; Max-Age=10; Expires=Tue, 01 Jan 2030 00:00:00 GMT; Domain=example.com; Path=/app; Secure; SameSite=None; Partitioned',
);
expect(setCookie('s', 'v', { secure: false, sameSite: 'strict' })).toBe('s=v; Path=/; HttpOnly; SameSite=Strict');
});
it('T5: refuses header injection and bad names, naming the field', () => {
expect(() => setCookie('s', 'v\r\nX: y')).toThrow(/value for 's'/);
expect(() => setCookie('a b', 'v')).toThrow(/name "a b"/);
for (const bad of ['a;b', 'a,b', 'a b', 'a\tb', 'a\u0001b'])
expect(() => setCookie('s', bad), JSON.stringify(bad)).toThrow(/value/);
expect(() => setCookie('s', 'v', { path: '/\r\nX: y' })).toThrow(/path/);
expect(() => setCookie('s', 'v', { domain: 'a.com\nX' })).toThrow(/domain/);
expect(() => setCookie('s', 'v', { path: '/; Domain=evil' })).toThrow(/path/);
expect(() => setCookie('s', 'v', { maxAge: 1.5 })).toThrow(/maxAge/);
expect(() => setCookie('s', 'v', { expires: new Date('nope') })).toThrow(/expires/);
expect(() => setCookie('s', 'v', { sameSite: 'loose' as never })).toThrow(/sameSite/);
});
it('T6: sameSite none and partitioned both require secure', () => {
expect(() => setCookie('s', 'v', { sameSite: 'none', secure: false })).toThrow(/sameSite 'none'.*secure/);
expect(() => setCookie('s', 'v', { partitioned: true, secure: false })).toThrow(/partitioned.*secure/);
});
});
describe('@cookie / @cookies on a live Node server', () => {
it('T1: first wins and decodes', async () => {
const res = await raw('/c/one', { cookie: 'a=1; a=2; b=%41' });
expect(JSON.parse(res.body)).toEqual({ a: '1', b: 'A' });
});
it('T2: malformed pairs never 400', async () => {
const res = await raw('/c/all', { cookie: '=x; c; d=%ZZ; e=5' });
expect(res.status).toBe(200);
expect(JSON.parse(res.body).all).toEqual({ d: '%ZZ', e: '5' });
});
it('T3: no Cookie header', async () => {
expect(JSON.parse((await raw('/c/all')).body).all).toEqual({});
expect(JSON.parse((await raw('/c/one')).body)).toEqual({ a: null, b: null });
});
it('picks a key list', async () => {
expect(JSON.parse((await raw('/c/pick', { cookie: 'd=4; e=5; f=6' })).body)).toEqual({ d: '4', e: '5' });
});
it('@needs("cookies") resolves the same map', async () => {
expect(JSON.parse((await raw('/c/needs', { cookie: 'sid=abc' })).body)).toEqual({ sid: 'abc' });
});
it('resolves on a WebSocket route', async () => {
await boot();
const client = new WebSocket(`ws://127.0.0.1:${port}/c/ws`, { headers: { cookie: 'a=hello' } });
const message = await new Promise<string>((resolve, reject) => {
client.on('message', (data) => resolve(String(data)));
client.on('error', reject);
});
client.close();
expect(message).toBe('a=hello');
});
});
describe('several Set-Cookie lines', () => {
it('T7: custom @Transformer, Node: two lines', async () => {
const res = await raw('/c/transformer');
expect(valuesOf(res.lines, 'set-cookie')).toEqual([C1, C2]);
});
it('T7: custom @Transformer, app.fetch: two lines', async () => {
const res = await fetchVia('/c/transformer');
expect(res.headers.getSetCookie()).toEqual([C1, C2]);
});
it('T8: HttpError.headers and an onError renderer: two lines on both adapters', async () => {
for (const path of ['/c/error', '/c/renderer']) {
const res = await raw(path);
expect(valuesOf(res.lines, 'set-cookie'), path).toEqual([C1, C2]);
expect((await fetchVia(path)).headers.getSetCookie(), path).toEqual([C1, C2]);
}
});
it('T9: array kept, injected vary merged with a handler vary array', async () => {
const res = await raw('/c/custom', { origin: 'http://ok.test' });
const vary = valuesOf(res.lines, 'vary');
expect(vary).toHaveLength(1);
expect(vary[0].split(', ')).toEqual(['Accept', 'Accept-Language', 'Origin']);
const viaFetch = await fetchVia('/c/custom', { origin: 'http://ok.test' });
expect(viaFetch.headers.get('vary')).toBe('Accept, Accept-Language, Origin');
const cookieRes = await raw('/c/transformer', { origin: 'http://ok.test' });
expect(valuesOf(cookieRes.lines, 'set-cookie')).toEqual([C1, C2]);
expect(valuesOf(cookieRes.lines, 'vary')).toEqual(['Origin']);
});
it('T11: any other array header is one line joined with ", "', async () => {
const res = await raw('/c/custom');
expect(valuesOf(res.lines, 'x-custom')).toEqual(['a, b']);
expect((await fetchVia('/c/custom')).headers.get('x-custom')).toBe('a, b');
});
it('injected security headers stay authoritative over a handler array', async () => {
@Route('/s')
class Spoof {
@Get('/')
@Transformer(() => ({ headers: { 'x-content-type-options': ['sniff', 'me'] }, body: '' }))
get() {
return null;
}
}
@Module({ mountpoint: '/', controllers: [Spoof] })
class SM {}
const res = await createApp({ modules: [SM] }).fetch(new Request('http://x/s'));
expect(res.headers.get('x-content-type-options')).toBe('nosniff');
});
});
describe('OpenAPI', () => {
it('lists a @cookie arg as an in: cookie parameter', () => {
const doc = app.openapi();
const params = (doc.paths['/c/one'].get as any).parameters;
expect(params).toEqual(
expect.arrayContaining([
{ name: 'a', in: 'cookie', required: false, schema: { type: 'string' } },
{ name: 'b', in: 'cookie', required: false, schema: { type: 'string' } },
]),
);
});
});
+43
View File
@@ -0,0 +1,43 @@
// CARD-16 (#112) under the real Deno runtime, importing `src/` the way JSR serves it — so `node:zlib`
// is reached through `nodeRequire`'s `process.getBuiltinModule` path. Deno runs zlib's async API on
// the main thread (documented limitation); these checks cover correctness, not throughput.
// Run with: npm run test:deno
import 'npm:reflect-metadata';
import { serveDeno } from '../../src/deno.ts';
import { compressionApp } from '../fixtures/compression-app.ts';
import { checks, serverDoesNotCompress, ticksDuringGzip } from '../fixtures/compression-checks.ts';
for (const [name, run] of Object.entries(checks)) {
Deno.test(`compression on Deno.serve: ${name}`, async () => {
const server = await serveDeno(compressionApp({ compression: true, etag: true }), {
hostname: '127.0.0.1',
port: 0,
onListen: () => {},
});
try {
await run((server as unknown as { addr: { port: number } }).addr.port);
} finally {
await server.close({ timeoutMs: 1000 });
}
});
}
// The documented Deno facts (CARD-16; `guides/runtimes.md`). If one of these starts failing, Deno
// changed and the docs have to change with it — not the assertion.
Deno.test('documented: Deno.serve does not compress by itself (core compression off → identity)', async () => {
const server = await serveDeno(compressionApp(), { hostname: '127.0.0.1', port: 0, onListen: () => {} });
try {
await serverDoesNotCompress((server as unknown as { addr: { port: number } }).addr.port);
} finally {
await server.close({ timeoutMs: 1000 });
}
});
Deno.test("documented: node:zlib's async gzip runs on Deno's main thread", async () => {
const { ms, ticks } = await ticksDuringGzip();
if (ms < 50) throw new Error(`gzip took ${Math.round(ms)} ms — too fast to tell; enlarge the input`);
if (ticks > Math.max(5, ms / 10))
throw new Error(`timers kept firing (${ticks} ticks in ${Math.round(ms)} ms): Deno now offloads zlib — update the docs`);
});
+29
View File
@@ -0,0 +1,29 @@
// CARD-14 (#113) under the real Deno runtime: Set-Cookie arrays leave `Deno.serve` as separate
// lines, and @cookie reads the request header. Run with: npm run test:deno
import 'npm:reflect-metadata';
import { assertEquals } from 'jsr:@std/assert';
import { createApp } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts';
import { CookieModule, C1, C2 } from '../fixtures/cookie-app.ts';
Deno.test('T7/T8/T11 on Deno.serve: two Set-Cookie lines, other arrays joined, @cookie decoded', async () => {
const server = await serveDeno(createApp({ modules: [CookieModule] }), { hostname: '127.0.0.1', port: 0, onListen: () => {} });
const port = (server as unknown as { addr: { port: number } }).addr.port;
try {
const two = await fetch(`http://127.0.0.1:${port}/c/two`);
await two.body?.cancel();
assertEquals(two.headers.getSetCookie(), [C1, C2]);
assertEquals(two.headers.get('x-custom'), 'a, b');
const error = await fetch(`http://127.0.0.1:${port}/c/error`);
await error.body?.cancel();
assertEquals(error.status, 401);
assertEquals(error.headers.getSetCookie(), [C1, C2]);
const one = await fetch(`http://127.0.0.1:${port}/c/one`, { headers: { cookie: 'a=1; a=2; b=%41' } });
assertEquals(await one.json(), { a: '1', b: 'A' });
} finally {
await server.close({ timeoutMs: 1000 });
}
});
+45
View File
@@ -0,0 +1,45 @@
// CARD-15 (#114) under the real Deno runtime: static 304 without reading the file (T1), and a
// handler ETag round-trip under `etag: true` (T5). Run with: npm run test:deno
import 'npm:reflect-metadata';
import fs from 'node:fs';
import { assertEquals, assertMatch } from 'jsr:@std/assert';
import { createApp } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts';
import { EtagModule, STATIC_DIR } from '../fixtures/etag-app.ts';
Deno.test('T1/T5 on Deno.serve: static and handler 304s, readFile once', async () => {
const original = fs.promises.readFile;
let reads = 0;
// deno-lint-ignore no-explicit-any
(fs.promises as any).readFile = (...args: unknown[]) => {
// Deno's own readFile re-enters this function with a file descriptor (FileHandle.readFile), so
// only calls naming a path are reads by core.
if (typeof args[0] === 'string') reads++;
// deno-lint-ignore no-explicit-any
return (original as any).apply(fs.promises, args);
};
const app = createApp({ modules: [EtagModule], etag: true, static: STATIC_DIR });
const server = await serveDeno(app, { hostname: '127.0.0.1', port: 0, onListen: () => {} });
const base = `http://127.0.0.1:${(server as unknown as { addr: { port: number } }).addr.port}`;
try {
const s1 = await fetch(`${base}/asset.txt`);
assertEquals(await s1.text(), 'served');
const etag = s1.headers.get('etag')!;
assertMatch(etag, /^W\/"\d+-[0-9a-z]+"$/);
assertEquals(s1.headers.get('cache-control'), 'no-cache');
const s2 = await fetch(`${base}/asset.txt`, { headers: { 'if-none-match': etag } });
assertEquals([s2.status, await s2.text(), s2.headers.get('etag'), s2.headers.get('content-type')], [304, '', etag, null]);
assertEquals(reads, 1);
const h1 = await fetch(`${base}/h/json`);
await h1.text();
const tag = h1.headers.get('etag')!;
const h2 = await fetch(`${base}/h/json`, { headers: { 'if-none-match': tag } });
assertEquals([h2.status, await h2.text(), h2.headers.get('etag')], [304, '', tag]);
} finally {
(fs.promises as { readFile: unknown }).readFile = original;
await server.close({ timeoutMs: 1000 });
}
});
+93
View File
@@ -99,3 +99,96 @@ Deno.test('mesh on Deno: a teacup reconnects to a teapot that came back', async
await teapot.stop();
}
});
// CARD-19 (#124, D15): remote routes follow teapot membership on Deno too.
@Route('/remote')
class PingCtl {
@Get('/ping', { export: true })
ping() {
return { from: 'teapot' };
}
}
@Module({ mountpoint: '/api', controllers: [PingCtl] })
class PingTeapotModule {}
@Module({ mountpoint: '/api', controllers: [] })
class BareTeacupModule {}
async function startPingTeapot(port: number) {
const app = createApp({ modules: [PingTeapotModule], experimental: true, mesh: { secret: SECRET } });
const server = await serveDeno(app, { port });
await new Promise((r) => setTimeout(r, 50));
return {
stop: async () => {
await server.shutdown();
await app.close();
},
};
}
/** Polls `GET path` until it answers `status`, or fails after `ms`. */
async function untilStatus(app: ReturnType<typeof createApp>, path: string, status: number, ms = 3000) {
const deadline = Date.now() + ms;
let last = 0;
while (Date.now() < deadline) {
const res = await app.fetch(new Request(`http://x${path}`));
await res.body?.cancel();
last = res.status;
if (last === status) return;
await settle(25);
}
throw new Error(`${path} answered ${last}, expected ${status}`);
}
const pingTeacup = (port: number) =>
createApp({
modules: [BareTeacupModule],
experimental: true,
mesh: {
teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: SECRET }],
reconnect: { initialDelayMs: 20, maxDelayMs: 60 },
bootTimeoutMs: 100,
heartbeatMs: 50,
timeoutMs: 2000,
},
});
Deno.test('mesh on Deno: a teapot absent at boot has its routes served once it connects (CARD-19 T1)', async () => {
const port = freePort();
const teacup = pingTeacup(port);
let teapot: Awaited<ReturnType<typeof startPingTeapot>> | undefined;
try {
const before = await teacup.fetch(new Request('http://x/api/remote/ping'));
await before.body?.cancel();
assertEquals(before.status, 404);
teapot = await startPingTeapot(port);
await untilStatus(teacup, '/api/remote/ping', 200);
} finally {
await teacup.close();
await teapot?.stop();
}
});
Deno.test('mesh on Deno: a reconnecting teapot keeps its routes with 503 + retry-after (CARD-19 T2)', async () => {
const port = freePort();
const teapot = await startPingTeapot(port);
const teacup = pingTeacup(port);
try {
await untilStatus(teacup, '/api/remote/ping', 200);
await teapot.stop();
await untilStatus(teacup, '/api/remote/ping', 503);
const down = await teacup.fetch(new Request('http://x/api/remote/ping'));
await down.body?.cancel();
assertEquals(down.status, 503);
assertEquals(Number(down.headers.get('retry-after')) >= 1, true);
const options = await teacup.fetch(new Request('http://x/api/remote/ping', { method: 'OPTIONS' }));
assertEquals(options.headers.get('allow'), 'GET, HEAD, OPTIONS');
} finally {
await teacup.close();
}
});
+36
View File
@@ -142,3 +142,39 @@ Deno.test('mesh on Deno: a remote step colliding with a local token fails the sp
await t.server.shutdown();
}
});
// CARD-20 (#125, D16): HEAD on a remote GET answers like HEAD on a local one.
@Route('/remote')
class RemoteHeadCtl {
@Get('/x', { export: true })
x() {
return { a: 1 };
}
}
@Module({ mountpoint: '/api', controllers: [RemoteHeadCtl] })
class RemoteHeadTeapotModule {}
@Module({ mountpoint: '/api', controllers: [] })
class EmptyTeacupModule {}
Deno.test('mesh on Deno: HEAD on a remote GET answers 200 with the GET headers and no body', async () => {
const teapot = createApp({ modules: [RemoteHeadTeapotModule], experimental: true, mesh: { secret: SECRET } });
const t = await serve(teapot);
const teacup = createApp({
modules: [EmptyTeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(t.port), secret: SECRET }], reconnect: false },
});
const c = await serve(teacup);
try {
const res = await fetch(`http://127.0.0.1:${c.port}/api/remote/x`, { method: 'HEAD' });
assertEquals(res.status, 200);
assertStringIncludes(res.headers.get('content-type') ?? '', 'application/json');
assertEquals(await res.text(), '');
} finally {
await teacup.close();
await c.server.shutdown();
await t.server.shutdown();
}
});
+13
View File
@@ -0,0 +1,13 @@
// CARD-16 (#112): the compression fixture served from real workerd, twice — through `edgeHandler`
// (T13) and as a bare `app.fetch` export (T16, reached with `Host: bare`). Core must never encode
// in either; the platform (miniflare locally, Cloudflare when deployed) may. See compression.ts.
import { edgeHandler } from '../../src/edge';
import { compressionApp } from '../fixtures/compression-app';
const viaHandler = edgeHandler(compressionApp({ compression: true }));
const bare = compressionApp({ compression: true });
export default {
fetch: (request: Request, env?: unknown, ctx?: Parameters<typeof viaHandler>[2]) =>
new URL(request.url).hostname === 'bare' ? bare.fetch(request) : viaHandler(request, env, ctx),
};
+155
View File
@@ -0,0 +1,155 @@
// CARD-16 (#112) on real workerd via miniflare: T1 (edge), T12, T13, T16 and SSE. Reads raw bytes
// off a real socket with node:http — `dispatchFetch` would decode and hide a double encoding — and
// peels encodings by magic bytes, requiring at most one layer and the original bytes. Run twice:
// with the default compat flags (workerd detected through `navigator.userAgent`) and with
// `no_global_navigator` (no `navigator` at all), so neither signal alone carries the result.
//
// Run with: tsx test/edge/compression.ts (chained from `npm run test:edge`)
import 'reflect-metadata';
import { strict as assert } from 'node:assert';
import * as http from 'node:http';
import * as zlib from 'node:zlib';
import { build } from 'esbuild';
import { Miniflare } from 'miniflare';
import { JSON_BODY, HTML_BODY, SSE_EVENTS, SSE_GAP_MS } from '../fixtures/compression-app';
const BUNDLE = 'test/edge/_compression-worker.mjs';
interface Raw {
status: number;
headers: http.IncomingHttpHeaders;
bytes: Buffer;
}
function get(url: URL, path: string, host: string, ae?: string): Promise<Raw> {
return new Promise((resolve, reject) => {
http
.get(new URL(path, url), { headers: { host, ...(ae ? { 'accept-encoding': ae } : {}) } }, (res) => {
const chunks: Buffer[] = [];
res.on('data', (c) => chunks.push(c));
res.on('end', () => resolve({ status: res.statusCode!, headers: res.headers, bytes: Buffer.concat(chunks) }));
})
.on('error', reject);
});
}
/** Decodes by magic bytes, not by header, so a second layer is counted even if the header lies. */
function peel(bytes: Buffer): { layers: string[]; text: string } {
const layers: string[] = [];
let b = bytes;
for (let k = 0; k < 4; k++) {
if (b[0] === 0x1f && b[1] === 0x8b) {
b = zlib.gunzipSync(b);
layers.push('gzip');
continue;
}
const first = b.toString('utf8', 0, 1);
if (b.length === 0 || first === '{' || first === '<') break;
try {
b = zlib.brotliDecompressSync(b);
layers.push('br');
} catch {
layers.push('??');
break;
}
}
return { layers, text: b.toString('utf8') };
}
function sseLags(url: URL, host: string): Promise<number[]> {
return new Promise((resolve, reject) => {
http
.get(new URL('/c/sse', url), { headers: { host, 'accept-encoding': 'gzip, br', accept: 'text/event-stream' } }, (res) => {
assert.equal(res.headers['content-encoding'], undefined, 'edge SSE: encoded');
const out: number[] = [];
let buf = '';
res.on('data', (d: Buffer) => {
buf += d.toString();
let i;
while ((i = buf.indexOf('\n\n')) >= 0) {
const m = buf.slice(0, i).match(/data: (\{.*\})/);
buf = buf.slice(i + 2);
if (m) out.push(Date.now() - JSON.parse(m[1]).t);
}
});
res.on('end', () => resolve(out));
})
.on('error', reject);
});
}
async function run(flags: string[]): Promise<void> {
const mf = new Miniflare({
modules: true,
scriptPath: BUNDLE,
compatibilityDate: '2024-11-01',
compatibilityFlags: flags,
host: '127.0.0.1',
port: 0,
});
const url = await mf.ready;
try {
for (const host of ['handler', 'bare']) {
for (const [path, original] of [
['/c/json', JSON_BODY],
['/c/html', HTML_BODY],
] as const) {
for (const ae of ['gzip, br', 'gzip', 'br', 'br;q=0, gzip', 'identity', undefined]) {
const label = `[${flags.join(',')}] ${host} ${path} ${ae ?? '(none)'}`;
const r = await get(url, path, host, ae);
const { layers, text } = peel(r.bytes);
assert.equal(r.status, 200, `${label}: status ${r.status}`);
assert.ok(layers.length <= 1, `${label}: ${layers.join('+')} — doubly encoded`);
assert.equal(text, original, `${label}: body mismatch`);
assert.equal(r.headers['content-encoding'], layers[0], `${label}: header does not match the payload`);
assert.match(String(r.headers.vary), /accept-encoding/i, `${label}: no Vary`);
if (!ae || ae === 'identity') assert.equal(layers.length, 0, `${label}: identity client got an encoding`);
}
}
const lags = await sseLags(url, host);
assert.equal(lags.length, SSE_EVENTS, `${host}: SSE events`);
for (const lag of lags) assert.ok(lag < SSE_GAP_MS / 2, `${host}: SSE lag ${lag} ms`);
}
} finally {
await mf.dispose();
}
}
async function main() {
await build({
entryPoints: ['test/edge/compression-worker.ts'],
bundle: true,
format: 'esm',
outfile: BUNDLE,
platform: 'browser',
target: 'esnext',
external: ['node:*', 'http', 'https'],
alias: {
crypto: 'node:crypto',
stream: 'node:stream',
zlib: 'node:zlib',
buffer: 'node:buffer',
events: 'node:events',
net: 'node:net',
tls: 'node:tls',
util: 'node:util',
},
});
await run(['nodejs_compat']);
await run(['nodejs_compat', 'no_global_navigator']);
console.log(
'edge (workerd): compression — edgeHandler and bare app.fetch, with and without navigator: identity from core, ≤ 1 layer on the wire, Vary set, SSE on time — PASS',
);
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
+27 -1
View File
@@ -66,6 +66,32 @@ async function main() {
assert.equal(httpRes.status, 200);
assert.deepEqual(await httpRes.json(), { ok: true });
// CARD-14 (#113): a Set-Cookie array leaves workerd as one line per cookie; other arrays join.
const cookieRes = await mf.dispatchFetch('http://localhost/rt/cookies');
await cookieRes.arrayBuffer();
assert.deepEqual(cookieRes.headers.getSetCookie(), ['a=1; Path=/', 'b=2; Path=/']);
assert.equal(cookieRes.headers.get('x-custom'), 'a, b');
const cookieErr = await mf.dispatchFetch('http://localhost/rt/cookie-error');
await cookieErr.arrayBuffer();
assert.equal(cookieErr.status, 401);
assert.deepEqual(cookieErr.headers.getSetCookie(), ['a=1; Path=/', 'b=2; Path=/']);
const readCookie = await mf.dispatchFetch('http://localhost/rt/cookie', { headers: { cookie: 'a=1; b=%41' } });
assert.deepEqual(await readCookie.json(), { b: 'A' });
// CARD-15 (#114), T5/T11: handler ETag round-trip on workerd. Static is a boot error there (N/A).
const tag1 = await mf.dispatchFetch('http://etag/rt/hello');
await tag1.arrayBuffer();
const etag = tag1.headers.get('etag');
assert.match(String(etag), /^W\/"\w+-\w+"$/);
const tag2 = await mf.dispatchFetch('http://etag/rt/hello', { headers: { 'if-none-match': String(etag) } });
assert.equal(tag2.status, 304);
assert.equal(await tag2.text(), '');
assert.equal(tag2.headers.get('etag'), etag);
assert.equal(tag2.headers.get('content-type'), null);
const untagged = await mf.dispatchFetch('http://localhost/rt/hello');
await untagged.arrayBuffer();
assert.equal(untagged.headers.get('etag'), null, 'etag off: no ETag');
// 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
@@ -191,7 +217,7 @@ async function main() {
assert.equal(ready.headers.get('cache-control'), 'no-store');
console.log(
'edge (workerd via miniflare): HTTP 200 + body limits 413/413/200/413 + WS echo:hi + ws limits + cf-connecting-ip under trustProxy + reserved path + health — PASS',
'edge (workerd via miniflare): HTTP 200 + cookies + etag/304 + body limits 413/413/200/413 + WS echo:hi + ws limits + cf-connecting-ip under trustProxy + reserved path + health — PASS',
);
} finally {
await mf.dispose();
+20 -1
View File
@@ -1,7 +1,7 @@
// Worker entry for the real workerd (Miniflare) integration test.
// Mirrors test/deno/ws.test.ts's graph so HTTP + WebSocket behavior is proven
// identically across runtimes. Run via `npm run test:edge` (see test/edge/run.ts).
import { createApp, Route, Get, Post, Ws, body, ctx, Module } from '../../src/index';
import { createApp, Route, Get, Post, Ws, body, ctx, cookie, Module, Transformer, HttpError } from '../../src/index';
import { edgeHandler } from '../../src/edge';
@Route('/rt')
@@ -11,6 +11,23 @@ class Rt {
return { ok: true };
}
// CARD-14 (#113): two Set-Cookie lines from workerd, and @cookie on the request side.
@Get('/cookies')
@Transformer(() => ({ headers: { 'set-cookie': ['a=1; Path=/', 'b=2; Path=/'], 'x-custom': ['a', 'b'] }, body: '{}' }))
cookies() {
return null;
}
@Get('/cookie-error')
cookieError() {
throw new HttpError(401, 'nope', undefined, { 'set-cookie': ['a=1; Path=/', 'b=2; Path=/'] });
}
@Get('/cookie')
readCookie(@cookie('b') b: string | undefined) {
return { b: b ?? null };
}
// #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.
@@ -70,6 +87,8 @@ const handlers: Record<string, ReturnType<typeof edgeHandler>> = {
trusted: edgeHandler(trusted),
// CARD-17 T10: health probes, reached through the `health` host. Never booted by anything but probes.
health: edgeHandler(createApp({ modules: [M], health: true })),
// CARD-15 (#114): the same graph with handler ETags on, reached through the `etag` host.
etag: edgeHandler(createApp({ modules: [M], etag: true })),
};
// CARD-21 (D17): a route on the reserved mesh path must fail createApp inside workerd too. Built per
+273
View File
@@ -0,0 +1,273 @@
// CARD-15 (#114): weak ETags and conditional GET for static files (always, D12) and buffered handler
// responses (`createApp({ etag: true })`). Deno, Bun and edge repeat T1/T5 in their own suites.
import 'reflect-metadata';
import fs, { mkdtempSync, writeFileSync, utimesSync } from 'node:fs';
import http from 'node:http';
import type { AddressInfo } from 'node:net';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { describe, expect, it, vi, afterEach } from 'vitest';
import { createApp, Route, Get, Post, Sse, Module, Transformer, NotModified } from '../src/index';
import { ifNoneMatchMatches, bodyEtag, notModifiedSince } from '../src/http/conditional';
const root = mkdtempSync(join(tmpdir(), 'gt-etag-'));
const file = join(root, 'a.txt');
writeFileSync(file, 'hello static');
const mtime = new Date(Date.UTC(2026, 0, 2, 3, 4, 5));
utimesSync(file, mtime, mtime);
@Route('/h')
class Handlers {
@Get('/json')
json() {
return { n: 1 };
}
@Get('/own')
@Transformer(() => ({ headers: { 'content-type': 'text/plain', ETag: '"v7"' }, body: 'v7' }))
own() {
return null;
}
@Post('/post')
post() {
return { n: 1 };
}
@Sse('/sse')
sse() {
return (async function* () {
yield 'x';
})();
}
@Get('/skip')
skip() {
throw new NotModified();
}
}
@Module({ mountpoint: '/', controllers: [Handlers] })
class M {}
const staticApp = createApp({ modules: [], static: root });
const etagApp = createApp({ modules: [M], etag: true });
const plainApp = createApp({ modules: [M] });
const req = (app: typeof staticApp, path: string, init: RequestInit = {}) =>
app.fetch(new Request(`http://x${path}`, init));
afterEach(() => vi.restoreAllMocks());
describe('comparison (RFC 9110 §13.1.2)', () => {
it('is weak, splits lists outside quotes, and honours *', () => {
expect(ifNoneMatchMatches('W/"v7"', '"v7"')).toBe(true);
expect(ifNoneMatchMatches('"v7"', 'W/"v7"')).toBe(true);
expect(ifNoneMatchMatches('"a", W/"b", "c"', 'W/"b"')).toBe(true);
expect(ifNoneMatchMatches('"a,b"', '"b"')).toBe(false);
expect(ifNoneMatchMatches('"x", "a,b"', '"a,b"')).toBe(true);
expect(ifNoneMatchMatches('*', '"anything"')).toBe(true);
expect(ifNoneMatchMatches('"nope"', '"v7"')).toBe(false);
});
it('If-Modified-Since compares at one-second resolution and ignores a bad date', () => {
expect(notModifiedSince(new Date(1000).toUTCString(), 1400)).toBe(true);
expect(notModifiedSince(new Date(1000).toUTCString(), 2000)).toBe(false);
expect(notModifiedSince('not a date', 0)).toBe(false);
});
it('a body tag is weak, deterministic and length-prefixed', () => {
expect(bodyEtag('abc')).toBe(bodyEtag(Buffer.from('abc')));
expect(bodyEtag('abc')).toMatch(/^W\/"3-[0-9a-z]+"$/);
expect(bodyEtag('abc')).not.toBe(bodyEtag('abd'));
expect(bodyEtag('é')).toMatch(/^W\/"2-/); // UTF-8 bytes, not UTF-16 units
});
});
describe('static (D12: always on)', () => {
it('T1: 200 with ETag + Last-Modified + no-cache, then 304 without reading the file', async () => {
const readFile = vi.spyOn(fs.promises, 'readFile');
const first = await req(staticApp, '/a.txt');
expect(first.status).toBe(200);
expect(await first.text()).toBe('hello static');
const etag = first.headers.get('etag')!;
expect(etag).toMatch(/^W\/"12-[0-9a-z]+"$/);
expect(first.headers.get('last-modified')).toBe(mtime.toUTCString());
expect(first.headers.get('cache-control')).toBe('no-cache');
const second = await req(staticApp, '/a.txt', { headers: { 'if-none-match': etag } });
expect(second.status).toBe(304);
expect(await second.text()).toBe('');
expect(second.headers.get('etag')).toBe(etag);
expect(second.headers.get('cache-control')).toBe('no-cache');
expect(second.headers.get('last-modified')).toBe(mtime.toUTCString());
expect(second.headers.get('content-type')).toBeNull();
expect(second.headers.get('x-content-type-options')).toBe('nosniff');
expect(readFile).toHaveBeenCalledTimes(1);
});
it('T2: If-Modified-Since at or after mtime, no If-None-Match → 304', async () => {
const res = await req(staticApp, '/a.txt', { headers: { 'if-modified-since': mtime.toUTCString() } });
expect(res.status).toBe(304);
const older = await req(staticApp, '/a.txt', {
headers: { 'if-modified-since': new Date(mtime.getTime() - 5000).toUTCString() },
});
expect(older.status).toBe(200);
});
it('T3: If-None-Match wins over a matching If-Modified-Since', async () => {
const res = await req(staticApp, '/a.txt', {
headers: { 'if-none-match': '"other"', 'if-modified-since': mtime.toUTCString() },
});
expect(res.status).toBe(200);
});
it('T4: a touched file gets a new ETag and a 200', async () => {
const touched = join(root, 'b.txt');
writeFileSync(touched, 'b');
utimesSync(touched, mtime, mtime);
const before = (await req(staticApp, '/b.txt')).headers.get('etag')!;
const later = new Date(mtime.getTime() + 60_000);
utimesSync(touched, later, later);
const res = await req(staticApp, '/b.txt', { headers: { 'if-none-match': before } });
expect(res.status).toBe(200);
expect(res.headers.get('etag')).not.toBe(before);
});
it('HEAD with a matching tag is a 304 too, and never reads', async () => {
const etag = (await req(staticApp, '/a.txt')).headers.get('etag')!;
const readFile = vi.spyOn(fs.promises, 'readFile');
const res = await req(staticApp, '/a.txt', { method: 'HEAD', headers: { 'if-none-match': etag } });
expect(res.status).toBe(304);
const head = await req(staticApp, '/a.txt', { method: 'HEAD' });
expect(head.status).toBe(200);
expect(head.headers.get('etag')).toBe(etag);
expect(readFile).not.toHaveBeenCalled();
});
it('static: { dir, cacheControl } replaces no-cache on 200 and 304', async () => {
const app = createApp({ modules: [], static: { dir: root, cacheControl: 'public, max-age=31536000, immutable' } });
const res = await req(app, '/a.txt');
expect(res.headers.get('cache-control')).toBe('public, max-age=31536000, immutable');
const nm = await req(app, '/a.txt', { headers: { 'if-none-match': res.headers.get('etag')! } });
expect(nm.status).toBe(304);
expect(nm.headers.get('cache-control')).toBe('public, max-age=31536000, immutable');
});
it('static object validation throws at createApp', () => {
expect(() => createApp({ modules: [], static: { dir: root, cachecontrol: 'x' } as never })).toThrow(
/unknown key 'cachecontrol'/,
);
expect(() => createApp({ modules: [], static: { cacheControl: 'no-cache\r\nX-Evil: 1' } })).toThrow(/CR or LF/);
expect(() => createApp({ modules: [], static: { cacheControl: 5 as never } })).toThrow(/cacheControl/);
});
});
describe('handlers (etag: true)', () => {
it('T5: a buffered JSON GET twice → 304, empty body, same ETag', async () => {
const first = await req(etagApp, '/h/json');
const etag = first.headers.get('etag')!;
expect(etag).toBe(bodyEtag(JSON.stringify({ n: 1 })));
const second = await req(etagApp, '/h/json', { headers: { 'if-none-match': etag } });
expect(second.status).toBe(304);
expect(await second.text()).toBe('');
expect(second.headers.get('etag')).toBe(etag);
expect(second.headers.get('content-type')).toBeNull();
});
it('T6: a handler-set ETag is kept and drives the comparison', async () => {
const first = await req(etagApp, '/h/own');
expect(first.headers.get('etag')).toBe('"v7"');
const res = await req(etagApp, '/h/own', { headers: { 'if-none-match': 'W/"v7"' } });
expect(res.status).toBe(304);
expect(res.headers.get('etag')).toBe('"v7"');
});
it('T7/T8: a list containing the tag, and *', async () => {
const etag = (await req(etagApp, '/h/json')).headers.get('etag')!;
const list = await req(etagApp, '/h/json', { headers: { 'if-none-match': `"a", ${etag}, "c"` } });
expect(list.status).toBe(304);
const star = await req(etagApp, '/h/json', { headers: { 'if-none-match': '*' } });
expect(star.status).toBe(304);
});
it('T9: POST, SSE and 404 get no ETag and no 304', async () => {
const post = await req(etagApp, '/h/post', { method: 'POST', headers: { 'if-none-match': '*' } });
expect(post.status).toBe(200);
expect(post.headers.get('etag')).toBeNull();
const sse = await req(etagApp, '/h/sse', { headers: { 'if-none-match': '*' } });
expect(sse.status).toBe(200);
expect(sse.headers.get('etag')).toBeNull();
await sse.body?.cancel();
const missing = await req(etagApp, '/h/nope', { headers: { 'if-none-match': '*' } });
expect(missing.status).toBe(404);
expect(missing.headers.get('etag')).toBeNull();
});
it('T10: HEAD with a matching tag → 304; HEAD and GET carry the same tag', async () => {
const etag = (await req(etagApp, '/h/json')).headers.get('etag')!;
const head = await req(etagApp, '/h/json', { method: 'HEAD' });
expect(head.headers.get('etag')).toBe(etag);
const res = await req(etagApp, '/h/json', { method: 'HEAD', headers: { 'if-none-match': etag } });
expect(res.status).toBe(304);
});
it('etag absent: no ETag on a handler response and no 304, even for a handler-set tag', async () => {
const res = await req(plainApp, '/h/json', { headers: { 'if-none-match': '*' } });
expect(res.status).toBe(200);
expect(res.headers.get('etag')).toBeNull();
const own = await req(plainApp, '/h/own', { headers: { 'if-none-match': '"v7"' } });
expect(own.status).toBe(200);
});
it('NotModified still works, and its 304 has no body or content-type', async () => {
for (const app of [plainApp, etagApp]) {
const res = await req(app, '/h/skip');
expect(res.status).toBe(304);
expect(await res.text()).toBe('');
expect(res.headers.get('content-type')).toBeNull();
}
});
it('createApp({ etag }) accepts only a boolean', () => {
expect(() => createApp({ modules: [], etag: 'yes' as never })).toThrow(/etag.*boolean/);
expect(() => createApp({ modules: [], etag: false })).not.toThrow();
});
});
describe('Node adapter (T11)', () => {
const raw = (port: number, path: string, headers: Record<string, string> = {}) =>
new Promise<{ status: number; headers: http.IncomingHttpHeaders; body: string }>((resolve, reject) => {
http
.get({ host: '127.0.0.1', port, path, headers }, (res) => {
let body = '';
res.on('data', (c) => (body += c));
res.on('end', () => resolve({ status: res.statusCode!, headers: res.headers, body }));
})
.on('error', reject);
});
it('T1 and T5 over a real socket: 304s carry the tag and no body', async () => {
const app = createApp({ modules: [M], etag: true, static: root });
const server = await app.listen(0);
const { port } = server.address() as AddressInfo;
try {
const readFile = vi.spyOn(fs.promises, 'readFile');
const s1 = await raw(port, '/a.txt');
const s2 = await raw(port, '/a.txt', { 'if-none-match': String(s1.headers.etag) });
expect([s1.status, s2.status]).toEqual([200, 304]);
expect(s2.body).toBe('');
expect(s2.headers.etag).toBe(s1.headers.etag);
expect(s2.headers['content-type']).toBeUndefined();
expect(readFile).toHaveBeenCalledTimes(1);
const h1 = await raw(port, '/h/json');
const h2 = await raw(port, '/h/json', { 'if-none-match': String(h1.headers.etag) });
expect([h1.status, h2.status]).toEqual([200, 304]);
expect(h2.body).toBe('');
expect(h2.headers['content-length']).toBeUndefined();
} finally {
server.close();
}
});
});
+143
View File
@@ -0,0 +1,143 @@
// CARD-16 (#112, D13): one app shared by the Node, Deno, Bun and edge compression tests, so every
// runtime is checked against the same routes and the same bytes (T12). Lifted from the D13 spike
// (`spike/d13-compression-b`). Import `reflect-metadata` first.
//
// Bodies are deterministic (seeded LCG), identical to the spikes' harness: a 10,205 B JSON and a
// 51,108 B HTML page — the HTML is also the body of the Deno memory check.
import { createApp, Route, Get, Head, Sse, Stream, Module, Transformer, NotModified } from '../../src/index';
function rng(seed: number): () => number {
let s = seed >>> 0;
return () => (s = (s * 1664525 + 1013904223) >>> 0) / 2 ** 32;
}
const WORDS = 'alpha bravo charlie delta echo foxtrot golf hotel india juliet kilo lima mike november oscar papa'.split(' ');
export const JSON_BODY: string = (() => {
const r = rng(42);
const items: unknown[] = [];
let s = '';
for (let i = 0; s.length < 10240; i++) {
items.push({
id: i,
uuid: Array.from({ length: 4 }, () => Math.floor(r() * 2 ** 32).toString(16).padStart(8, '0')).join('-'),
name: `${WORDS[Math.floor(r() * 16)]} ${WORDS[Math.floor(r() * 16)]}`,
price: Math.round(r() * 100000) / 100,
active: r() > 0.5,
tags: [WORDS[Math.floor(r() * 16)], WORDS[Math.floor(r() * 16)]],
});
s = JSON.stringify({ items });
}
return JSON.stringify({ items: items.slice(0, items.length - 1) });
})();
export const HTML_BODY: string = (() => {
const r = rng(7);
const w = () => WORDS[Math.floor(r() * 16)];
let s =
'<!doctype html><html><head><meta charset="utf-8"><title>Spike</title><style>body{font-family:sans-serif}.row{display:flex;gap:8px}</style></head><body><main>';
let i = 0;
while (s.length < 51200 - 200) {
s += `<div class="row" data-id="${i++}"><a href="/item/${Math.floor(r() * 1e6)}">${w()} ${w()}</a><span class="price">${(r() * 1000).toFixed(2)}</span><p>${w()} ${w()} ${w()} ${w()} ${w()} ${w()}.</p></div>\n`;
}
return s + '</main></body></html>';
})();
export const SMALL_BODY = JSON.stringify({ pad: 'x'.repeat(500) }); // 512 B, under the 1024 threshold
export const BIG_BODY = HTML_BODY.repeat(2); // 102 KiB
const PNG = 'P'.repeat(4096);
const TEXT = 'y'.repeat(4096);
const raw = (headers: Record<string, string>, status = 200) => (body: unknown) => ({
status,
headers,
body: body as string,
});
/** How many frames `/c/flood` has produced, across every request. */
export const flood = { produced: 0 };
export const SSE_EVENTS = 5;
export const SSE_GAP_MS = 200;
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
@Route('/c')
class Compressible {
@Get('/json') @Transformer(raw({ 'content-type': 'application/json' })) json() {
return JSON_BODY;
}
@Head('/json') @Transformer(raw({ 'content-type': 'application/json' })) headJson() {
return JSON_BODY;
}
@Get('/html') @Transformer(raw({ 'Content-Type': 'text/html; charset=utf-8' })) html() {
return HTML_BODY;
}
@Get('/big') @Transformer(raw({ 'content-type': 'text/html' })) big() {
return BIG_BODY;
}
@Get('/small') @Transformer(raw({ 'content-type': 'application/json' })) small() {
return SMALL_BODY;
}
@Get('/png') @Transformer(raw({ 'content-type': 'image/png' })) png() {
return PNG;
}
@Get('/notype') @Transformer(raw({})) notype() {
return TEXT;
}
@Get('/pre') @Transformer(raw({ 'content-type': 'text/plain', 'content-encoding': 'gzip' })) pre() {
return TEXT; // not really gzip: core must leave it byte-for-byte alone
}
@Get('/range')
@Transformer(raw({ 'content-type': 'text/plain', 'content-range': 'bytes 0-4095/8192' }, 206))
range() {
return TEXT;
}
@Get('/notransform') @Transformer(raw({ 'content-type': 'text/plain', 'cache-control': 'no-transform' })) nt() {
return TEXT;
}
@Get('/vary') @Transformer(raw({ 'content-type': 'text/plain', vary: 'Origin' })) vary() {
return TEXT;
}
@Get('/empty') @Transformer(raw({ 'content-type': 'text/plain' }, 204)) empty() {
return '';
}
@Get('/etag') @Transformer(raw({ 'content-type': 'application/json', etag: '"v1"' })) etag() {
return JSON_BODY;
}
@Get('/304') notModified() {
throw new NotModified();
}
@Sse('/sse') async *sse() {
for (let n = 0; n < SSE_EVENTS; n++) {
if (n) await sleep(SSE_GAP_MS);
yield { n, t: Date.now() };
}
}
@Stream('/ndjson') async *ndjson() {
for (let n = 0; n < 3; n++) yield { n };
}
@Get('/plainjson') plainJson() {
return JSON.parse(JSON_BODY); // through the default JsonTransformer, for the ETag interplay (T10)
}
/** Large, poorly compressible frames as fast as they are pulled: the slow-client backpressure case. */
@Stream('/flood') async *flood() {
const r = rng(9);
for (;;) {
flood.produced++;
yield { pad: Array.from({ length: 4096 }, () => Math.floor(r() * 2 ** 32).toString(36)).join('') };
}
}
/** Never ends on its own: the client-disconnect case. */
@Sse('/forever') async *forever() {
for (let n = 0; ; n++) {
yield { n, pad: 'z'.repeat(256) };
await sleep(5);
}
}
}
@Module({ mountpoint: '/', controllers: [Compressible] })
class CompressionModule {}
/** The fixture app; `opts` is spread into `createApp` (`compression`, `etag`, …). */
export const compressionApp = (opts: Omit<Parameters<typeof createApp>[0], 'modules'> = {}) =>
createApp({ modules: [CompressionModule], ...opts });
+160
View File
@@ -0,0 +1,160 @@
// CARD-16 (#112): the server-runtime checks shared by test/deno/compression.test.ts and
// test/bun/compression.test.ts, run against `compressionApp({ compression: true, etag: true })`
// served by the runtime's own server. Each check throws on failure. Reads go through `node:http`,
// which decodes nothing, so a double encoding cannot hide.
import http from 'node:http';
import zlib from 'node:zlib';
import { JSON_BODY, HTML_BODY, SSE_EVENTS, SSE_GAP_MS } from './compression-app';
interface Raw {
status: number;
headers: http.IncomingHttpHeaders;
bytes: Uint8Array;
}
function get(port: number, path: string, headers: Record<string, string> = {}, method = 'GET'): Promise<Raw> {
return new Promise((resolve, reject) => {
const req = http.request({ host: '127.0.0.1', port, path, method, headers }, (res) => {
const chunks: Uint8Array[] = [];
res.on('data', (c: Uint8Array) => chunks.push(c));
res.on('end', () => resolve({ status: res.statusCode!, headers: res.headers, bytes: Buffer.concat(chunks) }));
});
req.on('error', reject);
req.end();
});
}
const decode = (bytes: Uint8Array, ce: unknown): string =>
new TextDecoder().decode(
ce === 'br' ? zlib.brotliDecompressSync(bytes) : ce === 'gzip' ? zlib.gunzipSync(bytes) : bytes,
);
function check(cond: unknown, message: string): void {
if (!cond) throw new Error(message);
}
const hasVary = (r: Raw) => /accept-encoding/i.test(String(r.headers.vary ?? ''));
/** T1–T6 and T12: negotiation, one layer, original bytes. */
async function negotiation(port: number): Promise<void> {
const cases: [string, string | undefined, string | undefined, string][] = [
['/c/json', 'gzip, br', 'br', JSON_BODY], // T1
['/c/json', 'br;q=0, gzip', 'gzip', JSON_BODY], // T2
['/c/json', 'identity', undefined, JSON_BODY], // T3
['/c/json', undefined, undefined, JSON_BODY], // T3
['/c/json', '*;q=0', undefined, JSON_BODY], // T4
['/c/json', '*', 'br', JSON_BODY], // T5
['/c/html', 'gzip', 'gzip', HTML_BODY], // T12
['/c/html', 'br', 'br', HTML_BODY],
];
for (const [path, ae, ce, original] of cases) {
const r = await get(port, path, ae === undefined ? {} : { 'accept-encoding': ae });
const label = `${path} ${ae ?? '(none)'}`;
check(r.headers['content-encoding'] === ce, `${label}: content-encoding ${String(r.headers['content-encoding'])}, expected ${ce}`);
check(hasVary(r), `${label}: no Vary`);
check(decode(r.bytes, ce) === original, `${label}: body does not decode to the original bytes`);
}
}
/** T7, T8, T11, T15: skips, and the 304 shape. */
async function skips(port: number): Promise<void> {
for (const [path, vary] of [
['/c/small', true],
['/c/png', false],
['/c/notype', false],
['/c/range', false],
['/c/notransform', false],
] as const) {
const r = await get(port, path, { 'accept-encoding': 'gzip, br' });
check(r.headers['content-encoding'] === undefined, `${path}: encoded`);
check(hasVary(r) === vary, `${path}: Vary ${String(r.headers.vary)}`);
}
const head = await get(port, '/c/json', { 'accept-encoding': 'gzip' }, 'HEAD');
check(head.headers['content-encoding'] === undefined && hasVary(head), 'HEAD: encoded or no Vary');
const nm = await get(port, '/c/304', { 'accept-encoding': 'gzip' });
check(nm.status === 304 && hasVary(nm) && nm.headers['content-type'] === undefined, 'T15: 304 shape');
}
/** T10: the ETag does not change with the coding, and its 304 carries Vary. */
async function etag(port: number): Promise<void> {
const identity = await get(port, '/c/plainjson', { 'accept-encoding': 'identity' });
const gz = await get(port, '/c/plainjson', { 'accept-encoding': 'gzip' });
check(gz.headers['content-encoding'] === 'gzip', 'T10: not gzip');
check(gz.headers.etag !== undefined && gz.headers.etag === identity.headers.etag, 'T10: ETag differs by coding');
const nm = await get(port, '/c/plainjson', { 'accept-encoding': 'gzip', 'if-none-match': String(gz.headers.etag) });
check(nm.status === 304 && hasVary(nm) && nm.bytes.length === 0, 'T10: 304 without Vary or with a body');
}
/** T14: ndjson decodes to the same lines. */
async function ndjson(port: number): Promise<void> {
for (const ce of ['gzip', 'br']) {
const r = await get(port, '/c/ndjson', { 'accept-encoding': ce });
check(r.headers['content-encoding'] === ce, `T14 ${ce}: not encoded`);
check(decode(r.bytes, ce) === '{"n":0}\n{"n":1}\n{"n":2}\n', `T14 ${ce}: lines differ`);
}
}
/** T9: each SSE event decodes before the next one is produced. Returns the per-event lags. */
async function sse(port: number): Promise<Record<string, number[]>> {
const out: Record<string, number[]> = {};
for (const ce of ['gzip', 'br']) {
out[ce] = await new Promise<number[]>((resolve, reject) => {
http
.get({ host: '127.0.0.1', port, path: '/c/sse', headers: { 'accept-encoding': ce, accept: 'text/event-stream' } }, (res) => {
if (res.headers['content-encoding'] !== ce) reject(new Error(`T9 ${ce}: not encoded`));
const dec = ce === 'br' ? zlib.createBrotliDecompress() : zlib.createGunzip();
const lags: number[] = [];
let buf = '';
dec.on('data', (d: Uint8Array) => {
buf += new TextDecoder().decode(d);
let i;
while ((i = buf.indexOf('\n\n')) >= 0) {
const m = buf.slice(0, i).match(/data: (\{.*\})/);
buf = buf.slice(i + 2);
if (m) lags.push(Date.now() - JSON.parse(m[1]).t);
}
});
res.pipe(dec);
dec.on('end', () => resolve(lags));
dec.on('error', reject);
})
.on('error', reject);
});
check(out[ce].length === SSE_EVENTS, `T9 ${ce}: ${out[ce].length} events`);
for (const lag of out[ce]) check(lag < SSE_GAP_MS / 2, `T9 ${ce}: event lag ${lag} ms`);
}
return out;
}
export const checks = { negotiation, skips, etag, ndjson, sse };
/**
* How many 1 ms timer ticks fire while `zlib.gzip` (the async API core uses) compresses 16 MB of
* random bytes — incompressible, so the work takes a few hundred ms on any machine (repetitive
* input finished in 4 ms on a CI runner and proved nothing). When the runtime offloads zlib to a
* worker thread the loop keeps ticking, roughly one tick per ms; when it runs it on the main thread
* (Deno 2.9.7, SPIKE-COMPRESSION-B §7) almost none fire. The runtime docs state which one each
* runtime does, and the suites pin it with this.
*/
export async function ticksDuringGzip(): Promise<{ ms: number; ticks: number }> {
const bytes = new Uint8Array(16 * 1024 * 1024);
for (let i = 0; i < bytes.length; i += 65536) crypto.getRandomValues(bytes.subarray(i, i + 65536));
let ticks = 0;
const timer = setInterval(() => ticks++, 1);
const started = performance.now();
await new Promise<void>((resolve, reject) => zlib.gzip(bytes, (err) => (err ? reject(err) : resolve())));
const ms = performance.now() - started;
clearInterval(timer);
return { ms, ticks };
}
/** Compression off: the runtime's server sends identity even to a gzip client (it does not compress by itself). */
export async function serverDoesNotCompress(port: number): Promise<void> {
const r = await get(port, '/c/html', { 'accept-encoding': 'gzip, br' });
check(r.headers['content-encoding'] === undefined, `the server encoded by itself: ${String(r.headers['content-encoding'])}`);
check(decode(r.bytes, undefined) === HTML_BODY, 'body changed');
}
+28
View File
@@ -0,0 +1,28 @@
// CARD-14 (#113): one graph for the Deno and Bun cookie suites, so both prove the same thing the
// Node suite (test/cookies.test.ts) does — two cookies on one response arrive as two lines.
import { Route, Get, Module, Transformer, HttpError, cookie, setCookie } from '../../src/index';
export const C1 = setCookie('a', '1');
export const C2 = setCookie('b', '2', { maxAge: 60 });
@Route('/c')
class CookieCtl {
@Get('/one')
one(@cookie('a') a: string | undefined, @cookie('b') b: string | undefined) {
return { a: a ?? null, b: b ?? null };
}
@Get('/two')
@Transformer(() => ({ headers: { 'set-cookie': [C1, C2], 'x-custom': ['a', 'b'] }, body: '{}' }))
two() {
return null;
}
@Get('/error')
error() {
throw new HttpError(401, 'nope', undefined, { 'set-cookie': [C1, C2] });
}
}
@Module({ mountpoint: '/', controllers: [CookieCtl] })
export class CookieModule {}
+17
View File
@@ -0,0 +1,17 @@
// CARD-15 (#114): one graph for the Deno, Bun and edge ETag checks (T11), so each runtime answers
// the same T1/T5 the Node suite (test/etag.test.ts) does.
import { Route, Get, Module } from '../../src/index';
@Route('/h')
class EtagCtl {
@Get('/json')
json() {
return { n: 1 };
}
}
@Module({ mountpoint: '/', controllers: [EtagCtl] })
export class EtagModule {}
/** A committed file the static checks can serve: `asset.txt` under `test/fixtures/views`. */
export const STATIC_DIR = 'test/fixtures/views';
+25 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
import { mergeInjectedHeaders } from '../src/http/headers';
import { mergeInjectedHeaders, joinListHeaders, toWebHeaders } from '../src/http/headers';
describe('mergeInjectedHeaders', () => {
it('makes injected keys authoritative regardless of handler casing', () => {
@@ -23,3 +23,27 @@ describe('mergeInjectedHeaders', () => {
expect(out['vary']).toBe('Accept');
});
});
describe('array header values (D11)', () => {
it('keeps a handler array intact and still merges vary', () => {
const cookies = ['a=1', 'b=2'];
const out = mergeInjectedHeaders({ 'set-cookie': cookies, Vary: ['Accept', 'Accept-Language'] }, { vary: 'Origin' });
expect(out['set-cookie']).toEqual(['a=1', 'b=2']);
expect(out['vary']).toBe('Accept, Accept-Language, Origin');
});
it('joinListHeaders joins every array but set-cookie, and returns the input when there is none', () => {
const plain = { a: '1' };
expect(joinListHeaders(plain)).toBe(plain);
expect(joinListHeaders({ 'Set-Cookie': ['a=1', 'b=2'], 'x-list': ['a', 'b'] })).toEqual({
'Set-Cookie': ['a=1', 'b=2'],
'x-list': 'a, b',
});
});
it('toWebHeaders appends one set-cookie per element', () => {
const h = toWebHeaders({ 'set-cookie': ['a=1; Expires=Tue, 01 Jan 2030 00:00:00 GMT', 'b=2'], 'x-list': ['a', 'b'] });
expect(h.getSetCookie()).toEqual(['a=1; Expires=Tue, 01 Jan 2030 00:00:00 GMT', 'b=2']);
expect(h.get('x-list')).toBe('a, b');
});
});
+81 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect, vi } from 'vitest';
import { createApp, Step, Route, Get, Module, needs } from '../../src/index';
import { createApp, Step, Route, Get, Module, Transformer, needs } from '../../src/index';
const SECRET = 's3cr3t';
@@ -281,3 +281,83 @@ describe('mesh skeleton integration', () => {
tServer.close();
});
});
describe('mesh: Set-Cookie arrays (CARD-14, T10)', () => {
it('a remote route that returns two cookies reaches the teacup client as two lines', async () => {
@Route('/jar')
class JarCtl {
@Get('/two', { export: true })
@Transformer(() => ({ headers: { 'set-cookie': ['a=1; Path=/', 'b=2; Path=/'] }, body: '{}' }))
two() {
return null;
}
}
@Module({ mountpoint: '/api', controllers: [JarCtl] })
class JarTeapotModule {}
const teapot = createApp({ modules: [JarTeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const url = `ws://127.0.0.1:${(tServer.address() as any).port}/__mesh__/control`;
const teacup = createApp({ modules: [PlainTeacupModule], experimental: true, mesh: { teapots: [{ url, secret: SECRET }] } });
const cServer = await teacup.listen(0);
try {
const res = await fetch(`http://127.0.0.1:${(cServer.address() as any).port}/api/jar/two`);
expect(res.status).toBe(200);
expect(res.headers.getSetCookie()).toEqual(['a=1; Path=/', 'b=2; Path=/']);
} finally {
tServer.close();
cServer.close();
}
});
});
describe('mesh: compression of remote routes (CARD-16)', () => {
it('a remote buffered response is compressed by the teacup like a local one', async () => {
const { gunzipSync } = await import('node:zlib');
const http = await import('node:http');
const payload = { rows: Array.from({ length: 200 }, (_, i) => ({ i, name: `row ${i}` })) };
@Route('/big')
class BigCtl {
@Get('/json', { export: true })
json() {
return payload;
}
}
@Module({ mountpoint: '/api', controllers: [BigCtl] })
class BigTeapotModule {}
const teapot = createApp({ modules: [BigTeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const url = `ws://127.0.0.1:${(tServer.address() as any).port}/__mesh__/control`;
const teacup = createApp({
modules: [PlainTeacupModule],
experimental: true,
compression: true,
mesh: { teapots: [{ url, secret: SECRET }] },
});
const cServer = await teacup.listen(0);
try {
const raw = await new Promise<{ headers: Record<string, unknown>; bytes: Buffer }>((resolve, reject) => {
http
.get(
{ port: (cServer.address() as any).port, path: '/api/big/json', headers: { 'accept-encoding': 'gzip' } },
(res) => {
const chunks: Buffer[] = [];
res.on('data', (c) => chunks.push(c));
res.on('end', () => resolve({ headers: res.headers, bytes: Buffer.concat(chunks) }));
},
)
.on('error', reject);
});
expect(raw.headers['content-encoding']).toBe('gzip');
expect(String(raw.headers.vary)).toMatch(/Accept-Encoding/);
expect(JSON.parse(gunzipSync(raw.bytes).toString())).toEqual(payload);
} finally {
tServer.close();
cServer.close();
}
});
});
+438
View File
@@ -0,0 +1,438 @@
/**
* CARD-19 (#124, D15): a teacup's remote routes follow which teapots are connected.
*
* Late teapot → its routes are added. Reconnecting → they stay and answer 503 with `retry-after`.
* Gone for good → they are removed (404, `Allow` without them). A returning manifest adds and drops
* routes. A late route that conflicts is refused and logged. Every change emits `mesh:routes`, and
* none rebuilds the local route tree.
*/
import 'reflect-metadata';
import http from 'http';
import net from 'net';
import type { AddressInfo } from 'net';
import { describe, it, expect, afterEach } from 'vitest';
import { WebSocketServer } from 'ws';
import { encode, decode, MESH_PROTOCOL_VERSION, type RouteEntry } from '../../src/mesh/protocol';
import { createApp, Route, Get, Module } from '../../src/index';
import { routerSeamCounts } from '../../src/http/router';
import type { App, MeshConfig } from '../../src/app/types';
import type { EventPayload } from '../../src/bus';
const SECRET = 'membership-secret';
@Route('/remote')
class PingCtl {
@Get('/ping', { export: true }) ping() {
return { from: 'teapot' };
}
}
@Module({ mountpoint: '/api', controllers: [PingCtl] })
class PingTeapot {}
@Route('/remote')
class PingExtraCtl {
@Get('/ping', { export: true }) ping() {
return { from: 'teapot v2' };
}
@Get('/extra', { export: true }) extra() {
return { extra: true };
}
}
@Module({ mountpoint: '/api', controllers: [PingExtraCtl] })
class PingExtraTeapot {}
@Route('/remote')
class ExtraOnlyCtl {
@Get('/extra', { export: true }) extra() {
return { extra: true };
}
}
@Module({ mountpoint: '/api', controllers: [ExtraOnlyCtl] })
class ExtraOnlyTeapot {}
@Route('/shape')
class ShapeIdCtl {
@Get('/:id', { export: true }) get() {
return { from: 'id' };
}
}
@Module({ mountpoint: '/api', controllers: [ShapeIdCtl] })
class ShapeIdTeapot {}
@Route('/')
class ShapeNameCtl {
@Get('/shape/:name', { export: true }) get() {
return { from: 'name' };
}
@Get('/other', { export: true }) other() {
return { from: 'other' };
}
}
@Module({ mountpoint: '/api', controllers: [ShapeNameCtl] })
class ShapeNameTeapot {}
@Route('/local')
class LocalCtl {
@Get('/ok') ok() {
return { from: 'teacup' };
}
}
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {}
const FAST = { initialDelayMs: 20, maxDelayMs: 60 };
/** A port nothing listens 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;
}
const controlUrl = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`;
const open: App[] = [];
afterEach(async () => {
while (open.length) await open.pop()!.close();
});
async function teapotOn(port: number, module: new () => unknown): Promise<App> {
const teapot = createApp({ modules: [module], experimental: true, mesh: { secret: SECRET } });
await teapot.listen(port);
open.push(teapot);
return teapot;
}
async function stop(teapot: App): Promise<void> {
await teapot.close();
open.splice(open.indexOf(teapot), 1);
}
interface Teacup {
app: App;
warnings: string[];
events: EventPayload[];
/** Resolves on the next `name` event. */
next: (name: 'mesh:routes' | 'mesh:disconnect') => Promise<EventPayload>;
}
function teacup(ports: number[], mesh: Partial<MeshConfig> = {}, extra: { health?: boolean } = {}): Teacup {
const warnings: string[] = [];
const events: EventPayload[] = [];
const waiting = new Map<string, Array<(e: EventPayload) => void>>();
const app = createApp({
modules: [TeacupModule],
experimental: true,
...extra,
logger: { debug() {}, info() {}, warn: (m: string) => warnings.push(m), error: (m: string) => warnings.push(m) },
mesh: {
teapots: ports.map((port) => ({ url: controlUrl(port), secret: SECRET })),
bootTimeoutMs: 100,
timeoutMs: 1000,
heartbeatMs: 1000,
reconnect: FAST,
...mesh,
},
});
for (const name of ['mesh:routes', 'mesh:disconnect'] as const) {
app.bus.on(name, (payload) => {
if (name === 'mesh:routes') events.push(payload);
const list = waiting.get(name) ?? [];
waiting.delete(name);
for (const resolve of list) resolve(payload);
});
}
open.unshift(app); // closed before the teapots
const next = (name: string) =>
new Promise<EventPayload>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error(`no ${name} within 5s`)), 5000);
waiting.set(name, [
...(waiting.get(name) ?? []),
(e) => {
clearTimeout(timer);
resolve(e);
},
]);
});
return { app, warnings, events, next };
}
const get = (app: App, path: string, method = 'GET') => app.fetch(new Request(`http://mesh.test${path}`, { method }));
function nodeGet(port: number, path: string) {
return new Promise<{ status: number; body: string }>((resolve, reject) => {
const req = http.request({ host: '127.0.0.1', port, method: 'GET', path, agent: false }, (res) => {
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk) => (body += chunk));
res.on('end', () => resolve({ status: res.statusCode ?? 0, body }));
});
req.on('error', reject);
req.end();
});
}
/**
* A teapot speaking the wire protocol directly, so its manifest can carry what a real teapot's own
* boot refuses — an older or foreign peer advertising a reserved path. Every RPC answers `answer`.
*/
async function rawTeapotOn(
port: number,
routes: RouteEntry[],
answer: unknown,
): Promise<{ close: () => Promise<void> }> {
const wss = new WebSocketServer({ port, host: '127.0.0.1' });
wss.on('connection', (ws) => {
ws.on('message', (data) => {
const frame = decode(data.toString());
if (frame.type === 'hello') ws.send(encode({ type: 'manifest', v: MESH_PROTOCOL_VERSION, steps: [], routes }));
else if (frame.type === 'ping') ws.send(encode({ type: 'pong' }));
else if (frame.type === 'rpc-req')
ws.send(
encode({
type: 'rpc-res',
id: frame.id,
ok: true,
result: { status: 200, headers: { 'content-type': 'application/json' }, body: JSON.stringify(answer) },
}),
);
});
});
await new Promise((resolve) => wss.on('listening', resolve));
return {
close: () =>
new Promise<void>((done) => {
for (const client of wss.clients) client.terminate();
wss.close(() => done());
}),
};
}
describe('mesh: remote routes follow teapot membership (CARD-19, D15)', () => {
it('T1: a teapot absent at boot is served once it connects, on app.fetch and listen(), without rebuilding the local tree', async () => {
const port = await freePort();
const cup = teacup([port]);
const listenPort = ((await cup.app.listen(0)).address() as AddressInfo).port;
expect((await get(cup.app, '/api/remote/ping')).status).toBe(404);
expect((await get(cup.app, '/api/local/ok')).status).toBe(200);
const before = routerSeamCounts();
const routed = cup.next('mesh:routes');
await teapotOn(port, PingTeapot);
expect(await routed).toEqual({
name: controlUrl(port),
url: controlUrl(port),
added: ['GET /api/remote/ping'],
removed: [],
});
const res = await get(cup.app, '/api/remote/ping');
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ from: 'teapot' });
expect(await nodeGet(listenPort, '/api/remote/ping')).toEqual({ status: 200, body: '{"from":"teapot"}' });
expect((await get(cup.app, '/api/local/ok')).status).toBe(200);
const after = routerSeamCounts();
expect(after.indexBuilds).toBeGreaterThan(before.indexBuilds); // the remote trees were rebuilt
expect(after.localTreeBuilds).toBe(before.localTreeBuilds); // the local ones were not
});
it('T2/T3: a reconnecting teapot keeps its routes with 503 + retry-after, then serves again', async () => {
const port = await freePort();
let teapot = await teapotOn(port, PingTeapot);
const cup = teacup([port]);
expect((await get(cup.app, '/api/remote/ping')).status).toBe(200);
const dropped = cup.next('mesh:disconnect');
await stop(teapot);
await dropped;
const down = await get(cup.app, '/api/remote/ping');
expect(down.status).toBe(503);
expect(Number(down.headers.get('retry-after'))).toBeGreaterThanOrEqual(1);
expect((await get(cup.app, '/api/remote/ping', 'OPTIONS')).headers.get('allow')).toBe('GET, HEAD, OPTIONS');
expect((await get(cup.app, '/api/remote/ping', 'POST')).headers.get('allow')).toBe('GET, HEAD, OPTIONS');
teapot = await teapotOn(port, PingTeapot);
await expect.poll(async () => (await get(cup.app, '/api/remote/ping')).status, { timeout: 5000 }).toBe(200);
// Same routes back: nothing changed in the table, so no event.
expect(cup.events).toEqual([]);
});
it('T4: with reconnect: false a dropped teapot is gone — 404, Allow without its methods, local routes unaffected', async () => {
const port = await freePort();
const teapot = await teapotOn(port, PingTeapot);
const cup = teacup([port], { reconnect: false });
expect((await get(cup.app, '/api/remote/ping')).status).toBe(200);
const routed = cup.next('mesh:routes');
await stop(teapot);
expect(await routed).toMatchObject({ added: [], removed: ['GET /api/remote/ping'] });
const gone = await get(cup.app, '/api/remote/ping');
expect(gone.status).toBe(404);
expect(gone.headers.get('retry-after')).toBeNull();
const options = await get(cup.app, '/api/remote/ping', 'OPTIONS');
expect(options.status).toBe(404);
expect(options.headers.get('allow')).toBeNull();
expect((await get(cup.app, '/api/local/ok')).status).toBe(200);
expect(cup.warnings.some((w) => w.includes('gone for good'))).toBe(true);
});
it('T5: a teapot that returns with an extra route has it served', async () => {
const port = await freePort();
const teapot = await teapotOn(port, PingTeapot);
const cup = teacup([port]);
expect((await get(cup.app, '/api/remote/extra')).status).toBe(404);
const dropped = cup.next('mesh:disconnect');
await stop(teapot);
await dropped;
const routed = cup.next('mesh:routes');
await teapotOn(port, PingExtraTeapot);
expect(await routed).toMatchObject({ added: ['GET /api/remote/extra'], removed: [] });
expect((await get(cup.app, '/api/remote/extra')).status).toBe(200);
expect(await (await get(cup.app, '/api/remote/ping')).json()).toEqual({ from: 'teapot v2' });
});
it('T6: a teapot that returns without a route has it removed', async () => {
const port = await freePort();
const teapot = await teapotOn(port, PingTeapot);
const cup = teacup([port]);
expect((await get(cup.app, '/api/remote/ping')).status).toBe(200);
const dropped = cup.next('mesh:disconnect');
await stop(teapot);
await dropped;
const routed = cup.next('mesh:routes');
await teapotOn(port, ExtraOnlyTeapot);
expect(await routed).toMatchObject({ added: ['GET /api/remote/extra'], removed: ['GET /api/remote/ping'] });
expect((await get(cup.app, '/api/remote/ping')).status).toBe(404);
expect((await get(cup.app, '/api/remote/extra')).status).toBe(200);
});
it('T7: a late route ambiguous with another teapot’s is refused and logged; everything else serves', async () => {
const [portA, portB] = [await freePort(), await freePort()];
await teapotOn(portA, ShapeIdTeapot);
const cup = teacup([portA, portB]);
expect(await (await get(cup.app, '/api/shape/1')).json()).toEqual({ from: 'id' });
const routed = cup.next('mesh:routes');
await teapotOn(portB, ShapeNameTeapot);
expect(await routed).toMatchObject({ url: controlUrl(portB), added: ['GET /api/other'], removed: [] });
expect(await (await get(cup.app, '/api/shape/1')).json()).toEqual({ from: 'id' });
expect((await get(cup.app, '/api/other')).status).toBe(200);
expect(
cup.warnings.some((w) => w.includes('not serving a route from') && w.includes("'GET /api/shape/:name'")),
).toBe(true);
});
it('T8: 1 000 requests across a late connect each see the old table or the new one', async () => {
const port = await freePort();
const cup = teacup([port]);
expect((await get(cup.app, '/api/remote/ping')).status).toBe(404);
const routed = cup.next('mesh:routes');
const starting = teapotOn(port, PingTeapot);
const statuses: number[] = [];
let changed = false;
void routed.then(() => (changed = true));
// 100 waves of 10 concurrent requests, spread across the moment the table changes. Ten at a time,
// not more: past 16 RPCs in flight on one link the teapot's control channel hits the WebSocket
// inbound-queue bound (#107) and drops the link. That is pre-existing and not about membership.
for (let wave = 0; wave < 100; wave++) {
const batch = await Promise.all(
Array.from({ length: 10 }, () => get(cup.app, '/api/remote/ping').then((res) => res.status)),
);
statuses.push(...batch);
if (!changed) await new Promise((resolve) => setTimeout(resolve, 2));
}
await starting;
await routed;
expect(statuses).toHaveLength(1000);
expect(statuses.every((status) => status === 404 || status === 200)).toBe(true);
// Both tables were actually seen, so the change happened while requests were flowing.
expect(statuses).toContain(404);
expect(statuses).toContain(200);
expect((await get(cup.app, '/api/remote/ping')).status).toBe(200);
});
it('with reconnect: false a teapot absent at boot is not retried (no backoff to retry with)', async () => {
const port = await freePort();
const cup = teacup([port], { reconnect: false });
expect((await get(cup.app, '/api/remote/ping')).status).toBe(404);
await teapotOn(port, PingTeapot);
await new Promise((resolve) => setTimeout(resolve, 300));
expect((await get(cup.app, '/api/remote/ping')).status).toBe(404);
expect(cup.events).toEqual([]);
});
it('a late teapot advertising /__mesh__/control has that route refused; its other routes are served', async () => {
const port = await freePort();
const cup = teacup([port]);
expect((await get(cup.app, '/api/fake/ok')).status).toBe(404);
const routed = cup.next('mesh:routes');
const raw = await rawTeapotOn(
port,
[
{ method: 'GET', pattern: '/__mesh__/control' },
{ method: 'GET', pattern: '/api/fake/ok' },
],
{ from: 'raw teapot' },
);
try {
expect(await routed).toMatchObject({ added: ['GET /api/fake/ok'], removed: [] });
expect(await (await get(cup.app, '/api/fake/ok')).json()).toEqual({ from: 'raw teapot' });
expect(await (await get(cup.app, '/__mesh__/control')).text()).not.toContain('raw teapot');
expect(
cup.warnings.some((w) => w.includes('not serving a route from') && w.includes("'GET /__mesh__/control'")),
).toBe(true);
} finally {
await cup.app.close();
open.splice(open.indexOf(cup.app), 1);
await raw.close();
}
});
it('with health on, a late teapot advertising /__ready__ has that route refused; its other routes are served', async () => {
const port = await freePort();
const cup = teacup([port], {}, { health: true });
expect((await get(cup.app, '/api/fake/ok')).status).toBe(404);
const routed = cup.next('mesh:routes');
const raw = await rawTeapotOn(
port,
[
{ method: 'GET', pattern: '/__ready__' },
{ method: 'GET', pattern: '/api/fake/ok' },
],
{ from: 'raw teapot' },
);
try {
expect(await routed).toMatchObject({ added: ['GET /api/fake/ok'], removed: [] });
expect((await get(cup.app, '/api/fake/ok')).status).toBe(200);
expect(await (await get(cup.app, '/__ready__')).text()).not.toContain('raw teapot');
expect(cup.warnings.some((w) => w.includes('not serving a route from') && w.includes("'GET /__ready__'"))).toBe(
true,
);
} finally {
await cup.app.close();
open.splice(open.indexOf(cup.app), 1);
await raw.close();
}
});
});
+5 -3
View File
@@ -143,7 +143,7 @@ describe('missingFromManifest', () => {
expect(missingFromManifest(booted, booted)).toEqual([]);
});
it('accepts extra exports — the graph is fixed at boot and nothing new is spliced', () => {
it('accepts extra exports — extra steps are ignored, since the graph is fixed at boot', () => {
const wider: Manifest = {
steps: [...booted.steps, 'billing'],
routes: [...booted.routes, { method: 'POST', pattern: '/svc/new' }],
@@ -161,8 +161,10 @@ describe('missingFromManifest', () => {
expect(missingFromManifest(booted, shrunk)).toEqual(["step 'auth'"]);
});
it('reports a missing route by method and pattern', () => {
// D15 (CARD-19): routes are not part of the graph, so a returning teapot's routes replace the old
// ones (a dropped route is removed from the remote table) instead of refusing the reconnect.
it('does not report a missing route — routes follow the returning manifest', () => {
const routeless: Manifest = { steps: booted.steps, routes: [] };
expect(missingFromManifest(booted, routeless)).toEqual(["route 'GET /svc/:id'"]);
expect(missingFromManifest(booted, routeless)).toEqual([]);
});
});
+152
View File
@@ -0,0 +1,152 @@
/**
* CARD-20 (#125, D16): `HEAD` on a remote buffered `GET` behaves like `HEAD` on a local one.
*
* The teacup resolves `HEAD` to the remote `GET` (implicit HEAD) and forwards it to the teapot as a
* `GET`, then drops the body. The teapot is unchanged, so an older teapot works too.
*/
import 'reflect-metadata';
import http from 'http';
import type { AddressInfo } from 'net';
import { describe, it, expect, afterEach } from 'vitest';
import { createApp, Route, Get, Head, Module, NotFound, ctx } from '../../src/index';
import type { App } from '../../src/app/types';
import type { Logger } from '../../src/logger';
const SECRET = 'head-secret';
const quiet: Logger = { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} };
const seen: string[] = [];
@Route('/')
class RemoteCtl {
@Get('/x', { export: true }) x(@ctx() c: { req: { method: string } }) {
seen.push(`x ${c.req.method}`);
return { a: 1 };
}
@Get('/missing', { export: true }) missing() {
seen.push('missing');
throw new NotFound();
}
@Get('/boom', { export: true }) boom() {
seen.push('boom');
throw new Error('kaboom');
}
@Get('/both', { export: true }) bothGet() {
seen.push('both GET');
return { via: 'get' };
}
@Head('/both', { export: true }) bothHead(@ctx() c: { req: { method: string } }) {
seen.push(`both HEAD as ${c.req.method}`);
return { via: 'head' };
}
}
@Module({ mountpoint: '/api', controllers: [RemoteCtl] })
class TeapotModule {}
@Module({ mountpoint: '/api', controllers: [] })
class TeacupModule {}
const open: App[] = [];
afterEach(async () => {
while (open.length) await open.pop()!.close();
seen.length = 0;
});
async function mesh(): Promise<{ teacup: App; port: number }> {
const teapot = createApp({ modules: [TeapotModule], experimental: true, logger: quiet, mesh: { secret: SECRET } });
open.push(teapot);
const tPort = ((await teapot.listen(0)).address() as AddressInfo).port;
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
logger: quiet,
mesh: { teapots: [{ url: `ws://127.0.0.1:${tPort}/__mesh__/control`, secret: SECRET }], reconnect: false },
});
open.unshift(teacup); // closed first
const port = ((await teacup.listen(0)).address() as AddressInfo).port;
return { teacup, port };
}
function nodeRequest(port: number, method: string, path: string) {
return new Promise<{ status: number; headers: http.IncomingHttpHeaders; body: string }>((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({ status: res.statusCode ?? 0, headers: res.headers, body }));
});
req.on('error', reject);
req.end();
});
}
const fetchVia = (app: App, method: string, path: string) =>
app.fetch(new Request(`http://mesh.test${path}`, { method }));
describe('mesh: HEAD on a remote GET route (CARD-20, D16)', () => {
it('T1: HEAD via app.fetch answers 200 with the GET headers and no body', async () => {
const { teacup } = await mesh();
const get = await fetchVia(teacup, 'GET', '/api/x');
const head = await fetchVia(teacup, 'HEAD', '/api/x');
expect(head.status).toBe(200);
expect(head.headers.get('content-type')).toBe(get.headers.get('content-type'));
expect(head.headers.get('content-type')).toContain('application/json');
expect(await head.text()).toBe('');
expect(await get.json()).toEqual({ a: 1 });
});
it('T2: HEAD via the Node listener answers 200 with the GET headers and no body', async () => {
const { port } = await mesh();
const get = await nodeRequest(port, 'GET', '/api/x');
const head = await nodeRequest(port, 'HEAD', '/api/x');
expect(head.status).toBe(200);
expect(head.headers['content-type']).toBe(get.headers['content-type']);
expect(head.body).toBe('');
});
it('OPTIONS still advertises GET, HEAD, OPTIONS', async () => {
const { teacup, port } = await mesh();
expect((await fetchVia(teacup, 'OPTIONS', '/api/x')).headers.get('allow')).toBe('GET, HEAD, OPTIONS');
expect((await nodeRequest(port, 'OPTIONS', '/api/x')).headers.allow).toBe('GET, HEAD, OPTIONS');
});
it('T3: an explicit remote HEAD route keeps precedence over the implicit fallback', async () => {
const { teacup, port } = await mesh();
const viaFetch = await fetchVia(teacup, 'HEAD', '/api/both');
expect(viaFetch.status).toBe(200);
expect(await viaFetch.text()).toBe('');
const viaNode = await nodeRequest(port, 'HEAD', '/api/both');
expect(viaNode.status).toBe(200);
expect(viaNode.body).toBe('');
// The explicit HEAD handler ran, reached as HEAD — the GET handler never did.
expect(seen).toEqual(['both HEAD as HEAD', 'both HEAD as HEAD']);
});
it('T4: a remote GET that throws NotFound answers HEAD with 404 and no body', async () => {
const { teacup, port } = await mesh();
const viaFetch = await fetchVia(teacup, 'HEAD', '/api/missing');
expect(viaFetch.status).toBe(404);
expect(await viaFetch.text()).toBe('');
const viaNode = await nodeRequest(port, 'HEAD', '/api/missing');
expect(viaNode.status).toBe(404);
expect(viaNode.body).toBe('');
// The teapot handler ran: the 404 is the route's, not a missing HEAD plan on the teapot.
expect(seen).toEqual(['missing', 'missing']);
});
it('a remote GET that fails answers HEAD with 500 and no body', async () => {
const { teacup, port } = await mesh();
const viaFetch = await fetchVia(teacup, 'HEAD', '/api/boom');
expect(viaFetch.status).toBe(500);
expect(await viaFetch.text()).toBe('');
const viaNode = await nodeRequest(port, 'HEAD', '/api/boom');
expect(viaNode.status).toBe(500);
expect(viaNode.body).toBe('');
});
it('T5: one HEAD calls the teapot handler once, as a GET', async () => {
const { teacup } = await mesh();
await fetchVia(teacup, 'HEAD', '/api/x');
expect(seen).toEqual(['x GET']);
});
});
+1 -1
View File
@@ -31,7 +31,7 @@ Nothing can regenerate the baseline by accident:
| `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/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 (built once at boot at the pinned revision; since CARD-19 it follows teapot membership — 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()`. |
@@ -206,7 +206,7 @@
"adapter": "fetch",
"method": "HEAD",
"path": "/api/x",
"status": 404,
"status": 200,
"headers": {
"content-type": "application/json",
"referrer-policy": "no-referrer",
@@ -472,7 +472,7 @@
"adapter": "node",
"method": "HEAD",
"path": "/api/x",
"status": 404,
"status": 200,
"headers": {
"content-type": "application/json",
"referrer-policy": "no-referrer",
@@ -101,17 +101,17 @@
"phase": "B2 teapot up after boot",
"method": "GET",
"path": "/api/remote/ping",
"status": 404,
"status": 200,
"allow": null,
"body": "{\"error\":\"Not Found\"}"
"body": "{\"from\":\"teapot\"}"
},
{
"phase": "B2 teapot up after boot",
"method": "POST",
"path": "/api/remote/ping",
"status": 404,
"allow": null,
"body": "{\"error\":\"Not Found\"}"
"status": 405,
"allow": "GET, HEAD, OPTIONS",
"body": "{\"error\":\"Method Not Allowed\"}"
},
{
"phase": "B2 teapot up after boot",
+24 -7
View File
@@ -88,15 +88,30 @@ const teacupFor = (port: number) =>
teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: SECRET }],
bootTimeoutMs: 300,
timeoutMs: 500,
reconnect: false,
// Reconnect on (CARD-19, D15): a dropped teapot is "reconnecting" and keeps its routes (A2),
// and one absent at boot is retried in the background (B). Captured at ed47836 with
// `reconnect: false`, when neither depended on it. Fast backoff keeps the test short.
reconnect: { initialDelayMs: 20, maxDelayMs: 60 },
},
});
/** Resolves on the teacup's next `mesh:routes` event: its remote table changed. */
const routesChanged = (app: App) =>
new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error('no mesh:routes within 5s')), 5000);
const off = app.bus.on('mesh:routes', () => {
clearTimeout(timer);
off();
resolve();
});
});
/**
* 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.
* comes up afterwards. At ed47836 the HTTP table was built once, at boot, and never changed, so B2
* answered 404. Since CARD-19 (D15, owner approval) the remote routes follow membership: a teapot
* that is reconnecting keeps its routes and answers 503 (A2), and a late one is spliced in when it
* connects (B2). CARD-10 can reuse this to assert the index is not rebuilt per request.
*/
async function meshLifetimes() {
const results = [];
@@ -118,7 +133,9 @@ async function meshLifetimes() {
const teapotB = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
try {
results.push(...(await probe(teacupB, 'B1 teapot absent at boot')));
const spliced = routesChanged(teacupB);
await teapotB.listen(portB);
await spliced;
results.push(...(await probe(teacupB, 'B2 teapot up after boot')));
} finally {
await teacupB.close();
@@ -141,9 +158,9 @@ class RemoteMixCtl {
return { from: 'teapot', route: 'POST /api/v/:id' };
}
// Remote only: remote routes are `buffer`, so the teacup's router resolves HEAD to it implicitly.
// Captured as observed at ed47836: the teacup forwards the request as HEAD, the teapot looks its
// plan up by (pattern, method) and has none for HEAD, so HEAD answers 404 while OPTIONS still
// advertises HEAD. That is the mesh proxy's behaviour, not the matcher's; CARD-07 must keep it.
// Captured at ed47836 as HEAD → 404 (the teacup forwarded HEAD, and the teapot has no HEAD plan).
// CARD-20 (#125, D16) changed that deliberately, with owner approval: the teacup forwards the
// HEAD as a GET and drops the body, so HEAD now answers 200 like a local route.
@Get('/x', { export: true }) x() {
return { from: 'teapot', route: 'GET /api/x' };
}
+1 -1
View File
@@ -172,5 +172,5 @@ it('a root created after the first request starts serving without a restart', as
expect(await resolve('/a.txt')).toBeUndefined();
mkdirSync(late);
writeFileSync(join(late, 'a.txt'), 'late');
expect((await resolve('/a.txt'))?.body.toString()).toBe('late');
expect((await (await resolve('/a.txt'))?.read())?.toString()).toBe('late');
});