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