feat(app): add app.ready() so introspection works on any app
inspect()/graph()/explain() are synchronous, but a mesh graph is not knowable
until its teapots have been asked, so on a mesh app they threw and the caller had
no way to fix it. Code holding an `App` could not tell which kind it had — the
Liskov complaint from the audit, and the last of it: fetch/upgrade stopped
throwing when the boot moved into the gate.
app.ready() resolves the graph and returns. On a mesh app it connects the
teapots; on every other app it is a no-op. So one shape works for both:
await app.ready();
app.graph();
which is what actually restores substitutability — a uniform protocol, not a type
that describes the asymmetry.
Deliberately not a full boot: it does not run provider factories. Resolving the
graph and being ready to serve are different things, and a devtool drawing a
diagram should not open your database connections. Serving boots them too and
shares the same memoized step, so ready() then fetch() resolves the graph once.
The guards stay — sync code cannot await network I/O — but the message names the
fix instead of describing the trap.
createApp hit 26 on the complexity gate with ready() added. Both boot stages had
their own copy of the same memoisation, so it collapses into one `once` helper
used by both, which is a smaller createApp than before this change.
Refs .specs/2026-07-15-green-tea-solid-audit (App/Mesh LSP)
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
7 files changed
+147
-11
No files matched your search
@@ -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<void>`** — 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
|
||||
|
||||
+24
-8
@@ -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<void>): () => Promise<void> {
|
||||
let promise: Promise<void> | undefined;
|
||||
|
||||
return (): Promise<void> => {
|
||||
if (!promise) promise = run();
|
||||
|
||||
return promise;
|
||||
};
|
||||
}
|
||||
|
||||
/** Request-time helpers shared by the HTTP, WS and mesh route builders. */
|
||||
interface PipelineDeps {
|
||||
providedSeed(plan: RoutePlan): Promise<Record<string, unknown>>;
|
||||
@@ -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<void>,
|
||||
): () => Promise<void> {
|
||||
let bootPromise: Promise<void> | undefined;
|
||||
|
||||
const runBoot = async (): Promise<void> => {
|
||||
await prepareGraph();
|
||||
applyOverrides(overrides, registry);
|
||||
@@ -621,10 +640,7 @@ function makeAppBooter(
|
||||
}
|
||||
};
|
||||
|
||||
return (): Promise<void> => {
|
||||
if (!bootPromise) bootPromise = runBoot();
|
||||
return bootPromise;
|
||||
};
|
||||
return once(runBoot);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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}`);
|
||||
|
||||
@@ -36,6 +36,18 @@ export interface Explain {
|
||||
export interface App {
|
||||
listen(port: number): Promise<http.Server>;
|
||||
close(): Promise<void>;
|
||||
/**
|
||||
* 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<void>;
|
||||
/** 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<Response>;
|
||||
/** Run a WebSocket upgrade through the graph using an adapter-provided socket (Deno/Bun/edge). Node uses its own listener path. */
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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.
|
||||
|
||||
Reference in new issue
Block a user