Skip to main content

redseat_api/
direct.rs

1//! Which address to reach a server at. Port of `@redseat/api-http` `direct.ts` and of
2//! the candidate order of the web app's `direct-access.ts`.
3//!
4//! Direct HTTPS to a Redseat server is `https://<ip-encoded>.<label>.<zone>:<port>`: the
5//! zone's DNS decodes the IP from the first label, and the server holds a wildcard
6//! certificate for `*.<label>.<zone>`, so every address gets a valid TLS name.
7
8use std::net::{IpAddr, Ipv6Addr};
9
10use serde::{Deserialize, Serialize};
11
12use crate::cloud::{CloudServer, ServerDirect};
13
14/// Where a candidate address comes from.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
16#[serde(rename_all = "camelCase")]
17pub enum CandidateKind {
18    Lan,
19    Ipv6,
20    Ipv4,
21    /// The server's custom domain, behind its own reverse proxy.
22    Domain,
23}
24
25/// A base URL to try.
26#[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    /// Base URL without trailing slash.
32    pub url: String,
33}
34
35/// `192.168.1.10` → `192-168-1-10`; `2a01:e0a::1` → `2a01-e0a--1`. `None` when
36/// `address` is not an IP address.
37pub 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
44/// RFC 5952 text of an IPv6 address, always in hex groups like the WHATWG URL
45/// serializer (Rust's `Display` writes IPv4-mapped addresses with dots).
46fn ipv6_canonical(ip: &Ipv6Addr) -> String {
47    let segments = ip.segments();
48    // The first longest run of at least two zero groups is compressed.
49    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
81/// `<ip-encoded>.<label>.<zone>`.
82pub 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
91/// `https://<ip-encoded>.<label>.<zone>[:port]`.
92pub 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
104/// Candidates in preference order: LAN, then global IPv6, then public IPv4. Addresses
105/// that are not IPs and duplicates are skipped.
106pub 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
130/// A server's custom domain, served over HTTPS by its own reverse proxy.
131pub 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
143/// URL for links meant to leave this device (share, a player on another machine): a
144/// public address, never a LAN one. IPv4 first, since recipients may lack IPv6.
145pub 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
157/// Public URL of a server: its public direct address, else its custom domain.
158pub 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
171/// Every address of a server, best first: direct HTTPS candidates, then the custom
172/// domain. A `preferred` URL (the last one that worked, cached by the app) goes first.
173pub 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        // Stable: the others keep their order.
184        candidates.sort_by_key(|c| c.url != preferred);
185    }
186    candidates
187}
188
189/// Probe timing.
190#[derive(Debug, Clone, Copy, PartialEq, Eq)]
191pub struct ProbeOptions {
192    /// Overall deadline.
193    pub timeout: std::time::Duration,
194    /// How long a success waits for a more preferred candidate that is still pending.
195    /// Keeps LAN ahead of a public address that happens to answer a few ms sooner.
196    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/// Pings every candidate at once with `ping` (true: it answered). A success wins as
209/// soon as every more preferred candidate (earlier in the list) has failed, or after
210/// `preference_window` otherwise; the best success so far is used. `None` when none
211/// answers before `timeout`. Port of `probeDirectCandidates`.
212#[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    // Per candidate: None = pending, Some(true) = answered, Some(false) = failed.
239    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        /// `(answers, delay in ms)` per candidate index.
375        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}