coqui_peer/waiting.rs
1//! The bounds on a waiting queue, kept apart from where its entries are stored.
2
3use alloc::collections::VecDeque;
4use core::net::{IpAddr, SocketAddr};
5use std::collections::HashMap;
6use std::time::Instant;
7
8use crate::id::PeerId;
9use crate::store::{DEFAULT_IPV6_PREFIX, WaitingLimits, source_key};
10
11/// What [`WaitingQueue::admit`] decided for one peer.
12#[derive(Debug, Clone, PartialEq, Eq)]
13#[non_exhaustive]
14pub struct Admission {
15 /// Whether to record the peer as waiting now.
16 pub record: bool,
17 /// Entries of the same source to remove first, oldest first: the source holds
18 /// [`per_source`](WaitingLimits::per_source) entries at most.
19 pub evict: Vec<PeerId>,
20}
21
22/// Decides which unaccepted peers are recorded as waiting, without storing anything: the
23/// policy of [`TrustStore::record_waiting`](crate::TrustStore::record_waiting), for a host
24/// that keeps its waiting entries elsewhere.
25///
26/// A source is an IPv4 address (an IPv4-mapped IPv6 address counts as its IPv4 address), an
27/// IPv6 prefix of [`with_ipv6_prefix`](WaitingQueue::with_ipv6_prefix) bits (/64 unless set,
28/// since one holder controls every address of a /64), or no address at all, which is one
29/// source. The queue remembers what it admitted, per source, oldest first; it forgets nothing
30/// on its own, beyond the `per_source` entries it keeps for each source.
31#[derive(Debug, Clone)]
32pub struct WaitingQueue {
33 limits: WaitingLimits,
34 ipv6_prefix: u8,
35 sources: HashMap<Option<IpAddr>, VecDeque<(PeerId, Instant)>>,
36}
37
38impl WaitingQueue {
39 /// An empty queue under `limits`, grouping IPv6 sources by /64.
40 pub fn new(limits: WaitingLimits) -> Self {
41 Self {
42 limits,
43 ipv6_prefix: DEFAULT_IPV6_PREFIX,
44 sources: HashMap::new(),
45 }
46 }
47
48 /// This queue grouping IPv6 sources by their first `bits` bits (values above 128 are 128).
49 #[must_use]
50 pub fn with_ipv6_prefix(mut self, bits: u8) -> Self {
51 self.ipv6_prefix = bits.min(128);
52 self
53 }
54
55 /// The limits it applies.
56 pub fn limits(&self) -> WaitingLimits {
57 self.limits
58 }
59
60 /// The IPv6 prefix length sources are grouped by.
61 pub fn ipv6_prefix(&self) -> u8 {
62 self.ipv6_prefix
63 }
64
65 /// Decides whether `id`, from `source`, is recorded now.
66 ///
67 /// `stored` is how many waiting entries the host holds; at
68 /// [`total`](WaitingLimits::total) or above, nothing is recorded (the newcomer waits, no
69 /// entry is dropped for it). The same peer from the same source is recorded again only
70 /// after [`rerecord`](WaitingLimits::rerecord). A source past
71 /// [`per_source`](WaitingLimits::per_source) gives up its oldest entries, listed in
72 /// [`Admission::evict`] for the host to remove. The host checks itself whether `id` is
73 /// already stored, and does not call this then.
74 pub fn admit(
75 &mut self,
76 id: PeerId,
77 source: Option<SocketAddr>,
78 stored: usize,
79 now: Instant,
80 ) -> Admission {
81 let refused = Admission {
82 record: false,
83 evict: Vec::new(),
84 };
85 if stored >= self.limits.total {
86 return refused;
87 }
88 let bucket = source.map(|source| source_key(source.ip(), self.ipv6_prefix));
89 let held = self.sources.entry(bucket).or_default();
90 if held.iter().any(|(had, at)| {
91 *had == id && now.saturating_duration_since(*at) < self.limits.rerecord
92 }) {
93 return refused;
94 }
95 held.retain(|(had, _)| *had != id);
96 held.push_back((id, now));
97 let mut evict = Vec::new();
98 while held.len() > self.limits.per_source {
99 if let Some((old, _)) = held.pop_front() {
100 evict.push(old);
101 }
102 }
103 Admission {
104 record: true,
105 evict,
106 }
107 }
108
109 /// Remembers that `id` from `source` was recorded at `at`, for a host that seeds the queue
110 /// from entries it stored earlier. Entries past `per_source` for that source are
111 /// forgotten, oldest first, and returned.
112 pub fn remember(&mut self, id: PeerId, source: Option<SocketAddr>, at: Instant) -> Vec<PeerId> {
113 let bucket = source.map(|source| source_key(source.ip(), self.ipv6_prefix));
114 let held = self.sources.entry(bucket).or_default();
115 held.retain(|(had, _)| *had != id);
116 let position = held
117 .iter()
118 .position(|(_, when)| *when > at)
119 .unwrap_or(held.len());
120 held.insert(position, (id, at));
121 let mut forgotten = Vec::new();
122 while held.len() > self.limits.per_source {
123 if let Some((old, _)) = held.pop_front() {
124 forgotten.push(old);
125 }
126 }
127 forgotten
128 }
129
130 /// Forgets every entry the host no longer stores (`stored` is false for it) once its
131 /// [`rerecord`](WaitingLimits::rerecord) time has passed; within it the entry still keeps
132 /// the same peer from being recorded again from its source.
133 ///
134 /// For a host whose entries another process may accept or remove: without it, the queue
135 /// remembers them, and its memory grows with every source it has seen.
136 pub fn prune(&mut self, now: Instant, stored: impl Fn(&PeerId) -> bool) {
137 let rerecord = self.limits.rerecord;
138 for held in self.sources.values_mut() {
139 held.retain(|(id, at)| stored(id) || now.saturating_duration_since(*at) < rerecord);
140 }
141 self.sources.retain(|_, held| !held.is_empty());
142 }
143
144 /// The number of entries remembered, across every source.
145 pub fn len(&self) -> usize {
146 self.sources.values().map(VecDeque::len).sum()
147 }
148
149 /// Whether nothing is remembered.
150 pub fn is_empty(&self) -> bool {
151 self.sources.is_empty()
152 }
153
154 /// Forgets `id` from every source, as when the host accepts or removes it.
155 pub fn forget(&mut self, id: &PeerId) {
156 for held in self.sources.values_mut() {
157 held.retain(|(had, _)| had != id);
158 }
159 self.sources.retain(|_, held| !held.is_empty());
160 }
161}