Skip to main content

hyprstream_metrics/storage/
cache.rs

1use std::sync::Arc;
2use std::time::{Duration, SystemTime, UNIX_EPOCH};
3use tokio::sync::RwLock;
4use tonic::Status;
5
6/// Shared cache eviction manager that can be used across different storage backends.
7#[derive(Clone)]
8pub struct CacheManager {
9    ttl: Option<u64>,
10    last_eviction: Arc<RwLock<SystemTime>>,
11    min_eviction_interval: Duration,
12}
13
14impl CacheManager {
15    /// Creates a new cache manager with the specified TTL.
16    pub fn new(ttl: Option<u64>) -> Self {
17        Self {
18            ttl,
19            last_eviction: Arc::new(RwLock::new(SystemTime::now())),
20            min_eviction_interval: Duration::from_secs(60), // Default 60s between evictions
21        }
22    }
23
24    /// Sets a custom minimum interval between evictions.
25    pub fn set_min_eviction_interval(&mut self, interval: Duration) {
26        self.min_eviction_interval = interval;
27    }
28
29    /// Checks if eviction should be performed based on TTL and rate limiting.
30    /// Returns the cutoff timestamp if eviction should proceed, None otherwise.
31    pub async fn should_evict(&self) -> Result<Option<i64>, Status> {
32        match self.ttl {
33            None | Some(0) => Ok(None), // No TTL or TTL=0 means no eviction
34            Some(ttl) => {
35                let now = SystemTime::now();
36                let last = *self.last_eviction.read().await;
37
38                // Check if enough time has passed since last eviction
39                if now.duration_since(last).unwrap_or(Duration::from_secs(0))
40                    < self.min_eviction_interval
41                {
42                    return Ok(None);
43                }
44
45                // Calculate cutoff timestamp
46                let now_secs = i64::try_from(
47                    now.duration_since(UNIX_EPOCH)
48                        .map_err(|e| Status::internal(e.to_string()))?
49                        .as_secs(),
50                )
51                .unwrap_or(i64::MAX);
52                let ttl_secs = i64::try_from(ttl).unwrap_or(i64::MAX);
53                let cutoff = now_secs.saturating_sub(ttl_secs);
54
55                // Update last eviction time
56                *self.last_eviction.write().await = now;
57
58                Ok(Some(cutoff))
59            }
60        }
61    }
62
63    /// Generates an optimized SQL query for evicting expired entries.
64    pub fn eviction_query(&self, cutoff: i64) -> String {
65        format!(
66            "DELETE FROM metrics USING (
67                SELECT timestamp 
68                FROM metrics 
69                WHERE timestamp < {cutoff} 
70                LIMIT 10000
71            ) as expired 
72            WHERE metrics.timestamp = expired.timestamp"
73        )
74    }
75}
76
77/// Trait for storage backends that support cache eviction.
78#[async_trait::async_trait]
79pub trait CacheEviction {
80    /// Executes the eviction query in the background.
81    async fn execute_eviction(&self, query: &str) -> Result<(), Status>;
82}