@tanstack/pacer 0.4.0 → 0.6.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 +39 -15
- package/dist/cjs/async-debouncer.cjs.map +1 -1
- package/dist/cjs/async-debouncer.d.cts +63 -11
- package/dist/cjs/async-queuer.cjs +102 -119
- package/dist/cjs/async-queuer.cjs.map +1 -1
- package/dist/cjs/async-queuer.d.cts +94 -52
- package/dist/cjs/async-rate-limiter.cjs +48 -16
- package/dist/cjs/async-rate-limiter.cjs.map +1 -1
- package/dist/cjs/async-rate-limiter.d.cts +74 -9
- package/dist/cjs/async-throttler.cjs +42 -17
- package/dist/cjs/async-throttler.cjs.map +1 -1
- package/dist/cjs/async-throttler.d.cts +62 -10
- package/dist/cjs/debouncer.cjs +16 -3
- package/dist/cjs/debouncer.cjs.map +1 -1
- package/dist/cjs/debouncer.d.cts +14 -4
- package/dist/cjs/index.cjs +2 -0
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/queuer.cjs +13 -5
- package/dist/cjs/queuer.cjs.map +1 -1
- package/dist/cjs/queuer.d.cts +9 -3
- package/dist/cjs/rate-limiter.cjs +26 -7
- package/dist/cjs/rate-limiter.cjs.map +1 -1
- package/dist/cjs/rate-limiter.d.cts +20 -6
- package/dist/cjs/throttler.cjs +19 -5
- package/dist/cjs/throttler.cjs.map +1 -1
- package/dist/cjs/throttler.d.cts +15 -4
- package/dist/cjs/types.d.cts +1 -0
- package/dist/cjs/utils.cjs +18 -7
- package/dist/cjs/utils.cjs.map +1 -1
- package/dist/cjs/utils.d.cts +3 -0
- package/dist/esm/async-debouncer.d.ts +63 -11
- package/dist/esm/async-debouncer.js +39 -15
- package/dist/esm/async-debouncer.js.map +1 -1
- package/dist/esm/async-queuer.d.ts +94 -52
- package/dist/esm/async-queuer.js +102 -119
- package/dist/esm/async-queuer.js.map +1 -1
- package/dist/esm/async-rate-limiter.d.ts +74 -9
- package/dist/esm/async-rate-limiter.js +48 -16
- package/dist/esm/async-rate-limiter.js.map +1 -1
- package/dist/esm/async-throttler.d.ts +62 -10
- package/dist/esm/async-throttler.js +42 -17
- package/dist/esm/async-throttler.js.map +1 -1
- package/dist/esm/debouncer.d.ts +14 -4
- package/dist/esm/debouncer.js +16 -3
- package/dist/esm/debouncer.js.map +1 -1
- package/dist/esm/index.js +3 -1
- package/dist/esm/queuer.d.ts +9 -3
- package/dist/esm/queuer.js +13 -5
- package/dist/esm/queuer.js.map +1 -1
- package/dist/esm/rate-limiter.d.ts +20 -6
- package/dist/esm/rate-limiter.js +26 -7
- package/dist/esm/rate-limiter.js.map +1 -1
- package/dist/esm/throttler.d.ts +15 -4
- package/dist/esm/throttler.js +19 -5
- package/dist/esm/throttler.js.map +1 -1
- package/dist/esm/types.d.ts +1 -0
- package/dist/esm/utils.d.ts +3 -0
- package/dist/esm/utils.js +19 -8
- package/dist/esm/utils.js.map +1 -1
- package/package.json +9 -3
- package/src/async-debouncer.ts +89 -22
- package/src/async-queuer.ts +205 -175
- package/src/async-rate-limiter.ts +111 -25
- package/src/async-throttler.ts +92 -24
- package/src/debouncer.ts +24 -7
- package/src/queuer.ts +19 -7
- package/src/rate-limiter.ts +37 -13
- package/src/throttler.ts +28 -9
- package/src/types.ts +3 -0
- package/src/utils.ts +19 -5
|
@@ -1,14 +1,20 @@
|
|
|
1
|
+
import { AnyAsyncFunction } from './types.cjs';
|
|
1
2
|
import { QueuePosition } from './queuer.cjs';
|
|
2
|
-
export
|
|
3
|
+
export type AsyncQueuerFn = AnyAsyncFunction & {
|
|
4
|
+
priority?: number;
|
|
5
|
+
};
|
|
6
|
+
export interface AsyncQueuerOptions<TFn extends AsyncQueuerFn> {
|
|
3
7
|
/**
|
|
4
8
|
* Default position to add items to the queuer
|
|
5
9
|
* @default 'back'
|
|
6
10
|
*/
|
|
7
11
|
addItemsTo?: QueuePosition;
|
|
8
12
|
/**
|
|
9
|
-
* Maximum number of concurrent tasks to process
|
|
13
|
+
* Maximum number of concurrent tasks to process.
|
|
14
|
+
* Can be a number or a function that returns a number.
|
|
15
|
+
* @default 1
|
|
10
16
|
*/
|
|
11
|
-
concurrency?: number;
|
|
17
|
+
concurrency?: number | ((queuer: AsyncQueuer<TFn>) => number);
|
|
12
18
|
/**
|
|
13
19
|
* Maximum time in milliseconds that an item can stay in the queue
|
|
14
20
|
* If not provided, items will never expire
|
|
@@ -18,7 +24,7 @@ export interface AsyncQueuerOptions<TValue> {
|
|
|
18
24
|
* Function to determine if an item has expired
|
|
19
25
|
* If provided, this overrides the expirationDuration behavior
|
|
20
26
|
*/
|
|
21
|
-
getIsExpired?: (item:
|
|
27
|
+
getIsExpired?: (item: TFn, addedAt: number) => boolean;
|
|
22
28
|
/**
|
|
23
29
|
* Default position to get items from during processing
|
|
24
30
|
* @default 'front'
|
|
@@ -29,45 +35,67 @@ export interface AsyncQueuerOptions<TValue> {
|
|
|
29
35
|
* Higher priority items will be processed first
|
|
30
36
|
* If not provided, will use static priority values attached to tasks
|
|
31
37
|
*/
|
|
32
|
-
getPriority?: (item:
|
|
38
|
+
getPriority?: (item: TFn) => number;
|
|
33
39
|
/**
|
|
34
40
|
* Initial items to populate the queuer with
|
|
35
41
|
*/
|
|
36
|
-
initialItems?: Array<
|
|
42
|
+
initialItems?: Array<TFn & {
|
|
37
43
|
priority?: number;
|
|
38
44
|
}>;
|
|
39
45
|
/**
|
|
40
46
|
* Maximum number of items allowed in the queuer
|
|
41
47
|
*/
|
|
42
48
|
maxSize?: number;
|
|
49
|
+
/**
|
|
50
|
+
* Optional error handler for when a task throws.
|
|
51
|
+
* If provided, the handler will be called with the error and queuer instance.
|
|
52
|
+
* This can be used alongside throwOnError - the handler will be called before any error is thrown.
|
|
53
|
+
*/
|
|
54
|
+
onError?: (error: unknown, queuer: AsyncQueuer<TFn>) => void;
|
|
55
|
+
/**
|
|
56
|
+
* Callback fired whenever an item expires in the queuer
|
|
57
|
+
*/
|
|
58
|
+
onExpire?: (item: TFn, queuer: AsyncQueuer<TFn>) => void;
|
|
43
59
|
/**
|
|
44
60
|
* Callback fired whenever an item is removed from the queuer
|
|
45
61
|
*/
|
|
46
|
-
onGetNextItem?: (item:
|
|
62
|
+
onGetNextItem?: (item: TFn, queuer: AsyncQueuer<TFn>) => void;
|
|
47
63
|
/**
|
|
48
64
|
* Callback fired whenever the queuer's running state changes
|
|
49
65
|
*/
|
|
50
|
-
onIsRunningChange?: (queuer: AsyncQueuer<
|
|
66
|
+
onIsRunningChange?: (queuer: AsyncQueuer<TFn>) => void;
|
|
51
67
|
/**
|
|
52
68
|
* Callback fired whenever an item is added or removed from the queuer
|
|
53
69
|
*/
|
|
54
|
-
onItemsChange?: (queuer: AsyncQueuer<
|
|
70
|
+
onItemsChange?: (queuer: AsyncQueuer<TFn>) => void;
|
|
55
71
|
/**
|
|
56
72
|
* Callback fired whenever an item is rejected from being added to the queuer
|
|
57
73
|
*/
|
|
58
|
-
onReject?: (item:
|
|
74
|
+
onReject?: (item: TFn, queuer: AsyncQueuer<TFn>) => void;
|
|
59
75
|
/**
|
|
60
|
-
*
|
|
76
|
+
* Optional callback to call when a task is settled
|
|
77
|
+
*/
|
|
78
|
+
onSettled?: (queuer: AsyncQueuer<TFn>) => void;
|
|
79
|
+
/**
|
|
80
|
+
* Optional callback to call when a task succeeds
|
|
61
81
|
*/
|
|
62
|
-
|
|
82
|
+
onSuccess?: (result: TFn, queuer: AsyncQueuer<TFn>) => void;
|
|
63
83
|
/**
|
|
64
84
|
* Whether the queuer should start processing tasks immediately or not.
|
|
65
85
|
*/
|
|
66
86
|
started?: boolean;
|
|
67
87
|
/**
|
|
68
|
-
*
|
|
88
|
+
* Whether to throw errors when they occur.
|
|
89
|
+
* Defaults to true if no onError handler is provided, false if an onError handler is provided.
|
|
90
|
+
* Can be explicitly set to override these defaults.
|
|
91
|
+
*/
|
|
92
|
+
throwOnError?: boolean;
|
|
93
|
+
/**
|
|
94
|
+
* Time in milliseconds to wait between processing items.
|
|
95
|
+
* Can be a number or a function that returns a number.
|
|
96
|
+
* @default 0
|
|
69
97
|
*/
|
|
70
|
-
wait?: number;
|
|
98
|
+
wait?: number | ((queuer: AsyncQueuer<TFn>) => number);
|
|
71
99
|
}
|
|
72
100
|
/**
|
|
73
101
|
* A flexible asynchronous queue that processes tasks with configurable concurrency control.
|
|
@@ -84,44 +112,59 @@ export interface AsyncQueuerOptions<TValue> {
|
|
|
84
112
|
* Tasks are processed concurrently up to the configured concurrency limit. When a task completes,
|
|
85
113
|
* the next pending task is processed if below the concurrency limit.
|
|
86
114
|
*
|
|
115
|
+
* Error Handling:
|
|
116
|
+
* - If an `onError` handler is provided, it will be called with the error and queuer instance
|
|
117
|
+
* - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
|
|
118
|
+
* - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
|
|
119
|
+
* - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
|
|
120
|
+
* - The error state can be checked using the underlying AsyncQueuer instance
|
|
121
|
+
*
|
|
87
122
|
* @example
|
|
88
123
|
* ```ts
|
|
89
|
-
* const asyncQueuer = new AsyncQueuer<string>({
|
|
124
|
+
* const asyncQueuer = new AsyncQueuer<string>({
|
|
125
|
+
* concurrency: 2,
|
|
126
|
+
* onSuccess: (result) => {
|
|
127
|
+
* console.log(result); // 'Hello'
|
|
128
|
+
* }
|
|
129
|
+
* });
|
|
90
130
|
*
|
|
91
131
|
* asyncQueuer.addItem(async () => {
|
|
92
132
|
* return 'Hello';
|
|
93
133
|
* });
|
|
94
134
|
*
|
|
95
135
|
* asyncQueuer.start();
|
|
96
|
-
*
|
|
97
|
-
* asyncQueuer.onSuccess((result) => {
|
|
98
|
-
* console.log(result); // 'Hello'
|
|
99
|
-
* });
|
|
100
136
|
* ```
|
|
101
137
|
*/
|
|
102
|
-
export declare class AsyncQueuer<
|
|
138
|
+
export declare class AsyncQueuer<TFn extends AsyncQueuerFn> {
|
|
103
139
|
private _options;
|
|
104
140
|
private _activeItems;
|
|
105
|
-
private
|
|
141
|
+
private _successCount;
|
|
142
|
+
private _errorCount;
|
|
143
|
+
private _settledCount;
|
|
106
144
|
private _rejectionCount;
|
|
107
145
|
private _expirationCount;
|
|
108
146
|
private _items;
|
|
109
147
|
private _itemTimestamps;
|
|
110
|
-
private _onErrorCallbacks;
|
|
111
|
-
private _onSettledCallbacks;
|
|
112
|
-
private _onSuccessCallbacks;
|
|
113
148
|
private _pendingTick;
|
|
114
149
|
private _running;
|
|
115
|
-
constructor(initialOptions?: AsyncQueuerOptions<
|
|
150
|
+
constructor(initialOptions?: AsyncQueuerOptions<TFn>);
|
|
116
151
|
/**
|
|
117
152
|
* Updates the queuer options
|
|
118
153
|
* Returns the new options state
|
|
119
154
|
*/
|
|
120
|
-
setOptions(newOptions: Partial<AsyncQueuerOptions<
|
|
155
|
+
setOptions(newOptions: Partial<AsyncQueuerOptions<TFn>>): void;
|
|
121
156
|
/**
|
|
122
157
|
* Returns the current queuer options
|
|
123
158
|
*/
|
|
124
|
-
getOptions():
|
|
159
|
+
getOptions(): AsyncQueuerOptions<TFn>;
|
|
160
|
+
/**
|
|
161
|
+
* Returns the current wait time between processing items
|
|
162
|
+
*/
|
|
163
|
+
getWait(): number;
|
|
164
|
+
/**
|
|
165
|
+
* Returns the current concurrency limit
|
|
166
|
+
*/
|
|
167
|
+
getConcurrency(): number;
|
|
125
168
|
/**
|
|
126
169
|
* Processes items in the queuer
|
|
127
170
|
*/
|
|
@@ -149,17 +192,15 @@ export declare class AsyncQueuer<TValue> {
|
|
|
149
192
|
/**
|
|
150
193
|
* Adds a task to the queuer
|
|
151
194
|
*/
|
|
152
|
-
addItem(fn:
|
|
153
|
-
priority?: number;
|
|
154
|
-
}, position?: QueuePosition, runOnUpdate?: boolean): Promise<TValue>;
|
|
195
|
+
addItem(fn: TFn, position?: QueuePosition, runOnItemsChange?: boolean): void;
|
|
155
196
|
/**
|
|
156
197
|
* Removes and returns an item from the queuer
|
|
157
198
|
*/
|
|
158
|
-
getNextItem(position?: QueuePosition):
|
|
199
|
+
getNextItem(position?: QueuePosition): TFn | undefined;
|
|
159
200
|
/**
|
|
160
201
|
* Returns an item without removing it
|
|
161
202
|
*/
|
|
162
|
-
getPeek(position?: QueuePosition):
|
|
203
|
+
getPeek(position?: QueuePosition): TFn | undefined;
|
|
163
204
|
/**
|
|
164
205
|
* Returns true if the queuer is empty
|
|
165
206
|
*/
|
|
@@ -175,19 +216,27 @@ export declare class AsyncQueuer<TValue> {
|
|
|
175
216
|
/**
|
|
176
217
|
* Returns a copy of all items in the queuer
|
|
177
218
|
*/
|
|
178
|
-
getAllItems(): Array<
|
|
219
|
+
getAllItems(): Array<TFn>;
|
|
179
220
|
/**
|
|
180
221
|
* Returns the active items
|
|
181
222
|
*/
|
|
182
|
-
getActiveItems(): Array<
|
|
223
|
+
getActiveItems(): Array<TFn>;
|
|
183
224
|
/**
|
|
184
225
|
* Returns the pending items
|
|
185
226
|
*/
|
|
186
|
-
getPendingItems(): Array<
|
|
227
|
+
getPendingItems(): Array<TFn>;
|
|
228
|
+
/**
|
|
229
|
+
* Returns the number of items that have been successfully processed
|
|
230
|
+
*/
|
|
231
|
+
getSuccessCount(): number;
|
|
232
|
+
/**
|
|
233
|
+
* Returns the number of items that have failed processing
|
|
234
|
+
*/
|
|
235
|
+
getErrorCount(): number;
|
|
187
236
|
/**
|
|
188
|
-
* Returns the number of items that have
|
|
237
|
+
* Returns the number of items that have completed processing (success or error)
|
|
189
238
|
*/
|
|
190
|
-
|
|
239
|
+
getSettledCount(): number;
|
|
191
240
|
/**
|
|
192
241
|
* Returns the number of items that have been rejected from the queuer
|
|
193
242
|
*/
|
|
@@ -200,18 +249,6 @@ export declare class AsyncQueuer<TValue> {
|
|
|
200
249
|
* Returns true if the queuer is running but has no items to process
|
|
201
250
|
*/
|
|
202
251
|
getIsIdle(): boolean;
|
|
203
|
-
/**
|
|
204
|
-
* Adds a callback to be called when a task succeeds
|
|
205
|
-
*/
|
|
206
|
-
onSuccess(cb: (result: TValue) => void): () => void;
|
|
207
|
-
/**
|
|
208
|
-
* Adds a callback to be called when a task errors
|
|
209
|
-
*/
|
|
210
|
-
onError(cb: (error: Error) => void): () => void;
|
|
211
|
-
/**
|
|
212
|
-
* Adds a callback to be called when a task is settled
|
|
213
|
-
*/
|
|
214
|
-
onSettled(cb: (result: TValue | Error) => void): () => void;
|
|
215
252
|
/**
|
|
216
253
|
* Returns the number of items that have expired from the queuer
|
|
217
254
|
*/
|
|
@@ -221,6 +258,13 @@ export declare class AsyncQueuer<TValue> {
|
|
|
221
258
|
* Creates a new AsyncQueuer instance with the given options and returns a bound addItem function.
|
|
222
259
|
* The queuer is automatically started and ready to process items.
|
|
223
260
|
*
|
|
261
|
+
* Error Handling:
|
|
262
|
+
* - If an `onError` handler is provided, it will be called with the error and queuer instance
|
|
263
|
+
* - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
|
|
264
|
+
* - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
|
|
265
|
+
* - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
|
|
266
|
+
* - The error state can be checked using the underlying AsyncQueuer instance
|
|
267
|
+
*
|
|
224
268
|
* @example
|
|
225
269
|
* ```ts
|
|
226
270
|
* const enqueue = asyncQueue<string>();
|
|
@@ -234,6 +278,4 @@ export declare class AsyncQueuer<TValue> {
|
|
|
234
278
|
* @param options - Configuration options for the AsyncQueuer
|
|
235
279
|
* @returns A bound addItem function that can be used to add tasks to the queuer
|
|
236
280
|
*/
|
|
237
|
-
export declare function asyncQueue<
|
|
238
|
-
priority?: number;
|
|
239
|
-
}, position?: QueuePosition, runOnUpdate?: boolean) => Promise<TValue>;
|
|
281
|
+
export declare function asyncQueue<TFn extends AsyncQueuerFn>(options: AsyncQueuerOptions<TFn>): (fn: TFn, position?: QueuePosition, runOnItemsChange?: boolean) => void;
|
|
@@ -1,15 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const utils = require("./utils.cjs");
|
|
3
4
|
const defaultOptions = {
|
|
4
5
|
enabled: true,
|
|
5
|
-
onError: () => {
|
|
6
|
-
},
|
|
7
|
-
onReject: () => {
|
|
8
|
-
},
|
|
9
|
-
onSettled: () => {
|
|
10
|
-
},
|
|
11
|
-
onSuccess: () => {
|
|
12
|
-
},
|
|
13
6
|
windowType: "fixed"
|
|
14
7
|
};
|
|
15
8
|
class AsyncRateLimiter {
|
|
@@ -23,7 +16,8 @@ class AsyncRateLimiter {
|
|
|
23
16
|
this._isExecuting = false;
|
|
24
17
|
this._options = {
|
|
25
18
|
...defaultOptions,
|
|
26
|
-
...initialOptions
|
|
19
|
+
...initialOptions,
|
|
20
|
+
throwOnError: initialOptions.throwOnError ?? !initialOptions.onError
|
|
27
21
|
};
|
|
28
22
|
}
|
|
29
23
|
/**
|
|
@@ -39,11 +33,42 @@ class AsyncRateLimiter {
|
|
|
39
33
|
getOptions() {
|
|
40
34
|
return this._options;
|
|
41
35
|
}
|
|
36
|
+
/**
|
|
37
|
+
* Returns the current enabled state of the rate limiter
|
|
38
|
+
*/
|
|
39
|
+
getEnabled() {
|
|
40
|
+
return !!utils.parseFunctionOrValue(this._options.enabled, this);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Returns the current limit of executions allowed within the time window
|
|
44
|
+
*/
|
|
45
|
+
getLimit() {
|
|
46
|
+
return utils.parseFunctionOrValue(this._options.limit, this);
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Returns the current time window in milliseconds
|
|
50
|
+
*/
|
|
51
|
+
getWindow() {
|
|
52
|
+
return utils.parseFunctionOrValue(this._options.window, this);
|
|
53
|
+
}
|
|
42
54
|
/**
|
|
43
55
|
* Attempts to execute the rate-limited function if within the configured limits.
|
|
44
56
|
* Will reject execution if the number of calls in the current window exceeds the limit.
|
|
45
57
|
* If execution is allowed, waits for any previous execution to complete before proceeding.
|
|
46
58
|
*
|
|
59
|
+
* Error Handling:
|
|
60
|
+
* - If the rate-limited function throws and no `onError` handler is configured,
|
|
61
|
+
* the error will be thrown from this method.
|
|
62
|
+
* - If an `onError` handler is configured, errors will be caught and passed to the handler,
|
|
63
|
+
* and this method will return undefined.
|
|
64
|
+
* - If the rate limit is exceeded, the execution will be rejected and the `onReject` handler
|
|
65
|
+
* will be called if configured.
|
|
66
|
+
* - The error state can be checked using `getErrorCount()` and `getIsExecuting()`.
|
|
67
|
+
* - Rate limit rejections can be tracked using `getRejectionCount()`.
|
|
68
|
+
*
|
|
69
|
+
* @returns A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError
|
|
70
|
+
* @throws The error from the rate-limited function if no onError handler is configured
|
|
71
|
+
*
|
|
47
72
|
* @example
|
|
48
73
|
* ```ts
|
|
49
74
|
* const rateLimiter = new AsyncRateLimiter(fn, { limit: 5, window: 1000 });
|
|
@@ -57,16 +82,18 @@ class AsyncRateLimiter {
|
|
|
57
82
|
*/
|
|
58
83
|
async maybeExecute(...args) {
|
|
59
84
|
this.cleanupOldExecutions();
|
|
85
|
+
const limit = this.getLimit();
|
|
86
|
+
const window = this.getWindow();
|
|
60
87
|
if (this._options.windowType === "sliding") {
|
|
61
|
-
if (this._executionTimes.length <
|
|
88
|
+
if (this._executionTimes.length < limit) {
|
|
62
89
|
await this.executeFunction(...args);
|
|
63
90
|
return this._lastResult;
|
|
64
91
|
}
|
|
65
92
|
} else {
|
|
66
93
|
const now = Date.now();
|
|
67
94
|
const oldestExecution = Math.min(...this._executionTimes);
|
|
68
|
-
const isNewWindow = oldestExecution +
|
|
69
|
-
if (isNewWindow || this._executionTimes.length <
|
|
95
|
+
const isNewWindow = oldestExecution + window <= now;
|
|
96
|
+
if (isNewWindow || this._executionTimes.length < limit) {
|
|
70
97
|
await this.executeFunction(...args);
|
|
71
98
|
return this._lastResult;
|
|
72
99
|
}
|
|
@@ -76,7 +103,7 @@ class AsyncRateLimiter {
|
|
|
76
103
|
}
|
|
77
104
|
async executeFunction(...args) {
|
|
78
105
|
var _a, _b, _c, _d, _e, _f;
|
|
79
|
-
if (!this.
|
|
106
|
+
if (!this.getEnabled()) return;
|
|
80
107
|
this._isExecuting = true;
|
|
81
108
|
const now = Date.now();
|
|
82
109
|
this._executionTimes.push(now);
|
|
@@ -87,6 +114,11 @@ class AsyncRateLimiter {
|
|
|
87
114
|
} catch (error) {
|
|
88
115
|
this._errorCount++;
|
|
89
116
|
(_d = (_c = this._options).onError) == null ? void 0 : _d.call(_c, error, this);
|
|
117
|
+
if (this._options.throwOnError) {
|
|
118
|
+
throw error;
|
|
119
|
+
} else {
|
|
120
|
+
console.error(error);
|
|
121
|
+
}
|
|
90
122
|
} finally {
|
|
91
123
|
this._isExecuting = false;
|
|
92
124
|
this._settleCount++;
|
|
@@ -102,7 +134,7 @@ class AsyncRateLimiter {
|
|
|
102
134
|
}
|
|
103
135
|
cleanupOldExecutions() {
|
|
104
136
|
const now = Date.now();
|
|
105
|
-
const windowStart = now - this.
|
|
137
|
+
const windowStart = now - this.getWindow();
|
|
106
138
|
this._executionTimes = this._executionTimes.filter(
|
|
107
139
|
(time) => time > windowStart
|
|
108
140
|
);
|
|
@@ -112,7 +144,7 @@ class AsyncRateLimiter {
|
|
|
112
144
|
*/
|
|
113
145
|
getRemainingInWindow() {
|
|
114
146
|
this.cleanupOldExecutions();
|
|
115
|
-
return Math.max(0, this.
|
|
147
|
+
return Math.max(0, this.getLimit() - this._executionTimes.length);
|
|
116
148
|
}
|
|
117
149
|
/**
|
|
118
150
|
* Returns the number of milliseconds until the next execution will be possible
|
|
@@ -124,7 +156,7 @@ class AsyncRateLimiter {
|
|
|
124
156
|
return 0;
|
|
125
157
|
}
|
|
126
158
|
const oldestExecution = Math.min(...this._executionTimes);
|
|
127
|
-
return oldestExecution + this.
|
|
159
|
+
return oldestExecution + this.getWindow() - Date.now();
|
|
128
160
|
}
|
|
129
161
|
/**
|
|
130
162
|
* Returns the number of times the function has been executed
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"async-rate-limiter.cjs","sources":["../../src/async-rate-limiter.ts"],"sourcesContent":["import type { AnyAsyncFunction } from './types'\n\n/**\n * Options for configuring an async rate-limited function\n */\nexport interface AsyncRateLimiterOptions<TFn extends AnyAsyncFunction> {\n /**\n * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean\n /**\n * Maximum number of executions allowed within the time window\n */\n limit: number\n /**\n * Optional error handler for when the rate-limited function throws\n */\n onError?: (error: unknown, rateLimiter: AsyncRateLimiter<TFn>) => void\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (rateLimiter: AsyncRateLimiter<TFn>) => void\n /**\n * Optional function to call when the rate-limited function is executed\n */\n onSettled?: (rateLimiter: AsyncRateLimiter<TFn>) => void\n /**\n * Optional function to call when the rate-limited function is executed\n */\n onSuccess?: (\n result: ReturnType<TFn>,\n rateLimiter: AsyncRateLimiter<TFn>,\n ) => void\n /**\n * Time window in milliseconds within which the limit applies\n */\n window: number\n /**\n * Type of window to use for rate limiting\n * - 'fixed': Uses a fixed window that resets after the window period\n * - 'sliding': Uses a sliding window that allows executions as old ones expire\n * Defaults to 'fixed'\n */\n windowType?: 'fixed' | 'sliding'\n}\n\nconst defaultOptions: Required<\n Omit<AsyncRateLimiterOptions<any>, 'limit' | 'window'>\n> = {\n enabled: true,\n onError: () => {},\n onReject: () => {},\n onSettled: () => {},\n onSuccess: () => {},\n windowType: 'fixed',\n}\n\n/**\n * A class that creates an async rate-limited function.\n *\n * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,\n * then blocks all subsequent calls until the window passes. This can lead to \"bursty\" behavior where\n * all executions happen immediately, followed by a complete block.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * Unlike the non-async RateLimiter, this async version supports returning values from the rate-limited function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the rate-limited function.\n *\n * For smoother execution patterns, consider using:\n * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)\n * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)\n *\n * Rate limiting is best used for hard API limits or resource constraints. For UI updates or\n * smoothing out frequent events, throttling or debouncing usually provide better user experience.\n *\n * @example\n * ```ts\n * const rateLimiter = new AsyncRateLimiter(\n * async (id: string) => await api.getData(id),\n * { limit: 5, window: 1000, windowType: 'sliding' } // 5 calls per second with sliding window\n * );\n *\n * // Will execute immediately until limit reached, then block\n * // Returns the API response directly\n * const data = await rateLimiter.maybeExecute('123');\n * ```\n */\nexport class AsyncRateLimiter<TFn extends AnyAsyncFunction> {\n private _options: AsyncRateLimiterOptions<TFn>\n private _errorCount = 0\n private _executionTimes: Array<number> = []\n private _lastResult: ReturnType<TFn> | undefined\n private _rejectionCount = 0\n private _settleCount = 0\n private _successCount = 0\n private _isExecuting = false\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncRateLimiterOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the rate limiter options\n * Returns the new options state\n */\n setOptions(newOptions: Partial<AsyncRateLimiterOptions<TFn>>): void {\n this._options = { ...this._options, ...newOptions }\n }\n\n /**\n * Returns the current rate limiter options\n */\n getOptions(): Required<AsyncRateLimiterOptions<TFn>> {\n return this._options as Required<AsyncRateLimiterOptions<TFn>>\n }\n\n /**\n * Attempts to execute the rate-limited function if within the configured limits.\n * Will reject execution if the number of calls in the current window exceeds the limit.\n * If execution is allowed, waits for any previous execution to complete before proceeding.\n *\n * @example\n * ```ts\n * const rateLimiter = new AsyncRateLimiter(fn, { limit: 5, window: 1000 });\n *\n * // First 5 calls will execute\n * await rateLimiter.maybeExecute('arg1', 'arg2');\n *\n * // Additional calls within the window will be rejected\n * await rateLimiter.maybeExecute('arg1', 'arg2'); // Rejected\n * ```\n */\n async maybeExecute(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n this.cleanupOldExecutions()\n\n if (this._options.windowType === 'sliding') {\n // For sliding window, we can execute if we have capacity in the current window\n if (this._executionTimes.length < this._options.limit) {\n await this.executeFunction(...args)\n return this._lastResult\n }\n } else {\n // For fixed window, we need to check if we're in a new window\n const now = Date.now()\n const oldestExecution = Math.min(...this._executionTimes)\n const isNewWindow = oldestExecution + this._options.window <= now\n\n if (isNewWindow || this._executionTimes.length < this._options.limit) {\n await this.executeFunction(...args)\n return this._lastResult\n }\n }\n\n this.rejectFunction()\n return undefined\n }\n\n private async executeFunction(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n if (!this._options.enabled) return\n this._isExecuting = true\n const now = Date.now()\n this._executionTimes.push(now)\n\n try {\n this._lastResult = await this.fn(...args)\n this._successCount++\n this._options.onSuccess?.(this._lastResult!, this)\n } catch (error) {\n this._errorCount++\n this._options.onError?.(error, this)\n } finally {\n this._isExecuting = false\n this._settleCount++\n this._options.onSettled?.(this)\n }\n\n return this._lastResult\n }\n\n private rejectFunction(): void {\n this._rejectionCount++\n if (this._options.onReject) {\n this._options.onReject(this)\n }\n }\n\n private cleanupOldExecutions(): void {\n const now = Date.now()\n const windowStart = now - this._options.window\n this._executionTimes = this._executionTimes.filter(\n (time) => time > windowStart,\n )\n }\n\n /**\n * Returns the number of remaining executions allowed in the current window\n */\n getRemainingInWindow(): number {\n this.cleanupOldExecutions()\n return Math.max(0, this._options.limit - this._executionTimes.length)\n }\n\n /**\n * Returns the number of milliseconds until the next execution will be possible\n * For fixed windows, this is the time until the current window resets\n * For sliding windows, this is the time until the oldest execution expires\n */\n getMsUntilNextWindow(): number {\n if (this.getRemainingInWindow() > 0) {\n return 0\n }\n const oldestExecution = Math.min(...this._executionTimes)\n return oldestExecution + this._options.window - Date.now()\n }\n\n /**\n * Returns the number of times the function has been executed\n */\n getSuccessCount(): number {\n return this._successCount\n }\n\n /**\n * Returns the number of times the function has been settled\n */\n getSettleCount(): number {\n return this._settleCount\n }\n\n /**\n * Returns the number of times the function has errored\n */\n getErrorCount(): number {\n return this._errorCount\n }\n\n /**\n * Returns the number of times the function has been rejected\n */\n getRejectionCount(): number {\n return this._rejectionCount\n }\n\n /**\n * Returns whether the function is currently executing\n */\n getIsExecuting(): boolean {\n return this._isExecuting\n }\n\n /**\n * Resets the rate limiter state\n */\n reset(): void {\n this._executionTimes = []\n this._successCount = 0\n this._errorCount = 0\n this._rejectionCount = 0\n this._settleCount = 0\n }\n}\n\n/**\n * Creates an async rate-limited function that will execute the provided function up to a maximum number of times within a time window.\n *\n * Unlike the non-async rate limiter, this async version supports returning values from the rate-limited function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the rate-limited function.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:\n * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets\n * - A throttler ensures even spacing between executions, which can be better for consistent performance\n * - A debouncer collapses multiple calls into one, which is better for handling bursts of events\n *\n * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically\n * need to enforce a hard limit on the number of executions within a time period.\n *\n * @example\n * ```ts\n * // Rate limit to 5 calls per minute with a sliding window\n * const rateLimited = asyncRateLimit(makeApiCall, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * onReject: (rateLimiter) => {\n * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * }\n * });\n *\n * // First 5 calls will execute immediately\n * // Additional calls will be rejected until the minute window resets\n * // Returns the API response directly\n * const result = await rateLimited();\n *\n * // For more even execution, consider using throttle instead:\n * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds\n * ```\n */\nexport function asyncRateLimit<TFn extends AnyAsyncFunction>(\n fn: TFn,\n initialOptions: Omit<AsyncRateLimiterOptions<TFn>, 'enabled'>,\n) {\n const rateLimiter = new AsyncRateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute.bind(rateLimiter)\n}\n"],"names":[],"mappings":";;AA+CA,MAAM,iBAEF;AAAA,EACF,SAAS;AAAA,EACT,SAAS,MAAM;AAAA,EAAC;AAAA,EAChB,UAAU,MAAM;AAAA,EAAC;AAAA,EACjB,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,YAAY;AACd;AAsCO,MAAM,iBAA+C;AAAA,EAU1D,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AATV,SAAQ,cAAc;AACtB,SAAQ,kBAAiC,CAAC;AAE1C,SAAQ,kBAAkB;AAC1B,SAAQ,eAAe;AACvB,SAAQ,gBAAgB;AACxB,SAAQ,eAAe;AAMrB,SAAK,WAAW;AAAA,MACd,GAAG;AAAA,MACH,GAAG;AAAA,IACL;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,WAAW,YAAyD;AAClE,SAAK,WAAW,EAAE,GAAG,KAAK,UAAU,GAAG,WAAW;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMpD,aAAqD;AACnD,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAmBd,MAAM,gBACD,MACmC;AACtC,SAAK,qBAAqB;AAEtB,QAAA,KAAK,SAAS,eAAe,WAAW;AAE1C,UAAI,KAAK,gBAAgB,SAAS,KAAK,SAAS,OAAO;AAC/C,cAAA,KAAK,gBAAgB,GAAG,IAAI;AAClC,eAAO,KAAK;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;AAAA;AAAA;AAAA;AAAA,EAQtE,uBAA+B;AACzB,QAAA,KAAK,qBAAqB,IAAI,GAAG;AAC5B,aAAA;AAAA,IAAA;AAET,UAAM,kBAAkB,KAAK,IAAI,GAAG,KAAK,eAAe;AACxD,WAAO,kBAAkB,KAAK,SAAS,SAAS,KAAK,IAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAM3D,kBAA0B;AACxB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,iBAAyB;AACvB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,gBAAwB;AACtB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,iBAA0B;AACxB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,QAAc;AACZ,SAAK,kBAAkB,CAAC;AACxB,SAAK,gBAAgB;AACrB,SAAK,cAAc;AACnB,SAAK,kBAAkB;AACvB,SAAK,eAAe;AAAA,EAAA;AAExB;AA4CgB,SAAA,eACd,IACA,gBACA;AACA,QAAM,cAAc,IAAI,iBAAiB,IAAI,cAAc;AACpD,SAAA,YAAY,aAAa,KAAK,WAAW;AAClD;;;"}
|
|
1
|
+
{"version":3,"file":"async-rate-limiter.cjs","sources":["../../src/async-rate-limiter.ts"],"sourcesContent":["import { parseFunctionOrValue } from './utils'\nimport type { AnyAsyncFunction, OptionalKeys } from './types'\n\n/**\n * Options for configuring an async rate-limited function\n */\nexport interface AsyncRateLimiterOptions<TFn extends AnyAsyncFunction> {\n /**\n * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.\n * Can be a boolean or a function that returns a boolean.\n * Defaults to true.\n */\n enabled?: boolean | ((rateLimiter: AsyncRateLimiter<TFn>) => boolean)\n /**\n * Maximum number of executions allowed within the time window.\n * Can be a number or a function that returns a number.\n */\n limit: number | ((rateLimiter: AsyncRateLimiter<TFn>) => number)\n /**\n * Optional error handler for when the rate-limited function throws.\n * If provided, the handler will be called with the error and rate limiter instance.\n * This can be used alongside throwOnError - the handler will be called before any error is thrown.\n */\n onError?: (error: unknown, rateLimiter: AsyncRateLimiter<TFn>) => void\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (rateLimiter: AsyncRateLimiter<TFn>) => void\n /**\n * Optional function to call when the rate-limited function is executed\n */\n onSettled?: (rateLimiter: AsyncRateLimiter<TFn>) => void\n /**\n * Optional function to call when the rate-limited function is executed\n */\n onSuccess?: (\n result: ReturnType<TFn>,\n rateLimiter: AsyncRateLimiter<TFn>,\n ) => void\n /**\n * Whether to throw errors when they occur.\n * Defaults to true if no onError handler is provided, false if an onError handler is provided.\n * Can be explicitly set to override these defaults.\n */\n throwOnError?: boolean\n /**\n * Time window in milliseconds within which the limit applies.\n * Can be a number or a function that returns a number.\n */\n window: number | ((rateLimiter: AsyncRateLimiter<TFn>) => number)\n /**\n * Type of window to use for rate limiting\n * - 'fixed': Uses a fixed window that resets after the window period\n * - 'sliding': Uses a sliding window that allows executions as old ones expire\n * Defaults to 'fixed'\n */\n windowType?: 'fixed' | 'sliding'\n}\n\ntype AsyncRateLimiterOptionsWithOptionalCallbacks = OptionalKeys<\n AsyncRateLimiterOptions<any>,\n 'onError' | 'onReject' | 'onSettled' | 'onSuccess'\n>\n\nconst defaultOptions: Omit<\n AsyncRateLimiterOptionsWithOptionalCallbacks,\n 'limit' | 'window'\n> = {\n enabled: true,\n windowType: 'fixed',\n}\n\n/**\n * A class that creates an async rate-limited function.\n *\n * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,\n * then blocks all subsequent calls until the window passes. This can lead to \"bursty\" behavior where\n * all executions happen immediately, followed by a complete block.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * Unlike the non-async RateLimiter, this async version supports returning values from the rate-limited function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the rate-limited function.\n *\n * For smoother execution patterns, consider using:\n * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)\n * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)\n *\n * Rate limiting is best used for hard API limits or resource constraints. For UI updates or\n * smoothing out frequent events, throttling or debouncing usually provide better user experience.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and rate limiter instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncRateLimiter instance\n * - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler\n *\n * @example\n * ```ts\n * const rateLimiter = new AsyncRateLimiter(\n * async (id: string) => await api.getData(id),\n * {\n * limit: 5,\n * window: 1000,\n * windowType: 'sliding',\n * onError: (error) => {\n * console.error('API call failed:', error);\n * },\n * onReject: (limiter) => {\n * console.log(`Rate limit exceeded. Try again in ${limiter.getMsUntilNextWindow()}ms`);\n * }\n * }\n * );\n *\n * // Will execute immediately until limit reached, then block\n * // Returns the API response directly\n * const data = await rateLimiter.maybeExecute('123');\n * ```\n */\nexport class AsyncRateLimiter<TFn extends AnyAsyncFunction> {\n private _options: AsyncRateLimiterOptionsWithOptionalCallbacks\n private _errorCount = 0\n private _executionTimes: Array<number> = []\n private _lastResult: ReturnType<TFn> | undefined\n private _rejectionCount = 0\n private _settleCount = 0\n private _successCount = 0\n private _isExecuting = false\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncRateLimiterOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n throwOnError: initialOptions.throwOnError ?? !initialOptions.onError,\n }\n }\n\n /**\n * Updates the rate limiter options\n * Returns the new options state\n */\n setOptions(newOptions: Partial<AsyncRateLimiterOptions<TFn>>): void {\n this._options = { ...this._options, ...newOptions }\n }\n\n /**\n * Returns the current rate limiter options\n */\n getOptions(): AsyncRateLimiterOptions<TFn> {\n return this._options\n }\n\n /**\n * Returns the current enabled state of the rate limiter\n */\n getEnabled(): boolean {\n return !!parseFunctionOrValue(this._options.enabled, this)\n }\n\n /**\n * Returns the current limit of executions allowed within the time window\n */\n getLimit(): number {\n return parseFunctionOrValue(this._options.limit, this)\n }\n\n /**\n * Returns the current time window in milliseconds\n */\n getWindow(): number {\n return parseFunctionOrValue(this._options.window, this)\n }\n\n /**\n * Attempts to execute the rate-limited function if within the configured limits.\n * Will reject execution if the number of calls in the current window exceeds the limit.\n * If execution is allowed, waits for any previous execution to complete before proceeding.\n *\n * Error Handling:\n * - If the rate-limited function throws and no `onError` handler is configured,\n * the error will be thrown from this method.\n * - If an `onError` handler is configured, errors will be caught and passed to the handler,\n * and this method will return undefined.\n * - If the rate limit is exceeded, the execution will be rejected and the `onReject` handler\n * will be called if configured.\n * - The error state can be checked using `getErrorCount()` and `getIsExecuting()`.\n * - Rate limit rejections can be tracked using `getRejectionCount()`.\n *\n * @returns A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError\n * @throws The error from the rate-limited function if no onError handler is configured\n *\n * @example\n * ```ts\n * const rateLimiter = new AsyncRateLimiter(fn, { limit: 5, window: 1000 });\n *\n * // First 5 calls will execute\n * await rateLimiter.maybeExecute('arg1', 'arg2');\n *\n * // Additional calls within the window will be rejected\n * await rateLimiter.maybeExecute('arg1', 'arg2'); // Rejected\n * ```\n */\n async maybeExecute(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n this.cleanupOldExecutions()\n\n const limit = this.getLimit()\n const window = this.getWindow()\n\n if (this._options.windowType === 'sliding') {\n // For sliding window, we can execute if we have capacity in the current window\n if (this._executionTimes.length < limit) {\n await this.executeFunction(...args)\n return this._lastResult\n }\n } else {\n // For fixed window, we need to check if we're in a new window\n const now = Date.now()\n const oldestExecution = Math.min(...this._executionTimes)\n const isNewWindow = oldestExecution + window <= now\n\n if (isNewWindow || this._executionTimes.length < limit) {\n await this.executeFunction(...args)\n return this._lastResult\n }\n }\n\n this.rejectFunction()\n return undefined\n }\n\n private async executeFunction(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n if (!this.getEnabled()) return\n this._isExecuting = true\n const now = Date.now()\n this._executionTimes.push(now)\n\n try {\n this._lastResult = await this.fn(...args)\n this._successCount++\n this._options.onSuccess?.(this._lastResult!, this)\n } catch (error) {\n this._errorCount++\n this._options.onError?.(error, this)\n if (this._options.throwOnError) {\n throw error\n } else {\n console.error(error)\n }\n } finally {\n this._isExecuting = false\n this._settleCount++\n this._options.onSettled?.(this)\n }\n\n return this._lastResult\n }\n\n private rejectFunction(): void {\n this._rejectionCount++\n if (this._options.onReject) {\n this._options.onReject(this)\n }\n }\n\n private cleanupOldExecutions(): void {\n const now = Date.now()\n const windowStart = now - this.getWindow()\n this._executionTimes = this._executionTimes.filter(\n (time) => time > windowStart,\n )\n }\n\n /**\n * Returns the number of remaining executions allowed in the current window\n */\n getRemainingInWindow(): number {\n this.cleanupOldExecutions()\n return Math.max(0, this.getLimit() - this._executionTimes.length)\n }\n\n /**\n * Returns the number of milliseconds until the next execution will be possible\n * For fixed windows, this is the time until the current window resets\n * For sliding windows, this is the time until the oldest execution expires\n */\n getMsUntilNextWindow(): number {\n if (this.getRemainingInWindow() > 0) {\n return 0\n }\n const oldestExecution = Math.min(...this._executionTimes)\n return oldestExecution + this.getWindow() - Date.now()\n }\n\n /**\n * Returns the number of times the function has been executed\n */\n getSuccessCount(): number {\n return this._successCount\n }\n\n /**\n * Returns the number of times the function has been settled\n */\n getSettleCount(): number {\n return this._settleCount\n }\n\n /**\n * Returns the number of times the function has errored\n */\n getErrorCount(): number {\n return this._errorCount\n }\n\n /**\n * Returns the number of times the function has been rejected\n */\n getRejectionCount(): number {\n return this._rejectionCount\n }\n\n /**\n * Returns whether the function is currently executing\n */\n getIsExecuting(): boolean {\n return this._isExecuting\n }\n\n /**\n * Resets the rate limiter state\n */\n reset(): void {\n this._executionTimes = []\n this._successCount = 0\n this._errorCount = 0\n this._rejectionCount = 0\n this._settleCount = 0\n }\n}\n\n/**\n * Creates an async rate-limited function that will execute the provided function up to a maximum number of times within a time window.\n *\n * Unlike the non-async rate limiter, this async version supports returning values from the rate-limited function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the rate-limited function.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:\n * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets\n * - A throttler ensures even spacing between executions, which can be better for consistent performance\n * - A debouncer collapses multiple calls into one, which is better for handling bursts of events\n *\n * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically\n * need to enforce a hard limit on the number of executions within a time period.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and rate limiter instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncRateLimiter instance\n * - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler\n *\n * @example\n * ```ts\n * // Rate limit to 5 calls per minute with a sliding window\n * const rateLimited = asyncRateLimit(makeApiCall, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * onError: (error) => {\n * console.error('API call failed:', error);\n * },\n * onReject: (rateLimiter) => {\n * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * }\n * });\n *\n * // First 5 calls will execute immediately\n * // Additional calls will be rejected until the minute window resets\n * // Returns the API response directly\n * const result = await rateLimited();\n *\n * // For more even execution, consider using throttle instead:\n * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds\n * ```\n */\nexport function asyncRateLimit<TFn extends AnyAsyncFunction>(\n fn: TFn,\n initialOptions: AsyncRateLimiterOptions<TFn>,\n) {\n const rateLimiter = new AsyncRateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute.bind(rateLimiter)\n}\n"],"names":["parseFunctionOrValue"],"mappings":";;;AAgEA,MAAM,iBAGF;AAAA,EACF,SAAS;AAAA,EACT,YAAY;AACd;AAwDO,MAAM,iBAA+C;AAAA,EAU1D,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AATV,SAAQ,cAAc;AACtB,SAAQ,kBAAiC,CAAC;AAE1C,SAAQ,kBAAkB;AAC1B,SAAQ,eAAe;AACvB,SAAQ,gBAAgB;AACxB,SAAQ,eAAe;AAMrB,SAAK,WAAW;AAAA,MACd,GAAG;AAAA,MACH,GAAG;AAAA,MACH,cAAc,eAAe,gBAAgB,CAAC,eAAe;AAAA,IAC/D;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,WAAW,YAAyD;AAClE,SAAK,WAAW,EAAE,GAAG,KAAK,UAAU,GAAG,WAAW;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMpD,aAA2C;AACzC,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,aAAsB;AACpB,WAAO,CAAC,CAACA,MAAAA,qBAAqB,KAAK,SAAS,SAAS,IAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAM3D,WAAmB;AACjB,WAAOA,MAAqB,qBAAA,KAAK,SAAS,OAAO,IAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMvD,YAAoB;AAClB,WAAOA,MAAqB,qBAAA,KAAK,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AuDgB,SAAA,eACd,IACA,gBACA;AACA,QAAM,cAAc,IAAI,iBAAiB,IAAI,cAAc;AACpD,SAAA,YAAY,aAAa,KAAK,WAAW;AAClD;;;"}
|
|
@@ -5,15 +5,19 @@ import { AnyAsyncFunction } from './types.cjs';
|
|
|
5
5
|
export interface AsyncRateLimiterOptions<TFn extends AnyAsyncFunction> {
|
|
6
6
|
/**
|
|
7
7
|
* Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.
|
|
8
|
+
* Can be a boolean or a function that returns a boolean.
|
|
8
9
|
* Defaults to true.
|
|
9
10
|
*/
|
|
10
|
-
enabled?: boolean;
|
|
11
|
+
enabled?: boolean | ((rateLimiter: AsyncRateLimiter<TFn>) => boolean);
|
|
11
12
|
/**
|
|
12
|
-
* Maximum number of executions allowed within the time window
|
|
13
|
+
* Maximum number of executions allowed within the time window.
|
|
14
|
+
* Can be a number or a function that returns a number.
|
|
13
15
|
*/
|
|
14
|
-
limit: number;
|
|
16
|
+
limit: number | ((rateLimiter: AsyncRateLimiter<TFn>) => number);
|
|
15
17
|
/**
|
|
16
|
-
* Optional error handler for when the rate-limited function throws
|
|
18
|
+
* Optional error handler for when the rate-limited function throws.
|
|
19
|
+
* If provided, the handler will be called with the error and rate limiter instance.
|
|
20
|
+
* This can be used alongside throwOnError - the handler will be called before any error is thrown.
|
|
17
21
|
*/
|
|
18
22
|
onError?: (error: unknown, rateLimiter: AsyncRateLimiter<TFn>) => void;
|
|
19
23
|
/**
|
|
@@ -29,9 +33,16 @@ export interface AsyncRateLimiterOptions<TFn extends AnyAsyncFunction> {
|
|
|
29
33
|
*/
|
|
30
34
|
onSuccess?: (result: ReturnType<TFn>, rateLimiter: AsyncRateLimiter<TFn>) => void;
|
|
31
35
|
/**
|
|
32
|
-
*
|
|
36
|
+
* Whether to throw errors when they occur.
|
|
37
|
+
* Defaults to true if no onError handler is provided, false if an onError handler is provided.
|
|
38
|
+
* Can be explicitly set to override these defaults.
|
|
33
39
|
*/
|
|
34
|
-
|
|
40
|
+
throwOnError?: boolean;
|
|
41
|
+
/**
|
|
42
|
+
* Time window in milliseconds within which the limit applies.
|
|
43
|
+
* Can be a number or a function that returns a number.
|
|
44
|
+
*/
|
|
45
|
+
window: number | ((rateLimiter: AsyncRateLimiter<TFn>) => number);
|
|
35
46
|
/**
|
|
36
47
|
* Type of window to use for rate limiting
|
|
37
48
|
* - 'fixed': Uses a fixed window that resets after the window period
|
|
@@ -64,11 +75,29 @@ export interface AsyncRateLimiterOptions<TFn extends AnyAsyncFunction> {
|
|
|
64
75
|
* Rate limiting is best used for hard API limits or resource constraints. For UI updates or
|
|
65
76
|
* smoothing out frequent events, throttling or debouncing usually provide better user experience.
|
|
66
77
|
*
|
|
78
|
+
* Error Handling:
|
|
79
|
+
* - If an `onError` handler is provided, it will be called with the error and rate limiter instance
|
|
80
|
+
* - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
|
|
81
|
+
* - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
|
|
82
|
+
* - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
|
|
83
|
+
* - The error state can be checked using the underlying AsyncRateLimiter instance
|
|
84
|
+
* - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler
|
|
85
|
+
*
|
|
67
86
|
* @example
|
|
68
87
|
* ```ts
|
|
69
88
|
* const rateLimiter = new AsyncRateLimiter(
|
|
70
89
|
* async (id: string) => await api.getData(id),
|
|
71
|
-
* {
|
|
90
|
+
* {
|
|
91
|
+
* limit: 5,
|
|
92
|
+
* window: 1000,
|
|
93
|
+
* windowType: 'sliding',
|
|
94
|
+
* onError: (error) => {
|
|
95
|
+
* console.error('API call failed:', error);
|
|
96
|
+
* },
|
|
97
|
+
* onReject: (limiter) => {
|
|
98
|
+
* console.log(`Rate limit exceeded. Try again in ${limiter.getMsUntilNextWindow()}ms`);
|
|
99
|
+
* }
|
|
100
|
+
* }
|
|
72
101
|
* );
|
|
73
102
|
*
|
|
74
103
|
* // Will execute immediately until limit reached, then block
|
|
@@ -95,12 +124,37 @@ export declare class AsyncRateLimiter<TFn extends AnyAsyncFunction> {
|
|
|
95
124
|
/**
|
|
96
125
|
* Returns the current rate limiter options
|
|
97
126
|
*/
|
|
98
|
-
getOptions():
|
|
127
|
+
getOptions(): AsyncRateLimiterOptions<TFn>;
|
|
128
|
+
/**
|
|
129
|
+
* Returns the current enabled state of the rate limiter
|
|
130
|
+
*/
|
|
131
|
+
getEnabled(): boolean;
|
|
132
|
+
/**
|
|
133
|
+
* Returns the current limit of executions allowed within the time window
|
|
134
|
+
*/
|
|
135
|
+
getLimit(): number;
|
|
136
|
+
/**
|
|
137
|
+
* Returns the current time window in milliseconds
|
|
138
|
+
*/
|
|
139
|
+
getWindow(): number;
|
|
99
140
|
/**
|
|
100
141
|
* Attempts to execute the rate-limited function if within the configured limits.
|
|
101
142
|
* Will reject execution if the number of calls in the current window exceeds the limit.
|
|
102
143
|
* If execution is allowed, waits for any previous execution to complete before proceeding.
|
|
103
144
|
*
|
|
145
|
+
* Error Handling:
|
|
146
|
+
* - If the rate-limited function throws and no `onError` handler is configured,
|
|
147
|
+
* the error will be thrown from this method.
|
|
148
|
+
* - If an `onError` handler is configured, errors will be caught and passed to the handler,
|
|
149
|
+
* and this method will return undefined.
|
|
150
|
+
* - If the rate limit is exceeded, the execution will be rejected and the `onReject` handler
|
|
151
|
+
* will be called if configured.
|
|
152
|
+
* - The error state can be checked using `getErrorCount()` and `getIsExecuting()`.
|
|
153
|
+
* - Rate limit rejections can be tracked using `getRejectionCount()`.
|
|
154
|
+
*
|
|
155
|
+
* @returns A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError
|
|
156
|
+
* @throws The error from the rate-limited function if no onError handler is configured
|
|
157
|
+
*
|
|
104
158
|
* @example
|
|
105
159
|
* ```ts
|
|
106
160
|
* const rateLimiter = new AsyncRateLimiter(fn, { limit: 5, window: 1000 });
|
|
@@ -172,6 +226,14 @@ export declare class AsyncRateLimiter<TFn extends AnyAsyncFunction> {
|
|
|
172
226
|
* Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically
|
|
173
227
|
* need to enforce a hard limit on the number of executions within a time period.
|
|
174
228
|
*
|
|
229
|
+
* Error Handling:
|
|
230
|
+
* - If an `onError` handler is provided, it will be called with the error and rate limiter instance
|
|
231
|
+
* - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
|
|
232
|
+
* - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
|
|
233
|
+
* - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
|
|
234
|
+
* - The error state can be checked using the underlying AsyncRateLimiter instance
|
|
235
|
+
* - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler
|
|
236
|
+
*
|
|
175
237
|
* @example
|
|
176
238
|
* ```ts
|
|
177
239
|
* // Rate limit to 5 calls per minute with a sliding window
|
|
@@ -179,6 +241,9 @@ export declare class AsyncRateLimiter<TFn extends AnyAsyncFunction> {
|
|
|
179
241
|
* limit: 5,
|
|
180
242
|
* window: 60000,
|
|
181
243
|
* windowType: 'sliding',
|
|
244
|
+
* onError: (error) => {
|
|
245
|
+
* console.error('API call failed:', error);
|
|
246
|
+
* },
|
|
182
247
|
* onReject: (rateLimiter) => {
|
|
183
248
|
* console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
|
|
184
249
|
* }
|
|
@@ -193,4 +258,4 @@ export declare class AsyncRateLimiter<TFn extends AnyAsyncFunction> {
|
|
|
193
258
|
* const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
|
|
194
259
|
* ```
|
|
195
260
|
*/
|
|
196
|
-
export declare function asyncRateLimit<TFn extends AnyAsyncFunction>(fn: TFn, initialOptions:
|
|
261
|
+
export declare function asyncRateLimit<TFn extends AnyAsyncFunction>(fn: TFn, initialOptions: AsyncRateLimiterOptions<TFn>): (...args: Parameters<TFn>) => Promise<ReturnType<TFn> | undefined>;
|