opticedge-cloud-utils 1.1.13 → 1.1.15

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.
@@ -1,416 +1,416 @@
1
- /* eslint-disable @typescript-eslint/no-explicit-any */
2
- // tests/retry.test.ts
3
-
4
- import axios from 'axios'
5
- import { retry, isRetryableDefault, sleep, isRetryableAxios } from '../src'
6
-
7
- describe('sleep()', () => {
8
- const realAbortController = global.AbortController
9
-
10
- afterEach(() => {
11
- // restore timers and AbortController if changed
12
- jest.useRealTimers()
13
- global.AbortController = realAbortController
14
- jest.clearAllMocks()
15
- })
16
-
17
- test('resolves after the specified delay', async () => {
18
- jest.useFakeTimers()
19
- const p = sleep(100)
20
-
21
- // advance timers by the sleep duration
22
- jest.advanceTimersByTime(100)
23
-
24
- // allow the Promise microtask queue to run
25
- await Promise.resolve()
26
-
27
- await expect(p).resolves.toBeUndefined()
28
- })
29
-
30
- test('rejects immediately if signal is already aborted', async () => {
31
- const ac = new AbortController()
32
- ac.abort()
33
-
34
- await expect(sleep(50, ac.signal)).rejects.toThrow('Aborted')
35
- })
36
-
37
- test('rejects when aborted after scheduling', async () => {
38
- jest.useFakeTimers()
39
- const ac = new AbortController()
40
-
41
- const p = sleep(1000, ac.signal)
42
-
43
- // abort after the sleep has been scheduled but before timeout
44
- ac.abort()
45
-
46
- // allow the event-loop microtasks to run
47
- await Promise.resolve()
48
-
49
- await expect(p).rejects.toThrow('Aborted')
50
-
51
- // advancing timers should not resolve the promise
52
- jest.advanceTimersByTime(1000)
53
- await Promise.resolve()
54
- await expect(p).rejects.toThrow('Aborted')
55
- })
56
- })
57
-
58
- describe('isRetryableDefault', () => {
59
- test('returns false for falsy errors (covers `if (!err) return false`)', () => {
60
- expect(isRetryableDefault(null)).toBe(false)
61
- expect(isRetryableDefault(undefined)).toBe(false)
62
- // Also check a falsy-but-not-nullish value is handled (should coerce to false at top)
63
- expect(isRetryableDefault(0 as unknown as any)).toBe(false)
64
- })
65
-
66
- test('returns false for an object with no retryable properties', () => {
67
- expect(isRetryableDefault({})).toBe(false)
68
- expect(isRetryableDefault({ foo: 'bar' })).toBe(false)
69
- })
70
-
71
- test('matches message containing "timeout" (case-insensitive)', () => {
72
- expect(isRetryableDefault(new Error('Request timed out'))).toBe(true)
73
- expect(isRetryableDefault(new Error('TIMEOUT occurred'))).toBe(true)
74
- expect(isRetryableDefault({ message: 'this is a timeout error' })).toBe(true)
75
- })
76
-
77
- test('matches message containing "temporary"', () => {
78
- expect(isRetryableDefault(new Error('Temporary failure contacting host'))).toBe(true)
79
- expect(isRetryableDefault({ message: 'temporary issue' })).toBe(true)
80
- })
81
-
82
- test('matches message containing "unavailable"', () => {
83
- expect(isRetryableDefault(new Error('Service Unavailable'))).toBe(true)
84
- expect(isRetryableDefault({ message: 'unavailable resource' })).toBe(true)
85
- })
86
-
87
- test('matches message containing "econnreset" or "etimedout" (substrings, case-insensitive)', () => {
88
- expect(isRetryableDefault(new Error('ECONNRESET by peer'))).toBe(true)
89
- expect(isRetryableDefault(new Error('econnreset'))).toBe(true)
90
- expect(isRetryableDefault(new Error('ETIMEDOUT waiting for response'))).toBe(true)
91
- expect(isRetryableDefault({ message: 'some ETIMEDOUT occurred' })).toBe(true)
92
- })
93
-
94
- test('does not treat unrelated messages as retryable', () => {
95
- expect(isRetryableDefault(new Error('Bad request'))).toBe(false)
96
- expect(isRetryableDefault({ message: 'invalid parameter provided' })).toBe(false)
97
- })
98
-
99
- test('still returns true when message sits alongside other properties (defensive)', () => {
100
- const errLike: any = {
101
- code: undefined,
102
- response: undefined,
103
- message: 'temporary network hiccup'
104
- }
105
- expect(isRetryableDefault(errLike)).toBe(true)
106
- })
107
- })
108
-
109
- describe('isRetryableAxios()', () => {
110
- // Helper to synthesize axios-like errors
111
- function makeAxiosError(payload: Partial<any> = {}) {
112
- // minimal axios-style error: flag + response optionally
113
- const err: any = new Error(payload.message ?? 'axios-err')
114
- err.isAxiosError = true
115
- if (Object.prototype.hasOwnProperty.call(payload, 'response')) {
116
- err.response = payload.response
117
- } else if (payload.response === undefined && payload.noResponse) {
118
- // explicit network/no-response: leave out response
119
- }
120
- if (payload.code) err.code = payload.code
121
- if (payload.message) err.message = payload.message
122
- return err
123
- }
124
-
125
- test('returns false when err is falsy', () => {
126
- expect(isRetryableAxios(null)).toBe(false)
127
- expect(isRetryableAxios(undefined)).toBe(false)
128
- // also check other falsy-ish values that shouldn't be considered retryable
129
- expect(isRetryableAxios(false as any)).toBe(false)
130
- expect(isRetryableAxios('' as any)).toBe(false)
131
- })
132
-
133
- test('returns true for network/no-response axios errors', () => {
134
- const networkErr = makeAxiosError({ noResponse: true })
135
- expect(axios.isAxiosError(networkErr)).toBe(true) // sanity check
136
- expect(isRetryableAxios(networkErr)).toBe(true)
137
- })
138
-
139
- test('returns true for 500 server error', () => {
140
- const serverErr = makeAxiosError({ response: { status: 500, data: {} } })
141
- expect(isRetryableAxios(serverErr)).toBe(true)
142
- })
143
-
144
- test('returns true for 503 server error', () => {
145
- const serverErr = makeAxiosError({ response: { status: 503, data: {} } })
146
- expect(isRetryableAxios(serverErr)).toBe(true)
147
- })
148
-
149
- test('returns true for 429 rate limit', () => {
150
- const rateErr = makeAxiosError({ response: { status: 429, data: {} } })
151
- expect(isRetryableAxios(rateErr)).toBe(true)
152
- })
153
-
154
- test('returns false for 400 client error (do not retry)', () => {
155
- const badReq = makeAxiosError({ response: { status: 400, data: {} } })
156
- expect(isRetryableAxios(badReq)).toBe(false)
157
- })
158
-
159
- test('delegates to isRetryableDefault for non-axios errors', () => {
160
- // make a network-style Node error that isRetryableDefault recognizes
161
- const nodeErr = { code: 'ECONNRESET', message: 'socket closed' }
162
- expect(isRetryableDefault(nodeErr)).toBe(true) // sanity
163
- expect(isRetryableAxios(nodeErr)).toBe(true)
164
- })
165
-
166
- test('returns false for non-retryable non-axios error', () => {
167
- const normalErr = new Error('something bad but not retryable')
168
- // isRetryableDefault likely returns false for a plain Error w/o hint
169
- expect(isRetryableDefault(normalErr)).toBe(false)
170
- expect(isRetryableAxios(normalErr)).toBe(false)
171
- })
172
- })
173
-
174
- describe('retry util', () => {
175
- afterEach(() => {
176
- jest.restoreAllMocks()
177
- })
178
-
179
- test('returns result when fn succeeds immediately', async () => {
180
- const fn = jest.fn(async () => 'ok')
181
- const res = await retry(fn, { retries: 3 })
182
- expect(res).toBe('ok')
183
- expect(fn).toHaveBeenCalledTimes(1)
184
- })
185
-
186
- test('retries on transient error and eventually succeeds; onRetry called expected times', async () => {
187
- // fail twice with retryable error (gRPC code 14), then succeed
188
- let calls = 0
189
- const fn = jest.fn(async () => {
190
- calls++
191
- if (calls <= 2) {
192
- const e: any = new Error('transient-gprc')
193
- e.code = 14
194
- throw e
195
- }
196
- return 'ok-after-retries'
197
- })
198
-
199
- const onRetry = jest.fn()
200
- // Make delays zero by forcing Math.random to 0 so tests are deterministic and fast
201
- const mathSpy = jest.spyOn(Math, 'random').mockReturnValue(0)
202
-
203
- const res = await retry(fn, { retries: 5, baseDelayMs: 10, onRetry })
204
- expect(res).toBe('ok-after-retries')
205
- expect(fn).toHaveBeenCalledTimes(3)
206
- // onRetry called for the 2 transient failures
207
- expect(onRetry).toHaveBeenCalledTimes(2)
208
-
209
- mathSpy.mockRestore()
210
- })
211
-
212
- test('non-retryable error is rethrown immediately', async () => {
213
- const fn = jest.fn(async () => {
214
- const e = new Error('bad request')
215
- // create non-retryable structure: status 400
216
- ;(e as any).status = 400
217
- throw e
218
- })
219
-
220
- await expect(retry(fn, { retries: 3 })).rejects.toThrow('bad request')
221
- expect(fn).toHaveBeenCalledTimes(1)
222
- })
223
-
224
- test('exhausts retries and throws final error preserving original', async () => {
225
- const original = new Error('permanent transient-like')
226
- ;(original as any).code = 14 // make it retryable
227
- const fn = jest.fn(async () => {
228
- throw original
229
- })
230
-
231
- // make delays 0 to run fast
232
- jest.spyOn(Math, 'random').mockReturnValue(0)
233
-
234
- await expect(retry(fn, { retries: 2, baseDelayMs: 1 })).rejects.toHaveProperty(
235
- 'original',
236
- original
237
- )
238
- // initial call + 2 retries = 3 attempts
239
- expect(fn).toHaveBeenCalledTimes(3)
240
- })
241
-
242
- test('isRetryableDefault recognizes common shapes', () => {
243
- const e1: any = new Error('econnreset happened')
244
- e1.code = 'ECONNRESET'
245
- expect(isRetryableDefault(e1)).toBe(true)
246
-
247
- const e2: any = new Error('http 500')
248
- e2.response = { status: 500 }
249
- expect(isRetryableDefault(e2)).toBe(true)
250
-
251
- const e3: any = new Error('not retryable')
252
- e3.status = 400
253
- expect(isRetryableDefault(e3)).toBe(false)
254
-
255
- const e4: any = new Error('gRPC unavailable')
256
- e4.code = 14
257
- expect(isRetryableDefault(e4)).toBe(true)
258
- })
259
-
260
- test('abort signal aborts immediately when already aborted', async () => {
261
- const controller = new AbortController()
262
- controller.abort()
263
- const fn = jest.fn(async () => 'should-not-run')
264
-
265
- await expect(retry(fn, { signal: controller.signal })).rejects.toThrow('Aborted')
266
- // function should not be called at all because we check signal at loop start
267
- expect(fn).toHaveBeenCalledTimes(0)
268
- })
269
-
270
- test('abort during wait causes rejection', async () => {
271
- // Function will fail once (retryable), then retry -> sleep -> we abort during sleep.
272
- let calls = 0
273
- const fn = jest.fn(async () => {
274
- calls++
275
- if (calls === 1) {
276
- const e: any = new Error('transient')
277
- e.code = 14
278
- throw e
279
- }
280
- return 'should-not-get-here'
281
- })
282
-
283
- // Make delay large so we can abort during sleep (but we will abort synchronously)
284
- jest.spyOn(Math, 'random').mockReturnValue(1) // picks the max exp
285
- const controller = new AbortController()
286
-
287
- // Start the retry but abort immediately after allowing the utility to start.
288
- // We do not await retry here yet; create a Promise and then abort and await
289
- const p = retry(fn, { retries: 3, baseDelayMs: 200, signal: controller.signal })
290
-
291
- // Abort immediately — this should cause the pending sleep to reject
292
- controller.abort()
293
-
294
- await expect(p).rejects.toThrow('Aborted')
295
- })
296
-
297
- test('abort during wait causes rejection and triggers onAbort (clears timeout)', async () => {
298
- // Function will fail once (retryable), then retry -> sleep -> we abort during sleep.
299
- let calls = 0
300
- const fn = jest.fn(async () => {
301
- calls++
302
- if (calls === 1) {
303
- const e: any = new Error('transient')
304
- e.code = 14
305
- throw e
306
- }
307
- return 'should-not-get-here'
308
- })
309
-
310
- // Make sure there is a non-zero delay so sleep schedules a timer
311
- jest.spyOn(Math, 'random').mockReturnValue(0.5)
312
- const controller = new AbortController()
313
-
314
- // Start the retry (it will throw once, then call sleep)
315
- const p = retry(fn, { retries: 3, baseDelayMs: 200, signal: controller.signal })
316
-
317
- // Wait a tick so `sleep` has a chance to attach the abort listener and call setTimeout.
318
- // Using setTimeout 0 (or small timeout) guarantees the timer and listener are attached.
319
- await new Promise(resolve => setTimeout(resolve, 0))
320
-
321
- // Now abort — this should call the onAbort handler inside sleep which clears the timeout
322
- controller.abort()
323
-
324
- await expect(p).rejects.toThrow('Aborted')
325
-
326
- // restore mocks
327
- ;(Math.random as jest.Mock).mockRestore()
328
- })
329
-
330
- test('respects timeoutMs and breaks before waiting (covers timeout check)', async () => {
331
- // Make the wrapped fn throw a retryable error once
332
- const original = new Error('transient-timeout')
333
- ;(original as any).code = 14 // make it retryable via isRetryableDefault
334
- const fn = jest.fn(async () => {
335
- throw original
336
- })
337
-
338
- // Force Math.random to 1 so delay === exp (max for that attempt)
339
- const mathSpy = jest.spyOn(Math, 'random').mockReturnValue(1)
340
-
341
- // Use a baseDelayMs larger than timeoutMs so elapsed + delay > timeoutMs triggers the "break"
342
- await expect(
343
- retry(fn, {
344
- retries: 5,
345
- baseDelayMs: 50, // exp for attempt 1 = 50
346
- timeoutMs: 10 // 50 > 10 so we should break before sleeping
347
- })
348
- ).rejects.toHaveProperty('original', original)
349
-
350
- // fn should only have been called once (no retry/sleep occurred)
351
- expect(fn).toHaveBeenCalledTimes(1)
352
-
353
- mathSpy.mockRestore()
354
- })
355
-
356
- test('omitted opts uses default retries and eventually succeeds', async () => {
357
- // Fail twice with retryable error (gRPC code 14), then succeed
358
- let calls = 0
359
- const fn = jest.fn(async () => {
360
- calls++
361
- if (calls <= 2) {
362
- const e: any = new Error('transient')
363
- e.code = 14
364
- throw e
365
- }
366
- return 'ok-defaults'
367
- })
368
-
369
- // Make delays deterministic & small (Math.random = 0 -> delay = 0)
370
- jest.spyOn(Math, 'random').mockReturnValue(0)
371
-
372
- const res = await retry(fn) // <- call WITHOUT opts to exercise default param
373
- expect(res).toBe('ok-defaults')
374
-
375
- // Called initial + 2 retries = 3 times
376
- expect(fn).toHaveBeenCalledTimes(3)
377
- ;(Math.random as jest.Mock).mockRestore()
378
- })
379
-
380
- test('omitted opts exhausts default retries (5 attempts total) and throws', async () => {
381
- const original = new Error('always-transient')
382
- ;(original as any).code = 14 // make it retryable
383
- const fn = jest.fn(async () => {
384
- throw original
385
- })
386
-
387
- // Make delays 0 so test runs fast
388
- jest.spyOn(Math, 'random').mockReturnValue(0)
389
-
390
- // Default retries is 4 -> total attempts = 5
391
- await expect(retry(fn)).rejects.toHaveProperty('original', original)
392
- expect(fn).toHaveBeenCalledTimes(5)
393
- ;(Math.random as jest.Mock).mockRestore()
394
- })
395
-
396
- test('final error message falls back to String(lastErr) when lastErr.message is undefined', async () => {
397
- // original is a plain object (no .message)
398
- const original: any = { code: 14, detail: 'plain-object-no-message' }
399
-
400
- const fn = jest.fn(async () => {
401
- throw original // will be assigned to lastErr in retry()
402
- })
403
-
404
- // Make delays deterministic & fast
405
- const mathSpy = jest.spyOn(Math, 'random').mockReturnValue(0)
406
-
407
- // retries = 1 -> attempt will be 1 in finalErr message
408
- await expect(retry(fn, { retries: 1, baseDelayMs: 1 })).rejects.toMatchObject({
409
- message: expect.stringContaining('[object Object]'),
410
- // Ensure original error was preserved on the thrown final error
411
- original
412
- })
413
-
414
- mathSpy.mockRestore()
415
- })
416
- })
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ // tests/retry.test.ts
3
+
4
+ import axios from 'axios'
5
+ import { retry, isRetryableDefault, sleep, isRetryableAxios } from '../src'
6
+
7
+ describe('sleep()', () => {
8
+ const realAbortController = global.AbortController
9
+
10
+ afterEach(() => {
11
+ // restore timers and AbortController if changed
12
+ jest.useRealTimers()
13
+ global.AbortController = realAbortController
14
+ jest.clearAllMocks()
15
+ })
16
+
17
+ test('resolves after the specified delay', async () => {
18
+ jest.useFakeTimers()
19
+ const p = sleep(100)
20
+
21
+ // advance timers by the sleep duration
22
+ jest.advanceTimersByTime(100)
23
+
24
+ // allow the Promise microtask queue to run
25
+ await Promise.resolve()
26
+
27
+ await expect(p).resolves.toBeUndefined()
28
+ })
29
+
30
+ test('rejects immediately if signal is already aborted', async () => {
31
+ const ac = new AbortController()
32
+ ac.abort()
33
+
34
+ await expect(sleep(50, ac.signal)).rejects.toThrow('Aborted')
35
+ })
36
+
37
+ test('rejects when aborted after scheduling', async () => {
38
+ jest.useFakeTimers()
39
+ const ac = new AbortController()
40
+
41
+ const p = sleep(1000, ac.signal)
42
+
43
+ // abort after the sleep has been scheduled but before timeout
44
+ ac.abort()
45
+
46
+ // allow the event-loop microtasks to run
47
+ await Promise.resolve()
48
+
49
+ await expect(p).rejects.toThrow('Aborted')
50
+
51
+ // advancing timers should not resolve the promise
52
+ jest.advanceTimersByTime(1000)
53
+ await Promise.resolve()
54
+ await expect(p).rejects.toThrow('Aborted')
55
+ })
56
+ })
57
+
58
+ describe('isRetryableDefault', () => {
59
+ test('returns false for falsy errors (covers `if (!err) return false`)', () => {
60
+ expect(isRetryableDefault(null)).toBe(false)
61
+ expect(isRetryableDefault(undefined)).toBe(false)
62
+ // Also check a falsy-but-not-nullish value is handled (should coerce to false at top)
63
+ expect(isRetryableDefault(0 as unknown as any)).toBe(false)
64
+ })
65
+
66
+ test('returns false for an object with no retryable properties', () => {
67
+ expect(isRetryableDefault({})).toBe(false)
68
+ expect(isRetryableDefault({ foo: 'bar' })).toBe(false)
69
+ })
70
+
71
+ test('matches message containing "timeout" (case-insensitive)', () => {
72
+ expect(isRetryableDefault(new Error('Request timed out'))).toBe(true)
73
+ expect(isRetryableDefault(new Error('TIMEOUT occurred'))).toBe(true)
74
+ expect(isRetryableDefault({ message: 'this is a timeout error' })).toBe(true)
75
+ })
76
+
77
+ test('matches message containing "temporary"', () => {
78
+ expect(isRetryableDefault(new Error('Temporary failure contacting host'))).toBe(true)
79
+ expect(isRetryableDefault({ message: 'temporary issue' })).toBe(true)
80
+ })
81
+
82
+ test('matches message containing "unavailable"', () => {
83
+ expect(isRetryableDefault(new Error('Service Unavailable'))).toBe(true)
84
+ expect(isRetryableDefault({ message: 'unavailable resource' })).toBe(true)
85
+ })
86
+
87
+ test('matches message containing "econnreset" or "etimedout" (substrings, case-insensitive)', () => {
88
+ expect(isRetryableDefault(new Error('ECONNRESET by peer'))).toBe(true)
89
+ expect(isRetryableDefault(new Error('econnreset'))).toBe(true)
90
+ expect(isRetryableDefault(new Error('ETIMEDOUT waiting for response'))).toBe(true)
91
+ expect(isRetryableDefault({ message: 'some ETIMEDOUT occurred' })).toBe(true)
92
+ })
93
+
94
+ test('does not treat unrelated messages as retryable', () => {
95
+ expect(isRetryableDefault(new Error('Bad request'))).toBe(false)
96
+ expect(isRetryableDefault({ message: 'invalid parameter provided' })).toBe(false)
97
+ })
98
+
99
+ test('still returns true when message sits alongside other properties (defensive)', () => {
100
+ const errLike: any = {
101
+ code: undefined,
102
+ response: undefined,
103
+ message: 'temporary network hiccup'
104
+ }
105
+ expect(isRetryableDefault(errLike)).toBe(true)
106
+ })
107
+ })
108
+
109
+ describe('isRetryableAxios()', () => {
110
+ // Helper to synthesize axios-like errors
111
+ function makeAxiosError(payload: Partial<any> = {}) {
112
+ // minimal axios-style error: flag + response optionally
113
+ const err: any = new Error(payload.message ?? 'axios-err')
114
+ err.isAxiosError = true
115
+ if (Object.prototype.hasOwnProperty.call(payload, 'response')) {
116
+ err.response = payload.response
117
+ } else if (payload.response === undefined && payload.noResponse) {
118
+ // explicit network/no-response: leave out response
119
+ }
120
+ if (payload.code) err.code = payload.code
121
+ if (payload.message) err.message = payload.message
122
+ return err
123
+ }
124
+
125
+ test('returns false when err is falsy', () => {
126
+ expect(isRetryableAxios(null)).toBe(false)
127
+ expect(isRetryableAxios(undefined)).toBe(false)
128
+ // also check other falsy-ish values that shouldn't be considered retryable
129
+ expect(isRetryableAxios(false as any)).toBe(false)
130
+ expect(isRetryableAxios('' as any)).toBe(false)
131
+ })
132
+
133
+ test('returns true for network/no-response axios errors', () => {
134
+ const networkErr = makeAxiosError({ noResponse: true })
135
+ expect(axios.isAxiosError(networkErr)).toBe(true) // sanity check
136
+ expect(isRetryableAxios(networkErr)).toBe(true)
137
+ })
138
+
139
+ test('returns true for 500 server error', () => {
140
+ const serverErr = makeAxiosError({ response: { status: 500, data: {} } })
141
+ expect(isRetryableAxios(serverErr)).toBe(true)
142
+ })
143
+
144
+ test('returns true for 503 server error', () => {
145
+ const serverErr = makeAxiosError({ response: { status: 503, data: {} } })
146
+ expect(isRetryableAxios(serverErr)).toBe(true)
147
+ })
148
+
149
+ test('returns true for 429 rate limit', () => {
150
+ const rateErr = makeAxiosError({ response: { status: 429, data: {} } })
151
+ expect(isRetryableAxios(rateErr)).toBe(true)
152
+ })
153
+
154
+ test('returns false for 400 client error (do not retry)', () => {
155
+ const badReq = makeAxiosError({ response: { status: 400, data: {} } })
156
+ expect(isRetryableAxios(badReq)).toBe(false)
157
+ })
158
+
159
+ test('delegates to isRetryableDefault for non-axios errors', () => {
160
+ // make a network-style Node error that isRetryableDefault recognizes
161
+ const nodeErr = { code: 'ECONNRESET', message: 'socket closed' }
162
+ expect(isRetryableDefault(nodeErr)).toBe(true) // sanity
163
+ expect(isRetryableAxios(nodeErr)).toBe(true)
164
+ })
165
+
166
+ test('returns false for non-retryable non-axios error', () => {
167
+ const normalErr = new Error('something bad but not retryable')
168
+ // isRetryableDefault likely returns false for a plain Error w/o hint
169
+ expect(isRetryableDefault(normalErr)).toBe(false)
170
+ expect(isRetryableAxios(normalErr)).toBe(false)
171
+ })
172
+ })
173
+
174
+ describe('retry util', () => {
175
+ afterEach(() => {
176
+ jest.restoreAllMocks()
177
+ })
178
+
179
+ test('returns result when fn succeeds immediately', async () => {
180
+ const fn = jest.fn(async () => 'ok')
181
+ const res = await retry(fn, { retries: 3 })
182
+ expect(res).toBe('ok')
183
+ expect(fn).toHaveBeenCalledTimes(1)
184
+ })
185
+
186
+ test('retries on transient error and eventually succeeds; onRetry called expected times', async () => {
187
+ // fail twice with retryable error (gRPC code 14), then succeed
188
+ let calls = 0
189
+ const fn = jest.fn(async () => {
190
+ calls++
191
+ if (calls <= 2) {
192
+ const e: any = new Error('transient-gprc')
193
+ e.code = 14
194
+ throw e
195
+ }
196
+ return 'ok-after-retries'
197
+ })
198
+
199
+ const onRetry = jest.fn()
200
+ // Make delays zero by forcing Math.random to 0 so tests are deterministic and fast
201
+ const mathSpy = jest.spyOn(Math, 'random').mockReturnValue(0)
202
+
203
+ const res = await retry(fn, { retries: 5, baseDelayMs: 10, onRetry })
204
+ expect(res).toBe('ok-after-retries')
205
+ expect(fn).toHaveBeenCalledTimes(3)
206
+ // onRetry called for the 2 transient failures
207
+ expect(onRetry).toHaveBeenCalledTimes(2)
208
+
209
+ mathSpy.mockRestore()
210
+ })
211
+
212
+ test('non-retryable error is rethrown immediately', async () => {
213
+ const fn = jest.fn(async () => {
214
+ const e = new Error('bad request')
215
+ // create non-retryable structure: status 400
216
+ ;(e as any).status = 400
217
+ throw e
218
+ })
219
+
220
+ await expect(retry(fn, { retries: 3 })).rejects.toThrow('bad request')
221
+ expect(fn).toHaveBeenCalledTimes(1)
222
+ })
223
+
224
+ test('exhausts retries and throws final error preserving original', async () => {
225
+ const original = new Error('permanent transient-like')
226
+ ;(original as any).code = 14 // make it retryable
227
+ const fn = jest.fn(async () => {
228
+ throw original
229
+ })
230
+
231
+ // make delays 0 to run fast
232
+ jest.spyOn(Math, 'random').mockReturnValue(0)
233
+
234
+ await expect(retry(fn, { retries: 2, baseDelayMs: 1 })).rejects.toHaveProperty(
235
+ 'original',
236
+ original
237
+ )
238
+ // initial call + 2 retries = 3 attempts
239
+ expect(fn).toHaveBeenCalledTimes(3)
240
+ })
241
+
242
+ test('isRetryableDefault recognizes common shapes', () => {
243
+ const e1: any = new Error('econnreset happened')
244
+ e1.code = 'ECONNRESET'
245
+ expect(isRetryableDefault(e1)).toBe(true)
246
+
247
+ const e2: any = new Error('http 500')
248
+ e2.response = { status: 500 }
249
+ expect(isRetryableDefault(e2)).toBe(true)
250
+
251
+ const e3: any = new Error('not retryable')
252
+ e3.status = 400
253
+ expect(isRetryableDefault(e3)).toBe(false)
254
+
255
+ const e4: any = new Error('gRPC unavailable')
256
+ e4.code = 14
257
+ expect(isRetryableDefault(e4)).toBe(true)
258
+ })
259
+
260
+ test('abort signal aborts immediately when already aborted', async () => {
261
+ const controller = new AbortController()
262
+ controller.abort()
263
+ const fn = jest.fn(async () => 'should-not-run')
264
+
265
+ await expect(retry(fn, { signal: controller.signal })).rejects.toThrow('Aborted')
266
+ // function should not be called at all because we check signal at loop start
267
+ expect(fn).toHaveBeenCalledTimes(0)
268
+ })
269
+
270
+ test('abort during wait causes rejection', async () => {
271
+ // Function will fail once (retryable), then retry -> sleep -> we abort during sleep.
272
+ let calls = 0
273
+ const fn = jest.fn(async () => {
274
+ calls++
275
+ if (calls === 1) {
276
+ const e: any = new Error('transient')
277
+ e.code = 14
278
+ throw e
279
+ }
280
+ return 'should-not-get-here'
281
+ })
282
+
283
+ // Make delay large so we can abort during sleep (but we will abort synchronously)
284
+ jest.spyOn(Math, 'random').mockReturnValue(1) // picks the max exp
285
+ const controller = new AbortController()
286
+
287
+ // Start the retry but abort immediately after allowing the utility to start.
288
+ // We do not await retry here yet; create a Promise and then abort and await
289
+ const p = retry(fn, { retries: 3, baseDelayMs: 200, signal: controller.signal })
290
+
291
+ // Abort immediately — this should cause the pending sleep to reject
292
+ controller.abort()
293
+
294
+ await expect(p).rejects.toThrow('Aborted')
295
+ })
296
+
297
+ test('abort during wait causes rejection and triggers onAbort (clears timeout)', async () => {
298
+ // Function will fail once (retryable), then retry -> sleep -> we abort during sleep.
299
+ let calls = 0
300
+ const fn = jest.fn(async () => {
301
+ calls++
302
+ if (calls === 1) {
303
+ const e: any = new Error('transient')
304
+ e.code = 14
305
+ throw e
306
+ }
307
+ return 'should-not-get-here'
308
+ })
309
+
310
+ // Make sure there is a non-zero delay so sleep schedules a timer
311
+ jest.spyOn(Math, 'random').mockReturnValue(0.5)
312
+ const controller = new AbortController()
313
+
314
+ // Start the retry (it will throw once, then call sleep)
315
+ const p = retry(fn, { retries: 3, baseDelayMs: 200, signal: controller.signal })
316
+
317
+ // Wait a tick so `sleep` has a chance to attach the abort listener and call setTimeout.
318
+ // Using setTimeout 0 (or small timeout) guarantees the timer and listener are attached.
319
+ await new Promise(resolve => setTimeout(resolve, 0))
320
+
321
+ // Now abort — this should call the onAbort handler inside sleep which clears the timeout
322
+ controller.abort()
323
+
324
+ await expect(p).rejects.toThrow('Aborted')
325
+
326
+ // restore mocks
327
+ ;(Math.random as jest.Mock).mockRestore()
328
+ })
329
+
330
+ test('respects timeoutMs and breaks before waiting (covers timeout check)', async () => {
331
+ // Make the wrapped fn throw a retryable error once
332
+ const original = new Error('transient-timeout')
333
+ ;(original as any).code = 14 // make it retryable via isRetryableDefault
334
+ const fn = jest.fn(async () => {
335
+ throw original
336
+ })
337
+
338
+ // Force Math.random to 1 so delay === exp (max for that attempt)
339
+ const mathSpy = jest.spyOn(Math, 'random').mockReturnValue(1)
340
+
341
+ // Use a baseDelayMs larger than timeoutMs so elapsed + delay > timeoutMs triggers the "break"
342
+ await expect(
343
+ retry(fn, {
344
+ retries: 5,
345
+ baseDelayMs: 50, // exp for attempt 1 = 50
346
+ timeoutMs: 10 // 50 > 10 so we should break before sleeping
347
+ })
348
+ ).rejects.toHaveProperty('original', original)
349
+
350
+ // fn should only have been called once (no retry/sleep occurred)
351
+ expect(fn).toHaveBeenCalledTimes(1)
352
+
353
+ mathSpy.mockRestore()
354
+ })
355
+
356
+ test('omitted opts uses default retries and eventually succeeds', async () => {
357
+ // Fail twice with retryable error (gRPC code 14), then succeed
358
+ let calls = 0
359
+ const fn = jest.fn(async () => {
360
+ calls++
361
+ if (calls <= 2) {
362
+ const e: any = new Error('transient')
363
+ e.code = 14
364
+ throw e
365
+ }
366
+ return 'ok-defaults'
367
+ })
368
+
369
+ // Make delays deterministic & small (Math.random = 0 -> delay = 0)
370
+ jest.spyOn(Math, 'random').mockReturnValue(0)
371
+
372
+ const res = await retry(fn) // <- call WITHOUT opts to exercise default param
373
+ expect(res).toBe('ok-defaults')
374
+
375
+ // Called initial + 2 retries = 3 times
376
+ expect(fn).toHaveBeenCalledTimes(3)
377
+ ;(Math.random as jest.Mock).mockRestore()
378
+ })
379
+
380
+ test('omitted opts exhausts default retries (5 attempts total) and throws', async () => {
381
+ const original = new Error('always-transient')
382
+ ;(original as any).code = 14 // make it retryable
383
+ const fn = jest.fn(async () => {
384
+ throw original
385
+ })
386
+
387
+ // Make delays 0 so test runs fast
388
+ jest.spyOn(Math, 'random').mockReturnValue(0)
389
+
390
+ // Default retries is 4 -> total attempts = 5
391
+ await expect(retry(fn)).rejects.toHaveProperty('original', original)
392
+ expect(fn).toHaveBeenCalledTimes(5)
393
+ ;(Math.random as jest.Mock).mockRestore()
394
+ })
395
+
396
+ test('final error message falls back to String(lastErr) when lastErr.message is undefined', async () => {
397
+ // original is a plain object (no .message)
398
+ const original: any = { code: 14, detail: 'plain-object-no-message' }
399
+
400
+ const fn = jest.fn(async () => {
401
+ throw original // will be assigned to lastErr in retry()
402
+ })
403
+
404
+ // Make delays deterministic & fast
405
+ const mathSpy = jest.spyOn(Math, 'random').mockReturnValue(0)
406
+
407
+ // retries = 1 -> attempt will be 1 in finalErr message
408
+ await expect(retry(fn, { retries: 1, baseDelayMs: 1 })).rejects.toMatchObject({
409
+ message: expect.stringContaining('[object Object]'),
410
+ // Ensure original error was preserved on the thrown final error
411
+ original
412
+ })
413
+
414
+ mathSpy.mockRestore()
415
+ })
416
+ })