diff --git a/CHANGELOG.md b/CHANGELOG.md index cd43a36..ce9bf08 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,17 +13,47 @@ 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. +- **`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 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/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/src/app/index.ts b/src/app/index.ts index a624c6e..7226502 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'; @@ -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'; @@ -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>; @@ -112,10 +127,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 +142,35 @@ export function createApp(opts: { if (!opts.mesh) finalize(); + 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; + + // 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, + }); + }; + + // 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); @@ -147,17 +194,15 @@ export function createApp(opts: { return routes; }; - 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, + ready, ); const staticResolver = opts.static ? buildStaticResolver(opts.static) : undefined; @@ -173,43 +218,21 @@ 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, - ); + 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; - // 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(); - - const meshControl = buildMeshControl(opts.mesh, registry, { - container, - orderedProviders, - orderedSteps, - deps, - }); + // 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 httpRoutes = [...buildHttpRoutes(routePlans, remoteRoutes, deps), ...devRoutes()]; const wsRoutes = buildWsRoutes(routePlans, deps); @@ -232,7 +255,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 @@ -241,6 +270,7 @@ export function createApp(opts: { return { listen, close, + ready, fetch: fetchFn, upgrade: upgradeFn, inspect, @@ -457,6 +487,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 ?? []) { @@ -477,6 +508,35 @@ 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); + + // 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, @@ -547,11 +607,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 +624,11 @@ function makeProviderBooter( bus: Bus; }, degradedProviders: string[], + /** 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); degradedProviders.length = 0; degradedProviders.push(...(await bootProviders(getOrderedProviders(), deps))); @@ -577,10 +640,7 @@ function makeProviderBooter( } }; - return (): Promise => { - if (!bootPromise) bootPromise = runBoot(); - return bootPromise; - }; + return once(runBoot); } /** @@ -606,15 +666,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]; }; @@ -693,29 +751,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); }; } @@ -724,35 +780,56 @@ 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>, ensureBooted: () => Promise, + getMeshControl: () => MeshControl | undefined, ): (request: WsRequest, socket: WsSocket) => Promise { 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); - } + // 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 - await ensureBooted(); // idempotent: no-op if listen() already booted the providers 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); }; } @@ -788,7 +865,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 +875,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/app/introspect.ts b/src/app/introspect.ts index 7607c3d..22f2450 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: 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}`); 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: 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: [ ...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: 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}`); const toExplainNode = (node: GraphNode, kind: 'provider' | 'step'): ExplainNode => ({ 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/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/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/http/types.ts b/src/http/types.ts index 5e5f444..7ea2406 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,10 @@ 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. + * Resolves when the connection ends, like `runWsConnection`. + */ + handle(socket: WsSocket): Promise; } diff --git a/src/http/ws-adapter.ts b/src/http/ws-adapter.ts new file mode 100644 index 0000000..8f9307e --- /dev/null +++ b/src/http/ws-adapter.ts @@ -0,0 +1,162 @@ +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: 'open' | 'message' | 'close' | 'error', + listener: (event: { data?: string | ArrayBuffer; error?: unknown }) => 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 */ + } + }, + }; +} + +/** 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, + * 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 + }); +} diff --git a/src/http/ws.ts b/src/http/ws.ts index 2f34b8a..6c8188a 100644 --- a/src/http/ws.ts +++ b/src/http/ws.ts @@ -38,7 +38,10 @@ 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. + // 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/link.ts b/src/mesh/link.ts index 397364a..a2ce38e 100644 --- a/src/mesh/link.ts +++ b/src/mesh/link.ts @@ -1,8 +1,8 @@ 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) +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(). */ export interface Link { @@ -18,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) { @@ -36,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', @@ -51,29 +45,25 @@ 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, - connId: string, - 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; return { manifest, rpc(kind, name, ctx) { - const id = `${connId}:${counter++}`; + 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(); }, }; } @@ -97,50 +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(); - const connId = `c${connSeq++}`; - 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', 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') { - manifest = { scopes: frame.scopes, routes: frame.routes }; + const hs: Handshake = { + url: args.url, + socket, + pending, + timeoutMs, + bus: args.bus, + resolve, + reject, + onManifest: () => { + manifest = true; clearTimeout(connectTimer); - args.bus?.emit('mesh:connect', { name: args.url }); - resolve(buildLink(ws, pending, manifest, connId, timeoutMs)); - return; - } + }, + }; - if (frame.type === 'rpc-res') { - settleRpcResponse(pending, frame, args.bus); - } + opened.then( + () => socket.send(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: args.secret })), + (error) => reject(error), + ); + + // 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 }, + ); + + void readFrames(hs).catch(() => { + /* inbound failed; the abort listener above reports it */ }); }); } 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..c59503b 100644 --- a/src/mesh/teapot.ts +++ b/src/mesh/teapot.ts @@ -1,8 +1,20 @@ -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 { 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 +61,44 @@ function notExported(name: string): Error { return error; } -/** Validate an unauthenticated hello frame; reply with the manifest on success or close on mismatch. */ -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' }); +/** + * 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(socket: WsSocket, frame: Frame, deps: MeshControlDeps): boolean { + if (frame.type !== 'hello') { + socket.close(1008); - return true; + return false; } - ws.close(1008); + if (frame.v !== MESH_PROTOCOL_VERSION) { + socket.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)) { + socket.close(1008); + + return false; + } + + socket.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. */ @@ -85,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, @@ -96,44 +134,71 @@ 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) => 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(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' })); + /** + * 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/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/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/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) }; } 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/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/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/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/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); +}); 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 new file mode 100644 index 0000000..c75f4c5 --- /dev/null +++ b/test/mesh/fetch-boot.test.ts @@ -0,0 +1,308 @@ +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'; + +@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 {} + +@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: + * 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('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('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); + 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(); + }); +}); + +/** + * 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); + }); +}); diff --git a/test/mesh/integration.test.ts b/test/mesh/integration.test.ts index 98bbf37..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'; @@ -23,6 +23,39 @@ 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 {} + +// 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 } }); @@ -52,6 +85,104 @@ 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('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/test/mesh/link.test.ts b/test/mesh/link.test.ts index 69bdd18..d80965e 100644 --- a/test/mesh/link.test.ts +++ b/test/mesh/link.test.ts @@ -1,7 +1,10 @@ import { describe, it, expect } from 'vitest'; -import { WebSocketServer } from 'ws'; +import WS, { WebSocketServer } from 'ws'; import { connectLink } from '../../src/mesh/link'; -import { encode, decode } from '../../src/mesh/protocol'; +import { loadWebSocketCtor, type SocketCtor } from '../../src/http/ws-adapter'; +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 +16,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 +36,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 +44,64 @@ 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() }; +} + +/** + * 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[] = []; + 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..50f92fb 100644 --- a/test/mesh/teapot.test.ts +++ b/test/mesh/teapot.test.ts @@ -1,15 +1,45 @@ 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'; +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', () => { @@ -22,63 +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', 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', () => { - const ws = fakeWs(); make().handle(ws); - ws.emit('message', encode({ type: 'hello', secret: 'good' })); - expect(ws.sent[0]).toMatchObject({ type: 'manifest', 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', async () => { + const t = fakeSocket(); + make().handle(t.socket); + // correct secret, wrong protocol: must still be refused — and not as an auth failure + 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', 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', 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', 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', 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']); + }); }); diff --git a/website/src/content/docs/guides/mesh.md b/website/src/content/docs/guides/mesh.md index fe9bfae..b3d9df6 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,50 @@ 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. + +## 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. + +## 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/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: 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.