1use std::{collections::BTreeSet, fmt, sync::Arc};
8
9use iroh_relay::{RelayConfig, RelayMap};
10use n0_future::time::Duration;
11
12use crate::net_report::Report;
13
14const DEFAULT_INITIAL_RETRANSMIT: Duration = Duration::from_millis(100);
16
17const HTTPS_OFFSET: Duration = Duration::from_millis(200);
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, derive_more::Display)]
22#[repr(u8)]
23#[cfg_attr(not(feature = "unstable-net-report"), allow(unreachable_pub))]
24#[non_exhaustive]
25pub enum Probe {
26 Https,
28 #[cfg(not(wasm_browser))]
30 QadIpv4,
31 #[cfg(not(wasm_browser))]
33 QadIpv6,
34}
35
36#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
49pub(super) struct ProbeSet {
50 proto: Probe,
52 probes: Vec<(Duration, Arc<RelayConfig>)>,
54}
55
56impl ProbeSet {
57 fn new(proto: Probe) -> Self {
58 Self {
59 probes: Vec::new(),
60 proto,
61 }
62 }
63
64 pub(super) fn proto(&self) -> Probe {
65 self.proto
66 }
67
68 fn push(&mut self, delay: Duration, endpoint: Arc<RelayConfig>) {
69 self.probes.push((delay, endpoint));
70 }
71
72 fn is_empty(&self) -> bool {
73 self.probes.is_empty()
74 }
75
76 pub(super) fn params(&self) -> impl Iterator<Item = &(Duration, Arc<RelayConfig>)> {
77 self.probes.iter()
78 }
79}
80
81#[derive(Debug, Default, PartialEq, Eq)]
92pub(super) struct ProbePlan {
93 set: BTreeSet<ProbeSet>,
94}
95
96impl ProbePlan {
97 pub(super) fn initial(relay_map: &RelayMap, protocols: &BTreeSet<Probe>) -> Self {
99 let mut plan = Self::default();
100
101 for relay in relay_map.relays::<Vec<_>>() {
102 let mut https_probes = ProbeSet::new(Probe::Https);
103
104 for attempt in 0u32..3 {
105 let delay = HTTPS_OFFSET + DEFAULT_INITIAL_RETRANSMIT * attempt;
106 https_probes.push(delay, relay.clone());
107 }
108
109 plan.add_if_enabled(protocols, https_probes);
110 }
111 plan
112 }
113
114 pub(super) fn with_last_report(
118 relay_map: &RelayMap,
119 last_report: &Report,
120 protocols: &BTreeSet<Probe>,
121 ) -> Self {
122 if last_report.relay_latency.is_empty() {
123 return Self::initial(relay_map, protocols);
124 }
125
126 Self::default()
128 }
129
130 pub(super) fn iter(&self) -> impl Iterator<Item = &ProbeSet> {
132 self.set.iter()
133 }
134
135 fn add_if_enabled(&mut self, protocols: &BTreeSet<Probe>, set: ProbeSet) {
138 if !set.is_empty() && protocols.contains(&set.proto) {
139 self.set.insert(set);
140 }
141 }
142}
143
144impl fmt::Display for ProbePlan {
145 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146 writeln!(f, "ProbePlan {{")?;
147 for probe_set in self.set.iter() {
148 writeln!(f, r#" ProbeSet("{}") {{"#, probe_set.proto)?;
149 for (delay, endpoint) in probe_set.probes.iter() {
150 writeln!(f, " {delay:?} to {endpoint},")?;
151 }
152 writeln!(f, " }}")?;
153 }
154 writeln!(f, "}}")
155 }
156}
157
158impl FromIterator<ProbeSet> for ProbePlan {
159 fn from_iter<T: IntoIterator<Item = ProbeSet>>(iter: T) -> Self {
160 Self {
161 set: iter.into_iter().collect(),
162 }
163 }
164}
165
166#[cfg(test)]
167mod tests {
168 use pretty_assertions::assert_eq;
169
170 use super::*;
171 use crate::net_report::test_utils;
172
173 macro_rules! probeset {
179 (proto: Probe::$kind:ident, relay: $endpoint:expr, delays: $delays:expr,) => {
180 ProbeSet {
181 proto: Probe::$kind,
182 probes: $delays.iter().map(|delay| (*delay, $endpoint)).collect(),
183 }
184 };
185 }
186
187 fn default_protocols() -> BTreeSet<Probe> {
188 BTreeSet::from([Probe::QadIpv4, Probe::QadIpv6, Probe::Https])
189 }
190
191 #[tokio::test]
192 async fn test_initial_probeplan() {
193 let (_servers, relay_map) = test_utils::relay_map(2).await;
194 let relay_1 = &relay_map.relays::<Vec<_>>()[0];
195 let relay_2 = &relay_map.relays::<Vec<_>>()[1];
196 let plan = ProbePlan::initial(&relay_map, &default_protocols());
197
198 let expected_plan: ProbePlan = [
199 probeset! {
200 proto: Probe::Https,
201 relay: relay_1.clone(),
202 delays: [
203 Duration::from_millis(200),
204 Duration::from_millis(300),
205 Duration::from_millis(400)
206 ],
207 },
208 probeset! {
209 proto: Probe::Https,
210 relay: relay_2.clone(),
211 delays: [
212 Duration::from_millis(200),
213 Duration::from_millis(300),
214 Duration::from_millis(400)
215 ],
216 },
217 ]
218 .into_iter()
219 .collect();
220
221 println!("expected:");
222 println!("{expected_plan}");
223 println!("actual:");
224 println!("{plan}");
225 assert_eq!(plan.to_string(), expected_plan.to_string());
227 assert_eq!(plan, expected_plan);
229 }
230
231 #[tokio::test]
232 async fn test_initial_probeplan_some_protocols() {
233 let (_servers, relay_map) = test_utils::relay_map(2).await;
234 let relay_1 = &relay_map.relays::<Vec<_>>()[0];
235 let relay_2 = &relay_map.relays::<Vec<_>>()[1];
236 let plan = ProbePlan::initial(&relay_map, &BTreeSet::from([Probe::Https]));
237
238 let expected_plan: ProbePlan = [
239 probeset! {
240 proto: Probe::Https,
241 relay: relay_1.clone(),
242 delays: [Duration::from_millis(200),
243 Duration::from_millis(300),
244 Duration::from_millis(400)],
245 },
246 probeset! {
247 proto: Probe::Https,
248 relay: relay_2.clone(),
249 delays: [Duration::from_millis(200),
250 Duration::from_millis(300),
251 Duration::from_millis(400)],
252 },
253 ]
254 .into_iter()
255 .collect();
256
257 println!("expected:");
258 println!("{expected_plan}");
259 println!("actual:");
260 println!("{plan}");
261 assert_eq!(plan.to_string(), expected_plan.to_string());
263 assert_eq!(plan, expected_plan);
265 }
266}