Repository navigation
fix: honor Retry-After delay seconds #340
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
SoulPancake
wants to merge
5
commits into
main
Choose a base branch
from
fix/retry-after-delay-seconds
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.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
ec88544
fix: honor Retry-After delay seconds
SoulPancake 8cdeacc
fix: parse Retry-After with stdlib and stop urllib3 pre-empting SDK r…
SoulPancake 29ab01b
test: trim retry-after tests and comments
SoulPancake 9ec3fdb
refactor: use RETRY_AFTER_HEADER_NAME constant for Retry-After lookup
SoulPancake 22c1a2a
refactor: derive retry-after header key from RETRY_AFTER_HEADER_NAME
SoulPancake 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
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
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
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,154 @@ | ||
| from datetime import datetime, timedelta, timezone | ||
| from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer | ||
| from threading import Thread | ||
| from unittest.mock import AsyncMock, patch | ||
|
|
||
| import pytest | ||
| import pytest_asyncio | ||
|
|
||
| from openfga_sdk.api_client import ApiClient as AsyncApiClient | ||
| from openfga_sdk.configuration import Configuration, RetryParams | ||
| from openfga_sdk.sync.api_client import ApiClient as SyncApiClient | ||
|
|
||
|
|
||
| BACKOFF = 0.125 | ||
| IMF_FIXDATE = "%a, %d %b %Y %H:%M:%S GMT" | ||
|
|
||
|
|
||
| def http_date(**delta): | ||
| return (datetime.now(timezone.utc) + timedelta(**delta)).strftime(IMF_FIXDATE) | ||
|
|
||
|
|
||
| # urllib3 retries idempotent methods like GET on its own unless the SDK stops it. | ||
| http_methods = pytest.mark.parametrize("method", ["GET", "POST"]) | ||
|
|
||
| retry_after_cases = pytest.mark.parametrize( | ||
| "status,retry_after,expected_wait", | ||
| [ | ||
| (429, "0", BACKOFF), | ||
| (429, "1", 1), | ||
| (429, "10", 10), | ||
| (429, "31", 31), | ||
| (429, "60", 60), | ||
| (429, "1800", 1800), | ||
| (429, "-1", BACKOFF), | ||
| (429, "1801", BACKOFF), | ||
| (429, "not-a-date", BACKOFF), | ||
| (503, "60", 60), | ||
| ], | ||
| ) | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def retry_server(status, retry_after): | ||
| requests = [] | ||
|
|
||
| class Handler(BaseHTTPRequestHandler): | ||
| def log_message(self, format, *args): | ||
| pass | ||
|
|
||
| def _respond(self): | ||
| requests.append(self.path) | ||
| self.send_response(status if len(requests) == 1 else 200) | ||
| self.send_header("Content-Type", "application/json") | ||
| self.send_header("Retry-After", retry_after) | ||
| self.send_header("Content-Length", "2") | ||
| self.end_headers() | ||
| self.wfile.write(b"{}") | ||
|
|
||
| do_GET = do_POST = _respond | ||
|
|
||
| with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: | ||
| thread = Thread( | ||
| target=server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True | ||
| ) | ||
| thread.start() | ||
| try: | ||
| yield f"http://127.0.0.1:{server.server_port}", requests | ||
| finally: | ||
| server.shutdown() | ||
| thread.join() | ||
|
|
||
|
|
||
| @http_methods | ||
| @retry_after_cases | ||
| @pytest.mark.asyncio | ||
| async def test_async_retry_after_over_http(retry_server, method, expected_wait): | ||
| url, requests = retry_server | ||
| configuration = Configuration( | ||
| api_url=url, retry_params=RetryParams(max_retry=1, max_wait_in_sec=1) | ||
| ) | ||
| with ( | ||
| patch("openfga_sdk.api_client.random_time", return_value=BACKOFF), | ||
| patch("asyncio.sleep", new_callable=AsyncMock) as sleep, | ||
| ): | ||
| async with AsyncApiClient(configuration) as client: | ||
| result = await client.call_api( | ||
| "/retry", method, response_types_map={}, _return_http_data_only=True | ||
| ) | ||
|
|
||
| assert result is None | ||
| assert requests == ["/retry", "/retry"] | ||
| sleep.assert_awaited_once_with(expected_wait) | ||
|
|
||
|
|
||
| @http_methods | ||
| @retry_after_cases | ||
| def test_sync_retry_after_over_http(retry_server, method, expected_wait): | ||
| url, requests = retry_server | ||
| configuration = Configuration( | ||
| api_url=url, retry_params=RetryParams(max_retry=1, max_wait_in_sec=1) | ||
| ) | ||
| with ( | ||
| patch("openfga_sdk.sync.api_client.random_time", return_value=BACKOFF), | ||
| patch("time.sleep") as sleep, | ||
| SyncApiClient(configuration) as client, | ||
| ): | ||
| result = client.call_api( | ||
| "/retry", method, response_types_map={}, _return_http_data_only=True | ||
| ) | ||
|
|
||
| assert result is None | ||
| assert requests == ["/retry", "/retry"] | ||
| sleep.assert_called_once_with(expected_wait) | ||
|
|
||
|
|
||
| @pytest_asyncio.fixture(params=["async", "sync"]) | ||
| async def parse_retry_after(request): | ||
| configuration = Configuration(api_url="http://localhost:8080") | ||
| if request.param == "async": | ||
| async with AsyncApiClient(configuration) as client: | ||
| yield lambda value: client._parse_retry_after_header({"retry-after": value}) | ||
| else: | ||
| with SyncApiClient(configuration) as client: | ||
| yield lambda value: client._parse_retry_after_header({"retry-after": value}) | ||
|
|
||
|
|
||
| # HTTP-date formats a recipient must accept per RFC 9110 section 5.6.7. | ||
| @pytest.mark.parametrize( | ||
| "http_date_format", | ||
| [IMF_FIXDATE, "%A, %d-%b-%y %H:%M:%S GMT", "%a %b %d %H:%M:%S %Y"], | ||
| ids=["imf-fixdate", "rfc850", "asctime"], | ||
| ) | ||
| @pytest.mark.asyncio | ||
| async def test_parse_retry_after_http_date(parse_retry_after, http_date_format): | ||
| retry_at = datetime.now(timezone.utc) + timedelta(seconds=60) | ||
|
|
||
| wait = parse_retry_after(retry_at.strftime(http_date_format)) | ||
|
|
||
| assert 59 <= wait <= 60 | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "value", | ||
| [ | ||
| "1.5", | ||
| "5s", | ||
| pytest.param(http_date(seconds=-5), id="date-in-past"), | ||
| pytest.param(http_date(hours=1), id="date-above-max"), | ||
| ], | ||
| ) | ||
| @pytest.mark.asyncio | ||
| async def test_parse_retry_after_rejects_invalid(parse_retry_after, value): | ||
| with pytest.raises(ValueError): | ||
| parse_retry_after(value) |
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.
Uh oh!
There was an error while loading. Please reload this page.