forked from Lilly-Protocol/lily-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch-http-client-concurrency.test.ts
More file actions
96 lines (85 loc) · 2.74 KB
/
Copy pathfetch-http-client-concurrency.test.ts
File metadata and controls
96 lines (85 loc) · 2.74 KB
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
import { afterEach, describe, expect, it, vi } from 'vitest';
import { createFetchHttpClient } from '../src/http/fetch-http-client';
describe('fetch HTTP client concurrency', () => {
afterEach(() => {
vi.useRealTimers();
});
it('keeps retry and timeout state isolated across concurrent requests', async () => {
vi.useFakeTimers();
const requestCount = 12;
const attempts = new Map<string, number>();
const fetchMock = vi.fn((input: URL | RequestInfo) => {
const url = new URL(
typeof input === 'string'
? input
: input instanceof URL
? input.href
: input.url,
);
const requestId = url.searchParams.get('requestId');
if (requestId === null) {
throw new Error('Expected a requestId query parameter');
}
const attempt = (attempts.get(requestId) ?? 0) + 1;
attempts.set(requestId, attempt);
return new Promise<Response>((resolve) => {
// Resolve requests out of order so their retry delays and timeout timers overlap.
const staggerMs = (requestCount - Number(requestId)) * 3;
setTimeout(() => {
resolve(
new Response(
JSON.stringify(
attempt === 1
? { requestId, retry: true }
: { requestId, attempt },
),
{
status: attempt === 1 ? 503 : 200,
headers: { 'content-type': 'application/json' },
},
),
);
}, staggerMs);
});
});
const httpClient = createFetchHttpClient({
baseUrl: new URL('https://api.lily.test/'),
timeoutMs: 1_000,
retry: {
retries: 1,
retryDelayMs: 25,
retryableStatusCodes: [503],
},
defaultHeaders: {},
userAgent: 'lily-sdk/test',
fetch: fetchMock,
});
const responsesPromise = Promise.all(
Array.from({ length: requestCount }, (_, requestId) =>
httpClient.request<{ requestId: string; attempt: number }>({
method: 'GET',
path: '/v1/system/health',
query: { requestId },
}),
),
);
await vi.runAllTimersAsync();
const responses = await responsesPromise;
expect(responses.map(({ data }) => data)).toEqual(
Array.from({ length: requestCount }, (_, requestId) => ({
requestId: String(requestId),
attempt: 2,
})),
);
expect(Object.fromEntries(attempts)).toEqual(
Object.fromEntries(
Array.from({ length: requestCount }, (_, requestId) => [
String(requestId),
2,
]),
),
);
expect(fetchMock).toHaveBeenCalledTimes(requestCount * 2);
expect(vi.getTimerCount()).toBe(0);
});
});