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>
170 lines
7.7 KiB
TypeScript
170 lines
7.7 KiB
TypeScript
import { describe, it, expect } from 'vitest';
|
|
import {
|
|
compilePattern,
|
|
matchPattern,
|
|
matchRoute,
|
|
resolveRoute,
|
|
allowedMethods,
|
|
normalizeRequestPath,
|
|
} from '../src/http/router';
|
|
import type { RouteDef } from '../src/http/types';
|
|
|
|
const route = (method: string, pattern: string): RouteDef => ({
|
|
method,
|
|
pattern,
|
|
transport: 'buffer',
|
|
handler: async () => ({ status: 200, headers: {}, body: '' }),
|
|
});
|
|
|
|
describe('matchPattern', () => {
|
|
it('matches the root pattern only at root', () => {
|
|
expect(matchPattern('/', '/')).toEqual({});
|
|
expect(matchPattern('/', '/users')).toBeUndefined();
|
|
});
|
|
|
|
it('matches static and :param segments, decoding params', () => {
|
|
expect(matchPattern('/users/:id', '/users/a%20b')).toEqual({ id: 'a b' });
|
|
expect(matchPattern('/users/:id', '/users')).toBeUndefined();
|
|
expect(matchPattern('/users', '/users/1')).toBeUndefined();
|
|
});
|
|
|
|
it(':name* captures the rest of the path, slashes included', () => {
|
|
expect(matchPattern('/files/:path*', '/files/img/2026/logo.png')).toEqual({ path: 'img/2026/logo.png' });
|
|
expect(matchPattern('/files/:path*', '/files/a%2Fb')).toEqual({ path: 'a/b' });
|
|
});
|
|
|
|
it(':name* matches zero remaining segments as an empty string', () => {
|
|
expect(matchPattern('/files/:path*', '/files')).toEqual({ path: '' });
|
|
});
|
|
|
|
it('matches safe constraints against the complete decoded segment', () => {
|
|
expect(matchPattern('/users/:id(\\d+)', '/users/42')).toEqual({ id: '42' });
|
|
expect(matchPattern('/users/:id(\\d+)', '/users/42x')).toBeUndefined();
|
|
expect(matchPattern('/posts/:slug([a-z0-9_-]+)', '/posts/green-tea_26')).toEqual({ slug: 'green-tea_26' });
|
|
expect(matchPattern('/build/:version(\\d{2}\\.\\d{1,2})', '/build/26.8')).toEqual({ version: '26.8' });
|
|
});
|
|
});
|
|
|
|
describe('compilePattern', () => {
|
|
it('records a stable shape independent of parameter names', () => {
|
|
expect(compilePattern('/users/:id').shape).toBe(compilePattern('/users/:name').shape);
|
|
expect(compilePattern('/users/:id(\\d+)').shape).not.toBe(compilePattern('/users/:id').shape);
|
|
});
|
|
|
|
it.each([
|
|
'/files/:rest*/tail',
|
|
'/users/:',
|
|
'/users/:id/:id',
|
|
'/users//:id',
|
|
'/users/:id((a+)+)',
|
|
'/users/:id((?=a)a)',
|
|
'/users/:id(\\1)',
|
|
'/users/:id(a|b)',
|
|
])('rejects invalid or unsafe pattern %s', (pattern) => {
|
|
expect(() => compilePattern(pattern)).toThrow(/invalid route pattern|unsafe route constraint/);
|
|
});
|
|
});
|
|
|
|
describe('normalizeRequestPath', () => {
|
|
it('treats one trailing slash as equivalent and preserves root', () => {
|
|
expect(normalizeRequestPath('/users')).toBe('/users');
|
|
expect(normalizeRequestPath('/users/')).toBe('/users');
|
|
expect(normalizeRequestPath('/')).toBe('/');
|
|
});
|
|
|
|
it('rejects repeated slashes and malformed percent encoding', () => {
|
|
expect(() => normalizeRequestPath('/users//42')).toThrow(/repeated slash/);
|
|
expect(() => normalizeRequestPath('/users/%E0%A4%A')).toThrow(/malformed path encoding/);
|
|
});
|
|
|
|
// The reference for every case below is `new URL('http://x' + path).pathname`, because that is
|
|
// what Deno, Bun and workerd apply before green-tea is handed the request. Node has no such step,
|
|
// so this is where the two adapters are made to agree.
|
|
it('resolves dot segments the way the URL parser does', () => {
|
|
expect(normalizeRequestPath('/public/../admin')).toBe('/admin');
|
|
expect(normalizeRequestPath('/./admin')).toBe('/admin');
|
|
expect(normalizeRequestPath('/a/b/../../c')).toBe('/c');
|
|
expect(normalizeRequestPath('/a/.')).toBe('/a');
|
|
expect(normalizeRequestPath('/..')).toBe('/');
|
|
expect(normalizeRequestPath('/a/../..')).toBe('/');
|
|
});
|
|
|
|
it('resolves percent-encoded dot segments, which the URL parser also treats as dots', () => {
|
|
expect(normalizeRequestPath('/public/%2e%2e/admin')).toBe('/admin');
|
|
expect(normalizeRequestPath('/public/%2E%2E/admin')).toBe('/admin');
|
|
expect(normalizeRequestPath('/%2e/admin')).toBe('/admin');
|
|
expect(normalizeRequestPath('/public/.%2e/admin')).toBe('/admin');
|
|
});
|
|
|
|
it('leaves dots that are not whole segments alone', () => {
|
|
expect(normalizeRequestPath('/assets/logo.png')).toBe('/assets/logo.png');
|
|
expect(normalizeRequestPath('/files/.hidden')).toBe('/files/.hidden');
|
|
expect(normalizeRequestPath('/v1.2/status')).toBe('/v1.2/status');
|
|
// %2f is not a separator to the URL parser, so `..%2fb` is one ordinary segment.
|
|
expect(normalizeRequestPath('/a/..%2fb')).toBe('/a/..%2fb');
|
|
});
|
|
});
|
|
|
|
describe('matchRoute precedence', () => {
|
|
it('static beats :param beats catch-all regardless of registration order', () => {
|
|
const routes = [route('GET', '/a/:rest*'), route('GET', '/a/:id'), route('GET', '/a/b')];
|
|
expect(matchRoute(routes, 'GET', '/a/b')?.def.pattern).toBe('/a/b');
|
|
expect(matchRoute(routes, 'GET', '/a/x')?.def.pattern).toBe('/a/:id');
|
|
expect(matchRoute(routes, 'GET', '/a/x/y')?.def.pattern).toBe('/a/:rest*');
|
|
});
|
|
|
|
it('constrained params beat unconstrained params regardless of registration order', () => {
|
|
const routes = [route('GET', '/users/:value'), route('GET', '/users/:id(\\d+)')];
|
|
expect(matchRoute(routes, 'GET', '/users/42')?.def.pattern).toBe('/users/:id(\\d+)');
|
|
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();
|
|
});
|
|
|
|
it('does not match a route registered under a different method', () => {
|
|
expect(matchRoute([route('POST', '/a')], 'GET', '/a')).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
describe('allowedMethods (405 support)', () => {
|
|
it('lists methods in canonical order with implicit HEAD and OPTIONS', () => {
|
|
const routes = [route('POST', '/a'), route('GET', '/a'), route('GET', '/b')];
|
|
expect(allowedMethods(routes, '/a')).toEqual(['GET', 'HEAD', 'POST', 'OPTIONS']);
|
|
expect(allowedMethods(routes, '/nope')).toEqual([]);
|
|
});
|
|
});
|
|
|
|
describe('resolveRoute', () => {
|
|
it('prefers explicit HEAD and otherwise falls back to buffered GET', () => {
|
|
const explicit = [route('GET', '/a'), route('HEAD', '/a')];
|
|
expect(resolveRoute(explicit, 'HEAD', '/a')).toMatchObject({ implicitHead: false, def: { method: 'HEAD' } });
|
|
|
|
const fallback = resolveRoute([route('GET', '/a')], 'HEAD', '/a');
|
|
expect(fallback).toMatchObject({ implicitHead: true, def: { method: 'GET' } });
|
|
});
|
|
|
|
it('does not use a streaming GET as implicit HEAD', () => {
|
|
const streaming = { ...route('GET', '/a'), transport: 'sse' as const };
|
|
expect(resolveRoute([streaming], 'HEAD', '/a')).toBeUndefined();
|
|
});
|
|
});
|