class documentation

Asynchronous bearer that refreshes tokens into a file-backed cache.

This bearer wraps a network-facing nebius.aio.token.token.Bearer and uses a ThrottledTokenCache for persistence. A background task may be spawned to proactively refresh the token before expiry. The class exposes control methods such as request_renewal, stop and close to coordinate lifecycle and shutdown.

Example

Wrap a custom bearer with a name and file cache:

from nebius.sdk import SDK
from nebius.aio.token.token import NamedBearer, Bearer, Receiver, Token
from nebius.aio.token.file_cache.async_renewable_bearer import (
    AsynchronousRenewableFileCacheBearer
)

class SomeCustomHeavyLoadBearer(Bearer):
    def receiver(self) -> Receiver:
        return SomeReceiver()

class SomeReceiver(Receiver):
    async def _fetch(self, timeout=None, options=None) -> Token:
        # Simulate heavy load token fetch
        return Token("heavy-token")

    def can_retry(self, err, options=None) -> bool:
        return False

custom_bearer = SomeCustomHeavyLoadBearer()
named_bearer = NamedBearer(custom_bearer, "heavy-load-bearer")
cached_bearer = AsynchronousRenewableFileCacheBearer(named_bearer)

sdk = SDK(credentials=cached_bearer)
Parameters
sourceWrapped bearer used to obtain fresh tokens. The source must have a non-empty nebius.aio.token.token.Bearer.name used as the cache key.
max_retriesDefault maximum retries for receivers produced by receiver.
initial_safety_marginSafety margin before token expiration used for the first fetch. The token will be immediately refreshed if the cache token is closer to expiry than this margin.
retry_safety_marginSafety margin applied when computing the initial retry interval for the background loop.
lifetime_safe_fractionFraction of the token lifetime used to schedule proactive refreshes (e.g. 0.9 means refresh at 90% of life).
initial_retry_timeoutInitial retry backoff timeout used after failures.
max_retry_timeoutMaximum retry backoff timeout used when backing off.
retry_timeout_exponentExponent used for exponential backoff.
refresh_request_timeoutDefault timeout forwarded to the wrapped receiver during refresh operations.
file_cache_throttleThrottle interval passed to ThrottledTokenCache to reduce disk reads.
Method __init__ Initialize the asynchronous renewable bearer.
Method bg_task Run a coroutine in fire-and-forget mode.
Async Method close Close the bearer and shutdown background tasks.
Async Method fetch Fetch a token, using the file cache and optionally requesting renewal.
Method is_renewal_required Return whether a renewal is required.
Method receiver Return a new AsynchronousRenewableFileCacheReceiver.
Method request_renewal Request a background token renewal.
Method stop Stop the background refresh loop and break any running attempt.
Instance Variable safety_margin A datetime.timedelta or seconds value used to determine when a token is considered too close to expiry. When None the cache will be used until tokens are actually expired.
Property wrapped Return the wrapped bearer instance.
Async Method _fetch_once Perform a single token refresh attempt.
Async Method _run Background refresh loop.
Instance Variable _break_previous_attempt Undocumented
Instance Variable _file_cache Undocumented
Instance Variable _initial_retry_timeout Undocumented
Instance Variable _is_fresh Undocumented
Instance Variable _is_stopped Undocumented
Instance Variable _lifetime_safe_fraction Undocumented
Instance Variable _max_retries Undocumented
Instance Variable _max_retry_timeout Undocumented
Instance Variable _refresh_request_timeout Undocumented
Instance Variable _refresh_task Undocumented
Instance Variable _renew_requested Undocumented
Instance Variable _renew_synchronous_options Undocumented
Instance Variable _renew_synchronous_timeout Undocumented
Instance Variable _renewal_attempt Undocumented
Instance Variable _renewal_future Undocumented
Instance Variable _retry_safety_margin Undocumented
Instance Variable _retry_timeout_exponent Undocumented
Instance Variable _source Undocumented
Instance Variable _synchronous_can_proceed Undocumented
Instance Variable _tasks Undocumented

Inherited from Bearer:

Property name Optional human-readable name for the bearer.
def __init__(self, source: ParentBearer, max_retries: int = 2, initial_safety_margin: timedelta | float | None = timedelta(hours=2), retry_safety_margin: timedelta = timedelta(hours=2), lifetime_safe_fraction: float = 0.9, initial_retry_timeout: timedelta = timedelta(seconds=1), max_retry_timeout: timedelta = timedelta(minutes=1), retry_timeout_exponent: float = 1.5, refresh_request_timeout: timedelta = timedelta(seconds=5), file_cache_throttle: timedelta | float = timedelta(minutes=5)): (source)

Initialize the asynchronous renewable bearer.

The constructor constructs a ThrottledTokenCache using the source bearer's nebius.aio.token.token.Bearer.name and prepares internal synchronization primitives used by the background refresh loop.

Raises
ValueErrorWhen the wrapped bearer has no name.
def bg_task(self, coro: Awaitable[T]) -> Task[None]: (source)

Run a coroutine in fire-and-forget mode.

The helper wraps the provided coroutine in a simple error-handling wrapper so exceptions are logged rather than lost. The returned asyncio.Task is tracked in _tasks and will be automatically removed when done.

Parameters
coro:Awaitable[T]Awaitable to schedule.
Returns
Task[None]The created asyncio.Task.
async def close(self, grace: float | None = None): (source)

Close the bearer and shutdown background tasks.

The method attempts a graceful shutdown by requesting the wrapped source to close, signalling the background loop to stop and cancelling any outstanding fire-and-forget tasks. Non-cancellation exceptions raised during shutdown are logged.

Parameters
grace:float | NoneOptional grace period forwarded to the wrapped bearer's close method.
async def fetch(self, timeout: float | None = None, options: dict[str, str] | None = None) -> Token: (source)

Fetch a token, using the file cache and optionally requesting renewal.

The method attempts to return a cached token when it is considered fresh according to safety_margin. If the token is missing or too close to expiry a renewal is requested. The renewal may be handled asynchronously by the background refresh loop or synchronously if the caller requests it via provided options.

Supported options

Parameters
timeout:float | NoneTimeout in seconds for synchronous waits.
options:dict[str, str] | NoneOptional dictionary of string options (see above).
Returns
TokenA valid Token.
Raises
RenewalErrorIf the cache is still empty after a renewal.
def is_renewal_required(self) -> bool: (source)

Return whether a renewal is required.

A renewal is considered required when no token is available in the in-memory cache or when a renewal request event has been set.

Return a new AsynchronousRenewableFileCacheReceiver.

Returns
AsynchronousRenewableFileCacheReceiverA receiver bound to this bearer which will forward fetch requests to the bearer and participate in the retry semantics.
def request_renewal(self): (source)

Request a background token renewal.

This method sets internal events so the background loop will attempt a refresh. If the bearer has been stopped the request is ignored.

def stop(self): (source)

Stop the background refresh loop and break any running attempt.

After calling this method the bearer will not perform further renewals until a new instance is created. The method also clears fresh-state events so callers waiting for tokens will fail fast.

safety_margin = (source)

A datetime.timedelta or seconds value used to determine when a token is considered too close to expiry. When None the cache will be used until tokens are actually expired.

Return the wrapped bearer instance.

Returns
The underlying bearer provided at construction.
async def _fetch_once(self) -> Token: (source)

Perform a single token refresh attempt.

This helper arranges concurrent tasks for fetching a token from the wrapped bearer and for canceling that fetch if a newer synchronous request arrives. On success the new token is persisted into the file cache and any waiting synchronous future is fulfilled.

Returns
TokenThe newly fetched Token.
async def _run(self, wait_for_timeout: bool = False): (source)

Background refresh loop.

The loop waits either for a renewal request event or for a timer indicating the next refresh time. On renewal it calls _fetch_once and updates the interval used for the next run. Failures are logged and the retry interval is increased using an exponential backoff strategy up to _max_retry_timeout.

Parameters
wait_for_timeout:boolWhen true the loop will compute an initial wait interval based on the currently cached token to avoid immediate refreshes.
_break_previous_attempt = (source)

Undocumented

_file_cache = (source)

Undocumented

_initial_retry_timeout = (source)

Undocumented

_is_fresh = (source)

Undocumented

_is_stopped = (source)

Undocumented

_lifetime_safe_fraction = (source)

Undocumented

_max_retries = (source)

Undocumented

_max_retry_timeout = (source)

Undocumented

_refresh_request_timeout = (source)

Undocumented

_refresh_task: Task[Any] | None = (source)

Undocumented

_renew_requested = (source)

Undocumented

_renew_synchronous_options: dict[str, str] | None = (source)

Undocumented

_renew_synchronous_timeout: float | None = (source)

Undocumented

_renewal_attempt: int = (source)

Undocumented

_renewal_future: Future[Token] | None = (source)

Undocumented

_retry_safety_margin = (source)

Undocumented

_retry_timeout_exponent = (source)

Undocumented

Undocumented

_synchronous_can_proceed = (source)

Undocumented

Undocumented