Skip to main content

qualia_core_db/net/peer/connectivity/
candidates.rs

1//! Bounded candidate and pair tables. No unbounded Cartesian product.
2
3use super::policy::PathPolicy;
4
5pub const MAX_LOCAL: usize = 32;
6pub const MAX_REMOTE: usize = 32;
7pub const MAX_PAIRS: usize = 64;
8pub const MAX_ATTEMPTS: usize = 8;
9pub const MAX_ACTIVE_PATHS: usize = 3;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum CandidateKind {
13    Host = 126,
14    PeerReflexive = 110,
15    ServerReflexive = 100,
16    Relayed = 0,
17}
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum AddrFamily {
21    V6,
22    V4,
23}
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub struct Candidate {
27    pub kind: CandidateKind,
28    pub family: AddrFamily,
29    pub foundation: u32,
30    pub component: u8,
31    pub priority: u32,
32}
33
34impl Candidate {
35    /// Host candidate for `family`/`foundation`.
36    pub fn host(family: AddrFamily, foundation: u32) -> Self {
37        Self::new(CandidateKind::Host, family, foundation)
38    }
39
40    /// Relayed candidate.
41    pub fn relayed(family: AddrFamily, foundation: u32) -> Self {
42        Self::new(CandidateKind::Relayed, family, foundation)
43    }
44
45    /// Server-reflexive candidate.
46    pub fn srflx(family: AddrFamily, foundation: u32) -> Self {
47        Self::new(CandidateKind::ServerReflexive, family, foundation)
48    }
49
50    fn new(kind: CandidateKind, family: AddrFamily, foundation: u32) -> Self {
51        let type_pref = kind as u32;
52        let local_pref = match family {
53            AddrFamily::V6 => 65_535,
54            AddrFamily::V4 => 65_534,
55        };
56        let priority = (type_pref << 24) + (local_pref << 8) + (256 - 1);
57        Self {
58            kind,
59            family,
60            foundation,
61            component: 1,
62            priority,
63        }
64    }
65}
66
67/// RFC 8445 pair priority. `g` is the controlling agent's candidate priority.
68pub fn pair_priority(g: u32, d: u32) -> u64 {
69    let min = u64::from(g.min(d));
70    let max = u64::from(g.max(d));
71    (1u64 << 32) * min + 2 * max + u64::from(g > d)
72}
73
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub enum PairState {
76    Waiting,
77    InProgress,
78    Succeeded,
79    Failed,
80    Frozen,
81}
82
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub struct CandidatePair {
85    pub local_idx: u8,
86    pub remote_idx: u8,
87    pub priority: u64,
88    pub state: PairState,
89    /// Set only after a real connectivity check (STUN Binding or TURN Allocate).
90    pub checked: bool,
91}
92
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub struct CandidateTables {
95    pub local: [Option<Candidate>; MAX_LOCAL],
96    pub local_len: usize,
97    pub remote: [Option<Candidate>; MAX_REMOTE],
98    pub remote_len: usize,
99    pub pairs: [Option<CandidatePair>; MAX_PAIRS],
100    pub pair_len: usize,
101}
102
103impl CandidateTables {
104    /// Empty value.
105    pub const fn empty() -> Self {
106        Self {
107            local: [None; MAX_LOCAL],
108            local_len: 0,
109            remote: [None; MAX_REMOTE],
110            remote_len: 0,
111            pairs: [None; MAX_PAIRS],
112            pair_len: 0,
113        }
114    }
115
116    /// Pushes a local candidate; `Err(())` at capacity.
117    pub fn push_local(&mut self, c: Candidate) -> Result<usize, ()> {
118        if self.local_len >= MAX_LOCAL {
119            return Err(());
120        }
121        let i = self.local_len;
122        self.local[i] = Some(c);
123        self.local_len += 1;
124        Ok(i)
125    }
126
127    /// Pushes a remote candidate.
128    pub fn push_remote(&mut self, c: Candidate) -> Result<usize, ()> {
129        if self.remote_len >= MAX_REMOTE {
130            return Err(());
131        }
132        let i = self.remote_len;
133        self.remote[i] = Some(c);
134        self.remote_len += 1;
135        Ok(i)
136    }
137
138    /// Diversity-aware pairing. Stops at [`MAX_PAIRS`].
139    pub fn form_pairs(&mut self, controlling: bool) -> usize {
140        self.pair_len = 0;
141        self.pairs = [None; MAX_PAIRS];
142        let mut i = 0usize;
143        while i < self.local_len && self.pair_len < MAX_PAIRS {
144            let Some(l) = self.local[i] else {
145                i += 1;
146                continue;
147            };
148            let mut j = 0usize;
149            while j < self.remote_len && self.pair_len < MAX_PAIRS {
150                let Some(r) = self.remote[j] else {
151                    j += 1;
152                    continue;
153                };
154                if l.family != r.family || l.component != r.component {
155                    j += 1;
156                    continue;
157                }
158                let (g, d) = if controlling {
159                    (l.priority, r.priority)
160                } else {
161                    (r.priority, l.priority)
162                };
163                self.pairs[self.pair_len] = Some(CandidatePair {
164                    local_idx: i as u8,
165                    remote_idx: j as u8,
166                    priority: pair_priority(g, d),
167                    state: PairState::Waiting,
168                    checked: false,
169                });
170                self.pair_len += 1;
171                j += 1;
172            }
173            i += 1;
174        }
175        self.sort_pairs();
176        self.pair_len
177    }
178
179    fn sort_pairs(&mut self) {
180        let n = self.pair_len;
181        let mut a = 0usize;
182        while a + 1 < n {
183            let mut b = 0usize;
184            while b + 1 < n - a {
185                let pa = self.pairs[b].unwrap().priority;
186                let pb = self.pairs[b + 1].unwrap().priority;
187                if pa < pb {
188                    self.pairs.swap(b, b + 1);
189                }
190                b += 1;
191            }
192            a += 1;
193        }
194    }
195}
196
197/// Gather the candidates this policy permits. No sockets.
198pub fn gather_permitted(policy: PathPolicy, has_v6: bool, has_v4: bool) -> CandidateTables {
199    let mut t = CandidateTables::empty();
200    if policy.allows_relay() {
201        let _ = t.push_local(Candidate::relayed(AddrFamily::V6, 1));
202        if has_v4 {
203            let _ = t.push_local(Candidate::relayed(AddrFamily::V4, 2));
204        }
205    }
206    if policy.allows_direct_probes() {
207        if has_v6 {
208            let _ = t.push_local(Candidate::host(AddrFamily::V6, 3));
209        }
210        if has_v4 {
211            let _ = t.push_local(Candidate::host(AddrFamily::V4, 4));
212        }
213        if policy.allows_public_stun() {
214            if has_v6 {
215                let _ = t.push_local(Candidate::srflx(AddrFamily::V6, 5));
216            }
217            if has_v4 {
218                let _ = t.push_local(Candidate::srflx(AddrFamily::V4, 6));
219            }
220        }
221    }
222    t
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228
229    #[test]
230    fn relay_only_has_no_host_or_srflx() {
231        let t = gather_permitted(PathPolicy::RELAY_ONLY, true, true);
232        let mut i = 0;
233        while i < t.local_len {
234            let k = t.local[i].unwrap().kind;
235            assert_eq!(k, CandidateKind::Relayed);
236            i += 1;
237        }
238    }
239
240    #[test]
241    fn pair_cap_is_64() {
242        assert_eq!(MAX_PAIRS, 64);
243        assert_eq!(MAX_ATTEMPTS, 8);
244        assert_eq!(MAX_ACTIVE_PATHS, 3);
245    }
246}