Skip to main content

alef_component_runtime/
download.rs

1//! Download tuning for [`ArtifactCache`](crate::ArtifactCache): timeouts, retry policy,
2//! progress reporting, cancellation, and transient-error classification.
3
4use crate::ComponentError;
5use std::fmt;
6use std::path::PathBuf;
7use std::sync::Arc;
8use std::sync::atomic::{AtomicBool, Ordering};
9use std::time::Duration;
10
11/// Default time allowed to establish a connection to a component's download URL.
12pub const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
13/// Default time allowed for an entire component download, connection included.
14pub const DEFAULT_TOTAL_TIMEOUT: Duration = Duration::from_secs(300);
15/// Default number of attempts (the first try included) for transient download failures.
16pub const DEFAULT_MAX_ATTEMPTS: u32 = 3;
17/// Default delay before the first retry; doubled for every further retry.
18pub const DEFAULT_RETRY_BACKOFF: Duration = Duration::from_millis(500);
19
20/// Callback invoked as archive bytes stream in: `(downloaded, total)`, where `total` is the
21/// archive size pinned by the lock entry.
22pub type ProgressCallback = Arc<dyn Fn(u64, u64) + Send + Sync>;
23
24/// Which trust anchors verify the TLS server certificate of a component download.
25///
26/// `WebPki` (the default) uses the Mozilla root set compiled into the binary, so behaviour does not
27/// depend on the machine. `PlatformVerifier` defers to the operating system trust store, which is
28/// what hosts behind a TLS-inspecting corporate proxy need: the proxy's CA is installed system-wide
29/// but is not in the Mozilla set. It requires the `platform-verifier` cargo feature of this crate;
30/// without it a download fails with [`ComponentError::Download`] naming the missing feature rather
31/// than silently falling back to `WebPki`. Integrity of the downloaded archive is unaffected: it is
32/// still pinned by the lock entry's SHA-256 (and signature).
33#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
34pub enum RootCerts {
35    /// Mozilla root certificates compiled into the binary.
36    #[default]
37    WebPki,
38    /// The operating system's certificate verifier (needs the `platform-verifier` feature).
39    PlatformVerifier,
40}
41
42/// How a component archive is downloaded.
43///
44/// `Default` reproduces the historical behaviour: 10 s connect timeout, 300 s total timeout,
45/// no progress callback, no cancellation, and up to 3 attempts on transient failures.
46/// Build one with the `with_*` methods:
47///
48/// ```
49/// use alef_component_runtime::DownloadOptions;
50/// use std::time::Duration;
51///
52/// let options = DownloadOptions::default()
53///     .with_total_timeout(Duration::from_secs(900))
54///     .with_progress(|downloaded, total| eprintln!("{downloaded}/{total}"));
55/// ```
56///
57/// Retries apply to connect errors, timeouts, interrupted body reads and HTTP 408/429/5xx.
58/// HTTP 4xx responses and integrity failures (size, digest, signature) are never retried.
59/// `progress` and `cancel` also apply to `file://` sources and
60/// [`ArtifactCache::install_from_reader`](crate::ArtifactCache::install_from_reader).
61#[derive(Clone)]
62#[non_exhaustive]
63pub struct DownloadOptions {
64    pub connect_timeout: Duration,
65    pub total_timeout: Duration,
66    pub progress: Option<ProgressCallback>,
67    /// Set to `true` from any thread to abort; checked between chunks and between retries.
68    /// An aborted install returns [`ComponentError::Cancelled`](crate::ComponentError::Cancelled).
69    pub cancel: Option<Arc<AtomicBool>>,
70    /// Total attempts including the first; values below 1 are treated as 1.
71    pub max_attempts: u32,
72    /// Delay before the first retry, doubled each time.
73    pub retry_backoff: Duration,
74    /// Trust anchors for HTTPS downloads; see [`RootCerts`].
75    pub root_certs: RootCerts,
76}
77
78impl Default for DownloadOptions {
79    fn default() -> Self {
80        Self {
81            connect_timeout: DEFAULT_CONNECT_TIMEOUT,
82            total_timeout: DEFAULT_TOTAL_TIMEOUT,
83            progress: None,
84            cancel: None,
85            max_attempts: DEFAULT_MAX_ATTEMPTS,
86            retry_backoff: DEFAULT_RETRY_BACKOFF,
87            root_certs: RootCerts::default(),
88        }
89    }
90}
91
92impl fmt::Debug for DownloadOptions {
93    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94        f.debug_struct("DownloadOptions")
95            .field("connect_timeout", &self.connect_timeout)
96            .field("total_timeout", &self.total_timeout)
97            .field("progress", &self.progress.as_ref().map(|_| "<callback>"))
98            .field("cancel", &self.cancel)
99            .field("max_attempts", &self.max_attempts)
100            .field("retry_backoff", &self.retry_backoff)
101            .field("root_certs", &self.root_certs)
102            .finish()
103    }
104}
105
106impl DownloadOptions {
107    #[must_use]
108    pub fn with_connect_timeout(mut self, timeout: Duration) -> Self {
109        self.connect_timeout = timeout;
110        self
111    }
112
113    #[must_use]
114    pub fn with_total_timeout(mut self, timeout: Duration) -> Self {
115        self.total_timeout = timeout;
116        self
117    }
118
119    #[must_use]
120    pub fn with_progress(mut self, progress: impl Fn(u64, u64) + Send + Sync + 'static) -> Self {
121        self.progress = Some(Arc::new(progress));
122        self
123    }
124
125    #[must_use]
126    pub fn with_cancel(mut self, cancel: Arc<AtomicBool>) -> Self {
127        self.cancel = Some(cancel);
128        self
129    }
130
131    #[must_use]
132    pub fn with_max_attempts(mut self, attempts: u32) -> Self {
133        self.max_attempts = attempts;
134        self
135    }
136
137    #[must_use]
138    pub fn with_retry_backoff(mut self, backoff: Duration) -> Self {
139        self.retry_backoff = backoff;
140        self
141    }
142
143    /// Select the trust anchors for HTTPS downloads; see [`RootCerts`].
144    #[must_use]
145    pub fn with_root_certs(mut self, root_certs: RootCerts) -> Self {
146        self.root_certs = root_certs;
147        self
148    }
149
150    /// The ureq TLS configuration for these options. `url` only labels the error.
151    #[cfg_attr(
152        feature = "platform-verifier",
153        expect(unused_variables, reason = "only the build without the feature reports the URL")
154    )]
155    pub(crate) fn tls_config(&self, url: &str) -> Result<ureq::tls::TlsConfig, ComponentError> {
156        let roots = match self.root_certs {
157            RootCerts::WebPki => ureq::tls::RootCerts::WebPki,
158            #[cfg(feature = "platform-verifier")]
159            RootCerts::PlatformVerifier => ureq::tls::RootCerts::PlatformVerifier,
160            #[cfg(not(feature = "platform-verifier"))]
161            RootCerts::PlatformVerifier => {
162                return Err(ComponentError::Download {
163                    url: url.to_owned(),
164                    message: "RootCerts::PlatformVerifier requires the `platform-verifier` feature of \
165                              alef-component-runtime"
166                        .to_owned(),
167                });
168            }
169        };
170        Ok(ureq::tls::TlsConfig::builder().root_certs(roots).build())
171    }
172
173    pub(crate) fn is_cancelled(&self) -> bool {
174        self.cancel.as_ref().is_some_and(|flag| flag.load(Ordering::Relaxed))
175    }
176
177    pub(crate) fn report(&self, downloaded: u64, total: u64) {
178        if let Some(progress) = &self.progress {
179            progress(downloaded, total);
180        }
181    }
182
183    /// Delay to wait after failed attempt number `attempt` (1-based).
184    pub(crate) fn backoff_delay(&self, attempt: u32) -> Duration {
185        self.retry_backoff
186            .saturating_mul(1_u32 << attempt.saturating_sub(1).min(16))
187    }
188}
189
190/// Whether an HTTP status is worth retrying.
191/// The local path a `file:` URL names, or `None` for any other scheme.
192///
193/// Parsed as a URL rather than by stripping `file://`: percent-escapes are decoded
194/// (`file:///tmp/a%20b` is `/tmp/a b`), and Windows drive and UNC forms
195/// (`file:///C:/cache/x.tar.gz`, `file://server/share/x.tar.gz`) become real Windows paths. A URL
196/// naming a remote host on Unix is refused rather than read as a local path.
197pub(crate) fn local_file_url(url: &str) -> Option<Result<PathBuf, ComponentError>> {
198    let scheme = url.split_once(':')?.0;
199    if !scheme.eq_ignore_ascii_case("file") {
200        return None;
201    }
202    let invalid = || ComponentError::Download {
203        url: url.to_owned(),
204        message: "not a local file URL".to_owned(),
205    };
206    Some(
207        url::Url::parse(url)
208            .map_err(|_| invalid())
209            .and_then(|parsed| parsed.to_file_path().map_err(|()| invalid())),
210    )
211}
212
213pub(crate) fn is_transient_status(status: u16) -> bool {
214    status >= 500 || status == 408 || status == 429
215}
216
217/// Whether a request-phase failure is worth retrying.
218pub(crate) fn is_transient_request_error(error: &ureq::Error) -> bool {
219    match error {
220        ureq::Error::StatusCode(status) => is_transient_status(*status),
221        ureq::Error::Io(_)
222        | ureq::Error::Timeout(_)
223        | ureq::Error::ConnectionFailed
224        | ureq::Error::HostNotFound
225        | ureq::Error::BodyStalled => true,
226        _ => false,
227    }
228}
229
230/// Wraps a body reader and remembers whether the underlying read failed, so a broken
231/// connection (retryable) can be told apart from a local write or integrity failure.
232pub(crate) struct TrackedReader<R> {
233    inner: R,
234    pub(crate) read_failed: bool,
235}
236
237impl<R> TrackedReader<R> {
238    pub(crate) fn new(inner: R) -> Self {
239        Self {
240            inner,
241            read_failed: false,
242        }
243    }
244}
245
246impl<R: std::io::Read> std::io::Read for TrackedReader<R> {
247    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
248        self.inner.read(buf).inspect_err(|_| self.read_failed = true)
249    }
250}
251
252#[cfg(test)]
253mod tests {
254    use super::*;
255
256    #[test]
257    fn non_file_urls_are_not_local() {
258        assert!(local_file_url("https://example.invalid/x.tar.gz").is_none());
259        assert!(local_file_url("no-scheme").is_none());
260    }
261
262    /// Regression: `file://` was stripped as a prefix, so escapes stayed encoded and Windows URLs
263    /// (`file:///C:/...`) became the path `/C:/...`.
264    #[cfg(unix)]
265    #[test]
266    fn unix_file_urls_decode_escapes_and_refuse_remote_hosts() {
267        assert_eq!(
268            local_file_url("file:///tmp/a%20b/x.tar.gz").unwrap().unwrap(),
269            PathBuf::from("/tmp/a b/x.tar.gz")
270        );
271        assert_eq!(
272            local_file_url("FILE:///tmp/x.tar.gz").unwrap().unwrap(),
273            PathBuf::from("/tmp/x.tar.gz")
274        );
275        assert!(matches!(
276            local_file_url("file://mirror.example/share/x.tar.gz"),
277            Some(Err(ComponentError::Download { .. }))
278        ));
279    }
280
281    #[cfg(windows)]
282    #[test]
283    fn windows_file_urls_become_drive_and_unc_paths() {
284        assert_eq!(
285            local_file_url("file:///C:/cache/a%20b/x.tar.gz").unwrap().unwrap(),
286            PathBuf::from(r"C:\cache\a b\x.tar.gz")
287        );
288        assert_eq!(
289            local_file_url("file://server/share/x.tar.gz").unwrap().unwrap(),
290            PathBuf::from(r"\\server\share\x.tar.gz")
291        );
292    }
293
294    #[test]
295    fn defaults_preserve_historical_timeouts() {
296        let options = DownloadOptions::default();
297        assert_eq!(options.connect_timeout, Duration::from_secs(10));
298        assert_eq!(options.total_timeout, Duration::from_secs(300));
299        assert_eq!(options.max_attempts, 3);
300    }
301
302    #[test]
303    fn only_server_and_throttle_statuses_are_transient() {
304        for status in [500, 502, 503, 504, 408, 429] {
305            assert!(is_transient_status(status), "{status}");
306        }
307        for status in [400, 401, 403, 404, 410] {
308            assert!(!is_transient_status(status), "{status}");
309        }
310    }
311
312    #[test]
313    fn request_errors_are_classified() {
314        assert!(is_transient_request_error(&ureq::Error::StatusCode(503)));
315        assert!(!is_transient_request_error(&ureq::Error::StatusCode(404)));
316        assert!(is_transient_request_error(&ureq::Error::ConnectionFailed));
317        assert!(is_transient_request_error(&ureq::Error::Io(std::io::Error::other(
318            "reset"
319        ))));
320        assert!(!is_transient_request_error(&ureq::Error::TooManyRedirects));
321    }
322
323    #[test]
324    fn default_root_certs_is_webpki() {
325        assert_eq!(DownloadOptions::default().root_certs, RootCerts::WebPki);
326        assert!(DownloadOptions::default().tls_config("https://example.test").is_ok());
327    }
328
329    #[test]
330    fn platform_verifier_config_matches_feature() {
331        let options = DownloadOptions::default().with_root_certs(RootCerts::PlatformVerifier);
332        let result = options.tls_config("https://example.test");
333        if cfg!(feature = "platform-verifier") {
334            assert!(result.is_ok());
335        } else {
336            let error = result.unwrap_err().to_string();
337            assert!(error.contains("platform-verifier"), "{error}");
338        }
339    }
340
341    #[test]
342    fn backoff_doubles_per_attempt() {
343        let options = DownloadOptions::default().with_retry_backoff(Duration::from_millis(100));
344        assert_eq!(options.backoff_delay(1), Duration::from_millis(100));
345        assert_eq!(options.backoff_delay(2), Duration::from_millis(200));
346        assert_eq!(options.backoff_delay(3), Duration::from_millis(400));
347    }
348
349    #[test]
350    fn tracked_reader_records_read_failures() {
351        struct Failing;
352        impl std::io::Read for Failing {
353            fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
354                Err(std::io::Error::other("boom"))
355            }
356        }
357        let mut reader = TrackedReader::new(Failing);
358        assert!(std::io::Read::read(&mut reader, &mut [0; 4]).is_err());
359        assert!(reader.read_failed);
360    }
361}