-
Notifications
You must be signed in to change notification settings - Fork 4
feat: handle retrying requests when rate limit exceeded #60
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
Draft
ahal
wants to merge
1
commit into
mozilla-releng:main
Choose a base branch
from
ahal:ahal/push-ulzwukurnyvp
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.
Draft
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
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,82 @@ | ||
| from time import time | ||
|
|
||
| from simple_github.util.types import BaseResponse | ||
|
|
||
|
|
||
| def is_rate_limited(resp: BaseResponse) -> bool: | ||
| """ | ||
| Determine if a response indicates a rate limit has been reached. | ||
| Checks the response headers and body to identify if the request was | ||
| rate-limited. It handles both GraphQL and REST API responses, looking for | ||
| specific status codes, headers, and error messages. | ||
| Args: | ||
| resp (Response): The HTTP response object to evaluate. | ||
| Returns: | ||
| bool: True if the response indicates a rate limit, False otherwise. | ||
| """ | ||
| resource = resp.headers.get("x-ratelimit-resource") | ||
|
|
||
| if resource == "graphql": | ||
| if resp.status_code in (200, 403): | ||
| data = resp.json() | ||
| errors = data.get("errors", []) | ||
| for error in errors: | ||
| if ( | ||
| error.get("type") == "RATE_LIMITED" | ||
| or error.get("extensions", {}).get("code") == "RATE_LIMITED" | ||
| or "rate limit" in error.get("message", "").lower() | ||
| ): | ||
| return True | ||
|
|
||
| elif resp.status_code in (403, 429): | ||
| if resp.headers.get("x-ratelimit-remaining") == "0" or resp.headers.get( | ||
| "retry-after" | ||
| ): | ||
| return True | ||
|
|
||
| try: | ||
| data = resp.json() | ||
| message = data.get("message", "").lower() | ||
| if "rate limit exceeded" or "too many requests" in message: | ||
| return True | ||
| except ValueError: | ||
| pass | ||
|
|
||
| return False | ||
|
|
||
|
|
||
| def get_wait_time(resp: BaseResponse, attempt: int = 1) -> int: | ||
| """ | ||
| Calculate the wait time before retrying a request after hitting a rate limit. | ||
| Determines the appropriate wait time based on the response headers and the | ||
| number of retry attempts. It prioritizes the `x-ratelimit-reset` and | ||
| `retry-after` headers if available, and falls back to a default wait time | ||
| strategy otherwise. | ||
| Args: | ||
| resp (Response): The HTTP response object containing rate limit headers. | ||
| attempt (int): The current retry attempt number (default is 1). | ||
| Returns: | ||
| int: The calculated wait time in seconds. | ||
| """ | ||
| attempt = max(attempt, 1) | ||
| remaining = resp.headers.get("x-ratelimit-remaining") | ||
| reset = resp.headers.get("x-ratelimit-reset") | ||
| retry_after = resp.headers.get("retry-after") | ||
|
|
||
| if remaining == "0" and reset: | ||
| wait_time = max(0, int(reset) - int(time())) | ||
| elif retry_after: | ||
| wait_time = int(retry_after) | ||
|
Comment on lines
+73
to
+75
Contributor
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. handle ValueError from the casts? |
||
| else: | ||
| # If the `x-ratelimit-reset` or `retry-after` headers aren't set, then | ||
| # the recommendation is to wait at least one minute and increase the | ||
| # interval with each new attempt. | ||
| wait_time = 60 + (20 * (attempt - 1)) | ||
|
|
||
| return wait_time | ||
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,12 @@ | ||
| from typing import Any, Coroutine, Dict, Optional, Union | ||
|
|
||
| from aiohttp import ClientResponse | ||
| from requests import Response as RequestsResponse | ||
|
|
||
| Response = Union[RequestsResponse, ClientResponse] | ||
| RequestData = Optional[Dict[str, Any]] | ||
|
|
||
| # Implementations of the base class can be either sync or async. | ||
| BaseDict = Union[Dict[str, Any], Coroutine[None, None, Dict[str, Any]]] | ||
| BaseNone = Union[None, Coroutine[None, None, None]] | ||
| BaseResponse = Union[Response, Coroutine[None, None, Response]] |
Oops, something went wrong.
Oops, something went wrong.
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.
we might want to log something before sleep?