diff --git a/CHANGELOG.md b/CHANGELOG.md index d2389a7..fbb481e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/README.md b/README.md index 32c7ec6..7073d1c 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/api/index.api.md b/api/index.api.md index e5243d9..07414df 100644 --- a/api/index.api.md +++ b/api/index.api.md @@ -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 { diff --git a/src/app/index.ts b/src/app/index.ts index 3ad2b63..1769b82 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -58,6 +58,7 @@ import { type SecurityOptions, type CorsOptions, } from '../security'; +import { HttpError } from '../signals'; import { buildRemote, type RemoteRoute as TeacupRemoteRoute } from '../mesh/teacup'; import { buildManifest, @@ -1002,6 +1003,9 @@ function provideBuiltins(registry: Registry, logger: Logger, bus: Bus): void { // 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. @@ -1060,17 +1064,7 @@ function assertNeedsSatisfiable( ...providerNodes.flatMap((node) => node.provides), ...stepNodes.flatMap((node) => node.provides), ]); - const allowed = new Set([ - ...producedKeys, - 'req', - 'params', - 'query', - 'body', - 'headers', - 'cookies', - 'inbound', - 'abort', - ]); + const allowed = new Set([...producedKeys, ...REQUEST_SEEDS]); for (const plan of routePlans) { for (const need of plan.needs) { @@ -1118,11 +1112,9 @@ function assertNeedsSatisfiable( * 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, @@ -1153,16 +1145,15 @@ async function connectUntilDeadline( // 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; } @@ -1398,6 +1389,10 @@ interface MembershipContext { bus: Bus; logger: Logger; table: RemoteTable; + /** Tokens served degraded since boot (#96); `run` is filled in when a late teapot exports one. */ + degraded: Map; + /** Teapots absent at boot that have not connected yet. */ + waiting: Set; } /** Applies one teapot's routes after boot and emits `mesh:routes` when the table actually changed. */ @@ -1438,6 +1433,82 @@ function connectTeapot( }); } +/** + * 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; @@ -1473,11 +1544,7 @@ function retryLateTeapot( 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; @@ -1526,7 +1593,7 @@ async function spliceRemoteScopes( 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 @@ -1558,6 +1625,7 @@ async function spliceRemoteScopes( if (!link) { absent.push(teapot.url); + ctx.waiting.add(teapot.url); const bounds = lateBounds(mesh); if (bounds) meshLinks.push(retryLateTeapot(ctx, teapot, bounds)); continue; @@ -1579,6 +1647,8 @@ async function spliceRemoteScopes( throw err; } + if (absent.length) degradeUnproduced(ctx, registry, absent); + return { meshLinks, absent }; } diff --git a/src/app/types.ts b/src/app/types.ts index bb0b045..bae0e11 100644 --- a/src/app/types.ts +++ b/src/app/types.ts @@ -180,18 +180,21 @@ export interface MeshConfig { * 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; /** diff --git a/src/bus.ts b/src/bus.ts index c89691a..c4dce3c 100644 --- a/src/bus.ts +++ b/src/bus.ts @@ -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. diff --git a/test/bun/mesh-reconnect.test.ts b/test/bun/mesh-reconnect.test.ts index 47af3f7..1ecdecb 100644 --- a/test/bun/mesh-reconnect.test.ts +++ b/test/bun/mesh-reconnect.test.ts @@ -213,3 +213,36 @@ test('mesh on Bun: three absent teapots boot in about one bootTimeoutMs', async await teacup.close(); } }, 15_000); + +// #96: a token whose teapot was absent at boot answers 503, then serves once the teapot connects. +test('mesh on Bun: a degraded token serves again once its teapot connects late', async () => { + const port = freePort(); + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + logger: { debug() {}, info() {}, warn() {}, error() {} }, + mesh: { + teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: SECRET }], + timeoutMs: 2000, + bootTimeoutMs: 0, + reconnect: { initialDelayMs: 20, maxDelayMs: 60 }, + }, + }); + let teapot: Awaited> | undefined; + + try { + const down = await teacup.fetch(new Request('http://x/api/local/who')); + expect(down.status).toBe(503); + expect(down.headers.get('retry-after')).toBe('1'); + + teapot = await startTeapot(port); + await settle(400); + + const up = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } })); + expect(up.status).toBe(200); + expect((await up.json()).auth).toEqual({ token: 'abc' }); + } finally { + await teacup.close(); + await teapot?.stop(); + } +}, 15_000); diff --git a/test/deno/mesh-reconnect.test.ts b/test/deno/mesh-reconnect.test.ts index 38b029b..e2b3839 100644 --- a/test/deno/mesh-reconnect.test.ts +++ b/test/deno/mesh-reconnect.test.ts @@ -218,3 +218,37 @@ Deno.test('mesh on Deno: three absent teapots boot in about one bootTimeoutMs', await teacup.close(); } }); + +// #96: a token whose teapot was absent at boot answers 503, then serves once the teapot connects. +Deno.test('mesh on Deno: a degraded token serves again once its teapot connects late', async () => { + const port = freePort(); + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + logger: { debug() {}, info() {}, warn() {}, error() {} }, + mesh: { + teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: SECRET }], + timeoutMs: 2000, + bootTimeoutMs: 0, + reconnect: { initialDelayMs: 20, maxDelayMs: 60 }, + }, + }); + let teapot: Awaited> | undefined; + + try { + const down = await teacup.fetch(new Request('http://x/api/local/who')); + assertEquals(down.status, 503); + assertEquals(down.headers.get('retry-after'), '1'); + await down.body?.cancel(); + + teapot = await startTeapot(port); + await settle(400); + + const up = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } })); + assertEquals(up.status, 200); + assertEquals((await up.json()).auth, { token: 'abc' }); + } finally { + await teacup.close(); + await teapot?.stop(); + } +}); diff --git a/test/mesh/boot-retry.test.ts b/test/mesh/boot-retry.test.ts index f686728..58d4a77 100644 --- a/test/mesh/boot-retry.test.ts +++ b/test/mesh/boot-retry.test.ts @@ -55,7 +55,10 @@ const freePort = async (): Promise => const collect = () => { const lines: string[] = []; - return { lines, logger: { debug() {}, info() {}, warn: (m: string) => lines.push(m), error: (m: string) => lines.push(m) } }; + return { + lines, + logger: { debug() {}, info() {}, warn: (m: string) => lines.push(m), error: (m: string) => lines.push(m) }, + }; }; describe('mesh boot retry', () => { @@ -91,7 +94,7 @@ describe('mesh boot retry', () => { } }, 15_000); - it('still fails the boot once the budget is spent — a needed provider is not optional', async () => { + it('serves a needed token degraded once the budget is spent, instead of failing the boot (#96)', async () => { const { lines, logger } = collect(); const teacup = createApp({ modules: [TeacupModule], @@ -105,38 +108,47 @@ describe('mesh boot retry', () => { }); try { - // exhausting the budget is no longer fatal by itself (that's the point of this change) — - // the boot still fails here because `who` needs 'auth' and nothing local provides it. The - // exact message, not a bare /mesh/ match (which would also match this message's own - // "(local or connected mesh)" wording for an unrelated reason). - await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow( - /needs 'auth' but nothing \(local or connected mesh\) provides it[\s\S]*did not connect/i, - ); + const res = await teacup.fetch(new Request('http://x/api/local/who')); + expect(res.status).toBe(503); + expect(res.headers.get('retry-after')).toBe('1'); expect(lines.some((l) => l.includes('starting without it'))).toBe(true); + const warn = lines.find((l) => l.includes('serving it degraded')); + expect(warn).toContain("'auth'"); + expect(warn).toContain('ws://127.0.0.1:1/__mesh__/control'); } finally { await teacup.close(); } }, 15_000); - it('names the absent teapot when a route handler needs its token directly', async () => { - // `who` needs 'auth' via `@needs`, not through a `@Step` — this goes through - // `assertNeedsSatisfiable`, a different check than `topoSort`'s, and must carry the same note. + it('still fails the boot on an unknown token when every teapot connected — typos stay boot errors', async () => { + @Route('/typo') + class TypoCtl { + @Get('/') + who(@needs('auht') auth: any) { + return { auth }; + } + } + @Module({ mountpoint: '/api', controllers: [TypoCtl] }) + class TypoModule {} + + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } }); + const server = await teapot.listen(0); + const port = (server.address() as { port: number }).port; const teacup = createApp({ - modules: [TeacupModule], + modules: [TypoModule], experimental: true, - mesh: { - teapots: [{ url: 'ws://127.0.0.1:9/x', secret: 's' }], - secret: 's', - bootTimeoutMs: 300, - }, + logger: collect().logger, + mesh: { teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'good' }] }, }); try { await expect(teacup.ready()).rejects.toThrow( - /needs 'auth' but nothing \(local or connected mesh\) provides it[\s\S]*did not connect.*127\.0\.0\.1:9/i, + /needs 'auht' but nothing \(local or mesh\) provides it — did you mean 'auth'/, ); } finally { await teacup.close(); + await teapot.close(); + server.close(); } }, 15_000); @@ -226,10 +238,21 @@ describe('mesh boot retry', () => { } }, 15_000); - it('still fails the boot when a local step needs a token the absent teapot owned', async () => { + it('boots when a local step needs a token the absent teapot owned, and that step answers 503', async () => { + @Route('/profile') + class ProfileCtl { + @Get('/') + get(@needs('profile') profile: any) { + return { profile }; + } + } + @Module({ mountpoint: '/api', steps: [NeedsAuth], controllers: [ProfileCtl] }) + class ProfileModule {} + const teacup = createApp({ - modules: [NeedsAuthModule], // a step with needs: ['auth'] + modules: [ProfileModule], // a step with needs: ['auth'], and a route needing that step experimental: true, + logger: collect().logger, mesh: { teapots: [{ url: 'ws://127.0.0.1:9/x', secret: 's' }], secret: 's', @@ -238,7 +261,8 @@ describe('mesh boot retry', () => { }); try { - await expect(teacup.ready()).rejects.toThrow(/missing dependency: auth[\s\S]*did not connect/i); + await expect(teacup.ready()).resolves.toBeUndefined(); + expect((await teacup.fetch(new Request('http://x/api/profile'))).status).toBe(503); } finally { await teacup.close(); } @@ -302,15 +326,113 @@ describe('mesh boot retry', () => { }); try { - await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow( - /needs 'auth' but nothing \(local or connected mesh\) provides it[\s\S]*did not connect/i, - ); + expect((await teacup.fetch(new Request('http://x/api/local/who'))).status).toBe(503); expect(lines.filter((l) => l.includes('of boot budget left'))).toEqual([]); } finally { await teacup.close(); } }, 15_000); + it('a degraded token serves again once its teapot connects late (#96)', async () => { + const port = await freePort(); + const { logger } = collect(); + const events: string[] = []; + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + logger, + mesh: { + teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'good' }], + timeoutMs: 500, + bootTimeoutMs: 0, + reconnect: { initialDelayMs: 20, maxDelayMs: 60 }, + }, + }); + teacup.bus.on('mesh:degraded', (e) => events.push(`degraded ${e.name}`)); + teacup.bus.on('mesh:restored', (e) => events.push(`restored ${e.name}`)); + + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } }); + let server: Awaited> | undefined; + + try { + expect((await teacup.fetch(new Request('http://x/api/local/who'))).status).toBe(503); + server = await teapot.listen(port); + await new Promise((r) => setTimeout(r, 400)); + + const res = await teacup.fetch(new Request('http://x/api/local/who')); + expect(res.status).toBe(200); + expect(((await res.json()) as { auth: unknown }).auth).toEqual({ ok: true }); + expect(events).toEqual(['degraded auth', 'restored auth']); + } finally { + await teacup.close(); + await teapot.close(); + server?.close(); + } + }, 15_000); + + it('says once, as an error, when every late teapot connected and none exports a degraded token', async () => { + const port = await freePort(); + const { lines, logger } = collect(); + @Route('/typo') + class TypoCtl { + @Get('/') + who(@needs('auht') auth: any) { + return { auth }; + } + } + @Module({ mountpoint: '/api', controllers: [TypoCtl] }) + class TypoModule {} + + const teacup = createApp({ + modules: [TypoModule], + experimental: true, + logger, + mesh: { + teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'good' }], + timeoutMs: 500, + bootTimeoutMs: 0, + reconnect: { initialDelayMs: 20, maxDelayMs: 60 }, + }, + }); + + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } }); + let server: Awaited> | undefined; + + try { + await teacup.ready(); + server = await teapot.listen(port); + await new Promise((r) => setTimeout(r, 400)); + + expect((await teacup.fetch(new Request('http://x/api/typo'))).status).toBe(503); + expect(lines.filter((l) => l.includes("none exports 'auht'"))).toHaveLength(1); + } finally { + await teacup.close(); + await teapot.close(); + server?.close(); + } + }, 15_000); + + it('sends no retry-after for a degraded token when nothing will ever retry (reconnect: false)', async () => { + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + logger: collect().logger, + mesh: { + teapots: [{ url: 'ws://127.0.0.1:1/__mesh__/control', secret: 'good' }], + bootTimeoutMs: 0, + reconnect: false, + }, + }); + + try { + const res = await teacup.fetch(new Request('http://x/api/local/who')); + expect(res.status).toBe(503); + expect(res.headers.get('retry-after')).toBeNull(); + } finally { + await teacup.close(); + } + }, 15_000); + it('connects absent teapots in parallel, so three of them cost one boot budget (#95)', async () => { // Sequential connects spent bootTimeoutMs per absent teapot: 3 × 600ms here, ~1.8s. const teacup = createApp({