use crate::ComponentError;
use std::fmt;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
pub const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
pub const DEFAULT_TOTAL_TIMEOUT: Duration = Duration::from_secs(300);
pub const DEFAULT_MAX_ATTEMPTS: u32 = 3;
pub const DEFAULT_RETRY_BACKOFF: Duration = Duration::from_millis(500);
pub type ProgressCallback = Arc<dyn Fn(u64, u64) + Send + Sync>;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum RootCerts {
#[default]
WebPki,
PlatformVerifier,
}
#[derive(Clone)]
#[non_exhaustive]
pub struct DownloadOptions {
pub connect_timeout: Duration,
pub total_timeout: Duration,
pub progress: Option<ProgressCallback>,
pub cancel: Option<Arc<AtomicBool>>,
pub max_attempts: u32,
pub retry_backoff: Duration,
pub root_certs: RootCerts,
}
impl Default for DownloadOptions {
fn default() -> Self {
Self {
connect_timeout: DEFAULT_CONNECT_TIMEOUT,
total_timeout: DEFAULT_TOTAL_TIMEOUT,
progress: None,
cancel: None,
max_attempts: DEFAULT_MAX_ATTEMPTS,
retry_backoff: DEFAULT_RETRY_BACKOFF,
root_certs: RootCerts::default(),
}
}
}
impl fmt::Debug for DownloadOptions {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DownloadOptions")
.field("connect_timeout", &self.connect_timeout)
.field("total_timeout", &self.total_timeout)
.field("progress", &self.progress.as_ref().map(|_| "<callback>"))
.field("cancel", &self.cancel)
.field("max_attempts", &self.max_attempts)
.field("retry_backoff", &self.retry_backoff)
.field("root_certs", &self.root_certs)
.finish()
}
}
impl DownloadOptions {
#[must_use]
pub fn with_connect_timeout(mut self, timeout: Duration) -> Self {
self.connect_timeout = timeout;
self
}
#[must_use]
pub fn with_total_timeout(mut self, timeout: Duration) -> Self {
self.total_timeout = timeout;
self
}
#[must_use]
pub fn with_progress(mut self, progress: impl Fn(u64, u64) + Send + Sync + 'static) -> Self {
self.progress = Some(Arc::new(progress));
self
}
#[must_use]
pub fn with_cancel(mut self, cancel: Arc<AtomicBool>) -> Self {
self.cancel = Some(cancel);
self
}
#[must_use]
pub fn with_max_attempts(mut self, attempts: u32) -> Self {
self.max_attempts = attempts;
self
}
#[must_use]
pub fn with_retry_backoff(mut self, backoff: Duration) -> Self {
self.retry_backoff = backoff;
self
}
#[must_use]
pub fn with_root_certs(mut self, root_certs: RootCerts) -> Self {
self.root_certs = root_certs;
self
}
#[cfg_attr(
feature = "platform-verifier",
expect(unused_variables, reason = "only the build without the feature reports the URL")
)]
pub(crate) fn tls_config(&self, url: &str) -> Result<ureq::tls::TlsConfig, ComponentError> {
let roots = match self.root_certs {
RootCerts::WebPki => ureq::tls::RootCerts::WebPki,
#[cfg(feature = "platform-verifier")]
RootCerts::PlatformVerifier => ureq::tls::RootCerts::PlatformVerifier,
#[cfg(not(feature = "platform-verifier"))]
RootCerts::PlatformVerifier => {
return Err(ComponentError::Download {
url: url.to_owned(),
message: "RootCerts::PlatformVerifier requires the `platform-verifier` feature of \
alef-component-runtime"
.to_owned(),
});
}
};
Ok(ureq::tls::TlsConfig::builder().root_certs(roots).build())
}
pub(crate) fn is_cancelled(&self) -> bool {
self.cancel.as_ref().is_some_and(|flag| flag.load(Ordering::Relaxed))
}
pub(crate) fn report(&self, downloaded: u64, total: u64) {
if let Some(progress) = &self.progress {
progress(downloaded, total);
}
}
pub(crate) fn backoff_delay(&self, attempt: u32) -> Duration {
self.retry_backoff
.saturating_mul(1_u32 << attempt.saturating_sub(1).min(16))
}
}
pub(crate) fn local_file_url(url: &str) -> Option<Result<PathBuf, ComponentError>> {
let scheme = url.split_once(':')?.0;
if !scheme.eq_ignore_ascii_case("file") {
return None;
}
let invalid = || ComponentError::Download {
url: url.to_owned(),
message: "not a local file URL".to_owned(),
};
Some(
url::Url::parse(url)
.map_err(|_| invalid())
.and_then(|parsed| parsed.to_file_path().map_err(|()| invalid())),
)
}
pub(crate) fn is_transient_status(status: u16) -> bool {
status >= 500 || status == 408 || status == 429
}
pub(crate) fn is_transient_request_error(error: &ureq::Error) -> bool {
match error {
ureq::Error::StatusCode(status) => is_transient_status(*status),
ureq::Error::Io(_)
| ureq::Error::Timeout(_)
| ureq::Error::ConnectionFailed
| ureq::Error::HostNotFound
| ureq::Error::BodyStalled => true,
_ => false,
}
}
pub(crate) struct TrackedReader<R> {
inner: R,
pub(crate) read_failed: bool,
}
impl<R> TrackedReader<R> {
pub(crate) fn new(inner: R) -> Self {
Self {
inner,
read_failed: false,
}
}
}
impl<R: std::io::Read> std::io::Read for TrackedReader<R> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
self.inner.read(buf).inspect_err(|_| self.read_failed = true)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn non_file_urls_are_not_local() {
assert!(local_file_url("https://example.invalid/x.tar.gz").is_none());
assert!(local_file_url("no-scheme").is_none());
}
#[cfg(unix)]
#[test]
fn unix_file_urls_decode_escapes_and_refuse_remote_hosts() {
assert_eq!(
local_file_url("file:///tmp/a%20b/x.tar.gz").unwrap().unwrap(),
PathBuf::from("/tmp/a b/x.tar.gz")
);
assert_eq!(
local_file_url("FILE:///tmp/x.tar.gz").unwrap().unwrap(),
PathBuf::from("/tmp/x.tar.gz")
);
assert!(matches!(
local_file_url("file://mirror.example/share/x.tar.gz"),
Some(Err(ComponentError::Download { .. }))
));
}
#[cfg(windows)]
#[test]
fn windows_file_urls_become_drive_and_unc_paths() {
assert_eq!(
local_file_url("file:///C:/cache/a%20b/x.tar.gz").unwrap().unwrap(),
PathBuf::from(r"C:\cache\a b\x.tar.gz")
);
assert_eq!(
local_file_url("file://server/share/x.tar.gz").unwrap().unwrap(),
PathBuf::from(r"\\server\share\x.tar.gz")
);
}
#[test]
fn defaults_preserve_historical_timeouts() {
let options = DownloadOptions::default();
assert_eq!(options.connect_timeout, Duration::from_secs(10));
assert_eq!(options.total_timeout, Duration::from_secs(300));
assert_eq!(options.max_attempts, 3);
}
#[test]
fn only_server_and_throttle_statuses_are_transient() {
for status in [500, 502, 503, 504, 408, 429] {
assert!(is_transient_status(status), "{status}");
}
for status in [400, 401, 403, 404, 410] {
assert!(!is_transient_status(status), "{status}");
}
}
#[test]
fn request_errors_are_classified() {
assert!(is_transient_request_error(&ureq::Error::StatusCode(503)));
assert!(!is_transient_request_error(&ureq::Error::StatusCode(404)));
assert!(is_transient_request_error(&ureq::Error::ConnectionFailed));
assert!(is_transient_request_error(&ureq::Error::Io(std::io::Error::other(
"reset"
))));
assert!(!is_transient_request_error(&ureq::Error::TooManyRedirects));
}
#[test]
fn default_root_certs_is_webpki() {
assert_eq!(DownloadOptions::default().root_certs, RootCerts::WebPki);
assert!(DownloadOptions::default().tls_config("https://example.test").is_ok());
}
#[test]
fn platform_verifier_config_matches_feature() {
let options = DownloadOptions::default().with_root_certs(RootCerts::PlatformVerifier);
let result = options.tls_config("https://example.test");
if cfg!(feature = "platform-verifier") {
assert!(result.is_ok());
} else {
let error = result.unwrap_err().to_string();
assert!(error.contains("platform-verifier"), "{error}");
}
}
#[test]
fn backoff_doubles_per_attempt() {
let options = DownloadOptions::default().with_retry_backoff(Duration::from_millis(100));
assert_eq!(options.backoff_delay(1), Duration::from_millis(100));
assert_eq!(options.backoff_delay(2), Duration::from_millis(200));
assert_eq!(options.backoff_delay(3), Duration::from_millis(400));
}
#[test]
fn tracked_reader_records_read_failures() {
struct Failing;
impl std::io::Read for Failing {
fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
Err(std::io::Error::other("boom"))
}
}
let mut reader = TrackedReader::new(Failing);
assert!(std::io::Read::read(&mut reader, &mut [0; 4]).is_err());
assert!(reader.read_failed);
}
}