use super::{oxcache_error_to_io, DnsCacheService};
use crate::common::metrics_shim::counter;
use crate::infrastructure::oxcache::DnsCacheEntry;
use log::{debug, warn};
use std::net::IpAddr;
use std::time::Instant;
impl DnsCacheService {
pub(super) async fn cache_lookup(&self, cache_key: &String) -> Option<Vec<IpAddr>> {
match self.cache.get(cache_key).await {
Ok(Some(entry)) => {
debug!("DNS cache hit for {}", cache_key);
counter!(
"crawlrs_cache_hit_total",
"cache_type" => "dns",
"result" => "hit"
)
.increment(1);
Some(entry.ips)
}
Ok(None) => {
debug!("DNS cache miss for {}, performing lookup", cache_key);
counter!(
"crawlrs_cache_hit_total",
"cache_type" => "dns",
"result" => "miss"
)
.increment(1);
None
}
Err(e) => {
warn!("DNS cache error for {}: {}", cache_key, e);
counter!(
"crawlrs_cache_hit_total",
"cache_type" => "dns",
"result" => "miss"
)
.increment(1);
None
}
}
}
pub(super) async fn resolve_and_cache(
&self,
cache_key: &String,
hostname: &str,
) -> Result<DnsCacheEntry, std::io::Error> {
let resolver = &self.resolver;
let default_ttl = self.default_ttl;
self.cache
.get_or_with_ttl(cache_key, Some(default_ttl), || async {
let lookup = resolver.lookup_ip(hostname).await.map_err(|e| {
oxcache::OxCacheError::IoError(std::io::Error::other(format!(
"DNS resolution failed for {}: {}",
hostname, e
)))
})?;
let ips: Vec<IpAddr> = lookup.iter().collect();
if ips.is_empty() {
return Err(oxcache::OxCacheError::IoError(std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("No IP addresses resolved for {}", hostname),
)));
}
let ttl = lookup
.valid_until()
.checked_duration_since(Instant::now())
.map(|d| d.min(default_ttl))
.filter(|d| !d.is_zero())
.unwrap_or(default_ttl);
Ok(DnsCacheEntry {
ips,
remaining_ttl_secs: ttl.as_secs(),
})
})
.await
.map_err(oxcache_error_to_io)
}
}