| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import time |
| 4 |
import inspect |
| 5 |
import logging |
| 6 |
import threading |
| 7 |
from typing import Union, Generic, TypeVar, Callable, Optional, cast |
| 8 |
|
| 9 |
import anyio |
| 10 |
import httpx2 |
| 11 |
|
| 12 |
from ._types import AccessToken, AccessTokenProvider, AsyncAccessTokenProvider, is_async_token_provider |
| 13 |
from ..._utils import asyncify, signature_without_evaluating_annotations |
| 14 |
from ._workload import WorkloadIdentityError |
| 15 |
from ._constants import ADVISORY_REFRESH_SECONDS, MANDATORY_REFRESH_SECONDS |
| 16 |
from ..._exceptions import AnthropicError |
| 17 |
|
| 18 |
__all__ = ["TokenCache"] |
| 19 |
|
| 20 |
log: logging.Logger = logging.getLogger(__name__) |
| 21 |
|
| 22 |
# Skip advisory refreshes for this many seconds after a failure so a |
| 23 |
# token-endpoint outage isn't hammered at request rate. Fixed (no jitter): |
| 24 |
# trades fast recovery against fleet load during a sustained outage. |
| 25 |
ADVISORY_REFRESH_BACKOFF_SECONDS = 5 |
| 26 |
|
| 27 |
_EventT = TypeVar("_EventT", threading.Event, anyio.Event) |
| 28 |
|
| 29 |
|
| 30 |
def valid_access_token(value: object) -> AccessToken: |
| 31 |
if inspect.iscoroutine(value): |
| 32 |
# Closing it stops Python warning that the coroutine was never awaited. |
| 33 |
value.close() |
| 34 |
raise AnthropicError( |
| 35 |
"credentials provider returned a coroutine instead of an AccessToken; pass the `async def` function itself" |
| 36 |
) |
| 37 |
if not isinstance(value, AccessToken): |
| 38 |
raise AnthropicError(f"credentials provider returned {type(value).__name__} instead of an AccessToken") |
| 39 |
return value |
| 40 |
|
| 41 |
|
| 42 |
def accepts_force_refresh(provider: Callable[..., object]) -> bool: |
| 43 |
"""False for a legacy provider that takes no `force_refresh` argument; it is called without one.""" |
| 44 |
try: |
| 45 |
return any( |
| 46 |
parameter.name == "force_refresh" or parameter.kind is inspect.Parameter.VAR_KEYWORD |
| 47 |
for parameter in signature_without_evaluating_annotations(provider).parameters.values() |
| 48 |
) |
| 49 |
except (TypeError, ValueError): |
| 50 |
# No signature to inspect, as for some C callables. Assume the documented contract. |
| 51 |
return True |
| 52 |
|
| 53 |
|
| 54 |
class Refresh(Generic[_EventT]): |
| 55 |
"""What a caller that `TokenCache._next_step` told to call the provider needs to finish up.""" |
| 56 |
|
| 57 |
def __init__( |
| 58 |
self, |
| 59 |
*, |
| 60 |
owned_event: Optional[_EventT], |
| 61 |
force: bool, |
| 62 |
advisory_fallback: Optional[AccessToken], |
| 63 |
remaining_seconds: int, |
| 64 |
) -> None: |
| 65 |
self.owned_event: Optional[_EventT] = owned_event |
| 66 |
"""The single-flight event this caller created and must release. `None` for a |
| 67 |
per-request caller (cached `expires_at=0`), because nobody waits for it.""" |
| 68 |
self.force = force |
| 69 |
"""Whether to pass `force_refresh=True`. Only the single-flight leader ever forces.""" |
| 70 |
self.advisory_fallback = advisory_fallback |
| 71 |
"""The cached token to serve if this is an advisory refresh and it fails.""" |
| 72 |
self.remaining_seconds = remaining_seconds |
| 73 |
|
| 74 |
|
| 75 |
class TokenCache: |
| 76 |
"""Thread-safe cache wrapping an `AccessTokenProvider` or an |
| 77 |
`AsyncAccessTokenProvider` with two-tier proactive refresh and |
| 78 |
single-flight semantics. |
| 79 |
|
| 80 |
`async_get_token` applies the same policy as `get_token`: an async |
| 81 |
provider is awaited on the event loop, a sync one runs `get_token` in a |
| 82 |
worker thread. |
| 83 |
|
| 84 |
Refresh policy on each `get_token` call: |
| 85 |
|
| 86 |
* No cached token → call provider (blocking), cache, return. |
| 87 |
* Cached with `expires_at=None` → return cached forever (never refresh). |
| 88 |
* More than `advisory_refresh_seconds` remaining → return cached. |
| 89 |
* Between `mandatory_refresh_seconds` and `advisory_refresh_seconds` |
| 90 |
remaining (advisory window) → try provider; on success swap cache; on |
| 91 |
failure log a warning and return the stale cached token. If another |
| 92 |
caller is already refreshing, the advisory caller just returns the |
| 93 |
cached token — no second refresh, no waiting. |
| 94 |
* Less than `mandatory_refresh_seconds` remaining or already expired |
| 95 |
(mandatory window) → call provider; on failure RAISE. Concurrent |
| 96 |
mandatory callers wait on a shared `Event` so exactly one provider |
| 97 |
call is in flight. |
| 98 |
* Cached with `expires_at=0` → never served. The provider does its own |
| 99 |
caching, so every call asks it again and concurrent callers each make |
| 100 |
their own call, so the provider must be safe to call concurrently. Only |
| 101 |
exactly `0` does this; any other past value is an expired token and is |
| 102 |
refreshed one call at a time. After a 401 empties the cache, one caller |
| 103 |
makes the `force_refresh=True` call and callers that arrive after the |
| 104 |
401 wait for it; calls already in flight finish on their own and do not |
| 105 |
repopulate the cache. Normal caching resumes once the provider returns a |
| 106 |
token with a real expiry. |
| 107 |
|
| 108 |
The lock is released before the provider call so a 30-second HTTP POST |
| 109 |
doesn't serialize unrelated callers through a single thread. This matters |
| 110 |
under async: `asyncify(get_token)` runs on the thread pool, and holding |
| 111 |
the lock across the network call would pin an async worker for the whole |
| 112 |
exchange. |
| 113 |
""" |
| 114 |
|
| 115 |
def __init__( |
| 116 |
self, |
| 117 |
provider: AccessTokenProvider | AsyncAccessTokenProvider, |
| 118 |
*, |
| 119 |
advisory_refresh_seconds: int = ADVISORY_REFRESH_SECONDS, |
| 120 |
mandatory_refresh_seconds: int = MANDATORY_REFRESH_SECONDS, |
| 121 |
time_source: Callable[[], float] = time.time, |
| 122 |
) -> None: |
| 123 |
self._provider: Optional[AccessTokenProvider] = None |
| 124 |
self._async_provider: Optional[AsyncAccessTokenProvider] = None |
| 125 |
if is_async_token_provider(provider): |
| 126 |
self._async_provider = provider |
| 127 |
else: |
| 128 |
self._provider = provider |
| 129 |
self._accepts_force_refresh = accepts_force_refresh(provider) |
| 130 |
self._advisory = advisory_refresh_seconds |
| 131 |
self._mandatory = mandatory_refresh_seconds |
| 132 |
self._time_source = time_source |
| 133 |
self._lock = threading.Lock() |
| 134 |
self._cached: Optional[AccessToken] = None |
| 135 |
# Set while a single-flight refresh is in flight. Waiters in the |
| 136 |
# mandatory window block on this event; the leader clears it after |
| 137 |
# publishing the fresh token (or on failure). An anyio.Event belongs to |
| 138 |
# the loop that created it, so a cache with an async provider is single-loop. |
| 139 |
self._refresh_event: Optional[Union[threading.Event, anyio.Event]] = None |
| 140 |
# One-shot: invalidate() sets it; the next single-flight leader passes |
| 141 |
# force_refresh=True so on-disk providers don't re-serve a stale token. |
| 142 |
self._next_force = False |
| 143 |
# Time of last advisory-refresh failure (never reset on success — |
| 144 |
# only distance-from-now matters). |
| 145 |
self._last_advisory_failure_time: float = 0.0 |
| 146 |
|
| 147 |
def _invoke_provider(self, provider: AccessTokenProvider, *, force: bool) -> AccessToken: |
| 148 |
"""Invoke `provider`, leaving out `force_refresh` for a legacy provider that doesn't take it.""" |
| 149 |
if not self._accepts_force_refresh: |
| 150 |
return provider() |
| 151 |
return provider(force_refresh=force) |
| 152 |
|
| 153 |
async def _async_invoke_provider(self, provider: AsyncAccessTokenProvider, *, force: bool) -> AccessToken: |
| 154 |
"""Async version of `_invoke_provider`.""" |
| 155 |
if not self._accepts_force_refresh: |
| 156 |
return await provider() |
| 157 |
return await provider(force_refresh=force) |
| 158 |
|
| 159 |
def _call_provider(self, provider: AccessTokenProvider, *, force: bool) -> AccessToken: |
| 160 |
"""Call the provider, retrying once on a 401 from the token endpoint.""" |
| 161 |
try: |
| 162 |
return valid_access_token(self._invoke_provider(provider, force=force)) |
| 163 |
except WorkloadIdentityError as err: |
| 164 |
if err.status_code != 401: |
| 165 |
raise |
| 166 |
log.debug("Token provider returned 401; retrying once") |
| 167 |
return valid_access_token(self._invoke_provider(provider, force=True)) |
| 168 |
|
| 169 |
async def _async_call_provider(self, provider: AsyncAccessTokenProvider, *, force: bool) -> AccessToken: |
| 170 |
"""Async version of `_call_provider`.""" |
| 171 |
try: |
| 172 |
return valid_access_token(await self._async_invoke_provider(provider, force=force)) |
| 173 |
except WorkloadIdentityError as err: |
| 174 |
if err.status_code != 401: |
| 175 |
raise |
| 176 |
log.debug("Token provider returned 401; retrying once") |
| 177 |
return valid_access_token(await self._async_invoke_provider(provider, force=True)) |
| 178 |
|
| 179 |
def get_token(self) -> str: |
| 180 |
"""Return a valid bearer token, refreshing if necessary.""" |
| 181 |
provider = self._provider |
| 182 |
if provider is None: |
| 183 |
raise RuntimeError( |
| 184 |
"This `TokenCache` wraps an async provider; call `async_get_token()` instead of `get_token()`." |
| 185 |
) |
| 186 |
while True: |
| 187 |
step = self._next_step(threading.Event) |
| 188 |
if isinstance(step, str): |
| 189 |
return step |
| 190 |
if isinstance(step, threading.Event): |
| 191 |
step.wait() |
| 192 |
# Loop back and re-read the cache — the refresh may have |
| 193 |
# succeeded (return fresh token), failed (start a new |
| 194 |
# refresh ourselves), or been invalidated in between. |
| 195 |
continue |
| 196 |
|
| 197 |
# Run the provider outside the lock. The except catches |
| 198 |
# BaseException (not a narrow tuple) so the refresh event is |
| 199 |
# always released — a user-supplied provider raising e.g. |
| 200 |
# RuntimeError must not deadlock mandatory-window waiters. |
| 201 |
try: |
| 202 |
fresh = self._call_provider(provider, force=step.force) |
| 203 |
except BaseException as err: |
| 204 |
stale_token = self._end_failed_refresh(err, step) |
| 205 |
if stale_token is None: |
| 206 |
raise |
| 207 |
return stale_token |
| 208 |
return self._end_refresh(fresh, step) |
| 209 |
|
| 210 |
async def async_get_token(self) -> str: |
| 211 |
"""Async version of `get_token`. |
| 212 |
|
| 213 |
An async provider is awaited on the event loop. A sync provider runs |
| 214 |
`get_token` in a worker thread. |
| 215 |
""" |
| 216 |
provider = self._async_provider |
| 217 |
if provider is None: |
| 218 |
return await asyncify(self.get_token)() |
| 219 |
while True: |
| 220 |
step = self._next_step(anyio.Event) |
| 221 |
if isinstance(step, str): |
| 222 |
return step |
| 223 |
if isinstance(step, anyio.Event): |
| 224 |
await step.wait() |
| 225 |
continue |
| 226 |
# CancelledError lands in the except too. Nothing in there awaits, |
| 227 |
# so a cancelled leader still releases its waiters. |
| 228 |
try: |
| 229 |
fresh = await self._async_call_provider(provider, force=step.force) |
| 230 |
except BaseException as err: |
| 231 |
stale_token = self._end_failed_refresh(err, step) |
| 232 |
if stale_token is None: |
| 233 |
raise |
| 234 |
return stale_token |
| 235 |
return self._end_refresh(fresh, step) |
| 236 |
|
| 237 |
def _next_step(self, event_class: Callable[[], _EventT]) -> Union[str, _EventT, Refresh[_EventT]]: |
| 238 |
"""Decide under the lock what the caller does next. |
| 239 |
|
| 240 |
A `str` is the token to serve. An event is a refresh in flight to wait on |
| 241 |
before asking again. A `Refresh` means call the provider, then |
| 242 |
`_end_refresh` or `_end_failed_refresh`. |
| 243 |
""" |
| 244 |
advisory_fallback: Optional[AccessToken] = None |
| 245 |
remaining_seconds = 0 |
| 246 |
with self._lock: |
| 247 |
cached = self._cached |
| 248 |
if cached is not None: |
| 249 |
if cached.expires_at is None: |
| 250 |
return cached.token |
| 251 |
if cached.expires_at == 0: |
| 252 |
# Per-request: no single-flight, and never forced. invalidate() empties |
| 253 |
# the cache, so the forced call after a 401 is always made by a leader. |
| 254 |
return Refresh(owned_event=None, force=False, advisory_fallback=None, remaining_seconds=0) |
| 255 |
remaining = cached.expires_at - self._time_source() |
| 256 |
if remaining > self._advisory: |
| 257 |
return cached.token |
| 258 |
if remaining > self._mandatory: |
| 259 |
# Advisory window. If a refresh is already running, |
| 260 |
# keep serving the cached token — don't queue and |
| 261 |
# don't start a second refresh. |
| 262 |
if self._refresh_event is not None: |
| 263 |
return cached.token |
| 264 |
# Backoff: skip refresh and serve cached after a |
| 265 |
# recent advisory failure. |
| 266 |
if self._time_source() - self._last_advisory_failure_time < ADVISORY_REFRESH_BACKOFF_SECONDS: |
| 267 |
return cached.token |
| 268 |
advisory_fallback = cached |
| 269 |
remaining_seconds = int(remaining) |
| 270 |
|
| 271 |
if self._refresh_event is not None: |
| 272 |
# Mandatory-window caller with a refresh in flight: wait. |
| 273 |
# cast: neither checker can know that one cache only ever creates one kind of event. |
| 274 |
return cast(_EventT, self._refresh_event) |
| 275 |
# We're the leader. The force flag is read in the same lock hold that elects the |
| 276 |
# leader, so a per-request call that started before an invalidate() can't take it. |
| 277 |
owned_event = self._refresh_event = event_class() |
| 278 |
return Refresh( |
| 279 |
owned_event=owned_event, |
| 280 |
force=self._next_force, |
| 281 |
advisory_fallback=advisory_fallback, |
| 282 |
remaining_seconds=remaining_seconds, |
| 283 |
) |
| 284 |
|
| 285 |
def _end_refresh(self, fresh: AccessToken, refresh: Refresh[_EventT]) -> str: |
| 286 |
with self._lock: |
| 287 |
if refresh.owned_event is None: |
| 288 |
# A per-request caller may only overwrite another per-request token. After |
| 289 |
# invalidate() the cache has to stay empty, so that the next caller makes |
| 290 |
# the forced call and everyone else waits for it. |
| 291 |
if self._cached is not None and self._cached.expires_at == 0: |
| 292 |
self._cached = fresh |
| 293 |
else: |
| 294 |
# The same goes for a leader whose unforced call overlapped an invalidate(): |
| 295 |
# its token may be the rejected one, so it is used for this request only. |
| 296 |
if refresh.force or not self._next_force: |
| 297 |
self._cached = fresh |
| 298 |
if refresh.force: |
| 299 |
# Cleared only after a forced call succeeds, so a failure still forces the next call. |
| 300 |
self._next_force = False |
| 301 |
self._refresh_event = None |
| 302 |
if refresh.owned_event is not None: |
| 303 |
refresh.owned_event.set() |
| 304 |
return fresh.token |
| 305 |
|
| 306 |
def _end_failed_refresh(self, err: BaseException, refresh: Refresh[_EventT]) -> Optional[str]: |
| 307 |
"""Release any waiters. Returns the stale token to serve if this was an advisory |
| 308 |
refresh, or `None` if the caller should re-raise `err`.""" |
| 309 |
if refresh.owned_event is not None: |
| 310 |
with self._lock: |
| 311 |
self._refresh_event = None |
| 312 |
refresh.owned_event.set() |
| 313 |
if refresh.advisory_fallback is None or not isinstance(err, (AnthropicError, httpx2.HTTPError)): |
| 314 |
return None |
| 315 |
log.warning( |
| 316 |
"Advisory token refresh failed (%ds remaining); serving cached token: %s", |
| 317 |
refresh.remaining_seconds, |
| 318 |
err, |
| 319 |
) |
| 320 |
with self._lock: |
| 321 |
self._last_advisory_failure_time = self._time_source() |
| 322 |
return refresh.advisory_fallback.token |
| 323 |
|
| 324 |
def invalidate(self) -> None: |
| 325 |
"""Clear the cached token so the next `get_token` re-invokes the provider. |
| 326 |
|
| 327 |
Also sets a one-shot `force_refresh` flag so on-disk providers skip |
| 328 |
their freshness short-circuit instead of re-serving the revoked token. |
| 329 |
""" |
| 330 |
with self._lock: |
| 331 |
self._cached = None |
| 332 |
self._next_force = True |