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