hyprstream_metrics/storage/
cache.rs1use std::sync::Arc;
2use std::time::{Duration, SystemTime, UNIX_EPOCH};
3use tokio::sync::RwLock;
4use tonic::Status;
5
6#[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 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), }
22 }
23
24 pub fn set_min_eviction_interval(&mut self, interval: Duration) {
26 self.min_eviction_interval = interval;
27 }
28
29 pub async fn should_evict(&self) -> Result<Option<i64>, Status> {
32 match self.ttl {
33 None | Some(0) => Ok(None), Some(ttl) => {
35 let now = SystemTime::now();
36 let last = *self.last_eviction.read().await;
37
38 if now.duration_since(last).unwrap_or(Duration::from_secs(0))
40 < self.min_eviction_interval
41 {
42 return Ok(None);
43 }
44
45 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 *self.last_eviction.write().await = now;
57
58 Ok(Some(cutoff))
59 }
60 }
61 }
62
63 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#[async_trait::async_trait]
79pub trait CacheEviction {
80 async fn execute_eviction(&self, query: &str) -> Result<(), Status>;
82}