mirror of
https://github.com/discordjs/discord.js.git
synced 2026-03-09 16:13:31 +01:00
Experimental active ratelimits (adapted from Eris)
This commit is contained in:
55
lib/Util/Bucket.js
Normal file
55
lib/Util/Bucket.js
Normal 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"];
|
||||
Reference in New Issue
Block a user