77d4f32eff44e78ce656df787dde0ad6e4de2407
31
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
a9a4f6c6ef |
fix(ws): wait for the send buffer before pulling the next outbound value (CARD-26, #41)
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> |
||
|
|
8f73779a21 |
fix(mesh): hold the control channel to hello size until the peer authenticates
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> |
||
|
|
e98d5d33eb |
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> |
||
|
|
cad81223e5 |
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> |
||
|
|
713122d53a |
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> |
||
|
|
3296189093 |
feat(http): response compression with gzip and br (CARD-16, #112)
Text responses went out uncompressed unless a proxy sat in front of every
runtime. createApp({ compression: true | { threshold, encodings } }), off
by default, implements D13 strategy B as accepted on 2026-10-22.
- One function, compressOutcome, runs after handle() and before either
adapter writes, so Node and the fetch runtimes cannot diverge.
- Accept-Encoding negotiation with q-values, identity, * and q=0; ties go
to server preference (br before gzip). Vary: Accept-Encoding is merged
wherever the request decided the outcome, including every 304. Skips:
existing Content-Encoding or Content-Range, no or an incompressible
Content-Type (ndjson is compressible), Cache-Control: no-transform.
HEAD and bodies under threshold keep Vary; 204 gets none.
- Node, Deno, Bun: node:zlib only, loaded lazily through nodeRequire.
Buffered bodies use the async API, never the sync one; br at quality 4.
Content-Length is dropped from an encoded body.
- Streams (SSE, ndjson): a zlib stream flushed after every frame, error
frame and ping, piped into res on Node and wrapped around the
ReadableStream on fetch runtimes. Backpressure follows the compressor;
a client leaving destroys it.
- Edge: core never encodes and sets Vary only. Edge is recognised by
edgeHandler, which marks the app through an internal symbol, and by
createApp detecting workerd (navigator.userAgent, or node:zlib failing
to load), which covers a bare app.fetch export.
- ETags from CARD-15 are taken on the identity body and stay weak, so the
tag does not change with the coding.
Deno runs zlib's async API on the main thread; that is documented and
pinned by a test, not worked around.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
|
||
|
|
d32fc9f8d7 |
feat(http): ETag and 304 for static files and buffered responses (CARD-15, #114)
Conditional GETs were never answered: every revalidation re-downloaded
the file or response.
- Static (D12, always on): a hit carries W/"<size>-<mtimeMs base36>",
Last-Modified and Cache-Control from the stat the resolver already did.
A matching If-None-Match, or If-Modified-Since when If-None-Match is
absent, answers 304 before the file is read. StaticHit now carries the
stat and a read() for the bytes, and HEAD no longer reads either.
- static: { dir?, cacheControl? } (rule 1a): Cache-Control defaults to
no-cache so browsers revalidate rather than reuse a file for a lifetime
guessed from Last-Modified. An unknown key or CR/LF throws at boot.
- createApp({ etag: true }) (off by default, boolean only): a buffered 200
to GET/HEAD gets a weak tag from a 32-bit FNV-1a hash of its UTF-8 bytes
plus its length, computed before HEAD blanks the body. A handler-set
etag is kept and only compared. Weak comparison, lists split outside
quotes, and * are supported.
- Every buffered 304 leaves dispatch bodiless, with its content-* headers
dropped, so NotModified matches the ETag path on every adapter.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
|
||
|
|
7f9a0eef0f |
feat(http)!: cookie decorators, setCookie, and string | string[] response headers (CARD-14, #113)
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>
|
||
|
|
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>
|
||
|
|
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> |
||
|
|
f0530b15bb |
feat(http): liveness and readiness probes with a drain window (CARD-17, #115)
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>
|
||
|
|
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> |
||
|
|
56f953f0bb |
feat(graph)!: fail boot when a token has a second producer (CARD-18, GitHub #35)
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>
|
||
|
|
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>
|
||
|
|
f78c9dc6fd |
fix(runtime): give ctx.ip the socket peer on Deno and Bun
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>
|
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
9634ec73e8 |
feat(runtime)!: serveDeno and serveBun boot before they bind
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> |
||
|
|
e0da6cee16 |
test(runtimes): build plugins as named objects on Deno and Bun
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
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> |
||
|
|
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> |
||
|
|
e5d5fb801a |
feat(shutdown): opt into SIGINT/SIGTERM with createApp({ handleSignals })
The README promised shutdown was *"an extension point, not a SIGTERM handler you
write"*. Half of it was true: `dispose()`, `onShutdown` and `hooks` all deliver the
*content* of teardown, but nothing called `close()`, so every application still wrote
the handler — and wrote it three times, because the spelling is per runtime. Forget it
and the container is SIGKILLed after its grace period, every `dispose()` the registry
so carefully ordered never runs, and nothing reports it.
`createApp({ handleSignals: true })` registers SIGINT/SIGTERM to close and exit.
Off by default, and that is the design rather than caution: a library that installs
process-wide handlers behind your back is worse than one that installs none, because
when the process exits is the application's call. Both halves are now supported and
documented — keep the handler, or hand it over. What is not optional either way is
that *something* calls `close()`, and the README now says so instead of implying the
framework already had it covered.
Declared once on `createApp`, wired per runtime by whichever boot call runs:
`listen()`, `serveDeno()` and `serveBun()` each pass the closer that drains *their*
server to `app.handleSignals`, which returns a close that also unregisters. On Deno
that unregistering is load-bearing rather than tidy — a live `Deno.addSignalListener`
holds the process open, so an app that closed itself would otherwise hang.
Unregistering first also means a *second* signal falls through to the platform default
and ends the process at once. That is deliberate: Ctrl-C twice is the way out of a
teardown that is stuck, and swallowing it for the length of a 10s budget would read as
a hang. An orchestrator sends SIGTERM once and then SIGKILL, so it never gets there.
Tested against real processes, because a handler whose job is to exit its own process
cannot be fired by hand in the runner: Node covers SIGTERM, SIGINT, the double-signal
escape hatch and the default-off case; Deno covers `Deno.addSignalListener`/`Deno.exit`,
which is the API that actually differs. Bun shares Node's `process` path.
Closes #70.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
|
||
|
|
4896ee86d2 |
fix(jsr): resolve require from source, not from tsup's banner
JSR publishes `src/` and runs no bundler, so the `createRequire` banner tsup gives
the ESM build (tsup.config.ts) never exists there. Every lazy `require(...)` in the
source had nothing to resolve, and one of them was unguarded: `@Html('file')` and
template mode died at boot on Deno with `ReferenceError: require is not defined`.
The two guarded sites were worse than the crash, because they answered confidently
and wrongly. `static` reported *"needs a filesystem and is unavailable on this
runtime (edge)"* while running on Deno, which has one; multipart reported busboy as
not installed while it sat in node_modules. Both blamed the runtime for a packaging
problem, and both named a runtime the reader was not on.
Route all ten call sites through one `nodeRequire`, which prefers the ambient
`require` — so the CJS build and the banner-carrying ESM build behave exactly as
before — and otherwise rebuilds one from `process.getBuiltinModule('node:module')`.
Node 22.3+, Deno and Bun all expose that synchronously, which is the requirement:
every caller sits on a sync path a dynamic `import()` could not serve. It resolves
from `process.cwd()`, since a peer dependency like busboy belongs to the application,
not to a module served over https from a registry.
Where neither exists — workerd, where esbuild rewrites the call into its own throwing
stub — the behaviour is unchanged: the guarded sites still catch, and their "edge has
no filesystem" story is finally the true one.
Covered by a Deno suite that imports `src/` exactly as JSR serves it. The other Deno
tests already did that; none of them touched a path that loads a Node builtin lazily,
which is how a package that died at boot kept a green suite.
Closes #69.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
|
||
|
|
f2cb411eac |
feat(mesh): carry the caller's identity across the wire, and bound what an unauthenticated peer can do
The observability release gave every request an id and lost it at the process boundary — in the one place a distributed trace is the entire point. The RPC envelope now carries requestId, traceId and url, and the teapot adopts them instead of opening its own investigation. Both fields are optional on the wire, so the protocol version does not move. That decision needed a rule rather than a judgement call, so the rule is now written beside the constant: bump when an old peer would misparse or misbehave silently, not when work happened. Bumping per change would make the number mean the opposite of what it is for. Three things found while in here: - mesh:rpc:error emitted the per-link counter where every other emitter puts a name, so the two sides of one failure could not be matched up. - The teapot had no handshake deadline, so an unauthenticated peer could hold a socket by saying nothing, and no frame size cap, so it could make the process JSON.parse up to whatever the socket layer allowed — 100 MiB with the ws defaults, before authenticating. - The remote-route envelope was cast from the internal request object, putting ip and protocol on the wire as fields the protocol never declared. The cleartext warning is a warning and not a refusal on purpose: a private network already doing mutual TLS is legitimate, and green-tea cannot tell it apart from an exposed one. 4 of the 8 new tests verified to fail against the old code; the rest are the negative cases, which should pass both before and after. The Deno test drives the teapot's frame loop with a raw client, because server-side close codes are where these runtimes have already differed once. 431 vitest / 12 Deno / 7 Bun / edge / JSR dry run. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
6ffbad9825 |
fix(mesh): reconnect to a teapot that came back, refusing a manifest that no longer fits
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> |
||
|
|
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>
|
||
|
|
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> |
||
|
|
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>
|
||
|
|
f85b39c2c3 |
test(deno): serveDeno HTTP + WebSocket integration
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |