test(router): add owner-requested parity cases and a shared-prefix generator

Additions requested in CARD-08 review, captured from ed47836 like the rest of
the corpus and frozen in their own files, so the first capture is untouched.

- Backtracking: a static branch failing one level down, at depth 5 (and a
  param branch at depth 3), and with a constrained param on the fallback.
- Cross-pattern Allow: GET :id plus POST b, with and without DELETE :rest*,
  at matcher level and through app.fetch and Node.
- Encoded slashes in plain and constrained params. A constraint cannot itself
  contain a slash: the pattern splits there and is rejected as malformed.
- Zero-segment catch-alls without an exact sibling, and a root catch-all.
- The mesh HTTP table across a peer's lifetime. It is built once at boot and
  never changes: a peer that leaves keeps its routes (503 on hit, 405 Allow
  unchanged) and a peer that arrives after boot is never spliced in (404).
  CARD-10 can reuse this for its no-rebuild-per-request check.
- router-parity-gen-v2, same seed 10908, forces static, param, constrained
  and catch-all siblings under shared prefixes at depths 1-4. branches.ts
  measures the effect and the result is frozen with the fixture: 71.9% of v2
  requests reach sibling branches and 67.3% backtrack, against 36.5% and
  26.7% for v1. v1 and its fixture are unchanged.

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-10-10 17:27:11 -05:00
1 parent 98ea948ffa
commit a47c6564ab
10 files changed
+11835 -3

No files matched your search

+3 -1
View File
@@ -26,10 +26,12 @@ Nothing can regenerate the baseline by accident:
|---|---|
| `manifest.json` | Existing tests retained unchanged (ROUTER-CORPUS §1), with the verification result at the pinned revision. `manifest.test.ts` fails if a named file or test disappears. |
| `oracle.ts` | Verbatim copy of the pre-radix `matchRoute`, `resolveRoute`, `allowedMethods`, `normalizeRequestPath`, `compilePattern` and `matchWsRoute`. Test-only; `src/` must never import it. |
| `cases.ts`, `generator.ts` | Matcher inputs: 24 hand-picked scenarios (§2), and a fixed-seed generator (`router-parity-gen-v1`, seed `10908`). |
| `cases.ts`, `generator.ts` | Matcher inputs: 24 hand-picked scenarios (§2), 9 owner-requested scenarios (backtracking, cross-pattern `Allow`, encoded slashes, zero-segment catch-alls), and a fixed-seed generator in two versions, both seed `10908`: `router-parity-gen-v1`, and `router-parity-gen-v2`, which forces static/param/constrained/catch-all siblings under shared prefixes. |
| `branches.ts` | Measures the share of generated requests that walk into sibling branches and backtrack; frozen with the v2 fixture. |
| `frozen/matcher-*.json` | Captured matcher outputs: declaration ID, decoded params, `implicitHead`, ordered `Allow`, or the normalization error. The generated file also stores the seed, the generator rules and every generated input. |
| `frozen/app-*.json` | Status, headers, `Allow` and body through `app.fetch` and through a Node socket, including HEAD body suppression. |
| `frozen/ws-*.json` | WS upgrade selection through `app.upgrade` and the Node listener, plus HTTP requests at the WS paths. |
| `frozen/owner-*.json` | Owner additions needing a running app: cross-pattern `Allow` through both adapters, and the mesh HTTP route table across a peer's lifetime (it is built once at boot and never changes — see `owner.test.ts`). |
| `frozen/boot-*.json` | Boot-time rejections: pattern compilation, local ambiguity, mesh splicing. |
| `frozen/golden-*.json` | `graph()`, `explain()`, `openapi({ title: 'Parity', version: '1' })`, and a mesh teacup before and after `ready()`. |
+94
View File
@@ -0,0 +1,94 @@
/**
* Measures how much of a corpus exercises sibling branches, so "the generator covers backtracking"
* is a number rather than a hope. Method-agnostic: a tree is walked by path before a method is
* chosen, so any declaration that shares the walk counts.
*
* - sibling hit: two declarations both match the request's leading segments through a segment
* where their patterns differ — the lookup has two branches to choose between at that point.
* - backtrack: a sibling hit where at least one of those declarations then fails to match the
* whole path — a branch the lookup walks into and has to leave.
*/
import { compilePattern, normalizeRequestPath, type CompiledSegment } from './oracle';
import type { Scenario } from './matcher';
function segmentMatches(segment: CompiledSegment, value: string): boolean {
if (segment.kind === 'static') return segment.value === value;
if (segment.kind === 'catchAll') return true;
const decoded = value.includes('%') ? decodeURIComponent(value) : value;
return !segment.constraint || segment.constraint.test(decoded);
}
/** Leading segments matched, and whether the whole path matched. */
function walk(pattern: string, segs: string[]): { depth: number; full: boolean } {
const { segments } = compilePattern(pattern);
for (let i = 0; i < segments.length; i++) {
if (segments[i].kind === 'catchAll') return { depth: segments.length, full: true };
if (i >= segs.length || !segmentMatches(segments[i], segs[i])) return { depth: i, full: false };
}
return { depth: segments.length, full: segments.length === segs.length };
}
const sameSegment = (a: CompiledSegment, b: CompiledSegment): boolean =>
JSON.stringify({ ...a, constraint: undefined }) === JSON.stringify({ ...b, constraint: undefined });
export interface BranchStats {
requests: number;
validPaths: number;
siblingHits: number;
backtracks: number;
siblingShare: string;
backtrackShare: string;
}
export function branchStats(scenarios: Scenario[]): BranchStats {
let requests = 0;
let validPaths = 0;
let siblingHits = 0;
let backtracks = 0;
for (const scenario of scenarios) {
const patterns = [...new Set(scenario.declarations.map((d) => d.pattern))];
for (const { raw } of scenario.requests) {
requests++;
let path: string;
try {
path = normalizeRequestPath(raw);
} catch {
continue;
}
validPaths++;
const segs = path.split('/').filter(Boolean);
const walks = patterns.map((pattern) => ({ segments: compilePattern(pattern).segments, ...walk(pattern, segs) }));
let sibling = false;
let backtrack = false;
for (let i = 0; i < walks.length; i++) {
for (let j = i + 1; j < walks.length; j++) {
const [a, b] = [walks[i], walks[j]];
const shared = Math.min(a.depth, b.depth, a.segments.length, b.segments.length);
const diverge = Array.from({ length: shared }, (_, d) => d).find(
(d) => !sameSegment(a.segments[d], b.segments[d]),
);
if (diverge === undefined) continue;
sibling = true;
if (!a.full || !b.full) backtrack = true;
}
}
if (sibling) siblingHits++;
if (backtrack) backtracks++;
}
}
const pct = (n: number) => `${((n / requests) * 100).toFixed(1)}%`;
return {
requests,
validPaths,
siblingHits,
backtracks,
siblingShare: pct(siblingHits),
backtrackShare: pct(backtracks),
};
}
+90
View File
@@ -250,3 +250,93 @@ export const HAND_SCENARIOS: Scenario[] = [
get('/v/1/x', '/v/a/x', '/v/1', '/v'),
),
];
/**
* Owner-requested additions (CARD-08 review), frozen separately in `frozen/matcher-owner.json` so the
* first capture stays untouched. Inputs only, like everything above.
*/
export const OWNER_SCENARIOS: Scenario[] = [
scenario(
'O01-backtrack',
'a static branch that fails one level down must fall back to a sibling param branch',
[
['static', 'GET', '/a/b/c'],
['param', 'GET', '/a/:x/d'],
],
get('/a/b/d', '/a/b/c', '/a/z/d', '/a/b/x'),
),
scenario(
'O02-backtrack-deep',
'the static branch fails at depth 5 (and a param branch at depth 3), after walking four or two levels',
[
['static', 'GET', '/p/q/r/s/t'],
['paramDepth2', 'GET', '/p/:x/r/s/u'],
['paramDepth3', 'GET', '/p/q/:y/s/v'],
],
get('/p/q/r/s/u', '/p/q/r/s/t', '/p/z/r/s/u', '/p/q/r/s/v', '/p/q/z/s/v', '/p/q/r/s/w'),
),
scenario(
'O03-backtrack-constrained',
'the fallback branch is a constrained param',
[
['static', 'GET', '/k/1/c'],
['digits', 'GET', '/k/:n(\\d+)/d'],
],
get('/k/1/d', '/k/1/c', '/k/2/d', '/k/x/d'),
),
scenario(
'O04-cross-pattern-allow',
'Allow is the union of methods across different patterns matching the same path',
[
['getParam', 'GET', '/a/:id'],
['postStatic', 'POST', '/a/b'],
],
[
['PUT', '/a/b'],
['OPTIONS', '/a/b'],
['PUT', '/a/x'],
['HEAD', '/a/b'],
['GET', '/a/b'],
['POST', '/a/x'],
],
),
scenario(
'O05-cross-pattern-allow-catch-all',
'the same, with a catch-all contributing a method',
[
['getParam', 'GET', '/a/:id'],
['postStatic', 'POST', '/a/b'],
['deleteRest', 'DELETE', '/a/:rest*'],
],
[
['PUT', '/a/b'],
['OPTIONS', '/a/b'],
['PUT', '/a/x'],
['HEAD', '/a/b'],
['PUT', '/a/x/y'],
['DELETE', '/a'],
],
),
scenario(
'O06-encoded-slash-plain',
'an encoded slash inside one segment, plain param',
[['userId', 'GET', '/users/:id']],
get('/users/a%2Fb', '/users/a%2fb', '/users/%2F', '/users/a/b'),
),
scenario(
'O07-encoded-slash-constrained',
'an encoded slash against a word constraint and a non-space constraint (a / cannot appear inside a constraint: the pattern splits there)',
[
['word', 'GET', '/c/:id(\\w+)'],
['nonSpace', 'GET', '/d/:id(\\S+)'],
],
get('/c/a%2Fb', '/c/ab', '/d/a%2Fb', '/d/a%2fb', '/d/%2F', '/d/a/b'),
),
scenario(
'O08-zero-segment-catch-all',
'a catch-all with no exact sibling route',
[['rest', 'GET', '/files/:rest*']],
[...get('/files', '/files/', '/files/a', '/filesx'), ['HEAD', '/files'], ['OPTIONS', '/files']],
),
scenario('O09-root-catch-all', 'a root catch-all alone', [['rest', 'GET', '/:rest*']], get('/', '/a', '/a/b/')),
];
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,165 @@
{
"revision": "ed47836c9820c47bf4ed5e902d91e019abdb110a",
"data": [
{
"adapter": "fetch",
"method": "PUT",
"path": "/ca/b",
"status": 405,
"allow": "GET, HEAD, POST, OPTIONS",
"body": "{\"error\":\"Method Not Allowed\"}"
},
{
"adapter": "fetch",
"method": "OPTIONS",
"path": "/ca/b",
"status": 204,
"allow": "GET, HEAD, POST, OPTIONS",
"body": ""
},
{
"adapter": "fetch",
"method": "PUT",
"path": "/ca/x",
"status": 405,
"allow": "GET, HEAD, OPTIONS",
"body": "{\"error\":\"Method Not Allowed\"}"
},
{
"adapter": "fetch",
"method": "HEAD",
"path": "/ca/b",
"status": 200,
"allow": null,
"body": ""
},
{
"adapter": "fetch",
"method": "PUT",
"path": "/ca/x/y",
"status": 404,
"allow": null,
"body": "{\"error\":\"Not Found\"}"
},
{
"adapter": "fetch",
"method": "PUT",
"path": "/cb/b",
"status": 405,
"allow": "GET, HEAD, POST, DELETE, OPTIONS",
"body": "{\"error\":\"Method Not Allowed\"}"
},
{
"adapter": "fetch",
"method": "OPTIONS",
"path": "/cb/b",
"status": 204,
"allow": "GET, HEAD, POST, DELETE, OPTIONS",
"body": ""
},
{
"adapter": "fetch",
"method": "PUT",
"path": "/cb/x",
"status": 405,
"allow": "GET, HEAD, DELETE, OPTIONS",
"body": "{\"error\":\"Method Not Allowed\"}"
},
{
"adapter": "fetch",
"method": "HEAD",
"path": "/cb/b",
"status": 200,
"allow": null,
"body": ""
},
{
"adapter": "fetch",
"method": "PUT",
"path": "/cb/x/y",
"status": 405,
"allow": "DELETE, OPTIONS",
"body": "{\"error\":\"Method Not Allowed\"}"
},
{
"adapter": "node",
"method": "PUT",
"path": "/ca/b",
"status": 405,
"allow": "GET, HEAD, POST, OPTIONS",
"body": "{\"error\":\"Method Not Allowed\"}"
},
{
"adapter": "node",
"method": "OPTIONS",
"path": "/ca/b",
"status": 204,
"allow": "GET, HEAD, POST, OPTIONS",
"body": ""
},
{
"adapter": "node",
"method": "PUT",
"path": "/ca/x",
"status": 405,
"allow": "GET, HEAD, OPTIONS",
"body": "{\"error\":\"Method Not Allowed\"}"
},
{
"adapter": "node",
"method": "HEAD",
"path": "/ca/b",
"status": 200,
"allow": null,
"body": ""
},
{
"adapter": "node",
"method": "PUT",
"path": "/ca/x/y",
"status": 404,
"allow": null,
"body": "{\"error\":\"Not Found\"}"
},
{
"adapter": "node",
"method": "PUT",
"path": "/cb/b",
"status": 405,
"allow": "GET, HEAD, POST, DELETE, OPTIONS",
"body": "{\"error\":\"Method Not Allowed\"}"
},
{
"adapter": "node",
"method": "OPTIONS",
"path": "/cb/b",
"status": 204,
"allow": "GET, HEAD, POST, DELETE, OPTIONS",
"body": ""
},
{
"adapter": "node",
"method": "PUT",
"path": "/cb/x",
"status": 405,
"allow": "GET, HEAD, DELETE, OPTIONS",
"body": "{\"error\":\"Method Not Allowed\"}"
},
{
"adapter": "node",
"method": "HEAD",
"path": "/cb/b",
"status": 200,
"allow": null,
"body": ""
},
{
"adapter": "node",
"method": "PUT",
"path": "/cb/x/y",
"status": 405,
"allow": "DELETE, OPTIONS",
"body": "{\"error\":\"Method Not Allowed\"}"
}
]
}
@@ -0,0 +1,133 @@
{
"revision": "ed47836c9820c47bf4ed5e902d91e019abdb110a",
"data": [
{
"phase": "A1 teapot up at boot",
"method": "GET",
"path": "/api/remote/ping",
"status": 200,
"allow": null,
"body": "{\"from\":\"teapot\"}"
},
{
"phase": "A1 teapot up at boot",
"method": "POST",
"path": "/api/remote/ping",
"status": 405,
"allow": "GET, HEAD, OPTIONS",
"body": "{\"error\":\"Method Not Allowed\"}"
},
{
"phase": "A1 teapot up at boot",
"method": "GET",
"path": "/api/local/ok",
"status": 200,
"allow": null,
"body": "{\"from\":\"teacup\"}"
},
{
"phase": "A1 teapot up at boot",
"method": "GET",
"path": "/api/nope",
"status": 404,
"allow": null,
"body": "{\"error\":\"Not Found\"}"
},
{
"phase": "A2 teapot gone after boot",
"method": "GET",
"path": "/api/remote/ping",
"status": 503,
"allow": null,
"body": "{\"error\":\"mesh link to <teapot>/__mesh__/control is down\"}"
},
{
"phase": "A2 teapot gone after boot",
"method": "POST",
"path": "/api/remote/ping",
"status": 405,
"allow": "GET, HEAD, OPTIONS",
"body": "{\"error\":\"Method Not Allowed\"}"
},
{
"phase": "A2 teapot gone after boot",
"method": "GET",
"path": "/api/local/ok",
"status": 200,
"allow": null,
"body": "{\"from\":\"teacup\"}"
},
{
"phase": "A2 teapot gone after boot",
"method": "GET",
"path": "/api/nope",
"status": 404,
"allow": null,
"body": "{\"error\":\"Not Found\"}"
},
{
"phase": "B1 teapot absent at boot",
"method": "GET",
"path": "/api/remote/ping",
"status": 404,
"allow": null,
"body": "{\"error\":\"Not Found\"}"
},
{
"phase": "B1 teapot absent at boot",
"method": "POST",
"path": "/api/remote/ping",
"status": 404,
"allow": null,
"body": "{\"error\":\"Not Found\"}"
},
{
"phase": "B1 teapot absent at boot",
"method": "GET",
"path": "/api/local/ok",
"status": 200,
"allow": null,
"body": "{\"from\":\"teacup\"}"
},
{
"phase": "B1 teapot absent at boot",
"method": "GET",
"path": "/api/nope",
"status": 404,
"allow": null,
"body": "{\"error\":\"Not Found\"}"
},
{
"phase": "B2 teapot up after boot",
"method": "GET",
"path": "/api/remote/ping",
"status": 404,
"allow": null,
"body": "{\"error\":\"Not Found\"}"
},
{
"phase": "B2 teapot up after boot",
"method": "POST",
"path": "/api/remote/ping",
"status": 404,
"allow": null,
"body": "{\"error\":\"Not Found\"}"
},
{
"phase": "B2 teapot up after boot",
"method": "GET",
"path": "/api/local/ok",
"status": 200,
"allow": null,
"body": "{\"from\":\"teacup\"}"
},
{
"phase": "B2 teapot up after boot",
"method": "GET",
"path": "/api/nope",
"status": 404,
"allow": null,
"body": "{\"error\":\"Not Found\"}"
}
]
}
+90
View File
@@ -119,3 +119,93 @@ export function generateScenarios(seed: number = GENERATOR_SEED): Scenario[] {
return { id, note: `generated by ${GENERATOR_VERSION}, seed ${seed}`, declarations, requests };
});
}
/**
* Version 2: the same seed and helpers, plus rules that force shared prefixes, so a meaningful share
* of cases puts static, param, constrained and catch-all siblings under one prefix and makes the
* lookup leave a branch it has already walked into. Frozen in `frozen/matcher-generated-v2.json`;
* v1 above and its frozen file are unchanged.
*/
export const GENERATOR_V2_VERSION = 'router-parity-gen-v2';
export const GENERATOR_V2_RULES = [
'PRNG: mulberry32(seed), fresh for v2; every choice below draws from it in program order.',
'40 scenarios; each has a shared static prefix of 0-3 segments (a|b|c|x), so siblings sit at depth 1-4.',
'Each scenario has 3-6 sibling declarations: prefix + one sibling segment + a tail. The first sibling segment is ' +
'static, the second a plain or constrained param; the rest are static (p=0.35), plain (p=0.25), constrained ' +
'(p=0.25) or a final catch-all (p=0.15). Tails are 0-2 segments, static/plain/constrained, none after a catch-all.',
'Then 0-3 unrelated declarations made by the v1 declaration rule.',
'Methods and transports follow the v1 declaration rule.',
'Requests (12): p=0.5 instantiate a sibling; p=0.25 cross two siblings (prefix and sibling segment of one, tail ' +
'of another) to force a partial match; else prefix + 0-3 pool values. v1 decoration and request methods apply.',
'Unsupported patterns are never produced: every generated pattern must pass compilePattern.',
];
function siblingSegment(rng: Rng, depth: number, index: number): string {
if (index === 0) return pick(rng, STATICS);
if (index === 1) return rng() < 0.5 ? `:p${depth}` : `:p${depth}(${pick(rng, CONSTRAINTS)})`;
const roll = rng();
if (roll < 0.35) return pick(rng, STATICS);
if (roll < 0.6) return `:p${depth}`;
if (roll < 0.85) return `:p${depth}(${pick(rng, CONSTRAINTS)})`;
return `:p${depth}*`;
}
function siblingDeclaration(rng: Rng, id: string, prefix: string[], index: number): Declaration {
const sibling = siblingSegment(rng, prefix.length, index);
const segments = [...prefix, sibling];
if (!sibling.endsWith('*')) {
const tail = int(rng, 0, 2);
for (let t = 0; t < tail; t++) {
const depth = segments.length;
const roll = rng();
segments.push(
roll < 0.5 ? pick(rng, STATICS) : roll < 0.75 ? `:p${depth}` : `:p${depth}(${pick(rng, CONSTRAINTS)})`,
);
}
}
const method = pick(rng, DECL_METHODS);
const transport: Transport = method === 'GET' && rng() >= 0.7 ? pick(rng, STREAMING) : 'buffer';
const pattern = `/${segments.join('/')}`;
compilePattern(pattern);
return { id, method, pattern, transport };
}
function siblingRequest(rng: Rng, prefixLength: number, siblings: Declaration[]): Request {
const roll = rng();
let segments: string[];
if (roll < 0.5) {
segments = instantiate(rng, pick(rng, siblings));
} else if (roll < 0.75) {
const head = instantiate(rng, pick(rng, siblings)).slice(0, prefixLength + 1);
const tail = instantiate(rng, pick(rng, siblings)).slice(prefixLength + 1);
segments = [...head, ...tail];
} else {
const prefix = instantiate(rng, siblings[0]).slice(0, prefixLength);
segments = [...prefix, ...Array.from({ length: int(rng, 0, 3) }, () => pick(rng, VALUES))];
}
return { method: pick(rng, REQUEST_METHODS), raw: decorate(rng, segments) };
}
export function generateScenariosV2(seed: number = GENERATOR_SEED): Scenario[] {
const rng = mulberry32(seed);
return Array.from({ length: 40 }, (_, index): Scenario => {
const id = `S${String(index + 1).padStart(2, '0')}`;
const prefix = Array.from({ length: int(rng, 0, 3) }, () => pick(rng, STATICS));
const siblings = Array.from({ length: int(rng, 3, 6) }, (_, s) =>
siblingDeclaration(rng, `${id}.s${s + 1}`, prefix, s),
);
const unrelated = Array.from({ length: int(rng, 0, 3) }, (_, u) => declaration(rng, `${id}.u${u + 1}`));
const requests = Array.from({ length: 12 }, () => siblingRequest(rng, prefix.length, siblings));
return {
id,
note: `generated by ${GENERATOR_V2_VERSION}, seed ${seed}, shared prefix /${prefix.join('/')}`,
declarations: [...siblings, ...unrelated],
requests,
};
});
}
+58 -2
View File
@@ -13,8 +13,17 @@ 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 } from './cases';
import { generateScenarios, GENERATOR_RULES, GENERATOR_SEED, GENERATOR_VERSION } from './generator';
import { HAND_SCENARIOS, OWNER_SCENARIOS } from './cases';
import { branchStats, type BranchStats } from './branches';
import {
generateScenarios,
generateScenariosV2,
GENERATOR_RULES,
GENERATOR_SEED,
GENERATOR_VERSION,
GENERATOR_V2_RULES,
GENERATOR_V2_VERSION,
} from './generator';
import { frozen, expectFrozenEqual } from './frozen';
const LIVE: MatcherImpl = live;
@@ -81,6 +90,53 @@ describe(`router parity: generated matcher cases (${GENERATOR_VERSION}, seed ${G
}
});
describe('router parity: owner-requested matcher cases', () => {
let expected: Map<string, CapturedScenario>;
beforeAll(async () => {
const data = await frozen('matcher-owner', () => capture(OWNER_SCENARIOS));
expect(data.map((scenario) => scenario.id)).toEqual(OWNER_SCENARIOS.map((scenario) => scenario.id));
expected = new Map(data.map((scenario) => [scenario.id, scenario]));
});
for (const scenario of OWNER_SCENARIOS) {
it(`${scenario.id}: ${scenario.note}`, () => checkScenario(scenario, expected.get(scenario.id)));
}
});
interface GeneratedV2File extends GeneratedFile {
/** Share of generated requests that walk into sibling branches; v1's share is kept for contrast. */
branchStats: { v1: BranchStats; v2: BranchStats };
}
describe(`router parity: generated shared-prefix cases (${GENERATOR_V2_VERSION}, seed ${GENERATOR_SEED})`, () => {
const generated = generateScenariosV2(GENERATOR_SEED);
const stats = () => ({ v1: branchStats(generateScenarios(GENERATOR_SEED)), v2: branchStats(generated) });
let expected: Map<string, CapturedScenario>;
beforeAll(async () => {
const data = await frozen<GeneratedV2File>('matcher-generated-v2', () => ({
generator: GENERATOR_V2_VERSION,
seed: GENERATOR_SEED,
rules: GENERATOR_V2_RULES,
branchStats: stats(),
scenarios: capture(generated),
}));
expect({ generator: data.generator, seed: data.seed, rules: data.rules }).toEqual({
generator: GENERATOR_V2_VERSION,
seed: GENERATOR_SEED,
rules: GENERATOR_V2_RULES,
});
expect(stats()).toEqual(data.branchStats);
expect(data.scenarios.map((scenario) => scenario.id)).toEqual(generated.map((scenario) => scenario.id));
expected = new Map(data.scenarios.map((scenario) => [scenario.id, scenario]));
});
for (const scenario of generated) {
it(`${scenario.id}`, () => checkScenario(scenario, expected.get(scenario.id)));
}
});
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.
+204
View File
@@ -0,0 +1,204 @@
/**
* 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, Post, Delete, Module, param } from '../../src/index';
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<string, string>) {
return { id: 'caGet', p };
}
@Post('/ca/b') caPost() {
return { id: 'caPost' };
}
@Get('/cb/:id') cbGet(@param() p: Record<string, string>) {
return { id: 'cbGet', p };
}
@Post('/cb/b') cbPost() {
return { id: 'cbPost' };
}
@Delete('/cb/:rest*') cbDelete(@param() p: Record<string, string>) {
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<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();
});
}
async function fetchRequest(app: App, method: string, path: string): Promise<Seen> {
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';
@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);
});