From 922700674c7629d650d4fc6b2a4213a31e4ee77c Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 15 Jul 2026 13:33:47 -0500 Subject: [PATCH 01/13] fix(bus): emit step events for ws and mesh routes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/app/index.ts | 47 ++++++++++------------ src/pipeline.ts | 27 +++++++++---- test/app-upgrade.test.ts | 39 +++++++++++++++++- website/src/content/docs/guides/plugins.md | 2 +- 4 files changed, 81 insertions(+), 34 deletions(-) diff --git a/src/app/index.ts b/src/app/index.ts index a624c6e..13ae295 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -3,7 +3,7 @@ import { Bus } from '../bus'; import { Container } from '../container'; import { topoSort, subgraphFor, GraphNode, nearest } from '../graph'; import { toMermaid, toDOT, graphHtml, type GraphView } from '../graph-viz'; -import { runPipeline, PipelineStep } from '../pipeline'; +import { runPipeline, runSteps, PipelineStep } from '../pipeline'; import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http'; import type { HttpOptions } from '../http'; import { buildFetch } from '../http/web'; @@ -606,15 +606,13 @@ function buildMeshControl( const resolveScope = async (name: string, env: RequestEnvelope): Promise => { // context is intentionally `any`: providers and steps merge arbitrary keys into it - let context: any = { req: env, params: env.params, query: env.query, body: env.body, headers: env.headers }; + const seed: any = { req: env, params: env.params, query: env.query, body: env.body, headers: env.headers }; for (const provider of orderedProviders) - if (container.has(provider.name)) Object.assign(context, await container.resolve(provider.name)); + if (container.has(provider.name)) Object.assign(seed, await container.resolve(provider.name)); - for (const step of orderedSteps) { - const runner = runners.get(step.name)!; - context = { ...context, ...(await runner(context)) }; - } + const steps = orderedSteps.map((step) => ({ name: step.name, origin: step.origin, run: runners.get(step.name)! })); + const context = await runSteps(steps, seed, bus); return context[name]; }; @@ -788,7 +786,7 @@ function openApiRoute(openapi: () => unknown): RouteDef { /** Compiles every ws/negotiate route plan into a WebSocket route that seeds context and runs its steps + handler. */ function buildWsRoutes(routePlans: RoutePlan[], deps: PipelineDeps): WsRouteDef[] { - const { providedSeed, planSteps } = deps; + const { providedSeed, planSteps, bus } = deps; return routePlans .filter((plan) => plan.transport === 'ws' || plan.transport === 'negotiate') @@ -798,23 +796,22 @@ function buildWsRoutes(routePlans: RoutePlan[], deps: PipelineDeps): WsRouteDef[ const provided = await providedSeed(plan); // ws upgrades carry the neutral WsRequest (protocol/ip pre-derived by the runtime adapter); // trustProxy derivation for ws is out of scope here - // context is intentionally `any`: each step merges arbitrary keys into it - let context: any = { - ...provided, - req, - params, - query: parseQuery(req.url ?? ''), - body: undefined, - headers: req.headers, - inbound, - abort, - protocol: req.protocol, - ip: req.ip, - }; - - for (const step of planSteps(plan)) { - context = { ...context, ...(await step.run(context)) }; - } + const context = await runSteps( + planSteps(plan), + { + ...provided, + req, + params, + query: parseQuery(req.url ?? ''), + body: undefined, + headers: req.headers, + inbound, + abort, + protocol: req.protocol, + ip: req.ip, + }, + bus, + ); const result = await plan.run(context); if (!isAsyncIterable(result)) throw new Error(`@Ws handler '${plan.handlerName}' must return an AsyncIterable`); diff --git a/src/pipeline.ts b/src/pipeline.ts index 46a303f..1003e49 100644 --- a/src/pipeline.ts +++ b/src/pipeline.ts @@ -40,6 +40,25 @@ export function isStreamResult(result: PipelineResult): result is StreamResult { return 'stream' in result; } +/** + * Run `steps` in order, merging each step's output into the context and emitting + * `request:step:enter`/`leave` on the bus. The single place steps are executed — every + * transport (HTTP, ws, mesh) goes through here so observability is uniform by construction. + */ +export async function runSteps(steps: PipelineStep[], seed: Record, bus: Bus): Promise { + // context is intentionally `any`: each step merges arbitrary keys into the accumulator + let context: any = seed; + + for (const step of steps) { + bus.emit('request:step:enter', { name: step.name, scope: step.origin }); + const output = await step.run(context); + context = { ...context, ...output }; + bus.emit('request:step:leave', { name: step.name, scope: step.origin }); + } + + return context; +} + /** * Run `steps` in order over a context seeded from `seed`, then invoke `handler`. * An async-iterable handler result becomes a stream; anything else is run through `transformer`. @@ -59,13 +78,7 @@ export async function runPipeline(args: { let context: any = { ...seed }; try { - for (const step of steps) { - bus.emit('request:step:enter', { name: step.name, scope: step.origin }); - const output = await step.run(context); - context = { ...context, ...output }; - bus.emit('request:step:leave', { name: step.name, scope: step.origin }); - } - + context = await runSteps(steps, context, bus); const result = await handler(context); const streaming = isAsyncIterable(result); const contract = TRANSPORT_RETURN[transport]; diff --git a/test/app-upgrade.test.ts b/test/app-upgrade.test.ts index ebad14c..1e1f26b 100644 --- a/test/app-upgrade.test.ts +++ b/test/app-upgrade.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { createApp, Route, Ws, Module, ctx } from '../src/index'; +import { createApp, Route, Ws, Module, ctx, Step, needs } from '../src/index'; import { channel } from '../src/channel'; import type { WsSocket, WsRequest } from '../src/http/ws-core'; @@ -16,6 +16,24 @@ class Rt { class M {} const app = createApp({ modules: [M] }); +@Step({ provides: 'tag' }) +class Tagger { + run() { + return { tag: 't' }; + } +} +@Route('/tagged') +class TaggedCtl { + @Ws('/echo') + echo(@needs('tag') tag: string, @ctx() { inbound }: any) { + return (async function* () { + for await (const msg of inbound) yield `${tag}:${msg}`; + })(); + } +} +@Module({ mountpoint: '/', steps: [Tagger], controllers: [TaggedCtl] }) +class Tagged {} + function fakeSocket() { const inbound = channel(); const ac = new AbortController(); @@ -46,6 +64,25 @@ describe('app.upgrade', () => { expect(sent).toEqual(['echo:hi']); }); + it('emits request:step:enter/leave for ws steps, like HTTP routes do', async () => { + const seen: string[] = []; + const logger = (api: any) => { + api.bus.on('request:step:enter', (p: any) => seen.push(`enter:${p.name}`)); + api.bus.on('request:step:leave', (p: any) => seen.push(`leave:${p.name}`)); + }; + const wsApp = createApp({ modules: [Tagged], plugins: [logger] }); + const { socket, inbound, sent } = fakeSocket(); + const req: WsRequest = { url: '/tagged/echo', headers: {}, protocol: 'http', ip: '' }; + const run = wsApp.upgrade(req, socket); + await new Promise((resolve) => setTimeout(resolve, 0)); + inbound.push('hi'); + inbound.close(); + await run; + + expect(sent).toEqual(['t:hi']); + expect(seen).toEqual(['enter:tag', 'leave:tag']); + }); + it('closes 1008 on an unknown ws path', async () => { const { socket } = fakeSocket(); let closedCode: number | undefined; diff --git a/website/src/content/docs/guides/plugins.md b/website/src/content/docs/guides/plugins.md index f3b647a..d6d7a89 100644 --- a/website/src/content/docs/guides/plugins.md +++ b/website/src/content/docs/guides/plugins.md @@ -42,7 +42,7 @@ mesh activity without touching the pipeline itself: ```typescript api.bus.on('boot:provider:ready', (p: any) => { /* ... */ }); api.bus.on('request:step:enter', (p: any) => { /* ... */ }); -api.bus.on('request:step:exit', (p: any) => { /* ... */ }); +api.bus.on('request:step:leave', (p: any) => { /* ... */ }); ``` The full event vocabulary: From 9421b102d99ee4e5771b4672b51eb65fd4091752 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 15 Jul 2026 13:33:50 -0500 Subject: [PATCH 02/13] refactor(adapters): share ws plumbing across bun/deno/edge MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit toWsRequest, the neutral-socket wrapper and the upgrade error guard were copy-pasted across all three runtime adapters, comments included. A change to the upgrade close code meant remembering to touch three files. Extract the shared parts to http/ws-adapter (kept separate from ws-core: that module runs a connection, this one builds one from a host runtime's socket). Bun keeps its own socket wrapper — its events land on a server-level handler rather than the socket, so the lifecycle genuinely differs. Verified against real runtimes: deno test, bun test, workerd via miniflare. Signed-off-by: Diego Resendez --- src/bun.ts | 69 +++++------------------- src/deno.ts | 89 +++--------------------------- src/edge.ts | 80 ++------------------------- src/http/ws-adapter.ts | 120 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 144 insertions(+), 214 deletions(-) create mode 100644 src/http/ws-adapter.ts diff --git a/src/bun.ts b/src/bun.ts index 9169db7..4656034 100644 --- a/src/bun.ts +++ b/src/bun.ts @@ -2,6 +2,7 @@ import { channel } from './channel'; import type { Channel } from './channel'; import type { App } from './app/types'; import type { WsSocket, WsRequest } from './http/ws-core'; +import { decodeMessage, neutralSocket, toWsRequest, upgradeSafely } from './http/ws-adapter'; // Minimal ambient for the Bun globals we use — avoids a @types/bun devDep. // Mirrors the real Bun.serve / server.upgrade / ServerWebSocket signatures we call. @@ -33,8 +34,6 @@ interface BunServeOptions { type BunServeShortOptions = { port?: number; hostname?: string }; declare const Bun: { serve(options: BunServeOptions): BunServer }; -const decoder = new TextDecoder(); - /** Per-connection state stashed on ws.data between fetch (upgrade) and the open/message/close callbacks. */ interface BunConnData { wsReq: WsRequest; @@ -42,48 +41,15 @@ interface BunConnData { ac: AbortController; } -/** Builds a neutral WsRequest from a Bun request + server (for the client IP). */ -function toWsRequest(request: Request, server: BunServer): WsRequest { - const url = new URL(request.url); - const headers: Record = {}; - request.headers.forEach((v, k) => { - headers[k] = v; - }); - return { - url: url.pathname + url.search, - headers, - protocol: url.protocol === 'https:' ? 'https' : 'http', - ip: server.requestIP(request)?.address ?? '', - }; -} - -/** Wraps a Bun ServerWebSocket (+ its stashed channel/abort) as a neutral WsSocket. */ +/** + * Wraps a Bun ServerWebSocket as a neutral WsSocket. Unlike Deno/edge, Bun delivers socket + * events to a server-level handler rather than the socket, so the channel and abort are + * created during the upgrade and stashed on ws.data — there is nothing here to wire up. + */ function bunSocket(ws: BunServerWebSocket): WsSocket { const { inbound, ac } = ws.data as BunConnData; - return { - inbound, - abort: ac.signal, - get isOpen() { - return ws.readyState === 1; // 1 = OPEN - }, - send: (data) => { - ws.send(data); - }, - close: (code, reason) => { - try { - ws.close(code, reason); - } catch { - /* already closed */ - } - }, - terminate: () => { - try { - (ws.terminate ?? ws.close).call(ws); - } catch { - /* already closed */ - } - }, - }; + + return neutralSocket(ws, inbound, ac); } /** @@ -98,7 +64,8 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServer { if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') { const inbound = channel(); const ac = new AbortController(); - const data: BunConnData = { wsReq: toWsRequest(request, server), inbound, ac }; + const wsReq = toWsRequest(request, server.requestIP(request)?.address ?? ''); + const data: BunConnData = { wsReq, inbound, ac }; if (server.upgrade(request, { data })) return undefined; return new Response('WebSocket upgrade failed', { status: 400 }); } @@ -108,21 +75,13 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServer { websocket: { open(ws) { const { wsReq } = ws.data as BunConnData; - // fire-and-forget: app.upgrade can reject before runWsConnection's try/catch - // (mesh-before-listen, provider boot failure); guard it or an uncaught rejection - // could crash the Bun process. - void app.upgrade(wsReq, bunSocket(ws)).catch(() => { - try { - ws.close(1011, 'internal error'); - } catch { - /* already closed */ - } - }); + + void upgradeSafely(app, wsReq, bunSocket(ws)); }, message(ws, message) { const { inbound } = ws.data as BunConnData; - // decode binary to UTF-8 to match Node's Buffer.toString() (cross-adapter parity) - inbound.push(typeof message === 'string' ? message : decoder.decode(message)); + + inbound.push(decodeMessage(message)); }, close(ws) { const { inbound, ac } = ws.data as BunConnData; diff --git a/src/deno.ts b/src/deno.ts index eafe6dc..f73e80a 100644 --- a/src/deno.ts +++ b/src/deno.ts @@ -1,23 +1,11 @@ -import { channel } from './channel'; import type { App } from './app/types'; -import type { WsSocket, WsRequest } from './http/ws-core'; +import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter'; // The project tsconfig's `lib` doesn't include `DOM`, and the installed `@types/node` (18.x) -// doesn't declare a global `WebSocket` either — so we ambient-declare just the shape we use -// (both the instance interface and the `OPEN` static, mirroring the real WebSocket). -interface WebSocketEventMap { - message: { data: string | ArrayBuffer }; - close: object; - error: object; -} -interface WebSocket { - readonly readyState: number; +// doesn't declare a global `WebSocket` either — so we ambient-declare just the shape we use. +interface WebSocket extends EventfulSocket { binaryType: string; - send(data: string): void; - close(code?: number, reason?: string): void; - addEventListener(type: K, listener: (event: WebSocketEventMap[K]) => void): void; } -declare const WebSocket: { readonly OPEN: number }; // Minimal ambient for the Deno globals we use — avoids a @types/deno devDep. // Mirrors the real Deno.serve / Deno.upgradeWebSocket signatures we call. @@ -40,63 +28,6 @@ declare const Deno: { upgradeWebSocket(request: Request): { socket: WebSocket; response: Response }; }; -/** Builds a neutral WsRequest from a Deno upgrade Request + connection info. */ -function toWsRequest(request: Request, info: DenoServeHandlerInfo): WsRequest { - const url = new URL(request.url); - const headers: Record = {}; - request.headers.forEach((v, k) => { - headers[k] = v; - }); - return { - url: url.pathname + url.search, - headers, - protocol: url.protocol === 'https:' ? 'https' : 'http', - ip: info.remoteAddr.hostname, - }; -} - -/** Wraps a Deno/web WebSocket as a neutral WsSocket. */ -function denoSocket(ws: WebSocket): WsSocket { - const inbound = channel(); - const ac = new AbortController(); - ws.binaryType = 'arraybuffer'; - const decoder = new TextDecoder(); - ws.addEventListener('message', (e) => { - const data = e.data; - inbound.push(typeof data === 'string' ? data : decoder.decode(data as ArrayBuffer)); - }); - ws.addEventListener('close', () => { - inbound.close(); - ac.abort(); - }); - ws.addEventListener('error', () => { - inbound.fail(new Error('websocket error')); - ac.abort(); - }); - return { - inbound, - abort: ac.signal, - get isOpen() { - return ws.readyState === WebSocket.OPEN; - }, - send: (data) => ws.send(data), - close: (code, reason) => { - try { - ws.close(code, reason); - } catch { - /* already closed */ - } - }, - terminate: () => { - try { - ws.close(); - } catch { - /* already closed */ - } - }, - }; -} - /** * Serve a Green Tea app on Deno: HTTP + SSE via app.fetch, WebSocket via Deno.upgradeWebSocket. * WebSocket messages flow through app.upgrade over the shared neutral core. @@ -105,17 +36,9 @@ export function serveDeno(app: App, options?: DenoServeOptions): DenoHttpServer return Deno.serve(options ?? {}, (request, info) => { if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') { const { socket, response } = Deno.upgradeWebSocket(request); - // Fire-and-forget: the upgrade response must be returned synchronously while - // the graph runs. app.upgrade can reject BEFORE runWsConnection's own try/catch - // (mesh-before-listen throw, or a provider boot failure), so guard the call here — - // an uncaught rejection would be fatal on Deno and crash the whole server. - void app.upgrade(toWsRequest(request, info), denoSocket(socket)).catch(() => { - try { - socket.close(1011, 'internal error'); - } catch { - /* already closed */ - } - }); + socket.binaryType = 'arraybuffer'; // deliver binary frames as ArrayBuffer, which decodeMessage expects + // fire-and-forget: the 101 response must be returned synchronously while the graph runs + void upgradeSafely(app, toWsRequest(request, info.remoteAddr.hostname), eventSocket(socket)); return response; } diff --git a/src/edge.ts b/src/edge.ts index ec4780c..a064aa2 100644 --- a/src/edge.ts +++ b/src/edge.ts @@ -1,83 +1,16 @@ -import { channel } from './channel'; import type { App } from './app/types'; -import type { WsSocket, WsRequest } from './http/ws-core'; +import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter'; // Minimal ambient for the Cloudflare Workers globals we use — avoids @cloudflare/workers-types. // Declares only what we call; mirrors the real workerd signatures. -interface EdgeWebSocket { +interface EdgeWebSocket extends EventfulSocket { accept(): void; - addEventListener( - type: 'message' | 'close' | 'error', - listener: (event: { data?: string | ArrayBuffer }) => void, - ): void; - send(data: string): void; - close(code?: number, reason?: string): void; - readyState: number; } interface EdgeCtx { waitUntil(promise: Promise): void; } declare const WebSocketPair: { new (): { 0: EdgeWebSocket; 1: EdgeWebSocket } }; -const decoder = new TextDecoder(); - -/** Builds a neutral WsRequest from a Cloudflare Worker request. */ -function toWsRequest(request: Request): WsRequest { - const url = new URL(request.url); - const headers: Record = {}; - request.headers.forEach((v, k) => { - headers[k] = v; - }); - return { - url: url.pathname + url.search, - headers, - protocol: url.protocol === 'https:' ? 'https' : 'http', - ip: request.headers.get('cf-connecting-ip') ?? '', - }; -} - -/** Wraps a Cloudflare server-side WebSocket (already accept()ed) as a neutral WsSocket. */ -function edgeSocket(server: EdgeWebSocket): WsSocket { - const inbound = channel(); - const ac = new AbortController(); - server.addEventListener('message', (event) => { - const data = event.data; - inbound.push(typeof data === 'string' ? data : decoder.decode(data as ArrayBuffer)); - }); - server.addEventListener('close', () => { - inbound.close(); - ac.abort(); - }); - server.addEventListener('error', () => { - inbound.fail(new Error('websocket error')); - ac.abort(); - }); - return { - inbound, - abort: ac.signal, - get isOpen() { - return server.readyState === 1; // 1 = OPEN - }, - send: (data) => { - server.send(data); - }, - close: (code, reason) => { - try { - server.close(code, reason); - } catch { - /* already closed */ - } - }, - terminate: () => { - try { - server.close(); - } catch { - /* already closed */ - } - }, - }; -} - /** * Cloudflare Workers / edge handler: HTTP + SSE via app.fetch, WebSocket via WebSocketPair. * Use as `export default { fetch: edgeHandler(app) }`. Requires the `nodejs_compat` @@ -90,13 +23,8 @@ export function edgeHandler( if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') { const [client, server] = Object.values(new WebSocketPair()) as [EdgeWebSocket, EdgeWebSocket]; server.accept(); - const lifecycle = app.upgrade(toWsRequest(request), edgeSocket(server)).catch(() => { - try { - server.close(1011, 'internal error'); - } catch { - /* already closed */ - } - }); + const wsReq = toWsRequest(request, request.headers.get('cf-connecting-ip') ?? ''); + const lifecycle = upgradeSafely(app, wsReq, eventSocket(server)); if (ctx?.waitUntil) ctx.waitUntil(lifecycle); else void lifecycle; diff --git a/src/http/ws-adapter.ts b/src/http/ws-adapter.ts new file mode 100644 index 0000000..8e024c0 --- /dev/null +++ b/src/http/ws-adapter.ts @@ -0,0 +1,120 @@ +import { channel } from '../channel'; +import type { App } from '../app/types'; +import type { WsRequest, WsSocket } from './ws-core'; + +/** + * Shared plumbing for the runtime adapters (Bun/Deno/edge) that bridge a host WebSocket + * to the neutral {@link WsSocket} the core talks to. Separate from `ws-core` on purpose: + * that module *runs* a connection, this one *builds* one from a host runtime's socket. + */ + +const decoder = new TextDecoder(); +const OPEN = 1; // WebSocket.OPEN — same constant in every runtime; avoids a per-runtime ambient + +/** Decodes a host `message` payload to the string the core expects (parity with Node's Buffer.toString()). */ +export function decodeMessage(data: string | ArrayBuffer | Uint8Array): string { + return typeof data === 'string' ? data : decoder.decode(data); +} + +/** + * Builds a neutral {@link WsRequest} from a Web-standard `Request`. Every adapter derives + * url/headers/protocol identically; only the client IP is runtime-specific, so it's passed in. + */ +export function toWsRequest(request: Request, ip: string): WsRequest { + const url = new URL(request.url); + const headers: Record = {}; + request.headers.forEach((value, key) => { + headers[key] = value; + }); + + return { + url: url.pathname + url.search, + headers, + protocol: url.protocol === 'https:' ? 'https' : 'http', + ip, + }; +} + +/** The subset of a host WebSocket that {@link eventSocket} drives (Deno's WebSocket and workerd's both satisfy it). */ +export interface EventfulSocket { + readonly readyState: number; + send(data: string): void; + close(code?: number, reason?: string): void; + addEventListener( + type: 'message' | 'close' | 'error', + listener: (event: { data?: string | ArrayBuffer }) => void, + ): void; +} + +/** + * Wraps an `addEventListener`-style host socket (Deno, workerd) as a neutral {@link WsSocket}: + * creates the inbound channel and abort controller and wires message/close/error into them. + * Bun does not use this — its socket events are delivered to a server-level handler rather + * than the socket, so it builds its own {@link WsSocket} over state stashed on `ws.data`. + */ +export function eventSocket(host: EventfulSocket): WsSocket { + const inbound = channel(); + const ac = new AbortController(); + + host.addEventListener('message', (event) => { + inbound.push(decodeMessage(event.data as string | ArrayBuffer)); + }); + host.addEventListener('close', () => { + inbound.close(); + ac.abort(); + }); + host.addEventListener('error', () => { + inbound.fail(new Error('websocket error')); + ac.abort(); + }); + + return neutralSocket(host, inbound, ac); +} + +/** + * Wraps a host socket's send/close/readyState as a neutral {@link WsSocket} over an + * already-wired channel and abort controller. `close`/`terminate` swallow throws so + * callers never have to guard an already-closed socket. + */ +export function neutralSocket( + host: Pick & { terminate?(): void }, + inbound: ReturnType>, + ac: AbortController, +): WsSocket { + return { + inbound, + abort: ac.signal, + get isOpen() { + return host.readyState === OPEN; + }, + send: (data) => { + host.send(data); + }, + close: (code, reason) => { + try { + host.close(code, reason); + } catch { + /* already closed */ + } + }, + terminate: () => { + try { + (host.terminate ?? host.close).call(host); + } catch { + /* already closed */ + } + }, + }; +} + +/** + * Runs the ws lifecycle, closing with 1011 if it rejects. `app.upgrade` can reject *before* + * `runWsConnection`'s own try/catch (mesh-before-listen, provider boot failure); unguarded, + * that surfaces as an uncaught rejection and is fatal on Bun/Deno. Returns the promise so + * edge can hand it to `ctx.waitUntil`. + */ +export function upgradeSafely(app: App, request: WsRequest, socket: WsSocket): Promise { + return app.upgrade(request, socket).catch(() => { + socket.close(1011, 'internal error'); // neutral close already swallows throws + }); +} From d56eeafcd8354f95f9518303902ca1bd08933ddb Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 15 Jul 2026 13:33:52 -0500 Subject: [PATCH 03/13] refactor: close type holes on the transport and error axes - OpenApiRoute.transport was typed `string`, so the compiler could not check the transport branching at all. Type it Transport and key the documented 200 off a Record, so a new transport fails the build instead of silently going undocumented. - pickEncoder fell through to ndjson for unknown transports; make the mapping exhaustive so a new transport cannot inherit the wrong wire format by accident. - HttpError carries optional headers, removing the instanceof Redirect special case that coupled the error renderer to one subclass. Custom errors needing headers (retry-after, etag) no longer require touching transformers. - Drop the module-global connSeq in mesh/link: `pending` is already per-connection, so a per-link counter suffices and connection ids stop depending on test order. Signed-off-by: Diego Resendez --- src/http/stream.ts | 22 ++++++++++++++++++---- src/mesh/link.ts | 17 +++++------------ src/openapi.ts | 38 +++++++++++++++++++++++--------------- src/signals.ts | 9 +++++++-- src/transformers.ts | 5 ++--- 5 files changed, 55 insertions(+), 36 deletions(-) diff --git a/src/http/stream.ts b/src/http/stream.ts index 9532fa2..f34783c 100644 --- a/src/http/stream.ts +++ b/src/http/stream.ts @@ -6,11 +6,25 @@ import type { Bus } from '../bus'; const PING_MS = 15_000; -/** Selects the stream encoder for a transport, falling back to the client's `Accept` header for `stream`. */ +/** + * Stream encoder per transport, or `null` for transports that never produce an HTTP stream. + * A new transport must add a row — the compiler fails until it does, so it can't silently + * inherit ndjson framing. + */ +const STREAM_ENCODERS: Record StreamEncoder) | null> = { + buffer: null, // a buffered handler returning a stream throws TransportMismatchError before reaching here + ws: null, // not an HTTP response; ws routes are served via upgrade, not handle() + sse: () => sseEncoder, + ndjson: () => ndjsonEncoder, + negotiate: (accept) => (accept.includes('text/event-stream') ? sseEncoder : ndjsonEncoder), +}; + +/** Selects the stream encoder for a transport, falling back to the client's `Accept` header for `negotiate`. */ export function pickEncoder(transport: Transport, accept: string): StreamEncoder { - if (transport === 'sse') return sseEncoder; - if (transport === 'ndjson') return ndjsonEncoder; - return accept.includes('text/event-stream') ? sseEncoder : ndjsonEncoder; + const pick = STREAM_ENCODERS[transport]; + if (!pick) throw new Error(`transport '${transport}' does not produce an HTTP stream`); + + return pick(accept); } /** Pipes an async-iterable result to the response as an HTTP stream, with keep-alive pings and backpressure handling. */ diff --git a/src/mesh/link.ts b/src/mesh/link.ts index 397364a..e946e65 100644 --- a/src/mesh/link.ts +++ b/src/mesh/link.ts @@ -2,8 +2,6 @@ import type { Bus } from '../bus'; import { HttpError } from '../signals'; import { encode, decode, type Manifest, type RequestEnvelope, type Frame } from './protocol'; -let connSeq = 0; // module-level: deterministic unique connection-id prefix (no Date.now/Math.random) - /** Client handle to a remote mesh server: its manifest, an RPC caller, and a close(). */ export interface Link { manifest: Manifest; @@ -56,19 +54,15 @@ function sendRpc( } /** Assemble the client-facing Link once the manifest arrives. */ -function buildLink( - ws: any, - pending: Map, - manifest: Manifest, - connId: string, - timeoutMs: number, -): Link { +function buildLink(ws: any, pending: Map, manifest: Manifest, timeoutMs: number): Link { + // ids only need to be unique within this link: `pending` is per-connection, so a + // per-link counter suffices (no module-global sequence, no test-order coupling). let counter = 0; return { manifest, rpc(kind, name, ctx) { - const id = `${connId}:${counter++}`; + const id = String(counter++); return sendRpc(ws, pending, id, kind, name, ctx, timeoutMs); }, @@ -103,7 +97,6 @@ export function connectLink(args: { url: string; secret: string; timeoutMs?: num const WS = loadWs(); const ws = new WS(args.url); const pending = new Map(); - const connId = `c${connSeq++}`; let manifest: Manifest | undefined; return new Promise((resolve, reject) => { @@ -134,7 +127,7 @@ export function connectLink(args: { url: string; secret: string; timeoutMs?: num manifest = { scopes: frame.scopes, routes: frame.routes }; clearTimeout(connectTimer); args.bus?.emit('mesh:connect', { name: args.url }); - resolve(buildLink(ws, pending, manifest, connId, timeoutMs)); + resolve(buildLink(ws, pending, manifest, timeoutMs)); return; } diff --git a/src/openapi.ts b/src/openapi.ts index 7eba251..4acf4f4 100644 --- a/src/openapi.ts +++ b/src/openapi.ts @@ -1,10 +1,11 @@ import type { ArgSpec } from './params'; +import type { Transport } from './metadata'; /** Minimal per-route input the OpenAPI projection needs, derived from a route plan. */ export interface OpenApiRoute { method: string; pattern: string; - transport: string; + transport: Transport; args: ArgSpec[]; } @@ -55,17 +56,23 @@ function argParams(args: ArgSpec[]): Parameter[] { return params; } -/** The success/error responses documented for a route, keyed by transport and whether any input is validated. */ -function responses(route: OpenApiRoute): Record { - const result: Record = {}; +/** + * The documented `200` per transport. `ws` is absent by construction — ws routes are not + * HTTP request/response and are filtered out before this runs. A new transport adds a row, + * and the compiler fails until it does. + */ +type HttpTransport = Exclude; - if (route.transport === 'sse') { - result['200'] = { description: 'Event stream', content: { 'text/event-stream': {} } }; - } else if (route.transport === 'ndjson' || route.transport === 'negotiate') { - result['200'] = { description: 'Stream', content: { 'application/x-ndjson': {} } }; - } else { - result['200'] = { description: 'OK', content: { 'application/json': { schema: {} } } }; - } +const TRANSPORT_OK: Record> = { + buffer: { description: 'OK', content: { 'application/json': { schema: {} } } }, + sse: { description: 'Event stream', content: { 'text/event-stream': {} } }, + ndjson: { description: 'Stream', content: { 'application/x-ndjson': {} } }, + negotiate: { description: 'Stream', content: { 'application/x-ndjson': {} } }, +}; + +/** The success/error responses documented for a route, keyed by transport and whether any input is validated. */ +function responses(route: OpenApiRoute, transport: HttpTransport): Record { + const result: Record = { '200': TRANSPORT_OK[transport] }; if (route.args.some((arg) => arg.schema)) result['422'] = { description: 'Validation failed' }; result['500'] = { description: 'Internal Server Error' }; @@ -73,9 +80,9 @@ function responses(route: OpenApiRoute): Record { } /** Builds a single OpenAPI operation object for a route. */ -function operation(route: OpenApiRoute): Record { +function operation(route: OpenApiRoute, transport: HttpTransport): Record { const parameters = [...pathParams(route.pattern), ...argParams(route.args)]; - const op: Record = { responses: responses(route) }; + const op: Record = { responses: responses(route, transport) }; if (parameters.length) op.parameters = parameters; @@ -95,9 +102,10 @@ export function buildOpenApi(routes: OpenApiRoute[], info?: OpenApiInfo): OpenAp const paths: Record> = {}; for (const route of routes) { - if (route.transport === 'ws') continue; // not an HTTP request/response + const transport = route.transport; + if (transport === 'ws') continue; // not an HTTP request/response; narrows to HttpTransport below const path = templatePath(route.pattern); - (paths[path] ??= {})[route.method.toLowerCase()] = operation(route); + (paths[path] ??= {})[route.method.toLowerCase()] = operation(route, transport); } return { diff --git a/src/signals.ts b/src/signals.ts index 29f5507..c34dfc1 100644 --- a/src/signals.ts +++ b/src/signals.ts @@ -1,11 +1,16 @@ import type { StandardIssue } from './standard-schema'; -/** Error carrying an HTTP status code and optional response body. Base of all signals. */ +/** + * Error carrying an HTTP status code and optional response body. Base of all signals. + * A subclass needing response headers (e.g. `location`, `retry-after`) sets `headers` + * rather than requiring a special case in the error renderer. + */ export class HttpError extends Error { constructor( readonly status: number, message?: string, readonly body?: unknown, + readonly headers?: Record, ) { super(message ?? `HTTP ${status}`); this.name = new.target.name; @@ -36,7 +41,7 @@ export class NotModified extends HttpError { /** 302 redirect to `location`. */ export class Redirect extends HttpError { constructor(readonly location: string) { - super(302); + super(302, undefined, undefined, { location }); } } diff --git a/src/transformers.ts b/src/transformers.ts index 328783b..eac5c81 100644 --- a/src/transformers.ts +++ b/src/transformers.ts @@ -1,4 +1,4 @@ -import { isHttpError, Redirect, ValidationError } from './signals'; +import { isHttpError, ValidationError } from './signals'; import type { TransformerFn } from './metadata'; import { flattenPath } from './standard-schema'; @@ -47,8 +47,7 @@ export function errorToResponse(error: unknown): ErrorResponse { } if (isHttpError(error)) { - const headers: Record = { 'content-type': 'application/json' }; - if (error instanceof Redirect) headers.location = error.location; + const headers = { 'content-type': 'application/json', ...error.headers }; const payload = error.body !== undefined ? error.body : { error: error.message }; return { status: error.status, headers, body: JSON.stringify(payload) }; } From dd0ea91a1bb7753a9f7f286765e291e774b4ff91 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 15 Jul 2026 14:47:35 -0500 Subject: [PATCH 04/13] feat(mesh): version the wire protocol and validate frame shapes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/mesh/link.ts | 17 +++++++-- src/mesh/protocol.ts | 67 +++++++++++++++++++++++++++++------ src/mesh/teapot.ts | 50 ++++++++++++++++++++++----- test/mesh/link.test.ts | 40 +++++++++++++++++++-- test/mesh/protocol.test.ts | 71 ++++++++++++++++++++++++++++++++++---- test/mesh/teapot.test.ts | 36 ++++++++++++++----- 6 files changed, 243 insertions(+), 38 deletions(-) diff --git a/src/mesh/link.ts b/src/mesh/link.ts index e946e65..caa6f6c 100644 --- a/src/mesh/link.ts +++ b/src/mesh/link.ts @@ -1,6 +1,6 @@ import type { Bus } from '../bus'; import { HttpError } from '../signals'; -import { encode, decode, type Manifest, type RequestEnvelope, type Frame } from './protocol'; +import { encode, decode, MESH_PROTOCOL_VERSION, type Manifest, type RequestEnvelope, type Frame } from './protocol'; /** Client handle to a remote mesh server: its manifest, an RPC caller, and a close(). */ export interface Link { @@ -105,7 +105,7 @@ export function connectLink(args: { url: string; secret: string; timeoutMs?: num reject(new Error(`mesh connect timeout: ${args.url}`)); }, timeoutMs); - ws.on('open', () => ws.send(encode({ type: 'hello', secret: args.secret }))); + ws.on('open', () => ws.send(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: args.secret }))); ws.on('error', (error: unknown) => reject(error)); ws.on('close', () => { clearTimeout(connectTimer); @@ -124,8 +124,19 @@ export function connectLink(args: { url: string; secret: string; timeoutMs?: num } if (frame.type === 'manifest') { - manifest = { scopes: frame.scopes, routes: frame.routes }; clearTimeout(connectTimer); + + if (frame.v !== MESH_PROTOCOL_VERSION) { + ws.close(); + reject( + new Error( + `mesh protocol version mismatch at ${args.url}: teapot speaks v${frame.v}, this teacup speaks v${MESH_PROTOCOL_VERSION}`, + ), + ); + return; + } + + manifest = { scopes: frame.scopes, routes: frame.routes }; args.bus?.emit('mesh:connect', { name: args.url }); resolve(buildLink(ws, pending, manifest, timeoutMs)); return; diff --git a/src/mesh/protocol.ts b/src/mesh/protocol.ts index e2731b2..5f4b82b 100644 --- a/src/mesh/protocol.ts +++ b/src/mesh/protocol.ts @@ -1,3 +1,11 @@ +/** + * Version of the mesh wire protocol. Peers are separate processes on separate deploy + * cadences — possibly on different runtimes — so the frame shapes are a contract between + * green-tea versions, not an internal detail. Bump on any breaking frame change; peers + * refuse each other on mismatch rather than misparsing downstream. + */ +export const MESH_PROTOCOL_VERSION = 1; + /** Serialized request context sent across the mesh for a scope or route RPC. */ export interface RequestEnvelope { method: string; @@ -23,28 +31,67 @@ export interface Manifest { routes: RouteEntry[]; } -/** Discriminated union of every message on the mesh wire. */ +/** Discriminated union of every message on the mesh wire. The handshake frames carry `v`. */ export type Frame = - | { type: 'hello'; secret: string } - | { type: 'manifest'; scopes: ScopeEntry[]; routes: RouteEntry[] } + | { type: 'hello'; v: number; secret: string } + | { type: 'manifest'; v: number; scopes: ScopeEntry[]; routes: RouteEntry[] } | { type: 'rpc-req'; id: string; kind: 'scope' | 'route'; name: string; ctx: RequestEnvelope } | { type: 'rpc-res'; id: string; ok: true; result: unknown } | { type: 'rpc-res'; id: string; ok: false; error: { message: string; status?: number } }; -const TYPES = new Set(['hello', 'manifest', 'rpc-req', 'rpc-res']); +const isString = (value: unknown): value is string => typeof value === 'string'; +const isNumber = (value: unknown): boolean => typeof value === 'number'; +const isObject = (value: unknown): boolean => typeof value === 'object' && value !== null; + +/** Rejects a frame whose fields don't match its `type` tag. `bad` always throws. */ +type ShapeCheck = (frame: Record, bad: (why: string) => never) => void; + +/** + * Field checks per frame type. `decode` is the mesh's trust boundary: past it, frames are fed + * straight to the scope/route resolvers, so a bad shape must die here rather than surface as a + * confusing failure downstream. A new frame type must add a row — the compiler fails until it does. + */ +const SHAPE: Record = { + hello: (frame, bad) => { + if (!isNumber(frame.v)) bad('missing protocol version'); + if (!isString(frame.secret)) bad('secret must be a string'); + }, + manifest: (frame, bad) => { + if (!isNumber(frame.v)) bad('missing protocol version'); + if (!Array.isArray(frame.scopes) || !Array.isArray(frame.routes)) bad('scopes and routes must be arrays'); + }, + 'rpc-req': (frame, bad) => { + if (!isString(frame.id)) bad('id must be a string'); + if (frame.kind !== 'scope' && frame.kind !== 'route') bad("kind must be 'scope' or 'route'"); + if (!isString(frame.name)) bad('name must be a string'); + if (!isObject(frame.ctx)) bad('ctx must be an object'); + }, + 'rpc-res': (frame, bad) => { + if (!isString(frame.id)) bad('id must be a string'); + if (typeof frame.ok !== 'boolean') bad('ok must be a boolean'); + if (frame.ok === false && !isObject(frame.error)) bad('error must be an object when ok is false'); + }, +}; /** Serialize a frame to a JSON wire string. */ export function encode(frame: Frame): string { return JSON.stringify(frame); } -/** Parse a wire string into a frame, throwing if the `type` tag is unknown. */ +/** Parse a wire string into a frame, throwing if the `type` tag is unknown or the shape is malformed. */ export function decode(json: string): Frame { - const parsed = JSON.parse(json) as { type?: unknown }; + const parsed = JSON.parse(json) as Record; + const type = parsed.type; + // own-property check, not a bare lookup: `type` is peer-controlled, and SHAPE['constructor'] + // would otherwise resolve up the prototype chain to a truthy non-check. + const known = isString(type) && Object.prototype.hasOwnProperty.call(SHAPE, type); + const check = known ? SHAPE[type as Frame['type']] : undefined; - if (typeof parsed.type !== 'string' || !TYPES.has(parsed.type)) { - throw new Error(`unknown frame type: ${String(parsed.type)}`); - } + if (!check) throw new Error(`unknown frame type: ${String(type)}`); - return parsed as Frame; + check(parsed, (why) => { + throw new Error(`malformed ${String(type)} frame: ${why}`); + }); + + return parsed as unknown as Frame; } diff --git a/src/mesh/teapot.ts b/src/mesh/teapot.ts index b7922fa..6561bbf 100644 --- a/src/mesh/teapot.ts +++ b/src/mesh/teapot.ts @@ -2,7 +2,15 @@ import crypto from 'crypto'; import type { Bus } from '../bus'; import type { ResponseShape } from '../pipeline'; import { isHttpError } from '../signals'; -import { encode, decode, type Manifest, type RequestEnvelope, type RouteEntry, type Frame } from './protocol'; +import { + encode, + decode, + MESH_PROTOCOL_VERSION, + type Manifest, + type RequestEnvelope, + type RouteEntry, + type Frame, +} from './protocol'; /** WebSocket path where a teapot exposes its mesh control channel. */ export const MESH_CONTROL_PATH = '/__mesh__/control'; @@ -49,18 +57,44 @@ function notExported(name: string): Error { return error; } -/** Validate an unauthenticated hello frame; reply with the manifest on success or close on mismatch. */ +/** + * Validate an unauthenticated hello frame; reply with the manifest on success or close on mismatch. + * The version is checked *before* the secret: a skewed peer is not an auth failure, and telling it + * "wrong secret" would send its operator hunting the wrong bug. + */ function handleHandshake(ws: any, frame: Frame, deps: MeshControlDeps): boolean { - if (frame.type === 'hello' && safeEqual(frame.secret, deps.secret)) { - ws.send(encode({ type: 'manifest', scopes: deps.manifest.scopes, routes: deps.manifest.routes })); - deps.bus?.emit('mesh:connect', { name: 'teapot' }); + if (frame.type !== 'hello') { + ws.close(1008); - return true; + return false; } - ws.close(1008); + if (frame.v !== MESH_PROTOCOL_VERSION) { + ws.close( + 1008, + `mesh protocol version mismatch: peer speaks v${frame.v}, this teapot speaks v${MESH_PROTOCOL_VERSION}`, + ); - return false; + return false; + } + + if (!safeEqual(frame.secret, deps.secret)) { + ws.close(1008); + + return false; + } + + ws.send( + encode({ + type: 'manifest', + v: MESH_PROTOCOL_VERSION, + scopes: deps.manifest.scopes, + routes: deps.manifest.routes, + }), + ); + deps.bus?.emit('mesh:connect', { name: 'teapot' }); + + return true; } /** Resolve an authenticated rpc-req against the exported scopes/routes, enforcing export gating. */ diff --git a/test/mesh/link.test.ts b/test/mesh/link.test.ts index 69bdd18..888aafd 100644 --- a/test/mesh/link.test.ts +++ b/test/mesh/link.test.ts @@ -1,7 +1,9 @@ import { describe, it, expect } from 'vitest'; import { WebSocketServer } from 'ws'; import { connectLink } from '../../src/mesh/link'; -import { encode, decode } from '../../src/mesh/protocol'; +import { encode, decode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol'; + +const V = MESH_PROTOCOL_VERSION; const env = { method: 'GET', params: {}, query: {}, body: undefined, headers: {} }; @@ -13,7 +15,7 @@ function startTeapot(secret = 'good') { ws.on('message', (d) => { const f = decode(d.toString()); if (!authed) { - if (f.type === 'hello' && f.secret === secret) { authed = true; ws.send(encode({ type: 'manifest', scopes: [{ token: 'auth', scope: 'request' }], routes: [] })); } + if (f.type === 'hello' && f.secret === secret) { authed = true; ws.send(encode({ type: 'manifest', v: V, scopes: [{ token: 'auth', scope: 'request' }], routes: [] })); } else ws.close(1008); return; } @@ -33,7 +35,7 @@ function startSilentTeapot(secret = 'good') { wss.on('connection', (ws) => { ws.on('message', (d) => { const f = decode(d.toString()); - if (f.type === 'hello' && f.secret === secret) ws.send(encode({ type: 'manifest', scopes: [], routes: [] })); + if (f.type === 'hello' && f.secret === secret) ws.send(encode({ type: 'manifest', v: V, scopes: [], routes: [] })); // ignore rpc-req entirely }); }); @@ -41,7 +43,39 @@ function startSilentTeapot(secret = 'good') { return { url: `ws://127.0.0.1:${port}/__mesh__/control`, close: () => wss.close() }; } +// teapot running a future protocol: handshakes, but answers with a skewed manifest +function startSkewedTeapot() { + const wss = new WebSocketServer({ port: 0 }); + wss.on('connection', (ws) => { + ws.on('message', () => ws.send(encode({ type: 'manifest', v: V + 1, scopes: [], routes: [] } as any))); + }); + const port = (wss.address() as any).port; + return { url: `ws://127.0.0.1:${port}/__mesh__/control`, close: () => wss.close() }; +} + describe('connectLink', () => { + it('sends its protocol version in the hello', async () => { + const seen: any[] = []; + const wss = new WebSocketServer({ port: 0 }); + wss.on('connection', (ws) => + ws.on('message', (d) => { + seen.push(decode(d.toString())); + ws.send(encode({ type: 'manifest', v: V, scopes: [], routes: [] })); + }), + ); + const url = `ws://127.0.0.1:${(wss.address() as any).port}/__mesh__/control`; + const link = await connectLink({ url, secret: 'good' }); + expect(seen[0]).toMatchObject({ type: 'hello', v: V }); + link.close(); + wss.close(); + }); + + it('refuses a teapot on a different protocol version', async () => { + const t = startSkewedTeapot(); + await expect(connectLink({ url: t.url, secret: 'good', timeoutMs: 500 })).rejects.toThrow(/version/i); + t.close(); + }); + it('handshakes and exposes the manifest', async () => { const t = startTeapot(); const link = await connectLink({ url: t.url, secret: 'good' }); diff --git a/test/mesh/protocol.test.ts b/test/mesh/protocol.test.ts index f390593..029fe06 100644 --- a/test/mesh/protocol.test.ts +++ b/test/mesh/protocol.test.ts @@ -1,16 +1,22 @@ import { describe, it, expect } from 'vitest'; -import { encode, decode, type Frame, type RequestEnvelope } from '../../src/mesh/protocol'; +import { encode, decode, MESH_PROTOCOL_VERSION, type Frame, type RequestEnvelope } from '../../src/mesh/protocol'; const env: RequestEnvelope = { method: 'GET', params: { id: '1' }, query: {}, body: undefined, headers: {} }; +const V = MESH_PROTOCOL_VERSION; describe('protocol codec', () => { it('round-trips each frame type', () => { const frames: Frame[] = [ - { type: 'hello', secret: 's3cr3t' }, - { type: 'manifest', scopes: [{ token: 'auth', scope: 'request' }], routes: [{ method: 'GET', pattern: '/u/:id' }] }, - { type: 'rpc-req', id: 'c1:1', kind: 'scope', name: 'auth', ctx: env }, - { type: 'rpc-res', id: 'c1:1', ok: true, result: { id: 'u1' } }, - { type: 'rpc-res', id: 'c1:2', ok: false, error: { message: 'no', status: 401 } }, + { type: 'hello', v: V, secret: 's3cr3t' }, + { + type: 'manifest', + v: V, + scopes: [{ token: 'auth', scope: 'request' }], + routes: [{ method: 'GET', pattern: '/u/:id' }], + }, + { type: 'rpc-req', id: '1', kind: 'scope', name: 'auth', ctx: env }, + { type: 'rpc-res', id: '1', ok: true, result: { id: 'u1' } }, + { type: 'rpc-res', id: '2', ok: false, error: { message: 'no', status: 401 } }, ]; for (const f of frames) expect(decode(encode(f))).toEqual(f); }); @@ -22,4 +28,57 @@ describe('protocol codec', () => { it('throws on unknown frame type', () => { expect(() => decode(JSON.stringify({ type: 'bogus' }))).toThrow(/unknown frame/i); }); + + it.each(['constructor', 'toString', '__proto__', 'hasOwnProperty'])( + 'treats inherited Object property %s as an unknown type, not a validator', + (type) => { + // `type` is peer-controlled; a bare SHAPE[type] lookup would walk the prototype chain + expect(() => decode(JSON.stringify({ type }))).toThrow(/unknown frame/i); + }, + ); + + it('throws on a non-string type tag', () => { + expect(() => decode(JSON.stringify({ type: 42 }))).toThrow(/unknown frame/i); + expect(() => decode(JSON.stringify({}))).toThrow(/unknown frame/i); + }); +}); + +describe('protocol versioning', () => { + it('carries the protocol version on the handshake frames', () => { + const hello = decode(encode({ type: 'hello', v: V, secret: 's' })); + const manifest = decode(encode({ type: 'manifest', v: V, scopes: [], routes: [] })); + + expect(hello).toMatchObject({ v: V }); + expect(manifest).toMatchObject({ v: V }); + }); + + it('rejects a handshake frame with no version — an unversioned peer is not decodable', () => { + expect(() => decode(JSON.stringify({ type: 'hello', secret: 's' }))).toThrow(/malformed hello/i); + expect(() => decode(JSON.stringify({ type: 'manifest', scopes: [], routes: [] }))).toThrow(/malformed manifest/i); + }); +}); + +describe('protocol field validation', () => { + // decode is the trust boundary: past it, teapot.ts feeds frames straight into + // resolveScope/resolveRoute. A bad shape must die here, not downstream. + it.each([ + ['hello without secret', { type: 'hello', v: V }], + ['hello with non-string secret', { type: 'hello', v: V, secret: 42 }], + ['manifest with non-array scopes', { type: 'manifest', v: V, scopes: 'nope', routes: [] }], + ['rpc-req without id', { type: 'rpc-req', kind: 'scope', name: 'auth', ctx: env }], + ['rpc-req without ctx', { type: 'rpc-req', id: '1', kind: 'scope', name: 'auth' }], + ['rpc-req with unknown kind', { type: 'rpc-req', id: '1', kind: 'bogus', name: 'auth', ctx: env }], + ['rpc-req without name', { type: 'rpc-req', id: '1', kind: 'scope', ctx: env }], + ['rpc-res without id', { type: 'rpc-res', ok: true, result: 1 }], + ['rpc-res with non-boolean ok', { type: 'rpc-res', id: '1', ok: 'yes' }], + ['rpc-res error without an error payload', { type: 'rpc-res', id: '1', ok: false }], + ])('rejects %s', (_label, frame) => { + expect(() => decode(JSON.stringify(frame))).toThrow(/malformed/i); + }); + + it('accepts a valid rpc-req unchanged', () => { + const frame: Frame = { type: 'rpc-req', id: '1', kind: 'route', name: '/u/:id', ctx: env }; + + expect(decode(encode(frame))).toEqual(frame); + }); }); diff --git a/test/mesh/teapot.test.ts b/test/mesh/teapot.test.ts index 3ed2746..b2194ce 100644 --- a/test/mesh/teapot.test.ts +++ b/test/mesh/teapot.test.ts @@ -1,7 +1,9 @@ import { describe, it, expect, vi } from 'vitest'; import { EventEmitter } from 'events'; import { buildManifest, createMeshControl } from '../../src/mesh/teapot'; -import { encode, decode } from '../../src/mesh/protocol'; +import { encode, decode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol'; + +const V = MESH_PROTOCOL_VERSION; import { Unauthorized } from '../../src/signals'; const fakeWs = () => { @@ -36,15 +38,33 @@ describe('createMeshControl', () => { it('rejects a bad secret and closes', () => { const ws = fakeWs(); make().handle(ws); - ws.emit('message', encode({ type: 'hello', secret: 'wrong' })); + ws.emit('message', encode({ type: 'hello', v: V, secret: 'wrong' })); expect(ws.close).toHaveBeenCalledWith(1008); expect(ws.sent).toEqual([]); }); - it('answers a good hello with the manifest', () => { + it('answers a good hello with the manifest, stamped with the protocol version', () => { const ws = fakeWs(); make().handle(ws); - ws.emit('message', encode({ type: 'hello', secret: 'good' })); - expect(ws.sent[0]).toMatchObject({ type: 'manifest', scopes: manifest.scopes }); + ws.emit('message', encode({ type: 'hello', v: V, secret: 'good' })); + expect(ws.sent[0]).toMatchObject({ type: 'manifest', v: V, scopes: manifest.scopes }); + }); + + it('rejects a version-skewed peer before checking its secret, naming both versions', () => { + const ws = fakeWs(); make().handle(ws); + // correct secret, wrong protocol: must still be refused — and not as an auth failure + ws.emit('message', encode({ type: 'hello', v: V + 1, secret: 'good' } as any)); + expect(ws.sent).toEqual([]); + const [code, reason] = ws.close.mock.calls[0]; + expect(code).toBe(1008); + expect(reason).toContain(String(V)); + expect(reason).toContain(String(V + 1)); + }); + + it('refuses a version-skewed peer even when its secret is also wrong', () => { + const ws = fakeWs(); make().handle(ws); + ws.emit('message', encode({ type: 'hello', v: V + 1, secret: 'wrong' } as any)); + expect(ws.sent).toEqual([]); + expect(ws.close).toHaveBeenCalled(); }); it('does NOT process rpc before handshake', async () => { @@ -56,7 +76,7 @@ describe('createMeshControl', () => { it('resolves an exported scope after handshake', async () => { const ws = fakeWs(); make().handle(ws); - ws.emit('message', encode({ type: 'hello', secret: 'good' })); + ws.emit('message', encode({ type: 'hello', v: V, secret: 'good' })); ws.emit('message', encode({ type: 'rpc-req', id: '7', kind: 'scope', name: 'config', ctx: {} as any })); await new Promise((r) => setTimeout(r, 5)); expect(ws.sent.find((f: any) => f.type === 'rpc-res')).toEqual({ type: 'rpc-res', id: '7', ok: true, result: { resolved: 'config' } }); @@ -64,7 +84,7 @@ describe('createMeshControl', () => { it('rejects an unexported scope', async () => { const ws = fakeWs(); make().handle(ws); - ws.emit('message', encode({ type: 'hello', secret: 'good' })); + ws.emit('message', encode({ type: 'hello', v: V, secret: 'good' })); ws.emit('message', encode({ type: 'rpc-req', id: '8', kind: 'scope', name: 'secretsvc', ctx: {} as any })); await new Promise((r) => setTimeout(r, 5)); const res: any = ws.sent.find((f: any) => f.type === 'rpc-res'); @@ -75,7 +95,7 @@ describe('createMeshControl', () => { it('propagates a thrown HttpError status in the error frame', async () => { const ws = fakeWs(); make({ resolveScope: async () => { throw new Unauthorized('nope'); } }).handle(ws); - ws.emit('message', encode({ type: 'hello', secret: 'good' })); + ws.emit('message', encode({ type: 'hello', v: V, secret: 'good' })); ws.emit('message', encode({ type: 'rpc-req', id: '9', kind: 'scope', name: 'config', ctx: {} as any })); await new Promise((r) => setTimeout(r, 5)); const res: any = ws.sent.find((f: any) => f.type === 'rpc-res'); From 87772868abaf218f57401f307dadffef2bb167ad Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 15 Jul 2026 14:53:07 -0500 Subject: [PATCH 05/13] refactor(mesh): import node:crypto explicitly in the teapot MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit safeEqual guards the mesh shared secret and reached for Buffer + timingSafeEqual through a bare 'crypto' specifier, leaving resolution to Deno/Bun node-compat heuristics. Name the builtin explicitly — the authentication path should not depend on which compat layer happens to answer. Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Task 2 Signed-off-by: Diego Resendez --- src/mesh/teapot.ts | 90 +++++++++++++++++++++++++++++----------------- 1 file changed, 57 insertions(+), 33 deletions(-) diff --git a/src/mesh/teapot.ts b/src/mesh/teapot.ts index 6561bbf..f453633 100644 --- a/src/mesh/teapot.ts +++ b/src/mesh/teapot.ts @@ -1,5 +1,9 @@ -import crypto from 'crypto'; +// node: prefix, not a bare specifier: this is the mesh auth path, and on Deno/Bun a bare +// 'crypto' leans on node-compat resolution heuristics. Buffer + timingSafeEqual resolve +// under node-compat on both; edge/workerd is out of scope (see the cross-runtime spec). +import crypto from 'node:crypto'; import type { Bus } from '../bus'; +import type { WsSocket } from '../http/ws-core'; import type { ResponseShape } from '../pipeline'; import { isHttpError } from '../signals'; import { @@ -62,15 +66,15 @@ function notExported(name: string): Error { * The version is checked *before* the secret: a skewed peer is not an auth failure, and telling it * "wrong secret" would send its operator hunting the wrong bug. */ -function handleHandshake(ws: any, frame: Frame, deps: MeshControlDeps): boolean { +function handleHandshake(socket: WsSocket, frame: Frame, deps: MeshControlDeps): boolean { if (frame.type !== 'hello') { - ws.close(1008); + socket.close(1008); return false; } if (frame.v !== MESH_PROTOCOL_VERSION) { - ws.close( + socket.close( 1008, `mesh protocol version mismatch: peer speaks v${frame.v}, this teapot speaks v${MESH_PROTOCOL_VERSION}`, ); @@ -79,12 +83,12 @@ function handleHandshake(ws: any, frame: Frame, deps: MeshControlDeps): boolean } if (!safeEqual(frame.secret, deps.secret)) { - ws.close(1008); + socket.close(1008); return false; } - ws.send( + socket.send( encode({ type: 'manifest', v: MESH_PROTOCOL_VERSION, @@ -119,7 +123,7 @@ function resolveRpc( /** Serve one authenticated rpc-req: resolve it and frame the ok/error response back to the peer. */ async function handleRpc( - ws: any, + socket: WsSocket, frame: RpcReqFrame, deps: MeshControlDeps, exportedScopes: Set, @@ -130,44 +134,64 @@ async function handleRpc( try { const result = await resolveRpc(frame, deps, exportedScopes, exportedRoutes); - ws.send(encode({ type: 'rpc-res', id, ok: true, result })); + socket.send(encode({ type: 'rpc-res', id, ok: true, result })); } catch (err) { const status = isHttpError(err) ? err.status : ((err as any)?.status ?? 500); deps.bus?.emit('mesh:rpc:error', { name, error: err }); - ws.send(encode({ type: 'rpc-res', id, ok: false, error: { message: (err as Error).message, status } })); + socket.send(encode({ type: 'rpc-res', id, ok: false, error: { message: (err as Error).message, status } })); } } -/** Build a WebSocket handler that authenticates peers and serves scope/route RPCs from the manifest. */ -export function createMeshControl(deps: MeshControlDeps): { path: string; handle: (ws: any) => void } { +/** Drive one control connection to completion: handshake, then serve RPCs until the socket ends. */ +async function serveFrames( + socket: WsSocket, + deps: MeshControlDeps, + exportedScopes: Set, + exportedRoutes: Set, +): Promise { + let authed = false; + + try { + for await (const data of socket.inbound) { + let frame: Frame; + + try { + frame = decode(String(data)); + } catch { + continue; // undecodable frames are ignored, as before + } + + if (!authed) { + authed = handleHandshake(socket, frame, deps); + continue; + } + + if (frame.type !== 'rpc-req') continue; + + // deliberately not awaited: RPCs overlap, exactly as they did under the `ws.on('message')` + // listener. The id-keyed `pending` map on the peer exists to allow in-flight concurrency — + // awaiting here would silently serialize every mesh call. + void handleRpc(socket, frame, deps, exportedScopes, exportedRoutes); + } + } catch { + /* socket failed; the disconnect emit below is the same signal a clean close gives */ + } finally { + deps.bus?.emit('mesh:disconnect', { name: 'teapot' }); + } +} + +/** Build a control handler that authenticates peers and serves scope/route RPCs from the manifest. */ +export function createMeshControl(deps: MeshControlDeps): { path: string; handle: (socket: WsSocket) => void } { const exportedScopes = new Set(deps.manifest.scopes.map((scope) => scope.token)); const exportedRoutes = new Set(deps.manifest.routes.map((route) => `${route.method} ${route.pattern}`)); return { path: MESH_CONTROL_PATH, - handle(ws: any) { - let authed = false; - ws.on('message', async (data: unknown) => { - let frame: Frame; - - try { - frame = decode(String(data)); - } catch { - return; - } - - if (!authed) { - authed = handleHandshake(ws, frame, deps); - - return; - } - - if (frame.type !== 'rpc-req') return; - - await handleRpc(ws, frame, deps, exportedScopes, exportedRoutes); - }); - ws.on('close', () => deps.bus?.emit('mesh:disconnect', { name: 'teapot' })); + handle(socket: WsSocket) { + // `channel` is fan-out and subscribes when the async iterator is created, which + // `for await` does synchronously — so the loop is live before any frame can arrive. + void serveFrames(socket, deps, exportedScopes, exportedRoutes); }, }; } From 71b59e7c25b8a9da1bda1d693f06123a3a58c22d Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 15 Jul 2026 14:53:09 -0500 Subject: [PATCH 06/13] refactor(mesh): serve the control channel over the neutral WsSocket MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/http/types.ts | 9 +- src/http/ws.ts | 4 +- test/mesh/teapot.test.ts | 173 +++++++++++++++++++++++++++------------ 3 files changed, 128 insertions(+), 58 deletions(-) diff --git a/src/http/types.ts b/src/http/types.ts index 5e5f444..4526f69 100644 --- a/src/http/types.ts +++ b/src/http/types.ts @@ -1,9 +1,8 @@ -import type http from 'http'; import type { Transport } from '../metadata'; import type { PipelineResult } from '../pipeline'; import type { ErrorRenderer } from '../transformers'; import type { TlsOptions, SecurityOptions, CorsOptions } from '../security'; -import type { WsRequest } from './ws-core'; +import type { WsRequest, WsSocket } from './ws-core'; import type { StaticResolver } from '../views'; /** Per-request size and timeout ceilings applied by the server. */ @@ -74,5 +73,9 @@ export interface WsRouteDef { /** Hook for a mesh gateway to take over WebSocket upgrades on a fixed path. */ export interface MeshControl { path: string; - handle(ws: any, req: http.IncomingMessage): void; + /** + * Serves one control connection over the neutral socket — the same capability every other ws + * consumer takes, so Node (via `nodeSocket`) and Deno/Bun (via `app.upgrade`) both feed it. + */ + handle(socket: WsSocket): void; } diff --git a/src/http/ws.ts b/src/http/ws.ts index 2f34b8a..1665ada 100644 --- a/src/http/ws.ts +++ b/src/http/ws.ts @@ -38,7 +38,9 @@ function handleMeshUpgrade( return true; } - wss.handleUpgrade(req, socket, head, (ws: any) => meshControl.handle(ws, req)); + // nodeSocket, not the raw ws: the control channel is the last consumer that spoke the + // `ws` EventEmitter API directly. It now takes the same neutral socket every route does. + wss.handleUpgrade(req, socket, head, (ws: any) => meshControl.handle(nodeSocket(ws))); return true; } diff --git a/test/mesh/teapot.test.ts b/test/mesh/teapot.test.ts index b2194ce..50f92fb 100644 --- a/test/mesh/teapot.test.ts +++ b/test/mesh/teapot.test.ts @@ -1,17 +1,45 @@ import { describe, it, expect, vi } from 'vitest'; -import { EventEmitter } from 'events'; import { buildManifest, createMeshControl } from '../../src/mesh/teapot'; import { encode, decode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol'; - -const V = MESH_PROTOCOL_VERSION; +import { channel } from '../../src/channel'; +import type { WsSocket } from '../../src/http/ws-core'; import { Unauthorized } from '../../src/signals'; -const fakeWs = () => { - const ws: any = new EventEmitter(); - ws.sent = []; - ws.send = (s: string) => ws.sent.push(decode(s)); - ws.close = vi.fn(); - return ws; +const V = MESH_PROTOCOL_VERSION; + +/** Lets the control loop drain: it consumes `inbound` asynchronously and does not await RPCs. */ +const settle = () => new Promise((resolve) => setTimeout(resolve, 5)); + +/** + * A fake neutral WsSocket — the same capability `nodeSocket` builds on Node and `app.upgrade` + * hands over on Deno/Bun. `close` also ends `inbound`, mirroring a real socket's close. + */ +const fakeSocket = () => { + const inbound = channel(); + const ac = new AbortController(); + const sent: any[] = []; + const close = vi.fn((_code?: number, _reason?: string) => { + inbound.close(); + ac.abort(); + }); + const socket: WsSocket = { + inbound, + abort: ac.signal, + isOpen: true, + send: (data: string) => { + sent.push(decode(data)); + }, + close, + terminate: () => ac.abort(), + }; + + /** Deliver a frame the way a peer would, then let the loop process it. */ + const deliver = async (frame: unknown) => { + inbound.push(encode(frame as never)); + await settle(); + }; + + return { socket, sent, close, deliver, inbound }; }; describe('buildManifest', () => { @@ -24,81 +52,118 @@ describe('buildManifest', () => { }); describe('createMeshControl', () => { - const manifest = buildManifest({ providers: ['config'], steps: ['auth'], routes: [{ method: 'GET', pattern: '/u/:id' }] }); - const make = (over: Partial[0]> = {}) => createMeshControl({ - secret: 'good', manifest, - resolveScope: async (name) => ({ resolved: name }), - resolveRoute: async () => ({ status: 200, headers: {}, body: 'route-body' }), - ...over, + const manifest = buildManifest({ + providers: ['config'], + steps: ['auth'], + routes: [{ method: 'GET', pattern: '/u/:id' }], }); + const make = (over: Partial[0]> = {}) => + createMeshControl({ + secret: 'good', + manifest, + resolveScope: async (name) => ({ resolved: name }), + resolveRoute: async () => ({ status: 200, headers: {}, body: 'route-body' }), + ...over, + }); it('exposes the reserved control path', () => { expect(make().path).toBe('/__mesh__/control'); }); - it('rejects a bad secret and closes', () => { - const ws = fakeWs(); make().handle(ws); - ws.emit('message', encode({ type: 'hello', v: V, secret: 'wrong' })); - expect(ws.close).toHaveBeenCalledWith(1008); - expect(ws.sent).toEqual([]); + it('rejects a bad secret and closes', async () => { + const t = fakeSocket(); + make().handle(t.socket); + await t.deliver({ type: 'hello', v: V, secret: 'wrong' }); + expect(t.close).toHaveBeenCalledWith(1008); + expect(t.sent).toEqual([]); }); - it('answers a good hello with the manifest, stamped with the protocol version', () => { - const ws = fakeWs(); make().handle(ws); - ws.emit('message', encode({ type: 'hello', v: V, secret: 'good' })); - expect(ws.sent[0]).toMatchObject({ type: 'manifest', v: V, scopes: manifest.scopes }); + it('answers a good hello with the manifest, stamped with the protocol version', async () => { + const t = fakeSocket(); + make().handle(t.socket); + await t.deliver({ type: 'hello', v: V, secret: 'good' }); + expect(t.sent[0]).toMatchObject({ type: 'manifest', v: V, scopes: manifest.scopes }); }); - it('rejects a version-skewed peer before checking its secret, naming both versions', () => { - const ws = fakeWs(); make().handle(ws); + it('rejects a version-skewed peer before checking its secret, naming both versions', async () => { + const t = fakeSocket(); + make().handle(t.socket); // correct secret, wrong protocol: must still be refused — and not as an auth failure - ws.emit('message', encode({ type: 'hello', v: V + 1, secret: 'good' } as any)); - expect(ws.sent).toEqual([]); - const [code, reason] = ws.close.mock.calls[0]; + await t.deliver({ type: 'hello', v: V + 1, secret: 'good' }); + expect(t.sent).toEqual([]); + const [code, reason] = t.close.mock.calls[0]; expect(code).toBe(1008); expect(reason).toContain(String(V)); expect(reason).toContain(String(V + 1)); }); - it('refuses a version-skewed peer even when its secret is also wrong', () => { - const ws = fakeWs(); make().handle(ws); - ws.emit('message', encode({ type: 'hello', v: V + 1, secret: 'wrong' } as any)); - expect(ws.sent).toEqual([]); - expect(ws.close).toHaveBeenCalled(); + it('refuses a version-skewed peer even when its secret is also wrong', async () => { + const t = fakeSocket(); + make().handle(t.socket); + await t.deliver({ type: 'hello', v: V + 1, secret: 'wrong' }); + expect(t.sent).toEqual([]); + expect(t.close).toHaveBeenCalled(); }); it('does NOT process rpc before handshake', async () => { - const ws = fakeWs(); make().handle(ws); - ws.emit('message', encode({ type: 'rpc-req', id: '1', kind: 'scope', name: 'config', ctx: {} as any })); - await new Promise((r) => setTimeout(r, 5)); - expect(ws.sent).toEqual([]); + const t = fakeSocket(); + make().handle(t.socket); + await t.deliver({ type: 'rpc-req', id: '1', kind: 'scope', name: 'config', ctx: {} }); + expect(t.sent).toEqual([]); }); it('resolves an exported scope after handshake', async () => { - const ws = fakeWs(); make().handle(ws); - ws.emit('message', encode({ type: 'hello', v: V, secret: 'good' })); - ws.emit('message', encode({ type: 'rpc-req', id: '7', kind: 'scope', name: 'config', ctx: {} as any })); - await new Promise((r) => setTimeout(r, 5)); - expect(ws.sent.find((f: any) => f.type === 'rpc-res')).toEqual({ type: 'rpc-res', id: '7', ok: true, result: { resolved: 'config' } }); + const t = fakeSocket(); + make().handle(t.socket); + await t.deliver({ type: 'hello', v: V, secret: 'good' }); + await t.deliver({ type: 'rpc-req', id: '7', kind: 'scope', name: 'config', ctx: {} }); + expect(t.sent.find((f: any) => f.type === 'rpc-res')).toEqual({ + type: 'rpc-res', + id: '7', + ok: true, + result: { resolved: 'config' }, + }); }); it('rejects an unexported scope', async () => { - const ws = fakeWs(); make().handle(ws); - ws.emit('message', encode({ type: 'hello', v: V, secret: 'good' })); - ws.emit('message', encode({ type: 'rpc-req', id: '8', kind: 'scope', name: 'secretsvc', ctx: {} as any })); - await new Promise((r) => setTimeout(r, 5)); - const res: any = ws.sent.find((f: any) => f.type === 'rpc-res'); + const t = fakeSocket(); + make().handle(t.socket); + await t.deliver({ type: 'hello', v: V, secret: 'good' }); + await t.deliver({ type: 'rpc-req', id: '8', kind: 'scope', name: 'secretsvc', ctx: {} }); + const res: any = t.sent.find((f: any) => f.type === 'rpc-res'); expect(res.ok).toBe(false); expect(res.error.status).toBe(403); }); it('propagates a thrown HttpError status in the error frame', async () => { - const ws = fakeWs(); - make({ resolveScope: async () => { throw new Unauthorized('nope'); } }).handle(ws); - ws.emit('message', encode({ type: 'hello', v: V, secret: 'good' })); - ws.emit('message', encode({ type: 'rpc-req', id: '9', kind: 'scope', name: 'config', ctx: {} as any })); - await new Promise((r) => setTimeout(r, 5)); - const res: any = ws.sent.find((f: any) => f.type === 'rpc-res'); + const t = fakeSocket(); + make({ + resolveScope: async () => { + throw new Unauthorized('nope'); + }, + }).handle(t.socket); + await t.deliver({ type: 'hello', v: V, secret: 'good' }); + await t.deliver({ type: 'rpc-req', id: '9', kind: 'scope', name: 'config', ctx: {} }); + const res: any = t.sent.find((f: any) => f.type === 'rpc-res'); expect(res).toMatchObject({ id: '9', ok: false, error: { message: 'nope', status: 401 } }); }); + + it('serves overlapping RPCs concurrently rather than head-of-line blocking', async () => { + // the loop must not await handleRpc: a slow call would otherwise stall every later one. + // fast is delivered second but resolves first, which can only happen if they overlap. + const t = fakeSocket(); + make({ + resolveScope: async (name) => { + if (name === 'config') await new Promise((r) => setTimeout(r, 30)); + return { resolved: name }; + }, + }).handle(t.socket); + await t.deliver({ type: 'hello', v: V, secret: 'good' }); + t.inbound.push(encode({ type: 'rpc-req', id: 'slow', kind: 'scope', name: 'config', ctx: {} as never })); + t.inbound.push(encode({ type: 'rpc-req', id: 'fast', kind: 'scope', name: 'auth', ctx: {} as never })); + await new Promise((r) => setTimeout(r, 60)); + + const ids = t.sent.filter((f: any) => f.type === 'rpc-res').map((f: any) => f.id); + expect(ids).toEqual(['fast', 'slow']); + }); }); From 0ea4db3fef22c6b821986d785f7fa77406413ac1 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 15 Jul 2026 15:00:04 -0500 Subject: [PATCH 07/13] feat(mesh): connect the teacup over a runtime-neutral WebSocket client MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/http/ws-adapter.ts | 46 ++++++++++++- src/mesh/link.ts | 150 ++++++++++++++++++++++++++--------------- test/mesh/link.test.ts | 28 +++++++- 3 files changed, 168 insertions(+), 56 deletions(-) diff --git a/src/http/ws-adapter.ts b/src/http/ws-adapter.ts index 8e024c0..8f9307e 100644 --- a/src/http/ws-adapter.ts +++ b/src/http/ws-adapter.ts @@ -41,8 +41,8 @@ export interface EventfulSocket { send(data: string): void; close(code?: number, reason?: string): void; addEventListener( - type: 'message' | 'close' | 'error', - listener: (event: { data?: string | ArrayBuffer }) => void, + type: 'open' | 'message' | 'close' | 'error', + listener: (event: { data?: string | ArrayBuffer; error?: unknown }) => void, ): void; } @@ -107,6 +107,48 @@ export function neutralSocket( }; } +/** Constructs a host WebSocket *client*. Both the platform global and the `ws` package satisfy it. */ +export type SocketCtor = new (url: string) => EventfulSocket; + +/** + * The WebSocket client implementation: the platform global where it exists (Deno, Bun, and + * Node >= 22), else the `ws` optional peer — Node 18-21, our declared floor, has no global. + * + * Both expose the same `addEventListener` API and deliver text frames as `event.data` strings, + * so one bridge covers both. That is verified rather than assumed: `ws` implements the + * browser-compatible event API alongside its EventEmitter one. + */ +export function loadWebSocketCtor(): SocketCtor { + const platform = (globalThis as { WebSocket?: SocketCtor }).WebSocket; + + if (platform) return platform; + + // eslint-disable-next-line @typescript-eslint/no-require-imports + return require('ws') as SocketCtor; +} + +/** + * Opens a client connection and wraps it as a neutral {@link WsSocket}. `opened` resolves once + * the socket is live (the caller's cue to send its first frame) and rejects if it never opens. + * + * `Ctor` is injectable so both implementations can be exercised on one runtime — otherwise CI + * on a single Node version would silently cover only one of the two paths. + */ +export function connectSocket( + url: string, + Ctor: SocketCtor = loadWebSocketCtor(), +): { socket: WsSocket; opened: Promise } { + const host = new Ctor(url); + // registered before eventSocket's own error listener, so a connect failure rejects `opened` + // with the host's real error rather than eventSocket's generic one + const opened = new Promise((resolve, reject) => { + host.addEventListener('open', () => resolve()); + host.addEventListener('error', (event) => reject(event?.error ?? new Error(`websocket error: ${url}`))); + }); + + return { socket: eventSocket(host), opened }; +} + /** * Runs the ws lifecycle, closing with 1011 if it rejects. `app.upgrade` can reject *before* * `runWsConnection`'s own try/catch (mesh-before-listen, provider boot failure); unguarded, diff --git a/src/mesh/link.ts b/src/mesh/link.ts index caa6f6c..a2ce38e 100644 --- a/src/mesh/link.ts +++ b/src/mesh/link.ts @@ -1,5 +1,7 @@ import type { Bus } from '../bus'; import { HttpError } from '../signals'; +import { connectSocket, type SocketCtor } from '../http/ws-adapter'; +import type { WsSocket } from '../http/ws-core'; import { encode, decode, MESH_PROTOCOL_VERSION, type Manifest, type RequestEnvelope, type Frame } from './protocol'; /** Client handle to a remote mesh server: its manifest, an RPC caller, and a close(). */ @@ -16,12 +18,6 @@ type PendingEntry = { timer: ReturnType; }; -function loadWs(): any { - // lazy/optional, like streams; the ws CJS export is the WebSocket class - // eslint-disable-next-line @typescript-eslint/no-require-imports - return require('ws'); -} - /** Reject and clear every in-flight RPC — used when the link closes. */ function rejectAllPending(pending: Map, reason: string): void { for (const [, entry] of pending) { @@ -34,7 +30,7 @@ function rejectAllPending(pending: Map, reason: string): v /** Register one RPC in `pending` by id, send its request, and reject it on timeout. */ function sendRpc( - ws: any, + socket: WsSocket, pending: Map, id: string, kind: 'scope' | 'route', @@ -49,12 +45,12 @@ function sendRpc( }, timeoutMs); pending.set(id, { resolve: resolveCall, reject: rejectCall, timer }); - ws.send(encode({ type: 'rpc-req', id, kind, name, ctx })); + socket.send(encode({ type: 'rpc-req', id, kind, name, ctx })); }); } /** Assemble the client-facing Link once the manifest arrives. */ -function buildLink(ws: any, pending: Map, manifest: Manifest, timeoutMs: number): Link { +function buildLink(socket: WsSocket, pending: Map, manifest: Manifest, timeoutMs: number): Link { // ids only need to be unique within this link: `pending` is per-connection, so a // per-link counter suffices (no module-global sequence, no test-order coupling). let counter = 0; @@ -64,10 +60,10 @@ function buildLink(ws: any, pending: Map, manifest: Manife rpc(kind, name, ctx) { const id = String(counter++); - return sendRpc(ws, pending, id, kind, name, ctx, timeoutMs); + return sendRpc(socket, pending, id, kind, name, ctx, timeoutMs); }, close() { - ws.close(); + socket.close(); }, }; } @@ -91,60 +87,108 @@ function settleRpcResponse( } } -/** Open a WebSocket link to a mesh server, handshake with `secret`, and resolve once its manifest arrives. */ -export function connectLink(args: { url: string; secret: string; timeoutMs?: number; bus?: Bus }): Promise { +/** Handle for the in-flight handshake, so the frame loop can settle `connectLink`'s promise. */ +interface Handshake { + url: string; + socket: WsSocket; + pending: Map; + timeoutMs: number; + bus?: Bus; + resolve: (link: Link) => void; + reject: (error: unknown) => void; + onManifest: () => void; +} + +/** Settle the handshake from a `manifest` frame: refuse a version mismatch, else build the Link. */ +function settleManifest(frame: Extract, hs: Handshake): void { + if (frame.v !== MESH_PROTOCOL_VERSION) { + hs.socket.close(); + hs.reject( + new Error( + `mesh protocol version mismatch at ${hs.url}: teapot speaks v${frame.v}, this teacup speaks v${MESH_PROTOCOL_VERSION}`, + ), + ); + + return; + } + + hs.onManifest(); + hs.bus?.emit('mesh:connect', { name: hs.url }); + hs.resolve(buildLink(hs.socket, hs.pending, { scopes: frame.scopes, routes: frame.routes }, hs.timeoutMs)); +} + +/** Consume the link's inbound frames until it closes, settling the handshake then each RPC. */ +async function readFrames(hs: Handshake): Promise { + for await (const data of hs.socket.inbound) { + let frame: Frame; + + try { + frame = decode(String(data)); + } catch { + continue; // undecodable frames are ignored + } + + if (frame.type === 'manifest') settleManifest(frame, hs); + else if (frame.type === 'rpc-res') settleRpcResponse(hs.pending, frame, hs.bus); + } +} + +/** + * Open a WebSocket link to a mesh server, handshake with `secret`, and resolve once its manifest + * arrives. `Ctor` is injectable to exercise both client implementations on a single runtime. + */ +export function connectLink(args: { + url: string; + secret: string; + timeoutMs?: number; + bus?: Bus; + Ctor?: SocketCtor; +}): Promise { const timeoutMs = args.timeoutMs ?? 30_000; - const WS = loadWs(); - const ws = new WS(args.url); + const { socket, opened } = connectSocket(args.url, args.Ctor ?? undefined); const pending = new Map(); - let manifest: Manifest | undefined; + let manifest = false; return new Promise((resolve, reject) => { const connectTimer = setTimeout(() => { - ws.close(); + socket.close(); reject(new Error(`mesh connect timeout: ${args.url}`)); }, timeoutMs); - ws.on('open', () => ws.send(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: args.secret }))); - ws.on('error', (error: unknown) => reject(error)); - ws.on('close', () => { - clearTimeout(connectTimer); - args.bus?.emit('mesh:disconnect', { name: args.url }); - rejectAllPending(pending, 'mesh link closed'); - if (!manifest) reject(new Error(`mesh handshake failed: ${args.url}`)); - }); - - ws.on('message', (data: unknown) => { - let frame: Frame; - - try { - frame = decode(String(data)); - } catch { - return; - } - - if (frame.type === 'manifest') { + const hs: Handshake = { + url: args.url, + socket, + pending, + timeoutMs, + bus: args.bus, + resolve, + reject, + onManifest: () => { + manifest = true; clearTimeout(connectTimer); + }, + }; - if (frame.v !== MESH_PROTOCOL_VERSION) { - ws.close(); - reject( - new Error( - `mesh protocol version mismatch at ${args.url}: teapot speaks v${frame.v}, this teacup speaks v${MESH_PROTOCOL_VERSION}`, - ), - ); - return; - } + opened.then( + () => socket.send(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: args.secret })), + (error) => reject(error), + ); - manifest = { scopes: frame.scopes, routes: frame.routes }; - args.bus?.emit('mesh:connect', { name: args.url }); - resolve(buildLink(ws, pending, manifest, timeoutMs)); - return; - } + // abort fires on close *and* on error (see eventSocket), covering both paths the raw + // 'close' listener used to: a refused handshake and a dropped link. + socket.abort.addEventListener( + 'abort', + () => { + clearTimeout(connectTimer); + args.bus?.emit('mesh:disconnect', { name: args.url }); + rejectAllPending(pending, 'mesh link closed'); + if (!manifest) reject(new Error(`mesh handshake failed: ${args.url}`)); + }, + { once: true }, + ); - if (frame.type === 'rpc-res') { - settleRpcResponse(pending, frame, args.bus); - } + void readFrames(hs).catch(() => { + /* inbound failed; the abort listener above reports it */ }); }); } diff --git a/test/mesh/link.test.ts b/test/mesh/link.test.ts index 888aafd..d80965e 100644 --- a/test/mesh/link.test.ts +++ b/test/mesh/link.test.ts @@ -1,6 +1,7 @@ import { describe, it, expect } from 'vitest'; -import { WebSocketServer } from 'ws'; +import WS, { WebSocketServer } from 'ws'; import { connectLink } from '../../src/mesh/link'; +import { loadWebSocketCtor, type SocketCtor } from '../../src/http/ws-adapter'; import { encode, decode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol'; const V = MESH_PROTOCOL_VERSION; @@ -53,6 +54,31 @@ function startSkewedTeapot() { return { url: `ws://127.0.0.1:${port}/__mesh__/control`, close: () => wss.close() }; } +/** + * Both client implementations, exercised on whatever Node runs the suite. `ws` is always in the + * list: it is the Node 18-21 path, and on a modern CI the platform global would otherwise be the + * only one ever covered — the fallback would rot unnoticed until someone ran the declared floor. + */ +const platform = (globalThis as { WebSocket?: SocketCtor }).WebSocket; +const CTORS: [string, SocketCtor][] = [['the ws package (Node < 22 path)', WS as unknown as SocketCtor]]; +if (platform) CTORS.push(['the platform global WebSocket', platform]); + +describe('WebSocket client implementations', () => { + it.each(CTORS)('handshakes and serves RPC over %s', async (_label, Ctor) => { + const t = startTeapot(); + const link = await connectLink({ url: t.url, secret: 'good', Ctor }); + + expect(link.manifest.scopes).toEqual([{ token: 'auth', scope: 'request' }]); + expect(await link.rpc('scope', 'auth', env)).toEqual({ got: 'auth' }); + link.close(); + t.close(); + }); + + it('prefers the platform global when it exists, else falls back to the ws package', () => { + expect(loadWebSocketCtor()).toBe(platform ?? (WS as unknown as SocketCtor)); + }); +}); + describe('connectLink', () => { it('sends its protocol version in the hello', async () => { const seen: any[] = []; From db9a7712afe1b7b7ee5b98ba105bd401171786a0 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 15 Jul 2026 15:04:49 -0500 Subject: [PATCH 08/13] feat(mesh): boot the mesh graph from the app boot gate, not listen() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/app/index.ts | 85 ++++++++++++------------ src/app/introspect.ts | 15 ++++- test/fetch.test.ts | 27 ++++++-- test/mesh/fetch-boot.test.ts | 123 +++++++++++++++++++++++++++++++++++ 4 files changed, 201 insertions(+), 49 deletions(-) create mode 100644 test/mesh/fetch-boot.test.ts diff --git a/src/app/index.ts b/src/app/index.ts index 13ae295..c320650 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -112,10 +112,13 @@ export function createApp(opts: { // For each route, resolve which providers/steps feed it via topo order. // MVP: every route depends on every declared step + provider in the app graph. - // For mesh apps, finalize is DEFERRED to listen() so remote scopes can join the graph first. + // For mesh apps, finalize is DEFERRED to the boot gate so remote scopes can join the graph + // first — connecting to teapots is network I/O, so it cannot happen during construction. let orderedProviders: GraphNode[] = []; let orderedSteps: GraphNode[] = []; let booted = false; + let remoteRoutes: RouteDef[] = []; + const meshLinks: Link[] = []; const finalize = (): void => { ({ orderedProviders, orderedSteps } = finalizeGraph(registry)); @@ -124,6 +127,16 @@ export function createApp(opts: { if (!opts.mesh) finalize(); + // mesh teacup: connect remote teapots and splice their scopes/routes in, then finalize. + const prepareGraph = async (): Promise => { + if (!opts.mesh || booted) return; + + const spliced = await spliceRemoteScopes(opts.mesh, bus, registry); + remoteRoutes = spliced.remoteRoutes; + meshLinks.push(...spliced.meshLinks); + finalize(); + }; + const inspect = (routePath: string): InspectLine[] => inspectRoute(routePlans, routePath, booted); const graph = (): GraphView => buildGraphView(providerNodes, stepNodes, routePlans, booted); const explain = (routePath: string): Explain => explainRoute(routePlans, routePath, booted); @@ -150,14 +163,15 @@ export function createApp(opts: { const providedSeed = (plan: RoutePlan) => seedProviders(container, plan); const planSteps = (plan: RoutePlan) => compilePlanSteps(runners, plan); - // Boots app-scope providers exactly once, however first triggered (app.fetch or listen()); calling - // both never double-boots (which would re-run provider factories and their side effects). - const bootAppProviders = makeProviderBooter( + // Boots exactly once, however first triggered (app.fetch, app.upgrade or listen()); calling + // several never double-boots (which would re-run provider factories and their side effects). + const bootApp = makeAppBooter( registry, opts.overrides, () => orderedProviders, { runners, container, providerMeta, bus }, degradedProviders, + prepareGraph, ); const staticResolver = opts.static ? buildStaticResolver(opts.static) : undefined; @@ -173,36 +187,25 @@ export function createApp(opts: { static: staticResolver, }; const fetchFn = buildAppFetch( - () => booted, routePlans, { providedSeed, planSteps, bus, onError: opts.onError }, fetchOpts, - bootAppProviders, + bootApp, devRoutes, + () => remoteRoutes, ); const upgradeFn = buildAppUpgrade( - () => booted, routePlans, { providedSeed, planSteps, bus, onError: opts.onError }, streams, - bootAppProviders, + bootApp, ); const listen = async (port: number): Promise => { const deps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError }; - // mesh teacup: connect remote teapots, splice their scopes/routes into the graph, then finalize - let remoteRoutes: RouteDef[] = []; - const meshLinks: Link[] = []; - - if (opts.mesh && !booted) { - const spliced = await spliceRemoteScopes(opts.mesh, bus, registry); - remoteRoutes = spliced.remoteRoutes; - meshLinks.push(...spliced.meshLinks); - finalize(); - } - - await bootAppProviders(); + // the same gate app.fetch uses: splices remote mesh scopes, finalizes, boots providers + await bootApp(); const meshControl = buildMeshControl(opts.mesh, registry, { container, @@ -547,11 +550,13 @@ async function bootProviders( } /** - * Returns a memoized boot function: applies overrides and boots app-scope providers exactly once, - * however first triggered — {@link buildAppFetch}'s handler or `listen()` may both call it, and the - * memoization guarantees only the first call actually runs (and warns about) the boot sequence. + * Returns a memoized boot function: prepares the graph, applies overrides and boots app-scope + * providers exactly once, however first triggered — `app.fetch`, `app.upgrade` and `listen()` may + * all call it, and the memoization guarantees only the first runs the sequence. This is the single + * place an app becomes ready, which is what lets a mesh app boot on any runtime rather than only + * where `listen()` (a Node http.Server) can be built. */ -function makeProviderBooter( +function makeAppBooter( registry: Registry, overrides: Record | undefined, getOrderedProviders: () => GraphNode[], @@ -562,10 +567,13 @@ function makeProviderBooter( bus: Bus; }, degradedProviders: string[], + /** Splices remote mesh scopes in and finalizes the graph. Must precede providers: remote nodes join the topo sort. */ + prepareGraph: () => Promise, ): () => Promise { let bootPromise: Promise | undefined; const runBoot = async (): Promise => { + await prepareGraph(); applyOverrides(overrides, registry); degradedProviders.length = 0; degradedProviders.push(...(await bootProviders(getOrderedProviders(), deps))); @@ -691,29 +699,27 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps /** * Builds `app.fetch`: a Web-Standards handler over the same route table `listen()` uses, so * `Deno.serve(app.fetch)` / `Bun.serve({ fetch: app.fetch })` work without ever calling `listen()`. - * Non-mesh apps finalize eagerly, so `getBooted()` is already `true` and the route table is built - * on the very first call. Mesh apps defer finalize to `listen()` (remote scopes must splice into the - * graph first): `getBooted` reads the outer `booted` flag *live* on every call — exactly like - * `explain()`/`graph()`/`inspect()` do — so the returned function throws until `listen()` finalizes, - * then starts working from the next call on, without ever needing to be rebuilt. + * The boot is awaited *before* the route table is built: for a mesh app the table is not knowable + * until remote scopes have spliced in, and the boot is what does that. Both are memoized, so this + * costs one flag check per request after the first. */ function buildAppFetch( - getBooted: () => boolean, routePlans: RoutePlan[], deps: PipelineDeps, fetchOpts: HttpOptions, ensureBooted: () => Promise, devRoutes: () => RouteDef[], + getRemoteRoutes: () => RouteDef[], ): (request: Request) => Promise { let handler: ((request: Request) => Promise) | undefined; return async (request: Request): Promise => { + await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted + if (!handler) { - if (!getBooted()) throw new Error('fetch() unavailable before listen() for mesh apps'); - handler = buildFetch([...buildHttpRoutes(routePlans, [], deps), ...devRoutes()], fetchOpts); + handler = buildFetch([...buildHttpRoutes(routePlans, getRemoteRoutes(), deps), ...devRoutes()], fetchOpts); } - await ensureBooted(); // idempotent: no-op if listen() already booted the providers return handler(request); }; } @@ -722,12 +728,9 @@ function buildAppFetch( * Builds `app.upgrade`: the neutral WebSocket entry over the same route table `listen()` uses, so * Deno/Bun/edge adapters can drive ws connections without ever calling `listen()`. Node keeps its own * `server.on('upgrade')` path (see `attachWs`) and never calls this. - * Mirrors {@link buildAppFetch}'s finalize guard exactly: non-mesh apps finalize eagerly, so - * `getBooted()` is already `true` and the ws route table builds on the first call; mesh apps defer - * finalize to `listen()`, so this throws until `listen()` finalizes, then works from the next call on. + * Mirrors {@link buildAppFetch}: the boot is awaited before the ws route table is built. */ function buildAppUpgrade( - getBooted: () => boolean, routePlans: RoutePlan[], deps: PipelineDeps, streams: Set<() => void>, @@ -736,12 +739,10 @@ function buildAppUpgrade( let wsRoutes: WsRouteDef[] | undefined; return async (request: WsRequest, socket: WsSocket): Promise => { - if (!wsRoutes) { - if (!getBooted()) throw new Error('upgrade() unavailable before listen() for mesh apps'); - wsRoutes = buildWsRoutes(routePlans, deps); - } + await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted + + if (!wsRoutes) wsRoutes = buildWsRoutes(routePlans, deps); - await ensureBooted(); // idempotent: no-op if listen() already booted the providers const path = request.url.split('?')[0]; const route = matchWsRoute(wsRoutes, path); diff --git a/src/app/introspect.ts b/src/app/introspect.ts index 7607c3d..a85f937 100644 --- a/src/app/introspect.ts +++ b/src/app/introspect.ts @@ -4,7 +4,10 @@ import type { InspectLine, Explain, ExplainNode, RoutePlan } from './types'; /** Lists the provider/step/handler chain for a route, in execution order. */ export function inspectRoute(routePlans: RoutePlan[], routePath: string, booted: boolean): InspectLine[] { - if (!booted) throw new Error('inspect() unavailable before listen() for mesh apps'); + if (!booted) + throw new Error( + 'inspect() unavailable until a mesh app has booted — call listen(), or serve one request through app.fetch/app.upgrade, which splices the remote scopes in', + ); const plan = routePlans.find((candidate) => candidate.pattern === routePath); if (!plan) throw new Error(`no route: ${routePath}`); return [ @@ -25,7 +28,10 @@ export function buildGraphView( routePlans: RoutePlan[], booted: boolean, ): GraphView { - if (!booted) throw new Error('graph() unavailable before listen() for mesh apps'); + if (!booted) + throw new Error( + 'graph() unavailable until a mesh app has booted — call listen(), or serve one request through app.fetch/app.upgrade, which splices the remote scopes in', + ); return { nodes: [ ...providerNodes.map((node) => ({ @@ -54,7 +60,10 @@ export function buildGraphView( /** Explains a single route: its match criteria and the ordered chain with each node's needs/provides. */ export function explainRoute(routePlans: RoutePlan[], routePath: string, booted: boolean): Explain { - if (!booted) throw new Error('explain() unavailable before listen() for mesh apps'); + if (!booted) + throw new Error( + 'explain() unavailable until a mesh app has booted — call listen(), or serve one request through app.fetch/app.upgrade, which splices the remote scopes in', + ); const plan = routePlans.find((candidate) => candidate.pattern === routePath); if (!plan) throw new Error(`no route: ${routePath}`); const toExplainNode = (node: GraphNode, kind: 'provider' | 'step'): ExplainNode => ({ diff --git a/test/fetch.test.ts b/test/fetch.test.ts index 1d0373b..5505077 100644 --- a/test/fetch.test.ts +++ b/test/fetch.test.ts @@ -110,17 +110,36 @@ describe('app.fetch trustProxy gates x-forwarded-for', () => { }); }); -describe('app.fetch mesh gating (live `booted` read)', () => { - it('throws before listen() and starts working after listen() finalizes', async () => { +describe('app.fetch on a mesh app', () => { + // Previously this asserted fetch() *threw* until listen() ran, which made mesh Node-only: + // Deno/Bun/edge serve through app.fetch and can never call listen() (it builds an http.Server). + // The boot gate now finalizes the mesh graph on first use, whoever triggers it. + it('serves without ever calling listen()', async () => { const meshApp = createApp({ modules: [MeshModule], experimental: true, mesh: { secret: 's3cr3t' } }); - await expect(meshApp.fetch(new Request('http://x/api/mesh/ping'))).rejects.toThrow(/unavailable before listen/); + const res = await meshApp.fetch(new Request('http://x/api/mesh/ping')); + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ pong: true }); + await meshApp.close(); + }); + + it('does not re-boot when listen() follows a fetch', async () => { + const meshApp = createApp({ modules: [MeshModule], experimental: true, mesh: { secret: 's3cr3t' } }); + let booted = 0; + meshApp.bus.on('boot:provider:start', () => { + booted += 1; + }); + + await meshApp.fetch(new Request('http://x/api/mesh/ping')); + const bootsAfterFetch = booted; const server = await meshApp.listen(0); + try { const res = await meshApp.fetch(new Request('http://x/api/mesh/ping')); expect(res.status).toBe(200); - expect(await res.json()).toEqual({ pong: true }); + // listen() shares fetch's memoized gate: provider factories must not run twice + expect(booted).toBe(bootsAfterFetch); } finally { server.close(); } diff --git a/test/mesh/fetch-boot.test.ts b/test/mesh/fetch-boot.test.ts new file mode 100644 index 0000000..49c1477 --- /dev/null +++ b/test/mesh/fetch-boot.test.ts @@ -0,0 +1,123 @@ +import { describe, it, expect } from 'vitest'; +import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index'; + +const SECRET = 's3cr3t'; + +@Provider({ provides: 'config', export: true }) +class Config { + provide() { + return { config: { region: 'mx' } }; + } +} +@Step({ provides: 'auth', needs: [], export: true }) +class Auth { + run(ctx: any) { + return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; + } +} +@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] }) +class TeapotModule {} + +@Route('/local') +class LocalCtl { + @Get('/who') + who(@needs('config') config: any, @needs('auth') auth: any) { + return { config, auth }; + } +} +@Module({ mountpoint: '/api', controllers: [LocalCtl] }) +class TeacupModule {} + +const teapotUrl = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`; + +/** + * A mesh teacup driven purely through `app.fetch` — the entry point Deno/Bun/edge use. + * `listen()` is never called on the teacup, because on those runtimes it cannot be: + * it builds a Node http.Server. + */ +describe('mesh over app.fetch (no listen)', () => { + it('boots the mesh graph on the first request and resolves remote scopes', async () => { + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); + const tServer = await teapot.listen(0); + const url = teapotUrl((tServer.address() as any).port); + + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + mesh: { teapots: [{ url, secret: SECRET }] }, + }); + + const res = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } })); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ config: { region: 'mx' }, auth: { token: 'abc' } }); + + await teacup.close(); + tServer.close(); + }); + + it('boots exactly once across concurrent first requests', async () => { + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); + const tServer = await teapot.listen(0); + const url = teapotUrl((tServer.address() as any).port); + + let connects = 0; + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + mesh: { teapots: [{ url, secret: SECRET }] }, + }); + teacup.bus.on('mesh:connect', () => { + connects += 1; + }); + + const hit = () => teacup.fetch(new Request('http://x/api/local/who')); + const all = await Promise.all([hit(), hit(), hit()]); + + expect(all.map((r) => r.status)).toEqual([200, 200, 200]); + expect(connects).toBe(1); // the boot gate is memoized: three racing requests splice once + + await teacup.close(); + tServer.close(); + }); + + it('serves the remote scope in inspect() once a request has booted the graph', async () => { + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); + const tServer = await teapot.listen(0); + const url = teapotUrl((tServer.address() as any).port); + + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + mesh: { teapots: [{ url, secret: SECRET }] }, + }); + + await teacup.fetch(new Request('http://x/api/local/who')); + const chain = teacup.inspect('/api/local/who').map((line) => `${line.kind}:${line.name}`); + + // the remote provider and step spliced into the local route's chain + expect(chain).toContain('provider:config'); + expect(chain).toContain('step:auth'); + expect(teacup.graph().nodes.some((n) => n.name === 'config')).toBe(true); + + await teacup.close(); + tServer.close(); + }); + + it('surfaces a failed mesh boot as a request error, not a silent success', async () => { + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); + const tServer = await teapot.listen(0); + const url = teapotUrl((tServer.address() as any).port); + + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + mesh: { teapots: [{ url, secret: 'WRONG' }], timeoutMs: 800 }, + }); + + await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow(); + + await teacup.close(); + tServer.close(); + }); +}); From 0c68cba5321d862738b8722f408fde38d8e77f09 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 15 Jul 2026 15:12:53 -0500 Subject: [PATCH 09/13] feat(mesh): mount the control channel on app.upgrade, and close links without a server MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/app/index.ts | 96 +++++++++++++++++--------- src/http/types.ts | 3 +- src/http/ws.ts | 3 +- src/mesh/teapot.ts | 17 +++-- test/mesh/control-upgrade.test.ts | 2 +- test/mesh/fetch-boot.test.ts | 110 ++++++++++++++++++++++++++++++ 6 files changed, 191 insertions(+), 40 deletions(-) diff --git a/src/app/index.ts b/src/app/index.ts index c320650..f89abe5 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -30,7 +30,7 @@ import { connectLink, type Link } from '../mesh/link'; import { Rooms } from '../rooms'; import type { TlsOptions, SecurityOptions, CorsOptions } from '../security'; import { buildRemote } from '../mesh/teacup'; -import { buildManifest, createMeshControl } from '../mesh/teapot'; +import { buildManifest, createMeshControl, MESH_CONTROL_PATH } from '../mesh/teapot'; import type { MeshControl } from '../http'; import type { RequestEnvelope, RouteEntry } from '../mesh/protocol'; import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types'; @@ -127,14 +127,28 @@ export function createApp(opts: { if (!opts.mesh) finalize(); - // mesh teacup: connect remote teapots and splice their scopes/routes in, then finalize. - const prepareGraph = async (): Promise => { - if (!opts.mesh || booted) return; + const providedSeed = (plan: RoutePlan) => seedProviders(container, plan); + const planSteps = (plan: RoutePlan) => compilePlanSteps(runners, plan); + const pipelineDeps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError }; + let meshControl: MeshControl | undefined; - const spliced = await spliceRemoteScopes(opts.mesh, bus, registry); - remoteRoutes = spliced.remoteRoutes; - meshLinks.push(...spliced.meshLinks); - finalize(); + // mesh teacup: connect remote teapots and splice their scopes/routes in, then finalize. + // mesh teapot: build the control channel — it captures the *finalized* ordered nodes, so it + // can only be built here, after finalize(), and never at construction time. + const prepareGraph = async (): Promise => { + if (opts.mesh && !booted) { + const spliced = await spliceRemoteScopes(opts.mesh, bus, registry); + remoteRoutes = spliced.remoteRoutes; + meshLinks.push(...spliced.meshLinks); + finalize(); + } + + meshControl = buildMeshControl(opts.mesh, registry, { + container, + orderedProviders, + orderedSteps, + deps: pipelineDeps, + }); }; const inspect = (routePath: string): InspectLine[] => inspectRoute(routePlans, routePath, booted); @@ -160,9 +174,6 @@ export function createApp(opts: { return routes; }; - const providedSeed = (plan: RoutePlan) => seedProviders(container, plan); - const planSteps = (plan: RoutePlan) => compilePlanSteps(runners, plan); - // Boots exactly once, however first triggered (app.fetch, app.upgrade or listen()); calling // several never double-boots (which would re-run provider factories and their side effects). const bootApp = makeAppBooter( @@ -194,26 +205,15 @@ export function createApp(opts: { devRoutes, () => remoteRoutes, ); - const upgradeFn = buildAppUpgrade( - routePlans, - { providedSeed, planSteps, bus, onError: opts.onError }, - streams, - bootApp, - ); + const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl); const listen = async (port: number): Promise => { - const deps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError }; + const deps = pipelineDeps; - // the same gate app.fetch uses: splices remote mesh scopes, finalizes, boots providers + // the same gate app.fetch uses: splices remote mesh scopes, finalizes, boots providers, + // and builds the mesh control channel — so Node and Deno/Bun serve an identical graph await bootApp(); - const meshControl = buildMeshControl(opts.mesh, registry, { - container, - orderedProviders, - orderedSteps, - deps, - }); - const httpRoutes = [...buildHttpRoutes(routePlans, remoteRoutes, deps), ...devRoutes()]; const wsRoutes = buildWsRoutes(routePlans, deps); @@ -235,7 +235,13 @@ export function createApp(opts: { const close = (): Promise => new Promise((resolve) => { + // before the server check: a mesh app booted through app.fetch (Deno/Bun, where listen() + // never runs) has links but no server, and would otherwise leak every teapot connection. + // Closing a link rejects its in-flight RPCs via the socket's abort. + closeLinks(meshLinks); + if (!server) return resolve(); + server.close(() => resolve()); // waits for in-flight buffered to drain for (const closeStream of streams) closeStream(); // force-close long-lived SSE/WS so close() resolves server.closeIdleConnections(); // Node >=18.2: drop idle keep-alive @@ -735,23 +741,49 @@ function buildAppUpgrade( deps: PipelineDeps, streams: Set<() => void>, ensureBooted: () => Promise, + getMeshControl: () => MeshControl | undefined, ): (request: WsRequest, socket: WsSocket) => Promise { let wsRoutes: WsRouteDef[] | undefined; return async (request: WsRequest, socket: WsSocket): Promise => { + // Subscribe to inbound BEFORE awaiting the boot. `channel` is fan-out: a frame pushed with no + // subscriber is dropped, so anything the peer sends while providers are still booting would be + // lost. For the mesh control channel that is the `hello` itself — the handshake would hang + // until timeout against a teapot whose providers happened to boot slowly. + const frames = socket.inbound[Symbol.asyncIterator](); + const ready: WsSocket = Object.create(socket, { + inbound: { value: { [Symbol.asyncIterator]: () => frames } }, + }) as WsSocket; + await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted - if (!wsRoutes) wsRoutes = buildWsRoutes(routePlans, deps); - const path = request.url.split('?')[0]; - const route = matchWsRoute(wsRoutes, path); + const meshControl = getMeshControl(); - if (!route) { - socket.close(1008, 'no matching ws route'); + // The reserved mesh path, checked before route matching: this is what lets a teapot export + // its scopes from Deno/Bun, where the Node `server.on('upgrade')` path does not exist. + if (path === MESH_CONTROL_PATH) { + // an explicit refusal, not "no matching ws route": the path is reserved either way, and a + // peer that reached a teapot with nothing exported deserves to be told which it was + if (!meshControl) { + ready.close(1008, 'mesh control channel not enabled: this app exports nothing, or has no mesh.secret'); + return; + } + + await meshControl.handle(ready); return; } - await runWsConnection(socket, request, route, deps.bus, streams); + if (!wsRoutes) wsRoutes = buildWsRoutes(routePlans, deps); + + const route = matchWsRoute(wsRoutes, path); + + if (!route) { + ready.close(1008, 'no matching ws route'); + return; + } + + await runWsConnection(ready, request, route, deps.bus, streams); }; } diff --git a/src/http/types.ts b/src/http/types.ts index 4526f69..7ea2406 100644 --- a/src/http/types.ts +++ b/src/http/types.ts @@ -76,6 +76,7 @@ export interface MeshControl { /** * Serves one control connection over the neutral socket — the same capability every other ws * consumer takes, so Node (via `nodeSocket`) and Deno/Bun (via `app.upgrade`) both feed it. + * Resolves when the connection ends, like `runWsConnection`. */ - handle(socket: WsSocket): void; + handle(socket: WsSocket): Promise; } diff --git a/src/http/ws.ts b/src/http/ws.ts index 1665ada..6c8188a 100644 --- a/src/http/ws.ts +++ b/src/http/ws.ts @@ -40,7 +40,8 @@ function handleMeshUpgrade( // nodeSocket, not the raw ws: the control channel is the last consumer that spoke the // `ws` EventEmitter API directly. It now takes the same neutral socket every route does. - wss.handleUpgrade(req, socket, head, (ws: any) => meshControl.handle(nodeSocket(ws))); + // serveFrames swallows its own failures, so the floating promise cannot reject + wss.handleUpgrade(req, socket, head, (ws: any) => void meshControl.handle(nodeSocket(ws))); return true; } diff --git a/src/mesh/teapot.ts b/src/mesh/teapot.ts index f453633..c59503b 100644 --- a/src/mesh/teapot.ts +++ b/src/mesh/teapot.ts @@ -182,16 +182,23 @@ async function serveFrames( } /** Build a control handler that authenticates peers and serves scope/route RPCs from the manifest. */ -export function createMeshControl(deps: MeshControlDeps): { path: string; handle: (socket: WsSocket) => void } { +export function createMeshControl(deps: MeshControlDeps): { + path: string; + handle: (socket: WsSocket) => Promise; +} { const exportedScopes = new Set(deps.manifest.scopes.map((scope) => scope.token)); const exportedRoutes = new Set(deps.manifest.routes.map((route) => `${route.method} ${route.pattern}`)); return { path: MESH_CONTROL_PATH, - handle(socket: WsSocket) { - // `channel` is fan-out and subscribes when the async iterator is created, which - // `for await` does synchronously — so the loop is live before any frame can arrive. - void serveFrames(socket, deps, exportedScopes, exportedRoutes); + /** + * Resolves when the connection ends, mirroring `runWsConnection` — so `app.upgrade` can await + * the control channel's lifetime the same way it awaits a regular ws route's. + * `channel` is fan-out and subscribes when the async iterator is created, which `for await` + * does synchronously, so the loop is live before any frame can arrive. + */ + handle(socket: WsSocket): Promise { + return serveFrames(socket, deps, exportedScopes, exportedRoutes); }, }; } diff --git a/test/mesh/control-upgrade.test.ts b/test/mesh/control-upgrade.test.ts index cd50118..454b4dd 100644 --- a/test/mesh/control-upgrade.test.ts +++ b/test/mesh/control-upgrade.test.ts @@ -5,7 +5,7 @@ import { createHttpServer, type MeshControl } from '../../src/http'; describe('mesh control upgrade', () => { it('routes the reserved path to meshControl.handle and leaves wsRoutes intact', async () => { let handled = false; - const meshControl: MeshControl = { path: '/__mesh__/control', handle: (ws) => { handled = true; ws.send('hi'); } }; + const meshControl: MeshControl = { path: '/__mesh__/control', handle: async (ws) => { handled = true; ws.send('hi'); } }; const server = createHttpServer([], [], undefined, meshControl); await new Promise((r) => server.listen(0, r)); const port = (server.address() as any).port; diff --git a/test/mesh/fetch-boot.test.ts b/test/mesh/fetch-boot.test.ts index 49c1477..7ba41bd 100644 --- a/test/mesh/fetch-boot.test.ts +++ b/test/mesh/fetch-boot.test.ts @@ -1,5 +1,8 @@ import { describe, it, expect } from 'vitest'; import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index'; +import { channel } from '../../src/channel'; +import { encode, decode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol'; +import type { WsSocket, WsRequest } from '../../src/http/ws-core'; const SECRET = 's3cr3t'; @@ -28,8 +31,43 @@ class LocalCtl { @Module({ mountpoint: '/api', controllers: [LocalCtl] }) class TeacupModule {} +@Route('/plain') +class PlainCtl { + @Get('/ok') + ok() { + return { ok: true }; + } +} +@Module({ mountpoint: '/', controllers: [PlainCtl] }) +class PlainModule {} + const teapotUrl = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`; +/** A neutral socket, exactly what serveDeno/serveBun hand to app.upgrade. */ +const fakePeer = () => { + const inbound = channel(); + const ac = new AbortController(); + const sent: any[] = []; + const closed: { code?: number; reason?: string }[] = []; + const socket: WsSocket = { + inbound, + abort: ac.signal, + isOpen: true, + send: (data: string) => { + sent.push(decode(data)); + }, + close: (code, reason) => { + closed.push({ code, reason }); + inbound.close(); + ac.abort(); + }, + terminate: () => ac.abort(), + }; + return { socket, sent, closed, inbound }; +}; + +const controlReq = (): WsRequest => ({ url: '/__mesh__/control', headers: {}, protocol: 'http', ip: '' }); + /** * A mesh teacup driven purely through `app.fetch` — the entry point Deno/Bun/edge use. * `listen()` is never called on the teacup, because on those runtimes it cannot be: @@ -104,6 +142,30 @@ describe('mesh over app.fetch (no listen)', () => { tServer.close(); }); + it('closes the teapot links, even with no server to hang the close off', async () => { + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); + const tServer = await teapot.listen(0); + const url = teapotUrl((tServer.address() as any).port); + + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + mesh: { teapots: [{ url, secret: SECRET }] }, + }); + const disconnects: string[] = []; + teacup.bus.on('mesh:disconnect', (p) => disconnects.push(p.name)); + + await teacup.fetch(new Request('http://x/api/local/who')); + expect(disconnects).toEqual([]); + + // listen() never ran, so there is no server whose 'close' could reap the links + await teacup.close(); + await new Promise((r) => setTimeout(r, 50)); + + expect(disconnects).toEqual([url]); + tServer.close(); + }); + it('surfaces a failed mesh boot as a request error, not a silent success', async () => { const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); const tServer = await teapot.listen(0); @@ -121,3 +183,51 @@ describe('mesh over app.fetch (no listen)', () => { tServer.close(); }); }); + +/** + * A teapot *exporting* over app.upgrade — the path serveDeno/serveBun drive. Without this the + * control channel only existed on Node's server.on('upgrade'), so a teapot could not run off Node + * and "mesh on 3 runtimes" would have meant consuming only. + */ +describe('mesh control over app.upgrade (no listen)', () => { + it('serves the handshake to a peer that never touched a Node server', async () => { + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); + const peer = fakePeer(); + + void teapot.upgrade(controlReq(), peer.socket); + peer.inbound.push(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: SECRET })); + await new Promise((r) => setTimeout(r, 20)); + + expect(peer.sent[0]).toMatchObject({ + type: 'manifest', + v: MESH_PROTOCOL_VERSION, + scopes: expect.arrayContaining([{ token: 'config', scope: 'app' }]), + }); + await teapot.close(); + }); + + it('rejects a bad secret over app.upgrade too', async () => { + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); + const peer = fakePeer(); + + void teapot.upgrade(controlReq(), peer.socket); + peer.inbound.push(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: 'WRONG' })); + await new Promise((r) => setTimeout(r, 20)); + + expect(peer.sent).toEqual([]); + expect(peer.closed[0].code).toBe(1008); + await teapot.close(); + }); + + it('refuses the reserved path explicitly on an app that exports nothing', async () => { + // a plain, self-contained app: the path is reserved regardless, so say so rather than + // let it fall through to the generic "no matching ws route" + const plain = createApp({ modules: [PlainModule] }); + const peer = fakePeer(); + + await plain.upgrade(controlReq(), peer.socket); + + expect(peer.closed[0].code).toBe(1008); + expect(peer.closed[0].reason).toMatch(/mesh control channel not enabled/i); + }); +}); From a74417494f7426bae885ffd58a5af65b60a52284 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 15 Jul 2026 15:30:43 -0500 Subject: [PATCH 10/13] test(mesh): prove mesh across Node, Deno and Bun MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- package.json | 2 +- test/bun/mesh.test.ts | 84 ++++++++++++++++ test/deno/mesh-interop.test.ts | 170 +++++++++++++++++++++++++++++++++ test/deno/mesh.test.ts | 108 +++++++++++++++++++++ test/interop/_node-peer.ts | 71 ++++++++++++++ 5 files changed, 434 insertions(+), 1 deletion(-) create mode 100644 test/bun/mesh.test.ts create mode 100644 test/deno/mesh-interop.test.ts create mode 100644 test/deno/mesh.test.ts create mode 100644 test/interop/_node-peer.ts diff --git a/package.json b/package.json index b17be00..7169e50 100644 --- a/package.json +++ b/package.json @@ -79,7 +79,7 @@ "build": "tsup", "test": "vitest run", "test:dev": "vitest", - "test:deno": "deno test --allow-net --allow-read --no-check test/deno/", + "test:deno": "deno test --allow-net --allow-read --allow-run --allow-env --no-check test/deno/", "test:bun": "bun test test/bun/", "test:edge": "tsx test/edge/run.ts", "typecheck": "tsc --noEmit -p tsconfig.json", diff --git a/test/bun/mesh.test.ts b/test/bun/mesh.test.ts new file mode 100644 index 0000000..136a496 --- /dev/null +++ b/test/bun/mesh.test.ts @@ -0,0 +1,84 @@ +// Real Bun integration test for mesh: a teapot exporting its scopes and a teacup consuming +// them, both under the actual Bun runtime, driven entirely through serveBun. +// +// Bun's ws lifecycle differs from Deno's — its socket events land on a server-level handler +// rather than the socket — so the control channel reaching app.upgrade here is a distinct +// path from the Deno test, not a duplicate of it. +// +// Run with: npm run test:bun +import 'reflect-metadata'; +import { test, expect } from 'bun:test'; +import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts'; +import { serveBun } from '../../src/bun.ts'; + +const SECRET = 's3cr3t'; + +@Provider({ provides: 'config', export: true }) +class Config { + provide() { + return { config: { region: 'mx', runtime: 'bun' } }; + } +} +@Step({ provides: 'auth', needs: [], export: true }) +class Auth { + run(ctx: any) { + return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; + } +} +@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] }) +class TeapotModule {} + +@Route('/local') +class LocalCtl { + @Get('/who') + who(@needs('config') config: any, @needs('auth') auth: any) { + return { config, auth }; + } +} +@Module({ mountpoint: '/api', controllers: [LocalCtl] }) +class TeacupModule {} + +const controlUrl = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`; + +test('mesh on Bun: teacup resolves a Bun teapot through the graph', async () => { + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); + const tServer = serveBun(teapot, { port: 0 }); + + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + mesh: { teapots: [{ url: controlUrl(tServer.port), secret: SECRET }] }, + }); + const cServer = serveBun(teacup, { port: 0 }); + + try { + const res = await fetch(`http://127.0.0.1:${cServer.port}/api/local/who`, { headers: { 'x-token': 'abc' } }); + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + config: { region: 'mx', runtime: 'bun' }, + auth: { token: 'abc' }, + }); + } finally { + await teacup.close(); + cServer.stop(true); + tServer.stop(true); + } +}); + +test('mesh on Bun: a teapot refuses a bad secret over its control channel', async () => { + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); + const tServer = serveBun(teapot, { port: 0 }); + + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + mesh: { teapots: [{ url: controlUrl(tServer.port), secret: 'WRONG' }], timeoutMs: 1000 }, + }); + + try { + await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow(/mesh/); + } finally { + await teacup.close(); + tServer.stop(true); + } +}); diff --git a/test/deno/mesh-interop.test.ts b/test/deno/mesh-interop.test.ts new file mode 100644 index 0000000..9fae7d4 --- /dev/null +++ b/test/deno/mesh-interop.test.ts @@ -0,0 +1,170 @@ +// Cross-runtime mesh: a Node peer and a Deno peer, in separate processes, talking over the +// wire protocol. This is the test the whole cross-runtime effort exists for. +// +// Deno<->Deno and Node<->Node passing prove each runtime works with itself; neither proves a +// Node teapot can serve a Deno teacup, which is the shape mesh actually deploys in once it +// spans runtimes. The two sides use genuinely different code here — Node serves through the +// `ws` package (WebSocketServer + nodeSocket) and connects with it too; Deno uses its global +// WebSocket both ways — so only a real cross-process run exercises the pairing. +// +// Run with: npm run test:deno (needs --allow-run to spawn the Node peer) +import 'npm:reflect-metadata'; +import { assertEquals, assertStringIncludes } from 'jsr:@std/assert'; +import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts'; + +const SECRET = 's3cr3t'; +const NODE_PEER = 'test/interop/_node-peer.ts'; + +@Provider({ provides: 'config', export: true }) +class Config { + provide() { + return { config: { region: 'mx', runtime: 'deno' } }; + } +} +@Step({ provides: 'auth', needs: [], export: true }) +class Auth { + run(ctx: any) { + return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; + } +} +@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] }) +class TeapotModule {} + +@Route('/local') +class LocalCtl { + @Get('/who') + who(@needs('config') config: any, @needs('auth') auth: any) { + return { config, auth }; + } +} +@Module({ mountpoint: '/api', controllers: [LocalCtl] }) +class TeacupModule {} + +const controlUrl = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`; + +/** Spawns the Node peer under tsx, streaming its stdout lines. */ +function spawnNodePeer(args: string[]) { + const child = new Deno.Command('npx', { + args: ['tsx', NODE_PEER, ...args], + env: { ...Deno.env.toObject(), MESH_SECRET: SECRET }, + stdout: 'piped', + stderr: 'piped', + }).spawn(); + + return child; +} + +/** Reads stdout until a JSON line parses, or the peer dies / we run out of patience. */ +async function firstJsonLine(child: Deno.ChildProcess, timeoutMs = 30_000): Promise { + const reader = child.stdout.getReader(); + const decoder = new TextDecoder(); + let buffer = ''; + const deadline = Date.now() + timeoutMs; + + try { + while (Date.now() < deadline) { + const { value, done } = await reader.read(); + if (done) break; + buffer += decoder.decode(value, { stream: true }); + + for (const line of buffer.split('\n')) { + const trimmed = line.trim(); + if (!trimmed.startsWith('{')) continue; + try { + return JSON.parse(trimmed); + } catch { + /* partial line; keep reading */ + } + } + } + } finally { + reader.releaseLock(); + } + + throw new Error(`node peer produced no JSON line within ${timeoutMs}ms`); +} + +async function kill(child: Deno.ChildProcess): Promise { + try { + child.kill('SIGKILL'); + } catch { + /* already gone */ + } + await child.status; + try { + await child.stdout.cancel(); + await child.stderr.cancel(); + } catch { + /* already released */ + } +} + +Deno.test('interop: a Deno teacup consumes a Node teapot', async () => { + const node = spawnNodePeer(['teapot']); + const { port } = await firstJsonLine(node); + + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + mesh: { teapots: [{ url: controlUrl(port), secret: SECRET }], timeoutMs: 5000 }, + }); + + try { + const res = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } })); + assertEquals(res.status, 200); + // the config came from the Node process: proof the scope crossed the runtime boundary + assertEquals(await res.json(), { + config: { region: 'mx', runtime: 'node' }, + auth: { token: 'abc' }, + }); + } finally { + await teacup.close(); + await kill(node); + } +}); + +Deno.test('interop: a Node teacup consumes a Deno teapot', async () => { + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); + let port = 0; + const { serveDeno } = await import('../../src/deno.ts'); + const server = serveDeno(teapot, { + port: 0, + onListen: (addr) => { + port = addr.port; + }, + }); + await new Promise((resolve) => setTimeout(resolve, 50)); + + const node = spawnNodePeer(['teacup', controlUrl(port)]); + + try { + const result = await firstJsonLine(node); + assertEquals(result.ok, true); + // the Node peer resolved a scope served by Deno's app.upgrade control channel + assertEquals(result.body.config, { region: 'mx', runtime: 'deno' }); + assertEquals(result.body.auth, { token: 'abc' }); + } finally { + await kill(node); + await server.shutdown(); + } +}); + +Deno.test('interop: a version-skewed peer is refused across runtimes', async () => { + const node = spawnNodePeer(['teapot']); + const { port } = await firstJsonLine(node); + + try { + // hand-rolled peer speaking a future protocol: the teapot must refuse before the secret + const ws = new WebSocket(controlUrl(port)); + const closed = await new Promise<{ code: number; reason: string }>((resolve, reject) => { + ws.onopen = () => ws.send(JSON.stringify({ type: 'hello', v: 999, secret: SECRET })); + ws.onclose = (e) => resolve({ code: e.code, reason: e.reason }); + ws.onerror = () => reject(new Error('ws error')); + }); + + assertEquals(closed.code, 1008); + assertStringIncludes(closed.reason, '999'); + } finally { + await kill(node); + } +}); diff --git a/test/deno/mesh.test.ts b/test/deno/mesh.test.ts new file mode 100644 index 0000000..cb8fc28 --- /dev/null +++ b/test/deno/mesh.test.ts @@ -0,0 +1,108 @@ +// Real Deno integration test for mesh: a teapot exporting its scopes and a teacup consuming +// them, both under the actual Deno runtime, driven entirely through serveDeno. +// +// This is the test that makes "mesh runs off Node" a fact rather than an intention. It covers, +// in one round-trip, everything that used to be Node-only: +// - the teacup's WebSocket client is Deno's global (no `ws` package here at all) +// - the teapot's control channel is served via app.upgrade (Deno has no server.on('upgrade')) +// - the graph boots on the first request; `listen()` is never called and cannot be +// - node:crypto's timingSafeEqual + Buffer resolve under Deno's node-compat +// +// Run with: npm run test:deno +// `--no-check`: see the note in ws.test.ts — Deno type-checks the whole reachable graph, +// including Node-only modules this test never executes. tsc covers those. +import 'npm:reflect-metadata'; +import { assertEquals, assertStringIncludes } from 'jsr:@std/assert'; +import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts'; +import { serveDeno } from '../../src/deno.ts'; + +const SECRET = 's3cr3t'; + +@Provider({ provides: 'config', export: true }) +class Config { + provide() { + return { config: { region: 'mx', runtime: 'deno' } }; + } +} +@Step({ provides: 'auth', needs: [], export: true }) +class Auth { + run(ctx: any) { + return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; + } +} +@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] }) +class TeapotModule {} + +@Route('/local') +class LocalCtl { + @Get('/who') + who(@needs('config') config: any, @needs('auth') auth: any) { + return { config, auth }; + } +} +@Module({ mountpoint: '/api', controllers: [LocalCtl] }) +class TeacupModule {} + +/** Starts an app on Deno and resolves once its port is known. */ +async function serve(app: ReturnType) { + let port = 0; + const server = serveDeno(app, { + port: 0, + onListen: (addr) => { + port = addr.port; + }, + }); + await new Promise((resolve) => setTimeout(resolve, 50)); + return { server, port }; +} + +const controlUrl = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`; + +Deno.test('mesh on Deno: teacup resolves a Deno teapot through the graph', async () => { + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); + const t = await serve(teapot); + + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + mesh: { teapots: [{ url: controlUrl(t.port), secret: SECRET }] }, + }); + const c = await serve(teacup); + + try { + const res = await fetch(`http://127.0.0.1:${c.port}/api/local/who`, { headers: { 'x-token': 'abc' } }); + assertEquals(res.status, 200); + assertEquals(await res.json(), { + config: { region: 'mx', runtime: 'deno' }, + auth: { token: 'abc' }, + }); + } finally { + await teacup.close(); + await c.server.shutdown(); + await t.server.shutdown(); + } +}); + +Deno.test('mesh on Deno: a teapot refuses a bad secret over its control channel', async () => { + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); + const t = await serve(teapot); + + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + mesh: { teapots: [{ url: controlUrl(t.port), secret: 'WRONG' }], timeoutMs: 1000 }, + }); + + try { + let message = ''; + try { + await teacup.fetch(new Request('http://x/api/local/who')); + } catch (err) { + message = String((err as Error).message); + } + assertStringIncludes(message, 'mesh'); + } finally { + await teacup.close(); + await t.server.shutdown(); + } +}); diff --git a/test/interop/_node-peer.ts b/test/interop/_node-peer.ts new file mode 100644 index 0000000..dada500 --- /dev/null +++ b/test/interop/_node-peer.ts @@ -0,0 +1,71 @@ +// Not a test — a Node-hosted mesh peer, spawned by mesh-interop.test.ts. Deno's test runner +// only discovers *.test.ts, so this file is ignored by `deno test`. +// +// It exists so the interop claim is tested rather than reasoned about: Deno<->Deno passing +// says nothing about a Node teapot serving a Deno teacup, which is the actual deployment +// shape once mesh spans runtimes. Node's side uses the `ws` package (WebSocketServer + +// nodeSocket); Deno's uses its global WebSocket. Only a real cross-process run exercises both. +// +// Modes: +// teapot -> exports scopes, prints {"port":N}, serves until killed +// teacup -> consumes the remote scopes, prints {"ok":true,"body":{...}} +import 'reflect-metadata'; +import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index'; + +const SECRET = process.env.MESH_SECRET ?? 's3cr3t'; + +@Provider({ provides: 'config', export: true }) +class Config { + provide() { + return { config: { region: 'mx', runtime: 'node' } }; + } +} +@Step({ provides: 'auth', needs: [], export: true }) +class Auth { + run(ctx: any) { + return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; + } +} +@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] }) +class TeapotModule {} + +@Route('/local') +class LocalCtl { + @Get('/who') + who(@needs('config') config: any, @needs('auth') auth: any) { + return { config, auth }; + } +} +@Module({ mountpoint: '/api', controllers: [LocalCtl] }) +class TeacupModule {} + +const [mode, controlUrl] = process.argv.slice(2); + +async function main(): Promise { + if (mode === 'teapot') { + const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); + const server = await app.listen(0); + console.log(JSON.stringify({ port: (server.address() as { port: number }).port })); + return; // stays alive on the open server until the parent kills it + } + + if (mode === 'teacup') { + const app = createApp({ + modules: [TeacupModule], + experimental: true, + mesh: { teapots: [{ url: controlUrl, secret: SECRET }], timeoutMs: 5000 }, + }); + const res = await app.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } })); + const body = await res.json(); + console.log(JSON.stringify({ ok: res.status === 200, body })); + await app.close(); + process.exit(0); + } + + throw new Error(`unknown mode: ${mode}`); +} + +main().catch((err: unknown) => { + console.log(JSON.stringify({ ok: false, error: String((err as Error).message) })); + process.exit(1); +}); From 033af2d1fc6ab30d3356fdebb0962f3970fd95aa Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 15 Jul 2026 16:04:57 -0500 Subject: [PATCH 11/13] fix(mesh): fail the boot when two teapots export the same route MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/app/index.ts | 17 +++++++++ test/mesh/integration.test.ts | 67 +++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+) diff --git a/src/app/index.ts b/src/app/index.ts index f89abe5..f6c34e5 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -466,6 +466,7 @@ async function spliceRemoteScopes( ): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[] }> { const remoteRoutes: RouteDef[] = []; const meshLinks: Link[] = []; + const routeOwners = new Map(); // "METHOD /pattern" -> the teapot that exported it try { for (const teapot of mesh.teapots ?? []) { @@ -486,6 +487,22 @@ async function spliceRemoteScopes( } for (const route of routes) { + const key = `${route.method} ${route.pattern}`; + const owner = routeOwners.get(key); + + // Fail the boot rather than pick one. Route matching keeps the first of two identical + // patterns, so the loser would be silently dead — and callers could come to depend on + // "first teapot wins", which would make adding balancing later a breaking change. + // Scope tokens already fail this way in setRunner; routes now match. + if (owner) { + throw new Error( + `mesh: route '${key}' is exported by more than one teapot (${owner} and ${teapot.url}) — ` + + 'load balancing across teapots is not implemented yet, so green-tea will not choose one for you. ' + + 'Export it from a single teapot.', + ); + } + + routeOwners.set(key, teapot.url); remoteRoutes.push({ method: route.method, pattern: route.pattern, diff --git a/test/mesh/integration.test.ts b/test/mesh/integration.test.ts index 98bbf37..3108417 100644 --- a/test/mesh/integration.test.ts +++ b/test/mesh/integration.test.ts @@ -23,6 +23,28 @@ class LocalCtl { @Module({ mountpoint: '/api', controllers: [LocalCtl] }) class TeacupModule {} +// Two teapots exporting the SAME route and no scopes — a scope clash would throw first +// (setRunner enforces unique tokens), which would hide the route clash under test. +@Route('/dup') +class DupCtl { + @Get('/ping', { export: true }) + ping() { + return { pong: true }; + } +} +@Module({ mountpoint: '/api', controllers: [DupCtl] }) +class DupTeapotModule {} + +@Route('/c') +class PlainCtl { + @Get('/ok') + ok() { + return { ok: true }; + } +} +@Module({ mountpoint: '/', controllers: [PlainCtl] }) +class PlainTeacupModule {} + describe('mesh skeleton integration', () => { it('teacup resolves remote app-scope + request-scope into a local handler', async () => { const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); @@ -52,6 +74,51 @@ describe('mesh skeleton integration', () => { s.close(); }); + it('refuses to boot when two teapots export the same route, naming both', async () => { + // No load balancing exists yet, so picking one silently would be a wrong answer that + // callers could come to depend on — and it would make adding LB later a breaking change. + const a = createApp({ modules: [DupTeapotModule], experimental: true, mesh: { secret: SECRET } }); + const b = createApp({ modules: [DupTeapotModule], experimental: true, mesh: { secret: SECRET } }); + const aServer = await a.listen(0); + const bServer = await b.listen(0); + const url = (s: any) => `ws://127.0.0.1:${(s.address() as any).port}/__mesh__/control`; + + const teacup = createApp({ + modules: [PlainTeacupModule], + experimental: true, + mesh: { + teapots: [ + { url: url(aServer), secret: SECRET }, + { url: url(bServer), secret: SECRET }, + ], + }, + }); + + await expect(teacup.fetch(new Request('http://x/c/ok'))).rejects.toThrow(/GET \/api\/dup\/ping/); + await expect(teacup.fetch(new Request('http://x/c/ok'))).rejects.toThrow(/load balancing/i); + + aServer.close(); + bServer.close(); + }); + + it('accepts the same route from a single teapot (regression: no false positive)', async () => { + const a = createApp({ modules: [DupTeapotModule], experimental: true, mesh: { secret: SECRET } }); + const aServer = await a.listen(0); + const url = `ws://127.0.0.1:${(aServer.address() as any).port}/__mesh__/control`; + + const teacup = createApp({ + modules: [PlainTeacupModule], + experimental: true, + mesh: { teapots: [{ url, secret: SECRET }] }, + }); + + const res = await teacup.fetch(new Request('http://x/api/dup/ping')); + expect(await res.json()).toEqual({ pong: true }); + + await teacup.close(); + aServer.close(); + }); + it('rejects a bad secret (teacup boot fails)', async () => { const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); const tServer = await teapot.listen(0); const tPort = (tServer.address() as any).port; From 34dbb32b2c99940dbdc9234d33cf79f0f4a8f3bd Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 15 Jul 2026 16:20:55 -0500 Subject: [PATCH 12/13] docs(mesh): warn on shadowed remote routes, and tell the truth about mesh MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- CHANGELOG.md | 28 ++++++++- src/app/index.ts | 13 ++++ test/mesh/integration.test.ts | 66 ++++++++++++++++++++- website/src/content/docs/guides/mesh.md | 45 +++++++++++++- website/src/content/docs/guides/runtimes.md | 18 +++--- 5 files changed, 159 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cd43a36..4418446 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,17 +13,41 @@ green-tea uses calendar versioning: `YY.MM.PATCH`. bring-your-own hook, and zero-config `static` directory serving (`createApp({ static: true })`). File and static serving require a filesystem (Node/Deno/Bun); string-mode `@Html` runs everywhere. - **`app.fetch(request): Promise`** — a Web-Standards handler so the - same app runs HTTP and SSE on Deno/Bun/edge runtimes via the Fetch API - (WebSocket and mesh remain Node-only). + same app runs HTTP and SSE on Deno/Bun/edge runtimes via the Fetch API. - **Deno adapter** (`@green-tea/core/deno`): `serveDeno(app)` runs HTTP + SSE + WebSocket on Deno. - **Bun adapter** (`@green-tea/core/bun`): `serveBun(app)` runs HTTP + SSE + WebSocket on Bun, reusing the neutral `app.upgrade` / `WsSocket` capability. WebSocket, rooms, and channels behave identically to Node and Deno. - **Cloudflare Workers / edge adapter** (`@green-tea/core/edge`): `edgeHandler(app)` runs HTTP + SSE + WebSocket on workerd, reusing the neutral `app.upgrade` / `WsSocket` capability. Requires the `nodejs_compat` compatibility flag. Green Tea now runs on Node, Deno, Bun, and the edge — with identical WebSocket, rooms, and channel behaviour on all four. - **`app.upgrade(request, socket)`**: neutral WebSocket entry point for non-Node runtimes, built on a shared `WsSocket` capability. WebSocket logic is now runtime-agnostic (`src/http/ws-core.ts`). +- **Mesh (alpha) runs on Node, Deno and Bun** — teapot *and* teacup, in any combination + (a Deno teapot can serve a Node teacup). It no longer needs `app.listen()`: the graph boots on + first use, so `serveDeno`/`serveBun` work through `app.fetch`/`app.upgrade`. Edge is **not** + supported — the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which + `nodejs_compat` does not provide. +- **`MESH_PROTOCOL_VERSION`**: the mesh wire is versioned. Peers exchange it in the `hello`/`manifest` + frames and refuse a mismatch, naming both versions, instead of misreading each other's frames. + The teapot checks the version *before* the secret — a skewed peer is not an auth failure. +- **`HttpError` accepts `headers`**, so a custom error can carry its own response headers + (`retry-after`, `etag`, …) without a special case in the error renderer. ### Fixed - The opt-in dev routes `/__graph__` (graph viewer) and `/__openapi__` are now served over `app.fetch` too, so they work on every runtime (Deno/Bun/edge), not only the Node `app.listen()` path. +- **`request:step:enter`/`leave` are now emitted for `@Ws` and mesh routes.** Only HTTP routes + emitted them, so a logging plugin silently observed nothing on a WebSocket route — a gap in a + documented plugin API. All transports now run their steps through one path. +- **A mesh route exported by two teapots now fails the boot**, naming the route and both teapots, + instead of silently serving whichever connected first and leaving the other dead. There is no + load balancing to fall back on, so green-tea will not pick for you. +- **A local route shadowing a remote one now warns.** Local still takes precedence — that is how you + override a teapot — but a silently shadowed export used to look like a broken teapot. +- **`app.close()` closes mesh links even with no server**, so a mesh app booted through `app.fetch` + (every Deno/Bun deployment) no longer leaks its teapot connections. +- **WebSocket frames arriving during boot are no longer dropped.** `app.upgrade` awaited the boot + before handing the socket to a consumer, and the inbound channel is fan-out, so a peer that spoke + first lost those frames — for mesh, that was the handshake itself. +- The plugins guide documented a `request:step:exit` event that has never existed; the bus emits + `request:step:leave`. ### Changed - App-scope providers now boot exactly once (memoized): a second `app.listen()` diff --git a/src/app/index.ts b/src/app/index.ts index f6c34e5..98e967e 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -503,6 +503,19 @@ async function spliceRemoteScopes( } routeOwners.set(key, teapot.url); + + // Local routes are merged ahead of remote ones (see buildHttpRoutes), so a local twin + // wins. That precedence is deliberate — your own code beats an imported one, and it is + // how you override a teapot — but silently shadowing an export looks exactly like a + // broken teapot from the outside. Warn and let the developer decide. + if (registry.routePlans.some((plan) => plan.method === route.method && plan.pattern === route.pattern)) { + console.warn( + `[green-tea] mesh: route '${key}' is exported by teapot ${teapot.url} but also declared locally — ` + + 'the local route takes precedence and the remote one will not be reached. ' + + 'Remove one if that is not what you meant.', + ); + } + remoteRoutes.push({ method: route.method, pattern: route.pattern, diff --git a/test/mesh/integration.test.ts b/test/mesh/integration.test.ts index 3108417..f7321c9 100644 --- a/test/mesh/integration.test.ts +++ b/test/mesh/integration.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect } from 'vitest'; +import { describe, it, expect, vi } from 'vitest'; import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index'; const SECRET = 's3cr3t'; @@ -45,6 +45,17 @@ class PlainCtl { @Module({ mountpoint: '/', controllers: [PlainCtl] }) class PlainTeacupModule {} +// A teacup declaring a route locally at the same path a teapot exports it. +@Route('/dup') +class ShadowCtl { + @Get('/ping') + ping() { + return { from: 'local' }; + } +} +@Module({ mountpoint: '/api', controllers: [ShadowCtl] }) +class ShadowTeacupModule {} + describe('mesh skeleton integration', () => { it('teacup resolves remote app-scope + request-scope into a local handler', async () => { const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); @@ -119,6 +130,59 @@ describe('mesh skeleton integration', () => { aServer.close(); }); + it('gives a local route precedence over a remote one, and says so', async () => { + // Local-wins is the design: your own code beats an imported one, and it is how you + // override a teapot. But it used to be an accident of [...local, ...remote] ordering + // with nothing said, so a shadowed export looked like a broken teapot. + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const teapot = createApp({ modules: [DupTeapotModule], experimental: true, mesh: { secret: SECRET } }); + const tServer = await teapot.listen(0); + const url = `ws://127.0.0.1:${(tServer.address() as any).port}/__mesh__/control`; + + const teacup = createApp({ + modules: [ShadowTeacupModule], + experimental: true, + mesh: { teapots: [{ url, secret: SECRET }] }, + }); + + try { + const res = await teacup.fetch(new Request('http://x/api/dup/ping')); + expect(await res.json()).toEqual({ from: 'local' }); // local wins, not the teapot's {pong:true} + + const warned = warn.mock.calls.map((c) => String(c[0])).join('\n'); + expect(warned).toMatch(/GET \/api\/dup\/ping/); + expect(warned).toMatch(/local/i); + expect(warned).toContain(url); // which teapot got shadowed + } finally { + warn.mockRestore(); + await teacup.close(); + tServer.close(); + } + }); + + it('does not warn when a remote route has no local twin', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const teapot = createApp({ modules: [DupTeapotModule], experimental: true, mesh: { secret: SECRET } }); + const tServer = await teapot.listen(0); + const url = `ws://127.0.0.1:${(tServer.address() as any).port}/__mesh__/control`; + + const teacup = createApp({ + modules: [PlainTeacupModule], + experimental: true, + mesh: { teapots: [{ url, secret: SECRET }] }, + }); + + try { + await teacup.fetch(new Request('http://x/c/ok')); + const shadowWarnings = warn.mock.calls.filter((c) => String(c[0]).includes('precedence')); + expect(shadowWarnings).toEqual([]); + } finally { + warn.mockRestore(); + await teacup.close(); + tServer.close(); + } + }); + it('rejects a bad secret (teacup boot fails)', async () => { const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); const tServer = await teapot.listen(0); const tPort = (tServer.address() as any).port; diff --git a/website/src/content/docs/guides/mesh.md b/website/src/content/docs/guides/mesh.md index fe9bfae..c0cf60d 100644 --- a/website/src/content/docs/guides/mesh.md +++ b/website/src/content/docs/guides/mesh.md @@ -11,6 +11,19 @@ A **teacup** can depend on a token that physically lives on another node — a * Exports are opt-in (`export: true`) and the control channel is gated by a shared secret. +## What runs where + +Mesh runs on **Node, Deno and Bun**, as both teapot and teacup, in any combination — a Deno teapot can serve a Node teacup. The wire is JSON over a WebSocket, so peers only have to agree on the protocol version, not the runtime. + +**Edge (Cloudflare Workers) is not supported.** The teapot's secret comparison uses `node:crypto`'s `timingSafeEqual`, which workerd's `nodejs_compat` does not provide. + +You do **not** need `listen()`. The graph boots on first use, so `Deno.serve`/`Bun.serve` work through `app.fetch`/`app.upgrade` like any other route: + +```typescript +serveDeno(teapot, { port: 3002 }); // control channel served via app.upgrade +serveBun(teacup, { port: 3003 }); // teapots connected on the first request +``` + ## Node A — teapot (exposes `config`, `auth`, and a route) ```typescript @@ -60,7 +73,37 @@ await teacup.listen(3003); - A **provider** export is **app-scope** — resolved once and cached. - A **step** export is **request-scope** — one RPC per request, carrying the request envelope. -Remote tokens become synthetic nodes in the local graph with RPC-backed runners, so the rest of the pipeline is unchanged. For non-mesh apps `createApp` stays synchronous; mesh apps defer graph finalization to `listen()` so remote scopes can join first. +Remote tokens become synthetic nodes in the local graph with RPC-backed runners, so the rest of the pipeline is unchanged. For non-mesh apps `createApp` stays synchronous; a mesh app defers graph finalization until it boots — connecting to teapots is network I/O — and boots on whichever comes first: `app.fetch`, `app.upgrade` or `listen()`. Whoever triggers it, it happens once. + +## Buffered routes only + +Mesh proxies **buffered** endpoints. `@Sse`, `@Stream` and `@Ws` routes are not exportable: a remote route is registered as `transport: 'buffer'`, and a handler that returns an `AsyncIterable` over a mesh call fails with `cannot proxy a streaming route`. Streams are a live socket between client and server; there is no meaningful way to relay one through an RPC hop today. + +## One teapot per route + +A route must be exported by exactly **one** teapot. If two export the same `method + pattern`, the boot **fails**, naming the route and both teapots: + +``` +mesh: route 'GET /api/svc/ping' is exported by more than one teapot +(ws://a/__mesh__/control and ws://b/__mesh__/control) — load balancing across +teapots is not implemented yet, so green-tea will not choose one for you. +``` + +This is a hard error rather than a silent pick because there is no load balancing to fall back on: choosing one would be an arbitrary answer you could come to depend on. Scope tokens (`@Provider`/`@Step`) are unique for the same reason — and balancing them would be meaningless anyway, since an app-scope export is resolved once and cached. + +**Local routes win.** If you declare a route locally *and* import it from a teapot, yours takes precedence — that is how you override a teapot — and green-tea warns so a shadowed export doesn't look like a broken one: + +``` +[green-tea] mesh: route 'GET /api/svc/ping' is exported by teapot ws://a/… but also +declared locally — the local route takes precedence and the remote one will not be +reached. Remove one if that is not what you meant. +``` + +## Protocol version + +Peers are separate processes on separate deploy cadences, so the wire is versioned: `MESH_PROTOCOL_VERSION` travels in the `hello` and `manifest` frames, and a mismatch is refused on both sides with both versions named. A teapot checks the version **before** the secret — a skewed peer is not an authentication failure, and reporting it as one would send you hunting the wrong bug. + +Bump the version and old peers refuse the connection loudly instead of misreading a frame. :::note[Skeleton limitations (by design)] No discovery, load-balancing, or failover yet; app-scope remote values are not reconciled on reconnect; the request envelope omits `req.url`. diff --git a/website/src/content/docs/guides/runtimes.md b/website/src/content/docs/guides/runtimes.md index e2f8c73..6ce091e 100644 --- a/website/src/content/docs/guides/runtimes.md +++ b/website/src/content/docs/guides/runtimes.md @@ -27,8 +27,9 @@ and body for the same request (enforced by a parity test suite). **All four runtimes now have full WebSocket support:** Node, Deno, and Bun via `serveDeno` / `serveBun`, and Cloudflare Workers / edge via `edgeHandler` (see below) — same graph, same -`@Ws` handlers, same rooms/channels everywhere. `app.listen()`, TLS, per-request timeouts, -and mesh remain Node-only; on Deno/Bun/edge you get `app.fetch` + the runtime's adapter. +`@Ws` handlers, same rooms/channels everywhere. `app.listen()`, TLS and per-request timeouts +remain Node-only; on Deno/Bun/edge you get `app.fetch` + the runtime's adapter. **Mesh (alpha) +runs on Node, Deno and Bun** — teapot and teacup, in any combination — but not on edge. **Body-size enforcement differs slightly:** on `app.fetch`, an oversized body is read in full before the `413` is returned, whereas Node aborts mid-stream once the limit is hit — so on @@ -58,8 +59,9 @@ Any runtime can build a `WsSocket` capability (`inbound`, `abort`, `isOpen`, `se `close`, `terminate`) and drive the graph — `serveBun` and `edgeHandler` build on the same primitive (see below). -**Still Node-only:** `app.listen()`, TLS, per-request timeouts, and mesh. On Deno you -get `app.fetch` + `serveDeno`. +**Still Node-only:** `app.listen()`, TLS and per-request timeouts. On Deno you get +`app.fetch` + `serveDeno`. [Mesh](/guides/mesh/) works here: the control channel is +served through `app.upgrade` and the teacup connects with Deno's global `WebSocket`. ## WebSocket on Bun @@ -80,8 +82,8 @@ serveBun(app, { port: 8000 }); `app.upgrade` — the same graph, the same `@Ws` handlers, the same rooms/channels you run on Node and Deno. Behaviour matches the Node reference. -**Still Node-only:** `app.listen()`, TLS, per-request timeouts, and mesh. On Bun you -get `app.fetch` + `serveBun`. +**Still Node-only:** `app.listen()`, TLS and per-request timeouts. On Bun you get +`app.fetch` + `serveBun`. [Mesh](/guides/mesh/) works here too. ## Cloudflare Workers / edge @@ -113,7 +115,9 @@ compatibility_date = "2024-09-23" # or later Green Tea's core statically imports Node built-ins that workerd only provides under this flag; without it, the Worker fails to load. -**Still Node-only:** `app.listen()`, TLS, per-request timeouts, and mesh. Cloudflare's +**Still Node-only:** `app.listen()`, TLS and per-request timeouts. [Mesh](/guides/mesh/) +is **not** supported on edge: the teapot's secret comparison needs `node:crypto`'s +`timingSafeEqual`, which `nodejs_compat` does not provide. Cloudflare's Durable Objects and WebSocket Hibernation are **not** used — `edgeHandler` accepts WebSockets with the standard `WebSocketPair` model, so a Worker holds the connection open for its lifetime rather than hibernating between messages. From 9886e5374789091207af809ad44ffed53f3a1e84 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 15 Jul 2026 23:00:14 -0500 Subject: [PATCH 13/13] feat(app): add app.ready() so introspection works on any app MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- CHANGELOG.md | 6 ++ src/app/index.ts | 32 ++++++++--- src/app/introspect.ts | 6 +- src/app/types.ts | 12 ++++ test/app.test.ts | 14 +++++ test/mesh/fetch-boot.test.ts | 75 +++++++++++++++++++++++++ website/src/content/docs/guides/mesh.md | 13 +++++ 7 files changed, 147 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4418446..ce9bf08 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,12 @@ green-tea uses calendar versioning: `YY.MM.PATCH`. The teapot checks the version *before* the secret — a skewed peer is not an auth failure. - **`HttpError` accepts `headers`**, so a custom error can carry its own response headers (`retry-after`, `etag`, …) without a special case in the error renderer. +- **`app.ready(): Promise`** — resolves the dependency graph and returns. On a mesh app it + connects the teapots and splices their scopes in; on every other app it is a no-op, so + `await app.ready()` before `inspect()`/`graph()`/`explain()` works against either kind without + knowing which you were handed. It does **not** boot providers: resolving the graph and being + ready to serve are different things, and drawing a diagram should not open your database + connections. Serving boots them too and shares the same memoized step. ### Fixed - The opt-in dev routes `/__graph__` (graph viewer) and `/__openapi__` are now diff --git a/src/app/index.ts b/src/app/index.ts index 98e967e..7226502 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -53,6 +53,21 @@ interface Registry { setRunner(name: string, runner: Runner): void; } +/** + * Memoizes an async step so repeat and concurrent callers share one run. Both boot stages need + * this: `fetch`, `upgrade`, `listen` and `ready` can each be the first to trigger them, and + * re-running would re-splice a mesh or re-run provider factories and their side effects. + */ +function once(run: () => Promise): () => Promise { + let promise: Promise | undefined; + + return (): Promise => { + if (!promise) promise = run(); + + return promise; + }; +} + /** Request-time helpers shared by the HTTP, WS and mesh route builders. */ interface PipelineDeps { providedSeed(plan: RoutePlan): Promise>; @@ -151,6 +166,11 @@ export function createApp(opts: { }); }; + // Memoized separately from the provider boot on purpose: resolving the graph and being ready + // to serve are different things. Introspection needs only the former, and must not run + // provider factories (and open their connections) as a side effect of drawing a diagram. + const ready = once(prepareGraph); + const inspect = (routePath: string): InspectLine[] => inspectRoute(routePlans, routePath, booted); const graph = (): GraphView => buildGraphView(providerNodes, stepNodes, routePlans, booted); const explain = (routePath: string): Explain => explainRoute(routePlans, routePath, booted); @@ -182,7 +202,7 @@ export function createApp(opts: { () => orderedProviders, { runners, container, providerMeta, bus }, degradedProviders, - prepareGraph, + ready, ); const staticResolver = opts.static ? buildStaticResolver(opts.static) : undefined; @@ -250,6 +270,7 @@ export function createApp(opts: { return { listen, close, + ready, fetch: fetchFn, upgrade: upgradeFn, inspect, @@ -603,11 +624,9 @@ function makeAppBooter( bus: Bus; }, degradedProviders: string[], - /** Splices remote mesh scopes in and finalizes the graph. Must precede providers: remote nodes join the topo sort. */ + /** Resolves the graph (splices remote mesh scopes, finalizes). Must precede providers: remote nodes join the topo sort. */ prepareGraph: () => Promise, ): () => Promise { - let bootPromise: Promise | undefined; - const runBoot = async (): Promise => { await prepareGraph(); applyOverrides(overrides, registry); @@ -621,10 +640,7 @@ function makeAppBooter( } }; - return (): Promise => { - if (!bootPromise) bootPromise = runBoot(); - return bootPromise; - }; + return once(runBoot); } /** diff --git a/src/app/introspect.ts b/src/app/introspect.ts index a85f937..22f2450 100644 --- a/src/app/introspect.ts +++ b/src/app/introspect.ts @@ -6,7 +6,7 @@ import type { InspectLine, Explain, ExplainNode, RoutePlan } from './types'; export function inspectRoute(routePlans: RoutePlan[], routePath: string, booted: boolean): InspectLine[] { if (!booted) throw new Error( - 'inspect() unavailable until a mesh app has booted — call listen(), or serve one request through app.fetch/app.upgrade, which splices the remote scopes in', + 'inspect() unavailable until a mesh app has booted: a mesh graph is not knowable until its teapots are asked. Call `await app.ready()` first — it is a no-op on a non-mesh app', ); const plan = routePlans.find((candidate) => candidate.pattern === routePath); if (!plan) throw new Error(`no route: ${routePath}`); @@ -30,7 +30,7 @@ export function buildGraphView( ): GraphView { if (!booted) throw new Error( - 'graph() unavailable until a mesh app has booted — call listen(), or serve one request through app.fetch/app.upgrade, which splices the remote scopes in', + 'graph() unavailable until a mesh app has booted: a mesh graph is not knowable until its teapots are asked. Call `await app.ready()` first — it is a no-op on a non-mesh app', ); return { nodes: [ @@ -62,7 +62,7 @@ export function buildGraphView( export function explainRoute(routePlans: RoutePlan[], routePath: string, booted: boolean): Explain { if (!booted) throw new Error( - 'explain() unavailable until a mesh app has booted — call listen(), or serve one request through app.fetch/app.upgrade, which splices the remote scopes in', + 'explain() unavailable until a mesh app has booted: a mesh graph is not knowable until its teapots are asked. Call `await app.ready()` first — it is a no-op on a non-mesh app', ); const plan = routePlans.find((candidate) => candidate.pattern === routePath); if (!plan) throw new Error(`no route: ${routePath}`); diff --git a/src/app/types.ts b/src/app/types.ts index 50606a1..c8a9bff 100644 --- a/src/app/types.ts +++ b/src/app/types.ts @@ -36,6 +36,18 @@ export interface Explain { export interface App { listen(port: number): Promise; close(): Promise; + /** + * Resolves the dependency graph, then returns. For a mesh app that means connecting to its + * teapots and splicing their scopes in — a mesh graph is not knowable without asking. For every + * other app it is a no-op, so code holding an `App` can `await app.ready()` before + * `inspect()`/`graph()`/`explain()` without caring which kind it was handed. + * + * Deliberately *not* a full boot: it does not run provider factories. Resolving the graph and + * being ready to serve are different things, and drawing a diagram should not open your + * database connections. Serving (`fetch`/`upgrade`/`listen`) boots the providers as well, and + * shares this same memoized step — calling both never resolves the graph twice. + */ + ready(): Promise; /** Web-Standards handler: run a Fetch API Request through the graph and return a Response (Node/Deno/Bun/edge). WS not included. */ fetch(request: Request): Promise; /** Run a WebSocket upgrade through the graph using an adapter-provided socket (Deno/Bun/edge). Node uses its own listener path. */ diff --git a/test/app.test.ts b/test/app.test.ts index fc944ad..1c39576 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -40,6 +40,20 @@ test('inspect lists the ordered chain with origins', () => { expect(lines.map((l) => `${l.kind}:${l.name}`)).toEqual(['provider:db', 'step:user', 'handler:getUser']); }); +test('ready() is a no-op on a non-mesh app, so one protocol works for both', async () => { + // The point: code holding an `App` should not have to know whether it is a mesh app. + // `await app.ready(); app.graph()` is uniform — here it changes nothing and boots nothing. + const app = createApp({ modules: [ApiModule] }); + const booted: string[] = []; + app.bus.on('boot:provider:start', (p) => booted.push(p.name)); + + const before = app.graph().nodes.length; + await app.ready(); + + expect(app.graph().nodes.length).toBe(before); + expect(booted).toEqual([]); +}); + test('a logger plugin observes step:enter without mutating the chain', async () => { const seen: string[] = []; const logger = (api: any) => api.bus.on('request:step:enter', (p: any) => seen.push(p.name)); diff --git a/test/mesh/fetch-boot.test.ts b/test/mesh/fetch-boot.test.ts index 7ba41bd..c75f4c5 100644 --- a/test/mesh/fetch-boot.test.ts +++ b/test/mesh/fetch-boot.test.ts @@ -166,6 +166,81 @@ describe('mesh over app.fetch (no listen)', () => { tServer.close(); }); + it('resolves the graph via ready() without serving a request', async () => { + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); + const tServer = await teapot.listen(0); + const url = teapotUrl((tServer.address() as any).port); + + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + mesh: { teapots: [{ url, secret: SECRET }] }, + }); + + // a mesh graph is not knowable without asking the teapots, so it throws until resolved + expect(() => teacup.graph()).toThrow(/until a mesh app has booted/); + + await teacup.ready(); + + expect(teacup.graph().nodes.some((n) => n.name === 'config')).toBe(true); + expect(teacup.inspect('/api/local/who').map((l) => `${l.kind}:${l.name}`)).toContain('provider:config'); + expect(teacup.explain('/api/local/who')).toBeTruthy(); + + await teacup.close(); + tServer.close(); + }); + + it('ready() resolves the graph but does NOT boot providers', async () => { + // the point of ready() over a full boot: a devtool asking for the graph must not run + // provider factories and open their connections as a side effect + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); + const tServer = await teapot.listen(0); + const url = teapotUrl((tServer.address() as any).port); + + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + mesh: { teapots: [{ url, secret: SECRET }] }, + }); + const booted: string[] = []; + teacup.bus.on('boot:provider:start', (p) => booted.push(p.name)); + + await teacup.ready(); + expect(teacup.graph().nodes.length).toBeGreaterThan(0); // graph is resolved + expect(booted).toEqual([]); // and nothing was booted to get it + + await teacup.fetch(new Request('http://x/api/local/who')); + expect(booted.length).toBeGreaterThan(0); // serving does boot them + + await teacup.close(); + tServer.close(); + }); + + it('ready() is memoized and shared with the boot: a later fetch does not re-splice', async () => { + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); + const tServer = await teapot.listen(0); + const url = teapotUrl((tServer.address() as any).port); + + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + mesh: { teapots: [{ url, secret: SECRET }] }, + }); + let connects = 0; + teacup.bus.on('mesh:connect', () => { + connects += 1; + }); + + await Promise.all([teacup.ready(), teacup.ready()]); + await teacup.fetch(new Request('http://x/api/local/who')); + await teacup.ready(); + + expect(connects).toBe(1); + + await teacup.close(); + tServer.close(); + }); + it('surfaces a failed mesh boot as a request error, not a silent success', async () => { const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); const tServer = await teapot.listen(0); diff --git a/website/src/content/docs/guides/mesh.md b/website/src/content/docs/guides/mesh.md index c0cf60d..b3d9df6 100644 --- a/website/src/content/docs/guides/mesh.md +++ b/website/src/content/docs/guides/mesh.md @@ -75,6 +75,19 @@ await teacup.listen(3003); Remote tokens become synthetic nodes in the local graph with RPC-backed runners, so the rest of the pipeline is unchanged. For non-mesh apps `createApp` stays synchronous; a mesh app defers graph finalization until it boots — connecting to teapots is network I/O — and boots on whichever comes first: `app.fetch`, `app.upgrade` or `listen()`. Whoever triggers it, it happens once. +## Inspecting a mesh graph + +`inspect()`, `graph()` and `explain()` are synchronous, but a mesh graph is not knowable until its teapots have been asked — so on a mesh app they throw until the graph is resolved. `await app.ready()` resolves it: + +```typescript +await app.ready(); // connects the teapots; a no-op on a non-mesh app +app.graph(); // now includes the remote scopes +``` + +Write those two lines and your code works against either kind of app without knowing which it got. `ready()` deliberately does **not** boot providers — resolving the graph and being ready to serve are different things, and drawing a diagram should not open your database connections. Serving (`fetch`/`upgrade`/`listen`) boots them too and shares the same memoized step, so calling both never resolves the graph twice. + +The dev routes (`/__graph__`, `/__openapi__`) need none of this: a request boots the app before the route runs. + ## Buffered routes only Mesh proxies **buffered** endpoints. `@Sse`, `@Stream` and `@Ws` routes are not exportable: a remote route is registered as `transport: 'buffer'`, and a handler that returns an `AsyncIterable` over a mesh call fails with `cannot proxy a streaming route`. Streams are a live socket between client and server; there is no meaningful way to relay one through an RPC hop today.