-
Notifications
You must be signed in to change notification settings - Fork 38
feat: ADD rate-limiting functionality #1396
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
Open
mattclegg
wants to merge
1
commit into
otto-de:main
Choose a base branch
from
mattclegg:rate-limiting
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+133
−1
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,18 +1,29 @@ | ||
| package de.otto.platform.gitactionboard.adapters.service; | ||
|
|
||
| import static org.springframework.http.HttpHeaders.AUTHORIZATION; | ||
| import static org.springframework.http.HttpStatus.FORBIDDEN; | ||
| import static org.springframework.http.HttpStatus.TOO_MANY_REQUESTS; | ||
|
|
||
| import java.time.Duration; | ||
| import java.time.Instant; | ||
| import java.util.Optional; | ||
| import java.util.concurrent.atomic.AtomicReference; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.beans.factory.annotation.Qualifier; | ||
| import org.springframework.http.HttpHeaders; | ||
| import org.springframework.stereotype.Service; | ||
| import org.springframework.web.client.HttpClientErrorException; | ||
| import org.springframework.web.client.RestClient; | ||
|
|
||
| @Slf4j | ||
| @Service | ||
| public class GithubApiService { | ||
| private static final String RATE_LIMIT_REMAINING_HEADER = "x-ratelimit-remaining"; | ||
| private static final String RATE_LIMIT_RESET_HEADER = "x-ratelimit-reset"; | ||
|
|
||
| private final String authToken; | ||
| private final RestClient.Builder restClientBuilder; | ||
| private final AtomicReference<Instant> rateLimitResetAt = new AtomicReference<>(Instant.EPOCH); | ||
|
|
||
| public GithubApiService( | ||
| @Qualifier("domainName") String baseUri, | ||
|
|
@@ -34,6 +45,60 @@ private RestClient getRestClient(String accessToken) { | |
| } | ||
|
|
||
| public <T> T getForObject(String url, String accessToken, Class<T> responseType) { | ||
| return getRestClient(accessToken).get().uri(url).retrieve().body(responseType); | ||
| final RestClient restClient = getRestClient(accessToken); | ||
|
|
||
| // Another request may already have tripped the GitHub rate limit; hold off until it resets. | ||
| waitUntilRateLimitResets(); | ||
|
|
||
| try { | ||
| return restClient.get().uri(url).retrieve().body(responseType); | ||
| } catch (HttpClientErrorException exception) { | ||
| if (!isRateLimited(exception)) { | ||
| throw exception; | ||
| } | ||
|
|
||
| rememberRateLimitReset(exception); | ||
| waitUntilRateLimitResets(); | ||
|
|
||
| // Retry once now that the window has reset; any further failure propagates to the caller. | ||
| return restClient.get().uri(url).retrieve().body(responseType); | ||
| } | ||
| } | ||
|
|
||
| private static boolean isRateLimited(HttpClientErrorException exception) { | ||
| final boolean rateLimitStatus = | ||
| FORBIDDEN.equals(exception.getStatusCode()) | ||
| || TOO_MANY_REQUESTS.equals(exception.getStatusCode()); | ||
| final HttpHeaders headers = exception.getResponseHeaders(); | ||
| return rateLimitStatus | ||
| && headers != null | ||
| && "0".equals(headers.getFirst(RATE_LIMIT_REMAINING_HEADER)); | ||
| } | ||
|
|
||
| private void rememberRateLimitReset(HttpClientErrorException exception) { | ||
| final HttpHeaders headers = exception.getResponseHeaders(); | ||
| final String resetEpochSeconds = | ||
| headers == null ? null : headers.getFirst(RATE_LIMIT_RESET_HEADER); | ||
| if (resetEpochSeconds == null) { | ||
| return; | ||
| } | ||
| final Instant resetAt = Instant.ofEpochSecond(Long.parseLong(resetEpochSeconds)); | ||
| rateLimitResetAt.accumulateAndGet( | ||
| resetAt, (current, candidate) -> candidate.isAfter(current) ? candidate : current); | ||
| } | ||
|
|
||
| private void waitUntilRateLimitResets() { | ||
| final Duration waitFor = Duration.between(Instant.now(), rateLimitResetAt.get()); | ||
| if (waitFor.isZero() || waitFor.isNegative()) { | ||
| return; | ||
| } | ||
| log.warn("GitHub rate limit hit; waiting {}s until reset", waitFor.toSeconds()); | ||
| try { | ||
| Thread.sleep(waitFor.toMillis()); | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Wouldn't it hang the complete system? also given waitUntilRateLimitResets will be called multiple times, multiple Threads will go on sleep mode. Ideally if the rate-limit got hit, then we should skip the remaining calls |
||
| } catch (InterruptedException interruptedException) { | ||
| Thread.currentThread().interrupt(); | ||
| throw new IllegalStateException( | ||
| "Interrupted while waiting for GitHub rate limit to reset", interruptedException); | ||
| } | ||
| } | ||
| } | ||
67 changes: 67 additions & 0 deletions
67
.../src/test/java/de/otto/platform/gitactionboard/adapters/service/GithubApiServiceTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| package de.otto.platform.gitactionboard.adapters.service; | ||
|
|
||
| import static org.assertj.core.api.Assertions.assertThat; | ||
| import static org.mockserver.matchers.Times.once; | ||
| import static org.mockserver.model.HttpRequest.request; | ||
| import static org.mockserver.model.HttpResponse.response; | ||
| import static org.mockserver.verify.VerificationTimes.exactly; | ||
|
|
||
| import de.otto.platform.gitactionboard.IntegrationTest; | ||
| import de.otto.platform.gitactionboard.Sequential; | ||
| import java.time.Instant; | ||
| import org.junit.jupiter.api.AfterEach; | ||
| import org.junit.jupiter.api.BeforeEach; | ||
| import org.junit.jupiter.api.Test; | ||
| import org.mockserver.integration.ClientAndServer; | ||
| import org.springframework.web.client.RestClient; | ||
|
|
||
| @IntegrationTest | ||
| @Sequential | ||
| class GithubApiServiceTest { | ||
| private static final String OWNER = "johndoe"; | ||
| private static final String PATH = "/hello-world/branches"; | ||
| private static final String FULL_PATH = "/repos/%s%s".formatted(OWNER, PATH); | ||
| private static final String ACCESS_TOKEN = "accessToken"; | ||
| private static final String RESPONSE_BODY = "{\"ok\":true}"; | ||
|
|
||
| private ClientAndServer mockServer; | ||
| private GithubApiService githubApiService; | ||
|
|
||
| @BeforeEach | ||
| void setUp() { | ||
| mockServer = ClientAndServer.startClientAndServer(); | ||
| githubApiService = | ||
| new GithubApiService( | ||
| "http://localhost:%d".formatted(mockServer.getPort()), | ||
| OWNER, | ||
| "defaultToken", | ||
| RestClient.builder()); | ||
| } | ||
|
|
||
| @AfterEach | ||
| void tearDown() { | ||
| mockServer.stop(); | ||
| } | ||
|
|
||
| @Test | ||
| void shouldWaitForRateLimitToResetAndThenRetryTheRequest() { | ||
| // First call is rate limited; reset ~1s in the future. | ||
| mockServer | ||
| .when(request().withMethod("GET").withPath(FULL_PATH), once()) | ||
| .respond( | ||
| response() | ||
| .withStatusCode(403) | ||
| .withHeader("x-ratelimit-remaining", "0") | ||
| .withHeader("x-ratelimit-reset", String.valueOf(Instant.now().getEpochSecond() + 1))); | ||
|
|
||
| // Second call (after the wait) succeeds. | ||
| mockServer | ||
| .when(request().withMethod("GET").withPath(FULL_PATH)) | ||
| .respond(response().withStatusCode(200).withBody(RESPONSE_BODY)); | ||
|
|
||
| final String body = githubApiService.getForObject(PATH, ACCESS_TOKEN, String.class); | ||
|
|
||
| assertThat(body).isEqualTo(RESPONSE_BODY); | ||
| mockServer.verify(request().withMethod("GET").withPath(FULL_PATH), exactly(2)); | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
429 is only rate limit status code, isn't it? FORBIDDEN is slightly different