24 Commits
Author SHA1 Message Date
chrnx 07f059ef2d fix(ws): wait for the send buffer before pulling the next outbound value (CARD-26, #41)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 17s
CI / build (pull_request) Successful in 27s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / runtimes (deno) (pull_request) Successful in 30s
The outbound pump pulled a @Ws handler's iterator as fast as it yielded,
whatever the peer read. With a slow client, 10,000 frames of 64 KiB were
all pulled at once and sat in the send buffer: 640 MiB.

WsSocket gains one optional member, drained(): it resolves once the
socket's send buffer is at or below the adapter's high-water mark
(WS_HIGH_WATER_MARK, 1 MiB, internal), or the socket has closed. The
pump awaits it before each pull, so the buffer peaks at the mark plus
one frame. A close ends the wait and the abort path runs the iterator's
return(), as before. A socket without drained() is never waited on.

Per runtime:
- Node: ws.bufferedAmount, released by each send's write callback;
- Bun: getBufferedAmount(), released by the server's drain callback;
- Deno: polls bufferedAmount every 10 ms, only while over the mark;
- workerd reports no buffered amount, so the edge never waits.

The Deno poll also waits while the socket is CONNECTING. Deno hands the
socket over before it opens, and a handler that yielded at once had its
first value pulled into a socket that was not open yet. The pump then
gave up, so the client saw no frame and a 1005 close.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:10:37 -05:00
chrnx f62a791afc fix(mesh): hold the control channel to hello size until the peer authenticates
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 26s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / runtimes (deno) (pull_request) Successful in 22s
boundInbound(socket, meshBounds) runs before ensureBooted() and before
the hello is checked, and meshBounds allowed 4,096 queued frames of up
to 7 MB each. During a slow boot nothing reads that queue, so an
unauthenticated peer could make the process buffer tens of GB.

The control channel's bounds are now phased (controlBounds() replaces
controlLimits()):
- until the hello is accepted: frames of at most HELLO_FRAME_BYTES
  (64 KiB) and the default 16-frame queue, so about 1 MiB per
  connection;
- after: the frame bound from #120 and the queue bound from #148.

boundInbound takes the second set as an optional `widened` argument and
keeps the switch on the bounded socket under a Symbol.for key. The
teapot calls widenInbound() when the handshake succeeds. The teapot's
own parse check follows the same phases, so a standalone
createMeshControl also refuses a pre-auth frame over hello size.

This is an auth-phased bound rather than a total-bytes cap: the only
unauthenticated frame with a purpose is the hello, and phasing keeps
the trusted path free of a second accounting rule. No new option.

On Node the control path's native maxPayload stays at the authed bound,
because ws cannot change it per phase. A pre-auth peer can still make
ws assemble one frame of up to that size before boundInbound closes
the connection with 1009. That frame is transient and never queued.

Tests: during a delayed boot, a 1 MB pre-auth frame closes 1009 at once
and a flood closes 1013 within 17 frames; after the hello, large frames
and a 64-ping burst are accepted. On Node, Deno and Bun, an
unauthenticated 1 MB frame over a real socket closes 1009. The #148
64-RPC test stays green.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:10:33 -05:00
chrnx 0f4b88ab1e fix(mesh): size control frames for the worst escaping a body can get (#120)
A 999,000-byte text/plain body of U+0001, within maxBodyBytes, still
failed 503: the envelope carries a text body as a JSON string, each
control character escapes to six characters, and the ~6 MB frame was
over the 4,000,000 the channel was sized to.

controlFrameLimit() is now 6 x maxBodyBytes plus 1 MiB for headers,
params, query and the envelope: 7,048,576 at the 1 MB default. Six is
the worst growth of any body byte; quotes and backslashes double, JSON
numbers like 1e20 grow about fivefold, multipart Buffers at most
fourfold, and non-ASCII text is not escaped. The fixed MAX_FRAME_CHARS
goes away with it.

Test (T1c) on Node, Deno and Bun: the control-character body now
answers 200 and the channel stays open.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:10:32 -05:00
chrnx e0c47f16e1 fix(mesh): give the control channel its own inbound queue bound (#148)
The control channel also inherited limits.maxWsQueue (16 undelivered
frames, close 1013) from #107. On Node, ws emits every frame of one
socket read synchronously, so a teacup with more than 16 RPCs in flight
sent a burst the teapot's queue refused: the link dropped and every
pending request failed 503. Deno and Bun deliver one frame per task and
did not trip.

controlLimits() now also raises maxWsQueue for the control channel, to
an internal 4,096 frames or maxWsQueue if larger, alongside the size
bound from #120. The teapot's frame loop never awaits between frames, so
the queue only holds one delivery burst, and one read (at most 64 KiB)
holds fewer than 4,096 of the smallest control frame. The bound stays
finite, so a peer flooding a channel nobody is reading is still cut off.
No new option. User @Ws routes keep closing 1013 at maxWsQueue.

Tests: 64 RPCs in one tick through app.fetch on one link all answer 200
(red on Node before), and a user route on the same teapot still closes
1013, on Node, Deno and Bun.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:10:32 -05:00
chrnx 9e3add7416 fix(mesh): bound the control channel by maxBodyBytes, not the 1 MiB ws cap (CARD-24, #120)
The 1 MiB inbound cap from #107 applied to every WebSocket, the mesh
control channel included. An RPC carries a whole request body, so a body
inside maxBodyBytes could still overflow the cap once wrapped in an
rpc-req frame, and the teapot then closed the whole channel with 1009:
every request through that link failed 503 until it reconnected.

The test asked for by the card (T1, a 1 MB JSON body at defaults) passes
on Node, Deno and Bun, because a JSON body re-encodes to about its own
size. Two other cases fail on all three before this change:
- T1b: a 999 KB text body of quotes doubles under JSON escaping;
- T4: maxBodyBytes raised to 4 MB, a 3.9 MB JSON body.

The control channel's bound is now derived from the teapot's
limits.maxBodyBytes via controlFrameLimit(): MAX_FRAME_CHARS (4,000,000)
at the 1 MB default, scaled by the same ratio above it, never below
maxWsMessageBytes. No new option. User @Ws routes keep
maxWsMessageBytes: Node gets a second WebSocketServer for the control
path, app.upgrade picks the bound from the path before subscribing, and
Bun's single native maxPayloadLength is raised on a teapot only, leaving
app.upgrade to close user routes 1009 itself.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:59:56 -05:00
chrnx 1da6bf2f99 Merge pull request 'feat(http): liveness and readiness probes with a drain window (CARD-17, #115)' (#145) from feature/fprd-001c-health into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 17s
CI / build (push) Successful in 27s
CI / runtimes (deno) (push) Successful in 20s
CI / runtimes (edge) (push) Successful in 14s
Promote → GitHub / push-github (push) Successful in 5s
2026-10-23 05:58:56 +00:00
chrnx f0530b15bb feat(http): liveness and readiness probes with a drain window (CARD-17, #115)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 27s
CI / runtimes (deno) (pull_request) Successful in 21s
CI / runtimes (edge) (pull_request) Successful in 14s
createApp({ health: true }) serves GET/HEAD /__live__ and /__ready__.
Ready reports booting until boot() resolves, ok or degraded (from
app.degraded()) after that, and draining from the moment close() starts.

Probes are answered by the adapters, ahead of the request gate and of
handle(): Node in serve() (src/http/server.ts), the Fetch path in
app.fetch before it awaits the boot. Otherwise ready could never say
booting. Being ahead of the gate means maxConcurrentRequests never sheds
a probe (D14). Being ahead of handle() means no step, provider, plugin or
onError runs, and no lifecycle event is emitted, so logRequests and
metrics never see a probe. Security headers still apply, plus
cache-control: no-store. Other methods get 405 with Allow: GET, HEAD.

A probe through app.fetch before any boot starts the boot without
awaiting it. On the edge, or under a bare Deno.serve(app.fetch), nothing
else may boot the app, and an orchestrator that waits for ready before
sending traffic would wait forever.

health: { drainDelayMs } (D14) marks the app draining and keeps the
listener open for that long before connections drain. Without it, Node
closes idle keep-alive sockets at once, and a probe sees a reset rather
than the 503. The window is spent out of the close budget. serveDeno and
serveBun start the same window, through a symbol-keyed hook on the app,
before server.shutdown() / server.stop(false). workerd has no close(),
so it never reports draining.

While health is on, /__live__ and /__ready__ join the reserved-path
boot check that CARD-21 introduced, for local and mesh-spliced routes.
Invalid health values throw at createApp.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:57:10 -05:00
chrnx 09251496c0 Merge pull request 'feat(mesh)!: reserve /__mesh__/control on every adapter (CARD-21, #126)' (#141) from feature/fprd-001c-mesh-reserved-path into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 15s
CI / build (push) Successful in 26s
CI / runtimes (deno) (push) Successful in 20s
CI / runtimes (edge) (push) Successful in 14s
Promote → GitHub / push-github (push) Successful in 7s
2026-10-23 05:57:05 +00:00
chrnx 9977d14605 test(router-parity): reserved mesh path refused on Node for CARD-21 (owner approval required)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 27s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 14s
Golden update for ws-node-upgrade.json, needs owner approval (CARD-08
rule). The WS parity fixture declared @Ws('/__mesh__/control') to
capture the old adapter split: the Node listener served it (101, the
route's frame, close 1005), app.upgrade refused it (1008). Under D17
that route fails createApp, so the fixture drops it and keeps the path
in UPGRADE_PATHS. The Node row now matches the app.upgrade row: 101, no
frame, close 1008 with the shared reason.

ws-app-upgrade.json is unchanged: app.upgrade already refused the path
before matching, so removing the route does not change its answer.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:53:55 -05:00
chrnx 2c00cc3407 feat(mesh)!: reserve /__mesh__/control on every adapter (CARD-21, #126)
The Node upgrade listener only intercepted /__mesh__/control when a mesh
control channel was configured; otherwise a user @Ws route there was
served. app.upgrade (Deno, Bun, edge) always checked the path first and
closed 1008. The same app therefore worked on Node and was refused
everywhere else.

D17 makes the path reserved in every app, mesh or not:

- createApp fails when a @Ws, @Stream or HTTP route claims the path,
  naming the declaration. A literal pattern is checked by equality, a
  parameterised one (/__mesh__/:x, /__mesh__/:rest*) by matching the
  reserved path against it. Patterns whose first segment is not the
  literal __mesh__ (/:org/:repo, /:rest*) still boot: the adapters
  answer the path before route matching, so those routes never see it.
- A route exported by a teapot is checked during the teacup splice.
- The Node listener, with no control channel, accepts the upgrade and
  closes 1008 with the reason app.upgrade gives. The reason is now one
  shared constant.

The check lives in src/http/reserved-paths.ts so CARD-17 can add
/__live__ and /__ready__ to the same list.

BREAKING CHANGE: an app that declares a route at /__mesh__/control, or a
pattern under /__mesh__/ that matches it, now fails createApp.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:53:55 -05:00
chrnx 444910b6f0 Merge pull request 'feat(graph)!: fail boot when a token has a second producer (CARD-18, GitHub #35)' (#143) from feature/fprd-001c-one-producer-per-token into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 15s
CI / build (push) Successful in 26s
CI / runtimes (deno) (push) Successful in 19s
CI / runtimes (edge) (push) Successful in 14s
Promote → GitHub / push-github (push) Successful in 6s
2026-10-23 05:51:52 +00:00
chrnx 56f953f0bb feat(graph)!: fail boot when a token has a second producer (CARD-18, GitHub #35)
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 26s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 14s
topoSort, topoLevels and subgraphFor built their token -> node map with
producedBy.set(key, node), so the last node registered for a token won.
Plugin nodes are registered after module nodes, which let a plugin's
scope.add({ name: 'shadow', provides: ['user'] }) silently replace the
app's own @Provider({ provides: 'user' }) for every route that needed
it. setRunner only rejects duplicate names, and scope.add is the one
path where a name and its tokens differ.

D9 settles it graph-wide: topoSort now throws when a token already has
a producer, naming both nodes and their origins (module:..., plugin,
mesh:<url>, builtin). One check on the whole node set covers every
current and future registration path. It also protects the built-ins
(logger, rooms, events) by rule rather than by registration order.
topoSort runs at finalize, after the mesh splice, so remote steps are
checked too. topoLevels and subgraphFor only ever see nodes topoSort
has already validated, so they keep their plain maps.

overrides replace the runner of an existing token and add no node, so
they are unaffected. Steps that provide nothing (plugin observers) are
not producers. The official plugins (jwt, metrics, rate-limit) pass
their suites against this build.

BREAKING CHANGE: an app whose graph has two nodes providing one token,
  e.g. a plugin scope node providing a token a module or built-in
  already provides, now fails createApp instead of letting the later
  node win.
Refs: GitHub #35

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:50:26 -05:00
chrnx a9e0555516 Merge pull request 'feat(edge)!: trust cf-connecting-ip only under trustProxy, for HTTP and WebSocket (CARD-23, #119)' (#139) from feature/fprd-001c-edge-cf-connecting-ip into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 16s
CI / build (push) Successful in 27s
CI / runtimes (deno) (push) Successful in 20s
CI / runtimes (edge) (push) Successful in 14s
Promote → GitHub / push-github (push) Successful in 6s
2026-10-23 05:49:45 +00:00
chrnx 88cbe41f72 feat(edge)!: trust cf-connecting-ip only under trustProxy, for HTTP and WebSocket (CARD-23, #119)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 25s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 15s
edgeHandler copied cf-connecting-ip into ctx.ip on every WebSocket
upgrade, so any client that sent the header chose its own address, and
it never read the header for HTTP, so IP-keyed plugins saw '' there.
D21 settles both: the header counts only under trustProxy, on both
paths, with no new option.

The adapter cannot make that call, because trustProxy is an app option.
So edgeHandler records the header against the object it hands the app
(the Request for HTTP, the WsRequest for an upgrade) in an internal
registry next to the Deno/Bun peer one, and app.fetch and app.upgrade
both consult it through one helper, trustedProxyClient(), which returns
'' unless trustProxy is on. Under trustProxy it takes precedence over
x-forwarded-for, since Cloudflare sets it itself and XFF can carry
client-supplied hops.

Nothing else records into the registry, so the Node, Deno and Bun
adapters, and a bare app.fetch or app.upgrade, ignore the header as
before.

BREAKING CHANGE: an edge WebSocket upgrade no longer takes ctx.ip from
  cf-connecting-ip unless the app sets trustProxy: true; without it,
  ctx.ip is ''.
Refs: #119

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:47:58 -05:00
chrnx 89ac955072 Merge pull request 'fix(http): keep every ? after the first in the query string (CARD-25, GitHub #48)' (#136) from feature/fprd-001c-query-string-question-marks into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 15s
CI / build (push) Successful in 27s
CI / runtimes (edge) (push) Successful in 13s
CI / runtimes (deno) (push) Successful in 20s
Promote → GitHub / push-github (push) Successful in 7s
2026-10-23 05:47:53 +00:00
chrnx 8bf54ec168 fix(http): keep every ? after the first in the query string (CARD-25, GitHub #48)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 27s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 14s
parseQuery took `url.split('?')[1]`, so a second `?` ended the query
string and `/search?q=what?now` gave `q: 'what'`. RFC 3986 §3.4 allows
`?` inside a query. The query string is now everything after the first
`?` and before `#`, if one is present. The early return for URLs without
a query is kept, and so is its measurement note. The comment that
deferred this behaviour question is removed because the question is now
decided (D23).

Path extraction already split on the first `?` and is unchanged.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:02:42 -05:00
73 changed files with 5642 additions and 295 deletions

No files matched your search

+171
View File
@@ -10,6 +10,15 @@ npm treats versions as semver and semver forbids leading zeros.
### Breaking
- **Response header values are `string | string[]`** (#113, D11). `TransformerFn`, `ErrorResponse.headers`,
`HttpError.headers` / `HttpErrorLike.headers` and the pipeline's `ResponseShape.headers` widen from
`Record<string, string>`, so a response can carry several `Set-Cookie` lines. Code that *produces*
headers is unaffected; code that *reads* `headers[k]` from one of these types as a `string` stops
compiling and must handle the array. A `set-cookie` array is sent as one header line per element
on Node, Deno, Bun and the edge — before, the fetch adapters stringified it into one broken
`a,b` cookie. Any other array is sent as one line joined with `, `. Injected security and CORS
headers stay authoritative, and a handler's `vary` array is merged with the injected one.
- **Node 18 and Node 20 are no longer supported; the minimum is Node 22.** Both are end-of-life
and receive no security patches, so `engines.node` is now `>=22`, CI runs Node 22 only, and the
build targets `node22`. Node 22 is the oldest line still maintained. The `node:crypto` fallback
@@ -58,8 +67,71 @@ npm treats versions as semver and semver forbids leading zeros.
constraints at a later segment of an otherwise unreachable route. The route then boots, as
before.
- **Edge WebSocket upgrades no longer trust `cf-connecting-ip` by default** (#119). `edgeHandler`
copied the header into `ctx.ip` on every upgrade, so any client that sent it chose its own
address. It now counts only under `trustProxy: true`, the same rule HTTP follows. Without it,
`ctx.ip` on an edge WebSocket is `''`, as it already was on edge HTTP: workerd exposes no peer
address. An app behind Cloudflare that keys anything on the WebSocket IP needs
`createApp({ trustProxy: true })`.
- **A token has one producer: a second one fails `createApp`** (GitHub #35). The graph kept the
last node registered for a token, and plugin nodes are registered after module nodes, so a
plugin whose `scope.add` provided `user` silently replaced the app's own `@Provider({ provides:
'user' })` for every route that needed it. Boot now fails instead, naming both nodes and where
they came from: `token 'user' is provided twice: by 'user' (module:AppModule) and by 'shadow'
(plugin)`. The rule covers the whole graph (modules, plugins, mesh steps spliced at boot, and
the built-ins `logger`, `rooms` and `events`), so a plugin node that provides `logger` under
another name fails as well, whatever order things are registered in. `overrides` keep working:
they replace the runner of an existing token and add no producer. Observer steps that provide
nothing are unaffected. The official plugins already follow name = node name = token.
- **`/__mesh__/control` is reserved in every app, mesh or not** (#126). A `@Ws`, `@Stream` or HTTP
route that claims it — `@Ws('/__mesh__/control')`, `@Get('/__mesh__/control')`,
`@Ws('/__mesh__/:x')`, `/__mesh__/:rest*`, or a mountpoint that adds up to one of these — now
fails `createApp`, naming the declaration and the reserved path. A route exported by a teapot is
checked the same way, and fails the teacup's boot. Before, the Node listener served a user route
there whenever no mesh control channel was configured, while `app.upgrade` (Deno, Bun, the edge)
always refused it, so the same route worked on one runtime and not the others. A pattern whose
first segment is not the literal `__mesh__` (`/:org/:repo`, `/:rest*`) still boots; the reserved
path is answered ahead of the route table on every runtime, so such a route never sees it.
An upgrade to `/__mesh__/control` on an app with no control channel is now refused identically
everywhere: the Node listener accepts it and closes `1008` with
`mesh control channel not enabled: this app exports nothing, or has no mesh.secret`, as
`app.upgrade` already did. An app with no `@Ws`/`@Stream` routes and no mesh attaches no upgrade
listener on Node, as before, so there the request still reaches the HTTP route table.
### Added
- **Health probes: `createApp({ health: true })`** (#115). Off by default. `GET`/`HEAD /__live__`
answers `200 {"status":"ok"}` whenever the process answers. `/__ready__` answers
`503 {"status":"booting"}` until `boot()` resolves, then `200 {"status":"ok"}` or
`200 {"status":"degraded","degraded":[…]}` (from `app.degraded()`), and
`503 {"status":"draining"}` from the moment `close()` starts: Node `app.close()`, and the
`close()` that `serveDeno()`/`serveBun()` return. Probes are answered by the adapter, ahead of
`maxConcurrentRequests` and the route table, so they are never shed and run no step, provider,
plugin or `onError`, and emit no lifecycle event (`logRequests` and metrics plugins do not see
them). Security headers still apply, plus `cache-control: no-store`; other methods get `405` with
`Allow: GET, HEAD`. While `health` is on, a route at either path fails the boot, local or spliced
from a teapot. A probe through `app.fetch` before the boot starts the boot without waiting for it.
`health: { drainDelayMs }` (default 0) keeps the listener open that long after `close()` starts,
with `/__ready__` already answering `503`, before connections drain. Without it Node closes idle
keep-alive connections at once, so a probe usually sees a refused connection rather than a `503`.
The window is spent out of the shutdown budget; `createApp` throws when `drainDelayMs` plus
`teardownTimeoutMs` exceeds `shutdownTimeoutMs`, and on any `health` value other than `true`,
`false` or `{ drainDelayMs?: number }`. On the edge there is no `close()`, so `/__ready__` never
reports `draining` there.
- **`@cookie('name')` / `@cookies()` argument decorators and `setCookie()`** (#113). Cookies are
parsed from the request's `Cookie` header on first use per request (RFC 6265: first value wins,
`%`-sequences decoded, malformed pairs skipped rather than answered with a 400), on HTTP and
WebSocket routes; `@needs('cookies')` gives the same map. OpenAPI lists a cookie argument as an
`in: cookie` parameter. `setCookie(name, value, options?)` returns a `Set-Cookie` value with
`HttpOnly`, `SameSite=Lax`, `Path=/` and `Secure` by default (D10; `secure: false` opts out), and
throws, naming the field, on a name outside the token set, a value with CR, LF, `;`, `,`,
whitespace or a control character, an attribute with CR/LF, `;` or a control character, and on
`sameSite: 'none'` or `partitioned` without `secure`. `parseCookies()` and `CookieOptions` are
exported too. No dependency: signing and sessions stay out of core.
- **`limits.maxWsMessageBytes` and `limits.maxWsQueue`** (#107): per-connection bounds on inbound
WebSocket messages, in bytes and in unread messages, server-wide on every runtime. `createApp`
throws a `TypeError` for anything but a positive integer. Node and Bun refuse an oversized message
@@ -69,6 +141,11 @@ npm treats versions as semver and semver forbids leading zeros.
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.
- **`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
- **HTTP route lookup uses a radix index** (#109). The router used to scan a specificity-sorted
@@ -81,8 +158,102 @@ npm treats versions as semver and semver forbids leading zeros.
param hit −88%, method miss −94%, path miss −96%; at 10 routes, every cell is within noise or
faster (late param hit +3.4%, 95% CI −5.0…+12.6%).
- **A query string keeps every `?` after the first** (GitHub #48). `parseQuery` took the text
between the first and second `?`, so `/search?q=what?now` gave `q: 'what'` and dropped the rest.
RFC 3986 §3.4 allows `?` inside a query, so the query string is now everything after the first
`?` and before `#`, if there is one: `q: 'what?now'`, and `/search?a=1&b=?` gives `b: '?'`. URLs
with a single `?` parse as before. Path extraction is unchanged.
- **Mesh (alpha): a teacup's remote routes follow which teapots are connected** (#124, D15). The
route table used to be built once at boot: a teapot that started late was never served, and a
teapot that was gone for good stayed advertised. Now:
- A teapot that missed `bootTimeoutMs` is retried in the background with the `reconnect` backoff.
When it connects, its routes are served, with no restart. Its steps are not added, because the
graph was validated at boot without them. With `reconnect: false` it is not retried.
- While a link is reconnecting, its routes stay and answer `503`, now with `retry-after` (the
seconds until the next attempt). `Allow` keeps them.
- A link that gives up for good has its routes removed: they answer `404` and leave `Allow`. That
is a link dropped with `reconnect: false`, or one refused permanently (a wrong secret, a protocol
mismatch) while reconnecting. A refused reconnect used to retry forever. It now stops.
- A returning teapot's routes replace its old ones: a route it added is served, one it dropped
answers `404`. A returning manifest is still refused for a missing **step**
(`onManifestChange: 'refuse'`), but no longer for a missing route.
- A late route that conflicts with another teapot's (same shape, or a CARD-13 sibling conflict)
is refused and logged, and the rest keep serving. At boot the same conflict still fails boot.
- A late or returning route on a reserved path (`/__mesh__/control`, and `/__live__`/`/__ready__`
with `health` on) is refused and logged the same way. At boot it still fails boot.
- Every change emits `mesh:routes` with `{ url, added, removed }` (new `EventPayload` fields).
Membership changes publish a new table. A request in flight routes against the old one or the
new one, never a mix. Only the remote route trees are rebuilt. `listen()` now reads the same
table as `app.fetch`, and `createHttpServer` accepts a getter as well as an array. Dev
introspection routes (`devGraph`, `devOpenapi`) now sit before remote routes in that table, so
in the one case where a teapot exports the same path at the same specificity, the dev route wins.
### Fixed
- **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`
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
`x-forwarded-for`, because Cloudflare sets it itself while XFF can carry hops the client supplied.
Without `trustProxy` it is ignored. Only `edgeHandler` reads it: the Node, Deno and Bun adapters, and a
bare `app.fetch`, ignore it as before.
- **Mesh (alpha): `HEAD` on a remote `GET` route now works** (#125). The teacup resolved `HEAD` to
the remote `GET` and `OPTIONS` advertised `HEAD`, but the request went to the teapot as `HEAD`,
which has no `HEAD` plan, so it answered `404`. The teacup now forwards it as a `GET` and drops
the body, so it answers like a local route: the `GET`'s status and headers, no body, and a
`404`/`500` from the route keeps its status. An explicit remote `HEAD` route still takes
precedence. The teapot is unchanged, so a new teacup works against an older teapot during a
rolling deploy.
- **`static` no longer serves files outside its root through a symlink** (#106). The traversal guard
compared paths lexically, and the file read then followed symlinks, so `public/leak -> /etc/hosts`
was served. Containment now compares real paths: the requested file, and a directory's
+5
View File
@@ -144,6 +144,7 @@ without growing the runtime dependency tree past `reflect-metadata`:
- **Resource ceilings, with safe defaults.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. `maxConcurrentRequests` is opt-in and applies per server or Fetch adapter instance; when set, excess in-flight requests receive `503` and `Retry-After: 1`. It bounds concurrently executing handlers, so a handler that never returns continues to hold its slot; on Node, a client disconnect releases that slot. Long-lived streams and WebSocket upgrades do not hold that request budget. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there. WebSocket connections are bounded too: `maxWsMessageBytes` (default 1 MiB) closes a connection whose message is larger with `1009`, and `maxWsQueue` (default `16`) closes one that has that many unread inbound messages and receives another with `1013`, rather than dropping anything. Both are server-wide and must be positive integers. Node and Bun refuse an oversized message before buffering it (Bun before 1.4 drops the connection, so its peer sees `1006`; Bun 1.4 and later send `1009`); Deno and the edge check it after the runtime has received it. Worst case, a server buffers about `maxConnections × maxWsQueue × maxWsMessageBytes` of inbound messages — ≈ 15.6 GiB at the Node defaults.
- **Observability without an integration.** Every request carries an id and a trace id through every lifecycle event, each step reports its own duration, and `createApp({ logger })` accepts any logger — the default writes structured JSON. Nothing in core writes to `console`. Metrics and tracing exporters read the same stream from outside core.
- **Graceful shutdown, with a deadline.** `app.close()` drains in-flight requests and closes live streams and mesh links, then warns and force-closes whatever is still open after 10 seconds — so a stuck handler cannot hold a deploy open forever. Change the number per call with `close({ timeoutMs })` or for the whole app with `createApp({ shutdownTimeoutMs })`. Connection *draining* is Node-only; on Deno and Bun the server `serveDeno()`/`serveBun()` returns carries the same `close({ timeoutMs })`.
- **Liveness and readiness probes.** `createApp({ health: true })` serves `/__live__` and `/__ready__`. Readiness reports `booting`, `ok`, `degraded` (optional providers that failed) or `draining` (from the moment `close()` starts). Probes are answered ahead of the pipeline: they are never shed and never show up in lifecycle events or request logs. `health: { drainDelayMs }` keeps the listener open for that window after `close()` starts, so a load balancer reads the `503` before connections drain. The edge never reports `draining`, because it has no `close()`.
- **Shutdown is an extension point.** A provider that opened a pool closes it in `dispose()`; a plugin registers `onShutdown(...)`; an application that wants neither passes `createApp({ hooks: [{ onShutdown }] })`. All three land in one registry, run in reverse boot order — a `cache` that needs `db` closes first — and are *awaited*, unlike a `bus.on` listener. A failure is logged and the rest still run, because one broken teardown must not leave the process up. Everything happens inside `close()`'s deadline; `createApp({ teardownTimeoutMs })` reserves a slice of it when a connection must get its chance. *Not available on the edge* — workerd has no shutdown to hook.
- **The `SIGTERM` handler is yours to keep or to hand over.** All of the above runs from `close()`, and something has to call it — a container `SIGKILL`ed after its grace period skips every `dispose()` and reports nothing. Write the handler yourself and keep the control, or set `createApp({ handleSignals: true })` and the framework registers `SIGINT`/`SIGTERM` to close and exit for you. Off by default, because a library that installs process-wide handlers behind your back is worse than one that installs none. Turning it on also absorbs the last runtime difference an app has: `process.on` on Node and Bun, `Deno.addSignalListener` on Deno, and the matching `exit` for each — `listen()`, `serveDeno()` and `serveBun()` each wire it to the closer that drains *their* server. `close()` unregisters, so a second Ctrl-C ends a teardown that is stuck.
- **Testable by construction.** `createApp({ overrides: { db: fakeDb } })` swaps any node in one line.
@@ -243,6 +244,10 @@ The handler signature declares exactly what it wants — in any order, nothing m
| `@body(...)` | parsed body (JSON / urlencoded / multipart) | `()` · `('field')` · `(schema)` |
| `@headers(...)` | request headers (whole bag or picked) | `()` · `('authorization')` · `(['a','b'])` · `(schema)` |
| `@header('name')` | one request header (singular alias of `@headers`) | `('x-trace')` · `('x-count', schema)` |
| `@cookies(...)` | request cookies, parsed from `Cookie` (whole map or picked) | `()` · `('sid')` · `(['a','b'])` · `(schema)` |
| `@cookie('name')` | one request cookie (singular alias of `@cookies`) | `('sid')` · `('sid', schema)` |
To send cookies, `setCookie(name, value, options?)` returns a `Set-Cookie` value with safe defaults (`HttpOnly`, `SameSite=Lax`, `Path=/`, `Secure`) and throws on anything that could inject a header. Response header values are `string | string[]`: a `set-cookie` array is sent as one line per cookie on every runtime, any other array as one line joined with `, `. Pass `secure: false` where the browser will not keep a `Secure` cookie over plain HTTP (Safari, a LAN IP). Signing and sessions are not in core.
`@needs` keys are validated at boot: nothing provides the key → `createApp` throws with a clear error instead of serving `undefined`. Pass a Standard Schema (`@body(User)`) and the value is validated, coerced, and typed before your handler sees it.
+507 -125
View File
@@ -7,9 +7,11 @@ import { toMermaid, toDOT, graphHtml, type GraphView } from '../graph-viz';
import { runPipeline, runSteps, PipelineStep } from '../pipeline';
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http';
import type { HttpOptions } from '../http';
import { buildFetch } from '../http/web';
import { trustedProxyClient } from '../http/peer';
import { answerFetchProbe, buildFetch } from '../http/web';
import {
boundInbound,
controlBounds,
validateWsLimits,
WS_MAX_MESSAGE_BYTES,
wsMessageBytes,
@@ -43,19 +45,30 @@ import { buildOpenApi, type OpenApiInfo } from '../openapi';
import { connectLink, isPermanentRefusal, type Link } from '../mesh/link';
import { Rooms } from '../rooms';
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
import { buildRemote } from '../mesh/teacup';
import { buildManifest, createMeshControl, MESH_CONTROL_PATH } from '../mesh/teapot';
import { buildRemote, type RemoteRoute as TeacupRemoteRoute } from '../mesh/teacup';
import {
buildManifest,
controlFrameLimit,
createMeshControl,
MESH_CONTROL_DISABLED_REASON,
MESH_CONTROL_PATH,
} from '../mesh/teapot';
import type { MeshControl } from '../http';
import type { RequestEnvelope, RouteEntry } from '../mesh/protocol';
import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types';
import { inspectRoute, buildGraphView, explainRoute } from './introspect';
import { compilePattern, markRemoteRoute, normalizeRequestPath } from '../http/router';
import { routeConflict, type Precedence, type RouteConflict } from '../http/route-conflicts';
import { assertNotReserved, type ReservedPath } from '../http/reserved-paths';
import { HEALTH_DRAIN, HEALTH_RESERVED, resolveHealth, trackHealth, type HealthConfig } from '../http/health';
export type { App, InspectLine, ExplainNode, Explain, MeshConfig, Hooks } from './types';
type Runner = (ctx: any) => any;
/** Something shutdown closes: a mesh link, or the retry loop of a teapot that missed boot. */
type Closable = Pick<Link, 'close'>;
/** Mutable graph state assembled from modules/plugins and later spliced with remote mesh scopes. */
interface Registry {
providerNodes: GraphNode[];
@@ -120,6 +133,27 @@ export function createApp(opts: {
limits?: RequestLimits;
devGraph?: boolean;
devOpenapi?: boolean;
/**
* Serve `GET`/`HEAD` `/__live__` and `/__ready__` for load balancers and orchestrators (default: off).
*
* - `/__live__` answers `200 {"status":"ok"}` whenever the process answers.
* - `/__ready__` answers `503 {"status":"booting"}` until `boot()` resolves, then
* `200 {"status":"ok"}` or `200 {"status":"degraded","degraded":[…]}` (see `app.degraded()`),
* and `503 {"status":"draining"}` from the moment `close()` starts.
*
* Probes skip the pipeline: no step, provider, plugin or `onError` runs and no lifecycle event is
* emitted, so `logRequests` and metrics plugins never see them. `maxConcurrentRequests` never sheds
* them. Security headers still apply, plus `cache-control: no-store`; other methods get `405`.
* While on, a route at either path fails the boot.
*
* `drainDelayMs` (default 0) keeps the listener open that long after `close()` starts, with
* `/__ready__` already answering `503`, before connections drain. Without it Node closes idle
* keep-alive connections at once, so a probe usually sees a refused connection rather than a `503`.
* The window is spent out of the shutdown budget (`shutdownTimeoutMs`), not added to it.
*
* On the edge there is no `close()`, so `/__ready__` never reports `draining` there.
*/
health?: boolean | { drainDelayMs?: number };
overrides?: Record<string, unknown>;
tls?: TlsOptions;
trustProxy?: boolean;
@@ -207,6 +241,7 @@ export function createApp(opts: {
}
validateWsLimits(opts.limits);
const health = resolveHealth(opts.health, opts.shutdownTimeoutMs, opts.teardownTimeoutMs);
const bus = new Bus();
const logger = opts.logger ?? createDefaultLogger();
@@ -220,6 +255,8 @@ export function createApp(opts: {
const viewsCtx: ViewsContext = { views: opts.views, viewEngine: opts.viewEngine };
const registry = collectModules(opts.modules, viewsCtx);
const { providerNodes, stepNodes, runners, providerMeta, routePlans } = registry;
const reserved = reservedPaths(health);
assertNoReservedRoutes(routePlans, reserved);
const teardown = buildTeardownRegistry(opts.hooks, opts.teardownTimeoutMs, opts.shutdownTimeoutMs);
mountPlugins(opts.plugins, bus, registry, teardown);
provideBuiltins(registry, logger, bus);
@@ -231,8 +268,7 @@ export function createApp(opts: {
let orderedProviders: GraphNode[] = [];
let orderedSteps: GraphNode[] = [];
let booted = false;
let remoteRoutes: RouteDef[] = [];
const meshLinks: Link[] = [];
const meshLinks: Closable[] = [];
const finalize = (missingNote?: string): void => {
({ orderedProviders, orderedSteps } = finalizeGraph(registry, logger, opts.warnGraphDepth, missingNote));
@@ -251,8 +287,7 @@ export function createApp(opts: {
// can only be built here, after finalize(), and never at construction time.
const prepareGraph = async (): Promise<void> => {
if (opts.mesh && !booted) {
const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger);
remoteRoutes = spliced.remoteRoutes;
const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger, reserved, publishRemote);
meshLinks.push(...spliced.meshLinks);
// Without this the error is `missing dependency: auth needed by getUser` and says nothing
// about the teapot that was away — which is the actual cause every time it is the cause.
@@ -267,6 +302,7 @@ export function createApp(opts: {
orderedProviders,
orderedSteps,
deps: pipelineDeps,
maxBodyBytes: opts.limits?.maxBodyBytes,
});
};
@@ -298,9 +334,14 @@ export function createApp(opts: {
return routes;
};
// The one HTTP route table, shared by app.fetch and listen() — see createRouteTable.
const table = createRouteTable(() => [...buildHttpRoutes(routePlans, pipelineDeps), ...devRoutes()]);
const currentTable = table.current;
const publishRemote = table.publish;
// Boots exactly once, however first triggered (app.fetch, app.upgrade or listen()); calling
// several never double-boots (which would re-run provider factories and their side effects).
const bootApp = makeAppBooter(
const bootGraph = makeAppBooter(
registry,
opts.overrides,
() => orderedProviders,
@@ -309,6 +350,8 @@ export function createApp(opts: {
ready,
);
const { bootApp, healthProbe, drain } = trackHealth(health, bootGraph, () => [...degradedProviders]);
const staticResolver = opts.static ? buildStaticResolver(opts.static) : undefined;
const fetchOpts: HttpOptions = {
@@ -322,16 +365,17 @@ export function createApp(opts: {
bodyDuplicates: opts.bodyDuplicates,
onError: opts.onError,
static: staticResolver,
health: healthProbe,
};
const fetchFn = buildAppFetch(
routePlans,
{ providedSeed, planSteps, bus, onError: opts.onError, logger },
fetchOpts,
bootApp,
devRoutes,
() => remoteRoutes,
);
const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl, opts.limits);
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, {
limits: opts.limits,
trustProxy: opts.trustProxy,
meshBounds,
});
const listen = async (port: number): Promise<http.Server> => {
const deps = pipelineDeps;
@@ -340,10 +384,10 @@ export function createApp(opts: {
// and builds the mesh control channel — so Node and Deno/Bun serve an identical graph
await bootApp();
const httpRoutes = [...buildHttpRoutes(routePlans, remoteRoutes, deps), ...devRoutes()];
const wsRoutes = buildWsRoutes(routePlans, deps);
server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, {
// A getter, not an array: mesh membership can change the table after this server starts.
server = createHttpServer(currentTable, wsRoutes, bus, meshControl, {
bus,
logger,
limits: opts.limits,
@@ -355,6 +399,7 @@ export function createApp(opts: {
bodyDuplicates: opts.bodyDuplicates,
onError: opts.onError,
static: staticResolver,
health: healthProbe,
});
server.on('close', () => closeLinks(meshLinks));
await new Promise<void>((resolve) => server!.listen(port, resolve));
@@ -374,13 +419,16 @@ export function createApp(opts: {
removeSignalHandlers = undefined;
};
const close = (options: { timeoutMs?: number } = {}): Promise<void> => {
const close = async (options: { timeoutMs?: number } = {}): Promise<void> => {
clearSignalHandlers();
// `/__ready__` flips to draining first, and the listener stays open for the drain window.
const budget = await spendDrainWindow(drain, options, opts.shutdownTimeoutMs, server !== undefined);
return closeApp(
server,
meshLinks,
streams,
options,
budget,
opts.shutdownTimeoutMs,
logger,
teardown,
@@ -420,7 +468,8 @@ export function createApp(opts: {
};
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,
});
}
@@ -628,6 +677,48 @@ function resolveTransformer(
return buildHtmlTransformer(html, viewsCtx);
}
/**
* Runs the drain window and returns the options `closeApp` should get for what is left.
*
* The window comes out of the close budget, so close() still returns within the timeout it was
* given. Adjusted only when there is a server: without one closeApp only runs teardown, and an
* explicit timeout there earns a warning the caller never asked for.
*/
async function spendDrainWindow(
drain: () => Promise<void>,
options: { timeoutMs?: number },
shutdownTimeoutMs: number | undefined,
hasServer: boolean,
): Promise<{ timeoutMs?: number }> {
const startedAt = Date.now();
await drain();
const waited = Date.now() - startedAt;
if (!hasServer || waited === 0) return options;
const budget = options.timeoutMs ?? shutdownTimeoutMs ?? 10_000;
return { timeoutMs: Math.max(0, budget - waited) };
}
/**
* The paths this app answers itself, ahead of the route table (D17).
*
* `/__mesh__/control` is reserved in every app, mesh or not: whether a route there is served must not
* depend on the runtime or on whether a mesh happens to be configured.
*/
function reservedPaths(health: HealthConfig | undefined): ReservedPath[] {
const mesh: ReservedPath = { path: MESH_CONTROL_PATH, purpose: 'the mesh control channel' };
// The probe paths only while health is on: with it off they are ordinary paths (CARD-17 rule 7).
return health ? [mesh, ...HEALTH_RESERVED] : [mesh];
}
/** Fails the boot when a declared route claims a reserved path (see {@link assertNotReserved}). */
function assertNoReservedRoutes(routePlans: RoutePlan[], reserved: readonly ReservedPath[]): void {
for (const plan of routePlans) {
const kind = plan.transport === 'ws' ? '@Ws' : plan.transport === 'negotiate' ? '@Stream' : plan.method;
assertNotReserved(plan.pattern, `route ${kind} ${plan.pattern} at ${plan.declaration}`, reserved);
}
}
/** Reads every module's metadata into a fresh {@link Registry} of graph nodes, runners and exports. */
function collectModules(modules: Ctor[], viewsCtx: ViewsContext): Registry {
const registry = emptyRegistry();
@@ -804,7 +895,17 @@ function assertNeedsSatisfiable(
...providerNodes.flatMap((node) => node.provides),
...stepNodes.flatMap((node) => node.provides),
]);
const allowed = new Set<string>([...producedKeys, 'req', 'params', 'query', 'body', 'headers', 'inbound', 'abort']);
const allowed = new Set<string>([
...producedKeys,
'req',
'params',
'query',
'body',
'headers',
'cookies',
'inbound',
'abort',
]);
for (const plan of routePlans) {
for (const need of plan.needs) {
@@ -966,24 +1067,173 @@ function assertNoRemoteSiblingConflict(accepted: RemoteRoute[], route: RemoteRou
}
}
/** Connects the configured teapots, splices their remote steps into the registry, and returns their routes. */
async function spliceRemoteScopes(
mesh: MeshConfig,
bus: Bus,
/** A teapot route the remote table serves: its export, its owner, and the def the router files. */
interface ServedRemote extends RemoteRoute {
def: RouteDef;
}
/**
* The teacup's remote routes, by teapot, published as a fresh array on every change (D15).
*
* Never mutated in place: the router caches an index by array identity, and a request that is
* already routing keeps the array it read, so it sees the whole old table or the whole new one.
*/
interface RemoteTable {
/**
* Replaces one teapot's routes and publishes the table. With `strict` (boot) a conflicting route
* fails the boot; after boot it is refused and logged, and everything else keeps serving.
*/
set(url: string, routes: TeacupRemoteRoute[], strict: boolean): { added: string[]; removed: string[] };
}
const showRoute = (route: { method: string; pattern: string }): string => `${route.method} ${route.pattern}`;
/**
* Throws when `route` cannot join the remote routes already accepted: the same effective shape and
* method as one of them, or a sibling conflict (CARD-13). Route matching keeps the first of two
* identical patterns, so the loser would be silently dead — and callers could come to depend on
* "first teapot wins", which would make adding balancing later a breaking change.
*/
function assertRemoteRouteFits(accepted: RemoteRoute[], route: RemoteRoute): void {
const shape = compilePattern(route.pattern).shape;
const owner = accepted.find(
(prior) => prior.method === route.method && compilePattern(prior.pattern).shape === shape,
);
if (owner) {
throw new Error(
`mesh: ambiguous remote route '${showRoute(route)}' from ${route.url} conflicts with ` +
`'${showRoute(owner)}' from ${owner.url} — ` +
'load balancing across teapots is not implemented yet, so green-tea will not choose one for you. ' +
'Export it from a single teapot.',
);
}
assertNoRemoteSiblingConflict(accepted, route);
}
/**
* Local routes are merged ahead of remote ones (see the route table), so a local twin wins. That
* precedence is deliberate — your own code beats an imported one, and it is how you override a
* teapot — but silently shadowing an export looks exactly like a broken teapot from the outside.
* Warn and let the developer decide.
*/
function warnIfShadowed(registry: Registry, route: RemoteRoute, logger: Logger): void {
const shape = compilePattern(route.pattern).shape;
if (!registry.routePlans.some((plan) => plan.method === route.method && compilePattern(plan.pattern).shape === shape))
return;
logger.warn(
`mesh: route '${showRoute(route)}' is exported by teapot ${route.url} but also declared locally — ` +
'the local route takes precedence and the remote one will not be reached. ' +
'Remove one if that is not what you meant.',
);
}
/** The route the router files for a teapot's export: marked remote, and forwarding a built envelope. */
function remoteRouteDef(route: TeacupRemoteRoute): RouteDef {
// Marked so the router files it in the remote tree; precedence is unchanged by the split.
return markRemoteRoute({
method: route.method,
pattern: route.pattern,
transport: 'buffer',
// Built explicitly rather than cast from the handler argument. The cast put the whole
// internal request on the wire — `ip` and `protocol` included — and sent fields the
// protocol never declared, so a teapot could come to rely on something we never promised.
handler: async (req) =>
route.handler({
// HEAD reaches a remote GET through the implicit-HEAD fallback, and the teapot looks
// its plan up by method, so a forwarded HEAD finds none and answers 404. Send it as the
// GET it resolved to; dispatch drops the body for HEAD. Fixed teacup-side (D16) so an
// unchanged, older teapot still answers it during a rolling deploy.
method: req.method === 'HEAD' && route.method === 'GET' ? 'GET' : req.method,
params: req.params,
query: req.query,
body: req.body,
headers: req.headers,
url: req.url,
correlation: { requestId: req.requestId, traceId: req.traceId },
}),
});
}
/** Builds the remote table over the configured teapots, in configuration order. */
function createRemoteTable(
urls: string[],
registry: Registry,
logger: Logger,
): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[]; absent: string[] }> {
const remoteRoutes: RouteDef[] = [];
const meshLinks: Link[] = [];
const absent: string[] = []; // urls of teapots that never connected within the boot budget
const routeOwners = new Map<string, { url: string; pattern: string }>(); // "METHOD effective-shape" -> owner
const remoteAccepted: RemoteRoute[] = []; // every remote route spliced so far, in teapot order
reserved: readonly ReservedPath[],
publish: (routes: RouteDef[]) => void,
): RemoteTable {
const byUrl = new Map<string, ServedRemote[]>();
return {
set(url, routes, strict) {
const others = urls.filter((other) => other !== url).flatMap((other) => byUrl.get(other) ?? []);
const before = new Set((byUrl.get(url) ?? []).map(showRoute));
const next: ServedRemote[] = [];
for (const route of routes) {
const candidate: RemoteRoute = { method: route.method, pattern: route.pattern, url };
try {
for (const teapot of mesh.teapots ?? []) {
warnIfCleartext(teapot.url, logger);
const link = await connectUntilDeadline(mesh, bus, logger, teapot.url, () =>
connectLink({
// A teapot's own boot refuses a reserved path, but the manifest is whatever arrives on the
// wire: an older or foreign teapot could still advertise one, at boot or later, and the
// teacup must not splice it (CARD-21/CARD-17).
assertNotReserved(route.pattern, `mesh: remote route '${showRoute(route)}' from ${url}`, reserved);
assertRemoteRouteFits([...others, ...next], candidate);
} catch (error) {
if (strict) throw error;
// Refused for this teapot only; the table that is serving stays as it was (D15, rule 5).
// The same goes for a reserved path: that one route is skipped, the rest are served.
logger.warn(`mesh: not serving a route from ${url} — ${(error as Error).message}`);
continue;
}
if (!before.has(showRoute(candidate))) warnIfShadowed(registry, candidate, logger);
next.push({ ...candidate, def: remoteRouteDef(route) });
}
byUrl.set(url, next);
publish(urls.flatMap((other) => (byUrl.get(other) ?? []).map((served) => served.def)));
const after = new Set(next.map(showRoute));
return {
added: [...after].filter((key) => !before.has(key)),
removed: [...before].filter((key) => !after.has(key)),
};
},
};
}
/** What a teapot's link needs to report membership back to the remote table after boot. */
interface MembershipContext {
mesh: MeshConfig;
bus: Bus;
logger: Logger;
table: RemoteTable;
}
/** Applies one teapot's routes after boot and emits `mesh:routes` when the table actually changed. */
function applyMembership(ctx: MembershipContext, url: string, routes: TeacupRemoteRoute[]): void {
const { added, removed } = ctx.table.set(url, routes, false);
if (!added.length && !removed.length) return;
ctx.bus.emit('mesh:routes', { name: url, url, added, removed });
}
/**
* Opens a link to one teapot, wired so a returning manifest updates its routes and a link that
* gives up for good removes them (D15). `holder.link` is filled in once the link exists, because
* the callbacks need the link to rebuild its route proxies.
*/
function connectTeapot(
ctx: MembershipContext,
teapot: { url: string; secret: string },
holder: { link?: Link },
): Promise<Link> {
const { mesh, bus, logger } = ctx;
return connectLink({
url: teapot.url,
secret: teapot.secret,
timeoutMs: mesh.timeoutMs,
@@ -992,14 +1242,120 @@ async function spliceRemoteScopes(
onManifestChange: mesh.onManifestChange,
logger,
bus,
}),
onReconnect: () => {
if (holder.link) applyMembership(ctx, teapot.url, buildRemote(holder.link).routes);
},
onGone: () => {
logger.warn(`mesh: teapot ${teapot.url} is gone for good — its routes are removed and now answer 404.`);
applyMembership(ctx, teapot.url, []);
},
});
}
/** Backoff bounds for retrying a late teapot: the reconnect ones, or nothing when reconnect is off. */
function lateBounds(mesh: MeshConfig): { initial: number; max: number } | undefined {
if (mesh.reconnect === false) return undefined;
const opts = typeof mesh.reconnect === 'object' ? mesh.reconnect : {};
return { initial: opts.initialDelayMs ?? 500, max: opts.maxDelayMs ?? 30_000 };
}
/**
* Keeps trying a teapot that missed the boot budget, with the reconnect backoff (D15, rule 1). When
* it connects, its routes join the remote table; its steps do not, because the graph was validated
* at boot without them. A permanent refusal stops the retries. The handle's `close()` stops them too,
* and closes the link if one came up, so shutdown never leaves a retry behind.
*/
function retryLateTeapot(
ctx: MembershipContext,
teapot: { url: string; secret: string },
bounds: { initial: number; max: number },
): { close: () => void } {
const holder: { link?: Link } = {};
let stopped = false;
let attempt = 0;
let timer: ReturnType<typeof setTimeout> | undefined;
const schedule = (): void => {
const capped = Math.min(bounds.initial * 2 ** attempt++, bounds.max);
timer = setTimeout(() => void tryOnce(), Math.round(capped / 2 + Math.random() * (capped / 2)));
timer.unref?.();
};
const tryOnce = async (): Promise<void> => {
try {
const link = await connectTeapot(ctx, teapot, holder);
if (stopped) return link.close();
holder.link = link;
const { steps, routes } = buildRemote(link);
if (steps.length)
ctx.logger.warn(
`mesh: teapot ${teapot.url} connected after boot — its routes are served now, but its steps ` +
`(${steps.map((step) => step.name).join(', ')}) are not: the graph was fixed at boot without them.`,
);
applyMembership(ctx, teapot.url, routes);
} catch (error) {
if (stopped) return;
if (isPermanentRefusal(error)) {
ctx.logger.error(
`mesh: teapot ${teapot.url} refused this peer — no longer retrying it (${(error as Error).message})`,
);
return;
}
schedule();
}
};
schedule();
return {
close: () => {
stopped = true;
clearTimeout(timer);
holder.link?.close();
},
};
}
/**
* Connects the configured teapots, splices their remote steps into the registry, and publishes their
* routes through `publish`, now and whenever membership changes after boot (D15).
*/
async function spliceRemoteScopes(
mesh: MeshConfig,
bus: Bus,
registry: Registry,
logger: Logger,
reserved: readonly ReservedPath[],
publish: (routes: RouteDef[]) => void,
): Promise<{ meshLinks: Closable[]; absent: string[] }> {
const meshLinks: Closable[] = [];
const absent: string[] = []; // urls of teapots that never connected within the boot budget
const teapots = mesh.teapots ?? [];
const table = createRemoteTable(
teapots.map((teapot) => teapot.url),
registry,
logger,
reserved,
publish,
);
const ctx: MembershipContext = { mesh, bus, logger, table };
try {
for (const teapot of teapots) {
warnIfCleartext(teapot.url, logger);
const holder: { link?: Link } = {};
const link = await connectUntilDeadline(mesh, bus, logger, teapot.url, () => connectTeapot(ctx, teapot, holder));
if (!link) {
absent.push(teapot.url);
const bounds = lateBounds(mesh);
if (bounds) meshLinks.push(retryLateTeapot(ctx, teapot, bounds));
continue;
}
holder.link = link;
meshLinks.push(link);
const { steps, routes } = buildRemote(link);
const origin = `mesh:${teapot.url}`;
@@ -1009,79 +1365,14 @@ async function spliceRemoteScopes(
registry.setRunner(step.name, step.run);
}
for (const route of routes) {
const display = `${route.method} ${route.pattern}`;
const key = `${route.method} ${compilePattern(route.pattern).shape}`;
const owner = routeOwners.get(key);
// Fail the boot rather than pick one. Route matching keeps the first of two identical
// patterns, so the loser would be silently dead — and callers could come to depend on
// "first teapot wins", which would make adding balancing later a breaking change.
// Scope tokens already fail this way in setRunner; routes now match.
if (owner) {
throw new Error(
`mesh: ambiguous remote route '${display}' from ${teapot.url} conflicts with ` +
`'${route.method} ${owner.pattern}' from ${owner.url} — ` +
'load balancing across teapots is not implemented yet, so green-tea will not choose one for you. ' +
'Export it from a single teapot.',
);
}
routeOwners.set(key, { url: teapot.url, pattern: route.pattern });
assertNoRemoteSiblingConflict(remoteAccepted, {
method: route.method,
pattern: route.pattern,
url: teapot.url,
});
remoteAccepted.push({ method: route.method, pattern: route.pattern, url: teapot.url });
// Local routes are merged ahead of remote ones (see buildHttpRoutes), so a local twin
// wins. That precedence is deliberate — your own code beats an imported one, and it is
// how you override a teapot — but silently shadowing an export looks exactly like a
// broken teapot from the outside. Warn and let the developer decide.
if (
registry.routePlans.some(
(plan) =>
plan.method === route.method &&
compilePattern(plan.pattern).shape === compilePattern(route.pattern).shape,
)
) {
logger.warn(
`mesh: route '${display}' is exported by teapot ${teapot.url} but also declared locally — ` +
'the local route takes precedence and the remote one will not be reached. ' +
'Remove one if that is not what you meant.',
);
}
// Marked so the router files it in the remote tree; precedence is unchanged by the split.
remoteRoutes.push(
markRemoteRoute({
method: route.method,
pattern: route.pattern,
transport: 'buffer',
// Built explicitly rather than cast from the handler argument. The cast put the whole
// internal request on the wire — `ip` and `protocol` included — and sent fields the
// protocol never declared, so a teapot could come to rely on something we never promised.
handler: async (req) =>
route.handler({
method: req.method,
params: req.params,
query: req.query,
body: req.body,
headers: req.headers,
url: req.url,
correlation: { requestId: req.requestId, traceId: req.traceId },
}),
}),
);
}
table.set(teapot.url, routes, true);
}
} catch (err) {
closeLinks(meshLinks);
throw err;
}
return { remoteRoutes, meshLinks, absent };
return { meshLinks, absent };
}
/** Swaps provider/step runners by token — a value replaces the runner, a function becomes it. */
@@ -1225,6 +1516,21 @@ function makeAppBooter(
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.
* Returns undefined when there is nothing to export; throws if exports are declared without a gating secret.
@@ -1232,7 +1538,13 @@ function makeAppBooter(
function buildMeshControl(
mesh: MeshConfig | undefined,
registry: Registry,
deps: { container: Container; orderedProviders: GraphNode[]; orderedSteps: GraphNode[]; deps: PipelineDeps },
deps: {
container: Container;
orderedProviders: GraphNode[];
orderedSteps: GraphNode[];
deps: PipelineDeps;
maxBodyBytes?: number;
},
): MeshControl | undefined {
const { exportedSteps, exportedRoutes, routePlans, runners } = registry;
const hasExports = exportedSteps.length || exportedRoutes.length;
@@ -1303,11 +1615,49 @@ function buildMeshControl(
return result;
};
return createMeshControl({ secret: mesh.secret, manifest, resolveScope, resolveRoute, bus });
return createMeshControl({
secret: mesh.secret,
manifest,
resolveScope,
resolveRoute,
bus,
maxBodyBytes: deps.maxBodyBytes,
});
}
/** Compiles every non-ws route plan into an HTTP route that seeds and runs the pipeline, plus any remote routes. */
function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps: PipelineDeps): RouteDef[] {
/**
* The one HTTP route table, shared by app.fetch and listen(): local and dev routes, then remote ones.
* Built after boot, on first use. A mesh membership change publishes a new array with the same local
* head (D15), so the router reuses its local trees and rebuilds only the remote ones, and a request in
* flight keeps the array it read. Dev routes sit before the remote ones so their positions, and with
* them the local trees, do not move when remote routes come and go.
*/
function createRouteTable(buildLocal: () => RouteDef[]): {
current: () => RouteDef[];
publish: (remote: RouteDef[]) => void;
} {
let remote: RouteDef[] = [];
let local: RouteDef[] | undefined;
let table: RouteDef[] | undefined;
return {
current: () => {
if (!table) {
local = buildLocal();
table = [...local, ...remote];
}
return table;
},
publish: (next) => {
remote = next;
if (local) table = [...local, ...next];
},
};
}
/** Compiles every non-ws route plan into an HTTP route that seeds and runs the pipeline. */
function buildHttpRoutes(routePlans: RoutePlan[], deps: PipelineDeps): RouteDef[] {
const { providedSeed, planSteps, bus, onError, logger } = deps;
const local = routePlans
@@ -1352,7 +1702,7 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps
},
}));
return [...local, ...remoteRoutes];
return local;
}
/**
@@ -1363,20 +1713,28 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps
* costs one flag check per request after the first.
*/
function buildAppFetch(
routePlans: RoutePlan[],
deps: PipelineDeps,
fetchOpts: HttpOptions,
ensureBooted: () => Promise<void>,
devRoutes: () => RouteDef[],
getRemoteRoutes: () => RouteDef[],
getRoutes: () => RouteDef[],
): (request: Request) => Promise<Response> {
let handler: ((request: Request) => Promise<Response>) | undefined;
return async (request: Request): Promise<Response> => {
// Before the boot, or `/__ready__` could never say `booting`: it would wait for the boot to end.
// The boot is still started, not awaited: on the edge, or under a bare `Deno.serve(app.fetch)`,
// nothing else may boot the app, and an orchestrator that waits for ready before sending traffic
// would wait forever. The rejection is dropped here only; the memo keeps it for real requests.
const probe = answerFetchProbe(request, fetchOpts);
if (probe) {
ensureBooted().catch(() => {});
return probe;
}
await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted
if (!handler) {
handler = buildFetch([...buildHttpRoutes(routePlans, getRemoteRoutes(), deps), ...devRoutes()], fetchOpts);
handler = buildFetch(getRoutes, fetchOpts);
}
return handler(request);
@@ -1395,7 +1753,15 @@ function buildAppUpgrade(
streams: Set<() => void>,
ensureBooted: () => Promise<void>,
getMeshControl: () => MeshControl | undefined,
limits?: RequestLimits,
{
limits,
trustProxy,
meshBounds,
}: {
limits?: RequestLimits;
trustProxy?: boolean;
meshBounds: ReturnType<typeof controlBounds>;
},
): (request: WsRequest, socket: WsSocket) => Promise<void> {
let wsRoutes: WsRouteDef[] | undefined;
@@ -1404,10 +1770,9 @@ function buildAppUpgrade(
// with no subscriber is dropped, so anything the peer sends while providers are still booting
// would be lost. For the mesh control channel that is the `hello` itself — the handshake would
// hang until timeout against a teapot whose providers happened to boot slowly.
const ready = boundInbound(socket, limits);
await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted
// 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
// its peer authenticates. Until then, and so throughout the boot, it takes hello-sized frames.
let path: string;
// The same normalization HTTP and the Node upgrade listener run. A malformed escape would
@@ -1415,10 +1780,17 @@ function buildAppUpgrade(
try {
path = normalizeRequestPath(request.url.split('?')[0]);
} catch {
ready.close(1008, 'invalid request path');
socket.close(1008, 'invalid request path');
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();
// The reserved mesh path, checked before route matching: this is what lets a teapot export
@@ -1427,7 +1799,7 @@ function buildAppUpgrade(
// an explicit refusal, not "no matching ws route": the path is reserved either way, and a
// peer that reached a teapot with nothing exported deserves to be told which it was
if (!meshControl) {
ready.close(1008, 'mesh control channel not enabled: this app exports nothing, or has no mesh.secret');
ready.close(1008, MESH_CONTROL_DISABLED_REASON);
return;
}
@@ -1444,10 +1816,20 @@ function buildAppUpgrade(
return;
}
await runWsConnection(ready, request, route, deps.bus, streams);
await runWsConnection(ready, withProxyClient(request, trustProxy), route, deps.bus, streams);
};
}
/**
* `request` with `ip` taken from the proxy header its adapter recorded, when `trustProxy` allows it
* (the edge adapter's `cf-connecting-ip`, CARD-23); otherwise `request` unchanged. The same check
* `app.fetch` runs, so an edge WebSocket upgrade and an edge HTTP request resolve `ctx.ip` alike.
*/
function withProxyClient(request: WsRequest, trustProxy: boolean | undefined): WsRequest {
const ip = trustedProxyClient(request, trustProxy);
return ip ? { ...request, ip } : request;
}
/** The dev-only `/__graph__` route: serves the dependency graph as Mermaid text or an HTML viewer. */
function devGraphRoute(graph: () => GraphView): RouteDef {
return {
@@ -1560,7 +1942,7 @@ function runTeardown(teardown: TeardownRegistry, logger: Logger, budgetMs: numbe
function closeApp(
server: http.Server | undefined,
meshLinks: Link[],
meshLinks: Closable[],
streams: Set<() => void>,
options: { timeoutMs?: number },
defaultTimeoutMs: number | undefined,
@@ -1645,7 +2027,7 @@ function closeApp(
}
/** Best-effort close of every mesh link, ignoring individual failures. */
function closeLinks(links: Link[]): void {
function closeLinks(links: Closable[]): void {
for (const link of links) {
try {
link.close();
+23
View File
@@ -37,6 +37,15 @@ export interface Explain {
/** A running application instance with lifecycle, introspection and graph-export methods. */
export interface App {
listen(port: number): Promise<http.Server>;
/**
* Drains in-flight work, closes the server and mesh links, then runs teardown, all within
* `timeoutMs` (default `shutdownTimeoutMs`, else 10s).
*
* With `createApp({ health })` on, `/__ready__` answers `503 {"status":"draining"}` from the first
* line of this call, and the listener stays open for `health.drainDelayMs` before draining starts.
* That window is part of `timeoutMs`. On Deno and Bun the same happens in the `close()` that
* `serveDeno()`/`serveBun()` return.
*/
close(options?: { timeoutMs?: number }): Promise<void>;
/**
* Wires `SIGINT`/`SIGTERM` to `closer` and returns a close that also unregisters them — or
@@ -135,6 +144,13 @@ export interface MeshConfig {
* `false` restores that fail-once behaviour. An object tunes the backoff, which doubles from
* `initialDelayMs` (500ms) up to `maxDelayMs` (30s) with jitter, so teacups that went down
* together do not come back in lockstep.
*
* It also decides what a dropped teapot's routes do (D15). While a link is reconnecting its routes
* stay in the table and answer `503` with `retry-after`, and `Allow` keeps them. A link that gives
* up for good — dropped with `reconnect: false`, or refused permanently (a wrong secret, a
* protocol mismatch) while reconnecting — has its routes removed: they answer `404` and leave
* `Allow`. Each change emits `mesh:routes` with `{ url, added, removed }`. A teapot that missed
* `bootTimeoutMs` is retried in the background with this backoff, unless it is `false`.
*/
reconnect?: boolean | { initialDelayMs?: number; maxDelayMs?: number };
/**
@@ -145,6 +161,9 @@ export interface MeshConfig {
* Serving against a manifest that no longer backs the graph would surface as a 500 that looks
* like application code. A future `'reconcile'` will rebuild the graph instead; it is named here
* rather than left implicit so that arriving is additive rather than a change of default.
*
* Only steps count. Routes are not part of the graph, so a returning teapot's routes replace its
* old ones: a route it added is served, one it dropped answers `404` (D15).
*/
onManifestChange?: 'refuse';
/**
@@ -161,6 +180,10 @@ export interface MeshConfig {
* one of its tokens still fails the boot, naming it. A permanent refusal — a wrong secret, a
* protocol mismatch — fails at once without spending the grace.
*
* After boot, such a teapot keeps being retried in the background with the `reconnect` backoff
* (not with `reconnect: false`). When it connects, its routes are added to the table and served;
* its steps are not, because the graph was validated at boot without them (D15).
*
* `0` means one attempt and no grace. That is the attempt count boot used to have, and nothing
* more: exhausting it no longer fails the boot, so a single unreachable teapot still warns and
* starts. To make a teapot's absence fatal, have something local `@needs` one of its tokens.
+41 -5
View File
@@ -1,7 +1,14 @@
import { channel } from './channel';
import type { Channel } from './channel';
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 { decodeMessage, neutralSocket, toWsRequest, upgradeSafely } from './http/ws-adapter';
import { closeWithDeadline } from './http/shutdown';
import { setPeer } from './http/peer';
@@ -14,12 +21,15 @@ interface BunServerWebSocket {
send(data: string): number;
close(code?: number, reason?: string): void;
terminate?(): void;
/** Bytes queued and not yet written; Bun's counterpart to `WebSocket.bufferedAmount`. */
getBufferedAmount?(): number;
}
interface BunWebSocketHandler {
maxPayloadLength?: number;
open?(ws: BunServerWebSocket): void;
message(ws: BunServerWebSocket, message: string | Uint8Array): void;
close?(ws: BunServerWebSocket, code: number, reason: string): void;
drain?(ws: BunServerWebSocket): void;
error?(ws: BunServerWebSocket, error?: unknown): void;
}
interface BunServer {
@@ -57,6 +67,13 @@ interface BunConnData {
wsReq: WsRequest;
inbound: Channel<unknown>;
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());
}
/**
@@ -65,9 +82,17 @@ interface BunConnData {
* created during the upgrade and stashed on ws.data — there is nothing here to wire up.
*/
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 });
}
/**
@@ -97,7 +122,7 @@ export async function serveBun(app: App, options?: BunServeShortOptions): Promis
const inbound = channel();
const ac = new AbortController();
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;
return new Response('WebSocket upgrade failed', { status: 400 });
}
@@ -111,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
// 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.
// 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:
(app as { [WS_MAX_MESSAGE_BYTES]?: number })[WS_MAX_MESSAGE_BYTES] ?? DEFAULT_MAX_WS_MESSAGE_BYTES,
open(ws) {
@@ -123,15 +150,20 @@ export async function serveBun(app: App, options?: BunServeShortOptions): Promis
inbound.push(decodeMessage(message));
},
drain(ws) {
releaseDrain(ws);
},
close(ws) {
const { inbound, ac } = ws.data as BunConnData;
inbound.close();
ac.abort();
releaseDrain(ws);
},
error(ws) {
const { inbound, ac } = ws.data as BunConnData;
inbound.fail(new Error('websocket error'));
ac.abort();
releaseDrain(ws);
},
},
});
@@ -149,7 +181,11 @@ export async function serveBun(app: App, options?: BunServeShortOptions): Promis
// registry, which is what makes one `close()` enough here instead of two. Called without
// options on purpose: passing a timeout it cannot use to drain would only earn its warning,
// and the deadline below already bounds the whole call.
() => server.stop(false).then(() => app.close()),
// The drain window first: `/__ready__` answers 503 while the listener is still open (D14).
() =>
beginDrain(app)
.then(() => server.stop(false))
.then(() => app.close()),
() => void server.stop(true),
closeOptions.timeoutMs ?? 10_000,
(ms) =>
+9
View File
@@ -45,6 +45,9 @@ export type LifecycleEvent =
// Separate from `mesh:disconnect`, which is a link that was up and went away — this one never
// came up, and a deploy watching for trouble wants to tell those apart.
| 'mesh:boot:retry'
// A teacup's remote routes changed after boot (D15): a late teapot connected, a returning one
// exported a different set, or a link gave up for good. Carries `url`, `added` and `removed`.
| 'mesh:routes'
| 'plugin:mounted'
// Paired: see the guarantee above. `request:start` has no status and no duration — it says a
// request arrived, not that it routed.
@@ -125,6 +128,12 @@ export interface EventPayload {
* framework does not know what was sent, and will not guess.
*/
status?: number;
/** `mesh:routes`: the teapot whose routes changed. */
url?: string;
/** `mesh:routes`: routes added to the remote table, as `'METHOD /pattern'`. */
added?: string[];
/** `mesh:routes`: routes removed from the remote table, as `'METHOD /pattern'`. */
removed?: string[];
}
/**
+150
View File
@@ -0,0 +1,150 @@
// src/cookies.ts — request cookie parsing and `Set-Cookie` serialisation (RFC 6265), dependency-free.
/**
* Options for {@link setCookie}. Every attribute is optional; the defaults are the safe ones
* (`httpOnly: true`, `sameSite: 'lax'`, `path: '/'`, `secure: true`).
*/
export interface CookieOptions {
/** `Max-Age` in seconds. An integer; `0` or a negative value tells the browser to drop the cookie. */
maxAge?: number;
/** `Expires`, written as an HTTP date. `maxAge` wins in browsers when both are set. */
expires?: Date;
/** `Path`. Default `'/'`. */
path?: string;
/** `Domain`. Omitted by default, which scopes the cookie to the exact host that set it. */
domain?: string;
/**
* `Secure`. Default `true`: Chrome, Edge and Firefox accept a `Secure` cookie on
* `http://localhost`. Safari, a LAN IP or a plain-HTTP dev hostname do not — pass `false` there
* (for example `secure: !isDev`).
*/
secure?: boolean;
/** `HttpOnly`. Default `true`, so page scripts cannot read the cookie. */
httpOnly?: boolean;
/** `SameSite`. Default `'lax'`. `'none'` requires `secure`. */
sameSite?: 'strict' | 'lax' | 'none';
/** `Partitioned` (CHIPS). Requires `secure`. */
partitioned?: boolean;
}
/** RFC 6265 §4.1.1 cookie-name: an RFC 7230 token. */
const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
/** What a cookie value may not contain: CR, LF, `;`, `,`, whitespace and every control character. */
// eslint-disable-next-line no-control-regex
const BAD_VALUE = /[\u0000- ;,\u007f]/;
/**
* What an attribute value may not contain. CR/LF is the header-injection case the card names; `;`
* and the other control characters are refused too, because a `;` inside `Path` would start a new
* attribute and change what the cookie means without breaking the header.
*/
// eslint-disable-next-line no-control-regex
const BAD_ATTRIBUTE = /[\u0000-\u001f;\u007f]/;
const SAME_SITE = { strict: 'Strict', lax: 'Lax', none: 'None' } as const;
/**
* Serialises one `Set-Cookie` header value.
*
* Throws, naming the field, rather than producing a header that would split or reshape the
* response: a name outside the RFC 6265 token set, a value carrying CR, LF, `;`, `,`, whitespace or a
* control character, an attribute carrying CR/LF, `;` or a control character, a non-integer
* `maxAge`, an invalid `expires`, and `sameSite: 'none'` or `partitioned` without `secure`.
*
* The value is written as given. Encode it yourself (`encodeURIComponent`) if it can hold any of the
* refused characters; the cookie decorators decode `%`-sequences on the way back in.
*
* Several cookies on one response go in an array: `headers: { 'set-cookie': [a, b] }`, and each
* element is sent as its own `Set-Cookie` line on every adapter.
*
* @example
* setCookie('session', id, { maxAge: 3600 })
* // 'session=<id>; Max-Age=3600; Path=/; Secure; HttpOnly; SameSite=Lax'
*/
export function setCookie(name: string, value: string, options: CookieOptions = {}): string {
if (typeof name !== 'string' || !TOKEN.test(name))
throw new TypeError(`setCookie: name ${JSON.stringify(name)} is not a valid cookie name (RFC 6265 token)`);
if (typeof value !== 'string' || BAD_VALUE.test(value))
throw new TypeError(
`setCookie: value for '${name}' contains a character a cookie value cannot carry (CR, LF, ';', ',', whitespace or a control character)`,
);
const secure = options.secure ?? true;
const sameSite = options.sameSite ?? 'lax';
const parts = [`${name}=${value}`];
if (options.maxAge !== undefined) {
if (!Number.isInteger(options.maxAge)) throw new TypeError(`setCookie: maxAge for '${name}' must be an integer`);
parts.push(`Max-Age=${options.maxAge}`);
}
if (options.expires !== undefined) {
if (!(options.expires instanceof Date) || Number.isNaN(options.expires.getTime()))
throw new TypeError(`setCookie: expires for '${name}' must be a valid Date`);
parts.push(`Expires=${options.expires.toUTCString()}`);
}
if (options.domain !== undefined) parts.push(`Domain=${attribute(name, 'domain', options.domain)}`);
parts.push(`Path=${attribute(name, 'path', options.path ?? '/')}`);
if (secure) parts.push('Secure');
if (options.httpOnly ?? true) parts.push('HttpOnly');
if (!Object.prototype.hasOwnProperty.call(SAME_SITE, sameSite))
throw new TypeError(`setCookie: sameSite for '${name}' must be 'strict', 'lax' or 'none'`);
if (sameSite === 'none' && !secure)
throw new TypeError(`setCookie: sameSite 'none' for '${name}' requires secure (browsers reject it otherwise)`);
parts.push(`SameSite=${SAME_SITE[sameSite]}`);
if (options.partitioned) {
if (!secure) throw new TypeError(`setCookie: partitioned for '${name}' requires secure`);
parts.push('Partitioned');
}
return parts.join('; ');
}
function attribute(name: string, field: string, value: string): string {
if (typeof value !== 'string' || value === '' || BAD_ATTRIBUTE.test(value))
throw new TypeError(
`setCookie: ${field} for '${name}' must be a non-empty string without CR, LF, ';' or control characters`,
);
return value;
}
/**
* Parses a request `Cookie` header into a name → value map (RFC 6265 §5.2 / §4.2).
*
* - The first value wins for a repeated name — the browser sends the most specific cookie first.
* - `%`-sequences are decoded; a value that fails to decode is kept raw rather than rejected.
* - A malformed pair (no `=`, or an empty name) is skipped. A broken cookie never becomes a 400:
* the header is client state the server did not choose and the request may not even need it.
* - Several `cookie` lines (HTTP/2, some proxies) arrive as an array and are joined with `; `.
*
* The map has no prototype, so a cookie named `__proto__` or `constructor` is just a key.
*/
export function parseCookies(header: string | string[] | undefined): Record<string, string> {
const out: Record<string, string> = Object.create(null);
if (header === undefined) return out;
const raw = Array.isArray(header) ? header.join('; ') : header;
for (const pair of raw.split(';')) {
const eq = pair.indexOf('=');
if (eq === -1) continue;
const key = pair.slice(0, eq).trim();
if (key === '' || key in out) continue;
out[key] = decode(pair.slice(eq + 1).trim());
}
return out;
}
function decode(value: string): string {
if (!value.includes('%')) return value;
try {
return decodeURIComponent(value);
} catch {
return value;
}
}
+6 -1
View File
@@ -1,4 +1,5 @@
import type { App } from './app/types';
import { beginDrain } from './http/health';
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
import { closeWithDeadline } from './http/shutdown';
import { setPeer } from './http/peer';
@@ -102,7 +103,11 @@ export async function serveDeno(app: App, options?: DenoServeOptions): Promise<D
// registry, which is what makes one `close()` enough here instead of two. Called without
// options on purpose: passing a timeout it cannot use to drain would only earn its warning,
// and the deadline below already bounds the whole call.
() => server.shutdown().then(() => app.close()),
// The drain window first: `/__ready__` answers 503 while the listener is still open (D14).
() =>
beginDrain(app)
.then(() => server.shutdown())
.then(() => app.close()),
// Nothing to force, and that is Deno's constraint rather than an omission here. Its two
// levers are mutually exclusive: aborting the serve signal after `shutdown()` is already
// pending throws `BadResource: Bad resource ID` from Deno's own abort listener, which
+16 -1
View File
@@ -1,5 +1,6 @@
import type { App } from './app/types';
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
import { setProxyClient } from './http/peer';
// Minimal ambient for the Cloudflare Workers globals we use — avoids @cloudflare/workers-types.
// Declares only what we call; mirrors the real workerd signatures.
@@ -30,7 +31,9 @@ export function edgeHandler(
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
const [client, server] = Object.values(new WebSocketPair()) as [EdgeWebSocket, EdgeWebSocket];
server.accept();
const wsReq = toWsRequest(request, request.headers.get('cf-connecting-ip') ?? '');
// No peer address on the edge, so `ip` starts empty; the header only fills it under `trustProxy`.
const wsReq = toWsRequest(request, '');
recordClient(wsReq, request);
const lifecycle = upgradeSafely(app, wsReq, eventSocket(server));
if (ctx?.waitUntil) ctx.waitUntil(lifecycle);
else void lifecycle;
@@ -38,6 +41,18 @@ export function edgeHandler(
return new Response(null, { status: 101, webSocket: client } as ResponseInit & { webSocket: EdgeWebSocket });
}
recordClient(request, request);
return app.fetch(request);
};
}
/**
* Hands the app the `cf-connecting-ip` header for `source`, the object the app will be given for this
* request. The app — not this adapter — decides whether it counts, since `trustProxy` is an app
* option; HTTP and WebSocket both go through here and through the same check on the app side.
* Without `trustProxy` the header is ignored and `ctx.ip` stays `''`: workerd exposes no peer address,
* and an untrusted header is whatever the client chose to send.
*/
function recordClient(source: object, request: Request): void {
setProxyClient(source, request.headers.get('cf-connecting-ip') ?? '');
}
+36 -3
View File
@@ -42,10 +42,43 @@ export interface GraphNode {
origin: string;
}
/** Orders nodes so every dependency precedes its dependents; throws on missing keys or cycles. */
export function topoSort(nodes: GraphNode[], seedKeys: string[], note = ''): GraphNode[] {
/**
* Maps every token to the one node that produces it; throws when a second node provides a token.
*
* One producer per token, across modules, plugins, mesh steps and built-ins alike (GitHub #35, D9).
* This used to be `producedBy.set(key, node)`, last one wins: plugin nodes are registered after
* module nodes, so a plugin's `scope.add` that provided `user` silently replaced the app's own `user`
* for every route that needed it. Checking here, on the whole graph, rather than at each place a node
* is registered, is what covers every path — current and future — and makes the built-in tokens
* (`logger`, `rooms`, `events`) safe by rule instead of by registration order.
*/
function producers(nodes: GraphNode[]): Map<string, GraphNode> {
const producedBy = new Map<string, GraphNode>();
for (const node of nodes) for (const key of node.provides) producedBy.set(key, node);
for (const node of nodes) {
for (const key of node.provides) {
const prior = producedBy.get(key);
if (prior && prior !== node) {
throw new Error(
`token '${key}' is provided twice: by '${prior.name}' (${prior.origin}) and by '${node.name}' (${node.origin}) — ` +
'a token has exactly one producer; rename one of them, or use `overrides` to replace a runner',
);
}
producedBy.set(key, node);
}
}
return producedBy;
}
/**
* Orders nodes so every dependency precedes its dependents; throws on a token with two producers,
* missing keys or cycles.
*/
export function topoSort(nodes: GraphNode[], seedKeys: string[], note = ''): GraphNode[] {
const producedBy = producers(nodes);
// validate dependencies exist
for (const node of nodes) {
+1 -1
View File
@@ -8,7 +8,7 @@ import type { MatchedRoute, HttpOptions } from './types';
/** A ready-to-send error response produced while acquiring the request body. */
export interface BodyFailure {
fail: { status: number; headers: Record<string, string>; body: string };
fail: { status: number; headers: Record<string, string | string[]>; body: string };
}
/** A value, or a promise of one. Readers that have nothing to await return the value directly. */
+3 -3
View File
@@ -85,10 +85,10 @@ export function correlateRequest(headers: Record<string, string | string[] | und
/** The neutral shape of a response: a fully buffered body, or a stream to pipe frame-by-frame. */
export type NeutralOutcome =
| { kind: 'buffered'; status: number; headers: Record<string, string>; body: string | Buffer }
| { kind: 'buffered'; status: number; headers: Record<string, string | string[]>; body: string | Buffer }
| {
kind: 'stream';
headers: Record<string, string>;
headers: Record<string, string | string[]>;
stream: AsyncIterable<unknown>;
encoder: StreamEncoder;
/** The matched route's pattern, for naming the stream lifecycle events. */
@@ -126,7 +126,7 @@ function errorOutcome(
req: NeutralRequest,
injected: Record<string, string>,
opts: HttpOptions | undefined,
headers: Record<string, string> = {},
headers: Record<string, string | string[]> = {},
): HandleResult {
const rendered = renderError(error, req, opts?.onError, opts?.logger);
return {
+46 -1
View File
@@ -19,7 +19,10 @@ export function mergeInjectedHeaders(
const lowerKey = key.toLowerCase();
if (lowerKey === 'vary') {
handlerVary = handlerHeaders[key];
// A header value may be an array (D11). `mergeVary` splits on commas, so joining first keeps
// every token a handler listed instead of stringifying the array by accident.
const value = handlerHeaders[key];
handlerVary = Array.isArray(value) ? value.join(', ') : value;
continue;
}
@@ -40,3 +43,45 @@ export function mergeInjectedHeaders(
else if (handlerVary !== undefined) merged['vary'] = handlerVary;
return merged;
}
/**
* Prepares merged headers for Node's `writeHead`, which writes one header line per array element
* for *any* header. That is right for `set-cookie`, the one header whose values cannot be
* comma-joined (an `Expires` date carries a comma), and wrong for every other: RFC 9110 §5.3 makes a
* list header's repeated lines equivalent to one comma-joined line, and joining keeps all four
* adapters sending the same bytes. So every other array is joined with `, ` here, before
* `writeHead`. Returns the input untouched when it holds no array, which is nearly every response.
*/
export function joinListHeaders<T extends Record<string, unknown>>(headers: T): T {
let out: Record<string, unknown> | undefined;
for (const key of Object.keys(headers)) {
const value = headers[key];
if (!Array.isArray(value) || key.toLowerCase() === 'set-cookie') continue;
out ??= { ...headers };
out[key] = value.join(', ');
}
return (out as T | undefined) ?? headers;
}
/**
* Builds a web `Headers` from merged headers. A plain record cannot be handed to `new Response`:
* the Fetch spec stringifies an array value to `a,b`, which for `set-cookie` is one broken cookie.
* `set-cookie` elements are appended one by one, so each reaches the client as its own line;
* every other array is joined with `, `, exactly as {@link joinListHeaders} does for Node.
*/
export function toWebHeaders(headers: Record<string, unknown>): Headers {
const out = new Headers();
for (const key of Object.keys(headers)) {
const value = headers[key];
if (value === undefined) continue;
if (!Array.isArray(value)) out.set(key, String(value));
else if (key.toLowerCase() === 'set-cookie') for (const cookie of value) out.append(key, String(cookie));
else out.set(key, value.join(', '));
}
return out;
}
+170
View File
@@ -0,0 +1,170 @@
import type { ReservedPath } from './reserved-paths';
/** Liveness probe path: `200` whenever the process answers. */
export const LIVE_PATH = '/__live__';
/** Readiness probe path: `503` while booting or draining, `200` otherwise. */
export const READY_PATH = '/__ready__';
/** The probe paths, as reserved-path entries for the boot check (only while `health` is on). */
export const HEALTH_RESERVED: readonly ReservedPath[] = [
{ path: LIVE_PATH, purpose: 'the liveness probe, health: true' },
{ path: READY_PATH, purpose: 'the readiness probe, health: true' },
];
/**
* Where an app is in its life, as `/__ready__` reports it.
*
* `booting` until `boot()` resolves, `ready` after, `draining` from the moment `close()` starts.
* Moves forward only: a boot that finishes while draining does not make the app ready again.
*/
export type HealthPhase = 'booting' | 'ready' | 'draining';
/** What the adapters read to answer a probe. Lives on {@link HttpOptions}; absent when `health` is off. */
export interface HealthProbe {
phase(): HealthPhase;
/** Optional providers that failed to boot, as `app.degraded()` reports them. */
degraded(): string[];
}
/**
* Close-time hook on the app object for the adapters that own the server (`serveDeno`, `serveBun`):
* marks the app draining and resolves after `drainDelayMs`, so the listener stays open while
* `/__ready__` answers `503`. Idempotent — later calls share the first window. Symbol-keyed because it
* is adapter plumbing, not public API.
*/
export const HEALTH_DRAIN: unique symbol = Symbol.for('green-tea.health-drain');
/** Starts the drain window on `app` (see {@link HEALTH_DRAIN}); resolves at once when health is off. */
export function beginDrain(app: object): Promise<void> {
return (app as { [HEALTH_DRAIN]?: () => Promise<void> })[HEALTH_DRAIN]?.() ?? Promise.resolve();
}
/** A probe response, before the adapter merges in the injected security headers. */
export interface ProbeAnswer {
status: number;
headers: Record<string, string>;
body: string;
}
const JSON_NO_STORE = { 'content-type': 'application/json', 'cache-control': 'no-store' };
/** The readiness body and status for the current phase. */
function readiness(probe: HealthProbe): { status: number; body: object } {
const phase = probe.phase();
if (phase === 'booting') return { status: 503, body: { status: 'booting' } };
if (phase === 'draining') return { status: 503, body: { status: 'draining' } };
const degraded = probe.degraded();
return degraded.length
? { status: 200, body: { status: 'degraded', degraded } }
: { status: 200, body: { status: 'ok' } };
}
/**
* Answers `/__live__` or `/__ready__`, or returns `undefined` for any other path.
*
* Called by each adapter before the request gate and before `handle()`, so a probe runs no step,
* provider, plugin or `onError`, emits no lifecycle event, and is never shed by
* `maxConcurrentRequests`. `url` may carry a query string; only the exact path is a probe.
*/
export function answerProbe(method: string, url: string, probe: HealthProbe): ProbeAnswer | undefined {
const query = url.indexOf('?');
const path = query === -1 ? url : url.slice(0, query);
if (path !== LIVE_PATH && path !== READY_PATH) return undefined;
if (method !== 'GET' && method !== 'HEAD') {
return {
status: 405,
headers: { ...JSON_NO_STORE, allow: 'GET, HEAD' },
body: JSON.stringify({ error: 'Method Not Allowed' }),
};
}
const { status, body } = path === LIVE_PATH ? { status: 200, body: { status: 'ok' } } : readiness(probe);
return { status, headers: { ...JSON_NO_STORE }, body: method === 'HEAD' ? '' : JSON.stringify(body) };
}
/** `createApp({ health })`, normalised. `undefined` when health is off. */
export interface HealthConfig {
drainDelayMs: number;
}
/**
* Validates `createApp({ health })` and normalises it. Throws on anything but `true`, `false`,
* `undefined` or `{ drainDelayMs?: number }`, and on a `drainDelayMs` that does not fit in the shutdown
* budget next to the teardown reservation.
*/
export function resolveHealth(
health: unknown,
shutdownTimeoutMs: number | undefined,
teardownTimeoutMs: number | undefined,
): HealthConfig | undefined {
if (health === undefined || health === false) return undefined;
if (health === true) return { drainDelayMs: 0 };
if (typeof health !== 'object' || health === null || Array.isArray(health)) {
throw new Error(`health must be true, false or { drainDelayMs?: number } — got ${JSON.stringify(health)}`);
}
const unknown = Object.keys(health).filter((key) => key !== 'drainDelayMs');
if (unknown.length) {
throw new Error(
`health: unknown option ${unknown.map((key) => `'${key}'`).join(', ')} — only drainDelayMs is supported`,
);
}
const drainDelayMs = (health as { drainDelayMs?: unknown }).drainDelayMs ?? 0;
if (typeof drainDelayMs !== 'number' || !Number.isFinite(drainDelayMs) || drainDelayMs < 0) {
throw new Error(`health.drainDelayMs must be a non-negative number of milliseconds — got ${String(drainDelayMs)}`);
}
const budget = shutdownTimeoutMs ?? 10_000;
const reserved = teardownTimeoutMs ?? 0;
if (drainDelayMs + reserved > budget) {
throw new Error(
`health.drainDelayMs (${drainDelayMs}) plus teardownTimeoutMs (${reserved}) cannot exceed ` +
`shutdownTimeoutMs (${budget}) — the drain window is spent out of the shutdown budget, ` +
'so close() would have no time left to drain connections or run teardown.',
);
}
return { drainDelayMs };
}
/**
* The health state machine for one app: wraps `bootGraph` so a resolved boot marks it ready, and
* offers the drain that `close()` (and `serveDeno`/`serveBun` through {@link HEALTH_DRAIN}) starts.
* With health off the probe is absent and the drain resolves at once.
*/
export function trackHealth(
health: HealthConfig | undefined,
bootGraph: () => Promise<void>,
degraded: () => string[],
): { bootApp: () => Promise<void>; healthProbe: HealthProbe | undefined; drain: () => Promise<void> } {
// Forward only: a boot that resolves after close() started stays draining.
let phase: HealthPhase = 'booting';
// Shared by every drain call. Left referenced on purpose: the process must stay up for the window.
let drainWindow: Promise<void> | undefined;
const bootApp = async (): Promise<void> => {
await bootGraph();
if (phase === 'booting') phase = 'ready';
};
const drain = (): Promise<void> => {
if (!health) return Promise.resolve();
if (!drainWindow) {
phase = 'draining';
const ms = health.drainDelayMs;
drainWindow = ms > 0 ? new Promise((resolve) => setTimeout(resolve, ms)) : Promise.resolve();
}
return drainWindow;
};
return { bootApp, healthProbe: health ? { phase: () => phase, degraded } : undefined, drain };
}
+25
View File
@@ -25,3 +25,28 @@ export function setPeer(request: Request, ip: string): void {
export function peerOf(request: Request): string {
return peers.get(request) ?? '';
}
// The client address a runtime adapter read from a header its platform's proxy sets — today only the
// edge adapter, from `cf-connecting-ip`. Unlike the socket peer above, a header is client-supplied
// unless a proxy in front overwrites it, so it only counts under `trustProxy`; the adapter cannot
// decide that, because the option lives on the app, so it records the value and the app decides.
// Keyed by the `Request` (HTTP) or the `WsRequest` (WebSocket upgrade) the adapter hands the app, for
// the same reasons as the peer: no handler-visible header, no extra public parameter. Same
// `globalThis` registration, because `@green-tea/core/edge` is a separate bundle too.
const PROXY_KEY = Symbol.for('@green-tea/core:proxy-client');
const proxyRegistry = globalThis as { [PROXY_KEY]?: WeakMap<object, string> };
const proxyClients = (proxyRegistry[PROXY_KEY] ??= new WeakMap<object, string>());
/** Records `ip` as the client address a proxy header named for `source`. An empty value is not recorded. */
export function setProxyClient(source: object, ip: string): void {
if (ip) proxyClients.set(source, ip);
}
/**
* The client address an adapter recorded for `source` from a proxy header, when `trustProxy` is on;
* `''` otherwise. The one check both `app.fetch` and `app.upgrade` run, so HTTP and WebSocket cannot
* disagree about whether the header counts.
*/
export function trustedProxyClient(source: object, trustProxy: boolean | undefined): string {
return trustProxy ? (proxyClients.get(source) ?? '') : '';
}
+49
View File
@@ -0,0 +1,49 @@
import { compilePattern, matchPattern } from './router';
/**
* A path the framework answers itself, ahead of the route table, so no declared route may claim it.
*
* Each adapter intercepts these before route matching. A user route that could also match one would
* be served on some code paths and shadowed on others, which is exactly the "works on Node, refused
* on Deno" split a reserved path exists to prevent, so the boot refuses it instead.
*/
export interface ReservedPath {
/** The concrete request path, e.g. `/__mesh__/control`. */
path: string;
/** What the framework serves there, for the error message (e.g. `the mesh control channel`). */
purpose: string;
}
/**
* Returns the reserved path `pattern` would claim, or `undefined` when it claims none.
*
* A pattern claims a reserved path when it matches it *and* its first segment is the reserved path's
* own first segment, spelled literally. The literal-prefix half is deliberate: `/:org/:repo` or a
* `/:rest*` fallback also match `/__mesh__/control`, but they never ask for it — the adapter intercepts
* the reserved path before matching, so such a route simply never sees that one path, the same way
* on every runtime. Refusing them would fail the boot of ordinary apps for a path they never named.
* A literal pattern is therefore checked by equality and a parameterised one (`/__mesh__/:x`,
* `/__mesh__/:rest*`) by matching the reserved path against it.
*/
export function claimedReservedPath(pattern: string, reserved: readonly ReservedPath[]): ReservedPath | undefined {
const first = compilePattern(pattern).segments[0];
if (first?.kind !== 'static') return undefined;
return reserved.find(
(entry) => entry.path.split('/')[1] === first.value && matchPattern(pattern, entry.path) !== undefined,
);
}
/**
* Throws when `pattern` claims a reserved path. `subject` names the declaration for the message,
* e.g. `route GET /__mesh__/control at Chat.control`.
*/
export function assertNotReserved(pattern: string, subject: string, reserved: readonly ReservedPath[]): void {
const claimed = claimedReservedPath(pattern, reserved);
if (!claimed) return;
throw new Error(
`${subject} uses the reserved path ${claimed.path} (${claimed.purpose}) — ` +
'green-tea answers that path itself on every runtime, so no route may declare it. Move the route.',
);
}
+52 -14
View File
@@ -1,4 +1,4 @@
import type { RouteDef, MatchedRoute } from './types';
import type { RouteDef, RouteTable, MatchedRoute } from './types';
export type CompiledSegment =
| { kind: 'static'; value: string }
@@ -152,9 +152,9 @@ function segmentShape(segment: CompiledSegment): string {
* spy on the export cannot see it, so the counts are kept here; they let a test prove that misses
* after the index is built recompile nothing and rebuild nothing (FPRD-001 CARD-10).
*/
const seamCounts = { compilePattern: 0, indexBuilds: 0 };
const seamCounts = { compilePattern: 0, indexBuilds: 0, localTreeBuilds: 0 };
/** @internal Calls so far to `compilePattern` (cache hits included) and route-index builds. For tests. */
/** @internal Calls so far to `compilePattern` (cache hits included), route-index builds and local-tree builds. For tests. */
export const routerSeamCounts = (): Readonly<typeof seamCounts> => ({ ...seamCounts });
/** Compiles and validates one route pattern. Results are cached by source string. */
@@ -417,6 +417,11 @@ interface RouteIndex {
/** The routes a mesh teacup spliced in from its teapots. Identity-keyed, so a route is remote wherever it travels. */
const remoteRouteDefs = new WeakSet<RouteDef>();
/** The array a {@link RouteTable} holds right now. Servers call it once per request. */
export function currentRoutes(table: RouteTable): RouteDef[] {
return typeof table === 'function' ? table() : table;
}
/** Marks a route as spliced in from a mesh teapot, so the index files it in the remote tree. */
export function markRemoteRoute<T extends RouteDef>(def: T): T {
remoteRouteDefs.add(def);
@@ -505,6 +510,34 @@ function buildTrees(entries: Array<{ def: RouteDef; order: number }>): Map<strin
return trees;
}
/**
* The last local trees built, and the `(def, position)` entries they were built from.
*
* When mesh membership changes, the app publishes a new array whose local entries are the same
* objects at the same positions, with only the remote tail different (CARD-19, D15). Reusing the
* local trees then means a peer coming or going rebuilds the remote trees alone. Keyed by the
* first local def, so it is collected with the table that owns it.
*/
const localTreeCache = new WeakMap<
RouteDef,
{ entries: Array<{ def: RouteDef; order: number }>; trees: Map<string, MethodTree> }
>();
function sameEntries(a: Array<{ def: RouteDef; order: number }>, b: Array<{ def: RouteDef; order: number }>): boolean {
return a.length === b.length && a.every((entry, i) => entry.def === b[i].def && entry.order === b[i].order);
}
function localTrees(local: Array<{ def: RouteDef; order: number }>): Map<string, MethodTree> {
if (!local.length) return buildTrees(local);
const cached = localTreeCache.get(local[0].def);
if (cached && sameEntries(cached.entries, local)) return cached.trees;
seamCounts.localTreeBuilds++;
const trees = buildTrees(local);
localTreeCache.set(local[0].def, { entries: local, trees });
return trees;
}
function routeIndex(routes: RouteDef[]): RouteIndex {
const cached = routeIndexCache.get(routes);
if (cached?.size === routes.length) return cached;
@@ -516,7 +549,7 @@ function routeIndex(routes: RouteDef[]): RouteIndex {
const index: RouteIndex = {
size: routes.length,
local: buildTrees(local),
local: localTrees(local),
remote: remote.length ? buildTrees(remote) : undefined,
methods: [...new Set(routes.map((route) => route.method))],
};
@@ -743,18 +776,23 @@ export function allowedMethods(routes: RouteDef[], path: string): string[] {
});
}
/** Parses a URL's query string into a flat string map (last value wins for repeated keys). */
/**
* Parses a URL's query string into a flat string map (last value wins for repeated keys).
*
* The query string is everything after the **first** `?` and before a `#`, if one is present.
* A `?` inside the query is a legal character (RFC 3986 §3.4), so `/search?q=what?now` gives
* `{ q: 'what?now' }`.
*/
export function parseQuery(url: string): Record<string, string> {
// Most requests carry no query string, and the work below is not free for them: `split` builds
// an array, `new URLSearchParams('')` builds an object, and the loop runs zero times — three
// allocations to arrive at `{}`. Measured at 92.3 ns against 18.6 ns for this check.
//
// Only the guard is new; the parse below is untouched on purpose. Reaching for `indexOf` +
// `slice` instead of `split` would also drop an allocation, but it changes what a second `?`
// means, and that is a behaviour question rather than a performance one.
if (!url.includes('?')) return {};
// Most requests carry no query string, and the work below is not free for them:
// `new URLSearchParams('')` builds an object and the loop runs zero times, to arrive at `{}`.
// Measured at 92.3 ns against 18.6 ns for this check.
const start = url.indexOf('?');
if (start < 0) return {};
const queryString = url.split('?')[1] ?? '';
// `split('?')[1]` used to stop at a second `?` and drop the rest of the value (GitHub #48).
const hash = url.indexOf('#', start + 1);
const queryString = hash < 0 ? url.slice(start + 1) : url.slice(start + 1, hash);
const out: Record<string, string> = {};
for (const [key, value] of new URLSearchParams(queryString)) out[key] = value;
return out;
+25 -7
View File
@@ -6,7 +6,7 @@ import type { Bus } from '../bus';
import { readBody as readBodyBytes, deriveSecure, deriveIp } from './request';
import { pipeStream } from './stream';
import { attachWs } from './ws';
import { mergeInjectedHeaders } from './headers';
import { mergeInjectedHeaders, joinListHeaders } from './headers';
import {
handle,
correlateRequest,
@@ -17,12 +17,14 @@ import {
type Preflight,
} from './core';
import type { BodyFailure, BodyReader } from './body';
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
import type { RouteTable, WsRouteDef, MeshControl, HttpOptions } from './types';
import { currentRoutes } from './router';
import type { Logger } from '../logger';
import { nodeRequire } from '../node-require';
import { answerProbe } from './health';
interface HandlerConfig {
routes: RouteDef[];
routes: RouteTable;
bus?: Bus;
opts?: HttpOptions;
trustProxy: boolean;
@@ -35,14 +37,14 @@ function errorRequest(req: http.IncomingMessage): ErrorRequest {
/**
* Builds an HTTP/HTTPS server that routes requests, parses bodies, streams results, and handles WebSocket upgrades.
* @param routes HTTP route definitions.
* @param routes HTTP route definitions, or a getter read once per request (a mesh teacup's table changes as peers come and go).
* @param wsRoutes WebSocket route definitions (requires the optional `ws` peer dependency).
* @param bus Optional event bus for stream lifecycle events.
* @param meshControl Optional mesh gateway hook for a reserved upgrade path.
* @param opts Limits, TLS, security, CORS, and body-parsing options.
*/
export function createHttpServer(
routes: RouteDef[],
routes: RouteTable,
wsRoutes: WsRouteDef[] = [],
bus?: Bus,
meshControl?: MeshControl,
@@ -116,6 +118,8 @@ function createRequestHandler(cfg: HandlerConfig) {
const injected = computeInjected(opts, { secure, headers: req.headers });
patchResponseHeaders(res, injected);
if (writeProbe(req, res, opts)) return;
let result: HandleResult | Preflight;
let acquired = false;
const watching = watchingRequests(bus);
@@ -158,7 +162,7 @@ function createRequestHandler(cfg: HandlerConfig) {
}
result = await handle(
routes,
currentRoutes(routes), // once per request, see buildFetch
opts,
{
...correlation,
@@ -203,6 +207,20 @@ function createRequestHandler(cfg: HandlerConfig) {
}
}
/**
* 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
* event sees one. Written through the patched writeHead, so the security headers still land.
*/
function writeProbe(req: http.IncomingMessage, res: http.ServerResponse, opts: HttpOptions | undefined): boolean {
const probe = opts?.health && answerProbe(req.method ?? 'GET', req.url ?? '/', opts.health);
if (!probe) return false;
res.writeHead(probe.status, probe.headers);
res.end(probe.body);
return true;
}
/**
* The last resort for a request whose handling rejected. Deliberately does not call `onError`: this
* runs because something already failed past the point where errors convert to a response, and user
@@ -268,7 +286,7 @@ function patchResponseHeaders(res: http.ServerResponse, injected: Record<string,
(res as any).writeHead = (status: number, arg2?: any, arg3?: any) => {
const handlerHeaders = (typeof arg2 === 'string' ? arg3 : arg2) as Record<string, any> | undefined;
const merged = mergeInjectedHeaders(handlerHeaders, injected);
const merged = joinListHeaders(mergeInjectedHeaders(handlerHeaders, injected));
return typeof arg2 === 'string' ? origWriteHead(status, arg2, merged) : origWriteHead(status, merged);
};
}
+19
View File
@@ -1,4 +1,5 @@
import type { Transport } from '../metadata';
import type { HealthProbe } from './health';
import type { PipelineResult } from '../pipeline';
import type { ErrorRenderer } from '../transformers';
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
@@ -62,6 +63,11 @@ export interface HttpOptions {
bodyDuplicates?: 'array' | 'last';
onError?: ErrorRenderer;
static?: StaticResolver;
/**
* Answers `/__live__` and `/__ready__` ahead of the gate and the route table (`createApp({ health })`).
* Absent when health is off, so no path is intercepted.
*/
health?: HealthProbe;
}
/** Handler for a matched HTTP route; receives a normalized request and resolves to a pipeline result. */
@@ -91,6 +97,13 @@ export interface RouteDef {
maxParts?: number; // per-route override of the server's multipart maxParts
}
/**
* A route table: a fixed array, or a getter the server reads once per request. A mesh teacup passes
* a getter, because its remote routes change as teapots come and go (CARD-19); each change publishes
* a new array, so a request sees the whole old table or the whole new one.
*/
export type RouteTable = RouteDef[] | (() => RouteDef[]);
/** Result of matching a request path against a route: extracted params plus the matched definition. */
export interface MatchedRoute {
params: Record<string, string>;
@@ -114,6 +127,12 @@ export interface WsRouteDef {
/** Hook for a mesh gateway to take over WebSocket upgrades on a fixed path. */
export interface MeshControl {
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
* consumer takes, so Node (via `nodeSocket`) and Deno/Bun (via `app.upgrade`) both feed it.
+40 -9
View File
@@ -10,12 +10,14 @@ import {
type HandleResult,
type Preflight,
} from './core';
import { mergeInjectedHeaders } from './headers';
import { peerOf } from './peer';
import { mergeInjectedHeaders, toWebHeaders } from './headers';
import { peerOf, trustedProxyClient } from './peer';
import { declaresOverLimit, type BodyFailure, type BodyReader, type MaybePromise } from './body';
import { HttpError } from '../signals';
import { renderError, type ErrorRequest } from '../transformers';
import type { RouteDef, HttpOptions } from './types';
import type { RouteTable, HttpOptions } from './types';
import { answerProbe } from './health';
import { currentRoutes } from './router';
/**
* Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream
@@ -202,7 +204,7 @@ export function toBodyInit(body: string | Buffer): ResponseBody {
/** Converts a {@link HandleResult}'s outcome into a web `Response`, buffered or streamed. */
function outcomeToResponse(result: HandleResult, bus?: Bus, correlation: Correlation = {}): Response {
const headers = mergeInjectedHeaders(result.outcome.headers, result.injected) as Record<string, string>;
const headers = toWebHeaders(mergeInjectedHeaders(result.outcome.headers, result.injected));
if (result.outcome.kind === 'stream') {
const body = asReadableStream(
@@ -235,7 +237,7 @@ function forwardedFor(headers: Record<string, string>, opts: HttpOptions | undef
* Routing, body parsing, limits and error rendering all live in the core; this file is the part
* that knows how to get bytes out of a `Request` and how to put them into a `Response`.
*/
export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
export function buildFetch(routes: RouteTable, opts: HttpOptions | undefined) {
// Built once per server, not once per request — see `BodyReader`.
const readBody: BodyReader = (source, limit) => readFetchBytes(source, limit, opts);
const gate = createRequestGate(opts?.limits?.maxConcurrentRequests);
@@ -272,20 +274,24 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
return new Response(JSON.stringify({ error: 'Service Unavailable' }), {
status: 503,
headers: mergeInjectedHeaders(
headers: toWebHeaders(
mergeInjectedHeaders(
{
'content-type': 'application/json',
'retry-after': '1',
},
injected,
),
),
});
}
acquired = gate.limited;
result = await handle(
routes,
// Read once per request: a mesh teacup swaps its table when peers come and go, and one
// request must route and build `Allow` against the same table (CARD-19).
currentRoutes(routes),
opts,
{
...correlation,
@@ -299,7 +305,10 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
// proxy is trusted, and take its first hop — an untrusted XFF is client-spoofable.
// Otherwise the socket peer, which only the Deno and Bun adapters can supply; a bare
// `app.fetch` has none, so there the answer is still ''.
ip: forwardedFor(headers, opts) || peerOf(request),
// Ahead of both, under `trustProxy` only: the address the edge adapter read from
// `cf-connecting-ip`. Cloudflare sets that header itself, while XFF can carry hops the
// client supplied, so on the edge it wins (CARD-23).
ip: trustedProxyClient(request, opts?.trustProxy) || forwardedFor(headers, opts) || peerOf(request),
},
// Already computed above for the shed-503 path; handing it down keeps `cors.origins` to
// one call per request.
@@ -316,10 +325,32 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
if ('preflight' in result) {
return new Response(null, {
status: 204,
headers: mergeInjectedHeaders(result.preflight, injected),
headers: toWebHeaders(mergeInjectedHeaders(result.preflight, injected)),
});
}
return outcomeToResponse(result, opts?.bus, correlation);
};
}
/**
* Answers a health probe through the Fetch API, or returns `undefined` for any other request (or when
* `health` is off). `app.fetch` calls this before awaiting the boot, which is what lets `/__ready__`
* report `booting` at all, and before the gate and `handle()`, for the same reasons as the Node adapter.
*/
export function answerFetchProbe(request: Request, opts: HttpOptions | undefined): Response | undefined {
if (!opts?.health) return undefined;
const url = new URL(request.url);
const probe = answerProbe(request.method, url.pathname + url.search, opts.health);
if (!probe) return undefined;
const injected = computeInjected(opts, {
secure: url.protocol === 'https:',
headers: headersToRecord(request.headers),
});
return new Response(probe.body || null, {
status: probe.status,
headers: mergeInjectedHeaders(probe.headers, injected) as Record<string, string>,
});
}
+35 -2
View File
@@ -1,6 +1,6 @@
import { channel, type Channel } from '../channel';
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';
/**
@@ -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). */
export interface EventfulSocket {
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;
close(code?: number, reason?: string): void;
addEventListener(
@@ -90,7 +92,7 @@ export function eventSocket(host: EventfulSocket): WsSocket {
* callers never have to guard an already-closed socket.
*/
export function neutralSocket(
host: Pick<EventfulSocket, 'readyState' | 'send' | 'close'> & { terminate?(): void },
host: Pick<EventfulSocket, 'readyState' | 'send' | 'close' | 'bufferedAmount'> & { terminate?(): void },
inbound: Channel<unknown>,
ac: AbortController,
): WsSocket {
@@ -103,6 +105,7 @@ export function neutralSocket(
send: (data) => {
host.send(data);
},
drained: () => pollDrained(host, ac.signal),
close: (code, reason) => {
try {
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. */
export type SocketCtor = new (url: string) => EventfulSocket;
+94 -3
View File
@@ -21,8 +21,24 @@ export interface WsSocket {
send(data: string): void;
close(code?: number, reason?: string): 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. */
export const DEFAULT_MAX_WS_MESSAGE_BYTES = 1_048_576;
/** 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;
}
/**
* 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). */
export function validateWsLimits(limits: RequestLimits | undefined): void {
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
* 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.
*
* `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(
socket: WsSocket,
limits?: Pick<RequestLimits, 'maxWsMessageBytes' | 'maxWsQueue'>,
widened?: InboundLimits,
): WsSocket {
const fanout = new InboundFanout(socket, wsMessageBytes(limits), limits?.maxWsQueue ?? DEFAULT_MAX_WS_QUEUE);
@@ -87,6 +162,7 @@ export function boundInbound(
return Object.create(socket, {
inbound: { value: { [Symbol.asyncIterator]: () => fanout.subscribe() } },
...(widened && { [WIDEN_INBOUND]: { value: () => fanout.widen(widened) } }),
}) as WsSocket;
}
@@ -100,12 +176,18 @@ class InboundFanout {
constructor(
private readonly socket: WsSocket,
private readonly maxBytes: number,
private readonly maxQueue: number,
private maxBytes: number,
private maxQueue: number,
) {
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
* 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 };
}
/** 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> {
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();
if (done) break;
if (!socket.isOpen) break;
+55 -5
View File
@@ -6,13 +6,16 @@ import {
matchWsRoute,
trackUntil,
boundInbound,
controlBounds,
wsMessageBytes,
WS_HIGH_WATER_MARK,
type WsSocket,
type WsRequest,
} from './ws-core';
import type { WsRouteDef, MeshControl, RequestLimits } from './types';
import { normalizeRequestPath } from './router';
import { nodeRequire } from '../node-require';
import { MESH_CONTROL_DISABLED_REASON, MESH_CONTROL_PATH } from '../mesh/teapot';
/** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */
function loadWss(): any | null {
@@ -49,19 +52,36 @@ function handleMeshUpgrade(
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
// `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
// an untracked control channel leaves the teapot's server.close() waiting on it forever.
// serveFrames swallows its own failures, so the floating promise cannot reject.
wss.handleUpgrade(req, socket, head, (ws: any) => {
const neutral = boundInbound(nodeSocket(ws), limits);
const neutral = boundInbound(nodeSocket(ws), bounds.preAuth, bounds.authed);
void trackUntil(neutral, meshControl.handle(neutral), streams);
});
return true;
}
/** Accepts an upgrade to the reserved mesh path on an app without a control channel, then closes it 1008. */
function refuseMeshUpgrade(wss: any, req: http.IncomingMessage, socket: any, head: Buffer): void {
if (!wss) {
rejectUpgrade(socket, 501, 'Not Implemented');
return;
}
wss.handleUpgrade(req, socket, head, (ws: { close(code: number, reason: string): void }) =>
ws.close(1008, MESH_CONTROL_DISABLED_REASON),
);
}
/** Builds the neutral WsRequest from a Node upgrade request. Same values the old open() read from req.socket. */
function nodeWsRequest(req: http.IncomingMessage): WsRequest {
return {
@@ -76,10 +96,21 @@ function nodeWsRequest(req: http.IncomingMessage): WsRequest {
function nodeSocket(ws: any): WsSocket {
const inbound = channel<unknown>();
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('close', () => {
inbound.close();
ac.abort();
release();
});
ws.on('error', (err: unknown) => inbound.fail(err));
return {
@@ -88,7 +119,8 @@ function nodeSocket(ws: any): WsSocket {
get isOpen() {
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) => {
try {
ws.close(code, reason);
@@ -115,6 +147,14 @@ export function attachWs(
// fragmented or not, before it is assembled, and closes 1009 itself. `boundInbound` repeats the
// check on the decoded text, which is the only half Deno and the edge have.
const wss = WebSocketServer ? new WebSocketServer({ noServer: true, maxPayload: wsMessageBytes(limits) }) : null;
// 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) => {
// 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.
@@ -123,7 +163,7 @@ export function attachWs(
// Nothing thrown in here may escape. This is a raw EventEmitter listener, so a throw is an
// uncaught exception that takes the whole process down, not a 500 for one client.
try {
routeUpgrade({ wss, wsRoutes, bus, meshControl, streams, limits }, req, socket, head);
routeUpgrade({ wss, meshWss, wsRoutes, bus, meshControl, streams, limits }, req, socket, head);
} catch {
if (socket.writable) rejectUpgrade(socket, 500, 'Internal Server Error');
else socket.destroy();
@@ -134,6 +174,8 @@ export function attachWs(
/** What every upgrade on one server shares. */
interface UpgradeEnv {
wss: any;
/** The mesh control channel's server, bounded by its own frame limit (#120). */
meshWss: any;
wsRoutes: WsRouteDef[];
bus?: Bus;
meshControl?: MeshControl;
@@ -143,7 +185,7 @@ interface UpgradeEnv {
/** Routes one upgrade: validates the path the way HTTP does, then mesh control, then the ws route table. */
function routeUpgrade(env: UpgradeEnv, req: http.IncomingMessage, socket: any, head: Buffer): void {
const { wss, wsRoutes, bus, meshControl, streams, limits } = env;
const { wss, meshWss, wsRoutes, bus, meshControl, streams, limits } = env;
let path: string;
// The same normalization the HTTP path runs (`dispatch` in core.ts). Without it a malformed
@@ -155,7 +197,15 @@ function routeUpgrade(env: UpgradeEnv, req: http.IncomingMessage, socket: any, h
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,
// Bun and the edge — accept, then close 1008 with the same reason (D17). Never falls through to the
// ws route table: the boot already refuses any route that claims this path.
if (path === MESH_CONTROL_PATH) {
refuseMeshUpgrade(wss, req, socket, head);
return;
}
const route = matchWsRoute(wsRoutes, path);
+5 -1
View File
@@ -78,9 +78,13 @@ export { flow, Flow } from './flow';
export type { StepFn, CompiledFlow } from './flow';
// Parameter decorators
export { needs, ctx, param, query, body, headers, header, inbound, abort } from './params';
export { needs, ctx, param, query, body, headers, header, cookies, cookie, inbound, abort } from './params';
export type { Query, Headers, Context, ArgSpec, ArgDecorator } from './params';
// Cookies
export { setCookie, parseCookies } from './cookies';
export type { CookieOptions } from './cookies';
// Observability
export { createDefaultLogger, logRequests, withConsoleFallback } from './logger';
export type { Logger, LogLevel, LogFields } from './logger';
+135 -47
View File
@@ -2,7 +2,6 @@ import type { Bus } from '../bus';
import type { Logger } from '../logger';
import { HttpError } from '../signals';
import { connectSocket, type SocketCtor } from '../http/ws-adapter';
import { compilePattern } from '../http/router';
import type { WsSocket } from '../http/ws-core';
import { encode, decode, MESH_PROTOCOL_VERSION, type Manifest, type RequestEnvelope, type Frame } from './protocol';
@@ -64,6 +63,8 @@ interface LinkState {
socket: WsSocket | undefined;
closed: boolean;
retry: ReturnType<typeof setTimeout> | undefined;
/** When the scheduled reconnect attempt fires (epoch ms), for the `retry-after` a 503 carries. */
retryAt: number | undefined;
}
/** One established connection: its socket, the manifest it announced, and its heartbeat. */
@@ -81,10 +82,10 @@ const DEFAULT_MAX_DELAY_MS = 30_000;
* 503, not a bare Error: a dead upstream is not "this service broke", and the status is what
* tells a caller it may retry and an operator where to look. A bare Error renders as a 500.
*/
function rejectAllPending(pending: Map<string, PendingEntry>, reason: string): void {
function rejectAllPending(pending: Map<string, PendingEntry>, reason: string, headers?: Record<string, string>): void {
for (const [, entry] of pending) {
clearTimeout(entry.timer);
entry.reject(new HttpError(503, reason));
entry.reject(new HttpError(503, reason, undefined, headers));
}
pending.clear();
@@ -99,13 +100,14 @@ function sendRpc(
name: string,
ctx: RequestEnvelope,
timeoutMs: number,
downHeaders?: Record<string, string>,
): Promise<unknown> {
// Answer now rather than in timeoutMs. A closed socket cannot deliver the frame, so waiting
// would make every request to a downed teapot hang for the full timeout (30s by default)
// before failing anyway — the caller pays for a verdict already known. This is also the
// window a reconnecting link sits in: down, and answering immediately.
if (!socket?.isOpen) {
return Promise.reject(new HttpError(503, `mesh link is down: cannot resolve '${name}'`));
return Promise.reject(new HttpError(503, `mesh link is down: cannot resolve '${name}'`, undefined, downHeaders));
}
return new Promise((resolveCall, rejectCall) => {
@@ -329,37 +331,109 @@ function stepKeys(manifest: Manifest): Set<string> {
}
/**
* Route keys by method plus *effective shape*, the same comparison `spliceRemoteScopes` uses to
* detect ambiguity — so `/:id` renamed to `/:name` is the same route and does not trip the refusal.
*/
function routeKeys(manifest: Manifest): Set<string> {
return new Set(manifest.routes.map((route) => `${route.method} ${compilePattern(route.pattern).shape}`));
}
/**
* What the boot manifest had that a returning one does not.
* The steps the boot manifest had that a returning one does not.
*
* The graph was validated at boot against the first manifest and is already serving. A token that
* vanished cannot be validated away after the fact, so a manifest missing anything this link
* contributed is refused rather than accepted — see `ManifestPolicy`. Extra exports are *not*
* missing and are ignored: the graph is fixed at boot and nothing new is spliced into it.
* The graph was validated at boot against the first manifest and is already serving. A step token
* that vanished cannot be validated away after the fact, so a manifest missing one is refused
* rather than accepted — see `ManifestPolicy`. Extra steps are ignored: the graph is fixed at boot
* and nothing new is spliced into it.
*
* Routes are not compared. They are not part of the graph, so a returning teapot's routes replace
* the old ones instead (D15): a route it added is served, one it dropped is removed.
*/
export function missingFromManifest(booted: Manifest, returned: Manifest): string[] {
const steps = stepKeys(returned);
const routes = routeKeys(returned);
const missing: string[] = [];
for (const step of booted.steps) {
if (!steps.has(step)) missing.push(`step '${step}'`);
}
for (const route of booted.routes) {
if (!routes.has(`${route.method} ${compilePattern(route.pattern).shape}`)) {
missing.push(`route '${route.method} ${route.pattern}'`);
}
return missing;
}
return missing;
/**
* `retry-after` for a 503 while the link is down and will try again: the seconds until the next
* attempt, at least 1. Nothing when it will not try again, so a client is not told to come back to
* a link that has given up.
*/
function retryAfter(state: LinkState, reconnects: boolean): Record<string, string> | undefined {
if (state.closed || !reconnects) return undefined;
const waitMs = state.retryAt === undefined ? 0 : state.retryAt - Date.now();
return { 'retry-after': String(Math.max(1, Math.ceil(waitMs / 1000))) };
}
/** A session dropped with reconnection off: the link is gone for good, if it was ever up. */
function dropWithoutReconnect(adopted: boolean, giveUp: () => void): void {
if (adopted) giveUp();
}
/** Stop a link for good and say so: a drop with reconnection off, or a permanent refusal (D15). */
function stopForGood(state: LinkState, onGone: (() => void) | undefined): void {
if (state.closed) return;
state.closed = true;
clearTimeout(state.retry);
state.retry = undefined;
onGone?.();
}
/**
* Whether a failed reconnect attempt was the teapot refusing this peer on purpose, in which case the
* link gives up. Retrying reaches the same answer forever, so the link stops and its routes go (D15),
* the same verdict boot gives a refusal.
*/
function refusedWhileReconnecting(
url: string,
error: unknown,
logger: Logger | undefined,
giveUp: () => void,
): boolean {
if (!isPermanentRefusal(error)) return false;
logger?.warn(`mesh: ${url} refused this peer while reconnecting (${(error as Error).message}) — giving up on it.`);
giveUp();
return true;
}
/**
* Hang up on a session whose manifest no longer backs the graph, and return the fingerprint now logged.
*
* Logged once per distinct manifest, not once per attempt: at the 30s ceiling this would otherwise be
* ~2,880 identical lines a day. A rollback can still fix it, which is why the link keeps retrying
* rather than giving up.
*/
function refuseSession(
session: Session,
missing: string[],
logged: string,
url: string,
logger: Logger | undefined,
): string {
session.heartbeat.stop();
session.socket.close();
const fingerprint = missing.join('|');
if (fingerprint !== logged) {
logger?.warn(
`mesh: refusing to reconnect to ${url} — its manifest no longer exports ${missing.join(', ')}, ` +
'which the graph was validated against at boot. Retrying in case this is a partial deploy.',
);
}
return fingerprint;
}
/** A session was adopted. When it is a returning one: keep the boot steps, take its routes (D15), and tell the caller. */
function reconnected(
returning: boolean,
link: Link,
returned: Manifest,
onReconnect: ((manifest: Manifest) => void) | undefined,
): void {
if (!returning) return;
link.manifest = { steps: link.manifest.steps, routes: returned.routes };
onReconnect?.(link.manifest);
}
/** Resolved backoff bounds, or `undefined` when the caller turned reconnection off. */
@@ -394,19 +468,36 @@ export function connectLink(args: {
/** What to do when a returning teapot's manifest no longer backs the graph (default: `'refuse'`). */
onManifestChange?: ManifestPolicy;
logger?: Logger;
/**
* Called each time a dropped link reconnects and its session is adopted, after `link.manifest`
* has taken the returning manifest's routes. Not called for the first connection: the caller
* has the link, and its manifest, when the returned promise resolves.
*/
onReconnect?: (manifest: Manifest) => void;
/**
* Called once when the link gives up for good: its session dropped with `reconnect: false`, or a
* reconnect attempt was refused permanently (a wrong secret, a protocol mismatch). Not called by
* `close()`, which is the application hanging up, not the teapot going away.
*/
onGone?: () => void;
}): Promise<Link> {
const timeoutMs = args.timeoutMs ?? 30_000;
const heartbeatMs = args.heartbeatMs ?? HEARTBEAT_MS;
const bounds = backoffBounds(args.reconnect);
const pending = new Map<string, PendingEntry>();
const state: LinkState = { socket: undefined, closed: false, retry: undefined };
const state: LinkState = { socket: undefined, closed: false, retry: undefined, retryAt: undefined };
let refusalLogged = '';
let adopted = false; // a session was adopted at least once, so the link has something to lose
const downHeaders = (): Record<string, string> | undefined => retryAfter(state, bounds !== undefined);
const giveUp = (): void => stopForGood(state, args.onGone);
const link: Link = {
// replaced with the real manifest before this object escapes; a reconnect never changes it,
// because the graph is fixed at boot and only the *boot* manifest describes what it holds.
// replaced with the real manifest before this object escapes. A reconnect keeps the boot
// manifest's steps, because the graph is fixed at boot, and takes the returning one's routes.
manifest: { steps: [], routes: [] },
rpc: (kind, name, ctx) => sendRpc(state.socket, pending, String(counter++), kind, name, ctx, timeoutMs),
rpc: (kind, name, ctx) =>
sendRpc(state.socket, pending, String(counter++), kind, name, ctx, timeoutMs, downHeaders()),
close: () => {
// Terminal, by contract. `closeLinks` runs on shutdown, and a link that reconnected after
// the application hung up would leave a process that cannot exit.
@@ -438,6 +529,8 @@ export function connectLink(args: {
// the teapot the moment it returns.
const delay = Math.round(capped / 2 + Math.random() * (capped / 2));
clearTimeout(state.retry);
state.retryAt = Date.now() + delay;
state.retry = setTimeout(() => void attemptReconnect(attempt + 1), delay);
state.retry.unref?.();
};
@@ -446,8 +539,12 @@ export function connectLink(args: {
const endSession = (attempt: number): void => {
state.socket = undefined;
args.bus?.emit('mesh:disconnect', { name: args.url });
rejectAllPending(pending, `mesh link to ${args.url} is down`);
// Scheduled before the rejection, so the 503s carry the real wait in `retry-after`.
scheduleRetry(attempt);
rejectAllPending(pending, `mesh link to ${args.url} is down`, downHeaders());
// With reconnection off, a link that was up and dropped is gone for good (D15). `adopted`
// keeps a first connect that never succeeded out of this: that link never escaped.
if (!bounds) dropWithoutReconnect(adopted, giveUp);
};
/** Adopt an established session, or refuse it when its manifest no longer backs the graph. */
@@ -455,27 +552,16 @@ export function connectLink(args: {
const missing = missingFromManifest(link.manifest, session.manifest);
if (missing.length > 0) {
session.heartbeat.stop();
session.socket.close();
// Logged once per distinct manifest, not once per attempt: at the 30s ceiling this would
// otherwise be ~2,880 identical lines a day. A rollback can still fix it, which is why the
// link keeps retrying rather than giving up.
const fingerprint = missing.join('|');
if (fingerprint !== refusalLogged) {
refusalLogged = fingerprint;
args.logger?.warn(
`mesh: refusing to reconnect to ${args.url} — its manifest no longer exports ${missing.join(', ')}, ` +
'which the graph was validated against at boot. Retrying in case this is a partial deploy.',
);
}
refusalLogged = refuseSession(session, missing, refusalLogged, args.url, args.logger);
return false;
}
refusalLogged = '';
state.socket = session.socket;
const returning = adopted;
adopted = true;
args.bus?.emit('mesh:connect', { name: args.url });
reconnected(returning, link, session.manifest, args.onReconnect);
return true;
};
@@ -492,10 +578,12 @@ export function connectLink(args: {
}
if (!adopt(session)) scheduleRetry(attempt);
} catch {
// openSession's own abort listener already scheduled the retry through `onEnd`; a rejection
// that never opened a socket (a bad URL, DNS) needs one scheduled here instead.
if (!state.socket && !state.retry) scheduleRetry(attempt);
} catch (error) {
// A permanent refusal ends the link. Otherwise: openSession's own abort listener already
// scheduled the retry through `onEnd`; a rejection that never opened a socket (a bad URL,
// DNS) needs one scheduled here instead.
if (!refusedWhileReconnecting(args.url, error, args.logger, giveUp) && !state.socket && !state.retry)
scheduleRetry(attempt);
}
};
+62 -15
View File
@@ -3,7 +3,7 @@
// under node-compat on both; edge/workerd is out of scope (see the cross-runtime spec).
import crypto from 'node:crypto';
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 { isHttpError } from '../signals';
import {
@@ -17,9 +17,21 @@ import {
type Frame,
} from './protocol';
/** WebSocket path where a teapot exposes its mesh control channel. */
/**
* WebSocket path where a teapot exposes its mesh control channel.
*
* Reserved in every app, mesh or not (D17): `createApp` refuses a route that claims it, and an upgrade
* to it on an app without a control channel closes `1008` on every adapter.
*/
export const MESH_CONTROL_PATH = '/__mesh__/control';
/**
* Close reason for an upgrade to {@link MESH_CONTROL_PATH} on an app with no control channel. One
* string shared by `app.upgrade` and the Node listener, so every adapter refuses it identically (D17).
*/
export const MESH_CONTROL_DISABLED_REASON =
'mesh control channel not enabled: this app exports nothing, or has no mesh.secret';
/**
* How long an unauthenticated peer may hold the control channel open before it is hung up on.
*
@@ -29,18 +41,34 @@ export const MESH_CONTROL_PATH = '/__mesh__/control';
*/
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.
*
* `decode` runs `JSON.parse` on peer-controlled input, and until the handshake succeeds that peer
* is *unauthenticated* — so without a cap, anyone who can reach the port can make the process parse
* as much as its WebSocket layer will accept (100 MiB under the `ws` package's defaults, and no
* 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.
* 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
* escape. Nothing a body can hold grows more: a `"` or backslash doubles, a JSON number such as
* `1e20` re-encodes to about five times its length, a multipart `Buffer` to at most four, and
* non-ASCII text is not escaped at all.
*/
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. */
export function buildManifest(args: { steps: string[]; routes: RouteEntry[] }): Manifest {
@@ -61,6 +89,11 @@ export interface MeshControlDeps {
resolveScope: (name: string, env: RequestEnvelope) => Promise<unknown>;
resolveRoute: (name: string, env: RequestEnvelope) => Promise<ResponseShape>;
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. */
@@ -101,6 +134,9 @@ function handleHandshake(socket: WsSocket, frame: Frame, deps: MeshControlDeps):
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(
encode({
type: 'manifest',
@@ -175,6 +211,7 @@ async function serveFrames(
deps: MeshControlDeps,
exportedScopes: Set<string>,
exportedRoutes: Set<string>,
maxFrameChars: number,
): Promise<void> {
let authed = false;
// Armed before the loop, and cleared by the handshake. An unauthenticated peer that simply
@@ -188,8 +225,9 @@ async function serveFrames(
for await (const data of socket.inbound) {
const raw = String(data);
// Checked before `decode`, because decoding is the expensive part being defended.
if (raw.length > MAX_FRAME_CHARS) {
// Checked before `decode`, because decoding is the expensive part being defended. Until the
// 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');
break;
}
@@ -232,13 +270,22 @@ async function serveFrames(
/** Build a control handler that authenticates peers and serves scope/route RPCs from the manifest. */
export function createMeshControl(deps: MeshControlDeps): {
path: string;
maxFrameBytes: number;
handle: (socket: WsSocket) => Promise<void>;
} {
const exportedScopes = new Set(deps.manifest.steps);
const exportedRoutes = new Set(deps.manifest.routes.map((route) => `${route.method} ${route.pattern}`));
const maxFrameChars = controlFrameLimit(deps.maxBodyBytes);
return {
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
* the control channel's lifetime the same way it awaits a regular ws route's.
@@ -246,7 +293,7 @@ export function createMeshControl(deps: MeshControlDeps): {
* does synchronously, so the loop is live before any frame can arrive.
*/
handle(socket: WsSocket): Promise<void> {
return serveFrames(socket, deps, exportedScopes, exportedRoutes);
return serveFrames(socket, deps, exportedScopes, exportedRoutes, maxFrameChars);
},
};
}
+5 -1
View File
@@ -3,7 +3,11 @@ import 'reflect-metadata';
/** Any class constructor. Kept `any` because decorators must accept every target shape. */
export type Ctor = new (...args: any[]) => any;
/** Serializes a handler's return value into an HTTP response envelope. */
export type TransformerFn = (value: unknown) => { status?: number; headers?: Record<string, string>; body: string };
export type TransformerFn = (value: unknown) => {
status?: number;
headers?: Record<string, string | string[]>;
body: string;
};
/** Metadata attached by `@Html`: optional file path and whether it is a template. */
export interface HtmlMeta {
+11 -4
View File
@@ -26,7 +26,7 @@ export interface OpenApiDoc {
type Parameter = {
name: string;
in: 'path' | 'query' | 'header';
in: 'path' | 'query' | 'header' | 'cookie';
required: boolean;
schema: { type: 'string'; pattern?: string };
};
@@ -57,13 +57,20 @@ function pathParams(pattern: string): Parameter[] {
});
}
/** Query and header parameters declared by the handler's `@query` / `@headers` / `@header` argument decorators. */
/** Where each argument source sits in an OpenAPI parameter list; sources absent here are not parameters. */
const ARG_LOCATION: Partial<Record<ArgSpec['source'], Parameter['in']>> = {
query: 'query',
headers: 'header',
cookies: 'cookie',
};
/** Query, header and cookie parameters declared by `@query` / `@headers` / `@header` / `@cookies` / `@cookie`. */
function argParams(args: ArgSpec[]): Parameter[] {
const params: Parameter[] = [];
for (const arg of args) {
if (arg.source !== 'query' && arg.source !== 'headers') continue;
const location = arg.source === 'query' ? 'query' : 'header';
const location = ARG_LOCATION[arg.source];
if (!location) continue;
const names = arg.keys ?? (arg.key ? [arg.key] : []);
for (const name of names) params.push({ name, in: location, required: false, schema: { type: 'string' } });
}
+27 -3
View File
@@ -2,6 +2,7 @@ import 'reflect-metadata';
import type { Ctor } from './metadata';
import { isStandardSchema, type StandardSchemaV1 } from './standard-schema';
import { ValidationError } from './signals';
import { parseCookies } from './cookies';
/** Parsed URL query string as flat key/value pairs. */
export type Query = Record<string, string>;
@@ -10,7 +11,7 @@ export type Headers = Record<string, string | string[] | undefined>;
/** Per-request bag that accumulates values produced by steps and providers. */
export type Context = Record<string, unknown>;
type ArgSource = 'ctx' | 'needs' | 'params' | 'query' | 'body' | 'headers' | 'inbound' | 'abort';
type ArgSource = 'ctx' | 'needs' | 'params' | 'query' | 'body' | 'headers' | 'cookies' | 'inbound' | 'abort';
/** Describes how a single handler parameter is sourced and (optionally) validated. */
export interface ArgSpec {
index: number;
@@ -71,6 +72,14 @@ export const body: ArgDecorator = envelope('body');
export const headers: ArgDecorator = envelope('headers');
/** Inject a single request header by name (singular alias of {@link headers}); accepts a schema to validate it. */
export const header: ArgDecorator = envelope('headers');
/**
* Inject request cookies, parsed from the `Cookie` header: no arg for the whole map (`{}` when the
* request has none), a key to pick one, an array to pick several. Accepts a schema to validate.
* First value wins for a repeated name, `%`-sequences are decoded, malformed pairs are skipped.
*/
export const cookies: ArgDecorator = envelope('cookies');
/** Inject a single request cookie by name (singular alias of {@link cookies}); `undefined` when absent. */
export const cookie: ArgDecorator = envelope('cookies');
/** Inject a value produced upstream by a step or provider, addressed by key. */
export function needs(key: string): ParameterDecorator {
@@ -126,10 +135,11 @@ export async function resolveArgs(specs: ArgSpec[], context: Context): Promise<u
function resolveOne(spec: ArgSpec, context: Context): unknown {
if (spec.source === 'ctx') return context;
if (spec.source === 'needs') return context[spec.key as string];
// `cookies` is a seed token like `headers`, but parsed on demand rather than seeded on every request.
if (spec.source === 'needs') return spec.key === 'cookies' ? cookiesOf(context) : context[spec.key as string];
if (spec.source === 'inbound') return context.inbound;
if (spec.source === 'abort') return context.abort;
const bag = context[spec.source];
const bag = spec.source === 'cookies' ? cookiesOf(context) : context[spec.source];
if (typeof bag !== 'object' || bag === null) return bag; // can't pick from a non-object; return as-is
const values = bag as Record<string, unknown>;
@@ -142,3 +152,17 @@ function resolveOne(spec: ArgSpec, context: Context): unknown {
if (spec.key !== undefined) return values[spec.key];
return values;
}
/**
* The request's cookie map, parsed on first use and cached on the context, so a route that never
* declares a cookie argument never parses the header and one that declares several parses it once.
* Serves `@cookie`, `@cookies` and `@needs('cookies')` alike.
*/
function cookiesOf(context: Context): unknown {
if (context.cookies === undefined) {
const headers = context.headers as Headers | undefined;
context.cookies = parseCookies(headers?.cookie);
}
return context.cookies;
}
+2 -1
View File
@@ -14,7 +14,8 @@ export interface PipelineStep {
/** A fully materialized HTTP response produced by a transformer. */
export interface ResponseShape {
status: number;
headers: Record<string, string>;
/** A value may be an array: `set-cookie` arrays are sent one line per element, others joined with `, `. */
headers: Record<string, string | string[]>;
body: string;
}
/** A streaming response; the async iterable is written to the socket and bypasses the transformer. */
+2 -2
View File
@@ -20,7 +20,7 @@ export interface HttpErrorLike {
status: number;
message: string;
body?: unknown;
headers?: Record<string, string>;
headers?: Record<string, string | string[]>;
}
/**
@@ -35,7 +35,7 @@ export class HttpError extends Error {
readonly status: number,
message?: string,
readonly body?: unknown,
readonly headers?: Record<string, string>,
readonly headers?: Record<string, string | string[]>,
) {
super(message ?? `HTTP ${status}`);
this.name = new.target.name;
+2 -1
View File
@@ -6,7 +6,8 @@ import type { Logger } from './logger';
/** A ready-to-send HTTP response. */
export interface ErrorResponse {
status: number;
headers: Record<string, string>;
/** A value may be an array: `set-cookie` arrays are sent one line per element, others joined with `, `. */
headers: Record<string, string | string[]>;
body: string;
}
+29
View File
@@ -0,0 +1,29 @@
// CARD-14 (#113) under the real Bun runtime: Set-Cookie arrays leave `Bun.serve` as separate
// lines, and @cookie reads the request header. Run with: npm run test:bun
import 'reflect-metadata';
import { test, expect } from 'bun:test';
import { createApp } from '../../src/index.ts';
import { serveBun } from '../../src/bun.ts';
import { CookieModule, C1, C2 } from '../fixtures/cookie-app.ts';
test('T7/T8/T11 on Bun.serve: two Set-Cookie lines, other arrays joined, @cookie decoded', async () => {
const server = await serveBun(createApp({ modules: [CookieModule] }), { hostname: '127.0.0.1', port: 0 });
try {
const base = `http://127.0.0.1:${server.port}`;
const two = await fetch(`${base}/c/two`);
await two.arrayBuffer();
expect(two.headers.getSetCookie()).toEqual([C1, C2]);
expect(two.headers.get('x-custom')).toBe('a, b');
const error = await fetch(`${base}/c/error`);
await error.arrayBuffer();
expect(error.status).toBe(401);
expect(error.headers.getSetCookie()).toEqual([C1, C2]);
const one = await fetch(`${base}/c/one`, { headers: { cookie: 'a=1; a=2; b=%41' } });
expect(await one.json()).toEqual({ a: '1', b: 'A' });
} finally {
await server.close({ timeoutMs: 1000 });
}
});
+208
View File
@@ -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();
}
});
+88
View File
@@ -99,3 +99,91 @@ test('mesh on Bun: a teacup reconnects to a teapot that came back', async () =>
await teapot.stop();
}
});
// CARD-19 (#124, D15): remote routes follow teapot membership on Bun too.
@Route('/remote')
class PingCtl {
@Get('/ping', { export: true })
ping() {
return { from: 'teapot' };
}
}
@Module({ mountpoint: '/api', controllers: [PingCtl] })
class PingTeapotModule {}
@Module({ mountpoint: '/api', controllers: [] })
class BareTeacupModule {}
async function startPingTeapot(port: number) {
const app = createApp({ modules: [PingTeapotModule], experimental: true, mesh: { secret: SECRET } });
const server = await serveBun(app, { port });
return {
stop: async () => {
server.stop(true);
await app.close();
},
};
}
/** Polls `GET path` until it answers `status`, or fails after `ms`. */
async function untilStatus(app: ReturnType<typeof createApp>, path: string, status: number, ms = 3000) {
const deadline = Date.now() + ms;
let last = 0;
while (Date.now() < deadline) {
const res = await app.fetch(new Request(`http://x${path}`));
await res.text();
last = res.status;
if (last === status) return;
await settle(25);
}
throw new Error(`${path} answered ${last}, expected ${status}`);
}
const pingTeacup = (port: number) =>
createApp({
modules: [BareTeacupModule],
experimental: true,
mesh: {
teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: SECRET }],
reconnect: { initialDelayMs: 20, maxDelayMs: 60 },
bootTimeoutMs: 100,
heartbeatMs: 50,
timeoutMs: 2000,
},
});
test('mesh on Bun: a teapot absent at boot has its routes served once it connects (CARD-19 T1)', async () => {
const port = freePort();
const teacup = pingTeacup(port);
let teapot: Awaited<ReturnType<typeof startPingTeapot>> | undefined;
try {
expect((await teacup.fetch(new Request('http://x/api/remote/ping'))).status).toBe(404);
teapot = await startPingTeapot(port);
await untilStatus(teacup, '/api/remote/ping', 200);
} finally {
await teacup.close();
await teapot?.stop();
}
});
test('mesh on Bun: a reconnecting teapot keeps its routes with 503 + retry-after (CARD-19 T2)', async () => {
const port = freePort();
const teapot = await startPingTeapot(port);
const teacup = pingTeacup(port);
try {
await untilStatus(teacup, '/api/remote/ping', 200);
await teapot.stop();
await untilStatus(teacup, '/api/remote/ping', 503);
const down = await teacup.fetch(new Request('http://x/api/remote/ping'));
expect(down.status).toBe(503);
expect(Number(down.headers.get('retry-after'))).toBeGreaterThanOrEqual(1);
const options = await teacup.fetch(new Request('http://x/api/remote/ping', { method: 'OPTIONS' }));
expect(options.headers.get('allow')).toBe('GET, HEAD, OPTIONS');
} finally {
await teacup.close();
}
});
+66
View File
@@ -82,3 +82,69 @@ test('mesh on Bun: a teapot refuses a bad secret over its control channel', asyn
tServer.stop(true);
}
});
// CARD-18 T6 (GitHub #35, D9): a remote step whose token a local node already provides fails the
// splice, on Bun as on Node. Today that is the duplicate-name check in `setRunner`, which runs
// before the graph-wide one-producer check; this pins that the splice still refuses it.
@Step({ provides: 'auth', needs: [] })
class LocalAuth {
run() {
return { auth: { token: 'local' } };
}
}
@Module({ mountpoint: '/api', steps: [LocalAuth], controllers: [LocalCtl] })
class ShadowingTeacupModule {}
test('mesh on Bun: a remote step colliding with a local token fails the splice', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await serveBun(teapot, { port: 0 });
const teacup = createApp({
modules: [ShadowingTeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(tServer.port), secret: SECRET }], timeoutMs: 1000 },
});
try {
await expect(teacup.ready()).rejects.toThrow("duplicate provider/step name 'auth'");
} finally {
await teacup.close().catch(() => {});
tServer.stop(true);
}
});
// CARD-20 (#125, D16): HEAD on a remote GET answers like HEAD on a local one.
@Route('/remote')
class RemoteHeadCtl {
@Get('/x', { export: true })
x() {
return { a: 1 };
}
}
@Module({ mountpoint: '/api', controllers: [RemoteHeadCtl] })
class RemoteHeadTeapotModule {}
@Module({ mountpoint: '/api', controllers: [] })
class EmptyTeacupModule {}
test('mesh on Bun: HEAD on a remote GET answers 200 with the GET headers and no body', async () => {
const teapot = createApp({ modules: [RemoteHeadTeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await serveBun(teapot, { port: 0 });
const teacup = createApp({
modules: [EmptyTeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(tServer.port), secret: SECRET }], reconnect: false },
});
const cServer = await serveBun(teacup, { port: 0 });
try {
const res = await fetch(`http://127.0.0.1:${cServer.port}/api/remote/x`, { method: 'HEAD' });
expect(res.status).toBe(200);
expect(res.headers.get('content-type') ?? '').toContain('application/json');
expect(await res.text()).toBe('');
} finally {
await teacup.close();
cServer.stop(true);
tServer.stop(true);
}
});
+21
View File
@@ -97,3 +97,24 @@ test('serveBun rejects when a provider fails, instead of binding a port that 500
await expect(serveBun(app, { port: 0 })).rejects.toThrow(/no such key file/);
});
// CARD-17 T5 (D14): close() marks the app draining before the server stops, and the drain window
// keeps the listener open long enough for a probe to read the 503.
test('serveBun close() with health.drainDelayMs: /__ready__ 503 draining, in-flight request 200', async () => {
const app = createApp({ modules: [M], health: { drainDelayMs: 300 } });
const server = await serveBun(app, { port: 0 });
const base = `http://127.0.0.1:${server.port}`;
expect((await fetch(`${base}/__ready__`)).status).toBe(200);
const inFlight = fetch(`${base}/slow`).then((r) => r.json());
await Bun.sleep(50);
const closing = server.close({ timeoutMs: 5000 });
const probe = await fetch(`${base}/__ready__`);
expect(probe.status).toBe(503);
expect(await probe.json()).toEqual({ status: 'draining' });
expect(await inFlight).toEqual({ ok: true });
await closing;
});
+78
View File
@@ -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);
+28
View File
@@ -139,3 +139,31 @@ test('serveBun: ws message size default is 1 MiB', async () => {
server.stop(true);
}
});
// CARD-21 (D17): the reserved mesh path is refused the way the Node listener refuses it, and a route
// that claims it fails createApp here too.
test('serveBun: /__mesh__/control without a control channel closes 1008; a route there fails createApp', async () => {
@Route('/')
class Claims {
@Ws('/__mesh__/control')
control() {
return (async function* () {})();
}
}
@Module({ mountpoint: '/', controllers: [Claims] })
class ClaimsModule {}
expect(() => createApp({ modules: [ClaimsModule] })).toThrow(
/^route @Ws \/__mesh__\/control at Claims\.control uses the reserved path/,
);
const app = createApp({ modules: [M] });
const server = await serveBun(app, { port: 0 });
try {
expect((await exchange(server.port, '/__mesh__/control', [])).close).toEqual({
code: 1008,
reason: 'mesh control channel not enabled: this app exports nothing, or has no mesh.secret',
});
} finally {
server.stop(true);
}
});
+306
View File
@@ -0,0 +1,306 @@
// CARD-14 (#113): reading cookies with @cookie/@cookies, writing them with setCookie, and more than
// one Set-Cookie line per response on the Node adapter and app.fetch. Deno, Bun and edge repeat the
// two-line cases in test/deno/cookies.test.ts, test/bun/cookies.test.ts and test/edge/run.ts.
import 'reflect-metadata';
import http from 'node:http';
import type { AddressInfo } from 'node:net';
import WebSocket from 'ws';
import { describe, expect, it, afterAll } from 'vitest';
import {
createApp,
Route,
Get,
Ws,
Module,
Transformer,
HttpError,
needs,
cookie,
cookies,
setCookie,
parseCookies,
type TransformerFn,
} from '../src/index';
const C1 = setCookie('a', '1');
const C2 = setCookie('b', '2', { maxAge: 60 });
const twoCookies: TransformerFn = (value) => ({
status: 200,
headers: { 'content-type': 'application/json', 'set-cookie': [C1, C2] },
body: JSON.stringify(value),
});
@Route('/c')
class CookieCtl {
@Get('/one')
one(@cookie('a') a: string | undefined, @cookie('b') b: string | undefined) {
return { a: a ?? null, b: b ?? null };
}
@Get('/all')
all(@cookies() all: Record<string, string>) {
return { all, keys: Object.keys(all) };
}
@Get('/pick')
pick(@cookies(['d', 'e']) picked: Record<string, string>) {
return picked;
}
@Get('/needs')
viaNeeds(@needs('cookies') jar: Record<string, string>) {
return { sid: jar.sid ?? null };
}
@Get('/transformer')
@Transformer(twoCookies)
transformer() {
return { ok: true };
}
@Get('/error')
error() {
throw new HttpError(401, 'nope', undefined, { 'set-cookie': [C1, C2] });
}
@Get('/custom')
@Transformer((v) => ({ headers: { 'x-custom': ['a', 'b'], vary: ['Accept', 'Accept-Language'] }, body: String(v) }))
custom() {
return 'x';
}
@Get('/renderer')
renderer() {
throw new Error('render me');
}
@Ws('/ws')
ws(@cookie('a') a: string | undefined) {
return (async function* () {
yield `a=${a}`;
})();
}
}
@Module({ mountpoint: '/', controllers: [CookieCtl] })
class M {}
const app = createApp({
modules: [M],
cors: { origins: ['http://ok.test'] },
onError: (error) =>
error instanceof Error && error.message === 'render me'
? { status: 418, headers: { 'content-type': 'text/plain', 'set-cookie': [C1, C2] }, body: 'teapot' }
: undefined,
});
let server: http.Server;
let port: number;
afterAll(() => server?.close());
async function boot(): Promise<void> {
if (server) return;
server = await app.listen(0);
port = (server.address() as AddressInfo).port;
}
/** A raw request, so repeated header lines are visible as they came off the socket. */
async function raw(
path: string,
headers: Record<string, string> = {},
): Promise<{ status: number; lines: [string, string][]; body: string }> {
await boot();
return new Promise((resolve, reject) => {
http
.get({ host: '127.0.0.1', port, path, headers }, (res) => {
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk) => (body += chunk));
res.on('end', () => {
const lines: [string, string][] = [];
for (let i = 0; i < res.rawHeaders.length; i += 2)
lines.push([res.rawHeaders[i].toLowerCase(), res.rawHeaders[i + 1]]);
resolve({ status: res.statusCode!, lines, body });
});
})
.on('error', reject);
});
}
const valuesOf = (lines: [string, string][], name: string) => lines.filter(([k]) => k === name).map(([, v]) => v);
const fetchVia = (path: string, headers: Record<string, string> = {}) =>
app.fetch(new Request(`http://x${path}`, { headers }));
describe('parseCookies', () => {
it('T1: first value wins, %-sequences decode', () => {
expect(parseCookies('a=1; a=2; b=%41')).toEqual({ a: '1', b: 'A' });
});
it('T2: malformed pairs are skipped, an undecodable value is kept raw', () => {
expect({ ...parseCookies('=x; c; d=%ZZ; e=5') }).toEqual({ d: '%ZZ', e: '5' });
});
it('T3: no header is an empty map', () => {
expect({ ...parseCookies(undefined) }).toEqual({});
});
it('joins several cookie lines (HTTP/2, proxies) with "; "', () => {
expect({ ...parseCookies(['a=1', 'b=2; a=3']) }).toEqual({ a: '1', b: '2' });
});
it('treats __proto__ as an ordinary key, never a prototype write', () => {
const map = parseCookies('__proto__=x; constructor=y');
expect(map['__proto__']).toBe('x');
expect(map['constructor']).toBe('y');
expect(({} as any).x).toBeUndefined();
});
});
describe('setCookie', () => {
it('T4: documented defaults, Secure per D10', () => {
expect(setCookie('s', 'v')).toBe('s=v; Path=/; Secure; HttpOnly; SameSite=Lax');
});
it('serialises every option', () => {
const expires = new Date(Date.UTC(2030, 0, 1));
expect(
setCookie('s', 'v', {
maxAge: 10,
expires,
domain: 'example.com',
path: '/app',
httpOnly: false,
sameSite: 'none',
partitioned: true,
}),
).toBe(
's=v; Max-Age=10; Expires=Tue, 01 Jan 2030 00:00:00 GMT; Domain=example.com; Path=/app; Secure; SameSite=None; Partitioned',
);
expect(setCookie('s', 'v', { secure: false, sameSite: 'strict' })).toBe('s=v; Path=/; HttpOnly; SameSite=Strict');
});
it('T5: refuses header injection and bad names, naming the field', () => {
expect(() => setCookie('s', 'v\r\nX: y')).toThrow(/value for 's'/);
expect(() => setCookie('a b', 'v')).toThrow(/name "a b"/);
for (const bad of ['a;b', 'a,b', 'a b', 'a\tb', 'a\u0001b'])
expect(() => setCookie('s', bad), JSON.stringify(bad)).toThrow(/value/);
expect(() => setCookie('s', 'v', { path: '/\r\nX: y' })).toThrow(/path/);
expect(() => setCookie('s', 'v', { domain: 'a.com\nX' })).toThrow(/domain/);
expect(() => setCookie('s', 'v', { path: '/; Domain=evil' })).toThrow(/path/);
expect(() => setCookie('s', 'v', { maxAge: 1.5 })).toThrow(/maxAge/);
expect(() => setCookie('s', 'v', { expires: new Date('nope') })).toThrow(/expires/);
expect(() => setCookie('s', 'v', { sameSite: 'loose' as never })).toThrow(/sameSite/);
});
it('T6: sameSite none and partitioned both require secure', () => {
expect(() => setCookie('s', 'v', { sameSite: 'none', secure: false })).toThrow(/sameSite 'none'.*secure/);
expect(() => setCookie('s', 'v', { partitioned: true, secure: false })).toThrow(/partitioned.*secure/);
});
});
describe('@cookie / @cookies on a live Node server', () => {
it('T1: first wins and decodes', async () => {
const res = await raw('/c/one', { cookie: 'a=1; a=2; b=%41' });
expect(JSON.parse(res.body)).toEqual({ a: '1', b: 'A' });
});
it('T2: malformed pairs never 400', async () => {
const res = await raw('/c/all', { cookie: '=x; c; d=%ZZ; e=5' });
expect(res.status).toBe(200);
expect(JSON.parse(res.body).all).toEqual({ d: '%ZZ', e: '5' });
});
it('T3: no Cookie header', async () => {
expect(JSON.parse((await raw('/c/all')).body).all).toEqual({});
expect(JSON.parse((await raw('/c/one')).body)).toEqual({ a: null, b: null });
});
it('picks a key list', async () => {
expect(JSON.parse((await raw('/c/pick', { cookie: 'd=4; e=5; f=6' })).body)).toEqual({ d: '4', e: '5' });
});
it('@needs("cookies") resolves the same map', async () => {
expect(JSON.parse((await raw('/c/needs', { cookie: 'sid=abc' })).body)).toEqual({ sid: 'abc' });
});
it('resolves on a WebSocket route', async () => {
await boot();
const client = new WebSocket(`ws://127.0.0.1:${port}/c/ws`, { headers: { cookie: 'a=hello' } });
const message = await new Promise<string>((resolve, reject) => {
client.on('message', (data) => resolve(String(data)));
client.on('error', reject);
});
client.close();
expect(message).toBe('a=hello');
});
});
describe('several Set-Cookie lines', () => {
it('T7: custom @Transformer, Node: two lines', async () => {
const res = await raw('/c/transformer');
expect(valuesOf(res.lines, 'set-cookie')).toEqual([C1, C2]);
});
it('T7: custom @Transformer, app.fetch: two lines', async () => {
const res = await fetchVia('/c/transformer');
expect(res.headers.getSetCookie()).toEqual([C1, C2]);
});
it('T8: HttpError.headers and an onError renderer: two lines on both adapters', async () => {
for (const path of ['/c/error', '/c/renderer']) {
const res = await raw(path);
expect(valuesOf(res.lines, 'set-cookie'), path).toEqual([C1, C2]);
expect((await fetchVia(path)).headers.getSetCookie(), path).toEqual([C1, C2]);
}
});
it('T9: array kept, injected vary merged with a handler vary array', async () => {
const res = await raw('/c/custom', { origin: 'http://ok.test' });
const vary = valuesOf(res.lines, 'vary');
expect(vary).toHaveLength(1);
expect(vary[0].split(', ')).toEqual(['Accept', 'Accept-Language', 'Origin']);
const viaFetch = await fetchVia('/c/custom', { origin: 'http://ok.test' });
expect(viaFetch.headers.get('vary')).toBe('Accept, Accept-Language, Origin');
const cookieRes = await raw('/c/transformer', { origin: 'http://ok.test' });
expect(valuesOf(cookieRes.lines, 'set-cookie')).toEqual([C1, C2]);
expect(valuesOf(cookieRes.lines, 'vary')).toEqual(['Origin']);
});
it('T11: any other array header is one line joined with ", "', async () => {
const res = await raw('/c/custom');
expect(valuesOf(res.lines, 'x-custom')).toEqual(['a, b']);
expect((await fetchVia('/c/custom')).headers.get('x-custom')).toBe('a, b');
});
it('injected security headers stay authoritative over a handler array', async () => {
@Route('/s')
class Spoof {
@Get('/')
@Transformer(() => ({ headers: { 'x-content-type-options': ['sniff', 'me'] }, body: '' }))
get() {
return null;
}
}
@Module({ mountpoint: '/', controllers: [Spoof] })
class SM {}
const res = await createApp({ modules: [SM] }).fetch(new Request('http://x/s'));
expect(res.headers.get('x-content-type-options')).toBe('nosniff');
});
});
describe('OpenAPI', () => {
it('lists a @cookie arg as an in: cookie parameter', () => {
const doc = app.openapi();
const params = (doc.paths['/c/one'].get as any).parameters;
expect(params).toEqual(
expect.arrayContaining([
{ name: 'a', in: 'cookie', required: false, schema: { type: 'string' } },
{ name: 'b', in: 'cookie', required: false, schema: { type: 'string' } },
]),
);
});
});
+29
View File
@@ -0,0 +1,29 @@
// CARD-14 (#113) under the real Deno runtime: Set-Cookie arrays leave `Deno.serve` as separate
// lines, and @cookie reads the request header. Run with: npm run test:deno
import 'npm:reflect-metadata';
import { assertEquals } from 'jsr:@std/assert';
import { createApp } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts';
import { CookieModule, C1, C2 } from '../fixtures/cookie-app.ts';
Deno.test('T7/T8/T11 on Deno.serve: two Set-Cookie lines, other arrays joined, @cookie decoded', async () => {
const server = await serveDeno(createApp({ modules: [CookieModule] }), { hostname: '127.0.0.1', port: 0, onListen: () => {} });
const port = (server as unknown as { addr: { port: number } }).addr.port;
try {
const two = await fetch(`http://127.0.0.1:${port}/c/two`);
await two.body?.cancel();
assertEquals(two.headers.getSetCookie(), [C1, C2]);
assertEquals(two.headers.get('x-custom'), 'a, b');
const error = await fetch(`http://127.0.0.1:${port}/c/error`);
await error.body?.cancel();
assertEquals(error.status, 401);
assertEquals(error.headers.getSetCookie(), [C1, C2]);
const one = await fetch(`http://127.0.0.1:${port}/c/one`, { headers: { cookie: 'a=1; a=2; b=%41' } });
assertEquals(await one.json(), { a: '1', b: 'A' });
} finally {
await server.close({ timeoutMs: 1000 });
}
});
+204
View File
@@ -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();
}
});
+93
View File
@@ -99,3 +99,96 @@ Deno.test('mesh on Deno: a teacup reconnects to a teapot that came back', async
await teapot.stop();
}
});
// CARD-19 (#124, D15): remote routes follow teapot membership on Deno too.
@Route('/remote')
class PingCtl {
@Get('/ping', { export: true })
ping() {
return { from: 'teapot' };
}
}
@Module({ mountpoint: '/api', controllers: [PingCtl] })
class PingTeapotModule {}
@Module({ mountpoint: '/api', controllers: [] })
class BareTeacupModule {}
async function startPingTeapot(port: number) {
const app = createApp({ modules: [PingTeapotModule], experimental: true, mesh: { secret: SECRET } });
const server = await serveDeno(app, { port });
await new Promise((r) => setTimeout(r, 50));
return {
stop: async () => {
await server.shutdown();
await app.close();
},
};
}
/** Polls `GET path` until it answers `status`, or fails after `ms`. */
async function untilStatus(app: ReturnType<typeof createApp>, path: string, status: number, ms = 3000) {
const deadline = Date.now() + ms;
let last = 0;
while (Date.now() < deadline) {
const res = await app.fetch(new Request(`http://x${path}`));
await res.body?.cancel();
last = res.status;
if (last === status) return;
await settle(25);
}
throw new Error(`${path} answered ${last}, expected ${status}`);
}
const pingTeacup = (port: number) =>
createApp({
modules: [BareTeacupModule],
experimental: true,
mesh: {
teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: SECRET }],
reconnect: { initialDelayMs: 20, maxDelayMs: 60 },
bootTimeoutMs: 100,
heartbeatMs: 50,
timeoutMs: 2000,
},
});
Deno.test('mesh on Deno: a teapot absent at boot has its routes served once it connects (CARD-19 T1)', async () => {
const port = freePort();
const teacup = pingTeacup(port);
let teapot: Awaited<ReturnType<typeof startPingTeapot>> | undefined;
try {
const before = await teacup.fetch(new Request('http://x/api/remote/ping'));
await before.body?.cancel();
assertEquals(before.status, 404);
teapot = await startPingTeapot(port);
await untilStatus(teacup, '/api/remote/ping', 200);
} finally {
await teacup.close();
await teapot?.stop();
}
});
Deno.test('mesh on Deno: a reconnecting teapot keeps its routes with 503 + retry-after (CARD-19 T2)', async () => {
const port = freePort();
const teapot = await startPingTeapot(port);
const teacup = pingTeacup(port);
try {
await untilStatus(teacup, '/api/remote/ping', 200);
await teapot.stop();
await untilStatus(teacup, '/api/remote/ping', 503);
const down = await teacup.fetch(new Request('http://x/api/remote/ping'));
await down.body?.cancel();
assertEquals(down.status, 503);
assertEquals(Number(down.headers.get('retry-after')) >= 1, true);
const options = await teacup.fetch(new Request('http://x/api/remote/ping', { method: 'OPTIONS' }));
assertEquals(options.headers.get('allow'), 'GET, HEAD, OPTIONS');
} finally {
await teacup.close();
}
});
+72
View File
@@ -106,3 +106,75 @@ Deno.test('mesh on Deno: a teapot refuses a bad secret over its control channel'
await t.server.shutdown();
}
});
// CARD-18 T6 (GitHub #35, D9): a remote step whose token a local node already provides fails the
// splice, on Deno as on Node. Today that is the duplicate-name check in `setRunner`, which runs
// before the graph-wide one-producer check; this pins that the splice still refuses it.
@Step({ provides: 'auth', needs: [] })
class LocalAuth {
run() {
return { auth: { token: 'local' } };
}
}
@Module({ mountpoint: '/api', steps: [LocalAuth], controllers: [LocalCtl] })
class ShadowingTeacupModule {}
Deno.test('mesh on Deno: a remote step colliding with a local token fails the splice', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const t = await serve(teapot);
const teacup = createApp({
modules: [ShadowingTeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(t.port), secret: SECRET }], timeoutMs: 1000 },
});
try {
let message = '';
try {
await teacup.ready();
} catch (err) {
message = String((err as Error).message);
}
assertStringIncludes(message, "duplicate provider/step name 'auth'");
} finally {
await teacup.close().catch(() => {});
await t.server.shutdown();
}
});
// CARD-20 (#125, D16): HEAD on a remote GET answers like HEAD on a local one.
@Route('/remote')
class RemoteHeadCtl {
@Get('/x', { export: true })
x() {
return { a: 1 };
}
}
@Module({ mountpoint: '/api', controllers: [RemoteHeadCtl] })
class RemoteHeadTeapotModule {}
@Module({ mountpoint: '/api', controllers: [] })
class EmptyTeacupModule {}
Deno.test('mesh on Deno: HEAD on a remote GET answers 200 with the GET headers and no body', async () => {
const teapot = createApp({ modules: [RemoteHeadTeapotModule], experimental: true, mesh: { secret: SECRET } });
const t = await serve(teapot);
const teacup = createApp({
modules: [EmptyTeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(t.port), secret: SECRET }], reconnect: false },
});
const c = await serve(teacup);
try {
const res = await fetch(`http://127.0.0.1:${c.port}/api/remote/x`, { method: 'HEAD' });
assertEquals(res.status, 200);
assertStringIncludes(res.headers.get('content-type') ?? '', 'application/json');
assertEquals(await res.text(), '');
} finally {
await teacup.close();
await c.server.shutdown();
await t.server.shutdown();
}
});
+26
View File
@@ -121,3 +121,29 @@ Deno.test('serveDeno rejects when a provider fails, instead of binding a port th
throw new Error(`expected serveDeno to reject with the provider's error, got: ${message || '<resolved>'}`);
}
});
// CARD-17 T5 (D14): close() marks the app draining before the server shuts down, and the drain window
// keeps the listener open long enough for a probe to read the 503.
Deno.test('serveDeno close() with health.drainDelayMs: /__ready__ 503 draining, in-flight request 200', async () => {
const app = createApp({ modules: [M], health: { drainDelayMs: 300 } });
const server = await serveDeno(app, { port: 0, onListen: () => {} });
const base = `http://127.0.0.1:${portOf(server)}`;
const ready = await fetch(`${base}/__ready__`);
if (ready.status !== 200) throw new Error(`ready before close: ${ready.status}`);
await ready.body?.cancel();
const inFlight = fetch(`${base}/slow`).then((r) => r.json());
await new Promise((r) => setTimeout(r, 50));
const closing = server.close({ timeoutMs: 5000 });
const probe = await fetch(`${base}/__ready__`);
const body = await probe.json();
if (probe.status !== 503 || body.status !== 'draining') {
throw new Error(`probe during close: ${probe.status} ${JSON.stringify(body)}`);
}
const done = await inFlight;
if (done.ok !== true) throw new Error(`in-flight request was cut: ${JSON.stringify(done)}`);
await closing;
});
+114
View File
@@ -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();
}
});
+40
View File
@@ -181,3 +181,43 @@ Deno.test('serveDeno: ws message size default is 1 MiB', async () => {
await server.shutdown();
}
});
// CARD-21 (D17): the reserved mesh path is refused the way the Node listener refuses it, and a route
// that claims it fails createApp here too.
Deno.test('serveDeno: /__mesh__/control without a control channel closes 1008; a route there fails createApp', async () => {
@Route('/')
class Claims {
@Ws('/__mesh__/control')
control() {
return (async function* () {})();
}
}
@Module({ mountpoint: '/', controllers: [Claims] })
class ClaimsModule {}
let message = '';
try {
createApp({ modules: [ClaimsModule] });
} catch (error) {
message = (error as Error).message;
}
assertEquals(message.startsWith('route @Ws /__mesh__/control at Claims.control uses the reserved path'), true);
const app = createApp({ modules: [M] });
let port = 0;
const server = await serveDeno(app, {
port: 0,
onListen: (addr) => {
port = addr.port;
},
});
await new Promise((resolve) => setTimeout(resolve, 50));
try {
assertEquals((await exchange(port, '/__mesh__/control', [])).close, {
code: 1008,
reason: 'mesh control channel not enabled: this app exports nothing, or has no mesh.secret',
});
} finally {
await server.shutdown();
}
});
+119
View File
@@ -0,0 +1,119 @@
// CARD-23 (#119, D21): on the edge, `cf-connecting-ip` sets `ctx.ip` only under `trustProxy`, for HTTP
// and WebSocket alike, and wins over `x-forwarded-for`. The full WebSocket path through workerd
// (`WebSocketPair`, a 101 response) cannot run under Node, so it is covered in `test/edge/run.ts`;
// here the edge HTTP path runs through `edgeHandler` itself, and the WebSocket side through
// `app.upgrade` with the value recorded the way `edgeHandler` records it.
import 'reflect-metadata';
import { describe, expect, it } from 'vitest';
import type { AddressInfo } from 'node:net';
import { createApp, Route, Get, Ws, Module, ctx } from '../src/index';
import { edgeHandler } from '../src/edge';
import { channel } from '../src/channel';
import { setProxyClient } from '../src/http/peer';
import type { WsSocket, WsRequest } from '../src/http/ws-core';
@Route('/ip')
class IpCtl {
@Get('/whoami') whoami(@ctx() c: any) {
return { ip: c.ip };
}
@Ws('/ws')
ws(@ctx() c: any) {
return (async function* () {
yield String(c.ip);
})();
}
}
@Module({ mountpoint: '/', controllers: [IpCtl] })
class IpModule {}
const trusting = createApp({ modules: [IpModule], trustProxy: true });
const untrusting = createApp({ modules: [IpModule] });
const whoami = async (handler: (r: Request) => Response | Promise<Response>, headers: Record<string, string>) =>
((await (await handler(new Request('http://x/ip/whoami', { headers }))).json()) as { ip: string }).ip;
describe('edge HTTP: cf-connecting-ip', () => {
it('T1: under trustProxy it sets ctx.ip', async () => {
expect(await whoami(edgeHandler(trusting), { 'cf-connecting-ip': '1.2.3.4' })).toBe('1.2.3.4');
});
it('T2: under trustProxy it wins over x-forwarded-for', async () => {
const headers = { 'cf-connecting-ip': '1.2.3.4', 'x-forwarded-for': '9.9.9.9' };
expect(await whoami(edgeHandler(trusting), headers)).toBe('1.2.3.4');
});
it('under trustProxy without the header, x-forwarded-for still applies', async () => {
expect(await whoami(edgeHandler(trusting), { 'x-forwarded-for': '9.9.9.9' })).toBe('9.9.9.9');
});
it('T3: without trustProxy it is ignored and ctx.ip stays empty', async () => {
expect(await whoami(edgeHandler(untrusting), { 'cf-connecting-ip': '1.2.3.4' })).toBe('');
});
});
function fakeSocket() {
const ac = new AbortController();
const sent: string[] = [];
const socket: WsSocket = {
inbound: channel<unknown>(),
abort: ac.signal,
isOpen: true,
send: (d) => sent.push(d),
close: () => ac.abort(),
terminate: () => ac.abort(),
};
return { socket, sent };
}
/** Upgrades the way `edgeHandler` does: `ip` empty, the header recorded on the `WsRequest`. */
async function edgeWsIp(app: typeof trusting, cfConnectingIp: string): Promise<string> {
const headers = { 'cf-connecting-ip': cfConnectingIp };
const req: WsRequest = { url: '/ip/ws', headers, protocol: 'http', ip: '' };
setProxyClient(req, cfConnectingIp);
const { socket, sent } = fakeSocket();
await app.upgrade(req, socket);
return sent[0];
}
describe('edge WebSocket: cf-connecting-ip', () => {
it('T4: without trustProxy it is ignored and ctx.ip stays empty', async () => {
expect(await edgeWsIp(untrusting, '1.2.3.4')).toBe('');
});
it('T5: under trustProxy it sets ctx.ip', async () => {
expect(await edgeWsIp(trusting, '1.2.3.4')).toBe('1.2.3.4');
});
it('an adapter-supplied ip with nothing recorded is passed through unchanged', async () => {
const { socket, sent } = fakeSocket();
await trusting.upgrade({ url: '/ip/ws', headers: {}, protocol: 'http', ip: '203.0.113.7' }, socket);
expect(sent).toEqual(['203.0.113.7']);
});
});
describe('outside the edge adapter the header means nothing', () => {
it('T6: the Node listener under trustProxy ignores cf-connecting-ip', async () => {
const server = await createApp({ modules: [IpModule], trustProxy: true }).listen(0);
try {
const { port } = server.address() as AddressInfo;
const res = await fetch(`http://127.0.0.1:${port}/ip/whoami`, { headers: { 'cf-connecting-ip': '1.2.3.4' } });
const { ip } = (await res.json()) as { ip: string };
expect(ip).not.toBe('1.2.3.4');
expect(ip).toMatch(/127\.0\.0\.1|::1/);
} finally {
await new Promise<void>((resolve) => server.close(() => resolve()));
}
});
it('a bare app.fetch under trustProxy ignores cf-connecting-ip', async () => {
expect(await whoami((r) => trusting.fetch(r), { 'cf-connecting-ip': '1.2.3.4' })).toBe('');
});
it('a bare app.upgrade under trustProxy ignores the header in WsRequest.headers', async () => {
const { socket, sent } = fakeSocket();
await trusting.upgrade({ url: '/ip/ws', headers: { 'cf-connecting-ip': '1.2.3.4' }, protocol: 'http', ip: '' }, socket);
expect(sent).toEqual(['']);
});
});
+67 -1
View File
@@ -66,6 +66,18 @@ async function main() {
assert.equal(httpRes.status, 200);
assert.deepEqual(await httpRes.json(), { ok: true });
// CARD-14 (#113): a Set-Cookie array leaves workerd as one line per cookie; other arrays join.
const cookieRes = await mf.dispatchFetch('http://localhost/rt/cookies');
await cookieRes.arrayBuffer();
assert.deepEqual(cookieRes.headers.getSetCookie(), ['a=1; Path=/', 'b=2; Path=/']);
assert.equal(cookieRes.headers.get('x-custom'), 'a, b');
const cookieErr = await mf.dispatchFetch('http://localhost/rt/cookie-error');
await cookieErr.arrayBuffer();
assert.equal(cookieErr.status, 401);
assert.deepEqual(cookieErr.headers.getSetCookie(), ['a=1; Path=/', 'b=2; Path=/']);
const readCookie = await mf.dispatchFetch('http://localhost/rt/cookie', { headers: { cookie: 'a=1; b=%41' } });
assert.deepEqual(await readCookie.json(), { b: 'A' });
// Body limits (#105): the same statuses as app.fetch, Deno and Bun. workerd may drop a
// chunked upload's content-length, so the streamed case is enforced by the read count alone.
const LIMIT = 1000; // the route's maxBodyBytes, see worker.ts
@@ -138,7 +150,61 @@ async function main() {
assert.equal((await exchange(mf, 'http://localhost/rt/echo', ['a'.repeat(1_048_576)])).replies.length, 1);
assert.equal((await exchange(mf, 'http://localhost/rt/echo', ['a'.repeat(1_048_577)])).close?.code, 1009);
console.log('edge (workerd via miniflare): HTTP 200 + body limits 413/413/200/413 + WS echo:hi + ws limits — PASS');
// CARD-23 (#119): `cf-connecting-ip` sets ctx.ip only under trustProxy, for HTTP and WS alike,
// and wins over x-forwarded-for.
const cf = { 'cf-connecting-ip': '1.2.3.4' };
const httpIp = async (host: string, headers: Record<string, string>) =>
((await (await mf.dispatchFetch(`http://${host}/rt/ip`, { headers })).json()) as { ip: string }).ip;
const wsIp = async (host: string, headers: Record<string, string>) => {
const res = await mf.dispatchFetch(`http://${host}/rt/ws-ip`, { headers: { Upgrade: 'websocket', ...headers } });
const socket = res.webSocket;
assert.ok(socket, 'expected a client webSocket on the 101 response');
const reply = new Promise<string>((resolve) =>
socket.addEventListener('message', (e: { data: unknown }) => resolve(String(e.data))),
);
socket.accept();
const got = await reply;
socket.close();
return got;
};
assert.equal(await httpIp('trusted', cf), '1.2.3.4', 'T1 edge HTTP under trustProxy');
assert.equal(await httpIp('trusted', { ...cf, 'x-forwarded-for': '9.9.9.9' }), '1.2.3.4', 'T2 cf wins over XFF');
assert.equal(await httpIp('localhost', cf), '', 'T3 edge HTTP without trustProxy');
assert.equal(await wsIp('localhost', cf), 'ip:', 'T4 edge WS without trustProxy');
assert.equal(await wsIp('trusted', cf), 'ip:1.2.3.4', 'T5 edge WS under trustProxy');
// CARD-21 (D17): the reserved mesh path closes 1008 with the Node listener's reason, and a route
// that claims it fails createApp.
assert.deepEqual((await exchange(mf, 'http://localhost/__mesh__/control', [])).close, {
code: 1008,
reason: 'mesh control channel not enabled: this app exports nothing, or has no mesh.secret',
});
const reservedRes = await mf.dispatchFetch('http://reserved/');
assert.equal(reservedRes.status, 500);
assert.match(await reservedRes.text(), /^route @Ws \/__mesh__\/control at Claims\.control uses the reserved path/);
// CARD-17 T10: live 200; ready booting → ok, with only probes reaching the isolate. There is no
// close() on workerd, so draining is never reported here (documented, not tested for). Any probe
// starts the boot, so ready is asked first to see `booting`.
const first = await mf.dispatchFetch('http://health/__ready__');
assert.equal(first.status, 503);
assert.deepEqual(await first.json(), { status: 'booting' });
const live = await mf.dispatchFetch('http://health/__live__');
assert.equal(live.status, 200);
assert.deepEqual(await live.json(), { status: 'ok' });
let ready = await mf.dispatchFetch('http://health/__ready__');
for (let i = 0; i < 20 && ready.status !== 200; i++) {
await ready.arrayBuffer();
await new Promise((resolve) => setTimeout(resolve, 25));
ready = await mf.dispatchFetch('http://health/__ready__');
}
assert.equal(ready.status, 200);
assert.deepEqual(await ready.json(), { status: 'ok' });
assert.equal(ready.headers.get('cache-control'), 'no-store');
console.log(
'edge (workerd via miniflare): HTTP 200 + cookies + body limits 413/413/200/413 + WS echo:hi + ws limits + cf-connecting-ip under trustProxy + reserved path + health — PASS',
);
} finally {
await mf.dispose();
}
+66 -4
View File
@@ -1,7 +1,7 @@
// Worker entry for the real workerd (Miniflare) integration test.
// Mirrors test/deno/ws.test.ts's graph so HTTP + WebSocket behavior is proven
// identically across runtimes. Run via `npm run test:edge` (see test/edge/run.ts).
import { createApp, Route, Get, Post, Ws, body, ctx, Module } from '../../src/index';
import { createApp, Route, Get, Post, Ws, body, ctx, cookie, Module, Transformer, HttpError } from '../../src/index';
import { edgeHandler } from '../../src/edge';
@Route('/rt')
@@ -11,6 +11,23 @@ class Rt {
return { ok: true };
}
// CARD-14 (#113): two Set-Cookie lines from workerd, and @cookie on the request side.
@Get('/cookies')
@Transformer(() => ({ headers: { 'set-cookie': ['a=1; Path=/', 'b=2; Path=/'], 'x-custom': ['a', 'b'] }, body: '{}' }))
cookies() {
return null;
}
@Get('/cookie-error')
cookieError() {
throw new HttpError(401, 'nope', undefined, { 'set-cookie': ['a=1; Path=/', 'b=2; Path=/'] });
}
@Get('/cookie')
readCookie(@cookie('b') b: string | undefined) {
return { b: b ?? null };
}
// #105: the body limit, read from workerd's own request stream. Small, so every refused body still
// fits in the socket buffer: a client that is mid-upload when the 413 lands can see ECONNRESET
// instead, which is the transport racing the answer rather than a different answer.
@@ -35,6 +52,19 @@ class Rt {
})();
}
// CARD-23: what `ctx.ip` resolved to, over HTTP and over a WebSocket upgrade.
@Get('/ip')
ip(@ctx() c: any) {
return { ip: c.ip };
}
@Ws('/ws-ip')
wsIp(@ctx() c: any) {
return (async function* () {
yield `ip:${c.ip}`;
})();
}
@Ws('/room/:name')
room(@ctx() { inbound }: any) {
return (async function* () {
@@ -49,9 +79,41 @@ class M {}
const app = createApp({ modules: [M] });
// #107: the same graph with tight ws limits, reached through the `limited` host.
const limited = createApp({ modules: [M], limits: { maxWsMessageBytes: 1024, maxWsQueue: 4 } });
const handlers = { default: edgeHandler(app), limited: edgeHandler(limited) };
// CARD-23: the same graph under `trustProxy`, reached through the `trusted` host.
const trusted = createApp({ modules: [M], trustProxy: true });
const handlers: Record<string, ReturnType<typeof edgeHandler>> = {
default: edgeHandler(app),
limited: edgeHandler(limited),
trusted: edgeHandler(trusted),
// CARD-17 T10: health probes, reached through the `health` host. Never booted by anything but probes.
health: edgeHandler(createApp({ modules: [M], health: true })),
};
// CARD-21 (D17): a route on the reserved mesh path must fail createApp inside workerd too. Built per
// request on the `reserved` host so a regression answers with a status instead of breaking the worker.
@Route('/')
class Claims {
@Ws('/__mesh__/control')
control() {
return (async function* () {})();
}
}
@Module({ mountpoint: '/', controllers: [Claims] })
class ClaimsModule {}
function reservedBoot(): Response {
try {
createApp({ modules: [ClaimsModule] });
} catch (error) {
return new Response((error as Error).message, { status: 500 });
}
return new Response('booted', { status: 200 });
}
export default {
fetch: (request: Request, env?: unknown, ctx?: Parameters<typeof handlers.default>[2]) =>
(new URL(request.url).hostname === 'limited' ? handlers.limited : handlers.default)(request, env, ctx),
fetch: (request: Request, env?: unknown, ctx?: Parameters<ReturnType<typeof edgeHandler>>[2]) => {
const host = new URL(request.url).hostname;
if (host === 'reserved') return reservedBoot();
return (handlers[host] ?? handlers.default)(request, env, ctx);
},
};
+28
View File
@@ -0,0 +1,28 @@
// CARD-14 (#113): one graph for the Deno and Bun cookie suites, so both prove the same thing the
// Node suite (test/cookies.test.ts) does — two cookies on one response arrive as two lines.
import { Route, Get, Module, Transformer, HttpError, cookie, setCookie } from '../../src/index';
export const C1 = setCookie('a', '1');
export const C2 = setCookie('b', '2', { maxAge: 60 });
@Route('/c')
class CookieCtl {
@Get('/one')
one(@cookie('a') a: string | undefined, @cookie('b') b: string | undefined) {
return { a: a ?? null, b: b ?? null };
}
@Get('/two')
@Transformer(() => ({ headers: { 'set-cookie': [C1, C2], 'x-custom': ['a', 'b'] }, body: '{}' }))
two() {
return null;
}
@Get('/error')
error() {
throw new HttpError(401, 'nope', undefined, { 'set-cookie': [C1, C2] });
}
}
@Module({ mountpoint: '/', controllers: [CookieCtl] })
export class CookieModule {}
+28
View File
@@ -24,6 +24,34 @@ test('throws on cycle', () => {
expect(() => topoSort(nodes, [])).toThrow(/cycle detected/);
});
// CARD-18 (GitHub #35, D9): the check is a rule over the whole node set, not an artefact of the
// order nodes were registered in — so swapping `provideBuiltins` and `mountPlugins` cannot reopen it.
describe('one producer per token', () => {
const builtin: GraphNode = { name: 'logger', needs: [], provides: ['logger'], origin: 'builtin' };
const plugin: GraphNode = { name: 'fake', needs: [], provides: ['logger'], origin: 'plugin' };
it.each([
['built-in first', [builtin, plugin]],
['plugin first', [plugin, builtin]],
])('throws naming both producers and origins (%s)', (_, nodes) => {
expect(() => topoSort(nodes, [])).toThrow(/token 'logger' is provided twice/);
expect(() => topoSort(nodes, [])).toThrow(/'logger' \(builtin\)/);
expect(() => topoSort(nodes, [])).toThrow(/'fake' \(plugin\)/);
});
it('names a mesh origin like any other', () => {
const local: GraphNode = { name: 'auth', needs: [], provides: ['auth'], origin: 'module:App' };
const remote: GraphNode = { name: 'auth-remote', needs: [], provides: ['auth'], origin: 'mesh:ws://t' };
expect(() => topoSort([local, remote], [])).toThrow(
"token 'auth' is provided twice: by 'auth' (module:App) and by 'auth-remote' (mesh:ws://t)",
);
});
it('allows a node to list its own token twice', () => {
expect(topoSort([node('a', [], ['a', 'a'])], []).map((n) => n.name)).toEqual(['a']);
});
});
const N = (name: string, needs: string[] = []) => ({ name, needs, provides: [name], origin: 'm' });
describe('subgraphFor', () => {
+389
View File
@@ -0,0 +1,389 @@
/**
* CARD-17 (#115, D14): `createApp({ health })` serves `/__live__` and `/__ready__` outside the pipeline,
* with booting / ok / degraded / draining states and a drain window on close(). Deno and Bun repeat
* the drain case (T5) in their own suites; workerd covers T10 in `test/edge/run.ts`.
*/
import 'reflect-metadata';
import { describe, it, expect, vi, afterEach } from 'vitest';
import http from 'http';
import type { AddressInfo } from 'net';
import { WebSocketServer } from 'ws';
import { createApp, Route, Get, Ws, Module, Provider } from '../src/index';
import type { Logger } from '../src/logger';
import type { Plugin } from '../src/plugin';
import { encode, decode, MESH_PROTOCOL_VERSION } from '../src/mesh/protocol';
const silentLogger = (): Logger => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() });
const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
let releaseSlow: () => void = () => {};
@Route('/')
class Ctl {
@Get('/ping') ping() {
return { ok: true };
}
// Held open until the test releases it: an in-flight request across close().
@Get('/slow') async slow() {
await new Promise<void>((resolve) => (releaseSlow = resolve));
return { slow: true };
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
type AppOpts = Parameters<typeof createApp>[0];
const make = (extra: Partial<AppOpts> = {}) => createApp({ modules: [M], logger: silentLogger(), ...extra });
async function probe(app: ReturnType<typeof createApp>, path: string, method = 'GET') {
const res = await app.fetch(new Request(`http://x${path}`, { method }));
const text = await res.text();
return { status: res.status, body: text ? JSON.parse(text) : undefined, headers: res.headers };
}
describe('CARD-17: health probes through app.fetch', () => {
it('T1: /__ready__ is 503 booting while a slow provider boots, /__live__ is 200', async () => {
let finish: () => void = () => {};
@Provider({ provides: 'slowDb' })
class SlowDb {
async provide() {
await new Promise<void>((resolve) => (finish = resolve));
return {};
}
}
@Module({ mountpoint: '/', controllers: [Ctl], providers: [SlowDb] })
class Slow {}
const app = createApp({ modules: [Slow], health: true, logger: silentLogger() });
const booting = app.boot();
await sleep(10);
expect(await probe(app, '/__ready__')).toMatchObject({ status: 503, body: { status: 'booting' } });
expect(await probe(app, '/__live__')).toMatchObject({ status: 200, body: { status: 'ok' } });
finish();
await booting;
expect(await probe(app, '/__ready__')).toMatchObject({ status: 200, body: { status: 'ok' } });
});
it('T1: a probe before any boot starts the boot without waiting for it', async () => {
let started = false;
@Provider({ provides: 'watched' })
class Watched {
provide() {
started = true;
return {};
}
}
@Module({ mountpoint: '/', controllers: [Ctl], providers: [Watched] })
class W {}
const app = createApp({ modules: [W], health: true, logger: silentLogger() });
expect((await probe(app, '/__ready__')).body).toEqual({ status: 'booting' });
await sleep(10);
expect(started).toBe(true);
expect((await probe(app, '/__ready__')).body).toEqual({ status: 'ok' });
});
it('a failed boot keeps /__ready__ at 503 booting and still fails real requests', async () => {
@Provider({ provides: 'broken' })
class Broken {
provide(): never {
throw new Error('no pool');
}
}
@Module({ mountpoint: '/', controllers: [Ctl], providers: [Broken] })
class B {}
const app = createApp({ modules: [B], health: true, logger: silentLogger() });
await probe(app, '/__ready__');
await sleep(10);
expect(await probe(app, '/__ready__')).toMatchObject({ status: 503, body: { status: 'booting' } });
await expect(app.fetch(new Request('http://x/ping'))).rejects.toThrow("provider 'broken' failed: no pool");
});
it('T2: booted with nothing degraded → 200 ok', async () => {
const app = make({ health: true });
await app.boot();
expect(await probe(app, '/__ready__')).toMatchObject({ status: 200, body: { status: 'ok' } });
});
it('T3: an optional provider failed → 200 degraded with its name', async () => {
@Provider({ provides: 'x', optional: true })
class X {
provide(): never {
throw new Error('down');
}
}
@Module({ mountpoint: '/', controllers: [Ctl], providers: [X] })
class D {}
const app = createApp({ modules: [D], health: true, logger: silentLogger() });
await app.boot();
expect(await probe(app, '/__ready__')).toMatchObject({
status: 200,
body: { status: 'degraded', degraded: ['x'] },
});
});
it('T7: POST /__ready__ → 405 with Allow: GET, HEAD; HEAD answers with no body', async () => {
const app = make({ health: true });
await app.boot();
const post = await probe(app, '/__ready__', 'POST');
expect(post.status).toBe(405);
expect(post.headers.get('allow')).toBe('GET, HEAD');
const head = await probe(app, '/__live__', 'HEAD');
expect(head.status).toBe(200);
expect(head.body).toBeUndefined();
});
it('security headers are injected, cache-control is no-store, a query string is ignored', async () => {
const app = make({ health: true });
await app.boot();
const res = await probe(app, '/__ready__?verbose=1');
expect(res.status).toBe(200);
expect(res.headers.get('cache-control')).toBe('no-store');
expect(res.headers.get('x-content-type-options')).toBe('nosniff');
});
it('T9 + rule 5: no lifecycle event, no plugin step, no log line for a probe', async () => {
const step = vi.fn(() => ({}));
const plugin: Plugin = {
name: 'global-step',
mount(api) {
api.scope.add({ kind: 'step', name: 'everywhere', needs: [], provides: [], run: step });
},
};
const logger = silentLogger();
const app = createApp({ modules: [M], plugins: [plugin], health: true, logRequests: true, logger });
await app.boot();
const emit = vi.spyOn(app.bus, 'emit');
for (let i = 0; i < 10; i++) await probe(app, i % 2 ? '/__live__' : '/__ready__');
expect(emit).not.toHaveBeenCalled();
expect(step).not.toHaveBeenCalled();
expect(logger.info).not.toHaveBeenCalled();
// the control: an ordinary request does run the step and log
await app.fetch(new Request('http://x/ping'));
expect(step).toHaveBeenCalled();
expect(logger.info).toHaveBeenCalled();
});
it('T6: probes answer while maxConcurrentRequests sheds everything else', async () => {
const app = make({ health: true, limits: { maxConcurrentRequests: 1 } });
await app.boot();
const held = app.fetch(new Request('http://x/slow'));
await sleep(10);
expect((await app.fetch(new Request('http://x/ping'))).status).toBe(503);
expect((await probe(app, '/__ready__')).status).toBe(200);
expect((await probe(app, '/__live__')).status).toBe(200);
releaseSlow();
expect((await held).status).toBe(200);
});
it('health off: the probe paths are ordinary paths (404)', async () => {
const app = make();
expect((await app.fetch(new Request('http://x/__ready__'))).status).toBe(404);
});
it('draining after close() on an app served through app.fetch', async () => {
const app = make({ health: true });
await app.boot();
await app.close();
expect(await probe(app, '/__ready__')).toMatchObject({ status: 503, body: { status: 'draining' } });
expect((await probe(app, '/__live__')).status).toBe(200);
});
});
describe('CARD-17: health option validation and reserved paths', () => {
it('invalid health values throw at createApp', () => {
expect(() => make({ health: 'yes' as never })).toThrow(/health must be true, false or \{ drainDelayMs/);
expect(() => make({ health: { drainDelayMs: -1 } })).toThrow(/drainDelayMs must be a non-negative number/);
expect(() => make({ health: { drainDelayMs: Number.NaN } })).toThrow(/non-negative number/);
expect(() => make({ health: { checks: [] } as never })).toThrow(/unknown option 'checks'/);
expect(() => make({ health: { drainDelayMs: 20_000 } })).toThrow(/cannot exceed shutdownTimeoutMs \(10000\)/);
expect(() => make({ health: { drainDelayMs: 600 }, shutdownTimeoutMs: 1000, teardownTimeoutMs: 500 })).toThrow(
/plus teardownTimeoutMs \(500\)/,
);
expect(() => make({ health: { drainDelayMs: 500 } })).not.toThrow();
expect(() => make({ health: false })).not.toThrow();
});
it('T8: @Get(/__live__) with health on fails createApp, naming the route', () => {
@Route('/')
class Own {
@Get('/__live__') live() {
return {};
}
}
@Module({ mountpoint: '/', controllers: [Own] })
class O {}
expect(() => createApp({ modules: [O], health: true })).toThrow(
'route GET /__live__ at Own.live uses the reserved path /__live__ (the liveness probe, health: true) — ' +
'green-tea answers that path itself on every runtime, so no route may declare it. Move the route.',
);
});
it('a route at /__ready__ (HTTP or WS) fails with health on and serves with it off', async () => {
@Route('/')
class Own {
@Get('/__ready__') ready() {
return { mine: true };
}
}
@Module({ mountpoint: '/', controllers: [Own] })
class O {}
@Route('/')
class OwnWs {
@Ws('/__ready__') ready() {
return (async function* () {})();
}
}
@Module({ mountpoint: '/', controllers: [OwnWs] })
class OW {}
expect(() => createApp({ modules: [O], health: true })).toThrow(/^route GET \/__ready__ at Own\.ready uses/);
expect(() => createApp({ modules: [OW], health: true })).toThrow(/^route @Ws \/__ready__ at OwnWs\.ready uses/);
const off = createApp({ modules: [O] });
expect(await (await off.fetch(new Request('http://x/__ready__'))).json()).toEqual({ mine: true });
});
it('a teapot route at /__ready__ fails the teacup splice while health is on', async () => {
const wss = new WebSocketServer({ port: 0 });
wss.on('connection', (ws) => {
ws.on('message', (data) => {
if (decode(data.toString()).type === 'hello') {
ws.send(
encode({
type: 'manifest',
v: MESH_PROTOCOL_VERSION,
steps: [],
routes: [{ method: 'GET', pattern: '/__ready__' }],
}),
);
}
});
});
const url = `ws://127.0.0.1:${(wss.address() as AddressInfo).port}/__mesh__/control`;
const teacup = createApp({
modules: [M],
health: true,
experimental: true,
mesh: { teapots: [{ url, secret: 's' }] },
logger: silentLogger(),
});
try {
await expect(teacup.ready()).rejects.toThrow(
`mesh: remote route 'GET /__ready__' from ${url} uses the reserved path /__ready__`,
);
} finally {
await teacup.close();
wss.close();
}
});
});
/** One request on `agent` (kept alive), resolving with status and body. */
function request(port: number, path: string, agent: http.Agent) {
return new Promise<{ status: number; body: string }>((resolve, reject) => {
const req = http.get({ host: '127.0.0.1', port, path, agent }, (res) => {
let body = '';
res.on('data', (chunk) => (body += chunk));
res.on('end', () => resolve({ status: res.statusCode ?? 0, body }));
});
req.on('error', reject);
});
}
describe('CARD-17: the Node listener', () => {
const agents: http.Agent[] = [];
afterEach(() => agents.splice(0).forEach((agent) => agent.destroy()));
it('serves the probes before the gate; listen() boots first, so the listener never says booting', async () => {
const app = make({ health: true });
const server = await app.listen(0);
const agent = new http.Agent({ keepAlive: true });
agents.push(agent);
try {
const port = (server.address() as AddressInfo).port;
expect(await request(port, '/__ready__', agent)).toEqual({ status: 200, body: '{"status":"ok"}' });
expect(await request(port, '/__live__', agent)).toEqual({ status: 200, body: '{"status":"ok"}' });
} finally {
await app.close();
}
});
it('T4: close() flips /__ready__ to 503 on a kept-alive connection while a slow request completes', async () => {
const app = make({ health: { drainDelayMs: 300 } });
const server = await app.listen(0);
const port = (server.address() as AddressInfo).port;
const agent = new http.Agent({ keepAlive: true, maxSockets: 1 });
const slowAgent = new http.Agent({ keepAlive: true });
agents.push(agent, slowAgent);
// Warm the probe connection so the next probe reuses it.
expect((await request(port, '/__ready__', agent)).status).toBe(200);
const slow = request(port, '/slow', slowAgent);
await sleep(20);
const closing = app.close();
const drained = await request(port, '/__ready__', agent);
expect(drained).toEqual({ status: 503, body: '{"status":"draining"}' });
releaseSlow();
expect(await slow).toEqual({ status: 200, body: '{"slow":true}' });
await closing;
});
it('T4 without drainDelayMs: close() still marks the app draining before it drains', async () => {
const app = make({ health: true });
await app.listen(0);
await app.close();
expect((await probe(app, '/__ready__')).body).toEqual({ status: 'draining' });
});
it('the drain window comes out of the close() budget', async () => {
const app = make({ health: { drainDelayMs: 200 } });
await app.listen(0);
const started = Date.now();
await app.close({ timeoutMs: 1000 });
const took = Date.now() - started;
expect(took).toBeGreaterThanOrEqual(190);
expect(took).toBeLessThan(1000);
});
it('a POST probe on the listener answers 405 with Allow', async () => {
const app = make({ health: true });
const server = await app.listen(0);
try {
const port = (server.address() as AddressInfo).port;
const res = await new Promise<http.IncomingMessage>((resolve) => {
const req = http.request({ host: '127.0.0.1', port, path: '/__ready__', method: 'POST' }, resolve);
req.end();
});
res.resume();
expect(res.statusCode).toBe(405);
expect(res.headers.allow).toBe('GET, HEAD');
expect(res.headers['cache-control']).toBe('no-store');
} finally {
await app.close();
}
});
});
+83
View File
@@ -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',
);
});
}
+25 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
import { mergeInjectedHeaders } from '../src/http/headers';
import { mergeInjectedHeaders, joinListHeaders, toWebHeaders } from '../src/http/headers';
describe('mergeInjectedHeaders', () => {
it('makes injected keys authoritative regardless of handler casing', () => {
@@ -23,3 +23,27 @@ describe('mergeInjectedHeaders', () => {
expect(out['vary']).toBe('Accept');
});
});
describe('array header values (D11)', () => {
it('keeps a handler array intact and still merges vary', () => {
const cookies = ['a=1', 'b=2'];
const out = mergeInjectedHeaders({ 'set-cookie': cookies, Vary: ['Accept', 'Accept-Language'] }, { vary: 'Origin' });
expect(out['set-cookie']).toEqual(['a=1', 'b=2']);
expect(out['vary']).toBe('Accept, Accept-Language, Origin');
});
it('joinListHeaders joins every array but set-cookie, and returns the input when there is none', () => {
const plain = { a: '1' };
expect(joinListHeaders(plain)).toBe(plain);
expect(joinListHeaders({ 'Set-Cookie': ['a=1', 'b=2'], 'x-list': ['a', 'b'] })).toEqual({
'Set-Cookie': ['a=1', 'b=2'],
'x-list': 'a, b',
});
});
it('toWebHeaders appends one set-cookie per element', () => {
const h = toWebHeaders({ 'set-cookie': ['a=1; Expires=Tue, 01 Jan 2030 00:00:00 GMT', 'b=2'], 'x-list': ['a', 'b'] });
expect(h.getSetCookie()).toEqual(['a=1; Expires=Tue, 01 Jan 2030 00:00:00 GMT', 'b=2']);
expect(h.get('x-list')).toBe('a, b');
});
});
+100
View File
@@ -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 -2
View File
@@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest';
import { WebSocketServer } from 'ws';
import { connectLink } from '../../src/mesh/link';
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 { Bus } from '../../src/bus';
import { createApp, Step, Route, Get, Module, needs } from '../../src/index';
@@ -139,7 +139,7 @@ describe('teapot hardening', () => {
const fake = fakeSocket();
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;
expect(fake.closes[0]?.code).toBe(1009);
+31 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect, vi } from 'vitest';
import { createApp, Step, Route, Get, Module, needs } from '../../src/index';
import { createApp, Step, Route, Get, Module, Transformer, needs } from '../../src/index';
const SECRET = 's3cr3t';
@@ -281,3 +281,33 @@ describe('mesh skeleton integration', () => {
tServer.close();
});
});
describe('mesh: Set-Cookie arrays (CARD-14, T10)', () => {
it('a remote route that returns two cookies reaches the teacup client as two lines', async () => {
@Route('/jar')
class JarCtl {
@Get('/two', { export: true })
@Transformer(() => ({ headers: { 'set-cookie': ['a=1; Path=/', 'b=2; Path=/'] }, body: '{}' }))
two() {
return null;
}
}
@Module({ mountpoint: '/api', controllers: [JarCtl] })
class JarTeapotModule {}
const teapot = createApp({ modules: [JarTeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const url = `ws://127.0.0.1:${(tServer.address() as any).port}/__mesh__/control`;
const teacup = createApp({ modules: [PlainTeacupModule], experimental: true, mesh: { teapots: [{ url, secret: SECRET }] } });
const cServer = await teacup.listen(0);
try {
const res = await fetch(`http://127.0.0.1:${(cServer.address() as any).port}/api/jar/two`);
expect(res.status).toBe(200);
expect(res.headers.getSetCookie()).toEqual(['a=1; Path=/', 'b=2; Path=/']);
} finally {
tServer.close();
cServer.close();
}
});
});
+185
View File
@@ -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();
}
});
});
+438
View File
@@ -0,0 +1,438 @@
/**
* CARD-19 (#124, D15): a teacup's remote routes follow which teapots are connected.
*
* Late teapot → its routes are added. Reconnecting → they stay and answer 503 with `retry-after`.
* Gone for good → they are removed (404, `Allow` without them). A returning manifest adds and drops
* routes. A late route that conflicts is refused and logged. Every change emits `mesh:routes`, and
* none rebuilds the local route tree.
*/
import 'reflect-metadata';
import http from 'http';
import net from 'net';
import type { AddressInfo } from 'net';
import { describe, it, expect, afterEach } from 'vitest';
import { WebSocketServer } from 'ws';
import { encode, decode, MESH_PROTOCOL_VERSION, type RouteEntry } from '../../src/mesh/protocol';
import { createApp, Route, Get, Module } from '../../src/index';
import { routerSeamCounts } from '../../src/http/router';
import type { App, MeshConfig } from '../../src/app/types';
import type { EventPayload } from '../../src/bus';
const SECRET = 'membership-secret';
@Route('/remote')
class PingCtl {
@Get('/ping', { export: true }) ping() {
return { from: 'teapot' };
}
}
@Module({ mountpoint: '/api', controllers: [PingCtl] })
class PingTeapot {}
@Route('/remote')
class PingExtraCtl {
@Get('/ping', { export: true }) ping() {
return { from: 'teapot v2' };
}
@Get('/extra', { export: true }) extra() {
return { extra: true };
}
}
@Module({ mountpoint: '/api', controllers: [PingExtraCtl] })
class PingExtraTeapot {}
@Route('/remote')
class ExtraOnlyCtl {
@Get('/extra', { export: true }) extra() {
return { extra: true };
}
}
@Module({ mountpoint: '/api', controllers: [ExtraOnlyCtl] })
class ExtraOnlyTeapot {}
@Route('/shape')
class ShapeIdCtl {
@Get('/:id', { export: true }) get() {
return { from: 'id' };
}
}
@Module({ mountpoint: '/api', controllers: [ShapeIdCtl] })
class ShapeIdTeapot {}
@Route('/')
class ShapeNameCtl {
@Get('/shape/:name', { export: true }) get() {
return { from: 'name' };
}
@Get('/other', { export: true }) other() {
return { from: 'other' };
}
}
@Module({ mountpoint: '/api', controllers: [ShapeNameCtl] })
class ShapeNameTeapot {}
@Route('/local')
class LocalCtl {
@Get('/ok') ok() {
return { from: 'teacup' };
}
}
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {}
const FAST = { initialDelayMs: 20, maxDelayMs: 60 };
/** A port nothing listens on, that a teapot can take later. */
async function freePort(): Promise<number> {
const server = net.createServer();
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const { port } = server.address() as AddressInfo;
await new Promise<void>((resolve) => server.close(() => resolve()));
return port;
}
const controlUrl = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`;
const open: App[] = [];
afterEach(async () => {
while (open.length) await open.pop()!.close();
});
async function teapotOn(port: number, module: new () => unknown): Promise<App> {
const teapot = createApp({ modules: [module], experimental: true, mesh: { secret: SECRET } });
await teapot.listen(port);
open.push(teapot);
return teapot;
}
async function stop(teapot: App): Promise<void> {
await teapot.close();
open.splice(open.indexOf(teapot), 1);
}
interface Teacup {
app: App;
warnings: string[];
events: EventPayload[];
/** Resolves on the next `name` event. */
next: (name: 'mesh:routes' | 'mesh:disconnect') => Promise<EventPayload>;
}
function teacup(ports: number[], mesh: Partial<MeshConfig> = {}, extra: { health?: boolean } = {}): Teacup {
const warnings: string[] = [];
const events: EventPayload[] = [];
const waiting = new Map<string, Array<(e: EventPayload) => void>>();
const app = createApp({
modules: [TeacupModule],
experimental: true,
...extra,
logger: { debug() {}, info() {}, warn: (m: string) => warnings.push(m), error: (m: string) => warnings.push(m) },
mesh: {
teapots: ports.map((port) => ({ url: controlUrl(port), secret: SECRET })),
bootTimeoutMs: 100,
timeoutMs: 1000,
heartbeatMs: 1000,
reconnect: FAST,
...mesh,
},
});
for (const name of ['mesh:routes', 'mesh:disconnect'] as const) {
app.bus.on(name, (payload) => {
if (name === 'mesh:routes') events.push(payload);
const list = waiting.get(name) ?? [];
waiting.delete(name);
for (const resolve of list) resolve(payload);
});
}
open.unshift(app); // closed before the teapots
const next = (name: string) =>
new Promise<EventPayload>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error(`no ${name} within 5s`)), 5000);
waiting.set(name, [
...(waiting.get(name) ?? []),
(e) => {
clearTimeout(timer);
resolve(e);
},
]);
});
return { app, warnings, events, next };
}
const get = (app: App, path: string, method = 'GET') => app.fetch(new Request(`http://mesh.test${path}`, { method }));
function nodeGet(port: number, path: string) {
return new Promise<{ status: number; body: string }>((resolve, reject) => {
const req = http.request({ host: '127.0.0.1', port, method: 'GET', path, agent: false }, (res) => {
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk) => (body += chunk));
res.on('end', () => resolve({ status: res.statusCode ?? 0, body }));
});
req.on('error', reject);
req.end();
});
}
/**
* A teapot speaking the wire protocol directly, so its manifest can carry what a real teapot's own
* boot refuses — an older or foreign peer advertising a reserved path. Every RPC answers `answer`.
*/
async function rawTeapotOn(
port: number,
routes: RouteEntry[],
answer: unknown,
): Promise<{ close: () => Promise<void> }> {
const wss = new WebSocketServer({ port, host: '127.0.0.1' });
wss.on('connection', (ws) => {
ws.on('message', (data) => {
const frame = decode(data.toString());
if (frame.type === 'hello') ws.send(encode({ type: 'manifest', v: MESH_PROTOCOL_VERSION, steps: [], routes }));
else if (frame.type === 'ping') ws.send(encode({ type: 'pong' }));
else if (frame.type === 'rpc-req')
ws.send(
encode({
type: 'rpc-res',
id: frame.id,
ok: true,
result: { status: 200, headers: { 'content-type': 'application/json' }, body: JSON.stringify(answer) },
}),
);
});
});
await new Promise((resolve) => wss.on('listening', resolve));
return {
close: () =>
new Promise<void>((done) => {
for (const client of wss.clients) client.terminate();
wss.close(() => done());
}),
};
}
describe('mesh: remote routes follow teapot membership (CARD-19, D15)', () => {
it('T1: a teapot absent at boot is served once it connects, on app.fetch and listen(), without rebuilding the local tree', async () => {
const port = await freePort();
const cup = teacup([port]);
const listenPort = ((await cup.app.listen(0)).address() as AddressInfo).port;
expect((await get(cup.app, '/api/remote/ping')).status).toBe(404);
expect((await get(cup.app, '/api/local/ok')).status).toBe(200);
const before = routerSeamCounts();
const routed = cup.next('mesh:routes');
await teapotOn(port, PingTeapot);
expect(await routed).toEqual({
name: controlUrl(port),
url: controlUrl(port),
added: ['GET /api/remote/ping'],
removed: [],
});
const res = await get(cup.app, '/api/remote/ping');
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ from: 'teapot' });
expect(await nodeGet(listenPort, '/api/remote/ping')).toEqual({ status: 200, body: '{"from":"teapot"}' });
expect((await get(cup.app, '/api/local/ok')).status).toBe(200);
const after = routerSeamCounts();
expect(after.indexBuilds).toBeGreaterThan(before.indexBuilds); // the remote trees were rebuilt
expect(after.localTreeBuilds).toBe(before.localTreeBuilds); // the local ones were not
});
it('T2/T3: a reconnecting teapot keeps its routes with 503 + retry-after, then serves again', async () => {
const port = await freePort();
let teapot = await teapotOn(port, PingTeapot);
const cup = teacup([port]);
expect((await get(cup.app, '/api/remote/ping')).status).toBe(200);
const dropped = cup.next('mesh:disconnect');
await stop(teapot);
await dropped;
const down = await get(cup.app, '/api/remote/ping');
expect(down.status).toBe(503);
expect(Number(down.headers.get('retry-after'))).toBeGreaterThanOrEqual(1);
expect((await get(cup.app, '/api/remote/ping', 'OPTIONS')).headers.get('allow')).toBe('GET, HEAD, OPTIONS');
expect((await get(cup.app, '/api/remote/ping', 'POST')).headers.get('allow')).toBe('GET, HEAD, OPTIONS');
teapot = await teapotOn(port, PingTeapot);
await expect.poll(async () => (await get(cup.app, '/api/remote/ping')).status, { timeout: 5000 }).toBe(200);
// Same routes back: nothing changed in the table, so no event.
expect(cup.events).toEqual([]);
});
it('T4: with reconnect: false a dropped teapot is gone — 404, Allow without its methods, local routes unaffected', async () => {
const port = await freePort();
const teapot = await teapotOn(port, PingTeapot);
const cup = teacup([port], { reconnect: false });
expect((await get(cup.app, '/api/remote/ping')).status).toBe(200);
const routed = cup.next('mesh:routes');
await stop(teapot);
expect(await routed).toMatchObject({ added: [], removed: ['GET /api/remote/ping'] });
const gone = await get(cup.app, '/api/remote/ping');
expect(gone.status).toBe(404);
expect(gone.headers.get('retry-after')).toBeNull();
const options = await get(cup.app, '/api/remote/ping', 'OPTIONS');
expect(options.status).toBe(404);
expect(options.headers.get('allow')).toBeNull();
expect((await get(cup.app, '/api/local/ok')).status).toBe(200);
expect(cup.warnings.some((w) => w.includes('gone for good'))).toBe(true);
});
it('T5: a teapot that returns with an extra route has it served', async () => {
const port = await freePort();
const teapot = await teapotOn(port, PingTeapot);
const cup = teacup([port]);
expect((await get(cup.app, '/api/remote/extra')).status).toBe(404);
const dropped = cup.next('mesh:disconnect');
await stop(teapot);
await dropped;
const routed = cup.next('mesh:routes');
await teapotOn(port, PingExtraTeapot);
expect(await routed).toMatchObject({ added: ['GET /api/remote/extra'], removed: [] });
expect((await get(cup.app, '/api/remote/extra')).status).toBe(200);
expect(await (await get(cup.app, '/api/remote/ping')).json()).toEqual({ from: 'teapot v2' });
});
it('T6: a teapot that returns without a route has it removed', async () => {
const port = await freePort();
const teapot = await teapotOn(port, PingTeapot);
const cup = teacup([port]);
expect((await get(cup.app, '/api/remote/ping')).status).toBe(200);
const dropped = cup.next('mesh:disconnect');
await stop(teapot);
await dropped;
const routed = cup.next('mesh:routes');
await teapotOn(port, ExtraOnlyTeapot);
expect(await routed).toMatchObject({ added: ['GET /api/remote/extra'], removed: ['GET /api/remote/ping'] });
expect((await get(cup.app, '/api/remote/ping')).status).toBe(404);
expect((await get(cup.app, '/api/remote/extra')).status).toBe(200);
});
it('T7: a late route ambiguous with another teapot’s is refused and logged; everything else serves', async () => {
const [portA, portB] = [await freePort(), await freePort()];
await teapotOn(portA, ShapeIdTeapot);
const cup = teacup([portA, portB]);
expect(await (await get(cup.app, '/api/shape/1')).json()).toEqual({ from: 'id' });
const routed = cup.next('mesh:routes');
await teapotOn(portB, ShapeNameTeapot);
expect(await routed).toMatchObject({ url: controlUrl(portB), added: ['GET /api/other'], removed: [] });
expect(await (await get(cup.app, '/api/shape/1')).json()).toEqual({ from: 'id' });
expect((await get(cup.app, '/api/other')).status).toBe(200);
expect(
cup.warnings.some((w) => w.includes('not serving a route from') && w.includes("'GET /api/shape/:name'")),
).toBe(true);
});
it('T8: 1 000 requests across a late connect each see the old table or the new one', async () => {
const port = await freePort();
const cup = teacup([port]);
expect((await get(cup.app, '/api/remote/ping')).status).toBe(404);
const routed = cup.next('mesh:routes');
const starting = teapotOn(port, PingTeapot);
const statuses: number[] = [];
let changed = false;
void routed.then(() => (changed = true));
// 100 waves of 10 concurrent requests, spread across the moment the table changes. Ten at a time,
// not more: past 16 RPCs in flight on one link the teapot's control channel hits the WebSocket
// inbound-queue bound (#107) and drops the link. That is pre-existing and not about membership.
for (let wave = 0; wave < 100; wave++) {
const batch = await Promise.all(
Array.from({ length: 10 }, () => get(cup.app, '/api/remote/ping').then((res) => res.status)),
);
statuses.push(...batch);
if (!changed) await new Promise((resolve) => setTimeout(resolve, 2));
}
await starting;
await routed;
expect(statuses).toHaveLength(1000);
expect(statuses.every((status) => status === 404 || status === 200)).toBe(true);
// Both tables were actually seen, so the change happened while requests were flowing.
expect(statuses).toContain(404);
expect(statuses).toContain(200);
expect((await get(cup.app, '/api/remote/ping')).status).toBe(200);
});
it('with reconnect: false a teapot absent at boot is not retried (no backoff to retry with)', async () => {
const port = await freePort();
const cup = teacup([port], { reconnect: false });
expect((await get(cup.app, '/api/remote/ping')).status).toBe(404);
await teapotOn(port, PingTeapot);
await new Promise((resolve) => setTimeout(resolve, 300));
expect((await get(cup.app, '/api/remote/ping')).status).toBe(404);
expect(cup.events).toEqual([]);
});
it('a late teapot advertising /__mesh__/control has that route refused; its other routes are served', async () => {
const port = await freePort();
const cup = teacup([port]);
expect((await get(cup.app, '/api/fake/ok')).status).toBe(404);
const routed = cup.next('mesh:routes');
const raw = await rawTeapotOn(
port,
[
{ method: 'GET', pattern: '/__mesh__/control' },
{ method: 'GET', pattern: '/api/fake/ok' },
],
{ from: 'raw teapot' },
);
try {
expect(await routed).toMatchObject({ added: ['GET /api/fake/ok'], removed: [] });
expect(await (await get(cup.app, '/api/fake/ok')).json()).toEqual({ from: 'raw teapot' });
expect(await (await get(cup.app, '/__mesh__/control')).text()).not.toContain('raw teapot');
expect(
cup.warnings.some((w) => w.includes('not serving a route from') && w.includes("'GET /__mesh__/control'")),
).toBe(true);
} finally {
await cup.app.close();
open.splice(open.indexOf(cup.app), 1);
await raw.close();
}
});
it('with health on, a late teapot advertising /__ready__ has that route refused; its other routes are served', async () => {
const port = await freePort();
const cup = teacup([port], {}, { health: true });
expect((await get(cup.app, '/api/fake/ok')).status).toBe(404);
const routed = cup.next('mesh:routes');
const raw = await rawTeapotOn(
port,
[
{ method: 'GET', pattern: '/__ready__' },
{ method: 'GET', pattern: '/api/fake/ok' },
],
{ from: 'raw teapot' },
);
try {
expect(await routed).toMatchObject({ added: ['GET /api/fake/ok'], removed: [] });
expect((await get(cup.app, '/api/fake/ok')).status).toBe(200);
expect(await (await get(cup.app, '/__ready__')).text()).not.toContain('raw teapot');
expect(cup.warnings.some((w) => w.includes('not serving a route from') && w.includes("'GET /__ready__'"))).toBe(
true,
);
} finally {
await cup.app.close();
open.splice(open.indexOf(cup.app), 1);
await raw.close();
}
});
});
+5 -3
View File
@@ -143,7 +143,7 @@ describe('missingFromManifest', () => {
expect(missingFromManifest(booted, booted)).toEqual([]);
});
it('accepts extra exports — the graph is fixed at boot and nothing new is spliced', () => {
it('accepts extra exports — extra steps are ignored, since the graph is fixed at boot', () => {
const wider: Manifest = {
steps: [...booted.steps, 'billing'],
routes: [...booted.routes, { method: 'POST', pattern: '/svc/new' }],
@@ -161,8 +161,10 @@ describe('missingFromManifest', () => {
expect(missingFromManifest(booted, shrunk)).toEqual(["step 'auth'"]);
});
it('reports a missing route by method and pattern', () => {
// D15 (CARD-19): routes are not part of the graph, so a returning teapot's routes replace the old
// ones (a dropped route is removed from the remote table) instead of refusing the reconnect.
it('does not report a missing route — routes follow the returning manifest', () => {
const routeless: Manifest = { steps: booted.steps, routes: [] };
expect(missingFromManifest(booted, routeless)).toEqual(["route 'GET /svc/:id'"]);
expect(missingFromManifest(booted, routeless)).toEqual([]);
});
});
+152
View File
@@ -0,0 +1,152 @@
/**
* CARD-20 (#125, D16): `HEAD` on a remote buffered `GET` behaves like `HEAD` on a local one.
*
* The teacup resolves `HEAD` to the remote `GET` (implicit HEAD) and forwards it to the teapot as a
* `GET`, then drops the body. The teapot is unchanged, so an older teapot works too.
*/
import 'reflect-metadata';
import http from 'http';
import type { AddressInfo } from 'net';
import { describe, it, expect, afterEach } from 'vitest';
import { createApp, Route, Get, Head, Module, NotFound, ctx } from '../../src/index';
import type { App } from '../../src/app/types';
import type { Logger } from '../../src/logger';
const SECRET = 'head-secret';
const quiet: Logger = { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} };
const seen: string[] = [];
@Route('/')
class RemoteCtl {
@Get('/x', { export: true }) x(@ctx() c: { req: { method: string } }) {
seen.push(`x ${c.req.method}`);
return { a: 1 };
}
@Get('/missing', { export: true }) missing() {
seen.push('missing');
throw new NotFound();
}
@Get('/boom', { export: true }) boom() {
seen.push('boom');
throw new Error('kaboom');
}
@Get('/both', { export: true }) bothGet() {
seen.push('both GET');
return { via: 'get' };
}
@Head('/both', { export: true }) bothHead(@ctx() c: { req: { method: string } }) {
seen.push(`both HEAD as ${c.req.method}`);
return { via: 'head' };
}
}
@Module({ mountpoint: '/api', controllers: [RemoteCtl] })
class TeapotModule {}
@Module({ mountpoint: '/api', controllers: [] })
class TeacupModule {}
const open: App[] = [];
afterEach(async () => {
while (open.length) await open.pop()!.close();
seen.length = 0;
});
async function mesh(): Promise<{ teacup: App; port: number }> {
const teapot = createApp({ modules: [TeapotModule], experimental: true, logger: quiet, mesh: { secret: SECRET } });
open.push(teapot);
const tPort = ((await teapot.listen(0)).address() as AddressInfo).port;
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
logger: quiet,
mesh: { teapots: [{ url: `ws://127.0.0.1:${tPort}/__mesh__/control`, secret: SECRET }], reconnect: false },
});
open.unshift(teacup); // closed first
const port = ((await teacup.listen(0)).address() as AddressInfo).port;
return { teacup, port };
}
function nodeRequest(port: number, method: string, path: string) {
return new Promise<{ status: number; headers: http.IncomingHttpHeaders; body: string }>((resolve, reject) => {
const req = http.request({ host: '127.0.0.1', port, method, path, agent: false }, (res) => {
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk) => (body += chunk));
res.on('end', () => resolve({ status: res.statusCode ?? 0, headers: res.headers, body }));
});
req.on('error', reject);
req.end();
});
}
const fetchVia = (app: App, method: string, path: string) =>
app.fetch(new Request(`http://mesh.test${path}`, { method }));
describe('mesh: HEAD on a remote GET route (CARD-20, D16)', () => {
it('T1: HEAD via app.fetch answers 200 with the GET headers and no body', async () => {
const { teacup } = await mesh();
const get = await fetchVia(teacup, 'GET', '/api/x');
const head = await fetchVia(teacup, 'HEAD', '/api/x');
expect(head.status).toBe(200);
expect(head.headers.get('content-type')).toBe(get.headers.get('content-type'));
expect(head.headers.get('content-type')).toContain('application/json');
expect(await head.text()).toBe('');
expect(await get.json()).toEqual({ a: 1 });
});
it('T2: HEAD via the Node listener answers 200 with the GET headers and no body', async () => {
const { port } = await mesh();
const get = await nodeRequest(port, 'GET', '/api/x');
const head = await nodeRequest(port, 'HEAD', '/api/x');
expect(head.status).toBe(200);
expect(head.headers['content-type']).toBe(get.headers['content-type']);
expect(head.body).toBe('');
});
it('OPTIONS still advertises GET, HEAD, OPTIONS', async () => {
const { teacup, port } = await mesh();
expect((await fetchVia(teacup, 'OPTIONS', '/api/x')).headers.get('allow')).toBe('GET, HEAD, OPTIONS');
expect((await nodeRequest(port, 'OPTIONS', '/api/x')).headers.allow).toBe('GET, HEAD, OPTIONS');
});
it('T3: an explicit remote HEAD route keeps precedence over the implicit fallback', async () => {
const { teacup, port } = await mesh();
const viaFetch = await fetchVia(teacup, 'HEAD', '/api/both');
expect(viaFetch.status).toBe(200);
expect(await viaFetch.text()).toBe('');
const viaNode = await nodeRequest(port, 'HEAD', '/api/both');
expect(viaNode.status).toBe(200);
expect(viaNode.body).toBe('');
// The explicit HEAD handler ran, reached as HEAD — the GET handler never did.
expect(seen).toEqual(['both HEAD as HEAD', 'both HEAD as HEAD']);
});
it('T4: a remote GET that throws NotFound answers HEAD with 404 and no body', async () => {
const { teacup, port } = await mesh();
const viaFetch = await fetchVia(teacup, 'HEAD', '/api/missing');
expect(viaFetch.status).toBe(404);
expect(await viaFetch.text()).toBe('');
const viaNode = await nodeRequest(port, 'HEAD', '/api/missing');
expect(viaNode.status).toBe(404);
expect(viaNode.body).toBe('');
// The teapot handler ran: the 404 is the route's, not a missing HEAD plan on the teapot.
expect(seen).toEqual(['missing', 'missing']);
});
it('a remote GET that fails answers HEAD with 500 and no body', async () => {
const { teacup, port } = await mesh();
const viaFetch = await fetchVia(teacup, 'HEAD', '/api/boom');
expect(viaFetch.status).toBe(500);
expect(await viaFetch.text()).toBe('');
const viaNode = await nodeRequest(port, 'HEAD', '/api/boom');
expect(viaNode.status).toBe(500);
expect(viaNode.body).toBe('');
});
it('T5: one HEAD calls the teapot handler once, as a GET', async () => {
const { teacup } = await mesh();
await fetchVia(teacup, 'HEAD', '/api/x');
expect(seen).toEqual(['x GET']);
});
});
+134
View File
@@ -0,0 +1,134 @@
// CARD-18 (GitHub #35, D9): every token has at most one producer across modules, plugins, mesh steps
// and built-ins. A second producer fails `createApp`, naming both nodes and their origins.
import 'reflect-metadata';
import { describe, expect, it } from 'vitest';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../src/index';
import type { Plugin, ScopeNode } from '../src/index';
@Provider({ provides: 'user' })
class User {
provide() {
return { user: { id: 'real' } };
}
}
@Route('/u')
class UserCtl {
@Get('/me') me(@needs('user') user: unknown) {
return { user };
}
}
@Module({ mountpoint: '/', providers: [User], controllers: [UserCtl] })
class AppModule {}
/** A plugin that adds one scope node, the way an official plugin would. */
const adds = (name: string, node: Omit<ScopeNode, 'run'> & Partial<Pick<ScopeNode, 'run'>>): Plugin => ({
name,
mount({ scope }) {
scope.add({ run: () => Object.fromEntries(node.provides.map((key) => [key, `from ${name}`])), ...node });
},
});
describe('one producer per token', () => {
it('T1: a plugin node providing a module-provided token fails boot, naming both nodes and origins', () => {
const shadow = adds('shadow', { kind: 'provider', name: 'shadow', needs: [], provides: ['user'] });
expect(() => createApp({ modules: [AppModule], plugins: [shadow] })).toThrow(
"token 'user' is provided twice: by 'user' (module:AppModule) and by 'shadow' (plugin)",
);
});
it('T1: a plugin step providing it fails the same way', () => {
const shadow = adds('shadow', { kind: 'step', name: 'shadow', needs: [], provides: ['user'] });
expect(() => createApp({ modules: [AppModule], plugins: [shadow] })).toThrow(/'user' \(module:AppModule\).*'shadow' \(plugin\)/);
});
it('T2: a plugin node providing a built-in token fails boot instead of losing silently', () => {
const fake = adds('fake-logger', { kind: 'provider', name: 'fake-logger', needs: [], provides: ['logger'] });
// Plugins mount before the built-ins are registered, so the plugin is the one seen first. The
// order the two are reported in is not the point; that both are, with their origins, is.
expect(() => createApp({ modules: [AppModule], plugins: [fake] })).toThrow(
"token 'logger' is provided twice: by 'fake-logger' (plugin) and by 'logger' (builtin)",
);
});
it.each(['rooms', 'events'])('T2: the same holds for the built-in %s', (token) => {
const fake = adds('fake', { kind: 'provider', name: 'fake', needs: [], provides: [token] });
expect(() => createApp({ modules: [AppModule], plugins: [fake] })).toThrow(`token '${token}' is provided twice`);
});
it('T3: a plugin node providing two tokens, one of them taken, fails naming the taken one', () => {
const both = adds('both', { kind: 'provider', name: 'both', needs: [], provides: ['a', 'user'] });
expect(() => createApp({ modules: [AppModule], plugins: [both] })).toThrow(/^token 'user' is provided twice/);
});
it('T4: two plugins providing distinct tokens boot', async () => {
const a = adds('a', { kind: 'provider', name: 'a', needs: [], provides: ['a'] });
const b = adds('b', { kind: 'provider', name: 'b', needs: [], provides: ['b'] });
const app = createApp({ modules: [AppModule], plugins: [a, b] });
await expect(app.boot()).resolves.toBeUndefined();
});
it('two plugin nodes providing the same token fail, naming both', () => {
const a = adds('a', { kind: 'step', name: 'a', needs: [], provides: ['shared'] });
const b = adds('b', { kind: 'step', name: 'b', needs: [], provides: ['shared'] });
expect(() => createApp({ modules: [AppModule], plugins: [a, b] })).toThrow(
"token 'shared' is provided twice: by 'a' (plugin) and by 'b' (plugin)",
);
});
it('observer steps that provide nothing do not count as producers', async () => {
const one = adds('one', { kind: 'step', name: 'one', needs: [], provides: [] });
const two = adds('two', { kind: 'step', name: 'two', needs: [], provides: [] });
await expect(createApp({ modules: [AppModule], plugins: [one, two] }).boot()).resolves.toBeUndefined();
});
it('T5: overrides replace the runner of an existing token, not add a producer', async () => {
const app = createApp({ modules: [AppModule], overrides: { user: { id: 1 } } });
const res = await app.fetch(new Request('http://x/u/me'));
expect(await res.json()).toEqual({ user: { id: 1 } });
});
});
describe('one producer per token: mesh', () => {
const SECRET = 's3cr3t';
@Step({ provides: 'auth', needs: [], export: true })
class RemoteAuth {
run() {
return { auth: 'remote' };
}
}
@Module({ mountpoint: '/', steps: [RemoteAuth] })
class TeapotModule {}
@Step({ provides: 'auth', needs: [] })
class LocalAuth {
run() {
return { auth: 'local' };
}
}
@Route('/a')
class AuthCtl {
@Get('/who') who(@needs('auth') auth: unknown) {
return { auth };
}
}
@Module({ mountpoint: '/', steps: [LocalAuth], controllers: [AuthCtl] })
class TeacupModule {}
it('T6: a remote step whose token a local node provides still fails at splice', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const server = await teapot.listen(0);
const url = `ws://127.0.0.1:${(server.address() as any).port}/__mesh__/control`;
const teacup = createApp({ modules: [TeacupModule], experimental: true, mesh: { teapots: [{ url, secret: SECRET }] } });
try {
await expect(teacup.ready()).rejects.toThrow("duplicate provider/step name 'auth'");
} finally {
await teacup.close().catch(() => {});
await teapot.close();
}
});
});
+61
View File
@@ -0,0 +1,61 @@
import 'reflect-metadata';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import type { AddressInfo } from 'node:net';
import type { Server } from 'node:http';
import { Get, Module, Route, Transformer } from '../src/metadata';
import { JsonTransformer } from '../src/transformers';
import { createApp } from '../src/app';
import { parseQuery } from '../src/http';
import { query } from '../src/params';
// CARD-25 / GitHub #48: the query string is everything after the FIRST `?` (and before `#`).
const CASES: Array<[string, Record<string, string>]> = [
['/search?q=what?now', { q: 'what?now' }], // T1
['/search?a=1&b=?', { a: '1', b: '?' }], // T2
['/search?', {}], // T3
['/search', {}], // T4
];
describe('parseQuery', () => {
test.each(CASES)('%s', (url, expected) => {
expect(parseQuery(url)).toEqual(expected);
});
test('stops at a fragment', () => {
expect(parseQuery('/search?q=a?b#frag?x=1')).toEqual({ q: 'a?b' });
});
});
@Route('/search')
class SearchCtl {
@Get('/')
@Transformer(JsonTransformer)
search(@query() q: Record<string, string>) {
return q;
}
}
@Module({ mountpoint: '/', controllers: [SearchCtl] })
class SearchModule {}
describe('query string with more than one `?`', () => {
const app = createApp({ modules: [SearchModule] });
let server: Server;
let base: string;
beforeAll(async () => {
server = await app.listen(0);
base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
});
afterAll(() => new Promise<void>((resolve) => server.close(() => resolve())));
test.each(CASES)('app.fetch %s', async (url, expected) => {
const res = await app.fetch(new Request(`http://x${url}`));
expect(await res.json()).toEqual(expected);
});
test.each(CASES)('Node listener %s', async (url, expected) => {
const res = await fetch(`${base}${url}`);
expect(await res.json()).toEqual(expected);
});
});
+247
View File
@@ -0,0 +1,247 @@
/**
* CARD-21 (#126, D17): `/__mesh__/control` is reserved in every app, mesh or not. Boot refuses a route
* that claims it, and an upgrade to it on an app without a control channel is refused the same way
* by the Node listener and by `app.upgrade`. Deno, Bun and workerd repeat T1/T5 in their own suites.
*/
import 'reflect-metadata';
import { describe, it, expect, afterEach } from 'vitest';
import type { AddressInfo } from 'net';
import type http from 'http';
import WebSocket, { WebSocketServer } from 'ws';
import { createApp, Route, Get, Post, Ws, Stream, Module, param, MESH_CONTROL_PATH } from '../src/index';
import type { RouteDecorator } from '../src/metadata';
import { channel } from '../src/channel';
import type { WsRequest, WsSocket } from '../src/http/ws-core';
import { claimedReservedPath } from '../src/http/reserved-paths';
import { encode, decode, MESH_PROTOCOL_VERSION } from '../src/mesh/protocol';
const REASON = 'mesh control channel not enabled: this app exports nothing, or has no mesh.secret';
const RESERVED = [{ path: MESH_CONTROL_PATH, purpose: 'the mesh control channel' }];
type Decl = [RouteDecorator, string];
/** One controller under `mountpoint`, a handler per declaration (`h0`, `h1`, …). */
function moduleWith(decls: Decl[], mountpoint = '/', name = 'Routes') {
const Routes = { [name]: class {} }[name];
decls.forEach(([decorator, path], index) => {
const handler = `h${index}`;
Object.defineProperty(Routes.prototype, handler, {
value: (p: Record<string, string>) =>
(async function* () {
yield { route: handler, params: p };
})(),
configurable: true,
});
param()(Routes.prototype, handler, 0);
decorator(path)(Routes.prototype, handler, Object.getOwnPropertyDescriptor(Routes.prototype, handler)!);
});
Route('/')(Routes);
class RoutesModule {}
Module({ mountpoint, controllers: [Routes] })(RoutesModule);
return RoutesModule;
}
const bootError = (decls: Decl[], mountpoint?: string): string => {
try {
createApp({ modules: [moduleWith(decls, mountpoint)] });
} catch (error) {
return (error as Error).message;
}
throw new Error('expected the app to refuse to boot');
};
describe('CARD-21: a route on the reserved mesh path fails createApp', () => {
it('T1: @Ws(/__mesh__/control) on a non-mesh app', () => {
expect(bootError([[Ws, '/__mesh__/control']])).toBe(
'route @Ws /__mesh__/control at Routes.h0 uses the reserved path /__mesh__/control (the mesh control channel) — ' +
'green-tea answers that path itself on every runtime, so no route may declare it. Move the route.',
);
});
it('T2: @Get(/__mesh__/control)', () => {
expect(bootError([[Get, '/__mesh__/control']])).toMatch(
/^route GET \/__mesh__\/control at Routes\.h0 uses the reserved path \/__mesh__\/control/,
);
});
it('T3: @Ws(/__mesh__/:x) — a parameterised pattern is checked by matching', () => {
expect(bootError([[Ws, '/__mesh__/:x']])).toMatch(/^route @Ws \/__mesh__\/:x at Routes\.h0 uses the reserved path/);
});
it('@Stream, other methods, catch-alls, a trailing slash and a mountpoint are caught too', () => {
expect(bootError([[Stream, '/__mesh__/control']])).toMatch(/^route @Stream \/__mesh__\/control at/);
expect(bootError([[Post, '/__mesh__/control']])).toMatch(/^route POST /);
expect(bootError([[Get, '/__mesh__/:rest*']])).toMatch(/uses the reserved path/);
expect(bootError([[Get, '/__mesh__/control/']])).toMatch(/uses the reserved path/);
expect(bootError([[Get, '/control']], '/__mesh__')).toMatch(/^route GET \/__mesh__\/control at/);
expect(bootError([[Get, '/__mesh__/:x(c.*)']])).toMatch(/uses the reserved path/);
});
it('a mesh-enabled app gets the same refusal: the reservation does not depend on the mesh', () => {
expect(() =>
createApp({
modules: [moduleWith([[Ws, '/__mesh__/control']])],
experimental: true,
mesh: { secret: 's' },
}),
).toThrow(/uses the reserved path \/__mesh__\/control/);
});
it('patterns that do not name the reserved prefix still boot (the path is carved out of them)', () => {
expect(() =>
createApp({
modules: [
moduleWith([
[Get, '/:org/:repo'],
[Get, '/__mesh__/other'],
[Get, '/__mesh__/:x(\\d+)'],
[Get, '/__mesh__'],
[Get, '/__mesh__/control/deeper'],
]),
],
}),
).not.toThrow();
expect(() => createApp({ modules: [moduleWith([[Ws, '/:a/:b']])] })).not.toThrow();
expect(() => createApp({ modules: [moduleWith([[Get, '/:rest*']])] })).not.toThrow();
});
it('claimedReservedPath: literal by equality, parameterised by matching, prefix spelled literally', () => {
expect(claimedReservedPath('/__mesh__/control', RESERVED)).toEqual(RESERVED[0]);
expect(claimedReservedPath('/__mesh__/:x', RESERVED)).toEqual(RESERVED[0]);
expect(claimedReservedPath('/__mesh__/:rest*', RESERVED)).toEqual(RESERVED[0]);
expect(claimedReservedPath('/:a/control', RESERVED)).toBeUndefined();
expect(claimedReservedPath('/:rest*', RESERVED)).toBeUndefined();
expect(claimedReservedPath('/', RESERVED)).toBeUndefined();
expect(claimedReservedPath('/__mesh__/:x(\\d+)', RESERVED)).toBeUndefined();
});
});
/** Drives `app.upgrade` with an in-memory socket and records what it sent and how it closed. */
async function viaAppUpgrade(app: ReturnType<typeof createApp>, path: string) {
const sent: unknown[] = [];
const closes: Array<{ code?: number; reason?: string }> = [];
const ac = new AbortController();
let open = true;
const socket: WsSocket = {
inbound: channel<unknown>(),
abort: ac.signal,
get isOpen() {
return open;
},
send: (data) => sent.push(data),
close: (code, reason) => {
open = false;
closes.push({ code, reason });
ac.abort();
},
terminate: () => {
open = false;
ac.abort();
},
};
const request: WsRequest = { url: path, headers: {}, protocol: 'http', ip: '127.0.0.1' };
await app.upgrade(request, socket);
return { sent, closes };
}
/** Opens a `ws` client on the Node listener and resolves with the HTTP status or the close frame. */
function viaNodeUpgrade(port: number, path: string) {
return new Promise<{ status: number; close?: { code: number; reason: string } }>((resolve) => {
const client = new WebSocket(`ws://127.0.0.1:${port}${path}`);
client.on('unexpected-response', (_req, res) => {
resolve({ status: res.statusCode ?? 0 });
res.resume();
client.terminate();
});
client.on('close', (code, reason) => resolve({ status: 101, close: { code, reason: String(reason) } }));
client.on('error', () => {});
});
}
describe('CARD-21: an upgrade to the reserved path on an app with no control channel', () => {
const servers: http.Server[] = [];
afterEach(async () => {
await Promise.all(servers.splice(0).map((server) => new Promise((resolve) => server.close(resolve))));
});
const ordinary = () => moduleWith([[Ws, '/echo']], '/', 'Ordinary');
it('T4: the Node listener accepts and closes 1008 with the app.upgrade reason', async () => {
const app = createApp({ modules: [ordinary()] });
const server = await app.listen(0);
servers.push(server);
expect(await viaNodeUpgrade((server.address() as AddressInfo).port, '/__mesh__/control')).toEqual({
status: 101,
close: { code: 1008, reason: REASON },
});
});
it('T4: a teapot with no exports (mesh configured, no control channel) refuses the same way on Node', async () => {
const app = createApp({ modules: [ordinary()], experimental: true, mesh: {} });
const server = await app.listen(0);
servers.push(server);
expect(await viaNodeUpgrade((server.address() as AddressInfo).port, '/__mesh__/control')).toEqual({
status: 101,
close: { code: 1008, reason: REASON },
});
});
it('T5: app.upgrade closes 1008 with the same reason', async () => {
const app = createApp({ modules: [ordinary()] });
expect(await viaAppUpgrade(app, '/__mesh__/control')).toEqual({
sent: [],
closes: [{ code: 1008, reason: REASON }],
});
});
});
describe('CARD-21 T7: a teapot that advertises a route on the reserved path', () => {
let wss: WebSocketServer | undefined;
afterEach(() => wss?.close());
/** A hand-rolled teapot: a real one refuses such a route at its own boot, so only the wire can carry it. */
function foreignTeapot(pattern: string): string {
wss = new WebSocketServer({ port: 0 });
wss.on('connection', (ws) => {
ws.on('message', (data) => {
const frame = decode(data.toString());
if (frame.type === 'hello') {
ws.send(
encode({
type: 'manifest',
v: MESH_PROTOCOL_VERSION,
steps: [],
routes: [{ method: 'GET', pattern }],
}),
);
}
});
});
return `ws://127.0.0.1:${(wss.address() as AddressInfo).port}/__mesh__/control`;
}
it('the teacup splice fails and names the teapot', async () => {
const url = foreignTeapot('/__mesh__/:x');
const teacup = createApp({
modules: [moduleWith([[Get, '/ok']])],
experimental: true,
mesh: { teapots: [{ url, secret: 's' }] },
});
try {
await expect(teacup.ready()).rejects.toThrow(
`mesh: remote route 'GET /__mesh__/:x' from ${url} uses the reserved path /__mesh__/control ` +
'(the mesh control channel)',
);
} finally {
await teacup.close();
}
});
});
+1 -1
View File
@@ -31,7 +31,7 @@ Nothing can regenerate the baseline by accident:
| `frozen/matcher-*.json` | Captured matcher outputs: declaration ID, decoded params, `implicitHead`, ordered `Allow`, or the normalization error. The generated file also stores the seed, the generator rules and every generated input. |
| `frozen/app-*.json` | Status, headers, `Allow` and body through `app.fetch` and through a Node socket, including HEAD body suppression. |
| `frozen/ws-*.json` | WS upgrade selection through `app.upgrade` and the Node listener, plus HTTP requests at the WS paths. |
| `frozen/owner-*.json` | Owner additions needing a running app: cross-pattern `Allow` through both adapters, and the mesh HTTP route table across a peer's lifetime (it is built once at boot and never changes — see `owner.test.ts`). |
| `frozen/owner-*.json` | Owner additions needing a running app: cross-pattern `Allow` through both adapters, and the mesh HTTP route table across a peer's lifetime (built once at boot at the pinned revision; since CARD-19 it follows teapot membership — see `owner.test.ts`). |
| `frozen/boot-*.json` | Boot-time rejections: pattern compilation, local ambiguity, mesh splicing. |
| `frozen/golden-*.json` | `graph()`, `explain()`, `openapi({ title: 'Parity', version: '1' })`, and a mesh teacup before and after `ready()`. |
@@ -206,7 +206,7 @@
"adapter": "fetch",
"method": "HEAD",
"path": "/api/x",
"status": 404,
"status": 200,
"headers": {
"content-type": "application/json",
"referrer-policy": "no-referrer",
@@ -472,7 +472,7 @@
"adapter": "node",
"method": "HEAD",
"path": "/api/x",
"status": 404,
"status": 200,
"headers": {
"content-type": "application/json",
"referrer-policy": "no-referrer",
@@ -101,17 +101,17 @@
"phase": "B2 teapot up after boot",
"method": "GET",
"path": "/api/remote/ping",
"status": 404,
"status": 200,
"allow": null,
"body": "{\"error\":\"Not Found\"}"
"body": "{\"from\":\"teapot\"}"
},
{
"phase": "B2 teapot up after boot",
"method": "POST",
"path": "/api/remote/ping",
"status": 404,
"allow": null,
"body": "{\"error\":\"Not Found\"}"
"status": 405,
"allow": "GET, HEAD, OPTIONS",
"body": "{\"error\":\"Method Not Allowed\"}"
},
{
"phase": "B2 teapot up after boot",
@@ -134,15 +134,10 @@
{
"path": "/__mesh__/control",
"status": 101,
"sent": [
{
"id": "reserved",
"params": {}
}
],
"sent": [],
"close": {
"code": 1005,
"reason": ""
"code": 1008,
"reason": "mesh control channel not enabled: this app exports nothing, or has no mesh.secret"
}
}
]
+24 -7
View File
@@ -88,15 +88,30 @@ const teacupFor = (port: number) =>
teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: SECRET }],
bootTimeoutMs: 300,
timeoutMs: 500,
reconnect: false,
// Reconnect on (CARD-19, D15): a dropped teapot is "reconnecting" and keeps its routes (A2),
// and one absent at boot is retried in the background (B). Captured at ed47836 with
// `reconnect: false`, when neither depended on it. Fast backoff keeps the test short.
reconnect: { initialDelayMs: 20, maxDelayMs: 60 },
},
});
/** Resolves on the teacup's next `mesh:routes` event: its remote table changed. */
const routesChanged = (app: App) =>
new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error('no mesh:routes within 5s')), 5000);
const off = app.bus.on('mesh:routes', () => {
clearTimeout(timer);
off();
resolve();
});
});
/**
* Two lifetimes. A: the teapot is up at boot, then goes away. B: the teapot is absent at boot and
* comes up afterwards. The current code builds the HTTP table once, at boot, and never changes it:
* routes spliced at boot stay in the table after their peer leaves, and a peer that arrives late
* is never spliced in. CARD-10 can reuse this to assert the index is not rebuilt per request.
* comes up afterwards. At ed47836 the HTTP table was built once, at boot, and never changed, so B2
* answered 404. Since CARD-19 (D15, owner approval) the remote routes follow membership: a teapot
* that is reconnecting keeps its routes and answers 503 (A2), and a late one is spliced in when it
* connects (B2). CARD-10 can reuse this to assert the index is not rebuilt per request.
*/
async function meshLifetimes() {
const results = [];
@@ -118,7 +133,9 @@ async function meshLifetimes() {
const teapotB = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
try {
results.push(...(await probe(teacupB, 'B1 teapot absent at boot')));
const spliced = routesChanged(teacupB);
await teapotB.listen(portB);
await spliced;
results.push(...(await probe(teacupB, 'B2 teapot up after boot')));
} finally {
await teacupB.close();
@@ -141,9 +158,9 @@ class RemoteMixCtl {
return { from: 'teapot', route: 'POST /api/v/:id' };
}
// Remote only: remote routes are `buffer`, so the teacup's router resolves HEAD to it implicitly.
// Captured as observed at ed47836: the teacup forwards the request as HEAD, the teapot looks its
// plan up by (pattern, method) and has none for HEAD, so HEAD answers 404 while OPTIONS still
// advertises HEAD. That is the mesh proxy's behaviour, not the matcher's; CARD-07 must keep it.
// Captured at ed47836 as HEAD → 404 (the teacup forwarded HEAD, and the teapot has no HEAD plan).
// CARD-20 (#125, D16) changed that deliberately, with owner approval: the teacup forwards the
// HEAD as a GET and drops the body, so HEAD now answers 200 like a local route.
@Get('/x', { export: true }) x() {
return { from: 'teapot', route: 'GET /api/x' };
}
+4 -5
View File
@@ -3,7 +3,8 @@
* with no specificity ranking, an HTTP route at the same path never takes the upgrade, and the mesh
* control path is checked before WS route matching. Captured through both upgrade entry points —
* `app.upgrade` (Deno/Bun/edge) and the Node `server.on('upgrade')` listener — because they are
* separate code paths and do not agree on everything (see the reserved-path rows in the fixture).
* separate code paths. They used to disagree on the reserved mesh path; since CARD-21 (D17) both refuse
* it with the same 1008 close.
*/
import 'reflect-metadata';
import type { AddressInfo } from 'net';
@@ -40,10 +41,8 @@ class ParityWs {
@Stream('/feed') feed() {
return announce('feed', {});
}
// A user route on the reserved mesh path, on an app with no mesh: the two adapters disagree here.
@Ws('/__mesh__/control') reserved(@param() p: Record<string, string>) {
return announce('reserved', p);
}
// No route on the reserved mesh path: since CARD-21 (D17) the boot refuses one. The path stays in
// UPGRADE_PATHS so both adapters' refusal on an app with no mesh is captured; they now agree.
}
@Module({ mountpoint: '/', controllers: [ParityWs] })
+109
View File
@@ -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);
});
+103
View File
@@ -152,3 +152,106 @@ describe('runWsConnection correlation', () => {
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
});
});