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