@baukit/api-runtime 0.30.6 → 0.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +56 -9
- package/dist/backoff.d.ts +1 -1
- package/dist/backoff.d.ts.map +1 -1
- package/dist/backoff.js +6 -3
- package/dist/backoff.js.map +1 -1
- package/dist/cooldown.d.ts +31 -0
- package/dist/cooldown.d.ts.map +1 -0
- package/dist/cooldown.js +92 -0
- package/dist/cooldown.js.map +1 -0
- package/dist/errors.d.ts +10 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +17 -0
- package/dist/errors.js.map +1 -1
- package/dist/fetch.d.ts +8 -0
- package/dist/fetch.d.ts.map +1 -1
- package/dist/fetch.js +112 -17
- package/dist/fetch.js.map +1 -1
- package/dist/index.d.ts +18 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/retry.d.ts +15 -2
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +36 -4
- package/dist/retry.js.map +1 -1
- package/dist/timeout.d.ts +13 -0
- package/dist/timeout.d.ts.map +1 -0
- package/dist/timeout.js +34 -0
- package/dist/timeout.js.map +1 -0
- package/package.json +4 -2
- package/src/backoff.ts +6 -3
- package/src/cooldown.test.ts +62 -0
- package/src/cooldown.ts +123 -0
- package/src/errors.ts +20 -0
- package/src/fetch.ts +140 -16
- package/src/index.ts +19 -0
- package/src/origin.property.test.ts +122 -0
- package/src/origin.test.ts +87 -0
- package/src/resilience-vectors.test.ts +128 -0
- package/src/resilience.test.ts +344 -0
- package/src/retry.ts +48 -4
- package/src/timeout.ts +39 -0
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
ApiUnavailableError,
|
|
5
|
+
HttpError,
|
|
6
|
+
IDEMPOTENCY_KEY_HEADER,
|
|
7
|
+
MockFetch,
|
|
8
|
+
NetworkError,
|
|
9
|
+
createApiFetch,
|
|
10
|
+
isApiUnavailableError,
|
|
11
|
+
type FetchImplementation,
|
|
12
|
+
} from './index.js';
|
|
13
|
+
|
|
14
|
+
const baseOptions = { baseUrl: 'https://api.example.test/v1', environment: 'test' } as const;
|
|
15
|
+
const START = Date.UTC(2026, 0, 1);
|
|
16
|
+
|
|
17
|
+
function manualClock(): { now: () => number; advance: (ms: number) => void } {
|
|
18
|
+
let current = START;
|
|
19
|
+
return {
|
|
20
|
+
now: () => current,
|
|
21
|
+
advance: (ms) => {
|
|
22
|
+
current += ms;
|
|
23
|
+
},
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function clockedRetry(clock: ReturnType<typeof manualClock>, delays: number[]) {
|
|
28
|
+
return {
|
|
29
|
+
random: () => 1,
|
|
30
|
+
sleep: (delayMs: number) => {
|
|
31
|
+
delays.push(delayMs);
|
|
32
|
+
clock.advance(delayMs);
|
|
33
|
+
return Promise.resolve();
|
|
34
|
+
},
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function hangingFetch(): FetchImplementation {
|
|
39
|
+
return (_input, init) =>
|
|
40
|
+
new Promise((_resolve, reject) => {
|
|
41
|
+
init?.signal?.addEventListener('abort', () => {
|
|
42
|
+
reject(new DOMException('aborted', 'AbortError'));
|
|
43
|
+
});
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
afterEach(() => {
|
|
48
|
+
vi.useRealTimers();
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
describe('request timeout', () => {
|
|
52
|
+
it('fails a hanging attempt after requestTimeoutMs as a non-aborted network error', async () => {
|
|
53
|
+
vi.useFakeTimers();
|
|
54
|
+
const apiFetch = createApiFetch({
|
|
55
|
+
...baseOptions,
|
|
56
|
+
fetch: hangingFetch(),
|
|
57
|
+
requestTimeoutMs: 1_000,
|
|
58
|
+
retry: false,
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
const pending = apiFetch('/hang').catch((error: unknown) => error);
|
|
62
|
+
await vi.advanceTimersByTimeAsync(1_000);
|
|
63
|
+
const caught = await pending;
|
|
64
|
+
|
|
65
|
+
expect(caught).toBeInstanceOf(NetworkError);
|
|
66
|
+
expect(caught).toMatchObject({ aborted: false, message: 'API request timed out' });
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it('defaults to a 30 second timeout', async () => {
|
|
70
|
+
vi.useFakeTimers();
|
|
71
|
+
const apiFetch = createApiFetch({ ...baseOptions, fetch: hangingFetch(), retry: false });
|
|
72
|
+
let settled = false;
|
|
73
|
+
const pending = apiFetch('/hang').catch((error: unknown) => {
|
|
74
|
+
settled = true;
|
|
75
|
+
return error;
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
await vi.advanceTimersByTimeAsync(29_999);
|
|
79
|
+
expect(settled).toBe(false);
|
|
80
|
+
await vi.advanceTimersByTimeAsync(1);
|
|
81
|
+
await expect(pending).resolves.toMatchObject({ message: 'API request timed out' });
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it('still honours the caller signal and reports it as aborted', async () => {
|
|
85
|
+
const controller = new AbortController();
|
|
86
|
+
const apiFetch = createApiFetch({ ...baseOptions, fetch: hangingFetch(), retry: false });
|
|
87
|
+
const pending = apiFetch('/hang', { signal: controller.signal }).catch(
|
|
88
|
+
(error: unknown) => error,
|
|
89
|
+
);
|
|
90
|
+
controller.abort('stop');
|
|
91
|
+
|
|
92
|
+
await expect(pending).resolves.toMatchObject({ aborted: true });
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it('retries a timed-out GET', async () => {
|
|
96
|
+
vi.useFakeTimers();
|
|
97
|
+
let calls = 0;
|
|
98
|
+
const fetch: FetchImplementation = (input, init) => {
|
|
99
|
+
calls += 1;
|
|
100
|
+
return calls === 1 ? hangingFetch()(input, init) : Promise.resolve(new Response('{}'));
|
|
101
|
+
};
|
|
102
|
+
const apiFetch = createApiFetch({
|
|
103
|
+
...baseOptions,
|
|
104
|
+
fetch,
|
|
105
|
+
requestTimeoutMs: 100,
|
|
106
|
+
retry: { baseDelayMs: 0 },
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
const pending = apiFetch('/slow');
|
|
110
|
+
await vi.advanceTimersByTimeAsync(101);
|
|
111
|
+
await expect(pending).resolves.toHaveProperty('status', 200);
|
|
112
|
+
expect(calls).toBe(2);
|
|
113
|
+
});
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
describe('Retry-After', () => {
|
|
117
|
+
it.each([429, 503])('retries a GET %i after the delay-seconds value', async (status) => {
|
|
118
|
+
const clock = manualClock();
|
|
119
|
+
const delays: number[] = [];
|
|
120
|
+
const mock = new MockFetch()
|
|
121
|
+
.enqueue(new Response(null, { status, headers: { 'retry-after': '3' } }))
|
|
122
|
+
.enqueueJson({ ok: true });
|
|
123
|
+
const apiFetch = createApiFetch({
|
|
124
|
+
...baseOptions,
|
|
125
|
+
fetch: mock.fetch,
|
|
126
|
+
now: clock.now,
|
|
127
|
+
retry: clockedRetry(clock, delays),
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
await expect(apiFetch('/limited')).resolves.toHaveProperty('status', 200);
|
|
131
|
+
expect(delays).toEqual([3_000]);
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
it('accepts an HTTP date and clamps to maxRetryAfterMs', async () => {
|
|
135
|
+
const clock = manualClock();
|
|
136
|
+
const delays: number[] = [];
|
|
137
|
+
const inTwoSeconds = new Date(START + 2_000).toUTCString();
|
|
138
|
+
const inAnHour = new Date(START + 3_600_000).toUTCString();
|
|
139
|
+
const mock = new MockFetch()
|
|
140
|
+
.enqueue(new Response(null, { status: 503, headers: { 'retry-after': inTwoSeconds } }))
|
|
141
|
+
.enqueue(new Response(null, { status: 429, headers: { 'retry-after': inAnHour } }))
|
|
142
|
+
.enqueueJson({ ok: true });
|
|
143
|
+
const apiFetch = createApiFetch({
|
|
144
|
+
...baseOptions,
|
|
145
|
+
fetch: mock.fetch,
|
|
146
|
+
now: clock.now,
|
|
147
|
+
retry: { ...clockedRetry(clock, delays), maxRetryAfterMs: 10_000 },
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
await expect(apiFetch('/limited')).resolves.toHaveProperty('status', 200);
|
|
151
|
+
expect(delays).toEqual([2_000, 10_000]);
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
it('does not retry an unkeyed POST but still starts the cooldown', async () => {
|
|
155
|
+
const clock = manualClock();
|
|
156
|
+
const mock = new MockFetch().enqueue(
|
|
157
|
+
new Response(null, { status: 429, headers: { 'retry-after': '5' } }),
|
|
158
|
+
);
|
|
159
|
+
const apiFetch = createApiFetch({
|
|
160
|
+
...baseOptions,
|
|
161
|
+
fetch: mock.fetch,
|
|
162
|
+
now: clock.now,
|
|
163
|
+
retry: { methods: ['GET', 'POST'] },
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
await expect(apiFetch('/write', { method: 'POST' })).rejects.toBeInstanceOf(HttpError);
|
|
167
|
+
const caught = await apiFetch('/read').catch((error: unknown) => error);
|
|
168
|
+
expect(caught).toBeInstanceOf(ApiUnavailableError);
|
|
169
|
+
expect(caught).toMatchObject({ retryAt: START + 5_000 });
|
|
170
|
+
expect(mock.requests).toHaveLength(1);
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
it('retries a keyed POST that opted in', async () => {
|
|
174
|
+
const clock = manualClock();
|
|
175
|
+
const mock = new MockFetch()
|
|
176
|
+
.enqueue(new Response(null, { status: 429, headers: { 'retry-after': '1' } }))
|
|
177
|
+
.enqueueJson({}, { status: 201 });
|
|
178
|
+
const apiFetch = createApiFetch({
|
|
179
|
+
...baseOptions,
|
|
180
|
+
fetch: mock.fetch,
|
|
181
|
+
now: clock.now,
|
|
182
|
+
retry: { ...clockedRetry(clock, []), methods: ['POST'] },
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
await expect(
|
|
186
|
+
apiFetch('/write', { method: 'POST', headers: { [IDEMPOTENCY_KEY_HEADER]: 'k' } }),
|
|
187
|
+
).resolves.toHaveProperty('status', 201);
|
|
188
|
+
expect(mock.requests).toHaveLength(2);
|
|
189
|
+
});
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
describe('per-origin cooldown', () => {
|
|
193
|
+
it('turns 50 concurrent calls after a 503 with Retry-After: 5 into no extra requests', async () => {
|
|
194
|
+
vi.useFakeTimers({ now: START });
|
|
195
|
+
let sent = 0;
|
|
196
|
+
const fetch: FetchImplementation = () => {
|
|
197
|
+
sent += 1;
|
|
198
|
+
return Promise.resolve(
|
|
199
|
+
sent === 1
|
|
200
|
+
? new Response(null, { status: 503, headers: { 'retry-after': '5' } })
|
|
201
|
+
: new Response('{}'),
|
|
202
|
+
);
|
|
203
|
+
};
|
|
204
|
+
const apiFetch = createApiFetch({ ...baseOptions, fetch });
|
|
205
|
+
|
|
206
|
+
const first = apiFetch('/feed');
|
|
207
|
+
await vi.advanceTimersByTimeAsync(0);
|
|
208
|
+
const results = await Promise.allSettled(Array.from({ length: 50 }, () => apiFetch('/feed')));
|
|
209
|
+
|
|
210
|
+
expect(sent).toBe(1);
|
|
211
|
+
expect(results.every((result) => result.status === 'rejected')).toBe(true);
|
|
212
|
+
expect(
|
|
213
|
+
results.every(
|
|
214
|
+
(result) => result.status === 'rejected' && isApiUnavailableError(result.reason),
|
|
215
|
+
),
|
|
216
|
+
).toBe(true);
|
|
217
|
+
|
|
218
|
+
await vi.advanceTimersByTimeAsync(5_000);
|
|
219
|
+
await expect(first).resolves.toHaveProperty('status', 200);
|
|
220
|
+
await expect(apiFetch('/feed')).resolves.toHaveProperty('status', 200);
|
|
221
|
+
expect(sent).toBe(3);
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
it('opens after 5 consecutive network failures and fails fast until the cooldown ends', async () => {
|
|
225
|
+
const clock = manualClock();
|
|
226
|
+
const mock = new MockFetch();
|
|
227
|
+
for (let index = 0; index < 5; index += 1) {
|
|
228
|
+
mock.enqueue(new TypeError('offline'));
|
|
229
|
+
}
|
|
230
|
+
mock.enqueueJson({ ok: true });
|
|
231
|
+
const apiFetch = createApiFetch({
|
|
232
|
+
...baseOptions,
|
|
233
|
+
fetch: mock.fetch,
|
|
234
|
+
now: clock.now,
|
|
235
|
+
retry: false,
|
|
236
|
+
cooldown: { networkFailureCooldownMs: 10_000, random: () => 0 },
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
for (let index = 0; index < 5; index += 1) {
|
|
240
|
+
await expect(apiFetch('/down')).rejects.toBeInstanceOf(NetworkError);
|
|
241
|
+
}
|
|
242
|
+
await expect(apiFetch('/down')).rejects.toMatchObject({ retryAt: START + 10_000 });
|
|
243
|
+
expect(mock.requests).toHaveLength(5);
|
|
244
|
+
|
|
245
|
+
clock.advance(10_000);
|
|
246
|
+
await expect(apiFetch('/down')).resolves.toHaveProperty('status', 200);
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
it('resets the failure count on any response', async () => {
|
|
250
|
+
const clock = manualClock();
|
|
251
|
+
const mock = new MockFetch();
|
|
252
|
+
for (let index = 0; index < 4; index += 1) {
|
|
253
|
+
mock.enqueue(new TypeError('offline'));
|
|
254
|
+
}
|
|
255
|
+
mock.enqueue(new Response(null, { status: 500 }));
|
|
256
|
+
for (let index = 0; index < 4; index += 1) {
|
|
257
|
+
mock.enqueue(new TypeError('offline'));
|
|
258
|
+
}
|
|
259
|
+
mock.enqueueJson({ ok: true });
|
|
260
|
+
const apiFetch = createApiFetch({
|
|
261
|
+
...baseOptions,
|
|
262
|
+
fetch: mock.fetch,
|
|
263
|
+
now: clock.now,
|
|
264
|
+
retry: false,
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
for (let index = 0; index < 9; index += 1) {
|
|
268
|
+
await apiFetch('/flaky').catch(() => undefined);
|
|
269
|
+
}
|
|
270
|
+
await expect(apiFetch('/flaky')).resolves.toHaveProperty('status', 200);
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
it('does not count caller aborts as network failures', async () => {
|
|
274
|
+
const clock = manualClock();
|
|
275
|
+
const apiFetch = createApiFetch({
|
|
276
|
+
...baseOptions,
|
|
277
|
+
fetch: hangingFetch(),
|
|
278
|
+
now: clock.now,
|
|
279
|
+
retry: false,
|
|
280
|
+
cooldown: { networkFailureThreshold: 1, random: () => 0 },
|
|
281
|
+
});
|
|
282
|
+
const controller = new AbortController();
|
|
283
|
+
const pending = apiFetch('/hang', { signal: controller.signal }).catch(
|
|
284
|
+
(error: unknown) => error,
|
|
285
|
+
);
|
|
286
|
+
controller.abort();
|
|
287
|
+
await expect(pending).resolves.toMatchObject({ aborted: true });
|
|
288
|
+
|
|
289
|
+
const mock = new MockFetch().enqueueJson({});
|
|
290
|
+
const next = createApiFetch({ ...baseOptions, fetch: mock.fetch, now: clock.now });
|
|
291
|
+
await expect(next('/ok')).resolves.toHaveProperty('status', 200);
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
it('fails fast instead of sleeping through a network cooldown during retries', async () => {
|
|
295
|
+
const clock = manualClock();
|
|
296
|
+
const delays: number[] = [];
|
|
297
|
+
const mock = new MockFetch().enqueue(new TypeError('offline')).enqueueJson({});
|
|
298
|
+
const apiFetch = createApiFetch({
|
|
299
|
+
...baseOptions,
|
|
300
|
+
fetch: mock.fetch,
|
|
301
|
+
now: clock.now,
|
|
302
|
+
retry: clockedRetry(clock, delays),
|
|
303
|
+
cooldown: { networkFailureThreshold: 1, random: () => 0 },
|
|
304
|
+
});
|
|
305
|
+
|
|
306
|
+
await expect(apiFetch('/down')).rejects.toBeInstanceOf(ApiUnavailableError);
|
|
307
|
+
expect(delays).toEqual([]);
|
|
308
|
+
expect(mock.requests).toHaveLength(1);
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
it('keeps other origins callable', async () => {
|
|
312
|
+
const clock = manualClock();
|
|
313
|
+
const mock = new MockFetch()
|
|
314
|
+
.enqueue(new Response(null, { status: 503, headers: { 'retry-after': '60' } }))
|
|
315
|
+
.enqueueJson({ ok: true });
|
|
316
|
+
const apiFetch = createApiFetch({
|
|
317
|
+
...baseOptions,
|
|
318
|
+
fetch: mock.fetch,
|
|
319
|
+
now: clock.now,
|
|
320
|
+
retry: false,
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
await expect(apiFetch('/a')).rejects.toBeInstanceOf(HttpError);
|
|
324
|
+
await expect(apiFetch('https://other.example.test/b')).resolves.toHaveProperty('status', 200);
|
|
325
|
+
await expect(apiFetch('/a')).rejects.toBeInstanceOf(ApiUnavailableError);
|
|
326
|
+
});
|
|
327
|
+
|
|
328
|
+
it('can be disabled', async () => {
|
|
329
|
+
const clock = manualClock();
|
|
330
|
+
const mock = new MockFetch()
|
|
331
|
+
.enqueue(new Response(null, { status: 503, headers: { 'retry-after': '60' } }))
|
|
332
|
+
.enqueueJson({ ok: true });
|
|
333
|
+
const apiFetch = createApiFetch({
|
|
334
|
+
...baseOptions,
|
|
335
|
+
fetch: mock.fetch,
|
|
336
|
+
now: clock.now,
|
|
337
|
+
retry: false,
|
|
338
|
+
cooldown: false,
|
|
339
|
+
});
|
|
340
|
+
|
|
341
|
+
await expect(apiFetch('/a')).rejects.toBeInstanceOf(HttpError);
|
|
342
|
+
await expect(apiFetch('/a')).resolves.toHaveProperty('status', 200);
|
|
343
|
+
});
|
|
344
|
+
});
|
package/src/retry.ts
CHANGED
|
@@ -7,6 +7,7 @@ export interface NormalizedRetryOptions {
|
|
|
7
7
|
readonly maxRetries: number;
|
|
8
8
|
readonly baseDelayMs: number;
|
|
9
9
|
readonly maxDelayMs: number;
|
|
10
|
+
readonly maxRetryAfterMs: number;
|
|
10
11
|
readonly methods: ReadonlySet<RetryableMethod>;
|
|
11
12
|
readonly random: () => number;
|
|
12
13
|
readonly sleep: (delayMs: number, signal: AbortSignal | null) => Promise<void>;
|
|
@@ -23,10 +24,14 @@ const RETRYABLE_METHODS = new Set<string>([
|
|
|
23
24
|
'PATCH',
|
|
24
25
|
]);
|
|
25
26
|
const RETRYABLE_STATUSES = new Set([502, 503, 504]);
|
|
27
|
+
const RETRY_AFTER_STATUSES = new Set([429, 503]);
|
|
28
|
+
const MS_PER_SECOND = 1_000;
|
|
29
|
+
const DELAY_SECONDS = /^\d+$/u;
|
|
26
30
|
|
|
27
31
|
const DEFAULT_MAX_RETRIES = 2;
|
|
28
32
|
const DEFAULT_BASE_DELAY_MS = 100;
|
|
29
33
|
const DEFAULT_MAX_DELAY_MS = 2_000;
|
|
34
|
+
const DEFAULT_MAX_RETRY_AFTER_MS = 30_000;
|
|
30
35
|
const DISABLED_RETRY: RetryOptions = { maxRetries: 0, methods: [] };
|
|
31
36
|
|
|
32
37
|
export function normalizeRetryOptions(
|
|
@@ -39,6 +44,8 @@ export function normalizeRetryOptions(
|
|
|
39
44
|
assertFiniteNonNegativeInteger(maxRetries, 'maxRetries');
|
|
40
45
|
assertFiniteNonNegative(baseDelayMs, 'baseDelayMs');
|
|
41
46
|
assertFiniteNonNegative(maxDelayMs, 'maxDelayMs');
|
|
47
|
+
const maxRetryAfterMs = configured.maxRetryAfterMs ?? DEFAULT_MAX_RETRY_AFTER_MS;
|
|
48
|
+
assertFiniteNonNegative(maxRetryAfterMs, 'maxRetryAfterMs');
|
|
42
49
|
const requestedMethods = configured.methods ?? ['GET', 'HEAD'];
|
|
43
50
|
const methods = new Set(
|
|
44
51
|
requestedMethods.filter((method): method is RetryableMethod => RETRYABLE_METHODS.has(method)),
|
|
@@ -47,6 +54,7 @@ export function normalizeRetryOptions(
|
|
|
47
54
|
maxRetries,
|
|
48
55
|
baseDelayMs,
|
|
49
56
|
maxDelayMs,
|
|
57
|
+
maxRetryAfterMs,
|
|
50
58
|
methods,
|
|
51
59
|
random: configured.random ?? Math.random,
|
|
52
60
|
sleep: configured.sleep ?? abortableSleep,
|
|
@@ -74,27 +82,63 @@ export function shouldRetryMethod(request: Request, retry: NormalizedRetryOption
|
|
|
74
82
|
return !KEYED_RETRY_ONLY.has(method) || request.headers.has(IDEMPOTENCY_KEY_HEADER);
|
|
75
83
|
}
|
|
76
84
|
|
|
85
|
+
/**
|
|
86
|
+
* Returns the clamped `Retry-After` delay of a `429` or `503`, or null when the response has none.
|
|
87
|
+
*
|
|
88
|
+
* Accepts delay-seconds and HTTP dates; a date in the past yields 0.
|
|
89
|
+
*/
|
|
90
|
+
export function retryAfterDelayMs(
|
|
91
|
+
response: Response,
|
|
92
|
+
retry: NormalizedRetryOptions,
|
|
93
|
+
now: number,
|
|
94
|
+
): number | null {
|
|
95
|
+
if (!RETRY_AFTER_STATUSES.has(response.status)) {
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
const delayMs = parseRetryAfterMs(response.headers.get('retry-after'), now);
|
|
99
|
+
return delayMs === null ? null : Math.min(delayMs, retry.maxRetryAfterMs);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function parseRetryAfterMs(value: string | null, now: number): number | null {
|
|
103
|
+
const trimmed = value?.trim() ?? '';
|
|
104
|
+
if (DELAY_SECONDS.test(trimmed)) {
|
|
105
|
+
return Number(trimmed) * MS_PER_SECOND;
|
|
106
|
+
}
|
|
107
|
+
const date = Date.parse(trimmed);
|
|
108
|
+
return Number.isNaN(date) ? null : Math.max(0, date - now);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Retries a `Retry-After` response, or a 502/503/504 without one, for retryable requests. */
|
|
77
112
|
export function shouldRetryResponse(
|
|
78
113
|
request: Request,
|
|
79
|
-
status: number,
|
|
114
|
+
response: { readonly status: number; readonly retryAfterMs: number | null },
|
|
80
115
|
retries: number,
|
|
81
116
|
retry: NormalizedRetryOptions,
|
|
82
117
|
): boolean {
|
|
83
118
|
return (
|
|
84
119
|
retries < retry.maxRetries &&
|
|
85
120
|
shouldRetryMethod(request, retry) &&
|
|
86
|
-
RETRYABLE_STATUSES.has(status)
|
|
121
|
+
(response.retryAfterMs !== null || RETRYABLE_STATUSES.has(response.status))
|
|
87
122
|
);
|
|
88
123
|
}
|
|
89
124
|
|
|
90
|
-
|
|
125
|
+
/** The next backoff delay: the server's `Retry-After` when present, else full jitter. */
|
|
126
|
+
export function nextRetryDelayMs(
|
|
91
127
|
retryIndex: number,
|
|
92
128
|
retry: NormalizedRetryOptions,
|
|
129
|
+
retryAfterMs: number | null,
|
|
130
|
+
): number {
|
|
131
|
+
return retryAfterMs ?? fullJitterBackoffMs(retryIndex, retry);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export async function retryDelay(
|
|
135
|
+
delayMs: number,
|
|
136
|
+
retry: NormalizedRetryOptions,
|
|
93
137
|
signal: AbortSignal,
|
|
94
138
|
requestId: string,
|
|
95
139
|
): Promise<void> {
|
|
96
140
|
try {
|
|
97
|
-
await retry.sleep(
|
|
141
|
+
await retry.sleep(delayMs, signal);
|
|
98
142
|
} catch (cause) {
|
|
99
143
|
throw new NetworkError('API request was aborted', requestId, cause, true);
|
|
100
144
|
}
|
package/src/timeout.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/** A signal that aborts when the parent aborts or the timeout elapses. */
|
|
2
|
+
export interface AttemptSignal {
|
|
3
|
+
readonly signal: AbortSignal;
|
|
4
|
+
timedOut(): boolean;
|
|
5
|
+
dispose(): void;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Links the caller's signal with a per-attempt timeout.
|
|
10
|
+
*
|
|
11
|
+
* `AbortSignal.any` is missing on React Native, so the two sources are linked by hand.
|
|
12
|
+
*/
|
|
13
|
+
export function attemptSignal(parent: AbortSignal, timeoutMs: number | null): AttemptSignal {
|
|
14
|
+
if (timeoutMs === null) {
|
|
15
|
+
return { signal: parent, timedOut: () => false, dispose: () => undefined };
|
|
16
|
+
}
|
|
17
|
+
const controller = new AbortController();
|
|
18
|
+
let expired = false;
|
|
19
|
+
const onParentAbort = (): void => {
|
|
20
|
+
controller.abort(parent.reason);
|
|
21
|
+
};
|
|
22
|
+
const timer = globalThis.setTimeout(() => {
|
|
23
|
+
expired = true;
|
|
24
|
+
controller.abort(new Error('API request timed out'));
|
|
25
|
+
}, timeoutMs);
|
|
26
|
+
if (parent.aborted) {
|
|
27
|
+
onParentAbort();
|
|
28
|
+
} else {
|
|
29
|
+
parent.addEventListener('abort', onParentAbort, { once: true });
|
|
30
|
+
}
|
|
31
|
+
return {
|
|
32
|
+
signal: controller.signal,
|
|
33
|
+
timedOut: () => expired,
|
|
34
|
+
dispose: () => {
|
|
35
|
+
globalThis.clearTimeout(timer);
|
|
36
|
+
parent.removeEventListener('abort', onParentAbort);
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
}
|