@tanstack/pacer 0.1.0 → 0.2.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 +60 -44
- package/dist/cjs/async-debouncer.cjs.map +1 -1
- package/dist/cjs/async-debouncer.d.cts +37 -24
- package/dist/cjs/async-queuer.cjs +149 -125
- package/dist/cjs/async-queuer.cjs.map +1 -1
- package/dist/cjs/async-queuer.d.cts +65 -48
- package/dist/cjs/async-rate-limiter.cjs +63 -46
- package/dist/cjs/async-rate-limiter.cjs.map +1 -1
- package/dist/cjs/async-rate-limiter.d.cts +39 -27
- package/dist/cjs/async-throttler.cjs +70 -47
- package/dist/cjs/async-throttler.cjs.map +1 -1
- package/dist/cjs/async-throttler.d.cts +43 -25
- package/dist/cjs/debouncer.cjs +46 -22
- package/dist/cjs/debouncer.cjs.map +1 -1
- package/dist/cjs/debouncer.d.cts +25 -11
- package/dist/cjs/index.cjs +2 -0
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.cts +2 -0
- package/dist/cjs/queuer.cjs +114 -104
- package/dist/cjs/queuer.cjs.map +1 -1
- package/dist/cjs/queuer.d.cts +53 -40
- package/dist/cjs/rate-limiter.cjs +54 -42
- package/dist/cjs/rate-limiter.cjs.map +1 -1
- package/dist/cjs/rate-limiter.d.cts +37 -45
- package/dist/cjs/throttler.cjs +61 -41
- package/dist/cjs/throttler.cjs.map +1 -1
- package/dist/cjs/throttler.d.cts +35 -22
- package/dist/cjs/types.d.cts +12 -0
- package/dist/cjs/utils.cjs +13 -0
- package/dist/cjs/utils.cjs.map +1 -0
- package/dist/cjs/utils.d.cts +1 -0
- package/dist/esm/async-debouncer.d.ts +37 -24
- package/dist/esm/async-debouncer.js +60 -44
- package/dist/esm/async-debouncer.js.map +1 -1
- package/dist/esm/async-queuer.d.ts +65 -48
- package/dist/esm/async-queuer.js +149 -125
- package/dist/esm/async-queuer.js.map +1 -1
- package/dist/esm/async-rate-limiter.d.ts +39 -27
- package/dist/esm/async-rate-limiter.js +63 -46
- package/dist/esm/async-rate-limiter.js.map +1 -1
- package/dist/esm/async-throttler.d.ts +43 -25
- package/dist/esm/async-throttler.js +70 -47
- package/dist/esm/async-throttler.js.map +1 -1
- package/dist/esm/debouncer.d.ts +25 -11
- package/dist/esm/debouncer.js +46 -22
- package/dist/esm/debouncer.js.map +1 -1
- package/dist/esm/index.d.ts +2 -0
- package/dist/esm/index.js +2 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/queuer.d.ts +53 -40
- package/dist/esm/queuer.js +114 -104
- package/dist/esm/queuer.js.map +1 -1
- package/dist/esm/rate-limiter.d.ts +37 -45
- package/dist/esm/rate-limiter.js +54 -42
- package/dist/esm/rate-limiter.js.map +1 -1
- package/dist/esm/throttler.d.ts +35 -22
- package/dist/esm/throttler.js +61 -41
- package/dist/esm/throttler.js.map +1 -1
- package/dist/esm/types.d.ts +12 -0
- package/dist/esm/utils.d.ts +1 -0
- package/dist/esm/utils.js +13 -0
- package/dist/esm/utils.js.map +1 -0
- package/package.json +8 -1
- package/src/async-debouncer.ts +90 -62
- package/src/async-queuer.ts +178 -145
- package/src/async-rate-limiter.ts +93 -67
- package/src/async-throttler.ts +98 -63
- package/src/debouncer.ts +71 -35
- package/src/index.ts +2 -0
- package/src/queuer.ts +135 -118
- package/src/rate-limiter.ts +79 -81
- package/src/throttler.ts +87 -61
- package/src/types.ts +17 -0
- package/src/utils.ts +13 -0
|
@@ -34,10 +34,18 @@ export interface AsyncQueuerOptions<TValue> {
|
|
|
34
34
|
* Callback fired whenever an item is removed from the queuer
|
|
35
35
|
*/
|
|
36
36
|
onGetNextItem?: (item: () => Promise<TValue>, queuer: AsyncQueuer<TValue>) => void;
|
|
37
|
+
/**
|
|
38
|
+
* Callback fired whenever the queuer's running state changes
|
|
39
|
+
*/
|
|
40
|
+
onIsRunningChange?: (queuer: AsyncQueuer<TValue>) => void;
|
|
37
41
|
/**
|
|
38
42
|
* Callback fired whenever an item is added or removed from the queuer
|
|
39
43
|
*/
|
|
40
|
-
|
|
44
|
+
onItemsChange?: (queuer: AsyncQueuer<TValue>) => void;
|
|
45
|
+
/**
|
|
46
|
+
* Callback fired whenever an item is rejected from being added to the queuer
|
|
47
|
+
*/
|
|
48
|
+
onReject?: (item: () => Promise<TValue>, queuer: AsyncQueuer<TValue>) => void;
|
|
41
49
|
/**
|
|
42
50
|
* Whether the queuer should start processing tasks immediately
|
|
43
51
|
*/
|
|
@@ -48,13 +56,13 @@ export interface AsyncQueuerOptions<TValue> {
|
|
|
48
56
|
wait?: number;
|
|
49
57
|
}
|
|
50
58
|
/**
|
|
51
|
-
* A flexible asynchronous
|
|
59
|
+
* A flexible asynchronous queue that processes tasks with configurable concurrency control.
|
|
52
60
|
*
|
|
53
61
|
* Features:
|
|
54
|
-
* - Priority
|
|
62
|
+
* - Priority queue support via getPriority option
|
|
55
63
|
* - Configurable concurrency limit
|
|
56
64
|
* - Task success/error/completion callbacks
|
|
57
|
-
* - FIFO (First In First Out) or LIFO (Last In First Out)
|
|
65
|
+
* - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior
|
|
58
66
|
* - Pause/resume task processing
|
|
59
67
|
* - Task cancellation
|
|
60
68
|
*
|
|
@@ -63,39 +71,60 @@ export interface AsyncQueuerOptions<TValue> {
|
|
|
63
71
|
*
|
|
64
72
|
* @example
|
|
65
73
|
* ```ts
|
|
66
|
-
* const
|
|
74
|
+
* const asyncQueuer = new AsyncQueuer<string>({ concurrency: 2 });
|
|
67
75
|
*
|
|
68
|
-
*
|
|
76
|
+
* asyncQueuer.addItem(async () => {
|
|
69
77
|
* return 'Hello';
|
|
70
78
|
* });
|
|
71
79
|
*
|
|
72
|
-
*
|
|
80
|
+
* asyncQueuer.start();
|
|
73
81
|
*
|
|
74
|
-
*
|
|
82
|
+
* asyncQueuer.onSuccess((result) => {
|
|
75
83
|
* console.log(result); // 'Hello'
|
|
76
84
|
* });
|
|
77
85
|
* ```
|
|
78
86
|
*/
|
|
79
87
|
export declare class AsyncQueuer<TValue> {
|
|
80
|
-
|
|
81
|
-
private
|
|
82
|
-
private
|
|
83
|
-
private
|
|
84
|
-
private
|
|
85
|
-
private
|
|
86
|
-
private
|
|
87
|
-
private
|
|
88
|
-
private
|
|
88
|
+
private _options;
|
|
89
|
+
private _activeItems;
|
|
90
|
+
private _executionCount;
|
|
91
|
+
private _rejectionCount;
|
|
92
|
+
private _items;
|
|
93
|
+
private _onErrorCallbacks;
|
|
94
|
+
private _onSettledCallbacks;
|
|
95
|
+
private _onSuccessCallbacks;
|
|
96
|
+
private _pendingTick;
|
|
97
|
+
private _running;
|
|
89
98
|
constructor(initialOptions?: AsyncQueuerOptions<TValue>);
|
|
90
99
|
/**
|
|
91
100
|
* Updates the queuer options
|
|
92
101
|
* Returns the new options state
|
|
93
102
|
*/
|
|
94
103
|
setOptions(newOptions: Partial<AsyncQueuerOptions<TValue>>): AsyncQueuerOptions<TValue>;
|
|
104
|
+
/**
|
|
105
|
+
* Returns the current queuer options
|
|
106
|
+
*/
|
|
107
|
+
getOptions(): Required<AsyncQueuerOptions<TValue>>;
|
|
95
108
|
/**
|
|
96
109
|
* Processes items in the queuer
|
|
97
110
|
*/
|
|
98
|
-
|
|
111
|
+
private tick;
|
|
112
|
+
/**
|
|
113
|
+
* Starts the queuer and processes items
|
|
114
|
+
*/
|
|
115
|
+
start(): Promise<void>;
|
|
116
|
+
/**
|
|
117
|
+
* Stops the queuer from processing items
|
|
118
|
+
*/
|
|
119
|
+
stop(): void;
|
|
120
|
+
/**
|
|
121
|
+
* Removes all items from the queuer
|
|
122
|
+
*/
|
|
123
|
+
clear(): void;
|
|
124
|
+
/**
|
|
125
|
+
* Resets the queuer to its initial state
|
|
126
|
+
*/
|
|
127
|
+
reset(withInitialItems?: boolean): void;
|
|
99
128
|
/**
|
|
100
129
|
* Adds a task to the queuer
|
|
101
130
|
*/
|
|
@@ -109,35 +138,23 @@ export declare class AsyncQueuer<TValue> {
|
|
|
109
138
|
/**
|
|
110
139
|
* Returns an item without removing it
|
|
111
140
|
*/
|
|
112
|
-
|
|
141
|
+
getPeek(position?: QueuePosition): (() => Promise<TValue>) | undefined;
|
|
113
142
|
/**
|
|
114
143
|
* Returns true if the queuer is empty
|
|
115
144
|
*/
|
|
116
|
-
|
|
145
|
+
getIsEmpty(): boolean;
|
|
117
146
|
/**
|
|
118
147
|
* Returns true if the queuer is full
|
|
119
148
|
*/
|
|
120
|
-
|
|
149
|
+
getIsFull(): boolean;
|
|
121
150
|
/**
|
|
122
151
|
* Returns the current size of the queuer
|
|
123
152
|
*/
|
|
124
|
-
|
|
125
|
-
/**
|
|
126
|
-
* Removes all items from the queuer
|
|
127
|
-
*/
|
|
128
|
-
clear(): void;
|
|
129
|
-
/**
|
|
130
|
-
* Resets the queuer to its initial state
|
|
131
|
-
*/
|
|
132
|
-
reset(withInitialItems?: boolean): void;
|
|
153
|
+
getSize(): number;
|
|
133
154
|
/**
|
|
134
155
|
* Returns a copy of all items in the queuer
|
|
135
156
|
*/
|
|
136
157
|
getAllItems(): Array<() => Promise<TValue>>;
|
|
137
|
-
/**
|
|
138
|
-
* Returns the number of items that have been removed from the queuer
|
|
139
|
-
*/
|
|
140
|
-
getExecutionCount(): number;
|
|
141
158
|
/**
|
|
142
159
|
* Returns the active items
|
|
143
160
|
*/
|
|
@@ -147,33 +164,33 @@ export declare class AsyncQueuer<TValue> {
|
|
|
147
164
|
*/
|
|
148
165
|
getPendingItems(): Array<() => Promise<TValue>>;
|
|
149
166
|
/**
|
|
150
|
-
*
|
|
167
|
+
* Returns the number of items that have been removed from the queuer
|
|
151
168
|
*/
|
|
152
|
-
|
|
169
|
+
getExecutionCount(): number;
|
|
153
170
|
/**
|
|
154
|
-
*
|
|
171
|
+
* Returns the number of items that have been rejected from the queuer
|
|
155
172
|
*/
|
|
156
|
-
|
|
173
|
+
getRejectionCount(): number;
|
|
157
174
|
/**
|
|
158
|
-
*
|
|
175
|
+
* Returns true if the queuer is running
|
|
159
176
|
*/
|
|
160
|
-
|
|
177
|
+
getIsRunning(): boolean;
|
|
161
178
|
/**
|
|
162
|
-
*
|
|
179
|
+
* Returns true if the queuer is running but has no items to process
|
|
163
180
|
*/
|
|
164
|
-
|
|
181
|
+
getIsIdle(): boolean;
|
|
165
182
|
/**
|
|
166
|
-
*
|
|
183
|
+
* Adds a callback to be called when a task succeeds
|
|
167
184
|
*/
|
|
168
|
-
|
|
185
|
+
onSuccess(cb: (result: TValue) => void): () => void;
|
|
169
186
|
/**
|
|
170
|
-
*
|
|
187
|
+
* Adds a callback to be called when a task errors
|
|
171
188
|
*/
|
|
172
|
-
|
|
189
|
+
onError(cb: (error: Error) => void): () => void;
|
|
173
190
|
/**
|
|
174
|
-
*
|
|
191
|
+
* Adds a callback to be called when a task is settled
|
|
175
192
|
*/
|
|
176
|
-
|
|
193
|
+
onSettled(cb: (result: TValue | Error) => void): () => void;
|
|
177
194
|
}
|
|
178
195
|
/**
|
|
179
196
|
* Creates a new AsyncQueuer instance with the given options and returns a bound addItem function.
|
|
@@ -1,13 +1,22 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const defaultOptions = {
|
|
4
|
+
enabled: true,
|
|
5
|
+
onReject: () => {
|
|
6
|
+
},
|
|
7
|
+
onError: () => {
|
|
8
|
+
},
|
|
9
|
+
onExecute: () => {
|
|
10
|
+
}
|
|
11
|
+
};
|
|
3
12
|
class AsyncRateLimiter {
|
|
4
13
|
constructor(fn, initialOptions) {
|
|
5
14
|
this.fn = fn;
|
|
6
|
-
this.
|
|
7
|
-
this.
|
|
8
|
-
this.
|
|
9
|
-
this.
|
|
10
|
-
|
|
15
|
+
this._executionCount = 0;
|
|
16
|
+
this._executionTimes = [];
|
|
17
|
+
this._rejectionCount = 0;
|
|
18
|
+
this._options = {
|
|
19
|
+
...defaultOptions,
|
|
11
20
|
...initialOptions
|
|
12
21
|
};
|
|
13
22
|
}
|
|
@@ -16,30 +25,17 @@ class AsyncRateLimiter {
|
|
|
16
25
|
* Returns the new options state
|
|
17
26
|
*/
|
|
18
27
|
setOptions(newOptions) {
|
|
19
|
-
this.
|
|
20
|
-
...this.
|
|
28
|
+
this._options = {
|
|
29
|
+
...this._options,
|
|
21
30
|
...newOptions
|
|
22
31
|
};
|
|
23
|
-
return this.
|
|
32
|
+
return this._options;
|
|
24
33
|
}
|
|
25
34
|
/**
|
|
26
|
-
* Returns the
|
|
35
|
+
* Returns the current rate limiter options
|
|
27
36
|
*/
|
|
28
|
-
|
|
29
|
-
return this.
|
|
30
|
-
}
|
|
31
|
-
/**
|
|
32
|
-
* Returns the number of times the function has been rejected
|
|
33
|
-
*/
|
|
34
|
-
getRejectionCount() {
|
|
35
|
-
return this.rejectionCount;
|
|
36
|
-
}
|
|
37
|
-
/**
|
|
38
|
-
* Returns the number of remaining executions allowed in the current window
|
|
39
|
-
*/
|
|
40
|
-
getRemainingInWindow() {
|
|
41
|
-
this.cleanupOldExecutions();
|
|
42
|
-
return Math.max(0, this.options.limit - this.executionTimes.length);
|
|
37
|
+
getOptions() {
|
|
38
|
+
return this._options;
|
|
43
39
|
}
|
|
44
40
|
/**
|
|
45
41
|
* Attempts to execute the rate-limited function if within the configured limits.
|
|
@@ -59,7 +55,7 @@ class AsyncRateLimiter {
|
|
|
59
55
|
*/
|
|
60
56
|
async maybeExecute(...args) {
|
|
61
57
|
this.cleanupOldExecutions();
|
|
62
|
-
if (this.
|
|
58
|
+
if (this._executionTimes.length < this._options.limit) {
|
|
63
59
|
await this.executeFunction(...args);
|
|
64
60
|
return true;
|
|
65
61
|
}
|
|
@@ -67,50 +63,71 @@ class AsyncRateLimiter {
|
|
|
67
63
|
return false;
|
|
68
64
|
}
|
|
69
65
|
async executeFunction(...args) {
|
|
70
|
-
|
|
66
|
+
var _a, _b;
|
|
67
|
+
if (!this._options.enabled) return;
|
|
71
68
|
const now = Date.now();
|
|
72
|
-
this.
|
|
73
|
-
this.
|
|
69
|
+
this._executionCount++;
|
|
70
|
+
this._executionTimes.push(now);
|
|
74
71
|
try {
|
|
75
72
|
await this.fn(...args);
|
|
76
73
|
} catch (error) {
|
|
77
|
-
if (this.
|
|
74
|
+
if (this._options.onError) {
|
|
78
75
|
try {
|
|
79
|
-
this.
|
|
80
|
-
} catch {
|
|
76
|
+
this._options.onError(error);
|
|
77
|
+
} catch (error2) {
|
|
78
|
+
console.error("Error in onError handler", error2);
|
|
81
79
|
}
|
|
82
80
|
}
|
|
83
81
|
throw error;
|
|
84
82
|
} finally {
|
|
83
|
+
(_b = (_a = this._options).onExecute) == null ? void 0 : _b.call(_a, this);
|
|
85
84
|
}
|
|
86
85
|
}
|
|
87
86
|
rejectFunction() {
|
|
88
|
-
this.
|
|
89
|
-
if (this.
|
|
90
|
-
|
|
91
|
-
const msUntilNextWindow = oldestExecution + this.options.window - Date.now();
|
|
92
|
-
this.options.onReject({
|
|
93
|
-
msUntilNextWindow,
|
|
94
|
-
currentExecutions: this.executionTimes.length,
|
|
95
|
-
limit: this.options.limit,
|
|
96
|
-
rejectionCount: this.rejectionCount
|
|
97
|
-
});
|
|
87
|
+
this._rejectionCount++;
|
|
88
|
+
if (this._options.onReject) {
|
|
89
|
+
this._options.onReject(this);
|
|
98
90
|
}
|
|
99
91
|
}
|
|
100
92
|
cleanupOldExecutions() {
|
|
101
93
|
const now = Date.now();
|
|
102
|
-
const windowStart = now - this.
|
|
103
|
-
this.
|
|
94
|
+
const windowStart = now - this._options.window;
|
|
95
|
+
this._executionTimes = this._executionTimes.filter(
|
|
104
96
|
(time) => time > windowStart
|
|
105
97
|
);
|
|
106
98
|
}
|
|
99
|
+
/**
|
|
100
|
+
* Returns the number of times the function has been executed
|
|
101
|
+
*/
|
|
102
|
+
getExecutionCount() {
|
|
103
|
+
return this._executionCount;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Returns the number of times the function has been rejected
|
|
107
|
+
*/
|
|
108
|
+
getRejectionCount() {
|
|
109
|
+
return this._rejectionCount;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Returns the number of remaining executions allowed in the current window
|
|
113
|
+
*/
|
|
114
|
+
getRemainingInWindow() {
|
|
115
|
+
this.cleanupOldExecutions();
|
|
116
|
+
return Math.max(0, this._options.limit - this._executionTimes.length);
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Returns the number of milliseconds until the next execution will be possible
|
|
120
|
+
*/
|
|
121
|
+
getMsUntilNextWindow() {
|
|
122
|
+
return this.getRemainingInWindow() * this._options.window;
|
|
123
|
+
}
|
|
107
124
|
/**
|
|
108
125
|
* Resets the rate limiter state
|
|
109
126
|
*/
|
|
110
127
|
reset() {
|
|
111
|
-
this.
|
|
112
|
-
this.
|
|
113
|
-
this.
|
|
128
|
+
this._executionTimes = [];
|
|
129
|
+
this._executionCount = 0;
|
|
130
|
+
this._rejectionCount = 0;
|
|
114
131
|
}
|
|
115
132
|
}
|
|
116
133
|
function asyncRateLimit(fn, initialOptions) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"async-rate-limiter.cjs","sources":["../../src/async-rate-limiter.ts"],"sourcesContent":["import type {
|
|
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<\n TFn extends AnyAsyncFunction,\n TArgs extends Parameters<TFn>,\n> {\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) => void\n /**\n * Optional function to call when the rate-limited function is executed\n */\n onExecute?: (rateLimiter: AsyncRateLimiter<TFn, TArgs>) => void\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (rateLimiter: AsyncRateLimiter<TFn, TArgs>) => void\n /**\n * Time window in milliseconds within which the limit applies\n */\n window: number\n}\n\nconst defaultOptions: Required<\n Omit<AsyncRateLimiterOptions<any, any>, 'limit' | 'window'>\n> = {\n enabled: true,\n onReject: () => {},\n onError: () => {},\n onExecute: () => {},\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 * 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 } // 5 calls per second\n * );\n *\n * // Will execute immediately until limit reached, then block\n * await rateLimiter.maybeExecute('123');\n * ```\n */\nexport class AsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TArgs extends Parameters<TFn>,\n> {\n private _executionCount = 0\n private _executionTimes: Array<number> = []\n private _options: AsyncRateLimiterOptions<TFn, TArgs>\n private _rejectionCount = 0\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncRateLimiterOptions<TFn, TArgs>,\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(\n newOptions: Partial<AsyncRateLimiterOptions<TFn, TArgs>>,\n ): AsyncRateLimiterOptions<TFn, TArgs> {\n this._options = {\n ...this._options,\n ...newOptions,\n }\n return this._options\n }\n\n /**\n * Returns the current rate limiter options\n */\n getOptions(): Required<AsyncRateLimiterOptions<TFn, TArgs>> {\n return this._options as Required<AsyncRateLimiterOptions<TFn, TArgs>>\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(...args: TArgs): Promise<boolean> {\n this.cleanupOldExecutions()\n\n if (this._executionTimes.length < this._options.limit) {\n await this.executeFunction(...args)\n return true\n }\n\n this.rejectFunction()\n return false\n }\n\n private async executeFunction(...args: TArgs): Promise<void> {\n if (!this._options.enabled) return\n const now = Date.now()\n this._executionCount++\n this._executionTimes.push(now)\n\n try {\n await this.fn(...args)\n } catch (error) {\n if (this._options.onError) {\n try {\n this._options.onError(error)\n } catch (error) {\n console.error('Error in onError handler', error)\n }\n }\n throw error\n } finally {\n this._options.onExecute?.(this)\n }\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 times the function has been executed\n */\n getExecutionCount(): number {\n return this._executionCount\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 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 */\n getMsUntilNextWindow(): number {\n return this.getRemainingInWindow() * this._options.window\n }\n\n /**\n * Resets the rate limiter state\n */\n reset(): void {\n this._executionTimes = []\n this._executionCount = 0\n this._rejectionCount = 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 * 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\n * const rateLimited = asyncRateLimit(makeApiCall, {\n * limit: 5,\n * window: 60000,\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 * 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<\n TFn extends AnyAsyncFunction,\n TArgs extends Parameters<TFn>,\n>(\n fn: TFn,\n initialOptions: Omit<AsyncRateLimiterOptions<TFn, TArgs>, 'enabled'>,\n) {\n const rateLimiter = new AsyncRateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute.bind(rateLimiter)\n}\n"],"names":["error"],"mappings":";;AAoCA,MAAM,iBAEF;AAAA,EACF,SAAS;AAAA,EACT,UAAU,MAAM;AAAA,EAAC;AAAA,EACjB,SAAS,MAAM;AAAA,EAAC;AAAA,EAChB,WAAW,MAAM;AAAA,EAAA;AACnB;AA2BO,MAAM,iBAGX;AAAA,EAMA,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AANV,SAAQ,kBAAkB;AAC1B,SAAQ,kBAAiC,CAAC;AAE1C,SAAQ,kBAAkB;AAMxB,SAAK,WAAW;AAAA,MACd,GAAG;AAAA,MACH,GAAG;AAAA,IACL;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,WACE,YACqC;AACrC,SAAK,WAAW;AAAA,MACd,GAAG,KAAK;AAAA,MACR,GAAG;AAAA,IACL;AACA,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,aAA4D;AAC1D,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAmBd,MAAM,gBAAgB,MAA+B;AACnD,SAAK,qBAAqB;AAE1B,QAAI,KAAK,gBAAgB,SAAS,KAAK,SAAS,OAAO;AAC/C,YAAA,KAAK,gBAAgB,GAAG,IAAI;AAC3B,aAAA;AAAA,IAAA;AAGT,SAAK,eAAe;AACb,WAAA;AAAA,EAAA;AAAA,EAGT,MAAc,mBAAmB,MAA4B;;AACvD,QAAA,CAAC,KAAK,SAAS,QAAS;AACtB,UAAA,MAAM,KAAK,IAAI;AAChB,SAAA;AACA,SAAA,gBAAgB,KAAK,GAAG;AAEzB,QAAA;AACI,YAAA,KAAK,GAAG,GAAG,IAAI;AAAA,aACd,OAAO;AACV,UAAA,KAAK,SAAS,SAAS;AACrB,YAAA;AACG,eAAA,SAAS,QAAQ,KAAK;AAAA,iBACpBA,QAAO;AACN,kBAAA,MAAM,4BAA4BA,MAAK;AAAA,QAAA;AAAA,MACjD;AAEI,YAAA;AAAA,IAAA,UACN;AACK,uBAAA,UAAS,cAAT,4BAAqB;AAAA,IAAI;AAAA,EAChC;AAAA,EAGM,iBAAuB;AACxB,SAAA;AACD,QAAA,KAAK,SAAS,UAAU;AACrB,WAAA,SAAS,SAAS,IAAI;AAAA,IAAA;AAAA,EAC7B;AAAA,EAGM,uBAA6B;AAC7B,UAAA,MAAM,KAAK,IAAI;AACf,UAAA,cAAc,MAAM,KAAK,SAAS;AACnC,SAAA,kBAAkB,KAAK,gBAAgB;AAAA,MAC1C,CAAC,SAAS,OAAO;AAAA,IACnB;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMF,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,uBAA+B;AAC7B,SAAK,qBAAqB;AACnB,WAAA,KAAK,IAAI,GAAG,KAAK,SAAS,QAAQ,KAAK,gBAAgB,MAAM;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMtE,uBAA+B;AAC7B,WAAO,KAAK,qBAAA,IAAyB,KAAK,SAAS;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMrD,QAAc;AACZ,SAAK,kBAAkB,CAAC;AACxB,SAAK,kBAAkB;AACvB,SAAK,kBAAkB;AAAA,EAAA;AAE3B;AAgCgB,SAAA,eAId,IACA,gBACA;AACA,QAAM,cAAc,IAAI,iBAAiB,IAAI,cAAc;AACpD,SAAA,YAAY,aAAa,KAAK,WAAW;AAClD;;;"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { AnyAsyncFunction } from './types.cjs';
|
|
2
2
|
/**
|
|
3
3
|
* Options for configuring an async rate-limited function
|
|
4
4
|
*/
|
|
5
|
-
export interface AsyncRateLimiterOptions {
|
|
5
|
+
export interface AsyncRateLimiterOptions<TFn extends AnyAsyncFunction, TArgs extends Parameters<TFn>> {
|
|
6
6
|
/**
|
|
7
7
|
* Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.
|
|
8
8
|
* Defaults to true.
|
|
@@ -13,17 +13,21 @@ export interface AsyncRateLimiterOptions {
|
|
|
13
13
|
*/
|
|
14
14
|
limit: number;
|
|
15
15
|
/**
|
|
16
|
-
*
|
|
16
|
+
* Optional error handler for when the rate-limited function throws
|
|
17
17
|
*/
|
|
18
|
-
|
|
18
|
+
onError?: (error: unknown) => void;
|
|
19
|
+
/**
|
|
20
|
+
* Optional function to call when the rate-limited function is executed
|
|
21
|
+
*/
|
|
22
|
+
onExecute?: (rateLimiter: AsyncRateLimiter<TFn, TArgs>) => void;
|
|
19
23
|
/**
|
|
20
24
|
* Optional callback function that is called when an execution is rejected due to rate limiting
|
|
21
25
|
*/
|
|
22
|
-
onReject?: (
|
|
26
|
+
onReject?: (rateLimiter: AsyncRateLimiter<TFn, TArgs>) => void;
|
|
23
27
|
/**
|
|
24
|
-
*
|
|
28
|
+
* Time window in milliseconds within which the limit applies
|
|
25
29
|
*/
|
|
26
|
-
|
|
30
|
+
window: number;
|
|
27
31
|
}
|
|
28
32
|
/**
|
|
29
33
|
* A class that creates an async rate-limited function.
|
|
@@ -50,30 +54,22 @@ export interface AsyncRateLimiterOptions {
|
|
|
50
54
|
* await rateLimiter.maybeExecute('123');
|
|
51
55
|
* ```
|
|
52
56
|
*/
|
|
53
|
-
export declare class AsyncRateLimiter<TFn extends
|
|
57
|
+
export declare class AsyncRateLimiter<TFn extends AnyAsyncFunction, TArgs extends Parameters<TFn>> {
|
|
54
58
|
private fn;
|
|
55
|
-
private
|
|
56
|
-
private
|
|
57
|
-
private
|
|
58
|
-
private
|
|
59
|
-
constructor(fn: TFn, initialOptions: AsyncRateLimiterOptions);
|
|
59
|
+
private _executionCount;
|
|
60
|
+
private _executionTimes;
|
|
61
|
+
private _options;
|
|
62
|
+
private _rejectionCount;
|
|
63
|
+
constructor(fn: TFn, initialOptions: AsyncRateLimiterOptions<TFn, TArgs>);
|
|
60
64
|
/**
|
|
61
65
|
* Updates the rate limiter options
|
|
62
66
|
* Returns the new options state
|
|
63
67
|
*/
|
|
64
|
-
setOptions(newOptions: Partial<AsyncRateLimiterOptions
|
|
65
|
-
/**
|
|
66
|
-
* Returns the number of times the function has been executed
|
|
67
|
-
*/
|
|
68
|
-
getExecutionCount(): number;
|
|
69
|
-
/**
|
|
70
|
-
* Returns the number of times the function has been rejected
|
|
71
|
-
*/
|
|
72
|
-
getRejectionCount(): number;
|
|
68
|
+
setOptions(newOptions: Partial<AsyncRateLimiterOptions<TFn, TArgs>>): AsyncRateLimiterOptions<TFn, TArgs>;
|
|
73
69
|
/**
|
|
74
|
-
* Returns the
|
|
70
|
+
* Returns the current rate limiter options
|
|
75
71
|
*/
|
|
76
|
-
|
|
72
|
+
getOptions(): Required<AsyncRateLimiterOptions<TFn, TArgs>>;
|
|
77
73
|
/**
|
|
78
74
|
* Attempts to execute the rate-limited function if within the configured limits.
|
|
79
75
|
* Will reject execution if the number of calls in the current window exceeds the limit.
|
|
@@ -94,6 +90,22 @@ export declare class AsyncRateLimiter<TFn extends (...args: Array<any>) => Promi
|
|
|
94
90
|
private executeFunction;
|
|
95
91
|
private rejectFunction;
|
|
96
92
|
private cleanupOldExecutions;
|
|
93
|
+
/**
|
|
94
|
+
* Returns the number of times the function has been executed
|
|
95
|
+
*/
|
|
96
|
+
getExecutionCount(): number;
|
|
97
|
+
/**
|
|
98
|
+
* Returns the number of times the function has been rejected
|
|
99
|
+
*/
|
|
100
|
+
getRejectionCount(): number;
|
|
101
|
+
/**
|
|
102
|
+
* Returns the number of remaining executions allowed in the current window
|
|
103
|
+
*/
|
|
104
|
+
getRemainingInWindow(): number;
|
|
105
|
+
/**
|
|
106
|
+
* Returns the number of milliseconds until the next execution will be possible
|
|
107
|
+
*/
|
|
108
|
+
getMsUntilNextWindow(): number;
|
|
97
109
|
/**
|
|
98
110
|
* Resets the rate limiter state
|
|
99
111
|
*/
|
|
@@ -116,8 +128,8 @@ export declare class AsyncRateLimiter<TFn extends (...args: Array<any>) => Promi
|
|
|
116
128
|
* const rateLimited = asyncRateLimit(makeApiCall, {
|
|
117
129
|
* limit: 5,
|
|
118
130
|
* window: 60000,
|
|
119
|
-
* onReject: (
|
|
120
|
-
* console.log(`Rate limit exceeded. Try again in ${
|
|
131
|
+
* onReject: (rateLimiter) => {
|
|
132
|
+
* console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
|
|
121
133
|
* }
|
|
122
134
|
* });
|
|
123
135
|
*
|
|
@@ -129,4 +141,4 @@ export declare class AsyncRateLimiter<TFn extends (...args: Array<any>) => Promi
|
|
|
129
141
|
* const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
|
|
130
142
|
* ```
|
|
131
143
|
*/
|
|
132
|
-
export declare function asyncRateLimit<TFn extends
|
|
144
|
+
export declare function asyncRateLimit<TFn extends AnyAsyncFunction, TArgs extends Parameters<TFn>>(fn: TFn, initialOptions: Omit<AsyncRateLimiterOptions<TFn, TArgs>, 'enabled'>): (...args: TArgs) => Promise<boolean>;
|