Skip to main content

ant_node/payment/
cache.rs

1//! LRU cache for verified `XorName` values.
2//!
3//! Caches `XorName` values that have been verified to exist on the autonomi network,
4//! reducing the number of network queries needed for repeated/popular data.
5
6use lru::LruCache;
7use parking_lot::Mutex;
8use std::num::NonZeroUsize;
9use std::sync::atomic::{AtomicU64, Ordering};
10use std::sync::Arc;
11
12pub use super::quote::XorName;
13pub use super::verifier::PaymentTarget as PaidKey;
14
15/// Default cache capacity (100,000 entries = 3.2MB memory).
16const DEFAULT_CACHE_CAPACITY: usize = 100_000;
17
18/// LRU cache for verified `XorName` values.
19///
20/// This cache stores `XorName` values that have been verified to exist on the
21/// autonomi network, avoiding repeated network queries for the same data.
22///
23/// Each entry records which fresh proof verification level inserted it. A
24/// paid-list entry must not satisfy a later client-PUT fast-path because
25/// paid-list admission does not authorize storing the actual chunk. Stronger
26/// entries satisfy weaker lookups.
27#[derive(Clone)]
28pub struct VerifiedCache {
29    inner: Arc<Mutex<LruCache<PaidKey, VerificationLevel>>>,
30    hits: Arc<AtomicU64>,
31    misses: Arc<AtomicU64>,
32    additions: Arc<AtomicU64>,
33}
34
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
36enum VerificationLevel {
37    PaidList,
38    ClientPut,
39}
40
41impl VerificationLevel {
42    fn satisfies(self, required: Self) -> bool {
43        matches!(
44            (self, required),
45            (Self::PaidList, Self::PaidList) | (Self::ClientPut, Self::PaidList | Self::ClientPut)
46        )
47    }
48}
49
50/// Cache statistics for monitoring.
51#[derive(Debug, Default, Clone, Copy)]
52pub struct CacheStats {
53    /// Number of cache hits.
54    pub hits: u64,
55    /// Number of cache misses.
56    pub misses: u64,
57    /// Number of entries added.
58    pub additions: u64,
59}
60
61impl CacheStats {
62    /// Calculate hit rate as a percentage.
63    #[must_use]
64    #[allow(clippy::cast_precision_loss)]
65    pub fn hit_rate(&self) -> f64 {
66        let total = self.hits + self.misses;
67        if total == 0 {
68            0.0
69        } else {
70            (self.hits as f64 / total as f64) * 100.0
71        }
72    }
73}
74
75impl VerifiedCache {
76    /// Create a new cache with default capacity.
77    #[must_use]
78    pub fn new() -> Self {
79        Self::with_capacity(DEFAULT_CACHE_CAPACITY)
80    }
81
82    /// Create a new cache with the specified capacity.
83    ///
84    /// If capacity is 0, defaults to 1.
85    #[must_use]
86    pub fn with_capacity(capacity: usize) -> Self {
87        // Use max(1, capacity) to ensure non-zero, avoiding unsafe or expect
88        let effective_capacity = capacity.max(1);
89        // This is guaranteed to succeed since effective_capacity >= 1
90        // Using if-let pattern since we know it will always be Some
91        let cap = NonZeroUsize::new(effective_capacity).unwrap_or(NonZeroUsize::MIN);
92        Self {
93            inner: Arc::new(Mutex::new(LruCache::new(cap))),
94            hits: Arc::new(AtomicU64::new(0)),
95            misses: Arc::new(AtomicU64::new(0)),
96            additions: Arc::new(AtomicU64::new(0)),
97        }
98    }
99
100    /// Check if a `XorName` is in the cache (verified under any fresh check set).
101    ///
102    /// Returns `true` if the `XorName` is cached (verified to exist on autonomi).
103    /// Paid-list and client-PUT lookups must use their stricter helpers.
104    #[must_use]
105    pub fn contains_key(&self, key: &PaidKey) -> bool {
106        let found = self.inner.lock().get(key).is_some();
107
108        if found {
109            self.hits.fetch_add(1, Ordering::Relaxed);
110        } else {
111            self.misses.fetch_add(1, Ordering::Relaxed);
112        }
113
114        found
115    }
116
117    /// Check if a `XorName` is cached AND its verification ran at least the
118    /// paid-list admission check set.
119    ///
120    /// A client-PUT entry returns `true` here because it passed the stricter
121    /// store-admission path at the caller.
122    #[must_use]
123    pub fn contains_paid_list_verified_key(&self, key: &PaidKey) -> bool {
124        let found = self
125            .inner
126            .lock()
127            .get(key)
128            .copied()
129            .is_some_and(|level| level.satisfies(VerificationLevel::PaidList));
130
131        if found {
132            self.hits.fetch_add(1, Ordering::Relaxed);
133        } else {
134            self.misses.fetch_add(1, Ordering::Relaxed);
135        }
136
137        found
138    }
139
140    /// Check if a `XorName` is cached AND its verification ran the full
141    /// client-PUT store-admission check set.
142    ///
143    /// Paid-list entries return `false` here because they did not pass the
144    /// client-PUT store-admission path.
145    #[must_use]
146    pub fn contains_client_put_verified_key(&self, key: &PaidKey) -> bool {
147        let found = self
148            .inner
149            .lock()
150            .get(key)
151            .copied()
152            .is_some_and(|level| level.satisfies(VerificationLevel::ClientPut));
153
154        if found {
155            self.hits.fetch_add(1, Ordering::Relaxed);
156        } else {
157            self.misses.fetch_add(1, Ordering::Relaxed);
158        }
159
160        found
161    }
162
163    /// Add a `XorName` verified under the full client-PUT check set.
164    ///
165    /// This should be called after verifying that data exists on the autonomi network.
166    /// Also upgrades an existing paid-list-verified entry.
167    pub fn insert_key(&self, key: PaidKey) {
168        self.insert_with_level(key, VerificationLevel::ClientPut);
169    }
170
171    /// Add a `XorName` verified under paid-list admission checks.
172    ///
173    /// Never downgrades an existing client-PUT-verified entry.
174    pub fn insert_paid_list_verified_key(&self, key: PaidKey) {
175        self.insert_with_level(key, VerificationLevel::PaidList);
176    }
177
178    fn insert_with_level(&self, key: PaidKey, level: VerificationLevel) {
179        let added = {
180            let mut inner = self.inner.lock();
181            // `get_mut` refreshes LRU recency for existing entries of either kind.
182            if inner.get(&key).is_some() {
183                if let Some(existing) = inner.get_mut(&key) {
184                    if !existing.satisfies(level) {
185                        *existing = level;
186                    }
187                }
188                false
189            } else {
190                inner.put(key, level);
191                true
192            }
193        };
194        if added {
195            self.additions.fetch_add(1, Ordering::Relaxed);
196        }
197    }
198
199    /// As [`Self::contains_key`], for a chunk at `address`.
200    #[must_use]
201    pub fn contains(&self, address: &XorName) -> bool {
202        self.contains_key(&PaidKey::Chunk(*address))
203    }
204
205    /// As [`Self::contains_paid_list_verified_key`], for a chunk at `address`.
206    #[must_use]
207    pub fn contains_paid_list_verified(&self, address: &XorName) -> bool {
208        self.contains_paid_list_verified_key(&PaidKey::Chunk(*address))
209    }
210
211    /// As [`Self::contains_client_put_verified_key`], for a chunk at `address`.
212    #[must_use]
213    pub fn contains_client_put_verified(&self, address: &XorName) -> bool {
214        self.contains_client_put_verified_key(&PaidKey::Chunk(*address))
215    }
216
217    /// As [`Self::insert_key`], for a chunk at `address`.
218    pub fn insert(&self, address: XorName) {
219        self.insert_key(PaidKey::Chunk(address));
220    }
221
222    /// As [`Self::insert_paid_list_verified_key`], for a chunk at `address`.
223    pub fn insert_paid_list_verified(&self, address: XorName) {
224        self.insert_paid_list_verified_key(PaidKey::Chunk(address));
225    }
226
227    /// Get current cache statistics.
228    #[must_use]
229    pub fn stats(&self) -> CacheStats {
230        CacheStats {
231            hits: self.hits.load(Ordering::Relaxed),
232            misses: self.misses.load(Ordering::Relaxed),
233            additions: self.additions.load(Ordering::Relaxed),
234        }
235    }
236
237    /// Get the current number of entries in the cache.
238    #[must_use]
239    pub fn len(&self) -> usize {
240        self.inner.lock().len()
241    }
242
243    /// Check if the cache is empty.
244    #[must_use]
245    pub fn is_empty(&self) -> bool {
246        self.inner.lock().is_empty()
247    }
248
249    /// Clear all entries from the cache.
250    pub fn clear(&self) {
251        self.inner.lock().clear();
252    }
253}
254
255impl Default for VerifiedCache {
256    fn default() -> Self {
257        Self::new()
258    }
259}
260
261#[cfg(test)]
262#[allow(clippy::expect_used)]
263mod tests {
264    use super::*;
265
266    #[test]
267    fn test_cache_basic_operations() {
268        let cache = VerifiedCache::new();
269
270        let key1 = [1u8; 32];
271        let key2 = [2u8; 32];
272
273        // Initially empty
274        assert!(cache.is_empty());
275        assert!(!cache.contains(&key1));
276
277        // Insert and check
278        cache.insert(key1);
279        assert!(cache.contains(&key1));
280        assert!(!cache.contains(&key2));
281        assert_eq!(cache.len(), 1);
282
283        // Insert another
284        cache.insert(key2);
285        assert!(cache.contains(&key1));
286        assert!(cache.contains(&key2));
287        assert_eq!(cache.len(), 2);
288    }
289
290    #[test]
291    fn test_cache_verification_levels_do_not_downgrade_or_over_authorize() {
292        let cache = VerifiedCache::new();
293        let paid_list = [2u8; 32];
294        let client_put = [3u8; 32];
295
296        cache.insert_paid_list_verified(paid_list);
297        assert!(cache.contains(&paid_list));
298        assert!(cache.contains_paid_list_verified(&paid_list));
299        assert!(!cache.contains_client_put_verified(&paid_list));
300
301        cache.insert(paid_list);
302        assert!(cache.contains_client_put_verified(&paid_list));
303
304        cache.insert(client_put);
305        assert!(cache.contains(&client_put));
306        assert!(cache.contains_paid_list_verified(&client_put));
307        assert!(cache.contains_client_put_verified(&client_put));
308
309        cache.insert_paid_list_verified(client_put);
310        assert!(cache.contains_client_put_verified(&client_put));
311    }
312
313    #[test]
314    fn test_cache_stats() {
315        let cache = VerifiedCache::new();
316        let key = [1u8; 32];
317
318        // Miss
319        assert!(!cache.contains(&key));
320        let stats = cache.stats();
321        assert_eq!(stats.misses, 1);
322        assert_eq!(stats.hits, 0);
323
324        // Add
325        cache.insert(key);
326        let stats = cache.stats();
327        assert_eq!(stats.additions, 1);
328
329        // Hit
330        assert!(cache.contains(&key));
331        let stats = cache.stats();
332        assert_eq!(stats.hits, 1);
333        assert_eq!(stats.misses, 1);
334
335        // Hit rate should be 50%
336        assert!((stats.hit_rate() - 50.0).abs() < 0.01);
337    }
338
339    #[test]
340    fn test_cache_lru_eviction() {
341        // Small cache for testing eviction
342        let cache = VerifiedCache::with_capacity(2);
343
344        let key1 = [1u8; 32];
345        let key2 = [2u8; 32];
346        let key3 = [3u8; 32];
347
348        cache.insert(key1);
349        cache.insert(key2);
350        assert_eq!(cache.len(), 2);
351
352        // Insert third, should evict key1 (least recently used)
353        cache.insert(key3);
354        assert_eq!(cache.len(), 2);
355        assert!(!cache.contains(&key1)); // evicted
356                                         // Note: after contains call on evicted item, stats will show a miss
357    }
358
359    #[test]
360    fn test_cache_clear() {
361        let cache = VerifiedCache::new();
362
363        cache.insert([1u8; 32]);
364        cache.insert([2u8; 32]);
365        assert_eq!(cache.len(), 2);
366
367        cache.clear();
368        assert!(cache.is_empty());
369    }
370
371    #[test]
372    fn test_with_capacity_zero_defaults_to_one() {
373        let cache = VerifiedCache::with_capacity(0);
374        // Should be able to store at least 1 element
375        cache.insert([1u8; 32]);
376        assert_eq!(cache.len(), 1);
377    }
378
379    #[test]
380    fn test_default_impl() {
381        let cache = VerifiedCache::default();
382        assert!(cache.is_empty());
383        cache.insert([1u8; 32]);
384        assert!(cache.contains(&[1u8; 32]));
385    }
386
387    #[test]
388    fn test_hit_rate_zero_total() {
389        let stats = CacheStats::default();
390        assert!(stats.hit_rate().abs() < f64::EPSILON);
391    }
392
393    #[test]
394    fn test_hit_rate_all_hits() {
395        let stats = CacheStats {
396            hits: 10,
397            misses: 0,
398            additions: 0,
399        };
400        assert!((stats.hit_rate() - 100.0).abs() < 0.01);
401    }
402
403    #[test]
404    fn test_hit_rate_all_misses() {
405        let stats = CacheStats {
406            hits: 0,
407            misses: 10,
408            additions: 0,
409        };
410        assert!(stats.hit_rate().abs() < f64::EPSILON);
411    }
412
413    #[test]
414    fn test_clear_does_not_reset_stats() {
415        let cache = VerifiedCache::new();
416        cache.insert([1u8; 32]);
417        let _ = cache.contains(&[1u8; 32]); // hit
418        let _ = cache.contains(&[2u8; 32]); // miss
419
420        cache.clear();
421
422        // Stats should persist after clear
423        let stats = cache.stats();
424        assert_eq!(stats.hits, 1);
425        assert_eq!(stats.misses, 1);
426        assert_eq!(stats.additions, 1);
427    }
428
429    #[test]
430    fn test_concurrent_insert_and_contains() {
431        use std::sync::Arc;
432        use std::thread;
433
434        let cache = Arc::new(VerifiedCache::with_capacity(1000));
435        let mut handles = Vec::new();
436
437        // 10 threads inserting
438        for i in 0..10u8 {
439            let c = cache.clone();
440            handles.push(thread::spawn(move || {
441                let key = [i; 32];
442                c.insert(key);
443            }));
444        }
445
446        // 10 threads checking
447        for i in 0..10u8 {
448            let c = cache.clone();
449            handles.push(thread::spawn(move || {
450                let key = [i; 32];
451                let _ = c.contains(&key);
452            }));
453        }
454
455        for handle in handles {
456            handle.join().expect("thread panicked");
457        }
458
459        // All 10 should have been inserted
460        assert_eq!(cache.len(), 10);
461    }
462
463    #[test]
464    fn test_cache_stats_copy() {
465        let stats = CacheStats {
466            hits: 5,
467            misses: 3,
468            additions: 8,
469        };
470        let stats2 = stats; // Copy
471        assert_eq!(stats.hits, stats2.hits);
472        assert_eq!(stats.misses, stats2.misses);
473        assert_eq!(stats.additions, stats2.additions);
474    }
475}