From af4777ab37cd72919c6942df07efff480cf62393 Mon Sep 17 00:00:00 2001 From: SoulPancake Date: Wed, 25 Nov 2026 18:23:34 +0530 Subject: [PATCH 1/2] fix: retry transient network errors Retry dropped connections, timeouts and other network errors on API and token requests, except certificate errors. Streams now connect and check the status before returning, so those failures are retried too, and errors while reading a stream are raised. Fixes #342 --- README.md | 6 +- openfga_sdk/api_client.py | 27 +++- openfga_sdk/configuration.py | 5 +- openfga_sdk/oauth2.py | 10 ++ openfga_sdk/rest.py | 76 ++++----- openfga_sdk/sync/api_client.py | 17 ++ openfga_sdk/sync/oauth2.py | 6 + openfga_sdk/sync/open_fga_api.py | 4 +- openfga_sdk/sync/rest.py | 56 ++++--- test/network_retry_test.py | 264 +++++++++++++++++++++++++++++++ test/oauth2_test.py | 67 +++++++- test/rest_test.py | 80 ++++++---- test/sync/oauth2_test.py | 44 ++++++ test/sync/rest_test.py | 64 +++++++- 14 files changed, 620 insertions(+), 106 deletions(-) create mode 100644 test/network_retry_test.py diff --git a/README.md b/README.md index da4473df..78113ddc 100644 --- a/README.md +++ b/README.md @@ -128,7 +128,7 @@ import openfga_sdk We strongly recommend you initialize the `OpenFgaClient` only once and then re-use it throughout your app, otherwise you will incur the cost of having to re-initialize multiple times or at every request, the cost of reduced connection pooling and re-use, and would be particularly costly in the client credentials flow, as that flow will be preformed on every request. -> The `OpenFgaClient` will by default retry API requests up to 3 times on 429 and 5xx errors. +> The `OpenFgaClient` will by default retry API requests up to 3 times on 429 and 5xx errors and on network errors. #### No Credentials @@ -1385,7 +1385,9 @@ response = await fga_client.execute_api_request( ### Retries -If a network request fails with a 429 or 5xx error from the server, the SDK will automatically retry the request up to 3 times with a minimum wait time of 100 milliseconds between each attempt. +If a request fails with a 429 or 5xx error from the server, or with a network error such as a dropped connection or timeout, the SDK will automatically retry the request up to 3 times with a minimum wait time of 100 milliseconds between each attempt. + +Network errors are retried for writes too, and the timeout applies to each attempt. A write that timed out may still have been applied, so its retry can fail as a duplicate unless the [conflict options](#conflict-options-for-write-operations) are set to `IGNORE`. In the async client, aiohttp may also resend a GET, PUT or DELETE request once by itself if the connection drops. The SDK honors `Retry-After` delay seconds or HTTP dates up to 30 minutes. Unparseable or out-of-range values fall back to exponential backoff. In the sync client, urllib3's own `Retry-After` handling is disabled unless you set `Configuration.retries`. diff --git a/openfga_sdk/api_client.py b/openfga_sdk/api_client.py index e010e30d..3bbe66c3 100644 --- a/openfga_sdk/api_client.py +++ b/openfga_sdk/api_client.py @@ -11,6 +11,8 @@ from email.utils import parsedate_to_datetime from multiprocessing.pool import ThreadPool +import aiohttp + from dateutil.parser import parse # type: ignore[import-untyped] import openfga_sdk.models @@ -333,6 +335,29 @@ async def __call_api( if isinstance(operation_name, str): e.operation_name = operation_name.lower() raise e + except aiohttp.ClientConnectorCertificateError: + # Also a network error, but retrying won't fix it + raise + except rest.NETWORK_ERRORS: + if retry == max_retry: + raise + + _telemetry_attributes = TelemetryAttributes.fromResponse( + credentials=self.configuration.credentials, + attributes=_telemetry_attributes, + start=start, + ) + + self._telemetry.metrics.request( + attributes=_telemetry_attributes, + configuration=self.configuration.telemetry, + ) + + await asyncio.sleep( + min(random_time(retry, min_wait_in_ms), max_wait_in_sec) + ) + + continue except ApiException as e: e.body = e.body.decode("utf-8") response_type = response_types_map.get(e.status, None) @@ -684,7 +709,7 @@ async def request( ) if _streaming: - return self.rest_client.stream( + return await self.rest_client.stream( method, url, query_params=query_params, diff --git a/openfga_sdk/configuration.py b/openfga_sdk/configuration.py index 02f8e5ee..bc015d76 100644 --- a/openfga_sdk/configuration.py +++ b/openfga_sdk/configuration.py @@ -304,8 +304,9 @@ def __init__( """Safe chars for path_param """ self.retries = None - """urllib3 Retry for the sync client. Defaults to 3 retries with - Retry-After handling disabled; the SDK retries 429/5xx itself. + """urllib3 Retry for the sync client. Defaults to 3 retries for + redirects and TLS errors, with Retry-After handling disabled; the SDK + retries connect and read errors, 429 and 5xx itself. """ # Enable client side validation self.client_side_validation = True diff --git a/openfga_sdk/oauth2.py b/openfga_sdk/oauth2.py index 084b497d..178296ae 100644 --- a/openfga_sdk/oauth2.py +++ b/openfga_sdk/oauth2.py @@ -4,6 +4,7 @@ from datetime import datetime, timedelta +import aiohttp import urllib3 from openfga_sdk._version import USER_AGENT @@ -19,6 +20,7 @@ ServiceException, ) from openfga_sdk.oauth2_common import _TokenState, jitter +from openfga_sdk.rest import NETWORK_ERRORS from openfga_sdk.telemetry.attributes import TelemetryAttributes from openfga_sdk.telemetry.telemetry import Telemetry @@ -125,6 +127,14 @@ async def _obtain_token(self, client): await asyncio.sleep(jitter(attempt, min_wait_in_ms)) continue raise + except aiohttp.ClientConnectorCertificateError: + # Also a network error, but retrying won't fix it + raise + except NETWORK_ERRORS: + if attempt < max_retry: + await asyncio.sleep(jitter(attempt, min_wait_in_ms)) + continue + raise if 500 <= raw_response.status <= 599 or raw_response.status == 429: if attempt < max_retry and raw_response.status != 501: diff --git a/openfga_sdk/rest.py b/openfga_sdk/rest.py index 00ee8ad9..a6299fb8 100644 --- a/openfga_sdk/rest.py +++ b/openfga_sdk/rest.py @@ -1,3 +1,4 @@ +import asyncio import io import json import logging @@ -23,6 +24,12 @@ logger = logging.getLogger(__name__) +NETWORK_ERRORS = ( + aiohttp.ClientConnectionError, + aiohttp.ClientPayloadError, + asyncio.TimeoutError, +) + class RESTResponse(io.IOBase): """ @@ -336,7 +343,7 @@ async def stream( :param body: Optional body for the request. :param post_params: Optional form/multipart parameters. :param _request_timeout: An optional request timeout in seconds. - :yields: Parsed JSON objects as Python data structures. + :return: An async iterator of parsed JSON objects. """ # Build our request payload @@ -351,36 +358,41 @@ async def stream( _request_timeout=_request_timeout, ) + # Send the request and check its status before returning the stream + stream = self._stream(args) + await anext(stream) + return stream + + async def _stream(self, args: dict): + """ + Sends the request and yields once its status is checked, then yields + JSON objects from the response and releases it. + """ + + # Send request, collect response handler + response = await self.pool_manager.request(**args) + # Initialize buffers for data chunks buffer = bytearray() leftover = b"" - response: aiohttp.ClientResponse | None = None try: - # Send request, collect response handler - async with self.pool_manager.request(**args) as resp: - response = resp - try: - # Iterate over streamed/chunked response data - async for data, _ in resp.content.iter_chunks(): - if data: - # Process data chunk - leftover, decoded_objects = self._accumulate_json_lines( - leftover, data, buffer - ) - - # Yield any complete objects - for obj in decoded_objects: - yield obj - - except Exception as e: - logger.exception("Stream reading error: %s", e) - - except Exception as conn_err: - logger.exception("Connection or request setup error: %s", conn_err) - - # Handle any remaining data after stream ends - if response is not None: + # Handle any HTTP errors that may have occurred + await self.handle_response_exception(response) + yield + + # Iterate over streamed/chunked response data + async for data, _ in response.content.iter_chunks(): + if data: + # Process data chunk + leftover, decoded_objects = self._accumulate_json_lines( + leftover, data, buffer + ) + + # Yield any complete objects + for obj in decoded_objects: + yield obj + # Check for any leftover data if leftover: try: @@ -396,16 +408,8 @@ async def stream( # Decode the complete/buffered data for logging purposes if isinstance(response, aiohttp.ClientResponse): logger.debug("response body: %s", buffer.decode("utf-8")) - - try: - # Handle any HTTP errors that may have occurred - await self.handle_response_exception(response) - finally: - # Release the response object back to the connection pool. - # This must always run, even if handle_response_exception raises, - # to avoid leaking the connection (preload_content=False means - # the connection is not auto-released). - response.release() + finally: + response.release() async def request( self, diff --git a/openfga_sdk/sync/api_client.py b/openfga_sdk/sync/api_client.py index 1d9e23c1..453e8169 100644 --- a/openfga_sdk/sync/api_client.py +++ b/openfga_sdk/sync/api_client.py @@ -333,6 +333,23 @@ def __call_api( if isinstance(operation_name, str): e.operation_name = operation_name.lower() raise + except rest.NETWORK_ERRORS: + if retry == max_retry: + raise + + _telemetry_attributes = TelemetryAttributes.fromResponse( + credentials=self.configuration.credentials, + attributes=_telemetry_attributes, + start=start, + ) + + self._telemetry.metrics.request( + attributes=_telemetry_attributes, + configuration=self.configuration.telemetry, + ) + + time.sleep(min(random_time(retry, min_wait_in_ms), max_wait_in_sec)) + continue except ApiException as e: e.body = e.body.decode("utf-8") response_type = response_types_map.get(e.status, None) diff --git a/openfga_sdk/sync/oauth2.py b/openfga_sdk/sync/oauth2.py index afc0800d..67154f68 100644 --- a/openfga_sdk/sync/oauth2.py +++ b/openfga_sdk/sync/oauth2.py @@ -20,6 +20,7 @@ ServiceException, ) from openfga_sdk.oauth2_common import _TokenState, jitter +from openfga_sdk.sync.rest import NETWORK_ERRORS from openfga_sdk.telemetry.attributes import TelemetryAttributes from openfga_sdk.telemetry.telemetry import Telemetry @@ -126,6 +127,11 @@ def _obtain_token(self, client): time.sleep(jitter(attempt, min_wait_in_ms)) continue raise + except NETWORK_ERRORS: + if attempt < max_retry: + time.sleep(jitter(attempt, min_wait_in_ms)) + continue + raise if 500 <= raw_response.status <= 599 or raw_response.status == 429: if attempt < max_retry and raw_response.status != 501: diff --git a/openfga_sdk/sync/open_fga_api.py b/openfga_sdk/sync/open_fga_api.py index 8518138e..efe7d389 100644 --- a/openfga_sdk/sync/open_fga_api.py +++ b/openfga_sdk/sync/open_fga_api.py @@ -58,7 +58,9 @@ def __init__(self, api_client=None): if api_client.configuration is not None: credentials = api_client.configuration.credentials if credentials is not None and credentials.method == "client_credentials": - self._oauth2_client = OAuth2Client(credentials) + self._oauth2_client = OAuth2Client( + credentials, api_client.configuration + ) self._telemetry = Telemetry() diff --git a/openfga_sdk/sync/rest.py b/openfga_sdk/sync/rest.py index dd2f0986..01ce6cc5 100644 --- a/openfga_sdk/sync/rest.py +++ b/openfga_sdk/sync/rest.py @@ -23,6 +23,13 @@ logger = logging.getLogger(__name__) +# TimeoutError also covers NewConnectionError and NameResolutionError. +NETWORK_ERRORS = ( + urllib3.exceptions.ProtocolError, + urllib3.exceptions.ProxyError, + urllib3.exceptions.TimeoutError, +) + class RESTResponse(io.IOBase): """ @@ -168,10 +175,11 @@ def __init__( if hasattr(configuration, "retries") and configuration.retries is not None: addition_pool_args["retries"] = configuration.retries else: - # The SDK retries 429/5xx itself; keep urllib3 from also retrying - # idempotent requests and sleeping for an uncapped Retry-After. + # The SDK retries connect and read errors, 429 and 5xx itself; keep + # urllib3 from also retrying them or sleeping for an uncapped + # Retry-After. urllib3 still follows redirects and retries TLS errors. addition_pool_args["retries"] = urllib3.Retry( - total=3, respect_retry_after_header=False + total=3, connect=False, read=False, respect_retry_after_header=False ) if ( @@ -393,7 +401,7 @@ def stream( :param body: Optional body for the request. :param post_params: Optional form/multipart parameters. :param _request_timeout: An optional request timeout in seconds or (connect, read) tuple. - :yields: Parsed JSON objects as Python data structures. + :return: An iterator of parsed JSON objects. """ # Build our request payload @@ -408,14 +416,29 @@ def stream( _request_timeout=_request_timeout, ) - # Initialize buffers for data chunks - buffer = bytearray() - leftover = b"" + # Send the request and check its status before returning the stream + stream = self._stream(args) + next(stream) + return stream + + def _stream(self, args: dict): + """ + Sends the request and yields once its status is checked, then yields + JSON objects from the response and releases the connection. + """ # Send request, collect response handler response = self.pool_manager.request(**args) + # Initialize buffers for data chunks + buffer = bytearray() + leftover = b"" + try: + # Handle any HTTP errors that may have occurred + self.handle_response_exception(response) + yield + # Iterate over streamed/chunked response data for chunk in response.stream(1024): # Process data chunk @@ -426,11 +449,6 @@ def stream( # Yield any complete objects yield from decoded_objects - except Exception as e: - logger.exception("Stream error: %s", e) - - # Handle any remaining data after stream ends - if response is not None: # Check for any leftover data if leftover: try: @@ -442,16 +460,10 @@ def stream( except json.JSONDecodeError: logger.debug("Incomplete leftover data at end of stream.") - - try: - # Handle any HTTP errors that may have occurred - self.handle_response_exception(response) - finally: - # Release the response object back to the connection pool. - # This must always run, even if handle_response_exception raises, - # to avoid leaking the connection (preload_content=False means - # urllib3 does not auto-release). - response.release_conn() + finally: + # Close first so a connection with unread data isn't reused + response.close() + response.release_conn() def request( self, diff --git a/test/network_retry_test.py b/test/network_retry_test.py new file mode 100644 index 00000000..ac37a38c --- /dev/null +++ b/test/network_retry_test.py @@ -0,0 +1,264 @@ +import json +import socket +import ssl + +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from threading import Thread +from unittest.mock import AsyncMock, MagicMock, patch + +import aiohttp +import pytest +import urllib3 + +from openfga_sdk.api_client import ApiClient as AsyncApiClient +from openfga_sdk.configuration import Configuration, RetryParams +from openfga_sdk.credentials import CredentialConfiguration, Credentials +from openfga_sdk.sync.api_client import ApiClient as SyncApiClient +from openfga_sdk.sync.open_fga_api import OpenFgaApi as SyncOpenFgaApi +from openfga_sdk.telemetry.attributes import TelemetryAttributes +from openfga_sdk.telemetry.metrics import TelemetryMetrics + + +CALL_ARGS = {"response_types_map": {}, "_return_http_data_only": True} +OBJECTS = [{"result": {"object": f"document:{i}"}} for i in range(3)] +NDJSON = b"".join(json.dumps(obj).encode() + b"\n" for obj in OBJECTS) + +# The configured max_retry=1 allows two attempts; the per-call override allows one. +exhausted_cases = pytest.mark.parametrize( + "retry_params,attempts", + [(None, 2), (RetryParams(max_retry=0), 1)], + ids=["retries-exhausted", "retries-disabled-per-call"], +) + + +def configuration(url, **kwargs): + return Configuration(api_url=url, retry_params=RetryParams(max_retry=1), **kwargs) + + +@pytest.fixture +def server(): + """ + Replies to each request with the next queued action, then with 200: + "drop" closes the connection without a response, "503" sends a 503 and + "truncate" closes the connection after the first chunk of the body. + """ + actions, requests = [], [] + + class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, format, *args): + pass + + def _respond(self): + self.rfile.read(int(self.headers.get("Content-Length", 0))) + requests.append(self.command) + action = actions.pop(0) if actions else "200" + if action == "drop": + self.close_connection = True + return + + self.send_response(503 if action == "503" else 200) + self.send_header("Content-Type", "application/json") + self.send_header("Transfer-Encoding", "chunked") + self.end_headers() + for line in (b"{}" if action == "503" else NDJSON).splitlines(True): + self.wfile.write(b"%x\r\n%s\r\n" % (len(line), line)) + if action == "truncate": + self.close_connection = True + return + self.wfile.write(b"0\r\n\r\n") + + do_GET = do_POST = _respond + + with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as httpd: + thread = Thread( + target=httpd.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True + ) + thread.start() + try: + yield f"http://127.0.0.1:{httpd.server_port}", actions, requests + finally: + httpd.shutdown() + thread.join() + + +@pytest.fixture +def resend_counts(): + """The http.request.resend_count of every request metric recorded.""" + counts = [] + + def request(self, attributes, configuration=None): + counts.append(attributes[TelemetryAttributes.http_request_resend_count]) + + with patch.object(TelemetryMetrics, "request", request): + yield counts + + +@pytest.mark.asyncio +async def test_async_retries_dropped_connection(server, resend_counts): + url, actions, requests = server + actions.append("drop") + with patch("asyncio.sleep", new_callable=AsyncMock) as sleep: + async with AsyncApiClient(configuration(url)) as client: + await client.call_api("/check", "POST", **CALL_ARGS) + + assert requests == ["POST", "POST"] + assert resend_counts == [0, 1] + sleep.assert_awaited_once() + + +def test_sync_retries_dropped_connection(server, resend_counts): + url, actions, requests = server + actions.append("drop") + with patch("time.sleep") as sleep, SyncApiClient(configuration(url)) as client: + client.call_api("/check", "POST", **CALL_ARGS) + + assert requests == ["POST", "POST"] + assert resend_counts == [0, 1] + sleep.assert_called_once() + + +@exhausted_cases +@pytest.mark.asyncio +async def test_async_raises_network_error_when_out_of_retries( + server, retry_params, attempts +): + url, actions, requests = server + actions.extend(["drop"] * attempts) + with patch("asyncio.sleep", new_callable=AsyncMock): + async with AsyncApiClient(configuration(url)) as client: + with pytest.raises(aiohttp.ServerDisconnectedError): + await client.call_api( + "/check", "POST", _retry_params=retry_params, **CALL_ARGS + ) + + assert requests == ["POST"] * attempts + + +# urllib3 would otherwise resend the GET on its own. +@exhausted_cases +def test_sync_raises_network_error_when_out_of_retries(server, retry_params, attempts): + url, actions, requests = server + actions.extend(["drop"] * attempts) + with ( + patch("time.sleep"), + SyncApiClient(configuration(url)) as client, + pytest.raises(urllib3.exceptions.ProtocolError), + ): + client.call_api("/stores", "GET", _retry_params=retry_params, **CALL_ARGS) + + assert requests == ["GET"] * attempts + + +def test_sync_retries_unreachable_proxy(): + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + port = sock.getsockname()[1] + + config = configuration("http://fga.example") + config.proxy = f"http://127.0.0.1:{port}" + with ( + patch("time.sleep") as sleep, + SyncApiClient(config) as client, + pytest.raises(urllib3.exceptions.ProxyError), + ): + client.call_api("/check", "POST", **CALL_ARGS) + + sleep.assert_called_once() + + +@pytest.mark.asyncio +async def test_async_does_not_retry_certificate_errors(): + error = aiohttp.ClientConnectorCertificateError( + MagicMock(), ssl.SSLCertVerificationError("certificate verify failed") + ) + with ( + patch("asyncio.sleep", new_callable=AsyncMock) as sleep, + patch( + "openfga_sdk.rest.RESTClientObject.request", side_effect=error + ) as request, + ): + async with AsyncApiClient(configuration("https://fga.example")) as client: + with pytest.raises(aiohttp.ClientConnectorCertificateError): + await client.call_api("/check", "POST", **CALL_ARGS) + + request.assert_called_once() + sleep.assert_not_awaited() + + +# max_retry=1 allows two token requests; the default would allow four. +def test_sync_token_request_uses_client_retry_params(server): + url, actions, requests = server + actions.extend(["drop"] * 4) + credentials = Credentials( + method="client_credentials", + configuration=CredentialConfiguration( + client_id="client-id", + client_secret="client-secret", + api_issuer=f"{url}/oauth/token", + api_audience="audience", + ), + ) + with ( + patch("time.sleep"), + SyncApiClient(configuration(url, credentials=credentials)) as client, + pytest.raises(urllib3.exceptions.ProtocolError), + ): + SyncOpenFgaApi(client).list_stores() + + assert requests == ["POST", "POST"] + + +@pytest.mark.parametrize("failure", ["drop", "503"]) +@pytest.mark.asyncio +async def test_async_stream_retries_until_connected(server, failure): + url, actions, requests = server + actions.append(failure) + with patch("asyncio.sleep", new_callable=AsyncMock): + async with AsyncApiClient(configuration(url)) as client: + stream = await client.call_api( + "/stream", "POST", _streaming=True, **CALL_ARGS + ) + received = [obj async for obj in stream] + + assert received == OBJECTS + assert requests == ["POST", "POST"] + + +@pytest.mark.parametrize("failure", ["drop", "503"]) +def test_sync_stream_retries_until_connected(server, failure): + url, actions, requests = server + actions.append(failure) + with patch("time.sleep"), SyncApiClient(configuration(url)) as client: + stream = client.call_api("/stream", "POST", _streaming=True, **CALL_ARGS) + received = list(stream) + + assert received == OBJECTS + assert requests == ["POST", "POST"] + + +@pytest.mark.asyncio +async def test_async_stream_raises_without_retry_once_connected(server): + url, actions, requests = server + actions.append("truncate") + with patch("asyncio.sleep", new_callable=AsyncMock): + async with AsyncApiClient(configuration(url)) as client: + stream = await client.call_api( + "/stream", "POST", _streaming=True, **CALL_ARGS + ) + with pytest.raises(aiohttp.ClientPayloadError): + [obj async for obj in stream] + + assert requests == ["POST"] + + +def test_sync_stream_raises_without_retry_once_connected(server): + url, actions, requests = server + actions.append("truncate") + with patch("time.sleep"), SyncApiClient(configuration(url)) as client: + stream = client.call_api("/stream", "POST", _streaming=True, **CALL_ARGS) + with pytest.raises(urllib3.exceptions.ProtocolError): + list(stream) + + assert requests == ["POST"] diff --git a/test/oauth2_test.py b/test/oauth2_test.py index f677d36d..233431ee 100644 --- a/test/oauth2_test.py +++ b/test/oauth2_test.py @@ -1,9 +1,11 @@ import asyncio +import ssl from datetime import datetime, timedelta from unittest import IsolatedAsyncioTestCase -from unittest.mock import patch +from unittest.mock import MagicMock, patch +import aiohttp import urllib3 from openfga_sdk import rest @@ -315,6 +317,69 @@ async def test_get_authentication_does_not_retry_501(self, mock_request): self.assertEqual(mock_request.call_count, 1) await rest_client.close() + @patch.object(rest.RESTClientObject, "request") + async def test_get_authentication_retries_network_errors(self, mock_request): + """ + Token requests that fail with a network error are retried + """ + response_body = '{"expires_in": 120, "access_token": "AABBCCDD"}' + mock_request.side_effect = [ + aiohttp.ServerDisconnectedError(), + asyncio.TimeoutError(), + mock_response(response_body, 200), + ] + + configuration = Configuration() + rest_client = rest.RESTClientObject(configuration) + client = OAuth2Client(self._client_credentials(), configuration) + + auth_header = await client.get_authentication_header(rest_client) + + self.assertEqual(mock_request.call_count, 3) + self.assertEqual(auth_header, {"Authorization": "Bearer AABBCCDD"}) + await rest_client.close() + + @patch.object(rest.RESTClientObject, "request") + async def test_get_authentication_raises_network_error_when_retries_exhausted( + self, mock_request + ): + """ + After max_retry retries, the last network error is raised + """ + mock_request.side_effect = aiohttp.ServerDisconnectedError() + + configuration = Configuration() + configuration.retry_params.max_retry = 2 + rest_client = rest.RESTClientObject(configuration) + client = OAuth2Client(self._client_credentials(), configuration) + + with self.assertRaises(aiohttp.ServerDisconnectedError): + await client.get_authentication_header(rest_client) + + self.assertEqual(mock_request.call_count, 3) + await rest_client.close() + + @patch.object(rest.RESTClientObject, "request") + async def test_get_authentication_does_not_retry_certificate_errors( + self, mock_request + ): + """ + Certificate errors are raised without retrying + """ + mock_request.side_effect = aiohttp.ClientConnectorCertificateError( + MagicMock(), ssl.SSLCertVerificationError("certificate verify failed") + ) + + configuration = Configuration() + rest_client = rest.RESTClientObject(configuration) + client = OAuth2Client(self._client_credentials(), configuration) + + with self.assertRaises(aiohttp.ClientConnectorCertificateError): + await client.get_authentication_header(rest_client) + + self.assertEqual(mock_request.call_count, 1) + await rest_client.close() + @patch.object(rest.RESTClientObject, "request") async def test_get_authentication_retries_5xx_responses(self, mock_request): """ diff --git a/test/rest_test.py b/test/rest_test.py index 1609989b..51398586 100644 --- a/test/rest_test.py +++ b/test/rest_test.py @@ -351,17 +351,13 @@ async def iter_chunks(self): mock_response.data = None mock_response.content = FakeContent() - mock_context_manager = AsyncMock() - mock_context_manager.__aenter__.return_value = mock_response - mock_context_manager.__aexit__.return_value = None - - mock_session.request.return_value = mock_context_manager + mock_session.request = AsyncMock(return_value=mock_response) client.handle_response_exception = AsyncMock() client.close = AsyncMock() results = [] - async for item in client.stream("GET", "http://example.com"): + async for item in await client.stream("GET", "http://example.com"): results.append(item) assert results == [{"foo": "bar"}, {"hello": "world"}] @@ -398,21 +394,15 @@ async def iter_chunks(self): mock_response.data = None mock_response.content = FakeContent() - mock_context_manager = AsyncMock() - mock_context_manager.__aenter__.return_value = mock_response - mock_context_manager.__aexit__.return_value = None - - mock_session.request.return_value = mock_context_manager + mock_session.request = AsyncMock(return_value=mock_response) client.handle_response_exception = AsyncMock() client.close = AsyncMock() results = [] - try: - async for item in client.stream("GET", "http://example.com"): + with pytest.raises(ValueError, match="Boom!"): + async for item in await client.stream("GET", "http://example.com"): results.append(item) - except ValueError: - pass assert results == [] client.handle_response_exception.assert_awaited_once() @@ -446,17 +436,13 @@ async def iter_chunks(self): mock_response.data = None mock_response.content = FakeContent() - mock_context_manager = AsyncMock() - mock_context_manager.__aenter__.return_value = mock_response - mock_context_manager.__aexit__.return_value = None - - mock_session.request.return_value = mock_context_manager + mock_session.request = AsyncMock(return_value=mock_response) client.handle_response_exception = AsyncMock() client.close = AsyncMock() results = [] - async for item in client.stream("GET", "http://example.com"): + async for item in await client.stream("GET", "http://example.com"): results.append(item) assert results == [{"foo": "bar"}, {"hello": "world"}] @@ -493,11 +479,7 @@ async def iter_chunks(self): mock_response.data = None mock_response.content = FakeContent() - mock_context_manager = AsyncMock() - mock_context_manager.__aenter__.return_value = mock_response - mock_context_manager.__aexit__.return_value = None - - mock_session.request.return_value = mock_context_manager + mock_session.request = AsyncMock(return_value=mock_response) # Make handle_response_exception raise an exception client.handle_response_exception = AsyncMock( @@ -505,10 +487,8 @@ async def iter_chunks(self): ) client.close = AsyncMock() - results = [] with pytest.raises(ServiceException): - async for item in client.stream("GET", "http://example.com"): - results.append(item) + await client.stream("GET", "http://example.com") # The critical assertion: release() must be called even though # handle_response_exception raised ServiceException @@ -542,19 +522,49 @@ async def iter_chunks(self): mock_response.data = None mock_response.content = FakeContent() - mock_context_manager = AsyncMock() - mock_context_manager.__aenter__.return_value = mock_response - mock_context_manager.__aexit__.return_value = None - - mock_session.request.return_value = mock_context_manager + mock_session.request = AsyncMock(return_value=mock_response) client.handle_response_exception = AsyncMock() client.close = AsyncMock() results = [] - async for item in client.stream("GET", "http://example.com"): + async for item in await client.stream("GET", "http://example.com"): results.append(item) assert results == [{"ok": True}] client.handle_response_exception.assert_awaited_once() mock_response.release.assert_called_once() + + +@pytest.mark.asyncio +async def test_stream_releases_conn_when_closed_before_reading(): + """Ensure release() is called when a stream is closed before reading.""" + mock_config = MagicMock() + mock_config.ssl_ca_cert = None + mock_config.cert_file = None + mock_config.key_file = None + mock_config.verify_ssl = True + mock_config.connection_pool_maxsize = 4 + mock_config.proxy = None + mock_config.proxy_headers = None + mock_config.timeout_millisec = 5000 + + client = RESTClientObject(configuration=mock_config) + mock_session = MagicMock() + client.pool_manager = mock_session + + mock_response = MagicMock() + mock_response.status = 200 + mock_response.reason = "OK" + + mock_session.request = AsyncMock(return_value=mock_response) + + client.handle_response_exception = AsyncMock() + client.close = AsyncMock() + + stream = await client.stream("GET", "http://example.com") + mock_response.release.assert_not_called() + + await stream.aclose() + + mock_response.release.assert_called_once() diff --git a/test/sync/oauth2_test.py b/test/sync/oauth2_test.py index 83e15a7d..a0c3a3c9 100644 --- a/test/sync/oauth2_test.py +++ b/test/sync/oauth2_test.py @@ -428,6 +428,50 @@ def test_get_authentication_does_not_retry_501(self, mock_request): self.assertEqual(mock_request.call_count, 1) rest_client.close() + @patch.object(rest.RESTClientObject, "request") + def test_get_authentication_retries_network_errors(self, mock_request): + """ + Token requests that fail with a network error are retried + """ + response_body = '{"expires_in": 120, "access_token": "AABBCCDD"}' + mock_request.side_effect = [ + urllib3.exceptions.ProtocolError("Connection aborted."), + urllib3.exceptions.ConnectTimeoutError(), + mock_response(response_body, 200), + ] + + configuration = Configuration() + rest_client = rest.RESTClientObject(configuration) + client = OAuth2Client(self._client_credentials(), configuration) + + auth_header = client.get_authentication_header(rest_client) + + self.assertEqual(mock_request.call_count, 3) + self.assertEqual(auth_header, {"Authorization": "Bearer AABBCCDD"}) + rest_client.close() + + @patch.object(rest.RESTClientObject, "request") + def test_get_authentication_raises_network_error_when_retries_exhausted( + self, mock_request + ): + """ + After max_retry retries, the last network error is raised + """ + mock_request.side_effect = urllib3.exceptions.ProtocolError( + "Connection aborted." + ) + + configuration = Configuration() + configuration.retry_params.max_retry = 2 + rest_client = rest.RESTClientObject(configuration) + client = OAuth2Client(self._client_credentials(), configuration) + + with self.assertRaises(urllib3.exceptions.ProtocolError): + client.get_authentication_header(rest_client) + + self.assertEqual(mock_request.call_count, 3) + rest_client.close() + @patch.object(rest.RESTClientObject, "request") def test_get_authentication_retries_5xx_responses(self, mock_request): """ diff --git a/test/sync/rest_test.py b/test/sync/rest_test.py index 2df77fd8..d76d1f0d 100644 --- a/test/sync/rest_test.py +++ b/test/sync/rest_test.py @@ -2,7 +2,7 @@ import logging import ssl -from unittest.mock import MagicMock, patch +from unittest.mock import MagicMock, call, patch import pytest @@ -457,6 +457,9 @@ def stream(self, chunk_size): # Single chunk with two JSON lines yield b'{"foo":"bar"}\n{"hello":"world"}' + def close(self): + pass + def release_conn(self): pass @@ -508,6 +511,9 @@ def stream(self, chunk_size): yield b'{"foo":"b' yield b'ar"}\n{"hello":"world"}' + def close(self): + pass + def release_conn(self): pass @@ -558,15 +564,17 @@ def stream(self, chunk_size): # Raise an exception while streaming raise ValueError("Boom!") + def close(self): + pass + def release_conn(self): pass mock_response = FakeHTTPResponse() mock_pool_manager.request.return_value = mock_response - results = list(client.stream("GET", "http://example.com")) - # Exception is logged, we yield nothing - assert results == [] + with pytest.raises(ValueError, match="Boom!"): + list(client.stream("GET", "http://example.com")) mock_pool_manager.request.assert_called_once() @@ -609,8 +617,7 @@ def test_stream_releases_conn_on_error_status(): mock_pool_manager.request.return_value = mock_response with pytest.raises(ServiceException): - # Must consume the generator to trigger the finally block - list(client.stream("GET", "http://example.com")) + client.stream("GET", "http://example.com") # The critical assertion: release_conn() must be called even though # handle_response_exception raised ServiceException @@ -660,6 +667,51 @@ def test_stream_releases_conn_on_success(): mock_response.release_conn.assert_called_once() +def test_stream_closes_response_when_closed_before_reading(): + """Ensure a stream closed before reading closes the response before + releasing it, so a connection with unread data isn't reused.""" + mock_config = MagicMock( + spec=[ + "verify_ssl", + "ssl_ca_cert", + "cert_file", + "key_file", + "assert_hostname", + "retries", + "socket_options", + "connection_pool_maxsize", + "timeout_millisec", + "proxy", + "proxy_headers", + ] + ) + mock_config.ssl_ca_cert = None + mock_config.cert_file = None + mock_config.key_file = None + mock_config.verify_ssl = True + mock_config.connection_pool_maxsize = 4 + mock_config.timeout_millisec = 5000 + mock_config.proxy = None + mock_config.proxy_headers = None + + client = RESTClientObject(configuration=mock_config) + mock_pool_manager = MagicMock() + client.pool_manager = mock_pool_manager + + mock_response = MagicMock() + mock_response.status = 200 + mock_response.reason = "OK" + + mock_pool_manager.request.return_value = mock_response + + stream = client.stream("GET", "http://example.com") + mock_response.release_conn.assert_not_called() + + stream.close() + + assert mock_response.method_calls == [call.close(), call.release_conn()] + + # Tests for SSL Context Reuse (fix for OpenSSL 3.0+ performance issues) @patch("ssl.create_default_context") @patch("urllib3.PoolManager") From 74f37195874339e0580f4d774dd75d71e1eae12f Mon Sep 17 00:00:00 2001 From: SoulPancake Date: Thu, 26 Nov 2026 13:22:12 +0530 Subject: [PATCH 2/2] fix: count every retry attempt, skip TLS retries, cap token backoff Record the request metric for the final failed attempt on network errors and 429/5xx, so the count matches the requests sent. Don't retry aiohttp TLS errors. Cap token retry waits with max_wait_in_sec. Document that a stream holds its connection until exhausted or closed, and add tests for timeouts, Retry-After handling and resend counts. --- openfga_sdk/api_client.py | 30 ++-- openfga_sdk/oauth2.py | 24 ++- openfga_sdk/rest.py | 4 + openfga_sdk/sync/api_client.py | 28 +-- openfga_sdk/sync/oauth2.py | 16 +- openfga_sdk/sync/rest.py | 8 +- test/network_retry_test.py | 309 ++++++++++++++++++++------------- test/oauth2_test.py | 48 ++++- test/sync/oauth2_test.py | 25 +++ 9 files changed, 330 insertions(+), 162 deletions(-) diff --git a/openfga_sdk/api_client.py b/openfga_sdk/api_client.py index 3bbe66c3..8afbd0c1 100644 --- a/openfga_sdk/api_client.py +++ b/openfga_sdk/api_client.py @@ -293,19 +293,19 @@ async def __call_api( _streaming=_streaming, ) except (RateLimitExceededError, ServiceException) as e: - if retry < max_retry and e.status != 501: - _telemetry_attributes = TelemetryAttributes.fromResponse( - response=e.body.decode("utf-8"), - credentials=self.configuration.credentials, - attributes=_telemetry_attributes, - start=start, - ) + _telemetry_attributes = TelemetryAttributes.fromResponse( + response=e.body.decode("utf-8"), + credentials=self.configuration.credentials, + attributes=_telemetry_attributes, + start=start, + ) - self._telemetry.metrics.request( - attributes=_telemetry_attributes, - configuration=self.configuration.telemetry, - ) + self._telemetry.metrics.request( + attributes=_telemetry_attributes, + configuration=self.configuration.telemetry, + ) + if retry < max_retry and e.status != 501: wait_time_in_sec: float try: wait_time_in_sec = self._parse_retry_after_header(e.header) @@ -335,13 +335,10 @@ async def __call_api( if isinstance(operation_name, str): e.operation_name = operation_name.lower() raise e - except aiohttp.ClientConnectorCertificateError: + except aiohttp.ClientSSLError: # Also a network error, but retrying won't fix it raise except rest.NETWORK_ERRORS: - if retry == max_retry: - raise - _telemetry_attributes = TelemetryAttributes.fromResponse( credentials=self.configuration.credentials, attributes=_telemetry_attributes, @@ -353,6 +350,9 @@ async def __call_api( configuration=self.configuration.telemetry, ) + if retry == max_retry: + raise + await asyncio.sleep( min(random_time(retry, min_wait_in_ms), max_wait_in_sec) ) diff --git a/openfga_sdk/oauth2.py b/openfga_sdk/oauth2.py index 178296ae..4c040356 100644 --- a/openfga_sdk/oauth2.py +++ b/openfga_sdk/oauth2.py @@ -10,6 +10,7 @@ from openfga_sdk._version import USER_AGENT from openfga_sdk.configuration import Configuration from openfga_sdk.constants import ( + MAX_BACKOFF_TIME_IN_SEC, TOKEN_EXPIRY_JITTER_IN_SEC, TOKEN_EXPIRY_THRESHOLD_BUFFER_IN_SEC, ) @@ -108,6 +109,15 @@ async def _obtain_token(self, client): else 0 ) + max_wait_in_sec = ( + self.configuration.retry_params.max_wait_in_sec + if ( + self.configuration.retry_params is not None + and self.configuration.retry_params.max_wait_in_sec is not None + ) + else MAX_BACKOFF_TIME_IN_SEC + ) + for attempt in range(max_retry + 1): try: raw_response = await client.request( @@ -124,21 +134,27 @@ async def _obtain_token(self, client): # The REST client raises on 429 and 5xx responses instead of returning them, # so retry here, like the status check below intends. 501 isn't retried. if attempt < max_retry and err.status != 501: - await asyncio.sleep(jitter(attempt, min_wait_in_ms)) + await asyncio.sleep( + min(jitter(attempt, min_wait_in_ms), max_wait_in_sec) + ) continue raise - except aiohttp.ClientConnectorCertificateError: + except aiohttp.ClientSSLError: # Also a network error, but retrying won't fix it raise except NETWORK_ERRORS: if attempt < max_retry: - await asyncio.sleep(jitter(attempt, min_wait_in_ms)) + await asyncio.sleep( + min(jitter(attempt, min_wait_in_ms), max_wait_in_sec) + ) continue raise if 500 <= raw_response.status <= 599 or raw_response.status == 429: if attempt < max_retry and raw_response.status != 501: - await asyncio.sleep(jitter(attempt, min_wait_in_ms)) + await asyncio.sleep( + min(jitter(attempt, min_wait_in_ms), max_wait_in_sec) + ) continue if 200 <= raw_response.status <= 299: diff --git a/openfga_sdk/rest.py b/openfga_sdk/rest.py index a6299fb8..b872fd22 100644 --- a/openfga_sdk/rest.py +++ b/openfga_sdk/rest.py @@ -336,6 +336,10 @@ async def stream( Streams JSON objects from a specified endpoint, handling partial chunks and leftover data at the end of the stream. + The request is sent and the status checked before returning, so errors + raise here. The returned iterator holds the connection until it is + exhausted or closed. + :param method: The HTTP method (GET, POST, etc.). :param url: The endpoint URL. :param query_params: Query parameters to be appended to the URL. diff --git a/openfga_sdk/sync/api_client.py b/openfga_sdk/sync/api_client.py index 453e8169..61b6108d 100644 --- a/openfga_sdk/sync/api_client.py +++ b/openfga_sdk/sync/api_client.py @@ -291,19 +291,19 @@ def __call_api( _streaming=_streaming, ) except (RateLimitExceededError, ServiceException) as e: - if retry < max_retry and e.status != 501: - _telemetry_attributes = TelemetryAttributes.fromResponse( - response=e.body.decode("utf-8"), - credentials=self.configuration.credentials, - attributes=_telemetry_attributes, - start=start, - ) + _telemetry_attributes = TelemetryAttributes.fromResponse( + response=e.body.decode("utf-8"), + credentials=self.configuration.credentials, + attributes=_telemetry_attributes, + start=start, + ) - self._telemetry.metrics.request( - attributes=_telemetry_attributes, - configuration=self.configuration.telemetry, - ) + self._telemetry.metrics.request( + attributes=_telemetry_attributes, + configuration=self.configuration.telemetry, + ) + if retry < max_retry and e.status != 501: wait_time_in_sec: float try: wait_time_in_sec = self._parse_retry_after_header(e.header) @@ -334,9 +334,6 @@ def __call_api( e.operation_name = operation_name.lower() raise except rest.NETWORK_ERRORS: - if retry == max_retry: - raise - _telemetry_attributes = TelemetryAttributes.fromResponse( credentials=self.configuration.credentials, attributes=_telemetry_attributes, @@ -348,6 +345,9 @@ def __call_api( configuration=self.configuration.telemetry, ) + if retry == max_retry: + raise + time.sleep(min(random_time(retry, min_wait_in_ms), max_wait_in_sec)) continue except ApiException as e: diff --git a/openfga_sdk/sync/oauth2.py b/openfga_sdk/sync/oauth2.py index 67154f68..19bb5a22 100644 --- a/openfga_sdk/sync/oauth2.py +++ b/openfga_sdk/sync/oauth2.py @@ -10,6 +10,7 @@ from openfga_sdk._version import USER_AGENT from openfga_sdk.configuration import Configuration from openfga_sdk.constants import ( + MAX_BACKOFF_TIME_IN_SEC, TOKEN_EXPIRY_JITTER_IN_SEC, TOKEN_EXPIRY_THRESHOLD_BUFFER_IN_SEC, ) @@ -108,6 +109,15 @@ def _obtain_token(self, client): else 0 ) + max_wait_in_sec = ( + self.configuration.retry_params.max_wait_in_sec + if ( + self.configuration.retry_params is not None + and self.configuration.retry_params.max_wait_in_sec is not None + ) + else MAX_BACKOFF_TIME_IN_SEC + ) + for attempt in range(max_retry + 1): try: raw_response = client.request( @@ -124,18 +134,18 @@ def _obtain_token(self, client): # The REST client raises on 429 and 5xx responses instead of returning them, # so retry here, like the status check below intends. 501 isn't retried. if attempt < max_retry and err.status != 501: - time.sleep(jitter(attempt, min_wait_in_ms)) + time.sleep(min(jitter(attempt, min_wait_in_ms), max_wait_in_sec)) continue raise except NETWORK_ERRORS: if attempt < max_retry: - time.sleep(jitter(attempt, min_wait_in_ms)) + time.sleep(min(jitter(attempt, min_wait_in_ms), max_wait_in_sec)) continue raise if 500 <= raw_response.status <= 599 or raw_response.status == 429: if attempt < max_retry and raw_response.status != 501: - time.sleep(jitter(attempt, min_wait_in_ms)) + time.sleep(min(jitter(attempt, min_wait_in_ms), max_wait_in_sec)) continue if 200 <= raw_response.status <= 299: diff --git a/openfga_sdk/sync/rest.py b/openfga_sdk/sync/rest.py index 01ce6cc5..6806824c 100644 --- a/openfga_sdk/sync/rest.py +++ b/openfga_sdk/sync/rest.py @@ -23,7 +23,9 @@ logger = logging.getLogger(__name__) -# TimeoutError also covers NewConnectionError and NameResolutionError. +# urllib3 errors retried by the sync client; the async client has its own tuple +# in openfga_sdk.rest. TimeoutError also covers NewConnectionError and +# NameResolutionError. NETWORK_ERRORS = ( urllib3.exceptions.ProtocolError, urllib3.exceptions.ProxyError, @@ -394,6 +396,10 @@ def stream( Streams JSON objects from a specified endpoint, reassembling partial chunks and yielding one decoded object at a time. + The request is sent and the status checked before returning, so errors + raise here. The returned iterator holds the connection until it is + exhausted or closed. + :param method: The HTTP method (GET, POST, etc.). :param url: The endpoint URL. :param query_params: Query parameters to be appended to the URL. diff --git a/test/network_retry_test.py b/test/network_retry_test.py index ac37a38c..3e526c47 100644 --- a/test/network_retry_test.py +++ b/test/network_retry_test.py @@ -1,10 +1,13 @@ +import asyncio import json import socket import ssl +import time +from dataclasses import dataclass, field from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from threading import Thread -from unittest.mock import AsyncMock, MagicMock, patch +from threading import Event, Thread +from unittest.mock import AsyncMock, MagicMock import aiohttp import pytest @@ -13,6 +16,8 @@ from openfga_sdk.api_client import ApiClient as AsyncApiClient from openfga_sdk.configuration import Configuration, RetryParams from openfga_sdk.credentials import CredentialConfiguration, Credentials +from openfga_sdk.exceptions import ServiceException +from openfga_sdk.rest import RESTClientObject as AsyncRESTClientObject from openfga_sdk.sync.api_client import ApiClient as SyncApiClient from openfga_sdk.sync.open_fga_api import OpenFgaApi as SyncOpenFgaApi from openfga_sdk.telemetry.attributes import TelemetryAttributes @@ -22,27 +27,40 @@ CALL_ARGS = {"response_types_map": {}, "_return_http_data_only": True} OBJECTS = [{"result": {"object": f"document:{i}"}} for i in range(3)] NDJSON = b"".join(json.dumps(obj).encode() + b"\n" for obj in OBJECTS) +RETRY_AFTER_IN_SEC = 7 +# The first retry waits random_time(0, min_wait_in_ms) seconds. +MIN_WAIT_IN_SEC = RetryParams().min_wait_in_ms / 1000 # The configured max_retry=1 allows two attempts; the per-call override allows one. exhausted_cases = pytest.mark.parametrize( "retry_params,attempts", - [(None, 2), (RetryParams(max_retry=0), 1)], - ids=["retries-exhausted", "retries-disabled-per-call"], + [ + pytest.param(None, 2, id="retries-exhausted"), + pytest.param(RetryParams(max_retry=0), 1, id="retries-disabled-per-call"), + ], ) -def configuration(url, **kwargs): +def make_configuration(url, **kwargs): return Configuration(api_url=url, retry_params=RetryParams(max_retry=1), **kwargs) +@dataclass +class FakeServer: + url: str + actions: list[str] = field(default_factory=list) + requests: list[str] = field(default_factory=list) + + @pytest.fixture def server(): """ Replies to each request with the next queued action, then with 200: - "drop" closes the connection without a response, "503" sends a 503 and - "truncate" closes the connection after the first chunk of the body. + "drop" closes the connection without a response, "hang" never responds, + "503" sends a 503 with a Retry-After header and "truncate" closes the + connection after the first chunk of the body. """ - actions, requests = [], [] + stopping = Event() class Handler(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" @@ -52,8 +70,11 @@ def log_message(self, format, *args): def _respond(self): self.rfile.read(int(self.headers.get("Content-Length", 0))) - requests.append(self.command) - action = actions.pop(0) if actions else "200" + fake.requests.append(self.command) + action = fake.actions.pop(0) if fake.actions else "200" + if action == "hang": + stopping.wait(5) + action = "drop" if action == "drop": self.close_connection = True return @@ -61,6 +82,8 @@ def _respond(self): self.send_response(503 if action == "503" else 200) self.send_header("Content-Type", "application/json") self.send_header("Transfer-Encoding", "chunked") + if action == "503": + self.send_header("Retry-After", str(RETRY_AFTER_IN_SEC)) self.end_headers() for line in (b"{}" if action == "503" else NDJSON).splitlines(True): self.wfile.write(b"%x\r\n%s\r\n" % (len(line), line)) @@ -72,193 +95,247 @@ def _respond(self): do_GET = do_POST = _respond with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as httpd: + fake = FakeServer(url=f"http://127.0.0.1:{httpd.server_port}") thread = Thread( target=httpd.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True ) thread.start() try: - yield f"http://127.0.0.1:{httpd.server_port}", actions, requests + yield fake finally: + stopping.set() httpd.shutdown() thread.join() @pytest.fixture -def resend_counts(): +def sleeps(monkeypatch): + """Skips time.sleep and asyncio.sleep; the list records the requested waits.""" + waits = [] + + async def async_sleep(seconds): + waits.append(seconds) + + monkeypatch.setattr(time, "sleep", waits.append) + monkeypatch.setattr(asyncio, "sleep", async_sleep) + return waits + + +@pytest.fixture +def resend_counts(monkeypatch): """The http.request.resend_count of every request metric recorded.""" counts = [] def request(self, attributes, configuration=None): counts.append(attributes[TelemetryAttributes.http_request_resend_count]) - with patch.object(TelemetryMetrics, "request", request): - yield counts + monkeypatch.setattr(TelemetryMetrics, "request", request) + return counts @pytest.mark.asyncio -async def test_async_retries_dropped_connection(server, resend_counts): - url, actions, requests = server - actions.append("drop") - with patch("asyncio.sleep", new_callable=AsyncMock) as sleep: - async with AsyncApiClient(configuration(url)) as client: - await client.call_api("/check", "POST", **CALL_ARGS) +async def test_async_retries_dropped_connection(server, sleeps, resend_counts): + server.actions.append("drop") + async with AsyncApiClient(make_configuration(server.url)) as client: + await client.call_api("/check", "POST", **CALL_ARGS) + + assert server.requests == ["POST", "POST"] + assert resend_counts == [0, 1] + assert len(sleeps) == 1 + assert MIN_WAIT_IN_SEC <= sleeps[0] < 2 * MIN_WAIT_IN_SEC + + +def test_sync_retries_dropped_connection(server, sleeps, resend_counts): + server.actions.append("drop") + with SyncApiClient(make_configuration(server.url)) as client: + client.call_api("/check", "POST", **CALL_ARGS) + + assert server.requests == ["POST", "POST"] + assert resend_counts == [0, 1] + assert len(sleeps) == 1 + assert MIN_WAIT_IN_SEC <= sleeps[0] < 2 * MIN_WAIT_IN_SEC + + +@pytest.mark.asyncio +async def test_async_retries_timeout(server, sleeps, resend_counts): + server.actions.append("hang") + configuration = make_configuration(server.url, timeout_millisec=200) + async with AsyncApiClient(configuration) as client: + await client.call_api("/check", "POST", **CALL_ARGS) - assert requests == ["POST", "POST"] + assert server.requests == ["POST", "POST"] assert resend_counts == [0, 1] - sleep.assert_awaited_once() -def test_sync_retries_dropped_connection(server, resend_counts): - url, actions, requests = server - actions.append("drop") - with patch("time.sleep") as sleep, SyncApiClient(configuration(url)) as client: +def test_sync_retries_timeout(server, sleeps, resend_counts): + server.actions.append("hang") + configuration = make_configuration(server.url, timeout_millisec=200) + with SyncApiClient(configuration) as client: client.call_api("/check", "POST", **CALL_ARGS) - assert requests == ["POST", "POST"] + assert server.requests == ["POST", "POST"] assert resend_counts == [0, 1] - sleep.assert_called_once() +# Every attempt is recorded, including the last failed one. +@pytest.mark.parametrize( + "failure,error", + [ + pytest.param("drop", aiohttp.ServerDisconnectedError, id="network"), + pytest.param("503", ServiceException, id="status"), + ], +) @exhausted_cases @pytest.mark.asyncio -async def test_async_raises_network_error_when_out_of_retries( - server, retry_params, attempts +async def test_async_raises_when_out_of_retries( + server, sleeps, resend_counts, failure, error, retry_params, attempts ): - url, actions, requests = server - actions.extend(["drop"] * attempts) - with patch("asyncio.sleep", new_callable=AsyncMock): - async with AsyncApiClient(configuration(url)) as client: - with pytest.raises(aiohttp.ServerDisconnectedError): - await client.call_api( - "/check", "POST", _retry_params=retry_params, **CALL_ARGS - ) + server.actions.extend([failure] * attempts) + async with AsyncApiClient(make_configuration(server.url)) as client: + with pytest.raises(error): + await client.call_api( + "/check", "POST", _retry_params=retry_params, **CALL_ARGS + ) - assert requests == ["POST"] * attempts + assert server.requests == ["POST"] * attempts + assert resend_counts == list(range(attempts)) # urllib3 would otherwise resend the GET on its own. +@pytest.mark.parametrize( + "failure,error", + [ + pytest.param("drop", urllib3.exceptions.ProtocolError, id="network"), + pytest.param("503", ServiceException, id="status"), + ], +) @exhausted_cases -def test_sync_raises_network_error_when_out_of_retries(server, retry_params, attempts): - url, actions, requests = server - actions.extend(["drop"] * attempts) - with ( - patch("time.sleep"), - SyncApiClient(configuration(url)) as client, - pytest.raises(urllib3.exceptions.ProtocolError), - ): - client.call_api("/stores", "GET", _retry_params=retry_params, **CALL_ARGS) +def test_sync_raises_when_out_of_retries( + server, sleeps, resend_counts, failure, error, retry_params, attempts +): + server.actions.extend([failure] * attempts) + with SyncApiClient(make_configuration(server.url)) as client: + with pytest.raises(error): + client.call_api("/stores", "GET", _retry_params=retry_params, **CALL_ARGS) - assert requests == ["GET"] * attempts + assert server.requests == ["GET"] * attempts + assert resend_counts == list(range(attempts)) -def test_sync_retries_unreachable_proxy(): +# With its default Retry, urllib3 would retry a GET that got a 503 with a +# Retry-After header itself, sleeping for the uncapped header value each time. +def test_sync_only_sdk_handles_retry_after(server, sleeps, monkeypatch): + urllib3_sleep = MagicMock() + monkeypatch.setattr(urllib3.Retry, "sleep", urllib3_sleep) + server.actions.append("503") + with SyncApiClient(make_configuration(server.url)) as client: + client.call_api("/stores", "GET", **CALL_ARGS) + + assert server.requests == ["GET", "GET"] + assert sleeps == [RETRY_AFTER_IN_SEC] + urllib3_sleep.assert_not_called() + + +def test_sync_retries_unreachable_proxy(sleeps): with socket.socket() as sock: sock.bind(("127.0.0.1", 0)) port = sock.getsockname()[1] - config = configuration("http://fga.example") - config.proxy = f"http://127.0.0.1:{port}" - with ( - patch("time.sleep") as sleep, - SyncApiClient(config) as client, - pytest.raises(urllib3.exceptions.ProxyError), - ): - client.call_api("/check", "POST", **CALL_ARGS) + configuration = make_configuration("http://fga.example") + configuration.proxy = f"http://127.0.0.1:{port}" + with SyncApiClient(configuration) as client: + with pytest.raises(urllib3.exceptions.ProxyError): + client.call_api("/check", "POST", **CALL_ARGS) - sleep.assert_called_once() + assert len(sleeps) == 1 +@pytest.mark.parametrize( + "error", + [ + pytest.param( + aiohttp.ClientConnectorCertificateError( + MagicMock(), ssl.SSLCertVerificationError("certificate verify failed") + ), + id="certificate", + ), + pytest.param( + aiohttp.ClientConnectorSSLError(MagicMock(), ssl.SSLError("wrong version")), + id="handshake", + ), + ], +) @pytest.mark.asyncio -async def test_async_does_not_retry_certificate_errors(): - error = aiohttp.ClientConnectorCertificateError( - MagicMock(), ssl.SSLCertVerificationError("certificate verify failed") - ) - with ( - patch("asyncio.sleep", new_callable=AsyncMock) as sleep, - patch( - "openfga_sdk.rest.RESTClientObject.request", side_effect=error - ) as request, - ): - async with AsyncApiClient(configuration("https://fga.example")) as client: - with pytest.raises(aiohttp.ClientConnectorCertificateError): - await client.call_api("/check", "POST", **CALL_ARGS) +async def test_async_does_not_retry_tls_errors(sleeps, monkeypatch, error): + request = AsyncMock(side_effect=error) + monkeypatch.setattr(AsyncRESTClientObject, "request", request) + async with AsyncApiClient(make_configuration("https://fga.example")) as client: + with pytest.raises(type(error)): + await client.call_api("/check", "POST", **CALL_ARGS) - request.assert_called_once() - sleep.assert_not_awaited() + request.assert_awaited_once() + assert sleeps == [] # max_retry=1 allows two token requests; the default would allow four. -def test_sync_token_request_uses_client_retry_params(server): - url, actions, requests = server - actions.extend(["drop"] * 4) +def test_sync_token_request_uses_client_retry_params(server, sleeps): + server.actions.extend(["drop"] * 4) credentials = Credentials( method="client_credentials", configuration=CredentialConfiguration( client_id="client-id", client_secret="client-secret", - api_issuer=f"{url}/oauth/token", + api_issuer=f"{server.url}/oauth/token", api_audience="audience", ), ) - with ( - patch("time.sleep"), - SyncApiClient(configuration(url, credentials=credentials)) as client, - pytest.raises(urllib3.exceptions.ProtocolError), - ): - SyncOpenFgaApi(client).list_stores() + configuration = make_configuration(server.url, credentials=credentials) + with SyncApiClient(configuration) as client: + with pytest.raises(urllib3.exceptions.ProtocolError): + SyncOpenFgaApi(client).list_stores() - assert requests == ["POST", "POST"] + assert server.requests == ["POST", "POST"] @pytest.mark.parametrize("failure", ["drop", "503"]) @pytest.mark.asyncio -async def test_async_stream_retries_until_connected(server, failure): - url, actions, requests = server - actions.append(failure) - with patch("asyncio.sleep", new_callable=AsyncMock): - async with AsyncApiClient(configuration(url)) as client: - stream = await client.call_api( - "/stream", "POST", _streaming=True, **CALL_ARGS - ) - received = [obj async for obj in stream] +async def test_async_stream_retries_until_connected(server, sleeps, failure): + server.actions.append(failure) + async with AsyncApiClient(make_configuration(server.url)) as client: + stream = await client.call_api("/stream", "POST", _streaming=True, **CALL_ARGS) + received = [obj async for obj in stream] assert received == OBJECTS - assert requests == ["POST", "POST"] + assert server.requests == ["POST", "POST"] @pytest.mark.parametrize("failure", ["drop", "503"]) -def test_sync_stream_retries_until_connected(server, failure): - url, actions, requests = server - actions.append(failure) - with patch("time.sleep"), SyncApiClient(configuration(url)) as client: +def test_sync_stream_retries_until_connected(server, sleeps, failure): + server.actions.append(failure) + with SyncApiClient(make_configuration(server.url)) as client: stream = client.call_api("/stream", "POST", _streaming=True, **CALL_ARGS) received = list(stream) assert received == OBJECTS - assert requests == ["POST", "POST"] + assert server.requests == ["POST", "POST"] @pytest.mark.asyncio -async def test_async_stream_raises_without_retry_once_connected(server): - url, actions, requests = server - actions.append("truncate") - with patch("asyncio.sleep", new_callable=AsyncMock): - async with AsyncApiClient(configuration(url)) as client: - stream = await client.call_api( - "/stream", "POST", _streaming=True, **CALL_ARGS - ) - with pytest.raises(aiohttp.ClientPayloadError): - [obj async for obj in stream] +async def test_async_stream_raises_without_retry_once_connected(server, sleeps): + server.actions.append("truncate") + async with AsyncApiClient(make_configuration(server.url)) as client: + stream = await client.call_api("/stream", "POST", _streaming=True, **CALL_ARGS) + with pytest.raises(aiohttp.ClientPayloadError): + [obj async for obj in stream] - assert requests == ["POST"] + assert server.requests == ["POST"] -def test_sync_stream_raises_without_retry_once_connected(server): - url, actions, requests = server - actions.append("truncate") - with patch("time.sleep"), SyncApiClient(configuration(url)) as client: +def test_sync_stream_raises_without_retry_once_connected(server, sleeps): + server.actions.append("truncate") + with SyncApiClient(make_configuration(server.url)) as client: stream = client.call_api("/stream", "POST", _streaming=True, **CALL_ARGS) with pytest.raises(urllib3.exceptions.ProtocolError): list(stream) - assert requests == ["POST"] + assert server.requests == ["POST"] diff --git a/test/oauth2_test.py b/test/oauth2_test.py index 233431ee..2049f51c 100644 --- a/test/oauth2_test.py +++ b/test/oauth2_test.py @@ -360,24 +360,54 @@ async def test_get_authentication_raises_network_error_when_retries_exhausted( await rest_client.close() @patch.object(rest.RESTClientObject, "request") - async def test_get_authentication_does_not_retry_certificate_errors( - self, mock_request + async def test_get_authentication_does_not_retry_tls_errors(self, mock_request): + """ + Certificate and other TLS errors are raised without retrying + """ + errors = [ + aiohttp.ClientConnectorCertificateError( + MagicMock(), ssl.SSLCertVerificationError("certificate verify failed") + ), + aiohttp.ClientConnectorSSLError(MagicMock(), ssl.SSLError("wrong version")), + ] + for error in errors: + with self.subTest(error=type(error).__name__): + mock_request.reset_mock() + mock_request.side_effect = error + + configuration = Configuration() + rest_client = rest.RESTClientObject(configuration) + client = OAuth2Client(self._client_credentials(), configuration) + + with self.assertRaises(type(error)): + await client.get_authentication_header(rest_client) + + self.assertEqual(mock_request.call_count, 1) + await rest_client.close() + + @patch.object(rest.RESTClientObject, "request") + @patch("openfga_sdk.oauth2.jitter", return_value=10_000) + @patch("asyncio.sleep") + async def test_get_authentication_caps_retry_wait( + self, mock_sleep, mock_jitter, mock_request ): """ - Certificate errors are raised without retrying + The wait between token requests is capped by max_wait_in_sec """ - mock_request.side_effect = aiohttp.ClientConnectorCertificateError( - MagicMock(), ssl.SSLCertVerificationError("certificate verify failed") - ) + response_body = '{"expires_in": 120, "access_token": "AABBCCDD"}' + mock_request.side_effect = [ + aiohttp.ServerDisconnectedError(), + mock_response(response_body, 200), + ] configuration = Configuration() + configuration.retry_params.max_wait_in_sec = 7 rest_client = rest.RESTClientObject(configuration) client = OAuth2Client(self._client_credentials(), configuration) - with self.assertRaises(aiohttp.ClientConnectorCertificateError): - await client.get_authentication_header(rest_client) + await client.get_authentication_header(rest_client) - self.assertEqual(mock_request.call_count, 1) + mock_sleep.assert_awaited_once_with(7) await rest_client.close() @patch.object(rest.RESTClientObject, "request") diff --git a/test/sync/oauth2_test.py b/test/sync/oauth2_test.py index a0c3a3c9..455d87a0 100644 --- a/test/sync/oauth2_test.py +++ b/test/sync/oauth2_test.py @@ -472,6 +472,31 @@ def test_get_authentication_raises_network_error_when_retries_exhausted( self.assertEqual(mock_request.call_count, 3) rest_client.close() + @patch.object(rest.RESTClientObject, "request") + @patch("openfga_sdk.sync.oauth2.jitter", return_value=10_000) + @patch("time.sleep") + def test_get_authentication_caps_retry_wait( + self, mock_sleep, mock_jitter, mock_request + ): + """ + The wait between token requests is capped by max_wait_in_sec + """ + response_body = '{"expires_in": 120, "access_token": "AABBCCDD"}' + mock_request.side_effect = [ + urllib3.exceptions.ProtocolError("Connection aborted."), + mock_response(response_body, 200), + ] + + configuration = Configuration() + configuration.retry_params.max_wait_in_sec = 7 + rest_client = rest.RESTClientObject(configuration) + client = OAuth2Client(self._client_credentials(), configuration) + + client.get_authentication_header(rest_client) + + mock_sleep.assert_called_once_with(7) + rest_client.close() + @patch.object(rest.RESTClientObject, "request") def test_get_authentication_retries_5xx_responses(self, mock_request): """