Two halves of the same "mesh off Node" gap; they touch the same file and landed
together.
Control channel (Task 6): meshControl existed only inside listen(), passed to
createHttpServer, so a teapot could only export its scopes from Node. app.upgrade
— the path serveDeno/serveBun drive — had never heard of it, which would have left
"mesh on three runtimes" meaning consume-only. It is now built in the boot gate
(it captures the finalized ordered nodes, so it cannot exist before finalize) and
the reserved path is routed from app.upgrade. Task 3 already made handle() take a
neutral WsSocket and upgrade holds one, so this is a direct call, not a second
implementation. handle() returns the connection's lifetime like runWsConnection,
so upgrade awaits it instead of returning while the peer is still talking. An app
with nothing exported refuses the reserved path explicitly rather than falling
through to "no matching ws route".
Link lifecycle (Task 7): links were reaped by server.on('close'), reachable only
through listen(), so a mesh app booted through app.fetch had links and no server
and leaked every teapot connection at `if (!server) return`. close() now closes
them first either way; that aborts each socket, which rejects its in-flight RPCs.
Also fixes a race the new tests exposed: upgrade awaited the boot *before* handing
the socket to a consumer, but `channel` is fan-out, so frames arriving during the
boot were dropped with no subscriber attached. For the control channel that is
`hello` itself — against a teapot with slow providers the handshake would hang
until timeout. Inbound is now subscribed synchronously on entry and the buffered
iterator handed down, closing the same gap for regular @Ws routes.
Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Tasks 6, 7
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
234 lines
8.0 KiB
TypeScript
234 lines
8.0 KiB
TypeScript
import { describe, it, expect } from 'vitest';
|
|
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index';
|
|
import { channel } from '../../src/channel';
|
|
import { encode, decode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol';
|
|
import type { WsSocket, WsRequest } from '../../src/http/ws-core';
|
|
|
|
const SECRET = 's3cr3t';
|
|
|
|
@Provider({ provides: 'config', export: true })
|
|
class Config {
|
|
provide() {
|
|
return { config: { region: 'mx' } };
|
|
}
|
|
}
|
|
@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 {}
|
|
|
|
@Route('/plain')
|
|
class PlainCtl {
|
|
@Get('/ok')
|
|
ok() {
|
|
return { ok: true };
|
|
}
|
|
}
|
|
@Module({ mountpoint: '/', controllers: [PlainCtl] })
|
|
class PlainModule {}
|
|
|
|
const teapotUrl = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`;
|
|
|
|
/** A neutral socket, exactly what serveDeno/serveBun hand to app.upgrade. */
|
|
const fakePeer = () => {
|
|
const inbound = channel<unknown>();
|
|
const ac = new AbortController();
|
|
const sent: any[] = [];
|
|
const closed: { code?: number; reason?: string }[] = [];
|
|
const socket: WsSocket = {
|
|
inbound,
|
|
abort: ac.signal,
|
|
isOpen: true,
|
|
send: (data: string) => {
|
|
sent.push(decode(data));
|
|
},
|
|
close: (code, reason) => {
|
|
closed.push({ code, reason });
|
|
inbound.close();
|
|
ac.abort();
|
|
},
|
|
terminate: () => ac.abort(),
|
|
};
|
|
return { socket, sent, closed, inbound };
|
|
};
|
|
|
|
const controlReq = (): WsRequest => ({ url: '/__mesh__/control', headers: {}, protocol: 'http', ip: '' });
|
|
|
|
/**
|
|
* A mesh teacup driven purely through `app.fetch` — the entry point Deno/Bun/edge use.
|
|
* `listen()` is never called on the teacup, because on those runtimes it cannot be:
|
|
* it builds a Node http.Server.
|
|
*/
|
|
describe('mesh over app.fetch (no listen)', () => {
|
|
it('boots the mesh graph on the first request and resolves remote scopes', async () => {
|
|
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
|
const tServer = await teapot.listen(0);
|
|
const url = teapotUrl((tServer.address() as any).port);
|
|
|
|
const teacup = createApp({
|
|
modules: [TeacupModule],
|
|
experimental: true,
|
|
mesh: { teapots: [{ url, secret: SECRET }] },
|
|
});
|
|
|
|
const res = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } }));
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(await res.json()).toEqual({ config: { region: 'mx' }, auth: { token: 'abc' } });
|
|
|
|
await teacup.close();
|
|
tServer.close();
|
|
});
|
|
|
|
it('boots exactly once across concurrent first requests', async () => {
|
|
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
|
const tServer = await teapot.listen(0);
|
|
const url = teapotUrl((tServer.address() as any).port);
|
|
|
|
let connects = 0;
|
|
const teacup = createApp({
|
|
modules: [TeacupModule],
|
|
experimental: true,
|
|
mesh: { teapots: [{ url, secret: SECRET }] },
|
|
});
|
|
teacup.bus.on('mesh:connect', () => {
|
|
connects += 1;
|
|
});
|
|
|
|
const hit = () => teacup.fetch(new Request('http://x/api/local/who'));
|
|
const all = await Promise.all([hit(), hit(), hit()]);
|
|
|
|
expect(all.map((r) => r.status)).toEqual([200, 200, 200]);
|
|
expect(connects).toBe(1); // the boot gate is memoized: three racing requests splice once
|
|
|
|
await teacup.close();
|
|
tServer.close();
|
|
});
|
|
|
|
it('serves the remote scope in inspect() once a request has booted the graph', async () => {
|
|
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
|
const tServer = await teapot.listen(0);
|
|
const url = teapotUrl((tServer.address() as any).port);
|
|
|
|
const teacup = createApp({
|
|
modules: [TeacupModule],
|
|
experimental: true,
|
|
mesh: { teapots: [{ url, secret: SECRET }] },
|
|
});
|
|
|
|
await teacup.fetch(new Request('http://x/api/local/who'));
|
|
const chain = teacup.inspect('/api/local/who').map((line) => `${line.kind}:${line.name}`);
|
|
|
|
// the remote provider and step spliced into the local route's chain
|
|
expect(chain).toContain('provider:config');
|
|
expect(chain).toContain('step:auth');
|
|
expect(teacup.graph().nodes.some((n) => n.name === 'config')).toBe(true);
|
|
|
|
await teacup.close();
|
|
tServer.close();
|
|
});
|
|
|
|
it('closes the teapot links, even with no server to hang the close off', async () => {
|
|
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
|
const tServer = await teapot.listen(0);
|
|
const url = teapotUrl((tServer.address() as any).port);
|
|
|
|
const teacup = createApp({
|
|
modules: [TeacupModule],
|
|
experimental: true,
|
|
mesh: { teapots: [{ url, secret: SECRET }] },
|
|
});
|
|
const disconnects: string[] = [];
|
|
teacup.bus.on('mesh:disconnect', (p) => disconnects.push(p.name));
|
|
|
|
await teacup.fetch(new Request('http://x/api/local/who'));
|
|
expect(disconnects).toEqual([]);
|
|
|
|
// listen() never ran, so there is no server whose 'close' could reap the links
|
|
await teacup.close();
|
|
await new Promise((r) => setTimeout(r, 50));
|
|
|
|
expect(disconnects).toEqual([url]);
|
|
tServer.close();
|
|
});
|
|
|
|
it('surfaces a failed mesh boot as a request error, not a silent success', async () => {
|
|
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
|
const tServer = await teapot.listen(0);
|
|
const url = teapotUrl((tServer.address() as any).port);
|
|
|
|
const teacup = createApp({
|
|
modules: [TeacupModule],
|
|
experimental: true,
|
|
mesh: { teapots: [{ url, secret: 'WRONG' }], timeoutMs: 800 },
|
|
});
|
|
|
|
await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow();
|
|
|
|
await teacup.close();
|
|
tServer.close();
|
|
});
|
|
});
|
|
|
|
/**
|
|
* A teapot *exporting* over app.upgrade — the path serveDeno/serveBun drive. Without this the
|
|
* control channel only existed on Node's server.on('upgrade'), so a teapot could not run off Node
|
|
* and "mesh on 3 runtimes" would have meant consuming only.
|
|
*/
|
|
describe('mesh control over app.upgrade (no listen)', () => {
|
|
it('serves the handshake to a peer that never touched a Node server', async () => {
|
|
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
|
const peer = fakePeer();
|
|
|
|
void teapot.upgrade(controlReq(), peer.socket);
|
|
peer.inbound.push(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: SECRET }));
|
|
await new Promise((r) => setTimeout(r, 20));
|
|
|
|
expect(peer.sent[0]).toMatchObject({
|
|
type: 'manifest',
|
|
v: MESH_PROTOCOL_VERSION,
|
|
scopes: expect.arrayContaining([{ token: 'config', scope: 'app' }]),
|
|
});
|
|
await teapot.close();
|
|
});
|
|
|
|
it('rejects a bad secret over app.upgrade too', async () => {
|
|
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
|
const peer = fakePeer();
|
|
|
|
void teapot.upgrade(controlReq(), peer.socket);
|
|
peer.inbound.push(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: 'WRONG' }));
|
|
await new Promise((r) => setTimeout(r, 20));
|
|
|
|
expect(peer.sent).toEqual([]);
|
|
expect(peer.closed[0].code).toBe(1008);
|
|
await teapot.close();
|
|
});
|
|
|
|
it('refuses the reserved path explicitly on an app that exports nothing', async () => {
|
|
// a plain, self-contained app: the path is reserved regardless, so say so rather than
|
|
// let it fall through to the generic "no matching ws route"
|
|
const plain = createApp({ modules: [PlainModule] });
|
|
const peer = fakePeer();
|
|
|
|
await plain.upgrade(controlReq(), peer.socket);
|
|
|
|
expect(peer.closed[0].code).toBe(1008);
|
|
expect(peer.closed[0].reason).toMatch(/mesh control channel not enabled/i);
|
|
});
|
|
});
|