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

+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 */
});
});
}