Skip to content
Merged
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
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
45 changes: 34 additions & 11 deletions docs/user_guide.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
90 changes: 90 additions & 0 deletions glpi_python_client/_async/_retry.py
Original file line number Diff line number Diff line change
@@ -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
22 changes: 14 additions & 8 deletions glpi_python_client/_async/auth/_v1_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand All @@ -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:
Expand All @@ -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"
Expand Down
37 changes: 22 additions & 15 deletions glpi_python_client/_async/auth/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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__(
Expand All @@ -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
Expand Down Expand Up @@ -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.

Expand All @@ -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.
Expand All @@ -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.

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