Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle rate limiting by retrying after the stated time #52

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

package jetbrains.buildServer.commitPublisher;

import java.time.Duration;
import jetbrains.buildServer.ssh.ServerSshKeyManager;
import org.jetbrains.annotations.NotNull;

Expand Down Expand Up @@ -62,6 +63,7 @@ public class Constants {
public static final String GITHUB_OAUTH_PROVIDER_ID = "github_oauth_provider_id";
public static final String GITHUB_CUSTOM_CONTEXT_BUILD_PARAM = "teamcity.commitStatusPublisher.githubContext";
public static final String GITHUB_CONTEXT = "github_context";
public static final String GITHUB_RATE_LIMIT_RESET_HEADER = "X-RateLimit-Reset";

public static final String BITBUCKET_PUBLISHER_ID = "bitbucketCloudPublisher";
public static final String BITBUCKET_CLOUD_USERNAME = "bitbucketUsername";
Expand All @@ -71,6 +73,8 @@ public class Constants {
public static final String GITLAB_API_URL = "gitlabApiUrl";
public static final String GITLAB_TOKEN = "secure:gitlabAccessToken";

public static final Duration RATE_LIMIT_RESET_BUFFER = Duration.ofSeconds(1);


@NotNull
public String getVcsRootIdParam() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@
import java.io.IOException;
import java.net.URISyntaxException;
import java.security.KeyStore;
import java.time.Duration;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
Expand Down Expand Up @@ -51,6 +54,7 @@ private static void call(@NotNull HttpMethod method,
final AtomicReference<String> content = new AtomicReference<String>();
final AtomicReference<Integer> code = new AtomicReference<Integer>(0);
final AtomicReference<String> text = new AtomicReference<String>();
final AtomicReference<Duration> retryDelay = new AtomicReference<Duration>();

final HTTPRequestBuilder builder;
try {
Expand All @@ -76,6 +80,14 @@ public void consume(@NotNull final HTTPRequestBuilder.Response response) throws
content.set(response.getBodyAsString());
code.set(response.getStatusCode());
text.set(response.getStatusText());
String retryAfter = response.getHeader("Retry-After");
if (retryAfter != null) {
try {
retryDelay.set(Duration.ofSeconds(Long.parseLong(retryAfter)));
} catch (NumberFormatException ex) {
retryDelay.set(Duration.between(Instant.now(), Instant.from(DateTimeFormatter.RFC_1123_DATE_TIME.parse(retryAfter))));
}
}
}
})
.onSuccess(new HTTPRequestBuilder.ResponseConsumer() {
Expand Down Expand Up @@ -103,7 +115,13 @@ public void consume(@NotNull final HTTPRequestBuilder.Response response) throws
}
}

if (processor != null) {
Duration duration = retryDelay.get();
if (duration != null) {
try {
Thread.sleep(duration.plus(Constants.RATE_LIMIT_RESET_BUFFER).toMillis());
} catch (InterruptedException ignored) {}
call(method, url, username, password, headers, timeout, trustStore, processor, modifier);
} else if (processor != null) {
processor.processResponse(new HttpResponse(code.get(), text.get(), content.get()));
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Matcher;
Expand Down Expand Up @@ -112,6 +114,7 @@ public CombinedCommitStatus readChangeCombinedStatus(@NotNull final String repoO

final AtomicReference<CombinedCommitStatus> status = new AtomicReference<>();
final AtomicReference<Exception> exceptionRef = new AtomicReference<>();
final AtomicReference<Duration> retryDelay = new AtomicReference<>();
IOGuard.allowNetworkCall(() -> {
myClient.get(statusUrl, authenticationCredentials(), defaultHeaders(),
success -> {
Expand All @@ -135,14 +138,25 @@ public CombinedCommitStatus readChangeCombinedStatus(@NotNull final String repoO
}
},
response -> {
logFailedResponse(method, statusUrl, null, response);
exceptionRef.set(new IOException(getErrorMessage(response, null)));
String reset = response.getHeader(Constants.GITHUB_RATE_LIMIT_RESET_HEADER);
if (reset != null) {
retryDelay.set(Duration.between(Instant.now(), Instant.ofEpochSecond(Long.parseLong(reset))));
} else {
logFailedResponse(method, statusUrl, null, response);
exceptionRef.set(new IOException(getErrorMessage(response, null)));
}
},
e -> exceptionRef.set(e));
});

final Exception ex;
if ((ex = exceptionRef.get()) != null) {
final Duration duration = retryDelay.get();
if (duration != null) {
try {
Thread.sleep(duration.plus(Constants.RATE_LIMIT_RESET_BUFFER).toMillis());
} catch (InterruptedException ignored) {}
return readChangeCombinedStatus(repoOwner, repoName, hash, perPage, page);
} else if ((ex = exceptionRef.get()) != null) {
if (ex instanceof IOException) {
throw (IOException) ex;
} else {
Expand Down Expand Up @@ -176,21 +190,33 @@ public void setChangeStatus(@NotNull final String repoOwner,
LoggerUtil.logRequest(Constants.GITHUB_PUBLISHER_ID, method, url, entity);

final AtomicReference<Exception> exceptionRef = new AtomicReference<>();
final AtomicReference<Duration> retryDelay = new AtomicReference<>();
IOGuard.allowNetworkCall(() -> {
myClient.post(
url, authenticationCredentials(), defaultHeaders(),
entity, ContentType.APPLICATION_JSON.getMimeType(), ContentType.APPLICATION_JSON.getCharset(),
response -> {
},
response -> {
logFailedResponse(method, url, entity, response);
exceptionRef.set(new IOException(getErrorMessage(response, MSG_PROXY_OR_PERMISSIONS)));
String reset = response.getHeader(Constants.GITHUB_RATE_LIMIT_RESET_HEADER);
if (reset != null) {
retryDelay.set(Duration.between(Instant.now(), Instant.ofEpochSecond(Long.parseLong(reset))));
} else {
logFailedResponse(method, url, entity, response);
exceptionRef.set(new IOException(getErrorMessage(response, MSG_PROXY_OR_PERMISSIONS)));
}
},
e -> exceptionRef.set(e));
});

final Exception ex;
if ((ex = exceptionRef.get()) != null) {
final Duration duration = retryDelay.get();
if (duration != null) {
try {
Thread.sleep(duration.plus(Constants.RATE_LIMIT_RESET_BUFFER).toMillis());
} catch (InterruptedException ignored) {}
setChangeStatus(repoOwner, repoName, hash, status, targetUrl, description, context);
} else if ((ex = exceptionRef.get()) != null) {
if (ex instanceof IOException) {
throw (IOException) ex;
} else {
Expand Down Expand Up @@ -249,6 +275,7 @@ private <T> T processResponse(@NotNull String uri, @NotNull final Class<T> clazz

final AtomicReference<Exception> exceptionRef = new AtomicReference<>();
final AtomicReference<T> resultRef = new AtomicReference<>();
final AtomicReference<Duration> retryDelay = new AtomicReference<>();
IOGuard.allowNetworkCall(() -> {
myClient.get(uri, authenticationCredentials(), defaultHeaders(),
success -> {
Expand All @@ -267,8 +294,13 @@ private <T> T processResponse(@NotNull String uri, @NotNull final Class<T> clazz
}
},
error -> {
logFailedResponse(HttpMethod.GET, uri, null, error, logErrorsDebugOnly);
exceptionRef.set(new IOException(getErrorMessage(error, MSG_PROXY_OR_PERMISSIONS)));
String reset = error.getHeader(Constants.GITHUB_RATE_LIMIT_RESET_HEADER);
if (reset != null) {
retryDelay.set(Duration.between(Instant.now(), Instant.ofEpochSecond(Long.parseLong(reset))));
} else {
logFailedResponse(HttpMethod.GET, uri, null, error, logErrorsDebugOnly);
exceptionRef.set(new IOException(getErrorMessage(error, MSG_PROXY_OR_PERMISSIONS)));
}
},
e -> {
exceptionRef.set(e);
Expand All @@ -277,7 +309,13 @@ private <T> T processResponse(@NotNull String uri, @NotNull final Class<T> clazz
});

final Exception ex;
if ((ex = exceptionRef.get()) != null) {
final Duration duration = retryDelay.get();
if (duration != null) {
try {
Thread.sleep(duration.plus(Constants.RATE_LIMIT_RESET_BUFFER).toMillis());
} catch (InterruptedException ignored) {}
return processResponse(uri, clazz, logErrorsDebugOnly);
} else if ((ex = exceptionRef.get()) != null) {
if (ex instanceof IOException) {
throw (IOException)ex;
} else if (ex instanceof PublisherException) {
Expand Down Expand Up @@ -350,21 +388,33 @@ public void postComment(@NotNull final String ownerName,
LoggerUtil.logRequest(Constants.GITHUB_PUBLISHER_ID, method, url, entity);

final AtomicReference<Exception> exceptionRef = new AtomicReference<>();
final AtomicReference<Duration> retryDelay = new AtomicReference<>();
IOGuard.allowNetworkCall(() -> {
myClient.post(
url, authenticationCredentials(), defaultHeaders(),
entity, ContentType.APPLICATION_JSON.getMimeType(), ContentType.APPLICATION_JSON.getCharset(),
response -> {
},
response -> {
logFailedResponse(method, url, entity, response);
exceptionRef.set(new IOException(getErrorMessage(response, null)));
String reset = response.getHeader(Constants.GITHUB_RATE_LIMIT_RESET_HEADER);
if (reset != null) {
retryDelay.set(Duration.between(Instant.now(), Instant.ofEpochSecond(Long.parseLong(reset))));
} else {
logFailedResponse(method, url, entity, response);
exceptionRef.set(new IOException(getErrorMessage(response, null)));
}
},
e -> exceptionRef.set(e));
});

final Exception ex;
if ((ex = exceptionRef.get()) != null) {
final Duration duration = retryDelay.get();
if (duration != null) {
try {
Thread.sleep(duration.plus(Constants.RATE_LIMIT_RESET_BUFFER).toMillis());
} catch (InterruptedException ignored) {}
postComment(ownerName, repoName, hash, comment);
} else if ((ex = exceptionRef.get()) != null) {
if (ex instanceof IOException) {
throw (IOException) ex;
} else {
Expand Down