CachingTokenProvider

class CachingTokenProvider(refreshLeeway: Duration = 30.seconds, clock: () -> Instant = Instant::now, fetch: suspend () -> String)

Caches the token from an access-token provider until shortly before it expires, so the provider is consulted once per token lifetime instead of once per request.

Expiry comes from the token itself: Ledger API tokens are JWTs, and the standard exp claim is read from the payload. A token without a parseable exp is cached until refreshIfChanged forces a fetch — the right behaviour for non-expiring development tokens.

refreshIfChanged exists for the failure path: when the server rejects a connection for authentication reasons, the caller fetches fresh and learns whether retrying can possibly help. A provider that returns the same token it returned before has nothing new to offer, and the rejection is final.

Constructors

Link copied to clipboard
constructor(refreshLeeway: Duration = 30.seconds, clock: () -> Instant = Instant::now, fetch: suspend () -> String)

Functions

Link copied to clipboard
fun cached(): String?

Last token handed out, without fetching. Null until the first token call.

Link copied to clipboard
suspend fun refreshIfChanged(previous: String?): Boolean

Forces a fetch and reports whether the result differs from previous. false means the provider cannot supply anything newer — an authentication failure seen with previous will repeat.

Link copied to clipboard
suspend fun token(): String

The cached token, refreshed via fetch when within refreshLeeway of expiry.