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