@tanstack/pacer 0.22.0 → 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 (100) hide show
  1. package/README.md +4 -4
  2. package/dist/async-batcher.d.ts +11 -13
  3. package/dist/async-batcher.js +185 -131
  4. package/dist/async-debouncer.d.ts +6 -8
  5. package/dist/async-debouncer.js +186 -142
  6. package/dist/async-queuer.d.ts +11 -13
  7. package/dist/async-queuer.js +383 -290
  8. package/dist/async-rate-limiter.d.ts +6 -8
  9. package/dist/async-rate-limiter.js +197 -143
  10. package/dist/async-retryer.d.ts +6 -8
  11. package/dist/async-retryer.js +209 -179
  12. package/dist/async-throttler.d.ts +6 -8
  13. package/dist/async-throttler.js +214 -157
  14. package/dist/batcher.d.ts +5 -7
  15. package/dist/batcher.js +107 -87
  16. package/dist/debouncer.d.ts +6 -8
  17. package/dist/debouncer.js +99 -86
  18. package/dist/event-client.d.ts +8 -10
  19. package/dist/event-client.js +1 -2
  20. package/dist/queuer.d.ts +7 -9
  21. package/dist/queuer.js +277 -212
  22. package/dist/rate-limiter.d.ts +6 -8
  23. package/dist/rate-limiter.js +127 -109
  24. package/dist/throttler.d.ts +6 -8
  25. package/dist/throttler.js +127 -90
  26. package/dist/types.d.ts +4 -6
  27. package/dist/utils.d.ts +3 -5
  28. package/dist/utils.js +1 -2
  29. package/package.json +21 -68
  30. package/dist/async-batcher.cjs +0 -337
  31. package/dist/async-batcher.cjs.map +0 -1
  32. package/dist/async-batcher.d.cts +0 -343
  33. package/dist/async-batcher.js.map +0 -1
  34. package/dist/async-debouncer.cjs +0 -327
  35. package/dist/async-debouncer.cjs.map +0 -1
  36. package/dist/async-debouncer.d.cts +0 -299
  37. package/dist/async-debouncer.js.map +0 -1
  38. package/dist/async-queuer.cjs +0 -516
  39. package/dist/async-queuer.cjs.map +0 -1
  40. package/dist/async-queuer.d.cts +0 -440
  41. package/dist/async-queuer.js.map +0 -1
  42. package/dist/async-rate-limiter.cjs +0 -370
  43. package/dist/async-rate-limiter.cjs.map +0 -1
  44. package/dist/async-rate-limiter.d.cts +0 -356
  45. package/dist/async-rate-limiter.js.map +0 -1
  46. package/dist/async-retryer.cjs +0 -365
  47. package/dist/async-retryer.cjs.map +0 -1
  48. package/dist/async-retryer.d.cts +0 -321
  49. package/dist/async-retryer.js.map +0 -1
  50. package/dist/async-throttler.cjs +0 -344
  51. package/dist/async-throttler.cjs.map +0 -1
  52. package/dist/async-throttler.d.cts +0 -319
  53. package/dist/async-throttler.js.map +0 -1
  54. package/dist/batcher.cjs +0 -200
  55. package/dist/batcher.cjs.map +0 -1
  56. package/dist/batcher.d.cts +0 -179
  57. package/dist/batcher.js.map +0 -1
  58. package/dist/debouncer.cjs +0 -203
  59. package/dist/debouncer.cjs.map +0 -1
  60. package/dist/debouncer.d.cts +0 -166
  61. package/dist/debouncer.js.map +0 -1
  62. package/dist/event-client.cjs +0 -64
  63. package/dist/event-client.cjs.map +0 -1
  64. package/dist/event-client.d.cts +0 -65
  65. package/dist/event-client.js.map +0 -1
  66. package/dist/index.cjs +0 -52
  67. package/dist/index.d.cts +0 -15
  68. package/dist/queuer.cjs +0 -406
  69. package/dist/queuer.cjs.map +0 -1
  70. package/dist/queuer.d.cts +0 -345
  71. package/dist/queuer.js.map +0 -1
  72. package/dist/rate-limiter.cjs +0 -263
  73. package/dist/rate-limiter.cjs.map +0 -1
  74. package/dist/rate-limiter.d.cts +0 -214
  75. package/dist/rate-limiter.js.map +0 -1
  76. package/dist/throttler.cjs +0 -215
  77. package/dist/throttler.cjs.map +0 -1
  78. package/dist/throttler.d.cts +0 -206
  79. package/dist/throttler.js.map +0 -1
  80. package/dist/types.cjs +0 -0
  81. package/dist/types.d.cts +0 -13
  82. package/dist/utils.cjs +0 -13
  83. package/dist/utils.cjs.map +0 -1
  84. package/dist/utils.d.cts +0 -7
  85. package/dist/utils.js.map +0 -1
  86. package/src/async-batcher.ts +0 -594
  87. package/src/async-debouncer.ts +0 -566
  88. package/src/async-queuer.ts +0 -988
  89. package/src/async-rate-limiter.ts +0 -648
  90. package/src/async-retryer.ts +0 -673
  91. package/src/async-throttler.ts +0 -634
  92. package/src/batcher.ts +0 -329
  93. package/src/debouncer.ts +0 -334
  94. package/src/event-client.ts +0 -129
  95. package/src/index.ts +0 -24
  96. package/src/queuer.ts +0 -751
  97. package/src/rate-limiter.ts +0 -429
  98. package/src/throttler.ts +0 -380
  99. package/src/types.ts +0 -12
  100. package/src/utils.ts +0 -12
@@ -1,648 +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: Awaited<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: Awaited<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<Awaited<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<Awaited<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(
397
- this.fn,
398
- this.options.asyncRetryerOptions,
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 Awaited<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
- // other executions may still be in flight within the window
420
- isExecuting: this.asyncRetryers.size > 0,
421
- settleCount: this.store.state.settleCount + 1,
422
- })
423
- this.options.onSettled?.(args, this)
424
- }
425
-
426
- return this.store.state.lastResult
427
- }
428
-
429
- #getExecutionTimesInWindow = (): Array<number> => {
430
- if (this.options.windowType === 'sliding') {
431
- // For sliding window, return all executions within the current window
432
- return this.store.state.executionTimes.filter(
433
- (time) => time > Date.now() - this.#getWindow(),
434
- )
435
- } else {
436
- // For fixed window, return all executions in the current window
437
- // The window starts from the oldest execution time
438
- if (this.store.state.executionTimes.length === 0) {
439
- return []
440
- }
441
- const oldestExecution = Math.min(...this.store.state.executionTimes)
442
- const windowStart = oldestExecution
443
- const windowEnd = windowStart + this.#getWindow()
444
- const now = Date.now()
445
-
446
- // If the window has expired, return empty array
447
- if (now > windowEnd) {
448
- return []
449
- }
450
-
451
- // Otherwise, return all executions in the current window
452
- return this.store.state.executionTimes.filter(
453
- (time) => time >= windowStart && time <= windowEnd,
454
- )
455
- }
456
- }
457
-
458
- #setCleanupTimeout = (executionTime: number): void => {
459
- if (
460
- this.options.windowType === 'sliding' ||
461
- this.#timeoutIds.size === 0 // new fixed window
462
- ) {
463
- const now = Date.now()
464
- const timeUntilExpiration = executionTime - now + this.#getWindow() + 1
465
- const timeoutId = setTimeout(() => {
466
- this.#cleanupOldExecutions()
467
- this.#clearTimeout(timeoutId)
468
- }, timeUntilExpiration)
469
- this.#timeoutIds.add(timeoutId)
470
- }
471
- }
472
-
473
- #clearTimeout = (timeoutId: ReturnType<typeof setTimeout>): void => {
474
- clearTimeout(timeoutId)
475
- this.#timeoutIds.delete(timeoutId)
476
- }
477
-
478
- #clearTimeouts = (): void => {
479
- this.#timeoutIds.forEach((timeoutId) => clearTimeout(timeoutId))
480
- this.#timeoutIds.clear()
481
- }
482
-
483
- #cleanupOldExecutions = (): void => {
484
- this.#setState({
485
- executionTimes: this.#getExecutionTimesInWindow(),
486
- })
487
- }
488
-
489
- /**
490
- * Returns the number of remaining executions allowed in the current window
491
- */
492
- getRemainingInWindow = (): number => {
493
- const relevantExecutionTimes = this.#getExecutionTimesInWindow()
494
- return Math.max(0, this.#getLimit() - relevantExecutionTimes.length)
495
- }
496
-
497
- /**
498
- * Returns the number of milliseconds until the next execution will be possible
499
- * For fixed windows, this is the time until the current window resets
500
- * For sliding windows, this is the time until the oldest execution expires
501
- */
502
- getMsUntilNextWindow = (): number => {
503
- if (this.getRemainingInWindow() > 0) {
504
- return 0
505
- }
506
- const oldestExecution = this.store.state.executionTimes[0] ?? Infinity
507
- return oldestExecution + this.#getWindow() - Date.now()
508
- }
509
-
510
- /**
511
- * Returns the AbortSignal for a specific execution.
512
- * If no maybeExecuteCount is provided, returns the signal for the most recent execution.
513
- * Returns null if no execution is found or not currently executing.
514
- *
515
- * @param maybeExecuteCount - Optional specific execution to get signal for
516
- * @example
517
- * ```typescript
518
- * const rateLimiter = new AsyncRateLimiter(
519
- * async (userId: string) => {
520
- * const signal = rateLimiter.getAbortSignal()
521
- * if (signal) {
522
- * const response = await fetch(`/api/users/${userId}`, { signal })
523
- * return response.json()
524
- * }
525
- * },
526
- * { limit: 5, window: 1000 }
527
- * )
528
- * ```
529
- */
530
- getAbortSignal = (maybeExecuteCount?: number): AbortSignal | null => {
531
- const count = maybeExecuteCount ?? this.store.state.maybeExecuteCount
532
- const retryer = this.asyncRetryers.get(count)
533
- return retryer?.getAbortSignal() ?? null
534
- }
535
-
536
- /**
537
- * Aborts all ongoing executions with the internal abort controllers.
538
- * Does NOT clear out the execution times or reset the rate limiter.
539
- */
540
- abort = (): void => {
541
- this.asyncRetryers.forEach((retryer) => retryer.abort())
542
- this.asyncRetryers.clear()
543
- this.#setState({
544
- isExecuting: false,
545
- })
546
- }
547
-
548
- /**
549
- * Resets the rate limiter state
550
- */
551
- reset = (): void => {
552
- this.#setState(getDefaultAsyncRateLimiterState())
553
- this.#clearTimeouts()
554
- this.asyncRetryers.forEach((retryer) => retryer.reset())
555
- }
556
- }
557
-
558
- /**
559
- * Creates an async rate-limited function that will execute the provided function up to a maximum number of times within a time window.
560
- *
561
- * Async vs Sync Versions:
562
- * The async version provides advanced features over the sync rate limit function:
563
- * - Returns promises that can be awaited for rate-limited function results
564
- * - Built-in retry support via AsyncRetryer integration
565
- * - Abort support to cancel in-flight executions
566
- * - Comprehensive error handling with onError callbacks and throwOnError control
567
- * - Detailed execution tracking (success/error/settle counts, rejection counts)
568
- * - More sophisticated window management with automatic cleanup
569
- *
570
- * The sync rate limit function is lighter weight and simpler when you don't need async features,
571
- * return values, or execution control.
572
- *
573
- * What is Rate Limiting?
574
- * Rate limiting allows a function to execute up to a limit within a time window,
575
- * then blocks all subsequent calls until the window passes. This can lead to "bursty" behavior where
576
- * all executions happen immediately, followed by a complete block.
577
- *
578
- * Window Types:
579
- * - 'fixed': A strict window that resets after the window period. All executions within the window count
580
- * towards the limit, and the window resets completely after the period.
581
- * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
582
- * consistent rate of execution over time.
583
- *
584
- * Configuration Options:
585
- * - `limit`: Maximum number of executions allowed within the window (required)
586
- * - `window`: Time window in milliseconds (required)
587
- * - `windowType`: 'fixed' or 'sliding' (default: 'fixed')
588
- * - `enabled`: Whether the rate limiter is enabled (default: true)
589
- * - `asyncRetryerOptions`: Configure retry behavior for executions
590
- *
591
- * When to Use Rate Limiting:
592
- * Rate limiting is best used for hard API limits or resource constraints. For UI updates or
593
- * smoothing out frequent events, throttling or debouncing usually provide better user experience.
594
- * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets
595
- * - A throttler ensures even spacing between executions, which can be better for consistent performance
596
- * - A debouncer collapses multiple calls into one, which is better for handling bursts of events
597
- *
598
- * Error Handling:
599
- * - If an `onError` handler is provided, it will be called with the error and rate limiter instance
600
- * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
601
- * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
602
- * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
603
- * - The error state can be checked using the underlying AsyncRateLimiter instance
604
- * - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler
605
- *
606
- * State Management:
607
- * - Uses TanStack Store for reactive state management
608
- * - Use `initialState` to provide initial state values when creating the rate limiter
609
- * - `initialState` can be a partial state object
610
- * - Use `onSuccess` callback to react to successful function execution and implement custom logic
611
- * - Use `onError` callback to react to function execution errors and implement custom error handling
612
- * - Use `onSettled` callback to react to function execution completion (success or error) and implement custom logic
613
- * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded
614
- * - The state includes execution times, success/error counts, and current execution status
615
- * - State can be accessed via the underlying AsyncRateLimiter instance's `store.state` property
616
- * - When using framework adapters (React/Solid), state is accessed from the hook's state property
617
- *
618
- * @example
619
- * ```ts
620
- * // Rate limit to 5 calls per minute with a sliding window
621
- * const rateLimited = asyncRateLimit(makeApiCall, {
622
- * limit: 5,
623
- * window: 60000,
624
- * windowType: 'sliding',
625
- * onError: (error) => {
626
- * console.error('API call failed:', error);
627
- * },
628
- * onReject: (rateLimiter) => {
629
- * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
630
- * }
631
- * });
632
- *
633
- * // First 5 calls will execute immediately
634
- * // Additional calls will be rejected until the minute window resets
635
- * // Returns the API response directly
636
- * const result = await rateLimited();
637
- *
638
- * // For more even execution, consider using throttle instead:
639
- * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
640
- * ```
641
- */
642
- export function asyncRateLimit<TFn extends AnyAsyncFunction>(
643
- fn: TFn,
644
- initialOptions: AsyncRateLimiterOptions<TFn>,
645
- ) {
646
- const rateLimiter = new AsyncRateLimiter(fn, initialOptions)
647
- return rateLimiter.maybeExecute
648
- }