diff --git a/src/rest/RESTManager.js b/src/rest/RESTManager.js index 4b725f4d2..3d42b0b0e 100644 --- a/src/rest/RESTManager.js +++ b/src/rest/RESTManager.js @@ -9,7 +9,6 @@ class RESTManager { constructor(client, tokenPrefix = 'Bot') { this.client = client; this.handlers = new Collection(); - this.globallyRateLimited = false; this.tokenPrefix = tokenPrefix; this.versioned = true; this.globalTimeout = null; diff --git a/src/rest/RequestHandler.js b/src/rest/RequestHandler.js index 7275da57a..67d645038 100644 --- a/src/rest/RequestHandler.js +++ b/src/rest/RequestHandler.js @@ -43,7 +43,7 @@ class RequestHandler { } get limited() { - return (this.manager.globallyRateLimited || this.remaining <= 0) && Date.now() < this.reset; + return (this.manager.globalTimeout || this.remaining <= 0) && Date.now() < this.reset; } get _inactive() { @@ -85,18 +85,8 @@ class RequestHandler { }); } - if (this.manager.globallyRateLimited && !this.manager.globalTimeout) { - // Set a global rate limit for all of the handlers instead of each one individually - this.manager.globalTimeout = this.manager.client.setTimeout(() => { - this.manager.globalTimeout = null; - this.manager.globallyRateLimited = false; - this.busy = false; - this.run(); - }, timeout); - } else if (this.manager.globalTimeout) { - // Already waiting for a global rate limit to clear - this.queue.unshift(item); - return null; + if (this.manager.globalTimeout) { + await this.manager.globalTimeout; } else { // Wait for the timeout to expire in order to avoid an actual 429 await Util.delayFor(timeout); @@ -116,8 +106,6 @@ class RequestHandler { } if (res && res.headers) { - if (res.headers.get('x-ratelimit-global')) this.manager.globallyRateLimited = true; - const serverDate = res.headers.get('date'); const limit = res.headers.get('x-ratelimit-limit'); const remaining = res.headers.get('x-ratelimit-remaining'); @@ -133,6 +121,18 @@ class RequestHandler { if (item.request.route.includes('reactions')) { this.reset = new Date(serverDate).getTime() - getAPIOffset(serverDate) + 250; } + + // Handle global ratelimit + if (res.headers.get('x-ratelimit-global')) { + // Set the manager's global timeout as the promise for other requests to "wait" + this.manager.globalTimeout = Util.delayFor(this.retryAfter); + + // Wait for the global timeout to resolve before continue + await this.manager.globalTimeout; + + // Clean up global timeout + this.manager.globalTimeout = null; + } } // Finished handling headers, safe to unlock manager