94 lines
2.6 KiB
Rust
94 lines
2.6 KiB
Rust
use cm_dashboard_shared::{CacheConfig, Metric};
|
|
use std::collections::HashMap;
|
|
use std::fs;
|
|
use std::path::Path;
|
|
use std::sync::Arc;
|
|
use tokio::sync::RwLock;
|
|
use tracing::{info, warn, debug};
|
|
|
|
/// Simple persistent cache for metrics
|
|
pub struct SimpleCache {
|
|
metrics: RwLock<HashMap<String, Metric>>,
|
|
persist_path: String,
|
|
}
|
|
|
|
impl SimpleCache {
|
|
pub fn new(config: CacheConfig) -> Self {
|
|
let cache = Self {
|
|
metrics: RwLock::new(HashMap::new()),
|
|
persist_path: config.persist_path,
|
|
};
|
|
|
|
// Clear cache file on startup to ensure fresh data
|
|
cache.clear_cache_file();
|
|
cache
|
|
}
|
|
|
|
/// Store metric in cache
|
|
pub async fn store_metric(&self, metric: Metric) {
|
|
let mut metrics = self.metrics.write().await;
|
|
metrics.insert(metric.name.clone(), metric);
|
|
}
|
|
|
|
/// Get all cached metrics
|
|
pub async fn get_all_cached_metrics(&self) -> Vec<Metric> {
|
|
let metrics = self.metrics.read().await;
|
|
metrics.values().cloned().collect()
|
|
}
|
|
|
|
/// Save cache to disk
|
|
pub async fn save_to_disk(&self) {
|
|
// Cache persistence disabled to prevent stale data issues during debugging
|
|
debug!("Cache persistence disabled - not saving to disk");
|
|
}
|
|
|
|
/// Load cache from disk (DISABLED)
|
|
fn load_from_disk(&self) {
|
|
// Cache loading disabled to prevent stale data issues during debugging
|
|
info!("Cache loading disabled - starting with fresh cache");
|
|
}
|
|
|
|
/// Clear cache file on startup to ensure fresh data
|
|
fn clear_cache_file(&self) {
|
|
if Path::new(&self.persist_path).exists() {
|
|
match fs::remove_file(&self.persist_path) {
|
|
Ok(_) => info!("Cleared cache file {} on startup", self.persist_path),
|
|
Err(e) => warn!("Failed to clear cache file {}: {}", self.persist_path, e),
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
#[derive(Clone)]
|
|
pub struct MetricCacheManager {
|
|
cache: Arc<SimpleCache>,
|
|
}
|
|
|
|
impl MetricCacheManager {
|
|
pub fn new(config: CacheConfig) -> Self {
|
|
Self {
|
|
cache: Arc::new(SimpleCache::new(config)),
|
|
}
|
|
}
|
|
|
|
pub async fn store_metric(&self, metric: Metric) {
|
|
self.cache.store_metric(metric).await;
|
|
}
|
|
|
|
pub async fn cache_metric(&self, metric: Metric) {
|
|
self.store_metric(metric).await;
|
|
}
|
|
|
|
pub async fn start_background_tasks(&self) {
|
|
// No background tasks needed for simple cache
|
|
}
|
|
|
|
pub async fn get_all_cached_metrics(&self) -> Result<Vec<Metric>, anyhow::Error> {
|
|
Ok(self.cache.get_all_cached_metrics().await)
|
|
}
|
|
|
|
pub async fn save_to_disk(&self) {
|
|
self.cache.save_to_disk().await;
|
|
}
|
|
} |