Route matching scanned every method-matching route on every request and ranked the
candidates as it went, calling `moreSpecific` — two `compilePattern` lookups each — per
candidate. Both the scan and the ranking scale with the size of the route table, and the
answer they compute cannot change between requests: the table is assembled once, after the
graph is prepared, and handed to the adapter unchanged.
So the ranking moves to where the table is built. Routes are compiled, bucketed by method
and sorted most-specific-first, and matching walks until the first match and returns it.
`sort` is stable, so patterns of equal specificity keep registration order — which is what
the old scan produced by refusing to replace its best on a tie.
Measured on a request to a parameterised route registered last, against the same tree
without these changes, medians of five and seven rounds:
6 routes no change (every row overlaps)
50 routes +3.3%, +3.5% across two runs
200 routes +14.9%, +12.0% — twelve rounds, not one crossing sample
The shape is the point rather than any single number: the saving is proportional to how
many candidates a request walks past, so it is invisible on a small table by construction.
That is also why it went unnoticed. The benchmark had no route-table-width dimension until
this commit added one, so every matcher change measured as noise no matter how real.
Two smaller savings on the same path. `decodeSegment` now skips `decodeURIComponent` when
the segment holds no `%`, the same gate `normalizeRequestPath` already applies to the whole
path for the same reason. And decoding memoizes per request rather than per candidate: a
scan reaching the same parameter position on several routes used to decode the same string
once per route, and position is all decoding depends on.
`allStatic` is deleted. It short-circuited the scan on an all-literal match, which sorting
subsumes — such a pattern now sorts first and wins by position.
The index is keyed by the identity of the route array, so it is built once and collected
with the table it describes. A table assembled fresh — mesh splicing a teapot's exports in
at boot — is a different array and gets its own index, so no caller has to invalidate
anything.
`matchRoute precedence` already covered the ordering this rewrite had to preserve, and it
passes unchanged. Two cases were missing and are added: that equal specificity keeps
registration order, which is the property the stable sort now carries, and that a parameter
decodes to the same value however many candidates the scan walks. Both pass against the
previous implementation too — they describe behaviour that already existed, which is what
makes them evidence the rewrite preserved it rather than evidence of the change.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
446 lines
18 KiB
TypeScript
446 lines
18 KiB
TypeScript
import type { RouteDef, MatchedRoute } from './types';
|
|
|
|
export type CompiledSegment =
|
|
| { kind: 'static'; value: string }
|
|
| { kind: 'param'; name: string; constraint?: RegExp; constraintSource?: string }
|
|
| { kind: 'catchAll'; name: string };
|
|
|
|
/** Parsed route pattern reused by matching, specificity, ambiguity checks, and OpenAPI projection. */
|
|
export interface CompiledPattern {
|
|
source: string;
|
|
normalized: string;
|
|
shape: string;
|
|
segments: CompiledSegment[];
|
|
kinds: number[];
|
|
catchAll: boolean;
|
|
}
|
|
|
|
const compiledCache = new Map<string, CompiledPattern>();
|
|
const PARAM_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
const MAX_CONSTRAINT_LENGTH = 128;
|
|
|
|
/** Request-path syntax error. Adapters translate this to the standard 400 response envelope. */
|
|
export class InvalidRequestPathError extends Error {
|
|
constructor(message: string) {
|
|
super(message);
|
|
this.name = 'InvalidRequestPathError';
|
|
}
|
|
}
|
|
|
|
interface ConstraintToken {
|
|
length: number;
|
|
unbounded: boolean;
|
|
separator: boolean;
|
|
}
|
|
|
|
/** Reads one atom plus its optional quantifier from the deliberately small safe-regex subset. */
|
|
function readConstraintToken(source: string): ConstraintToken | undefined {
|
|
const atom = /^(?:\\[dDsSwW]|\\[.\-_/]|[A-Za-z0-9_.-]|\[(?:\\.|[^\]\\])+\])/u.exec(source)?.[0];
|
|
if (!atom) return undefined;
|
|
|
|
const rest = source.slice(atom.length);
|
|
const quantifier = /^(?:[+*?]|\{\d+(?:,\d*)?\})/u.exec(rest)?.[0] ?? '';
|
|
if (quantifier.startsWith('{')) assertBoundedQuantifier(quantifier);
|
|
|
|
return {
|
|
length: atom.length + quantifier.length,
|
|
unbounded: quantifier === '+' || quantifier === '*' || quantifier.endsWith(',}'),
|
|
separator: quantifier === '' && /^(?:\\[.\-_/]|[._-])$/u.test(atom),
|
|
};
|
|
}
|
|
|
|
/** Rejects nonsensical or excessively large counted quantifiers before RegExp compilation. */
|
|
function assertBoundedQuantifier(quantifier: string): void {
|
|
const [minText, maxText] = quantifier.slice(1, -1).split(',');
|
|
const min = Number(minText);
|
|
const max = maxText === undefined || maxText === '' ? min : Number(maxText);
|
|
if (min > max || max > 2048) throw new Error(`unsafe route constraint: invalid quantifier '${quantifier}'`);
|
|
}
|
|
|
|
/** Accepts only a linear, group-free regex subset to keep attacker-controlled segments ReDoS-safe. */
|
|
function assertSafeConstraint(source: string): void {
|
|
if (!source || source.length > MAX_CONSTRAINT_LENGTH)
|
|
throw new Error('unsafe route constraint: expression must contain 1-128 characters');
|
|
|
|
let offset = 0;
|
|
let previousUnbounded = false;
|
|
|
|
while (offset < source.length) {
|
|
const token = readConstraintToken(source.slice(offset));
|
|
if (!token) throw new Error(`unsafe route constraint: unsupported expression '${source}'`);
|
|
if (previousUnbounded && token.unbounded)
|
|
throw new Error(`unsafe route constraint: adjacent unbounded quantifiers in '${source}'`);
|
|
previousUnbounded = token.separator ? false : token.unbounded;
|
|
offset += token.length;
|
|
}
|
|
}
|
|
|
|
function assertParamName(name: string, pattern: string): void {
|
|
if (!PARAM_NAME.test(name)) throw new Error(`invalid route pattern '${pattern}': invalid parameter name '${name}'`);
|
|
}
|
|
|
|
function compileParam(segment: string, pattern: string): Extract<CompiledSegment, { kind: 'param' }> {
|
|
const constraintStart = segment.indexOf('(');
|
|
|
|
if (constraintStart < 0) {
|
|
const name = segment.slice(1);
|
|
assertParamName(name, pattern);
|
|
return { kind: 'param', name };
|
|
}
|
|
|
|
if (!segment.endsWith(')')) throw new Error(`invalid route pattern '${pattern}': malformed constraint`);
|
|
const name = segment.slice(1, constraintStart);
|
|
const constraintSource = segment.slice(constraintStart + 1, -1);
|
|
assertParamName(name, pattern);
|
|
assertSafeConstraint(constraintSource);
|
|
return {
|
|
kind: 'param',
|
|
name,
|
|
constraintSource,
|
|
constraint: new RegExp(`^(?:${constraintSource})$`, 'u'),
|
|
};
|
|
}
|
|
|
|
function compileSegments(pattern: string, rawSegments: string[]): CompiledSegment[] {
|
|
const names = new Set<string>();
|
|
const compiled: CompiledSegment[] = [];
|
|
|
|
for (let index = 0; index < rawSegments.length; index++) {
|
|
const raw = rawSegments[index];
|
|
let segment: CompiledSegment;
|
|
|
|
if (raw.startsWith(':') && raw.endsWith('*')) {
|
|
const name = raw.slice(1, -1);
|
|
assertParamName(name, pattern);
|
|
if (index !== rawSegments.length - 1)
|
|
throw new Error(`invalid route pattern '${pattern}': catch-all must be the final segment`);
|
|
segment = { kind: 'catchAll', name };
|
|
} else if (raw.startsWith(':')) {
|
|
segment = compileParam(raw, pattern);
|
|
} else {
|
|
segment = { kind: 'static', value: raw };
|
|
}
|
|
|
|
if (segment.kind !== 'static') {
|
|
if (names.has(segment.name))
|
|
throw new Error(`invalid route pattern '${pattern}': duplicate parameter '${segment.name}'`);
|
|
names.add(segment.name);
|
|
}
|
|
|
|
compiled.push(segment);
|
|
}
|
|
|
|
return compiled;
|
|
}
|
|
|
|
function segmentShape(segment: CompiledSegment): string {
|
|
if (segment.kind === 'static') return `s:${segment.value}`;
|
|
if (segment.kind === 'catchAll') return 'c';
|
|
return segment.constraintSource ? `r:${segment.constraintSource}` : 'p';
|
|
}
|
|
|
|
/** Compiles and validates one route pattern. Results are cached by source string. */
|
|
export function compilePattern(pattern: string): CompiledPattern {
|
|
const cached = compiledCache.get(pattern);
|
|
if (cached) return cached;
|
|
if (!pattern.startsWith('/')) throw new Error(`invalid route pattern '${pattern}': pattern must start with '/'`);
|
|
if (pattern.includes('//')) throw new Error(`invalid route pattern '${pattern}': repeated slash`);
|
|
|
|
const normalized = pattern.length > 1 && pattern.endsWith('/') ? pattern.slice(0, -1) : pattern;
|
|
const rawSegments = normalized === '/' ? [] : normalized.split('/').slice(1);
|
|
const segments = compileSegments(pattern, rawSegments);
|
|
const compiled: CompiledPattern = {
|
|
source: pattern,
|
|
normalized,
|
|
shape: segments.map(segmentShape).join('/'),
|
|
segments,
|
|
kinds: segments
|
|
.filter((segment) => segment.kind !== 'catchAll')
|
|
.map((segment) => (segment.kind === 'static' ? 3 : segment.constraint ? 2 : 1)),
|
|
catchAll: segments.at(-1)?.kind === 'catchAll',
|
|
};
|
|
compiledCache.set(pattern, compiled);
|
|
return compiled;
|
|
}
|
|
|
|
/** Matches a `.` or `..` segment, percent-encoded or not, sitting alone between separators. */
|
|
const DOT_SEGMENT = /(?:^|\/)(?:\.|%2e){1,2}(?:\/|$)/i;
|
|
|
|
/**
|
|
* Classifies one path segment as `.`, `..`, or neither.
|
|
*
|
|
* `%2e` is a dot as far as the URL spec is concerned, so `/a/%2e%2e/b` and `/a/../b` are the same
|
|
* path. Skipping the encoded spelling would leave the encoded form as a way to reach a route the
|
|
* plain form resolves away from.
|
|
*/
|
|
function dotSegment(segment: string): '.' | '..' | undefined {
|
|
if (segment === '.' || segment === '..') return segment;
|
|
if (segment.length > 6 || !segment.includes('%')) return undefined;
|
|
const decoded = segment.toLowerCase().replace(/%2e/g, '.');
|
|
return decoded === '.' || decoded === '..' ? decoded : undefined;
|
|
}
|
|
|
|
/**
|
|
* Resolves `.` and `..` segments, the way RFC 3986 §5.2.4 and the WHATWG URL parser both do.
|
|
*
|
|
* This runs for the *Node* adapter's benefit. Every fetch-based runtime — Deno, Bun, workerd —
|
|
* resolves dot segments inside the `Request` constructor, before green-tea is handed anything:
|
|
* `new Request('http://x/public/../admin').url` is already `http://x/admin`. The raw target is
|
|
* simply not recoverable there, so rejecting dot segments outright — which is what this module
|
|
* does for `//`, and would be the stricter policy — cannot be implemented on three of the four
|
|
* runtimes. Resolving is the only rule all four can agree on.
|
|
*
|
|
* Before this, the same bytes on the wire routed differently per runtime: `GET /public/../admin`
|
|
* reached a `/admin` route under Deno/Bun/edge and 404'd under Node.
|
|
*/
|
|
function resolveDotSegments(path: string): string {
|
|
const out: string[] = [];
|
|
|
|
for (const segment of path.split('/').slice(1)) {
|
|
const dots = dotSegment(segment);
|
|
if (dots === '.') continue;
|
|
|
|
if (dots === '..') {
|
|
out.pop();
|
|
continue;
|
|
}
|
|
|
|
out.push(segment);
|
|
}
|
|
|
|
return `/${out.join('/')}`;
|
|
}
|
|
|
|
/** Applies the public trailing-slash policy and validates every segment's percent encoding. */
|
|
export function normalizeRequestPath(path: string): string {
|
|
if (!path.startsWith('/')) throw new InvalidRequestPathError('invalid request path: path must start with slash');
|
|
if (path.includes('//')) throw new InvalidRequestPathError('invalid request path: repeated slash');
|
|
|
|
// Two `indexOf` scans gate the regex, and the regex gates the split. A path with no `.` and no
|
|
// `%` at all — which is most of them — pays only the scans.
|
|
const resolved =
|
|
(path.includes('.') || path.includes('%')) && DOT_SEGMENT.test(path) ? resolveDotSegments(path) : path;
|
|
const normalized = resolved.length > 1 && resolved.endsWith('/') ? resolved.slice(0, -1) : resolved;
|
|
|
|
// Validation only — the decoded value is deliberately discarded, matching is done on the raw
|
|
// path. So the work is skipped entirely unless there is something to validate.
|
|
//
|
|
// This used to split the path and call `decodeURIComponent` per segment, on every request, and
|
|
// throw all of it away. Measured on this path: 95.8 ns for `/hello`, 342.7 ns for a six-segment
|
|
// route — around 8% of a whole request, spent proving that a string nobody decodes could be
|
|
// decoded. The guard below is 15.7 ns and 6.7 ns for the same two paths.
|
|
//
|
|
// One call on the whole string rather than per segment is the same check: `decodeURIComponent`
|
|
// throws on the first malformed `%` sequence wherever it appears, and a `%2F` inside a segment
|
|
// decodes fine either way. Only the throw matters here, never the result.
|
|
if (normalized.includes('%')) {
|
|
try {
|
|
decodeURIComponent(normalized);
|
|
} catch {
|
|
throw new InvalidRequestPathError('invalid request path: malformed path encoding');
|
|
}
|
|
}
|
|
|
|
return normalized;
|
|
}
|
|
|
|
function decodeSegment(value: string): string {
|
|
// Same gate `normalizeRequestPath` uses on the whole path, for the same reason: a segment with no
|
|
// `%` decodes to itself, so the call only ever proves that. Most segments have no `%`, and this
|
|
// runs for every param segment of every candidate route the scan reaches.
|
|
return value.includes('%') ? decodeURIComponent(value) : value;
|
|
}
|
|
|
|
/**
|
|
* Splits a request path into its non-empty segments.
|
|
*
|
|
* Called once per request by the scanning functions below, not once per candidate route. It used to
|
|
* live inside {@link matchCompiled}, which meant `split` + `filter` — two allocations — ran for every
|
|
* registered route on every request, always producing the same array.
|
|
*/
|
|
function splitPath(path: string): string[] {
|
|
return path.split('/').filter(Boolean);
|
|
}
|
|
|
|
/**
|
|
* Matches one compiled pattern against a request's segments.
|
|
*
|
|
* `decoded` memoizes per request, not per candidate: a scan reaching the same parameter position on
|
|
* several routes decoded the same string once per route. Position is all decoding depends on, so one
|
|
* array shared across the scan is the same answer for less work.
|
|
*/
|
|
function matchCompiled(
|
|
compiled: CompiledPattern,
|
|
pathSegs: string[],
|
|
decoded?: Array<string | undefined>,
|
|
): Record<string, string> | undefined {
|
|
const params: Record<string, string> = {};
|
|
|
|
for (let index = 0; index < compiled.segments.length; index++) {
|
|
const segment = compiled.segments[index];
|
|
|
|
if (segment.kind === 'catchAll') {
|
|
params[segment.name] = pathSegs.slice(index).map(decodeSegment).join('/');
|
|
return params;
|
|
}
|
|
|
|
if (index >= pathSegs.length) return undefined;
|
|
|
|
if (segment.kind === 'static') {
|
|
if (segment.value !== pathSegs[index]) return undefined;
|
|
continue;
|
|
}
|
|
|
|
const value = decoded ? (decoded[index] ??= decodeSegment(pathSegs[index])) : decodeSegment(pathSegs[index]);
|
|
if (segment.constraint && !segment.constraint.test(value)) return undefined;
|
|
params[segment.name] = value;
|
|
}
|
|
|
|
return compiled.segments.length === pathSegs.length ? params : undefined;
|
|
}
|
|
|
|
/** Matches a compiled segment pattern and returns its decoded parameters. */
|
|
export function matchPattern(pattern: string, path: string): Record<string, string> | undefined {
|
|
return matchCompiled(compilePattern(pattern), splitPath(path));
|
|
}
|
|
|
|
/**
|
|
* Orders patterns by exactness, then static/constrained/plain segment specificity.
|
|
*
|
|
* Takes compiled patterns rather than their source strings: it used to re-derive both through
|
|
* `compilePattern`, which is a `Map` lookup each, on every comparison of every request.
|
|
*/
|
|
function moreSpecific(a: CompiledPattern, b: CompiledPattern): number {
|
|
const scoreA = a;
|
|
const scoreB = b;
|
|
if (scoreA.catchAll !== scoreB.catchAll) return scoreA.catchAll ? -1 : 1;
|
|
const length = Math.max(scoreA.kinds.length, scoreB.kinds.length);
|
|
|
|
for (let index = 0; index < length; index++) {
|
|
const kindA = scoreA.kinds[index] ?? -1;
|
|
const kindB = scoreB.kinds[index] ?? -1;
|
|
if (kindA !== kindB) return kindA - kindB;
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
/** One route with its pattern already compiled. Built once per table, ordered within its method. */
|
|
interface IndexedRoute {
|
|
def: RouteDef;
|
|
compiled: CompiledPattern;
|
|
}
|
|
|
|
/**
|
|
* Compiled, method-bucketed, specificity-ordered route tables, keyed by the identity of the array
|
|
* they were built from.
|
|
*
|
|
* A server hands the same array to every request, so this is built once and collected with the
|
|
* table it describes. A table assembled fresh — mesh splicing a teapot's exports in at boot — is a
|
|
* different array and gets its own index, so nothing has to remember to invalidate anything.
|
|
*/
|
|
const routeIndexCache = new WeakMap<RouteDef[], Map<string, IndexedRoute[]>>();
|
|
|
|
function routeIndex(routes: RouteDef[]): Map<string, IndexedRoute[]> {
|
|
const cached = routeIndexCache.get(routes);
|
|
if (cached) return cached;
|
|
|
|
const byMethod = new Map<string, IndexedRoute[]>();
|
|
|
|
for (const def of routes) {
|
|
const entry: IndexedRoute = { def, compiled: compilePattern(def.pattern) };
|
|
const bucket = byMethod.get(def.method);
|
|
if (bucket) bucket.push(entry);
|
|
else byMethod.set(def.method, [entry]);
|
|
}
|
|
|
|
// Most specific first, so the first match *is* the answer. `sort` is stable, so equal patterns
|
|
// keep registration order — which is exactly what the old scan did by refusing to replace its
|
|
// best on a tie.
|
|
for (const bucket of byMethod.values()) bucket.sort((a, b) => moreSpecific(b.compiled, a.compiled));
|
|
|
|
routeIndexCache.set(routes, byMethod);
|
|
return byMethod;
|
|
}
|
|
|
|
/**
|
|
* Finds the most specific route matching both method and path; ties keep registration order.
|
|
*
|
|
* The ranking is settled when the table is built, not per request: the answer cannot change between
|
|
* requests, and re-deriving it charged every request for a scan to the end plus a `moreSpecific`
|
|
* call — two `compilePattern` lookups each — per candidate. Both scaled with the size of the route
|
|
* table. What is left here is a walk that stops at the first match.
|
|
*/
|
|
export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined {
|
|
const candidates = routeIndex(routes).get(method);
|
|
if (!candidates) return undefined;
|
|
|
|
const pathSegs = splitPath(path);
|
|
const decoded: Array<string | undefined> = new Array(pathSegs.length);
|
|
|
|
for (const { def, compiled } of candidates) {
|
|
const params = matchCompiled(compiled, pathSegs, decoded);
|
|
if (params) return { params, def };
|
|
}
|
|
|
|
return undefined;
|
|
}
|
|
|
|
/** Route resolution adds the one HTTP fallback the matcher supports: buffered GET serves HEAD. */
|
|
export interface ResolvedRoute extends MatchedRoute {
|
|
implicitHead: boolean;
|
|
}
|
|
|
|
export function resolveRoute(routes: RouteDef[], method: string, path: string): ResolvedRoute | undefined {
|
|
const explicit = matchRoute(routes, method, path);
|
|
if (explicit) return { ...explicit, implicitHead: false };
|
|
if (method !== 'HEAD') return undefined;
|
|
|
|
const fallback = matchRoute(
|
|
routes.filter((route) => route.transport === 'buffer'),
|
|
'GET',
|
|
path,
|
|
);
|
|
return fallback ? { ...fallback, implicitHead: true } : undefined;
|
|
}
|
|
|
|
const METHOD_ORDER = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];
|
|
|
|
/** Lists the distinct HTTP methods whose pattern matches the path — used to build a 405 `Allow` header. */
|
|
export function allowedMethods(routes: RouteDef[], path: string): string[] {
|
|
const pathSegs = splitPath(path);
|
|
const methods = new Set<string>();
|
|
|
|
for (const route of routes) {
|
|
if (!matchCompiled(compilePattern(route.pattern), pathSegs)) continue;
|
|
methods.add(route.method);
|
|
if (route.method === 'GET' && route.transport === 'buffer') methods.add('HEAD');
|
|
}
|
|
|
|
if (methods.size) methods.add('OPTIONS');
|
|
return [...methods].sort((a, b) => {
|
|
const indexA = METHOD_ORDER.indexOf(a);
|
|
const indexB = METHOD_ORDER.indexOf(b);
|
|
return (
|
|
(indexA < 0 ? METHOD_ORDER.length : indexA) - (indexB < 0 ? METHOD_ORDER.length : indexB) || a.localeCompare(b)
|
|
);
|
|
});
|
|
}
|
|
|
|
/** Parses a URL's query string into a flat string map (last value wins for repeated keys). */
|
|
export function parseQuery(url: string): Record<string, string> {
|
|
// Most requests carry no query string, and the work below is not free for them: `split` builds
|
|
// an array, `new URLSearchParams('')` builds an object, and the loop runs zero times — three
|
|
// allocations to arrive at `{}`. Measured at 92.3 ns against 18.6 ns for this check.
|
|
//
|
|
// Only the guard is new; the parse below is untouched on purpose. Reaching for `indexOf` +
|
|
// `slice` instead of `split` would also drop an allocation, but it changes what a second `?`
|
|
// means, and that is a behaviour question rather than a performance one.
|
|
if (!url.includes('?')) return {};
|
|
|
|
const queryString = url.split('?')[1] ?? '';
|
|
const out: Record<string, string> = {};
|
|
for (const [key, value] of new URLSearchParams(queryString)) out[key] = value;
|
|
return out;
|
|
}
|