-
Notifications
You must be signed in to change notification settings - Fork 324
/
Copy pathrate_limiter.js
51 lines (37 loc) · 1.19 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
'use strict'
const limiter = require('limiter')
class RateLimiter {
constructor (rateLimit) {
this._rateLimit = parseInt(rateLimit)
this._limiter = new limiter.RateLimiter(this._rateLimit, 'second')
this._tokensRequested = 0
this._prevWindowRate = null
}
isAllowed () {
const curIntervalStart = this._limiter.curIntervalStart
const allowed = this._isAllowed()
if (curIntervalStart !== this._limiter.curIntervalStart) {
this._prevWindowRate = this._currentWindowRate()
this._tokensRequested = 0
}
this._tokensRequested++
return allowed
}
effectiveRate () {
const currentWindowRate = this._currentWindowRate()
if (this._prevWindowRate === null) return currentWindowRate
return (currentWindowRate + this._prevWindowRate) / 2
}
_isAllowed () {
if (this._rateLimit < 0) return true
if (this._rateLimit === 0) return false
return this._limiter.tryRemoveTokens(1)
}
_currentWindowRate () {
if (this._rateLimit < 0) return 1
if (this._rateLimit === 0) return 0
if (this._tokensRequested === 0) return 1
return this._limiter.tokensThisInterval / this._tokensRequested
}
}
module.exports = RateLimiter