Skip to main content

syncweb_core/sync/
peer_tracker.rs

1use std::{
2    collections::{HashMap, HashSet},
3    time::{Duration, Instant},
4};
5
6use iroh::PublicKey;
7use iroh_blobs::Hash;
8
9/// Policy used when the peer availability cache reaches its size limit.
10#[derive(Clone, Copy, Debug, Eq, PartialEq)]
11#[non_exhaustive]
12pub enum EvictionStrategy {
13    Lru,
14    Fifo,
15}
16
17#[derive(Clone, Debug)]
18struct Availability {
19    peers: HashSet<PublicKey>,
20    inserted_at: u64,
21    accessed_at: u64,
22    last_seen: Instant,
23}
24
25/// Bounded cache mapping blob hashes to the peers observed serving them.
26///
27/// `len()` returns the number of unique blob hashes tracked, not the total
28/// number of peers. Use [`peer_count`](Self::peer_count) for per-blob counts.
29#[derive(Clone, Debug)]
30pub struct PeerTracker {
31    entries: HashMap<Hash, Availability>,
32    max_cache_size: usize,
33    strategy: EvictionStrategy,
34    expiry: Duration,
35    clock: u64,
36}
37
38impl PeerTracker {
39    #[must_use]
40    pub fn new(max_cache_size: usize, strategy: EvictionStrategy) -> Self {
41        Self::with_expiry(max_cache_size, strategy, Duration::from_mins(5))
42    }
43
44    #[must_use]
45    pub fn with_expiry(max_cache_size: usize, strategy: EvictionStrategy, expiry: Duration) -> Self {
46        Self {
47            entries: HashMap::new(),
48            max_cache_size,
49            strategy,
50            expiry,
51            clock: 0,
52        }
53    }
54
55    pub fn record_peer(&mut self, blob_hash: Hash, node_id: PublicKey) {
56        self.clock = self.clock.saturating_add(1);
57        let now = Instant::now();
58        let entry = self.entries.entry(blob_hash).or_insert_with(|| Availability {
59            peers: HashSet::new(),
60            inserted_at: self.clock,
61            accessed_at: self.clock,
62            last_seen: now,
63        });
64        entry.peers.insert(node_id);
65        entry.accessed_at = self.clock;
66        entry.last_seen = now;
67        self.evict_to_limit();
68    }
69
70    #[must_use]
71    pub fn get_peers(&mut self, blob_hash: &Hash) -> Vec<PublicKey> {
72        self.clock = self.clock.saturating_add(1);
73        self.entries.get_mut(blob_hash).map_or_else(Vec::new, |entry| {
74            if self.strategy == EvictionStrategy::Lru {
75                entry.accessed_at = self.clock;
76            }
77            entry.peers.iter().copied().collect()
78        })
79    }
80
81    #[must_use]
82    pub fn peer_count(&self, blob_hash: &Hash) -> usize {
83        self.entries.get(blob_hash).map_or(0, |entry| entry.peers.len())
84    }
85
86    #[must_use]
87    pub fn contains(&self, blob_hash: &Hash, node_id: &PublicKey) -> bool {
88        self.entries
89            .get(blob_hash)
90            .is_some_and(|entry| entry.peers.contains(node_id))
91    }
92
93    /// Remove a peer from all cached blob availability records.
94    pub fn on_peer_disconnected(&mut self, node_id: &PublicKey) {
95        self.entries.retain(|_, entry| {
96            entry.peers.remove(node_id);
97            !entry.peers.is_empty()
98        });
99    }
100
101    #[must_use]
102    pub fn is_fresh(&self, blob_hash: &Hash) -> bool {
103        self.entries
104            .get(blob_hash)
105            .is_some_and(|entry| entry.last_seen.elapsed() <= self.expiry)
106    }
107
108    #[must_use]
109    pub fn len(&self) -> usize {
110        self.entries.len()
111    }
112
113    #[must_use]
114    pub fn is_empty(&self) -> bool {
115        self.entries.is_empty()
116    }
117
118    pub fn tick_and_maybe_evict(&mut self) {
119        let now = Instant::now();
120        self.entries
121            .retain(|_, entry| now.saturating_duration_since(entry.last_seen) <= self.expiry);
122        self.evict_to_limit();
123    }
124
125    fn evict_to_limit(&mut self) {
126        while self.entries.len() > self.max_cache_size {
127            let oldest = self
128                .entries
129                .iter()
130                .min_by_key(|(_, entry)| match self.strategy {
131                    EvictionStrategy::Lru => entry.accessed_at,
132                    EvictionStrategy::Fifo => entry.inserted_at,
133                })
134                .map(|(hash, _)| *hash);
135            if let Some(hash) = oldest {
136                self.entries.remove(&hash);
137            } else {
138                break;
139            }
140        }
141    }
142}
143
144/// Compact peer presence cache using stable integer indices.
145#[derive(Clone, Debug, Default)]
146pub struct EfficientPeerCache {
147    hash_to_indices: HashMap<Hash, Vec<u16>>,
148    presence: HashMap<Hash, Vec<u64>>,
149    peer_to_index: HashMap<PublicKey, u16>,
150    index_peer: Vec<PublicKey>,
151    last_seen: HashMap<PublicKey, Instant>,
152}
153
154impl EfficientPeerCache {
155    #[must_use]
156    pub fn new() -> Self {
157        Self::default()
158    }
159
160    /// Record that a peer can serve a blob.
161    ///
162    /// # Errors
163    ///
164    /// Returns an error after all `u16` peer indices have been allocated.
165    pub fn add_presence(&mut self, hash: Hash, peer: PublicKey) -> crate::Result<()> {
166        let index = if let Some(index) = self.peer_to_index.get(&peer) {
167            *index
168        } else {
169            let index = u16::try_from(self.index_peer.len())
170                .map_err(|error| crate::SyncwebError::operation("peer cache capacity exceeded", error))?;
171            self.index_peer.push(peer);
172            self.peer_to_index.insert(peer, index);
173            index
174        };
175        self.last_seen.insert(peer, Instant::now());
176        let indices = self.hash_to_indices.entry(hash).or_default();
177        match indices.binary_search(&index) {
178            Ok(_) => {}
179            Err(position) => indices.insert(position, index),
180        }
181        let index_usize = usize::from(index);
182        let word_index = index_usize.checked_div(64).unwrap_or(0);
183        let bit_index = index_usize.checked_rem(64).unwrap_or(0);
184        let mask = 1_u64.checked_shl(u32::try_from(bit_index).unwrap_or(0)).unwrap_or(0);
185        let presence = self.presence.entry(hash).or_default();
186        presence.resize(word_index.saturating_add(1), 0);
187        if let Some(word) = presence.get_mut(word_index) {
188            *word |= mask;
189        }
190        Ok(())
191    }
192
193    pub fn remove_presence(&mut self, hash: &Hash, peer: &PublicKey) -> bool {
194        let Some(index) = self.peer_to_index.get(peer) else {
195            return false;
196        };
197        let Some(indices) = self.hash_to_indices.get_mut(hash) else {
198            return false;
199        };
200        let removed = indices.binary_search(index).is_ok_and(|position| {
201            indices.remove(position);
202            true
203        });
204        if indices.is_empty() {
205            self.hash_to_indices.remove(hash);
206        }
207        if removed {
208            let index_usize = usize::from(*index);
209            let word_index = index_usize.checked_div(64).unwrap_or(0);
210            let bit_index = index_usize.checked_rem(64).unwrap_or(0);
211            let mask = 1_u64.checked_shl(u32::try_from(bit_index).unwrap_or(0)).unwrap_or(0);
212            if let Some(word) = self.presence.get_mut(hash).and_then(|words| words.get_mut(word_index)) {
213                *word &= !mask;
214            }
215        }
216        removed
217    }
218
219    #[must_use]
220    pub fn has_peer(&self, hash: &Hash, peer: &PublicKey) -> bool {
221        self.peer_to_index.get(peer).is_some_and(|index| {
222            let index_usize = usize::from(*index);
223            let word_index = index_usize.checked_div(64).unwrap_or(0);
224            let bit_index = index_usize.checked_rem(64).unwrap_or(0);
225            let mask = 1_u64.checked_shl(u32::try_from(bit_index).unwrap_or(0)).unwrap_or(0);
226            self.presence
227                .get(hash)
228                .and_then(|words| words.get(word_index))
229                .is_some_and(|word| *word & mask != 0)
230        })
231    }
232
233    #[must_use]
234    pub fn peers(&self, hash: &Hash) -> Vec<PublicKey> {
235        self.hash_to_indices.get(hash).map_or_else(Vec::new, |indices| {
236            indices
237                .iter()
238                .filter_map(|index| self.index_peer.get(usize::from(*index)).copied())
239                .collect()
240        })
241    }
242
243    /// Return the total number of *unique* peers registered across all blobs.
244    /// For per-blob counts see [`active_peer_count`](Self::active_peer_count).
245    #[must_use]
246    pub const fn total_peers(&self) -> usize {
247        self.index_peer.len()
248    }
249
250    #[must_use]
251    pub fn active_peer_count(&self, hash: &Hash) -> usize {
252        self.hash_to_indices.get(hash).map_or(0, Vec::len)
253    }
254
255    #[must_use]
256    pub fn memory_usage(&self) -> usize {
257        let word_bytes = self
258            .presence
259            .values()
260            .map(|words| words.len().saturating_mul(8))
261            .sum::<usize>();
262        let index_bytes = self
263            .hash_to_indices
264            .values()
265            .map(|indices| indices.len().saturating_mul(2))
266            .sum::<usize>();
267        word_bytes
268            .saturating_add(index_bytes)
269            .saturating_add(
270                self.peer_to_index
271                    .len()
272                    .saturating_mul(std::mem::size_of::<PublicKey>().saturating_add(2)),
273            )
274            .saturating_add(self.index_peer.len().saturating_mul(std::mem::size_of::<PublicKey>()))
275    }
276
277    /// Remove a peer from every blob while retaining stable indices for peers
278    /// that may be observed again later.
279    pub fn remove_peer(&mut self, peer: &PublicKey) {
280        if !self.peer_to_index.contains_key(peer) {
281            return;
282        }
283        let hashes = self.hash_to_indices.keys().copied().collect::<Vec<_>>();
284        for hash in hashes {
285            let _removed = self.remove_presence(&hash, peer);
286        }
287        self.last_seen.remove(peer);
288    }
289
290    /// Remove peers whose `last_seen` timestamp exceeds the given TTL.
291    ///
292    /// Fully reclaims each removed peer's index, so the total number of
293    /// tracked peers stays bounded.
294    ///
295    /// Returns the number of peers removed.
296    pub fn retain_active(&mut self, ttl: Duration) -> usize {
297        self.retain_active_at(ttl, Instant::now())
298    }
299
300    /// Like [`retain_active`](Self::retain_active) but with an explicit
301    /// observation time for deterministic testing.
302    fn retain_active_at(&mut self, ttl: Duration, now: Instant) -> usize {
303        let cutoff = now.checked_sub(ttl).unwrap_or(now);
304        let stale: Vec<PublicKey> = self
305            .last_seen
306            .iter()
307            .filter(|(_, last_seen)| **last_seen < cutoff)
308            .map(|(peer, _)| *peer)
309            .collect();
310        let count = stale.len();
311        for peer in stale {
312            self.remove_peer(&peer);
313            if let Some(stale_index) = self.peer_to_index.remove(&peer) {
314                let last_index = self.index_peer.len().saturating_sub(1);
315                if usize::from(stale_index) != last_index
316                    && let Some(last_peer) = self.index_peer.get(last_index).copied()
317                {
318                    // Update presence bitmask for the moved peer: its bit
319                    // is still at last_index but must be moved to stale_index.
320                    self.remap_presence(last_index, usize::from(stale_index));
321                    if let Some(slot) = self.index_peer.get_mut(usize::from(stale_index)) {
322                        *slot = last_peer;
323                    }
324                    self.peer_to_index.insert(last_peer, stale_index);
325                }
326                self.index_peer.pop();
327            }
328        }
329        count
330    }
331
332    /// Move all presence bits from `old_index` to `new_index` after a
333    /// swap-remove compaction of `index_peer`.
334    fn remap_presence(&mut self, old_index: usize, new_index: usize) {
335        let old_u16 = u16::try_from(old_index).unwrap_or(u16::MAX);
336        let new_u16 = u16::try_from(new_index).unwrap_or(u16::MAX);
337        for (hash, indices) in &mut self.hash_to_indices {
338            // binary_search returns a valid index in the Ok case
339            let Ok(pos) = indices.binary_search(&old_u16) else {
340                continue;
341            };
342            if let Some(slot) = indices.get_mut(pos) {
343                *slot = new_u16;
344            }
345            let mut p = pos;
346            while p > 0 {
347                let prev = p.wrapping_sub(1);
348                if indices.get(prev).is_none_or(|&v| v <= new_u16) {
349                    break;
350                }
351                indices.swap(prev, p);
352                p = prev;
353            }
354            // Update bitvector: clear old bit, set new bit
355            if let Some(words) = self.presence.get_mut(hash) {
356                let old_word = old_index.checked_div(64).unwrap_or(0);
357                let old_bit = old_index.checked_rem(64).unwrap_or(0);
358                if let Some(word) = words.get_mut(old_word) {
359                    *word &= !(1_u64 << old_bit);
360                }
361                let new_word = new_index.checked_div(64).unwrap_or(0);
362                let new_bit = new_index.checked_rem(64).unwrap_or(0);
363                if new_word >= words.len() {
364                    words.resize(new_word.saturating_add(1), 0);
365                }
366                if let Some(word) = words.get_mut(new_word) {
367                    *word |= 1_u64 << new_bit;
368                }
369            }
370        }
371    }
372}