test(mesh): prove mesh across Node, Deno and Bun

Every mesh test ran on Node and drove listen(); nothing off Node was covered, so
the cross-runtime work was implemented but not demonstrated. vitest excludes
test/{deno,bun,edge}, so `npm test` would not have noticed either way.

Adds, in the real runtimes:
- Deno and Bun, teapot and teacup, served through serveDeno/serveBun. Bun is not a
  duplicate of Deno: its socket events land on a server-level handler, so the
  control channel reaches app.upgrade by a different path.
- The interop matrix, in separate processes: a Deno teacup consuming a Node teapot
  and a Node teacup consuming a Deno teapot. Each asserts the `runtime` field the
  *other* process produces, so a peer answering from the wrong side fails the test.
  Node serves and connects with the `ws` package; Deno uses its global WebSocket —
  same-runtime tests could never have exercised that pairing.
- A hand-rolled v999 peer, refused across the boundary with both versions named.

Verified these tests fail for the right reason: breaking the control-channel
routing in app.upgrade fails the Node-teacup-consumes-Deno-teapot case and only
that case.

test:deno needs --allow-run/--allow-env to spawn the Node peer. The peer lives in
test/interop rather than test/deno because tsconfig excludes test/deno, so tsx
would not apply experimentalDecorators there; vitest ignores it as a non-.test.ts.

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-07-15 15:30:43 -05:00
1 parent 0c68cba532
commit a74417494f
5 files changed
+434 -1

No files matched your search

+1 -1
View File
@@ -79,7 +79,7 @@
"build": "tsup",
"test": "vitest run",
"test:dev": "vitest",
"test:deno": "deno test --allow-net --allow-read --no-check test/deno/",
"test:deno": "deno test --allow-net --allow-read --allow-run --allow-env --no-check test/deno/",
"test:bun": "bun test test/bun/",
"test:edge": "tsx test/edge/run.ts",
"typecheck": "tsc --noEmit -p tsconfig.json",
+84
View File
@@ -0,0 +1,84 @@
// Real Bun integration test for mesh: a teapot exporting its scopes and a teacup consuming
// them, both under the actual Bun runtime, driven entirely through serveBun.
//
// Bun's ws lifecycle differs from Deno's — its socket events land on a server-level handler
// rather than the socket — so the control channel reaching app.upgrade here is a distinct
// path from the Deno test, not a duplicate of it.
//
// Run with: npm run test:bun
import 'reflect-metadata';
import { test, expect } from 'bun:test';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts';
import { serveBun } from '../../src/bun.ts';
const SECRET = 's3cr3t';
@Provider({ provides: 'config', export: true })
class Config {
provide() {
return { config: { region: 'mx', runtime: 'bun' } };
}
}
@Step({ provides: 'auth', needs: [], export: true })
class Auth {
run(ctx: any) {
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
}
}
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
class TeapotModule {}
@Route('/local')
class LocalCtl {
@Get('/who')
who(@needs('config') config: any, @needs('auth') auth: any) {
return { config, auth };
}
}
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {}
const controlUrl = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`;
test('mesh on Bun: teacup resolves a Bun teapot through the graph', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = serveBun(teapot, { port: 0 });
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(tServer.port), secret: SECRET }] },
});
const cServer = serveBun(teacup, { port: 0 });
try {
const res = await fetch(`http://127.0.0.1:${cServer.port}/api/local/who`, { headers: { 'x-token': 'abc' } });
expect(res.status).toBe(200);
expect(await res.json()).toEqual({
config: { region: 'mx', runtime: 'bun' },
auth: { token: 'abc' },
});
} finally {
await teacup.close();
cServer.stop(true);
tServer.stop(true);
}
});
test('mesh on Bun: a teapot refuses a bad secret over its control channel', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = serveBun(teapot, { port: 0 });
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(tServer.port), secret: 'WRONG' }], timeoutMs: 1000 },
});
try {
await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow(/mesh/);
} finally {
await teacup.close();
tServer.stop(true);
}
});
+170
View File
@@ -0,0 +1,170 @@
// Cross-runtime mesh: a Node peer and a Deno peer, in separate processes, talking over the
// wire protocol. This is the test the whole cross-runtime effort exists for.
//
// Deno<->Deno and Node<->Node passing prove each runtime works with itself; neither proves a
// Node teapot can serve a Deno teacup, which is the shape mesh actually deploys in once it
// spans runtimes. The two sides use genuinely different code here — Node serves through the
// `ws` package (WebSocketServer + nodeSocket) and connects with it too; Deno uses its global
// WebSocket both ways — so only a real cross-process run exercises the pairing.
//
// Run with: npm run test:deno (needs --allow-run to spawn the Node peer)
import 'npm:reflect-metadata';
import { assertEquals, assertStringIncludes } from 'jsr:@std/assert';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts';
const SECRET = 's3cr3t';
const NODE_PEER = 'test/interop/_node-peer.ts';
@Provider({ provides: 'config', export: true })
class Config {
provide() {
return { config: { region: 'mx', runtime: 'deno' } };
}
}
@Step({ provides: 'auth', needs: [], export: true })
class Auth {
run(ctx: any) {
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
}
}
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
class TeapotModule {}
@Route('/local')
class LocalCtl {
@Get('/who')
who(@needs('config') config: any, @needs('auth') auth: any) {
return { config, auth };
}
}
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {}
const controlUrl = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`;
/** Spawns the Node peer under tsx, streaming its stdout lines. */
function spawnNodePeer(args: string[]) {
const child = new Deno.Command('npx', {
args: ['tsx', NODE_PEER, ...args],
env: { ...Deno.env.toObject(), MESH_SECRET: SECRET },
stdout: 'piped',
stderr: 'piped',
}).spawn();
return child;
}
/** Reads stdout until a JSON line parses, or the peer dies / we run out of patience. */
async function firstJsonLine(child: Deno.ChildProcess, timeoutMs = 30_000): Promise<any> {
const reader = child.stdout.getReader();
const decoder = new TextDecoder();
let buffer = '';
const deadline = Date.now() + timeoutMs;
try {
while (Date.now() < deadline) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
for (const line of buffer.split('\n')) {
const trimmed = line.trim();
if (!trimmed.startsWith('{')) continue;
try {
return JSON.parse(trimmed);
} catch {
/* partial line; keep reading */
}
}
}
} finally {
reader.releaseLock();
}
throw new Error(`node peer produced no JSON line within ${timeoutMs}ms`);
}
async function kill(child: Deno.ChildProcess): Promise<void> {
try {
child.kill('SIGKILL');
} catch {
/* already gone */
}
await child.status;
try {
await child.stdout.cancel();
await child.stderr.cancel();
} catch {
/* already released */
}
}
Deno.test('interop: a Deno teacup consumes a Node teapot', async () => {
const node = spawnNodePeer(['teapot']);
const { port } = await firstJsonLine(node);
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(port), secret: SECRET }], timeoutMs: 5000 },
});
try {
const res = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } }));
assertEquals(res.status, 200);
// the config came from the Node process: proof the scope crossed the runtime boundary
assertEquals(await res.json(), {
config: { region: 'mx', runtime: 'node' },
auth: { token: 'abc' },
});
} finally {
await teacup.close();
await kill(node);
}
});
Deno.test('interop: a Node teacup consumes a Deno teapot', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
let port = 0;
const { serveDeno } = await import('../../src/deno.ts');
const server = serveDeno(teapot, {
port: 0,
onListen: (addr) => {
port = addr.port;
},
});
await new Promise((resolve) => setTimeout(resolve, 50));
const node = spawnNodePeer(['teacup', controlUrl(port)]);
try {
const result = await firstJsonLine(node);
assertEquals(result.ok, true);
// the Node peer resolved a scope served by Deno's app.upgrade control channel
assertEquals(result.body.config, { region: 'mx', runtime: 'deno' });
assertEquals(result.body.auth, { token: 'abc' });
} finally {
await kill(node);
await server.shutdown();
}
});
Deno.test('interop: a version-skewed peer is refused across runtimes', async () => {
const node = spawnNodePeer(['teapot']);
const { port } = await firstJsonLine(node);
try {
// hand-rolled peer speaking a future protocol: the teapot must refuse before the secret
const ws = new WebSocket(controlUrl(port));
const closed = await new Promise<{ code: number; reason: string }>((resolve, reject) => {
ws.onopen = () => ws.send(JSON.stringify({ type: 'hello', v: 999, secret: SECRET }));
ws.onclose = (e) => resolve({ code: e.code, reason: e.reason });
ws.onerror = () => reject(new Error('ws error'));
});
assertEquals(closed.code, 1008);
assertStringIncludes(closed.reason, '999');
} finally {
await kill(node);
}
});
+108
View File
@@ -0,0 +1,108 @@
// Real Deno integration test for mesh: a teapot exporting its scopes and a teacup consuming
// them, both under the actual Deno runtime, driven entirely through serveDeno.
//
// This is the test that makes "mesh runs off Node" a fact rather than an intention. It covers,
// in one round-trip, everything that used to be Node-only:
// - the teacup's WebSocket client is Deno's global (no `ws` package here at all)
// - the teapot's control channel is served via app.upgrade (Deno has no server.on('upgrade'))
// - the graph boots on the first request; `listen()` is never called and cannot be
// - node:crypto's timingSafeEqual + Buffer resolve under Deno's node-compat
//
// Run with: npm run test:deno
// `--no-check`: see the note in ws.test.ts — Deno type-checks the whole reachable graph,
// including Node-only modules this test never executes. tsc covers those.
import 'npm:reflect-metadata';
import { assertEquals, assertStringIncludes } from 'jsr:@std/assert';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts';
const SECRET = 's3cr3t';
@Provider({ provides: 'config', export: true })
class Config {
provide() {
return { config: { region: 'mx', runtime: 'deno' } };
}
}
@Step({ provides: 'auth', needs: [], export: true })
class Auth {
run(ctx: any) {
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
}
}
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
class TeapotModule {}
@Route('/local')
class LocalCtl {
@Get('/who')
who(@needs('config') config: any, @needs('auth') auth: any) {
return { config, auth };
}
}
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {}
/** Starts an app on Deno and resolves once its port is known. */
async function serve(app: ReturnType<typeof createApp>) {
let port = 0;
const server = serveDeno(app, {
port: 0,
onListen: (addr) => {
port = addr.port;
},
});
await new Promise((resolve) => setTimeout(resolve, 50));
return { server, port };
}
const controlUrl = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`;
Deno.test('mesh on Deno: teacup resolves a Deno teapot through the graph', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const t = await serve(teapot);
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(t.port), secret: SECRET }] },
});
const c = await serve(teacup);
try {
const res = await fetch(`http://127.0.0.1:${c.port}/api/local/who`, { headers: { 'x-token': 'abc' } });
assertEquals(res.status, 200);
assertEquals(await res.json(), {
config: { region: 'mx', runtime: 'deno' },
auth: { token: 'abc' },
});
} finally {
await teacup.close();
await c.server.shutdown();
await t.server.shutdown();
}
});
Deno.test('mesh on Deno: a teapot refuses a bad secret over its control channel', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const t = await serve(teapot);
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(t.port), secret: 'WRONG' }], timeoutMs: 1000 },
});
try {
let message = '';
try {
await teacup.fetch(new Request('http://x/api/local/who'));
} catch (err) {
message = String((err as Error).message);
}
assertStringIncludes(message, 'mesh');
} finally {
await teacup.close();
await t.server.shutdown();
}
});
+71
View File
@@ -0,0 +1,71 @@
// Not a test — a Node-hosted mesh peer, spawned by mesh-interop.test.ts. Deno's test runner
// only discovers *.test.ts, so this file is ignored by `deno test`.
//
// It exists so the interop claim is tested rather than reasoned about: Deno<->Deno passing
// says nothing about a Node teapot serving a Deno teacup, which is the actual deployment
// shape once mesh spans runtimes. Node's side uses the `ws` package (WebSocketServer +
// nodeSocket); Deno's uses its global WebSocket. Only a real cross-process run exercises both.
//
// Modes:
// teapot -> exports scopes, prints {"port":N}, serves until killed
// teacup <controlUrl> -> consumes the remote scopes, prints {"ok":true,"body":{...}}
import 'reflect-metadata';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index';
const SECRET = process.env.MESH_SECRET ?? 's3cr3t';
@Provider({ provides: 'config', export: true })
class Config {
provide() {
return { config: { region: 'mx', runtime: 'node' } };
}
}
@Step({ provides: 'auth', needs: [], export: true })
class Auth {
run(ctx: any) {
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
}
}
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
class TeapotModule {}
@Route('/local')
class LocalCtl {
@Get('/who')
who(@needs('config') config: any, @needs('auth') auth: any) {
return { config, auth };
}
}
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {}
const [mode, controlUrl] = process.argv.slice(2);
async function main(): Promise<void> {
if (mode === 'teapot') {
const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const server = await app.listen(0);
console.log(JSON.stringify({ port: (server.address() as { port: number }).port }));
return; // stays alive on the open server until the parent kills it
}
if (mode === 'teacup') {
const app = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl, secret: SECRET }], timeoutMs: 5000 },
});
const res = await app.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } }));
const body = await res.json();
console.log(JSON.stringify({ ok: res.status === 200, body }));
await app.close();
process.exit(0);
}
throw new Error(`unknown mode: ${mode}`);
}
main().catch((err: unknown) => {
console.log(JSON.stringify({ ok: false, error: String((err as Error).message) }));
process.exit(1);
});