From 684795a2de47355e5f5c187b409fc9d1f12e8d80 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 10 Oct 2026 17:38:36 -0500 Subject: [PATCH] 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 --- .gitignore | 1 + test/bun/router-parity.test.ts | 22 +++ test/deno/router-parity.test.ts | 23 +++ test/edge/parity-worker.ts | 32 ++++ test/edge/run.ts | 65 +++++++- test/router-parity/README.md | 15 ++ test/router-parity/app-fixture.ts | 241 +++++++++++++++++++++++++++++ test/router-parity/app.test.ts | 186 +++------------------- test/router-parity/differential.ts | 124 +++++++++++++++ test/router-parity/matcher.test.ts | 44 ++---- test/router-parity/owner.test.ts | 47 +----- 11 files changed, 553 insertions(+), 247 deletions(-) create mode 100644 test/bun/router-parity.test.ts create mode 100644 test/deno/router-parity.test.ts create mode 100644 test/edge/parity-worker.ts create mode 100644 test/router-parity/app-fixture.ts create mode 100644 test/router-parity/differential.ts diff --git a/.gitignore b/.gitignore index ce6697a..edf3388 100644 --- a/.gitignore +++ b/.gitignore @@ -21,6 +21,7 @@ coverage/ # Edge (Miniflare) test bundle artifact test/edge/_worker.mjs +test/edge/_parity-worker.mjs # Bun writes this on `bun install`, and nothing here consumes it: `npm run test:bun` runs # `bun test` against the node_modules npm installed, which package-lock.json already pins. diff --git a/test/bun/router-parity.test.ts b/test/bun/router-parity.test.ts new file mode 100644 index 0000000..28b5e1c --- /dev/null +++ b/test/bun/router-parity.test.ts @@ -0,0 +1,22 @@ +// The frozen router-parity differential under the real Bun runtime: every matcher case (hand-picked, +// owner, generated v1/v2, WS) through the oracle and the live router, and the app.fetch cases, all +// against the same frozen files the Node suite uses. See test/router-parity/README.md. +// +// Run with: npm run test:bun +import 'reflect-metadata'; +import { test, expect } from 'bun:test'; +import { runDifferential } from '../router-parity/differential.ts'; +import { runAppDifferential } from '../router-parity/app-fixture.ts'; + +const load = (name: string) => Bun.file(new URL(`../router-parity/frozen/${name}.json`, import.meta.url)).json(); + +test('router parity on Bun: frozen matcher differential, oracle and live', async () => { + const report = await runDifferential(load); + expect(report.mismatches).toEqual([]); + expect(report.sets.length).toBe(5); +}); + +test('router parity on Bun: app.fetch cases', async () => { + const report = await runAppDifferential(load); + expect(report.mismatches).toEqual([]); +}); diff --git a/test/deno/router-parity.test.ts b/test/deno/router-parity.test.ts new file mode 100644 index 0000000..17e5ca3 --- /dev/null +++ b/test/deno/router-parity.test.ts @@ -0,0 +1,23 @@ +// The frozen router-parity differential under the real Deno runtime: every matcher case (hand-picked, +// owner, generated v1/v2, WS) through the oracle and the live router, and the app.fetch cases, all +// against the same frozen files the Node suite uses. See test/router-parity/README.md. +// +// Run with: npm run test:deno +import 'npm:reflect-metadata'; +import { assertEquals } from 'jsr:@std/assert'; +import { runDifferential } from '../router-parity/differential.ts'; +import { runAppDifferential } from '../router-parity/app-fixture.ts'; + +const load = async (name: string) => + JSON.parse(await Deno.readTextFile(new URL(`../router-parity/frozen/${name}.json`, import.meta.url))); + +Deno.test('router parity on Deno: frozen matcher differential, oracle and live', async () => { + const report = await runDifferential(load); + assertEquals(report.mismatches, []); + assertEquals(report.sets.length, 5); +}); + +Deno.test('router parity on Deno: app.fetch cases', async () => { + const report = await runAppDifferential(load); + assertEquals(report.mismatches, []); +}); diff --git a/test/edge/parity-worker.ts b/test/edge/parity-worker.ts new file mode 100644 index 0000000..68b82dc --- /dev/null +++ b/test/edge/parity-worker.ts @@ -0,0 +1,32 @@ +// Worker entry that runs the frozen router-parity differential inside workerd: every matcher case +// through the oracle and the live router, and the app.fetch cases, against the same frozen files the +// Node suite uses. The frozen JSON is bundled in, since a worker has no file system. Driven by +// test/edge/run.ts; see test/router-parity/README.md. +import { runDifferential } from '../router-parity/differential'; +import { runAppDifferential } from '../router-parity/app-fixture'; +import matcherHand from '../router-parity/frozen/matcher-hand.json'; +import matcherOwner from '../router-parity/frozen/matcher-owner.json'; +import matcherGenerated from '../router-parity/frozen/matcher-generated.json'; +import matcherGeneratedV2 from '../router-parity/frozen/matcher-generated-v2.json'; +import matcherWs from '../router-parity/frozen/matcher-ws.json'; +import appFetch from '../router-parity/frozen/app-fetch.json'; +import ownerAppAllow from '../router-parity/frozen/owner-app-allow.json'; + +const FROZEN: Record = { + 'matcher-hand': matcherHand, + 'matcher-owner': matcherOwner, + 'matcher-generated': matcherGenerated, + 'matcher-generated-v2': matcherGeneratedV2, + 'matcher-ws': matcherWs, + 'app-fetch': appFetch, + 'owner-app-allow': ownerAppAllow, +}; + +export default { + fetch: async (): Promise => { + const load = (name: string) => FROZEN[name]; + const matcher = await runDifferential(load); + const app = await runAppDifferential(load); + return Response.json({ matcher, app }); + }, +}; diff --git a/test/edge/run.ts b/test/edge/run.ts index 681857c..8a523e6 100644 --- a/test/edge/run.ts +++ b/test/edge/run.ts @@ -118,7 +118,9 @@ async function main() { const bad = badRes.webSocket; assert.ok(bad, 'expected a client webSocket on the 101 response'); const closed = new Promise<{ code: number; reason: string }>((resolve) => - bad.addEventListener('close', (e: { code: number; reason: string }) => resolve({ code: e.code, reason: e.reason })), + bad.addEventListener('close', (e: { code: number; reason: string }) => + resolve({ code: e.code, reason: e.reason }), + ), ); bad.accept(); assert.deepEqual(await closed, { code: 1008, reason: 'invalid request path' }); @@ -142,6 +144,57 @@ async function main() { } } +const PARITY_BUNDLE = 'test/edge/_parity-worker.mjs'; + +/** + * The frozen router-parity differential inside workerd (test/router-parity/README.md). Same bundling + * as the main worker; the worker runs every case itself and answers with its mismatch report. + */ +async function parity() { + await build({ + entryPoints: ['test/edge/parity-worker.ts'], + bundle: true, + format: 'esm', + outfile: PARITY_BUNDLE, + platform: 'browser', + target: 'esnext', + external: ['node:*', 'http', 'https'], + alias: { + crypto: 'node:crypto', + stream: 'node:stream', + zlib: 'node:zlib', + buffer: 'node:buffer', + events: 'node:events', + net: 'node:net', + tls: 'node:tls', + util: 'node:util', + }, + }); + + const mf = new Miniflare({ + modules: true, + scriptPath: PARITY_BUNDLE, + compatibilityDate: '2024-11-01', + compatibilityFlags: ['nodejs_compat'], + }); + + try { + const res = await mf.dispatchFetch('http://localhost/'); + const report = (await res.json()) as { + matcher: { sets: Array<{ name: string; requests: number }>; mismatches: string[] }; + app: { requests: number; mismatches: string[] }; + }; + assert.deepEqual(report.matcher.mismatches, [], 'matcher differential mismatches under workerd'); + assert.deepEqual(report.app.mismatches, [], 'app.fetch parity mismatches under workerd'); + const requests = report.matcher.sets.reduce((sum, set) => sum + set.requests, 0); + console.log( + `edge (workerd): router parity — ${requests} matcher cases + ${report.app.requests} app.fetch cases — PASS`, + ); + } finally { + await mf.dispose(); + } +} + /** Opens a ws on `url`, sends `frames`, and resolves with the replies and the close (or none within `ms`). */ async function exchange(mf: Miniflare, url: string, frames: string[], ms = 1000) { const res = await mf.dispatchFetch(url, { headers: { Upgrade: 'websocket' } }); @@ -164,7 +217,9 @@ async function exchange(mf: Miniflare, url: string, frames: string[], ms = 1000) return result; } -main().catch((err) => { - console.error(err); - process.exit(1); -}); +main() + .then(parity) + .catch((err) => { + console.error(err); + process.exit(1); + }); diff --git a/test/router-parity/README.md b/test/router-parity/README.md index 86fae1e..281394b 100644 --- a/test/router-parity/README.md +++ b/test/router-parity/README.md @@ -49,4 +49,19 @@ Application-level, WS, boot and introspection files are compared against the liv because there is no second implementation of `app.fetch` to diff against; the frozen capture plays the oracle's role. +### On every runtime + +`differential.ts` and `app-fixture.ts` hold the same comparison with no vitest and no file API, so +it runs unchanged on Deno (`test/deno/router-parity.test.ts`), Bun (`test/bun/router-parity.test.ts`) +and workerd (`test/edge/parity-worker.ts`, driven by `test/edge/run.ts`). Each runtime runs every frozen +matcher case through both the oracle and the live router, plus the `app.fetch` cases from +`app-fetch.json` and `owner-app-allow.json`. The Node-socket, WS-upgrade, boot and mesh files stay +Node-only: they need `http.request`, the `ws` client, or a mesh peer listening on a port. + +### Mutation check + +`npm run parity:mutants` (not part of `npm test`) applies targeted mutants modelling likely radix +bugs to a temporary copy of `src/`, runs this suite against each, and reports which were killed. +`src/` itself is never modified. + The performance half of the baseline is in `bench/lookup.ts` and `bench/baseline/router-ed47836/`. diff --git a/test/router-parity/app-fixture.ts b/test/router-parity/app-fixture.ts new file mode 100644 index 0000000..d5e2a71 --- /dev/null +++ b/test/router-parity/app-fixture.ts @@ -0,0 +1,241 @@ +/** + * The application-level fetch fixtures, free of vitest and of any runtime API, so the same app and + * requests run through `app.fetch` on Node, Deno, Bun and workerd. `app.test.ts` and + * `owner.test.ts` use them with the frozen files; the runtime runners call {@link runAppDifferential}. + */ +import 'reflect-metadata'; +import { createApp, Route, Get, Head, Post, Put, Patch, Delete, Options, Sse, Module, param } from '../../src/index'; +import type { App } from '../../src/app/types'; +import type { FrozenLoader } from './differential'; + +const reply = (id: string, params: Record) => ({ id, params }); + +// Ordered on purpose: the overlapping declarations are registered least-specific first, so a +// lookup that fell back to registration order would answer differently from one that ranks. +@Route('/') +class ParityHttp { + @Get('/a/:rest*') aRest(@param() p: Record) { + return reply('aRest', p); + } + @Get('/a/:id') aId(@param() p: Record) { + return reply('aId', p); + } + @Get('/a/b') aB(@param() p: Record) { + return reply('aB', p); + } + @Get('/users/:value') usersValue(@param() p: Record) { + return reply('usersValue', p); + } + @Get('/users/:id(\\d+)') usersId(@param() p: Record) { + return reply('usersId', p); + } + @Get('/n/:num(\\d+)') nNum(@param() p: Record) { + return reply('nNum', p); + } + @Get('/n/:code([0-9a-f]+)') nCode(@param() p: Record) { + return reply('nCode', p); + } + @Get('/files') files(@param() p: Record) { + return reply('files', p); + } + @Get('/files/:rest*') filesRest(@param() p: Record) { + return reply('filesRest', p); + } + @Get('/m') mGet(@param() p: Record) { + return reply('mGet', p); + } + @Post('/m') mPost(@param() p: Record) { + return reply('mPost', p); + } + @Get('/h') hGet(@param() p: Record) { + return reply('hGet', p); + } + @Head('/h') hHead(@param() p: Record) { + return reply('hHead', p); + } + @Sse('/stream') stream() { + return (async function* () { + yield { id: 'stream' }; + })(); + } + @Sse('/s/live') sLive() { + return (async function* () { + yield { id: 'sLive' }; + })(); + } + @Get('/s/:id') sId(@param() p: Record) { + return reply('sId', p); + } + @Get('/Case') caseUpper(@param() p: Record) { + return reply('caseUpper', p); + } + @Get('/u/:name') uName(@param() p: Record) { + return reply('uName', p); + } + @Get('/admin') admin(@param() p: Record) { + return reply('admin', p); + } + @Get('/public/:file') publicFile(@param() p: Record) { + return reply('publicFile', p); + } + @Delete('/r') rDelete(@param() p: Record) { + return reply('rDelete', p); + } + @Patch('/r') rPatch(@param() p: Record) { + return reply('rPatch', p); + } + @Options('/r') rOptions(@param() p: Record) { + return reply('rOptions', p); + } + @Put('/r') rPut(@param() p: Record) { + return reply('rPut', p); + } + @Get('/') root(@param() p: Record) { + return reply('root', p); + } +} + +@Module({ mountpoint: '/', controllers: [ParityHttp] }) +export class ParityHttpModule {} + +export type Req = [method: string, raw: string]; + +export const REQUESTS: Req[] = [ + ['GET', '/a/b'], + ['GET', '/a/x'], + ['GET', '/a/x/y'], + ['GET', '/a'], + ['GET', '/users/42'], + ['GET', '/users/alice'], + ['GET', '/users/a%20b'], + ['GET', '/n/42'], + ['GET', '/n/ff'], + ['GET', '/files'], + ['GET', '/files/'], + ['GET', '/files/a%2Fb'], + ['GET', '/m'], + ['HEAD', '/m'], + ['OPTIONS', '/m'], + ['PUT', '/m'], + ['DELETE', '/m'], + ['POST', '/m'], + ['GET', '/h'], + ['HEAD', '/h'], + ['GET', '/stream'], + ['HEAD', '/stream'], + ['OPTIONS', '/stream'], + ['HEAD', '/s/live'], + ['HEAD', '/s/x'], + ['GET', '/absent'], + ['HEAD', '/absent'], + ['OPTIONS', '/absent'], + ['GET', '/users/%E0%A4%A'], + ['HEAD', '/users/%E0%A4%A'], + ['GET', '/a//b'], + ['GET', '/Case'], + ['GET', '/case'], + ['GET', '/caf%C3%A9'], + ['GET', '/u/caf%C3%A9'], + ['GET', '/public/../admin'], + ['GET', '/public/%2e%2e/admin'], + ['GET', '/public/..%2fadmin'], + ['GET', '/admin/'], + ['OPTIONS', '/r'], + ['HEAD', '/r'], + ['GET', '/r'], + ['PURGE', '/r'], // TRACE is a forbidden method for `new Request` + ['GET', '/'], + ['GET', '/?q=1'], +]; + +/** Headers that vary per run or per connection rather than per route decision. */ +const VOLATILE = new Set(['date', 'connection', 'keep-alive', 'x-request-id']); + +export function stableHeaders(entries: Iterable<[string, string]>): Record { + const out: Record = {}; + for (const [name, value] of [...entries].sort(([a], [b]) => a.localeCompare(b))) + if (!VOLATILE.has(name)) out[name] = value; + return out; +} + +export interface Observed { + method: string; + raw: string; + status: number; + headers: Record; + body: string; +} + +export async function viaFetch(app: App, [method, raw]: Req): Promise { + // `new Request` applies the URL parser first — exactly what Deno, Bun and workerd do. + const res = await app.fetch(new Request(`http://parity.test${raw}`, { method })); + return { method, raw, status: res.status, headers: stableHeaders(res.headers), body: await res.text() }; +} + +// `/ca` is GET :id + POST b; `/cb` adds DELETE :rest*. Two prefixes because one app cannot hold both +// variants at the same path. +@Route('/') +class CrossAllow { + @Get('/ca/:id') caGet(@param() p: Record) { + return { id: 'caGet', p }; + } + @Post('/ca/b') caPost() { + return { id: 'caPost' }; + } + @Get('/cb/:id') cbGet(@param() p: Record) { + return { id: 'cbGet', p }; + } + @Post('/cb/b') cbPost() { + return { id: 'cbPost' }; + } + @Delete('/cb/:rest*') cbDelete(@param() p: Record) { + return { id: 'cbDelete', p }; + } +} +@Module({ mountpoint: '/', controllers: [CrossAllow] }) +export class CrossAllowModule {} + +export const ALLOW_REQUESTS: Array<[string, string]> = ['/ca', '/cb'].flatMap((base): Array<[string, string]> => [ + ['PUT', `${base}/b`], + ['OPTIONS', `${base}/b`], + ['PUT', `${base}/x`], + ['HEAD', `${base}/b`], + ['PUT', `${base}/x/y`], +]); + +export interface Seen { + method: string; + path: string; + status: number; + allow: string | null; + body: string; +} + +export async function fetchRequest(app: App, method: string, path: string): Promise { + const res = await app.fetch(new Request(`http://parity.test${path}`, { method })); + return { method, path, status: res.status, allow: res.headers.get('allow'), body: await res.text() }; +} + +/** + * Runs the frozen `app.fetch` cases — `app-fetch.json` and the fetch rows of `owner-app-allow.json` + * — on whatever runtime calls it, and returns every mismatch. + */ +export async function runAppDifferential(load: FrozenLoader): Promise<{ requests: number; mismatches: string[] }> { + const mismatches: string[] = []; + const parity = createApp({ modules: [ParityHttpModule] }); + const appFetch = ((await load('app-fetch')) as { data: Observed[] }).data; + for (const [index, req] of REQUESTS.entries()) { + const seen = await viaFetch(parity, req); + if (JSON.stringify(seen) !== JSON.stringify(appFetch[index])) mismatches.push(`app-fetch ${req[0]} ${req[1]}`); + } + + const cross = createApp({ modules: [CrossAllowModule] }); + const allow = ((await load('owner-app-allow')) as { data: Array }).data; + const fetchRows = allow.filter((row) => row.adapter === 'fetch'); + for (const [index, [method, path]] of ALLOW_REQUESTS.entries()) { + const seen = { adapter: 'fetch', ...(await fetchRequest(cross, method, path)) }; + if (JSON.stringify(seen) !== JSON.stringify(fetchRows[index])) mismatches.push(`owner-app-allow ${method} ${path}`); + } + + return { requests: REQUESTS.length + ALLOW_REQUESTS.length, mismatches }; +} diff --git a/test/router-parity/app.test.ts b/test/router-parity/app.test.ts index 000dbd3..bdfe60a 100644 --- a/test/router-parity/app.test.ts +++ b/test/router-parity/app.test.ts @@ -4,178 +4,24 @@ * cannot prove these: the 404/405/OPTIONS decisions, the 400 for a bad path and the HEAD body rule * live in `src/http/core.ts`, around the matcher. */ -import 'reflect-metadata'; import http from 'http'; import type { AddressInfo } from 'net'; -import { describe, it, beforeAll, afterAll } from 'vitest'; -import { createApp, Route, Get, Head, Post, Put, Patch, Delete, Options, Sse, Module, param } from '../../src/index'; +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { createApp } from '../../src/index'; +import { readFileSync } from 'fs'; +import { join } from 'path'; +import { + ParityHttpModule, + REQUESTS, + runAppDifferential, + stableHeaders, + viaFetch, + type Observed, + type Req, +} from './app-fixture'; import type { App } from '../../src/app/types'; import { frozen, expectFrozenEqual } from './frozen'; -const reply = (id: string, params: Record) => ({ id, params }); - -// Ordered on purpose: the overlapping declarations are registered least-specific first, so a -// lookup that fell back to registration order would answer differently from one that ranks. -@Route('/') -class ParityHttp { - @Get('/a/:rest*') aRest(@param() p: Record) { - return reply('aRest', p); - } - @Get('/a/:id') aId(@param() p: Record) { - return reply('aId', p); - } - @Get('/a/b') aB(@param() p: Record) { - return reply('aB', p); - } - @Get('/users/:value') usersValue(@param() p: Record) { - return reply('usersValue', p); - } - @Get('/users/:id(\\d+)') usersId(@param() p: Record) { - return reply('usersId', p); - } - @Get('/n/:num(\\d+)') nNum(@param() p: Record) { - return reply('nNum', p); - } - @Get('/n/:code([0-9a-f]+)') nCode(@param() p: Record) { - return reply('nCode', p); - } - @Get('/files') files(@param() p: Record) { - return reply('files', p); - } - @Get('/files/:rest*') filesRest(@param() p: Record) { - return reply('filesRest', p); - } - @Get('/m') mGet(@param() p: Record) { - return reply('mGet', p); - } - @Post('/m') mPost(@param() p: Record) { - return reply('mPost', p); - } - @Get('/h') hGet(@param() p: Record) { - return reply('hGet', p); - } - @Head('/h') hHead(@param() p: Record) { - return reply('hHead', p); - } - @Sse('/stream') stream() { - return (async function* () { - yield { id: 'stream' }; - })(); - } - @Sse('/s/live') sLive() { - return (async function* () { - yield { id: 'sLive' }; - })(); - } - @Get('/s/:id') sId(@param() p: Record) { - return reply('sId', p); - } - @Get('/Case') caseUpper(@param() p: Record) { - return reply('caseUpper', p); - } - @Get('/u/:name') uName(@param() p: Record) { - return reply('uName', p); - } - @Get('/admin') admin(@param() p: Record) { - return reply('admin', p); - } - @Get('/public/:file') publicFile(@param() p: Record) { - return reply('publicFile', p); - } - @Delete('/r') rDelete(@param() p: Record) { - return reply('rDelete', p); - } - @Patch('/r') rPatch(@param() p: Record) { - return reply('rPatch', p); - } - @Options('/r') rOptions(@param() p: Record) { - return reply('rOptions', p); - } - @Put('/r') rPut(@param() p: Record) { - return reply('rPut', p); - } - @Get('/') root(@param() p: Record) { - return reply('root', p); - } -} - -@Module({ mountpoint: '/', controllers: [ParityHttp] }) -class ParityHttpModule {} - -type Req = [method: string, raw: string]; - -const REQUESTS: Req[] = [ - ['GET', '/a/b'], - ['GET', '/a/x'], - ['GET', '/a/x/y'], - ['GET', '/a'], - ['GET', '/users/42'], - ['GET', '/users/alice'], - ['GET', '/users/a%20b'], - ['GET', '/n/42'], - ['GET', '/n/ff'], - ['GET', '/files'], - ['GET', '/files/'], - ['GET', '/files/a%2Fb'], - ['GET', '/m'], - ['HEAD', '/m'], - ['OPTIONS', '/m'], - ['PUT', '/m'], - ['DELETE', '/m'], - ['POST', '/m'], - ['GET', '/h'], - ['HEAD', '/h'], - ['GET', '/stream'], - ['HEAD', '/stream'], - ['OPTIONS', '/stream'], - ['HEAD', '/s/live'], - ['HEAD', '/s/x'], - ['GET', '/absent'], - ['HEAD', '/absent'], - ['OPTIONS', '/absent'], - ['GET', '/users/%E0%A4%A'], - ['HEAD', '/users/%E0%A4%A'], - ['GET', '/a//b'], - ['GET', '/Case'], - ['GET', '/case'], - ['GET', '/caf%C3%A9'], - ['GET', '/u/caf%C3%A9'], - ['GET', '/public/../admin'], - ['GET', '/public/%2e%2e/admin'], - ['GET', '/public/..%2fadmin'], - ['GET', '/admin/'], - ['OPTIONS', '/r'], - ['HEAD', '/r'], - ['GET', '/r'], - ['PURGE', '/r'], // TRACE is a forbidden method for `new Request` - ['GET', '/'], - ['GET', '/?q=1'], -]; - -/** Headers that vary per run or per connection rather than per route decision. */ -const VOLATILE = new Set(['date', 'connection', 'keep-alive', 'x-request-id']); - -function stableHeaders(entries: Iterable<[string, string]>): Record { - const out: Record = {}; - for (const [name, value] of [...entries].sort(([a], [b]) => a.localeCompare(b))) - if (!VOLATILE.has(name)) out[name] = value; - return out; -} - -interface Observed { - method: string; - raw: string; - status: number; - headers: Record; - body: string; -} - -async function viaFetch(app: App, [method, raw]: Req): Promise { - // `new Request` applies the URL parser first — exactly what Deno, Bun and workerd do. - const res = await app.fetch(new Request(`http://parity.test${raw}`, { method })); - return { method, raw, status: res.status, headers: stableHeaders(res.headers), body: await res.text() }; -} - function viaNode(port: number, [method, raw]: Req): Promise { // `http.request` sends the path bytes as given, so the server sees the raw target. return new Promise((resolve, reject) => { @@ -231,4 +77,10 @@ describe('router parity: application-level HTTP outcomes', () => { const expected = await frozen('app-node', run); expectFrozenEqual(await run(), expected, 'node listener'); }); + + it('the runtime-neutral app differential (the one Deno, Bun and workerd run) reports no mismatch', async () => { + const dir = join(__dirname, 'frozen'); + const report = await runAppDifferential((name) => JSON.parse(readFileSync(join(dir, `${name}.json`), 'utf8'))); + expect(report.mismatches).toEqual([]); + }); }); diff --git a/test/router-parity/differential.ts b/test/router-parity/differential.ts new file mode 100644 index 0000000..07aa004 --- /dev/null +++ b/test/router-parity/differential.ts @@ -0,0 +1,124 @@ +/** + * The frozen matcher differential, free of vitest and of any runtime's file API, so the same + * comparison runs on Node (vitest), Deno, Bun and workerd. Each runtime passes a loader that + * returns a frozen file's parsed JSON. + * + * It compares exactly what `matcher.test.ts` compares — regenerated inputs, oracle outputs and live + * outputs against the frozen capture, key and array order included — and returns mismatches instead + * of throwing, so a runner can report them all. + */ +import * as live from '../../src/http/router'; +import { matchWsRoute as liveMatchWsRoute } from '../../src/http/ws-core'; +import type { WsRouteDef } from '../../src/http/types'; +import * as oracle from './oracle'; +import { runScenario, type MatcherImpl, type Outcome, type Scenario } from './matcher'; +import { HAND_SCENARIOS, OWNER_SCENARIOS } from './cases'; +import { generateScenarios, generateScenariosV2, GENERATOR_SEED } from './generator'; + +export type FrozenLoader = (name: string) => unknown | Promise; + +interface CapturedScenario extends Scenario { + outcomes: Outcome[]; +} + +// ── WebSocket matcher cases (first registered wins) ───────────────────────────────────────────── + +type WsDecl = WsRouteDef & { id: string }; +export type WsMatcher = ( + routes: WsRouteDef[], + path: string, +) => { def: WsRouteDef; params: Record | undefined } | undefined; + +const ws = (id: string, pattern: string): WsDecl => ({ id, pattern, open: async () => (async function* () {})() }); +const overlap = [ws('param', '/ws/:id'), ws('static', '/ws/static'), ws('rest', '/ws/:rest*')]; +const WS_SCENARIOS = [ + { id: 'W01-overlap', routes: overlap }, + { id: 'W02-overlap-reversed', routes: [...overlap].reverse() }, + { id: 'W03-catch-all-first', routes: [ws('rest', '/w/:rest*'), ws('exact', '/w')] }, +]; +// Fed already normalized, as both upgrade adapters do since #117. +const WS_PATHS = ['/ws/static', '/ws/x', '/ws/a%20b', '/ws', '/ws/x/y', '/w', '/w/a%2Fb/c', '/nope']; + +export function runWsMatcher(matchWs: WsMatcher) { + return WS_SCENARIOS.map(({ id, routes }) => ({ + id, + declarations: routes.map((route) => ({ id: route.id, pattern: route.pattern })), + outcomes: WS_PATHS.map((path) => { + const hit = matchWs(routes, path); + return { path, route: hit ? { id: (hit.def as WsDecl).id, params: hit.params } : null }; + }), + })); +} + +export const LIVE_WS_MATCHER: WsMatcher = liveMatchWsRoute; +export const ORACLE_WS_MATCHER: WsMatcher = oracle.matchWsRoute; + +// ── the comparison ────────────────────────────────────────────────────────────────────────────── + +const same = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b); +const plain = (value: unknown): unknown => JSON.parse(JSON.stringify(value)); + +export interface DifferentialReport { + sets: Array<{ name: string; scenarios: number; requests: number }>; + mismatches: string[]; +} + +const SETS: Array<{ name: string; scenarios: () => Scenario[]; inFile: (data: any) => CapturedScenario[] }> = [ + { name: 'matcher-hand', scenarios: () => HAND_SCENARIOS, inFile: (data) => data }, + { name: 'matcher-owner', scenarios: () => OWNER_SCENARIOS, inFile: (data) => data }, + { name: 'matcher-generated', scenarios: () => generateScenarios(GENERATOR_SEED), inFile: (data) => data.scenarios }, + { + name: 'matcher-generated-v2', + scenarios: () => generateScenariosV2(GENERATOR_SEED), + inFile: (data) => data.scenarios, + }, +]; + +function compareSet(name: string, scenarios: Scenario[], expected: CapturedScenario[], mismatches: string[]): number { + const byId = new Map(expected.map((scenario) => [scenario.id, scenario])); + if ( + !same( + expected.map((s) => s.id), + scenarios.map((s) => s.id), + ) + ) + mismatches.push(`${name}: scenario ids differ from the frozen file`); + + let requests = 0; + for (const scenario of scenarios) { + const frozen = byId.get(scenario.id); + if (!frozen) continue; + const { outcomes, ...inputs } = frozen; + requests += scenario.requests.length; + if (!same(plain(scenario), inputs)) mismatches.push(`${name} ${scenario.id}: inputs`); + const impls: Array<[string, MatcherImpl]> = [ + ['oracle', oracle], + ['live', live], + ]; + for (const [label, impl] of impls) + if (!same(plain(runScenario(impl, scenario)), outcomes)) mismatches.push(`${name} ${scenario.id}: ${label}`); + } + return requests; +} + +export async function runDifferential(load: FrozenLoader): Promise { + const mismatches: string[] = []; + const sets: DifferentialReport['sets'] = []; + + for (const set of SETS) { + const scenarios = set.scenarios(); + const file = (await load(set.name)) as { data: unknown }; + const requests = compareSet(set.name, scenarios, set.inFile(file.data), mismatches); + sets.push({ name: set.name, scenarios: scenarios.length, requests }); + } + + const wsFile = (await load('matcher-ws')) as { data: unknown }; + for (const [label, matcher] of [ + ['oracle', ORACLE_WS_MATCHER], + ['live', LIVE_WS_MATCHER], + ] as const) + if (!same(plain(runWsMatcher(matcher)), wsFile.data)) mismatches.push(`matcher-ws: ${label}`); + sets.push({ name: 'matcher-ws', scenarios: WS_SCENARIOS.length, requests: WS_SCENARIOS.length * WS_PATHS.length }); + + return { sets, mismatches }; +} diff --git a/test/router-parity/matcher.test.ts b/test/router-parity/matcher.test.ts index 18d0df6..613b68b 100644 --- a/test/router-parity/matcher.test.ts +++ b/test/router-parity/matcher.test.ts @@ -7,10 +7,10 @@ * for a radix index behind the same exports, the same test compares oracle against radix with no * edit here. */ +import { readFileSync } from 'fs'; +import { join } from 'path'; import { describe, it, expect, beforeAll } from 'vitest'; import * as live from '../../src/http/router'; -import { matchWsRoute as liveMatchWsRoute } from '../../src/http/ws-core'; -import type { WsRouteDef } from '../../src/http/types'; import * as oracle from './oracle'; import { runScenario, type MatcherImpl, type Outcome, type Scenario } from './matcher'; import { HAND_SCENARIOS, OWNER_SCENARIOS } from './cases'; @@ -25,6 +25,7 @@ import { GENERATOR_V2_VERSION, } from './generator'; import { frozen, expectFrozenEqual } from './frozen'; +import { runDifferential, runWsMatcher, LIVE_WS_MATCHER, ORACLE_WS_MATCHER } from './differential'; const LIVE: MatcherImpl = live; const ORACLE: MatcherImpl = oracle; @@ -139,34 +140,17 @@ describe(`router parity: generated shared-prefix cases (${GENERATOR_V2_VERSION}, describe('router parity: WebSocket matcher (first registered wins)', () => { // WS selection is a separate contract from HTTP: no specificity ranking, registration order only. - // Paths are fed already normalized, as both upgrade adapters do since #117. - type WsDecl = WsRouteDef & { id: string }; - type WsMatcher = ( - routes: WsRouteDef[], - path: string, - ) => { def: WsRouteDef; params: Record | undefined } | undefined; - const ws = (id: string, pattern: string): WsDecl => ({ id, pattern, open: async () => (async function* () {})() }); - const overlap = [ws('param', '/ws/:id'), ws('static', '/ws/static'), ws('rest', '/ws/:rest*')]; - const scenarios = [ - { id: 'W01-overlap', routes: overlap }, - { id: 'W02-overlap-reversed', routes: [...overlap].reverse() }, - { id: 'W03-catch-all-first', routes: [ws('rest', '/w/:rest*'), ws('exact', '/w')] }, - ]; - const paths = ['/ws/static', '/ws/x', '/ws/a%20b', '/ws', '/ws/x/y', '/w', '/w/a%2Fb/c', '/nope']; - - const run = (matchWs: WsMatcher) => - scenarios.map(({ id, routes }) => ({ - id, - declarations: routes.map((route) => ({ id: route.id, pattern: route.pattern })), - outcomes: paths.map((path) => { - const hit = matchWs(routes, path); - return { path, route: hit ? { id: (hit.def as WsDecl).id, params: hit.params } : null }; - }), - })); - it('oracle and live matchWsRoute equal the frozen capture', async () => { - const expected = await frozen('matcher-ws', () => run(liveMatchWsRoute)); - expectFrozenEqual(run(oracle.matchWsRoute), expected, 'ws oracle'); - expectFrozenEqual(run(liveMatchWsRoute), expected, 'ws live'); + const expected = await frozen('matcher-ws', () => runWsMatcher(LIVE_WS_MATCHER)); + expectFrozenEqual(runWsMatcher(ORACLE_WS_MATCHER), expected, 'ws oracle'); + expectFrozenEqual(runWsMatcher(LIVE_WS_MATCHER), expected, 'ws live'); + }); +}); + +describe('router parity: runtime-neutral differential (the one Deno, Bun and workerd run)', () => { + it('reports no mismatch on Node', async () => { + const dir = join(__dirname, 'frozen'); + const report = await runDifferential((name) => JSON.parse(readFileSync(join(dir, `${name}.json`), 'utf8'))); + expect(report.mismatches).toEqual([]); }); }); diff --git a/test/router-parity/owner.test.ts b/test/router-parity/owner.test.ts index 57e8be7..16c30ec 100644 --- a/test/router-parity/owner.test.ts +++ b/test/router-parity/owner.test.ts @@ -7,50 +7,12 @@ import http from 'http'; import net from 'net'; import type { AddressInfo } from 'net'; import { describe, it, afterAll, beforeAll } from 'vitest'; -import { createApp, Route, Get, Post, Delete, Module, param } from '../../src/index'; +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'; -// `/ca` is GET :id + POST b; `/cb` adds DELETE :rest*. Two prefixes because one app cannot hold both -// variants at the same path. -@Route('/') -class CrossAllow { - @Get('/ca/:id') caGet(@param() p: Record) { - return { id: 'caGet', p }; - } - @Post('/ca/b') caPost() { - return { id: 'caPost' }; - } - @Get('/cb/:id') cbGet(@param() p: Record) { - return { id: 'cbGet', p }; - } - @Post('/cb/b') cbPost() { - return { id: 'cbPost' }; - } - @Delete('/cb/:rest*') cbDelete(@param() p: Record) { - return { id: 'cbDelete', p }; - } -} -@Module({ mountpoint: '/', controllers: [CrossAllow] }) -class CrossAllowModule {} - -const ALLOW_REQUESTS: Array<[string, string]> = ['/ca', '/cb'].flatMap((base): Array<[string, string]> => [ - ['PUT', `${base}/b`], - ['OPTIONS', `${base}/b`], - ['PUT', `${base}/x`], - ['HEAD', `${base}/b`], - ['PUT', `${base}/x/y`], -]); - -interface Seen { - method: string; - path: string; - status: number; - allow: string | null; - body: string; -} - function nodeRequest(port: number, method: string, path: string): Promise { return new Promise((resolve, reject) => { const req = http.request({ host: '127.0.0.1', port, method, path, agent: false }, (res) => { @@ -66,11 +28,6 @@ function nodeRequest(port: number, method: string, path: string): Promise }); } -async function fetchRequest(app: App, method: string, path: string): Promise { - const res = await app.fetch(new Request(`http://parity.test${path}`, { method })); - return { method, path, status: res.status, allow: res.headers.get('allow'), body: await res.text() }; -} - // ── mesh: the HTTP route table across a peer's lifetime ───────────────────────────────────────── const SECRET = 'parity-secret';