use crate::scripting::Service;
use dashmap::DashMap;
use std::time::Instant;
struct CachedService {
service: Service,
cached_at: Instant,
}
pub struct ServiceCache {
entries: DashMap<(String, String), CachedService>,
ttl_secs: u64,
}
impl ServiceCache {
pub fn new(ttl_secs: u64) -> Self {
Self {
entries: DashMap::new(),
ttl_secs,
}
}
pub fn get(&self, db_name: &str, service_key: &str) -> Option<Service> {
let key = (db_name.to_string(), service_key.to_string());
if let Some(entry) = self.entries.get(&key) {
if entry.cached_at.elapsed().as_secs() < self.ttl_secs {
return Some(entry.service.clone());
}
drop(entry);
self.entries.remove(&key);
}
None
}
pub fn insert(&self, db_name: &str, service_key: &str, service: Service) {
let key = (db_name.to_string(), service_key.to_string());
self.entries.insert(
key,
CachedService {
service,
cached_at: Instant::now(),
},
);
}
pub fn invalidate(&self, db_name: &str, service_key: &str) {
self.entries
.remove(&(db_name.to_string(), service_key.to_string()));
}
}