/
BotRateLimiter.java
370 lines (338 loc) · 13 KB
/
BotRateLimiter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
/*
* Copyright 2015-2017 Austin Keener & Michael Ritter & Florian Spieß
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.dv8tion.jda.core.requests.ratelimit;
import com.mashape.unirest.http.Headers;
import com.mashape.unirest.http.HttpResponse;
import net.dv8tion.jda.core.entities.impl.JDAImpl;
import net.dv8tion.jda.core.events.ExceptionEvent;
import net.dv8tion.jda.core.requests.RateLimiter;
import net.dv8tion.jda.core.requests.Request;
import net.dv8tion.jda.core.requests.Requester;
import net.dv8tion.jda.core.requests.Route.CompiledRoute;
import net.dv8tion.jda.core.requests.Route.RateLimit;
import net.dv8tion.jda.core.utils.SimpleLog;
import org.json.JSONObject;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Iterator;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
public class BotRateLimiter extends RateLimiter
{
volatile Long timeOffset = null;
volatile AtomicLong globalCooldown = new AtomicLong(Long.MIN_VALUE);
public BotRateLimiter(Requester requester, int poolSize)
{
super(requester, poolSize);
}
@Override
public Long getRateLimit(CompiledRoute route)
{
Bucket bucket = getBucket(route);
synchronized (bucket)
{
return bucket.getRateLimit();
}
}
@Override
protected void queueRequest(Request request)
{
if (isShutdown)
throw new RejectedExecutionException("Cannot queue a request after shutdown");
Bucket bucket = getBucket(request.getRoute());
synchronized (bucket)
{
bucket.addToQueue(request);
}
}
@Override
protected Long handleResponse(CompiledRoute route, HttpResponse<String> response)
{
Bucket bucket = getBucket(route);
synchronized (bucket)
{
Headers headers = response.getHeaders();
int code = response.getStatus();
if (timeOffset == null)
setTimeOffset(headers);
if (code == 429)
{
String global = headers.getFirst("X-RateLimit-Global");
String retry = headers.getFirst("Retry-After");
if (retry == null || retry.isEmpty())
{
JSONObject limitObj = new JSONObject(response.getBody());
retry = limitObj.get("retry_after").toString();
}
long retryAfter = Long.parseLong(retry);
if (!Boolean.parseBoolean(global)) //Not global ratelimit
{
updateBucket(bucket, headers);
}
else
{
//If it is global, lock down the threads.
globalCooldown.set(getNow() + retryAfter);
}
return retryAfter;
}
else
{
updateBucket(bucket, headers);
return null;
}
}
}
private Bucket getBucket(CompiledRoute route)
{
String rateLimitRoute = route.getRatelimitRoute();
Bucket bucket = (Bucket) buckets.get(rateLimitRoute);
if (bucket == null)
{
synchronized (buckets)
{
bucket = (Bucket) buckets.get(rateLimitRoute);
if (bucket == null)
{
bucket = new Bucket(rateLimitRoute, route.getBaseRoute().getRatelimit());
buckets.put(rateLimitRoute, bucket);
}
}
}
return bucket;
}
public long getNow()
{
return System.currentTimeMillis() + getTimeOffset();
}
public long getTimeOffset()
{
return timeOffset == null ? 0 : timeOffset;
}
private void setTimeOffset(Headers headers)
{
//Store as soon as possible to get the most accurate time difference;
long time = System.currentTimeMillis();
if (timeOffset == null)
{
//Get the date header provided by Discord.
//Format: "date" : "Fri, 16 Sep 2016 05:49:36 GMT"
String date = headers.getFirst("Date");
if (date != null)
{
OffsetDateTime tDate = OffsetDateTime.parse(date, DateTimeFormatter.RFC_1123_DATE_TIME);
long lDate = tDate.toInstant().toEpochMilli(); //We want to work in milliseconds, not seconds
timeOffset = lDate - time; //Get offset in milliseconds.
}
}
}
private void updateBucket(Bucket bucket, Headers headers)
{
try
{
if (bucket.hasRatelimit()) // Check if there's a hardcoded rate limit
{
bucket.resetTime = getNow() + bucket.getRatelimit().getResetTime();
//routeUsageLimit provided by the ratelimit object already in the bucket.
}
else
{
bucket.resetTime = Long.parseLong(headers.getFirst("X-RateLimit-Reset")) * 1000; //Seconds to milliseconds
bucket.routeUsageLimit = Integer.parseInt(headers.getFirst("X-RateLimit-Limit"));
}
//Currently, we check the remaining amount even for hardcoded ratelimits just to further respect Discord
// however, if there should ever be a case where Discord informs that the remaining is less than what
// it actually is and we add a custom ratelimit to handle that, we will need to instead move this to the
// above else statement and add a bucket.routeUsageRemaining-- decrement to the above if body.
//An example of this statement needing to be moved would be if the custom ratelimit reset time interval is
// equal to or greater than 1000ms, and the remaining count provided by discord is less than the ACTUAL
// amount that their systems allow in such a way that isn't a bug.
//The custom ratelimit system is primarily for ratelimits that can't be properly represented by Discord's
// header system due to their headers only supporting accuracy to the second. The custom ratelimit system
// allows for hardcoded ratelimits that allow accuracy to the millisecond which is important for some
// ratelimits like Reactions which is 1/0.25s, but discord reports the ratelimit as 1/1s with headers.
bucket.routeUsageRemaining = Integer.parseInt(headers.getFirst("X-RateLimit-Remaining"));
}
catch (NumberFormatException ex)
{
if (!bucket.getRoute().equals("gateway")
&& !bucket.getRoute().equals("users/@me")
&& Requester.LOG.getEffectiveLevel().getPriority() <= SimpleLog.Level.DEBUG.getPriority())
{
Requester.LOG.debug("Encountered issue with headers when updating a bucket"
+ "\nRoute: " + bucket.getRoute()
+ "\nHeaders: " + headers);
}
}
}
private class Bucket implements IBucket, Runnable
{
final String route;
final RateLimit rateLimit;
volatile long resetTime = 0;
volatile int routeUsageRemaining = 1; //These are default values to only allow 1 request until we have properly
volatile int routeUsageLimit = 1; // ratelimit information.
volatile ConcurrentLinkedQueue<Request> requests = new ConcurrentLinkedQueue<>();
public Bucket(String route, RateLimit rateLimit)
{
this.route = route;
this.rateLimit = rateLimit;
if (rateLimit != null)
{
this.routeUsageRemaining = rateLimit.getUsageLimit();
this.routeUsageLimit = rateLimit.getUsageLimit();
}
}
void addToQueue(Request request)
{
requests.add(request);
submitForProcessing();
}
void submitForProcessing()
{
synchronized (submittedBuckets)
{
if (!submittedBuckets.contains(this))
{
Long delay = getRateLimit();
if (delay == null)
delay = 0L;
pool.schedule(this, delay, TimeUnit.MILLISECONDS);
submittedBuckets.add(this);
}
}
}
Long getRateLimit()
{
long gCooldown = globalCooldown.get();
if (gCooldown != Long.MIN_VALUE) //Are we on global cooldown?
{
long now = getNow();
if (now > gCooldown) //Verify that we should still be on cooldown.
{
globalCooldown.set(Long.MIN_VALUE); //If we are done cooling down, reset the globalCooldown and continue.
}
else
{
return gCooldown - now; //If we should still be on cooldown, return when we can go again.
}
}
if (this.routeUsageRemaining <= 0)
{
if (getNow() > this.resetTime)
{
this.routeUsageRemaining = this.routeUsageLimit;
this.resetTime = 0;
}
}
if (this.routeUsageRemaining > 0)
return null;
else
return this.resetTime - getNow();
}
@Override
public boolean equals(Object o)
{
if (!(o instanceof Bucket))
return false;
Bucket oBucket = (Bucket) o;
return route.equals(oBucket.route);
}
@Override
public int hashCode()
{
return route.hashCode();
}
@Override
public void run()
{
try
{
synchronized (requests)
{
for (Iterator<Request> it = requests.iterator(); it.hasNext(); )
{
Request request = null;
try
{
request = it.next();
Long retryAfter = requester.execute(request);
if (retryAfter != null)
{
break;
}
else
{
it.remove();
}
}
catch (Throwable t)
{
Requester.LOG.fatal("Requester system encountered an internal error");
Requester.LOG.log(t);
it.remove();
if (request != null)
request.onFailure(t);
}
}
synchronized (submittedBuckets)
{
submittedBuckets.remove(this);
if (!requests.isEmpty())
{
try
{
this.submitForProcessing();
}
catch (RejectedExecutionException e)
{
Requester.LOG.debug("Caught RejectedExecutionException when re-queuing a ratelimited request. The requester is probably shutdown, thus, this can be ignored.");
}
}
}
}
}
catch (Throwable err)
{
Requester.LOG.fatal("Requester system encountered an internal error from beyond the synchronized execution blocks. NOT GOOD!");
Requester.LOG.log(err);
if (err instanceof Error)
{
JDAImpl api = requester.getJDA();
api.getEventManager().handle(new ExceptionEvent(api, err, true));
}
}
}
@Override
public RateLimit getRatelimit()
{
return rateLimit;
}
@Override
public String getRoute()
{
return route;
}
@Override
public Queue<Request> getRequests()
{
return requests;
}
}
}