feat(mesh): teacup WS link client with id-correlated RPC
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
2 files changed
+177
No files matched your search
@@ -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,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();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user