@tanstack/pacer 0.15.4 → 0.16.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.
Files changed (92) hide show
  1. package/dist/cjs/async-batcher.cjs +66 -4
  2. package/dist/cjs/async-batcher.cjs.map +1 -1
  3. package/dist/cjs/async-batcher.d.cts +97 -16
  4. package/dist/cjs/async-debouncer.cjs +53 -18
  5. package/dist/cjs/async-debouncer.cjs.map +1 -1
  6. package/dist/cjs/async-debouncer.d.cts +79 -9
  7. package/dist/cjs/async-queuer.cjs +58 -1
  8. package/dist/cjs/async-queuer.cjs.map +1 -1
  9. package/dist/cjs/async-queuer.d.cts +103 -9
  10. package/dist/cjs/async-rate-limiter.cjs +51 -1
  11. package/dist/cjs/async-rate-limiter.cjs.map +1 -1
  12. package/dist/cjs/async-rate-limiter.d.cts +94 -27
  13. package/dist/cjs/async-retryer.cjs +286 -0
  14. package/dist/cjs/async-retryer.cjs.map +1 -0
  15. package/dist/cjs/async-retryer.d.cts +312 -0
  16. package/dist/cjs/async-throttler.cjs +101 -52
  17. package/dist/cjs/async-throttler.cjs.map +1 -1
  18. package/dist/cjs/async-throttler.d.cts +85 -9
  19. package/dist/cjs/batcher.cjs +5 -0
  20. package/dist/cjs/batcher.cjs.map +1 -1
  21. package/dist/cjs/batcher.d.cts +13 -1
  22. package/dist/cjs/debouncer.cjs +5 -0
  23. package/dist/cjs/debouncer.cjs.map +1 -1
  24. package/dist/cjs/debouncer.d.cts +10 -2
  25. package/dist/cjs/event-client.cjs.map +1 -1
  26. package/dist/cjs/event-client.d.cts +3 -0
  27. package/dist/cjs/index.cjs +13 -0
  28. package/dist/cjs/index.cjs.map +1 -1
  29. package/dist/cjs/index.d.cts +1 -0
  30. package/dist/cjs/queuer.cjs +5 -0
  31. package/dist/cjs/queuer.cjs.map +1 -1
  32. package/dist/cjs/queuer.d.cts +11 -3
  33. package/dist/cjs/rate-limiter.cjs +5 -0
  34. package/dist/cjs/rate-limiter.cjs.map +1 -1
  35. package/dist/cjs/rate-limiter.d.cts +11 -0
  36. package/dist/cjs/throttler.cjs +5 -0
  37. package/dist/cjs/throttler.cjs.map +1 -1
  38. package/dist/cjs/throttler.d.cts +11 -0
  39. package/dist/cjs/utils.cjs.map +1 -1
  40. package/dist/esm/async-batcher.d.ts +97 -16
  41. package/dist/esm/async-batcher.js +67 -5
  42. package/dist/esm/async-batcher.js.map +1 -1
  43. package/dist/esm/async-debouncer.d.ts +79 -9
  44. package/dist/esm/async-debouncer.js +54 -19
  45. package/dist/esm/async-debouncer.js.map +1 -1
  46. package/dist/esm/async-queuer.d.ts +103 -9
  47. package/dist/esm/async-queuer.js +59 -2
  48. package/dist/esm/async-queuer.js.map +1 -1
  49. package/dist/esm/async-rate-limiter.d.ts +94 -27
  50. package/dist/esm/async-rate-limiter.js +52 -2
  51. package/dist/esm/async-rate-limiter.js.map +1 -1
  52. package/dist/esm/async-retryer.d.ts +312 -0
  53. package/dist/esm/async-retryer.js +286 -0
  54. package/dist/esm/async-retryer.js.map +1 -0
  55. package/dist/esm/async-throttler.d.ts +85 -9
  56. package/dist/esm/async-throttler.js +102 -53
  57. package/dist/esm/async-throttler.js.map +1 -1
  58. package/dist/esm/batcher.d.ts +13 -1
  59. package/dist/esm/batcher.js +5 -0
  60. package/dist/esm/batcher.js.map +1 -1
  61. package/dist/esm/debouncer.d.ts +10 -2
  62. package/dist/esm/debouncer.js +6 -1
  63. package/dist/esm/debouncer.js.map +1 -1
  64. package/dist/esm/event-client.d.ts +3 -0
  65. package/dist/esm/event-client.js.map +1 -1
  66. package/dist/esm/index.d.ts +1 -0
  67. package/dist/esm/index.js +23 -10
  68. package/dist/esm/index.js.map +1 -1
  69. package/dist/esm/queuer.d.ts +11 -3
  70. package/dist/esm/queuer.js +6 -1
  71. package/dist/esm/queuer.js.map +1 -1
  72. package/dist/esm/rate-limiter.d.ts +11 -0
  73. package/dist/esm/rate-limiter.js +6 -1
  74. package/dist/esm/rate-limiter.js.map +1 -1
  75. package/dist/esm/throttler.d.ts +11 -0
  76. package/dist/esm/throttler.js +6 -1
  77. package/dist/esm/throttler.js.map +1 -1
  78. package/dist/esm/utils.js.map +1 -1
  79. package/package.json +12 -2
  80. package/src/async-batcher.ts +146 -19
  81. package/src/async-debouncer.ts +120 -30
  82. package/src/async-queuer.ts +149 -11
  83. package/src/async-rate-limiter.ts +131 -30
  84. package/src/async-retryer.ts +669 -0
  85. package/src/async-throttler.ts +198 -72
  86. package/src/batcher.ts +18 -1
  87. package/src/debouncer.ts +19 -2
  88. package/src/event-client.ts +3 -0
  89. package/src/index.ts +2 -0
  90. package/src/queuer.ts +21 -3
  91. package/src/rate-limiter.ts +20 -0
  92. package/src/throttler.ts +20 -0
@@ -0,0 +1,669 @@
1
+ import { Store } from '@tanstack/store'
2
+ import { createKey, parseFunctionOrValue } from './utils'
3
+ import { emitChange, pacerEventClient } from './event-client'
4
+ import type { AnyAsyncFunction } from './types'
5
+
6
+ export interface AsyncRetryerState<TFn extends AnyAsyncFunction> {
7
+ /**
8
+ * The current retry attempt number (0 when not executing)
9
+ */
10
+ currentAttempt: number
11
+ /**
12
+ * Total number of completed executions (successful or failed)
13
+ */
14
+ executionCount: number
15
+ /**
16
+ * Whether the retryer is currently executing the function
17
+ */
18
+ isExecuting: boolean
19
+ /**
20
+ * The most recent error encountered during execution
21
+ */
22
+ lastError: Error | undefined
23
+ /**
24
+ * Timestamp of the last execution completion in milliseconds
25
+ */
26
+ lastExecutionTime: number
27
+ /**
28
+ * The result from the most recent successful execution
29
+ */
30
+ lastResult: Awaited<ReturnType<TFn>> | undefined
31
+ /**
32
+ * Current execution status - 'disabled' when not enabled, 'idle' when ready, 'executing' when running
33
+ */
34
+ status: 'disabled' | 'idle' | 'executing' | 'retrying'
35
+ /**
36
+ * Total time spent executing (including retries) in milliseconds
37
+ */
38
+ totalExecutionTime: number
39
+ }
40
+
41
+ /**
42
+ * Creates the default initial state for an AsyncRetryer instance
43
+ * @returns The default state with all values reset to initial values
44
+ */
45
+ function getDefaultAsyncRetryerState<
46
+ TFn extends AnyAsyncFunction,
47
+ >(): AsyncRetryerState<TFn> {
48
+ return structuredClone({
49
+ currentAttempt: 0,
50
+ executionCount: 0,
51
+ isExecuting: false,
52
+ lastError: undefined,
53
+ lastExecutionTime: 0,
54
+ lastResult: undefined,
55
+ status: 'idle',
56
+ totalExecutionTime: 0,
57
+ })
58
+ }
59
+
60
+ export interface AsyncRetryerOptions<TFn extends AnyAsyncFunction> {
61
+ /**
62
+ * The backoff strategy for retry delays:
63
+ * - 'exponential': Wait time doubles with each attempt (1s, 2s, 4s, ...)
64
+ * - 'linear': Wait time increases linearly (1s, 2s, 3s, ...)
65
+ * - 'fixed': Same wait time for all attempts
66
+ * @default 'exponential'
67
+ */
68
+ backoff?: 'linear' | 'exponential' | 'fixed'
69
+ /**
70
+ * Base wait time in milliseconds between retries, or a function that returns the wait time
71
+ * @default 1000
72
+ */
73
+ baseWait?: number | ((retryer: AsyncRetryer<TFn>) => number)
74
+ /**
75
+ * Whether the retryer is enabled, or a function that determines if it's enabled
76
+ * @default true
77
+ */
78
+ enabled?: boolean | ((retryer: AsyncRetryer<TFn>) => boolean)
79
+ /**
80
+ * Initial state to merge with the default state
81
+ */
82
+ initialState?: Partial<AsyncRetryerState<TFn>>
83
+ /**
84
+ * Jitter percentage to add to retry delays (0-1). Adds randomness to prevent thundering herd.
85
+ * @default 0
86
+ */
87
+ jitter?: number
88
+ /**
89
+ * Optional key to identify this async retryer instance.
90
+ * If provided, the async retryer will be identified by this key in the devtools and PacerProvider if applicable.
91
+ */
92
+ key?: string
93
+ /**
94
+ * Maximum number of retry attempts, or a function that returns the max attempts
95
+ * @default 3
96
+ */
97
+ maxAttempts?: number | ((retryer: AsyncRetryer<TFn>) => number)
98
+ /**
99
+ * Maximum execution time in milliseconds for a single function call before aborting
100
+ * @default Infinity
101
+ */
102
+ maxExecutionTime?: number
103
+ /**
104
+ * Maximum total execution time in milliseconds for the entire retry operation before aborting
105
+ * @default Infinity
106
+ */
107
+ maxTotalExecutionTime?: number
108
+ /**
109
+ * Callback invoked when the execution is aborted (manually or due to timeouts)
110
+ */
111
+ onAbort?: (
112
+ reason: 'manual' | 'execution-timeout' | 'total-timeout' | 'new-execution',
113
+ retryer: AsyncRetryer<TFn>,
114
+ ) => void
115
+ /**
116
+ * Callback invoked when any error occurs during execution (including retries)
117
+ */
118
+ onError?: (
119
+ error: Error,
120
+ args: Parameters<TFn>,
121
+ retryer: AsyncRetryer<TFn>,
122
+ ) => void
123
+ /**
124
+ * Callback invoked when the final error occurs after all retries are exhausted
125
+ */
126
+ onLastError?: (error: Error, retryer: AsyncRetryer<TFn>) => void
127
+ /**
128
+ * Callback invoked before each retry attempt
129
+ */
130
+ onRetry?: (attempt: number, error: Error, retryer: AsyncRetryer<TFn>) => void
131
+ /**
132
+ * Callback invoked after execution completes (success or failure) of each attempt
133
+ */
134
+ onSettled?: (args: Parameters<TFn>, retryer: AsyncRetryer<TFn>) => void
135
+ /**
136
+ * Callback invoked when execution succeeds
137
+ */
138
+ onSuccess?: (
139
+ result: Awaited<ReturnType<TFn>>,
140
+ args: Parameters<TFn>,
141
+ retryer: AsyncRetryer<TFn>,
142
+ ) => void
143
+ /**
144
+ * Callback invoked when a single execution attempt times out (maxExecutionTime exceeded)
145
+ */
146
+ onExecutionTimeout?: (retryer: AsyncRetryer<TFn>) => void
147
+ /**
148
+ * Callback invoked when the total execution time times out (maxTotalExecutionTime exceeded)
149
+ */
150
+ onTotalExecutionTimeout?: (retryer: AsyncRetryer<TFn>) => void
151
+ /**
152
+ * Controls when errors are thrown:
153
+ * - 'last': Only throw the final error after all retries are exhausted
154
+ * - true: Throw every error immediately (disables retrying)
155
+ * - false: Never throw errors, return undefined instead
156
+ * @default 'last'
157
+ */
158
+ throwOnError?: boolean | 'last'
159
+ }
160
+
161
+ /**
162
+ * Utility function for sharing common `AsyncRetryerOptions` options between different `AsyncRetryer` instances.
163
+ */
164
+ export function asyncRetryerOptions<
165
+ TFn extends AnyAsyncFunction = AnyAsyncFunction,
166
+ TOptions extends Partial<AsyncRetryerOptions<TFn>> = Partial<
167
+ AsyncRetryerOptions<TFn>
168
+ >,
169
+ >(options: TOptions): TOptions {
170
+ return options
171
+ }
172
+
173
+ const defaultOptions: Omit<
174
+ Required<AsyncRetryerOptions<any>>,
175
+ | 'initialState'
176
+ | 'key'
177
+ | 'onAbort'
178
+ | 'onError'
179
+ | 'onLastError'
180
+ | 'onRetry'
181
+ | 'onSettled'
182
+ | 'onSuccess'
183
+ | 'onExecutionTimeout'
184
+ | 'onTotalExecutionTimeout'
185
+ > = {
186
+ backoff: 'exponential',
187
+ baseWait: 1000,
188
+ enabled: true,
189
+ jitter: 0,
190
+ maxAttempts: 3,
191
+ maxExecutionTime: Infinity,
192
+ maxTotalExecutionTime: Infinity,
193
+ throwOnError: 'last',
194
+ }
195
+
196
+ /**
197
+ * Provides robust retry functionality for asynchronous functions, supporting configurable backoff strategies,
198
+ * attempt limits, timeout controls, and detailed state management. The AsyncRetryer class is designed to help you reliably
199
+ * execute async operations that may fail intermittently, such as network requests or database operations,
200
+ * by automatically retrying them according to your chosen policy.
201
+ *
202
+ * ## Retrying Concepts
203
+ *
204
+ * - **Retrying**: Automatically re-executes a failed async function up to a specified number of attempts.
205
+ * Useful for handling transient errors (e.g., network flakiness, rate limits, temporary server issues).
206
+ * - **Backoff Strategies**: Controls the delay between retry attempts (default: `'exponential'`):
207
+ * - `'exponential'`: Wait time doubles with each attempt (1s, 2s, 4s, ...) - **DEFAULT**
208
+ * - `'linear'`: Wait time increases linearly (1s, 2s, 3s, ...)
209
+ * - `'fixed'`: Waits a constant amount of time (`baseWait`) between each attempt
210
+ * - **Jitter**: Adds randomness to retry delays to prevent thundering herd problems (default: `0`).
211
+ * Set to a value between 0-1 to apply that percentage of random variation to each delay.
212
+ * - **Timeout Controls**: Set limits on execution time to prevent hanging operations:
213
+ * - `maxExecutionTime`: Maximum time for a single function call (default: `Infinity`)
214
+ * - `maxTotalExecutionTime`: Maximum time for the entire retry operation (default: `Infinity`)
215
+ * - **Abort & Cancellation**: Supports cancellation via an internal `AbortController`. Call `abort()` to stop retries.
216
+ * Use `getAbortSignal()` to make your async function actually cancellable (e.g., with fetch requests).
217
+ *
218
+ * ## State Management
219
+ *
220
+ * Uses TanStack Store for fine-grained reactivity. State can be accessed via the `store.state` property.
221
+ *
222
+ * Available state properties:
223
+ * - `currentAttempt`: The current retry attempt number (0 when not executing)
224
+ * - `executionCount`: Total number of completed executions (successful or failed)
225
+ * - `isExecuting`: Whether the retryer is currently executing the function
226
+ * - `lastError`: The most recent error encountered during execution
227
+ * - `lastExecutionTime`: Timestamp of the last execution completion in milliseconds
228
+ * - `lastResult`: The result from the most recent successful execution
229
+ * - `status`: Current execution status ('disabled' | 'idle' | 'executing' | 'retrying')
230
+ * - `totalExecutionTime`: Total time spent executing (including retries) in milliseconds
231
+ *
232
+ * ## Error Handling
233
+ *
234
+ * The `throwOnError` option controls when errors are thrown (default: `'last'`):
235
+ * - `'last'`: Only throws the final error after all retries are exhausted - **DEFAULT**
236
+ * - `true`: Throws every error immediately (disables retrying)
237
+ * - `false`: Never throws errors, returns `undefined` instead
238
+ *
239
+ * Callbacks for lifecycle management:
240
+ * - `onAbort`: Called when execution is aborted (manually or due to timeouts)
241
+ * - `onError`: Called for every error (including during retries)
242
+ * - `onLastError`: Called only for the final error after all retries fail
243
+ * - `onRetry`: Called before each retry attempt
244
+ * - `onSettled`: Called after execution completes (success or failure) of each attempt
245
+ * - `onSuccess`: Called when execution succeeds
246
+ * - `onExecutionTimeout`: Called when a single execution attempt times out
247
+ * - `onTotalExecutionTimeout`: Called when the total execution time times out
248
+ *
249
+ * ## Usage
250
+ *
251
+ * - Use for async operations that may fail transiently and benefit from retrying.
252
+ * - Configure `maxAttempts`, `backoff`, `baseWait`, and `jitter` to control retry behavior.
253
+ * - Set `maxExecutionTime` and `maxTotalExecutionTime` to prevent hanging operations.
254
+ * - Use `onAbort`, `onError`, `onLastError`, `onRetry`, `onSettled`, `onSuccess`, `onExecutionTimeout`, and `onTotalExecutionTimeout` for custom side effects.
255
+ * - Call `abort()` to cancel ongoing execution and pending retries.
256
+ * - Call `reset()` to reset state and cancel execution.
257
+ * - Use `getAbortSignal()` to make your async function cancellable.
258
+ * - Use dynamic options (functions) for `maxAttempts`, `baseWait`, and `enabled` based on retryer state.
259
+ *
260
+ * **Important:** This class is designed for single-use execution. Calling `execute()` multiple times
261
+ * on the same instance will abort previous executions. For multiple calls, create a new instance
262
+ * each time.
263
+ *
264
+ * @example
265
+ * ```typescript
266
+ * // Retry a fetch operation up to 5 times with exponential backoff, jitter, and timeouts
267
+ * const retryer = new AsyncRetryer(async (url: string) => {
268
+ * const signal = retryer.getAbortSignal()
269
+ * return await fetch(url, { signal })
270
+ * }, {
271
+ * maxAttempts: 5,
272
+ * backoff: 'exponential',
273
+ * baseWait: 1000,
274
+ * jitter: 0.1, // Add 10% random variation to prevent thundering herd
275
+ * maxExecutionTime: 5000, // Abort individual calls after 5 seconds
276
+ * maxTotalExecutionTime: 30000, // Abort entire operation after 30 seconds
277
+ * onRetry: (attempt, error) => console.log(`Retry attempt ${attempt} after error:`, error),
278
+ * onSuccess: (result) => console.log('Success:', result),
279
+ * onError: (error) => console.error('Error:', error),
280
+ * onLastError: (error) => console.error('All retries failed:', error),
281
+ * })
282
+ *
283
+ * const result = await retryer.execute('/api/data')
284
+ * ```
285
+ *
286
+ * @template TFn The async function type to be retried.
287
+ */
288
+ export class AsyncRetryer<TFn extends AnyAsyncFunction> {
289
+ readonly store: Store<Readonly<AsyncRetryerState<TFn>>> = new Store(
290
+ getDefaultAsyncRetryerState<TFn>(),
291
+ )
292
+ key: string
293
+ options: AsyncRetryerOptions<TFn> & typeof defaultOptions
294
+ #abortController: AbortController | null = null
295
+
296
+ /**
297
+ * Creates a new AsyncRetryer instance
298
+ * @param fn The async function to retry
299
+ * @param initialOptions Configuration options for the retryer
300
+ */
301
+ constructor(
302
+ public fn: TFn,
303
+ initialOptions: AsyncRetryerOptions<TFn> = {},
304
+ ) {
305
+ this.key = createKey(initialOptions.key)
306
+ this.options = {
307
+ ...defaultOptions,
308
+ ...initialOptions,
309
+ throwOnError:
310
+ initialOptions.throwOnError ??
311
+ (initialOptions.onError ? false : defaultOptions.throwOnError),
312
+ }
313
+ this.#setState(this.options.initialState ?? {})
314
+
315
+ pacerEventClient.on('d-AsyncRetryer', (event) => {
316
+ if (event.payload.key !== this.key) return
317
+ this.#setState(event.payload.store.state as AsyncRetryerState<TFn>)
318
+ this.setOptions(event.payload.options)
319
+ })
320
+ }
321
+
322
+ /**
323
+ * Emits a change event for the async retryer instance. Mostly useful for devtools.
324
+ */
325
+ _emit = () => emitChange('AsyncRetryer', this)
326
+
327
+ /**
328
+ * Updates the retryer options
329
+ * @param newOptions Partial options to merge with existing options
330
+ */
331
+ setOptions = (newOptions: Partial<AsyncRetryerOptions<TFn>>): void => {
332
+ this.options = { ...this.options, ...newOptions }
333
+ }
334
+
335
+ #setState = (newState: Partial<AsyncRetryerState<TFn>>): void => {
336
+ this.store.setState((state) => {
337
+ const combinedState = {
338
+ ...state,
339
+ ...newState,
340
+ }
341
+ const { isExecuting, currentAttempt } = combinedState
342
+ return {
343
+ ...combinedState,
344
+ status: !this.#getEnabled()
345
+ ? 'disabled'
346
+ : isExecuting && currentAttempt === 1
347
+ ? 'executing'
348
+ : isExecuting && currentAttempt > 1
349
+ ? 'retrying'
350
+ : 'idle',
351
+ }
352
+ })
353
+ emitChange('AsyncRetryer', this)
354
+ }
355
+
356
+ #getEnabled = (): boolean => {
357
+ return !!parseFunctionOrValue(this.options.enabled, this)
358
+ }
359
+
360
+ #getMaxAttempts = (): number => {
361
+ return parseFunctionOrValue(this.options.maxAttempts, this)
362
+ }
363
+
364
+ #getBaseWait = (): number => {
365
+ return parseFunctionOrValue(this.options.baseWait, this)
366
+ }
367
+
368
+ #calculateJitter = (waitTime: number): number => {
369
+ const jitterAmount = this.options.jitter
370
+ if (jitterAmount <= 0) return 0
371
+
372
+ try {
373
+ const crypto =
374
+ typeof globalThis !== 'undefined' ? globalThis.crypto : undefined
375
+ if (crypto?.getRandomValues) {
376
+ const array = new Uint32Array(1)
377
+ crypto.getRandomValues(array)
378
+ // Convert to 0-1 range and apply jitter percentage
379
+ const randomFactor = (array[0]! / 0xffffffff) * 2 - 1 // -1 to 1
380
+ return Math.floor(waitTime * jitterAmount * randomFactor)
381
+ }
382
+ } catch {
383
+ // No crypto available
384
+ }
385
+ return 0
386
+ }
387
+
388
+ #calculateWait = (attempt: number): number => {
389
+ const baseWait = this.#getBaseWait()
390
+ let waitTime: number
391
+
392
+ switch (this.options.backoff) {
393
+ case 'linear':
394
+ waitTime = baseWait * attempt
395
+ break
396
+ case 'exponential':
397
+ waitTime = baseWait * Math.pow(2, attempt - 1)
398
+ break
399
+ case 'fixed':
400
+ default:
401
+ waitTime = baseWait
402
+ break
403
+ }
404
+
405
+ const jitter = this.#calculateJitter(waitTime)
406
+ return Math.max(0, waitTime + jitter)
407
+ }
408
+
409
+ /**
410
+ * Executes the function with retry logic
411
+ * @param args Arguments to pass to the function
412
+ * @returns The function result, or undefined if disabled or all retries failed (when throwOnError is false)
413
+ * @throws The last error if throwOnError is true and all retries fail
414
+ */
415
+ execute = async (
416
+ ...args: Parameters<TFn>
417
+ ): Promise<Awaited<ReturnType<TFn>> | undefined> => {
418
+ if (!this.#getEnabled()) {
419
+ return undefined
420
+ }
421
+
422
+ // Cancel any existing execution
423
+ this.abort('new-execution')
424
+
425
+ const startTime = Date.now()
426
+ let lastError: Error | undefined
427
+ let result: Awaited<ReturnType<TFn>> | undefined
428
+
429
+ this.#abortController = new AbortController()
430
+ const signal = this.#abortController.signal
431
+
432
+ this.#setState({
433
+ isExecuting: true,
434
+ currentAttempt: 0,
435
+ lastError: undefined,
436
+ })
437
+
438
+ // Set up total execution timeout
439
+ let totalTimeoutId: NodeJS.Timeout | undefined
440
+ if (this.options.maxTotalExecutionTime !== Infinity) {
441
+ totalTimeoutId = setTimeout(() => {
442
+ this.options.onTotalExecutionTimeout?.(this)
443
+ this.abort('total-timeout')
444
+ }, this.options.maxTotalExecutionTime)
445
+ }
446
+
447
+ let isLastAttempt = false
448
+ for (let attempt = 1; attempt <= this.#getMaxAttempts(); attempt++) {
449
+ isLastAttempt = attempt === this.#getMaxAttempts()
450
+ this.#setState({ currentAttempt: attempt })
451
+
452
+ try {
453
+ if (signal.aborted) {
454
+ return undefined
455
+ }
456
+
457
+ // Check if total execution time has been exceeded
458
+ const currentTotalTime = Date.now() - startTime
459
+ if (
460
+ this.options.maxTotalExecutionTime !== Infinity &&
461
+ currentTotalTime >= this.options.maxTotalExecutionTime
462
+ ) {
463
+ this.options.onTotalExecutionTimeout?.(this)
464
+ this.abort('total-timeout')
465
+ return undefined
466
+ }
467
+
468
+ // Execute with individual timeout if specified
469
+ if (this.options.maxExecutionTime === Infinity) {
470
+ result = (await this.fn(...args)) as Awaited<ReturnType<TFn>>
471
+ } else {
472
+ result = (await Promise.race([
473
+ this.fn(...args),
474
+ new Promise<never>((_, reject) => {
475
+ const timeout = setTimeout(() => {
476
+ this.options.onExecutionTimeout?.(this)
477
+ this.abort('execution-timeout')
478
+ reject(
479
+ new Error(
480
+ `Execution timeout: ${this.options.maxExecutionTime}ms exceeded`,
481
+ ),
482
+ )
483
+ }, this.options.maxExecutionTime)
484
+
485
+ signal.addEventListener(
486
+ 'abort',
487
+ () => {
488
+ clearTimeout(timeout)
489
+ reject(new Error('Aborted'))
490
+ },
491
+ { once: true },
492
+ )
493
+ }),
494
+ ])) as Awaited<ReturnType<TFn>>
495
+ }
496
+
497
+ // Check if cancelled during execution
498
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
499
+ if (signal.aborted) {
500
+ return undefined
501
+ }
502
+
503
+ const totalTime = Date.now() - startTime
504
+ this.#setState({
505
+ executionCount: this.store.state.executionCount + 1,
506
+ isExecuting: false,
507
+ lastExecutionTime: Date.now(),
508
+ totalExecutionTime: totalTime,
509
+ currentAttempt: 0,
510
+ lastResult: result,
511
+ })
512
+
513
+ this.options.onSuccess?.(result as Awaited<ReturnType<TFn>>, args, this)
514
+
515
+ return result
516
+ } catch (error) {
517
+ // Treat abort as a non-error cancellation outcome
518
+ if (
519
+ error &&
520
+ typeof error === 'object' &&
521
+ 'name' in error &&
522
+ (error as Error).name === 'AbortError'
523
+ ) {
524
+ return undefined
525
+ }
526
+ lastError = error instanceof Error ? error : new Error(String(error))
527
+ this.#setState({ lastError })
528
+
529
+ // Call onError for every error (including during retries)
530
+ this.options.onError?.(lastError, args, this)
531
+
532
+ if (attempt < this.#getMaxAttempts()) {
533
+ this.options.onRetry?.(attempt, lastError, this)
534
+
535
+ const wait = this.#calculateWait(attempt)
536
+ if (wait > 0) {
537
+ // Eagerly reflect retrying status during the wait window
538
+ this.#setState({ isExecuting: true, currentAttempt: attempt + 1 })
539
+ await new Promise<void>((resolve) => {
540
+ const timeout = setTimeout(() => {
541
+ signal.removeEventListener('abort', onAbort)
542
+ resolve()
543
+ }, wait)
544
+ const onAbort = () => {
545
+ clearTimeout(timeout)
546
+ signal.removeEventListener('abort', onAbort)
547
+ resolve()
548
+ }
549
+ signal.addEventListener('abort', onAbort)
550
+ })
551
+ if (signal.aborted) {
552
+ return undefined
553
+ }
554
+ }
555
+ }
556
+ } finally {
557
+ this.options.onSettled?.(args, this)
558
+ }
559
+ }
560
+
561
+ // Clean up total timeout
562
+ if (totalTimeoutId) {
563
+ clearTimeout(totalTimeoutId)
564
+ }
565
+
566
+ // Exhausted retries - finalize state
567
+ this.#setState({ isExecuting: false })
568
+ this.options.onLastError?.(lastError as Error, this)
569
+ this.options.onSettled?.(args, this)
570
+
571
+ if (
572
+ (this.options.throwOnError === 'last' && isLastAttempt) ||
573
+ this.options.throwOnError === true
574
+ ) {
575
+ throw lastError
576
+ }
577
+
578
+ return undefined
579
+ }
580
+
581
+ /**
582
+ * Returns the current AbortSignal for the executing operation.
583
+ * Use this signal in your async function to make it cancellable.
584
+ * Returns null when not currently executing.
585
+ *
586
+ * @example
587
+ * ```typescript
588
+ * const retryer = new AsyncRetryer(async (userId: string) => {
589
+ * const signal = retryer.getAbortSignal()
590
+ * if (signal) {
591
+ * return fetch(`/api/users/${userId}`, { signal })
592
+ * }
593
+ * return fetch(`/api/users/${userId}`)
594
+ * })
595
+ *
596
+ * // Abort will now actually cancel the fetch
597
+ * retryer.abort()
598
+ * ```
599
+ */
600
+ getAbortSignal(): AbortSignal | null {
601
+ return this.#abortController?.signal ?? null
602
+ }
603
+
604
+ /**
605
+ * Cancels the current execution and any pending retries
606
+ * @param reason The reason for the abort (defaults to 'manual')
607
+ */
608
+ abort = (
609
+ reason:
610
+ | 'manual'
611
+ | 'execution-timeout'
612
+ | 'total-timeout'
613
+ | 'new-execution' = 'manual',
614
+ ): void => {
615
+ if (this.#abortController) {
616
+ this.#abortController.abort()
617
+ this.#abortController = null
618
+ this.#setState({
619
+ isExecuting: false,
620
+ })
621
+ this.options.onAbort?.(reason, this)
622
+ }
623
+ }
624
+
625
+ /**
626
+ * Resets the retryer to its initial state
627
+ */
628
+ reset = (): void => {
629
+ this.#setState(getDefaultAsyncRetryerState<TFn>())
630
+ }
631
+ }
632
+
633
+ /**
634
+ * Creates a retry-enabled version of an async function. This is a convenience wrapper
635
+ * around the AsyncRetryer class that returns the execute method.
636
+ *
637
+ * @param fn The async function to add retry functionality to
638
+ * @param initialOptions Configuration options for the retry behavior
639
+ * @returns A new function that executes the original with retry logic
640
+ *
641
+ * @example
642
+ * ```typescript
643
+ * // Define your async function normally
644
+ * async function fetchData(url: string) {
645
+ * const response = await fetch(url)
646
+ * if (!response.ok) throw new Error('Request failed')
647
+ * return response.json()
648
+ * }
649
+ *
650
+ * // Create retry-enabled function
651
+ * const fetchWithRetry = asyncRetry(fetchData, {
652
+ * maxAttempts: 3,
653
+ * backoff: 'exponential',
654
+ * baseWait: 1000,
655
+ * jitter: 0.1
656
+ * })
657
+ *
658
+ * // Call it multiple times
659
+ * const data1 = await fetchWithRetry('/api/data1')
660
+ * const data2 = await fetchWithRetry('/api/data2')
661
+ * ```
662
+ */
663
+ export function asyncRetry<TFn extends AnyAsyncFunction>(
664
+ fn: TFn,
665
+ initialOptions: AsyncRetryerOptions<TFn> = {},
666
+ ): (...args: Parameters<TFn>) => Promise<Awaited<ReturnType<TFn>> | undefined> {
667
+ const retryer = new AsyncRetryer(fn, initialOptions)
668
+ return retryer.execute
669
+ }