-
Notifications
You must be signed in to change notification settings - Fork 3
/
rate-limited-queue.js
78 lines (63 loc) · 1.76 KB
/
rate-limited-queue.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
const SlidingWindowTimestams = require('./sliding-window-timestamps')
class RateLimitedQueue {
constructor(limitCount, limitInterval, nowFn = Date.now) {
this.limitCount = limitCount
this.limitInterval = limitInterval
this.nowFn = nowFn
this.queue = []
this.nextCallScheduled = false
this.timestamps = new SlidingWindowTimestams(limitInterval, nowFn)
this._performExecution = this._performExecution.bind(this)
}
enqueue(fn, ctx, args) {
return new Promise((resolve, reject) => {
this.queue.push({
fn,
ctx,
args,
resolve,
reject,
})
this._scheduleNextExecutionIfNeeded()
})
}
_remainingExecutions() {
return this.limitCount - this.timestamps.count()
}
_scheduleNextExecutionIfNeeded() {
if (this._remainingExecutions() > 0) {
this._performExecution()
}
const needsToSchedule = this.queue.length > 0 && !this.nextCallScheduled
if (needsToSchedule) {
const waitUntilNextExecution
= this.limitInterval - (this.nowFn() - this.timestamps.oldestInWindow())
this.timeoutId = setTimeout(
this._performExecution,
waitUntilNextExecution
)
this.nextCallScheduled = true
}
}
_performExecution() {
this.nextCallScheduled = false
const task = this.queue.shift()
if (task) {
this.timestamps.push(this.nowFn())
const { fn, ctx, args, resolve, reject, } = task
try {
resolve(fn.apply(ctx, args))
} catch (err) {
reject(err)
}
this._scheduleNextExecutionIfNeeded()
}
}
clearQueue() {
this.queue = []
this.timestamps.clear()
this.nextCallScheduled = false
clearTimeout(this.timeoutId)
}
}
module.exports = RateLimitedQueue