tobogganSe connecter

starfleet-ui

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

50 lignes · 1666 octetsBrut · Historique
1import { expect, test } from 'bun:test';
2import { captainKey, cached, mapSettled } from './cache';
3
4test('captainKey hashes the whole token, not a suffix', () => {
5 expect(captainKey('sfk_aaaa12345678')).not.toBe(captainKey('sfk_bbbb12345678'));
6 expect(captainKey('sfk_x')).not.toContain('sfk_x');
7});
8
9test('cached serves fresh hits without calling produce again', async () => {
10 let calls = 0;
11 const produce = async () => ++calls;
12 expect(await cached('fresh', 60_000, produce)).toBe(1);
13 expect(await cached('fresh', 60_000, produce)).toBe(1);
14 expect(calls).toBe(1);
15});
16
17test('cached serves stale values while refreshing in the background', async () => {
18 let calls = 0;
19 const produce = async () => ++calls;
20 await cached('stale', 0, produce, { maxStaleMs: 60_000 });
21 expect(await cached('stale', 0, produce, { maxStaleMs: 60_000 })).toBe(1); // stale served
22 await Bun.sleep(1);
23 expect(calls).toBe(2); // refresh ran
24});
25
26test('concurrent misses share one request', async () => {
27 let calls = 0;
28 const produce = async () => {
29 calls++;
30 await Bun.sleep(5);
31 return 'v';
32 };
33 await Promise.all([cached('dedupe', 1000, produce), cached('dedupe', 1000, produce)]);
34 expect(calls).toBe(1);
35});
36
37test('mapSettled caps concurrency and keeps order', async () => {
38 let active = 0;
39 let peak = 0;
40 const res = await mapSettled([1, 2, 3, 4, 5, 6, 7], 3, async (n) => {
41 active++;
42 peak = Math.max(peak, active);
43 await Bun.sleep(2);
44 active--;
45 if (n === 4) throw new Error('boom');
46 return n * 10;
47 });
48 expect(peak).toBeLessThanOrEqual(3);
49 expect(res.map((r) => (r.status === 'fulfilled' ? r.value : 'x'))).toEqual([10, 20, 30, 'x', 50, 60, 70]);
50});