Merge feature/mesh-skeleton: spec #3 green-tea mesh (walking skeleton)
Distributed DI over a WS control channel: a teacup invokes a remote scope/step or proxies a route on a teapot, via one id-correlated RPC. Remote tokens become synthetic graph nodes with RPC runners; opt-in export gated by a shared secret. No discovery/LB/failover yet. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
17 files changed
+770
-47
No files matched your search
+53
-1
@@ -1,4 +1,4 @@
|
||||
import { createApp, Provider, Step, Route, Get, Module, Transformer, JsonTransformer, Unauthorized, Plugin, needs, param, Sse, Ws, inbound, channel } from '../src/index';
|
||||
import { createApp, Provider, Step, Route, Get, Module, Transformer, JsonTransformer, Unauthorized, Plugin, needs, param, Sse, Ws, inbound, channel, MESH_CONTROL_PATH } from '../src/index';
|
||||
|
||||
interface User { id: string; name: string }
|
||||
|
||||
@@ -70,3 +70,55 @@ if (require.main === module) {
|
||||
app.listen(3000).then(() => console.log('green-tea on http://localhost:3000'));
|
||||
streamApp.listen(3001).then(() => console.log('green-tea streams on http://localhost:3001'));
|
||||
}
|
||||
|
||||
// ── Mesh Demo (teapot / teacup) ───────────────────────────────────────────
|
||||
|
||||
@Provider({ provides: 'config', export: true })
|
||||
class ConfigProvider {
|
||||
provide() {
|
||||
return { config: { env: 'demo' } };
|
||||
}
|
||||
}
|
||||
|
||||
@Step({ provides: 'auth', needs: [], export: true })
|
||||
class AuthStep {
|
||||
run(ctx: { headers?: Record<string, string | string[] | undefined> }) {
|
||||
const tok = ctx.headers?.['x-token'];
|
||||
return { auth: Array.isArray(tok) ? tok[0] ?? 'anonymous' : tok ?? 'anonymous' };
|
||||
}
|
||||
}
|
||||
|
||||
@Route('/svc')
|
||||
class PingController {
|
||||
@Get('/ping', { export: true })
|
||||
ping(@needs('config') config: { env: string }, @needs('auth') auth: string) {
|
||||
return { pong: true, config, auth };
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/mesh', providers: [ConfigProvider], steps: [AuthStep], controllers: [PingController] })
|
||||
class TeapotModule {}
|
||||
|
||||
export const teapotApp = createApp({ modules: [TeapotModule], mesh: { secret: 'demo-secret' } });
|
||||
|
||||
@Route('/remote')
|
||||
class TeacupController {
|
||||
@Get('/status')
|
||||
status(@needs('config') config: { env: string }, @needs('auth') auth: string) {
|
||||
return { via: 'teacup', config, auth };
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/', controllers: [TeacupController] })
|
||||
class TeacupModule {}
|
||||
|
||||
if (require.main === module) {
|
||||
teapotApp.listen(3002).then(() => {
|
||||
console.log('teapot on http://localhost:3002');
|
||||
const teacupApp = createApp({
|
||||
modules: [TeacupModule],
|
||||
mesh: { teapots: [{ url: `ws://127.0.0.1:3002${MESH_CONTROL_PATH}`, secret: 'demo-secret' }] },
|
||||
});
|
||||
teacupApp.listen(3003).then(() => console.log('teacup on http://localhost:3003'));
|
||||
});
|
||||
}
|
||||
+123
-30
@@ -11,6 +11,11 @@ import {
|
||||
Ctor, HttpMethod, Transport, getModuleMeta, getProviderMeta, getStepMeta, getRoutes, getTransformer, joinPath,
|
||||
} from './metadata';
|
||||
import { getArgs, getHandlerNeeds, resolveArgs } from './params';
|
||||
import { connectLink, type Link } from './mesh/link';
|
||||
import { buildRemote } from './mesh/teacup';
|
||||
import { buildManifest, createMeshControl } from './mesh/teapot';
|
||||
import type { MeshControl } from './http';
|
||||
import type { RequestEnvelope, RouteEntry } from './mesh/protocol';
|
||||
|
||||
export interface InspectLine { name: string; kind: 'provider' | 'step' | 'handler'; origin: string }
|
||||
export interface App {
|
||||
@@ -32,7 +37,13 @@ interface RoutePlan {
|
||||
transformer: typeof JsonTransformer;
|
||||
}
|
||||
|
||||
export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[] }): App {
|
||||
export interface MeshConfig {
|
||||
secret?: string;
|
||||
teapots?: Array<{ url: string; secret: string }>;
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig }): App {
|
||||
const bus = new Bus();
|
||||
const container = new Container();
|
||||
const extraSteps: ScopeNode[] = [];
|
||||
@@ -48,6 +59,9 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[] }): App {
|
||||
};
|
||||
const providerMeta = new Map<string, { optional: boolean }>();
|
||||
const routePlans: RoutePlan[] = [];
|
||||
const exportedProviders: string[] = [];
|
||||
const exportedSteps: string[] = [];
|
||||
const exportedRoutes: RouteEntry[] = [];
|
||||
|
||||
for (const mod of opts.modules) {
|
||||
const m = getModuleMeta(mod);
|
||||
@@ -58,12 +72,14 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[] }): App {
|
||||
const meta = getProviderMeta(P)!;
|
||||
providerNodes.push({ name: meta.provides, needs: meta.needs, provides: [meta.provides], origin });
|
||||
providerMeta.set(meta.provides, { optional: meta.optional });
|
||||
if (meta.export) exportedProviders.push(meta.provides);
|
||||
const inst: any = new P();
|
||||
setRunner(meta.provides, (ctx) => inst.provide(ctx));
|
||||
}
|
||||
for (const S of m.steps ?? []) {
|
||||
const meta = getStepMeta(S)!;
|
||||
stepNodes.push({ name: meta.provides, needs: meta.needs, provides: [meta.provides], origin });
|
||||
if (meta.export) exportedSteps.push(meta.provides);
|
||||
const inst: any = new S();
|
||||
setRunner(meta.provides, (ctx) => inst.run(ctx));
|
||||
}
|
||||
@@ -71,8 +87,13 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[] }): App {
|
||||
for (const route of getRoutes(C)) {
|
||||
const inst: any = new C();
|
||||
const argSpecs = getArgs(C, route.handlerName);
|
||||
const pattern = joinPath(m.mountpoint, route.path);
|
||||
if (route.export) {
|
||||
if (route.transport !== 'buffer') throw new Error(`cannot export streaming route ${pattern}`);
|
||||
exportedRoutes.push({ method: route.method, pattern });
|
||||
}
|
||||
routePlans.push({
|
||||
pattern: joinPath(m.mountpoint, route.path),
|
||||
pattern,
|
||||
method: route.method,
|
||||
transport: route.transport,
|
||||
origin,
|
||||
@@ -97,26 +118,34 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[] }): App {
|
||||
|
||||
// For each route, resolve which providers/steps feed it via topo order.
|
||||
// MVP: every route depends on every declared step + provider in the app graph.
|
||||
const seedKeys = ['req', 'params'];
|
||||
const ordered = topoSort([...providerNodes, ...stepNodes], seedKeys);
|
||||
const orderedProviders = ordered.filter((n) => providerNodes.includes(n));
|
||||
const orderedSteps = ordered.filter((n) => stepNodes.includes(n));
|
||||
for (const plan of routePlans) { plan.providers = orderedProviders; plan.steps = orderedSteps; }
|
||||
// For mesh apps, finalize is DEFERRED to listen() so remote scopes can join the graph first.
|
||||
let orderedProviders: GraphNode[] = [];
|
||||
let orderedSteps: GraphNode[] = [];
|
||||
let booted = false;
|
||||
const finalizeGraph = (): void => {
|
||||
const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params']);
|
||||
orderedProviders = ordered.filter((n) => providerNodes.includes(n));
|
||||
orderedSteps = ordered.filter((n) => stepNodes.includes(n));
|
||||
for (const plan of routePlans) { plan.providers = orderedProviders; plan.steps = orderedSteps; }
|
||||
|
||||
const producedKeys = new Set<string>([
|
||||
...providerNodes.flatMap((n) => n.provides),
|
||||
...stepNodes.flatMap((n) => n.provides),
|
||||
]);
|
||||
const allowed = new Set<string>([...producedKeys, 'req', 'params', 'query', 'body', 'headers', 'inbound', 'abort']);
|
||||
for (const plan of routePlans) {
|
||||
for (const need of plan.needs) {
|
||||
if (!allowed.has(need)) {
|
||||
throw new Error(`handler '${plan.handlerName}' needs '${need}' but nothing provides it`);
|
||||
const producedKeys = new Set<string>([
|
||||
...providerNodes.flatMap((n) => n.provides),
|
||||
...stepNodes.flatMap((n) => n.provides),
|
||||
]);
|
||||
const allowed = new Set<string>([...producedKeys, 'req', 'params', 'query', 'body', 'headers', 'inbound', 'abort']);
|
||||
for (const plan of routePlans) {
|
||||
for (const need of plan.needs) {
|
||||
if (!allowed.has(need)) {
|
||||
throw new Error(`handler '${plan.handlerName}' needs '${need}' but nothing (local or mesh) provides it`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
booted = true;
|
||||
};
|
||||
if (!opts.mesh) finalizeGraph();
|
||||
|
||||
const inspect = (routePath: string): InspectLine[] => {
|
||||
if (!booted) throw new Error('inspect() unavailable before listen() for mesh apps');
|
||||
const plan = routePlans.find((p) => p.pattern === routePath);
|
||||
if (!plan) throw new Error(`no route: ${routePath}`);
|
||||
return [
|
||||
@@ -140,6 +169,39 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[] }): App {
|
||||
});
|
||||
|
||||
const listen = async (port: number): Promise<http.Server> => {
|
||||
// mesh teacup: connect remote teapots, splice their scopes/routes into the graph, then finalize
|
||||
const remoteRoutes: RouteDef[] = [];
|
||||
const meshLinks: Link[] = [];
|
||||
let meshControl: MeshControl | undefined;
|
||||
if (opts.mesh && !booted) {
|
||||
try {
|
||||
for (const t of opts.mesh.teapots ?? []) {
|
||||
const link = await connectLink({ url: t.url, secret: t.secret, timeoutMs: opts.mesh.timeoutMs, bus });
|
||||
meshLinks.push(link);
|
||||
const { providers, steps, routes } = buildRemote(link, t.url);
|
||||
for (const p of providers) {
|
||||
providerNodes.push({ name: p.name, needs: [], provides: [p.name], origin: `mesh:${t.url}` });
|
||||
providerMeta.set(p.name, { optional: false });
|
||||
setRunner(p.name, p.run);
|
||||
}
|
||||
for (const s of steps) {
|
||||
stepNodes.push({ name: s.name, needs: [], provides: [s.name], origin: `mesh:${t.url}` });
|
||||
setRunner(s.name, s.run);
|
||||
}
|
||||
for (const r of routes) {
|
||||
remoteRoutes.push({
|
||||
method: r.method, pattern: r.pattern, transport: 'buffer',
|
||||
handler: async (req) => r.handler(req as RequestEnvelope),
|
||||
});
|
||||
}
|
||||
}
|
||||
finalizeGraph();
|
||||
} catch (err) {
|
||||
for (const l of meshLinks) { try { l.close(); } catch { /* */ } }
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// run app-scoped providers in order (fail-fast for required)
|
||||
for (const node of orderedProviders) {
|
||||
bus.emit('boot:provider:start', { name: node.name, scope: node.origin });
|
||||
@@ -159,18 +221,48 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[] }): App {
|
||||
}
|
||||
}
|
||||
|
||||
const httpRoutes: RouteDef[] = routePlans
|
||||
.filter((plan) => plan.transport !== 'ws') // buffer | sse | ndjson | negotiate
|
||||
.map((plan) => ({
|
||||
method: plan.method, pattern: plan.pattern, transport: plan.transport,
|
||||
handler: async (req) => {
|
||||
const provided = await providedSeed(plan);
|
||||
return runPipeline({
|
||||
steps: planSteps(plan), handler: plan.run, transformer: plan.transformer, bus,
|
||||
seed: { ...provided, req, params: req.params, query: req.query, body: req.body, headers: req.headers },
|
||||
});
|
||||
},
|
||||
}));
|
||||
// mesh teapot: expose declared exports over the control channel (lazy resolvers read live state)
|
||||
const hasExports = exportedProviders.length || exportedSteps.length || exportedRoutes.length;
|
||||
if (hasExports && !opts.mesh?.secret) {
|
||||
throw new Error('mesh: exports declared (export: true) but no mesh.secret configured to gate the control channel');
|
||||
}
|
||||
if (opts.mesh?.secret && hasExports) {
|
||||
const manifest = buildManifest({ providers: exportedProviders, steps: exportedSteps, routes: exportedRoutes });
|
||||
const resolveScope = async (name: string, env: RequestEnvelope): Promise<unknown> => {
|
||||
let ctx: any = { req: env, params: env.params, query: env.query, body: env.body, headers: env.headers };
|
||||
for (const p of orderedProviders) if (container.has(p.name)) Object.assign(ctx, await container.resolve(p.name));
|
||||
for (const s of orderedSteps) { const fn = runners.get(s.name)!; ctx = { ...ctx, ...(await fn(ctx)) }; }
|
||||
return ctx[name];
|
||||
};
|
||||
const resolveRoute = async (name: string, env: RequestEnvelope) => {
|
||||
const plan = routePlans.find((p) => p.pattern === name && p.method === env.method);
|
||||
if (!plan) { const e: any = new Error(`no route ${name}`); e.status = 404; throw e; }
|
||||
const provided = await providedSeed(plan);
|
||||
const result = await runPipeline({
|
||||
steps: planSteps(plan), handler: plan.run, transformer: plan.transformer, bus,
|
||||
seed: { ...provided, req: env, params: env.params, query: env.query, body: env.body, headers: env.headers },
|
||||
});
|
||||
if ('stream' in result) { const e: any = new Error('cannot proxy a streaming route'); e.status = 500; throw e; }
|
||||
return result;
|
||||
};
|
||||
meshControl = createMeshControl({ secret: opts.mesh.secret, manifest, resolveScope, resolveRoute, bus });
|
||||
}
|
||||
|
||||
const httpRoutes: RouteDef[] = [
|
||||
...routePlans
|
||||
.filter((plan) => plan.transport !== 'ws') // buffer | sse | ndjson | negotiate
|
||||
.map((plan): RouteDef => ({
|
||||
method: plan.method, pattern: plan.pattern, transport: plan.transport,
|
||||
handler: async (req) => {
|
||||
const provided = await providedSeed(plan);
|
||||
return runPipeline({
|
||||
steps: planSteps(plan), handler: plan.run, transformer: plan.transformer, bus,
|
||||
seed: { ...provided, req, params: req.params, query: req.query, body: req.body, headers: req.headers },
|
||||
});
|
||||
},
|
||||
})),
|
||||
...remoteRoutes,
|
||||
];
|
||||
|
||||
const wsRoutes: WsRouteDef[] = routePlans
|
||||
.filter((plan) => plan.transport === 'ws' || plan.transport === 'negotiate')
|
||||
@@ -187,7 +279,8 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[] }): App {
|
||||
},
|
||||
}));
|
||||
|
||||
const server = createHttpServer(httpRoutes, wsRoutes, bus);
|
||||
const server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl);
|
||||
server.on('close', () => { for (const l of meshLinks) { try { l.close(); } catch { /* */ } } });
|
||||
await new Promise<void>((resolve) => server.listen(port, resolve));
|
||||
return server;
|
||||
};
|
||||
|
||||
@@ -2,6 +2,7 @@ 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'
|
||||
| 'plugin:mounted';
|
||||
|
||||
export interface EventPayload {
|
||||
|
||||
+11
-4
@@ -26,6 +26,8 @@ export interface WsOpenCtx {
|
||||
}
|
||||
export interface WsRouteDef { pattern: string; open: (ctx: WsOpenCtx) => Promise<AsyncIterable<unknown>> }
|
||||
|
||||
export interface MeshControl { path: string; handle(ws: any, req: http.IncomingMessage): void }
|
||||
|
||||
const PING_MS = 15_000;
|
||||
|
||||
export function matchPattern(pattern: string, path: string): Record<string, string> | undefined {
|
||||
@@ -106,12 +108,17 @@ function loadWss(): any | null {
|
||||
try { return require('ws').WebSocketServer; } catch { return null; }
|
||||
}
|
||||
|
||||
function attachWs(server: http.Server, wsRoutes: WsRouteDef[], bus?: Bus): void {
|
||||
if (wsRoutes.length === 0) return;
|
||||
function attachWs(server: http.Server, wsRoutes: WsRouteDef[], bus?: Bus, meshControl?: MeshControl): void {
|
||||
if (wsRoutes.length === 0 && !meshControl) return;
|
||||
const WSS = loadWss();
|
||||
const wss = WSS ? new WSS({ noServer: true }) : null;
|
||||
server.on('upgrade', (req, socket, head) => {
|
||||
const path = (req.url ?? '/').split('?')[0];
|
||||
if (meshControl && path === meshControl.path) {
|
||||
if (!wss) { socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n'); socket.destroy(); return; }
|
||||
wss.handleUpgrade(req, socket, head, (ws: any) => meshControl.handle(ws, req));
|
||||
return;
|
||||
}
|
||||
const route = wsRoutes.map((r) => ({ r, params: matchPattern(r.pattern, path) })).find((x) => x.params);
|
||||
if (!route) { socket.destroy(); return; }
|
||||
if (!wss) { socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n'); socket.destroy(); return; }
|
||||
@@ -147,7 +154,7 @@ function attachWs(server: http.Server, wsRoutes: WsRouteDef[], bus?: Bus): void
|
||||
});
|
||||
}
|
||||
|
||||
export function createHttpServer(routes: RouteDef[], wsRoutes: WsRouteDef[] = [], bus?: Bus): http.Server {
|
||||
export function createHttpServer(routes: RouteDef[], wsRoutes: WsRouteDef[] = [], bus?: Bus, meshControl?: MeshControl): http.Server {
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const url = req.url ?? '/';
|
||||
const path = url.split('?')[0];
|
||||
@@ -193,6 +200,6 @@ export function createHttpServer(routes: RouteDef[], wsRoutes: WsRouteDef[] = []
|
||||
res.writeHead(r.status, r.headers);
|
||||
res.end(r.body);
|
||||
});
|
||||
attachWs(server, wsRoutes, bus);
|
||||
attachWs(server, wsRoutes, bus, meshControl);
|
||||
return server;
|
||||
}
|
||||
@@ -19,3 +19,8 @@ export type { Transport, HttpMethod } from './metadata';
|
||||
export { inbound, abort } from './params';
|
||||
export { sseEncoder, ndjsonEncoder } from './encoders';
|
||||
export type { StreamEncoder } from './encoders';
|
||||
export type { MeshConfig } from './app';
|
||||
export { connectLink } from './mesh/link';
|
||||
export { buildRemote, envelopeFrom } from './mesh/teacup';
|
||||
export { buildManifest, createMeshControl, MESH_CONTROL_PATH } from './mesh/teapot';
|
||||
export type { Manifest, RequestEnvelope, Frame } from './mesh/protocol';
|
||||
@@ -0,0 +1,99 @@
|
||||
import type { Bus } from '../bus';
|
||||
import { HttpError } from '../signals';
|
||||
import { encode, decode, type Manifest, type RequestEnvelope, type Frame } from './protocol';
|
||||
|
||||
let connSeq = 0; // module-level: deterministic unique connection-id prefix (no Date.now/Math.random)
|
||||
|
||||
export interface Link {
|
||||
manifest: Manifest;
|
||||
rpc(kind: 'scope' | 'route', name: string, ctx: RequestEnvelope): Promise<unknown>;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
function loadWs(): any {
|
||||
return require('ws'); // lazy/optional, like streams; the ws CJS export is the WebSocket class
|
||||
}
|
||||
|
||||
export function connectLink(args: {
|
||||
url: string;
|
||||
secret: string;
|
||||
timeoutMs?: number;
|
||||
bus?: Bus;
|
||||
}): Promise<Link> {
|
||||
const timeoutMs = args.timeoutMs ?? 30_000;
|
||||
const WS = loadWs();
|
||||
const ws = new WS(args.url);
|
||||
const pending = new Map<
|
||||
string,
|
||||
{ resolve: (v: unknown) => void; reject: (e: unknown) => void; timer: ReturnType<typeof setTimeout> }
|
||||
>();
|
||||
let counter = 0;
|
||||
const connId = `c${connSeq++}`;
|
||||
let manifest: Manifest | undefined;
|
||||
|
||||
return new Promise<Link>((resolve, reject) => {
|
||||
const connectTimer = setTimeout(() => {
|
||||
ws.close();
|
||||
reject(new Error(`mesh connect timeout: ${args.url}`));
|
||||
}, timeoutMs);
|
||||
|
||||
ws.on('open', () => ws.send(encode({ type: 'hello', secret: args.secret })));
|
||||
ws.on('error', (e: unknown) => reject(e));
|
||||
ws.on('close', () => {
|
||||
clearTimeout(connectTimer);
|
||||
args.bus?.emit('mesh:disconnect', { name: args.url });
|
||||
for (const [, p] of pending) {
|
||||
clearTimeout(p.timer);
|
||||
p.reject(new Error('mesh link closed'));
|
||||
}
|
||||
pending.clear();
|
||||
if (!manifest) reject(new Error(`mesh handshake failed: ${args.url}`));
|
||||
});
|
||||
|
||||
ws.on('message', (data: unknown) => {
|
||||
let frame: Frame;
|
||||
try {
|
||||
frame = decode(String(data));
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
if (frame.type === 'manifest') {
|
||||
manifest = { scopes: frame.scopes, routes: frame.routes };
|
||||
clearTimeout(connectTimer);
|
||||
args.bus?.emit('mesh:connect', { name: args.url });
|
||||
resolve({
|
||||
manifest,
|
||||
rpc(kind, name, ctx) {
|
||||
const id = `${connId}:${counter++}`;
|
||||
return new Promise((res, rej) => {
|
||||
const timer = setTimeout(() => {
|
||||
pending.delete(id);
|
||||
rej(new Error(`mesh rpc timeout: ${name}`));
|
||||
}, timeoutMs);
|
||||
pending.set(id, { resolve: res, reject: rej, timer });
|
||||
ws.send(encode({ type: 'rpc-req', id, kind, name, ctx }));
|
||||
});
|
||||
},
|
||||
close() {
|
||||
ws.close();
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (frame.type === 'rpc-res') {
|
||||
const p = pending.get(frame.id);
|
||||
if (!p) return;
|
||||
pending.delete(frame.id);
|
||||
clearTimeout(p.timer);
|
||||
if (frame.ok) {
|
||||
p.resolve(frame.result);
|
||||
} else {
|
||||
args.bus?.emit('mesh:rpc:error', { name: frame.id, error: frame.error });
|
||||
p.reject(new HttpError(frame.error.status ?? 500, frame.error.message));
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
export interface RequestEnvelope {
|
||||
method: string;
|
||||
params: Record<string, string>;
|
||||
query: Record<string, string>;
|
||||
body: unknown;
|
||||
headers: Record<string, string | string[] | undefined>;
|
||||
}
|
||||
|
||||
export interface ScopeEntry { token: string; scope: 'app' | 'request' }
|
||||
export interface RouteEntry { method: string; pattern: string }
|
||||
export interface Manifest { scopes: ScopeEntry[]; routes: RouteEntry[] }
|
||||
|
||||
export type Frame =
|
||||
| { type: 'hello'; secret: string }
|
||||
| { type: 'manifest'; scopes: ScopeEntry[]; 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 } };
|
||||
|
||||
const TYPES = new Set(['hello', 'manifest', 'rpc-req', 'rpc-res']);
|
||||
|
||||
export function encode(f: Frame): string {
|
||||
return JSON.stringify(f);
|
||||
}
|
||||
|
||||
export function decode(s: string): Frame {
|
||||
const f = JSON.parse(s) as { type?: unknown };
|
||||
if (typeof f.type !== 'string' || !TYPES.has(f.type)) {
|
||||
throw new Error(`unknown frame type: ${String(f.type)}`);
|
||||
}
|
||||
return f as Frame;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { Link } from './link';
|
||||
import type { RequestEnvelope } from './protocol';
|
||||
import type { ResponseShape } from '../pipeline';
|
||||
|
||||
export interface RemoteScopeNode { name: string; run: (ctx: any) => Promise<Record<string, unknown>> }
|
||||
export interface RemoteRoute { method: string; pattern: string; handler: (req: RequestEnvelope) => Promise<ResponseShape> }
|
||||
|
||||
export function envelopeFrom(ctx: any): RequestEnvelope {
|
||||
return {
|
||||
method: ctx?.req?.method ?? ctx?.method ?? 'GET',
|
||||
params: ctx?.params ?? {},
|
||||
query: ctx?.query ?? {},
|
||||
body: ctx?.body,
|
||||
headers: ctx?.headers ?? {},
|
||||
};
|
||||
}
|
||||
|
||||
export function buildRemote(link: Link, origin: string): {
|
||||
providers: RemoteScopeNode[]; steps: RemoteScopeNode[]; routes: RemoteRoute[];
|
||||
} {
|
||||
const providers: RemoteScopeNode[] = [];
|
||||
const steps: RemoteScopeNode[] = [];
|
||||
for (const s of link.manifest.scopes) {
|
||||
const node: RemoteScopeNode = {
|
||||
name: s.token,
|
||||
run: async (ctx: any) => ({ [s.token]: await link.rpc('scope', s.token, envelopeFrom(ctx)) }),
|
||||
};
|
||||
(s.scope === 'app' ? providers : steps).push(node);
|
||||
}
|
||||
const routes: RemoteRoute[] = link.manifest.routes.map((r) => ({
|
||||
method: r.method, pattern: r.pattern,
|
||||
handler: async (req: RequestEnvelope) => (await link.rpc('route', r.pattern, req)) as ResponseShape,
|
||||
}));
|
||||
return { providers, steps, routes };
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import crypto from 'crypto';
|
||||
import type { Bus } from '../bus';
|
||||
import type { ResponseShape } from '../pipeline';
|
||||
import { isHttpError } from '../signals';
|
||||
import { encode, decode, type Manifest, type RequestEnvelope, type RouteEntry, type Frame } from './protocol';
|
||||
|
||||
export const MESH_CONTROL_PATH = '/__mesh__/control';
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
function safeEqual(a: string, b: string): boolean {
|
||||
const ba = Buffer.from(a);
|
||||
const bb = Buffer.from(b);
|
||||
if (ba.length !== bb.length) return false;
|
||||
return crypto.timingSafeEqual(ba, bb);
|
||||
}
|
||||
|
||||
export interface MeshControlDeps {
|
||||
secret: string;
|
||||
manifest: Manifest;
|
||||
resolveScope: (name: string, env: RequestEnvelope) => Promise<unknown>;
|
||||
resolveRoute: (name: string, env: RequestEnvelope) => Promise<ResponseShape>;
|
||||
bus?: Bus;
|
||||
}
|
||||
|
||||
export function createMeshControl(deps: MeshControlDeps): { path: string; handle: (ws: any) => void } {
|
||||
const exportedScopes = new Set(deps.manifest.scopes.map((s) => s.token));
|
||||
const exportedRoutes = new Set(deps.manifest.routes.map((r) => `${r.method} ${r.pattern}`));
|
||||
|
||||
return {
|
||||
path: MESH_CONTROL_PATH,
|
||||
handle(ws: any) {
|
||||
let authed = false;
|
||||
ws.on('message', async (data: unknown) => {
|
||||
let frame: Frame;
|
||||
try { frame = decode(String(data)); } catch { return; }
|
||||
|
||||
if (!authed) {
|
||||
if (frame.type === 'hello' && safeEqual(frame.secret, deps.secret)) {
|
||||
authed = true;
|
||||
ws.send(encode({ type: 'manifest', scopes: deps.manifest.scopes, routes: deps.manifest.routes }));
|
||||
deps.bus?.emit('mesh:connect', { name: 'teapot' });
|
||||
} else {
|
||||
ws.close(1008);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (frame.type !== 'rpc-req') return;
|
||||
const { id, kind, name, ctx } = frame;
|
||||
try {
|
||||
let result: unknown;
|
||||
if (kind === 'scope') {
|
||||
if (!exportedScopes.has(name)) { const e: any = new Error(`not exported: ${name}`); e.status = 403; throw e; }
|
||||
result = await deps.resolveScope(name, ctx);
|
||||
} else {
|
||||
if (![...exportedRoutes].some((k) => k.endsWith(` ${name}`))) { const e: any = new Error(`not exported: ${name}`); e.status = 403; throw e; }
|
||||
result = await deps.resolveRoute(name, ctx);
|
||||
}
|
||||
ws.send(encode({ type: 'rpc-res', id, ok: true, result }));
|
||||
} catch (err) {
|
||||
const status = isHttpError(err) ? err.status : (err as any)?.status ?? 500;
|
||||
deps.bus?.emit('mesh:rpc:error', { name, error: err });
|
||||
ws.send(encode({ type: 'rpc-res', id, ok: false, error: { message: (err as Error).message, status } }));
|
||||
}
|
||||
});
|
||||
ws.on('close', () => deps.bus?.emit('mesh:disconnect', { name: 'teapot' }));
|
||||
},
|
||||
};
|
||||
}
|
||||
+9
-9
@@ -3,11 +3,11 @@ import 'reflect-metadata';
|
||||
export type Ctor = new (...args: any[]) => any;
|
||||
export type TransformerFn = (value: unknown) => { status?: number; headers?: Record<string, string>; body: string };
|
||||
|
||||
export interface ProviderMeta { provides: string; needs: string[]; optional: boolean }
|
||||
export interface StepMeta { provides: string; needs: string[]; optional: boolean }
|
||||
export interface ProviderMeta { provides: string; needs: string[]; optional: boolean; export: boolean }
|
||||
export interface StepMeta { provides: string; needs: string[]; optional: boolean; export: boolean }
|
||||
export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
||||
export type Transport = 'buffer' | 'sse' | 'ndjson' | 'negotiate' | 'ws';
|
||||
export interface RouteMeta { method: HttpMethod; path: string; handlerName: string; transport: Transport }
|
||||
export interface RouteMeta { method: HttpMethod; path: string; handlerName: string; transport: Transport; export: boolean }
|
||||
export interface ModuleOptions {
|
||||
mountpoint: string; providers?: Ctor[]; steps?: Ctor[]; controllers?: Ctor[];
|
||||
}
|
||||
@@ -21,16 +21,16 @@ const K = {
|
||||
transformer: Symbol('gt:transformer'),
|
||||
};
|
||||
|
||||
export function Provider(opts: { provides: string; needs?: string[]; optional?: boolean }): ClassDecorator {
|
||||
export function Provider(opts: { provides: string; needs?: string[]; optional?: boolean; export?: boolean }): ClassDecorator {
|
||||
return (target) => {
|
||||
const meta: ProviderMeta = { provides: opts.provides, needs: opts.needs ?? [], optional: opts.optional ?? false };
|
||||
const meta: ProviderMeta = { provides: opts.provides, needs: opts.needs ?? [], optional: opts.optional ?? false, export: opts.export ?? false };
|
||||
Reflect.defineMetadata(K.provider, meta, target);
|
||||
};
|
||||
}
|
||||
|
||||
export function Step(opts: { provides: string; needs?: string[]; optional?: boolean }): ClassDecorator {
|
||||
export function Step(opts: { provides: string; needs?: string[]; optional?: boolean; export?: boolean }): ClassDecorator {
|
||||
return (target) => {
|
||||
const meta: StepMeta = { provides: opts.provides, needs: opts.needs ?? [], optional: opts.optional ?? false };
|
||||
const meta: StepMeta = { provides: opts.provides, needs: opts.needs ?? [], optional: opts.optional ?? false, export: opts.export ?? false };
|
||||
Reflect.defineMetadata(K.step, meta, target);
|
||||
};
|
||||
}
|
||||
@@ -40,11 +40,11 @@ export function Route(prefix: string): ClassDecorator {
|
||||
}
|
||||
|
||||
function routeDecorator(method: HttpMethod, transport: Transport) {
|
||||
return (path: string): MethodDecorator =>
|
||||
return (path: string, opts?: { export?: boolean }): MethodDecorator =>
|
||||
(target, propertyKey) => {
|
||||
const ctor = target.constructor;
|
||||
const routes = (Reflect.getMetadata(K.routes, ctor) as RouteMeta[]) ?? [];
|
||||
routes.push({ method, path, handlerName: String(propertyKey), transport });
|
||||
routes.push({ method, path, handlerName: String(propertyKey), transport, export: opts?.export ?? false });
|
||||
Reflect.defineMetadata(K.routes, routes, ctor);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import WebSocket from 'ws';
|
||||
import { createHttpServer, type MeshControl } from '../../src/http';
|
||||
|
||||
describe('mesh control upgrade', () => {
|
||||
it('routes the reserved path to meshControl.handle and leaves wsRoutes intact', async () => {
|
||||
let handled = false;
|
||||
const meshControl: MeshControl = { path: '/__mesh__/control', handle: (ws) => { handled = true; ws.send('hi'); } };
|
||||
const server = createHttpServer([], [], undefined, meshControl);
|
||||
await new Promise<void>((r) => server.listen(0, r));
|
||||
const port = (server.address() as any).port;
|
||||
const client = new WebSocket(`ws://127.0.0.1:${port}/__mesh__/control`);
|
||||
const msg = await new Promise<string>((res) => { client.on('message', (d) => res(d.toString())); });
|
||||
expect(msg).toBe('hi');
|
||||
expect(handled).toBe(true);
|
||||
client.close(); server.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index';
|
||||
|
||||
const SECRET = 's3cr3t';
|
||||
|
||||
@Provider({ provides: 'config', export: true })
|
||||
class Config { provide() { return { config: { region: 'mx' } }; } }
|
||||
|
||||
@Step({ provides: 'auth', needs: [], export: true })
|
||||
class Auth { run(ctx: any) { return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; } }
|
||||
|
||||
@Route('/remote')
|
||||
class RemoteCtl { @Get('/ping', { export: true }) ping() { return { pong: true }; } }
|
||||
|
||||
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth], controllers: [RemoteCtl] })
|
||||
class TeapotModule {}
|
||||
|
||||
@Route('/local')
|
||||
class LocalCtl {
|
||||
@Get('/who')
|
||||
who(@needs('config') config: any, @needs('auth') auth: any) { return { config, auth }; }
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
|
||||
class TeacupModule {}
|
||||
|
||||
describe('mesh skeleton integration', () => {
|
||||
it('teacup resolves remote app-scope + request-scope into a local handler', async () => {
|
||||
const teapot = createApp({ modules: [TeapotModule], mesh: { secret: SECRET } });
|
||||
const tServer = await teapot.listen(0);
|
||||
const tPort = (tServer.address() as any).port;
|
||||
const url = `ws://127.0.0.1:${tPort}/__mesh__/control`;
|
||||
|
||||
const teacup = createApp({ modules: [TeacupModule], mesh: { teapots: [{ url, secret: SECRET }] } });
|
||||
const cServer = await teacup.listen(0);
|
||||
const cPort = (cServer.address() as any).port;
|
||||
|
||||
const res = await fetch(`http://127.0.0.1:${cPort}/api/local/who`, { headers: { 'x-token': 'abc' } });
|
||||
expect(await res.json()).toEqual({ config: { region: 'mx' }, auth: { token: 'abc' } });
|
||||
|
||||
tServer.close(); cServer.close();
|
||||
});
|
||||
|
||||
it('teapot still serves its own local route (regression)', async () => {
|
||||
const app = createApp({ modules: [TeapotModule], mesh: { secret: SECRET } });
|
||||
const s = await app.listen(0); const p = (s.address() as any).port;
|
||||
const res = await fetch(`http://127.0.0.1:${p}/api/remote/ping`);
|
||||
expect(await res.json()).toEqual({ pong: true });
|
||||
s.close();
|
||||
});
|
||||
|
||||
it('rejects a bad secret (teacup boot fails)', async () => {
|
||||
const teapot = createApp({ modules: [TeapotModule], mesh: { secret: SECRET } });
|
||||
const tServer = await teapot.listen(0); const tPort = (tServer.address() as any).port;
|
||||
const teacup = createApp({ modules: [TeacupModule], mesh: { teapots: [{ url: `ws://127.0.0.1:${tPort}/__mesh__/control`, secret: 'WRONG' }], timeoutMs: 800 } });
|
||||
await expect(teacup.listen(0)).rejects.toThrow();
|
||||
tServer.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { WebSocketServer } from 'ws';
|
||||
import { connectLink } from '../../src/mesh/link';
|
||||
import { encode, decode } from '../../src/mesh/protocol';
|
||||
|
||||
const env = { method: 'GET', params: {}, query: {}, body: undefined, headers: {} };
|
||||
|
||||
// teapot that validates secret 'good', returns a manifest, answers scope rpc (boom -> error)
|
||||
function startTeapot(secret = 'good') {
|
||||
const wss = new WebSocketServer({ port: 0 });
|
||||
wss.on('connection', (ws) => {
|
||||
let authed = false;
|
||||
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', scopes: [{ token: 'auth', scope: 'request' }], routes: [] })); }
|
||||
else ws.close(1008);
|
||||
return;
|
||||
}
|
||||
if (f.type === 'rpc-req') {
|
||||
if (f.name === 'boom') ws.send(encode({ type: 'rpc-res', id: f.id, ok: false, error: { message: 'denied', status: 403 } }));
|
||||
else ws.send(encode({ type: 'rpc-res', id: f.id, ok: true, result: { got: f.name } }));
|
||||
}
|
||||
});
|
||||
});
|
||||
const port = (wss.address() as any).port;
|
||||
return { url: `ws://127.0.0.1:${port}/__mesh__/control`, close: () => wss.close() };
|
||||
}
|
||||
|
||||
// teapot that completes the handshake but NEVER answers rpc-req (for timeout)
|
||||
function startSilentTeapot(secret = 'good') {
|
||||
const wss = new WebSocketServer({ port: 0 });
|
||||
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', scopes: [], routes: [] }));
|
||||
// ignore rpc-req entirely
|
||||
});
|
||||
});
|
||||
const port = (wss.address() as any).port;
|
||||
return { url: `ws://127.0.0.1:${port}/__mesh__/control`, close: () => wss.close() };
|
||||
}
|
||||
|
||||
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' }]);
|
||||
link.close(); t.close();
|
||||
});
|
||||
|
||||
it('rpc resolves a result by id', async () => {
|
||||
const t = startTeapot();
|
||||
const link = await connectLink({ url: t.url, secret: 'good' });
|
||||
expect(await link.rpc('scope', 'auth', env)).toEqual({ got: 'auth' });
|
||||
link.close(); t.close();
|
||||
});
|
||||
|
||||
it('rpc rejects with an HttpError carrying the remote status', async () => {
|
||||
const t = startTeapot();
|
||||
const link = await connectLink({ url: t.url, secret: 'good' });
|
||||
await expect(link.rpc('scope', 'boom', env)).rejects.toMatchObject({ status: 403, message: 'denied' });
|
||||
link.close(); t.close();
|
||||
});
|
||||
|
||||
it('rejects connect on bad secret', async () => {
|
||||
const t = startTeapot();
|
||||
await expect(connectLink({ url: t.url, secret: 'wrong', timeoutMs: 500 })).rejects.toThrow();
|
||||
t.close();
|
||||
});
|
||||
|
||||
it('times out an rpc when the teapot never answers', async () => {
|
||||
const t = startSilentTeapot();
|
||||
const link = await connectLink({ url: t.url, secret: 'good', timeoutMs: 150 });
|
||||
await expect(link.rpc('scope', 'whatever', env)).rejects.toThrow(/timeout/i);
|
||||
link.close(); t.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { encode, decode, type Frame, type RequestEnvelope } from '../../src/mesh/protocol';
|
||||
|
||||
const env: RequestEnvelope = { method: 'GET', params: { id: '1' }, query: {}, body: undefined, headers: {} };
|
||||
|
||||
describe('protocol codec', () => {
|
||||
it('round-trips each frame type', () => {
|
||||
const frames: Frame[] = [
|
||||
{ type: 'hello', secret: 's3cr3t' },
|
||||
{ type: 'manifest', scopes: [{ token: 'auth', scope: 'request' }], routes: [{ method: 'GET', pattern: '/u/:id' }] },
|
||||
{ type: 'rpc-req', id: 'c1:1', kind: 'scope', name: 'auth', ctx: env },
|
||||
{ type: 'rpc-res', id: 'c1:1', ok: true, result: { id: 'u1' } },
|
||||
{ type: 'rpc-res', id: 'c1:2', ok: false, error: { message: 'no', status: 401 } },
|
||||
];
|
||||
for (const f of frames) expect(decode(encode(f))).toEqual(f);
|
||||
});
|
||||
|
||||
it('throws on malformed json', () => {
|
||||
expect(() => decode('{not json')).toThrow();
|
||||
});
|
||||
|
||||
it('throws on unknown frame type', () => {
|
||||
expect(() => decode(JSON.stringify({ type: 'bogus' }))).toThrow(/unknown frame/i);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
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' }] },
|
||||
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 () => {
|
||||
const calls: any[] = [];
|
||||
const { providers, steps } = buildRemote(fakeLink(calls), 'ws://t');
|
||||
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 ctx = { req: {}, params: { id: '9' }, query: {}, body: undefined, headers: { x: '1' } };
|
||||
expect(await steps[0].run(ctx)).toEqual({ auth: { id: 'u1' } });
|
||||
expect(calls.find((c) => c.name === 'auth').ctx).toMatchObject({ params: { id: '9' }, headers: { x: '1' } });
|
||||
});
|
||||
|
||||
it('makes a proxy route entry with method+pattern', async () => {
|
||||
const calls: any[] = [];
|
||||
const { routes } = buildRemote(fakeLink(calls), 'ws://t');
|
||||
expect(routes[0]).toMatchObject({ method: 'GET', pattern: '/u/:id' });
|
||||
});
|
||||
|
||||
it('envelopeFrom extracts only serializable request fields', () => {
|
||||
const env = envelopeFrom({ method: 'POST', params: { a: '1' }, query: { q: 'x' }, body: { n: 1 }, headers: { h: 'v' }, db: { find() {} } } as any);
|
||||
expect(env).toEqual({ method: 'POST', params: { a: '1' }, query: { q: 'x' }, body: { n: 1 }, headers: { h: 'v' } });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { EventEmitter } from 'events';
|
||||
import { buildManifest, createMeshControl } from '../../src/mesh/teapot';
|
||||
import { encode, decode } from '../../src/mesh/protocol';
|
||||
import { Unauthorized } from '../../src/signals';
|
||||
|
||||
const fakeWs = () => {
|
||||
const ws: any = new EventEmitter();
|
||||
ws.sent = [];
|
||||
ws.send = (s: string) => ws.sent.push(decode(s));
|
||||
ws.close = vi.fn();
|
||||
return ws;
|
||||
};
|
||||
|
||||
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' }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createMeshControl', () => {
|
||||
const manifest = buildManifest({ providers: ['config'], steps: ['auth'], routes: [{ method: 'GET', pattern: '/u/:id' }] });
|
||||
const make = (over: Partial<Parameters<typeof createMeshControl>[0]> = {}) => createMeshControl({
|
||||
secret: 'good', manifest,
|
||||
resolveScope: async (name) => ({ resolved: name }),
|
||||
resolveRoute: async () => ({ status: 200, headers: {}, body: 'route-body' }),
|
||||
...over,
|
||||
});
|
||||
|
||||
it('exposes the reserved control path', () => {
|
||||
expect(make().path).toBe('/__mesh__/control');
|
||||
});
|
||||
|
||||
it('rejects a bad secret and closes', () => {
|
||||
const ws = fakeWs(); make().handle(ws);
|
||||
ws.emit('message', encode({ type: 'hello', secret: 'wrong' }));
|
||||
expect(ws.close).toHaveBeenCalledWith(1008);
|
||||
expect(ws.sent).toEqual([]);
|
||||
});
|
||||
|
||||
it('answers a good hello with the manifest', () => {
|
||||
const ws = fakeWs(); make().handle(ws);
|
||||
ws.emit('message', encode({ type: 'hello', secret: 'good' }));
|
||||
expect(ws.sent[0]).toMatchObject({ type: 'manifest', scopes: manifest.scopes });
|
||||
});
|
||||
|
||||
it('does NOT process rpc before handshake', async () => {
|
||||
const ws = fakeWs(); make().handle(ws);
|
||||
ws.emit('message', encode({ type: 'rpc-req', id: '1', kind: 'scope', name: 'config', ctx: {} as any }));
|
||||
await new Promise((r) => setTimeout(r, 5));
|
||||
expect(ws.sent).toEqual([]);
|
||||
});
|
||||
|
||||
it('resolves an exported scope after handshake', async () => {
|
||||
const ws = fakeWs(); make().handle(ws);
|
||||
ws.emit('message', encode({ type: 'hello', secret: 'good' }));
|
||||
ws.emit('message', encode({ type: 'rpc-req', id: '7', kind: 'scope', name: 'config', ctx: {} as any }));
|
||||
await new Promise((r) => setTimeout(r, 5));
|
||||
expect(ws.sent.find((f: any) => f.type === 'rpc-res')).toEqual({ type: 'rpc-res', id: '7', ok: true, result: { resolved: 'config' } });
|
||||
});
|
||||
|
||||
it('rejects an unexported scope', async () => {
|
||||
const ws = fakeWs(); make().handle(ws);
|
||||
ws.emit('message', encode({ type: 'hello', secret: 'good' }));
|
||||
ws.emit('message', encode({ type: 'rpc-req', id: '8', kind: 'scope', name: 'secretsvc', ctx: {} as any }));
|
||||
await new Promise((r) => setTimeout(r, 5));
|
||||
const res: any = ws.sent.find((f: any) => f.type === 'rpc-res');
|
||||
expect(res.ok).toBe(false);
|
||||
expect(res.error.status).toBe(403);
|
||||
});
|
||||
|
||||
it('propagates a thrown HttpError status in the error frame', async () => {
|
||||
const ws = fakeWs();
|
||||
make({ resolveScope: async () => { throw new Unauthorized('nope'); } }).handle(ws);
|
||||
ws.emit('message', encode({ type: 'hello', secret: 'good' }));
|
||||
ws.emit('message', encode({ type: 'rpc-req', id: '9', kind: 'scope', name: 'config', ctx: {} as any }));
|
||||
await new Promise((r) => setTimeout(r, 5));
|
||||
const res: any = ws.sent.find((f: any) => f.type === 'rpc-res');
|
||||
expect(res).toMatchObject({ id: '9', ok: false, error: { message: 'nope', status: 401 } });
|
||||
});
|
||||
});
|
||||
+24
-3
@@ -19,15 +19,15 @@ class Ctl { @Get('/:id') getUser() { return 1; } }
|
||||
class ApiModule {}
|
||||
|
||||
test('provider metadata is readable', () => {
|
||||
expect(getProviderMeta(Db)).toEqual({ provides: 'db', needs: ['config'], optional: false });
|
||||
expect(getProviderMeta(Db)).toEqual({ provides: 'db', needs: ['config'], optional: false, export: false });
|
||||
});
|
||||
|
||||
test('step metadata is readable', () => {
|
||||
expect(getStepMeta(Auth)).toEqual({ provides: 'user', needs: ['db', 'req'], optional: false });
|
||||
expect(getStepMeta(Auth)).toEqual({ provides: 'user', needs: ['db', 'req'], optional: false, export: false });
|
||||
});
|
||||
|
||||
test('routes carry method, path and handler name', () => {
|
||||
expect(getRoutes(Ctl)).toEqual([{ method: 'GET', path: '/users/:id', handlerName: 'getUser', transport: 'buffer' }]);
|
||||
expect(getRoutes(Ctl)).toEqual([{ method: 'GET', path: '/users/:id', handlerName: 'getUser', transport: 'buffer', export: false }]);
|
||||
});
|
||||
|
||||
test('module metadata lists members', () => {
|
||||
@@ -53,3 +53,24 @@ describe('stream route decorators', () => {
|
||||
expect(byName.make).toMatchObject({ method: 'POST', transport: 'buffer', path: '/make' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('mesh export flags', () => {
|
||||
it('providers/steps carry export (default false)', () => {
|
||||
@Provider({ provides: 'config', export: true }) class C { provide() { return {}; } }
|
||||
@Step({ provides: 'auth', export: true }) class A { run() { return {}; } }
|
||||
@Provider({ provides: 'priv' }) class P { provide() { return {}; } }
|
||||
expect(getProviderMeta(C)!.export).toBe(true);
|
||||
expect(getStepMeta(A)!.export).toBe(true);
|
||||
expect(getProviderMeta(P)!.export).toBe(false);
|
||||
});
|
||||
|
||||
it('routes carry export via decorator option (default false)', () => {
|
||||
class Ctl2 {
|
||||
@Get('/pub', { export: true }) pub() {}
|
||||
@Get('/priv') priv() {}
|
||||
}
|
||||
const byName = Object.fromEntries(getRoutes(Ctl2).map((r) => [r.handlerName, r]));
|
||||
expect(byName.pub.export).toBe(true);
|
||||
expect(byName.priv.export).toBe(false);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user