Skip to main content

alpha2_host_core/remote/
mod.rs

1//! Remote media read by byte range, behind a [`RangeTransport`] the host supplies.
2//!
3//! One [`RemoteSession`] per request probes each URL once ([`RemoteObject`]), holds the blocks
4//! fetched for it, and hands out readers ([`RemoteReader`], [`RemoteStream`]) that wait for bytes
5//! while marking the request's watches, so a network wait is never taken for a stalled decoder.
6
7mod cache;
8mod fetch;
9mod location;
10mod protocol;
11mod reader;
12
13use std::collections::HashMap;
14use std::io::Read;
15use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
16use std::sync::{Arc, Mutex, PoisonError};
17use std::time::Duration;
18
19use alpha2_media::CancelToken;
20
21pub use location::{SourceLocation, decode_error};
22pub use reader::{RemoteReader, RemoteStream};
23
24use cache::BlockCache;
25use protocol::ObjectFacts;
26
27/// Blocks are this long and aligned to the object's offsets.
28pub const BLOCK_BYTES: u64 = 256 * 1024;
29/// The smallest block cache a request may ask for.
30pub const MIN_CACHE_BYTES: u64 = 4 * 1024 * 1024;
31/// The block cache of a request that names none, before it is fitted to the machine.
32pub const DEFAULT_CACHE_BYTES: u64 = 64 * 1024 * 1024;
33/// Attempts at one range before it fails.
34pub const MAX_ATTEMPTS: usize = 5;
35/// The waits between attempts.
36pub const BACKOFF: [Duration; MAX_ATTEMPTS - 1] = [
37    Duration::from_millis(250),
38    Duration::from_millis(500),
39    Duration::from_secs(1),
40    Duration::from_secs(2),
41];
42/// A read waiting this long with no byte of what it waits for fails as unreachable.
43pub const NO_PROGRESS_LIMIT: Duration = Duration::from_secs(30);
44/// The longest `Retry-After` a busy failure reports.
45pub const MAX_RETRY_AFTER: Duration = Duration::from_secs(60);
46/// How long a transport may take to connect, TLS included.
47pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
48/// How long a transport may wait for a response head.
49pub const HEAD_TIMEOUT: Duration = Duration::from_secs(15);
50/// How long a response body may go without a byte.
51pub const BODY_IDLE_TIMEOUT: Duration = Duration::from_secs(15);
52const WAIT_POLL: Duration = Duration::from_millis(5);
53
54/// One `GET` of a byte range.
55#[derive(Clone, Debug, PartialEq, Eq)]
56pub struct RangeRequest {
57    /// The URL, query included.
58    pub url: String,
59    /// The first byte asked for.
60    pub first: u64,
61    /// The last byte asked for, inclusive.
62    pub last: u64,
63    /// The validator every range after the probe sends.
64    pub precondition: Option<Precondition>,
65}
66
67impl RangeRequest {
68    /// The `Range` header value.
69    #[must_use]
70    pub fn range_header(&self) -> String {
71        format!("bytes={}-{}", self.first, self.last)
72    }
73}
74
75/// A conditional request header (RFC 9110 section 13.1).
76#[derive(Clone, Debug, PartialEq, Eq)]
77pub enum Precondition {
78    /// `If-Match` with the probe's strong entity tag.
79    IfMatch(String),
80    /// `If-Unmodified-Since` with the probe's `Last-Modified`.
81    IfUnmodifiedSince(String),
82}
83
84impl Precondition {
85    /// The header's name and value.
86    #[must_use]
87    pub fn header(&self) -> (&'static str, &str) {
88        match self {
89            Self::IfMatch(tag) => ("If-Match", tag),
90            Self::IfUnmodifiedSince(date) => ("If-Unmodified-Since", date),
91        }
92    }
93}
94
95/// The response headers a range read looks at, each its first value.
96#[derive(Clone, Debug, Default, PartialEq, Eq)]
97pub struct ResponseHeaders {
98    /// `Content-Range`.
99    pub content_range: Option<String>,
100    /// `Content-Encoding`.
101    pub content_encoding: Option<String>,
102    /// `Content-Type`.
103    pub content_type: Option<String>,
104    /// `ETag`.
105    pub etag: Option<String>,
106    /// `Last-Modified`.
107    pub last_modified: Option<String>,
108    /// `Retry-After`.
109    pub retry_after: Option<String>,
110}
111
112/// A response that is not a redirect, with its body unread.
113pub struct RangeResponse {
114    /// The status code.
115    pub status: u16,
116    /// The headers read.
117    pub headers: ResponseHeaders,
118    /// The body; dropping it drops the connection.
119    pub body: Box<dyn Read + Send>,
120}
121
122impl RangeResponse {
123    fn retry_delay(&self) -> Option<Duration> {
124        self.headers
125            .retry_after
126            .as_deref()
127            .and_then(|value| protocol::retry_after(value, std::time::SystemTime::now()))
128    }
129}
130
131/// Why the transport has no response.
132#[derive(Clone, Debug, PartialEq, Eq)]
133pub enum TransportFailure {
134    /// The operator's policy refused the target before it was contacted.
135    Refused {
136        /// What refused it.
137        policy: RefusalPolicy,
138        /// Why, with the URL shown as [`shown_url`] shows it.
139        message: String,
140    },
141    /// The certificate verifier or the TLS handshake refused the server; never tried again.
142    Tls(String),
143    /// A resolve, connect, TLS I/O or timeout failure; tried again.
144    Unreachable(String),
145    /// The server answered something no range read can use, such as too many redirects; never
146    /// tried again.
147    Rejected(String),
148}
149
150/// The operator rule that refused a URL.
151#[derive(Clone, Copy, Debug, PartialEq, Eq)]
152pub enum RefusalPolicy {
153    /// The origin is not listed, or no origin is.
154    Origins,
155    /// A redirect left the listed origins.
156    Redirect,
157    /// The address is not global unicast.
158    Address,
159}
160
161impl RefusalPolicy {
162    /// The name `details.policy` carries.
163    #[must_use]
164    pub const fn name(self) -> &'static str {
165        match self {
166            Self::Origins => "origins",
167            Self::Redirect => "redirect",
168            Self::Address => "address",
169        }
170    }
171}
172
173/// Sends range requests; the host's uses HTTPS, tests script the answers.
174pub trait RangeTransport: Send + Sync {
175    /// One `GET` of `request`, its redirects followed.
176    ///
177    /// # Errors
178    /// Why there is no response.
179    fn get(&self, request: &RangeRequest) -> Result<RangeResponse, TransportFailure>;
180}
181
182/// How a remote read failed.
183#[derive(Clone, Copy, Debug, PartialEq, Eq)]
184pub enum RemoteFailure {
185    /// `MEDIA_REFUSED`.
186    Refused(RefusalPolicy),
187    /// `MEDIA_TLS_FAILED`.
188    TlsFailed,
189    /// `MEDIA_UNREACHABLE`.
190    Unreachable,
191    /// `MEDIA_BUSY`, with the server's delay in milliseconds, at most 60000.
192    Busy {
193        /// From `Retry-After`.
194        retry_after_ms: u64,
195    },
196    /// `MEDIA_RANGE_UNSUPPORTED`.
197    RangeUnsupported,
198    /// `MEDIA_REJECTED`.
199    Rejected,
200    /// `MEDIA_CHANGED`.
201    Changed,
202    /// The probe answered `404` or `410`: the source is offline, as a missing file is.
203    Offline,
204    /// The probe answered `416` for an empty object, which holds no media.
205    Empty,
206    /// The request's cancel was seen.
207    Cancelled,
208}
209
210impl RemoteFailure {
211    /// The protocol code a request fails with.
212    #[must_use]
213    pub const fn code(self) -> &'static str {
214        match self {
215            Self::Refused(_) => "MEDIA_REFUSED",
216            Self::TlsFailed => "MEDIA_TLS_FAILED",
217            Self::Unreachable => "MEDIA_UNREACHABLE",
218            Self::Busy { .. } => "MEDIA_BUSY",
219            Self::RangeUnsupported | Self::Empty => "MEDIA_RANGE_UNSUPPORTED",
220            Self::Rejected | Self::Offline => "MEDIA_REJECTED",
221            Self::Changed => "MEDIA_CHANGED",
222            Self::Cancelled => "CANCELLED",
223        }
224    }
225}
226
227/// A remote read's failure, its message showing the URL as [`shown_url`] does.
228#[derive(Clone, Debug, PartialEq, Eq)]
229pub struct RemoteError {
230    /// What failed.
231    pub failure: RemoteFailure,
232    /// What happened.
233    pub message: String,
234    /// The status the server answered, when it answered.
235    pub status: Option<u16>,
236    /// The URL read, as [`shown_url`] shows it, when a reader failed.
237    pub url: Option<String>,
238}
239
240impl RemoteError {
241    /// A failure with no status.
242    pub fn new(failure: RemoteFailure, message: impl Into<String>) -> Self {
243        Self {
244            failure,
245            message: message.into(),
246            status: None,
247            url: None,
248        }
249    }
250
251    /// The failure naming the shown URL a reader read.
252    #[must_use]
253    pub fn with_url(mut self, shown: &str) -> Self {
254        self.url = Some(shown.to_owned());
255        self
256    }
257
258    /// The failure with the status the server answered.
259    #[must_use]
260    pub const fn with_status(mut self, status: u16) -> Self {
261        self.status = Some(status);
262        self
263    }
264
265    fn cancelled() -> Self {
266        Self::new(RemoteFailure::Cancelled, "the request was cancelled")
267    }
268
269    /// The remote failure an I/O error from a reader carries, if it carries one.
270    #[must_use]
271    pub fn of(error: &std::io::Error) -> Option<&Self> {
272        error.get_ref()?.downcast_ref()
273    }
274}
275
276impl std::fmt::Display for RemoteError {
277    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
278        formatter.write_str(&self.message)
279    }
280}
281
282impl std::error::Error for RemoteError {}
283
284impl From<TransportFailure> for RemoteError {
285    fn from(failure: TransportFailure) -> Self {
286        match failure {
287            TransportFailure::Refused { policy, message } => {
288                Self::new(RemoteFailure::Refused(policy), message)
289            }
290            TransportFailure::Tls(message) => Self::new(RemoteFailure::TlsFailed, message),
291            TransportFailure::Unreachable(message) => {
292                Self::new(RemoteFailure::Unreachable, message)
293            }
294            TransportFailure::Rejected(message) => Self::new(RemoteFailure::Rejected, message),
295        }
296    }
297}
298
299impl From<RemoteError> for std::io::Error {
300    fn from(error: RemoteError) -> Self {
301        Self::other(error)
302    }
303}
304
305/// `url` as a message shows it: scheme, host, port and path, without user info, query or
306/// fragment, which may carry credentials (a signed URL's signature). A path is shown whole.
307#[must_use]
308pub fn shown_url(url: &str) -> String {
309    let Some((scheme, rest)) = url.split_once("://") else {
310        return url.to_owned();
311    };
312    if scheme.is_empty()
313        || !scheme
314            .bytes()
315            .all(|byte| byte.is_ascii_alphanumeric() || b"+-.".contains(&byte))
316    {
317        return url.to_owned();
318    }
319    let rest = rest.split(['?', '#']).next().unwrap_or_default();
320    let (authority, path) = rest.find('/').map_or((rest, ""), |at| rest.split_at(at));
321    let host = authority
322        .rsplit_once('@')
323        .map_or(authority, |(_, host)| host);
324    format!("{scheme}://{host}{path}")
325}
326
327pub(crate) trait Clock: Send + Sync {
328    fn now(&self) -> Duration;
329    fn sleep(&self, duration: Duration, stop: &dyn Fn() -> bool);
330}
331
332struct AwakeClock(alpha2_os::AwakeInstant);
333
334impl Clock for AwakeClock {
335    fn now(&self) -> Duration {
336        self.0.elapsed()
337    }
338
339    fn sleep(&self, duration: Duration, stop: &dyn Fn() -> bool) {
340        let until = self.now() + duration;
341        while !stop() {
342            let left = until.saturating_sub(self.now());
343            if left.is_zero() {
344                break;
345            }
346            std::thread::sleep(left.min(WAIT_POLL));
347        }
348    }
349}
350
351/// What a request's remote reads cost, for its `performance` report.
352#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
353pub struct RemoteCounts {
354    /// Body bytes received.
355    pub bytes: u64,
356    /// `GET`s sent, retries included.
357    pub requests: u64,
358    /// `GET`s sent again after a failed attempt.
359    pub retries: u64,
360    /// Milliseconds readers waited for bytes.
361    pub read_wait_ms: u64,
362}
363
364#[derive(Default)]
365struct Counters {
366    bytes: AtomicU64,
367    requests: AtomicU64,
368    retries: AtomicU64,
369    read_wait_ns: AtomicU64,
370}
371
372struct Shared {
373    transport: Arc<dyn RangeTransport>,
374    cancel: CancelToken,
375    clock: Arc<dyn Clock>,
376    cache: Mutex<BlockCache>,
377    counters: Counters,
378    readers: AtomicUsize,
379    next_object: AtomicU64,
380}
381
382impl Shared {
383    fn cache(&self) -> std::sync::MutexGuard<'_, BlockCache> {
384        self.cache.lock().unwrap_or_else(PoisonError::into_inner)
385    }
386
387    fn window_cap(&self) -> u64 {
388        let readers = self.readers.load(Ordering::Acquire).max(1) as u64;
389        let share = self.cache().budget() / 2 / readers;
390        (share / BLOCK_BYTES).max(1) * BLOCK_BYTES
391    }
392
393    fn waiting(&self) -> Result<(), RemoteError> {
394        crate::request_watch::beat_request();
395        crate::recovery::report_decode_progress();
396        if self.cancel.is_cancelled() {
397            return Err(RemoteError::cancelled());
398        }
399        Ok(())
400    }
401
402    fn waited(&self, since: Duration) {
403        let waited = self.clock.now().saturating_sub(since);
404        crate::recovery::report_input_wait(waited);
405        self.counters.read_wait_ns.fetch_add(
406            u64::try_from(waited.as_nanos()).unwrap_or(u64::MAX),
407            Ordering::Relaxed,
408        );
409    }
410}
411
412/// The remote reads of one request: each URL probed once, one block cache, one cancel.
413///
414/// Sessions share nothing, so a request reads only bytes its own URLs were answered with.
415pub struct RemoteSession {
416    shared: Arc<Shared>,
417    objects: Mutex<HashMap<String, Arc<RemoteObject>>>,
418}
419
420impl RemoteSession {
421    /// A session reading through `transport`, holding at most `cache_bytes` of blocks (at least
422    /// one per reader), stopped by `cancel`.
423    #[must_use]
424    pub fn new(transport: Arc<dyn RangeTransport>, cancel: CancelToken, cache_bytes: u64) -> Self {
425        Self::with_clock(
426            transport,
427            cancel,
428            cache_bytes,
429            Arc::new(AwakeClock(alpha2_os::AwakeInstant::now())),
430        )
431    }
432
433    pub(crate) fn with_clock(
434        transport: Arc<dyn RangeTransport>,
435        cancel: CancelToken,
436        cache_bytes: u64,
437        clock: Arc<dyn Clock>,
438    ) -> Self {
439        Self {
440            shared: Arc::new(Shared {
441                transport,
442                cancel,
443                clock,
444                cache: Mutex::new(BlockCache::new(cache_bytes)),
445                counters: Counters::default(),
446                readers: AtomicUsize::new(0),
447                next_object: AtomicU64::new(0),
448            }),
449            objects: Mutex::new(HashMap::new()),
450        }
451    }
452
453    /// The object at `url`, probed on its first open in this session: a `GET` of the first block
454    /// that must answer `206` with a numeric total, an identity body and a validator.
455    ///
456    /// # Errors
457    /// The probe's failure: [`RemoteFailure::Offline`] for `404` and `410`,
458    /// [`RemoteFailure::Empty`] for an empty object, or the code the failure maps to.
459    pub fn open(&self, url: &str) -> Result<Arc<RemoteObject>, RemoteError> {
460        if let Some(object) = self
461            .objects
462            .lock()
463            .unwrap_or_else(PoisonError::into_inner)
464            .get(url)
465        {
466            return Ok(Arc::clone(object));
467        }
468        let id = self.shared.next_object.fetch_add(1, Ordering::Relaxed);
469        let (facts, first_block) = fetch::probe(&self.shared, url)?;
470        self.shared.cache().insert((id, 0), Arc::from(first_block));
471        let object = Arc::new(RemoteObject {
472            id,
473            url: url.to_owned(),
474            shown: shown_url(url),
475            facts,
476            shared: Arc::clone(&self.shared),
477        });
478        Ok(Arc::clone(
479            self.objects
480                .lock()
481                .unwrap_or_else(PoisonError::into_inner)
482                .entry(url.to_owned())
483                .or_insert(object),
484        ))
485    }
486
487    /// What the session's reads cost so far.
488    #[must_use]
489    pub fn counts(&self) -> RemoteCounts {
490        let counters = &self.shared.counters;
491        RemoteCounts {
492            bytes: counters.bytes.load(Ordering::Relaxed),
493            requests: counters.requests.load(Ordering::Relaxed),
494            retries: counters.retries.load(Ordering::Relaxed),
495            read_wait_ms: counters.read_wait_ns.load(Ordering::Relaxed) / 1_000_000,
496        }
497    }
498
499    /// The bytes the block cache holds now.
500    #[must_use]
501    pub fn cached_bytes(&self) -> u64 {
502        self.shared.cache().held()
503    }
504}
505
506/// One URL as the probe found it: its length and validator, its blocks in the session's cache.
507pub struct RemoteObject {
508    id: u64,
509    url: String,
510    shown: String,
511    facts: ObjectFacts,
512    shared: Arc<Shared>,
513}
514
515impl RemoteObject {
516    /// The object's length in bytes.
517    #[must_use]
518    pub const fn len(&self) -> u64 {
519        self.facts.total
520    }
521
522    /// Whether the object holds no byte; a probed object never is.
523    #[must_use]
524    pub const fn is_empty(&self) -> bool {
525        self.facts.total == 0
526    }
527
528    /// The URL as messages show it.
529    #[must_use]
530    pub fn shown_url(&self) -> &str {
531        &self.shown
532    }
533
534    /// The probe's strong entity tag, if it named one.
535    #[must_use]
536    pub fn etag(&self) -> Option<&str> {
537        self.facts.etag.as_deref()
538    }
539
540    /// The probe's `Last-Modified`, if it named one.
541    #[must_use]
542    pub fn last_modified(&self) -> Option<&str> {
543        self.facts.last_modified.as_deref()
544    }
545
546    /// The probe's `Last-Modified` in Unix milliseconds, when it named a date that parses.
547    #[must_use]
548    pub fn last_modified_ms(&self) -> Option<i64> {
549        let date = protocol::http_date(self.last_modified()?)?;
550        let since = date
551            .duration_since(std::time::SystemTime::UNIX_EPOCH)
552            .ok()?;
553        i64::try_from(since.as_millis()).ok()
554    }
555
556    /// The validator the object is identified by in the request: its strong entity tag, else its
557    /// `Last-Modified`.
558    #[must_use]
559    pub fn validator(&self) -> &str {
560        self.etag()
561            .or_else(|| self.last_modified())
562            .unwrap_or_default()
563    }
564
565    /// A reader at offset 0 that reads through the session's block cache.
566    #[must_use]
567    pub fn reader(self: &Arc<Self>) -> RemoteReader {
568        RemoteReader::new(Arc::clone(self))
569    }
570
571    /// A reader of the whole object from its first byte that keeps only what it has not yet
572    /// returned, past the block cache.
573    #[must_use]
574    pub fn stream(self: &Arc<Self>) -> RemoteStream {
575        RemoteStream::new(Arc::clone(self))
576    }
577}
578
579#[cfg(test)]
580#[path = "../remote_tests.rs"]
581mod tests;