alef_component_runtime/
download.rs1use crate::ComponentError;
5use std::fmt;
6use std::sync::Arc;
7use std::sync::atomic::{AtomicBool, Ordering};
8use std::time::Duration;
9
10pub const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
12pub const DEFAULT_TOTAL_TIMEOUT: Duration = Duration::from_secs(300);
14pub const DEFAULT_MAX_ATTEMPTS: u32 = 3;
16pub const DEFAULT_RETRY_BACKOFF: Duration = Duration::from_millis(500);
18
19pub type ProgressCallback = Arc<dyn Fn(u64, u64) + Send + Sync>;
22
23#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
33pub enum RootCerts {
34 #[default]
36 WebPki,
37 PlatformVerifier,
39}
40
41#[derive(Clone)]
61#[non_exhaustive]
62pub struct DownloadOptions {
63 pub connect_timeout: Duration,
64 pub total_timeout: Duration,
65 pub progress: Option<ProgressCallback>,
66 pub cancel: Option<Arc<AtomicBool>>,
69 pub max_attempts: u32,
71 pub retry_backoff: Duration,
73 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 #[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 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 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
186pub(crate) fn is_transient_status(status: u16) -> bool {
188 status >= 500 || status == 408 || status == 429
189}
190
191pub(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
204pub(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}