From 31f91ee61f1d08e1695160381d433dbb06628afa Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 27 Jun 2026 20:23:58 -0500 Subject: [PATCH] feat(mesh): RPC frame protocol and codec Signed-off-by: Diego Resendez --- src/mesh/protocol.ts | 32 ++++++++++++++++++++++++++++++++ test/mesh/protocol.test.ts | 25 +++++++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 src/mesh/protocol.ts create mode 100644 test/mesh/protocol.test.ts diff --git a/src/mesh/protocol.ts b/src/mesh/protocol.ts new file mode 100644 index 0000000..b37d242 --- /dev/null +++ b/src/mesh/protocol.ts @@ -0,0 +1,32 @@ +export interface RequestEnvelope { + method: string; + params: Record; + query: Record; + body: unknown; + headers: Record; +} + +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; +} diff --git a/test/mesh/protocol.test.ts b/test/mesh/protocol.test.ts new file mode 100644 index 0000000..f390593 --- /dev/null +++ b/test/mesh/protocol.test.ts @@ -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); + }); +});