-
Notifications
You must be signed in to change notification settings - Fork 21
/
rate-limiter.js
90 lines (71 loc) · 1.93 KB
/
rate-limiter.js
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
import util from 'util';
const debuglog = util.debuglog('ib-tws-api');
export default class RateLimiter {
constructor(workload, callsPerSlot, slotIntervalMs, timeoutMs) {
this._slotIntervalMs = slotIntervalMs;
this._callsPerSlot = callsPerSlot;
this._timeoutMs = timeoutMs;
this._queue = [];
this._workload = workload;
}
run(item) {
return new Promise((resolve, reject) => {
this._queue.push({
item,
resolve,
reject
});
if (this._queue.length == 1) {
process.nextTick(() => {
this._processQueue();
});
}
});
}
runExpirable(item) {
return new Promise((resolve, reject) => {
this._queue.push({
item,
resolve,
reject,
expireDate: Date.now() + this._timeoutMs
});
if (this._queue.length == 1) {
process.nextTick(() => {
this._processQueue();
});
}
});
}
cancel() {
this._queue = [];
}
_processQueue() {
while (this._queue.length > 0) {
if (this._slot_end == null || Date.now() >= this._slot_end) {
this._slot_end = Date.now() + this._slotIntervalMs;
this._slot_remaining = this._callsPerSlot;
}
if (this._slot_remaining > 0) {
const i = this._queue.shift();
if (i.expireDate && i.expireDate < Date.now()) {
// expired requests just ignored since timeout handled by
// IncomeFieldsetHandler.awaitRequestId
debuglog('RateLimiter: expired item ignored ' + i.item);
} else {
this._slot_remaining--;
Promise.resolve(this._workload(i.item)).then(i.resolve, i.reject);
}
} else {
if (this._timer) {
clearTimeout(this._timer);
}
this._timer = setTimeout(() => {
this.timer = null;
this._processQueue();
}, this._slot_end - Date.now());
return;
}
}
}
}