File size: 13,498 Bytes
9368cc4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
#!/usr/bin/env python3
"""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  # noqa: E402

R = "typescript/router"

# ------------------------------------------------- specificity: sum vs lexicographic
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');
});
'''})

# ------------------------------------------------- middleware: reentrancy guard
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/);
});
'''})

# ------------------------------------------------- LRU recency
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);
});
'''})

# ------------------------------------------------- negotiation tie-break
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")