Experimental active ratelimits (adapted from Eris)

This commit is contained in:
abalabahaha
2016-07-29 05:37:43 +09:00
parent dc939c48ee
commit 952cfc0456
7 changed files with 511 additions and 328 deletions

55
lib/Util/Bucket.js Normal file
View File

@@ -0,0 +1,55 @@
"use strict";
exports.__esModule = true;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Bucket = (function () {
// Adapted from Eris
function Bucket(tokenLimit, interval) {
_classCallCheck(this, Bucket);
this.tokenLimit = tokenLimit;
this.interval = interval;
this.extraTime = 500;
this.lastReset = this.tokens = this.lastSend = 0;
this._queue = [];
}
Bucket.prototype.queue = function queue(func) {
this._queue.push(func);
this.check();
};
Bucket.prototype.check = function check() {
var _this = this;
if (this.timeout || this._queue.length === 0) {
return;
}
if (this.lastReset + this.interval + this.extraTime < Date.now()) {
this.lastReset = Date.now();
this.tokens = Math.max(0, this.tokens - this.tokenLimit);
}
var val;
while (this._queue.length > 0 && this.tokens < this.tokenLimit) {
this.tokens++;
this._queue.shift()();
this.lastSend = Date.now();
}
if (this._queue.length > 0 && !this.timeout) {
this.timeout = setTimeout(function () {
_this.timeout = null;
_this.check();
}, this.tokens < this.tokenLimit ? 1 : Math.max(0, this.lastReset + this.interval + this.extraTime - Date.now()));
}
};
return Bucket;
})();
exports["default"] = Bucket;
module.exports = exports["default"];