seer-core 0.26.4

Core library for Seer domain name utilities
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
//! TTL-based caching with stale-while-revalidate semantics.
//!
//! This module provides a thread-safe cache with time-to-live (TTL) expiration
//! and the ability to serve stale data during refresh failures.
//!
//! # Clock
//!
//! The cache uses [`tokio::time::Instant`] as its monotonic clock. In normal
//! operation this is identical to [`std::time::Instant`]; when a test runs
//! inside a `#[tokio::test(start_paused = true)]` runtime, the clock becomes
//! virtual and can be advanced deterministically via `tokio::time::advance`,
//! which keeps TTL unit tests fast and non-flaky.

use std::collections::HashMap;
use std::hash::Hash;
use std::sync::RwLock;
use std::time::Duration;

use tokio::time::Instant;
use tracing::{debug, warn};

/// A cache entry with TTL tracking.
#[derive(Debug, Clone)]
struct CacheEntry<V> {
    value: V,
    inserted_at: Instant,
    ttl: Duration,
}

impl<V> CacheEntry<V> {
    /// Creates a new cache entry.
    fn new(value: V, ttl: Duration) -> Self {
        Self {
            value,
            inserted_at: Instant::now(),
            ttl,
        }
    }

    /// Returns true if the entry has expired.
    fn is_expired(&self) -> bool {
        self.inserted_at.elapsed() > self.ttl
    }

    /// Returns true if the entry is stale (past 75% of TTL).
    /// This is used for stale-while-revalidate logic.
    fn is_stale(&self) -> bool {
        self.inserted_at.elapsed() > (self.ttl * 3 / 4)
    }

    /// Returns the age of the entry.
    fn age(&self) -> Duration {
        self.inserted_at.elapsed()
    }
}

/// Thread-safe TTL cache with stale-while-revalidate semantics.
///
/// This cache supports:
/// - Automatic expiration based on TTL
/// - Serving stale data when fresh data is unavailable
/// - Thread-safe access via RwLock
///
/// # Example
///
/// ```
/// use std::time::Duration;
/// use seer_core::cache::TtlCache;
///
/// let cache: TtlCache<String, String> = TtlCache::new(Duration::from_secs(3600));
///
/// // Insert a value
/// cache.insert("key".to_string(), "value".to_string());
///
/// // Get the value (returns None if expired)
/// if let Some(value) = cache.get(&"key".to_string()) {
///     println!("Got: {}", value);
/// }
/// ```
pub struct TtlCache<K, V> {
    entries: RwLock<HashMap<K, CacheEntry<V>>>,
    default_ttl: Duration,
    /// Maximum number of entries. When exceeded, expired entries are purged
    /// and if still over capacity, the oldest entry is evicted.
    max_capacity: usize,
}

/// Default maximum capacity for TtlCache instances.
const DEFAULT_MAX_CAPACITY: usize = 1024;

impl<K, V> TtlCache<K, V>
where
    K: Eq + Hash + Clone + std::fmt::Debug,
    V: Clone,
{
    /// Creates a new cache with the specified default TTL and default max capacity (1024).
    pub fn new(default_ttl: Duration) -> Self {
        Self {
            entries: RwLock::new(HashMap::new()),
            default_ttl,
            max_capacity: DEFAULT_MAX_CAPACITY,
        }
    }

    /// Creates a new cache with a specified TTL and max capacity.
    pub fn with_max_capacity(default_ttl: Duration, max_capacity: usize) -> Self {
        Self {
            entries: RwLock::new(HashMap::new()),
            default_ttl,
            max_capacity,
        }
    }

    /// Gets a value from the cache if it exists and is not expired.
    ///
    /// Returns `None` if the key doesn't exist, the entry has expired,
    /// or the lock is poisoned (with a warning logged).
    pub fn get(&self, key: &K) -> Option<V> {
        let entries = match self.entries.read() {
            Ok(guard) => guard,
            Err(poisoned) => {
                warn!("Cache read lock poisoned, recovering");
                poisoned.into_inner()
            }
        };
        let entry = entries.get(key)?;

        if entry.is_expired() {
            debug!(
                hit = false,
                ?key,
                age_secs = entry.age().as_secs(),
                "cache lookup (expired)"
            );
            None
        } else {
            debug!(hit = true, ?key, "cache lookup");
            Some(entry.value.clone())
        }
    }

    /// Gets a value from the cache even if it's expired.
    ///
    /// This is useful for stale-while-revalidate patterns where you want
    /// to serve stale data while attempting to refresh.
    pub fn get_stale(&self, key: &K) -> Option<V> {
        let entries = match self.entries.read() {
            Ok(guard) => guard,
            Err(poisoned) => {
                warn!("Cache read lock poisoned, recovering");
                poisoned.into_inner()
            }
        };
        entries.get(key).map(|entry| {
            if entry.is_expired() {
                debug!(
                    ?key,
                    age_secs = entry.age().as_secs(),
                    "Serving stale cache entry"
                );
            }
            entry.value.clone()
        })
    }

    /// Checks if a key exists and needs refresh (is stale but not expired).
    ///
    /// Returns `true` if the entry exists and is past 75% of its TTL.
    pub fn needs_refresh(&self, key: &K) -> bool {
        let entries = match self.entries.read() {
            Ok(guard) => guard,
            Err(poisoned) => {
                warn!("Cache read lock poisoned, recovering");
                poisoned.into_inner()
            }
        };

        entries.get(key).is_some_and(|entry| entry.is_stale())
    }

    /// Inserts a value into the cache with the default TTL.
    pub fn insert(&self, key: K, value: V) {
        self.insert_with_ttl(key, value, self.default_ttl);
    }

    /// Inserts a value into the cache with a custom TTL.
    ///
    /// If the cache exceeds max capacity, expired entries are purged first.
    /// If still over capacity, the oldest entry is evicted.
    pub fn insert_with_ttl(&self, key: K, value: V, ttl: Duration) {
        let mut entries = match self.entries.write() {
            Ok(guard) => guard,
            Err(poisoned) => {
                warn!("Cache write lock poisoned, recovering");
                poisoned.into_inner()
            }
        };

        // Evict if at capacity (before inserting)
        if entries.len() >= self.max_capacity && !entries.contains_key(&key) {
            // First, remove expired entries
            let before = entries.len();
            entries.retain(|_, entry| !entry.is_expired());
            let removed = before - entries.len();
            if removed > 0 {
                debug!(removed, "Evicted expired entries to make room");
            }

            // If still at capacity, evict the oldest entry
            if entries.len() >= self.max_capacity {
                if let Some(oldest_key) = entries
                    .iter()
                    .max_by_key(|(_, entry)| entry.age())
                    .map(|(k, _)| k.clone())
                {
                    entries.remove(&oldest_key);
                    debug!(?oldest_key, "Evicted oldest entry to make room");
                }
            }
        }

        debug!(?key, ttl_secs = ttl.as_secs(), "Inserting cache entry");
        entries.insert(key, CacheEntry::new(value, ttl));
    }

    /// Removes a value from the cache.
    pub fn remove(&self, key: &K) -> Option<V> {
        let mut entries = match self.entries.write() {
            Ok(guard) => guard,
            Err(poisoned) => {
                warn!("Cache write lock poisoned, recovering");
                poisoned.into_inner()
            }
        };
        entries.remove(key).map(|e| e.value)
    }

    /// Removes all expired entries from the cache.
    ///
    /// This is useful for periodic cleanup to prevent unbounded memory growth.
    pub fn cleanup(&self) {
        let mut entries = match self.entries.write() {
            Ok(guard) => guard,
            Err(poisoned) => {
                warn!("Cache write lock poisoned, recovering");
                poisoned.into_inner()
            }
        };
        let before = entries.len();
        entries.retain(|_, entry| !entry.is_expired());
        let removed = before - entries.len();
        if removed > 0 {
            debug!(removed, remaining = entries.len(), "Cache cleanup complete");
        }
    }

    /// Returns the number of entries in the cache (including expired ones).
    pub fn len(&self) -> usize {
        match self.entries.read() {
            Ok(entries) => entries.len(),
            Err(poisoned) => {
                warn!("Cache read lock poisoned, recovering");
                poisoned.into_inner().len()
            }
        }
    }

    /// Returns true if the cache is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Clears all entries from the cache.
    pub fn clear(&self) {
        let mut entries = match self.entries.write() {
            Ok(guard) => guard,
            Err(poisoned) => {
                warn!("Cache write lock poisoned, recovering");
                poisoned.into_inner()
            }
        };
        entries.clear();
    }
}

/// A single-value cache with TTL, useful for caching expensive one-off computations
/// like bootstrap data.
///
/// Provides stale-while-revalidate semantics: if refresh fails, stale data can be used.
pub struct SingleValueCache<V> {
    entry: RwLock<Option<CacheEntry<V>>>,
    ttl: Duration,
}

impl<V: Clone> SingleValueCache<V> {
    /// Creates a new single-value cache with the specified TTL.
    pub fn new(ttl: Duration) -> Self {
        Self {
            entry: RwLock::new(None),
            ttl,
        }
    }

    /// Gets the cached value if it exists and is not expired.
    pub fn get(&self) -> Option<V> {
        let guard = match self.entry.read() {
            Ok(guard) => guard,
            Err(poisoned) => {
                warn!("SingleValueCache read lock poisoned, recovering");
                poisoned.into_inner()
            }
        };
        let entry = guard.as_ref()?;

        if entry.is_expired() {
            None
        } else {
            Some(entry.value.clone())
        }
    }

    /// Gets the cached value even if expired (for fallback during refresh failures).
    pub fn get_stale(&self) -> Option<V> {
        let guard = match self.entry.read() {
            Ok(guard) => guard,
            Err(poisoned) => {
                warn!("SingleValueCache read lock poisoned, recovering");
                poisoned.into_inner()
            }
        };
        guard.as_ref().map(|e| e.value.clone())
    }

    /// Checks if the cache needs refresh (value is stale or missing).
    pub fn needs_refresh(&self) -> bool {
        let guard = match self.entry.read() {
            Ok(guard) => guard,
            Err(poisoned) => {
                warn!("SingleValueCache read lock poisoned, recovering");
                poisoned.into_inner()
            }
        };

        match guard.as_ref() {
            Some(e) => e.is_stale(),
            None => true,
        }
    }

    /// Checks if the cache has any value (even if expired).
    pub fn has_value(&self) -> bool {
        let guard = match self.entry.read() {
            Ok(guard) => guard,
            Err(poisoned) => {
                warn!("SingleValueCache read lock poisoned, recovering");
                poisoned.into_inner()
            }
        };
        guard.is_some()
    }

    /// Sets the cached value.
    pub fn set(&self, value: V) {
        let mut guard = match self.entry.write() {
            Ok(guard) => guard,
            Err(poisoned) => {
                warn!("SingleValueCache write lock poisoned, recovering");
                poisoned.into_inner()
            }
        };
        *guard = Some(CacheEntry::new(value, self.ttl));
    }

    /// Clears the cached value.
    pub fn clear(&self) {
        let mut guard = match self.entry.write() {
            Ok(guard) => guard,
            Err(poisoned) => {
                warn!("SingleValueCache write lock poisoned, recovering");
                poisoned.into_inner()
            }
        };
        *guard = None;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_cache_insert_and_get() {
        let cache: TtlCache<String, String> = TtlCache::new(Duration::from_secs(3600));

        cache.insert("key".to_string(), "value".to_string());

        assert_eq!(cache.get(&"key".to_string()), Some("value".to_string()));
    }

    #[test]
    fn test_cache_get_missing_key() {
        let cache: TtlCache<String, String> = TtlCache::new(Duration::from_secs(3600));

        assert_eq!(cache.get(&"missing".to_string()), None);
    }

    #[test]
    fn test_cache_expiration() {
        let cache: TtlCache<String, String> = TtlCache::new(Duration::from_millis(10));

        cache.insert("key".to_string(), "value".to_string());
        assert_eq!(cache.get(&"key".to_string()), Some("value".to_string()));

        // Wait for expiration
        std::thread::sleep(Duration::from_millis(20));

        assert_eq!(cache.get(&"key".to_string()), None);
    }

    #[test]
    fn test_cache_get_stale_after_expiration() {
        let cache: TtlCache<String, String> = TtlCache::new(Duration::from_millis(10));

        cache.insert("key".to_string(), "value".to_string());

        // Wait for expiration
        std::thread::sleep(Duration::from_millis(20));

        // get() returns None for expired
        assert_eq!(cache.get(&"key".to_string()), None);
        // get_stale() still returns the value
        assert_eq!(
            cache.get_stale(&"key".to_string()),
            Some("value".to_string())
        );
    }

    #[test]
    fn test_cache_remove() {
        let cache: TtlCache<String, String> = TtlCache::new(Duration::from_secs(3600));

        cache.insert("key".to_string(), "value".to_string());
        assert!(cache.get(&"key".to_string()).is_some());

        cache.remove(&"key".to_string());
        assert!(cache.get(&"key".to_string()).is_none());
    }

    #[test]
    fn test_cache_cleanup() {
        let cache: TtlCache<String, String> = TtlCache::new(Duration::from_millis(10));

        cache.insert("key1".to_string(), "value1".to_string());
        cache.insert("key2".to_string(), "value2".to_string());

        // Wait for expiration
        std::thread::sleep(Duration::from_millis(20));

        // Add a fresh entry
        cache.insert_with_ttl(
            "key3".to_string(),
            "value3".to_string(),
            Duration::from_secs(3600),
        );

        assert_eq!(cache.len(), 3);

        cache.cleanup();

        // Only the fresh entry should remain
        assert_eq!(cache.len(), 1);
        assert_eq!(cache.get(&"key3".to_string()), Some("value3".to_string()));
    }

    #[test]
    fn test_cache_clear() {
        let cache: TtlCache<String, String> = TtlCache::new(Duration::from_secs(3600));

        cache.insert("key1".to_string(), "value1".to_string());
        cache.insert("key2".to_string(), "value2".to_string());

        assert_eq!(cache.len(), 2);

        cache.clear();

        assert_eq!(cache.len(), 0);
        assert!(cache.is_empty());
    }

    #[test]
    fn test_single_value_cache() {
        let cache: SingleValueCache<String> = SingleValueCache::new(Duration::from_secs(3600));

        assert!(!cache.has_value());
        assert!(cache.get().is_none());

        cache.set("value".to_string());

        assert!(cache.has_value());
        assert_eq!(cache.get(), Some("value".to_string()));
    }

    #[test]
    fn test_single_value_cache_expiration() {
        let cache: SingleValueCache<String> = SingleValueCache::new(Duration::from_millis(10));

        cache.set("value".to_string());
        assert_eq!(cache.get(), Some("value".to_string()));

        // Wait for expiration
        std::thread::sleep(Duration::from_millis(20));

        assert!(cache.get().is_none());
        // Stale value still available
        assert_eq!(cache.get_stale(), Some("value".to_string()));
    }

    #[tokio::test(start_paused = true)]
    async fn test_needs_refresh() {
        // Uses tokio's virtual clock (TtlCache now uses tokio::time::Instant),
        // so we advance the clock deterministically instead of real sleeps.
        // TTL=1s, staleness threshold = 75% of TTL = 750ms.
        let cache: TtlCache<String, String> = TtlCache::new(Duration::from_secs(1));
        cache.insert("key".to_string(), "value".to_string());

        // Initially not stale.
        assert!(!cache.needs_refresh(&"key".to_string()));

        // Advance past 75% of TTL but before expiry.
        tokio::time::advance(Duration::from_millis(800)).await;
        assert!(
            cache.needs_refresh(&"key".to_string()),
            "entry must be stale at t=800ms (>= 750ms threshold)"
        );
        assert!(
            cache.get(&"key".to_string()).is_some(),
            "entry must not be expired at t=800ms (< 1000ms TTL)"
        );

        // Advance past expiry.
        tokio::time::advance(Duration::from_millis(300)).await;
        assert!(
            cache.get(&"key".to_string()).is_none(),
            "entry must be expired at t=1100ms (> 1000ms TTL)"
        );
    }
}