Add io.throttle-in-rate-limit for socket event rate
This commit is contained in:
parent
db2361aee9
commit
67b1c97d89
4 changed files with 44 additions and 4 deletions
|
|
@ -1,16 +1,27 @@
|
|||
class TokenBucket {
|
||||
constructor(capacity, refillRate) {
|
||||
if (typeof refillRate !== 'function') {
|
||||
const _refillRate = refillRate;
|
||||
refillRate = () => _refillRate;
|
||||
}
|
||||
if (typeof capacity !== 'function') {
|
||||
const _capacity = capacity;
|
||||
capacity = () => _capacity;
|
||||
}
|
||||
|
||||
this.capacity = capacity;
|
||||
this.refillRate = refillRate;
|
||||
this.count = capacity;
|
||||
this.count = capacity();
|
||||
this.lastRefill = Date.now();
|
||||
}
|
||||
|
||||
throttle() {
|
||||
const now = Date.now();
|
||||
const delta = Math.floor((now - this.lastRefill) / 1000 * this.refillRate);
|
||||
const delta = Math.floor(
|
||||
(now - this.lastRefill) / 1000 * this.refillRate()
|
||||
);
|
||||
if (delta > 0) {
|
||||
this.count = Math.min(this.capacity, this.count + delta);
|
||||
this.count = Math.min(this.capacity(), this.count + delta);
|
||||
this.lastRefill = now;
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue