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 @@ -4,6 +4,20 @@ All notable changes to this project are documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).

## Unreleased

### Fixed

- **Concurrent renewals of the legacy v1 session.** A client shared by
concurrent tasks or threads renewed the v1 session once per request that
found the token stale (every 15 minutes by default), on the first lazy
`initSession`, and after a 401/403 rejection: each renewal killed the
token and opened a session, so a second `killSession` answered 401 and
one server-side session leaked per renewal. Every acquisition now takes a
lock and re-checks under it whether the work is still needed, so waiters
reuse the token the first renewal obtained and the session is killed and
opened once. Retry behaviour is unchanged.

## 0.6.10 — 2026-11-16

A minor addition: the GLPI v2 `/Dropdowns/ITILCategory` routes, so a caller
Expand Down
70 changes: 52 additions & 18 deletions glpi_python_client/_async/auth/_v1_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@
kill) and exposes the typed ``upload_document`` helper plus the generic
``request_json`` JSON-only HTTP helper that newer mixins build on.

Session renewal is serialised by a lock and the need is re-checked under it,
so concurrent requests share one new session instead of each renewing.

Retry policy
------------
Every public dispatch helper (``_init_session``, ``request_json``,
Expand Down Expand Up @@ -43,6 +46,7 @@
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.clients.commons._config import build_http_session
from glpi_python_client._async.clients.commons._http import (
ensure_response_status,
Expand Down Expand Up @@ -111,6 +115,11 @@ def __init__(

self._session_token: str | None = None
self._session_started_at: datetime | None = None
# Serialises every acquisition or replacement of the session token.
# It is not re-entrant: only ``_ensure_session``,
# ``_renew_rejected_session`` and ``close`` take it, and none of them
# calls another of them (or ``_headers``) while holding it.
self._session_lock = Lock()

async def _dispatch(self, method: str, url: str, **kwargs: Any) -> httpx.Response:
"""Send one raw v1 HTTP call, translating transport faults.
Expand Down Expand Up @@ -178,13 +187,32 @@ async def _ensure_session(self) -> None:

The helper is called by every authenticated request before any header
construction so callers never have to manage the lifecycle directly.
Concurrent callers are serialised and the need is re-tested under the
lock, so a caller that waited reuses the token the first one obtained.
"""

if self._session_token is None:
await self._init_session()
if self._session_token is not None and not self._is_session_stale():
return
if self._is_session_stale():
logger.info("GLPI v1 session reached refresh interval; renewing session.")
async with self._session_lock:
if self._session_token is None:
await self._init_session()
elif self._is_session_stale():
logger.info(
"GLPI v1 session reached refresh interval; renewing session."
)
await self._renew_session()

async def _renew_rejected_session(self, rejected_token: str | None) -> None:
"""Renew the session after the server rejected ``rejected_token``.

Under the lock the current token is compared with the rejected one:
when another request already replaced it, the new token is reused
and nothing is killed or opened.
"""

async with self._session_lock:
if self._session_token != rejected_token:
return
await self._renew_session()

def _is_session_stale(self) -> bool:
Expand Down Expand Up @@ -218,6 +246,8 @@ def _session_headers(self) -> dict[str, str]:
async def _renew_session(self) -> None:
"""Drop the current GLPI v1 session token and acquire a new one.

The caller must hold ``_session_lock``; the helper never takes it.

The previous token is best-effort killed so the GLPI server can release
the associated session state immediately. ``_init_session`` will set
the new token on success or raise, leaving the existing state
Expand Down Expand Up @@ -267,7 +297,8 @@ async def _authenticated_request(
the caller to validate with :func:`ensure_response_status`.
"""

request_headers = {**await self._headers(), **(headers or {})}
session_headers = await self._headers()
request_headers = {**session_headers, **(headers or {})}
# Dispatch through ``request(method, ...)`` rather than looking up a
# per-verb attribute: it is the one call shape both transports share,
# and it keeps the verb a value instead of an attribute name.
Expand All @@ -278,7 +309,7 @@ async def _authenticated_request(
"GLPI v1 session token was rejected; refreshing session and "
"retrying request once."
)
await self._renew_session()
await self._renew_rejected_session(session_headers["Session-Token"])
request_headers = {**await self._headers(), **(headers or {})}
response = await self._dispatch(
verb, url, headers=request_headers, **kwargs
Expand All @@ -299,19 +330,22 @@ async def close(self) -> None:
"""

try:
if self._session_token is not None:
await self._dispatch(
"GET",
f"{self._base_url}/killSession",
headers=self._session_headers(),
timeout=10,
)
logger.info("GLPI v1 session killed.")
except Exception:
logger.warning("Failed to kill GLPI v1 session.", exc_info=True)
async with self._session_lock:
try:
if self._session_token is not None:
await self._dispatch(
"GET",
f"{self._base_url}/killSession",
headers=self._session_headers(),
timeout=10,
)
logger.info("GLPI v1 session killed.")
except Exception:
logger.warning("Failed to kill GLPI v1 session.", exc_info=True)
finally:
self._session_token = None
self._session_started_at = None
finally:
self._session_token = None
self._session_started_at = None
await self._http.aclose()

@_RETRY_ON_NETWORK_ERRORS
Expand Down
148 changes: 148 additions & 0 deletions glpi_python_client/_async/auth/tests/test_v1_session_concurrency.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
"""Concurrency tests for :class:`GLPIV1Session` on the async surface.

Hand-written on both sides of the codegen (see ``HAND_WRITTEN`` in
``unasync_build.py``): the claim is that tasks sharing one session renew it
once, which needs real suspension points inside the fake transport. The sync
twin of this module drives the same scenarios from threads.
"""

from __future__ import annotations

import asyncio
from datetime import UTC, datetime, timedelta
from typing import Any, cast

import httpx

from glpi_python_client._async.auth._v1_session import GLPIV1Session
from glpi_python_client.testing.utils import FakeResponse

_TASKS = 8


class _ServerSimulation:
"""Fake v1 server that tracks which session tokens are alive.

``killSession`` answers 401 for a token that is already dead, and any
other call answers 401 for a dead or unknown token, like the real API.
"""

def __init__(self) -> None:
self.alive: set[str] = set()
self.inits = 0
self.kills = 0
self.failed_kills = 0
self.tokens_used: list[str] = []

async def request(
self, method: str, url: str, headers: dict[str, str], **kwargs: Any
) -> FakeResponse:
await asyncio.sleep(0.01) # a real suspension point on every call
if url.endswith("/initSession"):
self.inits += 1
token = f"tk{self.inits}"
self.alive.add(token)
return FakeResponse(status_code=200, payload={"session_token": token})
token = headers["Session-Token"]
if url.endswith("/killSession"):
self.kills += 1
if token not in self.alive:
self.failed_kills += 1
return FakeResponse(status_code=401, payload={})
self.alive.discard(token)
return FakeResponse(status_code=200, payload={})
self.tokens_used.append(token)
if token not in self.alive:
return FakeResponse(status_code=401, payload={"err": "invalid"})
return FakeResponse(status_code=200, payload={"ok": True})

async def aclose(self) -> None:
return None


def _make(server: _ServerSimulation) -> GLPIV1Session:
session = GLPIV1Session(
base_url="https://glpi.example.test/apirest.php",
user_token="user-token",
app_token="app-token",
)
session._http = cast(httpx.AsyncClient, server) # type: ignore[assignment]
return session


def _adopt(
session: GLPIV1Session, server: _ServerSimulation, *, age: timedelta
) -> None:
"""Give ``session`` a live token acquired ``age`` ago."""

server.inits += 1
token = f"tk{server.inits}"
server.alive.add(token)
session._session_token = token
session._session_started_at = datetime.now(tz=UTC) - age


async def _burst(session: GLPIV1Session) -> list[object]:
return list(
await asyncio.wait_for(
asyncio.gather(
*(session.request_json("GET", "Ticket") for _ in range(_TASKS))
),
timeout=10,
)
)


async def test_concurrent_requests_on_a_stale_session_renew_it_once() -> None:
server = _ServerSimulation()
session = _make(server)
_adopt(session, server, age=timedelta(hours=1))

results = await _burst(session)

assert results == [{"ok": True}] * _TASKS
assert server.kills == 1
assert server.failed_kills == 0
assert server.inits == 2 # the adopted session and its single replacement
assert server.tokens_used == ["tk2"] * _TASKS
assert server.alive == {"tk2"} # nothing leaked on the server


async def test_concurrent_first_use_opens_one_session() -> None:
server = _ServerSimulation()
session = _make(server)

results = await _burst(session)

assert results == [{"ok": True}] * _TASKS
assert server.inits == 1
assert server.kills == 0
assert server.tokens_used == ["tk1"] * _TASKS


async def test_concurrent_rejections_of_one_token_renew_it_once() -> None:
server = _ServerSimulation()
session = _make(server)
_adopt(session, server, age=timedelta(seconds=1))
server.alive.clear() # the server dropped the session behind the client's back

results = await _burst(session)

assert results == [{"ok": True}] * _TASKS
assert server.inits == 2
assert server.kills == 1 # one best-effort kill of the dead token
assert server.alive == {"tk2"}
assert server.tokens_used.count("tk2") == _TASKS


async def test_close_after_a_renewal_kills_only_the_current_session() -> None:
server = _ServerSimulation()
session = _make(server)
_adopt(session, server, age=timedelta(hours=1))
await _burst(session)

await session.close()

assert server.alive == set()
assert server.kills == 2
assert session._session_token is None
Loading
Loading