diff --git a/CHANGELOG.md b/CHANGELOG.md index 118abe1..adab232 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,20 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## Unreleased +A new client setting turns the automatic retries off. Behaviour is unchanged +unless it is set. + +### Added + +- **`max_retries` and `retry_wait_seconds`** on both clients, on + `GLPITokenManager` and `GLPIV1Session`, and as `GLPI_MAX_RETRIES` and + `GLPI_RETRY_WAIT_SECONDS` for `from_env`. `max_retries` counts the retries + after the first attempt: the default `2` keeps today's 3 attempts, `0` + disables retrying, so a failing call raises after exactly one request. + `retry_wait_seconds` is the pause between attempts (default 3 seconds). The + setting applies to every retried call: the v2 verbs, the v1 session helpers + and OAuth token acquisition. Which errors are retried (network faults and + 5xx) is unchanged. ### Fixed - **Concurrent renewals of the legacy v1 session.** A client shared by diff --git a/docs/user_guide.rst b/docs/user_guide.rst index 41de66a..dc27f50 100644 --- a/docs/user_guide.rst +++ b/docs/user_guide.rst @@ -117,6 +117,10 @@ Optional constructor arguments ``"en_GB"``). * ``verify_ssl`` — set to ``False`` only on test instances with self-signed certificates. +* ``max_retries`` — automatic retries after the first attempt (default + ``2``, so 3 attempts in total); ``0`` disables retrying. See + :ref:`retry-behaviour`. +* ``retry_wait_seconds`` — pause between two attempts (default 3 seconds). * ``auth_token_refresh`` — number of seconds before token expiry at which the auth manager proactively refreshes the OAuth access token. * ``v1_base_url`` and ``v1_user_token`` — together enable the legacy v1 @@ -142,6 +146,7 @@ build the client for you: offset. There is no default: guessing UTC against a Europe/Paris instance shifts those values by an hour or two and never raises. * ``GLPI_LANGUAGE``, ``GLPI_VERIFY_SSL`` +* ``GLPI_MAX_RETRIES``, ``GLPI_RETRY_WAIT_SECONDS`` -- see :ref:`retry-behaviour`. * ``GLPI_V1_BASE_URL``, ``GLPI_V1_USER_TOKEN``, ``GLPI_V1_APP_TOKEN`` .. code-block:: python @@ -1776,7 +1781,8 @@ Connection failures, DNS errors and timeouts are translated into :class:`~glpi_python_client.GlpiTimeoutError` subclass for a timeout -- so you never need to import the HTTP library to catch them. The original transport exception stays attached as ``__cause__`` for debugging, and -these faults are retried three times before they surface: +these faults are retried (three attempts by default, see +:ref:`retry-behaviour`) before they surface: .. code-block:: python @@ -1806,7 +1812,7 @@ The hierarchy lets you narrow as far as you need: ├── GlpiStatusError GLPI answered with an unexpected status │ ├── GlpiAuthError 401 / 403 │ ├── GlpiNotFoundError 404 - │ └── GlpiServerError 5xx (retried up to 3 attempts before it + │ └── GlpiServerError 5xx (retried, 3 attempts by default, before it │ reaches you) ├── GlpiValidationError the client rejected your argument ├── GlpiProtocolError GLPI answered 2xx with an unusable body @@ -2222,27 +2228,44 @@ definition list's newline becomes a hard break. Bold inside bold link or image title loses a backslash before punctuation. The caption, colgroup and image-title shapes above settle too, on what they already lost. +.. _retry-behaviour: + Retry behaviour ~~~~~~~~~~~~~~~ -Each transport and v1-session retry decorator retries a server error -(5xx) up to 3 attempts with a 3-second fixed wait before -:class:`~glpi_python_client.GlpiServerError` reaches you. Client errors -(4xx) are never retried — they cannot succeed on a second attempt. +Every v2 verb, every v1-session helper and OAuth token acquisition retry a +network fault (:class:`~glpi_python_client.GlpiTransportError`) or a server +error (5xx, :class:`~glpi_python_client.GlpiServerError`) before it reaches +you. Client errors (4xx) are never retried — they cannot succeed on a second +attempt. The two client settings below govern all of these calls alike, +token acquisition included; which errors are retried does not depend on them: + +* ``max_retries`` — retries after the first attempt. The default ``2`` makes + 3 attempts in total; ``0`` disables retrying, so a failing call raises after + exactly one request. Use ``0`` when your own code owns the retry policy: a + retried write may already have been applied. +* ``retry_wait_seconds`` — fixed pause between two attempts (default 3 + seconds; ``None`` keeps it). + +.. code-block:: python + + client = GlpiClient.from_env(max_retries=0) # or GLPI_MAX_RETRIES=0 + +The counts below are those of the default setting (3 attempts). -OAuth token acquisition follows the same 3-attempt policy, with one +OAuth token acquisition follows the same policy, with one exception: refreshing an already-issued token does not raise directly on a failed response. It logs a warning and falls through to a fresh token -acquisition, which carries its own independent 3-attempt retry -decorator. The refresh method's own retry decorator only retries a +acquisition, which carries its own independent retry decorator. The +refresh method's own retry decorator only retries a network-level fault on the refresh request itself (a :class:`~glpi_python_client.GlpiTransportError` raised before any response is received) — it does **not** retry a :class:`~glpi_python_client.GlpiServerError` from the fall-through, since that failure is already being retried by the nested acquisition call. A persistent 5xx encountered while -refreshing therefore costs exactly 1 refresh POST + up to 3 nested -acquisition POSTs = 4 POST requests before +refreshing therefore costs, with the default setting, exactly 1 refresh +POST + up to 3 nested acquisition POSTs = 4 POST requests before :class:`~glpi_python_client.GlpiServerError` reaches you. A rejected credential (401/403) is not retried at either layer and fails after at most 2 POST requests. diff --git a/glpi_python_client/_async/_retry.py b/glpi_python_client/_async/_retry.py new file mode 100644 index 0000000..75ea326 --- /dev/null +++ b/glpi_python_client/_async/_retry.py @@ -0,0 +1,90 @@ +"""Configurable retry policy shared by the v2 transport, v1 session and OAuth. + +Every network-facing helper of the client retries a transient failure. The +policy is a per-client setting, not a decorator fixed at import time, so the +decorator built here reads two attributes from the object it decorates: + +``_max_retries`` + Retries after the first attempt. ``0`` disables retrying. +``_retry_wait_seconds`` + Fixed pause between attempts; ``None`` selects + :data:`DEFAULT_RETRY_WAIT_SECONDS`. + +Which errors are retried is decided by each call site (``retry_on``), not by +the setting. +""" + +from __future__ import annotations + +import functools +from collections.abc import Callable +from typing import Any, TypeVar, cast + +from tenacity import ( + AsyncRetrying, + retry_if_exception_type, + stop_after_attempt, + wait_fixed, +) + +from glpi_python_client._errors import GlpiValidationError + +#: Retries after the first attempt (3 attempts in total). +DEFAULT_MAX_RETRIES = 2 + +#: Seconds between two attempts when no wait is configured. +DEFAULT_RETRY_WAIT_SECONDS = 3.0 + +F = TypeVar("F", bound=Callable[..., Any]) + + +def validate_retry_settings( + max_retries: object, retry_wait_seconds: object +) -> tuple[int, float | None]: + """Return the validated ``(max_retries, retry_wait_seconds)`` pair. + + Raises + ------ + GlpiValidationError + If ``max_retries`` is not an integer >= 0, or ``retry_wait_seconds`` + is neither ``None`` nor a number >= 0. + """ + + if ( + isinstance(max_retries, bool) + or not isinstance(max_retries, int) + or max_retries < 0 + ): + raise GlpiValidationError("max_retries must be an integer >= 0") + if retry_wait_seconds is not None and ( + isinstance(retry_wait_seconds, bool) + or not isinstance(retry_wait_seconds, int | float) + or retry_wait_seconds < 0 + ): + raise GlpiValidationError("retry_wait_seconds must be a number >= 0 or None") + return max_retries, retry_wait_seconds + + +def retried( + retry_on: type[BaseException] | tuple[type[BaseException], ...], +) -> Callable[[F], F]: + """Retry the decorated method on ``retry_on`` per its instance's policy. + + The final error is re-raised as-is, never as ``tenacity.RetryError``. + """ + + def decorator(func: F) -> F: + @functools.wraps(func) + async def wrapper(self: Any, *args: Any, **kwargs: Any) -> Any: + wait = self._retry_wait_seconds + retrying = AsyncRetrying( + retry=retry_if_exception_type(retry_on), + stop=stop_after_attempt(self._max_retries + 1), + wait=wait_fixed(DEFAULT_RETRY_WAIT_SECONDS if wait is None else wait), + reraise=True, + ) + return await retrying(func, self, *args, **kwargs) + + return cast(F, wrapper) + + return decorator diff --git a/glpi_python_client/_async/auth/_v1_session.py b/glpi_python_client/_async/auth/_v1_session.py index 99f8ef8..9b9ac2c 100644 --- a/glpi_python_client/_async/auth/_v1_session.py +++ b/glpi_python_client/_async/auth/_v1_session.py @@ -20,7 +20,9 @@ ------------ Every public dispatch helper (``_init_session``, ``request_json``, ``upload_document``) carries the same :mod:`tenacity` retry decorator -used by the v2 transport: three attempts spaced by three seconds, +used by the v2 transport: by default three attempts spaced by three +seconds (the ``max_retries`` and ``retry_wait_seconds`` client settings, +``max_retries=0`` disables retrying), triggered by :class:`~glpi_python_client.GlpiTransportError` (network faults) and :class:`~glpi_python_client.GlpiServerError` (which @@ -44,9 +46,13 @@ from typing import Any, cast import httpx -from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_fixed from glpi_python_client._async._concurrency import Lock +from glpi_python_client._async._retry import ( + DEFAULT_MAX_RETRIES, + retried, + validate_retry_settings, +) from glpi_python_client._async.clients.commons._config import build_http_session from glpi_python_client._async.clients.commons._http import ( ensure_response_status, @@ -70,12 +76,7 @@ #: Mirrors the v2 transport policy deliberately: naming the HTTP library's #: own exception base here would make the retries stop matching — silently — #: the next time the transport changes. -_RETRY_ON_NETWORK_ERRORS = retry( - retry=retry_if_exception_type((GlpiTransportError, GlpiServerError)), - stop=stop_after_attempt(3), - wait=wait_fixed(3), - reraise=True, -) +_RETRY_ON_NETWORK_ERRORS = retried((GlpiTransportError, GlpiServerError)) class GLPIV1Session: @@ -96,10 +97,15 @@ def __init__( session_refresh_interval_seconds: int = ( _DEFAULT_SESSION_REFRESH_INTERVAL_SECONDS ), + max_retries: int = DEFAULT_MAX_RETRIES, + retry_wait_seconds: float | None = None, ) -> None: self._base_url = base_url.rstrip("/") self._user_token = user_token self._app_token = app_token + self._max_retries, self._retry_wait_seconds = validate_retry_settings( + max_retries, retry_wait_seconds + ) if session_refresh_interval_seconds < 1: raise GlpiValidationError( "session_refresh_interval_seconds must be a positive integer" diff --git a/glpi_python_client/_async/auth/auth.py b/glpi_python_client/_async/auth/auth.py index 64d7c32..a49a7f5 100644 --- a/glpi_python_client/_async/auth/auth.py +++ b/glpi_python_client/_async/auth/auth.py @@ -11,8 +11,12 @@ from datetime import UTC, datetime, timedelta import httpx -from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_fixed +from glpi_python_client._async._retry import ( + DEFAULT_MAX_RETRIES, + retried, + validate_retry_settings, +) from glpi_python_client._async.clients.commons._config import build_http_session from glpi_python_client._async.clients.commons._http import transport_error_from from glpi_python_client._errors import ( @@ -114,6 +118,12 @@ class GLPITokenManager: auth_token_refresh : int | None, optional Maximum token age in seconds before a refresh is attempted. ``None`` disables interval-based refreshes. + max_retries : int, optional + Retries after the first attempt of a failed token request + (network fault or 5xx); ``0`` disables retrying. Defaults to 2, + that is 3 attempts in total. + retry_wait_seconds : float | None, optional + Pause between two attempts; ``None`` keeps the 3-second default. """ def __init__( @@ -125,7 +135,12 @@ def __init__( password: str | None = None, session: httpx.AsyncClient | None = None, auth_token_refresh: int | None = None, + max_retries: int = DEFAULT_MAX_RETRIES, + retry_wait_seconds: float | None = None, ) -> None: + self._max_retries, self._retry_wait_seconds = validate_retry_settings( + max_retries, retry_wait_seconds + ) self._token_url = token_url self._client_id = client_id self._client_secret = client_secret @@ -284,12 +299,7 @@ def _should_refresh_by_interval(self, now: datetime) -> bool: return False return now >= self.token_updated_at + self._auth_token_refresh_interval - @retry( - retry=retry_if_exception_type((GlpiTransportError, GlpiServerError)), - stop=stop_after_attempt(3), - wait=wait_fixed(3), - reraise=True, - ) + @retried((GlpiTransportError, GlpiServerError)) async def _acquire_token(self) -> None: """Acquire an OAuth2 access token using the configured auth flow. @@ -303,7 +313,8 @@ async def _acquire_token(self) -> None: GlpiAuthError If GLPI rejects the credentials (401/403). Not retried. GlpiServerError - If the token endpoint fails (5xx). Retried up to 3 attempts. + If the token endpoint fails (5xx). Retried up to ``max_retries`` times + (3 attempts by default). GlpiStatusError If the token endpoint returns any other unexpected status. Not retried. @@ -326,12 +337,7 @@ async def _acquire_token(self) -> None: response_text=str(error_detail), ) - @retry( - retry=retry_if_exception_type(GlpiTransportError), - stop=stop_after_attempt(3), - wait=wait_fixed(3), - reraise=True, - ) + @retried(GlpiTransportError) async def _refresh_access_token(self) -> None: """Refresh the OAuth2 access token using the stored refresh token. @@ -356,7 +362,8 @@ async def _refresh_access_token(self) -> None: ``GlpiServerError``, so it does not retry the fall-through to :meth:`_acquire_token`. The nested call carries its own independent decorator, which does retry ``GlpiServerError`` up - to 3 attempts. A persistent 5xx therefore costs exactly 1 + to ``max_retries`` + 1 attempts (3 by default). A persistent 5xx + therefore costs (with the default setting) exactly 1 refresh POST + 3 nested acquire POSTs = 4 POST requests, not the 12 an earlier, less precise predicate produced by retrying the already-retried nested failure a second time. diff --git a/glpi_python_client/_async/auth/tests/test_auth.py b/glpi_python_client/_async/auth/tests/test_auth.py index b7050e2..f59d0c6 100644 --- a/glpi_python_client/_async/auth/tests/test_auth.py +++ b/glpi_python_client/_async/auth/tests/test_auth.py @@ -5,7 +5,6 @@ import httpx import pytest -from tenacity import wait_fixed from glpi_python_client import ( GlpiAuthError, @@ -243,12 +242,9 @@ async def test_oauth_401_is_not_retried() -> None: assert len(session.calls) == 1 -async def test_oauth_5xx_raises_glpi_server_error_after_retries( - monkeypatch: pytest.MonkeyPatch, -) -> None: +async def test_oauth_5xx_raises_glpi_server_error_after_retries() -> None: """A 5xx from the token endpoint is retried, then reraised as-is.""" - monkeypatch.setattr(GLPITokenManager._acquire_token.retry, "wait", wait_fixed(0)) session = _FakeSession(response=TokenResponse(status_code=503, payload={})) manager = GLPITokenManager( token_url="https://glpi.example.test/api.php/token", @@ -287,9 +283,7 @@ def _make_refresh_ready_manager( return manager -async def test_refresh_401_stays_final_with_one_nested_acquire_call( - monkeypatch: pytest.MonkeyPatch, -) -> None: +async def test_refresh_401_stays_final_with_one_nested_acquire_call() -> None: """A 4xx during refresh is not retried by either decorator. ``_refresh_access_token`` does not raise directly on a non-2xx response: @@ -302,10 +296,6 @@ async def test_refresh_401_stays_final_with_one_nested_acquire_call( of multiplying further (contrast with the 5xx case below). """ - monkeypatch.setattr(GLPITokenManager._acquire_token.retry, "wait", wait_fixed(0)) - monkeypatch.setattr( - GLPITokenManager._refresh_access_token.retry, "wait", wait_fixed(0) - ) session = _FakeSession( response=TokenResponse(status_code=401, payload={"error": "invalid_grant"}) ) @@ -320,15 +310,14 @@ async def test_refresh_401_stays_final_with_one_nested_acquire_call( assert len(session.calls) == 2 -async def test_refresh_5xx_persistent_costs_one_refresh_plus_nested_acquire_attempts( - monkeypatch: pytest.MonkeyPatch, -) -> None: +async def test_refresh_5xx_persistent_costs_one_refresh_plus_nested_acquires() -> None: """A persistent 5xx during refresh costs 4 POSTs, not 12. ``_refresh_access_token`` falls through to a *nested* ``_acquire_token()`` call on any non-2xx response instead of raising directly - (auth.py:327-332). That nested call is independently decorated with - ``stop_after_attempt(3)`` and retries ``GlpiServerError``. This method's + (auth.py:327-332). That nested call is independently retried per + the ``max_retries`` setting (3 attempts by default) and retries + ``GlpiServerError``. This method's own decorator only matches ``httpx.HTTPError`` (a genuine network fault on the refresh POST itself), not ``GlpiServerError``, so it does not retry the fall-through a second time on top of the nested @@ -342,10 +331,6 @@ async def test_refresh_5xx_persistent_costs_one_refresh_plus_nested_acquire_atte silently reintroduce the multiplication. """ - monkeypatch.setattr(GLPITokenManager._acquire_token.retry, "wait", wait_fixed(0)) - monkeypatch.setattr( - GLPITokenManager._refresh_access_token.retry, "wait", wait_fixed(0) - ) session = _FakeSession(response=TokenResponse(status_code=503, payload={})) manager = _make_refresh_ready_manager(session) @@ -356,9 +341,7 @@ async def test_refresh_5xx_persistent_costs_one_refresh_plus_nested_acquire_atte assert len(session.calls) == 4 -async def test_acquire_token_network_error_is_retried_three_times( - monkeypatch: pytest.MonkeyPatch, -) -> None: +async def test_acquire_token_network_error_is_retried_three_times() -> None: """A connection-level failure (no HTTP response at all) is retried. Mirrors ``test_network_errors_are_still_retried`` in @@ -366,8 +349,6 @@ async def test_acquire_token_network_error_is_retried_three_times( covers the OAuth token path, which previously had no equivalent test. """ - monkeypatch.setattr(GLPITokenManager._acquire_token.retry, "wait", wait_fixed(0)) - class _FailingSession: def __init__(self) -> None: self.calls: list[dict[str, object]] = [] @@ -392,9 +373,7 @@ async def post( assert len(session.calls) == 3 -async def test_refresh_network_error_is_retried_three_times( - monkeypatch: pytest.MonkeyPatch, -) -> None: +async def test_refresh_network_error_is_retried_three_times() -> None: """A connection-level failure during refresh is retried by refresh's own decorator. Pins the one predicate member not yet covered by another test: @@ -414,10 +393,6 @@ async def test_refresh_network_error_is_retried_three_times( it with every other test still green. """ - monkeypatch.setattr( - GLPITokenManager._refresh_access_token.retry, "wait", wait_fixed(0) - ) - class _FailingSession: def __init__(self) -> None: self.calls: list[dict[str, object]] = [] diff --git a/glpi_python_client/_async/auth/tests/test_v1_session.py b/glpi_python_client/_async/auth/tests/test_v1_session.py index effda30..aee9523 100644 --- a/glpi_python_client/_async/auth/tests/test_v1_session.py +++ b/glpi_python_client/_async/auth/tests/test_v1_session.py @@ -7,7 +7,6 @@ import httpx import pytest -from tenacity import wait_fixed from glpi_python_client import ( GlpiProtocolError, @@ -26,19 +25,6 @@ ) -@pytest.fixture(autouse=True) -def _no_sleep(monkeypatch: pytest.MonkeyPatch) -> None: - """Drop the 3s fixed wait so retry tests stay instant. - - Each decorated method's own ``Retrying`` object is patched directly. - Patching ``tenacity.nap.time.sleep`` would work today but silently stops - working on the async path, so it is deliberately not used here. - """ - - for name in _RETRIED_METHODS: - monkeypatch.setattr(getattr(GLPIV1Session, name).retry, "wait", wait_fixed(0)) - - class _FakeV1Http: """In-memory HTTP client stand-in capturing every call.""" diff --git a/glpi_python_client/_async/clients/_base_client.py b/glpi_python_client/_async/clients/_base_client.py index 8591f32..0203ab2 100644 --- a/glpi_python_client/_async/clients/_base_client.py +++ b/glpi_python_client/_async/clients/_base_client.py @@ -16,6 +16,10 @@ from typing import TYPE_CHECKING, Self from glpi_python_client._async._concurrency import Lock +from glpi_python_client._async._retry import ( + DEFAULT_MAX_RETRIES, + validate_retry_settings, +) from glpi_python_client._async.clients.commons._config import ( build_client_env_config, build_client_resources, @@ -55,6 +59,8 @@ def __init__( v1_base_url: str | None = None, v1_user_token: str | None = None, v1_app_token: str | None = None, + max_retries: int = DEFAULT_MAX_RETRIES, + retry_wait_seconds: float | None = None, ) -> None: """Build the shared resources for a GLPI client. @@ -111,6 +117,17 @@ def __init__( ``user_token`` for the v1 fallback session. v1_app_token : str | None, optional ``app_token`` for the v1 fallback session. + max_retries : int, optional + Automatic retries after the first attempt of a call that failed on + a network fault (``GlpiTransportError``) or a 5xx answer + (``GlpiServerError``): ``0`` disables retrying, the default ``2`` + makes 3 attempts in total. It applies to every v2 verb, the v1 + session helpers and OAuth token acquisition. A retried write may + already have been applied; pass ``0`` when the caller owns its + own retry policy. + retry_wait_seconds : float | None, optional + Pause between two attempts; ``None`` keeps the default of 3 + seconds. Raises ------ @@ -120,6 +137,9 @@ def __init__( """ self.server_timezone = resolve_server_timezone(server_timezone) + self._max_retries, self._retry_wait_seconds = validate_retry_settings( + max_retries, retry_wait_seconds + ) resources = build_client_resources( glpi_api_url=glpi_api_url, client_name=type(self).__name__, @@ -132,6 +152,8 @@ def __init__( v1_base_url=v1_base_url, v1_user_token=v1_user_token, v1_app_token=v1_app_token, + max_retries=self._max_retries, + retry_wait_seconds=self._retry_wait_seconds, ) self.glpi_api_url = resources.glpi_api_url self._session = resources.session @@ -160,7 +182,8 @@ def from_env( ``GLPI_V1_BASE_URL``, ``GLPI_V1_USER_TOKEN``, ``GLPI_V1_APP_TOKEN``, ``GLPI_ENTITY``, ``GLPI_PROFILE``, ``GLPI_ENTITY_RECURSIVE``, ``GLPI_LANGUAGE``, ``GLPI_AUTH_TOKEN_REFRESH``, - ``GLPI_SERVER_TIMEZONE``). + ``GLPI_SERVER_TIMEZONE``, ``GLPI_MAX_RETRIES``, + ``GLPI_RETRY_WAIT_SECONDS``). Parameters ---------- diff --git a/glpi_python_client/_async/clients/commons/_config.py b/glpi_python_client/_async/clients/commons/_config.py index 0236345..b9287f1 100644 --- a/glpi_python_client/_async/clients/commons/_config.py +++ b/glpi_python_client/_async/clients/commons/_config.py @@ -15,6 +15,7 @@ import httpx +from glpi_python_client._async._retry import DEFAULT_MAX_RETRIES from glpi_python_client._errors import GlpiValidationError if TYPE_CHECKING: @@ -112,6 +113,8 @@ def build_client_resources( v1_base_url: str | None, v1_user_token: str | None, v1_app_token: str | None, + max_retries: int = DEFAULT_MAX_RETRIES, + retry_wait_seconds: float | None = None, session_factory: SessionFactory | None = None, ) -> ClientResources: """Build the shared resources required by one client instance. @@ -166,6 +169,8 @@ def build_client_resources( password=password, session=session, auth_token_refresh=auth_token_refresh, + max_retries=max_retries, + retry_wait_seconds=retry_wait_seconds, ) v1: GLPIV1Session | None = None @@ -174,6 +179,8 @@ def build_client_resources( base_url=v1_base_url, user_token=v1_user_token, app_token=v1_app_token, + max_retries=max_retries, + retry_wait_seconds=retry_wait_seconds, verify_ssl=verify_ssl, ) @@ -272,6 +279,34 @@ def parse_optional_env_int(value: object) -> int | None: raise TypeError("Integer environment values must be strings or integers") +def parse_optional_env_float(value: object) -> float | None: + """Parse one optional number from an environment-style value. + + ``None`` is preserved, native numbers are accepted as-is and strings are + converted through ``float()``. + + Raises + ------ + GlpiValidationError + If a string value cannot be parsed as a number. + TypeError + If ``value`` is neither ``None``, a number, nor ``str``. + """ + + if value is None: + return None + if isinstance(value, int | float) and not isinstance(value, bool): + return float(value) + if isinstance(value, str): + try: + return float(value) + except ValueError as exc: + raise GlpiValidationError( + f"Invalid number environment value: {value!r}" + ) from exc + raise TypeError("Number environment values must be strings or numbers") + + def parse_optional_env_bool(value: object, *, default: bool) -> bool: """Parse one optional boolean from an environment-style value. @@ -330,6 +365,13 @@ def build_client_env_config( "v1_user_token": env.get(f"{prefix}V1_USER_TOKEN"), "v1_app_token": env.get(f"{prefix}V1_APP_TOKEN"), } + # Absent keys keep the constructor defaults (3 attempts, 3 s apart). + max_retries = parse_optional_env_int(env.get(f"{prefix}MAX_RETRIES")) + if max_retries is not None: + config["max_retries"] = max_retries + retry_wait = parse_optional_env_float(env.get(f"{prefix}RETRY_WAIT_SECONDS")) + if retry_wait is not None: + config["retry_wait_seconds"] = retry_wait config.update(overrides) return config diff --git a/glpi_python_client/_async/clients/commons/_transport.py b/glpi_python_client/_async/clients/commons/_transport.py index a0706c3..957de25 100644 --- a/glpi_python_client/_async/clients/commons/_transport.py +++ b/glpi_python_client/_async/clients/commons/_transport.py @@ -30,9 +30,9 @@ from typing import TYPE_CHECKING, Any, TypeVar import httpx -from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_fixed from glpi_python_client._async._concurrency import Lock +from glpi_python_client._async._retry import DEFAULT_MAX_RETRIES, retried from glpi_python_client._async.clients.commons._http import ( build_request_headers, build_request_url, @@ -72,12 +72,11 @@ #: :func:`~glpi_python_client._async.clients.commons._http.transport_error_from` #: guarantees every network fault is translated into, makes that failure #: impossible to reintroduce. -_RETRY_ON_NETWORK_ERRORS = retry( - retry=retry_if_exception_type((GlpiTransportError, GlpiServerError)), - stop=stop_after_attempt(3), - wait=wait_fixed(3), - reraise=True, -) +#: +#: How many times, and how long apart, is the client's ``max_retries`` and +#: ``retry_wait_seconds`` setting (read per call from ``self``); by default 3 +#: attempts in total, 3 s apart, and ``max_retries=0`` disables retrying. +_RETRY_ON_NETWORK_ERRORS = retried((GlpiTransportError, GlpiServerError)) class TransportMixin: @@ -102,6 +101,8 @@ class TransportMixin: _auth: GLPITokenManager _auth_lock: Lock _closed: bool = False + _max_retries: int = DEFAULT_MAX_RETRIES + _retry_wait_seconds: float | None = None _session: httpx.AsyncClient _v1: GLPIV1Session | None entity_recursive: bool @@ -313,7 +314,8 @@ async def _get_request( Network errors (:class:`~glpi_python_client.GlpiTransportError`) and 5xx responses (:class:`~glpi_python_client.GlpiServerError`) are - retried up to 3 times, with ``reraise=True`` so the real error + retried up to ``max_retries`` times (by default 2, so 3 attempts in + total; ``0`` disables retrying), with ``reraise=True`` so the real error propagates once retries are exhausted; 4xx responses are returned as-is without a retry. """ diff --git a/glpi_python_client/_async/clients/commons/tests/test_transport.py b/glpi_python_client/_async/clients/commons/tests/test_transport.py index 677f0c5..353798a 100644 --- a/glpi_python_client/_async/clients/commons/tests/test_transport.py +++ b/glpi_python_client/_async/clients/commons/tests/test_transport.py @@ -19,10 +19,8 @@ import httpx import pytest -from tenacity import wait_fixed from glpi_python_client import ( - AsyncGlpiClient, GlpiError, GlpiServerError, GlpiStatusError, @@ -233,19 +231,6 @@ async def _send(method: str, url: str, **kw: Any) -> FakeResponse: # rather than reusing ``transport_client``. -@pytest.fixture(autouse=True) -def _no_retry_sleep(monkeypatch: pytest.MonkeyPatch) -> None: - """Drop the 3s fixed wait so retry tests stay instant. - - The decorator's ``Retrying`` object is patched directly. Patching - ``tenacity.nap.time.sleep`` would work today but silently stops working - on the async path, so it is deliberately not used here. - """ - - for name in _RETRIED_METHODS: - monkeypatch.setattr(getattr(AsyncGlpiClient, name).retry, "wait", wait_fixed(0)) - - @pytest.fixture async def retry_client() -> AsyncIterator[Any]: """Return a client with auth stubbed so no token call is made.""" diff --git a/glpi_python_client/_async/conftest.py b/glpi_python_client/_async/conftest.py index 93fd730..0cdc568 100644 --- a/glpi_python_client/_async/conftest.py +++ b/glpi_python_client/_async/conftest.py @@ -11,9 +11,17 @@ import pytest from glpi_python_client import AsyncGlpiClient +from glpi_python_client._async import _retry from glpi_python_client._async._testing import make_client +@pytest.fixture(autouse=True) +def _no_retry_wait(monkeypatch: pytest.MonkeyPatch) -> None: + """Drop the default 3 s pause between retry attempts so tests stay instant.""" + + monkeypatch.setattr(_retry, "DEFAULT_RETRY_WAIT_SECONDS", 0.0) + + @pytest.fixture async def client() -> AsyncIterator[AsyncGlpiClient]: """Yield a default in-memory client and close it afterwards.""" diff --git a/glpi_python_client/_async/tests/test_concurrency.py b/glpi_python_client/_async/tests/test_concurrency.py index 46b6062..6cb3f8f 100644 --- a/glpi_python_client/_async/tests/test_concurrency.py +++ b/glpi_python_client/_async/tests/test_concurrency.py @@ -183,8 +183,6 @@ async def _boom(method: str, url: str, **kwargs: Any) -> _Response: raise httpx.ConnectError("network down") client._session.request = _boom # type: ignore[method-assign,assignment] - # Keep the retry from spending 6 real seconds on the way to failing. - client._get_request.retry.wait = lambda *a, **k: 0 # type: ignore[attr-defined] try: with pytest.raises(GlpiTransportError) as excinfo: await client.get_ticket(1) @@ -203,7 +201,6 @@ async def _slow(method: str, url: str, **kwargs: Any) -> _Response: raise httpx.ConnectTimeout("too slow") client._session.request = _slow # type: ignore[method-assign,assignment] - client._get_request.retry.wait = lambda *a, **k: 0 # type: ignore[attr-defined] try: with pytest.raises(GlpiTimeoutError): await client.get_ticket(1) diff --git a/glpi_python_client/_async/tests/test_retry_settings.py b/glpi_python_client/_async/tests/test_retry_settings.py new file mode 100644 index 0000000..b5a73ba --- /dev/null +++ b/glpi_python_client/_async/tests/test_retry_settings.py @@ -0,0 +1,275 @@ +"""The retry setting: ``max_retries`` and ``retry_wait_seconds``. + +The default (two retries after the first attempt, 3 s apart) reproduces the +historical behaviour of three attempts in total; ``max_retries=0`` turns +retrying off for every retried call: the v2 verbs, the v1 session helpers and +the OAuth token manager. +""" + +from __future__ import annotations + +from typing import Any + +import httpx +import pytest + +from glpi_python_client import ( + AsyncGlpiClient, + GlpiServerError, + GlpiTransportError, + GlpiValidationError, +) +from glpi_python_client._async import _retry +from glpi_python_client._async._testing import make_client +from glpi_python_client._async.auth._v1_session import GLPIV1Session +from glpi_python_client._async.auth.auth import GLPITokenManager +from glpi_python_client.testing.utils import FakeResponse + +_VERBS = ("_get_request", "_post_request", "_update_request", "_delete_request") + + +def _stub_send(client: Any, *, status: int | None, attempts: list[int]) -> None: + """Make every request attempt record itself, then fail as asked.""" + + async def _ensure_token() -> None: + return None + + async def _send(method: str, url: str, **kw: Any) -> FakeResponse: + attempts.append(1) + if status is None: + raise GlpiTransportError("network down") + return FakeResponse(status_code=status, payload={}, text="x", reason="r") + + client._auth.access_token = "test-token" + client._auth.ensure_token = _ensure_token + client._send_request = _send + + +@pytest.mark.parametrize("verb", _VERBS) +@pytest.mark.parametrize("status", [500, None]) +async def test_disabled_retries_send_one_request(verb: str, status: int | None) -> None: + """With ``max_retries=0`` a 5xx or a transport error costs one request.""" + + client = make_client(max_retries=0) + attempts: list[int] = [] + _stub_send(client, status=status, attempts=attempts) + expected = GlpiServerError if status else GlpiTransportError + try: + with pytest.raises(expected): + await getattr(client, verb)("Assistance/Ticket") + finally: + await client.close() + assert len(attempts) == 1 + + +@pytest.mark.parametrize("verb", _VERBS) +@pytest.mark.parametrize("status", [500, None]) +async def test_default_retries_make_three_attempts( + verb: str, status: int | None +) -> None: + """Without the setting the same call is attempted three times.""" + + client = make_client() + attempts: list[int] = [] + _stub_send(client, status=status, attempts=attempts) + expected = GlpiServerError if status else GlpiTransportError + try: + with pytest.raises(expected): + await getattr(client, verb)("Assistance/Ticket") + finally: + await client.close() + assert len(attempts) == 3 + + +async def test_max_retries_counts_retries_after_the_first_attempt() -> None: + client = make_client(max_retries=4) + attempts: list[int] = [] + _stub_send(client, status=503, attempts=attempts) + try: + with pytest.raises(GlpiServerError): + await client._get_request("Assistance/Ticket") + finally: + await client.close() + assert len(attempts) == 5 + + +async def test_4xx_is_still_not_retried() -> None: + """Which errors are retried does not depend on the setting.""" + + client = make_client(max_retries=5) + attempts: list[int] = [] + _stub_send(client, status=404, attempts=attempts) + try: + response = await client._get_request("Assistance/Ticket") + finally: + await client.close() + assert response.status_code == 404 + assert len(attempts) == 1 + + +def _spy_on_wait(monkeypatch: pytest.MonkeyPatch) -> list[float]: + """Record every wait the retry policy builds, without really waiting.""" + + waits: list[float] = [] + real = _retry.wait_fixed + + def _spy(seconds: float) -> Any: + waits.append(seconds) + return real(0) + + monkeypatch.setattr(_retry, "wait_fixed", _spy) + return waits + + +async def test_the_configured_wait_separates_attempts( + monkeypatch: pytest.MonkeyPatch, +) -> None: + waits = _spy_on_wait(monkeypatch) + client = make_client(retry_wait_seconds=7) + _stub_send(client, status=500, attempts=[]) + try: + with pytest.raises(GlpiServerError): + await client._get_request("Assistance/Ticket") + finally: + await client.close() + assert waits == [7] + + +async def test_the_default_wait_is_three_seconds( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # Undo the suite-wide zero wait so the real default is what gets built. + monkeypatch.setattr(_retry, "DEFAULT_RETRY_WAIT_SECONDS", 3.0) + waits = _spy_on_wait(monkeypatch) + client = make_client() + _stub_send(client, status=500, attempts=[]) + try: + with pytest.raises(GlpiServerError): + await client._get_request("Assistance/Ticket") + finally: + await client.close() + assert waits == [3.0] + assert _retry.DEFAULT_MAX_RETRIES == 2 + + +def _v1_session(handler: Any, **kwargs: Any) -> GLPIV1Session: + session = GLPIV1Session( + base_url="https://glpi.example.test/apirest.php", + user_token="user-token", + **kwargs, + ) + session._http = httpx.AsyncClient(transport=httpx.MockTransport(handler)) + return session + + +@pytest.mark.parametrize(("retries", "expected"), [(0, 1), (None, 3)]) +async def test_the_setting_reaches_a_v1_helper( + retries: int | None, expected: int +) -> None: + calls: list[str] = [] + + def handler(request: httpx.Request) -> httpx.Response: + calls.append(request.url.path) + if request.url.path.endswith("/initSession"): + return httpx.Response(200, json={"session_token": "tk"}) + return httpx.Response(500, json={}) + + kwargs = {} if retries is None else {"max_retries": retries} + session = _v1_session(handler, **kwargs) + try: + with pytest.raises(GlpiServerError): + await session.request_json("GET", "/Ticket/1") + finally: + await session._http.aclose() + assert len([c for c in calls if c.endswith("/Ticket/1")]) == expected + + +async def test_the_setting_reaches_the_v1_init_session() -> None: + calls: list[str] = [] + + def handler(request: httpx.Request) -> httpx.Response: + calls.append(request.url.path) + return httpx.Response(503, json={}) + + session = _v1_session(handler, max_retries=0) + try: + with pytest.raises(GlpiServerError): + await session._init_session() + finally: + await session._http.aclose() + assert len(calls) == 1 + + +@pytest.mark.parametrize(("retries", "expected"), [(0, 1), (None, 3)]) +async def test_the_setting_reaches_the_token_manager( + retries: int | None, expected: int +) -> None: + calls: list[int] = [] + + def handler(request: httpx.Request) -> httpx.Response: + calls.append(1) + return httpx.Response(503, json={}) + + kwargs = {} if retries is None else {"max_retries": retries} + http = httpx.AsyncClient(transport=httpx.MockTransport(handler)) + manager = GLPITokenManager( + token_url="https://glpi.example.test/api.php/token", + username="u", + password="p", + session=http, + **kwargs, + ) + try: + with pytest.raises(GlpiServerError): + await manager.ensure_token() + finally: + await http.aclose() + assert len(calls) == expected + + +async def test_the_client_hands_the_setting_to_its_collaborators() -> None: + client = make_client( + max_retries=1, + retry_wait_seconds=2, + v1_base_url="https://glpi.example.test/apirest.php", + v1_user_token="user-token", + ) + try: + assert client._max_retries == 1 + assert client._auth._max_retries == 1 + assert client._v1 is not None + assert client._v1._max_retries == 1 + assert client._v1._retry_wait_seconds == 2 + assert client._auth._retry_wait_seconds == 2 + finally: + await client.close() + + +async def test_from_env_reads_the_setting() -> None: + client = AsyncGlpiClient.from_env( + env={ + "GLPI_API_URL": "https://glpi.example.test/api.php/v2", + "GLPI_CLIENT_ID": "i", + "GLPI_CLIENT_SECRET": "s", + "GLPI_SERVER_TIMEZONE": "Europe/Paris", + "GLPI_MAX_RETRIES": "0", + "GLPI_RETRY_WAIT_SECONDS": "0.5", + } + ) + try: + assert client._max_retries == 0 + assert client._retry_wait_seconds == 0.5 + finally: + await client.close() + + +@pytest.mark.parametrize("bad", [-1, True, 1.5, "2"]) +async def test_a_bad_max_retries_is_rejected(bad: object) -> None: + with pytest.raises(GlpiValidationError): + make_client(max_retries=bad) + + +@pytest.mark.parametrize("bad", [-1, True, "3"]) +async def test_a_bad_retry_wait_is_rejected(bad: object) -> None: + with pytest.raises(GlpiValidationError): + make_client(retry_wait_seconds=bad) diff --git a/glpi_python_client/_errors.py b/glpi_python_client/_errors.py index a04bff3..bb03dc2 100644 --- a/glpi_python_client/_errors.py +++ b/glpi_python_client/_errors.py @@ -44,7 +44,8 @@ class GlpiTransportError(GlpiError): back-compatibility argument that applies to the status and validation errors does not apply here. - Network faults are retried before they surface -- three attempts -- so + Network faults are retried before they surface -- three attempts by + default (see the ``max_retries`` client setting) -- so receiving this means the fault persisted. """ diff --git a/glpi_python_client/_sync/_retry.py b/glpi_python_client/_sync/_retry.py new file mode 100644 index 0000000..57ffb3a --- /dev/null +++ b/glpi_python_client/_sync/_retry.py @@ -0,0 +1,90 @@ +"""Configurable retry policy shared by the v2 transport, v1 session and OAuth. + +Every network-facing helper of the client retries a transient failure. The +policy is a per-client setting, not a decorator fixed at import time, so the +decorator built here reads two attributes from the object it decorates: + +``_max_retries`` + Retries after the first attempt. ``0`` disables retrying. +``_retry_wait_seconds`` + Fixed pause between attempts; ``None`` selects + :data:`DEFAULT_RETRY_WAIT_SECONDS`. + +Which errors are retried is decided by each call site (``retry_on``), not by +the setting. +""" + +from __future__ import annotations + +import functools +from collections.abc import Callable +from typing import Any, TypeVar, cast + +from tenacity import ( + Retrying, + retry_if_exception_type, + stop_after_attempt, + wait_fixed, +) + +from glpi_python_client._errors import GlpiValidationError + +#: Retries after the first attempt (3 attempts in total). +DEFAULT_MAX_RETRIES = 2 + +#: Seconds between two attempts when no wait is configured. +DEFAULT_RETRY_WAIT_SECONDS = 3.0 + +F = TypeVar("F", bound=Callable[..., Any]) + + +def validate_retry_settings( + max_retries: object, retry_wait_seconds: object +) -> tuple[int, float | None]: + """Return the validated ``(max_retries, retry_wait_seconds)`` pair. + + Raises + ------ + GlpiValidationError + If ``max_retries`` is not an integer >= 0, or ``retry_wait_seconds`` + is neither ``None`` nor a number >= 0. + """ + + if ( + isinstance(max_retries, bool) + or not isinstance(max_retries, int) + or max_retries < 0 + ): + raise GlpiValidationError("max_retries must be an integer >= 0") + if retry_wait_seconds is not None and ( + isinstance(retry_wait_seconds, bool) + or not isinstance(retry_wait_seconds, int | float) + or retry_wait_seconds < 0 + ): + raise GlpiValidationError("retry_wait_seconds must be a number >= 0 or None") + return max_retries, retry_wait_seconds + + +def retried( + retry_on: type[BaseException] | tuple[type[BaseException], ...], +) -> Callable[[F], F]: + """Retry the decorated method on ``retry_on`` per its instance's policy. + + The final error is re-raised as-is, never as ``tenacity.RetryError``. + """ + + def decorator(func: F) -> F: + @functools.wraps(func) + def wrapper(self: Any, *args: Any, **kwargs: Any) -> Any: + wait = self._retry_wait_seconds + retrying = Retrying( + retry=retry_if_exception_type(retry_on), + stop=stop_after_attempt(self._max_retries + 1), + wait=wait_fixed(DEFAULT_RETRY_WAIT_SECONDS if wait is None else wait), + reraise=True, + ) + return retrying(func, self, *args, **kwargs) + + return cast(F, wrapper) + + return decorator diff --git a/glpi_python_client/_sync/auth/_v1_session.py b/glpi_python_client/_sync/auth/_v1_session.py index 1f0d3a5..39e9801 100644 --- a/glpi_python_client/_sync/auth/_v1_session.py +++ b/glpi_python_client/_sync/auth/_v1_session.py @@ -20,7 +20,9 @@ ------------ Every public dispatch helper (``_init_session``, ``request_json``, ``upload_document``) carries the same :mod:`tenacity` retry decorator -used by the v2 transport: three attempts spaced by three seconds, +used by the v2 transport: by default three attempts spaced by three +seconds (the ``max_retries`` and ``retry_wait_seconds`` client settings, +``max_retries=0`` disables retrying), triggered by :class:`~glpi_python_client.GlpiTransportError` (network faults) and :class:`~glpi_python_client.GlpiServerError` (which @@ -44,9 +46,13 @@ from typing import Any, cast import httpx -from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_fixed from glpi_python_client._sync._concurrency import Lock +from glpi_python_client._sync._retry import ( + DEFAULT_MAX_RETRIES, + retried, + validate_retry_settings, +) from glpi_python_client._sync.clients.commons._config import build_http_session from glpi_python_client._sync.clients.commons._http import ( ensure_response_status, @@ -70,12 +76,7 @@ #: Mirrors the v2 transport policy deliberately: naming the HTTP library's #: own exception base here would make the retries stop matching — silently — #: the next time the transport changes. -_RETRY_ON_NETWORK_ERRORS = retry( - retry=retry_if_exception_type((GlpiTransportError, GlpiServerError)), - stop=stop_after_attempt(3), - wait=wait_fixed(3), - reraise=True, -) +_RETRY_ON_NETWORK_ERRORS = retried((GlpiTransportError, GlpiServerError)) class GLPIV1Session: @@ -96,10 +97,15 @@ def __init__( session_refresh_interval_seconds: int = ( _DEFAULT_SESSION_REFRESH_INTERVAL_SECONDS ), + max_retries: int = DEFAULT_MAX_RETRIES, + retry_wait_seconds: float | None = None, ) -> None: self._base_url = base_url.rstrip("/") self._user_token = user_token self._app_token = app_token + self._max_retries, self._retry_wait_seconds = validate_retry_settings( + max_retries, retry_wait_seconds + ) if session_refresh_interval_seconds < 1: raise GlpiValidationError( "session_refresh_interval_seconds must be a positive integer" diff --git a/glpi_python_client/_sync/auth/auth.py b/glpi_python_client/_sync/auth/auth.py index a4ba60f..b77763d 100644 --- a/glpi_python_client/_sync/auth/auth.py +++ b/glpi_python_client/_sync/auth/auth.py @@ -11,8 +11,12 @@ from datetime import UTC, datetime, timedelta import httpx -from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_fixed +from glpi_python_client._sync._retry import ( + DEFAULT_MAX_RETRIES, + retried, + validate_retry_settings, +) from glpi_python_client._sync.clients.commons._config import build_http_session from glpi_python_client._sync.clients.commons._http import transport_error_from from glpi_python_client._errors import ( @@ -114,6 +118,12 @@ class GLPITokenManager: auth_token_refresh : int | None, optional Maximum token age in seconds before a refresh is attempted. ``None`` disables interval-based refreshes. + max_retries : int, optional + Retries after the first attempt of a failed token request + (network fault or 5xx); ``0`` disables retrying. Defaults to 2, + that is 3 attempts in total. + retry_wait_seconds : float | None, optional + Pause between two attempts; ``None`` keeps the 3-second default. """ def __init__( @@ -125,7 +135,12 @@ def __init__( password: str | None = None, session: httpx.Client | None = None, auth_token_refresh: int | None = None, + max_retries: int = DEFAULT_MAX_RETRIES, + retry_wait_seconds: float | None = None, ) -> None: + self._max_retries, self._retry_wait_seconds = validate_retry_settings( + max_retries, retry_wait_seconds + ) self._token_url = token_url self._client_id = client_id self._client_secret = client_secret @@ -284,12 +299,7 @@ def _should_refresh_by_interval(self, now: datetime) -> bool: return False return now >= self.token_updated_at + self._auth_token_refresh_interval - @retry( - retry=retry_if_exception_type((GlpiTransportError, GlpiServerError)), - stop=stop_after_attempt(3), - wait=wait_fixed(3), - reraise=True, - ) + @retried((GlpiTransportError, GlpiServerError)) def _acquire_token(self) -> None: """Acquire an OAuth2 access token using the configured auth flow. @@ -303,7 +313,8 @@ def _acquire_token(self) -> None: GlpiAuthError If GLPI rejects the credentials (401/403). Not retried. GlpiServerError - If the token endpoint fails (5xx). Retried up to 3 attempts. + If the token endpoint fails (5xx). Retried up to ``max_retries`` times + (3 attempts by default). GlpiStatusError If the token endpoint returns any other unexpected status. Not retried. @@ -326,12 +337,7 @@ def _acquire_token(self) -> None: response_text=str(error_detail), ) - @retry( - retry=retry_if_exception_type(GlpiTransportError), - stop=stop_after_attempt(3), - wait=wait_fixed(3), - reraise=True, - ) + @retried(GlpiTransportError) def _refresh_access_token(self) -> None: """Refresh the OAuth2 access token using the stored refresh token. @@ -356,7 +362,8 @@ def _refresh_access_token(self) -> None: ``GlpiServerError``, so it does not retry the fall-through to :meth:`_acquire_token`. The nested call carries its own independent decorator, which does retry ``GlpiServerError`` up - to 3 attempts. A persistent 5xx therefore costs exactly 1 + to ``max_retries`` + 1 attempts (3 by default). A persistent 5xx + therefore costs (with the default setting) exactly 1 refresh POST + 3 nested acquire POSTs = 4 POST requests, not the 12 an earlier, less precise predicate produced by retrying the already-retried nested failure a second time. diff --git a/glpi_python_client/_sync/auth/tests/test_auth.py b/glpi_python_client/_sync/auth/tests/test_auth.py index 221297a..3e85ff6 100644 --- a/glpi_python_client/_sync/auth/tests/test_auth.py +++ b/glpi_python_client/_sync/auth/tests/test_auth.py @@ -5,7 +5,6 @@ import httpx import pytest -from tenacity import wait_fixed from glpi_python_client import ( GlpiAuthError, @@ -243,12 +242,9 @@ def test_oauth_401_is_not_retried() -> None: assert len(session.calls) == 1 -def test_oauth_5xx_raises_glpi_server_error_after_retries( - monkeypatch: pytest.MonkeyPatch, -) -> None: +def test_oauth_5xx_raises_glpi_server_error_after_retries() -> None: """A 5xx from the token endpoint is retried, then reraised as-is.""" - monkeypatch.setattr(GLPITokenManager._acquire_token.retry, "wait", wait_fixed(0)) session = _FakeSession(response=TokenResponse(status_code=503, payload={})) manager = GLPITokenManager( token_url="https://glpi.example.test/api.php/token", @@ -287,9 +283,7 @@ def _make_refresh_ready_manager( return manager -def test_refresh_401_stays_final_with_one_nested_acquire_call( - monkeypatch: pytest.MonkeyPatch, -) -> None: +def test_refresh_401_stays_final_with_one_nested_acquire_call() -> None: """A 4xx during refresh is not retried by either decorator. ``_refresh_access_token`` does not raise directly on a non-2xx response: @@ -302,10 +296,6 @@ def test_refresh_401_stays_final_with_one_nested_acquire_call( of multiplying further (contrast with the 5xx case below). """ - monkeypatch.setattr(GLPITokenManager._acquire_token.retry, "wait", wait_fixed(0)) - monkeypatch.setattr( - GLPITokenManager._refresh_access_token.retry, "wait", wait_fixed(0) - ) session = _FakeSession( response=TokenResponse(status_code=401, payload={"error": "invalid_grant"}) ) @@ -320,15 +310,14 @@ def test_refresh_401_stays_final_with_one_nested_acquire_call( assert len(session.calls) == 2 -def test_refresh_5xx_persistent_costs_one_refresh_plus_nested_acquire_attempts( - monkeypatch: pytest.MonkeyPatch, -) -> None: +def test_refresh_5xx_persistent_costs_one_refresh_plus_nested_acquires() -> None: """A persistent 5xx during refresh costs 4 POSTs, not 12. ``_refresh_access_token`` falls through to a *nested* ``_acquire_token()`` call on any non-2xx response instead of raising directly - (auth.py:327-332). That nested call is independently decorated with - ``stop_after_attempt(3)`` and retries ``GlpiServerError``. This method's + (auth.py:327-332). That nested call is independently retried per + the ``max_retries`` setting (3 attempts by default) and retries + ``GlpiServerError``. This method's own decorator only matches ``httpx.HTTPError`` (a genuine network fault on the refresh POST itself), not ``GlpiServerError``, so it does not retry the fall-through a second time on top of the nested @@ -342,10 +331,6 @@ def test_refresh_5xx_persistent_costs_one_refresh_plus_nested_acquire_attempts( silently reintroduce the multiplication. """ - monkeypatch.setattr(GLPITokenManager._acquire_token.retry, "wait", wait_fixed(0)) - monkeypatch.setattr( - GLPITokenManager._refresh_access_token.retry, "wait", wait_fixed(0) - ) session = _FakeSession(response=TokenResponse(status_code=503, payload={})) manager = _make_refresh_ready_manager(session) @@ -356,9 +341,7 @@ def test_refresh_5xx_persistent_costs_one_refresh_plus_nested_acquire_attempts( assert len(session.calls) == 4 -def test_acquire_token_network_error_is_retried_three_times( - monkeypatch: pytest.MonkeyPatch, -) -> None: +def test_acquire_token_network_error_is_retried_three_times() -> None: """A connection-level failure (no HTTP response at all) is retried. Mirrors ``test_network_errors_are_still_retried`` in @@ -366,8 +349,6 @@ def test_acquire_token_network_error_is_retried_three_times( covers the OAuth token path, which previously had no equivalent test. """ - monkeypatch.setattr(GLPITokenManager._acquire_token.retry, "wait", wait_fixed(0)) - class _FailingSession: def __init__(self) -> None: self.calls: list[dict[str, object]] = [] @@ -392,9 +373,7 @@ def post( assert len(session.calls) == 3 -def test_refresh_network_error_is_retried_three_times( - monkeypatch: pytest.MonkeyPatch, -) -> None: +def test_refresh_network_error_is_retried_three_times() -> None: """A connection-level failure during refresh is retried by refresh's own decorator. Pins the one predicate member not yet covered by another test: @@ -414,10 +393,6 @@ def test_refresh_network_error_is_retried_three_times( it with every other test still green. """ - monkeypatch.setattr( - GLPITokenManager._refresh_access_token.retry, "wait", wait_fixed(0) - ) - class _FailingSession: def __init__(self) -> None: self.calls: list[dict[str, object]] = [] diff --git a/glpi_python_client/_sync/auth/tests/test_v1_session.py b/glpi_python_client/_sync/auth/tests/test_v1_session.py index e46ec27..356556c 100644 --- a/glpi_python_client/_sync/auth/tests/test_v1_session.py +++ b/glpi_python_client/_sync/auth/tests/test_v1_session.py @@ -7,7 +7,6 @@ import httpx import pytest -from tenacity import wait_fixed from glpi_python_client import ( GlpiProtocolError, @@ -26,19 +25,6 @@ ) -@pytest.fixture(autouse=True) -def _no_sleep(monkeypatch: pytest.MonkeyPatch) -> None: - """Drop the 3s fixed wait so retry tests stay instant. - - Each decorated method's own ``Retrying`` object is patched directly. - Patching ``tenacity.nap.time.sleep`` would work today but silently stops - working on the async path, so it is deliberately not used here. - """ - - for name in _RETRIED_METHODS: - monkeypatch.setattr(getattr(GLPIV1Session, name).retry, "wait", wait_fixed(0)) - - class _FakeV1Http: """In-memory HTTP client stand-in capturing every call.""" diff --git a/glpi_python_client/_sync/clients/_base_client.py b/glpi_python_client/_sync/clients/_base_client.py index 9a097a4..7b50629 100644 --- a/glpi_python_client/_sync/clients/_base_client.py +++ b/glpi_python_client/_sync/clients/_base_client.py @@ -16,6 +16,10 @@ from typing import TYPE_CHECKING, Self from glpi_python_client._sync._concurrency import Lock +from glpi_python_client._sync._retry import ( + DEFAULT_MAX_RETRIES, + validate_retry_settings, +) from glpi_python_client._sync.clients.commons._config import ( build_client_env_config, build_client_resources, @@ -55,6 +59,8 @@ def __init__( v1_base_url: str | None = None, v1_user_token: str | None = None, v1_app_token: str | None = None, + max_retries: int = DEFAULT_MAX_RETRIES, + retry_wait_seconds: float | None = None, ) -> None: """Build the shared resources for a GLPI client. @@ -111,6 +117,17 @@ def __init__( ``user_token`` for the v1 fallback session. v1_app_token : str | None, optional ``app_token`` for the v1 fallback session. + max_retries : int, optional + Automatic retries after the first attempt of a call that failed on + a network fault (``GlpiTransportError``) or a 5xx answer + (``GlpiServerError``): ``0`` disables retrying, the default ``2`` + makes 3 attempts in total. It applies to every v2 verb, the v1 + session helpers and OAuth token acquisition. A retried write may + already have been applied; pass ``0`` when the caller owns its + own retry policy. + retry_wait_seconds : float | None, optional + Pause between two attempts; ``None`` keeps the default of 3 + seconds. Raises ------ @@ -120,6 +137,9 @@ def __init__( """ self.server_timezone = resolve_server_timezone(server_timezone) + self._max_retries, self._retry_wait_seconds = validate_retry_settings( + max_retries, retry_wait_seconds + ) resources = build_client_resources( glpi_api_url=glpi_api_url, client_name=type(self).__name__, @@ -132,6 +152,8 @@ def __init__( v1_base_url=v1_base_url, v1_user_token=v1_user_token, v1_app_token=v1_app_token, + max_retries=self._max_retries, + retry_wait_seconds=self._retry_wait_seconds, ) self.glpi_api_url = resources.glpi_api_url self._session = resources.session @@ -160,7 +182,8 @@ def from_env( ``GLPI_V1_BASE_URL``, ``GLPI_V1_USER_TOKEN``, ``GLPI_V1_APP_TOKEN``, ``GLPI_ENTITY``, ``GLPI_PROFILE``, ``GLPI_ENTITY_RECURSIVE``, ``GLPI_LANGUAGE``, ``GLPI_AUTH_TOKEN_REFRESH``, - ``GLPI_SERVER_TIMEZONE``). + ``GLPI_SERVER_TIMEZONE``, ``GLPI_MAX_RETRIES``, + ``GLPI_RETRY_WAIT_SECONDS``). Parameters ---------- diff --git a/glpi_python_client/_sync/clients/commons/_config.py b/glpi_python_client/_sync/clients/commons/_config.py index 140e5e7..d39fd35 100644 --- a/glpi_python_client/_sync/clients/commons/_config.py +++ b/glpi_python_client/_sync/clients/commons/_config.py @@ -15,6 +15,7 @@ import httpx +from glpi_python_client._sync._retry import DEFAULT_MAX_RETRIES from glpi_python_client._errors import GlpiValidationError if TYPE_CHECKING: @@ -112,6 +113,8 @@ def build_client_resources( v1_base_url: str | None, v1_user_token: str | None, v1_app_token: str | None, + max_retries: int = DEFAULT_MAX_RETRIES, + retry_wait_seconds: float | None = None, session_factory: SessionFactory | None = None, ) -> ClientResources: """Build the shared resources required by one client instance. @@ -166,6 +169,8 @@ def build_client_resources( password=password, session=session, auth_token_refresh=auth_token_refresh, + max_retries=max_retries, + retry_wait_seconds=retry_wait_seconds, ) v1: GLPIV1Session | None = None @@ -174,6 +179,8 @@ def build_client_resources( base_url=v1_base_url, user_token=v1_user_token, app_token=v1_app_token, + max_retries=max_retries, + retry_wait_seconds=retry_wait_seconds, verify_ssl=verify_ssl, ) @@ -272,6 +279,34 @@ def parse_optional_env_int(value: object) -> int | None: raise TypeError("Integer environment values must be strings or integers") +def parse_optional_env_float(value: object) -> float | None: + """Parse one optional number from an environment-style value. + + ``None`` is preserved, native numbers are accepted as-is and strings are + converted through ``float()``. + + Raises + ------ + GlpiValidationError + If a string value cannot be parsed as a number. + TypeError + If ``value`` is neither ``None``, a number, nor ``str``. + """ + + if value is None: + return None + if isinstance(value, int | float) and not isinstance(value, bool): + return float(value) + if isinstance(value, str): + try: + return float(value) + except ValueError as exc: + raise GlpiValidationError( + f"Invalid number environment value: {value!r}" + ) from exc + raise TypeError("Number environment values must be strings or numbers") + + def parse_optional_env_bool(value: object, *, default: bool) -> bool: """Parse one optional boolean from an environment-style value. @@ -330,6 +365,13 @@ def build_client_env_config( "v1_user_token": env.get(f"{prefix}V1_USER_TOKEN"), "v1_app_token": env.get(f"{prefix}V1_APP_TOKEN"), } + # Absent keys keep the constructor defaults (3 attempts, 3 s apart). + max_retries = parse_optional_env_int(env.get(f"{prefix}MAX_RETRIES")) + if max_retries is not None: + config["max_retries"] = max_retries + retry_wait = parse_optional_env_float(env.get(f"{prefix}RETRY_WAIT_SECONDS")) + if retry_wait is not None: + config["retry_wait_seconds"] = retry_wait config.update(overrides) return config diff --git a/glpi_python_client/_sync/clients/commons/_transport.py b/glpi_python_client/_sync/clients/commons/_transport.py index 6ec2e12..9894d04 100644 --- a/glpi_python_client/_sync/clients/commons/_transport.py +++ b/glpi_python_client/_sync/clients/commons/_transport.py @@ -30,9 +30,9 @@ from typing import TYPE_CHECKING, Any, TypeVar import httpx -from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_fixed from glpi_python_client._sync._concurrency import Lock +from glpi_python_client._sync._retry import DEFAULT_MAX_RETRIES, retried from glpi_python_client._sync.clients.commons._http import ( build_request_headers, build_request_url, @@ -72,12 +72,11 @@ #: :func:`~glpi_python_client._sync.clients.commons._http.transport_error_from` #: guarantees every network fault is translated into, makes that failure #: impossible to reintroduce. -_RETRY_ON_NETWORK_ERRORS = retry( - retry=retry_if_exception_type((GlpiTransportError, GlpiServerError)), - stop=stop_after_attempt(3), - wait=wait_fixed(3), - reraise=True, -) +#: +#: How many times, and how long apart, is the client's ``max_retries`` and +#: ``retry_wait_seconds`` setting (read per call from ``self``); by default 3 +#: attempts in total, 3 s apart, and ``max_retries=0`` disables retrying. +_RETRY_ON_NETWORK_ERRORS = retried((GlpiTransportError, GlpiServerError)) class TransportMixin: @@ -102,6 +101,8 @@ class TransportMixin: _auth: GLPITokenManager _auth_lock: Lock _closed: bool = False + _max_retries: int = DEFAULT_MAX_RETRIES + _retry_wait_seconds: float | None = None _session: httpx.Client _v1: GLPIV1Session | None entity_recursive: bool @@ -313,7 +314,8 @@ def _get_request( Network errors (:class:`~glpi_python_client.GlpiTransportError`) and 5xx responses (:class:`~glpi_python_client.GlpiServerError`) are - retried up to 3 times, with ``reraise=True`` so the real error + retried up to ``max_retries`` times (by default 2, so 3 attempts in + total; ``0`` disables retrying), with ``reraise=True`` so the real error propagates once retries are exhausted; 4xx responses are returned as-is without a retry. """ diff --git a/glpi_python_client/_sync/clients/commons/tests/test_transport.py b/glpi_python_client/_sync/clients/commons/tests/test_transport.py index e4d4a69..4dcbcc5 100644 --- a/glpi_python_client/_sync/clients/commons/tests/test_transport.py +++ b/glpi_python_client/_sync/clients/commons/tests/test_transport.py @@ -19,10 +19,8 @@ import httpx import pytest -from tenacity import wait_fixed from glpi_python_client import ( - GlpiClient, GlpiError, GlpiServerError, GlpiStatusError, @@ -233,19 +231,6 @@ def _send(method: str, url: str, **kw: Any) -> FakeResponse: # rather than reusing ``transport_client``. -@pytest.fixture(autouse=True) -def _no_retry_sleep(monkeypatch: pytest.MonkeyPatch) -> None: - """Drop the 3s fixed wait so retry tests stay instant. - - The decorator's ``Retrying`` object is patched directly. Patching - ``tenacity.nap.time.sleep`` would work today but silently stops working - on the async path, so it is deliberately not used here. - """ - - for name in _RETRIED_METHODS: - monkeypatch.setattr(getattr(GlpiClient, name).retry, "wait", wait_fixed(0)) - - @pytest.fixture def retry_client() -> Iterator[Any]: """Return a client with auth stubbed so no token call is made.""" diff --git a/glpi_python_client/_sync/conftest.py b/glpi_python_client/_sync/conftest.py index 2a837d0..fcbeb66 100644 --- a/glpi_python_client/_sync/conftest.py +++ b/glpi_python_client/_sync/conftest.py @@ -11,9 +11,17 @@ import pytest from glpi_python_client import GlpiClient +from glpi_python_client._sync import _retry from glpi_python_client._sync._testing import make_client +@pytest.fixture(autouse=True) +def _no_retry_wait(monkeypatch: pytest.MonkeyPatch) -> None: + """Drop the default 3 s pause between retry attempts so tests stay instant.""" + + monkeypatch.setattr(_retry, "DEFAULT_RETRY_WAIT_SECONDS", 0.0) + + @pytest.fixture def client() -> Iterator[GlpiClient]: """Yield a default in-memory client and close it afterwards.""" diff --git a/glpi_python_client/_sync/tests/test_retry_settings.py b/glpi_python_client/_sync/tests/test_retry_settings.py new file mode 100644 index 0000000..201db90 --- /dev/null +++ b/glpi_python_client/_sync/tests/test_retry_settings.py @@ -0,0 +1,275 @@ +"""The retry setting: ``max_retries`` and ``retry_wait_seconds``. + +The default (two retries after the first attempt, 3 s apart) reproduces the +historical behaviour of three attempts in total; ``max_retries=0`` turns +retrying off for every retried call: the v2 verbs, the v1 session helpers and +the OAuth token manager. +""" + +from __future__ import annotations + +from typing import Any + +import httpx +import pytest + +from glpi_python_client import ( + GlpiClient, + GlpiServerError, + GlpiTransportError, + GlpiValidationError, +) +from glpi_python_client._sync import _retry +from glpi_python_client._sync._testing import make_client +from glpi_python_client._sync.auth._v1_session import GLPIV1Session +from glpi_python_client._sync.auth.auth import GLPITokenManager +from glpi_python_client.testing.utils import FakeResponse + +_VERBS = ("_get_request", "_post_request", "_update_request", "_delete_request") + + +def _stub_send(client: Any, *, status: int | None, attempts: list[int]) -> None: + """Make every request attempt record itself, then fail as asked.""" + + def _ensure_token() -> None: + return None + + def _send(method: str, url: str, **kw: Any) -> FakeResponse: + attempts.append(1) + if status is None: + raise GlpiTransportError("network down") + return FakeResponse(status_code=status, payload={}, text="x", reason="r") + + client._auth.access_token = "test-token" + client._auth.ensure_token = _ensure_token + client._send_request = _send + + +@pytest.mark.parametrize("verb", _VERBS) +@pytest.mark.parametrize("status", [500, None]) +def test_disabled_retries_send_one_request(verb: str, status: int | None) -> None: + """With ``max_retries=0`` a 5xx or a transport error costs one request.""" + + client = make_client(max_retries=0) + attempts: list[int] = [] + _stub_send(client, status=status, attempts=attempts) + expected = GlpiServerError if status else GlpiTransportError + try: + with pytest.raises(expected): + getattr(client, verb)("Assistance/Ticket") + finally: + client.close() + assert len(attempts) == 1 + + +@pytest.mark.parametrize("verb", _VERBS) +@pytest.mark.parametrize("status", [500, None]) +def test_default_retries_make_three_attempts( + verb: str, status: int | None +) -> None: + """Without the setting the same call is attempted three times.""" + + client = make_client() + attempts: list[int] = [] + _stub_send(client, status=status, attempts=attempts) + expected = GlpiServerError if status else GlpiTransportError + try: + with pytest.raises(expected): + getattr(client, verb)("Assistance/Ticket") + finally: + client.close() + assert len(attempts) == 3 + + +def test_max_retries_counts_retries_after_the_first_attempt() -> None: + client = make_client(max_retries=4) + attempts: list[int] = [] + _stub_send(client, status=503, attempts=attempts) + try: + with pytest.raises(GlpiServerError): + client._get_request("Assistance/Ticket") + finally: + client.close() + assert len(attempts) == 5 + + +def test_4xx_is_still_not_retried() -> None: + """Which errors are retried does not depend on the setting.""" + + client = make_client(max_retries=5) + attempts: list[int] = [] + _stub_send(client, status=404, attempts=attempts) + try: + response = client._get_request("Assistance/Ticket") + finally: + client.close() + assert response.status_code == 404 + assert len(attempts) == 1 + + +def _spy_on_wait(monkeypatch: pytest.MonkeyPatch) -> list[float]: + """Record every wait the retry policy builds, without really waiting.""" + + waits: list[float] = [] + real = _retry.wait_fixed + + def _spy(seconds: float) -> Any: + waits.append(seconds) + return real(0) + + monkeypatch.setattr(_retry, "wait_fixed", _spy) + return waits + + +def test_the_configured_wait_separates_attempts( + monkeypatch: pytest.MonkeyPatch, +) -> None: + waits = _spy_on_wait(monkeypatch) + client = make_client(retry_wait_seconds=7) + _stub_send(client, status=500, attempts=[]) + try: + with pytest.raises(GlpiServerError): + client._get_request("Assistance/Ticket") + finally: + client.close() + assert waits == [7] + + +def test_the_default_wait_is_three_seconds( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # Undo the suite-wide zero wait so the real default is what gets built. + monkeypatch.setattr(_retry, "DEFAULT_RETRY_WAIT_SECONDS", 3.0) + waits = _spy_on_wait(monkeypatch) + client = make_client() + _stub_send(client, status=500, attempts=[]) + try: + with pytest.raises(GlpiServerError): + client._get_request("Assistance/Ticket") + finally: + client.close() + assert waits == [3.0] + assert _retry.DEFAULT_MAX_RETRIES == 2 + + +def _v1_session(handler: Any, **kwargs: Any) -> GLPIV1Session: + session = GLPIV1Session( + base_url="https://glpi.example.test/apirest.php", + user_token="user-token", + **kwargs, + ) + session._http = httpx.Client(transport=httpx.MockTransport(handler)) + return session + + +@pytest.mark.parametrize(("retries", "expected"), [(0, 1), (None, 3)]) +def test_the_setting_reaches_a_v1_helper( + retries: int | None, expected: int +) -> None: + calls: list[str] = [] + + def handler(request: httpx.Request) -> httpx.Response: + calls.append(request.url.path) + if request.url.path.endswith("/initSession"): + return httpx.Response(200, json={"session_token": "tk"}) + return httpx.Response(500, json={}) + + kwargs = {} if retries is None else {"max_retries": retries} + session = _v1_session(handler, **kwargs) + try: + with pytest.raises(GlpiServerError): + session.request_json("GET", "/Ticket/1") + finally: + session._http.close() + assert len([c for c in calls if c.endswith("/Ticket/1")]) == expected + + +def test_the_setting_reaches_the_v1_init_session() -> None: + calls: list[str] = [] + + def handler(request: httpx.Request) -> httpx.Response: + calls.append(request.url.path) + return httpx.Response(503, json={}) + + session = _v1_session(handler, max_retries=0) + try: + with pytest.raises(GlpiServerError): + session._init_session() + finally: + session._http.close() + assert len(calls) == 1 + + +@pytest.mark.parametrize(("retries", "expected"), [(0, 1), (None, 3)]) +def test_the_setting_reaches_the_token_manager( + retries: int | None, expected: int +) -> None: + calls: list[int] = [] + + def handler(request: httpx.Request) -> httpx.Response: + calls.append(1) + return httpx.Response(503, json={}) + + kwargs = {} if retries is None else {"max_retries": retries} + http = httpx.Client(transport=httpx.MockTransport(handler)) + manager = GLPITokenManager( + token_url="https://glpi.example.test/api.php/token", + username="u", + password="p", + session=http, + **kwargs, + ) + try: + with pytest.raises(GlpiServerError): + manager.ensure_token() + finally: + http.close() + assert len(calls) == expected + + +def test_the_client_hands_the_setting_to_its_collaborators() -> None: + client = make_client( + max_retries=1, + retry_wait_seconds=2, + v1_base_url="https://glpi.example.test/apirest.php", + v1_user_token="user-token", + ) + try: + assert client._max_retries == 1 + assert client._auth._max_retries == 1 + assert client._v1 is not None + assert client._v1._max_retries == 1 + assert client._v1._retry_wait_seconds == 2 + assert client._auth._retry_wait_seconds == 2 + finally: + client.close() + + +def test_from_env_reads_the_setting() -> None: + client = GlpiClient.from_env( + env={ + "GLPI_API_URL": "https://glpi.example.test/api.php/v2", + "GLPI_CLIENT_ID": "i", + "GLPI_CLIENT_SECRET": "s", + "GLPI_SERVER_TIMEZONE": "Europe/Paris", + "GLPI_MAX_RETRIES": "0", + "GLPI_RETRY_WAIT_SECONDS": "0.5", + } + ) + try: + assert client._max_retries == 0 + assert client._retry_wait_seconds == 0.5 + finally: + client.close() + + +@pytest.mark.parametrize("bad", [-1, True, 1.5, "2"]) +def test_a_bad_max_retries_is_rejected(bad: object) -> None: + with pytest.raises(GlpiValidationError): + make_client(max_retries=bad) + + +@pytest.mark.parametrize("bad", [-1, True, "3"]) +def test_a_bad_retry_wait_is_rejected(bad: object) -> None: + with pytest.raises(GlpiValidationError): + make_client(retry_wait_seconds=bad) diff --git a/skills/glpi-client-setup/SKILL.md b/skills/glpi-client-setup/SKILL.md index dea767e..d7f929c 100644 --- a/skills/glpi-client-setup/SKILL.md +++ b/skills/glpi-client-setup/SKILL.md @@ -87,6 +87,7 @@ call `client.close()` (or `await client.close()`) when finished. - `GLPI_ENTITY`, `GLPI_PROFILE`, `GLPI_ENTITY_RECURSIVE` - `GLPI_SERVER_TIMEZONE` -- **required**. IANA name of the GLPI server's timezone (e.g. `Europe/Paris`). GLPI does not advertise it, and it is needed to interpret the timestamps the server sends without an offset -- there is no default, because guessing UTC against a Europe/Paris instance shifts those values silently. - `GLPI_LANGUAGE`, `GLPI_VERIFY_SSL`, `GLPI_AUTH_TOKEN_REFRESH` +- `GLPI_MAX_RETRIES` (retries after the first attempt, `0` disables retrying), `GLPI_RETRY_WAIT_SECONDS` - `GLPI_V1_BASE_URL`, `GLPI_V1_USER_TOKEN`, `GLPI_V1_APP_TOKEN` Pass keyword overrides to replace selected environment values. diff --git a/unasync_build.py b/unasync_build.py index b2497d0..4f166c9 100644 --- a/unasync_build.py +++ b/unasync_build.py @@ -108,6 +108,8 @@ # this is easy to miss. ``aiter_text``/``aiter_lines``/``aiter_raw`` # are equally un-rewritten and would each need an entry here. "aiter_bytes": "iter_bytes", + # tenacity: the async retrier has a sync twin of the same call shape. + "AsyncRetrying": "Retrying", }