-
Notifications
You must be signed in to change notification settings - Fork 72
Expand file tree
/
Copy pathfetch-retry.test.ts
More file actions
278 lines (229 loc) · 8.96 KB
/
Copy pathfetch-retry.test.ts
File metadata and controls
278 lines (229 loc) · 8.96 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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { fetchWithRetry, computeRetryDelay, type RetryOptions } from '../src/utils/fetch-retry'
describe('computeRetryDelay', () => {
// computeRetryDelay takes the resolved options without `caller`.
const defaults: Required<Omit<RetryOptions, 'caller'>> = {
maxRetries: 3,
baseDelayMs: 1000,
backoffFactor: 2,
maxDelayMs: 30_000,
jitter: false
}
it('computes exponential delays without jitter', () => {
expect(computeRetryDelay(0, defaults)).toBe(1000) // 1000 * 2^0
expect(computeRetryDelay(1, defaults)).toBe(2000) // 1000 * 2^1
expect(computeRetryDelay(2, defaults)).toBe(4000) // 1000 * 2^2
expect(computeRetryDelay(3, defaults)).toBe(8000) // 1000 * 2^3
})
it('caps delay at maxDelayMs', () => {
expect(computeRetryDelay(5, defaults)).toBe(30_000) // 1000 * 2^5 = 32000, capped at 30000
})
it('respects Retry-After header (seconds)', () => {
expect(computeRetryDelay(0, defaults, '5')).toBe(5000)
expect(computeRetryDelay(0, defaults, '2')).toBe(2000)
})
it('caps Retry-After at maxDelayMs', () => {
expect(computeRetryDelay(0, defaults, '60')).toBe(30_000) // 60s capped at 30s
})
it('ignores invalid Retry-After values', () => {
expect(computeRetryDelay(0, defaults, 'invalid')).toBe(1000)
expect(computeRetryDelay(0, defaults, '0')).toBe(1000)
expect(computeRetryDelay(0, defaults, '-1')).toBe(1000)
})
it('applies jitter between 50% and 100%', () => {
const opts = { ...defaults, jitter: true }
const results = new Set<number>()
for (let i = 0; i < 50; i++) {
const delay = computeRetryDelay(0, opts)
expect(delay).toBeGreaterThanOrEqual(500)
expect(delay).toBeLessThanOrEqual(1000)
results.add(Math.round(delay))
}
// With 50 samples, we should get some variation
expect(results.size).toBeGreaterThan(1)
})
})
describe('fetchWithRetry', () => {
let originalFetch: typeof globalThis.fetch
let warnSpy: ReturnType<typeof vi.spyOn>
let errorSpy: ReturnType<typeof vi.spyOn>
beforeEach(() => {
originalFetch = globalThis.fetch
warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
})
afterEach(() => {
globalThis.fetch = originalFetch
vi.restoreAllMocks()
})
it('returns immediately on 200', async () => {
const mockResponse = new Response('ok', { status: 200 })
globalThis.fetch = vi.fn().mockResolvedValue(mockResponse)
const result = await fetchWithRetry('https://api.example.com/test')
expect(result.status).toBe(200)
expect(globalThis.fetch).toHaveBeenCalledTimes(1)
})
it('returns immediately on non-429 errors (e.g. 401)', async () => {
const mockResponse = new Response('unauthorized', { status: 401 })
globalThis.fetch = vi.fn().mockResolvedValue(mockResponse)
const result = await fetchWithRetry('https://api.example.com/test')
expect(result.status).toBe(401)
expect(globalThis.fetch).toHaveBeenCalledTimes(1)
})
it('logs caller and url when retrying 429s', async () => {
const mock = vi
.fn()
.mockResolvedValueOnce(new Response('rate limited', { status: 429 }))
.mockResolvedValueOnce(new Response('ok', { status: 200 }))
globalThis.fetch = mock
const result = await fetchWithRetry('https://api.example.com/accounts', undefined, {
maxRetries: 1,
baseDelayMs: 1,
jitter: false,
caller: 'oauth_callback_identity_probe'
})
expect(result.status).toBe(200)
expect(warnSpy).toHaveBeenCalledWith(
'fetchWithRetry: 429 caller=oauth_callback_identity_probe url=https://api.example.com/accounts on attempt 1/2, retrying in 1ms'
)
})
it('retries on 429 and succeeds', async () => {
const mock = vi
.fn()
.mockResolvedValueOnce(new Response('rate limited', { status: 429 }))
.mockResolvedValueOnce(new Response('ok', { status: 200 }))
globalThis.fetch = mock
const result = await fetchWithRetry('https://api.example.com/test', undefined, {
maxRetries: 3,
baseDelayMs: 10, // fast for tests
jitter: false
})
expect(result.status).toBe(200)
expect(mock).toHaveBeenCalledTimes(2)
})
it('logs an error after exhausting 429 retries', async () => {
const mock = vi.fn().mockResolvedValue(new Response('rate limited', { status: 429 }))
globalThis.fetch = mock
const result = await fetchWithRetry('https://api.example.com/accounts', undefined, {
maxRetries: 0
})
expect(result.status).toBe(429)
expect(errorSpy).toHaveBeenCalledWith(
'fetchWithRetry: failed url=https://api.example.com/accounts after 1 attempts with status 429'
)
})
it('returns last 429 response after exhausting retries', async () => {
const mock = vi.fn().mockResolvedValue(new Response('rate limited', { status: 429 }))
globalThis.fetch = mock
const result = await fetchWithRetry('https://api.example.com/test', undefined, {
maxRetries: 2,
baseDelayMs: 10,
jitter: false
})
expect(result.status).toBe(429)
// 1 initial + 2 retries = 3 total
expect(mock).toHaveBeenCalledTimes(3)
})
it('retries on network errors and succeeds', async () => {
const mock = vi
.fn()
.mockRejectedValueOnce(new Error('network failure'))
.mockResolvedValueOnce(new Response('ok', { status: 200 }))
globalThis.fetch = mock
const result = await fetchWithRetry('https://api.example.com/test', undefined, {
maxRetries: 3,
baseDelayMs: 10,
jitter: false
})
expect(result.status).toBe(200)
expect(mock).toHaveBeenCalledTimes(2)
})
it('logs an error after exhausting network retries', async () => {
const error = new Error('network failure')
const mock = vi.fn().mockRejectedValue(error)
globalThis.fetch = mock
await expect(
fetchWithRetry('https://api.example.com/accounts', undefined, {
maxRetries: 0
})
).rejects.toThrow('network failure')
expect(errorSpy).toHaveBeenCalledWith(
'fetchWithRetry: failed url=https://api.example.com/accounts after 1 attempts',
error
)
})
it('throws after exhausting retries on network errors', async () => {
const mock = vi.fn().mockRejectedValue(new Error('network failure'))
globalThis.fetch = mock
await expect(
fetchWithRetry('https://api.example.com/test', undefined, {
maxRetries: 1,
baseDelayMs: 10,
jitter: false
})
).rejects.toThrow('network failure')
// 1 initial + 1 retry = 2 total
expect(mock).toHaveBeenCalledTimes(2)
})
it('passes through request init options', async () => {
const mockResponse = new Response('ok', { status: 200 })
globalThis.fetch = vi.fn().mockResolvedValue(mockResponse)
await fetchWithRetry('https://api.example.com/test', {
method: 'POST',
headers: { Authorization: 'Bearer token' },
body: '{"key":"value"}'
})
expect(globalThis.fetch).toHaveBeenCalledWith('https://api.example.com/test', {
method: 'POST',
headers: { Authorization: 'Bearer token' },
body: '{"key":"value"}'
})
})
it('respects Retry-After header from 429 response', async () => {
const headers429 = new Headers({ 'Retry-After': '1' })
const mock = vi
.fn()
.mockResolvedValueOnce(new Response('rate limited', { status: 429, headers: headers429 }))
.mockResolvedValueOnce(new Response('ok', { status: 200 }))
globalThis.fetch = mock
const start = Date.now()
const result = await fetchWithRetry('https://api.example.com/test', undefined, {
maxRetries: 3,
baseDelayMs: 10, // would be 10ms without Retry-After
jitter: false
})
const elapsed = Date.now() - start
expect(result.status).toBe(200)
// Retry-After: 1 means 1000ms minimum
expect(elapsed).toBeGreaterThanOrEqual(900) // allow small timing variance
})
it('handles mixed network errors and 429s', async () => {
const mock = vi
.fn()
.mockRejectedValueOnce(new Error('network failure'))
.mockResolvedValueOnce(new Response('rate limited', { status: 429 }))
.mockResolvedValueOnce(new Response('ok', { status: 200 }))
globalThis.fetch = mock
const result = await fetchWithRetry('https://api.example.com/test', undefined, {
maxRetries: 3,
baseDelayMs: 10,
jitter: false
})
expect(result.status).toBe(200)
expect(mock).toHaveBeenCalledTimes(3)
})
it('returns 429 if last response was 429 even after network errors', async () => {
const mock = vi
.fn()
.mockRejectedValueOnce(new Error('network failure'))
.mockResolvedValueOnce(new Response('rate limited', { status: 429 }))
globalThis.fetch = mock
const result = await fetchWithRetry('https://api.example.com/test', undefined, {
maxRetries: 1,
baseDelayMs: 10,
jitter: false
})
expect(result.status).toBe(429)
expect(mock).toHaveBeenCalledTimes(2)
})
})