Skip to main content

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 core::time::Duration;
6use std::collections::HashMap;
7use std::time::Instant;
8
9use crate::id::PeerId;
10use crate::store::{DEFAULT_IPV6_PREFIX, WaitingLimits, source_key};
11
12/// The least time between two new records from one source, unless
13/// [`record_interval`](WaitingQueueBuilder::record_interval) says otherwise.
14pub const DEFAULT_RECORD_INTERVAL: Duration = Duration::from_secs(1);
15
16/// What a source at [`per_source`](WaitingLimits::per_source) entries does with a newcomer.
17///
18/// In text `refuse` or `replace-oldest`.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, coqui_builder::Leaf)]
20#[map(rename_all = "kebab-case")]
21#[non_exhaustive]
22pub enum WhenFull {
23    /// Refuses the newcomer and leaves those waiting alone. A flood can fill a source, so that
24    /// nobody new is recorded from it until an operator clears it, but cannot remove anyone.
25    #[default]
26    Refuse,
27    /// Replaces the source's oldest entry. Peers sharing a source (everyone behind one reverse
28    /// proxy, when it is what connects) can then flush each other from the queue.
29    ReplaceOldest,
30}
31
32/// What [`WaitingQueue::admit`] decided for one peer.
33#[derive(Debug, Clone, PartialEq, Eq)]
34#[non_exhaustive]
35pub struct Admission {
36    /// Whether to record the peer as waiting now.
37    pub record: bool,
38    /// Entries of the same source to remove first, oldest first; always empty unless the queue
39    /// is [`WhenFull::ReplaceOldest`].
40    pub evict: Vec<PeerId>,
41}
42
43/// Decides which unaccepted peers are recorded as waiting, without storing anything: the
44/// policy of [`TrustStore::record_waiting`](crate::TrustStore::record_waiting), for a host
45/// that keeps its waiting entries elsewhere.
46///
47/// A source is an IPv4 address (an IPv4-mapped IPv6 address counts as its IPv4 address), an
48/// IPv6 prefix of [`ipv6_prefix`](WaitingQueueBuilder::ipv6_prefix) bits (/64 unless set,
49/// since one holder controls every address of a /64), or no address at all, which is one
50/// source. The queue remembers what it admitted, per source, oldest first; it forgets nothing
51/// on its own, beyond the `per_source` entries it keeps for each source.
52#[derive(Debug, Clone, coqui_builder::Configured)]
53pub struct WaitingQueue {
54    #[configured]
55    settings: WaitingSettings,
56    sources: HashMap<Option<IpAddr>, VecDeque<(PeerId, Instant)>>,
57}
58
59/// What a [`WaitingQueue`] is built from, in the form a file, a form or a peer fills.
60///
61/// Every key is optional (an absent one is its default) and an unknown key is refused. The type
62/// is `Describe`, so a `Partial<WaitingSettings>` is filled from text and built, and it is
63/// `#[non_exhaustive]`: start from [`Default`] and assign the fields.
64#[derive(Debug, Clone, Copy, PartialEq, Eq, coqui_builder::Describe)]
65#[builder(setters_on = WaitingQueueBuilder)]
66#[map(deny_unknown_fields)]
67#[non_exhaustive]
68pub struct WaitingSettings {
69    /// The bounds on entries. Default [`WaitingLimits::default`].
70    #[map(default = WaitingSettings::default().limits)]
71    pub limits: WaitingLimits,
72    /// The IPv6 prefix length sources are grouped by: 64, since one holder controls every address
73    /// of a /64. 128 counts each address alone, which lets the holder of a subnet fill the queue;
74    /// values above 128 are 128. IPv4 sources, IPv4-mapped IPv6 ones included, count per address.
75    #[map(default = WaitingSettings::default().ipv6_prefix)]
76    pub ipv6_prefix: u8,
77    /// What a source at its limit does with a newcomer. Default [`WhenFull::Refuse`], so that
78    /// strangers sharing a source cannot flush those already waiting.
79    #[map(default = WaitingSettings::default().when_full)]
80    pub when_full: WhenFull,
81    /// The least time between two new records from one source, each record being a synced write
82    /// a stranger can cause. Default [`DEFAULT_RECORD_INTERVAL`]; zero is no limit.
83    #[map(default = WaitingSettings::default().record_interval)]
84    pub record_interval: Duration,
85}
86
87impl Default for WaitingSettings {
88    fn default() -> Self {
89        Self {
90            limits: WaitingLimits::default(),
91            ipv6_prefix: DEFAULT_IPV6_PREFIX,
92            when_full: WhenFull::default(),
93            record_interval: DEFAULT_RECORD_INTERVAL,
94        }
95    }
96}
97
98impl WaitingSettings {
99    /// Every setting that differs from its default, named by key path (`limits.per_source`).
100    pub fn non_defaults(&self) -> Vec<coqui_builder::NonDefault> {
101        coqui_builder::non_defaults(self)
102    }
103}
104
105/// What a [`WaitingQueueBuilder`] collects: the settings.
106///
107/// Build the queue with [`WaitingQueue::builder`].
108#[derive(coqui_builder::Builder, Debug)]
109#[builder(build = WaitingQueue)]
110pub struct WaitingQueueParts {
111    settings: WaitingSettings,
112}
113
114impl From<WaitingQueueParts> for WaitingQueue {
115    fn from(parts: WaitingQueueParts) -> Self {
116        Self::from_settings(parts.settings)
117    }
118}
119
120impl WaitingQueue {
121    /// An empty queue under `settings`; an IPv6 prefix above 128 is 128.
122    pub(crate) fn from_settings(settings: WaitingSettings) -> Self {
123        Self {
124            settings: WaitingSettings {
125                ipv6_prefix: settings.ipv6_prefix.min(128),
126                ..settings
127            },
128            sources: HashMap::new(),
129        }
130    }
131
132    /// An empty queue under `limits` with every other setting at its default:
133    /// `WaitingQueue::builder().limits(limits).build()`.
134    pub fn new(limits: WaitingLimits) -> Self {
135        Self::from_settings(WaitingSettings {
136            limits,
137            ..WaitingSettings::default()
138        })
139    }
140
141    /// The settings it was built from.
142    pub fn settings(&self) -> WaitingSettings {
143        self.settings
144    }
145
146    /// What it does with a newcomer to a full source.
147    pub fn when_full(&self) -> WhenFull {
148        self.settings.when_full
149    }
150
151    /// The least time between two new records from one source.
152    pub fn record_interval(&self) -> Duration {
153        self.settings.record_interval
154    }
155
156    /// The limits it applies.
157    pub fn limits(&self) -> WaitingLimits {
158        self.settings.limits
159    }
160
161    /// The IPv6 prefix length sources are grouped by.
162    pub fn ipv6_prefix(&self) -> u8 {
163        self.settings.ipv6_prefix
164    }
165
166    /// Decides whether `id`, from `source`, is recorded now.
167    ///
168    /// `stored` is how many waiting entries the host holds; at
169    /// [`total`](WaitingLimits::total) or above, nothing is recorded (the newcomer waits, no
170    /// entry is dropped for it). The same peer from the same source is recorded again only
171    /// after [`rerecord`](WaitingLimits::rerecord). A source records a new peer at most once per
172    /// [`record_interval`](WaitingQueue::record_interval). A source at
173    /// [`per_source`](WaitingLimits::per_source) does what [`WhenFull`] says: by default the
174    /// newcomer is not recorded; with [`WhenFull::ReplaceOldest`] its oldest entries are listed in
175    /// [`Admission::evict`] for the host to remove. The host checks itself whether `id` is
176    /// already stored, and does not call this then.
177    pub fn admit(
178        &mut self,
179        id: PeerId,
180        source: Option<SocketAddr>,
181        stored: usize,
182        now: Instant,
183    ) -> Admission {
184        let refused = Admission {
185            record: false,
186            evict: Vec::new(),
187        };
188        if stored >= self.settings.limits.total {
189            return refused;
190        }
191        let bucket = source.map(|source| source_key(source.ip(), self.settings.ipv6_prefix));
192        let held = self.sources.entry(bucket).or_default();
193        if held.iter().any(|(had, at)| {
194            *had == id && now.saturating_duration_since(*at) < self.settings.limits.rerecord
195        }) {
196            return refused;
197        }
198        let interval = self.settings.record_interval;
199        if held
200            .iter()
201            .any(|(_, at)| now.saturating_duration_since(*at) < interval)
202        {
203            return refused;
204        }
205        held.retain(|(had, _)| *had != id);
206        if self.settings.when_full == WhenFull::Refuse
207            && held.len() >= self.settings.limits.per_source
208        {
209            return refused;
210        }
211        held.push_back((id, now));
212        let mut evict = Vec::new();
213        while held.len() > self.settings.limits.per_source {
214            if let Some((old, _)) = held.pop_front() {
215                evict.push(old);
216            }
217        }
218        Admission {
219            record: true,
220            evict,
221        }
222    }
223
224    /// Remembers that `id` from `source` was recorded at `at`, for a host that seeds the queue
225    /// from entries it stored earlier. Entries past `per_source` for that source are
226    /// forgotten, oldest first, and returned.
227    pub fn remember(&mut self, id: PeerId, source: Option<SocketAddr>, at: Instant) -> Vec<PeerId> {
228        let bucket = source.map(|source| source_key(source.ip(), self.settings.ipv6_prefix));
229        let held = self.sources.entry(bucket).or_default();
230        held.retain(|(had, _)| *had != id);
231        let position = held
232            .iter()
233            .position(|(_, when)| *when > at)
234            .unwrap_or(held.len());
235        held.insert(position, (id, at));
236        let mut forgotten = Vec::new();
237        while held.len() > self.settings.limits.per_source {
238            if let Some((old, _)) = held.pop_front() {
239                forgotten.push(old);
240            }
241        }
242        forgotten
243    }
244
245    /// Forgets every entry the host no longer stores (`stored` is false for it) once its
246    /// [`rerecord`](WaitingLimits::rerecord) time has passed; within it the entry still keeps
247    /// the same peer from being recorded again from its source.
248    ///
249    /// For a host whose entries another process may accept or remove: without it, the queue
250    /// remembers them, and its memory grows with every source it has seen.
251    pub fn prune(&mut self, now: Instant, stored: impl Fn(&PeerId) -> bool) {
252        let rerecord = self.settings.limits.rerecord;
253        for held in self.sources.values_mut() {
254            held.retain(|(id, at)| stored(id) || now.saturating_duration_since(*at) < rerecord);
255        }
256        self.sources.retain(|_, held| !held.is_empty());
257    }
258
259    /// The number of entries remembered, across every source.
260    pub fn len(&self) -> usize {
261        self.sources.values().map(VecDeque::len).sum()
262    }
263
264    /// Whether nothing is remembered.
265    pub fn is_empty(&self) -> bool {
266        self.sources.is_empty()
267    }
268
269    /// Forgets `id` from every source, as when the host accepts or removes it.
270    pub fn forget(&mut self, id: &PeerId) {
271        for held in self.sources.values_mut() {
272            held.retain(|(had, _)| had != id);
273        }
274        self.sources.retain(|_, held| !held.is_empty());
275    }
276}