Commit Graph
24 Commits
Author SHA1 Message Date
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 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 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 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 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 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 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
chrnxandClaude Opus 5.5 69bdc8adec test(bun): expect 1009 for oversized WebSocket frames on Bun 1.4+
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / build (pull_request) Successful in 27s
CI picked up Bun 1.4.4 (`oven-sh/setup-bun@v2`, latest), which now sends a
real `1009` close frame when `maxPayloadLength` refuses a frame. Bun 1.3
dropped the connection instead, so the peer saw `1006` — the difference D1
documented and these two assertions pinned on purpose so a Bun upgrade would
be noticed. It was: `runtimes (bun)` fails on develop.

The assertion now follows `Bun.version` (1006 before 1.4, 1009 from 1.4), so a
further change in either direction still fails. JSDoc, README and the #107
CHANGELOG entry say which Bun versions do what.

Verified with Bun 1.3.14 and 1.4.4 (26/26 each); lint, format, typecheck,
npm test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-22 23:50:30 -05:00
chrnx 684795a2de test(router): run the parity differential on Deno, Bun and workerd
The matcher comparison does not depend on the runtime, so it should run on every
runtime core supports. Only the Node suite ran it before.

The comparison and the app.fetch fixtures move into differential.ts and
app-fixture.ts, which use neither vitest nor a file API. Each runtime passes in
a loader for the frozen JSON. The vitest files use the same modules, plus a
Node check that the neutral runners report no mismatch, so the two paths cannot
drift.

- Deno and Bun: test/{deno,bun}/router-parity.test.ts run all 1158 frozen
  matcher cases (hand-picked, owner, generated v1 and v2, WS) through the oracle
  and the live router, plus the 55 app.fetch cases.
- workerd: test/edge/parity-worker.ts bundles the frozen JSON and runs the
  same checks; test/edge/run.ts adds the phase after its existing assertions.

The Node-socket, WS-upgrade, boot and mesh captures stay Node-only: they need
http.request, the ws client, or a mesh peer on a port.

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 17:38:36 -05:00
chrnx f78c9dc6fd fix(runtime): give ctx.ip the socket peer on Deno and Bun
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 32s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 15s
buildFetch had no channel for a peer address, so ctx.ip was '' for
every HTTP request served by serveDeno or serveBun unless trustProxy and
x-forwarded-for supplied one. Everything keyed on the address shared one
value: the rate-limit plugin put every client in a single bucket, and
one client could exhaust the limit for all of them.

The adapters now record the peer in a WeakMap keyed by the Request
object (src/http/peer.ts, not exported) and pass that same object to
app.fetch. A header would be visible to handlers and spoofable; a second
fetch parameter would be public API. buildFetch derives ctx.ip as Node's
deriveIp does: the first x-forwarded-for hop when trustProxy is on and
the header is present, the peer otherwise. trustProxy without the header
therefore falls back to the peer instead of answering ''.

The map hangs off globalThis under Symbol.for('@green-tea/core:peer')
rather than living in the module. tsup's CommonJS build bundles index,
deno and bun as separate files with no shared chunk, so each gets its
own copy of peer.ts; with a module-private map, serveBun from
@green-tea/core/bun recorded peers that app.fetch from @green-tea/core
never saw, and ctx.ip stayed ''. A test loads a second instance of the
module to pin this.

A bare app.fetch from user code, or a Request copied from the adapter's,
has no entry and answers exactly what it did before. Addresses are
passed through unnormalised. WebSocket and the edge adapter are
unchanged; trusting cf-connecting-ip is a separate decision.

Closes #116

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-09 13:59:59 -05:00
chrnx ae60cd68a2 fix(http): enforce maxBodyBytes while reading fetch request bodies
The fetch adapter read every body through request.arrayBuffer() and
compared the length afterwards, so Deno, Bun and the edge buffered an
oversized upload in full before refusing it. readFetchBytes now reads
request.body chunk by chunk, stops at the chunk that crosses the limit
and cancels the reader, so no further chunk is pulled.

A content-length that already declares more than the limit is refused
before anything is read, on both adapters. On Node the request used to
wait for its first chunk, which a client that sends only headers never
delivers. A malformed or absent header is ignored and the running count
enforces the limit. The response is the same 413 through onError, and
the route-over-server precedence for maxBodyBytes and maxParts is
untouched; the new tests pin it.

The over-read is proven with a counting stream rather than a status
code, which is the same 413 either way. The stream uses a high-water
mark of 0: the default of 1 pulls a chunk at construction, before any
reader exists, which would make "nothing was read" unprovable.

Socket-level tests on Deno, Bun and workerd use a 1000-byte route limit
so every refused body fits in the socket buffer. With a multi-megabyte
body the client is still writing when the 413 lands and sometimes sees
ECONNRESET instead, which is the transport racing the answer. The Bun
socket test also disables keep-alive: Bun's own fetch client reuses a
socket after a response that arrived before the body was read, and its
next request on it comes back 400 or 431. Node's fetch against the same
Bun server does not.

Closes #105

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-09 13:59:47 -05:00
chrnx 0540bef07b feat(ws)!: bound inbound WebSocket message size and queue
Inbound WebSocket traffic was unbounded per connection: Node used ws's
100 MiB default payload, the other runtimes had no cap of their own, and
the queue behind `inbound` was an unbounded channel on every runtime, so
one client could exhaust memory with large messages or a slow consumer.

Add `limits.maxWsMessageBytes` (default 1 MiB, close 1009) and
`limits.maxWsQueue` (default 16 unread messages, close 1013), as recorded
in D1. Both are server-wide and validated by createApp, which throws a
TypeError for anything but a positive integer. Enforcement is shared in
`boundInbound`, which subscribes immediately and replaces the
subscribe-before-boot trick in app.upgrade. Node and Bun also get the
native pre-buffer cap; Bun drops the connection without a close frame,
so its peer sees 1006, which is documented and tested. Deno and workerd
expose no such option and check the size after receipt.

BREAKING CHANGE: messages over 1 MiB now close the connection with 1009,
and a connection with 16 unread inbound messages is closed with 1013 on
the next one, including a handler that never reads `inbound`.

Closes #107

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-09 13:59:35 -05:00
chrnx 59763c9af5 fix(ws): reject malformed upgrades instead of crashing the server
The Node 'upgrade' listener matched the raw request path without the
normalization HTTP runs. A bad percent escape in a param segment threw
URIError synchronously inside the listener, an uncaught exception that
ends the process, and '//' silently matched a route HTTP refuses.

Upgrades now normalize the path first: malformed escapes and repeated
slashes get a 400, an unknown route a written 404 instead of a bare
destroy, and any other throw in the listener a 500. app.upgrade
(Deno/Bun/edge) closes 1008 'invalid request path' rather than 1011.

On Deno the adapter's socket is still CONNECTING when an early 1008 is
sent, and that close was a no-op that left the peer hanging; eventSocket
now defers such a close to 'open'.

Closes #104

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-09 13:59:35 -05:00
chrnx 53660adcce fix(views): confine static serving to the root's real path
The static resolver's traversal guard compared paths lexically, and the
read that followed it resolved symlinks, so a link inside the root such
as `public/leak -> /etc/hosts` served a file outside it.

Containment now compares real paths. The root's real path is resolved
on the first request and cached (a failed lookup is not, so a root
created after boot still starts serving); the requested file and a
directory's `index.html` are each realpath'd and must lie at or beneath
it, with the `root + sep` rule keeping a sibling such as `root-evil`
out. The lexical guard stays in front, since it rejects `..` without a
syscall.

An escape or a dangling link is a plain miss: 404 through `onError`, or
405/204 where the path has routes. Not 403, so a probe cannot tell a
file outside the root from one that does not exist. Re-pointing a root
symlink at runtime needs a restart. The realpath-to-read race is left
open and marked; closing it needs per-component O_NOFOLLOW, which is
not portable across Node, Deno and Bun.

Closes #106

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-09 13:59:03 -05:00
chrnx 9634ec73e8 feat(runtime)!: serveDeno and serveBun boot before they bind
CI / dco (pull_request) Successful in 6s
CI / build (pull_request) Successful in 30s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 13s
Both were synchronous and left the boot to the first request, with the fix
documented as something the caller should remember: `await app.boot()` before
`Deno.serve` / `Bun.serve`. That made the correct use of a core helper depend
on reading a README, in a framework whose whole argument is that order should
not be something you have to get right.

The failure it leaves is the bad kind. `app.fetch` boots lazily and the boot
memo keeps the *rejection*, so a missing signing key does not fail the deploy:
the port binds, every request is answered 500 by the runtime, and none of them
reach `onError`. Anything that health-checks by asking whether the process is
listening sees a healthy server.

`listen()` has always awaited `bootApp()` before binding its socket, with a
comment saying it exists so Node and Deno/Bun serve an identical graph. They
did not. Now the three helpers agree, and the two adapters return promises.

`edgeHandler` is deliberately unchanged: on workerd there is no startup outside
a request, so there is no earlier moment to move the failure to.

Both new tests were confirmed to fail with the gate commented out — without it
`serveBun` resolves instead of rejecting, and serveDeno binds a port that 500s.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-19 12:38:50 -05:00
chrnx e0da6cee16 test(runtimes): build plugins as named objects on Deno and Bun
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-16 22:27:25 -05:00
chrnx 03132b2048 docs(mesh): steps and routes are what a teapot exports
The CHANGELOG gains an [Unreleased] section — no version heading, no date —
covering the three mesh changes on this branch and why each one follows from
the first: a remote export is a step now, so it holds nothing between requests,
so an absent teapot costs a 503 rather than a boot.

The README says it in the Honest scope section, where the mesh caveats already
live: what can be exported, what happens if you export a provider anyway, and
why a missing token still fails the boot when an unreachable teapot no longer
does.

Two stale bits go with it. The JSDoc over assertNeedsSatisfiable still quoted
the old unconditional message; the Deno and Bun fixtures still said a teapot
exports its scopes. And the degrade plan's D6 planned to reuse a seam this
branch deleted — a dated note says so, and why a degraded step never needed it.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:25 -05:00
chrnx 9f5792c1c5 test(mesh): steps-only exports across Deno, Bun and the edge
Deno and Bun mesh fixtures still exported a @Provider, which now throws
at boot. Convert each to a @Step (provide() -> run(), move the class
from providers: [] to steps: []) so the fixtures build a graph the
current mesh actually allows.

test/edge/_worker.mjs is a gitignored esbuild bundle rebuilt by
test/edge/run.ts on every test:edge run, so no source change was needed
there once the fixtures matched. All four suites pass: vitest (Node),
deno test, bun test, and the workerd/miniflare edge run, plus
typecheck.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-12 15:40:25 -05:00
chrnx 6ffbad9825 fix(mesh): reconnect to a teapot that came back, refusing a manifest that no longer fits
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 24s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 18s
A dropped link stayed dead for the life of the process. Every RPC answered
503 until the teacup restarted, so deploying a teapot forced a restart of
every teacup depending on it and boot order became load-bearing — a worse
operational property than any gap the docs actually listed.

The Link now outlives any single socket, because the graph captured its rpc
closure at boot and a reconnect that produced a new Link would leave the graph
pointing at the dead one. Backoff doubles from 500ms to 30s with full jitter,
so teacups that went down together do not return in lockstep.

A returning teapot whose manifest no longer exports what the graph was
validated against is refused, not adopted: that graph is already serving, and
a token cannot be validated away after the fact. The link keeps retrying,
since a partial deploy may still restore it, and logs once per distinct
manifest rather than once per attempt. Refusal ships as a named policy
(onManifestChange: 'refuse') so hot reconciliation can arrive later as an
addition rather than as a change of what the default means — these are
separate processes on separate deploy cadences.

close() is terminal. closeLinks runs on shutdown, and a link that reconnected
after the application hung up would leave a process that cannot exit.

Also closes the documented gap where an app-scope export outlived its teapot
with a stale value: a successful reconnect re-registers those bindings, so the
next resolve re-runs the RPC. That invalidation is a named function rather
than inline, because it is the seam a future 'reconcile' reuses.

Tested on all three runtimes rather than on Node alone — Node's ws package,
Deno's global WebSocket and Bun's server-level socket handler are three
implementations, and swapping a socket under a live graph is where they stop
agreeing. 7 of the 9 new Node tests were verified to fail against the old
code; the 2 that pass are the ones that should, since the old code never
reconnected at all.

Mesh stays alpha.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-18 10:53:24 -05:00
chrnx 24feca481c feat: shutdown teardown for plugins, providers and applications
Closing a connection meant writing process.on('SIGTERM') by hand: closeApp
drained the server and mesh links and knew nothing about the graph, and the
Bus had no shutdown event at all, so a plugin could not even observe that the
app was going away.

Implements docs/plans/2026-08-17-shutdown-teardown-design.md, D1-D8.

Three doors into one registry, with one order and one failure policy — a
@Provider may declare dispose(), a plugin may call api.onShutdown(fn), and an
application that wants neither passes createApp({ hooks: [{ onShutdown }] }).
Shipping only the plugin half would have frozen the public API around the less
common case: the thing that holds a database connection is a provider.

Callbacks take no arguments. Whatever needs closing is already in the closure
that registered it, so nothing crosses a scope and the registry needs no
container, app reference or transport. That is what keeps this a registry
rather than a second event bus — Bus.on is synchronous and emit swallows
failures on purpose, and a teardown needs the opposite of both.

Provider dispose() is registered as the provider boots rather than as it is
collected, so reverse-registration is reverse-topological order for free: a
cache that needs db closes before the db it is holding, with no second sort to
keep in step. It registers inside the try, so a provider that failed to boot is
never disposed — nothing it might close was ever opened.

Teardown runs after the drain, because an in-flight request may still be using
what a teardown is about to close, and inside the same timeoutMs, because that
number is a promise about when close() returns. teardownTimeoutMs reserves a
slice of that budget rather than extending it, and is rejected at boot rather
than clamped.

Node, Deno and Bun reach it through the close() each runtime actually uses.
app.close() returns at its no-server guard everywhere but Node, so the Deno and
Bun adapters chain it after their own drain — and app.close() now runs teardown
on that path too, since an app served through app.fetch still booted providers
that opened things. The registry drains once, so both entry points are safe.

Edge gets a doc comment and nothing else. workerd has no shutdown to intercept;
a best-effort call on an event that does not exist would be worse than saying so.

Recorded in mountPlugin's comment while widening it: "isolation is structural"
is a guarantee about the registration surface, not about the request context. A
plugin's step already receives the live context and can overwrite keys in it.
Pre-existing, unrelated, and now written where the next reader will look.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-17 11:37:31 -05:00
chrnx 586e14da72 feat(runtimes): a bounded close() on the Deno and Bun adapters
Closes #15, taking the second of the two answers it framed: app.close() stays
Node-only, and each transport that owns a handle offers the same close({
timeoutMs }). app.close() returns at its `if (!server)` guard on Deno and Bun
because they serve through app.fetch and never through listen(), and only the
transport can drain what it accepted. The warning there now names the
replacement instead of pointing at this issue.

The runtimes do not agree, and the code says so rather than averaging them:

Bun escalates. stop(false) drains, stop(true) forces, and the deadline moves
between them like Node's closeAllConnections().

Deno cannot. Its two levers are mutually exclusive — aborting the serve signal
while shutdown() is pending throws BadResource from Deno's own listener,
uncaught and fatal under deno test. Measured on 2.9: abort alone is clean,
abort after shutdown is not. So on Deno the deadline bounds how long close()
waits, not when connections die, and both the type and the timeout warning say
that outright. Silently accepting an option that does less is the failure mode
AGENTS.md rules out.

closeWithDeadline is shared so the two cannot drift into different meanings of
the same timeoutMs, and it resolves on its own timer rather than awaiting the
force call — Bun's stop(true) was measured waiting out a handler with a pending
timer, which is exactly the unbounded wait the deadline exists to prevent.

serveDeno now owns the AbortController it serves with, chaining any caller
signal into it so neither party loses control; a test covers that. The Bun
ambient said stop() returns void, which was simply wrong.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 13:16:24 -05:00
chrnx a74417494f test(mesh): prove mesh across Node, Deno and Bun
Every mesh test ran on Node and drove listen(); nothing off Node was covered, so
the cross-runtime work was implemented but not demonstrated. vitest excludes
test/{deno,bun,edge}, so `npm test` would not have noticed either way.

Adds, in the real runtimes:
- Deno and Bun, teapot and teacup, served through serveDeno/serveBun. Bun is not a
  duplicate of Deno: its socket events land on a server-level handler, so the
  control channel reaches app.upgrade by a different path.
- The interop matrix, in separate processes: a Deno teacup consuming a Node teapot
  and a Node teacup consuming a Deno teapot. Each asserts the `runtime` field the
  *other* process produces, so a peer answering from the wrong side fails the test.
  Node serves and connects with the `ws` package; Deno uses its global WebSocket —
  same-runtime tests could never have exercised that pairing.
- A hand-rolled v999 peer, refused across the boundary with both versions named.

Verified these tests fail for the right reason: breaking the control-channel
routing in app.upgrade fails the Node-teacup-consumes-Deno-teapot case and only
that case.

test:deno needs --allow-run/--allow-env to spawn the Node peer. The peer lives in
test/interop rather than test/deno because tsconfig excludes test/deno, so tsx
would not apply experimentalDecorators there; vitest ignores it as a non-.test.ts.

Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Task 8

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 15:30:43 -05:00
chrnx 4351b41038 test(bun): serveBun HTTP + WebSocket integration
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 21:51:33 -05:00