-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlimiter.ts
182 lines (166 loc) · 4.29 KB
/
limiter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
type AsyncCallback = () => any | Promise<any>;
export interface ILimiter {
process: (...cb: AsyncCallback[]) => Promise<void>;
done: () => Promise<void>;
length: number;
isProcessing: boolean;
}
export interface ILimiterOptions {
limit?: number;
maxRetry?: number;
rps?: number;
onError?: (error: Error) => Promise<void> | void;
}
interface ILimiterRetryItem {
callback: AsyncCallback;
retries: number;
error?: Error;
}
export class LimiterRetryError extends Error {
constructor(message: string, error?: Error) {
super(message);
this.name = "RetryError";
if (error) {
this.stack = error.stack;
this.cause = error;
}
}
}
export class Limiter implements ILimiter {
#limit = 10;
#processing: boolean = false;
#promisesCount = 0;
#promises: Promise<any>[] = [];
#retryQueue: Array<ILimiterRetryItem> = [];
#maxRetry = 0;
#rps: number | undefined;
#onError?: (error: Error) => void | Promise<void>;
constructor({
limit = 10,
rps,
maxRetry = 0,
onError = undefined,
}: ILimiterOptions) {
this.#limit = limit;
this.#rps = rps;
this.#maxRetry = maxRetry;
this.#onError = onError?.bind(this);
}
#tick = Date.now();
async #limitRps(callback: AsyncCallback, delay = 0): Promise<any> {
if (!this.#rps) {
return await callback();
}
if (delay > 0) {
await new Promise((resolve) => setTimeout(resolve, delay));
}
const diff = Date.now() - this.#tick;
if (diff < 1000 / this.#rps!) {
return await this.#limitRps(callback, 1000 / this.#rps! - diff);
}
this.#tick = Date.now();
return await callback();
}
async #execute() {
try {
await Promise.all(this.#promises);
this.#promises = [];
} catch (error) {
if (!this.#onError) {
this.#promises = [];
this.#processing = false;
throw error;
}
for (;;) {
const promise = this.#promises.pop();
if (!promise) break;
promise.catch(this.#onError);
}
}
}
/**
* Process the callbacks.
* A callback must be a function that returns a promise.
* @param callbacks
*/
async process(...callbacks: AsyncCallback[] | ILimiterRetryItem[]) {
this.#processing = true;
for (;;) {
const item = callbacks.pop();
if (!item) break;
if (this.#promisesCount >= this.#limit) {
await this.#execute();
}
this.#promisesCount++;
const promise = (async (item) => {
const callback =
(item as ILimiterRetryItem).callback || (item as AsyncCallback);
try {
const res = await this.#limitRps(callback);
this.#promisesCount--;
return res;
} catch (error) {
this.#promisesCount--;
if (this.#maxRetry > 0) {
this.#retryQueue.push({
callback,
retries: (item as ILimiterRetryItem).retries ?? this.#maxRetry,
error: error as Error,
});
} else {
throw error;
}
}
})(item);
this.#promises.push(promise);
}
if (this.#promises.length > 0) {
await this.#execute();
}
if (this.#retryQueue.length > 0) {
const retryItems: ILimiterRetryItem[] = [];
for (;;) {
const item = this.#retryQueue.pop();
if (!item) break;
if (item.retries > 0) {
item.retries--;
retryItems.push(item);
} else if (this.#onError) {
this.#onError(
new LimiterRetryError("Retry limit exceeded", item.error),
);
} else {
this.#promises = [];
this.#retryQueue = [];
this.#processing = false;
throw new LimiterRetryError("Retry limit exceeded", item.error);
}
}
if (retryItems.length) {
await this.process(...retryItems);
}
}
this.#processing = false;
}
/**
* Wait until all the promises are resolved.
**/
async done() {
if (this.isProcessing) {
await new Promise((resolve) => setTimeout(resolve, 10));
await this.done();
}
}
/**
* Get the number of promises in the queue.
*/
get length(): number {
return this.#promisesCount;
}
/**
* Get the processing status.
*/
get isProcessing(): boolean {
return this.#processing;
}
}