ant_node/payment/
cache.rs1use 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
15const DEFAULT_CACHE_CAPACITY: usize = 100_000;
17
18#[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#[derive(Debug, Default, Clone, Copy)]
52pub struct CacheStats {
53 pub hits: u64,
55 pub misses: u64,
57 pub additions: u64,
59}
60
61impl CacheStats {
62 #[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 #[must_use]
78 pub fn new() -> Self {
79 Self::with_capacity(DEFAULT_CACHE_CAPACITY)
80 }
81
82 #[must_use]
86 pub fn with_capacity(capacity: usize) -> Self {
87 let effective_capacity = capacity.max(1);
89 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 #[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 #[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 #[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 pub fn insert_key(&self, key: PaidKey) {
168 self.insert_with_level(key, VerificationLevel::ClientPut);
169 }
170
171 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 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 #[must_use]
201 pub fn contains(&self, address: &XorName) -> bool {
202 self.contains_key(&PaidKey::Chunk(*address))
203 }
204
205 #[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 #[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 pub fn insert(&self, address: XorName) {
219 self.insert_key(PaidKey::Chunk(address));
220 }
221
222 pub fn insert_paid_list_verified(&self, address: XorName) {
224 self.insert_paid_list_verified_key(PaidKey::Chunk(address));
225 }
226
227 #[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 #[must_use]
239 pub fn len(&self) -> usize {
240 self.inner.lock().len()
241 }
242
243 #[must_use]
245 pub fn is_empty(&self) -> bool {
246 self.inner.lock().is_empty()
247 }
248
249 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 assert!(cache.is_empty());
275 assert!(!cache.contains(&key1));
276
277 cache.insert(key1);
279 assert!(cache.contains(&key1));
280 assert!(!cache.contains(&key2));
281 assert_eq!(cache.len(), 1);
282
283 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 assert!(!cache.contains(&key));
320 let stats = cache.stats();
321 assert_eq!(stats.misses, 1);
322 assert_eq!(stats.hits, 0);
323
324 cache.insert(key);
326 let stats = cache.stats();
327 assert_eq!(stats.additions, 1);
328
329 assert!(cache.contains(&key));
331 let stats = cache.stats();
332 assert_eq!(stats.hits, 1);
333 assert_eq!(stats.misses, 1);
334
335 assert!((stats.hit_rate() - 50.0).abs() < 0.01);
337 }
338
339 #[test]
340 fn test_cache_lru_eviction() {
341 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 cache.insert(key3);
354 assert_eq!(cache.len(), 2);
355 assert!(!cache.contains(&key1)); }
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 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]); let _ = cache.contains(&[2u8; 32]); cache.clear();
421
422 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 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 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 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; assert_eq!(stats.hits, stats2.hits);
472 assert_eq!(stats.misses, stats2.misses);
473 assert_eq!(stats.additions, stats2.additions);
474 }
475}