1use std::fmt::Debug;
4use std::hash::Hash;
5use std::sync::Arc;
6use std::time::Duration;
7
8use moka::future::Cache;
9use tracing::{info, trace};
10
11pub trait CacheKey: Hash + Eq + Send + Sync + Clone + Debug + 'static {
13 const CACHE_NAME: &'static str;
16
17 fn matches_source(&self, source_id: &str) -> bool;
19
20 fn record_outcome(&self, hit: bool);
22}
23
24pub trait Cacheable: Send + Sync + Clone + 'static {
26 fn weight(&self) -> u32;
29}
30
31#[derive(Clone)]
34pub struct ResourceCache<K: CacheKey, V: Cacheable> {
35 inner: Cache<K, V>,
36}
37
38impl<K: CacheKey, V: Cacheable> Debug for ResourceCache<K, V> {
39 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40 f.debug_struct("ResourceCache")
41 .field("name", &K::CACHE_NAME)
42 .field("entry_count", &self.inner.entry_count())
43 .field("weighted_size", &self.inner.weighted_size())
44 .finish()
45 }
46}
47
48impl<K: CacheKey, V: Cacheable> ResourceCache<K, V> {
49 #[must_use]
51 pub fn new(max_size_bytes: u64, expiry: Option<Duration>, idle_timeout: Option<Duration>) -> Self {
52 let mut builder = Cache::builder()
53 .name(K::CACHE_NAME)
54 .weigher(|_key: &K, value: &V| value.weight())
55 .max_capacity(max_size_bytes)
56 .support_invalidation_closures();
57 if let Some(ttl) = expiry {
58 builder = builder.time_to_live(ttl);
59 }
60 if let Some(tti) = idle_timeout {
61 builder = builder.time_to_idle(tti);
62 }
63 Self { inner: builder.build() }
64 }
65
66 pub async fn get_or_insert<F, Fut, E>(&self, key: K, compute: F) -> Result<V, Arc<E>>
68 where
69 F: FnOnce() -> Fut,
70 Fut: Future<Output = Result<V, E>>,
71 E: Send + Sync + 'static,
72 {
73 let entry = self
74 .inner
75 .entry_by_ref(&key)
76 .or_try_insert_with(async move { compute().await })
77 .await?;
78
79 let hit = !entry.is_fresh();
80 key.record_outcome(hit);
81 if hit {
82 trace!(
83 cache.name = %K::CACHE_NAME,
84 cache.key = ?key,
85 cache.entries = self.inner.entry_count(),
86 cache.size = self.inner.weighted_size(),
87 "Cache hit"
88 );
89 } else {
90 trace!(cache.name = %K::CACHE_NAME, cache.key = ?key, "Cache miss");
91 }
92
93 Ok(entry.into_value())
94 }
95
96 pub async fn get(&self, key: &K) -> Option<V> {
99 self.inner.get(key).await
100 }
101
102 pub async fn insert(&self, key: K, value: V) {
104 self.inner.insert(key, value).await;
105 }
106
107 pub fn invalidate_source(&self, source_id: &str) {
111 let source_id_owned = source_id.to_owned();
112 self.inner
113 .invalidate_entries_if(move |key, _| key.matches_source(&source_id_owned))
114 .expect("invalidate_entries_if predicate should not error");
115 info!(
116 cache.name = %K::CACHE_NAME,
117 source.id = %source_id,
118 "Invalidated cache for source"
119 );
120 }
121
122 pub fn invalidate_all(&self) {
126 self.inner.invalidate_all();
127 info!(cache.name = %K::CACHE_NAME, "Invalidated all cache entries");
128 }
129
130 #[must_use]
133 pub fn entry_count(&self) -> u64 {
134 self.inner.entry_count()
135 }
136
137 pub fn contains_key(&self, key: &K) -> bool {
146 self.inner.contains_key(key)
147 }
148
149 #[must_use]
151 pub fn weighted_size(&self) -> u64 {
152 self.inner.weighted_size()
153 }
154
155 pub async fn run_pending_tasks(&self) {
159 self.inner.run_pending_tasks().await;
160 }
161}
162
163impl Cacheable for Vec<u8> {
164 fn weight(&self) -> u32 {
165 self.len().try_into().unwrap_or(u32::MAX)
166 }
167}
168
169#[must_use]
172pub const fn hit_miss_label(hit: bool) -> &'static str {
173 if hit { "hit" } else { "miss" }
174}
175
176#[cfg(test)]
177mod tests {
178 use std::sync::atomic::{AtomicU32, Ordering};
179
180 use rstest::rstest;
181
182 use super::*;
183
184 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
187 struct TestKey {
188 ids: String,
189 }
190
191 impl TestKey {
192 fn new(ids: &str) -> Self {
193 Self { ids: ids.to_owned() }
194 }
195 }
196
197 impl CacheKey for TestKey {
198 const CACHE_NAME: &'static str = "test";
199
200 fn matches_source(&self, source_id: &str) -> bool {
201 self.ids.split(',').any(|s| s == source_id)
202 }
203
204 fn record_outcome(&self, _hit: bool) {}
205 }
206
207 fn cache() -> ResourceCache<TestKey, Vec<u8>> {
208 ResourceCache::new(1_000_000, None, None)
209 }
210
211 #[tokio::test]
212 async fn miss_calls_compute_and_returns_value() {
213 let cache = cache();
214 let calls = AtomicU32::new(0);
215
216 let value = cache
217 .get_or_insert(TestKey::new("a"), || async {
218 calls.fetch_add(1, Ordering::SeqCst);
219 Ok::<_, std::convert::Infallible>(vec![1, 2, 3])
220 })
221 .await
222 .unwrap();
223
224 assert_eq!(value, vec![1, 2, 3]);
225 assert_eq!(calls.load(Ordering::SeqCst), 1);
226 }
227
228 #[tokio::test]
229 async fn hit_does_not_call_compute() {
230 let cache = cache();
231 let calls = AtomicU32::new(0);
232 let compute = || async {
233 calls.fetch_add(1, Ordering::SeqCst);
234 Ok::<_, std::convert::Infallible>(vec![7])
235 };
236
237 cache.get_or_insert(TestKey::new("a"), compute).await.unwrap();
238 cache.get_or_insert(TestKey::new("a"), compute).await.unwrap();
239
240 assert_eq!(calls.load(Ordering::SeqCst), 1, "second call should hit cache");
241 }
242
243 #[rstest]
244 #[case::two_keys_invalidate_one(&["foo", "bar"], "foo", &["bar"])]
245 #[case::substring_regression(&["foo", "foobar"], "foo", &["foobar"])]
246 #[case::predicate_fires_for_csv_key(&["a,b,c"], "b", &[])]
247 #[tokio::test]
248 async fn invalidate_source(#[case] entries: &[&str], #[case] target: &str, #[case] expected_remaining: &[&str]) {
249 let cache = cache();
250 for ids in entries {
251 cache
252 .get_or_insert(TestKey::new(ids), || async {
253 Ok::<_, std::convert::Infallible>(vec![0_u8])
254 })
255 .await
256 .unwrap();
257 }
258 cache.run_pending_tasks().await;
259
260 cache.invalidate_source(target);
261 cache.run_pending_tasks().await;
262
263 for ids in entries {
264 let key = TestKey::new(ids);
265 let should_remain = expected_remaining.contains(ids);
266 assert_eq!(
267 cache.contains_key(&key),
268 should_remain,
269 "{ids:?} membership after invalidating {target:?}"
270 );
271 }
272 }
273
274 #[tokio::test]
275 async fn invalidate_all_clears_entries() {
276 let cache = cache();
277 let compute = || async { Ok::<_, std::convert::Infallible>(vec![0_u8]) };
278 let a = TestKey::new("a");
279 let b = TestKey::new("b");
280
281 cache.get_or_insert(a.clone(), compute).await.unwrap();
282 cache.get_or_insert(b.clone(), compute).await.unwrap();
283 cache.run_pending_tasks().await;
284
285 cache.invalidate_all();
286 cache.run_pending_tasks().await;
287
288 assert!(!cache.contains_key(&a));
289 assert!(!cache.contains_key(&b));
290 }
291
292 #[tokio::test]
293 async fn compute_error_is_not_cached() {
294 let cache = cache();
295 let calls = AtomicU32::new(0);
296
297 let first = cache
298 .get_or_insert(TestKey::new("a"), || async {
299 calls.fetch_add(1, Ordering::SeqCst);
300 Err::<Vec<u8>, _>("boom")
301 })
302 .await;
303 first.expect_err("compute returned Err so cache should propagate");
304
305 cache
306 .get_or_insert(TestKey::new("a"), || async {
307 calls.fetch_add(1, Ordering::SeqCst);
308 Ok::<_, &'static str>(vec![1])
309 })
310 .await
311 .unwrap();
312
313 assert_eq!(
314 calls.load(Ordering::SeqCst),
315 2,
316 "errored compute should not persist a cache entry"
317 );
318 }
319
320 #[test]
321 fn vec_u8_weight_is_length_saturating() {
322 assert_eq!(Cacheable::weight(&vec![]), 0);
323 assert_eq!(Cacheable::weight(&vec![0; 7]), 7);
324 }
325}