Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The documented aiohttp replay still bypasses the per-call retry budget in #342. With aiohttp 3.14.5, a dropped async GET sent two requests and succeeded even with RetryParams(max_retry=0). Disable aiohttp's replay for SDK-managed requests and add an async GET regression test that asserts exactly one request with retries disabled. The current async exhaustion test only covers POST.


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`.

Expand Down
49 changes: 37 additions & 12 deletions openfga_sdk/api_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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,
Expand Down
5 changes: 3 additions & 2 deletions openfga_sdk/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
30 changes: 28 additions & 2 deletions openfga_sdk/oauth2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
Expand All @@ -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

Expand Down Expand Up @@ -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(
Expand All @@ -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:
Comment thread
SoulPancake marked this conversation as resolved.
Resolved
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:
Expand Down
80 changes: 44 additions & 36 deletions openfga_sdk/rest.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import asyncio
import io
import json
import logging
Expand All @@ -23,6 +24,12 @@

logger = logging.getLogger(__name__)

NETWORK_ERRORS = (
aiohttp.ClientConnectionError,
aiohttp.ClientPayloadError,
asyncio.TimeoutError,
)


class RESTResponse(io.IOBase):
"""
Expand Down Expand Up @@ -329,14 +336,18 @@ 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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Closing the REST iterator works, but closing the public stream after one item still leaves the connection checked out. Both OpenFgaClient.streamed_list_objects() wrappers and async execute_streamed_api_request() do not forward close to the inner iterator, which ApiClient.last_response keeps alive. Use closing/aclosing around the inner iterators (including the async API wrapper), and assert that closing the public stream immediately releases the response.


:param method: The HTTP method (GET, POST, etc.).
:param url: The endpoint URL.
:param query_params: Query parameters to be appended to the URL.
:param headers: Optional headers to include in the request.
: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
Expand All @@ -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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The returned generator is already advanced. If the caller never iterates or closes it, the response is only released on GC. Document that it must be consumed or closed, or wrap it with aclose and __del__.

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:
Expand All @@ -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,
Expand Down
39 changes: 28 additions & 11 deletions openfga_sdk/sync/api_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
Loading