use std::time::{Duration, SystemTime};
use log::{error, warn};
use sieve_cache::SyncSieveCache;
use crate::dns_key::DNSKey;
#[derive(Clone)]
pub struct CachedResponse {
pub data: Vec<u8>,
pub expires_at: SystemTime,
}
impl CachedResponse {
pub fn new(data: Vec<u8>, ttl: Duration) -> Self {
let expires_at = SystemTime::now() + ttl;
Self { data, expires_at }
}
pub fn is_expired(&self) -> bool {
SystemTime::now().duration_since(self.expires_at).is_ok()
}
}
pub type SyncDnsCache = SyncSieveCache<DNSKey, CachedResponse>;
pub fn create_dns_cache(capacity: usize) -> SyncDnsCache {
match SyncSieveCache::<DNSKey, CachedResponse>::new(capacity) {
Ok(cache) => cache,
Err(e) => {
error!("Failed to create DNS cache with requested capacity {capacity}: {e}");
let smaller_capacity = std::cmp::max(100, capacity / 2);
warn!("Falling back to smaller DNS cache capacity: {smaller_capacity}");
SyncSieveCache::<DNSKey, CachedResponse>::new(smaller_capacity)
.expect("Critical error: Failed to allocate even minimal DNS cache")
}
}
}