Skip to content

Commit 7e3fac5

Browse files
committed
fixup! feat(platform): support external token providers and simplify caching
1 parent f74f48d commit 7e3fac5

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

src/aignostics/platform/_client.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,10 @@
2929

3030
from ._settings import settings
3131

32+
# Safety bound for the external token-provider cache. In normal usage callers
33+
# reuse a single provider reference, so this limit should never be reached.
34+
_MAX_EXTERNAL_CLIENTS = 16
35+
3236
RETRYABLE_EXCEPTIONS = (
3337
ServiceException,
3438
Urllib3TimeoutError,
@@ -290,6 +294,13 @@ def get_api_client(cache_token: bool = True, token_provider: Callable[[], str] |
290294

291295
# Store in the appropriate singleton cache
292296
if token_provider is not None:
297+
if len(Client._api_client_external) >= _MAX_EXTERNAL_CLIENTS:
298+
logger.warning(
299+
"External token provider cache exceeded {} entries; clearing to prevent resource leak. "
300+
"Reuse a stable token_provider reference for optimal connection reuse.",
301+
_MAX_EXTERNAL_CLIENTS,
302+
)
303+
Client._api_client_external.clear()
293304
Client._api_client_external[token_provider] = api_client
294305
elif cache_token:
295306
Client._api_client_cached = api_client

tests/aignostics/platform/client_token_provider_test.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,3 +205,26 @@ def test_none_token_provider_no_warning() -> None:
205205

206206
assert result == {}
207207
mock_logger.warning.assert_not_called()
208+
209+
210+
@pytest.mark.unit
211+
def test_external_provider_cache_bounded() -> None:
212+
"""Test that _api_client_external is bounded to _MAX_EXTERNAL_CLIENTS entries."""
213+
from aignostics.platform._client import _MAX_EXTERNAL_CLIENTS
214+
215+
with (
216+
patch("aignostics.platform._client.ApiClient"),
217+
patch.object(_AuthenticatedApi, "__init__", lambda self, *a, **kw: None),
218+
patch("aignostics.platform._client.logger") as mock_logger,
219+
):
220+
# Create more clients than the limit, each with a distinct provider
221+
for i in range(_MAX_EXTERNAL_CLIENTS + 5):
222+
Client(token_provider=_make_provider(f"token-{i}"))
223+
224+
# Cache must not exceed the limit (cleared + 1 new entry after overflow)
225+
assert len(Client._api_client_external) <= _MAX_EXTERNAL_CLIENTS
226+
227+
# A warning should have been logged when the cache was cleared
228+
mock_logger.warning.assert_called()
229+
warning_msg = mock_logger.warning.call_args[0][0]
230+
assert "resource leak" in warning_msg

0 commit comments

Comments
 (0)