77d4f32eff44e78ce656df787dde0ad6e4de2407
67
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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> |
||
|
|
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> |
||
|
|
88cbe41f72 |
feat(edge)!: trust cf-connecting-ip only under trustProxy, for HTTP and WebSocket (CARD-23, #119)
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> |
||
|
|
63f60134ea |
feat(router)!: fail boot on unreachable or ambiguous constrained params
Before, when two sibling routes could match the same request, the router
picked one by registration order or precedence, and nothing reported it.
Boot now refuses two cases between routes of the same method that branch at
the same segment under the same prefix:
- ambiguous: both params are constrained, the constraints accept a common
segment, and the rest of both patterns can match one request. The error
names both declarations and a witness segment with an example path.
- unreachable: a plain param sits next to a constraint that accepts every
segment, and the constraint wins every request the plain param could take.
A plain param next to a constraint that leaves some segments over is the
documented fallback pattern and still boots.
The check is exact. assertSafeConstraint admits only a linear, group-free
subset, so every constraint reads back as a sequence of (character set, min,
max) blocks. Atom sets follow u-flag semantics. \p{...} is the one construct
that is not modelled, and for it the engine is asked once per code point. A
product walk over two block sequences finds a common segment, or proves none
exists, in O(|A|*|B|*(|A|+|B|)*K) with K <= 2048. "Accepts every segment" is
a closed-form test on the blocks. Both are measured against what the router
hands a param: a decoded, non-empty segment that is never "." or "..".
The check runs per table under that table's own precedence. HTTP ranks by
specificity. WebSocket takes the first declared match. @Stream routes sit in
both tables. Routes exported by different teapots are checked against each
other. Local against remote keeps the local override and its warning.
The lookup path is unchanged. router.ts only exports the two token regexes,
so the boot check and assertSafeConstraint read atoms the same way.
BREAKING CHANGE: an app that declares two overlapping constrained siblings
(e.g. /u/:id(\d+) and /u/:n(\d{1,3})), or a plain param beside a constraint
that accepts every segment, now fails createApp. So do a plain WebSocket param
declared before a constrained sibling, and such pairs across mesh teapots.
Refs: #127
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
|
||
|
|
815f76116f |
perf(router): index HTTP routes in a radix tree
Replace the linear, specificity-sorted scan behind matchRoute, resolveRoute and allowedMethods with a segment trie per HTTP method, built once per route array from the compiled segments compilePattern already produces. Ranking stays global: every terminal carries its position in the old sorted bucket (moreSpecific, declaration order on ties), and the walk keeps the lowest rank it can reach, pruning subtrees that cannot beat it. The tree decides which routes can match; the rank alone decides which one does. A static branch that dead-ends deeper backtracks into its param, constrained and catch-all siblings. All-static routes are also kept by exact path per method. A hit there is provably the tree's best match, so a static request is answered without splitting the path; a miss falls through to the walk. Mesh-spliced remote routes go in a second tree, per the owner's design decision. Both trees answer, the more specific match wins and an equal one goes to the earlier declaration, so local still beats remote on a tie. Allow, 405 and implicit HEAD run over the union. An app without remote routes does one lookup. allowedMethods walks the index instead of recompiling every route on a miss, and an implicit HEAD no longer builds a fresh index from a filtered array on every request. The frozen parity corpus passes unchanged. The frozen mutant script cannot run against the new layout by design, so test/router-index-mutants.ts re-targets its twelve bug classes at the new code and runs the same untouched suite. Refs #109 Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
bd478ce09c |
build!: require Node 22
Node 18 and Node 20 are end-of-life and receive no security patches, so supporting them before RC.1 would mean promising a runtime nobody can patch. Node 22 is the oldest line still maintained. engines.node moves to >=22, @types/node to ^22, the tsup target to node22, and CI's build job from Node 18 to 22, so every workflow now runs Node 22 only. The docs, the bug report example and the comments that stated 18 as the floor follow. The node:crypto fallback in the HTTP core existed only for Node 18, which lacked the global crypto; it goes with its regression test, which said as much. The ws fallback for the WebSocket client stays: Node 22 has the global, but it can still be switched off with a flag. Moving off Node 18 and 20 also unblocks vitest 4, which the remaining dev audit advisories need. BREAKING CHANGE: Node 18 and Node 20 are no longer supported. The minimum is Node 22. 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> |
||
|
|
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> |
||
|
|
3fc761ce16 |
feat(app): expose boot() so providers can fail before serving
Only listen() booted before accepting traffic. Deno, Bun and edge all boot on the first request, and the memo keeps the rejection, so a bad key answered 500 for the life of the process while the app looked healthy. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
80f3f532f2 |
feat(plugin)!: a plugin is a named object, not a function
BREAKING CHANGE: `Plugin` is now `{ name, mount(api) }`. `fn.name` was the only
source for the name that plugin:mounted reports, and it is empty for a returned
arrow, "plugin" for a const, and whatever a minifier decides. A failed mount now
names the plugin and keeps the original error as its cause, and two plugins with
the same name fail createApp.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
|
||
|
|
249fc00f80 |
fix(mesh): name the teapot in the boot log a later 404 points back to
A route the absent teapot would have exported 404s, and that is the right status: nothing was ever registered for a manifest that never arrived, so there is no path to serve. But a bare 404 is indistinguishable from a typo in the path, and the boot log is the only place the two are told apart. It could not tell them apart either. The give-up warning relied on the error's own message to identify the teapot, which holds for a refusal -- `mesh handshake failed: <url>` -- but not for an unreachable one, where the error is a socket error that may carry no url at all. So the url is passed in now, and every line of the boot-connect story names it: the retries, the refusal, and the give-up. The give-up line also says no manifest was ever exchanged, which is the fact that explains the 404. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
e69f604053 |
docs(mesh): record the scopes->steps rename as an exception to the bump rule
The bump rule in protocol.ts says renaming a field earns a protocol bump, and this branch renamed the manifest's `scopes` to `steps` at v1 without one. The argument for that lived only in the CHANGELOG, so the rule as written read as simply broken to anyone who found it from the code. The exception is now stated where the rule is, with the three conditions it rests on: mesh is alpha, every app using it is gated behind `experimental: true`, and both peers ship out of this repo, so no deployed pair can be split across the rename. It retires with the first mesh release that drops `experimental`. Two other stale pointers go with it. The bootTimeoutMs JSDoc said `0` restores "the old behaviour of a single attempt", which now reads as restoring a boot that failed — it is only the attempt count, and the way to make a teapot's absence fatal is a local `@needs` on one of its tokens. And the reconnect plan's step 4 still pointed at invalidateRemoteBindings, which this branch deleted; it gets a dated note in the same shape as the degrade plan's D6. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
727987286b |
refactor(graph): the missing-dependency note is a string, not a callback
topoSort, finalizeGraph, assertNeedsSatisfiable and finalize all threaded a `(key: string) => string`, and no caller ever read `key` — the one producer, in prepareGraph, is `() => ...`. The note names which teapots did not connect, which does not vary by token, so the parameter was machinery for a customization nothing asked for. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
f5d4d0cd74 |
docs(mesh): an absent teapot 404s, it does not 503
A teapot that never connected sent no manifest, so spliceRemoteScopes registers nothing for it — no step runner, no route. Its routes therefore take the ordinary unmatched path and 404, and a local node that needs one of its tokens still fails the boot naming it. The 503 belongs to a teapot that connected and later died, where the link and its exports exist and the dead-link guard answers. The previous commit said 503 for the absent case in five places, including the warning an operator reads during a deploy. All five now tell the same story, and the bootTimeoutMs JSDoc — stale in the other direction, still claiming an absent teapot fails the boot — with them. The connectUntilDeadline JSDoc also had a paragraph saying it still throws, contradicted three paragraphs later; that one is gone. No behaviour changed. Serving 503 for an absent teapot's tokens means knowing what it would have exported, which is the expects list in the degrade plan and is deliberately not built. 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> |
||
|
|
4e8aacb6b7 |
fix(mesh): name the absent teapot in the route-level missing-need error too
assertNeedsSatisfiable is a separate check from topoSort, so it didn't get the note threaded into finalizeGraph -- a handler-level @needs against an absent teapot's token read as a typo or a forgotten export: true, which is worse than the pre-task behavior (the boot used to throw naming the teapot). Thread missingNote through and soften "local or mesh" to "local or connected mesh" when it's set, so the message doesn't claim a search that never happened. Also tightens two test assertions that only passed because "mesh" happened to appear inside the unrelated "(local or mesh)" wording, and removes adopt()'s now-fully-unused attempt parameter in mesh/link.ts instead of leaving it underscored. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
3b680480ab |
feat(mesh): an unreachable teapot no longer stops the teacup from booting
Blocking existed for app-scope exports, which have to resolve at boot because there is no later. Steps and proxied routes are all later. The grace budget stays -- a co-deploy still waits -- but exhausting it now warns instead of throwing. A missing token still fails the boot, and the error now names the teapots that were away. Also drops connectLink's onReconnect hook and the reconnected flag that fed it: its only caller was removed by an earlier commit on this branch, and it is not part of the public API (not re-exported, not documented). Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
6e66b05a41 |
refactor(mesh): drop the remote app-scope binding and its rebind seam
A remote provider was registered app-scope, resolved once, and cached for the process lifetime; invalidateRemoteBindings existed only to un-cache it on reconnect. With providers gone from the manifest, both go, and a remote step needs nothing on reconnect because it holds nothing between requests. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
55890442fe |
refactor(mesh)!: a manifest carries step names, not scoped tokens
Every exported token is request-scope now, so the lifetime field had one value and told a reader nothing. No protocol bump: mesh is alpha, both peers ship from this repo, and the number should mean incompatibility between deployed versions. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
f6c05a0929 |
feat(mesh)!: refuse to export a provider
A provider's value is the object it builds, which cannot cross a JSON wire. What did cross became an app-scope binding the teacup resolved once at boot and served from a cache the teapot no longer stood behind. A step is the shape that travels; the error says so. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
ccd329d12b |
perf(boot): run independent providers concurrently
`bootProviders` was a `for...of` with an `await` inside, so three providers that share nothing took the sum of their latencies rather than the longest one. Measured on the issue's case — three providers, no edges, 200ms each — 616ms before, 210ms after. The graph already knew. `topoSort` proves which nodes cannot constrain each other and then throws that away by returning a flat list; `topoLevels` groups the sorted list back into dependency levels in one forward pass, and boot runs a level with `Promise.all`. Nothing else about the ordering changes: level N is fully registered and warmed before level N+1 starts, which is the same guarantee the sequential walk gave. This is the second thing users get for declaring `needs`/`provides` instead of ordering `app.use` calls by hand. Pruning was the first. An Express app cannot parallelize its middleware because nothing declares what is independent — we have that declaration and were not spending it. Three things had to survive the change, and each has a test: - **Teardown stays deterministic.** Registration follows level order, not completion order, so the registry running in reverse still gives dependants teardown before their dependencies. Following whichever provider settled first would have turned that from a guarantee into luck. - **A failed sibling does not strand the level.** `bootProvider` returns an outcome instead of rejecting, and successful teardowns are registered before any failure is raised — so a boot aborted by a required provider still leaves whatever its siblings opened closeable. Previously they had not started at all; now they may be in flight. - **A provider that threw gets no teardown**, unchanged: it never provided anything, and `dispose()` on a half-constructed one is how a teardown finds a null connection. Behaviour visible to a bus consumer: `boot:provider:start` no longer strictly alternates with `:ok`. A level emits its starts together, then its results. That is the truth about what is happening rather than a change in what is reported. Verified non-vacuous: reverting `src/` fails the overlap assertion and all five `topoLevels` cases, and puts the benchmark back at 616ms. Closes #71 Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
1e76921d49 |
feat(di): a read-only events token, and framework names nobody can take
Three things that turned out to be one decision.
## `@needs('events')`
`app.bus` is public and `Bus` is an exported type, but the bus was not a graph token, so
`@needs('bus')` failed at boot. There is a good reason for the difference — putting the
`Bus` in the graph hands `emit` to every node and turns a one-way observation channel into
something anything can forge events on — and it was written down nowhere, inferable only
by reading `provideBuiltins` and noticing what is absent.
The read-only half is a token now: `events`, bound to `{ on }`, the same narrowing plugins
already get. `@needs('events')` works the way `@needs('logger')` does, which is the
symmetry a reader expects, and `emit` still belongs to nobody.
A plugin remains the right home for observation and the docs say so, because it gets
`on` and `onShutdown` *together*. The token gives the subscribe half alone: a `@Provider`
that subscribes should release in `dispose()` — `on()` returns its own unsubscribe — and a
`@Step` should not subscribe at all, since it runs per request and would add a listener
each time.
## The boot error teaches it
Documenting it prevents the mistake for a reader; it does nothing for the person typing
`@needs('bus')`, which is who the issue was about. That need now fails with what it should
have used and why, rather than the generic "nothing provides it" plus a nearest-match that
has nothing near enough to suggest.
## Framework names are reserved
**Behaviour change.** Builtins were registered with `if (!runners.has(name))`, so a
provider called `logger` silently replaced the framework's own and every `@needs('logger')`
in the app got something that was not the logger core writes to — a divergence you
discover from a log line that never appeared. `logger`, `rooms`, `events` and `bus` are
reserved now, enforced in `setRunner`, which is the single point modules, plugins and mesh
exports all register through. Taking one is a boot error naming it.
`bus` is reserved without being provided, so `@needs('bus')` cannot resolve to whatever a
user happened to call `bus` and be wrong in silence.
This replaces a test that asserted the old shadowing as a feature.
Closes #67.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
|
||
|
|
5294e62a5a |
fix(errors): an onError that throws degrades to the built-in renderer
`createApp({ onError })` is the advertised way to render errors, it runs on the request
path, and it ran with no boundary around it. A renderer that threw did not produce a 500
— it took the process with it, exit code 1.
This is #72 in a different callback, and easier to reach: not a cross-origin request, but
*any* request that produces an error. The stack from the reproduction goes through
`unmatchedOutcome`, so the renderer produces the 404 too — an app with a custom renderer
and no matching route was one request away from exiting.
It is also the worst-timed crash there was. The renderer only runs once something has
already gone wrong, so the failure mode read: an error occurs, the code written to report
it fails, and instead of a degraded report the server ends.
All six call sites funnel through `renderError`, so the guard goes there once. A renderer
that throws falls back to `errorToResponse` — the built-in rendering, which is exactly
what the option overrides and therefore the honest thing to fall back to. The original
error still gets its response; that is the whole point. The renderer's own failure is
logged separately and names both errors, because they are different errors and a reader
chasing the wrong one loses an afternoon.
Verified against the built `dist/` with the issue's own reproduction: `404`, process
alive, one error line naming the renderer.
`viewEngine` was checked in the same pass, since it is the other user callback on a render
path and its having a boundary was not something to assume. It has one — the pipeline's
catch covers it, so a broken engine is a 500. Asserted now rather than left to inference.
Amends the `request:failed` test added a commit ago, which asserted the crashing behaviour
as its baseline: a throwing renderer now yields the fallback's status rather than none.
The `finally` that carries the emission stays, demoted from first line of defence to
second — a failure whose reporting is what broke is the worst one to lose.
Closes #80.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
|
||
|
|
855e044d2a |
fix(types): export the extension-point types, not just the extension points
`Transformer` was exported and `TransformerFn` was not, so a custom transformer could
be attached but not typed. The workaround is to borrow the type off a value —
`const text: typeof JsonTransformer = ...` — which works and reads like a trick,
because it is one. `ErrorRenderer` and `StreamEncoder`, the two neighbouring extension
points, were both already exported; this one was an oversight rather than a decision.
Checking the rest of the barrel for the same shape turned up four more. A plugin split
into named functions rather than one inline arrow cannot annotate what it receives:
`Plugin` types the arrow, and `PluginApi`, `ScopeApi` and `ScopeNode` — the chain
reached through `api.scope.add`, which is how a plugin contributes to the graph — were
all unreachable. So was `Hooks`, which makes `createApp({ hooks })` typeable only
inline, and `TeardownFn`, the shape every one of those three doors takes.
Types only. Nothing at runtime moves, and no existing export changes.
Covered by a type test that fails to compile if any of them leaves the barrel again,
including the two that were already there — the failure mode this fixes is a barrel
edit nobody notices until a user writes the annotation.
Closes #66.
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>
|
||
|
|
82e1678dea |
fix: warn when connection limit drops a socket
Signed-off-by: hgshreyas <hgshreyas.cs24@bmsce.ac.in> |
||
|
|
1975a7c03f |
feat(mesh): give boot a grace period for a slow teapot, and fail for an absent one
A teapot that is thirty seconds behind and a teapot that does not exist look identical for the first thirty seconds, and only one of them should stop a deploy. bootTimeoutMs is that grace: retries with backoff until it passes. It still fails after that, deliberately. A provider the graph depends on is not optional, and booting without it would only move the failure to the first request, where it is a caller's 503 rather than the deploy's error. The full battery caught what the first cut got wrong: a bad secret was being retried. That is not a transient failure — it is the teapot's decision, and it will be the same decision in thirty seconds, so retrying only spends the deploy's patience to arrive at the identical error. Refusals now fail at once. Telling them apart without threading close codes through the neutral socket contract of four runtimes: a peer that accepted the connection and then hung up before answering rejected us on purpose; one that never accepted it may simply not be listening yet. That is exactly the distinction needed here. Retries are logged and emitted as mesh:boot:retry, kept separate from mesh:disconnect — that one 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. 437 vitest / 12 Deno / 7 Bun / edge / JSR dry run. 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> |
||
|
|
198e62944f |
fix(shutdown): arm the teardown timer before the callback that clears it
`runTeardown` declared `finish` above the `timer` it clears, so the reference held only because every caller — the timer's own callback and `teardown.run().then()` — happens to be asynchronous. That is correct by timing rather than by construction, which is what #20 asked to remove from this file; `closeApp` twenty lines below already arms its timer first and carries a comment explaining why that direction is the safe one. Reversing the order here leaves both shutdown paths resting the same forward reference on the same guarantee: setTimeout cannot invoke its callback synchronously. No behaviour changes. Closes #20 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>
|
||
|
|
e052d5ba8f |
feat(observability): request-level events, and request logging that reads them
Tasks 5 and 6, in that order rather than the plan's: request logging is a
subscriber, so the events it subscribes to had to exist first.
handle() now emits request:start, request:end, route:matched and
route:unmatched. request:end fires when the handler returns, not when a stream
it produced finishes — a streaming route is done here in milliseconds while its
connection may live for hours, and ending the span at close would put hour-long
SSE connections and 2ms buffered replies in one latency distribution. The
stream events already describe the connection and now share the requestId.
route:unmatched covers 404 and 405 both. Naming it after one outcome, as the
report's route.not_found does, would misreport the other.
logRequests(bus, logger) is the consumer: info per completed request, error per
failed one, and it returns an unsubscribe so it is removable rather than merely
optional. createApp({ logRequests: true }) turns it on and is off by default,
because a framework that writes to stdout uninvited is one you have to
configure before you can use it. withConsoleFallback wraps it, since Bus.emit
isolates listener failures by design and a user logger that throws would
otherwise stop writing with nothing to say so. A test proves both halves: the
request still succeeds, and the failure still surfaces.
The bus reaches handle() through HttpOptions so the Node and Fetch adapters
share one channel instead of growing separate ones.
Cost, measured: nothing. First attempt wrapped dispatch in a second async frame
and that alone cost 0.43us per request — a promise and two microtask ticks,
an order of magnitude more than the four Map lookups it was there to arrange.
handle() is no longer async and hands back dispatch's own promise when nothing
subscribes; 4.716-4.791us against 4.736-4.793 before, which is the same number.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
|
||
|
|
df460f01dd |
feat(observability): an injectable logger, and a lint rule that keeps core off console
Task 4. createApp({ logger }) accepts any Logger; the default writes structured
JSON, or a readable line on a TTY, decided once at construction rather than per
record. It writes through console, which is what lets core have a logging
contract while reflect-metadata stays the only runtime dependency.
Four levels, because four have callers. Core's diagnostics were all warn — every
one of the eight console.warn calls — and request logging adds info and error.
No trace, no fatal: a level nothing emits is a decision handed to the user for
no reason.
Registered rather than declared as a provider. Provider boot failures are
reported while the graph is still resolving and shutdown warnings after it is
gone, so a logger that lives in the graph cannot cover either end. It is also
registered as a builtin provider, so @needs('logger') reaches the same object —
one instance, two access paths — and exposed on App so serveDeno/serveBun report
through the application's logger instead of past it.
The [green-tea] prefix moves out of the prose into a `name` field: an aggregator
filters on a field and cannot filter on a substring of a sentence. Context that
was interpolated into messages is now structured alongside them.
#10 asks that nothing in core call console directly. That is now a lint rule
scoped to src/ rather than a grep somebody has to remember, with src/logger.ts
exempted because being the console sink is its entire job. Verified it fails on
a planted console.log.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
|
||
|
|
2c47ee8896 |
feat(observability): correlate and time the lifecycle event stream
Tasks 1-3 of the observability plan. The Bus already had 19 emission points; what it lacked was any way to tell which request an event belonged to, which made the whole stream unusable under concurrency. Every per-request event now carries requestId, traceId, route, method and transport, and request:step:leave carries durationMs — a field that has been declared in EventPayload since the beginning with nothing ever writing it. Identity is derived in the adapters rather than in handle(), because both read and size-check the body first: a 413 is answered without handle() ever seeing the request, so generating there would leave exactly the failures an operator most wants to correlate with nothing to correlate them by. An incoming x-request-id is adopted rather than replaced, and traceparent is carried verbatim — core implements no propagation spec. Timing takes N+1 readings for N steps, since one step's end is the next one's start. Measured at 25.2ns per step against a ~10.19us request. request:step:error now names the step that actually failed. It reported name: 'pipeline' before, discarding the one fact it exists to carry, because it was emitted from the outer catch where that is all that is known. The outer catch emits request:failed instead: one marks the span, the other the trace. route carries the matched pattern and never the concrete path. Labelling a metric on raw URLs gives unbounded cardinality and takes down the metrics backend rather than the app, so it is a contract, with a test. 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> |
||
|
|
085eb9a67d |
fix(app): arm the shutdown timer before finish(), and make the deadline an app option
Closes #20. finish() called clearTimeout(timer) from above the timer's own declaration. It worked because server.close(cb) always defers, so the assignment won the race — correct by timing, and a ReferenceError waiting in the shutdown path for whoever added a synchronous call site. The issue proposed hoisting a `let timer`, but prefer-const rejects that and is right to. Swapping the two blocks fixes it without a suppression and lands somewhere better: the surviving forward reference is the timer callback reaching finish(), and setTimeout not firing synchronously is the event loop rather than a library's current behaviour. Closes #19. The 10s deadline is now settable via createApp({ shutdownTimeoutMs }), with the per-call close({ timeoutMs }) still winning. close() is usually reached from a signal handler, a test helper or a shutdown hook you do not own, where passing it per call is not available. Nothing changes for anyone passing neither. The precedence test uses a 30s app-level default, so it can only pass if the per-call value took priority. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
3dcf784159 |
fix: add timeout to app.close()
Signed-off-by: YxnnXriel <yannariel13@gmail.com> |
||
|
|
63be0ef8f7 |
feat(router): expose HEAD and OPTIONS decorators
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
8e38fffd77 |
fix(router): reject invalid and ambiguous paths
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
642ef109b2 |
feat(app): warn at boot when a route's dependency chain is unusually deep
A route whose need-closure resolves to more than 20 steps is almost always a modeling smell -- a step doing too much, or work that belongs in a provider. Per-request cost is linear, so this is a design nudge, not a perf guard (and a warning, not an error).
Tunable and silenceable via createApp({ warnGraphDepth }): a number sets the threshold, false quiets it. Default 20.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
|
||
|
|
dba40b0c8b |
feat(mesh): heartbeat the link, and tell the truth when a teapot is gone
Three bugs, found by writing the tests for the status codes. A teapot with a live control channel could never shut down. Control connections were never registered with the stream registry, so server.close() sat waiting on a connected teacup that had no reason to hang up, and app.close() never resolved. Every other long-lived socket was already tracked; the control channel was the one that skipped it. A downed teapot answered 500 — after 30 seconds. sendRpc queued the frame on a closed socket and waited out the full timeout for a verdict already known. It now rejects immediately with 503: 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. An RPC that times out on a *live* link is 504 — a slow teapot and a gone one are different stories. Heartbeat: each teacup pings its teapots (`mesh.heartbeatMs`, default 15s) and closes a link after two unanswered rounds. This is what catches a half-open connection, where the socket looks open with nobody home — otherwise a teacup only learns on the next request. Ping/pong are mesh frames rather than WebSocket protocol pings because Deno's and Bun's platform WebSocket does not expose ws.ping(), so a protocol-level heartbeat could not work everywhere mesh runs. Added to v1 while the wire still has no deployed peers; later it would be a version bump that refuses every old peer. The heartbeat's first close code was 1011, which silently did nothing: a *client* may only send 1000 or 3000-4999, so it threw `invalid code` — and our neutral close swallows throws, so the link stayed open while looking closed. 4011 mirrors 1011's meaning inside the application range. Reconnect (and reconciling app-scope values, which survive their teapot from cache) stays out — it is a post-beta spec of its own. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
9886e53747 |
feat(app): add app.ready() so introspection works on any app
inspect()/graph()/explain() are synchronous, but a mesh graph is not knowable
until its teapots have been asked, so on a mesh app they threw and the caller had
no way to fix it. Code holding an `App` could not tell which kind it had — the
Liskov complaint from the audit, and the last of it: fetch/upgrade stopped
throwing when the boot moved into the gate.
app.ready() resolves the graph and returns. On a mesh app it connects the
teapots; on every other app it is a no-op. So one shape works for both:
await app.ready();
app.graph();
which is what actually restores substitutability — a uniform protocol, not a type
that describes the asymmetry.
Deliberately not a full boot: it does not run provider factories. Resolving the
graph and being ready to serve are different things, and a devtool drawing a
diagram should not open your database connections. Serving boots them too and
shares the same memoized step, so ready() then fetch() resolves the graph once.
The guards stay — sync code cannot await network I/O — but the message names the
fix instead of describing the trap.
createApp hit 26 on the complexity gate with ready() added. Both boot stages had
their own copy of the same memoisation, so it collapses into one `once` helper
used by both, which is a smaller createApp than before this change.
Refs .specs/2026-07-15-green-tea-solid-audit (App/Mesh LSP)
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
|