This commit is contained in:
Mateusz Gruszczyński committed 2026-11-22 14:21:54 +01:00
commit fa432bebda
189 files changed
+26219

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
[package]
name = "dns-cache"
description = "EasyDNS response/RRset cache with TTL, negative caching and LRU bound"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
dns-core.workspace = true
dns-config.workspace = true
lru.workspace = true
serde.workspace = true
[lints]
workspace = true
+555
View File
@@ -0,0 +1,555 @@
//! Bounded LRU cache for resolver/forwarder answers.
//!
//! * Keys are namespaced (`ns`): each resolution route (recursion, each forward zone)
//! has its own namespace, so data from a private forwarder never answers a
//! recursive lookup and vice versa. Authoritative data is never cached here.
//! * Entries hold the full answer for (name, type, DO-bit) – the CNAME chain, or the
//! negative proof (SOA) – plus infrastructure RRsets (NS, glue) used by the resolver.
//! * TTLs are clamped to `[min_ttl, max_ttl]`, negative TTLs to `max_negative_ttl`
//! (RFC 2308) and are never extended, except via explicit `serve_stale` (RFC 8767).
//! * Ranking (RFC 2181 §5.4.1): glue/additional data never replaces answer data.
//! * Concurrency: the cache is split into [`SHARDS`] independently locked LRU shards
//! (chosen by key hash), and each lock is held only to touch the LRU list and clone
//! an `Arc` – records are copied and TTL-adjusted after the lock is released. This
//! removes the single global lock that serialised every lookup on many-core hosts.
//! LRU order is per shard, i.e. approximately global; total capacity is unchanged.
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
use std::hash::{BuildHasher, RandomState};
use std::num::NonZeroUsize;
use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use dns_core::answer::{Answer, Security, Source};
use dns_core::proto::op::ResponseCode;
use dns_core::proto::rr::{LowerName, Name, Record, RecordType};
use lru::LruCache;
/// Trust rank of cached data (higher wins).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Rank {
Glue = 1,
Authority = 2,
Answer = 3,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Key {
pub ns: u16,
pub name: LowerName,
pub rtype: RecordType,
pub dnssec: bool,
}
/// Number of independently locked shards (power of two). Small caches use fewer
/// shards so that per-shard LRU stays meaningful.
pub const SHARDS: usize = 16;
#[derive(Debug)]
struct Entry {
rcode: ResponseCode,
// Boxed slices: no spare Vec capacity is kept per cached entry.
answers: Box<[Record]>,
authority: Box<[Record]>,
security: Security,
rank: Rank,
stored: Instant,
ttl: u32,
/// Hits since insertion (popularity for prefetch).
hits: std::sync::atomic::AtomicU32,
/// A background refresh has been started for this entry.
prefetching: std::sync::atomic::AtomicBool,
}
/// Cache statistics.
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct CacheStats {
pub entries: usize,
pub capacity: usize,
pub hits: u64,
pub misses: u64,
pub inserts: u64,
pub evictions: u64,
pub expired: u64,
pub stale_served: u64,
pub prefetches: u64,
}
type Shard = Mutex<LruCache<Key, Arc<Entry>>>;
pub struct Cache {
shards: Box<[Shard]>,
hasher: RandomState,
enabled: bool,
min_ttl: u32,
max_ttl: u32,
max_neg: u32,
serve_stale: bool,
stale_ttl: u32,
prefetch: bool,
prefetches: AtomicU64,
hits: AtomicU64,
misses: AtomicU64,
inserts: AtomicU64,
evictions: AtomicU64,
expired: AtomicU64,
stale_served: AtomicU64,
}
/// Maximum time beyond expiry that stale data may be served.
pub const MAX_STALE: Duration = Duration::from_secs(86_400);
impl Cache {
pub fn new(cfg: &dns_config::CacheConfig) -> Self {
let total = cfg.max_entries.max(1);
// at least 64 entries per shard, at most SHARDS shards; capacities sum to `total`
let n = (total / 64).clamp(1, SHARDS).next_power_of_two().min(SHARDS);
let shards = (0..n)
.map(|i| {
let cap = total / n + usize::from(i < total % n);
Mutex::new(LruCache::new(NonZeroUsize::new(cap).unwrap_or(NonZeroUsize::MIN)))
})
.collect();
Self {
shards,
hasher: RandomState::new(),
enabled: cfg.enabled,
min_ttl: cfg.min_ttl,
max_ttl: cfg.max_ttl,
max_neg: cfg.max_negative_ttl,
serve_stale: cfg.serve_stale,
stale_ttl: cfg.stale_ttl,
prefetch: cfg.prefetch,
prefetches: AtomicU64::new(0),
hits: AtomicU64::new(0),
misses: AtomicU64::new(0),
inserts: AtomicU64::new(0),
evictions: AtomicU64::new(0),
expired: AtomicU64::new(0),
stale_served: AtomicU64::new(0),
}
}
fn shard(&self, key: &Key) -> std::sync::MutexGuard<'_, LruCache<Key, Arc<Entry>>> {
// shard count is a power of two
let i = (self.hasher.hash_one(key) as usize) & (self.shards.len() - 1);
Self::lock(&self.shards[i])
}
fn lock(s: &Shard) -> std::sync::MutexGuard<'_, LruCache<Key, Arc<Entry>>> {
s.lock().unwrap_or_else(|e| e.into_inner())
}
/// Clamp a positive TTL.
pub fn clamp(&self, ttl: u32) -> u32 {
ttl.clamp(self.min_ttl, self.max_ttl.max(self.min_ttl))
}
fn with_ttl(records: &[Record], ttl: u32) -> Box<[Record]> {
records
.iter()
.map(|r| {
let mut r = r.clone();
r.ttl = r.ttl.min(ttl);
r
})
.collect()
}
/// Look up a cached answer; TTLs in the returned records are the remaining TTLs.
pub fn get(&self, key: &Key) -> Option<Answer> {
if !self.enabled {
return None;
}
let e = {
let mut c = self.shard(key);
let Some(e) = c.get(key) else {
drop(c);
self.misses.fetch_add(1, Relaxed);
return None;
};
if e.stored.elapsed().as_secs() >= u64::from(e.ttl) {
if !self.serve_stale {
c.pop(key);
}
drop(c);
self.expired.fetch_add(1, Relaxed);
self.misses.fetch_add(1, Relaxed);
return None;
}
Arc::clone(e)
}; // lock released: records are copied below without holding it
let age = (e.stored.elapsed().as_secs() as u32).min(e.ttl);
let remaining = e.ttl - age;
self.hits.fetch_add(1, Relaxed);
e.hits.fetch_add(1, Relaxed);
Some(Self::to_answer(&e, remaining, |r| {
let mut r = r.clone();
r.ttl = r.ttl.saturating_sub(age).min(remaining);
r
}))
}
fn to_answer(e: &Entry, _remaining: u32, f: impl Fn(&Record) -> Record) -> Answer {
let mut a = Answer::new(e.rcode, Source::Cache);
a.answers = e.answers.iter().map(&f).collect();
a.authority = e.authority.iter().map(&f).collect();
a.security = e.security;
a
}
/// Prefetch: `true` (once per entry) when a popular entry is about to expire and should
/// be refreshed in the background, so clients never wait for its re-resolution.
/// Conditions: original TTL ≥ 20 s, at least 2 hits, and less than 10 % of the TTL
/// (at least 2 s) left. Does not change LRU order.
pub fn prefetch_due(&self, key: &Key) -> bool {
if !self.enabled || !self.prefetch {
return false;
}
let Some(e) = self.shard(key).peek(key).map(Arc::clone) else { return false };
if e.ttl < 20 || e.hits.load(Relaxed) < 2 || e.rcode != ResponseCode::NoError {
return false;
}
let age = e.stored.elapsed().as_secs();
let remaining = u64::from(e.ttl).saturating_sub(age);
let window = u64::from((e.ttl / 10).max(2));
if remaining == 0 || remaining > window {
return false;
}
let first = !e.prefetching.swap(true, Relaxed);
if first {
self.prefetches.fetch_add(1, Relaxed);
}
first
}
/// RFC 8767: return expired data (TTL = `stale_ttl`) when fresh resolution failed.
pub fn get_stale(&self, key: &Key) -> Option<Answer> {
if !self.enabled || !self.serve_stale {
return None;
}
let e = Arc::clone(self.shard(key).peek(key)?);
if e.stored.elapsed() > Duration::from_secs(u64::from(e.ttl)) + MAX_STALE {
return None;
}
self.stale_served.fetch_add(1, Relaxed);
let st = self.stale_ttl;
let mut a = Self::to_answer(&e, st, |r| {
let mut r = r.clone();
r.ttl = st;
r
});
a.note = Some("stale".into());
Some(a)
}
fn put(&self, key: Key, e: Entry) {
if !self.enabled || e.ttl == 0 {
return;
}
let mut c = self.shard(&key);
if let Some(old) = c.peek(&key) {
let fresh = old.stored.elapsed().as_secs() < u64::from(old.ttl);
if fresh && old.rank > e.rank {
return;
}
}
if c.len() == c.cap().get() && !c.contains(&key) {
self.evictions.fetch_add(1, Relaxed);
}
c.put(key, Arc::new(e));
drop(c);
self.inserts.fetch_add(1, Relaxed);
}
/// Cache a complete answer (positive or negative) from resolution.
pub fn insert_answer(&self, key: Key, a: &Answer) {
if a.security == Security::Bogus {
return;
}
let ttl = match a.rcode {
ResponseCode::NoError if !a.answers.is_empty() => self.clamp(a.answers.iter().map(|r| r.ttl).min().unwrap_or(0)),
ResponseCode::NoError | ResponseCode::NXDomain => {
// RFC 2308 §5: negative TTL = min(SOA TTL, SOA MINIMUM); no SOA → don't cache
let soa = a.authority.iter().find_map(|r| match &r.data {
dns_core::proto::rr::RData::SOA(s) => Some(r.ttl.min(s.minimum)),
_ => None,
});
match soa {
Some(t) => t.min(self.max_neg),
None => 0,
}
}
// SERVFAIL etc.: brief caching protects authorities from retry storms (RFC 9520).
ResponseCode::ServFail => 5,
_ => 0,
};
let e = Entry {
rcode: a.rcode,
answers: Self::with_ttl(&a.answers, ttl),
authority: Self::with_ttl(&a.authority, ttl),
security: a.security,
rank: Rank::Answer,
stored: Instant::now(),
ttl,
hits: Default::default(),
prefetching: Default::default(),
};
self.put(key, e);
}
/// Cache an infrastructure RRset (NS set or addresses) learned from referrals.
pub fn insert_rrset(&self, ns: u16, records: &[Record], rank: Rank) {
let Some(first) = records.first() else { return };
let ttl = self.clamp(records.iter().map(|r| r.ttl).min().unwrap_or(0));
let key = Key { ns, name: LowerName::new(&first.name), rtype: first.record_type(), dnssec: false };
self.put(
key,
Entry {
rcode: ResponseCode::NoError,
answers: Self::with_ttl(records, ttl),
authority: Box::default(),
security: Security::Indeterminate,
rank,
stored: Instant::now(),
ttl,
hits: Default::default(),
prefetching: Default::default(),
},
);
}
/// Fetch a cached RRset (any rank) with remaining TTLs.
pub fn get_rrset(&self, ns: u16, name: &Name, rtype: RecordType) -> Option<Vec<Record>> {
let key = Key { ns, name: LowerName::new(name), rtype, dnssec: false };
let a = self.get(&key)?;
(a.rcode == ResponseCode::NoError && !a.answers.is_empty()).then_some(a.answers)
}
pub fn clear(&self) -> usize {
self.shards
.iter()
.map(|s| {
let mut c = Self::lock(s);
let n = c.len();
c.clear();
n
})
.sum()
}
/// Remove all entries at or below `name`.
pub fn clear_domain(&self, name: &Name) -> usize {
let l = LowerName::new(name);
let mut removed = 0;
for s in &*self.shards {
let mut c = Self::lock(s);
let keys: Vec<Key> = c.iter().filter(|(k, _)| l.zone_of(&k.name)).map(|(k, _)| k.clone()).collect();
for k in &keys {
c.pop(k);
}
removed += keys.len();
}
removed
}
pub fn stats(&self) -> CacheStats {
let (entries, capacity) = self.shards.iter().fold((0, 0), |(n, cap), s| {
let c = Self::lock(s);
(n + c.len(), cap + c.cap().get())
});
CacheStats {
entries,
capacity,
hits: self.hits.load(Relaxed),
misses: self.misses.load(Relaxed),
inserts: self.inserts.load(Relaxed),
evictions: self.evictions.load(Relaxed),
expired: self.expired.load(Relaxed),
stale_served: self.stale_served.load(Relaxed),
prefetches: self.prefetches.load(Relaxed),
}
}
/// Prometheus families for the cache.
pub fn render_metrics(&self) -> String {
let s = self.stats();
format!(
"# HELP dns_cache_hits_total Cache hits\n# TYPE dns_cache_hits_total counter\ndns_cache_hits_total {}\n\
# HELP dns_cache_misses_total Cache misses\n# TYPE dns_cache_misses_total counter\ndns_cache_misses_total {}\n\
# HELP dns_cache_evictions_total LRU evictions\n# TYPE dns_cache_evictions_total counter\ndns_cache_evictions_total {}\n\
# HELP dns_cache_entries Current cache entries\n# TYPE dns_cache_entries gauge\ndns_cache_entries {}\n\
# HELP dns_cache_prefetches_total Popular entries refreshed before expiry\n# TYPE dns_cache_prefetches_total counter\ndns_cache_prefetches_total {}\n",
s.hits, s.misses, s.evictions, s.entries, s.prefetches
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use dns_core::proto::rr::{
RData,
rdata::{A, SOA},
};
fn cfg(max: usize) -> dns_config::CacheConfig {
dns_config::CacheConfig { max_entries: max, max_ttl: 100, min_ttl: 0, ..Default::default() }
}
fn key(n: &str) -> Key {
Key { ns: 0, name: LowerName::new(&Name::from_ascii(n).unwrap()), rtype: RecordType::A, dnssec: false }
}
fn ans(n: &str, ttl: u32) -> Answer {
let mut a = Answer::new(ResponseCode::NoError, Source::Recursive);
a.answers.push(Record::from_rdata(Name::from_ascii(n).unwrap(), ttl, RData::A(A::new(192, 0, 2, 1))));
a
}
#[test]
fn ttl_clamp_and_hit() {
let c = Cache::new(&cfg(10));
c.insert_answer(key("a.example."), &ans("a.example.", 5000));
let a = c.get(&key("a.example.")).unwrap();
assert!(a.answers[0].ttl <= 100);
assert_eq!(a.source, Source::Cache);
assert!(c.get(&key("b.example.")).is_none());
let s = c.stats();
assert_eq!((s.hits, s.misses), (1, 1));
}
#[test]
fn negative_and_zero_ttl() {
let c = Cache::new(&cfg(10));
let mut neg = Answer::new(ResponseCode::NXDomain, Source::Recursive);
let z = Name::from_ascii("example.").unwrap();
neg.authority.push(Record::from_rdata(z.clone(), 3600, RData::SOA(SOA::new(z.clone(), z, 1, 1, 1, 1, 30))));
c.insert_answer(key("x.example."), &neg);
let a = c.get(&key("x.example.")).unwrap();
assert_eq!(a.rcode, ResponseCode::NXDomain);
assert!(a.authority[0].ttl <= 30);
// negative without SOA is not cached
c.insert_answer(key("y.example."), &Answer::new(ResponseCode::NXDomain, Source::Recursive));
assert!(c.get(&key("y.example.")).is_none());
c.insert_answer(key("z.example."), &ans("z.example.", 0));
assert!(c.get(&key("z.example.")).is_none());
}
#[test]
fn lru_bound_rank_and_clear() {
let c = Cache::new(&cfg(2));
for n in ["a.ex.", "b.ex.", "c.ex."] {
c.insert_answer(key(n), &ans(n, 50));
}
assert_eq!(c.stats().entries, 2);
assert_eq!(c.stats().evictions, 1);
// glue never replaces fresh answer data
let glue = vec![Record::from_rdata(Name::from_ascii("c.ex.").unwrap(), 50, RData::A(A::new(10, 0, 0, 1)))];
c.insert_rrset(0, &glue, Rank::Glue);
assert_eq!(c.get(&key("c.ex.")).unwrap().answers[0].data, RData::A(A::new(192, 0, 2, 1)));
assert_eq!(c.clear_domain(&Name::from_ascii("ex.").unwrap()), 2);
}
#[test]
fn namespaces_isolated() {
let c = Cache::new(&cfg(10));
c.insert_answer(key("p.corp."), &ans("p.corp.", 50));
let mut k = key("p.corp.");
k.ns = 1;
assert!(c.get(&k).is_none());
}
}
#[cfg(test)]
mod shard_tests {
use super::*;
use dns_core::proto::rr::{RData, rdata::A};
fn key(i: usize) -> Key {
Key { ns: 0, name: LowerName::new(&Name::from_ascii(format!("h{i}.example.")).unwrap()), rtype: RecordType::A, dnssec: false }
}
#[test]
fn shards_keep_total_capacity_and_bound() {
for cap in [1, 2, 63, 64, 1000, 100_000] {
let c = Cache::new(&dns_config::CacheConfig { max_entries: cap, max_ttl: 100, ..Default::default() });
assert_eq!(c.stats().capacity, cap, "capacity {cap}");
assert!(c.shards.len().is_power_of_two() && c.shards.len() <= SHARDS);
}
let c = Cache::new(&dns_config::CacheConfig { max_entries: 1000, max_ttl: 100, ..Default::default() });
for i in 0..5000 {
let mut a = Answer::new(ResponseCode::NoError, Source::Recursive);
a.answers.push(Record::from_rdata(Name::from_ascii(format!("h{i}.example.")).unwrap(), 50, RData::A(A::new(192, 0, 2, 1))));
c.insert_answer(key(i), &a);
}
let s = c.stats();
assert!(s.entries <= 1000 && s.entries > 900, "entries {}", s.entries);
assert!(c.get(&key(4999)).is_some());
assert_eq!(c.clear(), s.entries);
}
#[test]
fn prefetch_only_for_popular_entries_close_to_expiry() {
let c = Cache::new(&dns_config::CacheConfig { max_entries: 1000, max_ttl: 100_000, ..Default::default() });
let mk = |age: u64, ttl: u32| Entry {
rcode: ResponseCode::NoError,
answers: Box::default(),
authority: Box::default(),
security: Security::Indeterminate,
rank: Rank::Answer,
stored: Instant::now().checked_sub(Duration::from_secs(age)).unwrap(),
ttl,
hits: Default::default(),
prefetching: Default::default(),
};
// 100 s TTL, 95 s old: inside the last 10 %
c.put(key(1), mk(95, 100));
assert!(!c.prefetch_due(&key(1)), "not popular yet");
c.get(&key(1));
c.get(&key(1));
assert!(c.prefetch_due(&key(1)), "popular and about to expire");
assert!(!c.prefetch_due(&key(1)), "only one refresh per entry");
// young entry or short TTL: no prefetch
c.put(key(2), mk(10, 100));
c.get(&key(2));
c.get(&key(2));
assert!(!c.prefetch_due(&key(2)));
c.put(key(3), mk(9, 10));
c.get(&key(3));
c.get(&key(3));
assert!(!c.prefetch_due(&key(3)));
assert_eq!(c.stats().prefetches, 1);
// disabled by configuration
let off = Cache::new(&dns_config::CacheConfig { prefetch: false, ..Default::default() });
off.put(key(1), mk(95, 100));
off.get(&key(1));
off.get(&key(1));
assert!(!off.prefetch_due(&key(1)));
}
#[test]
fn concurrent_get_insert() {
let c = Arc::new(Cache::new(&dns_config::CacheConfig { max_entries: 10_000, max_ttl: 100, ..Default::default() }));
let hs: Vec<_> = (0..8)
.map(|t| {
let c = Arc::clone(&c);
std::thread::spawn(move || {
for i in 0..2000 {
let mut a = Answer::new(ResponseCode::NoError, Source::Recursive);
a.answers.push(Record::from_rdata(
Name::from_ascii(format!("h{i}.example.")).unwrap(),
50,
RData::A(A::new(192, 0, 2, t)),
));
c.insert_answer(key(i), &a);
assert!(c.get(&key(i)).is_some());
}
})
})
.collect();
for h in hs {
h.join().unwrap();
}
assert_eq!(c.stats().entries, 2000);
}
}