@h1s97x/request-queue 0.1.1
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/LICENSE +21 -0
- package/dist/index.cjs +223 -0
- package/dist/index.d.cts +91 -0
- package/dist/index.d.mts +91 -0
- package/dist/index.d.ts +91 -0
- package/dist/index.mjs +220 -0
- package/package.json +50 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 h1s97x
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const tokenBucket = require('@h1s97x/token-bucket');
|
|
4
|
+
|
|
5
|
+
var __defProp = Object.defineProperty;
|
|
6
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
7
|
+
var __publicField = (obj, key, value) => {
|
|
8
|
+
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
9
|
+
return value;
|
|
10
|
+
};
|
|
11
|
+
const DEFAULT_OPTIONS = {
|
|
12
|
+
maxSize: 100,
|
|
13
|
+
maxWaitTime: 6e4,
|
|
14
|
+
bucketCapacity: 20,
|
|
15
|
+
requestsPerSecond: 10
|
|
16
|
+
};
|
|
17
|
+
class RequestQueueManager {
|
|
18
|
+
constructor(options = {}) {
|
|
19
|
+
__publicField(this, "queue", []);
|
|
20
|
+
__publicField(this, "options");
|
|
21
|
+
__publicField(this, "rateLimiter");
|
|
22
|
+
__publicField(this, "stats");
|
|
23
|
+
__publicField(this, "cleanupInterval", null);
|
|
24
|
+
__publicField(this, "idCounter", 0);
|
|
25
|
+
this.options = { ...DEFAULT_OPTIONS, ...options };
|
|
26
|
+
this.rateLimiter = new tokenBucket.TokenBucketRateLimiter({
|
|
27
|
+
capacity: this.options.bucketCapacity,
|
|
28
|
+
refillRate: this.options.requestsPerSecond
|
|
29
|
+
});
|
|
30
|
+
this.stats = {
|
|
31
|
+
waiting: 0,
|
|
32
|
+
processing: 0,
|
|
33
|
+
completed: 0,
|
|
34
|
+
failed: 0,
|
|
35
|
+
timeout: 0,
|
|
36
|
+
maxQueueLength: 0,
|
|
37
|
+
totalProcessed: 0
|
|
38
|
+
};
|
|
39
|
+
this.cleanupInterval = setInterval(() => {
|
|
40
|
+
this.cleanup();
|
|
41
|
+
}, 1e4);
|
|
42
|
+
}
|
|
43
|
+
generateId() {
|
|
44
|
+
return `job_${Date.now()}_${++this.idCounter}`;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Enqueue a task for rate-limited execution.
|
|
48
|
+
* Returns a promise that resolves with the task's result
|
|
49
|
+
* once a rate-limit token is acquired and the task completes.
|
|
50
|
+
*/
|
|
51
|
+
async enqueue(task, timeout) {
|
|
52
|
+
const jobId = this.generateId();
|
|
53
|
+
const waitTimeout = timeout ?? this.options.maxWaitTime;
|
|
54
|
+
if (this.queue.length >= this.options.maxSize) {
|
|
55
|
+
throw new Error(`QUEUE_FULL: Queue is full (${this.options.maxSize})`);
|
|
56
|
+
}
|
|
57
|
+
this.stats.maxQueueLength = Math.max(
|
|
58
|
+
this.stats.maxQueueLength,
|
|
59
|
+
this.queue.length + 1
|
|
60
|
+
);
|
|
61
|
+
return new Promise((resolve, reject) => {
|
|
62
|
+
const timeoutId = setTimeout(() => {
|
|
63
|
+
const index = this.queue.findIndex((j) => j.id === jobId);
|
|
64
|
+
if (index !== -1) {
|
|
65
|
+
this.queue.splice(index, 1);
|
|
66
|
+
this.stats.waiting--;
|
|
67
|
+
}
|
|
68
|
+
this.stats.timeout++;
|
|
69
|
+
reject(new Error(`TIMEOUT: Task waited too long (${waitTimeout}ms)`));
|
|
70
|
+
}, waitTimeout);
|
|
71
|
+
const job = {
|
|
72
|
+
id: jobId,
|
|
73
|
+
task,
|
|
74
|
+
resolve,
|
|
75
|
+
reject,
|
|
76
|
+
createdAt: Date.now(),
|
|
77
|
+
timeout: timeoutId,
|
|
78
|
+
status: "waiting"
|
|
79
|
+
};
|
|
80
|
+
this.queue.push(job);
|
|
81
|
+
this.stats.waiting++;
|
|
82
|
+
this.processQueue();
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Process the queue: acquire tokens and execute tasks
|
|
87
|
+
*/
|
|
88
|
+
async processQueue() {
|
|
89
|
+
while (this.queue.length > 0) {
|
|
90
|
+
if (!this.rateLimiter.tryAcquire()) {
|
|
91
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
const job = this.queue.shift();
|
|
95
|
+
if (!job)
|
|
96
|
+
break;
|
|
97
|
+
clearTimeout(job.timeout);
|
|
98
|
+
this.stats.waiting--;
|
|
99
|
+
this.stats.processing++;
|
|
100
|
+
this.stats.totalProcessed++;
|
|
101
|
+
job.status = "processing";
|
|
102
|
+
try {
|
|
103
|
+
const result = await job.task();
|
|
104
|
+
job.status = "completed";
|
|
105
|
+
this.stats.processing--;
|
|
106
|
+
this.stats.completed++;
|
|
107
|
+
job.resolve(result);
|
|
108
|
+
} catch (error) {
|
|
109
|
+
job.status = "failed";
|
|
110
|
+
this.stats.processing--;
|
|
111
|
+
this.stats.failed++;
|
|
112
|
+
job.reject(error instanceof Error ? error : new Error(String(error)));
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Get queue statistics
|
|
118
|
+
*/
|
|
119
|
+
getStats() {
|
|
120
|
+
const now = Date.now();
|
|
121
|
+
const totalWaitTime = this.queue.reduce(
|
|
122
|
+
(sum, job) => sum + (now - job.createdAt),
|
|
123
|
+
0
|
|
124
|
+
);
|
|
125
|
+
const avgWaitTime = this.queue.length > 0 ? totalWaitTime / this.queue.length : 0;
|
|
126
|
+
return {
|
|
127
|
+
...this.stats,
|
|
128
|
+
avgWaitTime,
|
|
129
|
+
currentTokenBucket: this.rateLimiter.getStatus()
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Estimate wait time for a new task
|
|
134
|
+
*/
|
|
135
|
+
getEstimatedWaitTime() {
|
|
136
|
+
if (this.queue.length === 0)
|
|
137
|
+
return 0;
|
|
138
|
+
const avgWaitPerRequest = 1e3 / this.options.requestsPerSecond;
|
|
139
|
+
return Math.ceil(this.queue.length * avgWaitPerRequest);
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Check if a new task can be enqueued
|
|
143
|
+
*/
|
|
144
|
+
canEnqueue() {
|
|
145
|
+
if (this.queue.length >= this.options.maxSize) {
|
|
146
|
+
return {
|
|
147
|
+
allowed: false,
|
|
148
|
+
reason: `Queue is full (${this.queue.length}/${this.options.maxSize})`
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
const estimatedWait = this.getEstimatedWaitTime();
|
|
152
|
+
if (estimatedWait > this.options.maxWaitTime) {
|
|
153
|
+
return {
|
|
154
|
+
allowed: false,
|
|
155
|
+
reason: `Estimated wait too long (${Math.round(estimatedWait / 1e3)}s)`,
|
|
156
|
+
estimatedWait
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
return { allowed: true, estimatedWait };
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Periodic cleanup: evict stale tasks that exceeded maxWaitTime
|
|
163
|
+
*/
|
|
164
|
+
cleanup() {
|
|
165
|
+
const now = Date.now();
|
|
166
|
+
const expired = [];
|
|
167
|
+
for (let i = this.queue.length - 1; i >= 0; i--) {
|
|
168
|
+
const job = this.queue[i];
|
|
169
|
+
if (now - job.createdAt > this.options.maxWaitTime) {
|
|
170
|
+
expired.push(job);
|
|
171
|
+
this.queue.splice(i, 1);
|
|
172
|
+
this.stats.waiting--;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
for (const job of expired) {
|
|
176
|
+
clearTimeout(job.timeout);
|
|
177
|
+
job.status = "timeout";
|
|
178
|
+
this.stats.timeout++;
|
|
179
|
+
job.reject(new Error(`CLEANUP: Task evicted after ${this.options.maxWaitTime}ms`));
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Update rate limiting config
|
|
184
|
+
*/
|
|
185
|
+
updateRateLimit(refillRate, capacity) {
|
|
186
|
+
this.options.requestsPerSecond = refillRate;
|
|
187
|
+
if (capacity !== void 0) {
|
|
188
|
+
this.options.bucketCapacity = capacity;
|
|
189
|
+
}
|
|
190
|
+
this.rateLimiter.updateConfig(refillRate, capacity);
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Clear all queued tasks
|
|
194
|
+
*/
|
|
195
|
+
clear() {
|
|
196
|
+
for (const job of this.queue) {
|
|
197
|
+
clearTimeout(job.timeout);
|
|
198
|
+
job.reject(new Error("CLEARED: Queue has been cleared"));
|
|
199
|
+
}
|
|
200
|
+
this.queue = [];
|
|
201
|
+
this.stats.waiting = 0;
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Destroy the queue manager and release resources
|
|
205
|
+
*/
|
|
206
|
+
destroy() {
|
|
207
|
+
if (this.cleanupInterval !== null) {
|
|
208
|
+
clearInterval(this.cleanupInterval);
|
|
209
|
+
this.cleanupInterval = null;
|
|
210
|
+
}
|
|
211
|
+
this.clear();
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
let queueInstance = null;
|
|
215
|
+
function getRequestQueue() {
|
|
216
|
+
if (!queueInstance) {
|
|
217
|
+
queueInstance = new RequestQueueManager();
|
|
218
|
+
}
|
|
219
|
+
return queueInstance;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
exports.RequestQueueManager = RequestQueueManager;
|
|
223
|
+
exports.getRequestQueue = getRequestQueue;
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { TokenBucketRateLimiter } from '@h1s97x/token-bucket';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* FIFO request queue manager with rate limiting
|
|
5
|
+
*
|
|
6
|
+
* Features:
|
|
7
|
+
* - FIFO order for fairness
|
|
8
|
+
* - Configurable max queue length
|
|
9
|
+
* - Rate-limited task execution via token bucket
|
|
10
|
+
* - Timeout-based task eviction
|
|
11
|
+
* - Wait time estimation
|
|
12
|
+
* - Periodic stale cleanup
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
interface QueueOptions {
|
|
16
|
+
/** Maximum queue length */
|
|
17
|
+
maxSize: number;
|
|
18
|
+
/** Max task wait time in ms */
|
|
19
|
+
maxWaitTime: number;
|
|
20
|
+
/** Token bucket capacity (burst) */
|
|
21
|
+
bucketCapacity: number;
|
|
22
|
+
/** Requests allowed per second */
|
|
23
|
+
requestsPerSecond: number;
|
|
24
|
+
}
|
|
25
|
+
interface QueueStats {
|
|
26
|
+
waiting: number;
|
|
27
|
+
processing: number;
|
|
28
|
+
completed: number;
|
|
29
|
+
failed: number;
|
|
30
|
+
timeout: number;
|
|
31
|
+
avgWaitTime: number;
|
|
32
|
+
maxQueueLength: number;
|
|
33
|
+
totalProcessed: number;
|
|
34
|
+
currentTokenBucket: ReturnType<TokenBucketRateLimiter['getStatus']>;
|
|
35
|
+
}
|
|
36
|
+
declare class RequestQueueManager {
|
|
37
|
+
private queue;
|
|
38
|
+
private options;
|
|
39
|
+
private rateLimiter;
|
|
40
|
+
private stats;
|
|
41
|
+
private cleanupInterval;
|
|
42
|
+
private idCounter;
|
|
43
|
+
constructor(options?: Partial<QueueOptions>);
|
|
44
|
+
private generateId;
|
|
45
|
+
/**
|
|
46
|
+
* Enqueue a task for rate-limited execution.
|
|
47
|
+
* Returns a promise that resolves with the task's result
|
|
48
|
+
* once a rate-limit token is acquired and the task completes.
|
|
49
|
+
*/
|
|
50
|
+
enqueue<T>(task: () => Promise<T>, timeout?: number): Promise<T>;
|
|
51
|
+
/**
|
|
52
|
+
* Process the queue: acquire tokens and execute tasks
|
|
53
|
+
*/
|
|
54
|
+
private processQueue;
|
|
55
|
+
/**
|
|
56
|
+
* Get queue statistics
|
|
57
|
+
*/
|
|
58
|
+
getStats(): QueueStats;
|
|
59
|
+
/**
|
|
60
|
+
* Estimate wait time for a new task
|
|
61
|
+
*/
|
|
62
|
+
getEstimatedWaitTime(): number;
|
|
63
|
+
/**
|
|
64
|
+
* Check if a new task can be enqueued
|
|
65
|
+
*/
|
|
66
|
+
canEnqueue(): {
|
|
67
|
+
allowed: boolean;
|
|
68
|
+
reason?: string;
|
|
69
|
+
estimatedWait?: number;
|
|
70
|
+
};
|
|
71
|
+
/**
|
|
72
|
+
* Periodic cleanup: evict stale tasks that exceeded maxWaitTime
|
|
73
|
+
*/
|
|
74
|
+
private cleanup;
|
|
75
|
+
/**
|
|
76
|
+
* Update rate limiting config
|
|
77
|
+
*/
|
|
78
|
+
updateRateLimit(refillRate: number, capacity?: number): void;
|
|
79
|
+
/**
|
|
80
|
+
* Clear all queued tasks
|
|
81
|
+
*/
|
|
82
|
+
clear(): void;
|
|
83
|
+
/**
|
|
84
|
+
* Destroy the queue manager and release resources
|
|
85
|
+
*/
|
|
86
|
+
destroy(): void;
|
|
87
|
+
}
|
|
88
|
+
declare function getRequestQueue(): RequestQueueManager;
|
|
89
|
+
|
|
90
|
+
export { RequestQueueManager, getRequestQueue };
|
|
91
|
+
export type { QueueOptions, QueueStats };
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { TokenBucketRateLimiter } from '@h1s97x/token-bucket';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* FIFO request queue manager with rate limiting
|
|
5
|
+
*
|
|
6
|
+
* Features:
|
|
7
|
+
* - FIFO order for fairness
|
|
8
|
+
* - Configurable max queue length
|
|
9
|
+
* - Rate-limited task execution via token bucket
|
|
10
|
+
* - Timeout-based task eviction
|
|
11
|
+
* - Wait time estimation
|
|
12
|
+
* - Periodic stale cleanup
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
interface QueueOptions {
|
|
16
|
+
/** Maximum queue length */
|
|
17
|
+
maxSize: number;
|
|
18
|
+
/** Max task wait time in ms */
|
|
19
|
+
maxWaitTime: number;
|
|
20
|
+
/** Token bucket capacity (burst) */
|
|
21
|
+
bucketCapacity: number;
|
|
22
|
+
/** Requests allowed per second */
|
|
23
|
+
requestsPerSecond: number;
|
|
24
|
+
}
|
|
25
|
+
interface QueueStats {
|
|
26
|
+
waiting: number;
|
|
27
|
+
processing: number;
|
|
28
|
+
completed: number;
|
|
29
|
+
failed: number;
|
|
30
|
+
timeout: number;
|
|
31
|
+
avgWaitTime: number;
|
|
32
|
+
maxQueueLength: number;
|
|
33
|
+
totalProcessed: number;
|
|
34
|
+
currentTokenBucket: ReturnType<TokenBucketRateLimiter['getStatus']>;
|
|
35
|
+
}
|
|
36
|
+
declare class RequestQueueManager {
|
|
37
|
+
private queue;
|
|
38
|
+
private options;
|
|
39
|
+
private rateLimiter;
|
|
40
|
+
private stats;
|
|
41
|
+
private cleanupInterval;
|
|
42
|
+
private idCounter;
|
|
43
|
+
constructor(options?: Partial<QueueOptions>);
|
|
44
|
+
private generateId;
|
|
45
|
+
/**
|
|
46
|
+
* Enqueue a task for rate-limited execution.
|
|
47
|
+
* Returns a promise that resolves with the task's result
|
|
48
|
+
* once a rate-limit token is acquired and the task completes.
|
|
49
|
+
*/
|
|
50
|
+
enqueue<T>(task: () => Promise<T>, timeout?: number): Promise<T>;
|
|
51
|
+
/**
|
|
52
|
+
* Process the queue: acquire tokens and execute tasks
|
|
53
|
+
*/
|
|
54
|
+
private processQueue;
|
|
55
|
+
/**
|
|
56
|
+
* Get queue statistics
|
|
57
|
+
*/
|
|
58
|
+
getStats(): QueueStats;
|
|
59
|
+
/**
|
|
60
|
+
* Estimate wait time for a new task
|
|
61
|
+
*/
|
|
62
|
+
getEstimatedWaitTime(): number;
|
|
63
|
+
/**
|
|
64
|
+
* Check if a new task can be enqueued
|
|
65
|
+
*/
|
|
66
|
+
canEnqueue(): {
|
|
67
|
+
allowed: boolean;
|
|
68
|
+
reason?: string;
|
|
69
|
+
estimatedWait?: number;
|
|
70
|
+
};
|
|
71
|
+
/**
|
|
72
|
+
* Periodic cleanup: evict stale tasks that exceeded maxWaitTime
|
|
73
|
+
*/
|
|
74
|
+
private cleanup;
|
|
75
|
+
/**
|
|
76
|
+
* Update rate limiting config
|
|
77
|
+
*/
|
|
78
|
+
updateRateLimit(refillRate: number, capacity?: number): void;
|
|
79
|
+
/**
|
|
80
|
+
* Clear all queued tasks
|
|
81
|
+
*/
|
|
82
|
+
clear(): void;
|
|
83
|
+
/**
|
|
84
|
+
* Destroy the queue manager and release resources
|
|
85
|
+
*/
|
|
86
|
+
destroy(): void;
|
|
87
|
+
}
|
|
88
|
+
declare function getRequestQueue(): RequestQueueManager;
|
|
89
|
+
|
|
90
|
+
export { RequestQueueManager, getRequestQueue };
|
|
91
|
+
export type { QueueOptions, QueueStats };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { TokenBucketRateLimiter } from '@h1s97x/token-bucket';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* FIFO request queue manager with rate limiting
|
|
5
|
+
*
|
|
6
|
+
* Features:
|
|
7
|
+
* - FIFO order for fairness
|
|
8
|
+
* - Configurable max queue length
|
|
9
|
+
* - Rate-limited task execution via token bucket
|
|
10
|
+
* - Timeout-based task eviction
|
|
11
|
+
* - Wait time estimation
|
|
12
|
+
* - Periodic stale cleanup
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
interface QueueOptions {
|
|
16
|
+
/** Maximum queue length */
|
|
17
|
+
maxSize: number;
|
|
18
|
+
/** Max task wait time in ms */
|
|
19
|
+
maxWaitTime: number;
|
|
20
|
+
/** Token bucket capacity (burst) */
|
|
21
|
+
bucketCapacity: number;
|
|
22
|
+
/** Requests allowed per second */
|
|
23
|
+
requestsPerSecond: number;
|
|
24
|
+
}
|
|
25
|
+
interface QueueStats {
|
|
26
|
+
waiting: number;
|
|
27
|
+
processing: number;
|
|
28
|
+
completed: number;
|
|
29
|
+
failed: number;
|
|
30
|
+
timeout: number;
|
|
31
|
+
avgWaitTime: number;
|
|
32
|
+
maxQueueLength: number;
|
|
33
|
+
totalProcessed: number;
|
|
34
|
+
currentTokenBucket: ReturnType<TokenBucketRateLimiter['getStatus']>;
|
|
35
|
+
}
|
|
36
|
+
declare class RequestQueueManager {
|
|
37
|
+
private queue;
|
|
38
|
+
private options;
|
|
39
|
+
private rateLimiter;
|
|
40
|
+
private stats;
|
|
41
|
+
private cleanupInterval;
|
|
42
|
+
private idCounter;
|
|
43
|
+
constructor(options?: Partial<QueueOptions>);
|
|
44
|
+
private generateId;
|
|
45
|
+
/**
|
|
46
|
+
* Enqueue a task for rate-limited execution.
|
|
47
|
+
* Returns a promise that resolves with the task's result
|
|
48
|
+
* once a rate-limit token is acquired and the task completes.
|
|
49
|
+
*/
|
|
50
|
+
enqueue<T>(task: () => Promise<T>, timeout?: number): Promise<T>;
|
|
51
|
+
/**
|
|
52
|
+
* Process the queue: acquire tokens and execute tasks
|
|
53
|
+
*/
|
|
54
|
+
private processQueue;
|
|
55
|
+
/**
|
|
56
|
+
* Get queue statistics
|
|
57
|
+
*/
|
|
58
|
+
getStats(): QueueStats;
|
|
59
|
+
/**
|
|
60
|
+
* Estimate wait time for a new task
|
|
61
|
+
*/
|
|
62
|
+
getEstimatedWaitTime(): number;
|
|
63
|
+
/**
|
|
64
|
+
* Check if a new task can be enqueued
|
|
65
|
+
*/
|
|
66
|
+
canEnqueue(): {
|
|
67
|
+
allowed: boolean;
|
|
68
|
+
reason?: string;
|
|
69
|
+
estimatedWait?: number;
|
|
70
|
+
};
|
|
71
|
+
/**
|
|
72
|
+
* Periodic cleanup: evict stale tasks that exceeded maxWaitTime
|
|
73
|
+
*/
|
|
74
|
+
private cleanup;
|
|
75
|
+
/**
|
|
76
|
+
* Update rate limiting config
|
|
77
|
+
*/
|
|
78
|
+
updateRateLimit(refillRate: number, capacity?: number): void;
|
|
79
|
+
/**
|
|
80
|
+
* Clear all queued tasks
|
|
81
|
+
*/
|
|
82
|
+
clear(): void;
|
|
83
|
+
/**
|
|
84
|
+
* Destroy the queue manager and release resources
|
|
85
|
+
*/
|
|
86
|
+
destroy(): void;
|
|
87
|
+
}
|
|
88
|
+
declare function getRequestQueue(): RequestQueueManager;
|
|
89
|
+
|
|
90
|
+
export { RequestQueueManager, getRequestQueue };
|
|
91
|
+
export type { QueueOptions, QueueStats };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import { TokenBucketRateLimiter } from '@h1s97x/token-bucket';
|
|
2
|
+
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
5
|
+
var __publicField = (obj, key, value) => {
|
|
6
|
+
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
7
|
+
return value;
|
|
8
|
+
};
|
|
9
|
+
const DEFAULT_OPTIONS = {
|
|
10
|
+
maxSize: 100,
|
|
11
|
+
maxWaitTime: 6e4,
|
|
12
|
+
bucketCapacity: 20,
|
|
13
|
+
requestsPerSecond: 10
|
|
14
|
+
};
|
|
15
|
+
class RequestQueueManager {
|
|
16
|
+
constructor(options = {}) {
|
|
17
|
+
__publicField(this, "queue", []);
|
|
18
|
+
__publicField(this, "options");
|
|
19
|
+
__publicField(this, "rateLimiter");
|
|
20
|
+
__publicField(this, "stats");
|
|
21
|
+
__publicField(this, "cleanupInterval", null);
|
|
22
|
+
__publicField(this, "idCounter", 0);
|
|
23
|
+
this.options = { ...DEFAULT_OPTIONS, ...options };
|
|
24
|
+
this.rateLimiter = new TokenBucketRateLimiter({
|
|
25
|
+
capacity: this.options.bucketCapacity,
|
|
26
|
+
refillRate: this.options.requestsPerSecond
|
|
27
|
+
});
|
|
28
|
+
this.stats = {
|
|
29
|
+
waiting: 0,
|
|
30
|
+
processing: 0,
|
|
31
|
+
completed: 0,
|
|
32
|
+
failed: 0,
|
|
33
|
+
timeout: 0,
|
|
34
|
+
maxQueueLength: 0,
|
|
35
|
+
totalProcessed: 0
|
|
36
|
+
};
|
|
37
|
+
this.cleanupInterval = setInterval(() => {
|
|
38
|
+
this.cleanup();
|
|
39
|
+
}, 1e4);
|
|
40
|
+
}
|
|
41
|
+
generateId() {
|
|
42
|
+
return `job_${Date.now()}_${++this.idCounter}`;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Enqueue a task for rate-limited execution.
|
|
46
|
+
* Returns a promise that resolves with the task's result
|
|
47
|
+
* once a rate-limit token is acquired and the task completes.
|
|
48
|
+
*/
|
|
49
|
+
async enqueue(task, timeout) {
|
|
50
|
+
const jobId = this.generateId();
|
|
51
|
+
const waitTimeout = timeout ?? this.options.maxWaitTime;
|
|
52
|
+
if (this.queue.length >= this.options.maxSize) {
|
|
53
|
+
throw new Error(`QUEUE_FULL: Queue is full (${this.options.maxSize})`);
|
|
54
|
+
}
|
|
55
|
+
this.stats.maxQueueLength = Math.max(
|
|
56
|
+
this.stats.maxQueueLength,
|
|
57
|
+
this.queue.length + 1
|
|
58
|
+
);
|
|
59
|
+
return new Promise((resolve, reject) => {
|
|
60
|
+
const timeoutId = setTimeout(() => {
|
|
61
|
+
const index = this.queue.findIndex((j) => j.id === jobId);
|
|
62
|
+
if (index !== -1) {
|
|
63
|
+
this.queue.splice(index, 1);
|
|
64
|
+
this.stats.waiting--;
|
|
65
|
+
}
|
|
66
|
+
this.stats.timeout++;
|
|
67
|
+
reject(new Error(`TIMEOUT: Task waited too long (${waitTimeout}ms)`));
|
|
68
|
+
}, waitTimeout);
|
|
69
|
+
const job = {
|
|
70
|
+
id: jobId,
|
|
71
|
+
task,
|
|
72
|
+
resolve,
|
|
73
|
+
reject,
|
|
74
|
+
createdAt: Date.now(),
|
|
75
|
+
timeout: timeoutId,
|
|
76
|
+
status: "waiting"
|
|
77
|
+
};
|
|
78
|
+
this.queue.push(job);
|
|
79
|
+
this.stats.waiting++;
|
|
80
|
+
this.processQueue();
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Process the queue: acquire tokens and execute tasks
|
|
85
|
+
*/
|
|
86
|
+
async processQueue() {
|
|
87
|
+
while (this.queue.length > 0) {
|
|
88
|
+
if (!this.rateLimiter.tryAcquire()) {
|
|
89
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
const job = this.queue.shift();
|
|
93
|
+
if (!job)
|
|
94
|
+
break;
|
|
95
|
+
clearTimeout(job.timeout);
|
|
96
|
+
this.stats.waiting--;
|
|
97
|
+
this.stats.processing++;
|
|
98
|
+
this.stats.totalProcessed++;
|
|
99
|
+
job.status = "processing";
|
|
100
|
+
try {
|
|
101
|
+
const result = await job.task();
|
|
102
|
+
job.status = "completed";
|
|
103
|
+
this.stats.processing--;
|
|
104
|
+
this.stats.completed++;
|
|
105
|
+
job.resolve(result);
|
|
106
|
+
} catch (error) {
|
|
107
|
+
job.status = "failed";
|
|
108
|
+
this.stats.processing--;
|
|
109
|
+
this.stats.failed++;
|
|
110
|
+
job.reject(error instanceof Error ? error : new Error(String(error)));
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Get queue statistics
|
|
116
|
+
*/
|
|
117
|
+
getStats() {
|
|
118
|
+
const now = Date.now();
|
|
119
|
+
const totalWaitTime = this.queue.reduce(
|
|
120
|
+
(sum, job) => sum + (now - job.createdAt),
|
|
121
|
+
0
|
|
122
|
+
);
|
|
123
|
+
const avgWaitTime = this.queue.length > 0 ? totalWaitTime / this.queue.length : 0;
|
|
124
|
+
return {
|
|
125
|
+
...this.stats,
|
|
126
|
+
avgWaitTime,
|
|
127
|
+
currentTokenBucket: this.rateLimiter.getStatus()
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Estimate wait time for a new task
|
|
132
|
+
*/
|
|
133
|
+
getEstimatedWaitTime() {
|
|
134
|
+
if (this.queue.length === 0)
|
|
135
|
+
return 0;
|
|
136
|
+
const avgWaitPerRequest = 1e3 / this.options.requestsPerSecond;
|
|
137
|
+
return Math.ceil(this.queue.length * avgWaitPerRequest);
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Check if a new task can be enqueued
|
|
141
|
+
*/
|
|
142
|
+
canEnqueue() {
|
|
143
|
+
if (this.queue.length >= this.options.maxSize) {
|
|
144
|
+
return {
|
|
145
|
+
allowed: false,
|
|
146
|
+
reason: `Queue is full (${this.queue.length}/${this.options.maxSize})`
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
const estimatedWait = this.getEstimatedWaitTime();
|
|
150
|
+
if (estimatedWait > this.options.maxWaitTime) {
|
|
151
|
+
return {
|
|
152
|
+
allowed: false,
|
|
153
|
+
reason: `Estimated wait too long (${Math.round(estimatedWait / 1e3)}s)`,
|
|
154
|
+
estimatedWait
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
return { allowed: true, estimatedWait };
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Periodic cleanup: evict stale tasks that exceeded maxWaitTime
|
|
161
|
+
*/
|
|
162
|
+
cleanup() {
|
|
163
|
+
const now = Date.now();
|
|
164
|
+
const expired = [];
|
|
165
|
+
for (let i = this.queue.length - 1; i >= 0; i--) {
|
|
166
|
+
const job = this.queue[i];
|
|
167
|
+
if (now - job.createdAt > this.options.maxWaitTime) {
|
|
168
|
+
expired.push(job);
|
|
169
|
+
this.queue.splice(i, 1);
|
|
170
|
+
this.stats.waiting--;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
for (const job of expired) {
|
|
174
|
+
clearTimeout(job.timeout);
|
|
175
|
+
job.status = "timeout";
|
|
176
|
+
this.stats.timeout++;
|
|
177
|
+
job.reject(new Error(`CLEANUP: Task evicted after ${this.options.maxWaitTime}ms`));
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Update rate limiting config
|
|
182
|
+
*/
|
|
183
|
+
updateRateLimit(refillRate, capacity) {
|
|
184
|
+
this.options.requestsPerSecond = refillRate;
|
|
185
|
+
if (capacity !== void 0) {
|
|
186
|
+
this.options.bucketCapacity = capacity;
|
|
187
|
+
}
|
|
188
|
+
this.rateLimiter.updateConfig(refillRate, capacity);
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Clear all queued tasks
|
|
192
|
+
*/
|
|
193
|
+
clear() {
|
|
194
|
+
for (const job of this.queue) {
|
|
195
|
+
clearTimeout(job.timeout);
|
|
196
|
+
job.reject(new Error("CLEARED: Queue has been cleared"));
|
|
197
|
+
}
|
|
198
|
+
this.queue = [];
|
|
199
|
+
this.stats.waiting = 0;
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Destroy the queue manager and release resources
|
|
203
|
+
*/
|
|
204
|
+
destroy() {
|
|
205
|
+
if (this.cleanupInterval !== null) {
|
|
206
|
+
clearInterval(this.cleanupInterval);
|
|
207
|
+
this.cleanupInterval = null;
|
|
208
|
+
}
|
|
209
|
+
this.clear();
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
let queueInstance = null;
|
|
213
|
+
function getRequestQueue() {
|
|
214
|
+
if (!queueInstance) {
|
|
215
|
+
queueInstance = new RequestQueueManager();
|
|
216
|
+
}
|
|
217
|
+
return queueInstance;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export { RequestQueueManager, getRequestQueue };
|
package/package.json
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@h1s97x/request-queue",
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "FIFO request queue manager with rate limiting for Node.js and browser",
|
|
5
|
+
"author": "h1s97x",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"import": "./dist/index.mjs",
|
|
11
|
+
"require": "./dist/index.cjs",
|
|
12
|
+
"types": "./dist/index.d.ts"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"main": "./dist/index.cjs",
|
|
16
|
+
"module": "./dist/index.mjs",
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"files": [
|
|
19
|
+
"dist"
|
|
20
|
+
],
|
|
21
|
+
"sideEffects": false,
|
|
22
|
+
"dependencies": {
|
|
23
|
+
"@h1s97x/token-bucket": "0.1.1"
|
|
24
|
+
},
|
|
25
|
+
"devDependencies": {
|
|
26
|
+
"vitest": "^2.1.9"
|
|
27
|
+
},
|
|
28
|
+
"keywords": [
|
|
29
|
+
"request-queue",
|
|
30
|
+
"rate-limiter",
|
|
31
|
+
"fifo",
|
|
32
|
+
"throttle",
|
|
33
|
+
"typescript"
|
|
34
|
+
],
|
|
35
|
+
"repository": {
|
|
36
|
+
"type": "git",
|
|
37
|
+
"url": "git+https://github.com/h1s97x/toolkit.git",
|
|
38
|
+
"directory": "packages/request-queue"
|
|
39
|
+
},
|
|
40
|
+
"bugs": {
|
|
41
|
+
"url": "https://github.com/h1s97x/toolkit/issues"
|
|
42
|
+
},
|
|
43
|
+
"homepage": "https://github.com/h1s97x/toolkit/tree/main/packages/request-queue",
|
|
44
|
+
"scripts": {
|
|
45
|
+
"build": "unbuild",
|
|
46
|
+
"dev": "unbuild --stub",
|
|
47
|
+
"test": "vitest run",
|
|
48
|
+
"test:watch": "vitest"
|
|
49
|
+
}
|
|
50
|
+
}
|