| |
| """TypeScript tasks on the `router` repo. |
| |
| Chosen so the repair is a change of algorithm rather than a change of operator |
| -- that is the property measurement showed actually separates models. |
| """ |
| import sys |
| from pathlib import Path |
|
|
| sys.path.insert(0, str(Path(__file__).parent)) |
| from make_tasks import make, spec |
|
|
| R = "typescript/router" |
|
|
| |
| make(R, "specificity-by-sum", |
| spec("typescript", "logic", 5, """ |
| The wrong handler runs when two routes could both match. |
| |
| We serve /files/report/:format and /files/:name/raw. A request for |
| /files/report/raw is picked up by the second one, so it is treated as a raw |
| fetch of a file called "report" rather than as the report endpoint. Swapping |
| the order the two are registered in changes nothing. |
| |
| Both routes are the same length and each has one literal and one parameter, so |
| whatever decides between them is treating them as equally specific. It should |
| prefer the one that is more specific earlier in the path. Please fix it. |
| """), |
| [("src/matcher.ts", |
| """export function compareSpecificity(a: number[], b: number[]): number { |
| const length = Math.max(a.length, b.length); |
| for (let i = 0; i < length; i++) { |
| const left = a[i] ?? -1; |
| const right = b[i] ?? -1; |
| if (left !== right) return left - right; |
| } |
| return 0; |
| }""", |
| """export function compareSpecificity(a: number[], b: number[]): number { |
| const total = (v: number[]) => v.reduce((sum, n) => sum + n, 0); |
| return total(a) - total(b); |
| }""")], |
| {"specificity.test.ts": ''' |
| import { test } from 'node:test'; |
| import assert from 'node:assert'; |
| import { RouteTable, compareSpecificity, specificity, parsePattern } from '../src/index.ts'; |
| |
| function table(patterns: string[]) { |
| const t = new RouteTable<string>(); |
| for (const p of patterns) t.add(p, p); |
| return t; |
| } |
| |
| test('earlier segments dominate when totals tie', () => { |
| const t = table(['/files/report/:format', '/files/:name/raw']); |
| assert.strictEqual(t.match('/files/report/raw')!.route.value, '/files/report/:format'); |
| }); |
| |
| test('registration order is irrelevant', () => { |
| const a = table(['/files/report/:format', '/files/:name/raw']); |
| const b = table(['/files/:name/raw', '/files/report/:format']); |
| assert.strictEqual(a.match('/files/report/raw')!.route.value, |
| b.match('/files/report/raw')!.route.value); |
| }); |
| |
| test('leftmost literal wins across three competitors', () => { |
| const t = table(['/a/:x/:y', '/:p/b/:y', '/:p/:q/c']); |
| assert.strictEqual(t.match('/a/b/c')!.route.value, '/a/:x/:y'); |
| }); |
| |
| test('compare is lexicographic, not a total', () => { |
| assert.ok(compareSpecificity([2, 1], [1, 2]) > 0); |
| assert.ok(compareSpecificity([1, 2], [2, 1]) < 0); |
| assert.strictEqual(compareSpecificity([2, 1], [2, 1]), 0); |
| }); |
| |
| test('specificity vector shape is unchanged', () => { |
| assert.deepStrictEqual(specificity(parsePattern('/a/:b/*c')), [2, 1, 0]); |
| }); |
| |
| test('static still beats param beats wildcard', () => { |
| const t = table(['/u/*rest', '/u/:id', '/u/me']); |
| assert.strictEqual(t.match('/u/me')!.route.value, '/u/me'); |
| assert.strictEqual(t.match('/u/9')!.route.value, '/u/:id'); |
| assert.strictEqual(t.match('/u/a/b')!.route.value, '/u/*rest'); |
| }); |
| |
| test('exact match still preferred over everything', () => { |
| const t = table(['/:a/:b', '/x/y']); |
| assert.strictEqual(t.match('/x/y')!.route.value, '/x/y'); |
| }); |
| '''}) |
|
|
| |
| make(R, "middleware-reentrancy", |
| spec("typescript", "logic", 5, """ |
| A bug in one of our middlewares corrupted a whole batch of requests before we |
| noticed, and the router gave us no signal at all. |
| |
| The middleware in question awaited next(), then on a certain branch called |
| next() a second time. Everything below it in the stack ran twice against the |
| same request -- including a layer that charges a payment. We only found it from |
| the duplicate charges. |
| |
| Running the remainder of the stack twice for one request is never correct. |
| The composed handler should refuse it rather than quietly do it. |
| """), |
| [("src/middleware.ts", |
| """ return function composed(request: Request, final: Next): Promise<Response> { |
| let lastCalled = -1; |
| |
| function dispatch(index: number): Promise<Response> { |
| if (index <= lastCalled) { |
| return Promise.reject(new Error('next() called more than once')); |
| } |
| lastCalled = index; |
| if (index === layers.length) return final(); |
| const layer = layers[index]; |
| return layer(request, () => dispatch(index + 1)); |
| } |
| |
| return dispatch(0); |
| };""", |
| """ return function composed(request: Request, final: Next): Promise<Response> { |
| function dispatch(index: number): Promise<Response> { |
| if (index === layers.length) return final(); |
| const layer = layers[index]; |
| return layer(request, () => dispatch(index + 1)); |
| } |
| |
| return dispatch(0); |
| };""")], |
| {"middleware.test.ts": ''' |
| import { test } from 'node:test'; |
| import assert from 'node:assert'; |
| import { compose } from '../src/index.ts'; |
| import type { Middleware } from '../src/index.ts'; |
| |
| const REQ = {} as any; |
| const OK = async () => ({ status: 200, body: 'ok' }); |
| |
| test('calling next twice is rejected', async () => { |
| const twice: Middleware = async (_r, next) => { |
| await next(); |
| return next(); |
| }; |
| await assert.rejects(() => compose([twice])(REQ, OK)); |
| }); |
| |
| test('downstream runs only once per request', async () => { |
| let runs = 0; |
| const counter: Middleware = async (_r, next) => { runs++; return next(); }; |
| const twice: Middleware = async (_r, next) => { |
| await next(); |
| try { await next(); } catch { /* expected */ } |
| return { status: 200, body: '' }; |
| }; |
| await compose([twice, counter])(REQ, OK); |
| assert.strictEqual(runs, 1); |
| }); |
| |
| test('final handler runs only once', async () => { |
| let finals = 0; |
| const twice: Middleware = async (_r, next) => { |
| await next(); |
| try { await next(); } catch { /* expected */ } |
| return { status: 200, body: '' }; |
| }; |
| await compose([twice])(REQ, async () => { finals++; return { status: 200, body: '' }; }); |
| assert.strictEqual(finals, 1); |
| }); |
| |
| test('ordinary stacks still work end to end', async () => { |
| const seen: string[] = []; |
| const mk = (name: string): Middleware => async (_r, next) => { |
| seen.push(name + '-in'); |
| const res = await next(); |
| seen.push(name + '-out'); |
| return res; |
| }; |
| const res = await compose([mk('a'), mk('b'), mk('c')])(REQ, OK); |
| assert.strictEqual(res.body, 'ok'); |
| assert.deepStrictEqual(seen, ['a-in','b-in','c-in','c-out','b-out','a-out']); |
| }); |
| |
| test('empty stack calls the final handler', async () => { |
| assert.strictEqual((await compose([])(REQ, OK)).body, 'ok'); |
| }); |
| |
| test('a layer may short-circuit without calling next', async () => { |
| const stop: Middleware = async () => ({ status: 403, body: 'no' }); |
| let reached = false; |
| const after: Middleware = async (_r, next) => { reached = true; return next(); }; |
| const res = await compose([stop, after])(REQ, OK); |
| assert.strictEqual(res.status, 403); |
| assert.strictEqual(reached, false); |
| }); |
| |
| test('errors propagate', async () => { |
| const boom: Middleware = async () => { throw new Error('boom'); }; |
| await assert.rejects(() => compose([boom])(REQ, OK), /boom/); |
| }); |
| '''}) |
|
|
| |
| make(R, "lru-recency-on-read", |
| spec("typescript", "logic", 4, """ |
| Our hottest routes keep falling out of the route cache. |
| |
| The cache holds 128 entries and we serve far more distinct paths than that, but |
| a handful of endpoints take almost all the traffic. Those popular endpoints miss |
| constantly, while paths hit once at start-up survive for ages. Cache hit rate |
| sits far below what the traffic mix should give. |
| |
| The cache is meant to evict whatever has gone longest without being *used*. |
| Please make it do that. |
| """), |
| [("src/cache.ts", |
| """ const value = this.store.get(key) as V; |
| // reinsert so this key becomes the newest in iteration order |
| this.store.delete(key); |
| this.store.set(key, value); |
| this.hits++; |
| return value;""", |
| """ const value = this.store.get(key) as V; |
| this.hits++; |
| return value;""")], |
| {"cache.test.ts": ''' |
| import { test } from 'node:test'; |
| import assert from 'node:assert'; |
| import { LruCache } from '../src/index.ts'; |
| |
| test('reading an entry protects it from eviction', () => { |
| const c = new LruCache<string, number>(2); |
| c.set('a', 1); |
| c.set('b', 2); |
| c.get('a'); |
| c.set('c', 3); |
| assert.deepStrictEqual(c.keys().sort(), ['a', 'c']); |
| }); |
| |
| test('the least recently used key is evicted', () => { |
| const c = new LruCache<string, number>(3); |
| c.set('a', 1); c.set('b', 2); c.set('c', 3); |
| c.get('a'); c.get('c'); |
| c.set('d', 4); |
| assert.deepStrictEqual(c.keys().sort(), ['a', 'c', 'd']); |
| }); |
| |
| test('a repeatedly read key survives many insertions', () => { |
| const c = new LruCache<string, number>(3); |
| c.set('hot', 0); |
| for (let i = 0; i < 10; i++) { |
| c.get('hot'); |
| c.set('cold' + i, i); |
| } |
| assert.ok(c.has('hot')); |
| }); |
| |
| test('reading does not change the size', () => { |
| const c = new LruCache<string, number>(2); |
| c.set('a', 1); c.set('b', 2); |
| c.get('a'); |
| assert.strictEqual(c.size, 2); |
| }); |
| |
| test('values are still returned correctly', () => { |
| const c = new LruCache<string, number>(2); |
| c.set('a', 41); |
| assert.strictEqual(c.get('a'), 41); |
| assert.strictEqual(c.get('missing'), undefined); |
| }); |
| |
| test('hit and miss counters still work', () => { |
| const c = new LruCache<string, number>(2); |
| c.set('a', 1); |
| c.get('a'); c.get('nope'); |
| assert.strictEqual(c.hits, 1); |
| assert.strictEqual(c.misses, 1); |
| }); |
| |
| test('capacity is enforced', () => { |
| const c = new LruCache<string, number>(2); |
| c.set('a', 1); c.set('b', 2); c.set('c', 3); |
| assert.strictEqual(c.size, 2); |
| }); |
| |
| test('overwriting a key keeps one entry', () => { |
| const c = new LruCache<string, number>(2); |
| c.set('a', 1); c.set('a', 2); |
| assert.strictEqual(c.size, 1); |
| assert.strictEqual(c.get('a'), 2); |
| }); |
| '''}) |
|
|
| |
| make(R, "negotiate-tiebreak", |
| spec("typescript", "logic", 5, """ |
| Content negotiation ignores what the client asked for first. |
| |
| A client sending `Accept: text/html, application/json` -- no explicit |
| qualities, so both are equally acceptable -- gets JSON back. Per the spec, when |
| two acceptable types carry the same quality, the client's own ordering is the |
| tie-break, so that request should be served HTML. |
| |
| Requests that state explicit differing q-values are handled correctly; it is |
| only ties that come out wrong. Please fix. |
| """), |
| [("src/negotiate.ts", |
| """ const candidates = parseAccept(header).filter((c) => c.quality > 0); |
| let best: Candidate | undefined; |
| |
| for (const candidate of candidates) { |
| if (!matchesAny(candidate.type, offered)) continue; |
| if (best === undefined) { |
| best = candidate; |
| continue; |
| } |
| if (candidate.quality > best.quality) best = candidate; |
| }""", |
| """ const candidates = parseAccept(header) |
| .filter((c) => c.quality > 0) |
| .sort((a, b) => b.quality - a.quality || a.type.localeCompare(b.type)); |
| let best: Candidate | undefined; |
| |
| for (const candidate of candidates) { |
| if (!matchesAny(candidate.type, offered)) continue; |
| if (best === undefined) best = candidate; |
| }""")], |
| {"negotiate.test.ts": ''' |
| import { test } from 'node:test'; |
| import assert from 'node:assert'; |
| import { selectType, parseAccept } from '../src/index.ts'; |
| |
| const OFFER = ['text/html', 'application/json']; |
| |
| test('equal quality is broken by client order', () => { |
| assert.strictEqual(selectType('text/html, application/json', OFFER), 'text/html'); |
| assert.strictEqual(selectType('application/json, text/html', OFFER), 'application/json'); |
| }); |
| |
| test('explicit equal q values also use client order', () => { |
| assert.strictEqual(selectType('application/json;q=0.8, text/html;q=0.8', OFFER), |
| 'application/json'); |
| }); |
| |
| test('client order beats alphabetical order', () => { |
| assert.strictEqual(selectType('text/html, application/json', OFFER), 'text/html'); |
| }); |
| |
| test('three-way tie takes the first listed', () => { |
| const offer = ['text/plain', 'text/html', 'application/json']; |
| assert.strictEqual(selectType('text/plain, text/html, application/json', offer), |
| 'text/plain'); |
| }); |
| |
| test('higher quality still wins over order', () => { |
| assert.strictEqual(selectType('text/html;q=0.2, application/json;q=0.9', OFFER), |
| 'application/json'); |
| assert.strictEqual(selectType('application/json;q=0.1, text/html;q=0.7', OFFER), |
| 'text/html'); |
| }); |
| |
| test('zero quality is never selected', () => { |
| assert.strictEqual(selectType('text/html;q=0', ['text/html']), undefined); |
| }); |
| |
| test('wildcards still match', () => { |
| assert.strictEqual(selectType('*/*', ['text/html']), 'text/html'); |
| assert.strictEqual(selectType('text/*', ['text/html']), 'text/html'); |
| }); |
| |
| test('nothing acceptable yields undefined', () => { |
| assert.strictEqual(selectType('image/png', OFFER), undefined); |
| }); |
| |
| test('parseAccept still records order and quality', () => { |
| const parsed = parseAccept('a/b;q=0.5, c/d'); |
| assert.strictEqual(parsed[0].quality, 0.5); |
| assert.strictEqual(parsed[1].order, 1); |
| }); |
| '''}) |
|
|
| print("done") |
|
|