use std::net::{IpAddr, Ipv6Addr};
use serde::{Deserialize, Serialize};
use crate::cloud::{CloudServer, ServerDirect};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum CandidateKind {
Lan,
Ipv6,
Ipv4,
Domain,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DirectCandidate {
pub kind: CandidateKind,
pub address: String,
pub url: String,
}
pub fn encode_ip_label(address: &str) -> Option<String> {
match address.parse::<IpAddr>().ok()? {
IpAddr::V4(ip) => Some(ip.to_string().replace('.', "-")),
IpAddr::V6(ip) => Some(ipv6_canonical(&ip).replace(':', "-")),
}
}
fn ipv6_canonical(ip: &Ipv6Addr) -> String {
let segments = ip.segments();
let (mut best_start, mut best_len) = (0, 0);
let mut index = 0;
while index < 8 {
if segments[index] == 0 {
let start = index;
while index < 8 && segments[index] == 0 {
index += 1;
}
if index - start > best_len {
(best_start, best_len) = (start, index - start);
}
} else {
index += 1;
}
}
let hex = |range: &[u16]| {
range
.iter()
.map(|s| format!("{s:x}"))
.collect::<Vec<_>>()
.join(":")
};
if best_len < 2 {
return hex(&segments);
}
format!(
"{}::{}",
hex(&segments[..best_start]),
hex(&segments[best_start + best_len..])
)
}
pub fn direct_hostname(direct: &ServerDirect, address: &str) -> Option<String> {
Some(format!(
"{}.{}.{}",
encode_ip_label(address)?,
direct.label,
direct.zone
))
}
pub fn direct_url(direct: &ServerDirect, address: &str) -> Option<String> {
let port = if direct.port == 443 {
String::new()
} else {
format!(":{}", direct.port)
};
Some(format!(
"https://{}{port}",
direct_hostname(direct, address)?
))
}
pub fn direct_candidates(direct: &ServerDirect) -> Vec<DirectCandidate> {
let mut candidates: Vec<DirectCandidate> = Vec::new();
let addresses = &direct.addresses;
let all = addresses
.lan
.iter()
.map(|a| (CandidateKind::Lan, a))
.chain(addresses.ipv6.iter().map(|a| (CandidateKind::Ipv6, a)))
.chain(addresses.ipv4.iter().map(|a| (CandidateKind::Ipv4, a)));
for (kind, address) in all {
if candidates.iter().any(|c| &c.address == address) {
continue;
}
if let Some(url) = direct_url(direct, address) {
candidates.push(DirectCandidate {
kind,
address: address.clone(),
url,
});
}
}
candidates
}
pub fn domain_candidate(domain: &str, port: Option<u16>) -> DirectCandidate {
let suffix = match port {
None | Some(443) => String::new(),
Some(port) => format!(":{port}"),
};
DirectCandidate {
kind: CandidateKind::Domain,
address: domain.to_owned(),
url: format!("https://{domain}{suffix}"),
}
}
pub fn public_direct_url(direct: &ServerDirect) -> Option<String> {
let public: Vec<_> = direct_candidates(direct)
.into_iter()
.filter(|c| c.kind != CandidateKind::Lan)
.collect();
public
.iter()
.find(|c| c.kind == CandidateKind::Ipv4)
.or(public.first())
.map(|c| c.url.clone())
}
pub fn public_server_url(server: &CloudServer) -> Option<String> {
server
.direct
.as_ref()
.and_then(public_direct_url)
.or_else(|| {
server
.domain
.as_deref()
.map(|d| domain_candidate(d, server.port).url)
})
}
pub fn server_candidates(server: &CloudServer, preferred: Option<&str>) -> Vec<DirectCandidate> {
let mut candidates = server
.direct
.as_ref()
.map(direct_candidates)
.unwrap_or_default();
if let Some(domain) = server.domain.as_deref().filter(|d| !d.is_empty()) {
candidates.push(domain_candidate(domain, server.port));
}
if let Some(preferred) = preferred {
candidates.sort_by_key(|c| c.url != preferred);
}
candidates
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ProbeOptions {
pub timeout: std::time::Duration,
pub preference_window: std::time::Duration,
}
impl Default for ProbeOptions {
fn default() -> Self {
ProbeOptions {
timeout: std::time::Duration::from_millis(2_500),
preference_window: std::time::Duration::from_millis(150),
}
}
}
#[cfg(feature = "http")]
pub async fn probe_candidates_with<F, Fut>(
candidates: &[DirectCandidate],
options: ProbeOptions,
ping: F,
) -> Option<DirectCandidate>
where
F: Fn(&DirectCandidate) -> Fut,
Fut: std::future::Future<Output = bool>,
{
use futures_timer::Delay;
use futures_util::StreamExt;
use futures_util::future::{Either, select};
use futures_util::stream::FuturesUnordered;
if candidates.is_empty() {
return None;
}
let mut pending: FuturesUnordered<_> = candidates
.iter()
.enumerate()
.map(|(index, candidate)| {
let answer = ping(candidate);
async move { (index, answer.await) }
})
.collect();
let mut outcome: Vec<Option<bool>> = vec![None; candidates.len()];
let best = |outcome: &[Option<bool>]| {
outcome
.iter()
.position(|o| *o == Some(true))
.map(|i| candidates[i].clone())
};
let mut deadline = Delay::new(options.timeout);
let mut grace: Option<Delay> = None;
loop {
let timers = async {
match grace.as_mut() {
Some(grace) => {
select(&mut deadline, grace).await;
}
None => (&mut deadline).await,
}
};
let answer = match select(pending.next(), Box::pin(timers)).await {
Either::Left((answer, _)) => answer,
Either::Right(_) => return best(&outcome),
};
let Some((index, ok)) = answer else {
return best(&outcome);
};
outcome[index] = Some(ok);
match outcome.iter().position(|o| *o == Some(true)) {
None if outcome.iter().all(|o| *o == Some(false)) => return None,
None => {}
Some(first) if outcome[..first].iter().all(|o| *o == Some(false)) => {
return Some(candidates[first].clone());
}
Some(_) => {
grace.get_or_insert_with(|| Delay::new(options.preference_window));
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cloud::ServerDirectAddresses;
fn direct() -> ServerDirect {
ServerDirect {
label: "abc".into(),
zone: "redseat.direct".into(),
port: 8443,
addresses: ServerDirectAddresses {
lan: vec!["192.168.1.10".into(), "not-an-ip".into()],
ipv4: Some("203.0.113.5".into()),
ipv6: vec!["2a01:e0a:0:0::1".into(), "192.168.1.10".into()],
},
updated_at: 0,
}
}
#[test]
fn encodes_ip_labels() {
assert_eq!(encode_ip_label("192.168.1.10").unwrap(), "192-168-1-10");
assert_eq!(encode_ip_label("2A01:E0A:0:0::1").unwrap(), "2a01-e0a--1");
assert_eq!(encode_ip_label("::ffff:1.2.3.4").unwrap(), "--ffff-102-304");
assert_eq!(encode_ip_label("1:0:0:2:0:0:0:3").unwrap(), "1-0-0-2--3");
assert_eq!(
encode_ip_label("1:2:3:4:5:6:0:8").unwrap(),
"1-2-3-4-5-6-0-8"
);
assert_eq!(encode_ip_label("01.2.3.4"), None);
assert_eq!(encode_ip_label("example.org"), None);
}
#[test]
fn orders_candidates_lan_ipv6_ipv4() {
let urls: Vec<_> = direct_candidates(&direct())
.into_iter()
.map(|c| (c.kind, c.url))
.collect();
assert_eq!(
urls,
vec![
(
CandidateKind::Lan,
"https://192-168-1-10.abc.redseat.direct:8443".to_owned()
),
(
CandidateKind::Ipv6,
"https://2a01-e0a--1.abc.redseat.direct:8443".to_owned()
),
(
CandidateKind::Ipv4,
"https://203-0-113-5.abc.redseat.direct:8443".to_owned()
),
]
);
assert_eq!(
public_direct_url(&direct()).unwrap(),
"https://203-0-113-5.abc.redseat.direct:8443"
);
}
#[test]
fn adds_the_domain_and_puts_the_preferred_url_first() {
let server = CloudServer {
id: "srv".into(),
name: None,
url: "media.example.org".into(),
port: Some(443),
local: None,
direct: Some(direct()),
domain: Some("media.example.org".into()),
member: Some(true),
};
let candidates = server_candidates(&server, Some("https://media.example.org"));
assert_eq!(candidates.len(), 4);
assert_eq!(candidates[0].kind, CandidateKind::Domain);
assert_eq!(candidates[1].kind, CandidateKind::Lan);
assert_eq!(candidates[3].kind, CandidateKind::Ipv4);
assert_eq!(
domain_candidate("a.org", Some(8443)).url,
"https://a.org:8443"
);
}
#[cfg(feature = "http")]
mod probe {
use super::*;
use std::time::Duration;
fn candidates() -> Vec<DirectCandidate> {
direct_candidates(&direct())
}
async fn run(plan: Vec<(bool, u64)>, options: ProbeOptions) -> Option<CandidateKind> {
let candidates = candidates();
probe_candidates_with(&candidates, options, |candidate| {
let index = candidates.iter().position(|c| c == candidate).unwrap();
let (ok, delay) = plan[index];
async move {
futures_timer::Delay::new(Duration::from_millis(delay)).await;
ok
}
})
.await
.map(|c| c.kind)
}
#[tokio::test]
async fn the_first_preferred_success_wins_at_once() {
let winner = run(
vec![(true, 10), (true, 1), (true, 1)],
ProbeOptions {
preference_window: Duration::from_secs(5),
..Default::default()
},
)
.await;
assert_eq!(winner, Some(CandidateKind::Lan));
}
#[tokio::test]
async fn a_less_preferred_success_wins_after_the_window() {
let winner = run(
vec![(true, 2_000), (false, 1), (true, 1)],
ProbeOptions {
preference_window: Duration::from_millis(50),
..Default::default()
},
)
.await;
assert_eq!(winner, Some(CandidateKind::Ipv4));
}
#[tokio::test]
async fn a_success_wins_when_all_preferred_failed() {
let winner = run(
vec![(false, 1), (false, 5), (true, 10)],
ProbeOptions {
preference_window: Duration::from_secs(5),
..Default::default()
},
)
.await;
assert_eq!(winner, Some(CandidateKind::Ipv4));
}
#[tokio::test]
async fn none_when_all_fail_or_time_out() {
let all_fail = run(vec![(false, 1), (false, 1), (false, 1)], Default::default()).await;
assert_eq!(all_fail, None);
let too_slow = run(
vec![(true, 2_000), (true, 2_000), (true, 2_000)],
ProbeOptions {
timeout: Duration::from_millis(30),
..Default::default()
},
)
.await;
assert_eq!(too_slow, None);
}
}
}