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
189pub fn candidate_kind(server: &CloudServer, base_url: &str) -> Option<CandidateKind> {
193 let normal = |url: &str| {
195 let url = url.trim_end_matches('/');
196 url.strip_suffix(":443").unwrap_or(url).to_owned()
197 };
198 let base = normal(base_url);
199 if let Some(candidate) = server_candidates(server, None)
200 .into_iter()
201 .find(|c| normal(&c.url) == base)
202 {
203 return Some(candidate.kind);
204 }
205 let own = (!server.url.is_empty()).then(|| domain_candidate(&server.url, server.port));
206 own.filter(|own| normal(&own.url) == base)
207 .map(|_| CandidateKind::Domain)
208}
209
210#[derive(Debug, Clone, Copy, PartialEq, Eq)]
212pub struct ProbeOptions {
213 pub timeout: std::time::Duration,
215 pub preference_window: std::time::Duration,
218}
219
220impl Default for ProbeOptions {
221 fn default() -> Self {
222 ProbeOptions {
223 timeout: std::time::Duration::from_millis(2_500),
224 preference_window: std::time::Duration::from_millis(150),
225 }
226 }
227}
228
229#[cfg(feature = "http")]
234pub async fn probe_candidates_with<F, Fut>(
235 candidates: &[DirectCandidate],
236 options: ProbeOptions,
237 ping: F,
238) -> Option<DirectCandidate>
239where
240 F: Fn(&DirectCandidate) -> Fut,
241 Fut: std::future::Future<Output = bool>,
242{
243 use futures_timer::Delay;
244 use futures_util::StreamExt;
245 use futures_util::future::{Either, select};
246 use futures_util::stream::FuturesUnordered;
247
248 if candidates.is_empty() {
249 return None;
250 }
251 let mut pending: FuturesUnordered<_> = candidates
252 .iter()
253 .enumerate()
254 .map(|(index, candidate)| {
255 let answer = ping(candidate);
256 async move { (index, answer.await) }
257 })
258 .collect();
259 let mut outcome: Vec<Option<bool>> = vec![None; candidates.len()];
261 let best = |outcome: &[Option<bool>]| {
262 outcome
263 .iter()
264 .position(|o| *o == Some(true))
265 .map(|i| candidates[i].clone())
266 };
267 let mut deadline = Delay::new(options.timeout);
268 let mut grace: Option<Delay> = None;
269
270 loop {
271 let timers = async {
272 match grace.as_mut() {
273 Some(grace) => {
274 select(&mut deadline, grace).await;
275 }
276 None => (&mut deadline).await,
277 }
278 };
279 let answer = match select(pending.next(), Box::pin(timers)).await {
280 Either::Left((answer, _)) => answer,
281 Either::Right(_) => return best(&outcome),
282 };
283 let Some((index, ok)) = answer else {
284 return best(&outcome);
285 };
286 outcome[index] = Some(ok);
287
288 match outcome.iter().position(|o| *o == Some(true)) {
289 None if outcome.iter().all(|o| *o == Some(false)) => return None,
290 None => {}
291 Some(first) if outcome[..first].iter().all(|o| *o == Some(false)) => {
292 return Some(candidates[first].clone());
293 }
294 Some(_) => {
295 grace.get_or_insert_with(|| Delay::new(options.preference_window));
296 }
297 }
298 }
299}
300
301#[cfg(test)]
302mod tests {
303 use super::*;
304 use crate::cloud::ServerDirectAddresses;
305
306 fn direct() -> ServerDirect {
307 ServerDirect {
308 label: "abc".into(),
309 zone: "redseat.direct".into(),
310 port: 8443,
311 addresses: ServerDirectAddresses {
312 lan: vec!["192.168.1.10".into(), "not-an-ip".into()],
313 ipv4: Some("203.0.113.5".into()),
314 ipv6: vec!["2a01:e0a:0:0::1".into(), "192.168.1.10".into()],
315 },
316 updated_at: 0,
317 }
318 }
319
320 #[test]
321 fn encodes_ip_labels() {
322 assert_eq!(encode_ip_label("192.168.1.10").unwrap(), "192-168-1-10");
323 assert_eq!(encode_ip_label("2A01:E0A:0:0::1").unwrap(), "2a01-e0a--1");
324 assert_eq!(encode_ip_label("::ffff:1.2.3.4").unwrap(), "--ffff-102-304");
325 assert_eq!(encode_ip_label("1:0:0:2:0:0:0:3").unwrap(), "1-0-0-2--3");
326 assert_eq!(
327 encode_ip_label("1:2:3:4:5:6:0:8").unwrap(),
328 "1-2-3-4-5-6-0-8"
329 );
330 assert_eq!(encode_ip_label("01.2.3.4"), None);
331 assert_eq!(encode_ip_label("example.org"), None);
332 }
333
334 #[test]
335 fn orders_candidates_lan_ipv6_ipv4() {
336 let urls: Vec<_> = direct_candidates(&direct())
337 .into_iter()
338 .map(|c| (c.kind, c.url))
339 .collect();
340 assert_eq!(
341 urls,
342 vec![
343 (
344 CandidateKind::Lan,
345 "https://192-168-1-10.abc.redseat.direct:8443".to_owned()
346 ),
347 (
348 CandidateKind::Ipv6,
349 "https://2a01-e0a--1.abc.redseat.direct:8443".to_owned()
350 ),
351 (
352 CandidateKind::Ipv4,
353 "https://203-0-113-5.abc.redseat.direct:8443".to_owned()
354 ),
355 ]
356 );
357 assert_eq!(
358 public_direct_url(&direct()).unwrap(),
359 "https://203-0-113-5.abc.redseat.direct:8443"
360 );
361 }
362
363 #[test]
364 fn tells_which_address_a_base_url_is() {
365 let server = CloudServer {
366 id: "srv".into(),
367 name: None,
368 url: "media.example.org".into(),
369 port: Some(8443),
370 local: None,
371 direct: Some(direct()),
372 domain: None,
373 member: Some(true),
374 uid: None,
375 };
376 let kind = |url| candidate_kind(&server, url);
377 assert_eq!(
378 kind("https://192-168-1-10.abc.redseat.direct:8443/"),
379 Some(CandidateKind::Lan)
380 );
381 assert_eq!(
382 kind("https://203-0-113-5.abc.redseat.direct:8443"),
383 Some(CandidateKind::Ipv4)
384 );
385 assert_eq!(
387 kind("https://media.example.org:8443"),
388 Some(CandidateKind::Domain)
389 );
390 assert_eq!(kind("https://elsewhere.example.org"), None);
391
392 let on_443 = CloudServer {
393 port: None,
394 direct: None,
395 domain: Some("media.example.org".into()),
396 ..server.clone()
397 };
398 assert_eq!(
399 candidate_kind(&on_443, "https://media.example.org:443"),
400 Some(CandidateKind::Domain)
401 );
402 }
403
404 #[test]
405 fn adds_the_domain_and_puts_the_preferred_url_first() {
406 let server = CloudServer {
407 id: "srv".into(),
408 name: None,
409 url: "media.example.org".into(),
410 port: Some(443),
411 local: None,
412 direct: Some(direct()),
413 domain: Some("media.example.org".into()),
414 member: Some(true),
415 uid: None,
416 };
417 let candidates = server_candidates(&server, Some("https://media.example.org"));
418 assert_eq!(candidates.len(), 4);
419 assert_eq!(candidates[0].kind, CandidateKind::Domain);
420 assert_eq!(candidates[1].kind, CandidateKind::Lan);
421 assert_eq!(candidates[3].kind, CandidateKind::Ipv4);
422 assert_eq!(
423 domain_candidate("a.org", Some(8443)).url,
424 "https://a.org:8443"
425 );
426 }
427
428 #[cfg(feature = "http")]
429 mod probe {
430 use super::*;
431 use std::time::Duration;
432
433 fn candidates() -> Vec<DirectCandidate> {
434 direct_candidates(&direct())
435 }
436
437 async fn run(plan: Vec<(bool, u64)>, options: ProbeOptions) -> Option<CandidateKind> {
439 let candidates = candidates();
440 probe_candidates_with(&candidates, options, |candidate| {
441 let index = candidates.iter().position(|c| c == candidate).unwrap();
442 let (ok, delay) = plan[index];
443 async move {
444 futures_timer::Delay::new(Duration::from_millis(delay)).await;
445 ok
446 }
447 })
448 .await
449 .map(|c| c.kind)
450 }
451
452 #[tokio::test]
453 async fn the_first_preferred_success_wins_at_once() {
454 let winner = run(
455 vec![(true, 10), (true, 1), (true, 1)],
456 ProbeOptions {
457 preference_window: Duration::from_secs(5),
458 ..Default::default()
459 },
460 )
461 .await;
462 assert_eq!(winner, Some(CandidateKind::Lan));
463 }
464
465 #[tokio::test]
466 async fn a_less_preferred_success_wins_after_the_window() {
467 let winner = run(
468 vec![(true, 2_000), (false, 1), (true, 1)],
469 ProbeOptions {
470 preference_window: Duration::from_millis(50),
471 ..Default::default()
472 },
473 )
474 .await;
475 assert_eq!(winner, Some(CandidateKind::Ipv4));
476 }
477
478 #[tokio::test]
479 async fn a_success_wins_when_all_preferred_failed() {
480 let winner = run(
481 vec![(false, 1), (false, 5), (true, 10)],
482 ProbeOptions {
483 preference_window: Duration::from_secs(5),
484 ..Default::default()
485 },
486 )
487 .await;
488 assert_eq!(winner, Some(CandidateKind::Ipv4));
489 }
490
491 #[tokio::test]
492 async fn none_when_all_fail_or_time_out() {
493 let all_fail = run(vec![(false, 1), (false, 1), (false, 1)], Default::default()).await;
494 assert_eq!(all_fail, None);
495 let too_slow = run(
496 vec![(true, 2_000), (true, 2_000), (true, 2_000)],
497 ProbeOptions {
498 timeout: Duration::from_millis(30),
499 ..Default::default()
500 },
501 )
502 .await;
503 assert_eq!(too_slow, None);
504 }
505 }
506}