diff --git a/src/app/index.ts b/src/app/index.ts index c320650..f89abe5 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -30,7 +30,7 @@ import { connectLink, type Link } from '../mesh/link'; import { Rooms } from '../rooms'; import type { TlsOptions, SecurityOptions, CorsOptions } from '../security'; import { buildRemote } from '../mesh/teacup'; -import { buildManifest, createMeshControl } from '../mesh/teapot'; +import { buildManifest, createMeshControl, MESH_CONTROL_PATH } from '../mesh/teapot'; import type { MeshControl } from '../http'; import type { RequestEnvelope, RouteEntry } from '../mesh/protocol'; import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types'; @@ -127,14 +127,28 @@ export function createApp(opts: { if (!opts.mesh) finalize(); - // mesh teacup: connect remote teapots and splice their scopes/routes in, then finalize. - const prepareGraph = async (): Promise => { - if (!opts.mesh || booted) return; + const providedSeed = (plan: RoutePlan) => seedProviders(container, plan); + const planSteps = (plan: RoutePlan) => compilePlanSteps(runners, plan); + const pipelineDeps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError }; + let meshControl: MeshControl | undefined; - const spliced = await spliceRemoteScopes(opts.mesh, bus, registry); - remoteRoutes = spliced.remoteRoutes; - meshLinks.push(...spliced.meshLinks); - finalize(); + // mesh teacup: connect remote teapots and splice their scopes/routes in, then finalize. + // mesh teapot: build the control channel — it captures the *finalized* ordered nodes, so it + // can only be built here, after finalize(), and never at construction time. + const prepareGraph = async (): Promise => { + if (opts.mesh && !booted) { + const spliced = await spliceRemoteScopes(opts.mesh, bus, registry); + remoteRoutes = spliced.remoteRoutes; + meshLinks.push(...spliced.meshLinks); + finalize(); + } + + meshControl = buildMeshControl(opts.mesh, registry, { + container, + orderedProviders, + orderedSteps, + deps: pipelineDeps, + }); }; const inspect = (routePath: string): InspectLine[] => inspectRoute(routePlans, routePath, booted); @@ -160,9 +174,6 @@ export function createApp(opts: { return routes; }; - const providedSeed = (plan: RoutePlan) => seedProviders(container, plan); - const planSteps = (plan: RoutePlan) => compilePlanSteps(runners, plan); - // Boots exactly once, however first triggered (app.fetch, app.upgrade or listen()); calling // several never double-boots (which would re-run provider factories and their side effects). const bootApp = makeAppBooter( @@ -194,26 +205,15 @@ export function createApp(opts: { devRoutes, () => remoteRoutes, ); - const upgradeFn = buildAppUpgrade( - routePlans, - { providedSeed, planSteps, bus, onError: opts.onError }, - streams, - bootApp, - ); + const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl); const listen = async (port: number): Promise => { - const deps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError }; + const deps = pipelineDeps; - // the same gate app.fetch uses: splices remote mesh scopes, finalizes, boots providers + // the same gate app.fetch uses: splices remote mesh scopes, finalizes, boots providers, + // and builds the mesh control channel — so Node and Deno/Bun serve an identical graph await bootApp(); - const meshControl = buildMeshControl(opts.mesh, registry, { - container, - orderedProviders, - orderedSteps, - deps, - }); - const httpRoutes = [...buildHttpRoutes(routePlans, remoteRoutes, deps), ...devRoutes()]; const wsRoutes = buildWsRoutes(routePlans, deps); @@ -235,7 +235,13 @@ export function createApp(opts: { const close = (): Promise => new Promise((resolve) => { + // before the server check: a mesh app booted through app.fetch (Deno/Bun, where listen() + // never runs) has links but no server, and would otherwise leak every teapot connection. + // Closing a link rejects its in-flight RPCs via the socket's abort. + closeLinks(meshLinks); + if (!server) return resolve(); + server.close(() => resolve()); // waits for in-flight buffered to drain for (const closeStream of streams) closeStream(); // force-close long-lived SSE/WS so close() resolves server.closeIdleConnections(); // Node >=18.2: drop idle keep-alive @@ -735,23 +741,49 @@ function buildAppUpgrade( deps: PipelineDeps, streams: Set<() => void>, ensureBooted: () => Promise, + getMeshControl: () => MeshControl | undefined, ): (request: WsRequest, socket: WsSocket) => Promise { let wsRoutes: WsRouteDef[] | undefined; return async (request: WsRequest, socket: WsSocket): Promise => { + // Subscribe to inbound BEFORE awaiting the boot. `channel` is fan-out: a frame pushed with no + // subscriber is dropped, so anything the peer sends while providers are still booting would be + // lost. For the mesh control channel that is the `hello` itself — the handshake would hang + // until timeout against a teapot whose providers happened to boot slowly. + const frames = socket.inbound[Symbol.asyncIterator](); + const ready: WsSocket = Object.create(socket, { + inbound: { value: { [Symbol.asyncIterator]: () => frames } }, + }) as WsSocket; + await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted - if (!wsRoutes) wsRoutes = buildWsRoutes(routePlans, deps); - const path = request.url.split('?')[0]; - const route = matchWsRoute(wsRoutes, path); + const meshControl = getMeshControl(); - if (!route) { - socket.close(1008, 'no matching ws route'); + // The reserved mesh path, checked before route matching: this is what lets a teapot export + // its scopes from Deno/Bun, where the Node `server.on('upgrade')` path does not exist. + if (path === MESH_CONTROL_PATH) { + // an explicit refusal, not "no matching ws route": the path is reserved either way, and a + // peer that reached a teapot with nothing exported deserves to be told which it was + if (!meshControl) { + ready.close(1008, 'mesh control channel not enabled: this app exports nothing, or has no mesh.secret'); + return; + } + + await meshControl.handle(ready); return; } - await runWsConnection(socket, request, route, deps.bus, streams); + if (!wsRoutes) wsRoutes = buildWsRoutes(routePlans, deps); + + const route = matchWsRoute(wsRoutes, path); + + if (!route) { + ready.close(1008, 'no matching ws route'); + return; + } + + await runWsConnection(ready, request, route, deps.bus, streams); }; } diff --git a/src/http/types.ts b/src/http/types.ts index 4526f69..7ea2406 100644 --- a/src/http/types.ts +++ b/src/http/types.ts @@ -76,6 +76,7 @@ export interface MeshControl { /** * Serves one control connection over the neutral socket — the same capability every other ws * consumer takes, so Node (via `nodeSocket`) and Deno/Bun (via `app.upgrade`) both feed it. + * Resolves when the connection ends, like `runWsConnection`. */ - handle(socket: WsSocket): void; + handle(socket: WsSocket): Promise; } diff --git a/src/http/ws.ts b/src/http/ws.ts index 1665ada..6c8188a 100644 --- a/src/http/ws.ts +++ b/src/http/ws.ts @@ -40,7 +40,8 @@ function handleMeshUpgrade( // nodeSocket, not the raw ws: the control channel is the last consumer that spoke the // `ws` EventEmitter API directly. It now takes the same neutral socket every route does. - wss.handleUpgrade(req, socket, head, (ws: any) => meshControl.handle(nodeSocket(ws))); + // serveFrames swallows its own failures, so the floating promise cannot reject + wss.handleUpgrade(req, socket, head, (ws: any) => void meshControl.handle(nodeSocket(ws))); return true; } diff --git a/src/mesh/teapot.ts b/src/mesh/teapot.ts index f453633..c59503b 100644 --- a/src/mesh/teapot.ts +++ b/src/mesh/teapot.ts @@ -182,16 +182,23 @@ async function serveFrames( } /** Build a control handler that authenticates peers and serves scope/route RPCs from the manifest. */ -export function createMeshControl(deps: MeshControlDeps): { path: string; handle: (socket: WsSocket) => void } { +export function createMeshControl(deps: MeshControlDeps): { + path: string; + handle: (socket: WsSocket) => Promise; +} { const exportedScopes = new Set(deps.manifest.scopes.map((scope) => scope.token)); const exportedRoutes = new Set(deps.manifest.routes.map((route) => `${route.method} ${route.pattern}`)); return { path: MESH_CONTROL_PATH, - handle(socket: WsSocket) { - // `channel` is fan-out and subscribes when the async iterator is created, which - // `for await` does synchronously — so the loop is live before any frame can arrive. - void serveFrames(socket, deps, exportedScopes, exportedRoutes); + /** + * Resolves when the connection ends, mirroring `runWsConnection` — so `app.upgrade` can await + * the control channel's lifetime the same way it awaits a regular ws route's. + * `channel` is fan-out and subscribes when the async iterator is created, which `for await` + * does synchronously, so the loop is live before any frame can arrive. + */ + handle(socket: WsSocket): Promise { + return serveFrames(socket, deps, exportedScopes, exportedRoutes); }, }; } diff --git a/test/mesh/control-upgrade.test.ts b/test/mesh/control-upgrade.test.ts index cd50118..454b4dd 100644 --- a/test/mesh/control-upgrade.test.ts +++ b/test/mesh/control-upgrade.test.ts @@ -5,7 +5,7 @@ import { createHttpServer, type MeshControl } from '../../src/http'; describe('mesh control upgrade', () => { it('routes the reserved path to meshControl.handle and leaves wsRoutes intact', async () => { let handled = false; - const meshControl: MeshControl = { path: '/__mesh__/control', handle: (ws) => { handled = true; ws.send('hi'); } }; + const meshControl: MeshControl = { path: '/__mesh__/control', handle: async (ws) => { handled = true; ws.send('hi'); } }; const server = createHttpServer([], [], undefined, meshControl); await new Promise((r) => server.listen(0, r)); const port = (server.address() as any).port; diff --git a/test/mesh/fetch-boot.test.ts b/test/mesh/fetch-boot.test.ts index 49c1477..7ba41bd 100644 --- a/test/mesh/fetch-boot.test.ts +++ b/test/mesh/fetch-boot.test.ts @@ -1,5 +1,8 @@ import { describe, it, expect } from 'vitest'; import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index'; +import { channel } from '../../src/channel'; +import { encode, decode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol'; +import type { WsSocket, WsRequest } from '../../src/http/ws-core'; const SECRET = 's3cr3t'; @@ -28,8 +31,43 @@ class LocalCtl { @Module({ mountpoint: '/api', controllers: [LocalCtl] }) class TeacupModule {} +@Route('/plain') +class PlainCtl { + @Get('/ok') + ok() { + return { ok: true }; + } +} +@Module({ mountpoint: '/', controllers: [PlainCtl] }) +class PlainModule {} + const teapotUrl = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`; +/** A neutral socket, exactly what serveDeno/serveBun hand to app.upgrade. */ +const fakePeer = () => { + const inbound = channel(); + const ac = new AbortController(); + const sent: any[] = []; + const closed: { code?: number; reason?: string }[] = []; + const socket: WsSocket = { + inbound, + abort: ac.signal, + isOpen: true, + send: (data: string) => { + sent.push(decode(data)); + }, + close: (code, reason) => { + closed.push({ code, reason }); + inbound.close(); + ac.abort(); + }, + terminate: () => ac.abort(), + }; + return { socket, sent, closed, inbound }; +}; + +const controlReq = (): WsRequest => ({ url: '/__mesh__/control', headers: {}, protocol: 'http', ip: '' }); + /** * A mesh teacup driven purely through `app.fetch` — the entry point Deno/Bun/edge use. * `listen()` is never called on the teacup, because on those runtimes it cannot be: @@ -104,6 +142,30 @@ describe('mesh over app.fetch (no listen)', () => { tServer.close(); }); + it('closes the teapot links, even with no server to hang the close off', async () => { + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); + const tServer = await teapot.listen(0); + const url = teapotUrl((tServer.address() as any).port); + + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + mesh: { teapots: [{ url, secret: SECRET }] }, + }); + const disconnects: string[] = []; + teacup.bus.on('mesh:disconnect', (p) => disconnects.push(p.name)); + + await teacup.fetch(new Request('http://x/api/local/who')); + expect(disconnects).toEqual([]); + + // listen() never ran, so there is no server whose 'close' could reap the links + await teacup.close(); + await new Promise((r) => setTimeout(r, 50)); + + expect(disconnects).toEqual([url]); + tServer.close(); + }); + it('surfaces a failed mesh boot as a request error, not a silent success', async () => { const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); const tServer = await teapot.listen(0); @@ -121,3 +183,51 @@ describe('mesh over app.fetch (no listen)', () => { tServer.close(); }); }); + +/** + * A teapot *exporting* over app.upgrade — the path serveDeno/serveBun drive. Without this the + * control channel only existed on Node's server.on('upgrade'), so a teapot could not run off Node + * and "mesh on 3 runtimes" would have meant consuming only. + */ +describe('mesh control over app.upgrade (no listen)', () => { + it('serves the handshake to a peer that never touched a Node server', async () => { + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); + const peer = fakePeer(); + + void teapot.upgrade(controlReq(), peer.socket); + peer.inbound.push(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: SECRET })); + await new Promise((r) => setTimeout(r, 20)); + + expect(peer.sent[0]).toMatchObject({ + type: 'manifest', + v: MESH_PROTOCOL_VERSION, + scopes: expect.arrayContaining([{ token: 'config', scope: 'app' }]), + }); + await teapot.close(); + }); + + it('rejects a bad secret over app.upgrade too', async () => { + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); + const peer = fakePeer(); + + void teapot.upgrade(controlReq(), peer.socket); + peer.inbound.push(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: 'WRONG' })); + await new Promise((r) => setTimeout(r, 20)); + + expect(peer.sent).toEqual([]); + expect(peer.closed[0].code).toBe(1008); + await teapot.close(); + }); + + it('refuses the reserved path explicitly on an app that exports nothing', async () => { + // a plain, self-contained app: the path is reserved regardless, so say so rather than + // let it fall through to the generic "no matching ws route" + const plain = createApp({ modules: [PlainModule] }); + const peer = fakePeer(); + + await plain.upgrade(controlReq(), peer.socket); + + expect(peer.closed[0].code).toBe(1008); + expect(peer.closed[0].reason).toMatch(/mesh control channel not enabled/i); + }); +});