forked from Lilly-Protocol/lily-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp-timeout.test.ts
More file actions
257 lines (213 loc) · 7.42 KB
/
Copy pathhttp-timeout.test.ts
File metadata and controls
257 lines (213 loc) · 7.42 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
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
import { afterEach, describe, expect, it, vi } from 'vitest';
import { LilyConfigError, LilyTransportError } from '../src/errors/sdk-error';
import { createFetchHttpClient } from '../src/http/fetch-http-client';
import type { ResolvedLilySdkConfig } from '../src/config/types';
/**
* A fetch that never settles on its own and only rejects when the caller's
* AbortSignal fires — the same way a real fetch behaves against a server that
* has accepted the connection and gone quiet. Anything that resolves on a timer
* would be testing the timer, not the abort wiring.
*/
function hangingFetch(): ResolvedLilySdkConfig['fetch'] {
return vi.fn(
(_input: URL | RequestInfo, init?: RequestInit) =>
new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener('abort', () => {
// Node's fetch rejects with a DOMException named AbortError.
const error = new Error('The operation was aborted.');
error.name = 'AbortError';
reject(error);
});
}),
);
}
function client(overrides: Partial<ResolvedLilySdkConfig> = {}) {
return createFetchHttpClient({
baseUrl: new URL('https://api.lily.test/'),
timeoutMs: 2_000,
retry: {
retries: 0,
retryDelayMs: 0,
retryableStatusCodes: [],
},
defaultHeaders: {},
userAgent: 'lily-sdk/test',
fetch: hangingFetch(),
toHeaders: () => ({}),
...overrides,
});
}
describe('request timeout', () => {
afterEach(() => {
vi.useRealTimers();
});
it('aborts a request that outlives the configured timeout', async () => {
vi.useFakeTimers();
const pending = client({ timeoutMs: 2_000 }).request({
method: 'GET',
path: '/v1/system/health',
});
const assertion =
expect(pending).rejects.toBeInstanceOf(LilyTransportError);
await vi.advanceTimersByTimeAsync(2_000);
await assertion;
});
it('reports the timeout with the TIMEOUT code', async () => {
vi.useFakeTimers();
const pending = client({ timeoutMs: 1_000 }).request({
method: 'GET',
path: '/v1/system/health',
});
const assertion = expect(pending).rejects.toMatchObject({
code: 'TIMEOUT',
message: 'Request timed out while calling Lily Protocol API.',
});
await vi.advanceTimersByTimeAsync(1_000);
await assertion;
});
it('does not abort before the timeout elapses', async () => {
vi.useFakeTimers();
let settled = false;
const pending = client({ timeoutMs: 5_000 })
.request({ method: 'GET', path: '/v1/system/health' })
.catch(() => {
settled = true;
});
await vi.advanceTimersByTimeAsync(4_999);
expect(settled).toBe(false);
await vi.advanceTimersByTimeAsync(1);
await pending;
expect(settled).toBe(true);
});
it('lets a per-request timeout override the client default', async () => {
vi.useFakeTimers();
// Client default is 60s; the request asks for 500ms and must win.
const pending = client({ timeoutMs: 60_000 }).request({
method: 'GET',
path: '/v1/system/health',
timeoutMs: 500,
});
const assertion =
expect(pending).rejects.toBeInstanceOf(LilyTransportError);
await vi.advanceTimersByTimeAsync(500);
await assertion;
});
it('passes an AbortSignal to fetch so the socket is actually released', async () => {
// A timeout that rejects the promise but leaves the request in flight is
// a leak, not a timeout.
const fetchSpy = hangingFetch();
vi.useFakeTimers();
const pending = client({ timeoutMs: 100, fetch: fetchSpy })
.request({ method: 'GET', path: '/v1/system/health' })
.catch(() => undefined);
await vi.advanceTimersByTimeAsync(100);
await pending;
const init = vi.mocked(fetchSpy).mock.calls[0]?.[1];
expect(init?.signal).toBeInstanceOf(AbortSignal);
expect(init?.signal?.aborted).toBe(true);
});
it('clears the timer when a request completes in time', async () => {
// Otherwise a short-lived process is held open by a pending timer.
vi.useFakeTimers();
const clearSpy = vi.spyOn(globalThis, 'clearTimeout');
await client({
timeoutMs: 30_000,
fetch: vi.fn(() =>
Promise.resolve(
new Response(JSON.stringify({ status: 'ok' }), {
status: 200,
headers: { 'content-type': 'application/json' },
}),
),
),
}).request({ method: 'GET', path: '/v1/system/health' });
expect(clearSpy).toHaveBeenCalled();
clearSpy.mockRestore();
});
it('does not retry a timed-out request when retries are disabled', async () => {
const fetchSpy = hangingFetch();
vi.useFakeTimers();
const pending = client({ timeoutMs: 100, fetch: fetchSpy })
.request({ method: 'GET', path: '/v1/system/health' })
.catch(() => undefined);
await vi.advanceTimersByTimeAsync(100);
await pending;
expect(fetchSpy).toHaveBeenCalledOnce();
});
describe('per-request timeoutMs validation (issue #446)', () => {
it('rejects negative timeoutMs without dispatching request', async () => {
const fetchSpy = hangingFetch();
const httpClient = client({ fetch: fetchSpy });
await expect(
httpClient.request({
method: 'GET',
path: '/v1/system/health',
timeoutMs: -1,
}),
).rejects.toBeInstanceOf(LilyConfigError);
await expect(
httpClient.request({
method: 'GET',
path: '/v1/system/health',
timeoutMs: -100,
}),
).rejects.toThrow('`timeoutMs` must be a non-negative number.');
expect(fetchSpy).not.toHaveBeenCalled();
});
it('rejects NaN and non-finite timeoutMs without dispatching request', async () => {
const fetchSpy = hangingFetch();
const httpClient = client({ fetch: fetchSpy });
await expect(
httpClient.request({
method: 'GET',
path: '/v1/system/health',
timeoutMs: NaN,
}),
).rejects.toBeInstanceOf(LilyConfigError);
await expect(
httpClient.request({
method: 'GET',
path: '/v1/system/health',
timeoutMs: Infinity,
}),
).rejects.toBeInstanceOf(LilyConfigError);
expect(fetchSpy).not.toHaveBeenCalled();
});
it('rejects non-number timeoutMs without dispatching request', async () => {
const fetchSpy = hangingFetch();
const httpClient = client({ fetch: fetchSpy });
await expect(
httpClient.request({
method: 'GET',
path: '/v1/system/health',
timeoutMs: '1000' as any,
}),
).rejects.toBeInstanceOf(LilyConfigError);
expect(fetchSpy).not.toHaveBeenCalled();
});
it('allows timeoutMs: 0 and disables timeout', async () => {
const fetchSpy = vi.fn(
() =>
new Promise<Response>((resolve) => {
// Settle after delay
setTimeout(() => {
resolve(
new Response(JSON.stringify({ status: 'ok' }), {
status: 200,
headers: { 'content-type': 'application/json' },
}),
);
}, 10);
}),
);
const httpClient = client({ fetch: fetchSpy, timeoutMs: 1 });
const res = await httpClient.request({
method: 'GET',
path: '/v1/system/health',
timeoutMs: 0,
});
expect(res.status).toBe(200);
expect(fetchSpy).toHaveBeenCalledOnce();
});
});
});