@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,647 +0,0 @@
1
- import { Store } from '@tanstack/store'
2
- import { AsyncRetryer } from './async-retryer'
3
- import { parseFunctionOrValue } from './utils'
4
- import { emitChange, pacerEventClient } from './event-client'
5
- import type { AsyncRetryerOptions } from './async-retryer'
6
- import type { AnyAsyncFunction } from './types'
7
-
8
- export interface AsyncRateLimiterState<TFn extends AnyAsyncFunction> {
9
- /**
10
- * Number of function executions that have resulted in errors
11
- */
12
- errorCount: number
13
- /**
14
- * Array of timestamps when executions occurred for rate limiting calculations
15
- */
16
- executionTimes: Array<number>
17
- /**
18
- * Whether the rate limiter has exceeded the limit
19
- */
20
- isExceeded: boolean
21
- /**
22
- * Whether the rate-limited function is currently executing asynchronously
23
- */
24
- isExecuting: boolean
25
- /**
26
- * The result from the most recent successful function execution
27
- */
28
- lastResult: ReturnType<TFn> | undefined
29
- /**
30
- * Number of function executions that have been rejected due to rate limiting
31
- */
32
- rejectionCount: number
33
- /**
34
- * Number of function executions that have completed (either successfully or with errors)
35
- */
36
- settleCount: number
37
- /**
38
- * Current execution status - 'disabled' when not active, 'executing' when executing, 'idle' when not executing, 'exceeded' when rate limit is exceeded
39
- */
40
- status: 'disabled' | 'executing' | 'exceeded' | 'idle'
41
- /**
42
- * Number of function executions that have completed successfully
43
- */
44
- successCount: number
45
- /**
46
- * Number of times maybeExecute has been called (for reduction calculations)
47
- */
48
- maybeExecuteCount: number
49
- }
50
-
51
- function getDefaultAsyncRateLimiterState<
52
- TFn extends AnyAsyncFunction,
53
- >(): AsyncRateLimiterState<TFn> {
54
- return {
55
- errorCount: 0,
56
- executionTimes: [],
57
- isExceeded: false,
58
- isExecuting: false,
59
- lastResult: undefined,
60
- maybeExecuteCount: 0,
61
- rejectionCount: 0,
62
- settleCount: 0,
63
- status: 'idle',
64
- successCount: 0,
65
- }
66
- }
67
-
68
- /**
69
- * Options for configuring an async rate-limited function
70
- */
71
- export interface AsyncRateLimiterOptions<TFn extends AnyAsyncFunction> {
72
- /**
73
- * Options for configuring the underlying async retryer
74
- */
75
- asyncRetryerOptions?: AsyncRetryerOptions<TFn>
76
- /**
77
- * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.
78
- * Can be a boolean or a function that returns a boolean.
79
- * Defaults to true.
80
- */
81
- enabled?: boolean | ((rateLimiter: AsyncRateLimiter<TFn>) => boolean)
82
- /**
83
- * Initial state for the rate limiter
84
- */
85
- initialState?: Partial<AsyncRateLimiterState<TFn>>
86
- /**
87
- * Optional key to identify this async rate limiter instance.
88
- * If provided, the async rate limiter will be identified by this key in the devtools and PacerProvider if applicable.
89
- */
90
- key?: string
91
- /**
92
- * Maximum number of executions allowed within the time window.
93
- * Can be a number or a function that returns a number.
94
- */
95
- limit: number | ((rateLimiter: AsyncRateLimiter<TFn>) => number)
96
- /**
97
- * Optional error handler for when the rate-limited function throws.
98
- * If provided, the handler will be called with the error and rate limiter instance.
99
- * This can be used alongside throwOnError - the handler will be called before any error is thrown.
100
- */
101
- onError?: (
102
- error: Error,
103
- args: Parameters<TFn>,
104
- rateLimiter: AsyncRateLimiter<TFn>,
105
- ) => void
106
- /**
107
- * Optional callback function that is called when an execution is rejected due to rate limiting
108
- */
109
- onReject?: (args: Parameters<TFn>, rateLimiter: AsyncRateLimiter<TFn>) => void
110
- /**
111
- * Optional function to call when the rate-limited function is executed
112
- */
113
- onSettled?: (
114
- args: Parameters<TFn>,
115
- rateLimiter: AsyncRateLimiter<TFn>,
116
- ) => void
117
- /**
118
- * Optional function to call when the rate-limited function is executed
119
- */
120
- onSuccess?: (
121
- result: ReturnType<TFn>,
122
- args: Parameters<TFn>,
123
- rateLimiter: AsyncRateLimiter<TFn>,
124
- ) => void
125
- /**
126
- * Whether to throw errors when they occur.
127
- * Defaults to true if no onError handler is provided, false if an onError handler is provided.
128
- * Can be explicitly set to override these defaults.
129
- */
130
- throwOnError?: boolean
131
- /**
132
- * Time window in milliseconds within which the limit applies.
133
- * Can be a number or a function that returns a number.
134
- */
135
- window: number | ((rateLimiter: AsyncRateLimiter<TFn>) => number)
136
- /**
137
- * Type of window to use for rate limiting
138
- * - 'fixed': Uses a fixed window that resets after the window period
139
- * - 'sliding': Uses a sliding window that allows executions as old ones expire
140
- * Defaults to 'fixed'
141
- */
142
- windowType?: 'fixed' | 'sliding'
143
- }
144
-
145
- /**
146
- * Utility function for sharing common `AsyncRateLimiterOptions` options between different `AsyncRateLimiter` instances.
147
- */
148
- export function asyncRateLimiterOptions<
149
- TFn extends AnyAsyncFunction = AnyAsyncFunction,
150
- TOptions extends Partial<AsyncRateLimiterOptions<TFn>> = Partial<
151
- AsyncRateLimiterOptions<TFn>
152
- >,
153
- >(options: TOptions): TOptions {
154
- return options
155
- }
156
-
157
- const defaultOptions: Omit<
158
- Required<AsyncRateLimiterOptions<any>>,
159
- 'initialState' | 'onError' | 'onReject' | 'onSettled' | 'onSuccess' | 'key'
160
- > = {
161
- asyncRetryerOptions: {
162
- maxAttempts: 1,
163
- },
164
- enabled: true,
165
- limit: 1,
166
- window: 0,
167
- windowType: 'fixed',
168
- throwOnError: true,
169
- }
170
-
171
- /**
172
- * A class that creates an async rate-limited function.
173
- *
174
- * Async vs Sync Versions:
175
- * The async version provides advanced features over the sync RateLimiter:
176
- * - Returns promises that can be awaited for rate-limited function results
177
- * - Built-in retry support via AsyncRetryer integration
178
- * - Abort support to cancel in-flight executions
179
- * - Comprehensive error handling with onError callbacks and throwOnError control
180
- * - Detailed execution tracking (success/error/settle counts, rejection counts)
181
- * - More sophisticated window management with automatic cleanup
182
- *
183
- * The sync RateLimiter is lighter weight and simpler when you don't need async features,
184
- * return values, or execution control.
185
- *
186
- * What is Rate Limiting?
187
- * Rate limiting allows a function to execute up to a limit within a time window,
188
- * then blocks all subsequent calls until the window passes. This can lead to "bursty" behavior where
189
- * all executions happen immediately, followed by a complete block.
190
- *
191
- * Window Types:
192
- * - 'fixed': A strict window that resets after the window period. All executions within the window count
193
- * towards the limit, and the window resets completely after the period.
194
- * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
195
- * consistent rate of execution over time.
196
- *
197
- * When to Use Rate Limiting:
198
- * Rate limiting is best used for hard API limits or resource constraints. For UI updates or
199
- * smoothing out frequent events, throttling or debouncing usually provide better user experience.
200
- * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)
201
- * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)
202
- *
203
- * State Management:
204
- * - Uses TanStack Store for reactive state management
205
- * - Use `initialState` to provide initial state values when creating the rate limiter
206
- * - `initialState` can be a partial state object
207
- * - Use `onSuccess` callback to react to successful function execution and implement custom logic
208
- * - Use `onError` callback to react to function execution errors and implement custom error handling
209
- * - Use `onSettled` callback to react to function execution completion (success or error) and implement custom logic
210
- * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded
211
- * - The state includes execution times, success/error counts, and current execution status
212
- * - State can be accessed via `asyncRateLimiter.store.state` when using the class directly
213
- * - When using framework adapters (React/Solid), state is accessed from `asyncRateLimiter.state`
214
- *
215
- * Error Handling:
216
- * - If an `onError` handler is provided, it will be called with the error and rate limiter instance
217
- * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
218
- * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
219
- * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
220
- * - The error state can be checked using the underlying AsyncRateLimiter instance
221
- * - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler
222
- *
223
- * @example
224
- * ```ts
225
- * const rateLimiter = new AsyncRateLimiter(
226
- * async (id: string) => await api.getData(id),
227
- * {
228
- * limit: 5,
229
- * window: 1000,
230
- * windowType: 'sliding',
231
- * onError: (error) => {
232
- * console.error('API call failed:', error);
233
- * },
234
- * onReject: (limiter) => {
235
- * console.log(`Rate limit exceeded. Try again in ${limiter.getMsUntilNextWindow()}ms`);
236
- * }
237
- * }
238
- * );
239
- *
240
- * // Will execute immediately until limit reached, then block
241
- * // Returns the API response directly
242
- * const data = await rateLimiter.maybeExecute('123');
243
- * ```
244
- */
245
- export class AsyncRateLimiter<TFn extends AnyAsyncFunction> {
246
- readonly store: Store<Readonly<AsyncRateLimiterState<TFn>>> = new Store<
247
- AsyncRateLimiterState<TFn>
248
- >(getDefaultAsyncRateLimiterState<TFn>())
249
- key: string | undefined
250
- options: AsyncRateLimiterOptions<TFn>
251
- asyncRetryers = new Map<number, AsyncRetryer<TFn>>()
252
- #timeoutIds: Set<ReturnType<typeof setTimeout>> = new Set()
253
-
254
- constructor(
255
- public fn: TFn,
256
- initialOptions: AsyncRateLimiterOptions<TFn>,
257
- ) {
258
- this.key = initialOptions.key
259
- this.options = {
260
- ...defaultOptions,
261
- ...initialOptions,
262
- throwOnError: initialOptions.throwOnError ?? !initialOptions.onError,
263
- }
264
- this.#setState(this.options.initialState ?? {})
265
- for (const executionTime of this.#getExecutionTimesInWindow()) {
266
- this.#setCleanupTimeout(executionTime)
267
- }
268
-
269
- if (this.key) {
270
- pacerEventClient.on('d-AsyncRateLimiter', (event) => {
271
- if (event.payload.key !== this.key) return
272
- this.#setState(
273
- event.payload.store.state as Partial<AsyncRateLimiterState<TFn>>,
274
- )
275
- this.setOptions(
276
- event.payload.options as Partial<AsyncRateLimiterOptions<TFn>>,
277
- )
278
- })
279
- }
280
- }
281
-
282
- /**
283
- * Updates the async rate limiter options
284
- */
285
- setOptions = (newOptions: Partial<AsyncRateLimiterOptions<TFn>>): void => {
286
- this.options = { ...this.options, ...newOptions }
287
- }
288
-
289
- #setState = (newState: Partial<AsyncRateLimiterState<TFn>>): void => {
290
- this.store.setState((state) => {
291
- const combinedState = {
292
- ...state,
293
- ...newState,
294
- }
295
- const isExceeded = combinedState.executionTimes.length >= this.#getLimit()
296
- const status = !this.#getEnabled()
297
- ? 'disabled'
298
- : combinedState.isExecuting
299
- ? 'executing'
300
- : isExceeded
301
- ? 'exceeded'
302
- : 'idle'
303
- return {
304
- ...combinedState,
305
- isExceeded,
306
- status,
307
- }
308
- })
309
- emitChange('AsyncRateLimiter', this)
310
- }
311
-
312
- /**
313
- * Returns the current enabled state of the async rate limiter
314
- */
315
- #getEnabled = (): boolean => {
316
- return !!parseFunctionOrValue(this.options.enabled, this)
317
- }
318
-
319
- /**
320
- * Returns the current limit of executions allowed within the time window
321
- */
322
- #getLimit = (): number => {
323
- return parseFunctionOrValue(this.options.limit, this)
324
- }
325
-
326
- /**
327
- * Returns the current time window in milliseconds
328
- */
329
- #getWindow = (): number => {
330
- return parseFunctionOrValue(this.options.window, this)
331
- }
332
-
333
- /**
334
- * Attempts to execute the rate-limited function if within the configured limits.
335
- * Will reject execution if the number of calls in the current window exceeds the limit.
336
- *
337
- * Error Handling:
338
- * - If the rate-limited function throws and no `onError` handler is configured,
339
- * the error will be thrown from this method.
340
- * - If an `onError` handler is configured, errors will be caught and passed to the handler,
341
- * and this method will return undefined.
342
- * - The error state can be checked using `getErrorCount()` and `getIsExecuting()`.
343
- *
344
- * @returns A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError
345
- * @throws The error from the rate-limited function if no onError handler is configured
346
- *
347
- * @example
348
- * ```ts
349
- * const rateLimiter = new AsyncRateLimiter(fn, { limit: 5, window: 1000 });
350
- *
351
- * // First 5 calls will return a promise that resolves with the result
352
- * const result = await rateLimiter.maybeExecute('arg1', 'arg2');
353
- *
354
- * // Additional calls within the window will return undefined
355
- * const result2 = await rateLimiter.maybeExecute('arg1', 'arg2'); // undefined
356
- * ```
357
- */
358
- maybeExecute = async (
359
- ...args: Parameters<TFn>
360
- ): Promise<ReturnType<TFn> | undefined> => {
361
- this.#setState({
362
- maybeExecuteCount: this.store.state.maybeExecuteCount + 1,
363
- })
364
-
365
- this.#cleanupOldExecutions()
366
-
367
- const relevantExecutionTimes = this.#getExecutionTimesInWindow()
368
-
369
- if (relevantExecutionTimes.length < this.#getLimit()) {
370
- await this.#execute(...args)
371
- return this.store.state.lastResult
372
- }
373
-
374
- this.#setState({
375
- rejectionCount: this.store.state.rejectionCount + 1,
376
- })
377
- this.options.onReject?.(args, this)
378
- return undefined
379
- }
380
-
381
- #execute = async (
382
- ...args: Parameters<TFn>
383
- ): Promise<ReturnType<TFn> | undefined> => {
384
- if (!this.#getEnabled()) return
385
-
386
- const currentMaybeExecute = this.store.state.maybeExecuteCount
387
- const now = Date.now()
388
- const executionTimes = [...this.store.state.executionTimes, now]
389
- this.#setState({
390
- isExecuting: true,
391
- executionTimes,
392
- })
393
-
394
- try {
395
- // Create a new AsyncRetryer for this execution to avoid cancelling concurrent executions
396
- const currentAsyncRetryer = new AsyncRetryer(this.fn, {
397
- ...this.options.asyncRetryerOptions,
398
- key: `${this.key}-retryer-${currentMaybeExecute}`,
399
- })
400
- this.asyncRetryers.set(currentMaybeExecute, currentAsyncRetryer)
401
- const result = await currentAsyncRetryer.execute(...args) // EXECUTE!
402
- this.#setCleanupTimeout(now)
403
- this.#setState({
404
- successCount: this.store.state.successCount + 1,
405
- lastResult: result,
406
- })
407
- this.options.onSuccess?.(result as ReturnType<TFn>, args, this)
408
- } catch (error) {
409
- this.#setState({
410
- errorCount: this.store.state.errorCount + 1,
411
- })
412
- this.options.onError?.(error as Error, args, this)
413
- if (this.options.throwOnError) {
414
- throw error
415
- }
416
- } finally {
417
- this.asyncRetryers.delete(currentMaybeExecute) // dispose retryer
418
- this.#setState({
419
- isExecuting: false,
420
- settleCount: this.store.state.settleCount + 1,
421
- })
422
- this.options.onSettled?.(args, this)
423
- }
424
-
425
- return this.store.state.lastResult
426
- }
427
-
428
- #getExecutionTimesInWindow = (): Array<number> => {
429
- if (this.options.windowType === 'sliding') {
430
- // For sliding window, return all executions within the current window
431
- return this.store.state.executionTimes.filter(
432
- (time) => time > Date.now() - this.#getWindow(),
433
- )
434
- } else {
435
- // For fixed window, return all executions in the current window
436
- // The window starts from the oldest execution time
437
- if (this.store.state.executionTimes.length === 0) {
438
- return []
439
- }
440
- const oldestExecution = Math.min(...this.store.state.executionTimes)
441
- const windowStart = oldestExecution
442
- const windowEnd = windowStart + this.#getWindow()
443
- const now = Date.now()
444
-
445
- // If the window has expired, return empty array
446
- if (now > windowEnd) {
447
- return []
448
- }
449
-
450
- // Otherwise, return all executions in the current window
451
- return this.store.state.executionTimes.filter(
452
- (time) => time >= windowStart && time <= windowEnd,
453
- )
454
- }
455
- }
456
-
457
- #setCleanupTimeout = (executionTime: number): void => {
458
- if (
459
- this.options.windowType === 'sliding' ||
460
- this.#timeoutIds.size === 0 // new fixed window
461
- ) {
462
- const now = Date.now()
463
- const timeUntilExpiration = executionTime - now + this.#getWindow() + 1
464
- const timeoutId = setTimeout(() => {
465
- this.#cleanupOldExecutions()
466
- this.#clearTimeout(timeoutId)
467
- }, timeUntilExpiration)
468
- this.#timeoutIds.add(timeoutId)
469
- }
470
- }
471
-
472
- #clearTimeout = (timeoutId: ReturnType<typeof setTimeout>): void => {
473
- clearTimeout(timeoutId)
474
- this.#timeoutIds.delete(timeoutId)
475
- }
476
-
477
- #clearTimeouts = (): void => {
478
- this.#timeoutIds.forEach((timeoutId) => clearTimeout(timeoutId))
479
- this.#timeoutIds.clear()
480
- }
481
-
482
- #cleanupOldExecutions = (): void => {
483
- this.#setState({
484
- executionTimes: this.#getExecutionTimesInWindow(),
485
- })
486
- }
487
-
488
- /**
489
- * Returns the number of remaining executions allowed in the current window
490
- */
491
- getRemainingInWindow = (): number => {
492
- const relevantExecutionTimes = this.#getExecutionTimesInWindow()
493
- return Math.max(0, this.#getLimit() - relevantExecutionTimes.length)
494
- }
495
-
496
- /**
497
- * Returns the number of milliseconds until the next execution will be possible
498
- * For fixed windows, this is the time until the current window resets
499
- * For sliding windows, this is the time until the oldest execution expires
500
- */
501
- getMsUntilNextWindow = (): number => {
502
- if (this.getRemainingInWindow() > 0) {
503
- return 0
504
- }
505
- const oldestExecution = this.store.state.executionTimes[0] ?? Infinity
506
- return oldestExecution + this.#getWindow() - Date.now()
507
- }
508
-
509
- /**
510
- * Returns the AbortSignal for a specific execution.
511
- * If no maybeExecuteCount is provided, returns the signal for the most recent execution.
512
- * Returns null if no execution is found or not currently executing.
513
- *
514
- * @param maybeExecuteCount - Optional specific execution to get signal for
515
- * @example
516
- * ```typescript
517
- * const rateLimiter = new AsyncRateLimiter(
518
- * async (userId: string) => {
519
- * const signal = rateLimiter.getAbortSignal()
520
- * if (signal) {
521
- * const response = await fetch(`/api/users/${userId}`, { signal })
522
- * return response.json()
523
- * }
524
- * },
525
- * { limit: 5, window: 1000 }
526
- * )
527
- * ```
528
- */
529
- getAbortSignal = (maybeExecuteCount?: number): AbortSignal | null => {
530
- const count = maybeExecuteCount ?? this.store.state.maybeExecuteCount
531
- const retryer = this.asyncRetryers.get(count)
532
- return retryer?.getAbortSignal() ?? null
533
- }
534
-
535
- /**
536
- * Aborts all ongoing executions with the internal abort controllers.
537
- * Does NOT clear out the execution times or reset the rate limiter.
538
- */
539
- abort = (): void => {
540
- this.asyncRetryers.forEach((retryer) => retryer.abort())
541
- this.asyncRetryers.clear()
542
- this.#setState({
543
- isExecuting: false,
544
- })
545
- }
546
-
547
- /**
548
- * Resets the rate limiter state
549
- */
550
- reset = (): void => {
551
- this.#setState(getDefaultAsyncRateLimiterState())
552
- this.#clearTimeouts()
553
- this.asyncRetryers.forEach((retryer) => retryer.reset())
554
- }
555
- }
556
-
557
- /**
558
- * Creates an async rate-limited function that will execute the provided function up to a maximum number of times within a time window.
559
- *
560
- * Async vs Sync Versions:
561
- * The async version provides advanced features over the sync rate limit function:
562
- * - Returns promises that can be awaited for rate-limited function results
563
- * - Built-in retry support via AsyncRetryer integration
564
- * - Abort support to cancel in-flight executions
565
- * - Comprehensive error handling with onError callbacks and throwOnError control
566
- * - Detailed execution tracking (success/error/settle counts, rejection counts)
567
- * - More sophisticated window management with automatic cleanup
568
- *
569
- * The sync rate limit function is lighter weight and simpler when you don't need async features,
570
- * return values, or execution control.
571
- *
572
- * What is Rate Limiting?
573
- * Rate limiting allows a function to execute up to a limit within a time window,
574
- * then blocks all subsequent calls until the window passes. This can lead to "bursty" behavior where
575
- * all executions happen immediately, followed by a complete block.
576
- *
577
- * Window Types:
578
- * - 'fixed': A strict window that resets after the window period. All executions within the window count
579
- * towards the limit, and the window resets completely after the period.
580
- * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
581
- * consistent rate of execution over time.
582
- *
583
- * Configuration Options:
584
- * - `limit`: Maximum number of executions allowed within the window (required)
585
- * - `window`: Time window in milliseconds (required)
586
- * - `windowType`: 'fixed' or 'sliding' (default: 'fixed')
587
- * - `enabled`: Whether the rate limiter is enabled (default: true)
588
- * - `asyncRetryerOptions`: Configure retry behavior for executions
589
- *
590
- * When to Use Rate Limiting:
591
- * Rate limiting is best used for hard API limits or resource constraints. For UI updates or
592
- * smoothing out frequent events, throttling or debouncing usually provide better user experience.
593
- * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets
594
- * - A throttler ensures even spacing between executions, which can be better for consistent performance
595
- * - A debouncer collapses multiple calls into one, which is better for handling bursts of events
596
- *
597
- * Error Handling:
598
- * - If an `onError` handler is provided, it will be called with the error and rate limiter instance
599
- * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
600
- * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
601
- * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
602
- * - The error state can be checked using the underlying AsyncRateLimiter instance
603
- * - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler
604
- *
605
- * State Management:
606
- * - Uses TanStack Store for reactive state management
607
- * - Use `initialState` to provide initial state values when creating the rate limiter
608
- * - `initialState` can be a partial state object
609
- * - Use `onSuccess` callback to react to successful function execution and implement custom logic
610
- * - Use `onError` callback to react to function execution errors and implement custom error handling
611
- * - Use `onSettled` callback to react to function execution completion (success or error) and implement custom logic
612
- * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded
613
- * - The state includes execution times, success/error counts, and current execution status
614
- * - State can be accessed via the underlying AsyncRateLimiter instance's `store.state` property
615
- * - When using framework adapters (React/Solid), state is accessed from the hook's state property
616
- *
617
- * @example
618
- * ```ts
619
- * // Rate limit to 5 calls per minute with a sliding window
620
- * const rateLimited = asyncRateLimit(makeApiCall, {
621
- * limit: 5,
622
- * window: 60000,
623
- * windowType: 'sliding',
624
- * onError: (error) => {
625
- * console.error('API call failed:', error);
626
- * },
627
- * onReject: (rateLimiter) => {
628
- * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
629
- * }
630
- * });
631
- *
632
- * // First 5 calls will execute immediately
633
- * // Additional calls will be rejected until the minute window resets
634
- * // Returns the API response directly
635
- * const result = await rateLimited();
636
- *
637
- * // For more even execution, consider using throttle instead:
638
- * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
639
- * ```
640
- */
641
- export function asyncRateLimit<TFn extends AnyAsyncFunction>(
642
- fn: TFn,
643
- initialOptions: AsyncRateLimiterOptions<TFn>,
644
- ) {
645
- const rateLimiter = new AsyncRateLimiter(fn, initialOptions)
646
- return rateLimiter.maybeExecute
647
- }