The recipe closing #13 lives in the documentation repository, which imports
nothing from here — so nothing fails when the page and the framework drift
apart. That is the seam Phase 4 opened, and a worked example that quietly
stops working is the worst version of it: it is the page a reader trusts most,
because it looks like code that ran.
This executes the three claims the page rests on rather than asserting them in
prose. That breaker state survives across requests, which is the entire reason
the recipe uses a provider and not a step. That the window re-opens after it
elapses. And that a failed trial in half-open re-opens immediately instead of
making a recovering upstream earn the full threshold again.
Beyond the file list Phase 5 asked for, which named only the guide page. Kept
because it is small and it turns Task 4.4's written rule into something that
fails, for one page at least.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
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>
Both adapters routed every request themselves, and then handle() routed it
again from the same inputs — a four-route app walked its table 2.5 times
per request. Neither side was wrong: an adapter must know the route to
decide whether to read a body, and the core must know it to dispatch.
The cause was the shape of the handoff. NeutralRequest carried an
already-parsed body, so producing one was the adapter's problem, and every
policy that depends on the matched route came with it — these four chains
were written out in server.ts and web.ts character for character:
matched.def.maxBodyBytes ?? opts?.limits?.maxBodyBytes ?? 1_000_000
matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last'
matched.def.maxParts ?? opts?.limits?.maxParts ?? 1000
opts?.limits?.maxBodyBytes ?? 1_000_000
A fifth knob, or one changed default, meant editing both or letting the
runtimes quietly disagree about limits.
Handing over the ability to read rather than the result moves the decision
to where the route is already known. What stays in an adapter is what
genuinely differs between runtimes: getting bytes in, putting bytes out.
Enforcement stays with the reader too, because Node aborts an oversized
upload as chunks arrive while a fetch runtime can only measure what
arrayBuffer() already resolved — passing the limit in preserves that.
413/400/501 keep their exact current shape, Node's connection: close
included; it now has the test it never had.
Measured through app.fetch, both versions in one process, interleaved:
40 routes with the match declared last, 3.89 -> 3.58 us (-8.2%). One
route, where there is no second scan to save, is unchanged.
The first cut of this was 13% SLOWER, and the reason is worth recording:
a per-request closure for the reader plus the error-context object it
captured cost 250 ns, and the async frames around a body that did not
exist cost another 215 ns — together more than the duplicate scan the
whole change removes. The reader is now built once per server and takes
the runtime's request as an argument, and a bodiless request touches no
promise on this path at all.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
The same bytes on the wire reached different routes depending on where
the app ran. `GET /public/../admin` hit a `/admin` route under Deno, Bun
and workerd, and 404'd under Node — 200 vs 404 for one request.
The fetch-based runtimes resolve dot segments inside the `Request`
constructor, before green-tea is handed anything: `new Request(
'http://x/public/../admin').url` is already `http://x/admin`. Node's raw
target has no such step. Rejecting outright — the stricter policy, and
what this module already does for `//` — is not implementable on three of
the four runtimes, because the raw target is unrecoverable there. So Node
converges on the rule the other three cannot opt out of.
`%2e` is a dot to the URL parser, so the encoded spelling resolves too;
leaving it out would keep it as a way to reach a route the plain spelling
resolves away from.
Cost is gated: paths with no `.` and no `%` pay two indexOf scans
(20.0 -> 21.7 ns for `/hello`), a literal dot pays the regex (35.5 ns),
and only real dot segments pay the split (103.6 ns).
The existing parity suite could not have caught this — its `both()`
helper goes through `fetch()`, which normalizes the URL before it reaches
the wire. The new cases write the request line to a socket by hand.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
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>
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>
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>
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>
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>
npm and JSR publish from the same tag but read their identity from different
files. Bump package.json alone and that tag ships one version to npm and the
previous one to JSR, with nothing failing — the drift the deno.json manifest
introduced, closed where the other publication-metadata pins already live.
Also pins the entry points to npm's, so a docs example importing
@green-tea/core/bun keeps working whichever registry the reader installed from.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
A Node Buffer is a Uint8Array at runtime, but its declared backing store is
ArrayBufferLike, which admits SharedArrayBuffer — and BodyInit takes only
ArrayBuffer-backed views. Deno's lib rejected it outright at web.ts:112. This
is the app.fetch path, so the hole was on Deno, Bun and edge alike; it went
unnoticed because every implementation is forgiving about it at runtime.
Re-views rather than copies: this is the buffered-response path, and a copy
per response would cost real throughput on the runtimes that have no other
adapter. byteOffset and byteLength are load-bearing there — Buffer.from hands
back a window into a shared 8 KB pool, and dropping them returns the whole
pool. A direct test covers that; the static-serving one covers the integration.
The type is derived from Response's own constructor because BodyInit is not a
global under lib es2020 plus @types/node, though Response itself is.
Refs: Green-Tea/core#19
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
The test landed one line below the closing brace of describe('graceful
shutdown'), so it ran at the top level instead of under the block it
belongs to. Placement only; the assertions are untouched.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
author had no email and bugs had no address, so the only contact npm could show for a
published package was a GitHub issues URL. bugs.email is a field npm actually reads and
npm bugs surfaces, which makes it the right home for the catch-all.
No security address here on purpose: npm has no field for one, an invented key is read by
nothing, and the standard location is /.well-known/security.txt on the domain root, which
this repo does not serve.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
Replace an existing prerelease before publishing the refreshed candidate. Verdaccio remains mutable for validation while npmjs release versions stay immutable.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
Stage only release branches and preserve immutable versions. Repeated identical candidates now exit successfully, while content changes under an existing version require a prerelease bump.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
Link the package to its public source, issue tracker, and documentation so npm Trusted Publishing can validate provenance and consumers receive canonical project links.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
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>
runSteps rebuilt the whole request context every step with { ...context, ...output }, so an N-step route paid 1+2+...+N = O(N^2) property copies plus N throwaway objects. At 100 chained steps that measured ~250us/req vs ~100us after the fix (2.5x throughput); per-step cost drops from superlinear to a flat ~0.5us/step.
Mutate one accumulator in place with Object.assign -- O(N). The returned context is now the same object every step observes. Adds a regression guard that fails if a per-step copy is reintroduced; full suite green (322 tests).
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
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>
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>
Local routes are merged ahead of remote ones, so a local twin wins. That
precedence is worth keeping — your own code beating an imported one is how you
override a teapot — but it was an accident of [...local, ...remote] ordering with
nothing said, so a shadowed export looked like a broken teapot from the outside.
Warn, name the teapot, and leave the call to the developer.
The docs had gone stale in the way that started all of this. runtimes.md claimed
four times that mesh is Node-only; the mesh guide said finalization is deferred to
listen(); the changelog said "WebSocket and mesh remain Node-only". All false now.
The mesh guide gains what was enforced but never written down — which is how the
listen() trap got made in the first place, when the previous plan's "document it"
never landed:
- runs on Node/Deno/Bun, teapot and teacup, any combination; not on edge, and why
- no listen() required: the graph boots on first use
- buffered routes only, and why streams cannot cross an RPC hop
- one teapot per route, local-over-remote precedence, and the protocol version
Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Task 9
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
Duplicate scope tokens already threw in setRunner, but duplicate routes did not:
both were pushed into remoteRoutes, and matchRoute keeps the first of two
identical patterns (moreSpecific returns 0, not > 0). The second teapot's route
was silently dead. Same collision, two behaviours — one loud, one mute.
Fail the boot instead, naming the route and both teapots, since which pair
clashed is the thing an operator needs. The message says load balancing is not
implemented *yet*: it is a not-yet, not an impossibility.
Throwing now also keeps the door open. "First teapot wins" is a semantic callers
could come to rely on, so shipping it would make balancing a breaking change
later. An error cannot be relied on — turning it into a strategy stays additive.
Scopes keep failing rather than balancing, and should: an app-scope provider is
memoised, so "balancing" a cached value means nothing.
Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
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>
Two halves of the same "mesh off Node" gap; they touch the same file and landed
together.
Control channel (Task 6): meshControl existed only inside listen(), passed to
createHttpServer, so a teapot could only export its scopes from Node. app.upgrade
— the path serveDeno/serveBun drive — had never heard of it, which would have left
"mesh on three runtimes" meaning consume-only. It is now built in the boot gate
(it captures the finalized ordered nodes, so it cannot exist before finalize) and
the reserved path is routed from app.upgrade. Task 3 already made handle() take a
neutral WsSocket and upgrade holds one, so this is a direct call, not a second
implementation. handle() returns the connection's lifetime like runWsConnection,
so upgrade awaits it instead of returning while the peer is still talking. An app
with nothing exported refuses the reserved path explicitly rather than falling
through to "no matching ws route".
Link lifecycle (Task 7): links were reaped by server.on('close'), reachable only
through listen(), so a mesh app booted through app.fetch had links and no server
and leaked every teapot connection at `if (!server) return`. close() now closes
them first either way; that aborts each socket, which rejects its in-flight RPCs.
Also fixes a race the new tests exposed: upgrade awaited the boot *before* handing
the socket to a consumer, but `channel` is fan-out, so frames arriving during the
boot were dropped with no subscriber attached. For the control channel that is
`hello` itself — against a teapot with slow providers the handshake would hang
until timeout. Inbound is now subscribed synchronously on entry and the buffered
iterator handed down, closing the same gap for regular @Ws routes.
Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Tasks 6, 7
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
Only listen() spliced remote scopes and finalized the graph, and listen() builds
a Node http.Server. Deno/Bun/edge serve through app.fetch and can never call it,
so mesh was Node-only by construction: fetch() threw "unavailable before
listen()" forever on those runtimes, telling operators to call something they
had no way to call. buildAppFetch also hardcoded remoteRoutes to [], so even past
the guard it would not have served a remote route.
Move splice+finalize into the memoized boot gate that fetch, upgrade and listen
already share, ahead of the providers — remote nodes must join before the topo
sort. Await it before building the route table rather than after, since for a
mesh app the table is not knowable until the splice has run. listen() keeps
working by awaiting the same gate; the memoization means a fetch followed by a
listen boots once, and concurrent first requests splice once.
The fetch/upgrade guards are gone rather than reworded: they are now unreachable.
inspect()/graph()/explain() keep theirs — they are synchronous and cannot await
network I/O — but their message no longer claims listen() is the only way in.
test/fetch.test.ts asserted the old contract (fetch throws until listen), i.e.
the trap itself; it now pins that a mesh app serves without listen() and that
listen() afterwards does not re-run provider factories.
Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Task 5
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
connectLink constructed `require('ws')` directly and drove its EventEmitter API,
which is why a teacup could only run on Node. It now goes through the neutral
WsSocket like every other consumer, over whichever client the runtime provides:
the platform global (Deno, Bun, Node >= 22) or the `ws` peer for Node 18-21,
which has no global. `ws` stays optional and is only reached for when the global
is absent.
One bridge covers both because `ws` also implements the browser-compatible event
API and delivers text frames as `event.data` strings — probed against the real
package rather than taken on faith.
Both implementations are exercised in one run: `ws` is always in the matrix, so
the Node 18-21 path cannot rot unseen on CI that only runs a modern Node, which
is how a fallback quietly stops working. connectLink takes an optional Ctor to
make that possible; it doubles as a bring-your-own-WebSocket hook for runtimes
we do not ship an adapter for.
Verified the edge bundle is unaffected: `require('ws')` tree-shakes out of the
workerd build entirely.
Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Task 4
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
The mesh control channel was the last consumer speaking the `ws` EventEmitter
API directly: http/ws.ts handed meshControl.handle a raw socket, while every
@Ws route already went through nodeSocket() to get a neutral WsSocket. Mesh did
not lack an abstraction — it skipped the one the codebase already had.
handle() now takes a WsSocket and consumes `inbound`, so both feeds work: Node
via the existing nodeSocket, and Deno/Bun via app.upgrade, where the socket is
already neutral. That is what unblocks mounting the control channel off Node.
RPCs are still dispatched without awaiting. The old `ws.on('message')` listener
overlapped them, and the peer's id-keyed pending map exists for exactly that —
awaiting inside the receive loop would have silently serialized every mesh call.
A test now pins the overlap.
The unused `http` import in http/types.ts fell out with MeshControl's req
parameter: nothing in that module is Node-shaped any more.
Node behaviour is unchanged — the teapot↔teacup integration tests pass
untouched. teapot.test.ts drives handle() directly, so its fake moved from a raw
EventEmitter to a fake WsSocket.
Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Task 3
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
Cross-runtime mesh means peers are separate processes on separate deploy
cadences, so the frame union is a contract between green-tea versions rather
than an internal detail. There was no version field, and decode validated only
that `type` was a known tag before casting `parsed as Frame` — every other
field was trusted, so a skewed or malformed peer failed somewhere downstream
instead of at the boundary.
Add MESH_PROTOCOL_VERSION to the hello/manifest frames. Both ends refuse a
mismatch: the teapot checks the version *before* the secret, since a skewed
peer is not an auth failure and "wrong secret" would send its operator hunting
the wrong bug.
Validate fields per frame type via a Record keyed on the type tag, so a new
frame type must add a row. The lookup uses an own-property check: `type` is
peer-controlled and a bare lookup would resolve SHAPE['constructor'] up the
prototype chain to a truthy non-check.
This is a breaking wire change, done now because it is free exactly once —
mesh is alpha behind experimental:true and has no deployed peers. Adding a
version later would break every peer already in the field.
Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Task 1
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
Steps were executed by three separate hand-rolled loops: runPipeline (HTTP),
buildWsRoutes (ws) and resolveScope (mesh). Only the HTTP one emitted
request:step:enter/leave, so a logging plugin silently observed nothing on ws
routes — a gap in a documented public API, not just redundancy.
Route every transport through a single runSteps() so observability is uniform
by construction rather than by remembering to copy the emit calls.
Also fixes the plugins guide, which documented a request:step:exit event that
has never existed (the bus emits request:step:leave).
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
Boots the actual workerd engine locally (miniflare devDep, no CF account
needed) and round-trips HTTP (app.fetch) + WebSocket (WebSocketPair +
app.upgrade) through edgeHandler's real request path, mirroring the Deno/Bun
adapter tests' assertion shape.
workerd's nodejs_compat genuinely does not implement node:http/node:https
(confirmed in isolation against the real runtime; node:crypto, node:stream,
node:net, node:tls, node:events, node:util, node:buffer all load fine under
the same flags). The barrel statically imports them for the Node listen()
path even though edgeHandler never touches it, so the bundler stubs those
two modules at test-bundle time (inert createServer that throws if ever
called) purely to let the worker load — edgeHandler itself is untouched.
See project-docs/.superpowers/sdd/task-2-report.md for the full writeup and
the suggested core follow-up (lazy-defer those imports behind listen()).
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>