diff --git a/src/app/index.ts b/src/app/index.ts index 13ae295..c320650 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -112,10 +112,13 @@ export function createApp(opts: { // For each route, resolve which providers/steps feed it via topo order. // MVP: every route depends on every declared step + provider in the app graph. - // For mesh apps, finalize is DEFERRED to listen() so remote scopes can join the graph first. + // For mesh apps, finalize is DEFERRED to the boot gate so remote scopes can join the graph + // first — connecting to teapots is network I/O, so it cannot happen during construction. let orderedProviders: GraphNode[] = []; let orderedSteps: GraphNode[] = []; let booted = false; + let remoteRoutes: RouteDef[] = []; + const meshLinks: Link[] = []; const finalize = (): void => { ({ orderedProviders, orderedSteps } = finalizeGraph(registry)); @@ -124,6 +127,16 @@ export function createApp(opts: { if (!opts.mesh) finalize(); + // mesh teacup: connect remote teapots and splice their scopes/routes in, then finalize. + const prepareGraph = async (): Promise => { + if (!opts.mesh || booted) return; + + const spliced = await spliceRemoteScopes(opts.mesh, bus, registry); + remoteRoutes = spliced.remoteRoutes; + meshLinks.push(...spliced.meshLinks); + finalize(); + }; + const inspect = (routePath: string): InspectLine[] => inspectRoute(routePlans, routePath, booted); const graph = (): GraphView => buildGraphView(providerNodes, stepNodes, routePlans, booted); const explain = (routePath: string): Explain => explainRoute(routePlans, routePath, booted); @@ -150,14 +163,15 @@ export function createApp(opts: { const providedSeed = (plan: RoutePlan) => seedProviders(container, plan); const planSteps = (plan: RoutePlan) => compilePlanSteps(runners, plan); - // Boots app-scope providers exactly once, however first triggered (app.fetch or listen()); calling - // both never double-boots (which would re-run provider factories and their side effects). - const bootAppProviders = makeProviderBooter( + // Boots exactly once, however first triggered (app.fetch, app.upgrade or listen()); calling + // several never double-boots (which would re-run provider factories and their side effects). + const bootApp = makeAppBooter( registry, opts.overrides, () => orderedProviders, { runners, container, providerMeta, bus }, degradedProviders, + prepareGraph, ); const staticResolver = opts.static ? buildStaticResolver(opts.static) : undefined; @@ -173,36 +187,25 @@ export function createApp(opts: { static: staticResolver, }; const fetchFn = buildAppFetch( - () => booted, routePlans, { providedSeed, planSteps, bus, onError: opts.onError }, fetchOpts, - bootAppProviders, + bootApp, devRoutes, + () => remoteRoutes, ); const upgradeFn = buildAppUpgrade( - () => booted, routePlans, { providedSeed, planSteps, bus, onError: opts.onError }, streams, - bootAppProviders, + bootApp, ); const listen = async (port: number): Promise => { const deps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError }; - // mesh teacup: connect remote teapots, splice their scopes/routes into the graph, then finalize - let remoteRoutes: RouteDef[] = []; - const meshLinks: Link[] = []; - - if (opts.mesh && !booted) { - const spliced = await spliceRemoteScopes(opts.mesh, bus, registry); - remoteRoutes = spliced.remoteRoutes; - meshLinks.push(...spliced.meshLinks); - finalize(); - } - - await bootAppProviders(); + // the same gate app.fetch uses: splices remote mesh scopes, finalizes, boots providers + await bootApp(); const meshControl = buildMeshControl(opts.mesh, registry, { container, @@ -547,11 +550,13 @@ async function bootProviders( } /** - * Returns a memoized boot function: applies overrides and boots app-scope providers exactly once, - * however first triggered — {@link buildAppFetch}'s handler or `listen()` may both call it, and the - * memoization guarantees only the first call actually runs (and warns about) the boot sequence. + * Returns a memoized boot function: prepares the graph, applies overrides and boots app-scope + * providers exactly once, however first triggered — `app.fetch`, `app.upgrade` and `listen()` may + * all call it, and the memoization guarantees only the first runs the sequence. This is the single + * place an app becomes ready, which is what lets a mesh app boot on any runtime rather than only + * where `listen()` (a Node http.Server) can be built. */ -function makeProviderBooter( +function makeAppBooter( registry: Registry, overrides: Record | undefined, getOrderedProviders: () => GraphNode[], @@ -562,10 +567,13 @@ function makeProviderBooter( bus: Bus; }, degradedProviders: string[], + /** Splices remote mesh scopes in and finalizes the graph. Must precede providers: remote nodes join the topo sort. */ + prepareGraph: () => Promise, ): () => Promise { let bootPromise: Promise | undefined; const runBoot = async (): Promise => { + await prepareGraph(); applyOverrides(overrides, registry); degradedProviders.length = 0; degradedProviders.push(...(await bootProviders(getOrderedProviders(), deps))); @@ -691,29 +699,27 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps /** * Builds `app.fetch`: a Web-Standards handler over the same route table `listen()` uses, so * `Deno.serve(app.fetch)` / `Bun.serve({ fetch: app.fetch })` work without ever calling `listen()`. - * Non-mesh apps finalize eagerly, so `getBooted()` is already `true` and the route table is built - * on the very first call. Mesh apps defer finalize to `listen()` (remote scopes must splice into the - * graph first): `getBooted` reads the outer `booted` flag *live* on every call — exactly like - * `explain()`/`graph()`/`inspect()` do — so the returned function throws until `listen()` finalizes, - * then starts working from the next call on, without ever needing to be rebuilt. + * The boot is awaited *before* the route table is built: for a mesh app the table is not knowable + * until remote scopes have spliced in, and the boot is what does that. Both are memoized, so this + * costs one flag check per request after the first. */ function buildAppFetch( - getBooted: () => boolean, routePlans: RoutePlan[], deps: PipelineDeps, fetchOpts: HttpOptions, ensureBooted: () => Promise, devRoutes: () => RouteDef[], + getRemoteRoutes: () => RouteDef[], ): (request: Request) => Promise { let handler: ((request: Request) => Promise) | undefined; return async (request: Request): Promise => { + await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted + if (!handler) { - if (!getBooted()) throw new Error('fetch() unavailable before listen() for mesh apps'); - handler = buildFetch([...buildHttpRoutes(routePlans, [], deps), ...devRoutes()], fetchOpts); + handler = buildFetch([...buildHttpRoutes(routePlans, getRemoteRoutes(), deps), ...devRoutes()], fetchOpts); } - await ensureBooted(); // idempotent: no-op if listen() already booted the providers return handler(request); }; } @@ -722,12 +728,9 @@ function buildAppFetch( * Builds `app.upgrade`: the neutral WebSocket entry over the same route table `listen()` uses, so * Deno/Bun/edge adapters can drive ws connections without ever calling `listen()`. Node keeps its own * `server.on('upgrade')` path (see `attachWs`) and never calls this. - * Mirrors {@link buildAppFetch}'s finalize guard exactly: non-mesh apps finalize eagerly, so - * `getBooted()` is already `true` and the ws route table builds on the first call; mesh apps defer - * finalize to `listen()`, so this throws until `listen()` finalizes, then works from the next call on. + * Mirrors {@link buildAppFetch}: the boot is awaited before the ws route table is built. */ function buildAppUpgrade( - getBooted: () => boolean, routePlans: RoutePlan[], deps: PipelineDeps, streams: Set<() => void>, @@ -736,12 +739,10 @@ function buildAppUpgrade( let wsRoutes: WsRouteDef[] | undefined; return async (request: WsRequest, socket: WsSocket): Promise => { - if (!wsRoutes) { - if (!getBooted()) throw new Error('upgrade() unavailable before listen() for mesh apps'); - wsRoutes = buildWsRoutes(routePlans, deps); - } + await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted + + if (!wsRoutes) wsRoutes = buildWsRoutes(routePlans, deps); - await ensureBooted(); // idempotent: no-op if listen() already booted the providers const path = request.url.split('?')[0]; const route = matchWsRoute(wsRoutes, path); diff --git a/src/app/introspect.ts b/src/app/introspect.ts index 7607c3d..a85f937 100644 --- a/src/app/introspect.ts +++ b/src/app/introspect.ts @@ -4,7 +4,10 @@ import type { InspectLine, Explain, ExplainNode, RoutePlan } from './types'; /** Lists the provider/step/handler chain for a route, in execution order. */ export function inspectRoute(routePlans: RoutePlan[], routePath: string, booted: boolean): InspectLine[] { - if (!booted) throw new Error('inspect() unavailable before listen() for mesh apps'); + if (!booted) + throw new Error( + 'inspect() unavailable until a mesh app has booted — call listen(), or serve one request through app.fetch/app.upgrade, which splices the remote scopes in', + ); const plan = routePlans.find((candidate) => candidate.pattern === routePath); if (!plan) throw new Error(`no route: ${routePath}`); return [ @@ -25,7 +28,10 @@ export function buildGraphView( routePlans: RoutePlan[], booted: boolean, ): GraphView { - if (!booted) throw new Error('graph() unavailable before listen() for mesh apps'); + if (!booted) + throw new Error( + 'graph() unavailable until a mesh app has booted — call listen(), or serve one request through app.fetch/app.upgrade, which splices the remote scopes in', + ); return { nodes: [ ...providerNodes.map((node) => ({ @@ -54,7 +60,10 @@ export function buildGraphView( /** Explains a single route: its match criteria and the ordered chain with each node's needs/provides. */ export function explainRoute(routePlans: RoutePlan[], routePath: string, booted: boolean): Explain { - if (!booted) throw new Error('explain() unavailable before listen() for mesh apps'); + if (!booted) + throw new Error( + 'explain() unavailable until a mesh app has booted — call listen(), or serve one request through app.fetch/app.upgrade, which splices the remote scopes in', + ); const plan = routePlans.find((candidate) => candidate.pattern === routePath); if (!plan) throw new Error(`no route: ${routePath}`); const toExplainNode = (node: GraphNode, kind: 'provider' | 'step'): ExplainNode => ({ diff --git a/test/fetch.test.ts b/test/fetch.test.ts index 1d0373b..5505077 100644 --- a/test/fetch.test.ts +++ b/test/fetch.test.ts @@ -110,17 +110,36 @@ describe('app.fetch trustProxy gates x-forwarded-for', () => { }); }); -describe('app.fetch mesh gating (live `booted` read)', () => { - it('throws before listen() and starts working after listen() finalizes', async () => { +describe('app.fetch on a mesh app', () => { + // Previously this asserted fetch() *threw* until listen() ran, which made mesh Node-only: + // Deno/Bun/edge serve through app.fetch and can never call listen() (it builds an http.Server). + // The boot gate now finalizes the mesh graph on first use, whoever triggers it. + it('serves without ever calling listen()', async () => { const meshApp = createApp({ modules: [MeshModule], experimental: true, mesh: { secret: 's3cr3t' } }); - await expect(meshApp.fetch(new Request('http://x/api/mesh/ping'))).rejects.toThrow(/unavailable before listen/); + const res = await meshApp.fetch(new Request('http://x/api/mesh/ping')); + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ pong: true }); + await meshApp.close(); + }); + + it('does not re-boot when listen() follows a fetch', async () => { + const meshApp = createApp({ modules: [MeshModule], experimental: true, mesh: { secret: 's3cr3t' } }); + let booted = 0; + meshApp.bus.on('boot:provider:start', () => { + booted += 1; + }); + + await meshApp.fetch(new Request('http://x/api/mesh/ping')); + const bootsAfterFetch = booted; const server = await meshApp.listen(0); + try { const res = await meshApp.fetch(new Request('http://x/api/mesh/ping')); expect(res.status).toBe(200); - expect(await res.json()).toEqual({ pong: true }); + // listen() shares fetch's memoized gate: provider factories must not run twice + expect(booted).toBe(bootsAfterFetch); } finally { server.close(); } diff --git a/test/mesh/fetch-boot.test.ts b/test/mesh/fetch-boot.test.ts new file mode 100644 index 0000000..49c1477 --- /dev/null +++ b/test/mesh/fetch-boot.test.ts @@ -0,0 +1,123 @@ +import { describe, it, expect } from 'vitest'; +import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index'; + +const SECRET = 's3cr3t'; + +@Provider({ provides: 'config', export: true }) +class Config { + provide() { + return { config: { region: 'mx' } }; + } +} +@Step({ provides: 'auth', needs: [], export: true }) +class Auth { + run(ctx: any) { + return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; + } +} +@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] }) +class TeapotModule {} + +@Route('/local') +class LocalCtl { + @Get('/who') + who(@needs('config') config: any, @needs('auth') auth: any) { + return { config, auth }; + } +} +@Module({ mountpoint: '/api', controllers: [LocalCtl] }) +class TeacupModule {} + +const teapotUrl = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`; + +/** + * A mesh teacup driven purely through `app.fetch` — the entry point Deno/Bun/edge use. + * `listen()` is never called on the teacup, because on those runtimes it cannot be: + * it builds a Node http.Server. + */ +describe('mesh over app.fetch (no listen)', () => { + it('boots the mesh graph on the first request and resolves remote scopes', async () => { + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); + const tServer = await teapot.listen(0); + const url = teapotUrl((tServer.address() as any).port); + + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + mesh: { teapots: [{ url, secret: SECRET }] }, + }); + + const res = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } })); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ config: { region: 'mx' }, auth: { token: 'abc' } }); + + await teacup.close(); + tServer.close(); + }); + + it('boots exactly once across concurrent first requests', async () => { + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); + const tServer = await teapot.listen(0); + const url = teapotUrl((tServer.address() as any).port); + + let connects = 0; + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + mesh: { teapots: [{ url, secret: SECRET }] }, + }); + teacup.bus.on('mesh:connect', () => { + connects += 1; + }); + + const hit = () => teacup.fetch(new Request('http://x/api/local/who')); + const all = await Promise.all([hit(), hit(), hit()]); + + expect(all.map((r) => r.status)).toEqual([200, 200, 200]); + expect(connects).toBe(1); // the boot gate is memoized: three racing requests splice once + + await teacup.close(); + tServer.close(); + }); + + it('serves the remote scope in inspect() once a request has booted the graph', async () => { + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); + const tServer = await teapot.listen(0); + const url = teapotUrl((tServer.address() as any).port); + + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + mesh: { teapots: [{ url, secret: SECRET }] }, + }); + + await teacup.fetch(new Request('http://x/api/local/who')); + const chain = teacup.inspect('/api/local/who').map((line) => `${line.kind}:${line.name}`); + + // the remote provider and step spliced into the local route's chain + expect(chain).toContain('provider:config'); + expect(chain).toContain('step:auth'); + expect(teacup.graph().nodes.some((n) => n.name === 'config')).toBe(true); + + await teacup.close(); + tServer.close(); + }); + + it('surfaces a failed mesh boot as a request error, not a silent success', async () => { + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); + const tServer = await teapot.listen(0); + const url = teapotUrl((tServer.address() as any).port); + + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + mesh: { teapots: [{ url, secret: 'WRONG' }], timeoutMs: 800 }, + }); + + await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow(); + + await teacup.close(); + tServer.close(); + }); +});