Files
core/test/router-parity/owner.test.ts
T
chrnx 684795a2de test(router): run the parity differential on Deno, Bun and workerd
The matcher comparison does not depend on the runtime, so it should run on every
runtime core supports. Only the Node suite ran it before.

The comparison and the app.fetch fixtures move into differential.ts and
app-fixture.ts, which use neither vitest nor a file API. Each runtime passes in
a loader for the frozen JSON. The vitest files use the same modules, plus a
Node check that the neutral runners report no mismatch, so the two paths cannot
drift.

- Deno and Bun: test/{deno,bun}/router-parity.test.ts run all 1158 frozen
  matcher cases (hand-picked, owner, generated v1 and v2, WS) through the oracle
  and the live router, plus the 55 app.fetch cases.
- workerd: test/edge/parity-worker.ts bundles the frozen JSON and runs the
  same checks; test/edge/run.ts adds the phase after its existing assertions.

The Node-socket, WS-upgrade, boot and mesh captures stay Node-only: they need
http.request, the ws client, or a mesh peer on a port.

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 17:38:36 -05:00

162 lines
5.7 KiB
TypeScript

/**
* Owner-requested additions (CARD-08 review) that need a running app: cross-pattern `Allow` through
* both adapters, and the HTTP route table across a mesh peer's lifetime.
*/
import 'reflect-metadata';
import http from 'http';
import net from 'net';
import type { AddressInfo } from 'net';
import { describe, it, afterAll, beforeAll } from 'vitest';
import { createApp, Route, Get, Module } from '../../src/index';
import { ALLOW_REQUESTS, CrossAllowModule, fetchRequest, type Seen } from './app-fixture';
import type { App } from '../../src/app/types';
import type { Logger } from '../../src/logger';
import { frozen, expectFrozenEqual } from './frozen';
function nodeRequest(port: number, method: string, path: string): Promise<Seen> {
return new Promise((resolve, reject) => {
const req = http.request({ host: '127.0.0.1', port, method, path, agent: false }, (res) => {
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk) => (body += chunk));
res.on('end', () =>
resolve({ method, path, status: res.statusCode ?? 0, allow: (res.headers.allow as string) ?? null, body }),
);
});
req.on('error', reject);
req.end();
});
}
// ── mesh: the HTTP route table across a peer's lifetime ─────────────────────────────────────────
const SECRET = 'parity-secret';
@Route('/remote')
class RemoteCtl {
@Get('/ping', { export: true }) ping() {
return { from: 'teapot' };
}
}
@Module({ mountpoint: '/api', controllers: [RemoteCtl] })
class TeapotModule {}
@Route('/local')
class LocalCtl {
@Get('/ok') ok() {
return { from: 'teacup' };
}
}
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {}
const quiet: Logger = { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} };
/** A port nothing is listening on, that a teapot can take later. */
async function freePort(): Promise<number> {
const server = net.createServer();
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const { port } = server.address() as AddressInfo;
await new Promise<void>((resolve) => server.close(() => resolve()));
return port;
}
// Same probes at every phase: the remote hit, its method miss, a local hit and a path miss.
const PROBES: Array<[string, string]> = [
['GET', '/api/remote/ping'],
['POST', '/api/remote/ping'],
['GET', '/api/local/ok'],
['GET', '/api/nope'],
];
async function probe(app: App, phase: string) {
const out = [];
for (const [method, path] of PROBES) {
const { status, allow, body } = await fetchRequest(app, method, path);
// The teapot's ephemeral port appears in the 503 body; the port is not routing behaviour.
out.push({ phase, method, path, status, allow, body: body.replace(/ws:\/\/127\.0\.0\.1:\d+/g, '<teapot>') });
}
return out;
}
const teacupFor = (port: number) =>
createApp({
modules: [TeacupModule],
experimental: true,
logger: quiet,
mesh: {
teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: SECRET }],
bootTimeoutMs: 300,
timeoutMs: 500,
reconnect: false,
},
});
/**
* Two lifetimes. A: the teapot is up at boot, then goes away. B: the teapot is absent at boot and
* comes up afterwards. The current code builds the HTTP table once, at boot, and never changes it:
* routes spliced at boot stay in the table after their peer leaves, and a peer that arrives late
* is never spliced in. CARD-10 can reuse this to assert the index is not rebuilt per request.
*/
async function meshLifetimes() {
const results = [];
const portA = await freePort();
const teapotA = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
await teapotA.listen(portA);
const teacupA = teacupFor(portA);
try {
results.push(...(await probe(teacupA, 'A1 teapot up at boot')));
await teapotA.close();
results.push(...(await probe(teacupA, 'A2 teapot gone after boot')));
} finally {
await teacupA.close();
}
const portB = await freePort();
const teacupB = teacupFor(portB);
const teapotB = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
try {
results.push(...(await probe(teacupB, 'B1 teapot absent at boot')));
await teapotB.listen(portB);
results.push(...(await probe(teacupB, 'B2 teapot up after boot')));
} finally {
await teacupB.close();
await teapotB.close();
}
return results;
}
describe('router parity: owner-requested application cases', () => {
let fetchApp: App;
let nodeApp: App;
let port: number;
beforeAll(async () => {
fetchApp = createApp({ modules: [CrossAllowModule] });
nodeApp = createApp({ modules: [CrossAllowModule] });
port = ((await nodeApp.listen(0)).address() as AddressInfo).port;
});
afterAll(() => nodeApp.close());
it('cross-pattern Allow through app.fetch and Node equals the frozen capture', async () => {
const run = async () => {
const out: Array<Seen & { adapter: string }> = [];
for (const [method, path] of ALLOW_REQUESTS)
out.push({ adapter: 'fetch', ...(await fetchRequest(fetchApp, method, path)) });
for (const [method, path] of ALLOW_REQUESTS)
out.push({ adapter: 'node', ...(await nodeRequest(port, method, path)) });
return out;
};
const expected = await frozen('owner-app-allow', run);
expectFrozenEqual(await run(), expected, 'cross-pattern Allow');
});
it('the mesh HTTP route table across a peer lifetime equals the frozen capture', async () => {
const expected = await frozen('owner-mesh-lifetime', meshLifetimes);
expectFrozenEqual(await meshLifetimes(), expected, 'mesh lifetime');
}, 30_000);
});