diff --git a/README.md b/README.md index da4473d..78113dd 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 e010e30..8afbd0c 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 @@ -291,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) @@ -333,6 +335,29 @@ async def __call_api( if isinstance(operation_name, str): e.operation_name = operation_name.lower() raise e + except aiohttp.ClientSSLError: + # Also a network error, but retrying won't fix it + raise + except rest.NETWORK_ERRORS: + _telemetry_attributes = TelemetryAttributes.fromResponse( + credentials=self.configuration.credentials, + attributes=_telemetry_attributes, + start=start, + ) + + self._telemetry.metrics.request( + attributes=_telemetry_attributes, + configuration=self.configuration.telemetry, + ) + + if retry == max_retry: + raise + + 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 02f8e5e..bc015d7 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 084b497..4c04035 100644 --- a/openfga_sdk/oauth2.py +++ b/openfga_sdk/oauth2.py @@ -4,11 +4,13 @@ from datetime import datetime, timedelta +import aiohttp import urllib3 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, ) @@ -19,6 +21,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 @@ -106,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( @@ -122,13 +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.ClientSSLError: + # Also a network error, but retrying won't fix it + raise + except NETWORK_ERRORS: + if attempt < max_retry: + 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 00ee8ad..b872fd2 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): """ @@ -329,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. @@ -336,7 +347,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 +362,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 +412,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 1d9e23c..61b6108 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) @@ -333,6 +333,23 @@ def __call_api( if isinstance(operation_name, str): e.operation_name = operation_name.lower() raise + except rest.NETWORK_ERRORS: + _telemetry_attributes = TelemetryAttributes.fromResponse( + credentials=self.configuration.credentials, + attributes=_telemetry_attributes, + start=start, + ) + + self._telemetry.metrics.request( + attributes=_telemetry_attributes, + 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: 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 afc0800..19bb5a2 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, ) @@ -20,6 +21,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 @@ -107,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( @@ -123,13 +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(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/open_fga_api.py b/openfga_sdk/sync/open_fga_api.py index 8518138..efe7d38 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 dd2f098..6806824 100644 --- a/openfga_sdk/sync/rest.py +++ b/openfga_sdk/sync/rest.py @@ -23,6 +23,15 @@ logger = logging.getLogger(__name__) +# 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, + urllib3.exceptions.TimeoutError, +) + class RESTResponse(io.IOBase): """ @@ -168,10 +177,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 ( @@ -386,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. @@ -393,7 +407,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 +422,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 +455,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 +466,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 0000000..3e526c4 --- /dev/null +++ b/test/network_retry_test.py @@ -0,0 +1,341 @@ +import asyncio +import json +import socket +import ssl +import time + +from dataclasses import dataclass, field +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from threading import Event, Thread +from unittest.mock import AsyncMock, MagicMock + +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.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 +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) +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", + [ + pytest.param(None, 2, id="retries-exhausted"), + pytest.param(RetryParams(max_retry=0), 1, id="retries-disabled-per-call"), + ], +) + + +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, "hang" never responds, + "503" sends a 503 with a Retry-After header and "truncate" closes the + connection after the first chunk of the body. + """ + stopping = Event() + + 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))) + 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 + + 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)) + 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: + 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 fake + finally: + stopping.set() + httpd.shutdown() + thread.join() + + +@pytest.fixture +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]) + + monkeypatch.setattr(TelemetryMetrics, "request", request) + return counts + + +@pytest.mark.asyncio +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 server.requests == ["POST", "POST"] + assert resend_counts == [0, 1] + + +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 server.requests == ["POST", "POST"] + assert resend_counts == [0, 1] + + +# 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_when_out_of_retries( + server, sleeps, resend_counts, failure, error, retry_params, attempts +): + 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 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_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 server.requests == ["GET"] * attempts + assert resend_counts == list(range(attempts)) + + +# 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] + + 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) + + 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_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_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, sleeps): + server.actions.extend(["drop"] * 4) + credentials = Credentials( + method="client_credentials", + configuration=CredentialConfiguration( + client_id="client-id", + client_secret="client-secret", + api_issuer=f"{server.url}/oauth/token", + api_audience="audience", + ), + ) + configuration = make_configuration(server.url, credentials=credentials) + with SyncApiClient(configuration) as client: + with pytest.raises(urllib3.exceptions.ProtocolError): + SyncOpenFgaApi(client).list_stores() + + assert server.requests == ["POST", "POST"] + + +@pytest.mark.parametrize("failure", ["drop", "503"]) +@pytest.mark.asyncio +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 server.requests == ["POST", "POST"] + + +@pytest.mark.parametrize("failure", ["drop", "503"]) +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 server.requests == ["POST", "POST"] + + +@pytest.mark.asyncio +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 server.requests == ["POST"] + + +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 server.requests == ["POST"] diff --git a/test/oauth2_test.py b/test/oauth2_test.py index f677d36..2049f51 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,99 @@ 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_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 + ): + """ + The wait between token requests is capped by max_wait_in_sec + """ + 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) + + await client.get_authentication_header(rest_client) + + mock_sleep.assert_awaited_once_with(7) + 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 1609989..5139858 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 83e15a7..455d87a 100644 --- a/test/sync/oauth2_test.py +++ b/test/sync/oauth2_test.py @@ -428,6 +428,75 @@ 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") + @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): """ diff --git a/test/sync/rest_test.py b/test/sync/rest_test.py index 2df77fd..d76d1f0 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")