Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,16 @@ npm treats versions as semver and semver forbids leading zeros.

### Changed

- **Mesh: a token whose teapot is absent at boot is served degraded instead of failing the boot**
(#96, supersedes #56). When a local node `@needs` a token nothing provides and at least one
teapot did not connect, the teacup registers a request-scope step for it that answers `503`
with `retry-after`, warns once naming the token, the absent teapots and a did-you-mean hint, and
emits `mesh:degraded`. When a late teapot exports the token it serves again (`mesh:restored`).
If every late teapot connects and none exports it, one error says so (almost always a typo).
With every teapot connected at boot an unknown token still fails the boot. The mesh contributes
request-scope steps only, never providers. New events: `mesh:degraded`, `mesh:restored`.
Mesh is `@experimental`; no other API change.

- **Mesh: teapots connect in parallel at boot** (#95). Each absent teapot used to cost its own
`bootTimeoutMs` before the next one was tried, so three absent teapots held the boot for three
budgets; now they cost one. Remote steps and routes still register in config order, so the graph
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ green-tea is **beta**, on the road to a release candidate. Express and Fastify h

**mesh is alpha.** Distributed DI works, but discovery, load-balancing, and failover are not built, and its API and wire protocol may change between releases. It is gated behind an explicit opt-in — `createApp({ mesh, experimental: true })` — and `createApp` throws if you configure `mesh` without it. Don't ship mesh to production yet.

**What a teapot exports: steps and routes, and nothing else.** A `@Provider` marked `export: true` fails the boot with an error that says why — a provider's value *is* the object it builds, a pool or a client or a `db`, and the mesh moves data, not objects. Export a `@Step` instead: it runs on the teapot, per request, and its result is what comes back. That is also what lets a teacup boot without its teapot: a remote step holds nothing between requests, so a teacup whose teapot never answers still starts once the `bootTimeoutMs` grace runs out — it warns and carries on. Be precise about what that means, because it is narrower than it sounds. A teapot that never connected sent no manifest, so nothing of it reached the graph: its routes **404** rather than `503`, since nothing was registered to match, and a local step that `@needs` one of its tokens **still fails the boot**, naming the teapot that did not connect. That failure is deliberate — it is the check that catches a typo in a token name, which no amount of waiting will fix. `503` is what you get from a teapot that connected and *later* died, where the link and its exports do exist. So what the change buys is the teacup that does *not* depend on that teapot starting anyway, rather than refusing over a dependency it never had. Keeping a *needed* token serving while its teapot is legitimately away is a known gap, not an oversight: the intended answer is a per-teapot `expects` list that declares what a teapot would export, which is planned and not built.
**What a teapot exports: steps and routes, and nothing else.** A `@Provider` marked `export: true` fails the boot with an error that says why — a provider's value *is* the object it builds, a pool or a client or a `db`, and the mesh moves data, not objects. Export a `@Step` instead: it runs on the teapot, per request, and its result is what comes back. That is also what lets a teacup boot without its teapot: a remote step holds nothing between requests, so a teacup whose teapot never answers still starts once the `bootTimeoutMs` grace runs out — it warns and carries on. Be precise about what that means. A teapot that never connected sent no manifest, so nothing of it reached the graph: its routes **404** rather than `503`, since nothing was registered to match. A token a local node `@needs` that nothing provides is served **degraded** instead: the boot warns, naming the token and the teapots that did not connect, and requests that need it answer `503` with `retry-after` until a late teapot exports it, then serve again. With every teapot connected, an unknown token still fails the boot, because then the mesh was searched and the name is a typo. `503` with `retry-after` is also what a teapot that connected and *later* died gives, while its link reconnects. The mesh only ever contributes request-scope steps, never providers: a remote value can fail at registration, after it, or in the middle of a request.

**What is settled, and what is frozen.** From RC.1 the public surface of the four entry points (`@green-tea/core`, `/deno`, `/bun`, `/edge`) is frozen. Between RC.1 and the first stable release, releases are fixes only: nothing is added, removed, renamed or narrowed. Nothing published in `26.9.0-beta.2` was removed to reach the freeze. [API stability](#api-stability) has the full policy. That covers the graph (`needs`/`provides`, the order derived from them, and the boot-time failure when nothing provides a key), the decorators and handler shapes, the plugin API (`{ name, mount }` with `onShutdown`), the runtime entry points (`serveDeno()` and `serveBun()` are async so they boot before they bind), `createApp`'s options, and the pipeline context, which is one object mutated in place, so a step sees what earlier steps wrote. **Outside the freeze:** mesh, marked `@experimental` and described above. Legacy decorators are a standing *external* risk rather than a green-tea one — see [Why legacy decorators](#why-legacy-decorators). The [matcha](https://github.com/Expressive-Tea/matcha) CLI lives in its own repository and, since RC.1, is released with core under the same version.

Expand Down
2 changes: 1 addition & 1 deletion api/index.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -518,7 +518,7 @@ export function isValidationError(error: unknown): error is ValidationError;
export const JsonTransformer: TransformerFn;

// @public
export type LifecycleEvent = 'boot:provider:start' | 'boot:provider:ok' | 'boot:provider:fail' | 'request:step:enter' | 'request:step:leave' | 'request:step:error' | 'stream:open' | 'stream:close' | 'stream:error' | 'mesh:connect' | 'mesh:disconnect' | 'mesh:rpc:error' | 'mesh:boot:retry' | 'mesh:routes' | 'plugin:mounted' | 'request:start' | 'request:end' | 'request:failed' | 'route:matched' | 'route:unmatched';
export type LifecycleEvent = 'boot:provider:start' | 'boot:provider:ok' | 'boot:provider:fail' | 'request:step:enter' | 'request:step:leave' | 'request:step:error' | 'stream:open' | 'stream:close' | 'stream:error' | 'mesh:connect' | 'mesh:disconnect' | 'mesh:rpc:error' | 'mesh:boot:retry' | 'mesh:routes' | 'mesh:degraded' | 'mesh:restored' | 'plugin:mounted' | 'request:start' | 'request:end' | 'request:failed' | 'route:matched' | 'route:unmatched';

// @public
export interface Link {
Expand Down
124 changes: 97 additions & 27 deletions src/app/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
type SecurityOptions,
type CorsOptions,
} from '../security';
import { HttpError } from '../signals';
import { buildRemote, type RemoteRoute as TeacupRemoteRoute } from '../mesh/teacup';
import {
buildManifest,
Expand All @@ -77,7 +78,7 @@

export type { App, InspectLine, ExplainNode, Explain, MeshConfig, Hooks } from './types';

type Runner = (ctx: any) => any;

Check warning on line 81 in src/app/index.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type

Check warning on line 81 in src/app/index.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type

/** Something shutdown closes: a mesh link, or the retry loop of a teapot that missed boot. */
type Closable = Pick<Link, 'close'>;
Expand Down Expand Up @@ -670,7 +671,7 @@
'is the object itself, and the mesh transports data, not objects. ' +
'Export a @Step instead, which runs on the teapot per request and returns its result.',
);
const instance: any = new ProviderClass();

Check warning on line 674 in src/app/index.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
registry.providerInstances.set(meta.provides, instance);
registry.setRunner(
meta.provides,
Expand All @@ -685,7 +686,7 @@
const meta = getStepMeta(StepClass)!;
registry.stepNodes.push({ name: meta.provides, needs: meta.needs, provides: [meta.provides], origin });
if (meta.export) registry.exportedSteps.push(meta.provides);
const instance: any = new StepClass();

Check warning on line 689 in src/app/index.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
registry.setRunner(
meta.provides,
keyedRunner('step', meta.provides, [meta.provides], (ctx) => instance.run(ctx)),
Expand All @@ -703,7 +704,7 @@
): void {
for (const ControllerClass of controllers) {
for (const route of getRoutes(ControllerClass)) {
const instance: any = new ControllerClass();

Check warning on line 707 in src/app/index.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
const argSpecs = getArgs(ControllerClass, route.handlerName);
const pattern = joinPath(mountpoint, route.path);
const declaration = `${ControllerClass.name}.${route.handlerName}`;
Expand All @@ -725,7 +726,7 @@
steps: [],
handlerName: route.handlerName,
needs: getHandlerNeeds(argSpecs),
run: async (context: any) => instance[route.handlerName](...(await resolveArgs(argSpecs, context))),

Check warning on line 729 in src/app/index.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
transformer,
duplicates: route.duplicates,
maxBodyBytes: route.maxBodyBytes,
Expand Down Expand Up @@ -1002,6 +1003,9 @@
// Cost is linear so it isn't a perf problem — it's a design one. Generous on purpose.
const DEEP_GRAPH_WARN = 20;

/** Tokens every request seeds; a need on one is never missing. */
const REQUEST_SEEDS = ['req', 'params', 'query', 'body', 'headers', 'cookies', 'inbound', 'abort'];

/**
* Topo-sorts the graph, slices each route's provider/step closure into its plan, and validates every need.
* @returns The app-scope providers and request-scope steps in execution order.
Expand Down Expand Up @@ -1060,17 +1064,7 @@
...providerNodes.flatMap((node) => node.provides),
...stepNodes.flatMap((node) => node.provides),
]);
const allowed = new Set<string>([
...producedKeys,
'req',
'params',
'query',
'body',
'headers',
'cookies',
'inbound',
'abort',
]);
const allowed = new Set<string>([...producedKeys, ...REQUEST_SEEDS]);

for (const plan of routePlans) {
for (const need of plan.needs) {
Expand Down Expand Up @@ -1118,11 +1112,9 @@
* a proxied route — so nothing needed this link resolved by boot, and a teacup that refuses to
* start takes down the half of itself that never needed the teapot.
*
* Returning `undefined` is not the same as degrading it. The caller registers nothing for a link it
* never got, because a teapot that did not connect sent no manifest and so nobody knows what it
* would have exported. Its routes 404 like any unregistered path, and a local node that needs one
* of its tokens still fails the boot in finalize(), named. Serving 503 for those tokens instead
* needs an `expects` declaration, which is planned and not built.
* The caller registers nothing for a link it never got, because a teapot that did not connect sent
* no manifest and so nobody knows what it would have exported. Its routes 404 like any unregistered
* path; the tokens local nodes need from it are served degraded (see degradeUnproduced, #96).
*/
async function connectUntilDeadline(
mesh: MeshConfig,
Expand Down Expand Up @@ -1153,16 +1145,15 @@

// The budget is a grace for a co-deploy, not a requirement. Every export is a lazy step or a
// proxied route now, so nothing needed this link resolved by boot, and a teacup that refuses
// to start takes down the half of itself that never needed the teapot. What starting does NOT
// do is degrade the dependency: an absent teapot sent no manifest, so it contributes no nodes
// at all — its routes 404 and a local `needs` on its tokens still fails in finalize().
// to start takes down the half of itself that never needed the teapot. An absent teapot sent no
// manifest, so its routes 404; a local `needs` on its tokens is served degraded (503).
if (remaining <= 0) {
logger.warn(
`mesh: teapot ${url} unreachable after ${attempts} attempt(s) over ${budgetMs}ms ` +
`(${(error as Error).message}) — starting without it. No manifest was ever exchanged, ` +
`so none of its steps or routes are in this graph: its routes 404 like any path that ` +
`was never registered, and the boot still fails if anything local needs one of its ` +
`tokens. This line is what a later 404 on one of its routes points back to.`,
`was never registered, and what local nodes need from it answers 503 until it connects. ` +
`This line is what a later 404 on one of its routes points back to.`,
);
return undefined;
}
Expand Down Expand Up @@ -1398,6 +1389,10 @@
bus: Bus;
logger: Logger;
table: RemoteTable;
/** Tokens served degraded since boot (#96); `run` is filled in when a late teapot exports one. */
degraded: Map<string, { run?: Runner }>;
/** Teapots absent at boot that have not connected yet. */
waiting: Set<string>;
}

/** Applies one teapot's routes after boot and emits `mesh:routes` when the table actually changed. */
Expand Down Expand Up @@ -1438,6 +1433,82 @@
});
}

/**
* Serves degraded every token a local node needs that nothing produces, because an absent teapot may
* be the one that exports it (#96). Nobody can know: it never sent a manifest. Each token becomes a
* request-scope step that answers 503 until a late teapot exports it, and the boot goes on. A typo
* looks the same from here, so the warn carries the did-you-mean hint; with every teapot connected
* the boot still fails on it, since then the mesh was searched.
*
* Request scope only, by design: a remote value can fail at registration, after it, or in the
* middle of a request, so the mesh contributes virtual steps and never providers.
*/
function degradeUnproduced(ctx: MembershipContext, registry: Registry, absent: string[]): void {
const produced = new Set([...registry.providerNodes, ...registry.stepNodes].flatMap((node) => node.provides));
const seeds = new Set([...REQUEST_SEEDS, 'bus']); // 'bus' keeps its own boot error
const needed = [...registry.stepNodes, ...registry.routePlans].flatMap((node) => node.needs);
const bounds = lateBounds(ctx.mesh);
// No late retry means nothing will ever arrive, so no client is told to come back.
const headers = bounds ? { 'retry-after': String(Math.max(1, Math.ceil(bounds.initial / 1000))) } : undefined;

for (const token of new Set(needed)) {
if (produced.has(token) || seeds.has(token)) continue;
const slot: { run?: Runner } = {};
ctx.degraded.set(token, slot);
registry.stepNodes.push({ name: token, needs: [], provides: [token], origin: 'mesh:degraded' });
registry.setRunner(token, (req: unknown) =>
slot.run
? slot.run(req)
: Promise.reject(
new HttpError(503, `mesh: '${token}' is degraded, no connected teapot exports it`, undefined, headers),
),
);

const hint = nearest(token, produced);
ctx.logger.warn(
`mesh: nothing provides '${token}' and these teapots did not connect: ${absent.join(', ')} — serving ` +
`it degraded (503) until one of them exports it.${hint ? ` Did you mean '${hint}'?` : ''}`,
);
ctx.bus.emit('mesh:degraded', { name: token });
}
}

/**
* A late teapot's steps fill the degraded tokens it exports (#96); the rest stay out, because the
* graph was fixed at boot without them. Once every absent teapot has connected, a token still
* degraded is exported by nobody — almost always a typo — and says so once.
*/
function adoptLateSteps(ctx: MembershipContext, url: string, steps: { name: string; run: Runner }[]): void {
const ignored: string[] = [];

for (const step of steps) {
const slot = ctx.degraded.get(step.name);

if (!slot || slot.run) {
ignored.push(step.name);
continue;
}

slot.run = step.run;
ctx.logger.info(`mesh: '${step.name}' is served by ${url} now, no longer degraded`);
ctx.bus.emit('mesh:restored', { name: step.name });
}

if (ignored.length)
ctx.logger.warn(
`mesh: teapot ${url} connected after boot — its routes are served now, but its steps ` +
`(${ignored.join(', ')}) are not: the graph was fixed at boot without them.`,
);

ctx.waiting.delete(url);
const orphans = [...ctx.degraded].filter(([, slot]) => !slot.run).map(([token]) => token);
if (!ctx.waiting.size && orphans.length)
ctx.logger.error(
`mesh: every teapot has connected and none exports ${orphans.map((t) => `'${t}'`).join(', ')} — ` +
`these answer 503 until a restart. Check the token names.`,
);
}

/** Backoff bounds for retrying a late teapot: the reconnect ones, or nothing when reconnect is off. */
function lateBounds(mesh: MeshConfig): { initial: number; max: number } | undefined {
if (mesh.reconnect === false) return undefined;
Expand Down Expand Up @@ -1473,11 +1544,7 @@
if (stopped) return link.close();
holder.link = link;
const { steps, routes } = buildRemote(link);
if (steps.length)
ctx.logger.warn(
`mesh: teapot ${teapot.url} connected after boot — its routes are served now, but its steps ` +
`(${steps.map((step) => step.name).join(', ')}) are not: the graph was fixed at boot without them.`,
);
adoptLateSteps(ctx, teapot.url, steps);
applyMembership(ctx, teapot.url, routes);
} catch (error) {
if (stopped) return;
Expand Down Expand Up @@ -1526,7 +1593,7 @@
reserved,
publish,
);
const ctx: MembershipContext = { mesh, bus, logger, table };
const ctx: MembershipContext = { mesh, bus, logger, table, degraded: new Map(), waiting: new Set() };

// All teapots connect at once, so N absent ones cost one boot budget rather than N (#95). A refusal
// still fails the boot immediately; the attempts still running are closed as they land, since
Expand Down Expand Up @@ -1558,6 +1625,7 @@

if (!link) {
absent.push(teapot.url);
ctx.waiting.add(teapot.url);
const bounds = lateBounds(mesh);
if (bounds) meshLinks.push(retryLateTeapot(ctx, teapot, bounds));
continue;
Expand All @@ -1579,6 +1647,8 @@
throw err;
}

if (absent.length) degradeUnproduced(ctx, registry, absent);

return { meshLinks, absent };
}

Expand Down Expand Up @@ -1784,7 +1854,7 @@

const resolveScope = async (name: string, env: RequestEnvelope): Promise<unknown> => {
// context is intentionally `any`: providers and steps merge arbitrary keys into it
const seed: any = { req: env, params: env.params, query: env.query, body: env.body, headers: env.headers };

Check warning on line 1857 in src/app/index.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
// The teapot gates names before this runs, so an exported token always has a slice.
const { providers, steps } = slices.get(name)!;

Expand All @@ -1807,7 +1877,7 @@
const plan = routePlans.find((candidate) => candidate.pattern === name && candidate.method === env.method);

if (!plan) {
const error: any = new Error(`no route ${name}`);

Check warning on line 1880 in src/app/index.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
error.status = 404;
throw error;
}
Expand All @@ -1832,7 +1902,7 @@
});

if ('stream' in result) {
const error: any = new Error('cannot proxy a streaming route');

Check warning on line 1905 in src/app/index.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
error.status = 500;
throw error;
}
Expand Down
17 changes: 10 additions & 7 deletions src/app/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@
steps: GraphNode[];
handlerName: string;
needs: string[];
run: (ctx: any) => Promise<unknown>;

Check warning on line 120 in src/app/types.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
transformer: typeof JsonTransformer;
duplicates?: 'array' | 'last';
maxBodyBytes?: number;
Expand Down Expand Up @@ -180,18 +180,21 @@
* passes the teacup warns and starts anyway: every export is a step or a proxied route, so
* nothing needed that link resolved by boot.
*
* Starting is not degrading, though. A teapot that never connected sent no manifest, so none of
* its steps or routes are registered: its routes 404 rather than 503, and a local node that needs
* one of its tokens still fails the boot, naming it. A permanent refusal — a wrong secret, a
* protocol mismatch — fails at once without spending the grace.
* A teapot that never connected sent no manifest, so its routes are not registered: they 404
* rather than 503. A token a local node needs that nothing provides is served **degraded**
* instead (#96): a request-scope step that answers `503` with `retry-after`, announced once by a
* warn and a `mesh:degraded` event. With every teapot connected an unknown token still fails the
* boot, so a typo stays a boot error. A permanent refusal — a wrong secret, a protocol mismatch —
* fails at once without spending the grace.
*
* After boot, such a teapot keeps being retried in the background with the `reconnect` backoff
* (not with `reconnect: false`). When it connects, its routes are added to the table and served;
* its steps are not, because the graph was validated at boot without them (D15).
* (not with `reconnect: false`, and then a degraded token sends no `retry-after`). When it
* connects, its routes are served and the degraded tokens it exports serve again
* (`mesh:restored`); its other steps are not added, because the graph was fixed at boot (D15).
*
* `0` means one attempt and no grace. That is the attempt count boot used to have, and nothing
* more: exhausting it no longer fails the boot, so a single unreachable teapot still warns and
* starts. To make a teapot's absence fatal, have something local `@needs` one of its tokens.
* starts.
*/
bootTimeoutMs?: number;
/**
Expand Down
5 changes: 5 additions & 0 deletions src/bus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@ export type LifecycleEvent =
// A teacup's remote routes changed after boot (D15): a late teapot connected, a returning one
// exported a different set, or a link gave up for good. Carries `url`, `added` and `removed`.
| 'mesh:routes'
// A token a local node needs has no producer while a teapot is absent, so it is served degraded:
// its requests answer 503 until a late teapot exports it (#96). Once per token, at boot; the
// 503s themselves are counted by `request:end`. `mesh:restored` is the same token served again.
| 'mesh:degraded'
| 'mesh:restored'
| 'plugin:mounted'
// Paired: see the guarantee above. `request:start` has no status and no duration — it says a
// request arrived, not that it routed.
Expand Down
Loading