SudregEx.TokenCache (sudreg_ex v0.1.0)

Copy Markdown View Source

Caches OAuth2 bearer tokens per client_id and refreshes them on expiry.

Started under the application's supervision tree by default, unless disabled with config :sudreg_ex, start_token_cache: false. The cache is keyed by client_id only (the credential identity); a future multi-tenant need could re-key by {client_id, token_url}.

Concurrency

Requests are serialised through the GenServer. A valid cache hit replies immediately; a miss/expiry performs the token fetch synchronously inside the server, so while one refresh is in flight other callers wait behind it (and a refresh that just completed means the next caller usually sees a fresh token rather than refetching). Because the fetch is synchronous, fetch/2 uses a generous 30000ms call timeout — comfortably above Req's default receive timeout — so a slow token endpoint does not crash waiting callers.

A fully non-blocking refresh (replying to cache hits while a refresh runs off the call path) is a deliberate future enhancement; the current design keeps it simple, correct, and serialised.

Summary

Functions

Returns a specification to start this module under a supervisor.

Returns a valid token for client, fetching or refreshing as needed.

Starts the cache. Accepts :name (defaults to SudregEx.TokenCache).

Functions

child_spec(init_arg)

Returns a specification to start this module under a supervisor.

See Supervisor.

fetch(server \\ __MODULE__, client)

@spec fetch(GenServer.server(), SudregEx.Client.t()) ::
  {:ok, SudregEx.Token.t()} | {:error, SudregEx.Error.t()}

Returns a valid token for client, fetching or refreshing as needed.

start_link(opts \\ [])

@spec start_link(keyword()) :: GenServer.on_start()

Starts the cache. Accepts :name (defaults to SudregEx.TokenCache).