feat(mesh): RPC frame protocol and codec

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-06-27 20:23:58 -05:00
1 parent a4fb19210e
commit 31f91ee61f
2 files changed
+57

No files matched your search

+32
View File
@@ -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;
}
+25
View File
@@ -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);
});
});