diff --git a/src/http/router.ts b/src/http/router.ts index 0c9d381..4588140 100644 --- a/src/http/router.ts +++ b/src/http/router.ts @@ -13,8 +13,6 @@ export interface CompiledPattern { segments: CompiledSegment[]; kinds: number[]; catchAll: boolean; - /** Every segment is a literal, so this pattern scores the maximum specificity and cannot be outranked. */ - allStatic: boolean; } const compiledCache = new Map(); @@ -160,7 +158,6 @@ export function compilePattern(pattern: string): CompiledPattern { .filter((segment) => segment.kind !== 'catchAll') .map((segment) => (segment.kind === 'static' ? 3 : segment.constraint ? 2 : 1)), catchAll: segments.at(-1)?.kind === 'catchAll', - allStatic: segments.every((segment) => segment.kind === 'static'), }; compiledCache.set(pattern, compiled); return compiled; @@ -248,7 +245,10 @@ export function normalizeRequestPath(path: string): string { } function decodeSegment(value: string): string { - return decodeURIComponent(value); + // 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; } /** @@ -262,7 +262,18 @@ function splitPath(path: string): string[] { return path.split('/').filter(Boolean); } -function matchCompiled(compiled: CompiledPattern, pathSegs: string[]): Record | undefined { +/** + * 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, +): Record | undefined { const params: Record = {}; for (let index = 0; index < compiled.segments.length; index++) { @@ -280,7 +291,7 @@ function matchCompiled(compiled: CompiledPattern, pathSegs: string[]): Record>(); - // An all-static match ends the scan. Specificity ranks a literal segment above every other - // kind, so no pattern that also matches this path can outrank one made only of literals — and - // an equal rank keeps registration order, which is this route. Finishing the scan would - // re-derive the answer already in hand. - // - // The scan used to run to the end regardless: `/hello` cost the same whether it was declared - // first or last among 32 routes, 1227 ns against 1237 ns. That is ~38 ns of scanning per - // registered route on every request, and it grows with the route table. - if (compiled.allStatic) return { params, def: route }; +function routeIndex(routes: RouteDef[]): Map { + const cached = routeIndexCache.get(routes); + if (cached) return cached; - if (!best || moreSpecific(route.pattern, bestPattern) > 0) { - best = { params, def: route }; - bestPattern = route.pattern; - } + const byMethod = new Map(); + + 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]); } - return best; + // 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 = 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. */ diff --git a/test/router.test.ts b/test/router.test.ts index 3f61b1c..62a6d4e 100644 --- a/test/router.test.ts +++ b/test/router.test.ts @@ -119,6 +119,23 @@ describe('matchRoute precedence', () => { expect(matchRoute(routes, 'GET', '/users/diego')?.def.pattern).toBe('/users/:value'); }); + it('keeps registration order between patterns of equal specificity', () => { + // The tie-break the ordering rests on. Ranking is settled once when the table is built, and the + // sort that settles it is stable — which is what preserves the behaviour the scan used to get + // by refusing to replace its best on an equal rank. A sort that reordered equals would change + // which of two same-shape routes answers, silently and only for the ones that collide. + const routes = [route('GET', '/a/:first'), route('GET', '/a/:second')]; + expect(matchRoute(routes, 'GET', '/a/x')?.def.pattern).toBe('/a/:first'); + expect(matchRoute([...routes].reverse(), 'GET', '/a/x')?.def.pattern).toBe('/a/:second'); + }); + + it('decodes a parameter once per position, however many candidates the scan walks', () => { + // Not an optimisation detail: the decoded value each candidate sees must be the same one, so + // memoising per request cannot change which route matches or what it receives. + const routes = [route('GET', '/a/:x/zzz'), route('GET', '/a/:y/b')]; + expect(matchRoute(routes, 'GET', '/a/a%20b/b')?.params).toEqual({ y: 'a b' }); + }); + it('returns undefined when no pattern matches the path', () => { expect(matchRoute([route('GET', '/a')], 'GET', '/b')).toBeUndefined(); });