use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant};
use super::RecordType;
#[derive(Debug, Clone)]
pub struct DnsRecord {
pub value: String,
pub expires_at: Instant,
}
#[derive(Debug)]
pub struct DnsCache {
records: Arc<RwLock<HashMap<(String, RecordType), DnsRecord>>>,
}
impl DnsCache {
#[must_use]
pub fn new() -> Self {
Self {
records: Arc::new(RwLock::new(HashMap::new())),
}
}
#[must_use]
pub fn get(&self, name: &str, record_type: RecordType) -> Option<String> {
let records = self.records.read().ok()?;
let key = (name.to_string(), record_type);
let result = records.get(&key).and_then(|record| {
if record.expires_at > Instant::now() {
Some(record.value.clone())
} else {
None
}
});
drop(records);
result
}
pub fn add(&self, name: &str, record_type: RecordType, value: String, ttl: Duration) {
if let Ok(mut records) = self.records.write() {
let key = (name.to_string(), record_type);
let record = DnsRecord {
value,
expires_at: Instant::now() + ttl,
};
records.insert(key, record);
}
}
pub fn remove(&self, name: &str, record_type: RecordType) {
if let Ok(mut records) = self.records.write() {
let key = (name.to_string(), record_type);
records.remove(&key);
}
}
pub fn clear_expired(&self) {
if let Ok(mut records) = self.records.write() {
records.retain(|_, record| record.expires_at > Instant::now());
}
}
#[must_use]
pub fn get_ttl(&self, name: &str, record_type: RecordType) -> Option<Duration> {
let records = self.records.read().ok()?;
let key = (name.to_string(), record_type);
let result = records.get(&key).and_then(|record| {
let now = Instant::now();
if record.expires_at > now {
Some(record.expires_at.duration_since(now))
} else {
None
}
});
drop(records);
result
}
pub fn clear(&self) {
if let Ok(mut records) = self.records.write() {
records.clear();
}
}
}
impl Default for DnsCache {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug)]
pub struct SharedDnsCache {
cache: Arc<DnsCache>,
}
impl SharedDnsCache {
#[must_use]
pub fn new() -> Self {
Self {
cache: Arc::new(DnsCache::new()),
}
}
#[must_use]
pub fn get(&self, name: &str, record_type: RecordType) -> Option<String> {
self.cache.get(name, record_type)
}
pub fn add(&self, name: &str, record_type: RecordType, value: String, ttl: Duration) {
self.cache.add(name, record_type, value, ttl);
}
pub fn remove(&self, name: &str, record_type: RecordType) {
self.cache.remove(name, record_type);
}
pub fn clear_expired(&self) {
self.cache.clear_expired();
}
#[must_use]
pub fn get_ttl(&self, name: &str, record_type: RecordType) -> Option<Duration> {
self.cache.get_ttl(name, record_type)
}
pub fn clear(&self) {
self.cache.clear();
}
}
impl Default for SharedDnsCache {
fn default() -> Self {
Self::new()
}
}
impl Clone for SharedDnsCache {
fn clone(&self) -> Self {
Self {
cache: self.cache.clone(),
}
}
}