refactor(mesh): serve the control channel over the neutral WsSocket
The mesh control channel was the last consumer speaking the `ws` EventEmitter
API directly: http/ws.ts handed meshControl.handle a raw socket, while every
@Ws route already went through nodeSocket() to get a neutral WsSocket. Mesh did
not lack an abstraction — it skipped the one the codebase already had.
handle() now takes a WsSocket and consumes `inbound`, so both feeds work: Node
via the existing nodeSocket, and Deno/Bun via app.upgrade, where the socket is
already neutral. That is what unblocks mounting the control channel off Node.
RPCs are still dispatched without awaiting. The old `ws.on('message')` listener
overlapped them, and the peer's id-keyed pending map exists for exactly that —
awaiting inside the receive loop would have silently serialized every mesh call.
A test now pins the overlap.
The unused `http` import in http/types.ts fell out with MeshControl's req
parameter: nothing in that module is Node-shaped any more.
Node behaviour is unchanged — the teapot↔teacup integration tests pass
untouched. teapot.test.ts drives handle() directly, so its fake moved from a raw
EventEmitter to a fake WsSocket.
Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Task 3
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
3 files changed
+128
-58
No files matched your search
+6
-3
@@ -1,9 +1,8 @@
|
||||
import type http from 'http';
|
||||
import type { Transport } from '../metadata';
|
||||
import type { PipelineResult } from '../pipeline';
|
||||
import type { ErrorRenderer } from '../transformers';
|
||||
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
|
||||
import type { WsRequest } from './ws-core';
|
||||
import type { WsRequest, WsSocket } from './ws-core';
|
||||
import type { StaticResolver } from '../views';
|
||||
|
||||
/** Per-request size and timeout ceilings applied by the server. */
|
||||
@@ -74,5 +73,9 @@ export interface WsRouteDef {
|
||||
/** Hook for a mesh gateway to take over WebSocket upgrades on a fixed path. */
|
||||
export interface MeshControl {
|
||||
path: string;
|
||||
handle(ws: any, req: http.IncomingMessage): void;
|
||||
/**
|
||||
* Serves one control connection over the neutral socket — the same capability every other ws
|
||||
* consumer takes, so Node (via `nodeSocket`) and Deno/Bun (via `app.upgrade`) both feed it.
|
||||
*/
|
||||
handle(socket: WsSocket): void;
|
||||
}
|
||||
+3
-1
@@ -38,7 +38,9 @@ function handleMeshUpgrade(
|
||||
return true;
|
||||
}
|
||||
|
||||
wss.handleUpgrade(req, socket, head, (ws: any) => meshControl.handle(ws, req));
|
||||
// nodeSocket, not the raw ws: the control channel is the last consumer that spoke the
|
||||
// `ws` EventEmitter API directly. It now takes the same neutral socket every route does.
|
||||
wss.handleUpgrade(req, socket, head, (ws: any) => meshControl.handle(nodeSocket(ws)));
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
+119
-54
@@ -1,17 +1,45 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { EventEmitter } from 'events';
|
||||
import { buildManifest, createMeshControl } from '../../src/mesh/teapot';
|
||||
import { encode, decode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol';
|
||||
|
||||
const V = MESH_PROTOCOL_VERSION;
|
||||
import { channel } from '../../src/channel';
|
||||
import type { WsSocket } from '../../src/http/ws-core';
|
||||
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;
|
||||
const V = MESH_PROTOCOL_VERSION;
|
||||
|
||||
/** Lets the control loop drain: it consumes `inbound` asynchronously and does not await RPCs. */
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 5));
|
||||
|
||||
/**
|
||||
* A fake neutral WsSocket — the same capability `nodeSocket` builds on Node and `app.upgrade`
|
||||
* hands over on Deno/Bun. `close` also ends `inbound`, mirroring a real socket's close.
|
||||
*/
|
||||
const fakeSocket = () => {
|
||||
const inbound = channel<unknown>();
|
||||
const ac = new AbortController();
|
||||
const sent: any[] = [];
|
||||
const close = vi.fn((_code?: number, _reason?: string) => {
|
||||
inbound.close();
|
||||
ac.abort();
|
||||
});
|
||||
const socket: WsSocket = {
|
||||
inbound,
|
||||
abort: ac.signal,
|
||||
isOpen: true,
|
||||
send: (data: string) => {
|
||||
sent.push(decode(data));
|
||||
},
|
||||
close,
|
||||
terminate: () => ac.abort(),
|
||||
};
|
||||
|
||||
/** Deliver a frame the way a peer would, then let the loop process it. */
|
||||
const deliver = async (frame: unknown) => {
|
||||
inbound.push(encode(frame as never));
|
||||
await settle();
|
||||
};
|
||||
|
||||
return { socket, sent, close, deliver, inbound };
|
||||
};
|
||||
|
||||
describe('buildManifest', () => {
|
||||
@@ -24,81 +52,118 @@ describe('buildManifest', () => {
|
||||
});
|
||||
|
||||
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,
|
||||
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', v: V, secret: 'wrong' }));
|
||||
expect(ws.close).toHaveBeenCalledWith(1008);
|
||||
expect(ws.sent).toEqual([]);
|
||||
it('rejects a bad secret and closes', async () => {
|
||||
const t = fakeSocket();
|
||||
make().handle(t.socket);
|
||||
await t.deliver({ type: 'hello', v: V, secret: 'wrong' });
|
||||
expect(t.close).toHaveBeenCalledWith(1008);
|
||||
expect(t.sent).toEqual([]);
|
||||
});
|
||||
|
||||
it('answers a good hello with the manifest, stamped with the protocol version', () => {
|
||||
const ws = fakeWs(); make().handle(ws);
|
||||
ws.emit('message', encode({ type: 'hello', v: V, secret: 'good' }));
|
||||
expect(ws.sent[0]).toMatchObject({ type: 'manifest', v: V, scopes: manifest.scopes });
|
||||
it('answers a good hello with the manifest, stamped with the protocol version', async () => {
|
||||
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 });
|
||||
});
|
||||
|
||||
it('rejects a version-skewed peer before checking its secret, naming both versions', () => {
|
||||
const ws = fakeWs(); make().handle(ws);
|
||||
it('rejects a version-skewed peer before checking its secret, naming both versions', async () => {
|
||||
const t = fakeSocket();
|
||||
make().handle(t.socket);
|
||||
// correct secret, wrong protocol: must still be refused — and not as an auth failure
|
||||
ws.emit('message', encode({ type: 'hello', v: V + 1, secret: 'good' } as any));
|
||||
expect(ws.sent).toEqual([]);
|
||||
const [code, reason] = ws.close.mock.calls[0];
|
||||
await t.deliver({ type: 'hello', v: V + 1, secret: 'good' });
|
||||
expect(t.sent).toEqual([]);
|
||||
const [code, reason] = t.close.mock.calls[0];
|
||||
expect(code).toBe(1008);
|
||||
expect(reason).toContain(String(V));
|
||||
expect(reason).toContain(String(V + 1));
|
||||
});
|
||||
|
||||
it('refuses a version-skewed peer even when its secret is also wrong', () => {
|
||||
const ws = fakeWs(); make().handle(ws);
|
||||
ws.emit('message', encode({ type: 'hello', v: V + 1, secret: 'wrong' } as any));
|
||||
expect(ws.sent).toEqual([]);
|
||||
expect(ws.close).toHaveBeenCalled();
|
||||
it('refuses a version-skewed peer even when its secret is also wrong', async () => {
|
||||
const t = fakeSocket();
|
||||
make().handle(t.socket);
|
||||
await t.deliver({ type: 'hello', v: V + 1, secret: 'wrong' });
|
||||
expect(t.sent).toEqual([]);
|
||||
expect(t.close).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
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([]);
|
||||
const t = fakeSocket();
|
||||
make().handle(t.socket);
|
||||
await t.deliver({ type: 'rpc-req', id: '1', kind: 'scope', name: 'config', ctx: {} });
|
||||
expect(t.sent).toEqual([]);
|
||||
});
|
||||
|
||||
it('resolves an exported scope after handshake', async () => {
|
||||
const ws = fakeWs(); make().handle(ws);
|
||||
ws.emit('message', encode({ type: 'hello', v: V, 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' } });
|
||||
const t = fakeSocket();
|
||||
make().handle(t.socket);
|
||||
await t.deliver({ type: 'hello', v: V, secret: 'good' });
|
||||
await t.deliver({ type: 'rpc-req', id: '7', kind: 'scope', name: 'config', ctx: {} });
|
||||
expect(t.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', v: V, 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');
|
||||
const t = fakeSocket();
|
||||
make().handle(t.socket);
|
||||
await t.deliver({ type: 'hello', v: V, secret: 'good' });
|
||||
await t.deliver({ type: 'rpc-req', id: '8', kind: 'scope', name: 'secretsvc', ctx: {} });
|
||||
const res: any = t.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', v: V, 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');
|
||||
const t = fakeSocket();
|
||||
make({
|
||||
resolveScope: async () => {
|
||||
throw new Unauthorized('nope');
|
||||
},
|
||||
}).handle(t.socket);
|
||||
await t.deliver({ type: 'hello', v: V, secret: 'good' });
|
||||
await t.deliver({ type: 'rpc-req', id: '9', kind: 'scope', name: 'config', ctx: {} });
|
||||
const res: any = t.sent.find((f: any) => f.type === 'rpc-res');
|
||||
expect(res).toMatchObject({ id: '9', ok: false, error: { message: 'nope', status: 401 } });
|
||||
});
|
||||
|
||||
it('serves overlapping RPCs concurrently rather than head-of-line blocking', async () => {
|
||||
// the loop must not await handleRpc: a slow call would otherwise stall every later one.
|
||||
// fast is delivered second but resolves first, which can only happen if they overlap.
|
||||
const t = fakeSocket();
|
||||
make({
|
||||
resolveScope: async (name) => {
|
||||
if (name === 'config') await new Promise((r) => setTimeout(r, 30));
|
||||
return { resolved: name };
|
||||
},
|
||||
}).handle(t.socket);
|
||||
await t.deliver({ type: 'hello', v: V, secret: 'good' });
|
||||
t.inbound.push(encode({ type: 'rpc-req', id: 'slow', kind: 'scope', name: 'config', ctx: {} as never }));
|
||||
t.inbound.push(encode({ type: 'rpc-req', id: 'fast', kind: 'scope', name: 'auth', ctx: {} as never }));
|
||||
await new Promise((r) => setTimeout(r, 60));
|
||||
|
||||
const ids = t.sent.filter((f: any) => f.type === 'rpc-res').map((f: any) => f.id);
|
||||
expect(ids).toEqual(['fast', 'slow']);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user