refactor(mesh)!: a manifest carries step names, not scoped tokens
Every exported token is request-scope now, so the lifetime field had one value and told a reader nothing. No protocol bump: mesh is alpha, both peers ship from this repo, and the number should mean incompatibility between deployed versions. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
13 files changed
+104
-108
No files matched your search
+7
-3
@@ -33,7 +33,7 @@ import { buildOpenApi, type OpenApiInfo } from '../openapi';
|
||||
import { connectLink, isPermanentRefusal, type Link } from '../mesh/link';
|
||||
import { Rooms } from '../rooms';
|
||||
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
|
||||
import { buildRemote } from '../mesh/teacup';
|
||||
import { buildRemote, type RemoteScopeNode } from '../mesh/teacup';
|
||||
import { buildManifest, createMeshControl, MESH_CONTROL_PATH } from '../mesh/teapot';
|
||||
import type { MeshControl } from '../http';
|
||||
import type { RequestEnvelope, RouteEntry } from '../mesh/protocol';
|
||||
@@ -850,7 +850,11 @@ async function spliceRemoteScopes(
|
||||
}),
|
||||
);
|
||||
meshLinks.push(link);
|
||||
const { providers, steps, routes } = buildRemote(link);
|
||||
// `buildRemote` no longer returns `providers` — every exported token is a step now (Task 1
|
||||
// refuses a provider export at boot). Kept as an empty array, not deleted, so the loop below
|
||||
// still typechecks; Task 3 removes the loop itself along with the rest of provider-splicing.
|
||||
const providers: RemoteScopeNode[] = [];
|
||||
const { steps, routes } = buildRemote(link);
|
||||
const origin = `mesh:${teapot.url}`;
|
||||
|
||||
for (const provider of providers) {
|
||||
@@ -1094,7 +1098,7 @@ function buildMeshControl(
|
||||
if (!mesh?.secret || !hasExports) return undefined;
|
||||
const { container, orderedProviders, orderedSteps } = deps;
|
||||
const { bus, providedSeed, planSteps, onError, logger } = deps.deps;
|
||||
const manifest = buildManifest({ providers: exportedProviders, steps: exportedSteps, routes: exportedRoutes });
|
||||
const manifest = buildManifest({ steps: exportedSteps, routes: exportedRoutes });
|
||||
|
||||
const resolveScope = async (name: string, env: RequestEnvelope): Promise<unknown> => {
|
||||
// context is intentionally `any`: providers and steps merge arbitrary keys into it
|
||||
|
||||
+8
-8
@@ -218,7 +218,7 @@ function settleManifest(frame: Extract<Frame, { type: 'manifest' }>, hs: Handsha
|
||||
// `mesh:connect` is emitted by the caller, not here: a reconnect whose manifest no longer backs
|
||||
// the graph is refused after this point, and announcing a connection we are about to hang up on
|
||||
// would tell an operator the opposite of what happened.
|
||||
hs.resolve({ socket: hs.socket, manifest: { scopes: frame.scopes, routes: frame.routes }, heartbeat });
|
||||
hs.resolve({ socket: hs.socket, manifest: { steps: frame.steps, routes: frame.routes }, heartbeat });
|
||||
}
|
||||
|
||||
/** Consume the session's inbound frames until it closes, settling the handshake then each RPC. */
|
||||
@@ -323,9 +323,9 @@ function openSession(args: SessionArgs): Promise<Session> {
|
||||
});
|
||||
}
|
||||
|
||||
/** A scope token and its lifetime, flattened to the string the refusal check compares. */
|
||||
function scopeKeys(manifest: Manifest): Set<string> {
|
||||
return new Set(manifest.scopes.map((scope) => `${scope.scope}:${scope.token}`));
|
||||
/** A manifest's step tokens, flattened to the set the refusal check compares. */
|
||||
function stepKeys(manifest: Manifest): Set<string> {
|
||||
return new Set(manifest.steps);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -345,12 +345,12 @@ function routeKeys(manifest: Manifest): Set<string> {
|
||||
* missing and are ignored: the graph is fixed at boot and nothing new is spliced into it.
|
||||
*/
|
||||
export function missingFromManifest(booted: Manifest, returned: Manifest): string[] {
|
||||
const scopes = scopeKeys(returned);
|
||||
const steps = stepKeys(returned);
|
||||
const routes = routeKeys(returned);
|
||||
const missing: string[] = [];
|
||||
|
||||
for (const scope of booted.scopes) {
|
||||
if (!scopes.has(`${scope.scope}:${scope.token}`)) missing.push(`${scope.scope}-scope '${scope.token}'`);
|
||||
for (const step of booted.steps) {
|
||||
if (!steps.has(step)) missing.push(`step '${step}'`);
|
||||
}
|
||||
|
||||
for (const route of booted.routes) {
|
||||
@@ -407,7 +407,7 @@ export function connectLink(args: {
|
||||
const link: Link = {
|
||||
// replaced with the real manifest before this object escapes; a reconnect never changes it,
|
||||
// because the graph is fixed at boot and only the *boot* manifest describes what it holds.
|
||||
manifest: { scopes: [], routes: [] },
|
||||
manifest: { steps: [], routes: [] },
|
||||
rpc: (kind, name, ctx) => sendRpc(state.socket, pending, String(counter++), kind, name, ctx, timeoutMs),
|
||||
close: () => {
|
||||
// Terminal, by contract. `closeLinks` runs on shutdown, and a link that reconnected after
|
||||
|
||||
+11
-9
@@ -43,19 +43,21 @@ export interface RequestEnvelope {
|
||||
correlation?: { requestId?: string; traceId?: string };
|
||||
}
|
||||
|
||||
/** Manifest entry for an exported scope token and its lifetime. */
|
||||
export interface ScopeEntry {
|
||||
token: string;
|
||||
scope: 'app' | 'request';
|
||||
}
|
||||
/** Manifest entry for an exported route. */
|
||||
export interface RouteEntry {
|
||||
method: string;
|
||||
pattern: string;
|
||||
}
|
||||
/** A mesh server's advertised scopes and routes. */
|
||||
|
||||
/**
|
||||
* A mesh server's advertised steps and routes.
|
||||
*
|
||||
* Steps only: a provider's value is the object it builds, which cannot cross a JSON wire, so
|
||||
* exporting one is refused at boot (`collectProviders`). Every entry here is request-scope and
|
||||
* lazy — the token exists in the teacup's graph, and running it is an RPC.
|
||||
*/
|
||||
export interface Manifest {
|
||||
scopes: ScopeEntry[];
|
||||
steps: string[];
|
||||
routes: RouteEntry[];
|
||||
}
|
||||
|
||||
@@ -68,7 +70,7 @@ export interface Manifest {
|
||||
*/
|
||||
export type Frame =
|
||||
| { type: 'hello'; v: number; secret: string }
|
||||
| { type: 'manifest'; v: number; scopes: ScopeEntry[]; routes: RouteEntry[] }
|
||||
| { type: 'manifest'; v: number; steps: string[]; routes: RouteEntry[] }
|
||||
| { type: 'rpc-req'; id: string; kind: 'scope' | 'route'; name: string; ctx: RequestEnvelope }
|
||||
| { type: 'rpc-res'; id: string; ok: true; result: unknown }
|
||||
| { type: 'rpc-res'; id: string; ok: false; error: { message: string; status?: number } }
|
||||
@@ -94,7 +96,7 @@ const SHAPE: Record<Frame['type'], ShapeCheck> = {
|
||||
},
|
||||
manifest: (frame, bad) => {
|
||||
if (!isNumber(frame.v)) bad('missing protocol version');
|
||||
if (!Array.isArray(frame.scopes) || !Array.isArray(frame.routes)) bad('scopes and routes must be arrays');
|
||||
if (!Array.isArray(frame.steps) || !Array.isArray(frame.routes)) bad('steps and routes must be arrays');
|
||||
},
|
||||
'rpc-req': (frame, bad) => {
|
||||
if (!isString(frame.id)) bad('id must be a string');
|
||||
|
||||
+8
-17
@@ -37,27 +37,18 @@ export function envelopeFrom(ctx: any): RequestEnvelope {
|
||||
};
|
||||
}
|
||||
|
||||
/** Turn a link's manifest into local proxy nodes: app-scope providers, request-scope steps, and routes. */
|
||||
export function buildRemote(link: Link): {
|
||||
providers: RemoteScopeNode[];
|
||||
steps: RemoteScopeNode[];
|
||||
routes: RemoteRoute[];
|
||||
} {
|
||||
const providers: RemoteScopeNode[] = [];
|
||||
const steps: RemoteScopeNode[] = [];
|
||||
|
||||
for (const scope of link.manifest.scopes) {
|
||||
const node: RemoteScopeNode = {
|
||||
name: scope.token,
|
||||
run: async (ctx: any) => ({ [scope.token]: await link.rpc('scope', scope.token, envelopeFrom(ctx)) }),
|
||||
};
|
||||
(scope.scope === 'app' ? providers : steps).push(node);
|
||||
}
|
||||
/** Turn a link's manifest into local proxy nodes: lazy request-scope steps, and routes. */
|
||||
export function buildRemote(link: Link): { steps: RemoteScopeNode[]; routes: RemoteRoute[] } {
|
||||
const steps: RemoteScopeNode[] = link.manifest.steps.map((token) => ({
|
||||
name: token,
|
||||
run: async (ctx: any) => ({ [token]: await link.rpc('scope', token, envelopeFrom(ctx)) }),
|
||||
}));
|
||||
|
||||
const routes: RemoteRoute[] = link.manifest.routes.map((route) => ({
|
||||
method: route.method,
|
||||
pattern: route.pattern,
|
||||
handler: async (req: RequestEnvelope) => (await link.rpc('route', route.pattern, req)) as ResponseShape,
|
||||
}));
|
||||
return { providers, steps, routes };
|
||||
|
||||
return { steps, routes };
|
||||
}
|
||||
+5
-15
@@ -42,19 +42,9 @@ const HANDSHAKE_TIMEOUT_MS = 10_000;
|
||||
*/
|
||||
const MAX_FRAME_CHARS = 4_000_000;
|
||||
|
||||
/** Assemble a {@link Manifest} from exported provider/step tokens and buffered routes. */
|
||||
export function buildManifest(args: {
|
||||
providers: string[]; // exported provider tokens (app-scope)
|
||||
steps: string[]; // exported step tokens (request-scope)
|
||||
routes: RouteEntry[]; // exported buffered routes
|
||||
}): Manifest {
|
||||
return {
|
||||
scopes: [
|
||||
...args.providers.map((token) => ({ token, scope: 'app' as const })),
|
||||
...args.steps.map((token) => ({ token, scope: 'request' as const })),
|
||||
],
|
||||
routes: args.routes,
|
||||
};
|
||||
/** Assemble a {@link Manifest} from exported step tokens and buffered routes. */
|
||||
export function buildManifest(args: { steps: string[]; routes: RouteEntry[] }): Manifest {
|
||||
return { steps: [...args.steps], routes: args.routes };
|
||||
}
|
||||
|
||||
function safeEqual(left: string, right: string): boolean {
|
||||
@@ -115,7 +105,7 @@ function handleHandshake(socket: WsSocket, frame: Frame, deps: MeshControlDeps):
|
||||
encode({
|
||||
type: 'manifest',
|
||||
v: MESH_PROTOCOL_VERSION,
|
||||
scopes: deps.manifest.scopes,
|
||||
steps: deps.manifest.steps,
|
||||
routes: deps.manifest.routes,
|
||||
}),
|
||||
);
|
||||
@@ -244,7 +234,7 @@ export function createMeshControl(deps: MeshControlDeps): {
|
||||
path: string;
|
||||
handle: (socket: WsSocket) => Promise<void>;
|
||||
} {
|
||||
const exportedScopes = new Set(deps.manifest.scopes.map((scope) => scope.token));
|
||||
const exportedScopes = new Set(deps.manifest.steps);
|
||||
const exportedRoutes = new Set(deps.manifest.routes.map((route) => `${route.method} ${route.pattern}`));
|
||||
|
||||
return {
|
||||
|
||||
@@ -103,7 +103,7 @@ describe('mesh rpc errors', () => {
|
||||
const frame = decode(data.toString());
|
||||
if (!authed && frame.type === 'hello') {
|
||||
authed = true;
|
||||
ws.send(encode({ type: 'manifest', v: V, scopes: [{ token: 'billing', scope: 'request' }], routes: [] }));
|
||||
ws.send(encode({ type: 'manifest', v: V, steps: ['billing'], routes: [] }));
|
||||
return;
|
||||
}
|
||||
if (frame.type === 'rpc-req') {
|
||||
@@ -130,7 +130,7 @@ describe('teapot hardening', () => {
|
||||
const control = () =>
|
||||
createMeshControl({
|
||||
secret: 'good',
|
||||
manifest: { scopes: [{ token: 'auth', scope: 'request' }], routes: [] },
|
||||
manifest: { steps: ['auth'], routes: [] },
|
||||
resolveScope: async () => 'value',
|
||||
resolveRoute: async () => ({ status: 200, headers: {}, body: '' }),
|
||||
});
|
||||
|
||||
@@ -276,7 +276,7 @@ describe('mesh control over app.upgrade (no listen)', () => {
|
||||
expect(peer.sent[0]).toMatchObject({
|
||||
type: 'manifest',
|
||||
v: MESH_PROTOCOL_VERSION,
|
||||
scopes: expect.arrayContaining([{ token: 'config', scope: 'request' }]),
|
||||
steps: expect.arrayContaining(['config']),
|
||||
});
|
||||
await teapot.close();
|
||||
});
|
||||
|
||||
@@ -21,7 +21,7 @@ function startTeapot(opts: { answerPings: boolean }) {
|
||||
seen.push(frame.type);
|
||||
|
||||
if (frame.type === 'hello') {
|
||||
ws.send(encode({ type: 'manifest', v: V, scopes: [{ token: 'auth', scope: 'request' }], routes: [] }));
|
||||
ws.send(encode({ type: 'manifest', v: V, steps: ['auth'], routes: [] }));
|
||||
}
|
||||
if (frame.type === 'ping' && opts.answerPings) ws.send(encode({ type: 'pong' }));
|
||||
if (frame.type === 'rpc-req') ws.send(encode({ type: 'rpc-res', id: frame.id, ok: true, result: { got: 1 } }));
|
||||
|
||||
@@ -16,7 +16,7 @@ function startTeapot(secret = 'good') {
|
||||
ws.on('message', (d) => {
|
||||
const f = decode(d.toString());
|
||||
if (!authed) {
|
||||
if (f.type === 'hello' && f.secret === secret) { authed = true; ws.send(encode({ type: 'manifest', v: V, scopes: [{ token: 'auth', scope: 'request' }], routes: [] })); }
|
||||
if (f.type === 'hello' && f.secret === secret) { authed = true; ws.send(encode({ type: 'manifest', v: V, steps: ['auth'], routes: [] })); }
|
||||
else ws.close(1008);
|
||||
return;
|
||||
}
|
||||
@@ -36,7 +36,7 @@ function startSilentTeapot(secret = 'good') {
|
||||
wss.on('connection', (ws) => {
|
||||
ws.on('message', (d) => {
|
||||
const f = decode(d.toString());
|
||||
if (f.type === 'hello' && f.secret === secret) ws.send(encode({ type: 'manifest', v: V, scopes: [], routes: [] }));
|
||||
if (f.type === 'hello' && f.secret === secret) ws.send(encode({ type: 'manifest', v: V, steps: [], routes: [] }));
|
||||
// ignore rpc-req entirely
|
||||
});
|
||||
});
|
||||
@@ -48,7 +48,7 @@ function startSilentTeapot(secret = 'good') {
|
||||
function startSkewedTeapot() {
|
||||
const wss = new WebSocketServer({ port: 0 });
|
||||
wss.on('connection', (ws) => {
|
||||
ws.on('message', () => ws.send(encode({ type: 'manifest', v: V + 1, scopes: [], routes: [] } as any)));
|
||||
ws.on('message', () => ws.send(encode({ type: 'manifest', v: V + 1, steps: [], routes: [] } as any)));
|
||||
});
|
||||
const port = (wss.address() as any).port;
|
||||
return { url: `ws://127.0.0.1:${port}/__mesh__/control`, close: () => wss.close() };
|
||||
@@ -68,7 +68,7 @@ describe('WebSocket client implementations', () => {
|
||||
const t = startTeapot();
|
||||
const link = await connectLink({ url: t.url, secret: 'good', Ctor });
|
||||
|
||||
expect(link.manifest.scopes).toEqual([{ token: 'auth', scope: 'request' }]);
|
||||
expect(link.manifest.steps).toEqual(['auth']);
|
||||
expect(await link.rpc('scope', 'auth', env)).toEqual({ got: 'auth' });
|
||||
link.close();
|
||||
t.close();
|
||||
@@ -86,7 +86,7 @@ describe('connectLink', () => {
|
||||
wss.on('connection', (ws) =>
|
||||
ws.on('message', (d) => {
|
||||
seen.push(decode(d.toString()));
|
||||
ws.send(encode({ type: 'manifest', v: V, scopes: [], routes: [] }));
|
||||
ws.send(encode({ type: 'manifest', v: V, steps: [], routes: [] }));
|
||||
}),
|
||||
);
|
||||
const url = `ws://127.0.0.1:${(wss.address() as any).port}/__mesh__/control`;
|
||||
@@ -105,7 +105,7 @@ describe('connectLink', () => {
|
||||
it('handshakes and exposes the manifest', async () => {
|
||||
const t = startTeapot();
|
||||
const link = await connectLink({ url: t.url, secret: 'good' });
|
||||
expect(link.manifest.scopes).toEqual([{ token: 'auth', scope: 'request' }]);
|
||||
expect(link.manifest.steps).toEqual(['auth']);
|
||||
link.close(); t.close();
|
||||
});
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ describe('protocol codec', () => {
|
||||
{
|
||||
type: 'manifest',
|
||||
v: V,
|
||||
scopes: [{ token: 'auth', scope: 'request' }],
|
||||
steps: ['auth'],
|
||||
routes: [{ method: 'GET', pattern: '/u/:id' }],
|
||||
},
|
||||
{ type: 'rpc-req', id: '1', kind: 'scope', name: 'auth', ctx: env },
|
||||
@@ -21,6 +21,17 @@ describe('protocol codec', () => {
|
||||
for (const f of frames) expect(decode(encode(f))).toEqual(f);
|
||||
});
|
||||
|
||||
it('encodes a manifest of step names', () => {
|
||||
const frame = decode(encode({ type: 'manifest', v: V, steps: ['auth'], routes: [] }));
|
||||
expect(frame).toEqual({ type: 'manifest', v: V, steps: ['auth'], routes: [] });
|
||||
});
|
||||
|
||||
it('rejects a manifest whose steps are not an array', () => {
|
||||
expect(() => decode(JSON.stringify({ type: 'manifest', v: V, steps: 'auth', routes: [] }))).toThrow(
|
||||
/steps and routes must be arrays/,
|
||||
);
|
||||
});
|
||||
|
||||
it('throws on malformed json', () => {
|
||||
expect(() => decode('{not json')).toThrow();
|
||||
});
|
||||
@@ -46,7 +57,7 @@ describe('protocol codec', () => {
|
||||
describe('protocol versioning', () => {
|
||||
it('carries the protocol version on the handshake frames', () => {
|
||||
const hello = decode(encode({ type: 'hello', v: V, secret: 's' }));
|
||||
const manifest = decode(encode({ type: 'manifest', v: V, scopes: [], routes: [] }));
|
||||
const manifest = decode(encode({ type: 'manifest', v: V, steps: [], routes: [] }));
|
||||
|
||||
expect(hello).toMatchObject({ v: V });
|
||||
expect(manifest).toMatchObject({ v: V });
|
||||
@@ -54,7 +65,7 @@ describe('protocol versioning', () => {
|
||||
|
||||
it('rejects a handshake frame with no version — an unversioned peer is not decodable', () => {
|
||||
expect(() => decode(JSON.stringify({ type: 'hello', secret: 's' }))).toThrow(/malformed hello/i);
|
||||
expect(() => decode(JSON.stringify({ type: 'manifest', scopes: [], routes: [] }))).toThrow(/malformed manifest/i);
|
||||
expect(() => decode(JSON.stringify({ type: 'manifest', steps: [], routes: [] }))).toThrow(/malformed manifest/i);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -64,7 +75,7 @@ describe('protocol field validation', () => {
|
||||
it.each([
|
||||
['hello without secret', { type: 'hello', v: V }],
|
||||
['hello with non-string secret', { type: 'hello', v: V, secret: 42 }],
|
||||
['manifest with non-array scopes', { type: 'manifest', v: V, scopes: 'nope', routes: [] }],
|
||||
['manifest with non-array steps', { type: 'manifest', v: V, steps: 'nope', routes: [] }],
|
||||
['rpc-req without id', { type: 'rpc-req', kind: 'scope', name: 'auth', ctx: env }],
|
||||
['rpc-req without ctx', { type: 'rpc-req', id: '1', kind: 'scope', name: 'auth' }],
|
||||
['rpc-req with unknown kind', { type: 'rpc-req', id: '1', kind: 'bogus', name: 'auth', ctx: env }],
|
||||
|
||||
+18
-27
@@ -20,7 +20,7 @@ function teapotOn(port: number, manifest: Manifest, answer: unknown = { ok: true
|
||||
if (!authed) {
|
||||
if (frame.type === 'hello' && frame.secret === 'good') {
|
||||
authed = true;
|
||||
ws.send(encode({ type: 'manifest', v: V, scopes: manifest.scopes, routes: manifest.routes }));
|
||||
ws.send(encode({ type: 'manifest', v: V, steps: manifest.steps, routes: manifest.routes }));
|
||||
} else ws.close(1008);
|
||||
return;
|
||||
}
|
||||
@@ -54,13 +54,13 @@ async function freePort(): Promise<number> {
|
||||
|
||||
const settle = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
const url = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`;
|
||||
const SCOPES: Manifest = { scopes: [{ token: 'auth', scope: 'app' }], routes: [] };
|
||||
const STEPS: Manifest = { steps: ['auth'], routes: [] };
|
||||
const fast = { initialDelayMs: 20, maxDelayMs: 60 };
|
||||
|
||||
describe('mesh reconnection', () => {
|
||||
it('reconnects to the same teapot and serves again', async () => {
|
||||
const port = await freePort();
|
||||
let teapot = await teapotOn(port, SCOPES);
|
||||
let teapot = await teapotOn(port, STEPS);
|
||||
const link = await connectLink({ url: url(port), secret: 'good', reconnect: fast, heartbeatMs: 50 });
|
||||
|
||||
expect(await link.rpc('scope', 'auth', env)).toEqual({ ok: true });
|
||||
@@ -70,7 +70,7 @@ describe('mesh reconnection', () => {
|
||||
// the window where the link is down answers immediately rather than after timeoutMs
|
||||
await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 });
|
||||
|
||||
teapot = await teapotOn(port, SCOPES, { ok: 'again' });
|
||||
teapot = await teapotOn(port, STEPS, { ok: 'again' });
|
||||
await settle(300);
|
||||
|
||||
expect(await link.rpc('scope', 'auth', env)).toEqual({ ok: 'again' });
|
||||
@@ -80,7 +80,7 @@ describe('mesh reconnection', () => {
|
||||
|
||||
it('refuses a returning teapot whose manifest lost a token the graph needs', async () => {
|
||||
const port = await freePort();
|
||||
let teapot = await teapotOn(port, SCOPES);
|
||||
let teapot = await teapotOn(port, STEPS);
|
||||
const warnings: string[] = [];
|
||||
const logger = { debug() {}, info() {}, warn: (m: string) => warnings.push(m), error() {} };
|
||||
const link = await connectLink({ url: url(port), secret: 'good', reconnect: fast, heartbeatMs: 50, logger });
|
||||
@@ -89,11 +89,11 @@ describe('mesh reconnection', () => {
|
||||
await settle(50);
|
||||
|
||||
// comes back exporting nothing — the graph was validated against 'auth' at boot
|
||||
teapot = await teapotOn(port, { scopes: [], routes: [] });
|
||||
teapot = await teapotOn(port, { steps: [], routes: [] });
|
||||
await settle(300);
|
||||
|
||||
await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 });
|
||||
expect(warnings.some((w) => w.includes("app-scope 'auth'") && w.includes('refusing to reconnect'))).toBe(true);
|
||||
expect(warnings.some((w) => w.includes("step 'auth'") && w.includes('refusing to reconnect'))).toBe(true);
|
||||
// logged once per distinct manifest, not once per attempt
|
||||
expect(warnings.filter((w) => w.includes('refusing to reconnect')).length).toBe(1);
|
||||
|
||||
@@ -103,7 +103,7 @@ describe('mesh reconnection', () => {
|
||||
|
||||
it('stops reconnecting once the application closes the link', async () => {
|
||||
const port = await freePort();
|
||||
const teapot = await teapotOn(port, SCOPES);
|
||||
const teapot = await teapotOn(port, STEPS);
|
||||
const link = await connectLink({ url: url(port), secret: 'good', reconnect: fast, heartbeatMs: 50 });
|
||||
|
||||
await teapot.close();
|
||||
@@ -111,7 +111,7 @@ describe('mesh reconnection', () => {
|
||||
|
||||
// if close() were not terminal, the link would reconnect to the teapot that comes back here —
|
||||
// which is what would leave app.close() with a process that cannot exit
|
||||
const revived = await teapotOn(port, SCOPES, { ok: 'revived' });
|
||||
const revived = await teapotOn(port, STEPS, { ok: 'revived' });
|
||||
await settle(300);
|
||||
|
||||
await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 });
|
||||
@@ -120,11 +120,11 @@ describe('mesh reconnection', () => {
|
||||
|
||||
it('reconnect: false keeps the old fail-once behaviour', async () => {
|
||||
const port = await freePort();
|
||||
let teapot = await teapotOn(port, SCOPES);
|
||||
let teapot = await teapotOn(port, STEPS);
|
||||
const link = await connectLink({ url: url(port), secret: 'good', reconnect: false, heartbeatMs: 50 });
|
||||
|
||||
await teapot.close();
|
||||
teapot = await teapotOn(port, SCOPES);
|
||||
teapot = await teapotOn(port, STEPS);
|
||||
await settle(300);
|
||||
|
||||
await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 });
|
||||
@@ -135,10 +135,7 @@ describe('mesh reconnection', () => {
|
||||
|
||||
describe('missingFromManifest', () => {
|
||||
const booted: Manifest = {
|
||||
scopes: [
|
||||
{ token: 'auth', scope: 'request' },
|
||||
{ token: 'config', scope: 'app' },
|
||||
],
|
||||
steps: ['auth', 'config'],
|
||||
routes: [{ method: 'GET', pattern: '/svc/:id' }],
|
||||
};
|
||||
|
||||
@@ -148,30 +145,24 @@ describe('missingFromManifest', () => {
|
||||
|
||||
it('accepts extra exports — the graph is fixed at boot and nothing new is spliced', () => {
|
||||
const wider: Manifest = {
|
||||
scopes: [...booted.scopes, { token: 'billing', scope: 'app' }],
|
||||
steps: [...booted.steps, 'billing'],
|
||||
routes: [...booted.routes, { method: 'POST', pattern: '/svc/new' }],
|
||||
};
|
||||
expect(missingFromManifest(booted, wider)).toEqual([]);
|
||||
});
|
||||
|
||||
it('accepts a route parameter that was only renamed', () => {
|
||||
const renamed: Manifest = { scopes: booted.scopes, routes: [{ method: 'GET', pattern: '/svc/:name' }] };
|
||||
const renamed: Manifest = { steps: booted.steps, routes: [{ method: 'GET', pattern: '/svc/:name' }] };
|
||||
expect(missingFromManifest(booted, renamed)).toEqual([]);
|
||||
});
|
||||
|
||||
it('reports a token whose lifetime changed, since the graph resolved it under the old one', () => {
|
||||
const flipped: Manifest = {
|
||||
scopes: [
|
||||
{ token: 'auth', scope: 'app' },
|
||||
{ token: 'config', scope: 'app' },
|
||||
],
|
||||
routes: booted.routes,
|
||||
};
|
||||
expect(missingFromManifest(booted, flipped)).toEqual(["request-scope 'auth'"]);
|
||||
it('reports a step token that vanished, since the graph resolved it under the old manifest', () => {
|
||||
const shrunk: Manifest = { steps: ['config'], routes: booted.routes };
|
||||
expect(missingFromManifest(booted, shrunk)).toEqual(["step 'auth'"]);
|
||||
});
|
||||
|
||||
it('reports a missing route by method and pattern', () => {
|
||||
const routeless: Manifest = { scopes: booted.scopes, routes: [] };
|
||||
const routeless: Manifest = { steps: booted.steps, routes: [] };
|
||||
expect(missingFromManifest(booted, routeless)).toEqual(["route 'GET /svc/:id'"]);
|
||||
});
|
||||
});
|
||||
@@ -3,20 +3,28 @@ import { buildRemote, envelopeFrom } from '../../src/mesh/teacup';
|
||||
import type { Link } from '../../src/mesh/link';
|
||||
|
||||
const fakeLink = (calls: any[]): Link => ({
|
||||
manifest: { scopes: [{ token: 'config', scope: 'app' }, { token: 'auth', scope: 'request' }], routes: [{ method: 'GET', pattern: '/u/:id' }] },
|
||||
manifest: { steps: ['config', 'auth'], routes: [{ method: 'GET', pattern: '/u/:id' }] },
|
||||
rpc: async (kind, name, ctx) => { calls.push({ kind, name, ctx }); return name === 'config' ? { url: 'db://x' } : { id: 'u1' }; },
|
||||
close() {},
|
||||
});
|
||||
|
||||
describe('teacup buildRemote', () => {
|
||||
it('makes a provider node (app) and a step node (request) with RPC runners returning merge objects', async () => {
|
||||
it('turns every manifest step into a lazy remote node', async () => {
|
||||
const link = { manifest: { steps: ['auth'], routes: [] }, rpc: async () => ({ ok: true }) } as any;
|
||||
const { steps, routes } = buildRemote(link);
|
||||
|
||||
expect(routes).toEqual([]);
|
||||
expect(steps.map((s: any) => s.name)).toEqual(['auth']);
|
||||
expect(await steps[0].run({})).toEqual({ auth: { ok: true } });
|
||||
});
|
||||
|
||||
it('makes a step node per manifest token, with RPC runners returning merge objects', async () => {
|
||||
const calls: any[] = [];
|
||||
const { providers, steps } = buildRemote(fakeLink(calls));
|
||||
expect(providers.map((p) => p.name)).toEqual(['config']);
|
||||
expect(steps.map((s) => s.name)).toEqual(['auth']);
|
||||
expect(await providers[0].run({})).toEqual({ config: { url: 'db://x' } });
|
||||
const { steps } = buildRemote(fakeLink(calls));
|
||||
expect(steps.map((s) => s.name)).toEqual(['config', 'auth']);
|
||||
expect(await steps[0].run({})).toEqual({ config: { url: 'db://x' } });
|
||||
const ctx = { req: {}, params: { id: '9' }, query: {}, body: undefined, headers: { x: '1' } };
|
||||
expect(await steps[0].run(ctx)).toEqual({ auth: { id: 'u1' } });
|
||||
expect(await steps[1].run(ctx)).toEqual({ auth: { id: 'u1' } });
|
||||
expect(calls.find((c) => c.name === 'auth').ctx).toMatchObject({ params: { id: '9' }, headers: { x: '1' } });
|
||||
});
|
||||
|
||||
|
||||
@@ -43,18 +43,17 @@ const fakeSocket = () => {
|
||||
};
|
||||
|
||||
describe('buildManifest', () => {
|
||||
it('maps providers to app scope and steps to request scope', () => {
|
||||
const m = buildManifest({ providers: ['config'], steps: ['auth'], routes: [{ method: 'GET', pattern: '/u/:id' }] });
|
||||
expect(m.scopes).toContainEqual({ token: 'config', scope: 'app' });
|
||||
expect(m.scopes).toContainEqual({ token: 'auth', scope: 'request' });
|
||||
expect(m.routes).toEqual([{ method: 'GET', pattern: '/u/:id' }]);
|
||||
it('builds a manifest from step tokens and routes', () => {
|
||||
expect(buildManifest({ steps: ['auth'], routes: [{ method: 'GET', pattern: '/u/:id' }] })).toEqual({
|
||||
steps: ['auth'],
|
||||
routes: [{ method: 'GET', pattern: '/u/:id' }],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('createMeshControl', () => {
|
||||
const manifest = buildManifest({
|
||||
providers: ['config'],
|
||||
steps: ['auth'],
|
||||
steps: ['config', 'auth'],
|
||||
routes: [{ method: 'GET', pattern: '/u/:id' }],
|
||||
});
|
||||
const make = (over: Partial<Parameters<typeof createMeshControl>[0]> = {}) =>
|
||||
@@ -82,7 +81,7 @@ describe('createMeshControl', () => {
|
||||
const t = fakeSocket();
|
||||
make().handle(t.socket);
|
||||
await t.deliver({ type: 'hello', v: V, secret: 'good' });
|
||||
expect(t.sent[0]).toMatchObject({ type: 'manifest', v: V, scopes: manifest.scopes });
|
||||
expect(t.sent[0]).toMatchObject({ type: 'manifest', v: V, steps: manifest.steps });
|
||||
});
|
||||
|
||||
it('rejects a version-skewed peer before checking its secret, naming both versions', async () => {
|
||||
|
||||
Reference in new issue
Block a user