1use std::net::{IpAddr, Ipv6Addr};
9
10use serde::{Deserialize, Serialize};
11
12use crate::cloud::{CloudServer, ServerDirect};
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
16#[serde(rename_all = "camelCase")]
17pub enum CandidateKind {
18 Lan,
19 Ipv6,
20 Ipv4,
21 Domain,
23}
24
25#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
27#[serde(rename_all = "camelCase")]
28pub struct DirectCandidate {
29 pub kind: CandidateKind,
30 pub address: String,
31 pub url: String,
33}
34
35pub fn encode_ip_label(address: &str) -> Option<String> {
38 match address.parse::<IpAddr>().ok()? {
39 IpAddr::V4(ip) => Some(ip.to_string().replace('.', "-")),
40 IpAddr::V6(ip) => Some(ipv6_canonical(&ip).replace(':', "-")),
41 }
42}
43
44fn ipv6_canonical(ip: &Ipv6Addr) -> String {
47 let segments = ip.segments();
48 let (mut best_start, mut best_len) = (0, 0);
50 let mut index = 0;
51 while index < 8 {
52 if segments[index] == 0 {
53 let start = index;
54 while index < 8 && segments[index] == 0 {
55 index += 1;
56 }
57 if index - start > best_len {
58 (best_start, best_len) = (start, index - start);
59 }
60 } else {
61 index += 1;
62 }
63 }
64 let hex = |range: &[u16]| {
65 range
66 .iter()
67 .map(|s| format!("{s:x}"))
68 .collect::<Vec<_>>()
69 .join(":")
70 };
71 if best_len < 2 {
72 return hex(&segments);
73 }
74 format!(
75 "{}::{}",
76 hex(&segments[..best_start]),
77 hex(&segments[best_start + best_len..])
78 )
79}
80
81pub fn direct_hostname(direct: &ServerDirect, address: &str) -> Option<String> {
83 Some(format!(
84 "{}.{}.{}",
85 encode_ip_label(address)?,
86 direct.label,
87 direct.zone
88 ))
89}
90
91pub fn direct_url(direct: &ServerDirect, address: &str) -> Option<String> {
93 let port = if direct.port == 443 {
94 String::new()
95 } else {
96 format!(":{}", direct.port)
97 };
98 Some(format!(
99 "https://{}{port}",
100 direct_hostname(direct, address)?
101 ))
102}
103
104pub fn direct_candidates(direct: &ServerDirect) -> Vec<DirectCandidate> {
107 let mut candidates: Vec<DirectCandidate> = Vec::new();
108 let addresses = &direct.addresses;
109 let all = addresses
110 .lan
111 .iter()
112 .map(|a| (CandidateKind::Lan, a))
113 .chain(addresses.ipv6.iter().map(|a| (CandidateKind::Ipv6, a)))
114 .chain(addresses.ipv4.iter().map(|a| (CandidateKind::Ipv4, a)));
115 for (kind, address) in all {
116 if candidates.iter().any(|c| &c.address == address) {
117 continue;
118 }
119 if let Some(url) = direct_url(direct, address) {
120 candidates.push(DirectCandidate {
121 kind,
122 address: address.clone(),
123 url,
124 });
125 }
126 }
127 candidates
128}
129
130pub fn domain_candidate(domain: &str, port: Option<u16>) -> DirectCandidate {
132 let suffix = match port {
133 None | Some(443) => String::new(),
134 Some(port) => format!(":{port}"),
135 };
136 DirectCandidate {
137 kind: CandidateKind::Domain,
138 address: domain.to_owned(),
139 url: format!("https://{domain}{suffix}"),
140 }
141}
142
143pub fn public_direct_url(direct: &ServerDirect) -> Option<String> {
146 let public: Vec<_> = direct_candidates(direct)
147 .into_iter()
148 .filter(|c| c.kind != CandidateKind::Lan)
149 .collect();
150 public
151 .iter()
152 .find(|c| c.kind == CandidateKind::Ipv4)
153 .or(public.first())
154 .map(|c| c.url.clone())
155}
156
157pub fn public_server_url(server: &CloudServer) -> Option<String> {
159 server
160 .direct
161 .as_ref()
162 .and_then(public_direct_url)
163 .or_else(|| {
164 server
165 .domain
166 .as_deref()
167 .map(|d| domain_candidate(d, server.port).url)
168 })
169}
170
171pub fn server_candidates(server: &CloudServer, preferred: Option<&str>) -> Vec<DirectCandidate> {
174 let mut candidates = server
175 .direct
176 .as_ref()
177 .map(direct_candidates)
178 .unwrap_or_default();
179 if let Some(domain) = server.domain.as_deref().filter(|d| !d.is_empty()) {
180 candidates.push(domain_candidate(domain, server.port));
181 }
182 if let Some(preferred) = preferred {
183 candidates.sort_by_key(|c| c.url != preferred);
185 }
186 candidates
187}
188
189#[derive(Debug, Clone, Copy, PartialEq, Eq)]
191pub struct ProbeOptions {
192 pub timeout: std::time::Duration,
194 pub preference_window: std::time::Duration,
197}
198
199impl Default for ProbeOptions {
200 fn default() -> Self {
201 ProbeOptions {
202 timeout: std::time::Duration::from_millis(2_500),
203 preference_window: std::time::Duration::from_millis(150),
204 }
205 }
206}
207
208#[cfg(feature = "http")]
213pub async fn probe_candidates_with<F, Fut>(
214 candidates: &[DirectCandidate],
215 options: ProbeOptions,
216 ping: F,
217) -> Option<DirectCandidate>
218where
219 F: Fn(&DirectCandidate) -> Fut,
220 Fut: std::future::Future<Output = bool>,
221{
222 use futures_timer::Delay;
223 use futures_util::StreamExt;
224 use futures_util::future::{Either, select};
225 use futures_util::stream::FuturesUnordered;
226
227 if candidates.is_empty() {
228 return None;
229 }
230 let mut pending: FuturesUnordered<_> = candidates
231 .iter()
232 .enumerate()
233 .map(|(index, candidate)| {
234 let answer = ping(candidate);
235 async move { (index, answer.await) }
236 })
237 .collect();
238 let mut outcome: Vec<Option<bool>> = vec![None; candidates.len()];
240 let best = |outcome: &[Option<bool>]| {
241 outcome
242 .iter()
243 .position(|o| *o == Some(true))
244 .map(|i| candidates[i].clone())
245 };
246 let mut deadline = Delay::new(options.timeout);
247 let mut grace: Option<Delay> = None;
248
249 loop {
250 let timers = async {
251 match grace.as_mut() {
252 Some(grace) => {
253 select(&mut deadline, grace).await;
254 }
255 None => (&mut deadline).await,
256 }
257 };
258 let answer = match select(pending.next(), Box::pin(timers)).await {
259 Either::Left((answer, _)) => answer,
260 Either::Right(_) => return best(&outcome),
261 };
262 let Some((index, ok)) = answer else {
263 return best(&outcome);
264 };
265 outcome[index] = Some(ok);
266
267 match outcome.iter().position(|o| *o == Some(true)) {
268 None if outcome.iter().all(|o| *o == Some(false)) => return None,
269 None => {}
270 Some(first) if outcome[..first].iter().all(|o| *o == Some(false)) => {
271 return Some(candidates[first].clone());
272 }
273 Some(_) => {
274 grace.get_or_insert_with(|| Delay::new(options.preference_window));
275 }
276 }
277 }
278}
279
280#[cfg(test)]
281mod tests {
282 use super::*;
283 use crate::cloud::ServerDirectAddresses;
284
285 fn direct() -> ServerDirect {
286 ServerDirect {
287 label: "abc".into(),
288 zone: "redseat.direct".into(),
289 port: 8443,
290 addresses: ServerDirectAddresses {
291 lan: vec!["192.168.1.10".into(), "not-an-ip".into()],
292 ipv4: Some("203.0.113.5".into()),
293 ipv6: vec!["2a01:e0a:0:0::1".into(), "192.168.1.10".into()],
294 },
295 updated_at: 0,
296 }
297 }
298
299 #[test]
300 fn encodes_ip_labels() {
301 assert_eq!(encode_ip_label("192.168.1.10").unwrap(), "192-168-1-10");
302 assert_eq!(encode_ip_label("2A01:E0A:0:0::1").unwrap(), "2a01-e0a--1");
303 assert_eq!(encode_ip_label("::ffff:1.2.3.4").unwrap(), "--ffff-102-304");
304 assert_eq!(encode_ip_label("1:0:0:2:0:0:0:3").unwrap(), "1-0-0-2--3");
305 assert_eq!(
306 encode_ip_label("1:2:3:4:5:6:0:8").unwrap(),
307 "1-2-3-4-5-6-0-8"
308 );
309 assert_eq!(encode_ip_label("01.2.3.4"), None);
310 assert_eq!(encode_ip_label("example.org"), None);
311 }
312
313 #[test]
314 fn orders_candidates_lan_ipv6_ipv4() {
315 let urls: Vec<_> = direct_candidates(&direct())
316 .into_iter()
317 .map(|c| (c.kind, c.url))
318 .collect();
319 assert_eq!(
320 urls,
321 vec![
322 (
323 CandidateKind::Lan,
324 "https://192-168-1-10.abc.redseat.direct:8443".to_owned()
325 ),
326 (
327 CandidateKind::Ipv6,
328 "https://2a01-e0a--1.abc.redseat.direct:8443".to_owned()
329 ),
330 (
331 CandidateKind::Ipv4,
332 "https://203-0-113-5.abc.redseat.direct:8443".to_owned()
333 ),
334 ]
335 );
336 assert_eq!(
337 public_direct_url(&direct()).unwrap(),
338 "https://203-0-113-5.abc.redseat.direct:8443"
339 );
340 }
341
342 #[test]
343 fn adds_the_domain_and_puts_the_preferred_url_first() {
344 let server = CloudServer {
345 id: "srv".into(),
346 name: None,
347 url: "media.example.org".into(),
348 port: Some(443),
349 local: None,
350 direct: Some(direct()),
351 domain: Some("media.example.org".into()),
352 member: Some(true),
353 };
354 let candidates = server_candidates(&server, Some("https://media.example.org"));
355 assert_eq!(candidates.len(), 4);
356 assert_eq!(candidates[0].kind, CandidateKind::Domain);
357 assert_eq!(candidates[1].kind, CandidateKind::Lan);
358 assert_eq!(candidates[3].kind, CandidateKind::Ipv4);
359 assert_eq!(
360 domain_candidate("a.org", Some(8443)).url,
361 "https://a.org:8443"
362 );
363 }
364
365 #[cfg(feature = "http")]
366 mod probe {
367 use super::*;
368 use std::time::Duration;
369
370 fn candidates() -> Vec<DirectCandidate> {
371 direct_candidates(&direct())
372 }
373
374 async fn run(plan: Vec<(bool, u64)>, options: ProbeOptions) -> Option<CandidateKind> {
376 let candidates = candidates();
377 probe_candidates_with(&candidates, options, |candidate| {
378 let index = candidates.iter().position(|c| c == candidate).unwrap();
379 let (ok, delay) = plan[index];
380 async move {
381 futures_timer::Delay::new(Duration::from_millis(delay)).await;
382 ok
383 }
384 })
385 .await
386 .map(|c| c.kind)
387 }
388
389 #[tokio::test]
390 async fn the_first_preferred_success_wins_at_once() {
391 let winner = run(
392 vec![(true, 10), (true, 1), (true, 1)],
393 ProbeOptions {
394 preference_window: Duration::from_secs(5),
395 ..Default::default()
396 },
397 )
398 .await;
399 assert_eq!(winner, Some(CandidateKind::Lan));
400 }
401
402 #[tokio::test]
403 async fn a_less_preferred_success_wins_after_the_window() {
404 let winner = run(
405 vec![(true, 2_000), (false, 1), (true, 1)],
406 ProbeOptions {
407 preference_window: Duration::from_millis(50),
408 ..Default::default()
409 },
410 )
411 .await;
412 assert_eq!(winner, Some(CandidateKind::Ipv4));
413 }
414
415 #[tokio::test]
416 async fn a_success_wins_when_all_preferred_failed() {
417 let winner = run(
418 vec![(false, 1), (false, 5), (true, 10)],
419 ProbeOptions {
420 preference_window: Duration::from_secs(5),
421 ..Default::default()
422 },
423 )
424 .await;
425 assert_eq!(winner, Some(CandidateKind::Ipv4));
426 }
427
428 #[tokio::test]
429 async fn none_when_all_fail_or_time_out() {
430 let all_fail = run(vec![(false, 1), (false, 1), (false, 1)], Default::default()).await;
431 assert_eq!(all_fail, None);
432 let too_slow = run(
433 vec![(true, 2_000), (true, 2_000), (true, 2_000)],
434 ProbeOptions {
435 timeout: Duration::from_millis(30),
436 ..Default::default()
437 },
438 )
439 .await;
440 assert_eq!(too_slow, None);
441 }
442 }
443}