iroh/socket/
concurrent_read_map.rs

1//! This module implements a map that can be modified from only one task but read from many others.
2//!
3//! We ensure this map avoids race conditions from multiple writers by doing these two things:
4//! - We only allow writing from one owner of the `&mut self` [`ConcurrentReadMap`].
5//!   It cannot be cloned.
6//! - The read-only replicas [`ReadOnlyMap`] can only read, not write, but allow reading from
7//!   concurrent tasks.
8
9use std::{hash::Hash, sync::Arc};
10
11/// A map that can be modified from only one task but read from many others.
12///
13/// Only the single `&mut self`-based "leader" which owns this map can modify it, but cheaply
14/// clonable "followers" can be created with [`ConcurrentReadMap::read_only`].
15/// These clones will update with recent writes from the leader.
16///
17/// Uses a randomly keyed hasher because keys may be chosen by remote peers in the way iroh
18/// uses this map: enough colliding hash bits can stall [`papaya::HashMap`] resizing, causing
19/// subsequent iterations to hang.
20#[derive(Debug)]
21pub(crate) struct ConcurrentReadMap<K: Hash + Eq, V>(Arc<papaya::HashMap<K, V>>);
22
23impl<K: Hash + Eq, V> Default for ConcurrentReadMap<K, V> {
24    fn default() -> Self {
25        Self(Default::default())
26    }
27}
28
29impl<K: Hash + Eq, V> ConcurrentReadMap<K, V> {
30    pub(crate) fn get_or_insert_with<F>(&mut self, key: K, f: F) -> V
31    where
32        F: FnOnce() -> V,
33        V: Clone,
34    {
35        self.0.get_or_insert_with(key, f, &self.0.guard()).clone()
36    }
37
38    pub(crate) fn insert(&mut self, key: K, value: V) {
39        self.0.insert(key, value, &self.0.guard());
40    }
41
42    pub(crate) fn remove(&mut self, key: &K) {
43        self.0.remove(key, &self.0.guard());
44    }
45
46    pub(crate) fn read_only(&self) -> ReadOnlyMap<K, V> {
47        ReadOnlyMap(self.0.clone())
48    }
49}
50
51/// A read replica for a [`ConcurrentReadMap`].
52///
53/// These can be cloned cheaply and will read recent writes from the original map.
54#[derive(Clone, Debug)]
55pub(crate) struct ReadOnlyMap<K: Hash + Eq, V>(Arc<papaya::HashMap<K, V>>);
56
57impl<K: Hash + Eq, V> ReadOnlyMap<K, V> {
58    pub(crate) fn get(&self, key: &K) -> Option<V>
59    where
60        V: Clone,
61    {
62        self.0.get(key, &self.0.guard()).cloned()
63    }
64
65    pub(crate) fn guard(&self) -> papaya::LocalGuard<'_> {
66        self.0.guard()
67    }
68
69    pub(crate) fn values<'g, G: papaya::Guard>(&self, guard: &'g G) -> papaya::Values<'g, K, V, G> {
70        self.0.values(guard)
71    }
72}