Refactor socket.io controller
This commit is contained in:
parent
107155a661
commit
0118a6fb15
10 changed files with 480 additions and 253 deletions
26
src/util/token-bucket.js
Normal file
26
src/util/token-bucket.js
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
class TokenBucket {
|
||||
constructor(capacity, refillRate) {
|
||||
this.capacity = capacity;
|
||||
this.refillRate = refillRate;
|
||||
this.count = capacity;
|
||||
this.lastRefill = Date.now();
|
||||
}
|
||||
|
||||
throttle() {
|
||||
const now = Date.now();
|
||||
const delta = Math.floor((now - this.lastRefill) / 1000 * this.refillRate);
|
||||
if (delta > 0) {
|
||||
this.count = Math.min(this.capacity, this.count + delta);
|
||||
this.lastRefill = now;
|
||||
}
|
||||
|
||||
if (this.count === 0) {
|
||||
return true;
|
||||
} else {
|
||||
this.count--;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export { TokenBucket };
|
||||
Loading…
Add table
Add a link
Reference in a new issue