Skip to main content

graphrt_llm/credentials/
cached.rs

1//! Caching wrapper with single-flight refresh, fetch timeouts and shared failures.
2
3use std::collections::HashMap;
4use std::fmt;
5use std::sync::atomic::{AtomicU64, Ordering};
6use std::sync::{Arc, Mutex, PoisonError};
7use std::time::Duration;
8
9use futures::future::BoxFuture;
10use futures::lock::Mutex as AsyncMutex;
11
12use super::{Credential, CredentialSource, unix_now_ms};
13use crate::error::LlmError;
14
15/// Credentials are refreshed this long before they expire (60 s).
16pub const DEFAULT_REFRESH_SKEW_MS: u64 = 60_000;
17
18/// A fetch from the wrapped source that takes longer than this fails (15 s).
19pub const DEFAULT_FETCH_TIMEOUT: Duration = Duration::from_secs(15);
20
21#[derive(Default)]
22struct SlotState {
23    /// Cached credential and the source generation it was fetched under.
24    credential: Option<(Credential, u64)>,
25    /// Last failed fetch and its fetch sequence number.
26    failure: Option<(LlmError, u64)>,
27}
28
29/// One provider's cache slot. Holding the async lock while fetching makes
30/// concurrent requests wait for that single fetch instead of starting their own.
31#[derive(Default)]
32struct Slot {
33    state: AsyncMutex<SlotState>,
34    /// Number of fetches completed in this slot (success or failure).
35    completed: AtomicU64,
36}
37
38/// Caches credentials per provider until shortly before they expire.
39///
40/// - Credentials without `expires_at_ms` are cached until [`CredentialSource::invalidate`]
41///   or until the wrapped source's [`CredentialSource::generation`] changes (e.g. the
42///   host registered a different key source or signed the user out).
43/// - Concurrent requests for the same provider share one fetch. If that fetch
44///   fails, every request that was waiting behind it gets the same error instead of
45///   retrying the failing fetch one after another.
46/// - A fetch that does not finish within the fetch timeout (default 15 s) fails
47///   with [`LlmError::Auth`]. The timeout needs the `http` feature (it brings the
48///   Tokio timer) and a Tokio runtime. In builds without `http`, or outside a Tokio
49///   runtime, fetches are not time-limited: a source that never answers keeps its
50///   waiters waiting.
51/// - `invalidate` drops the cached value and forwards to the inner source.
52pub struct CachedCredentials<S> {
53    inner: S,
54    skew_ms: u64,
55    fetch_timeout: Duration,
56    slots: Mutex<HashMap<String, Arc<Slot>>>,
57}
58
59impl<S: CredentialSource> CachedCredentials<S> {
60    pub fn new(inner: S) -> Self {
61        Self {
62            inner,
63            skew_ms: DEFAULT_REFRESH_SKEW_MS,
64            fetch_timeout: DEFAULT_FETCH_TIMEOUT,
65            slots: Mutex::new(HashMap::new()),
66        }
67    }
68
69    /// Refresh this many milliseconds before expiry.
70    pub fn refresh_skew_ms(mut self, skew_ms: u64) -> Self {
71        self.skew_ms = skew_ms;
72        self
73    }
74
75    /// Fail a fetch from the wrapped source after this long.
76    pub fn fetch_timeout(mut self, timeout: Duration) -> Self {
77        self.fetch_timeout = timeout;
78        self
79    }
80
81    /// The wrapped source.
82    pub fn inner(&self) -> &S {
83        &self.inner
84    }
85
86    /// Drop every cached credential (all providers).
87    pub fn clear(&self) {
88        let mut slots = self.slots.lock().unwrap_or_else(PoisonError::into_inner);
89        slots.clear();
90    }
91
92    fn slot(&self, provider: &str) -> Arc<Slot> {
93        let mut slots = self.slots.lock().unwrap_or_else(PoisonError::into_inner);
94        slots.entry(provider.to_owned()).or_default().clone()
95    }
96
97    async fn fetch(&self, provider: &str) -> Result<Credential, LlmError> {
98        let fetch = self.inner.credential(provider);
99        #[cfg(feature = "http")]
100        {
101            if tokio::runtime::Handle::try_current().is_ok() {
102                return match tokio::time::timeout(self.fetch_timeout, fetch).await {
103                    Ok(result) => result,
104                    Err(_) => Err(LlmError::Auth(format!(
105                        "credential source for `{provider}` did not answer within {} ms",
106                        self.fetch_timeout.as_millis()
107                    ))),
108                };
109            }
110        }
111        fetch.await
112    }
113}
114
115impl<S> fmt::Debug for CachedCredentials<S>
116where
117    S: fmt::Debug,
118{
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        f.debug_struct("CachedCredentials")
121            .field("inner", &self.inner)
122            .field("skew_ms", &self.skew_ms)
123            .field("fetch_timeout", &self.fetch_timeout)
124            .finish()
125    }
126}
127
128impl<S: CredentialSource> CredentialSource for CachedCredentials<S> {
129    fn credential<'a>(&'a self, provider: &'a str) -> BoxFuture<'a, Result<Credential, LlmError>> {
130        Box::pin(async move {
131            let slot = self.slot(provider);
132            // Fetches completed before we started waiting; a failure recorded after
133            // this point belongs to a fetch we were queued behind.
134            let ticket = slot.completed.load(Ordering::SeqCst);
135            let mut state = slot.state.lock().await;
136            if let Some((error, seq)) = &state.failure
137                && *seq > ticket
138            {
139                return Err(error.clone());
140            }
141            let generation = self.inner.generation();
142            if let Some((credential, cached_generation)) = &state.credential {
143                let fresh = *cached_generation == generation && !credential.is_expired_at(unix_now_ms(), self.skew_ms);
144                if fresh {
145                    return Ok(credential.clone());
146                }
147            }
148            let result = self.fetch(provider).await;
149            let seq = slot.completed.fetch_add(1, Ordering::SeqCst).saturating_add(1);
150            match result {
151                Ok(credential) => {
152                    state.credential = Some((credential.clone(), generation));
153                    state.failure = None;
154                    Ok(credential)
155                }
156                Err(error) => {
157                    state.credential = None;
158                    state.failure = Some((error.clone(), seq));
159                    Err(error)
160                }
161            }
162        })
163    }
164
165    fn invalidate(&self, provider: &str) {
166        // Replace the slot: requests already waiting on the old slot finish with
167        // whatever it holds; new requests fetch again.
168        {
169            let mut slots = self.slots.lock().unwrap_or_else(PoisonError::into_inner);
170            slots.insert(provider.to_owned(), Arc::new(Slot::default()));
171        }
172        self.inner.invalidate(provider);
173    }
174
175    fn generation(&self) -> u64 {
176        self.inner.generation()
177    }
178}
179
180impl<S: CredentialSource + ?Sized> CredentialSource for Arc<S> {
181    fn credential<'a>(&'a self, provider: &'a str) -> BoxFuture<'a, Result<Credential, LlmError>> {
182        (**self).credential(provider)
183    }
184
185    fn invalidate(&self, provider: &str) {
186        (**self).invalidate(provider);
187    }
188
189    fn generation(&self) -> u64 {
190        (**self).generation()
191    }
192}
193
194#[cfg(test)]
195mod tests {
196    use std::sync::atomic::{AtomicUsize, Ordering};
197
198    use super::*;
199
200    #[derive(Debug, Default)]
201    struct Counting {
202        calls: AtomicUsize,
203        ttl_ms: Option<u64>,
204        generation: AtomicU64,
205    }
206
207    impl CredentialSource for Counting {
208        fn credential<'a>(&'a self, _provider: &'a str) -> BoxFuture<'a, Result<Credential, LlmError>> {
209            let n = self.calls.fetch_add(1, Ordering::SeqCst) + 1;
210            let mut c = Credential::new(format!("token-{n}"));
211            if let Some(ttl) = self.ttl_ms {
212                c = c.expires_at(unix_now_ms() + ttl);
213            }
214            Box::pin(async move { Ok(c) })
215        }
216
217        fn generation(&self) -> u64 {
218            self.generation.load(Ordering::SeqCst)
219        }
220    }
221
222    #[tokio::test]
223    async fn caches_until_invalidated() {
224        let cache = CachedCredentials::new(Counting::default());
225        let a = cache.credential("p").await.unwrap();
226        let b = cache.credential("p").await.unwrap();
227        assert_eq!(a.secret, "token-1");
228        assert_eq!(b.secret, "token-1");
229        cache.invalidate("p");
230        let c = cache.credential("p").await.unwrap();
231        assert_eq!(c.secret, "token-2");
232        // Providers are cached independently.
233        let other = cache.credential("q").await.unwrap();
234        assert_eq!(other.secret, "token-3");
235    }
236
237    #[tokio::test]
238    async fn source_generation_change_drops_cached_values() {
239        let cache = CachedCredentials::new(Counting::default());
240        assert_eq!(cache.credential("p").await.unwrap().secret, "token-1");
241        // e.g. the host signed user A out and registered user B's key source.
242        cache.inner().generation.fetch_add(1, Ordering::SeqCst);
243        assert_eq!(cache.credential("p").await.unwrap().secret, "token-2");
244        cache.clear();
245        assert_eq!(cache.credential("p").await.unwrap().secret, "token-3");
246    }
247
248    #[tokio::test]
249    async fn refreshes_near_expiry() {
250        // Expires in 30 s, refresh skew 60 s: always considered stale.
251        let cache = CachedCredentials::new(Counting { ttl_ms: Some(30_000), ..Counting::default() });
252        let a = cache.credential("p").await.unwrap();
253        let b = cache.credential("p").await.unwrap();
254        assert_ne!(a.secret, b.secret);
255        // With a smaller skew the same credential is reused.
256        let cache =
257            CachedCredentials::new(Counting { ttl_ms: Some(30_000), ..Counting::default() }).refresh_skew_ms(1_000);
258        let a = cache.credential("p").await.unwrap();
259        let b = cache.credential("p").await.unwrap();
260        assert_eq!(a.secret, b.secret);
261    }
262
263    #[tokio::test]
264    async fn concurrent_requests_share_one_fetch() {
265        #[derive(Debug, Default)]
266        struct Slow(AtomicUsize);
267        impl CredentialSource for Slow {
268            fn credential<'a>(&'a self, _p: &'a str) -> BoxFuture<'a, Result<Credential, LlmError>> {
269                Box::pin(async move {
270                    self.0.fetch_add(1, Ordering::SeqCst);
271                    tokio::time::sleep(std::time::Duration::from_millis(30)).await;
272                    Ok(Credential::new("t"))
273                })
274            }
275        }
276        let cache = Arc::new(CachedCredentials::new(Slow::default()));
277        let futs = (0..8).map(|_| {
278            let c = cache.clone();
279            async move { c.credential("p").await }
280        });
281        let results = futures::future::join_all(futs).await;
282        assert!(results.iter().all(Result::is_ok));
283        assert_eq!(cache.inner().0.load(Ordering::SeqCst), 1);
284    }
285
286    /// A source that never answers.
287    #[derive(Debug, Default)]
288    struct Hangs(AtomicUsize);
289    impl CredentialSource for Hangs {
290        fn credential<'a>(&'a self, _p: &'a str) -> BoxFuture<'a, Result<Credential, LlmError>> {
291            Box::pin(async move {
292                self.0.fetch_add(1, Ordering::SeqCst);
293                futures::future::pending::<()>().await;
294                Ok(Credential::new("never"))
295            })
296        }
297    }
298
299    /// Longest the timeout test waits: a regression fails the test instead of hanging it.
300    #[cfg(feature = "http")]
301    const TEST_LIMIT: Duration = Duration::from_secs(5);
302
303    #[cfg(feature = "http")]
304    #[tokio::test]
305    async fn waiters_share_one_failure_and_hung_sources_time_out() {
306        let cache = Arc::new(CachedCredentials::new(Hangs::default()).fetch_timeout(Duration::from_millis(50)));
307        let started = std::time::Instant::now();
308        let futs = (0..6).map(|_| {
309            let c = cache.clone();
310            async move { c.credential("p").await }
311        });
312        let results = tokio::time::timeout(TEST_LIMIT, futures::future::join_all(futs))
313            .await
314            .expect("the fetch timeout ends every waiter");
315        assert!(results.iter().all(|r| matches!(r, Err(LlmError::Auth(_)))));
316        // One fetch timed out and every waiter got its error: not 6 serial timeouts.
317        assert_eq!(cache.inner().0.load(Ordering::SeqCst), 1);
318        assert!(started.elapsed() < Duration::from_millis(250), "{:?}", started.elapsed());
319        // A later request tries again.
320        let again = tokio::time::timeout(TEST_LIMIT, cache.credential("p")).await.expect("times out again");
321        assert!(again.is_err());
322        assert_eq!(cache.inner().0.load(Ordering::SeqCst), 2);
323    }
324
325    /// Without `http` there is no timer: a hung source is not cut short, as documented.
326    #[cfg(not(feature = "http"))]
327    #[tokio::test]
328    async fn without_http_a_hung_source_is_not_time_limited() {
329        let cache = CachedCredentials::new(Hangs::default()).fetch_timeout(Duration::from_millis(10));
330        let waited = tokio::time::timeout(Duration::from_millis(200), cache.credential("p")).await;
331        assert!(waited.is_err(), "the fetch should still be pending");
332        assert_eq!(cache.inner().0.load(Ordering::SeqCst), 1);
333    }
334}