feat(mesh): connect the teacup over a runtime-neutral WebSocket client

connectLink constructed `require('ws')` directly and drove its EventEmitter API,
which is why a teacup could only run on Node. It now goes through the neutral
WsSocket like every other consumer, over whichever client the runtime provides:
the platform global (Deno, Bun, Node >= 22) or the `ws` peer for Node 18-21,
which has no global. `ws` stays optional and is only reached for when the global
is absent.

One bridge covers both because `ws` also implements the browser-compatible event
API and delivers text frames as `event.data` strings — probed against the real
package rather than taken on faith.

Both implementations are exercised in one run: `ws` is always in the matrix, so
the Node 18-21 path cannot rot unseen on CI that only runs a modern Node, which
is how a fallback quietly stops working. connectLink takes an optional Ctor to
make that possible; it doubles as a bring-your-own-WebSocket hook for runtimes
we do not ship an adapter for.

Verified the edge bundle is unaffected: `require('ws')` tree-shakes out of the
workerd build entirely.

Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Task 4

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-07-15 15:00:04 -05:00
1 parent 71b59e7c25
commit 0ea4db3fef
3 files changed
+168 -56

No files matched your search

+44 -2
View File
@@ -41,8 +41,8 @@ export interface EventfulSocket {
send(data: string): void;
close(code?: number, reason?: string): void;
addEventListener(
type: 'message' | 'close' | 'error',
listener: (event: { data?: string | ArrayBuffer }) => void,
type: 'open' | 'message' | 'close' | 'error',
listener: (event: { data?: string | ArrayBuffer; error?: unknown }) => void,
): void;
}
@@ -107,6 +107,48 @@ export function neutralSocket(
};
}
/** Constructs a host WebSocket *client*. Both the platform global and the `ws` package satisfy it. */
export type SocketCtor = new (url: string) => EventfulSocket;
/**
* The WebSocket client implementation: the platform global where it exists (Deno, Bun, and
* Node >= 22), else the `ws` optional peer — Node 18-21, our declared floor, has no global.
*
* Both expose the same `addEventListener` API and deliver text frames as `event.data` strings,
* so one bridge covers both. That is verified rather than assumed: `ws` implements the
* browser-compatible event API alongside its EventEmitter one.
*/
export function loadWebSocketCtor(): SocketCtor {
const platform = (globalThis as { WebSocket?: SocketCtor }).WebSocket;
if (platform) return platform;
// eslint-disable-next-line @typescript-eslint/no-require-imports
return require('ws') as SocketCtor;
}
/**
* Opens a client connection and wraps it as a neutral {@link WsSocket}. `opened` resolves once
* the socket is live (the caller's cue to send its first frame) and rejects if it never opens.
*
* `Ctor` is injectable so both implementations can be exercised on one runtime — otherwise CI
* on a single Node version would silently cover only one of the two paths.
*/
export function connectSocket(
url: string,
Ctor: SocketCtor = loadWebSocketCtor(),
): { socket: WsSocket; opened: Promise<void> } {
const host = new Ctor(url);
// registered before eventSocket's own error listener, so a connect failure rejects `opened`
// with the host's real error rather than eventSocket's generic one
const opened = new Promise<void>((resolve, reject) => {
host.addEventListener('open', () => resolve());
host.addEventListener('error', (event) => reject(event?.error ?? new Error(`websocket error: ${url}`)));
});
return { socket: eventSocket(host), opened };
}
/**
* Runs the ws lifecycle, closing with 1011 if it rejects. `app.upgrade` can reject *before*
* `runWsConnection`'s own try/catch (mesh-before-listen, provider boot failure); unguarded,
+97 -53
View File
@@ -1,5 +1,7 @@
import type { Bus } from '../bus';
import { HttpError } from '../signals';
import { connectSocket, type SocketCtor } from '../http/ws-adapter';
import type { WsSocket } from '../http/ws-core';
import { encode, decode, MESH_PROTOCOL_VERSION, type Manifest, type RequestEnvelope, type Frame } from './protocol';
/** Client handle to a remote mesh server: its manifest, an RPC caller, and a close(). */
@@ -16,12 +18,6 @@ type PendingEntry = {
timer: ReturnType<typeof setTimeout>;
};
function loadWs(): any {
// lazy/optional, like streams; the ws CJS export is the WebSocket class
// eslint-disable-next-line @typescript-eslint/no-require-imports
return require('ws');
}
/** Reject and clear every in-flight RPC — used when the link closes. */
function rejectAllPending(pending: Map<string, PendingEntry>, reason: string): void {
for (const [, entry] of pending) {
@@ -34,7 +30,7 @@ function rejectAllPending(pending: Map<string, PendingEntry>, reason: string): v
/** Register one RPC in `pending` by id, send its request, and reject it on timeout. */
function sendRpc(
ws: any,
socket: WsSocket,
pending: Map<string, PendingEntry>,
id: string,
kind: 'scope' | 'route',
@@ -49,12 +45,12 @@ function sendRpc(
}, timeoutMs);
pending.set(id, { resolve: resolveCall, reject: rejectCall, timer });
ws.send(encode({ type: 'rpc-req', id, kind, name, ctx }));
socket.send(encode({ type: 'rpc-req', id, kind, name, ctx }));
});
}
/** Assemble the client-facing Link once the manifest arrives. */
function buildLink(ws: any, pending: Map<string, PendingEntry>, manifest: Manifest, timeoutMs: number): Link {
function buildLink(socket: WsSocket, pending: Map<string, PendingEntry>, manifest: Manifest, timeoutMs: number): Link {
// ids only need to be unique within this link: `pending` is per-connection, so a
// per-link counter suffices (no module-global sequence, no test-order coupling).
let counter = 0;
@@ -64,10 +60,10 @@ function buildLink(ws: any, pending: Map<string, PendingEntry>, manifest: Manife
rpc(kind, name, ctx) {
const id = String(counter++);
return sendRpc(ws, pending, id, kind, name, ctx, timeoutMs);
return sendRpc(socket, pending, id, kind, name, ctx, timeoutMs);
},
close() {
ws.close();
socket.close();
},
};
}
@@ -91,60 +87,108 @@ function settleRpcResponse(
}
}
/** Open a WebSocket link to a mesh server, handshake with `secret`, and resolve once its manifest arrives. */
export function connectLink(args: { url: string; secret: string; timeoutMs?: number; bus?: Bus }): Promise<Link> {
/** Handle for the in-flight handshake, so the frame loop can settle `connectLink`'s promise. */
interface Handshake {
url: string;
socket: WsSocket;
pending: Map<string, PendingEntry>;
timeoutMs: number;
bus?: Bus;
resolve: (link: Link) => void;
reject: (error: unknown) => void;
onManifest: () => void;
}
/** Settle the handshake from a `manifest` frame: refuse a version mismatch, else build the Link. */
function settleManifest(frame: Extract<Frame, { type: 'manifest' }>, hs: Handshake): void {
if (frame.v !== MESH_PROTOCOL_VERSION) {
hs.socket.close();
hs.reject(
new Error(
`mesh protocol version mismatch at ${hs.url}: teapot speaks v${frame.v}, this teacup speaks v${MESH_PROTOCOL_VERSION}`,
),
);
return;
}
hs.onManifest();
hs.bus?.emit('mesh:connect', { name: hs.url });
hs.resolve(buildLink(hs.socket, hs.pending, { scopes: frame.scopes, routes: frame.routes }, hs.timeoutMs));
}
/** Consume the link's inbound frames until it closes, settling the handshake then each RPC. */
async function readFrames(hs: Handshake): Promise<void> {
for await (const data of hs.socket.inbound) {
let frame: Frame;
try {
frame = decode(String(data));
} catch {
continue; // undecodable frames are ignored
}
if (frame.type === 'manifest') settleManifest(frame, hs);
else if (frame.type === 'rpc-res') settleRpcResponse(hs.pending, frame, hs.bus);
}
}
/**
* Open a WebSocket link to a mesh server, handshake with `secret`, and resolve once its manifest
* arrives. `Ctor` is injectable to exercise both client implementations on a single runtime.
*/
export function connectLink(args: {
url: string;
secret: string;
timeoutMs?: number;
bus?: Bus;
Ctor?: SocketCtor;
}): Promise<Link> {
const timeoutMs = args.timeoutMs ?? 30_000;
const WS = loadWs();
const ws = new WS(args.url);
const { socket, opened } = connectSocket(args.url, args.Ctor ?? undefined);
const pending = new Map<string, PendingEntry>();
let manifest: Manifest | undefined;
let manifest = false;
return new Promise<Link>((resolve, reject) => {
const connectTimer = setTimeout(() => {
ws.close();
socket.close();
reject(new Error(`mesh connect timeout: ${args.url}`));
}, timeoutMs);
ws.on('open', () => ws.send(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: args.secret })));
ws.on('error', (error: unknown) => reject(error));
ws.on('close', () => {
clearTimeout(connectTimer);
args.bus?.emit('mesh:disconnect', { name: args.url });
rejectAllPending(pending, 'mesh link closed');
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') {
const hs: Handshake = {
url: args.url,
socket,
pending,
timeoutMs,
bus: args.bus,
resolve,
reject,
onManifest: () => {
manifest = true;
clearTimeout(connectTimer);
},
};
if (frame.v !== MESH_PROTOCOL_VERSION) {
ws.close();
reject(
new Error(
`mesh protocol version mismatch at ${args.url}: teapot speaks v${frame.v}, this teacup speaks v${MESH_PROTOCOL_VERSION}`,
),
);
return;
}
opened.then(
() => socket.send(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: args.secret })),
(error) => reject(error),
);
manifest = { scopes: frame.scopes, routes: frame.routes };
args.bus?.emit('mesh:connect', { name: args.url });
resolve(buildLink(ws, pending, manifest, timeoutMs));
return;
}
// abort fires on close *and* on error (see eventSocket), covering both paths the raw
// 'close' listener used to: a refused handshake and a dropped link.
socket.abort.addEventListener(
'abort',
() => {
clearTimeout(connectTimer);
args.bus?.emit('mesh:disconnect', { name: args.url });
rejectAllPending(pending, 'mesh link closed');
if (!manifest) reject(new Error(`mesh handshake failed: ${args.url}`));
},
{ once: true },
);
if (frame.type === 'rpc-res') {
settleRpcResponse(pending, frame, args.bus);
}
void readFrames(hs).catch(() => {
/* inbound failed; the abort listener above reports it */
});
});
}
+27 -1
View File
@@ -1,6 +1,7 @@
import { describe, it, expect } from 'vitest';
import { WebSocketServer } from 'ws';
import WS, { WebSocketServer } from 'ws';
import { connectLink } from '../../src/mesh/link';
import { loadWebSocketCtor, type SocketCtor } from '../../src/http/ws-adapter';
import { encode, decode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol';
const V = MESH_PROTOCOL_VERSION;
@@ -53,6 +54,31 @@ function startSkewedTeapot() {
return { url: `ws://127.0.0.1:${port}/__mesh__/control`, close: () => wss.close() };
}
/**
* Both client implementations, exercised on whatever Node runs the suite. `ws` is always in the
* list: it is the Node 18-21 path, and on a modern CI the platform global would otherwise be the
* only one ever covered — the fallback would rot unnoticed until someone ran the declared floor.
*/
const platform = (globalThis as { WebSocket?: SocketCtor }).WebSocket;
const CTORS: [string, SocketCtor][] = [['the ws package (Node < 22 path)', WS as unknown as SocketCtor]];
if (platform) CTORS.push(['the platform global WebSocket', platform]);
describe('WebSocket client implementations', () => {
it.each(CTORS)('handshakes and serves RPC over %s', async (_label, Ctor) => {
const t = startTeapot();
const link = await connectLink({ url: t.url, secret: 'good', Ctor });
expect(link.manifest.scopes).toEqual([{ token: 'auth', scope: 'request' }]);
expect(await link.rpc('scope', 'auth', env)).toEqual({ got: 'auth' });
link.close();
t.close();
});
it('prefers the platform global when it exists, else falls back to the ws package', () => {
expect(loadWebSocketCtor()).toBe(platform ?? (WS as unknown as SocketCtor));
});
});
describe('connectLink', () => {
it('sends its protocol version in the hello', async () => {
const seen: any[] = [];