iroh_dns_server/
store.rs

1//! Pkarr packet store used to resolve DNS queries.
2
3use std::{collections::BTreeMap, num::NonZeroUsize, path::Path, sync::Arc, time::Duration};
4
5use hickory_server::proto::{
6    ProtoError,
7    rr::{Name, RecordSet, RecordType, RrKey},
8};
9use iroh_dns::pkarr::{SignedPacket, SignedPacketVerifyError, Timestamp};
10use lru::LruCache;
11use n0_error::{Result, StdResultExt};
12use n0_mainline::{Dht, DhtBuilder, MutableItem};
13pub(crate) use signed_packets::Options;
14use tokio::sync::Mutex;
15use tracing::{debug, trace, warn};
16use ttl_cache::TtlCache;
17
18use self::signed_packets::SignedPacketStore;
19use crate::{
20    config::BootstrapOption,
21    metrics::Metrics,
22    util::{PublicKeyBytes, signed_packet_to_hickory_records_without_origin},
23};
24
25mod signed_packets;
26
27/// Cache up to 1 million pkarr zones by default
28const DEFAULT_CACHE_CAPACITY: usize = 1024 * 1024;
29/// Default TTL for DHT cache entries
30const DHT_CACHE_TTL: Duration = Duration::from_secs(300);
31
32/// Where a new pkarr packet comes from
33pub(crate) enum PacketSource {
34    /// Received via HTTPS relay PUT
35    PkarrPublish,
36}
37
38/// A store for pkarr signed packets.
39///
40/// Packets are stored in the persistent `SignedPacketStore`, and cached on-demand in an in-memory LRU
41/// cache used for resolving DNS queries.
42#[derive(Debug, Clone)]
43pub(crate) struct ZoneStore {
44    cache: Arc<Mutex<ZoneCache>>,
45    store: Arc<SignedPacketStore>,
46    dht: Option<Dht>,
47    metrics: Arc<Metrics>,
48}
49
50impl ZoneStore {
51    /// Create a persistent store
52    pub(crate) fn persistent(
53        path: impl AsRef<Path>,
54        options: Options,
55        metrics: Arc<Metrics>,
56    ) -> Result<Self> {
57        let packet_store = SignedPacketStore::persistent(path, options, metrics.clone())?;
58        Ok(Self::new(packet_store, metrics))
59    }
60
61    /// Create an in-memory store.
62    #[cfg(test)]
63    pub(crate) fn in_memory(options: Options, metrics: Arc<Metrics>) -> Result<Self> {
64        let packet_store = SignedPacketStore::in_memory(options, metrics.clone())?;
65        Ok(Self::new(packet_store, metrics))
66    }
67
68    /// Configure a mainline DHT client for resolution of packets as a fallback.
69    ///
70    /// This will be used only as a fallback if there is no local info available.
71    ///
72    /// Optionally set custom bootstrap nodes. If `bootstrap` is empty it will use the default
73    /// mainline bootstrap nodes.
74    pub(crate) fn with_mainline_fallback(self, bootstrap: BootstrapOption) -> Self {
75        let mut builder = DhtBuilder::default();
76        if let BootstrapOption::Custom(ref nodes) = bootstrap {
77            builder.bootstrap(nodes);
78        }
79        let dht = builder.build().expect("failed to build DHT node");
80        Self {
81            dht: Some(dht),
82            ..self
83        }
84    }
85
86    /// Create a new zone store.
87    fn new(store: SignedPacketStore, metrics: Arc<Metrics>) -> Self {
88        let zone_cache = ZoneCache::new(DEFAULT_CACHE_CAPACITY, metrics.clone());
89        Self {
90            store: Arc::new(store),
91            cache: Arc::new(Mutex::new(zone_cache)),
92            dht: None,
93            metrics,
94        }
95    }
96
97    /// Resolve a DNS query.
98    #[tracing::instrument("resolve", skip_all, fields(pubkey=%pubkey,name=%name,typ=%record_type))]
99    pub(crate) async fn resolve(
100        &self,
101        pubkey: &PublicKeyBytes,
102        name: &Name,
103        record_type: RecordType,
104    ) -> Result<Option<Arc<RecordSet>>> {
105        trace!("store resolve");
106
107        // Check cache first (short lock scope)
108        {
109            let mut cache = self.cache.lock().await;
110            if let Some(rset) = cache.resolve(pubkey, name, record_type) {
111                debug!(
112                    len = rset.records_without_rrsigs().count(),
113                    "resolved from cache"
114                );
115                return Ok(Some(rset));
116            }
117        }
118
119        // Check persistent store
120        if let Some(packet) = self.store.get(pubkey).await? {
121            trace!(packet_timestamp = ?packet.timestamp(), "store hit");
122            let mut cache = self.cache.lock().await;
123            let result = cache.insert_and_resolve(&packet, name, record_type);
124            return match result {
125                Ok(Some(rset)) => {
126                    debug!(
127                        len = rset.records_without_rrsigs().count(),
128                        "resolved from store"
129                    );
130                    Ok(Some(rset))
131                }
132                Ok(None) => {
133                    debug!("resolved to zone, but no matching records in zone");
134                    Ok(None)
135                }
136                Err(err) => {
137                    warn!("failed to retrieve zone after inserting in cache: {err:#?}");
138                    Err(err)
139                }
140            };
141        };
142
143        if let Some(dht) = self.dht.as_ref() {
144            debug!("DHT resolve {}", pubkey.to_z32());
145            let maybe_item = dht.get_mutable_most_recent(pubkey.as_bytes(), None).await?;
146            if let Some(item) = maybe_item
147                && let Ok(packet) = mutable_item_to_signed_packet(&item)
148            {
149                debug!("DHT resolve successful {:?}", packet);
150                return self
151                    .cache
152                    .lock()
153                    .await
154                    .insert_and_resolve_dht(&packet, name, record_type);
155            }
156            debug!("DHT resolve failed");
157        }
158        Ok(None)
159    }
160
161    /// Get the latest signed packet for a pubkey.
162    // allow unused async: this will be async soon.
163    #[allow(clippy::unused_async)]
164    pub(crate) async fn get_signed_packet(
165        &self,
166        pubkey: &PublicKeyBytes,
167    ) -> Result<Option<SignedPacket>> {
168        self.store.get(pubkey).await
169    }
170
171    /// Insert a signed packet into the cache and the store.
172    ///
173    /// Returns whether this produced an update, i.e. whether the packet is the newest for its
174    /// pubkey.
175    // allow unused async: this will be async soon.
176    #[allow(clippy::unused_async)]
177    pub(crate) async fn insert(
178        &self,
179        signed_packet: SignedPacket,
180        _source: PacketSource,
181    ) -> Result<bool> {
182        let pubkey = PublicKeyBytes::from_signed_packet(&signed_packet);
183        if self.store.upsert(signed_packet).await? {
184            self.metrics.pkarr_publish_update.inc();
185            self.cache.lock().await.remove(&pubkey);
186            Ok(true)
187        } else {
188            self.metrics.pkarr_publish_noop.inc();
189            Ok(false)
190        }
191    }
192}
193
194/// Convert a mainline [`MutableItem`] to a [`SignedPacket`].
195fn mutable_item_to_signed_packet(
196    item: &MutableItem,
197) -> Result<SignedPacket, SignedPacketVerifyError> {
198    SignedPacket::from_parts_unchecked(
199        item.key(),
200        item.signature(),
201        Timestamp::from_micros(item.seq() as u64),
202        item.value(),
203    )
204}
205
206#[derive(derive_more::Debug)]
207struct ZoneCache {
208    /// Cache for explicitly added entries
209    cache: LruCache<PublicKeyBytes, CachedZone>,
210    /// Cache for DHT entries, this must have a finite TTL
211    /// so we don't cache stale entries indefinitely.
212    #[debug("dht_cache")]
213    dht_cache: TtlCache<PublicKeyBytes, CachedZone>,
214    #[debug("metrics")]
215    metrics: Arc<Metrics>,
216}
217
218impl ZoneCache {
219    fn new(cap: usize, metrics: Arc<Metrics>) -> Self {
220        let cache =
221            LruCache::sparse(NonZeroUsize::new(cap).expect("capacity must be larger than 0"));
222        let dht_cache = TtlCache::new(cap);
223        Self {
224            cache,
225            dht_cache,
226            metrics,
227        }
228    }
229
230    fn resolve(
231        &mut self,
232        pubkey: &PublicKeyBytes,
233        name: &Name,
234        record_type: RecordType,
235    ) -> Option<Arc<RecordSet>> {
236        let zone = if let Some(zone) = self.cache.get(pubkey) {
237            trace!("cache hit {}", pubkey.to_z32());
238            zone
239        } else {
240            let zone = self.dht_cache.get(pubkey)?;
241            trace!("dht cache hit {}", pubkey.to_z32());
242            zone
243        };
244        zone.resolve(name, record_type)
245    }
246
247    fn insert_and_resolve(
248        &mut self,
249        signed_packet: &SignedPacket,
250        name: &Name,
251        record_type: RecordType,
252    ) -> Result<Option<Arc<RecordSet>>> {
253        let pubkey = PublicKeyBytes::from_signed_packet(signed_packet);
254        self.insert(signed_packet)?;
255        Ok(self.resolve(&pubkey, name, record_type))
256    }
257
258    fn insert_and_resolve_dht(
259        &mut self,
260        signed_packet: &SignedPacket,
261        name: &Name,
262        record_type: RecordType,
263    ) -> Result<Option<Arc<RecordSet>>> {
264        let pubkey = PublicKeyBytes::from_signed_packet(signed_packet);
265        let zone = CachedZone::from_signed_packet(signed_packet).anyerr()?;
266        let res = zone.resolve(name, record_type);
267        self.dht_cache.insert(pubkey, zone, DHT_CACHE_TTL);
268        self.metrics
269            .cache_zones_dht
270            .set(self.dht_cache.iter().count() as i64);
271        Ok(res)
272    }
273
274    fn insert(&mut self, signed_packet: &SignedPacket) -> Result<()> {
275        let pubkey = PublicKeyBytes::from_signed_packet(signed_packet);
276        if self
277            .cache
278            .peek(&pubkey)
279            .map(|old| old.is_newer_than(signed_packet))
280            .unwrap_or(false)
281        {
282            trace!("insert skip: cached is newer");
283            Ok(())
284        } else {
285            self.cache.put(
286                pubkey,
287                CachedZone::from_signed_packet(signed_packet).anyerr()?,
288            );
289            self.metrics.cache_zones.set(self.cache.len() as i64);
290            trace!("inserted into cache");
291            Ok(())
292        }
293    }
294
295    fn remove(&mut self, pubkey: &PublicKeyBytes) {
296        self.cache.pop(pubkey);
297        self.dht_cache.remove(pubkey);
298        self.metrics.cache_zones.set(self.cache.len() as i64);
299        self.metrics
300            .cache_zones_dht
301            .set(self.dht_cache.iter().count() as i64);
302    }
303}
304
305#[derive(Debug)]
306struct CachedZone {
307    timestamp: Timestamp,
308    records: BTreeMap<RrKey, Arc<RecordSet>>,
309}
310
311impl CachedZone {
312    fn from_signed_packet(signed_packet: &SignedPacket) -> Result<Self, ProtoError> {
313        let (_label, records) =
314            signed_packet_to_hickory_records_without_origin(signed_packet, |_| true)?;
315        Ok(Self {
316            records,
317            timestamp: signed_packet.timestamp(),
318        })
319    }
320
321    fn is_newer_than(&self, signed_packet: &SignedPacket) -> bool {
322        self.timestamp > signed_packet.timestamp()
323    }
324
325    fn resolve(&self, name: &Name, record_type: RecordType) -> Option<Arc<RecordSet>> {
326        trace!(name=%name, typ=%record_type, "resolve in zone");
327        let key = RrKey::new(name.into(), record_type);
328        self.records.get(&key).cloned()
329    }
330}