Compare commits
7
Commits
144d880171
...
23a600b438
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
23a600b438 | ||
|
|
8f73779a21 | ||
|
|
e98d5d33eb | ||
|
|
cad81223e5 | ||
|
|
713122d53a | ||
|
|
bfa4c1464a | ||
|
|
3296189093 |
No files matched your search
@@ -22,6 +22,7 @@ coverage/
|
|||||||
# Edge (Miniflare) test bundle artifact
|
# Edge (Miniflare) test bundle artifact
|
||||||
test/edge/_worker.mjs
|
test/edge/_worker.mjs
|
||||||
test/edge/_parity-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 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.
|
# `bun test` against the node_modules npm installed, which package-lock.json already pins.
|
||||||
|
|||||||
@@ -121,6 +121,25 @@ npm treats versions as semver and semver forbids leading zeros.
|
|||||||
`false` or `{ drainDelayMs?: number }`. On the edge there is no `close()`, so `/__ready__` never
|
`false` or `{ drainDelayMs?: number }`. On the edge there is no `close()`, so `/__ready__` never
|
||||||
reports `draining` there.
|
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
|
- **`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
|
`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
|
comparison, lists, `*`) gets a `304` with no body. A handler that sets its own `etag` keeps it, and
|
||||||
@@ -151,6 +170,11 @@ npm treats versions as semver and semver forbids leading zeros.
|
|||||||
about `maxConnections × maxWsQueue × maxWsMessageBytes`, ≈ 15.6 GiB at the Node defaults; Deno and
|
about `maxConnections × maxWsQueue × maxWsMessageBytes`, ≈ 15.6 GiB at the Node defaults; Deno and
|
||||||
Bun have no connection cap, so set one at the platform or proxy there.
|
Bun have no connection cap, so set one at the platform or proxy there.
|
||||||
|
|
||||||
|
- **`WsSocket.drained()`** (#41): an optional method an adapter's socket provides so the outbound
|
||||||
|
pump can wait for its send buffer. It resolves once the buffer is at or below the adapter's
|
||||||
|
high-water mark, or the socket has closed, and at once when it already is. The built-in adapters
|
||||||
|
all provide it. A socket built without it is never waited on, as before.
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
|
||||||
- **Static files are revalidated, not re-downloaded** (#114, D12). Every static hit carries a weak
|
- **Static files are revalidated, not re-downloaded** (#114, D12). Every static hit carries a weak
|
||||||
@@ -208,6 +232,52 @@ npm treats versions as semver and semver forbids leading zeros.
|
|||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|
||||||
|
- **WebSocket outbound respects backpressure** (#41). A `@Ws` handler's async iterator was pulled
|
||||||
|
as fast as it could yield, whatever the peer read, so a fast producer and a slow client grew the
|
||||||
|
send buffer without limit: 10,000 frames of 64 KiB put 640 MiB in memory at once. The pump now
|
||||||
|
waits before each pull while the socket's buffer is over 1 MiB, an internal mark rather than an
|
||||||
|
option, so a slow peer holds at most about that plus one frame. A peer that keeps up never makes
|
||||||
|
it wait. If the peer goes away while the pump waits, the wait ends and the iterator's `return()`
|
||||||
|
runs, as on any other close. Each runtime signals in its own way: Node uses `ws`'s
|
||||||
|
`bufferedAmount` and send callback, Bun uses `getBufferedAmount()` and its `drain` callback, and
|
||||||
|
Deno polls `bufferedAmount`, since its `WebSocket` has no drain event. **workerd reports no
|
||||||
|
buffered amount**, so on the edge the pump never waits and buffering is left to the platform.
|
||||||
|
|
||||||
|
- **On Deno, a `@Ws` handler that yields at once no longer loses the connection.** Deno hands the
|
||||||
|
socket over before it is open. A value yielded in that window was pulled, the pump found the
|
||||||
|
socket not open, and it gave up: the client got no frame and a close without a code (`1005`).
|
||||||
|
The pump now waits for the socket to open, as part of the same backpressure wait.
|
||||||
|
|
||||||
|
- **A mesh RPC whose body is within `maxBodyBytes` reaches the teapot again** (#120). The 1 MiB
|
||||||
|
WebSocket cap from #107 also bounded the mesh control channel, so a request body that fit the
|
||||||
|
HTTP limit could still exceed it once the teacup wrapped it in an RPC frame. A text body near
|
||||||
|
1 MB was enough, because JSON escaping doubles every `"` and backslash, and any body limit raised
|
||||||
|
above 1 MiB was capped at 1 MiB on the channel. Either way the teapot closed the whole channel
|
||||||
|
with `1009`, and every request through that link failed with `503` until it reconnected.
|
||||||
|
|
||||||
|
The control channel is now bounded by the teapot's `limits.maxBodyBytes`: six times the body
|
||||||
|
limit, the most JSON escaping can grow a body (a control character becomes `\u0001`), plus 1 MiB
|
||||||
|
for headers and the rest of the envelope. That is 7,048,576 bytes at the 1 MB default, up from
|
||||||
|
the frame parser's former fixed 4,000,000. `limits.maxWsMessageBytes` still governs every user
|
||||||
|
`@Ws` route, unchanged. On Bun, which takes one native payload limit for all sockets, a teapot
|
||||||
|
raises that limit to the control channel's bound, so an oversized frame on a user route is
|
||||||
|
refused by the framework instead: still `1009`, on every Bun version, where Bun before 1.4
|
||||||
|
refused natively by dropping the connection (`1006`).
|
||||||
|
|
||||||
|
- **More than 16 mesh RPCs in flight on one link no longer drop the control channel** (#148). The
|
||||||
|
16-frame inbound queue from #107 (`limits.maxWsQueue`) also applied to the control channel. On
|
||||||
|
Node, `ws` delivers every frame of one socket read at once, so a teacup sending a burst of RPCs
|
||||||
|
got the channel closed with `1013`, and every pending request failed with `503`. The control
|
||||||
|
channel now has its own queue bound of 4,096 frames, or `maxWsQueue` if that is larger, which is
|
||||||
|
more than one socket read can carry. User `@Ws` routes keep closing `1013` at `maxWsQueue`. Deno
|
||||||
|
and Bun deliver frames one at a time and did not hit this, but they now share the same bound.
|
||||||
|
|
||||||
|
Both larger bounds, this one and the frame size from #120, **apply only once the peer's `hello`
|
||||||
|
is accepted**. Until then the control channel takes frames of at most 64 KiB and queues at most
|
||||||
|
16, and closes with `1009` or `1013` past that. An unauthenticated peer can therefore make a
|
||||||
|
teapot hold about 1 MiB per connection, including while `app.upgrade` waits for a slow boot,
|
||||||
|
instead of thousands of multi-megabyte frames.
|
||||||
|
|
||||||
- **Edge HTTP fills `ctx.ip` from `cf-connecting-ip` under `trustProxy`** (#119). `edgeHandler`
|
- **Edge HTTP fills `ctx.ip` from `cf-connecting-ip` under `trustProxy`** (#119). `edgeHandler`
|
||||||
never read the header for HTTP, so IP-keyed plugins such as rate-limit saw `''`, one bucket for
|
never read the header for HTTP, so IP-keyed plugins such as rate-limit saw `''`, one bucket for
|
||||||
every client. Under `trustProxy: true` the header now sets `ctx.ip`, and it wins over
|
every client. Under `trustProxy: true` the header now sets `ctx.ip`, and it wins over
|
||||||
|
|||||||
@@ -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.
|
- **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.
|
- **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS.
|
||||||
- **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response.
|
- **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response.
|
||||||
- **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency. 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.
|
- **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.
|
- **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.
|
- **Observability without an integration.** Every request carries an id and a trace id through every lifecycle event, each step reports its own duration, and `createApp({ logger })` accepts any logger — the default writes structured JSON. Nothing in core writes to `console`. Metrics and tracing exporters read the same stream from outside core.
|
||||||
- **Graceful shutdown, with a deadline.** `app.close()` drains in-flight requests and closes live streams and mesh links, then warns and force-closes whatever is still open after 10 seconds — so a stuck handler cannot hold a deploy open forever. Change the number per call with `close({ timeoutMs })` or for the whole app with `createApp({ shutdownTimeoutMs })`. Connection *draining* is Node-only; on Deno and Bun the server `serveDeno()`/`serveBun()` returns carries the same `close({ timeoutMs })`.
|
- **Graceful shutdown, with a deadline.** `app.close()` drains in-flight requests and closes live streams and mesh links, then warns and force-closes whatever is still open after 10 seconds — so a stuck handler cannot hold a deploy open forever. Change the number per call with `close({ timeoutMs })` or for the whole app with `createApp({ shutdownTimeoutMs })`. Connection *draining* is Node-only; on Deno and Bun the server `serveDeno()`/`serveBun()` returns carries the same `close({ timeoutMs })`.
|
||||||
@@ -296,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.
|
**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.
|
**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
@@ -90,7 +90,7 @@
|
|||||||
"test:dev": "vitest",
|
"test:dev": "vitest",
|
||||||
"test:deno": "deno test --allow-net --allow-read --allow-run --allow-env --no-check test/deno/",
|
"test:deno": "deno test --allow-net --allow-read --allow-run --allow-env --no-check test/deno/",
|
||||||
"test:bun": "bun test test/bun/",
|
"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",
|
"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": "tsc --noEmit -p tsconfig.json",
|
||||||
"typecheck:bench": "tsc --noEmit -p bench/tsconfig.json",
|
"typecheck:bench": "tsc --noEmit -p bench/tsconfig.json",
|
||||||
|
|||||||
+97
-10
@@ -9,8 +9,10 @@ import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } fro
|
|||||||
import type { HttpOptions } from '../http';
|
import type { HttpOptions } from '../http';
|
||||||
import { trustedProxyClient } from '../http/peer';
|
import { trustedProxyClient } from '../http/peer';
|
||||||
import { answerFetchProbe, buildFetch } from '../http/web';
|
import { answerFetchProbe, buildFetch } from '../http/web';
|
||||||
|
import { resolveCompression, edgeMarker, MARK_EDGE, type CompressionOptions } from '../http/compression';
|
||||||
import {
|
import {
|
||||||
boundInbound,
|
boundInbound,
|
||||||
|
controlBounds,
|
||||||
validateWsLimits,
|
validateWsLimits,
|
||||||
WS_MAX_MESSAGE_BYTES,
|
WS_MAX_MESSAGE_BYTES,
|
||||||
wsMessageBytes,
|
wsMessageBytes,
|
||||||
@@ -45,7 +47,13 @@ import { connectLink, isPermanentRefusal, type Link } from '../mesh/link';
|
|||||||
import { Rooms } from '../rooms';
|
import { Rooms } from '../rooms';
|
||||||
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
|
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
|
||||||
import { buildRemote, type RemoteRoute as TeacupRemoteRoute } 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 {
|
||||||
|
buildManifest,
|
||||||
|
controlFrameLimit,
|
||||||
|
createMeshControl,
|
||||||
|
MESH_CONTROL_DISABLED_REASON,
|
||||||
|
MESH_CONTROL_PATH,
|
||||||
|
} from '../mesh/teapot';
|
||||||
import type { MeshControl } from '../http';
|
import type { MeshControl } from '../http';
|
||||||
import type { RequestEnvelope, RouteEntry } from '../mesh/protocol';
|
import type { RequestEnvelope, RouteEntry } from '../mesh/protocol';
|
||||||
import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types';
|
import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types';
|
||||||
@@ -180,6 +188,32 @@ export function createApp(opts: {
|
|||||||
* Anything but a boolean throws.
|
* Anything but a boolean throws.
|
||||||
*/
|
*/
|
||||||
etag?: boolean;
|
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
|
* 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
|
* (default: 10s). `close({ timeoutMs })` still wins per call. Set it here when `close()` is
|
||||||
@@ -315,6 +349,7 @@ export function createApp(opts: {
|
|||||||
orderedProviders,
|
orderedProviders,
|
||||||
orderedSteps,
|
orderedSteps,
|
||||||
deps: pipelineDeps,
|
deps: pipelineDeps,
|
||||||
|
maxBodyBytes: opts.limits?.maxBodyBytes,
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -367,7 +402,9 @@ export function createApp(opts: {
|
|||||||
const staticConfig = normalizeStatic(opts.static);
|
const staticConfig = normalizeStatic(opts.static);
|
||||||
const staticResolver = staticConfig ? buildStaticResolver(staticConfig.root, staticConfig.cacheControl) : undefined;
|
const staticResolver = staticConfig ? buildStaticResolver(staticConfig.root, staticConfig.cacheControl) : undefined;
|
||||||
|
|
||||||
|
const compression = resolveCompression(opts.compression);
|
||||||
const fetchOpts: HttpOptions = {
|
const fetchOpts: HttpOptions = {
|
||||||
|
compression,
|
||||||
bus,
|
bus,
|
||||||
logger,
|
logger,
|
||||||
limits: opts.limits,
|
limits: opts.limits,
|
||||||
@@ -382,9 +419,13 @@ export function createApp(opts: {
|
|||||||
etag: opts.etag,
|
etag: opts.etag,
|
||||||
};
|
};
|
||||||
const fetchFn = buildAppFetch(fetchOpts, bootApp, currentTable);
|
const fetchFn = buildAppFetch(fetchOpts, bootApp, currentTable);
|
||||||
|
// Known at construction, unlike the control channel itself, because `app.upgrade` must bound a
|
||||||
|
// socket before it awaits the boot (#120).
|
||||||
|
const meshBounds = controlBounds(opts.limits, controlFrameLimit(opts.limits?.maxBodyBytes));
|
||||||
const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl, {
|
const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl, {
|
||||||
limits: opts.limits,
|
limits: opts.limits,
|
||||||
trustProxy: opts.trustProxy,
|
trustProxy: opts.trustProxy,
|
||||||
|
meshBounds,
|
||||||
});
|
});
|
||||||
|
|
||||||
const listen = async (port: number): Promise<http.Server> => {
|
const listen = async (port: number): Promise<http.Server> => {
|
||||||
@@ -398,6 +439,7 @@ export function createApp(opts: {
|
|||||||
|
|
||||||
// A getter, not an array: mesh membership can change the table after this server starts.
|
// A getter, not an array: mesh membership can change the table after this server starts.
|
||||||
server = createHttpServer(currentTable, wsRoutes, bus, meshControl, {
|
server = createHttpServer(currentTable, wsRoutes, bus, meshControl, {
|
||||||
|
compression,
|
||||||
bus,
|
bus,
|
||||||
logger,
|
logger,
|
||||||
limits: opts.limits,
|
limits: opts.limits,
|
||||||
@@ -479,8 +521,11 @@ export function createApp(opts: {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return Object.assign(app, {
|
return Object.assign(app, {
|
||||||
[WS_MAX_MESSAGE_BYTES]: wsMessageBytes(opts.limits),
|
[WS_MAX_MESSAGE_BYTES]: nativeWsBytes(opts.mesh, registry, opts.limits, meshBounds),
|
||||||
[HEALTH_DRAIN]: drain,
|
[HEALTH_DRAIN]: drain,
|
||||||
|
|
||||||
|
// `edgeHandler` calls this: on the edge core never encodes, whatever detection concluded.
|
||||||
|
[MARK_EDGE]: edgeMarker(compression),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1527,6 +1572,21 @@ function makeAppBooter(
|
|||||||
return once(runBoot);
|
return once(runBoot);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The one inbound bound Bun applies natively to every socket (`WS_MAX_MESSAGE_BYTES`). A teapot
|
||||||
|
* raises it to its control channel's (#120); user routes still close at `maxWsMessageBytes`,
|
||||||
|
* because `app.upgrade` bounds them itself.
|
||||||
|
*/
|
||||||
|
function nativeWsBytes(
|
||||||
|
mesh: MeshConfig | undefined,
|
||||||
|
registry: Registry,
|
||||||
|
limits: RequestLimits | undefined,
|
||||||
|
meshBounds: ReturnType<typeof controlBounds>,
|
||||||
|
): number {
|
||||||
|
const servesControl = mesh?.secret && (registry.exportedSteps.length || registry.exportedRoutes.length);
|
||||||
|
return servesControl ? meshBounds.authed.maxWsMessageBytes : wsMessageBytes(limits);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Builds the mesh control gateway that exposes this node's declared exports over the control channel.
|
* Builds the mesh control gateway that exposes this node's declared exports over the control channel.
|
||||||
* Returns undefined when there is nothing to export; throws if exports are declared without a gating secret.
|
* Returns undefined when there is nothing to export; throws if exports are declared without a gating secret.
|
||||||
@@ -1534,7 +1594,13 @@ function makeAppBooter(
|
|||||||
function buildMeshControl(
|
function buildMeshControl(
|
||||||
mesh: MeshConfig | undefined,
|
mesh: MeshConfig | undefined,
|
||||||
registry: Registry,
|
registry: Registry,
|
||||||
deps: { container: Container; orderedProviders: GraphNode[]; orderedSteps: GraphNode[]; deps: PipelineDeps },
|
deps: {
|
||||||
|
container: Container;
|
||||||
|
orderedProviders: GraphNode[];
|
||||||
|
orderedSteps: GraphNode[];
|
||||||
|
deps: PipelineDeps;
|
||||||
|
maxBodyBytes?: number;
|
||||||
|
},
|
||||||
): MeshControl | undefined {
|
): MeshControl | undefined {
|
||||||
const { exportedSteps, exportedRoutes, routePlans, runners } = registry;
|
const { exportedSteps, exportedRoutes, routePlans, runners } = registry;
|
||||||
const hasExports = exportedSteps.length || exportedRoutes.length;
|
const hasExports = exportedSteps.length || exportedRoutes.length;
|
||||||
@@ -1605,7 +1671,14 @@ function buildMeshControl(
|
|||||||
return result;
|
return result;
|
||||||
};
|
};
|
||||||
|
|
||||||
return createMeshControl({ secret: mesh.secret, manifest, resolveScope, resolveRoute, bus });
|
return createMeshControl({
|
||||||
|
secret: mesh.secret,
|
||||||
|
manifest,
|
||||||
|
resolveScope,
|
||||||
|
resolveRoute,
|
||||||
|
bus,
|
||||||
|
maxBodyBytes: deps.maxBodyBytes,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1736,7 +1809,15 @@ function buildAppUpgrade(
|
|||||||
streams: Set<() => void>,
|
streams: Set<() => void>,
|
||||||
ensureBooted: () => Promise<void>,
|
ensureBooted: () => Promise<void>,
|
||||||
getMeshControl: () => MeshControl | undefined,
|
getMeshControl: () => MeshControl | undefined,
|
||||||
{ limits, trustProxy }: { limits?: RequestLimits; trustProxy?: boolean },
|
{
|
||||||
|
limits,
|
||||||
|
trustProxy,
|
||||||
|
meshBounds,
|
||||||
|
}: {
|
||||||
|
limits?: RequestLimits;
|
||||||
|
trustProxy?: boolean;
|
||||||
|
meshBounds: ReturnType<typeof controlBounds>;
|
||||||
|
},
|
||||||
): (request: WsRequest, socket: WsSocket) => Promise<void> {
|
): (request: WsRequest, socket: WsSocket) => Promise<void> {
|
||||||
let wsRoutes: WsRouteDef[] | undefined;
|
let wsRoutes: WsRouteDef[] | undefined;
|
||||||
|
|
||||||
@@ -1745,10 +1826,9 @@ function buildAppUpgrade(
|
|||||||
// with no subscriber is dropped, so anything the peer sends while providers are still booting
|
// with no subscriber is dropped, so anything the peer sends while providers are still booting
|
||||||
// would be lost. For the mesh control channel that is the `hello` itself — the handshake would
|
// would be lost. For the mesh control channel that is the `hello` itself — the handshake would
|
||||||
// hang until timeout against a teapot whose providers happened to boot slowly.
|
// hang until timeout against a teapot whose providers happened to boot slowly.
|
||||||
const ready = boundInbound(socket, limits);
|
// The path comes first, though, because it decides the bound: the mesh control channel carries
|
||||||
|
// whole request bodies and is bounded by the body limit, not `maxWsMessageBytes` (#120) — once
|
||||||
await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted
|
// its peer authenticates. Until then, and so throughout the boot, it takes hello-sized frames.
|
||||||
|
|
||||||
let path: string;
|
let path: string;
|
||||||
|
|
||||||
// The same normalization HTTP and the Node upgrade listener run. A malformed escape would
|
// The same normalization HTTP and the Node upgrade listener run. A malformed escape would
|
||||||
@@ -1756,10 +1836,17 @@ function buildAppUpgrade(
|
|||||||
try {
|
try {
|
||||||
path = normalizeRequestPath(request.url.split('?')[0]);
|
path = normalizeRequestPath(request.url.split('?')[0]);
|
||||||
} catch {
|
} catch {
|
||||||
ready.close(1008, 'invalid request path');
|
socket.close(1008, 'invalid request path');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const ready =
|
||||||
|
path === MESH_CONTROL_PATH
|
||||||
|
? boundInbound(socket, meshBounds.preAuth, meshBounds.authed)
|
||||||
|
: boundInbound(socket, limits);
|
||||||
|
|
||||||
|
await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted
|
||||||
|
|
||||||
const meshControl = getMeshControl();
|
const meshControl = getMeshControl();
|
||||||
|
|
||||||
// The reserved mesh path, checked before route matching: this is what lets a teapot export
|
// The reserved mesh path, checked before route matching: this is what lets a teapot export
|
||||||
|
|||||||
+35
-4
@@ -1,7 +1,13 @@
|
|||||||
import { channel } from './channel';
|
import { channel } from './channel';
|
||||||
import type { Channel } from './channel';
|
import type { Channel } from './channel';
|
||||||
import type { App } from './app/types';
|
import type { App } from './app/types';
|
||||||
import { WS_MAX_MESSAGE_BYTES, DEFAULT_MAX_WS_MESSAGE_BYTES, type WsSocket, type WsRequest } from './http/ws-core';
|
import {
|
||||||
|
WS_MAX_MESSAGE_BYTES,
|
||||||
|
DEFAULT_MAX_WS_MESSAGE_BYTES,
|
||||||
|
WS_HIGH_WATER_MARK,
|
||||||
|
type WsSocket,
|
||||||
|
type WsRequest,
|
||||||
|
} from './http/ws-core';
|
||||||
import { beginDrain } from './http/health';
|
import { beginDrain } from './http/health';
|
||||||
import { decodeMessage, neutralSocket, toWsRequest, upgradeSafely } from './http/ws-adapter';
|
import { decodeMessage, neutralSocket, toWsRequest, upgradeSafely } from './http/ws-adapter';
|
||||||
import { closeWithDeadline } from './http/shutdown';
|
import { closeWithDeadline } from './http/shutdown';
|
||||||
@@ -15,12 +21,15 @@ interface BunServerWebSocket {
|
|||||||
send(data: string): number;
|
send(data: string): number;
|
||||||
close(code?: number, reason?: string): void;
|
close(code?: number, reason?: string): void;
|
||||||
terminate?(): void;
|
terminate?(): void;
|
||||||
|
/** Bytes queued and not yet written; Bun's counterpart to `WebSocket.bufferedAmount`. */
|
||||||
|
getBufferedAmount?(): number;
|
||||||
}
|
}
|
||||||
interface BunWebSocketHandler {
|
interface BunWebSocketHandler {
|
||||||
maxPayloadLength?: number;
|
maxPayloadLength?: number;
|
||||||
open?(ws: BunServerWebSocket): void;
|
open?(ws: BunServerWebSocket): void;
|
||||||
message(ws: BunServerWebSocket, message: string | Uint8Array): void;
|
message(ws: BunServerWebSocket, message: string | Uint8Array): void;
|
||||||
close?(ws: BunServerWebSocket, code: number, reason: string): void;
|
close?(ws: BunServerWebSocket, code: number, reason: string): void;
|
||||||
|
drain?(ws: BunServerWebSocket): void;
|
||||||
error?(ws: BunServerWebSocket, error?: unknown): void;
|
error?(ws: BunServerWebSocket, error?: unknown): void;
|
||||||
}
|
}
|
||||||
interface BunServer {
|
interface BunServer {
|
||||||
@@ -58,6 +67,13 @@ interface BunConnData {
|
|||||||
wsReq: WsRequest;
|
wsReq: WsRequest;
|
||||||
inbound: Channel<unknown>;
|
inbound: Channel<unknown>;
|
||||||
ac: AbortController;
|
ac: AbortController;
|
||||||
|
/** `drained` callers waiting for Bun's `drain` callback or the close (#41). */
|
||||||
|
drainWaiters: Array<() => void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Wakes every `drained` caller; each rechecks the buffer and waits again if it is still over. */
|
||||||
|
function releaseDrain(ws: BunServerWebSocket): void {
|
||||||
|
(ws.data as BunConnData).drainWaiters.splice(0).forEach((resolve) => resolve());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -66,9 +82,17 @@ interface BunConnData {
|
|||||||
* created during the upgrade and stashed on ws.data — there is nothing here to wire up.
|
* created during the upgrade and stashed on ws.data — there is nothing here to wire up.
|
||||||
*/
|
*/
|
||||||
function bunSocket(ws: BunServerWebSocket): WsSocket {
|
function bunSocket(ws: BunServerWebSocket): WsSocket {
|
||||||
const { inbound, ac } = ws.data as BunConnData;
|
const { inbound, ac, drainWaiters } = ws.data as BunConnData;
|
||||||
|
|
||||||
return neutralSocket(ws, inbound, ac);
|
// Bun has no `bufferedAmount` property, so the generic poll would never wait. It has better: a
|
||||||
|
// `getBufferedAmount()` to read and a server-level `drain` callback to wait on, no timer needed.
|
||||||
|
const drained = async (): Promise<void> => {
|
||||||
|
while (!ac.signal.aborted && (ws.getBufferedAmount?.() ?? 0) > WS_HIGH_WATER_MARK) {
|
||||||
|
await new Promise<void>((resolve) => drainWaiters.push(resolve));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return Object.assign(neutralSocket(ws, inbound, ac), { drained });
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -98,7 +122,7 @@ export async function serveBun(app: App, options?: BunServeShortOptions): Promis
|
|||||||
const inbound = channel();
|
const inbound = channel();
|
||||||
const ac = new AbortController();
|
const ac = new AbortController();
|
||||||
const wsReq = toWsRequest(request, server.requestIP(request)?.address ?? '');
|
const wsReq = toWsRequest(request, server.requestIP(request)?.address ?? '');
|
||||||
const data: BunConnData = { wsReq, inbound, ac };
|
const data: BunConnData = { wsReq, inbound, ac, drainWaiters: [] };
|
||||||
if (server.upgrade(request, { data })) return undefined;
|
if (server.upgrade(request, { data })) return undefined;
|
||||||
return new Response('WebSocket upgrade failed', { status: 400 });
|
return new Response('WebSocket upgrade failed', { status: 400 });
|
||||||
}
|
}
|
||||||
@@ -112,6 +136,8 @@ export async function serveBun(app: App, options?: BunServeShortOptions): Promis
|
|||||||
// assembling it. Up to Bun 1.3 it dropped the connection without a close frame, so the peer
|
// assembling it. Up to Bun 1.3 it dropped the connection without a close frame, so the peer
|
||||||
// saw 1006 rather than 1009 — the price of not buffering the message at all. Bun 1.4 sends 1009.
|
// saw 1006 rather than 1009 — the price of not buffering the message at all. Bun 1.4 sends 1009.
|
||||||
// `app.upgrade` checks the same bound again on the decoded text.
|
// `app.upgrade` checks the same bound again on the decoded text.
|
||||||
|
// On a teapot the value is the mesh control channel's larger bound (#120), and `app.upgrade`
|
||||||
|
// alone holds user routes to `maxWsMessageBytes`, closing 1009 on every Bun version.
|
||||||
maxPayloadLength:
|
maxPayloadLength:
|
||||||
(app as { [WS_MAX_MESSAGE_BYTES]?: number })[WS_MAX_MESSAGE_BYTES] ?? DEFAULT_MAX_WS_MESSAGE_BYTES,
|
(app as { [WS_MAX_MESSAGE_BYTES]?: number })[WS_MAX_MESSAGE_BYTES] ?? DEFAULT_MAX_WS_MESSAGE_BYTES,
|
||||||
open(ws) {
|
open(ws) {
|
||||||
@@ -124,15 +150,20 @@ export async function serveBun(app: App, options?: BunServeShortOptions): Promis
|
|||||||
|
|
||||||
inbound.push(decodeMessage(message));
|
inbound.push(decodeMessage(message));
|
||||||
},
|
},
|
||||||
|
drain(ws) {
|
||||||
|
releaseDrain(ws);
|
||||||
|
},
|
||||||
close(ws) {
|
close(ws) {
|
||||||
const { inbound, ac } = ws.data as BunConnData;
|
const { inbound, ac } = ws.data as BunConnData;
|
||||||
inbound.close();
|
inbound.close();
|
||||||
ac.abort();
|
ac.abort();
|
||||||
|
releaseDrain(ws);
|
||||||
},
|
},
|
||||||
error(ws) {
|
error(ws) {
|
||||||
const { inbound, ac } = ws.data as BunConnData;
|
const { inbound, ac } = ws.data as BunConnData;
|
||||||
inbound.fail(new Error('websocket error'));
|
inbound.fail(new Error('websocket error'));
|
||||||
ac.abort();
|
ac.abort();
|
||||||
|
releaseDrain(ws);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import type { App } from './app/types';
|
import type { App } from './app/types';
|
||||||
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
|
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
|
||||||
import { setProxyClient } from './http/peer';
|
import { setProxyClient } from './http/peer';
|
||||||
|
import { MARK_EDGE } from './http/compression';
|
||||||
|
|
||||||
// Minimal ambient for the Cloudflare Workers globals we use — avoids @cloudflare/workers-types.
|
// Minimal ambient for the Cloudflare Workers globals we use — avoids @cloudflare/workers-types.
|
||||||
// Declares only what we call; mirrors the real workerd signatures.
|
// 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
|
* 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
|
* 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.
|
* 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(
|
export function edgeHandler(
|
||||||
app: App,
|
app: App,
|
||||||
): (request: Request, env?: unknown, ctx?: EdgeCtx) => Response | Promise<Response> {
|
): (request: Request, env?: unknown, ctx?: EdgeCtx) => Response | Promise<Response> {
|
||||||
|
(app as { [MARK_EDGE]?: () => void })[MARK_EDGE]?.();
|
||||||
|
|
||||||
return (request, _env, ctx) => {
|
return (request, _env, ctx) => {
|
||||||
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
|
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
|
||||||
const [client, server] = Object.values(new WebSocketPair()) as [EdgeWebSocket, EdgeWebSocket];
|
const [client, server] = Object.values(new WebSocketPair()) as [EdgeWebSocket, EdgeWebSocket];
|
||||||
|
|||||||
@@ -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(),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@ import { pickEncoder } from './stream';
|
|||||||
import { acquireBody, type BodyReader } from './body';
|
import { acquireBody, type BodyReader } from './body';
|
||||||
import { bodyEtag, findHeader, isNotModified, notModifiedHeaders, staticEtag } from './conditional';
|
import { bodyEtag, findHeader, isNotModified, notModifiedHeaders, staticEtag } from './conditional';
|
||||||
import type { StaticHit } from '../views';
|
import type { StaticHit } from '../views';
|
||||||
|
import type { Encoding } from './compression';
|
||||||
import type { RouteDef, HttpOptions } from './types';
|
import type { RouteDef, HttpOptions } from './types';
|
||||||
import type { StreamEncoder } from '../encoders';
|
import type { StreamEncoder } from '../encoders';
|
||||||
import type { Bus } from '../bus';
|
import type { Bus } from '../bus';
|
||||||
@@ -95,6 +96,8 @@ export type NeutralOutcome =
|
|||||||
encoder: StreamEncoder;
|
encoder: StreamEncoder;
|
||||||
/** The matched route's pattern, for naming the stream lifecycle events. */
|
/** The matched route's pattern, for naming the stream lifecycle events. */
|
||||||
route: string;
|
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. */
|
/** {@link handle}'s result for a normal (non-preflight) request. */
|
||||||
|
|||||||
+39
-22
@@ -2,7 +2,7 @@ import type http from 'http';
|
|||||||
import type https from 'https';
|
import type https from 'https';
|
||||||
import { createRequestGate } from './request-gate';
|
import { createRequestGate } from './request-gate';
|
||||||
import { renderError, type ErrorRequest } from '../transformers';
|
import { renderError, type ErrorRequest } from '../transformers';
|
||||||
import type { Bus } from '../bus';
|
import type { Bus, Correlation } from '../bus';
|
||||||
import { readBody as readBodyBytes, deriveSecure, deriveIp } from './request';
|
import { readBody as readBodyBytes, deriveSecure, deriveIp } from './request';
|
||||||
import { pipeStream } from './stream';
|
import { pipeStream } from './stream';
|
||||||
import { attachWs } from './ws';
|
import { attachWs } from './ws';
|
||||||
@@ -22,6 +22,7 @@ import { currentRoutes } from './router';
|
|||||||
import type { Logger } from '../logger';
|
import type { Logger } from '../logger';
|
||||||
import { nodeRequire } from '../node-require';
|
import { nodeRequire } from '../node-require';
|
||||||
import { answerProbe } from './health';
|
import { answerProbe } from './health';
|
||||||
|
import { compressOutcome } from './compression';
|
||||||
|
|
||||||
interface HandlerConfig {
|
interface HandlerConfig {
|
||||||
routes: RouteTable;
|
routes: RouteTable;
|
||||||
@@ -183,30 +184,46 @@ function createRequestHandler(cfg: HandlerConfig) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if ('preflight' in result) {
|
await writeResult(req, res, result, { opts, bus, correlation });
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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
|
* 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
|
* gate, so shedding never refuses a probe, and before `handle()`, so no step, plugin or lifecycle
|
||||||
|
|||||||
+18
-10
@@ -3,6 +3,8 @@ import { once } from 'events';
|
|||||||
import { sseEncoder, ndjsonEncoder, StreamEncoder } from '../encoders';
|
import { sseEncoder, ndjsonEncoder, StreamEncoder } from '../encoders';
|
||||||
import type { Transport } from '../metadata';
|
import type { Transport } from '../metadata';
|
||||||
import type { Bus, Correlation } from '../bus';
|
import type { Bus, Correlation } from '../bus';
|
||||||
|
import type { NeutralOutcome } from './core';
|
||||||
|
import { frameSink } from './compression';
|
||||||
|
|
||||||
const PING_MS = 15_000;
|
const PING_MS = 15_000;
|
||||||
|
|
||||||
@@ -27,34 +29,40 @@ export function pickEncoder(transport: Transport, accept: string): StreamEncoder
|
|||||||
return pick(accept);
|
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(
|
export async function pipeStream(
|
||||||
res: http.ServerResponse,
|
res: http.ServerResponse,
|
||||||
stream: AsyncIterable<unknown>,
|
outcome: Extract<NeutralOutcome, { kind: 'stream' }>,
|
||||||
encoder: StreamEncoder,
|
|
||||||
bus?: Bus,
|
bus?: Bus,
|
||||||
name = '',
|
|
||||||
streams?: Set<() => void>,
|
streams?: Set<() => void>,
|
||||||
correlation: Correlation = {},
|
correlation: Correlation = {},
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
|
const { stream, encoder, route: name } = outcome;
|
||||||
// `route` duplicates `name` here rather than being passed separately: on a stream event `name`
|
// `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
|
// 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
|
// 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`.
|
// absent on the longest-lived thing the server does. See `EventPayload.name`.
|
||||||
const trace = { name, route: name, ...correlation };
|
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
|
res.flushHeaders(); // establish the stream immediately so idle-until-event sources (e.g. subscriptions) don't deadlock clients awaiting headers
|
||||||
bus?.emit('stream:open', trace);
|
bus?.emit('stream:open', trace);
|
||||||
|
const sink = frameSink(res, outcome.encoding);
|
||||||
const iterator = stream[Symbol.asyncIterator]();
|
const iterator = stream[Symbol.asyncIterator]();
|
||||||
let ping: ReturnType<typeof setInterval> | undefined;
|
let ping: ReturnType<typeof setInterval> | undefined;
|
||||||
|
|
||||||
if (encoder.ping) {
|
if (encoder.ping) {
|
||||||
ping = setInterval(() => res.write(encoder.ping!()), PING_MS);
|
ping = setInterval(() => sink.write(encoder.ping!()), PING_MS);
|
||||||
ping.unref?.();
|
ping.unref?.();
|
||||||
}
|
}
|
||||||
|
|
||||||
const stop = () => {
|
const stop = () => {
|
||||||
if (ping) clearInterval(ping);
|
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(() => {});
|
void Promise.resolve(iterator.return?.()).catch(() => {});
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -76,19 +84,19 @@ export async function pipeStream(
|
|||||||
const { value, done } = await iterator.next();
|
const { value, done } = await iterator.next();
|
||||||
if (done) break;
|
if (done) break;
|
||||||
|
|
||||||
if (!res.write(encoder.encode(value))) {
|
if (!sink.write(encoder.encode(value))) {
|
||||||
await Promise.race([once(res, 'drain'), onClose]);
|
await Promise.race([once(sink.drains, 'drain'), onClose]);
|
||||||
if (res.destroyed) break; // let finally clean up
|
if (res.destroyed) break; // let finally clean up
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
bus?.emit('stream:error', { ...trace, error: err });
|
bus?.emit('stream:error', { ...trace, error: err });
|
||||||
const frame = encoder.encodeError(err);
|
const frame = encoder.encodeError(err);
|
||||||
if (frame && !res.writableEnded) res.write(frame);
|
if (frame && !res.writableEnded) sink.write(frame);
|
||||||
} finally {
|
} finally {
|
||||||
if (ping) clearInterval(ping);
|
if (ping) clearInterval(ping);
|
||||||
streams?.delete(closer);
|
streams?.delete(closer);
|
||||||
if (!res.writableEnded && !res.destroyed) res.end();
|
if (!res.writableEnded && !res.destroyed) sink.end();
|
||||||
bus?.emit('stream:close', trace);
|
bus?.emit('stream:close', trace);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -7,6 +7,7 @@ import type { WsRequest, WsSocket } from './ws-core';
|
|||||||
import type { StaticResolver } from '../views';
|
import type { StaticResolver } from '../views';
|
||||||
import type { Bus } from '../bus';
|
import type { Bus } from '../bus';
|
||||||
import type { Logger } from '../logger';
|
import type { Logger } from '../logger';
|
||||||
|
import type { CompressionConfig } from './compression';
|
||||||
|
|
||||||
/** Per-request and per-server resource ceilings applied by the server. */
|
/** Per-request and per-server resource ceilings applied by the server. */
|
||||||
export interface RequestLimits {
|
export interface RequestLimits {
|
||||||
@@ -70,6 +71,8 @@ export interface HttpOptions {
|
|||||||
health?: HealthProbe;
|
health?: HealthProbe;
|
||||||
/** Weak ETags + `304` for buffered `200` GET/HEAD handler responses (`createApp({ etag })`). */
|
/** Weak ETags + `304` for buffered `200` GET/HEAD handler responses (`createApp({ etag })`). */
|
||||||
etag?: boolean;
|
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. */
|
/** Handler for a matched HTTP route; receives a normalized request and resolves to a pipeline result. */
|
||||||
@@ -129,6 +132,12 @@ export interface WsRouteDef {
|
|||||||
/** Hook for a mesh gateway to take over WebSocket upgrades on a fixed path. */
|
/** Hook for a mesh gateway to take over WebSocket upgrades on a fixed path. */
|
||||||
export interface MeshControl {
|
export interface MeshControl {
|
||||||
path: string;
|
path: string;
|
||||||
|
/**
|
||||||
|
* Inbound bound for this channel's socket, in bytes, used in place of
|
||||||
|
* `limits.maxWsMessageBytes` when larger (#120): an RPC carries a whole request body, which
|
||||||
|
* `maxBodyBytes` bounds, not the WebSocket message limit.
|
||||||
|
*/
|
||||||
|
maxFrameBytes?: number;
|
||||||
/**
|
/**
|
||||||
* Serves one control connection over the neutral socket — the same capability every other ws
|
* Serves one control connection over the neutral socket — the same capability every other ws
|
||||||
* consumer takes, so Node (via `nodeSocket`) and Deno/Bun (via `app.upgrade`) both feed it.
|
* consumer takes, so Node (via `nodeSocket`) and Deno/Bun (via `app.upgrade`) both feed it.
|
||||||
|
|||||||
+19
-15
@@ -18,6 +18,8 @@ import { renderError, type ErrorRequest } from '../transformers';
|
|||||||
import type { RouteTable, HttpOptions } from './types';
|
import type { RouteTable, HttpOptions } from './types';
|
||||||
import { answerProbe } from './health';
|
import { answerProbe } from './health';
|
||||||
import { currentRoutes } from './router';
|
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
|
* Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream
|
||||||
@@ -202,23 +204,22 @@ export function toBodyInit(body: string | Buffer): ResponseBody {
|
|||||||
return new Uint8Array(body.buffer as ArrayBuffer, body.byteOffset, body.byteLength);
|
return new Uint8Array(body.buffer as ArrayBuffer, body.byteOffset, body.byteLength);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Converts a {@link HandleResult}'s outcome into a web `Response`, buffered or streamed. */
|
/** Converts an outcome (already through `compressOutcome`) into a web `Response`, buffered or streamed. */
|
||||||
function outcomeToResponse(result: HandleResult, bus?: Bus, correlation: Correlation = {}): Response {
|
function outcomeToResponse(
|
||||||
const headers = toWebHeaders(mergeInjectedHeaders(result.outcome.headers, result.injected));
|
outcome: NeutralOutcome,
|
||||||
|
injected: Record<string, string>,
|
||||||
|
bus?: Bus,
|
||||||
|
correlation: Correlation = {},
|
||||||
|
): Response {
|
||||||
|
const headers = toWebHeaders(mergeInjectedHeaders(outcome.headers, injected));
|
||||||
|
|
||||||
if (result.outcome.kind === 'stream') {
|
if (outcome.kind === 'stream') {
|
||||||
const body = asReadableStream(
|
const frames = asReadableStream(outcome.stream, outcome.encoder, bus, outcome.route, correlation);
|
||||||
result.outcome.stream,
|
return new Response(outcome.encoding ? compressWebStream(frames, outcome.encoding) : frames, { headers });
|
||||||
result.outcome.encoder,
|
|
||||||
bus,
|
|
||||||
result.outcome.route,
|
|
||||||
correlation,
|
|
||||||
);
|
|
||||||
return new Response(body, { headers });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const body = [204, 205, 304].includes(result.outcome.status) ? null : toBodyInit(result.outcome.body);
|
const body = [204, 205, 304].includes(outcome.status) ? null : toBodyInit(outcome.body);
|
||||||
return new Response(body, { status: result.outcome.status, headers });
|
return new Response(body, { status: outcome.status, headers });
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The first `x-forwarded-for` hop when the proxy is trusted, else `''`. */
|
/** The first `x-forwarded-for` hop when the proxy is trusted, else `''`. */
|
||||||
@@ -329,7 +330,10 @@ export function buildFetch(routes: RouteTable, opts: HttpOptions | undefined) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
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);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+35
-2
@@ -1,6 +1,6 @@
|
|||||||
import { channel, type Channel } from '../channel';
|
import { channel, type Channel } from '../channel';
|
||||||
import type { App } from '../app/types';
|
import type { App } from '../app/types';
|
||||||
import type { WsRequest, WsSocket } from './ws-core';
|
import { WS_HIGH_WATER_MARK, type WsRequest, type WsSocket } from './ws-core';
|
||||||
import { nodeRequire } from '../node-require';
|
import { nodeRequire } from '../node-require';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -40,6 +40,8 @@ export function toWsRequest(request: Request, ip: string): WsRequest {
|
|||||||
/** The subset of a host WebSocket that {@link eventSocket} drives (Deno's WebSocket and workerd's both satisfy it). */
|
/** The subset of a host WebSocket that {@link eventSocket} drives (Deno's WebSocket and workerd's both satisfy it). */
|
||||||
export interface EventfulSocket {
|
export interface EventfulSocket {
|
||||||
readonly readyState: number;
|
readonly readyState: number;
|
||||||
|
/** Bytes queued by `send` and not yet written. Deno reports it; a host without it is never waited on. */
|
||||||
|
readonly bufferedAmount?: number;
|
||||||
send(data: string): void;
|
send(data: string): void;
|
||||||
close(code?: number, reason?: string): void;
|
close(code?: number, reason?: string): void;
|
||||||
addEventListener(
|
addEventListener(
|
||||||
@@ -90,7 +92,7 @@ export function eventSocket(host: EventfulSocket): WsSocket {
|
|||||||
* callers never have to guard an already-closed socket.
|
* callers never have to guard an already-closed socket.
|
||||||
*/
|
*/
|
||||||
export function neutralSocket(
|
export function neutralSocket(
|
||||||
host: Pick<EventfulSocket, 'readyState' | 'send' | 'close'> & { terminate?(): void },
|
host: Pick<EventfulSocket, 'readyState' | 'send' | 'close' | 'bufferedAmount'> & { terminate?(): void },
|
||||||
inbound: Channel<unknown>,
|
inbound: Channel<unknown>,
|
||||||
ac: AbortController,
|
ac: AbortController,
|
||||||
): WsSocket {
|
): WsSocket {
|
||||||
@@ -103,6 +105,7 @@ export function neutralSocket(
|
|||||||
send: (data) => {
|
send: (data) => {
|
||||||
host.send(data);
|
host.send(data);
|
||||||
},
|
},
|
||||||
|
drained: () => pollDrained(host, ac.signal),
|
||||||
close: (code, reason) => {
|
close: (code, reason) => {
|
||||||
try {
|
try {
|
||||||
host.close(code, reason);
|
host.close(code, reason);
|
||||||
@@ -120,6 +123,36 @@ export function neutralSocket(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** How often {@link pollDrained} rereads `bufferedAmount` while a socket is backed up. */
|
||||||
|
const DRAIN_POLL_MS = 10;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@link WsSocket.drained} for a host that reports `bufferedAmount` but fires no drain event —
|
||||||
|
* the Web `WebSocket` API has none. Polls only while the socket is over the mark, so a socket that
|
||||||
|
* keeps up never starts a timer; the close (`signal`) ends the wait at once.
|
||||||
|
*
|
||||||
|
* A socket still CONNECTING is not writable either, and waits too. Deno hands its socket over in
|
||||||
|
* that state, and a route that yielded at once had its first frame pulled, found the socket not
|
||||||
|
* open, and the pump gave up on the connection.
|
||||||
|
*/
|
||||||
|
async function pollDrained(host: Pick<EventfulSocket, 'readyState' | 'bufferedAmount'>, signal: AbortSignal) {
|
||||||
|
const backedUp = () =>
|
||||||
|
host.readyState === CONNECTING || (host.readyState === OPEN && (host.bufferedAmount ?? 0) > WS_HIGH_WATER_MARK);
|
||||||
|
|
||||||
|
while (!signal.aborted && backedUp()) {
|
||||||
|
await new Promise<void>((resolve) => {
|
||||||
|
const done = () => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
signal.removeEventListener('abort', done);
|
||||||
|
resolve();
|
||||||
|
};
|
||||||
|
|
||||||
|
const timer = setTimeout(done, DRAIN_POLL_MS);
|
||||||
|
signal.addEventListener('abort', done, { once: true });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Constructs a host WebSocket *client*. Both the platform global and the `ws` package satisfy it. */
|
/** Constructs a host WebSocket *client*. Both the platform global and the `ws` package satisfy it. */
|
||||||
export type SocketCtor = new (url: string) => EventfulSocket;
|
export type SocketCtor = new (url: string) => EventfulSocket;
|
||||||
|
|
||||||
|
|||||||
+94
-3
@@ -21,8 +21,24 @@ export interface WsSocket {
|
|||||||
send(data: string): void;
|
send(data: string): void;
|
||||||
close(code?: number, reason?: string): void;
|
close(code?: number, reason?: string): void;
|
||||||
terminate(): void;
|
terminate(): void;
|
||||||
|
/**
|
||||||
|
* Resolves once the socket's send buffer is at or below the adapter's high-water mark, or the
|
||||||
|
* socket has closed — at once when it already is (#41). The outbound pump awaits it before
|
||||||
|
* pulling the next value, so a fast producer cannot grow the buffer without limit.
|
||||||
|
*
|
||||||
|
* Optional: a socket without it is never waited on, which is how every socket behaved before.
|
||||||
|
* The mark is the adapter's; {@link WS_HIGH_WATER_MARK} is what the built-in adapters use.
|
||||||
|
*/
|
||||||
|
drained?(): Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send-buffer level, in bytes, above which the built-in adapters report a socket as backed up
|
||||||
|
* (#41). Internal, not an option: it bounds what one slow peer can make the process hold, and
|
||||||
|
* a frame is sent whole, so the buffer peaks at this plus one frame.
|
||||||
|
*/
|
||||||
|
export const WS_HIGH_WATER_MARK = 1_048_576;
|
||||||
|
|
||||||
/** Default for `limits.maxWsMessageBytes`: 1 MiB. */
|
/** Default for `limits.maxWsMessageBytes`: 1 MiB. */
|
||||||
export const DEFAULT_MAX_WS_MESSAGE_BYTES = 1_048_576;
|
export const DEFAULT_MAX_WS_MESSAGE_BYTES = 1_048_576;
|
||||||
/** Default for `limits.maxWsQueue`, in undelivered inbound messages per connection (D1). */
|
/** Default for `limits.maxWsQueue`, in undelivered inbound messages per connection (D1). */
|
||||||
@@ -41,6 +57,61 @@ export function wsMessageBytes(limits: Pick<RequestLimits, 'maxWsMessageBytes'>
|
|||||||
return limits?.maxWsMessageBytes ?? DEFAULT_MAX_WS_MESSAGE_BYTES;
|
return limits?.maxWsMessageBytes ?? DEFAULT_MAX_WS_MESSAGE_BYTES;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Undelivered inbound frames the mesh control channel may hold once its peer is authenticated
|
||||||
|
* (#148), in place of `limits.maxWsQueue` when larger. Its consumer, the teapot's frame loop, never
|
||||||
|
* awaits between frames, so its queue only ever holds one delivery burst: `ws` emits every frame of
|
||||||
|
* one socket read synchronously, and a read is at most 64 KiB, under 4,096 of the smallest control
|
||||||
|
* frame (`{"type":"ping"}`). A teacup with many RPCs in flight sends exactly such bursts, which the
|
||||||
|
* 16-frame user default closed with 1013.
|
||||||
|
*/
|
||||||
|
const CONTROL_QUEUE = 4096;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Largest frame the mesh control channel accepts before its peer's `hello` is accepted. A hello
|
||||||
|
* is a version and a secret; nothing larger has a reason to arrive first.
|
||||||
|
*/
|
||||||
|
export const HELLO_FRAME_BYTES = 65_536;
|
||||||
|
|
||||||
|
/** Inbound bounds for one socket, as {@link boundInbound} takes them. */
|
||||||
|
type InboundLimits = { maxWsMessageBytes: number; maxWsQueue: number };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The bounds of the mesh control channel's socket, in two phases.
|
||||||
|
*
|
||||||
|
* - `preAuth`, until the peer's `hello` is accepted: hello-sized frames and the default 16-frame
|
||||||
|
* queue, so an unauthenticated peer can make the process hold about 1 MiB at most — including
|
||||||
|
* while `app.upgrade` waits for a slow boot, before anything reads the queue.
|
||||||
|
* - `authed`, after: `maxWsMessageBytes` raised to the channel's frame bound (#120) and `maxWsQueue`
|
||||||
|
* to {@link CONTROL_QUEUE} (#148), each only when larger. The peer holds the mesh secret by then.
|
||||||
|
*
|
||||||
|
* A user route never goes through this, so it keeps both limits as configured.
|
||||||
|
*/
|
||||||
|
export function controlBounds(
|
||||||
|
limits: Pick<RequestLimits, 'maxWsMessageBytes' | 'maxWsQueue'> | undefined,
|
||||||
|
maxFrameBytes: number | undefined,
|
||||||
|
): { preAuth: InboundLimits; authed: InboundLimits } {
|
||||||
|
return {
|
||||||
|
preAuth: { maxWsMessageBytes: HELLO_FRAME_BYTES, maxWsQueue: DEFAULT_MAX_WS_QUEUE },
|
||||||
|
authed: {
|
||||||
|
maxWsMessageBytes: Math.max(wsMessageBytes(limits), maxFrameBytes ?? 0),
|
||||||
|
maxWsQueue: Math.max(limits?.maxWsQueue ?? DEFAULT_MAX_WS_QUEUE, CONTROL_QUEUE),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where a socket bounded with a second phase keeps the switch to it; `Symbol.for`, as above. */
|
||||||
|
const WIDEN_INBOUND: unique symbol = Symbol.for('green-tea.widen-inbound');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Switches a socket from {@link boundInbound}'s first bounds to the `widened` ones it was given —
|
||||||
|
* for the mesh control channel, once the peer has authenticated. A no-op on any other socket.
|
||||||
|
* Frames already queued stay; the new bounds apply to the frames that arrive next.
|
||||||
|
*/
|
||||||
|
export function widenInbound(socket: WsSocket): void {
|
||||||
|
(socket as { [WIDEN_INBOUND]?: () => void })[WIDEN_INBOUND]?.();
|
||||||
|
}
|
||||||
|
|
||||||
/** Throws when a WebSocket limit is present but not a positive safe integer (#107). */
|
/** Throws when a WebSocket limit is present but not a positive safe integer (#107). */
|
||||||
export function validateWsLimits(limits: RequestLimits | undefined): void {
|
export function validateWsLimits(limits: RequestLimits | undefined): void {
|
||||||
for (const key of ['maxWsMessageBytes', 'maxWsQueue'] as const) {
|
for (const key of ['maxWsMessageBytes', 'maxWsQueue'] as const) {
|
||||||
@@ -74,10 +145,14 @@ function exceedsBytes(msg: unknown, max: number): boolean {
|
|||||||
* consumer. After that the returned `inbound` fans out like `channel`: each iterator gets every
|
* consumer. After that the returned `inbound` fans out like `channel`: each iterator gets every
|
||||||
* frame from the moment it subscribes, through its own queue, and the bound applies to each queue.
|
* frame from the moment it subscribes, through its own queue, and the bound applies to each queue.
|
||||||
* Every other capability is the original socket's.
|
* Every other capability is the original socket's.
|
||||||
|
*
|
||||||
|
* `widened`, when given, is a second set of bounds that {@link widenInbound} switches to later: the
|
||||||
|
* mesh control channel starts at hello size and widens once its peer authenticates.
|
||||||
*/
|
*/
|
||||||
export function boundInbound(
|
export function boundInbound(
|
||||||
socket: WsSocket,
|
socket: WsSocket,
|
||||||
limits?: Pick<RequestLimits, 'maxWsMessageBytes' | 'maxWsQueue'>,
|
limits?: Pick<RequestLimits, 'maxWsMessageBytes' | 'maxWsQueue'>,
|
||||||
|
widened?: InboundLimits,
|
||||||
): WsSocket {
|
): WsSocket {
|
||||||
const fanout = new InboundFanout(socket, wsMessageBytes(limits), limits?.maxWsQueue ?? DEFAULT_MAX_WS_QUEUE);
|
const fanout = new InboundFanout(socket, wsMessageBytes(limits), limits?.maxWsQueue ?? DEFAULT_MAX_WS_QUEUE);
|
||||||
|
|
||||||
@@ -87,6 +162,7 @@ export function boundInbound(
|
|||||||
|
|
||||||
return Object.create(socket, {
|
return Object.create(socket, {
|
||||||
inbound: { value: { [Symbol.asyncIterator]: () => fanout.subscribe() } },
|
inbound: { value: { [Symbol.asyncIterator]: () => fanout.subscribe() } },
|
||||||
|
...(widened && { [WIDEN_INBOUND]: { value: () => fanout.widen(widened) } }),
|
||||||
}) as WsSocket;
|
}) as WsSocket;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -100,12 +176,18 @@ class InboundFanout {
|
|||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly socket: WsSocket,
|
private readonly socket: WsSocket,
|
||||||
private readonly maxBytes: number,
|
private maxBytes: number,
|
||||||
private readonly maxQueue: number,
|
private maxQueue: number,
|
||||||
) {
|
) {
|
||||||
this.first = this.add();
|
this.first = this.add();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Applies the second phase's bounds; see {@link widenInbound}. */
|
||||||
|
widen(limits: InboundLimits): void {
|
||||||
|
this.maxBytes = limits.maxWsMessageBytes;
|
||||||
|
this.maxQueue = limits.maxWsQueue;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reads the adapter's channel inside its `push`. Runtimes emit a whole read's worth of frames
|
* Reads the adapter's channel inside its `push`. Runtimes emit a whole read's worth of frames
|
||||||
* synchronously — `ws` does — so a bound checked after the event loop yields is checked after an
|
* synchronously — `ws` does — so a bound checked after the event loop yields is checked after an
|
||||||
@@ -279,9 +361,18 @@ function trackConnection(socket: WsSocket, streams?: Set<() => void>): { closer:
|
|||||||
return { closer };
|
return { closer };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Drives the outbound async iterator, sending each yielded value until done or the socket closes. */
|
/**
|
||||||
|
* Drives the outbound async iterator, sending each yielded value until done or the socket closes.
|
||||||
|
* Waits for {@link WsSocket.drained} before each pull (#41): a value pulled while the peer is
|
||||||
|
* backed up has nowhere to go but the send buffer, so it is not pulled until there is room.
|
||||||
|
*/
|
||||||
async function pumpOutbound(socket: WsSocket, iterator: AsyncIterator<unknown>): Promise<void> {
|
async function pumpOutbound(socket: WsSocket, iterator: AsyncIterator<unknown>): Promise<void> {
|
||||||
while (true) {
|
while (true) {
|
||||||
|
if (socket.drained) await socket.drained();
|
||||||
|
// Closed while waiting: stop before pulling a value nobody can receive. The abort listener in
|
||||||
|
// `runWsConnection` has already called the iterator's `return()`. `abort`, not `isOpen`: Deno
|
||||||
|
// hands a socket over still CONNECTING, which is not open yet and not closed either.
|
||||||
|
if (socket.abort.aborted) break;
|
||||||
const { value, done } = await iterator.next();
|
const { value, done } = await iterator.next();
|
||||||
if (done) break;
|
if (done) break;
|
||||||
if (!socket.isOpen) break;
|
if (!socket.isOpen) break;
|
||||||
|
|||||||
+34
-5
@@ -6,7 +6,9 @@ import {
|
|||||||
matchWsRoute,
|
matchWsRoute,
|
||||||
trackUntil,
|
trackUntil,
|
||||||
boundInbound,
|
boundInbound,
|
||||||
|
controlBounds,
|
||||||
wsMessageBytes,
|
wsMessageBytes,
|
||||||
|
WS_HIGH_WATER_MARK,
|
||||||
type WsSocket,
|
type WsSocket,
|
||||||
type WsRequest,
|
type WsRequest,
|
||||||
} from './ws-core';
|
} from './ws-core';
|
||||||
@@ -50,13 +52,18 @@ function handleMeshUpgrade(
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// An RPC carries a whole request body, so once the peer authenticates the channel is bounded by
|
||||||
|
// the teapot's body limit rather than `maxWsMessageBytes` (#120). `wss` is built with that bound
|
||||||
|
// as `maxPayload`; until the hello is accepted, `boundInbound` holds the peer to hello size.
|
||||||
|
const bounds = controlBounds(limits, meshControl.maxFrameBytes);
|
||||||
|
|
||||||
// nodeSocket, not the raw ws: the control channel is the last consumer that spoke the
|
// nodeSocket, not the raw ws: the control channel is the last consumer that spoke the
|
||||||
// `ws` EventEmitter API directly. It now takes the same neutral socket every route does.
|
// `ws` EventEmitter API directly. It now takes the same neutral socket every route does.
|
||||||
// Tracked like any other long-lived socket: a connected teacup has no reason to hang up, so
|
// Tracked like any other long-lived socket: a connected teacup has no reason to hang up, so
|
||||||
// an untracked control channel leaves the teapot's server.close() waiting on it forever.
|
// an untracked control channel leaves the teapot's server.close() waiting on it forever.
|
||||||
// serveFrames swallows its own failures, so the floating promise cannot reject.
|
// serveFrames swallows its own failures, so the floating promise cannot reject.
|
||||||
wss.handleUpgrade(req, socket, head, (ws: any) => {
|
wss.handleUpgrade(req, socket, head, (ws: any) => {
|
||||||
const neutral = boundInbound(nodeSocket(ws), limits);
|
const neutral = boundInbound(nodeSocket(ws), bounds.preAuth, bounds.authed);
|
||||||
|
|
||||||
void trackUntil(neutral, meshControl.handle(neutral), streams);
|
void trackUntil(neutral, meshControl.handle(neutral), streams);
|
||||||
});
|
});
|
||||||
@@ -89,10 +96,21 @@ function nodeWsRequest(req: http.IncomingMessage): WsRequest {
|
|||||||
function nodeSocket(ws: any): WsSocket {
|
function nodeSocket(ws: any): WsSocket {
|
||||||
const inbound = channel<unknown>();
|
const inbound = channel<unknown>();
|
||||||
const ac = new AbortController();
|
const ac = new AbortController();
|
||||||
|
// `drained` callers waiting for the send buffer to fall to the mark (#41). Released by a send
|
||||||
|
// callback, which `ws` runs once that frame is written to the TCP socket, or by the close.
|
||||||
|
const waiters: Array<() => void> = [];
|
||||||
|
const release = () => waiters.splice(0).forEach((resolve) => resolve());
|
||||||
|
const backedUp = () => ws.readyState === 1 && ws.bufferedAmount > WS_HIGH_WATER_MARK;
|
||||||
|
|
||||||
|
const written = () => {
|
||||||
|
if (!backedUp()) release();
|
||||||
|
};
|
||||||
|
|
||||||
ws.on('message', (data: Buffer) => inbound.push(data.toString()));
|
ws.on('message', (data: Buffer) => inbound.push(data.toString()));
|
||||||
ws.on('close', () => {
|
ws.on('close', () => {
|
||||||
inbound.close();
|
inbound.close();
|
||||||
ac.abort();
|
ac.abort();
|
||||||
|
release();
|
||||||
});
|
});
|
||||||
ws.on('error', (err: unknown) => inbound.fail(err));
|
ws.on('error', (err: unknown) => inbound.fail(err));
|
||||||
return {
|
return {
|
||||||
@@ -101,7 +119,8 @@ function nodeSocket(ws: any): WsSocket {
|
|||||||
get isOpen() {
|
get isOpen() {
|
||||||
return ws.readyState === 1; // 1 = OPEN
|
return ws.readyState === 1; // 1 = OPEN
|
||||||
},
|
},
|
||||||
send: (data) => ws.send(data),
|
send: (data) => ws.send(data, written),
|
||||||
|
drained: () => (backedUp() ? new Promise<void>((resolve) => waiters.push(resolve)) : Promise.resolve()),
|
||||||
close: (code, reason) => {
|
close: (code, reason) => {
|
||||||
try {
|
try {
|
||||||
ws.close(code, reason);
|
ws.close(code, reason);
|
||||||
@@ -128,6 +147,14 @@ export function attachWs(
|
|||||||
// fragmented or not, before it is assembled, and closes 1009 itself. `boundInbound` repeats the
|
// fragmented or not, before it is assembled, and closes 1009 itself. `boundInbound` repeats the
|
||||||
// check on the decoded text, which is the only half Deno and the edge have.
|
// check on the decoded text, which is the only half Deno and the edge have.
|
||||||
const wss = WebSocketServer ? new WebSocketServer({ noServer: true, maxPayload: wsMessageBytes(limits) }) : null;
|
const wss = WebSocketServer ? new WebSocketServer({ noServer: true, maxPayload: wsMessageBytes(limits) }) : null;
|
||||||
|
// The control channel's own server, so its larger bound (#120) never reaches a user route.
|
||||||
|
const meshWss =
|
||||||
|
WebSocketServer && meshControl
|
||||||
|
? new WebSocketServer({
|
||||||
|
noServer: true,
|
||||||
|
maxPayload: controlBounds(limits, meshControl.maxFrameBytes).authed.maxWsMessageBytes,
|
||||||
|
})
|
||||||
|
: null;
|
||||||
server.on('upgrade', (req, socket, head) => {
|
server.on('upgrade', (req, socket, head) => {
|
||||||
// A peer that resets mid-rejection must not raise an unhandled 'error' on a socket nobody
|
// A peer that resets mid-rejection must not raise an unhandled 'error' on a socket nobody
|
||||||
// else is listening to yet: that is as fatal as a throw.
|
// else is listening to yet: that is as fatal as a throw.
|
||||||
@@ -136,7 +163,7 @@ export function attachWs(
|
|||||||
// Nothing thrown in here may escape. This is a raw EventEmitter listener, so a throw is an
|
// Nothing thrown in here may escape. This is a raw EventEmitter listener, so a throw is an
|
||||||
// uncaught exception that takes the whole process down, not a 500 for one client.
|
// uncaught exception that takes the whole process down, not a 500 for one client.
|
||||||
try {
|
try {
|
||||||
routeUpgrade({ wss, wsRoutes, bus, meshControl, streams, limits }, req, socket, head);
|
routeUpgrade({ wss, meshWss, wsRoutes, bus, meshControl, streams, limits }, req, socket, head);
|
||||||
} catch {
|
} catch {
|
||||||
if (socket.writable) rejectUpgrade(socket, 500, 'Internal Server Error');
|
if (socket.writable) rejectUpgrade(socket, 500, 'Internal Server Error');
|
||||||
else socket.destroy();
|
else socket.destroy();
|
||||||
@@ -147,6 +174,8 @@ export function attachWs(
|
|||||||
/** What every upgrade on one server shares. */
|
/** What every upgrade on one server shares. */
|
||||||
interface UpgradeEnv {
|
interface UpgradeEnv {
|
||||||
wss: any;
|
wss: any;
|
||||||
|
/** The mesh control channel's server, bounded by its own frame limit (#120). */
|
||||||
|
meshWss: any;
|
||||||
wsRoutes: WsRouteDef[];
|
wsRoutes: WsRouteDef[];
|
||||||
bus?: Bus;
|
bus?: Bus;
|
||||||
meshControl?: MeshControl;
|
meshControl?: MeshControl;
|
||||||
@@ -156,7 +185,7 @@ interface UpgradeEnv {
|
|||||||
|
|
||||||
/** Routes one upgrade: validates the path the way HTTP does, then mesh control, then the ws route table. */
|
/** Routes one upgrade: validates the path the way HTTP does, then mesh control, then the ws route table. */
|
||||||
function routeUpgrade(env: UpgradeEnv, req: http.IncomingMessage, socket: any, head: Buffer): void {
|
function routeUpgrade(env: UpgradeEnv, req: http.IncomingMessage, socket: any, head: Buffer): void {
|
||||||
const { wss, wsRoutes, bus, meshControl, streams, limits } = env;
|
const { wss, meshWss, wsRoutes, bus, meshControl, streams, limits } = env;
|
||||||
let path: string;
|
let path: string;
|
||||||
|
|
||||||
// The same normalization the HTTP path runs (`dispatch` in core.ts). Without it a malformed
|
// The same normalization the HTTP path runs (`dispatch` in core.ts). Without it a malformed
|
||||||
@@ -168,7 +197,7 @@ function routeUpgrade(env: UpgradeEnv, req: http.IncomingMessage, socket: any, h
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head, streams, limits)) return;
|
if (meshControl && handleMeshUpgrade(meshWss, meshControl, path, req, socket, head, streams, limits)) return;
|
||||||
|
|
||||||
// The reserved path with no control channel: refused exactly as `app.upgrade` refuses it on Deno,
|
// The reserved path with no control channel: refused exactly as `app.upgrade` refuses it on Deno,
|
||||||
// Bun and the edge — accept, then close 1008 with the same reason (D17). Never falls through to the
|
// Bun and the edge — accept, then close 1008 with the same reason (D17). Never falls through to the
|
||||||
|
|||||||
@@ -98,6 +98,7 @@ export type { StreamEncoder, SseEvent, SseFields } from './encoders';
|
|||||||
|
|
||||||
// HTTP, security & validation
|
// HTTP, security & validation
|
||||||
export type { RequestLimits } from './http';
|
export type { RequestLimits } from './http';
|
||||||
|
export type { CompressionOptions } from './http/compression';
|
||||||
export { UNMATCHED_ROUTE } from './http/core';
|
export { UNMATCHED_ROUTE } from './http/core';
|
||||||
export type { TlsOptions, CorsOptions, SecurityOptions } from './security';
|
export type { TlsOptions, CorsOptions, SecurityOptions } from './security';
|
||||||
export type { UploadedFile, MultipartBody } from './multipart';
|
export type { UploadedFile, MultipartBody } from './multipart';
|
||||||
|
|||||||
+49
-14
@@ -3,7 +3,7 @@
|
|||||||
// under node-compat on both; edge/workerd is out of scope (see the cross-runtime spec).
|
// under node-compat on both; edge/workerd is out of scope (see the cross-runtime spec).
|
||||||
import crypto from 'node:crypto';
|
import crypto from 'node:crypto';
|
||||||
import type { Bus } from '../bus';
|
import type { Bus } from '../bus';
|
||||||
import type { WsSocket } from '../http/ws-core';
|
import { HELLO_FRAME_BYTES, widenInbound, type WsSocket } from '../http/ws-core';
|
||||||
import type { ResponseShape } from '../pipeline';
|
import type { ResponseShape } from '../pipeline';
|
||||||
import { isHttpError } from '../signals';
|
import { isHttpError } from '../signals';
|
||||||
import {
|
import {
|
||||||
@@ -41,18 +41,34 @@ export const MESH_CONTROL_DISABLED_REASON =
|
|||||||
*/
|
*/
|
||||||
const HANDSHAKE_TIMEOUT_MS = 10_000;
|
const HANDSHAKE_TIMEOUT_MS = 10_000;
|
||||||
|
|
||||||
|
/** `limits.maxBodyBytes`'s default, which a teapot without one is sized for. */
|
||||||
|
const DEFAULT_MAX_BODY_BYTES = 1_000_000;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Largest control frame the teapot will parse, in characters.
|
* The most a body byte can grow inside an `rpc-req` envelope. The envelope is JSON, and a text
|
||||||
*
|
* body travels as a JSON string, so a control character (`\u0001`) becomes the six characters of its
|
||||||
* `decode` runs `JSON.parse` on peer-controlled input, and until the handshake succeeds that peer
|
* escape. Nothing a body can hold grows more: a `"` or backslash doubles, a JSON number such as
|
||||||
* is *unauthenticated* — so without a cap, anyone who can reach the port can make the process parse
|
* `1e20` re-encodes to about five times its length, a multipart `Buffer` to at most four, and
|
||||||
* as much as its WebSocket layer will accept (100 MiB under the `ws` package's defaults, and no
|
* non-ASCII text is not escaped at all.
|
||||||
* documented ceiling on the platform sockets Deno and Bun provide).
|
|
||||||
*
|
|
||||||
* Sized above the 1 MB default body limit an RPC can legitimately carry, with room for the JSON
|
|
||||||
* overhead of the envelope around it.
|
|
||||||
*/
|
*/
|
||||||
const MAX_FRAME_CHARS = 4_000_000;
|
const WORST_ESCAPE = 6;
|
||||||
|
|
||||||
|
/** Room in a frame for everything but the body: headers, params, query, url and the envelope. */
|
||||||
|
const ENVELOPE_HEADROOM = 1_048_576;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Largest control frame a teapot accepts, in characters, when the largest body it may be sent is
|
||||||
|
* `maxBodyBytes` (#120): the body at its worst escaping plus {@link ENVELOPE_HEADROOM}, so any body
|
||||||
|
* within the limit fits. 7,048,576 at the 1 MB default.
|
||||||
|
*
|
||||||
|
* `decode` runs `JSON.parse` on peer-controlled input, so the parse is capped by this figure — and
|
||||||
|
* an unauthenticated peer never gets near it: until its `hello` is accepted, the channel takes only
|
||||||
|
* hello-sized frames (`HELLO_FRAME_BYTES`, `controlBounds` in `ws-core`). Applies to the control
|
||||||
|
* channel only: user WebSocket routes keep `limits.maxWsMessageBytes`.
|
||||||
|
*/
|
||||||
|
export function controlFrameLimit(maxBodyBytes = DEFAULT_MAX_BODY_BYTES): number {
|
||||||
|
return WORST_ESCAPE * maxBodyBytes + ENVELOPE_HEADROOM;
|
||||||
|
}
|
||||||
|
|
||||||
/** Assemble a {@link Manifest} from exported step tokens and buffered routes. */
|
/** Assemble a {@link Manifest} from exported step tokens and buffered routes. */
|
||||||
export function buildManifest(args: { steps: string[]; routes: RouteEntry[] }): Manifest {
|
export function buildManifest(args: { steps: string[]; routes: RouteEntry[] }): Manifest {
|
||||||
@@ -73,6 +89,11 @@ export interface MeshControlDeps {
|
|||||||
resolveScope: (name: string, env: RequestEnvelope) => Promise<unknown>;
|
resolveScope: (name: string, env: RequestEnvelope) => Promise<unknown>;
|
||||||
resolveRoute: (name: string, env: RequestEnvelope) => Promise<ResponseShape>;
|
resolveRoute: (name: string, env: RequestEnvelope) => Promise<ResponseShape>;
|
||||||
bus?: Bus;
|
bus?: Bus;
|
||||||
|
/**
|
||||||
|
* The largest request body this teapot accepts, which sizes the control frames it parses
|
||||||
|
* ({@link controlFrameLimit}). Defaults to the 1 MB body default.
|
||||||
|
*/
|
||||||
|
maxBodyBytes?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The rpc-req member of the {@link Frame} union. */
|
/** The rpc-req member of the {@link Frame} union. */
|
||||||
@@ -113,6 +134,9 @@ function handleHandshake(socket: WsSocket, frame: Frame, deps: MeshControlDeps):
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The peer holds the secret now: lift the hello-sized bounds its socket was given to the ones
|
||||||
|
// that carry RPC bodies (#120, #148). A socket bounded without a second phase is left as it is.
|
||||||
|
widenInbound(socket);
|
||||||
socket.send(
|
socket.send(
|
||||||
encode({
|
encode({
|
||||||
type: 'manifest',
|
type: 'manifest',
|
||||||
@@ -187,6 +211,7 @@ async function serveFrames(
|
|||||||
deps: MeshControlDeps,
|
deps: MeshControlDeps,
|
||||||
exportedScopes: Set<string>,
|
exportedScopes: Set<string>,
|
||||||
exportedRoutes: Set<string>,
|
exportedRoutes: Set<string>,
|
||||||
|
maxFrameChars: number,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
let authed = false;
|
let authed = false;
|
||||||
// Armed before the loop, and cleared by the handshake. An unauthenticated peer that simply
|
// Armed before the loop, and cleared by the handshake. An unauthenticated peer that simply
|
||||||
@@ -200,8 +225,9 @@ async function serveFrames(
|
|||||||
for await (const data of socket.inbound) {
|
for await (const data of socket.inbound) {
|
||||||
const raw = String(data);
|
const raw = String(data);
|
||||||
|
|
||||||
// Checked before `decode`, because decoding is the expensive part being defended.
|
// Checked before `decode`, because decoding is the expensive part being defended. Until the
|
||||||
if (raw.length > MAX_FRAME_CHARS) {
|
// handshake, nothing larger than a hello is parsed, whatever the socket in front allowed.
|
||||||
|
if (raw.length > (authed ? maxFrameChars : HELLO_FRAME_BYTES)) {
|
||||||
socket.close(1009, 'mesh frame too large');
|
socket.close(1009, 'mesh frame too large');
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -244,13 +270,22 @@ async function serveFrames(
|
|||||||
/** Build a control handler that authenticates peers and serves scope/route RPCs from the manifest. */
|
/** Build a control handler that authenticates peers and serves scope/route RPCs from the manifest. */
|
||||||
export function createMeshControl(deps: MeshControlDeps): {
|
export function createMeshControl(deps: MeshControlDeps): {
|
||||||
path: string;
|
path: string;
|
||||||
|
maxFrameBytes: number;
|
||||||
handle: (socket: WsSocket) => Promise<void>;
|
handle: (socket: WsSocket) => Promise<void>;
|
||||||
} {
|
} {
|
||||||
const exportedScopes = new Set(deps.manifest.steps);
|
const exportedScopes = new Set(deps.manifest.steps);
|
||||||
const exportedRoutes = new Set(deps.manifest.routes.map((route) => `${route.method} ${route.pattern}`));
|
const exportedRoutes = new Set(deps.manifest.routes.map((route) => `${route.method} ${route.pattern}`));
|
||||||
|
const maxFrameChars = controlFrameLimit(deps.maxBodyBytes);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
path: MESH_CONTROL_PATH,
|
path: MESH_CONTROL_PATH,
|
||||||
|
/**
|
||||||
|
* The inbound bound a server puts on this channel's WebSocket in place of
|
||||||
|
* `limits.maxWsMessageBytes` (#120). The same figure as the character check below: the two agree
|
||||||
|
* on ASCII, and on other text the byte bound is the one that binds — a body measured in bytes by
|
||||||
|
* `maxBodyBytes` stays about that many bytes inside the envelope, so it still fits.
|
||||||
|
*/
|
||||||
|
maxFrameBytes: maxFrameChars,
|
||||||
/**
|
/**
|
||||||
* Resolves when the connection ends, mirroring `runWsConnection` — so `app.upgrade` can await
|
* Resolves when the connection ends, mirroring `runWsConnection` — so `app.upgrade` can await
|
||||||
* the control channel's lifetime the same way it awaits a regular ws route's.
|
* the control channel's lifetime the same way it awaits a regular ws route's.
|
||||||
@@ -258,7 +293,7 @@ export function createMeshControl(deps: MeshControlDeps): {
|
|||||||
* does synchronously, so the loop is live before any frame can arrive.
|
* does synchronously, so the loop is live before any frame can arrive.
|
||||||
*/
|
*/
|
||||||
handle(socket: WsSocket): Promise<void> {
|
handle(socket: WsSocket): Promise<void> {
|
||||||
return serveFrames(socket, deps, exportedScopes, exportedRoutes);
|
return serveFrames(socket, deps, exportedScopes, exportedRoutes, maxFrameChars);
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -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`);
|
||||||
|
});
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
// #120 (CARD-24, D22) on Bun: an RPC whose body is within `maxBodyBytes` reaches the teapot,
|
||||||
|
// although the control channel is a WebSocket bounded like every other. Node twin:
|
||||||
|
// test/mesh/large-body.test.ts, which explains the cases.
|
||||||
|
//
|
||||||
|
// Run with: npm run test:bun
|
||||||
|
import 'reflect-metadata';
|
||||||
|
import { test, expect } from 'bun:test';
|
||||||
|
import { createApp, Route, Post, Module, Ws, body, ctx } from '../../src/index.ts';
|
||||||
|
import { serveBun } from '../../src/bun.ts';
|
||||||
|
|
||||||
|
const SECRET = 's3cr3t';
|
||||||
|
const WRAP = '{"data":""}'.length;
|
||||||
|
|
||||||
|
@Route('/big')
|
||||||
|
class BigCtl {
|
||||||
|
@Post('/echo', { export: true })
|
||||||
|
echo(@body() b: { data: string } | string) {
|
||||||
|
return { length: typeof b === 'string' ? b.length : b.data.length };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Ws('/sock')
|
||||||
|
sock(@ctx() { inbound }: any) {
|
||||||
|
return (async function* () {
|
||||||
|
for await (const msg of inbound) yield `echo:${String(msg).length}`;
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Never reads `inbound`: every frame stays queued, so the 17th closes 1013 (#107).
|
||||||
|
@Ws('/stall')
|
||||||
|
stall() {
|
||||||
|
return (async function* () {
|
||||||
|
await new Promise<never>(() => {});
|
||||||
|
yield '';
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/api', controllers: [BigCtl] })
|
||||||
|
class TeapotModule {}
|
||||||
|
|
||||||
|
@Module({ mountpoint: '/api' })
|
||||||
|
class TeacupModule {}
|
||||||
|
|
||||||
|
async function serve(app: ReturnType<typeof createApp>) {
|
||||||
|
const server = await serveBun(app, { port: 0 });
|
||||||
|
return { server, port: server.port };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pair(maxBodyBytes?: number) {
|
||||||
|
const limits = maxBodyBytes ? { maxBodyBytes } : undefined;
|
||||||
|
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET }, limits });
|
||||||
|
const t = await serve(teapot);
|
||||||
|
const url = `ws://127.0.0.1:${t.port}/__mesh__/control`;
|
||||||
|
const teacup = createApp({
|
||||||
|
modules: [TeacupModule],
|
||||||
|
experimental: true,
|
||||||
|
mesh: { teapots: [{ url, secret: SECRET }] },
|
||||||
|
limits,
|
||||||
|
});
|
||||||
|
const c = await serve(teacup);
|
||||||
|
const post = (payload: string, type = 'application/json') =>
|
||||||
|
fetch(`http://127.0.0.1:${c.port}/api/big/echo`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'content-type': type },
|
||||||
|
body: payload,
|
||||||
|
});
|
||||||
|
const close = async () => {
|
||||||
|
await teacup.close();
|
||||||
|
await teapot.close();
|
||||||
|
c.server.stop(true);
|
||||||
|
t.server.stop(true);
|
||||||
|
};
|
||||||
|
return { post, close, tPort: t.port, teacup };
|
||||||
|
}
|
||||||
|
|
||||||
|
const json = (bytes: number) => JSON.stringify({ data: 'x'.repeat(bytes - WRAP) });
|
||||||
|
|
||||||
|
test('mesh on Bun: a 1 MB JSON body reaches the teapot (T1)', async () => {
|
||||||
|
const { post, close } = await pair();
|
||||||
|
try {
|
||||||
|
const res = await post(json(1_000_000));
|
||||||
|
expect(res.status).toEqual(200);
|
||||||
|
expect(await res.json()).toEqual({ length: 1_000_000 - WRAP });
|
||||||
|
expect((await post(json(1_000_000))).status).toEqual(200);
|
||||||
|
} finally {
|
||||||
|
await close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('mesh on Bun: a text body that JSON escaping doubles still reaches the teapot (T1b)', async () => {
|
||||||
|
const { post, close } = await pair();
|
||||||
|
try {
|
||||||
|
const res = await post('"'.repeat(999_000), 'text/plain');
|
||||||
|
expect(res.status).toEqual(200);
|
||||||
|
expect(await res.json()).toEqual({ length: 999_000 });
|
||||||
|
expect((await post('ok', 'text/plain')).status).toEqual(200);
|
||||||
|
} finally {
|
||||||
|
await close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('mesh on Bun: a text body of control characters, escaped 6x, still reaches the teapot (T1c)', async () => {
|
||||||
|
const { post, close } = await pair();
|
||||||
|
try {
|
||||||
|
const res = await post('\u0001'.repeat(999_000), 'text/plain');
|
||||||
|
expect(res.status).toEqual(200);
|
||||||
|
expect(await res.json()).toEqual({ length: 999_000 });
|
||||||
|
expect((await post('ok', 'text/plain')).status).toEqual(200);
|
||||||
|
} finally {
|
||||||
|
await close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('mesh on Bun: a body over maxBodyBytes is 413, and the channel stays open (T2)', async () => {
|
||||||
|
const { post, close, teacup } = await pair();
|
||||||
|
try {
|
||||||
|
// Through `app.fetch`, not the socket: a client still writing a 1 MB body when Bun's 413 lands
|
||||||
|
// can stall or reset (see body-limits.test.ts). That race is the transport's, not the mesh's.
|
||||||
|
const over = new Request('http://x/api/big/echo', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'content-type': 'application/json' },
|
||||||
|
body: json(1_000_001),
|
||||||
|
});
|
||||||
|
expect((await teacup.fetch(over)).status).toEqual(413);
|
||||||
|
expect((await post(json(1_000))).status).toEqual(200);
|
||||||
|
} finally {
|
||||||
|
await close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
// A teapot raises Bun's native `maxPayloadLength` to the control channel's bound, so a user route's
|
||||||
|
// oversized frame is refused by `app.upgrade` instead, with a real 1009 close frame rather than the
|
||||||
|
// 1006 drop the native bound gives (see ws.test.ts).
|
||||||
|
test('mesh on Bun: a user ws route on the same teapot still closes 1009 over 1 MiB (T3)', async () => {
|
||||||
|
const { close, tPort } = await pair();
|
||||||
|
try {
|
||||||
|
const code = await new Promise<number>((resolve) => {
|
||||||
|
const ws = new WebSocket(`ws://127.0.0.1:${tPort}/api/big/sock`);
|
||||||
|
ws.onopen = () => ws.send('x'.repeat(1_048_577));
|
||||||
|
ws.onclose = (e) => resolve(e.code);
|
||||||
|
});
|
||||||
|
expect(code).toEqual(1009);
|
||||||
|
} finally {
|
||||||
|
await close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('mesh on Bun: the control-channel cap follows a raised maxBodyBytes (T4)', async () => {
|
||||||
|
const { post, close } = await pair(4_000_000);
|
||||||
|
try {
|
||||||
|
const res = await post(json(3_900_000));
|
||||||
|
expect(res.status).toEqual(200);
|
||||||
|
expect(await res.json()).toEqual({ length: 3_900_000 - WRAP });
|
||||||
|
} finally {
|
||||||
|
await close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('mesh on Bun: 64 concurrent RPCs on one link all succeed (#148)', async () => {
|
||||||
|
const { post, close, teacup } = await pair();
|
||||||
|
try {
|
||||||
|
// In one tick, through `app.fetch`: all 64 rpc-req frames leave together and land in one read,
|
||||||
|
// which is the burst that tripped the 16-frame queue. Over HTTP sockets they trickle in.
|
||||||
|
const rpc = () =>
|
||||||
|
teacup.fetch(
|
||||||
|
new Request('http://x/api/big/echo', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'content-type': 'application/json' },
|
||||||
|
body: json(100),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const res = await Promise.all(Array.from({ length: 64 }, rpc));
|
||||||
|
expect(res.map((r) => r.status)).toEqual(Array(64).fill(200));
|
||||||
|
expect((await post(json(1_000))).status).toEqual(200);
|
||||||
|
} finally {
|
||||||
|
await close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('mesh on Bun: a user ws route on the same teapot still closes 1013 at maxWsQueue (#148)', async () => {
|
||||||
|
const { close, tPort } = await pair();
|
||||||
|
try {
|
||||||
|
const code = await new Promise<number>((resolve) => {
|
||||||
|
const ws = new WebSocket(`ws://127.0.0.1:${tPort}/api/big/stall`);
|
||||||
|
ws.onopen = () => {
|
||||||
|
for (let i = 0; i < 17; i++) ws.send(String(i));
|
||||||
|
};
|
||||||
|
ws.onclose = (e) => resolve(e.code);
|
||||||
|
});
|
||||||
|
expect(code).toEqual(1013);
|
||||||
|
} finally {
|
||||||
|
await close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('mesh on Bun: an unauthenticated peer sending a frame over hello size is closed 1009', async () => {
|
||||||
|
const { close, tPort } = await pair();
|
||||||
|
try {
|
||||||
|
const code = await new Promise<number>((resolve) => {
|
||||||
|
const ws = new WebSocket(`ws://127.0.0.1:${tPort}/__mesh__/control`);
|
||||||
|
ws.onopen = () => ws.send('x'.repeat(1_000_000));
|
||||||
|
ws.onclose = (e) => resolve(e.code);
|
||||||
|
});
|
||||||
|
expect(code).toEqual(1009);
|
||||||
|
} finally {
|
||||||
|
await close();
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
// #41 (CARD-26, D23) on Bun: the outbound pump waits while the socket is backed up. Bun has no
|
||||||
|
// `bufferedAmount` property; the adapter reads `getBufferedAmount()` and waits on `drain`.
|
||||||
|
// Node twin: test/ws-backpressure.test.ts, which explains the cases.
|
||||||
|
//
|
||||||
|
// Run with: npm run test:bun
|
||||||
|
import 'reflect-metadata';
|
||||||
|
import { test, expect } from 'bun:test';
|
||||||
|
import { createApp, Route, Ws, Module } from '../../src/index.ts';
|
||||||
|
import { serveBun } from '../../src/bun.ts';
|
||||||
|
import { rawWs } from '../helpers/raw-ws.ts';
|
||||||
|
|
||||||
|
const FRAMES = 10_000;
|
||||||
|
const FRAME = 64 * 1024;
|
||||||
|
const frame = (i: number) => String(i).padStart(8, '0') + 'x'.repeat(FRAME - 8);
|
||||||
|
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
const state = { pulled: 0, returned: false };
|
||||||
|
|
||||||
|
@Route('/bp')
|
||||||
|
class Flood {
|
||||||
|
@Ws('/flood')
|
||||||
|
flood() {
|
||||||
|
return (async function* () {
|
||||||
|
try {
|
||||||
|
for (let i = 0; i < FRAMES; i++) {
|
||||||
|
state.pulled++;
|
||||||
|
yield frame(i);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
state.returned = true;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', controllers: [Flood] })
|
||||||
|
class M {}
|
||||||
|
|
||||||
|
async function serve() {
|
||||||
|
state.pulled = 0;
|
||||||
|
state.returned = false;
|
||||||
|
const server = await serveBun(createApp({ modules: [M] }), { port: 0 });
|
||||||
|
return { server, port: server.port };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('serveBun: ws outbound stops pulling while the client is not reading, then delivers in order (T1)', async () => {
|
||||||
|
const { server, port } = await serve();
|
||||||
|
try {
|
||||||
|
const client = await rawWs(port, '/bp/flood', FRAME);
|
||||||
|
client.pause();
|
||||||
|
await sleep(300);
|
||||||
|
const stalled = state.pulled;
|
||||||
|
await sleep(200);
|
||||||
|
expect(state.pulled).toBe(stalled);
|
||||||
|
expect(stalled).toBeLessThan(FRAMES / 10);
|
||||||
|
|
||||||
|
expect(await client.readAll(FRAMES)).toEqual({ received: FRAMES, inOrder: true });
|
||||||
|
expect(state.pulled).toBe(FRAMES);
|
||||||
|
client.destroy();
|
||||||
|
} finally {
|
||||||
|
server.stop(true);
|
||||||
|
}
|
||||||
|
}, 60_000);
|
||||||
|
|
||||||
|
test('serveBun: ws outbound ends the wait and calls return() when the client goes away (T2)', async () => {
|
||||||
|
const { server, port } = await serve();
|
||||||
|
try {
|
||||||
|
const client = await rawWs(port, '/bp/flood', FRAME);
|
||||||
|
client.pause();
|
||||||
|
await sleep(300);
|
||||||
|
expect(state.pulled).toBeLessThan(FRAMES / 10);
|
||||||
|
|
||||||
|
client.destroy();
|
||||||
|
await sleep(300);
|
||||||
|
expect(state.returned).toBe(true);
|
||||||
|
expect(state.pulled).toBeLessThan(FRAMES / 10);
|
||||||
|
} finally {
|
||||||
|
server.stop(true);
|
||||||
|
}
|
||||||
|
}, 60_000);
|
||||||
@@ -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);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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`);
|
||||||
|
});
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
// #120 (CARD-24, D22) on Deno: an RPC whose body is within `maxBodyBytes` reaches the teapot,
|
||||||
|
// although the control channel is a WebSocket bounded like every other. Node twin:
|
||||||
|
// test/mesh/large-body.test.ts, which explains the cases.
|
||||||
|
//
|
||||||
|
// Run with: npm run test:deno
|
||||||
|
import 'npm:reflect-metadata';
|
||||||
|
import { assertEquals } from 'jsr:@std/assert';
|
||||||
|
import { createApp, Route, Post, Module, Ws, body, ctx } from '../../src/index.ts';
|
||||||
|
import { serveDeno } from '../../src/deno.ts';
|
||||||
|
|
||||||
|
const SECRET = 's3cr3t';
|
||||||
|
const WRAP = '{"data":""}'.length;
|
||||||
|
|
||||||
|
@Route('/big')
|
||||||
|
class BigCtl {
|
||||||
|
@Post('/echo', { export: true })
|
||||||
|
echo(@body() b: { data: string } | string) {
|
||||||
|
return { length: typeof b === 'string' ? b.length : b.data.length };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Ws('/sock')
|
||||||
|
sock(@ctx() { inbound }: any) {
|
||||||
|
return (async function* () {
|
||||||
|
for await (const msg of inbound) yield `echo:${String(msg).length}`;
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Never reads `inbound`: every frame stays queued, so the 17th closes 1013 (#107).
|
||||||
|
@Ws('/stall')
|
||||||
|
stall() {
|
||||||
|
return (async function* () {
|
||||||
|
await new Promise<never>(() => {});
|
||||||
|
yield '';
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/api', controllers: [BigCtl] })
|
||||||
|
class TeapotModule {}
|
||||||
|
|
||||||
|
@Module({ mountpoint: '/api' })
|
||||||
|
class TeacupModule {}
|
||||||
|
|
||||||
|
async function serve(app: ReturnType<typeof createApp>) {
|
||||||
|
let port = 0;
|
||||||
|
const server = await serveDeno(app, {
|
||||||
|
port: 0,
|
||||||
|
onListen: (addr) => {
|
||||||
|
port = addr.port;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||||
|
return { server, port };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pair(maxBodyBytes?: number) {
|
||||||
|
const limits = maxBodyBytes ? { maxBodyBytes } : undefined;
|
||||||
|
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET }, limits });
|
||||||
|
const t = await serve(teapot);
|
||||||
|
const url = `ws://127.0.0.1:${t.port}/__mesh__/control`;
|
||||||
|
const teacup = createApp({
|
||||||
|
modules: [TeacupModule],
|
||||||
|
experimental: true,
|
||||||
|
mesh: { teapots: [{ url, secret: SECRET }] },
|
||||||
|
limits,
|
||||||
|
});
|
||||||
|
const c = await serve(teacup);
|
||||||
|
const post = (payload: string, type = 'application/json') =>
|
||||||
|
fetch(`http://127.0.0.1:${c.port}/api/big/echo`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'content-type': type },
|
||||||
|
body: payload,
|
||||||
|
});
|
||||||
|
const close = async () => {
|
||||||
|
await teacup.close();
|
||||||
|
await teapot.close();
|
||||||
|
await c.server.shutdown();
|
||||||
|
await t.server.shutdown();
|
||||||
|
};
|
||||||
|
return { post, close, tPort: t.port, teacup };
|
||||||
|
}
|
||||||
|
|
||||||
|
const json = (bytes: number) => JSON.stringify({ data: 'x'.repeat(bytes - WRAP) });
|
||||||
|
|
||||||
|
Deno.test('mesh on Deno: a 1 MB JSON body reaches the teapot (T1)', async () => {
|
||||||
|
const { post, close } = await pair();
|
||||||
|
try {
|
||||||
|
const res = await post(json(1_000_000));
|
||||||
|
assertEquals(res.status, 200);
|
||||||
|
assertEquals(await res.json(), { length: 1_000_000 - WRAP });
|
||||||
|
assertEquals((await post(json(1_000_000))).status, 200);
|
||||||
|
} finally {
|
||||||
|
await close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Deno.test('mesh on Deno: a text body that JSON escaping doubles still reaches the teapot (T1b)', async () => {
|
||||||
|
const { post, close } = await pair();
|
||||||
|
try {
|
||||||
|
const res = await post('"'.repeat(999_000), 'text/plain');
|
||||||
|
assertEquals(res.status, 200);
|
||||||
|
assertEquals(await res.json(), { length: 999_000 });
|
||||||
|
assertEquals((await post('ok', 'text/plain')).status, 200);
|
||||||
|
} finally {
|
||||||
|
await close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Deno.test('mesh on Deno: a text body of control characters, escaped 6x, still reaches the teapot (T1c)', async () => {
|
||||||
|
const { post, close } = await pair();
|
||||||
|
try {
|
||||||
|
const res = await post('\u0001'.repeat(999_000), 'text/plain');
|
||||||
|
assertEquals(res.status, 200);
|
||||||
|
assertEquals(await res.json(), { length: 999_000 });
|
||||||
|
assertEquals((await post('ok', 'text/plain')).status, 200);
|
||||||
|
} finally {
|
||||||
|
await close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Deno.test('mesh on Deno: a body over maxBodyBytes is 413, and the channel stays open (T2)', async () => {
|
||||||
|
const { post, close } = await pair();
|
||||||
|
try {
|
||||||
|
assertEquals((await post(json(1_000_001))).status, 413);
|
||||||
|
assertEquals((await post(json(1_000))).status, 200);
|
||||||
|
} finally {
|
||||||
|
await close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Deno.test('mesh on Deno: a user ws route on the same teapot still closes 1009 over 1 MiB (T3)', async () => {
|
||||||
|
const { close, tPort } = await pair();
|
||||||
|
try {
|
||||||
|
const code = await new Promise<number>((resolve) => {
|
||||||
|
const ws = new WebSocket(`ws://127.0.0.1:${tPort}/api/big/sock`);
|
||||||
|
ws.onopen = () => ws.send('x'.repeat(1_048_577));
|
||||||
|
ws.onclose = (e) => resolve(e.code);
|
||||||
|
});
|
||||||
|
assertEquals(code, 1009);
|
||||||
|
} finally {
|
||||||
|
await close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Deno.test('mesh on Deno: the control-channel cap follows a raised maxBodyBytes (T4)', async () => {
|
||||||
|
const { post, close } = await pair(4_000_000);
|
||||||
|
try {
|
||||||
|
const res = await post(json(3_900_000));
|
||||||
|
assertEquals(res.status, 200);
|
||||||
|
assertEquals(await res.json(), { length: 3_900_000 - WRAP });
|
||||||
|
} finally {
|
||||||
|
await close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Deno.test('mesh on Deno: 64 concurrent RPCs on one link all succeed (#148)', async () => {
|
||||||
|
const { post, close, teacup } = await pair();
|
||||||
|
try {
|
||||||
|
// In one tick, through `app.fetch`: all 64 rpc-req frames leave together and land in one read,
|
||||||
|
// which is the burst that tripped the 16-frame queue. Over HTTP sockets they trickle in.
|
||||||
|
const rpc = () =>
|
||||||
|
teacup.fetch(
|
||||||
|
new Request('http://x/api/big/echo', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'content-type': 'application/json' },
|
||||||
|
body: json(100),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const res = await Promise.all(Array.from({ length: 64 }, rpc));
|
||||||
|
assertEquals(res.map((r) => r.status), Array(64).fill(200));
|
||||||
|
assertEquals((await post(json(1_000))).status, 200);
|
||||||
|
} finally {
|
||||||
|
await close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Deno.test('mesh on Deno: a user ws route on the same teapot still closes 1013 at maxWsQueue (#148)', async () => {
|
||||||
|
const { close, tPort } = await pair();
|
||||||
|
try {
|
||||||
|
const code = await new Promise<number>((resolve) => {
|
||||||
|
const ws = new WebSocket(`ws://127.0.0.1:${tPort}/api/big/stall`);
|
||||||
|
ws.onopen = () => {
|
||||||
|
for (let i = 0; i < 17; i++) ws.send(String(i));
|
||||||
|
};
|
||||||
|
ws.onclose = (e) => resolve(e.code);
|
||||||
|
});
|
||||||
|
assertEquals(code, 1013);
|
||||||
|
} finally {
|
||||||
|
await close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Deno.test('mesh on Deno: an unauthenticated peer sending a frame over hello size is closed 1009', async () => {
|
||||||
|
const { close, tPort } = await pair();
|
||||||
|
try {
|
||||||
|
const code = await new Promise<number>((resolve) => {
|
||||||
|
const ws = new WebSocket(`ws://127.0.0.1:${tPort}/__mesh__/control`);
|
||||||
|
ws.onopen = () => ws.send('x'.repeat(1_000_000));
|
||||||
|
ws.onclose = (e) => resolve(e.code);
|
||||||
|
});
|
||||||
|
assertEquals(code, 1009);
|
||||||
|
} finally {
|
||||||
|
await close();
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
// #41 (CARD-26, D23) on Deno: the outbound pump waits while the socket is backed up. Deno's
|
||||||
|
// WebSocket fires no drain event, so the adapter polls `bufferedAmount` while over the mark.
|
||||||
|
// Node twin: test/ws-backpressure.test.ts, which explains the cases.
|
||||||
|
//
|
||||||
|
// Run with: npm run test:deno
|
||||||
|
import 'npm:reflect-metadata';
|
||||||
|
import { assert, assertEquals } from 'jsr:@std/assert';
|
||||||
|
import { createApp, Route, Ws, Module } from '../../src/index.ts';
|
||||||
|
import { serveDeno } from '../../src/deno.ts';
|
||||||
|
import { rawWs } from '../helpers/raw-ws.ts';
|
||||||
|
|
||||||
|
const FRAMES = 10_000;
|
||||||
|
const FRAME = 64 * 1024;
|
||||||
|
const frame = (i: number) => String(i).padStart(8, '0') + 'x'.repeat(FRAME - 8);
|
||||||
|
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
const state = { pulled: 0, returned: false };
|
||||||
|
|
||||||
|
@Route('/bp')
|
||||||
|
class Flood {
|
||||||
|
@Ws('/flood')
|
||||||
|
flood() {
|
||||||
|
return (async function* () {
|
||||||
|
try {
|
||||||
|
for (let i = 0; i < FRAMES; i++) {
|
||||||
|
state.pulled++;
|
||||||
|
yield frame(i);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
state.returned = true;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Route('/early')
|
||||||
|
class Early {
|
||||||
|
// Yields before Deno's socket has left CONNECTING. The pump used to pull 'hi', find the socket
|
||||||
|
// not open, and give up: the client got no frame and a close without a code (1005).
|
||||||
|
@Ws('/hi')
|
||||||
|
hi() {
|
||||||
|
return (async function* () {
|
||||||
|
yield 'hi';
|
||||||
|
await new Promise<never>(() => {});
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', controllers: [Flood, Early] })
|
||||||
|
class M {}
|
||||||
|
|
||||||
|
async function serve() {
|
||||||
|
state.pulled = 0;
|
||||||
|
state.returned = false;
|
||||||
|
let port = 0;
|
||||||
|
const server = await serveDeno(createApp({ modules: [M] }), {
|
||||||
|
port: 0,
|
||||||
|
onListen: (addr) => {
|
||||||
|
port = addr.port;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await sleep(50);
|
||||||
|
return { server, port };
|
||||||
|
}
|
||||||
|
|
||||||
|
Deno.test('serveDeno: ws outbound stops pulling while the client is not reading, then delivers in order (T1)', async () => {
|
||||||
|
const { server, port } = await serve();
|
||||||
|
try {
|
||||||
|
const client = await rawWs(port, '/bp/flood', FRAME);
|
||||||
|
client.pause();
|
||||||
|
await sleep(300);
|
||||||
|
const stalled = state.pulled;
|
||||||
|
await sleep(200);
|
||||||
|
assertEquals(state.pulled, stalled);
|
||||||
|
assert(stalled < FRAMES / 10, `pulled ${stalled} of ${FRAMES} with nobody reading`);
|
||||||
|
|
||||||
|
assertEquals(await client.readAll(FRAMES), { received: FRAMES, inOrder: true });
|
||||||
|
assertEquals(state.pulled, FRAMES);
|
||||||
|
client.destroy();
|
||||||
|
} finally {
|
||||||
|
await server.shutdown();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Deno.test('serveDeno: ws outbound ends the wait and calls return() when the client goes away (T2)', async () => {
|
||||||
|
const { server, port } = await serve();
|
||||||
|
try {
|
||||||
|
const client = await rawWs(port, '/bp/flood', FRAME);
|
||||||
|
client.pause();
|
||||||
|
await sleep(300);
|
||||||
|
assert(state.pulled < FRAMES / 10);
|
||||||
|
|
||||||
|
client.destroy();
|
||||||
|
await sleep(300);
|
||||||
|
assertEquals(state.returned, true);
|
||||||
|
assert(state.pulled < FRAMES / 10);
|
||||||
|
} finally {
|
||||||
|
await server.shutdown();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Deno.test('serveDeno: a ws route that yields at once still delivers its first frame', async () => {
|
||||||
|
const { server, port } = await serve();
|
||||||
|
try {
|
||||||
|
const first = await new Promise<string>((resolve, reject) => {
|
||||||
|
const ws = new WebSocket(`ws://127.0.0.1:${port}/early/hi`);
|
||||||
|
ws.onmessage = (e) => {
|
||||||
|
resolve(String(e.data));
|
||||||
|
ws.close();
|
||||||
|
};
|
||||||
|
ws.onclose = (e) => reject(new Error(`closed ${e.code} before any frame`));
|
||||||
|
});
|
||||||
|
assertEquals(first, 'hi');
|
||||||
|
} finally {
|
||||||
|
await server.shutdown();
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -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),
|
||||||
|
};
|
||||||
@@ -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);
|
||||||
|
});
|
||||||
Vendored
+143
@@ -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 });
|
||||||
Vendored
+160
@@ -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');
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
// A WebSocket client over a bare `node:net` socket, for the backpressure tests (#41) on Deno and
|
||||||
|
// Bun. The platform `WebSocket` reads as fast as it can and cannot be told to stop; a TCP socket
|
||||||
|
// can be paused, which is the "client reads slowly" those tests need. Server frames are unmasked,
|
||||||
|
// and every frame these tests send is the same size, so frames are found by offset alone.
|
||||||
|
import net from 'node:net';
|
||||||
|
|
||||||
|
export interface RawWs {
|
||||||
|
/** Stop reading: the server's send buffer is all that can grow. */
|
||||||
|
pause(): void;
|
||||||
|
/** Resume reading; resolves once `count` frames have arrived, reporting whether they were in order. */
|
||||||
|
readAll(count: number): Promise<{ received: number; inOrder: boolean }>;
|
||||||
|
destroy(): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Opens `ws://127.0.0.1:<port><path>` and resolves once the 101 is in. Each server frame must be
|
||||||
|
* a text frame of exactly `payload` bytes (> 65535, so a 10-byte header) whose first 8 bytes are
|
||||||
|
* its zero-padded index.
|
||||||
|
*/
|
||||||
|
export function rawWs(port: number, path: string, payload: number): Promise<RawWs> {
|
||||||
|
const total = payload + 10;
|
||||||
|
const socket = net.connect(port, '127.0.0.1');
|
||||||
|
let head = '';
|
||||||
|
let upgraded = false;
|
||||||
|
let pos = 0;
|
||||||
|
let digits = '';
|
||||||
|
let received = 0;
|
||||||
|
let inOrder = true;
|
||||||
|
let onFrame = () => {};
|
||||||
|
|
||||||
|
const consume = (chunk: Uint8Array) => {
|
||||||
|
let i = 0;
|
||||||
|
while (i < chunk.length) {
|
||||||
|
if (pos < 18) {
|
||||||
|
if (pos === 0 && chunk[i] !== 0x81) inOrder = false;
|
||||||
|
if (pos >= 10) digits += String.fromCharCode(chunk[i]);
|
||||||
|
if (pos === 17) {
|
||||||
|
if (Number(digits) !== received) inOrder = false;
|
||||||
|
digits = '';
|
||||||
|
}
|
||||||
|
pos++;
|
||||||
|
i++;
|
||||||
|
} else {
|
||||||
|
const skip = Math.min(total - pos, chunk.length - i);
|
||||||
|
pos += skip;
|
||||||
|
i += skip;
|
||||||
|
}
|
||||||
|
if (pos === total) {
|
||||||
|
pos = 0;
|
||||||
|
received++;
|
||||||
|
onFrame();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
socket.once('error', reject);
|
||||||
|
socket.on('data', (chunk: Uint8Array) => {
|
||||||
|
if (upgraded) return consume(chunk);
|
||||||
|
head += new TextDecoder('latin1').decode(chunk);
|
||||||
|
const end = head.indexOf('\r\n\r\n');
|
||||||
|
if (end < 0) return;
|
||||||
|
upgraded = true;
|
||||||
|
const rest = chunk.subarray(chunk.length - (head.length - end - 4));
|
||||||
|
resolve({
|
||||||
|
pause: () => socket.pause(),
|
||||||
|
readAll: (count) =>
|
||||||
|
new Promise((done) => {
|
||||||
|
onFrame = () => {
|
||||||
|
if (received === count) done({ received, inOrder });
|
||||||
|
};
|
||||||
|
socket.resume();
|
||||||
|
}),
|
||||||
|
destroy: () => socket.destroy(),
|
||||||
|
});
|
||||||
|
consume(rest);
|
||||||
|
});
|
||||||
|
socket.write(
|
||||||
|
`GET ${path} HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n` +
|
||||||
|
'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
// Before a peer's `hello` is accepted, the mesh control channel takes only hello-sized frames and
|
||||||
|
// a small queue. The large bounds that carry RPC bodies (#120, #148) apply after authentication
|
||||||
|
// only, so an unauthenticated peer cannot make the process buffer `queue × frame` bytes — which
|
||||||
|
// at 4,096 × 7 MB was tens of GB, reachable while `app.upgrade` waits for a slow boot.
|
||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { createApp, Module, Provider, Step } from '../../src/index';
|
||||||
|
import { channel } from '../../src/channel';
|
||||||
|
import { MESH_CONTROL_PATH } from '../../src/mesh/teapot';
|
||||||
|
import { encode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol';
|
||||||
|
import type { WsSocket, WsRequest } from '../../src/http/ws-core';
|
||||||
|
|
||||||
|
@Provider({ provides: 'slow' })
|
||||||
|
class Slow {
|
||||||
|
async provide() {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 300));
|
||||||
|
return { slow: true };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Step({ provides: 'cfg', needs: [], export: true })
|
||||||
|
class Cfg {
|
||||||
|
run() {
|
||||||
|
return { cfg: 1 };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/api', providers: [Slow], steps: [Cfg] })
|
||||||
|
class SlowTeapot {}
|
||||||
|
|
||||||
|
function fakeSocket() {
|
||||||
|
const inbound = channel<unknown>();
|
||||||
|
const ac = new AbortController();
|
||||||
|
const sent: string[] = [];
|
||||||
|
const closes: number[] = [];
|
||||||
|
const socket: WsSocket = {
|
||||||
|
inbound,
|
||||||
|
abort: ac.signal,
|
||||||
|
get isOpen() {
|
||||||
|
return !ac.signal.aborted;
|
||||||
|
},
|
||||||
|
send: (d) => sent.push(d),
|
||||||
|
close: (code) => {
|
||||||
|
if (ac.signal.aborted) return;
|
||||||
|
closes.push(code ?? 1005);
|
||||||
|
ac.abort();
|
||||||
|
inbound.close();
|
||||||
|
},
|
||||||
|
terminate: () => ac.abort(),
|
||||||
|
};
|
||||||
|
return { socket, inbound, sent, closes };
|
||||||
|
}
|
||||||
|
|
||||||
|
const req: WsRequest = { url: MESH_CONTROL_PATH, headers: {}, protocol: 'http', ip: '' };
|
||||||
|
const teapot = () => createApp({ modules: [SlowTeapot], experimental: true, mesh: { secret: 's3cr3t' } });
|
||||||
|
|
||||||
|
describe('mesh control channel before authentication', () => {
|
||||||
|
it('closes 1009 on a frame over hello size while the boot is still running', async () => {
|
||||||
|
const app = teapot();
|
||||||
|
const { socket, inbound, closes } = fakeSocket();
|
||||||
|
const run = app.upgrade(req, socket);
|
||||||
|
|
||||||
|
inbound.push('x'.repeat(1_000_000));
|
||||||
|
expect(closes).toEqual([1009]); // at once: the boot has not finished, nothing was buffered
|
||||||
|
await run;
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('closes 1013 when an unauthenticated peer floods frames during the boot', async () => {
|
||||||
|
const app = teapot();
|
||||||
|
const { socket, inbound, closes } = fakeSocket();
|
||||||
|
const run = app.upgrade(req, socket);
|
||||||
|
|
||||||
|
let accepted = 0;
|
||||||
|
for (let i = 0; i < 64 && !closes.length; i++, accepted++) inbound.push('x'.repeat(1024));
|
||||||
|
expect(closes).toEqual([1013]);
|
||||||
|
expect(accepted).toBeLessThanOrEqual(17); // the user default, not the authenticated 4,096
|
||||||
|
await run;
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lifts the bounds once the hello is accepted', async () => {
|
||||||
|
const app = teapot();
|
||||||
|
const { socket, inbound, sent, closes } = fakeSocket();
|
||||||
|
const run = app.upgrade(req, socket);
|
||||||
|
|
||||||
|
inbound.push(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: 's3cr3t' }));
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 400)); // boot, then the handshake
|
||||||
|
expect(JSON.parse(sent[0]).type).toBe('manifest');
|
||||||
|
|
||||||
|
// A frame far over hello size is accepted now (undecodable, so ignored), and a burst of 64
|
||||||
|
// fits the authenticated queue.
|
||||||
|
inbound.push('x'.repeat(1_000_000));
|
||||||
|
for (let i = 0; i < 64; i++) inbound.push(encode({ type: 'ping' }));
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||||
|
expect(closes).toEqual([]);
|
||||||
|
expect(sent.filter((s) => s.includes('pong'))).toHaveLength(64);
|
||||||
|
|
||||||
|
socket.close(1000);
|
||||||
|
await run;
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest';
|
|||||||
import { WebSocketServer } from 'ws';
|
import { WebSocketServer } from 'ws';
|
||||||
import { connectLink } from '../../src/mesh/link';
|
import { connectLink } from '../../src/mesh/link';
|
||||||
import { envelopeFrom } from '../../src/mesh/teacup';
|
import { envelopeFrom } from '../../src/mesh/teacup';
|
||||||
import { createMeshControl } from '../../src/mesh/teapot';
|
import { controlFrameLimit, createMeshControl } from '../../src/mesh/teapot';
|
||||||
import { encode, decode, MESH_PROTOCOL_VERSION, type RequestEnvelope } from '../../src/mesh/protocol';
|
import { encode, decode, MESH_PROTOCOL_VERSION, type RequestEnvelope } from '../../src/mesh/protocol';
|
||||||
import { Bus } from '../../src/bus';
|
import { Bus } from '../../src/bus';
|
||||||
import { createApp, Step, Route, Get, Module, needs } from '../../src/index';
|
import { createApp, Step, Route, Get, Module, needs } from '../../src/index';
|
||||||
@@ -139,7 +139,7 @@ describe('teapot hardening', () => {
|
|||||||
const fake = fakeSocket();
|
const fake = fakeSocket();
|
||||||
const running = control().handle(fake.socket as never);
|
const running = control().handle(fake.socket as never);
|
||||||
|
|
||||||
fake.feed(`{"type":"hello","v":${V},"secret":"${'a'.repeat(4_000_001)}"}`);
|
fake.feed(`{"type":"hello","v":${V},"secret":"${'a'.repeat(controlFrameLimit() + 1)}"}`);
|
||||||
await running;
|
await running;
|
||||||
|
|
||||||
expect(fake.closes[0]?.code).toBe(1009);
|
expect(fake.closes[0]?.code).toBe(1009);
|
||||||
|
|||||||
@@ -311,3 +311,53 @@ describe('mesh: Set-Cookie arrays (CARD-14, T10)', () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
// #120 (CARD-24, D22): an RPC whose body is within `maxBodyBytes` must reach the teapot.
|
||||||
|
//
|
||||||
|
// The control channel is a WebSocket, and every WebSocket was bounded by
|
||||||
|
// `limits.maxWsMessageBytes` (1 MiB by default, #107). A body at the HTTP limit (1,000,000 B by
|
||||||
|
// default) travels inside an `rpc-req` envelope, re-encoded as JSON:
|
||||||
|
// - a JSON body re-encodes to about its own size, so 1 MB fits under 1 MiB (T1);
|
||||||
|
// - a text body does not: every `"` or `\` doubles under JSON escaping, so a 999 KB text body
|
||||||
|
// became a ~2 MB frame and the teapot hung up the whole channel with 1009 (T1b);
|
||||||
|
// - a raised `maxBodyBytes` was capped at 1 MiB on the channel regardless (T4).
|
||||||
|
// Its queue bound had the same problem (#148): `maxWsQueue` (16) closed it 1013 under a burst of
|
||||||
|
// RPCs, which Node's `ws` delivers in one go. The Deno and Bun twins live in test/deno and test/bun.
|
||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import WebSocket from 'ws';
|
||||||
|
import { createApp, Route, Post, Module, Ws, body, ctx } from '../../src/index';
|
||||||
|
|
||||||
|
const SECRET = 's3cr3t';
|
||||||
|
const WRAP = '{"data":""}'.length;
|
||||||
|
|
||||||
|
@Route('/big')
|
||||||
|
class BigCtl {
|
||||||
|
@Post('/echo', { export: true })
|
||||||
|
echo(@body() b: { data: string } | string) {
|
||||||
|
return { length: typeof b === 'string' ? b.length : b.data.length };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Ws('/sock')
|
||||||
|
sock(@ctx() { inbound }: any) {
|
||||||
|
return (async function* () {
|
||||||
|
for await (const msg of inbound) yield `echo:${String(msg).length}`;
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Never reads `inbound`: every frame stays queued, so the 17th closes 1013 (#107).
|
||||||
|
@Ws('/stall')
|
||||||
|
stall() {
|
||||||
|
return (async function* () {
|
||||||
|
await new Promise<never>(() => {});
|
||||||
|
yield '';
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/api', controllers: [BigCtl] })
|
||||||
|
class TeapotModule {}
|
||||||
|
|
||||||
|
@Module({ mountpoint: '/api' })
|
||||||
|
class TeacupModule {}
|
||||||
|
|
||||||
|
/** A JSON body of exactly `bytes` bytes: `{"data":"xxx…"}`. */
|
||||||
|
const json = (bytes: number) => JSON.stringify({ data: 'x'.repeat(bytes - WRAP) });
|
||||||
|
|
||||||
|
async function pair(maxBodyBytes?: number) {
|
||||||
|
const limits = maxBodyBytes ? { maxBodyBytes } : undefined;
|
||||||
|
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET }, limits });
|
||||||
|
const tServer = await teapot.listen(0);
|
||||||
|
const tPort = (tServer.address() as any).port;
|
||||||
|
const url = `ws://127.0.0.1:${tPort}/__mesh__/control`;
|
||||||
|
const teacup = createApp({ modules: [TeacupModule], experimental: true, mesh: { teapots: [{ url, secret: SECRET }] }, limits });
|
||||||
|
const cServer = await teacup.listen(0);
|
||||||
|
const cPort = (cServer.address() as any).port;
|
||||||
|
const post = (payload: string, type = 'application/json') =>
|
||||||
|
fetch(`http://127.0.0.1:${cPort}/api/big/echo`, { method: 'POST', headers: { 'content-type': type }, body: payload });
|
||||||
|
const close = async () => {
|
||||||
|
await teacup.close();
|
||||||
|
await teapot.close();
|
||||||
|
};
|
||||||
|
return { post, close, tPort, teacup };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('mesh RPC body near maxBodyBytes (#120)', () => {
|
||||||
|
it('a 1 MB JSON body reaches the teapot, and the channel stays open (T1)', async () => {
|
||||||
|
const { post, close } = await pair();
|
||||||
|
try {
|
||||||
|
const res = await post(json(1_000_000));
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(await res.json()).toEqual({ length: 1_000_000 - WRAP });
|
||||||
|
expect((await post(json(1_000_000))).status).toBe(200);
|
||||||
|
} finally {
|
||||||
|
await close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a text body that JSON escaping doubles still reaches the teapot (T1b)', async () => {
|
||||||
|
const { post, close } = await pair();
|
||||||
|
try {
|
||||||
|
const res = await post('"'.repeat(999_000), 'text/plain');
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(await res.json()).toEqual({ length: 999_000 });
|
||||||
|
expect((await post('ok', 'text/plain')).status).toBe(200);
|
||||||
|
} finally {
|
||||||
|
await close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a text body of control characters, escaped 6x, still reaches the teapot (T1c)', async () => {
|
||||||
|
const { post, close } = await pair();
|
||||||
|
try {
|
||||||
|
// `\u0001` re-encodes as the six characters `\u0001`: the worst escaping a body can get.
|
||||||
|
const res = await post('\u0001'.repeat(999_000), 'text/plain');
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(await res.json()).toEqual({ length: 999_000 });
|
||||||
|
expect((await post('ok', 'text/plain')).status).toBe(200);
|
||||||
|
} finally {
|
||||||
|
await close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a body over maxBodyBytes is refused 413 by the teacup, and the channel stays open (T2)', async () => {
|
||||||
|
const { post, close } = await pair();
|
||||||
|
try {
|
||||||
|
expect((await post(json(1_000_001))).status).toBe(413);
|
||||||
|
expect((await post(json(1_000))).status).toBe(200);
|
||||||
|
} finally {
|
||||||
|
await close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("a user ws route on the same teapot still closes 1009 over maxWsMessageBytes (T3)", async () => {
|
||||||
|
const { close, tPort } = await pair();
|
||||||
|
try {
|
||||||
|
const ws = new WebSocket(`ws://127.0.0.1:${tPort}/api/big/sock`);
|
||||||
|
await new Promise((resolve) => ws.once('open', resolve));
|
||||||
|
const closed = new Promise<number>((resolve) => ws.once('close', (code) => resolve(code)));
|
||||||
|
ws.send('x'.repeat(1_048_577));
|
||||||
|
expect(await closed).toBe(1009);
|
||||||
|
} finally {
|
||||||
|
await close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('the control-channel cap follows a raised maxBodyBytes (T4)', async () => {
|
||||||
|
const { post, close } = await pair(4_000_000);
|
||||||
|
try {
|
||||||
|
const res = await post(json(3_900_000));
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(await res.json()).toEqual({ length: 3_900_000 - WRAP });
|
||||||
|
} finally {
|
||||||
|
await close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
it('64 concurrent RPCs on one link all succeed: the control channel has its own queue bound (#148)', async () => {
|
||||||
|
const { post, close, teacup } = await pair();
|
||||||
|
try {
|
||||||
|
// In one tick, through `app.fetch`: all 64 rpc-req frames leave together and land in one read,
|
||||||
|
// which is the burst that tripped the 16-frame queue. Over HTTP sockets they trickle in.
|
||||||
|
const rpc = () =>
|
||||||
|
teacup.fetch(
|
||||||
|
new Request('http://x/api/big/echo', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'content-type': 'application/json' },
|
||||||
|
body: json(100),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const res = await Promise.all(Array.from({ length: 64 }, rpc));
|
||||||
|
expect(res.map((r) => r.status)).toEqual(Array(64).fill(200));
|
||||||
|
expect((await post(json(1_000))).status).toBe(200);
|
||||||
|
} finally {
|
||||||
|
await close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a user ws route on the same teapot still closes 1013 at maxWsQueue (#148)', async () => {
|
||||||
|
const { close, tPort } = await pair();
|
||||||
|
try {
|
||||||
|
const ws = new WebSocket(`ws://127.0.0.1:${tPort}/api/big/stall`);
|
||||||
|
await new Promise((resolve) => ws.once('open', resolve));
|
||||||
|
const closed = new Promise<number>((resolve) => ws.once('close', (code) => resolve(code)));
|
||||||
|
for (let i = 0; i < 17; i++) ws.send(String(i));
|
||||||
|
expect(await closed).toBe(1013);
|
||||||
|
} finally {
|
||||||
|
await close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
it('an unauthenticated peer sending a frame over hello size is closed 1009', async () => {
|
||||||
|
const { close, tPort } = await pair();
|
||||||
|
try {
|
||||||
|
const ws = new WebSocket(`ws://127.0.0.1:${tPort}/__mesh__/control`);
|
||||||
|
await new Promise((resolve) => ws.once('open', resolve));
|
||||||
|
const closed = new Promise<number>((resolve) => ws.once('close', (code) => resolve(code)));
|
||||||
|
ws.send('x'.repeat(1_000_000)); // within the authenticated bound, far over a hello
|
||||||
|
expect(await closed).toBe(1009);
|
||||||
|
} finally {
|
||||||
|
await close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
// #41 (CARD-26, D23): the outbound pump waits while the socket is backed up.
|
||||||
|
//
|
||||||
|
// Over a real `ws` server on Node: a route that can produce 10,000 frames of 64 KiB (640 MiB)
|
||||||
|
// for a client that has stopped reading. Without backpressure the pump pulls all of them into
|
||||||
|
// the send buffer at once; with it, it stops pulling after about the high-water mark plus what
|
||||||
|
// the kernel's socket buffers absorb. The Deno and Bun twins live in test/deno and test/bun; the
|
||||||
|
// exact "mark plus one frame" bound is pinned with a fake socket in ws-core.test.ts.
|
||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import WebSocket from 'ws';
|
||||||
|
import { createHttpServer, type WsRouteDef } from '../src/http';
|
||||||
|
|
||||||
|
const FRAMES = 10_000;
|
||||||
|
const FRAME = 64 * 1024;
|
||||||
|
/** Frame `i`: its index, zero-padded, then filler up to 64 KiB. */
|
||||||
|
const frame = (i: number) => String(i).padStart(8, '0') + 'x'.repeat(FRAME - 8);
|
||||||
|
|
||||||
|
const url = (server: import('http').Server, path: string) => {
|
||||||
|
const a = server.address();
|
||||||
|
if (a && typeof a === 'object') return `ws://127.0.0.1:${a.port}${path}`;
|
||||||
|
throw new Error('no address');
|
||||||
|
};
|
||||||
|
|
||||||
|
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
|
||||||
|
describe('ws outbound backpressure (#41)', () => {
|
||||||
|
it('stops pulling while the client is not reading, then delivers every frame in order (T1)', async () => {
|
||||||
|
let pulled = 0;
|
||||||
|
const wsRoutes: WsRouteDef[] = [
|
||||||
|
{
|
||||||
|
pattern: '/flood',
|
||||||
|
open: async () =>
|
||||||
|
(async function* () {
|
||||||
|
for (let i = 0; i < FRAMES; i++) {
|
||||||
|
pulled++;
|
||||||
|
yield frame(i);
|
||||||
|
}
|
||||||
|
})(),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const server = createHttpServer([], wsRoutes);
|
||||||
|
await new Promise<void>((resolve) => server.listen(0, resolve));
|
||||||
|
|
||||||
|
const client = new WebSocket(url(server, '/flood'));
|
||||||
|
await new Promise((resolve) => client.once('upgrade', resolve));
|
||||||
|
// The client stops reading from TCP: the server's send buffer is all that can grow.
|
||||||
|
(client as any)._socket.pause();
|
||||||
|
|
||||||
|
await sleep(300);
|
||||||
|
const stalled = pulled;
|
||||||
|
await sleep(200);
|
||||||
|
|
||||||
|
// Pulling has stopped, far short of the 10,000 frames on offer: about the 1 MiB mark plus the
|
||||||
|
// kernel's socket buffers. Before #41 every frame was pulled at once, 640 MiB in memory.
|
||||||
|
expect(pulled).toBe(stalled);
|
||||||
|
expect(stalled).toBeLessThan(FRAMES / 10);
|
||||||
|
|
||||||
|
let next = 0;
|
||||||
|
let inOrder = true;
|
||||||
|
const done = new Promise<void>((resolve) => {
|
||||||
|
client.on('message', (data) => {
|
||||||
|
if (data.toString('latin1', 0, 8) !== String(next).padStart(8, '0')) inOrder = false;
|
||||||
|
if (++next === FRAMES) resolve();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
(client as any)._socket.resume();
|
||||||
|
await done;
|
||||||
|
|
||||||
|
expect(inOrder).toBe(true);
|
||||||
|
expect(pulled).toBe(FRAMES);
|
||||||
|
client.close();
|
||||||
|
server.close();
|
||||||
|
}, 60_000);
|
||||||
|
|
||||||
|
it('calls the iterator return() when the client goes away while the pump waits (T2)', async () => {
|
||||||
|
let pulled = 0;
|
||||||
|
let returned = false;
|
||||||
|
const wsRoutes: WsRouteDef[] = [
|
||||||
|
{
|
||||||
|
pattern: '/flood',
|
||||||
|
open: async () =>
|
||||||
|
(async function* () {
|
||||||
|
try {
|
||||||
|
for (let i = 0; i < FRAMES; i++) {
|
||||||
|
pulled++;
|
||||||
|
yield frame(i);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
returned = true;
|
||||||
|
}
|
||||||
|
})(),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const server = createHttpServer([], wsRoutes);
|
||||||
|
await new Promise<void>((resolve) => server.listen(0, resolve));
|
||||||
|
|
||||||
|
const client = new WebSocket(url(server, '/flood'));
|
||||||
|
await new Promise((resolve) => client.once('upgrade', resolve));
|
||||||
|
(client as any)._socket.pause();
|
||||||
|
await sleep(300);
|
||||||
|
expect(pulled).toBeLessThan(FRAMES / 10); // waiting, not finished
|
||||||
|
|
||||||
|
client.terminate();
|
||||||
|
await sleep(200);
|
||||||
|
|
||||||
|
expect(returned).toBe(true);
|
||||||
|
expect(pulled).toBeLessThan(FRAMES / 10);
|
||||||
|
server.close();
|
||||||
|
}, 30_000);
|
||||||
|
});
|
||||||
@@ -152,3 +152,106 @@ describe('runWsConnection correlation', () => {
|
|||||||
expect(open.transport).toBe('ws');
|
expect(open.transport).toBe('ws');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('runWsConnection outbound backpressure (#41)', () => {
|
||||||
|
/** A fake socket with a send buffer that only empties when the test says so. */
|
||||||
|
function bufferedSocket(mark: number) {
|
||||||
|
const fake = fakeSocket();
|
||||||
|
let buffered = 0;
|
||||||
|
let wake: (() => void) | null = null;
|
||||||
|
const socket: WsSocket = Object.assign(Object.create(fake.socket), {
|
||||||
|
send: (d: string) => {
|
||||||
|
fake.sent.push(d);
|
||||||
|
buffered += d.length;
|
||||||
|
},
|
||||||
|
drained: () =>
|
||||||
|
buffered <= mark || fake.ac.signal.aborted
|
||||||
|
? Promise.resolve()
|
||||||
|
: new Promise<void>((resolve) => {
|
||||||
|
wake = resolve;
|
||||||
|
fake.ac.signal.addEventListener('abort', () => resolve(), { once: true });
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const flush = () => {
|
||||||
|
buffered = 0;
|
||||||
|
wake?.();
|
||||||
|
wake = null;
|
||||||
|
};
|
||||||
|
return { ...fake, socket, flush, buffered: () => buffered };
|
||||||
|
}
|
||||||
|
|
||||||
|
const flood = (count: number, size: number, onPull: () => void, onReturn = () => {}) => ({
|
||||||
|
pattern: '/ws',
|
||||||
|
open: async () =>
|
||||||
|
(async function* () {
|
||||||
|
try {
|
||||||
|
for (let i = 0; i < count; i++) {
|
||||||
|
onPull();
|
||||||
|
yield String(i).padStart(size, '0');
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
onReturn();
|
||||||
|
}
|
||||||
|
})(),
|
||||||
|
});
|
||||||
|
|
||||||
|
it('pulls nothing more once the buffer is over the mark: it peaks at the mark plus one frame (T1)', async () => {
|
||||||
|
let pulled = 0;
|
||||||
|
const { socket, flush, buffered, sent } = bufferedSocket(10);
|
||||||
|
const run = runWsConnection(socket, req, { def: flood(100, 4, () => pulled++), params: {} });
|
||||||
|
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||||
|
expect(pulled).toBe(3); // 4 + 4 + 4 = 12 > 10: waits after the third frame
|
||||||
|
expect(buffered()).toBeLessThanOrEqual(10 + 4);
|
||||||
|
|
||||||
|
while (pulled < 100) {
|
||||||
|
flush();
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||||
|
}
|
||||||
|
flush();
|
||||||
|
await run;
|
||||||
|
expect(sent.map(Number)).toEqual([...Array(100).keys()]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ends the wait on close and calls the iterator return(), without an unhandled rejection (T2)', async () => {
|
||||||
|
let pulled = 0;
|
||||||
|
let returned = false;
|
||||||
|
const unhandled: unknown[] = [];
|
||||||
|
const onUnhandled = (err: unknown) => unhandled.push(err);
|
||||||
|
process.on('unhandledRejection', onUnhandled);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { socket, ac } = bufferedSocket(0);
|
||||||
|
const run = runWsConnection(socket, req, {
|
||||||
|
def: flood(100, 4, () => pulled++, () => (returned = true)),
|
||||||
|
params: {},
|
||||||
|
});
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||||
|
expect(pulled).toBe(1);
|
||||||
|
|
||||||
|
ac.abort(); // the peer went away
|
||||||
|
await run;
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||||
|
|
||||||
|
expect(returned).toBe(true);
|
||||||
|
expect(pulled).toBe(1);
|
||||||
|
expect(unhandled).toEqual([]);
|
||||||
|
} finally {
|
||||||
|
process.off('unhandledRejection', onUnhandled);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('never waits below the mark: drained() answers at once and every frame goes out (T3)', async () => {
|
||||||
|
let waits = 0;
|
||||||
|
const { socket, sent } = fakeSocket();
|
||||||
|
const counted: WsSocket = Object.assign(Object.create(socket), {
|
||||||
|
drained: () => {
|
||||||
|
waits++;
|
||||||
|
return Promise.resolve();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await runWsConnection(counted, req, { def: flood(50, 4, () => {}), params: {} });
|
||||||
|
expect(sent).toHaveLength(50);
|
||||||
|
expect(waits).toBe(51); // once before each pull, the last one being the pull that ends it
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user