@tanstack/pacer 0.2.0 → 0.4.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.
- package/dist/cjs/async-debouncer.cjs +78 -45
- package/dist/cjs/async-debouncer.cjs.map +1 -1
- package/dist/cjs/async-debouncer.d.cts +60 -24
- package/dist/cjs/async-queuer.cjs +53 -3
- package/dist/cjs/async-queuer.cjs.map +1 -1
- package/dist/cjs/async-queuer.d.cts +28 -3
- package/dist/cjs/async-rate-limiter.cjs +75 -38
- package/dist/cjs/async-rate-limiter.cjs.map +1 -1
- package/dist/cjs/async-rate-limiter.d.cts +76 -24
- package/dist/cjs/async-throttler.cjs +85 -57
- package/dist/cjs/async-throttler.cjs.map +1 -1
- package/dist/cjs/async-throttler.d.cts +66 -25
- package/dist/cjs/debouncer.cjs +12 -14
- package/dist/cjs/debouncer.cjs.map +1 -1
- package/dist/cjs/debouncer.d.cts +10 -9
- package/dist/cjs/queuer.cjs +51 -1
- package/dist/cjs/queuer.cjs.map +1 -1
- package/dist/cjs/queuer.d.cts +30 -1
- package/dist/cjs/rate-limiter.cjs +19 -9
- package/dist/cjs/rate-limiter.cjs.map +1 -1
- package/dist/cjs/rate-limiter.d.cts +31 -11
- package/dist/cjs/throttler.cjs +29 -36
- package/dist/cjs/throttler.cjs.map +1 -1
- package/dist/cjs/throttler.d.cts +16 -17
- package/dist/cjs/types.d.cts +2 -6
- package/dist/cjs/utils.cjs.map +1 -1
- package/dist/cjs/utils.d.cts +1 -1
- package/dist/esm/async-debouncer.d.ts +60 -24
- package/dist/esm/async-debouncer.js +78 -45
- package/dist/esm/async-debouncer.js.map +1 -1
- package/dist/esm/async-queuer.d.ts +28 -3
- package/dist/esm/async-queuer.js +53 -3
- package/dist/esm/async-queuer.js.map +1 -1
- package/dist/esm/async-rate-limiter.d.ts +76 -24
- package/dist/esm/async-rate-limiter.js +75 -38
- package/dist/esm/async-rate-limiter.js.map +1 -1
- package/dist/esm/async-throttler.d.ts +66 -25
- package/dist/esm/async-throttler.js +85 -57
- package/dist/esm/async-throttler.js.map +1 -1
- package/dist/esm/debouncer.d.ts +10 -9
- package/dist/esm/debouncer.js +12 -14
- package/dist/esm/debouncer.js.map +1 -1
- package/dist/esm/queuer.d.ts +30 -1
- package/dist/esm/queuer.js +51 -1
- package/dist/esm/queuer.js.map +1 -1
- package/dist/esm/rate-limiter.d.ts +31 -11
- package/dist/esm/rate-limiter.js +19 -9
- package/dist/esm/rate-limiter.js.map +1 -1
- package/dist/esm/throttler.d.ts +16 -17
- package/dist/esm/throttler.js +29 -36
- package/dist/esm/throttler.js.map +1 -1
- package/dist/esm/types.d.ts +2 -6
- package/dist/esm/utils.d.ts +1 -1
- package/dist/esm/utils.js.map +1 -1
- package/package.json +1 -1
- package/src/async-debouncer.ts +130 -81
- package/src/async-queuer.ts +93 -8
- package/src/async-rate-limiter.ts +141 -67
- package/src/async-throttler.ts +152 -94
- package/src/debouncer.ts +26 -33
- package/src/queuer.ts +92 -4
- package/src/rate-limiter.ts +56 -32
- package/src/throttler.ts +45 -53
- package/src/types.ts +2 -10
- package/src/utils.ts +1 -1
package/src/async-queuer.ts
CHANGED
|
@@ -10,6 +10,16 @@ export interface AsyncQueuerOptions<TValue> {
|
|
|
10
10
|
* Maximum number of concurrent tasks to process
|
|
11
11
|
*/
|
|
12
12
|
concurrency?: number
|
|
13
|
+
/**
|
|
14
|
+
* Maximum time in milliseconds that an item can stay in the queue
|
|
15
|
+
* If not provided, items will never expire
|
|
16
|
+
*/
|
|
17
|
+
expirationDuration?: number
|
|
18
|
+
/**
|
|
19
|
+
* Function to determine if an item has expired
|
|
20
|
+
* If provided, this overrides the expirationDuration behavior
|
|
21
|
+
*/
|
|
22
|
+
getIsExpired?: (item: () => Promise<TValue>, addedAt: number) => boolean
|
|
13
23
|
/**
|
|
14
24
|
* Default position to get items from during processing
|
|
15
25
|
* @default 'front'
|
|
@@ -49,7 +59,11 @@ export interface AsyncQueuerOptions<TValue> {
|
|
|
49
59
|
*/
|
|
50
60
|
onReject?: (item: () => Promise<TValue>, queuer: AsyncQueuer<TValue>) => void
|
|
51
61
|
/**
|
|
52
|
-
*
|
|
62
|
+
* Callback fired whenever an item expires in the queuer
|
|
63
|
+
*/
|
|
64
|
+
onExpire?: (item: () => Promise<TValue>, queuer: AsyncQueuer<TValue>) => void
|
|
65
|
+
/**
|
|
66
|
+
* Whether the queuer should start processing tasks immediately or not.
|
|
53
67
|
*/
|
|
54
68
|
started?: boolean
|
|
55
69
|
/**
|
|
@@ -61,6 +75,8 @@ export interface AsyncQueuerOptions<TValue> {
|
|
|
61
75
|
const defaultOptions: Required<AsyncQueuerOptions<any>> = {
|
|
62
76
|
addItemsTo: 'back',
|
|
63
77
|
concurrency: 1,
|
|
78
|
+
expirationDuration: Infinity,
|
|
79
|
+
getIsExpired: () => false,
|
|
64
80
|
getItemsFrom: 'front',
|
|
65
81
|
getPriority: (item) => (item as any)?.priority ?? 0,
|
|
66
82
|
initialItems: [],
|
|
@@ -69,7 +85,8 @@ const defaultOptions: Required<AsyncQueuerOptions<any>> = {
|
|
|
69
85
|
onIsRunningChange: () => {},
|
|
70
86
|
onItemsChange: () => {},
|
|
71
87
|
onReject: () => {},
|
|
72
|
-
|
|
88
|
+
onExpire: () => {},
|
|
89
|
+
started: true,
|
|
73
90
|
wait: 0,
|
|
74
91
|
}
|
|
75
92
|
|
|
@@ -83,6 +100,7 @@ const defaultOptions: Required<AsyncQueuerOptions<any>> = {
|
|
|
83
100
|
* - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior
|
|
84
101
|
* - Pause/resume task processing
|
|
85
102
|
* - Task cancellation
|
|
103
|
+
* - Item expiration to clear stale items from the queue
|
|
86
104
|
*
|
|
87
105
|
* Tasks are processed concurrently up to the configured concurrency limit. When a task completes,
|
|
88
106
|
* the next pending task is processed if below the concurrency limit.
|
|
@@ -107,7 +125,9 @@ export class AsyncQueuer<TValue> {
|
|
|
107
125
|
private _activeItems: Set<() => Promise<TValue>> = new Set()
|
|
108
126
|
private _executionCount = 0
|
|
109
127
|
private _rejectionCount = 0
|
|
128
|
+
private _expirationCount = 0
|
|
110
129
|
private _items: Array<() => Promise<TValue>> = []
|
|
130
|
+
private _itemTimestamps: Array<number> = []
|
|
111
131
|
private _onErrorCallbacks: Array<(error: Error) => void> = []
|
|
112
132
|
private _onSettledCallbacks: Array<(result: TValue | Error) => void> = []
|
|
113
133
|
private _onSuccessCallbacks: Array<(result: TValue) => void> = []
|
|
@@ -129,11 +149,8 @@ export class AsyncQueuer<TValue> {
|
|
|
129
149
|
* Updates the queuer options
|
|
130
150
|
* Returns the new options state
|
|
131
151
|
*/
|
|
132
|
-
setOptions(
|
|
133
|
-
newOptions: Partial<AsyncQueuerOptions<TValue>>,
|
|
134
|
-
): AsyncQueuerOptions<TValue> {
|
|
152
|
+
setOptions(newOptions: Partial<AsyncQueuerOptions<TValue>>): void {
|
|
135
153
|
this._options = { ...this._options, ...newOptions }
|
|
136
|
-
return this._options
|
|
137
154
|
}
|
|
138
155
|
|
|
139
156
|
/**
|
|
@@ -152,6 +169,9 @@ export class AsyncQueuer<TValue> {
|
|
|
152
169
|
return
|
|
153
170
|
}
|
|
154
171
|
|
|
172
|
+
// Check for expired items
|
|
173
|
+
this.checkExpiredItems()
|
|
174
|
+
|
|
155
175
|
while (
|
|
156
176
|
this._activeItems.size < this._options.concurrency &&
|
|
157
177
|
!this.getIsEmpty()
|
|
@@ -196,6 +216,56 @@ export class AsyncQueuer<TValue> {
|
|
|
196
216
|
this._pendingTick = false
|
|
197
217
|
}
|
|
198
218
|
|
|
219
|
+
/**
|
|
220
|
+
* Checks for and removes expired items from the queuer
|
|
221
|
+
*/
|
|
222
|
+
private checkExpiredItems() {
|
|
223
|
+
if (
|
|
224
|
+
this._options.expirationDuration === Infinity &&
|
|
225
|
+
this._options.getIsExpired === defaultOptions.getIsExpired
|
|
226
|
+
)
|
|
227
|
+
return
|
|
228
|
+
|
|
229
|
+
const now = Date.now()
|
|
230
|
+
const expiredIndices: Array<number> = []
|
|
231
|
+
|
|
232
|
+
// Find indices of expired items
|
|
233
|
+
for (let i = 0; i < this._items.length; i++) {
|
|
234
|
+
const timestamp = this._itemTimestamps[i]
|
|
235
|
+
if (timestamp === undefined) continue
|
|
236
|
+
|
|
237
|
+
const item = this._items[i]
|
|
238
|
+
if (item === undefined) continue
|
|
239
|
+
|
|
240
|
+
const isExpired =
|
|
241
|
+
this._options.getIsExpired !== defaultOptions.getIsExpired
|
|
242
|
+
? this._options.getIsExpired(item, timestamp)
|
|
243
|
+
: now - timestamp > this._options.expirationDuration
|
|
244
|
+
|
|
245
|
+
if (isExpired) {
|
|
246
|
+
expiredIndices.push(i)
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// Remove expired items from back to front to maintain indices
|
|
251
|
+
for (let i = expiredIndices.length - 1; i >= 0; i--) {
|
|
252
|
+
const index = expiredIndices[i]
|
|
253
|
+
if (index === undefined) continue
|
|
254
|
+
|
|
255
|
+
const expiredItem = this._items[index]
|
|
256
|
+
if (expiredItem === undefined) continue
|
|
257
|
+
|
|
258
|
+
this._items.splice(index, 1)
|
|
259
|
+
this._itemTimestamps.splice(index, 1)
|
|
260
|
+
this._expirationCount++
|
|
261
|
+
this._options.onExpire(expiredItem, this)
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
if (expiredIndices.length > 0) {
|
|
265
|
+
this._options.onItemsChange(this)
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
199
269
|
/**
|
|
200
270
|
* Starts the queuer and processes items
|
|
201
271
|
*/
|
|
@@ -295,15 +365,19 @@ export class AsyncQueuer<TValue> {
|
|
|
295
365
|
|
|
296
366
|
if (insertIndex === -1) {
|
|
297
367
|
this._items.push(task)
|
|
368
|
+
this._itemTimestamps.push(Date.now())
|
|
298
369
|
} else {
|
|
299
370
|
this._items.splice(insertIndex, 0, task)
|
|
371
|
+
this._itemTimestamps.splice(insertIndex, 0, Date.now())
|
|
300
372
|
}
|
|
301
373
|
} else {
|
|
302
374
|
// Default FIFO/LIFO behavior
|
|
303
375
|
if (position === 'front') {
|
|
304
376
|
this._items.unshift(task)
|
|
377
|
+
this._itemTimestamps.unshift(Date.now())
|
|
305
378
|
} else {
|
|
306
379
|
this._items.push(task)
|
|
380
|
+
this._itemTimestamps.push(Date.now())
|
|
307
381
|
}
|
|
308
382
|
}
|
|
309
383
|
|
|
@@ -328,8 +402,10 @@ export class AsyncQueuer<TValue> {
|
|
|
328
402
|
|
|
329
403
|
if (position === 'front') {
|
|
330
404
|
item = this._items.shift()
|
|
405
|
+
this._itemTimestamps.shift()
|
|
331
406
|
} else {
|
|
332
407
|
item = this._items.pop()
|
|
408
|
+
this._itemTimestamps.pop()
|
|
333
409
|
}
|
|
334
410
|
|
|
335
411
|
if (item !== undefined) {
|
|
@@ -455,6 +531,13 @@ export class AsyncQueuer<TValue> {
|
|
|
455
531
|
)
|
|
456
532
|
}
|
|
457
533
|
}
|
|
534
|
+
|
|
535
|
+
/**
|
|
536
|
+
* Returns the number of items that have expired from the queuer
|
|
537
|
+
*/
|
|
538
|
+
getExpirationCount(): number {
|
|
539
|
+
return this._expirationCount
|
|
540
|
+
}
|
|
458
541
|
}
|
|
459
542
|
|
|
460
543
|
/**
|
|
@@ -474,7 +557,9 @@ export class AsyncQueuer<TValue> {
|
|
|
474
557
|
* @param options - Configuration options for the AsyncQueuer
|
|
475
558
|
* @returns A bound addItem function that can be used to add tasks to the queuer
|
|
476
559
|
*/
|
|
477
|
-
export function asyncQueue<TValue>(
|
|
478
|
-
|
|
560
|
+
export function asyncQueue<TValue>(
|
|
561
|
+
options: Omit<AsyncQueuerOptions<TValue>, 'started'> = {},
|
|
562
|
+
) {
|
|
563
|
+
const queuer = new AsyncQueuer<TValue>(options)
|
|
479
564
|
return queuer.addItem.bind(queuer)
|
|
480
565
|
}
|
|
@@ -3,10 +3,7 @@ import type { AnyAsyncFunction } from './types'
|
|
|
3
3
|
/**
|
|
4
4
|
* Options for configuring an async rate-limited function
|
|
5
5
|
*/
|
|
6
|
-
export interface AsyncRateLimiterOptions<
|
|
7
|
-
TFn extends AnyAsyncFunction,
|
|
8
|
-
TArgs extends Parameters<TFn>,
|
|
9
|
-
> {
|
|
6
|
+
export interface AsyncRateLimiterOptions<TFn extends AnyAsyncFunction> {
|
|
10
7
|
/**
|
|
11
8
|
* Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.
|
|
12
9
|
* Defaults to true.
|
|
@@ -19,28 +16,44 @@ export interface AsyncRateLimiterOptions<
|
|
|
19
16
|
/**
|
|
20
17
|
* Optional error handler for when the rate-limited function throws
|
|
21
18
|
*/
|
|
22
|
-
onError?: (error: unknown) => void
|
|
19
|
+
onError?: (error: unknown, rateLimiter: AsyncRateLimiter<TFn>) => void
|
|
20
|
+
/**
|
|
21
|
+
* Optional callback function that is called when an execution is rejected due to rate limiting
|
|
22
|
+
*/
|
|
23
|
+
onReject?: (rateLimiter: AsyncRateLimiter<TFn>) => void
|
|
23
24
|
/**
|
|
24
25
|
* Optional function to call when the rate-limited function is executed
|
|
25
26
|
*/
|
|
26
|
-
|
|
27
|
+
onSettled?: (rateLimiter: AsyncRateLimiter<TFn>) => void
|
|
27
28
|
/**
|
|
28
|
-
* Optional
|
|
29
|
+
* Optional function to call when the rate-limited function is executed
|
|
29
30
|
*/
|
|
30
|
-
|
|
31
|
+
onSuccess?: (
|
|
32
|
+
result: ReturnType<TFn>,
|
|
33
|
+
rateLimiter: AsyncRateLimiter<TFn>,
|
|
34
|
+
) => void
|
|
31
35
|
/**
|
|
32
36
|
* Time window in milliseconds within which the limit applies
|
|
33
37
|
*/
|
|
34
38
|
window: number
|
|
39
|
+
/**
|
|
40
|
+
* Type of window to use for rate limiting
|
|
41
|
+
* - 'fixed': Uses a fixed window that resets after the window period
|
|
42
|
+
* - 'sliding': Uses a sliding window that allows executions as old ones expire
|
|
43
|
+
* Defaults to 'fixed'
|
|
44
|
+
*/
|
|
45
|
+
windowType?: 'fixed' | 'sliding'
|
|
35
46
|
}
|
|
36
47
|
|
|
37
48
|
const defaultOptions: Required<
|
|
38
|
-
Omit<AsyncRateLimiterOptions<any
|
|
49
|
+
Omit<AsyncRateLimiterOptions<any>, 'limit' | 'window'>
|
|
39
50
|
> = {
|
|
40
51
|
enabled: true,
|
|
41
|
-
onReject: () => {},
|
|
42
52
|
onError: () => {},
|
|
43
|
-
|
|
53
|
+
onReject: () => {},
|
|
54
|
+
onSettled: () => {},
|
|
55
|
+
onSuccess: () => {},
|
|
56
|
+
windowType: 'fixed',
|
|
44
57
|
}
|
|
45
58
|
|
|
46
59
|
/**
|
|
@@ -50,6 +63,16 @@ const defaultOptions: Required<
|
|
|
50
63
|
* then blocks all subsequent calls until the window passes. This can lead to "bursty" behavior where
|
|
51
64
|
* all executions happen immediately, followed by a complete block.
|
|
52
65
|
*
|
|
66
|
+
* The rate limiter supports two types of windows:
|
|
67
|
+
* - 'fixed': A strict window that resets after the window period. All executions within the window count
|
|
68
|
+
* towards the limit, and the window resets completely after the period.
|
|
69
|
+
* - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
|
|
70
|
+
* consistent rate of execution over time.
|
|
71
|
+
*
|
|
72
|
+
* Unlike the non-async RateLimiter, this async version supports returning values from the rate-limited function,
|
|
73
|
+
* making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
|
|
74
|
+
* instead of setting the result on a state variable from within the rate-limited function.
|
|
75
|
+
*
|
|
53
76
|
* For smoother execution patterns, consider using:
|
|
54
77
|
* - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)
|
|
55
78
|
* - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)
|
|
@@ -61,25 +84,27 @@ const defaultOptions: Required<
|
|
|
61
84
|
* ```ts
|
|
62
85
|
* const rateLimiter = new AsyncRateLimiter(
|
|
63
86
|
* async (id: string) => await api.getData(id),
|
|
64
|
-
* { limit: 5, window: 1000 } // 5 calls per second
|
|
87
|
+
* { limit: 5, window: 1000, windowType: 'sliding' } // 5 calls per second with sliding window
|
|
65
88
|
* );
|
|
66
89
|
*
|
|
67
90
|
* // Will execute immediately until limit reached, then block
|
|
68
|
-
*
|
|
91
|
+
* // Returns the API response directly
|
|
92
|
+
* const data = await rateLimiter.maybeExecute('123');
|
|
69
93
|
* ```
|
|
70
94
|
*/
|
|
71
|
-
export class AsyncRateLimiter<
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
> {
|
|
75
|
-
private _executionCount = 0
|
|
95
|
+
export class AsyncRateLimiter<TFn extends AnyAsyncFunction> {
|
|
96
|
+
private _options: AsyncRateLimiterOptions<TFn>
|
|
97
|
+
private _errorCount = 0
|
|
76
98
|
private _executionTimes: Array<number> = []
|
|
77
|
-
private
|
|
99
|
+
private _lastResult: ReturnType<TFn> | undefined
|
|
78
100
|
private _rejectionCount = 0
|
|
101
|
+
private _settleCount = 0
|
|
102
|
+
private _successCount = 0
|
|
103
|
+
private _isExecuting = false
|
|
79
104
|
|
|
80
105
|
constructor(
|
|
81
106
|
private fn: TFn,
|
|
82
|
-
initialOptions: AsyncRateLimiterOptions<TFn
|
|
107
|
+
initialOptions: AsyncRateLimiterOptions<TFn>,
|
|
83
108
|
) {
|
|
84
109
|
this._options = {
|
|
85
110
|
...defaultOptions,
|
|
@@ -91,21 +116,15 @@ export class AsyncRateLimiter<
|
|
|
91
116
|
* Updates the rate limiter options
|
|
92
117
|
* Returns the new options state
|
|
93
118
|
*/
|
|
94
|
-
setOptions(
|
|
95
|
-
|
|
96
|
-
): AsyncRateLimiterOptions<TFn, TArgs> {
|
|
97
|
-
this._options = {
|
|
98
|
-
...this._options,
|
|
99
|
-
...newOptions,
|
|
100
|
-
}
|
|
101
|
-
return this._options
|
|
119
|
+
setOptions(newOptions: Partial<AsyncRateLimiterOptions<TFn>>): void {
|
|
120
|
+
this._options = { ...this._options, ...newOptions }
|
|
102
121
|
}
|
|
103
122
|
|
|
104
123
|
/**
|
|
105
124
|
* Returns the current rate limiter options
|
|
106
125
|
*/
|
|
107
|
-
getOptions(): Required<AsyncRateLimiterOptions<TFn
|
|
108
|
-
return this._options as Required<AsyncRateLimiterOptions<TFn
|
|
126
|
+
getOptions(): Required<AsyncRateLimiterOptions<TFn>> {
|
|
127
|
+
return this._options as Required<AsyncRateLimiterOptions<TFn>>
|
|
109
128
|
}
|
|
110
129
|
|
|
111
130
|
/**
|
|
@@ -124,38 +143,55 @@ export class AsyncRateLimiter<
|
|
|
124
143
|
* await rateLimiter.maybeExecute('arg1', 'arg2'); // Rejected
|
|
125
144
|
* ```
|
|
126
145
|
*/
|
|
127
|
-
async maybeExecute(
|
|
146
|
+
async maybeExecute(
|
|
147
|
+
...args: Parameters<TFn>
|
|
148
|
+
): Promise<ReturnType<TFn> | undefined> {
|
|
128
149
|
this.cleanupOldExecutions()
|
|
129
150
|
|
|
130
|
-
if (this.
|
|
131
|
-
|
|
132
|
-
|
|
151
|
+
if (this._options.windowType === 'sliding') {
|
|
152
|
+
// For sliding window, we can execute if we have capacity in the current window
|
|
153
|
+
if (this._executionTimes.length < this._options.limit) {
|
|
154
|
+
await this.executeFunction(...args)
|
|
155
|
+
return this._lastResult
|
|
156
|
+
}
|
|
157
|
+
} else {
|
|
158
|
+
// For fixed window, we need to check if we're in a new window
|
|
159
|
+
const now = Date.now()
|
|
160
|
+
const oldestExecution = Math.min(...this._executionTimes)
|
|
161
|
+
const isNewWindow = oldestExecution + this._options.window <= now
|
|
162
|
+
|
|
163
|
+
if (isNewWindow || this._executionTimes.length < this._options.limit) {
|
|
164
|
+
await this.executeFunction(...args)
|
|
165
|
+
return this._lastResult
|
|
166
|
+
}
|
|
133
167
|
}
|
|
134
168
|
|
|
135
169
|
this.rejectFunction()
|
|
136
|
-
return
|
|
170
|
+
return undefined
|
|
137
171
|
}
|
|
138
172
|
|
|
139
|
-
private async executeFunction(
|
|
173
|
+
private async executeFunction(
|
|
174
|
+
...args: Parameters<TFn>
|
|
175
|
+
): Promise<ReturnType<TFn> | undefined> {
|
|
140
176
|
if (!this._options.enabled) return
|
|
177
|
+
this._isExecuting = true
|
|
141
178
|
const now = Date.now()
|
|
142
|
-
this._executionCount++
|
|
143
179
|
this._executionTimes.push(now)
|
|
144
180
|
|
|
145
181
|
try {
|
|
146
|
-
await this.fn(...args)
|
|
182
|
+
this._lastResult = await this.fn(...args)
|
|
183
|
+
this._successCount++
|
|
184
|
+
this._options.onSuccess?.(this._lastResult!, this)
|
|
147
185
|
} catch (error) {
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
this._options.onError(error)
|
|
151
|
-
} catch (error) {
|
|
152
|
-
console.error('Error in onError handler', error)
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
throw error
|
|
186
|
+
this._errorCount++
|
|
187
|
+
this._options.onError?.(error, this)
|
|
156
188
|
} finally {
|
|
157
|
-
this.
|
|
189
|
+
this._isExecuting = false
|
|
190
|
+
this._settleCount++
|
|
191
|
+
this._options.onSettled?.(this)
|
|
158
192
|
}
|
|
193
|
+
|
|
194
|
+
return this._lastResult
|
|
159
195
|
}
|
|
160
196
|
|
|
161
197
|
private rejectFunction(): void {
|
|
@@ -173,33 +209,60 @@ export class AsyncRateLimiter<
|
|
|
173
209
|
)
|
|
174
210
|
}
|
|
175
211
|
|
|
212
|
+
/**
|
|
213
|
+
* Returns the number of remaining executions allowed in the current window
|
|
214
|
+
*/
|
|
215
|
+
getRemainingInWindow(): number {
|
|
216
|
+
this.cleanupOldExecutions()
|
|
217
|
+
return Math.max(0, this._options.limit - this._executionTimes.length)
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Returns the number of milliseconds until the next execution will be possible
|
|
222
|
+
* For fixed windows, this is the time until the current window resets
|
|
223
|
+
* For sliding windows, this is the time until the oldest execution expires
|
|
224
|
+
*/
|
|
225
|
+
getMsUntilNextWindow(): number {
|
|
226
|
+
if (this.getRemainingInWindow() > 0) {
|
|
227
|
+
return 0
|
|
228
|
+
}
|
|
229
|
+
const oldestExecution = Math.min(...this._executionTimes)
|
|
230
|
+
return oldestExecution + this._options.window - Date.now()
|
|
231
|
+
}
|
|
232
|
+
|
|
176
233
|
/**
|
|
177
234
|
* Returns the number of times the function has been executed
|
|
178
235
|
*/
|
|
179
|
-
|
|
180
|
-
return this.
|
|
236
|
+
getSuccessCount(): number {
|
|
237
|
+
return this._successCount
|
|
181
238
|
}
|
|
182
239
|
|
|
183
240
|
/**
|
|
184
|
-
* Returns the number of times the function has been
|
|
241
|
+
* Returns the number of times the function has been settled
|
|
185
242
|
*/
|
|
186
|
-
|
|
187
|
-
return this.
|
|
243
|
+
getSettleCount(): number {
|
|
244
|
+
return this._settleCount
|
|
188
245
|
}
|
|
189
246
|
|
|
190
247
|
/**
|
|
191
|
-
* Returns the number of
|
|
248
|
+
* Returns the number of times the function has errored
|
|
192
249
|
*/
|
|
193
|
-
|
|
194
|
-
this.
|
|
195
|
-
return Math.max(0, this._options.limit - this._executionTimes.length)
|
|
250
|
+
getErrorCount(): number {
|
|
251
|
+
return this._errorCount
|
|
196
252
|
}
|
|
197
253
|
|
|
198
254
|
/**
|
|
199
|
-
* Returns the number of
|
|
255
|
+
* Returns the number of times the function has been rejected
|
|
200
256
|
*/
|
|
201
|
-
|
|
202
|
-
return this.
|
|
257
|
+
getRejectionCount(): number {
|
|
258
|
+
return this._rejectionCount
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* Returns whether the function is currently executing
|
|
263
|
+
*/
|
|
264
|
+
getIsExecuting(): boolean {
|
|
265
|
+
return this._isExecuting
|
|
203
266
|
}
|
|
204
267
|
|
|
205
268
|
/**
|
|
@@ -207,14 +270,26 @@ export class AsyncRateLimiter<
|
|
|
207
270
|
*/
|
|
208
271
|
reset(): void {
|
|
209
272
|
this._executionTimes = []
|
|
210
|
-
this.
|
|
273
|
+
this._successCount = 0
|
|
274
|
+
this._errorCount = 0
|
|
211
275
|
this._rejectionCount = 0
|
|
276
|
+
this._settleCount = 0
|
|
212
277
|
}
|
|
213
278
|
}
|
|
214
279
|
|
|
215
280
|
/**
|
|
216
281
|
* Creates an async rate-limited function that will execute the provided function up to a maximum number of times within a time window.
|
|
217
282
|
*
|
|
283
|
+
* Unlike the non-async rate limiter, this async version supports returning values from the rate-limited function,
|
|
284
|
+
* making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
|
|
285
|
+
* instead of setting the result on a state variable from within the rate-limited function.
|
|
286
|
+
*
|
|
287
|
+
* The rate limiter supports two types of windows:
|
|
288
|
+
* - 'fixed': A strict window that resets after the window period. All executions within the window count
|
|
289
|
+
* towards the limit, and the window resets completely after the period.
|
|
290
|
+
* - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
|
|
291
|
+
* consistent rate of execution over time.
|
|
292
|
+
*
|
|
218
293
|
* Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:
|
|
219
294
|
* - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets
|
|
220
295
|
* - A throttler ensures even spacing between executions, which can be better for consistent performance
|
|
@@ -225,10 +300,11 @@ export class AsyncRateLimiter<
|
|
|
225
300
|
*
|
|
226
301
|
* @example
|
|
227
302
|
* ```ts
|
|
228
|
-
* // Rate limit to 5 calls per minute
|
|
303
|
+
* // Rate limit to 5 calls per minute with a sliding window
|
|
229
304
|
* const rateLimited = asyncRateLimit(makeApiCall, {
|
|
230
305
|
* limit: 5,
|
|
231
306
|
* window: 60000,
|
|
307
|
+
* windowType: 'sliding',
|
|
232
308
|
* onReject: (rateLimiter) => {
|
|
233
309
|
* console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
|
|
234
310
|
* }
|
|
@@ -236,18 +312,16 @@ export class AsyncRateLimiter<
|
|
|
236
312
|
*
|
|
237
313
|
* // First 5 calls will execute immediately
|
|
238
314
|
* // Additional calls will be rejected until the minute window resets
|
|
239
|
-
*
|
|
315
|
+
* // Returns the API response directly
|
|
316
|
+
* const result = await rateLimited();
|
|
240
317
|
*
|
|
241
318
|
* // For more even execution, consider using throttle instead:
|
|
242
319
|
* const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
|
|
243
320
|
* ```
|
|
244
321
|
*/
|
|
245
|
-
export function asyncRateLimit<
|
|
246
|
-
TFn extends AnyAsyncFunction,
|
|
247
|
-
TArgs extends Parameters<TFn>,
|
|
248
|
-
>(
|
|
322
|
+
export function asyncRateLimit<TFn extends AnyAsyncFunction>(
|
|
249
323
|
fn: TFn,
|
|
250
|
-
initialOptions: Omit<AsyncRateLimiterOptions<TFn
|
|
324
|
+
initialOptions: Omit<AsyncRateLimiterOptions<TFn>, 'enabled'>,
|
|
251
325
|
) {
|
|
252
326
|
const rateLimiter = new AsyncRateLimiter(fn, initialOptions)
|
|
253
327
|
return rateLimiter.maybeExecute.bind(rateLimiter)
|