Skip to content

Commit 32fe72f

Browse files
kyranetNotSugden
andauthored
feat(Rest): switch queue to AsyncQueue (#4835)
Co-authored-by: Sugden <28943913+NotSugden@users.noreply.github.com>
1 parent 1e63f37 commit 32fe72f

File tree

4 files changed

+135
-70
lines changed

4 files changed

+135
-70
lines changed

src/rest/APIRequest.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ class APIRequest {
1515
this.method = method;
1616
this.route = options.route;
1717
this.options = options;
18+
this.retries = 0;
1819

1920
let queryString = '';
2021
if (options.query) {

src/rest/AsyncQueue.js

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
/**
2+
* MIT License
3+
*
4+
* Copyright (c) 2020 kyranet, discord.js
5+
*
6+
* Permission is hereby granted, free of charge, to any person obtaining a copy
7+
* of this software and associated documentation files (the "Software"), to deal
8+
* in the Software without restriction, including without limitation the rights
9+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10+
* copies of the Software, and to permit persons to whom the Software is
11+
* furnished to do so, subject to the following conditions:
12+
*
13+
* The above copyright notice and this permission notice shall be included in all
14+
* copies or substantial portions of the Software.
15+
*
16+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22+
* SOFTWARE.
23+
*/
24+
25+
'use strict';
26+
27+
// TODO(kyranet, vladfrangu): replace this with discord.js v13's core AsyncQueue.
28+
29+
/**
30+
* An async queue that preserves the stack and prevents lock-ups.
31+
* @private
32+
*/
33+
class AsyncQueue {
34+
constructor() {
35+
/**
36+
* The promises array.
37+
* @type {Array<{promise: Promise<void>, resolve: Function}>}
38+
* @private
39+
*/
40+
this.promises = [];
41+
}
42+
43+
/**
44+
* The remaining amount of queued promises
45+
* @type {number}
46+
*/
47+
get remaining() {
48+
return this.promises.length;
49+
}
50+
51+
/**
52+
* Waits for last promise and queues a new one.
53+
* @returns {Promise<void>}
54+
* @example
55+
* const queue = new AsyncQueue();
56+
* async function request(url, options) {
57+
* await queue.wait();
58+
* try {
59+
* const result = await fetch(url, options);
60+
* // Do some operations with 'result'
61+
* } finally {
62+
* // Remove first entry from the queue and resolve for the next entry
63+
* queue.shift();
64+
* }
65+
* }
66+
*
67+
* request(someUrl1, someOptions1); // Will call fetch() immediately
68+
* request(someUrl2, someOptions2); // Will call fetch() after the first finished
69+
* request(someUrl3, someOptions3); // Will call fetch() after the second finished
70+
*/
71+
wait() {
72+
const next = this.promises.length ? this.promises[this.promises.length - 1].promise : Promise.resolve();
73+
let resolve;
74+
const promise = new Promise(res => {
75+
resolve = res;
76+
});
77+
78+
this.promises.push({
79+
resolve,
80+
promise,
81+
});
82+
83+
return next;
84+
}
85+
86+
/**
87+
* Frees the queue's lock for the next item to process.
88+
*/
89+
shift() {
90+
const deferred = this.promises.shift();
91+
if (typeof deferred !== 'undefined') deferred.resolve();
92+
}
93+
}
94+
95+
module.exports = AsyncQueue;

src/rest/RESTManager.js

Lines changed: 1 addition & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -35,19 +35,6 @@ class RESTManager {
3535
return Endpoints.CDN(this.client.options.http.cdn);
3636
}
3737

38-
push(handler, apiRequest) {
39-
return new Promise((resolve, reject) => {
40-
handler
41-
.push({
42-
request: apiRequest,
43-
resolve,
44-
reject,
45-
retries: 0,
46-
})
47-
.catch(reject);
48-
});
49-
}
50-
5138
request(method, url, options = {}) {
5239
const apiRequest = new APIRequest(this, method, url, options);
5340
let handler = this.handlers.get(apiRequest.route);
@@ -57,7 +44,7 @@ class RESTManager {
5744
this.handlers.set(apiRequest.route, handler);
5845
}
5946

60-
return this.push(handler, apiRequest);
47+
return handler.push(apiRequest);
6148
}
6249

6350
get endpoint() {

src/rest/RequestHandler.js

Lines changed: 38 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
'use strict';
22

3+
const AsyncQueue = require('./AsyncQueue');
34
const DiscordAPIError = require('./DiscordAPIError');
45
const HTTPError = require('./HTTPError');
56
const {
@@ -25,46 +26,31 @@ function calculateReset(reset, serverDate) {
2526
class RequestHandler {
2627
constructor(manager) {
2728
this.manager = manager;
28-
this.busy = false;
29-
this.queue = [];
29+
this.queue = new AsyncQueue();
3030
this.reset = -1;
3131
this.remaining = -1;
3232
this.limit = -1;
3333
this.retryAfter = -1;
3434
}
3535

36-
push(request) {
37-
if (this.busy) {
38-
this.queue.push(request);
39-
return this.run();
40-
} else {
41-
return this.execute(request);
36+
async push(request) {
37+
await this.queue.wait();
38+
try {
39+
return await this.execute(request);
40+
} finally {
41+
this.queue.shift();
4242
}
4343
}
4444

45-
run() {
46-
if (this.queue.length === 0) return Promise.resolve();
47-
return this.execute(this.queue.shift());
48-
}
49-
5045
get limited() {
5146
return Boolean(this.manager.globalTimeout) || (this.remaining <= 0 && Date.now() < this.reset);
5247
}
5348

5449
get _inactive() {
55-
return this.queue.length === 0 && !this.limited && this.busy !== true;
50+
return this.queue.remaining === 0 && !this.limited;
5651
}
5752

58-
async execute(item) {
59-
// Insert item back to the beginning if currently busy
60-
if (this.busy) {
61-
this.queue.unshift(item);
62-
return null;
63-
}
64-
65-
this.busy = true;
66-
const { reject, request, resolve } = item;
67-
53+
async execute(request) {
6854
// After calculations and requests have been done, pre-emptively stop further requests
6955
if (this.limited) {
7056
const timeout = this.reset + this.manager.client.options.restTimeOffset - Date.now();
@@ -103,8 +89,7 @@ class RequestHandler {
10389
res = await request.make();
10490
} catch (error) {
10591
// NodeFetch error expected for all "operational" errors, such as 500 status code
106-
this.busy = false;
107-
return reject(new HTTPError(error.message, error.constructor.name, error.status, request.method, request.path));
92+
throw new HTTPError(error.message, error.constructor.name, error.status, request.method, request.path);
10893
}
10994

11095
if (res && res.headers) {
@@ -120,7 +105,7 @@ class RequestHandler {
120105
this.retryAfter = retryAfter ? Number(retryAfter) : -1;
121106

122107
// https://github.com/discordapp/discord-api-docs/issues/182
123-
if (item.request.route.includes('reactions')) {
108+
if (request.route.includes('reactions')) {
124109
this.reset = new Date(serverDate).getTime() - getAPIOffset(serverDate) + 250;
125110
}
126111

@@ -137,42 +122,39 @@ class RequestHandler {
137122
}
138123
}
139124

140-
// Finished handling headers, safe to unlock manager
141-
this.busy = false;
142-
143125
if (res.ok) {
144-
const success = await parseResponse(res);
145126
// Nothing wrong with the request, proceed with the next one
146-
resolve(success);
147-
return this.run();
148-
} else if (res.status === 429) {
127+
return parseResponse(res);
128+
}
129+
130+
// Handle ratelimited requests
131+
if (res.status === 429) {
149132
// A ratelimit was hit - this should never happen
150-
this.queue.unshift(item);
151-
this.manager.client.emit('debug', `429 hit on route ${item.request.route}`);
133+
this.manager.client.emit('debug', `429 hit on route ${request.route}`);
152134
await Util.delayFor(this.retryAfter);
153-
return this.run();
154-
} else if (res.status >= 500 && res.status < 600) {
135+
return this.execute(request);
136+
}
137+
138+
// Handle server errors
139+
if (res.status >= 500 && res.status < 600) {
155140
// Retry the specified number of times for possible serverside issues
156-
if (item.retries === this.manager.client.options.retryLimit) {
157-
return reject(
158-
new HTTPError(res.statusText, res.constructor.name, res.status, item.request.method, request.path),
159-
);
160-
} else {
161-
item.retries++;
162-
this.queue.unshift(item);
163-
return this.run();
141+
if (request.retries === this.manager.client.options.retryLimit) {
142+
throw new HTTPError(res.statusText, res.constructor.name, res.status, request.method, request.path);
164143
}
165-
} else {
166-
// Handle possible malformed requests
167-
try {
168-
const data = await parseResponse(res);
169-
if (res.status >= 400 && res.status < 500) {
170-
return reject(new DiscordAPIError(request.path, data, request.method, res.status));
171-
}
172-
return null;
173-
} catch (err) {
174-
return reject(new HTTPError(err.message, err.constructor.name, err.status, request.method, request.path));
144+
145+
request.retries++;
146+
return this.execute(request);
147+
}
148+
149+
// Handle possible malformed requests
150+
try {
151+
const data = await parseResponse(res);
152+
if (res.status >= 400 && res.status < 500) {
153+
throw new DiscordAPIError(request.path, data, request.method, res.status);
175154
}
155+
return null;
156+
} catch (err) {
157+
throw new HTTPError(err.message, err.constructor.name, err.status, request.method, request.path);
176158
}
177159
}
178160
}

0 commit comments

Comments
 (0)