use of org.javacord.core.util.rest.RestRequestResponseInformationImpl in project Javacord by BtoBastian.
the class RatelimitManager method queueRequest.
/**
* Queues the given request.
* This method is automatically called when using {@link RestRequest#execute(Function)}!
*
* @param request The request to queue.
*/
public void queueRequest(RestRequest<?> request) {
final RatelimitBucket bucket;
final boolean alreadyInQueue;
synchronized (buckets) {
// Search for a bucket that fits to this request
bucket = buckets.stream().filter(b -> b.equals(request.getEndpoint(), request.getMajorUrlParameter().orElse(null))).findAny().orElseGet(() -> new RatelimitBucket(api, request.getEndpoint(), request.getMajorUrlParameter().orElse(null)));
// Must be executed BEFORE adding the request to the queue
alreadyInQueue = bucket.peekRequestFromQueue() != null;
// Add the bucket to the set of buckets (does nothing if it's already in the set)
buckets.add(bucket);
// Add the request to the bucket's queue
bucket.addRequestToQueue(request);
}
// If the bucket is already in the queue, there's nothing more to do
if (alreadyInQueue) {
return;
}
// Start working of the queue
api.getThreadPool().getExecutorService().submit(() -> {
RestRequest<?> currentRequest = bucket.peekRequestFromQueue();
RestRequestResult result = null;
long responseTimestamp = System.currentTimeMillis();
while (currentRequest != null) {
try {
int sleepTime = bucket.getTimeTillSpaceGetsAvailable();
if (sleepTime > 0) {
logger.debug("Delaying requests to {} for {}ms to prevent hitting ratelimits", bucket, sleepTime);
}
// Sleep until space is available
while (sleepTime > 0) {
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
logger.warn("We got interrupted while waiting for a rate limit!", e);
}
// Update in case something changed (e.g. because we hit a global ratelimit)
sleepTime = bucket.getTimeTillSpaceGetsAvailable();
}
// Execute the request
result = currentRequest.executeBlocking();
// Calculate the time offset, if it wasn't done before
responseTimestamp = System.currentTimeMillis();
} catch (Throwable t) {
responseTimestamp = System.currentTimeMillis();
if (currentRequest.getResult().isDone()) {
logger.warn("Received exception for a request that is already done. " + "This should not be able to happen!", t);
}
// Try to get the response from the exception if it exists
if (t instanceof DiscordException) {
result = ((DiscordException) t).getResponse().map(RestRequestResponseInformationImpl.class::cast).map(RestRequestResponseInformationImpl::getRestRequestResult).orElse(null);
}
// Complete the request
currentRequest.getResult().completeExceptionally(t);
} finally {
try {
// Calculate offset
calculateOffset(responseTimestamp, result);
// Handle the response
handleResponse(currentRequest, result, bucket, responseTimestamp);
} catch (Throwable t) {
logger.warn("Encountered unexpected exception.", t);
}
// The request didn't finish, so let's try again
if (!currentRequest.getResult().isDone()) {
continue;
}
// Poll a new quest
synchronized (buckets) {
bucket.pollRequestFromQueue();
currentRequest = bucket.peekRequestFromQueue();
if (currentRequest == null) {
buckets.remove(bucket);
}
}
}
}
});
}
Aggregations