iroh_dns_server/store/
signed_packets.rs

1use std::{
2    future::Future,
3    path::Path,
4    result,
5    sync::Arc,
6    time::{Duration, SystemTime},
7};
8
9use iroh_dns::pkarr::{SignedPacket, Timestamp};
10use n0_error::{Result, StackResultExt, StdResultExt, anyerr};
11use redb::{Database, MultimapTableDefinition, ReadableDatabase, ReadableTable, TableDefinition};
12use tokio::sync::{mpsc, oneshot};
13use tokio_util::sync::CancellationToken;
14use tracing::{debug, error, info, trace, warn};
15
16use crate::{metrics::Metrics, util::PublicKeyBytes};
17
18type SignedPacketsKey = [u8; 32];
19
20const SIGNED_PACKETS_TABLE: TableDefinition<&SignedPacketsKey, &[u8]> =
21    TableDefinition::new("signed-packets-1");
22const UPDATE_TIME_TABLE: MultimapTableDefinition<[u8; 8], SignedPacketsKey> =
23    MultimapTableDefinition::new("update-time-1");
24
25#[derive(Debug)]
26pub(super) struct SignedPacketStore {
27    send: mpsc::Sender<Message>,
28    cancel: CancellationToken,
29    _write_thread: IoThread,
30    _evict_thread: IoThread,
31}
32
33impl Drop for SignedPacketStore {
34    fn drop(&mut self) {
35        // cancel the actor
36        self.cancel.cancel();
37        // after cancellation, the two threads will be joined
38    }
39}
40
41#[derive(derive_more::Debug)]
42enum Message {
43    Upsert {
44        packet: SignedPacket,
45        res: oneshot::Sender<bool>,
46    },
47    Get {
48        key: PublicKeyBytes,
49        res: oneshot::Sender<Option<SignedPacket>>,
50    },
51    #[cfg(test)]
52    Remove {
53        key: PublicKeyBytes,
54        res: oneshot::Sender<bool>,
55    },
56    Snapshot {
57        #[debug(skip)]
58        res: oneshot::Sender<Snapshot>,
59    },
60    CheckExpired {
61        time: Timestamp,
62        key: PublicKeyBytes,
63    },
64}
65
66struct Actor {
67    db: Database,
68    recv: PeekableReceiver<Message>,
69    cancel: CancellationToken,
70    options: Options,
71    metrics: Arc<Metrics>,
72}
73
74/// Configuration for the signed-packet store.
75///
76/// Controls how incoming packets are batched into write transactions and how
77/// long packets are retained before the eviction task removes them.
78#[derive(Debug, Clone, Copy)]
79pub(crate) struct Options {
80    /// Maximum number of packets to process in a single write transaction.
81    pub(crate) max_batch_size: usize,
82    /// Maximum time to keep a write transaction open.
83    pub(crate) max_batch_time: Duration,
84    /// Time to keep packets in the store before eviction.
85    pub(crate) eviction: Duration,
86    /// Pause between eviction checks.
87    pub(crate) eviction_interval: Duration,
88}
89
90impl Default for Options {
91    fn default() -> Self {
92        Self {
93            // 64k packets
94            max_batch_size: 1024 * 64,
95            // this means we lose at most 1 second of data in case of a crash
96            max_batch_time: Duration::from_secs(1),
97            // 7 days
98            eviction: Duration::from_secs(3600 * 24 * 7),
99            // eviction can run frequently since it does not do a full scan
100            eviction_interval: Duration::from_secs(10),
101        }
102    }
103}
104
105impl Actor {
106    async fn run(mut self) {
107        match self.run0().await {
108            Ok(()) => {}
109            Err(e) => {
110                tracing::error!("packet store actor failed: {:?}", e);
111                self.cancel.cancel();
112            }
113        }
114    }
115
116    async fn run0(&mut self) -> Result<()> {
117        while let Some(msg) = self.recv.recv().await {
118            // if we get a snapshot message here we don't need to do a write transaction
119            let msg = if let Message::Snapshot { res } = msg {
120                let snapshot = Snapshot::new(&self.db)?;
121                res.send(snapshot).ok();
122                continue;
123            } else {
124                msg
125            };
126            trace!("batch");
127            self.recv.push_back(msg).unwrap();
128            let transaction = self.db.begin_write().anyerr()?;
129            let mut tables = Tables::new(&transaction).anyerr()?;
130            let timeout = tokio::time::sleep(self.options.max_batch_time);
131            tokio::pin!(timeout);
132            for _ in 0..self.options.max_batch_size {
133                tokio::select! {
134                    _ = self.cancel.cancelled() => {
135                        drop(tables);
136                        transaction.commit().anyerr()?;
137                        return Ok(());
138                    }
139                    _ = &mut timeout => break,
140                    Some(msg) = self.recv.recv() => self.handle_message(msg, &mut tables)?,
141                }
142            }
143            drop(tables);
144            transaction.commit().anyerr()?;
145        }
146        Ok(())
147    }
148
149    fn handle_message(&self, msg: Message, tables: &mut Tables) -> Result<()> {
150        match msg {
151            Message::Get { key, res } => match get_packet(&tables.signed_packets, &key) {
152                Ok(packet) => {
153                    trace!("get {key}: {}", packet.is_some());
154                    res.send(packet).ok();
155                }
156                Err(err) => {
157                    warn!("get {key} failed: {err:#}");
158                    return Err(err).context(format!("get packet for {key} failed"));
159                }
160            },
161            Message::Upsert { packet, res } => {
162                let key = PublicKeyBytes::from_signed_packet(&packet);
163                trace!("upsert {}", key);
164                let replaced = match get_packet(&tables.signed_packets, &key)? {
165                    Some(existing) => {
166                        if existing.more_recent_than(&packet) {
167                            res.send(false).ok();
168                            return Ok(());
169                        } else {
170                            // remove the old packet from the update time index
171                            tables
172                                .update_time
173                                .remove(&existing.timestamp().to_be_bytes(), key.as_bytes())
174                                .anyerr()?;
175                            true
176                        }
177                    }
178                    _ => false,
179                };
180                let value = serialize(&packet);
181                tables
182                    .signed_packets
183                    .insert(key.as_bytes(), &value[..])
184                    .anyerr()?;
185                tables
186                    .update_time
187                    .insert(&packet.timestamp().to_be_bytes(), key.as_bytes())
188                    .anyerr()?;
189                if replaced {
190                    self.metrics.store_packets_updated.inc();
191                } else {
192                    self.metrics.store_packets_inserted.inc();
193                }
194                res.send(true).ok();
195            }
196            #[cfg(test)]
197            Message::Remove { key, res } => {
198                trace!("remove {}", key);
199                let updated = match tables.signed_packets.remove(key.as_bytes()).anyerr()? {
200                    Some(row) => {
201                        let packet = deserialize(row.value())?;
202                        tables
203                            .update_time
204                            .remove(&packet.timestamp().to_be_bytes(), key.as_bytes())
205                            .anyerr()?;
206                        self.metrics.store_packets_removed.inc();
207                        true
208                    }
209                    _ => false,
210                };
211                res.send(updated).ok();
212            }
213            Message::Snapshot { res } => {
214                trace!("snapshot");
215                res.send(Snapshot::new(&self.db)?).ok();
216            }
217            Message::CheckExpired { key, time } => {
218                trace!("check expired {} at {}", key, fmt_time(time));
219                match get_packet(&tables.signed_packets, &key)? {
220                    Some(packet) => {
221                        let expiry_us = self.options.eviction.as_micros() as u64;
222                        let expired = Timestamp::from_micros(
223                            Timestamp::now().as_micros().saturating_sub(expiry_us),
224                        );
225                        if packet.timestamp() < expired {
226                            tables
227                                .update_time
228                                .remove(&time.to_be_bytes(), key.as_bytes())
229                                .anyerr()?;
230                            let _ = tables.signed_packets.remove(key.as_bytes()).anyerr()?;
231                            self.metrics.store_packets_expired.inc();
232                            debug!("removed expired packet {key}");
233                        } else {
234                            debug!(
235                                "packet {key} is no longer expired, removing obsolete expiry entry"
236                            );
237                            tables
238                                .update_time
239                                .remove(&time.to_be_bytes(), key.as_bytes())
240                                .anyerr()?;
241                        }
242                    }
243                    None => {
244                        debug!("expired packet {key} not found, remove from expiry table");
245                        tables
246                            .update_time
247                            .remove(&time.to_be_bytes(), key.as_bytes())
248                            .anyerr()?;
249                    }
250                }
251            }
252        }
253        Ok(())
254    }
255}
256
257fn fmt_time(t: Timestamp) -> String {
258    let duration = std::time::Duration::from_micros(t.as_micros());
259    humantime::format_rfc3339_micros(SystemTime::UNIX_EPOCH + duration).to_string()
260}
261
262/// A struct similar to [`redb::Table`] but for all tables that make up the
263/// signed packet store.
264struct Tables<'a> {
265    pub signed_packets: redb::Table<'a, &'static SignedPacketsKey, &'static [u8]>,
266    pub update_time: redb::MultimapTable<'a, [u8; 8], SignedPacketsKey>,
267}
268
269impl<'txn> Tables<'txn> {
270    fn new(tx: &'txn redb::WriteTransaction) -> result::Result<Self, redb::TableError> {
271        Ok(Self {
272            signed_packets: tx.open_table(SIGNED_PACKETS_TABLE)?,
273            update_time: tx.open_multimap_table(UPDATE_TIME_TABLE)?,
274        })
275    }
276}
277
278struct Snapshot {
279    #[allow(dead_code)]
280    pub signed_packets: redb::ReadOnlyTable<&'static SignedPacketsKey, &'static [u8]>,
281    pub update_time: redb::ReadOnlyMultimapTable<[u8; 8], SignedPacketsKey>,
282}
283
284impl Snapshot {
285    fn new(db: &Database) -> Result<Self> {
286        let tx = db.begin_read().anyerr()?;
287        Ok(Self {
288            signed_packets: tx.open_table(SIGNED_PACKETS_TABLE).anyerr()?,
289            update_time: tx.open_multimap_table(UPDATE_TIME_TABLE).anyerr()?,
290        })
291    }
292}
293
294impl SignedPacketStore {
295    pub(crate) fn persistent(
296        path: impl AsRef<Path>,
297        options: Options,
298        metrics: Arc<Metrics>,
299    ) -> Result<Self> {
300        let path = path.as_ref();
301        info!("loading packet database from {}", path.to_string_lossy());
302        if let Some(parent) = path.parent() {
303            std::fs::create_dir_all(parent).with_std_context(|_| {
304                format!(
305                    "failed to create database directory at {}",
306                    path.to_string_lossy()
307                )
308            })?;
309        }
310        let db = Database::builder()
311            .create(path)
312            .std_context("failed to open packet database")?;
313        Self::open(db, options, metrics)
314    }
315
316    #[cfg(test)]
317    pub(crate) fn in_memory(options: Options, metrics: Arc<Metrics>) -> Result<Self> {
318        info!("using in-memory packet database");
319        let db = Database::builder()
320            .create_with_backend(redb::backends::InMemoryBackend::new())
321            .anyerr()?;
322        Self::open(db, options, metrics)
323    }
324
325    pub(crate) fn open(db: Database, options: Options, metrics: Arc<Metrics>) -> Result<Self> {
326        // create tables
327        let write_tx = db.begin_write().anyerr()?;
328        let _ = Tables::new(&write_tx).anyerr()?;
329        write_tx.commit().anyerr()?;
330        let (send, recv) = mpsc::channel(1024);
331        let send2 = send.clone();
332        let cancel = CancellationToken::new();
333        let cancel2 = cancel.clone();
334        let cancel3 = cancel.clone();
335        let actor = Actor {
336            db,
337            recv: PeekableReceiver::new(recv),
338            cancel: cancel2,
339            options,
340            metrics,
341        };
342        // start an io thread and donate it to the tokio runtime so we can do blocking IO
343        // inside the thread despite being in a tokio runtime
344        let _write_thread = IoThread::new("packet-store-actor", move || actor.run())?;
345        let _evict_thread = IoThread::new("packet-store-evict", move || {
346            evict_task(send2, options, cancel3)
347        })?;
348        Ok(Self {
349            send,
350            cancel,
351            _write_thread,
352            _evict_thread,
353        })
354    }
355
356    pub(crate) async fn upsert(&self, packet: SignedPacket) -> Result<bool> {
357        let (tx, rx) = oneshot::channel();
358        self.send
359            .send(Message::Upsert { packet, res: tx })
360            .await
361            .anyerr()?;
362        rx.await.anyerr()
363    }
364
365    pub(crate) async fn get(&self, key: &PublicKeyBytes) -> Result<Option<SignedPacket>> {
366        let (tx, rx) = oneshot::channel();
367        self.send
368            .send(Message::Get { key: *key, res: tx })
369            .await
370            .anyerr()?;
371        rx.await.anyerr()
372    }
373
374    #[cfg(test)]
375    pub(crate) async fn remove(&self, key: &PublicKeyBytes) -> Result<bool> {
376        let (tx, rx) = oneshot::channel();
377        self.send
378            .send(Message::Remove { key: *key, res: tx })
379            .await
380            .anyerr()?;
381        rx.await.anyerr()
382    }
383}
384
385/// Serialize a signed packet for storage: `<8 bytes last_seen><packet bytes>`.
386fn serialize(packet: &SignedPacket) -> Vec<u8> {
387    let mut out = Vec::with_capacity(8 + packet.as_bytes().len());
388    out.extend_from_slice(&Timestamp::now().to_be_bytes());
389    out.extend_from_slice(packet.as_bytes());
390    out
391}
392
393/// Deserialize a signed packet from storage format.
394///
395/// Handles backwards compatibility with older storage formats that didn't include
396/// the `last_seen` prefix.
397fn deserialize(data: &[u8]) -> Result<SignedPacket> {
398    // Try parsing as <8 bytes last_seen><packet> (pkarr v3 format)
399    if data.len() >= 8
400        && let Ok(packet) = SignedPacket::from_bytes_unchecked(&data[8..])
401    {
402        return Ok(packet);
403    }
404    // Fall back to raw packet bytes (pre-v0.35 format without last_seen prefix)
405    SignedPacket::from_bytes_unchecked(data)
406        .map_err(|err| anyerr!("Failed to decode stored packet: {err:#}"))
407}
408
409fn get_packet(
410    table: &impl ReadableTable<&'static SignedPacketsKey, &'static [u8]>,
411    key: &PublicKeyBytes,
412) -> Result<Option<SignedPacket>> {
413    let Some(row) = table
414        .get(key.as_ref())
415        .std_context("database fetch failed")?
416    else {
417        return Ok(None);
418    };
419    Ok(Some(deserialize(row.value())?))
420}
421
422async fn evict_task(send: mpsc::Sender<Message>, options: Options, cancel: CancellationToken) {
423    let cancel2 = cancel.clone();
424    let _ = cancel2
425        .run_until_cancelled(async move {
426            info!("starting evict task");
427            if let Err(cause) = evict_task_inner(send, options).await {
428                error!("evict task failed: {:?}", cause);
429            }
430            // when we are done for whatever reason we want to shut down the actor
431            cancel.cancel();
432        })
433        .await;
434}
435
436/// Periodically check for expired packets and remove them.
437async fn evict_task_inner(send: mpsc::Sender<Message>, options: Options) -> Result<()> {
438    let expiry_us = options.eviction.as_micros() as u64;
439    loop {
440        let (tx, rx) = oneshot::channel();
441        let _ = send.send(Message::Snapshot { res: tx }).await.ok();
442        // if we can't get the snapshot we exit the loop, main actor dead
443        let snapshot = rx.await.std_context("failed to get snapshot")?;
444
445        let expired =
446            Timestamp::from_micros(Timestamp::now().as_micros().saturating_sub(expiry_us));
447        trace!("evicting packets older than {}", fmt_time(expired));
448        // if getting the range fails we exit the loop and shut down
449        // if individual reads fail we log the error and limp on
450        for item in snapshot
451            .update_time
452            .range(..expired.to_be_bytes())
453            .anyerr()?
454        {
455            let (time, keys) = match item {
456                Ok(v) => v,
457                Err(e) => {
458                    error!("failed to read update_time row {:?}", e);
459                    continue;
460                }
461            };
462            let time = Timestamp::from_be_bytes(time.value());
463            trace!("evicting expired packets at {}", fmt_time(time));
464            for item in keys {
465                let key = match item {
466                    Ok(v) => v,
467                    Err(e) => {
468                        error!(
469                            "failed to read update_time item at {}: {:?}",
470                            fmt_time(time),
471                            e
472                        );
473                        continue;
474                    }
475                };
476                // Safety: bytes were originally written from a validated PublicKey.
477                // If the database is corrupt, to_z32() may panic downstream.
478                let key = PublicKeyBytes::new_unchecked(key.value());
479
480                debug!("evicting expired packet {} {}", fmt_time(time), key);
481                send.send(Message::CheckExpired { time, key })
482                    .await
483                    .anyerr()?;
484            }
485        }
486        // sleep for the eviction interval so we don't constantly check
487        tokio::time::sleep(options.eviction_interval).await;
488    }
489}
490
491/// An io thread that drives a future to completion on the current tokio runtime
492///
493/// Inside the future, blocking IO can be done without blocking one of the tokio
494/// pool threads.
495#[derive(Debug)]
496struct IoThread {
497    handle: Option<std::thread::JoinHandle<()>>,
498}
499
500impl IoThread {
501    /// Spawn a new io thread.
502    ///
503    /// Calling this function requires that the current thread is running in a
504    /// tokio runtime. It is up to the caller to make sure the future exits,
505    /// e.g. by using a cancellation token. Otherwise, drop will block.
506    fn new<F, Fut>(name: &str, f: F) -> Result<Self>
507    where
508        F: FnOnce() -> Fut + Send + 'static,
509        Fut: Future<Output = ()>,
510    {
511        let rt = tokio::runtime::Handle::try_current().std_context("get tokio handle")?;
512        let handle = std::thread::Builder::new()
513            .name(name.into())
514            .spawn(move || rt.block_on(f()))
515            .std_context("failed to spawn thread")?;
516        Ok(Self {
517            handle: Some(handle),
518        })
519    }
520}
521
522impl Drop for IoThread {
523    fn drop(&mut self) {
524        if let Some(handle) = self.handle.take() {
525            let _ = handle.join();
526        }
527    }
528}
529
530/// A wrapper for a tokio mpsc receiver that allows peeking at the next message.
531#[derive(Debug)]
532struct PeekableReceiver<T> {
533    msg: Option<T>,
534    recv: tokio::sync::mpsc::Receiver<T>,
535}
536
537#[allow(dead_code)]
538impl<T> PeekableReceiver<T> {
539    fn new(recv: tokio::sync::mpsc::Receiver<T>) -> Self {
540        Self { msg: None, recv }
541    }
542
543    /// Receive the next message.
544    ///
545    /// Will block if there are no messages.
546    /// Returns None only if there are no more messages (sender is dropped).
547    async fn recv(&mut self) -> Option<T> {
548        if let Some(msg) = self.msg.take() {
549            return Some(msg);
550        }
551        self.recv.recv().await
552    }
553
554    /// Push back a message. This will only work if there is room for it.
555    /// Otherwise, it will fail and return the message.
556    fn push_back(&mut self, msg: T) -> std::result::Result<(), T> {
557        if self.msg.is_none() {
558            self.msg = Some(msg);
559            Ok(())
560        } else {
561            Err(msg)
562        }
563    }
564}
565
566#[cfg(test)]
567mod tests {
568    use iroh_base::SecretKey;
569
570    use super::*;
571
572    fn test_signed_packet() -> SignedPacket {
573        let secret_key = SecretKey::generate();
574        SignedPacket::from_txt_strings(&secret_key, "_iroh", ["relay=https://example.com"], 30)
575            .expect("valid packet")
576    }
577
578    #[test]
579    fn serialize_deserialize_roundtrip() {
580        let packet = test_signed_packet();
581        let serialized = serialize(&packet);
582        let deserialized = deserialize(&serialized).expect("roundtrip should succeed");
583        assert_eq!(packet.as_bytes(), deserialized.as_bytes());
584    }
585
586    #[test]
587    fn deserialize_old_format_without_last_seen_prefix() {
588        // Pre-v0.35 format: raw SignedPacket bytes without the 8-byte last_seen prefix
589        let packet = test_signed_packet();
590        let old_format = packet.as_bytes().to_vec();
591        let deserialized = deserialize(&old_format).expect("old format should be readable");
592        assert_eq!(packet.as_bytes(), deserialized.as_bytes());
593    }
594
595    #[tokio::test]
596    async fn remove_in_memory() {
597        let store = SignedPacketStore::in_memory(Options::default(), Arc::new(Metrics::default()))
598            .expect("in-memory store");
599        let packet = test_signed_packet();
600        let key = PublicKeyBytes::from_signed_packet(&packet);
601
602        assert!(store.upsert(packet.clone()).await.expect("upsert"));
603        assert!(store.get(&key).await.expect("get").is_some());
604
605        assert!(store.remove(&key).await.expect("remove existing"));
606        assert!(store.get(&key).await.expect("get after remove").is_none());
607
608        assert!(!store.remove(&key).await.expect("remove missing"));
609    }
610}