class AsynchronousRenewableFileCacheBearer(ParentBearer): (source)
Constructor: AsynchronousRenewableFileCacheBearer(source, max_retries, initial_safety_margin, retry_safety_margin, ...)
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 | |
| source | Wrapped 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 | Default maximum retries for receivers produced by
receiver. |
| initial | Safety 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 margin applied when computing the initial retry interval for the background loop. |
| lifetime | Fraction of the token lifetime used to schedule proactive refreshes (e.g. 0.9 means refresh at 90% of life). |
| initial | Initial retry backoff timeout used after failures. |
| max | Maximum retry backoff timeout used when backing off. |
| retry | Exponent used for exponential backoff. |
| refresh | Default timeout forwarded to the wrapped receiver during refresh operations. |
| file | Throttle interval passed to
ThrottledTokenCache to reduce disk reads. |
| Method | __init__ |
Initialize the asynchronous renewable bearer. |
| Method | bg |
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 |
Return whether a renewal is required. |
| Method | receiver |
Return a new AsynchronousRenewableFileCacheReceiver. |
| Method | request |
Request a background token renewal. |
| Method | stop |
Stop the background refresh loop and break any running attempt. |
| Instance Variable | safety |
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 |
Perform a single token refresh attempt. |
| Async Method | _run |
Background refresh loop. |
| Instance Variable | _break |
Undocumented |
| Instance Variable | _file |
Undocumented |
| Instance Variable | _initial |
Undocumented |
| Instance Variable | _is |
Undocumented |
| Instance Variable | _is |
Undocumented |
| Instance Variable | _lifetime |
Undocumented |
| Instance Variable | _max |
Undocumented |
| Instance Variable | _max |
Undocumented |
| Instance Variable | _refresh |
Undocumented |
| Instance Variable | _refresh |
Undocumented |
| Instance Variable | _renew |
Undocumented |
| Instance Variable | _renew |
Undocumented |
| Instance Variable | _renew |
Undocumented |
| Instance Variable | _renewal |
Undocumented |
| Instance Variable | _renewal |
Undocumented |
| Instance Variable | _retry |
Undocumented |
| Instance Variable | _retry |
Undocumented |
| Instance Variable | _source |
Undocumented |
| Instance Variable | _synchronous |
Undocumented |
| Instance Variable | _tasks |
Undocumented |
Inherited from Bearer:
| Property | name |
Optional human-readable name for the bearer. |
ParentBearer, max_retries: int = 2, initial_safety_margin: timedelta | float | None = timedelta(timedelta = timedelta(float = 0.9, initial_retry_timeout: timedelta = timedelta(timedelta = timedelta(float = 1.5, refresh_request_timeout: timedelta = timedelta(timedelta | float = timedelta(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 | |
ValueError | When the wrapped bearer has no name. |
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[ | Awaitable to schedule. |
| Returns | |
Task[ | The created asyncio.Task. |
nebius.aio.token.token.Bearer.closeClose 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 | None | Optional grace period forwarded to the wrapped
bearer's close method. |
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
OPTION_RENEW_REQUIRED-- Force a renewal even if a cached token exists.OPTION_RENEW_SYNCHRONOUS-- Request the renewal synchronously and wait for the result.OPTION_REPORT_ERROR-- Return exceptions from the renewal to the caller via the returned future.OPTION_RENEW_REQUEST_TIMEOUT-- When performing a synchronous request, this value (string float) can override the request timeout.
| Parameters | |
timeout:float | None | Timeout in seconds for synchronous waits. |
options:dict[ | Optional dictionary of string options (see above). |
| Returns | |
Token | A valid Token. |
| Raises | |
RenewalError | If the cache is still empty after a renewal. |
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.
nebius.aio.token.token.Bearer.receiverReturn a new AsynchronousRenewableFileCacheReceiver.
| Returns | |
AsynchronousRenewableFileCacheReceiver | A receiver bound to this bearer which will forward fetch requests to the bearer and participate in the retry semantics. |
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.
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.
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.
nebius.aio.token.token.Bearer.wrappedReturn the wrapped bearer instance.
| Returns | |
| The underlying bearer provided at construction. |
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 | |
Token | The newly fetched Token. |
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 | |
waitbool | When true the loop will compute an initial wait interval based on the currently cached token to avoid immediate refreshes. |