1use crate::ComponentError;
5use std::fmt;
6use std::path::PathBuf;
7use std::sync::Arc;
8use std::sync::atomic::{AtomicBool, Ordering};
9use std::time::Duration;
10
11pub const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
13pub const DEFAULT_TOTAL_TIMEOUT: Duration = Duration::from_secs(300);
15pub const DEFAULT_MAX_ATTEMPTS: u32 = 3;
17pub const DEFAULT_RETRY_BACKOFF: Duration = Duration::from_millis(500);
19
20pub type ProgressCallback = Arc<dyn Fn(u64, u64) + Send + Sync>;
23
24#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
34pub enum RootCerts {
35 #[default]
37 WebPki,
38 PlatformVerifier,
40}
41
42#[derive(Clone)]
62#[non_exhaustive]
63pub struct DownloadOptions {
64 pub connect_timeout: Duration,
65 pub total_timeout: Duration,
66 pub progress: Option<ProgressCallback>,
67 pub cancel: Option<Arc<AtomicBool>>,
70 pub max_attempts: u32,
72 pub retry_backoff: Duration,
74 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 #[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 #[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 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
190pub(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
217pub(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
230pub(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 #[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}