redseat-api 0.2.0

Rust client for Redseat media servers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
//! Which address to reach a server at. Port of `@redseat/api-http` `direct.ts` and of
//! the candidate order of the web app's `direct-access.ts`.
//!
//! Direct HTTPS to a Redseat server is `https://<ip-encoded>.<label>.<zone>:<port>`: the
//! zone's DNS decodes the IP from the first label, and the server holds a wildcard
//! certificate for `*.<label>.<zone>`, so every address gets a valid TLS name.

use std::net::{IpAddr, Ipv6Addr};

use serde::{Deserialize, Serialize};

use crate::cloud::{CloudServer, ServerDirect};

/// Where a candidate address comes from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum CandidateKind {
    Lan,
    Ipv6,
    Ipv4,
    /// The server's custom domain, behind its own reverse proxy.
    Domain,
}

/// A base URL to try.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DirectCandidate {
    pub kind: CandidateKind,
    pub address: String,
    /// Base URL without trailing slash.
    pub url: String,
}

/// `192.168.1.10` → `192-168-1-10`; `2a01:e0a::1` → `2a01-e0a--1`. `None` when
/// `address` is not an IP address.
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(':', "-")),
    }
}

/// RFC 5952 text of an IPv6 address, always in hex groups like the WHATWG URL
/// serializer (Rust's `Display` writes IPv4-mapped addresses with dots).
fn ipv6_canonical(ip: &Ipv6Addr) -> String {
    let segments = ip.segments();
    // The first longest run of at least two zero groups is compressed.
    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..])
    )
}

/// `<ip-encoded>.<label>.<zone>`.
pub fn direct_hostname(direct: &ServerDirect, address: &str) -> Option<String> {
    Some(format!(
        "{}.{}.{}",
        encode_ip_label(address)?,
        direct.label,
        direct.zone
    ))
}

/// `https://<ip-encoded>.<label>.<zone>[:port]`.
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)?
    ))
}

/// Candidates in preference order: LAN, then global IPv6, then public IPv4. Addresses
/// that are not IPs and duplicates are skipped.
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
}

/// A server's custom domain, served over HTTPS by its own reverse proxy.
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}"),
    }
}

/// URL for links meant to leave this device (share, a player on another machine): a
/// public address, never a LAN one. IPv4 first, since recipients may lack IPv6.
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())
}

/// Public URL of a server: its public direct address, else its custom domain.
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)
        })
}

/// Every address of a server, best first: direct HTTPS candidates, then the custom
/// domain. A `preferred` URL (the last one that worked, cached by the app) goes first.
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 {
        // Stable: the others keep their order.
        candidates.sort_by_key(|c| c.url != preferred);
    }
    candidates
}

/// Probe timing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ProbeOptions {
    /// Overall deadline.
    pub timeout: std::time::Duration,
    /// How long a success waits for a more preferred candidate that is still pending.
    /// Keeps LAN ahead of a public address that happens to answer a few ms sooner.
    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),
        }
    }
}

/// Pings every candidate at once with `ping` (true: it answered). A success wins as
/// soon as every more preferred candidate (earlier in the list) has failed, or after
/// `preference_window` otherwise; the best success so far is used. `None` when none
/// answers before `timeout`. Port of `probeDirectCandidates`.
#[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();
    // Per candidate: None = pending, Some(true) = answered, Some(false) = failed.
    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())
        }

        /// `(answers, delay in ms)` per candidate index.
        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);
        }
    }
}