diff --git a/CHANGELOG.md b/CHANGELOG.md index 4418446..ce9bf08 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,12 @@ green-tea uses calendar versioning: `YY.MM.PATCH`. The teapot checks the version *before* the secret — a skewed peer is not an auth failure. - **`HttpError` accepts `headers`**, so a custom error can carry its own response headers (`retry-after`, `etag`, …) without a special case in the error renderer. +- **`app.ready(): Promise`** — resolves the dependency graph and returns. On a mesh app it + connects the teapots and splices their scopes in; on every other app it is a no-op, so + `await app.ready()` before `inspect()`/`graph()`/`explain()` works against either kind without + knowing which you were handed. It does **not** boot providers: resolving the graph and being + ready to serve are different things, and drawing a diagram should not open your database + connections. Serving boots them too and shares the same memoized step. ### Fixed - The opt-in dev routes `/__graph__` (graph viewer) and `/__openapi__` are now diff --git a/src/app/index.ts b/src/app/index.ts index 98e967e..7226502 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -53,6 +53,21 @@ interface Registry { setRunner(name: string, runner: Runner): void; } +/** + * Memoizes an async step so repeat and concurrent callers share one run. Both boot stages need + * this: `fetch`, `upgrade`, `listen` and `ready` can each be the first to trigger them, and + * re-running would re-splice a mesh or re-run provider factories and their side effects. + */ +function once(run: () => Promise): () => Promise { + let promise: Promise | undefined; + + return (): Promise => { + if (!promise) promise = run(); + + return promise; + }; +} + /** Request-time helpers shared by the HTTP, WS and mesh route builders. */ interface PipelineDeps { providedSeed(plan: RoutePlan): Promise>; @@ -151,6 +166,11 @@ export function createApp(opts: { }); }; + // Memoized separately from the provider boot on purpose: resolving the graph and being ready + // to serve are different things. Introspection needs only the former, and must not run + // provider factories (and open their connections) as a side effect of drawing a diagram. + const ready = once(prepareGraph); + const inspect = (routePath: string): InspectLine[] => inspectRoute(routePlans, routePath, booted); const graph = (): GraphView => buildGraphView(providerNodes, stepNodes, routePlans, booted); const explain = (routePath: string): Explain => explainRoute(routePlans, routePath, booted); @@ -182,7 +202,7 @@ export function createApp(opts: { () => orderedProviders, { runners, container, providerMeta, bus }, degradedProviders, - prepareGraph, + ready, ); const staticResolver = opts.static ? buildStaticResolver(opts.static) : undefined; @@ -250,6 +270,7 @@ export function createApp(opts: { return { listen, close, + ready, fetch: fetchFn, upgrade: upgradeFn, inspect, @@ -603,11 +624,9 @@ function makeAppBooter( bus: Bus; }, degradedProviders: string[], - /** Splices remote mesh scopes in and finalizes the graph. Must precede providers: remote nodes join the topo sort. */ + /** Resolves the graph (splices remote mesh scopes, finalizes). Must precede providers: remote nodes join the topo sort. */ prepareGraph: () => Promise, ): () => Promise { - let bootPromise: Promise | undefined; - const runBoot = async (): Promise => { await prepareGraph(); applyOverrides(overrides, registry); @@ -621,10 +640,7 @@ function makeAppBooter( } }; - return (): Promise => { - if (!bootPromise) bootPromise = runBoot(); - return bootPromise; - }; + return once(runBoot); } /** diff --git a/src/app/introspect.ts b/src/app/introspect.ts index a85f937..22f2450 100644 --- a/src/app/introspect.ts +++ b/src/app/introspect.ts @@ -6,7 +6,7 @@ import type { InspectLine, Explain, ExplainNode, RoutePlan } from './types'; export function inspectRoute(routePlans: RoutePlan[], routePath: string, booted: boolean): InspectLine[] { if (!booted) throw new Error( - 'inspect() unavailable until a mesh app has booted — call listen(), or serve one request through app.fetch/app.upgrade, which splices the remote scopes in', + 'inspect() unavailable until a mesh app has booted: a mesh graph is not knowable until its teapots are asked. Call `await app.ready()` first — it is a no-op on a non-mesh app', ); const plan = routePlans.find((candidate) => candidate.pattern === routePath); if (!plan) throw new Error(`no route: ${routePath}`); @@ -30,7 +30,7 @@ export function buildGraphView( ): GraphView { if (!booted) throw new Error( - 'graph() unavailable until a mesh app has booted — call listen(), or serve one request through app.fetch/app.upgrade, which splices the remote scopes in', + 'graph() unavailable until a mesh app has booted: a mesh graph is not knowable until its teapots are asked. Call `await app.ready()` first — it is a no-op on a non-mesh app', ); return { nodes: [ @@ -62,7 +62,7 @@ export function buildGraphView( export function explainRoute(routePlans: RoutePlan[], routePath: string, booted: boolean): Explain { if (!booted) throw new Error( - 'explain() unavailable until a mesh app has booted — call listen(), or serve one request through app.fetch/app.upgrade, which splices the remote scopes in', + 'explain() unavailable until a mesh app has booted: a mesh graph is not knowable until its teapots are asked. Call `await app.ready()` first — it is a no-op on a non-mesh app', ); const plan = routePlans.find((candidate) => candidate.pattern === routePath); if (!plan) throw new Error(`no route: ${routePath}`); diff --git a/src/app/types.ts b/src/app/types.ts index 50606a1..c8a9bff 100644 --- a/src/app/types.ts +++ b/src/app/types.ts @@ -36,6 +36,18 @@ export interface Explain { export interface App { listen(port: number): Promise; close(): Promise; + /** + * Resolves the dependency graph, then returns. For a mesh app that means connecting to its + * teapots and splicing their scopes in — a mesh graph is not knowable without asking. For every + * other app it is a no-op, so code holding an `App` can `await app.ready()` before + * `inspect()`/`graph()`/`explain()` without caring which kind it was handed. + * + * Deliberately *not* a full boot: it does not run provider factories. Resolving the graph and + * being ready to serve are different things, and drawing a diagram should not open your + * database connections. Serving (`fetch`/`upgrade`/`listen`) boots the providers as well, and + * shares this same memoized step — calling both never resolves the graph twice. + */ + ready(): Promise; /** Web-Standards handler: run a Fetch API Request through the graph and return a Response (Node/Deno/Bun/edge). WS not included. */ fetch(request: Request): Promise; /** Run a WebSocket upgrade through the graph using an adapter-provided socket (Deno/Bun/edge). Node uses its own listener path. */ diff --git a/test/app.test.ts b/test/app.test.ts index fc944ad..1c39576 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -40,6 +40,20 @@ test('inspect lists the ordered chain with origins', () => { expect(lines.map((l) => `${l.kind}:${l.name}`)).toEqual(['provider:db', 'step:user', 'handler:getUser']); }); +test('ready() is a no-op on a non-mesh app, so one protocol works for both', async () => { + // The point: code holding an `App` should not have to know whether it is a mesh app. + // `await app.ready(); app.graph()` is uniform — here it changes nothing and boots nothing. + const app = createApp({ modules: [ApiModule] }); + const booted: string[] = []; + app.bus.on('boot:provider:start', (p) => booted.push(p.name)); + + const before = app.graph().nodes.length; + await app.ready(); + + expect(app.graph().nodes.length).toBe(before); + expect(booted).toEqual([]); +}); + test('a logger plugin observes step:enter without mutating the chain', async () => { const seen: string[] = []; const logger = (api: any) => api.bus.on('request:step:enter', (p: any) => seen.push(p.name)); diff --git a/test/mesh/fetch-boot.test.ts b/test/mesh/fetch-boot.test.ts index 7ba41bd..c75f4c5 100644 --- a/test/mesh/fetch-boot.test.ts +++ b/test/mesh/fetch-boot.test.ts @@ -166,6 +166,81 @@ describe('mesh over app.fetch (no listen)', () => { tServer.close(); }); + it('resolves the graph via ready() without serving a request', async () => { + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); + const tServer = await teapot.listen(0); + const url = teapotUrl((tServer.address() as any).port); + + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + mesh: { teapots: [{ url, secret: SECRET }] }, + }); + + // a mesh graph is not knowable without asking the teapots, so it throws until resolved + expect(() => teacup.graph()).toThrow(/until a mesh app has booted/); + + await teacup.ready(); + + expect(teacup.graph().nodes.some((n) => n.name === 'config')).toBe(true); + expect(teacup.inspect('/api/local/who').map((l) => `${l.kind}:${l.name}`)).toContain('provider:config'); + expect(teacup.explain('/api/local/who')).toBeTruthy(); + + await teacup.close(); + tServer.close(); + }); + + it('ready() resolves the graph but does NOT boot providers', async () => { + // the point of ready() over a full boot: a devtool asking for the graph must not run + // provider factories and open their connections as a side effect + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); + const tServer = await teapot.listen(0); + const url = teapotUrl((tServer.address() as any).port); + + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + mesh: { teapots: [{ url, secret: SECRET }] }, + }); + const booted: string[] = []; + teacup.bus.on('boot:provider:start', (p) => booted.push(p.name)); + + await teacup.ready(); + expect(teacup.graph().nodes.length).toBeGreaterThan(0); // graph is resolved + expect(booted).toEqual([]); // and nothing was booted to get it + + await teacup.fetch(new Request('http://x/api/local/who')); + expect(booted.length).toBeGreaterThan(0); // serving does boot them + + await teacup.close(); + tServer.close(); + }); + + it('ready() is memoized and shared with the boot: a later fetch does not re-splice', async () => { + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); + const tServer = await teapot.listen(0); + const url = teapotUrl((tServer.address() as any).port); + + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + mesh: { teapots: [{ url, secret: SECRET }] }, + }); + let connects = 0; + teacup.bus.on('mesh:connect', () => { + connects += 1; + }); + + await Promise.all([teacup.ready(), teacup.ready()]); + await teacup.fetch(new Request('http://x/api/local/who')); + await teacup.ready(); + + expect(connects).toBe(1); + + await teacup.close(); + tServer.close(); + }); + it('surfaces a failed mesh boot as a request error, not a silent success', async () => { const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); const tServer = await teapot.listen(0); diff --git a/website/src/content/docs/guides/mesh.md b/website/src/content/docs/guides/mesh.md index c0cf60d..b3d9df6 100644 --- a/website/src/content/docs/guides/mesh.md +++ b/website/src/content/docs/guides/mesh.md @@ -75,6 +75,19 @@ await teacup.listen(3003); Remote tokens become synthetic nodes in the local graph with RPC-backed runners, so the rest of the pipeline is unchanged. For non-mesh apps `createApp` stays synchronous; a mesh app defers graph finalization until it boots — connecting to teapots is network I/O — and boots on whichever comes first: `app.fetch`, `app.upgrade` or `listen()`. Whoever triggers it, it happens once. +## Inspecting a mesh graph + +`inspect()`, `graph()` and `explain()` are synchronous, but a mesh graph is not knowable until its teapots have been asked — so on a mesh app they throw until the graph is resolved. `await app.ready()` resolves it: + +```typescript +await app.ready(); // connects the teapots; a no-op on a non-mesh app +app.graph(); // now includes the remote scopes +``` + +Write those two lines and your code works against either kind of app without knowing which it got. `ready()` deliberately does **not** boot providers — resolving the graph and being ready to serve are different things, and drawing a diagram should not open your database connections. Serving (`fetch`/`upgrade`/`listen`) boots them too and shares the same memoized step, so calling both never resolves the graph twice. + +The dev routes (`/__graph__`, `/__openapi__`) need none of this: a request boots the app before the route runs. + ## Buffered routes only Mesh proxies **buffered** endpoints. `@Sse`, `@Stream` and `@Ws` routes are not exportable: a remote route is registered as `transport: 'buffer'`, and a handler that returns an `AsyncIterable` over a mesh call fails with `cannot proxy a streaming route`. Streams are a live socket between client and server; there is no meaningful way to relay one through an RPC hop today.