Skip to main content

reth_cli_commands/download/
fetch.rs

1use super::{
2    progress::{
3        ArchiveDownloadProgress, DownloadProgress, DownloadRequestLimiter, SharedProgress,
4        SharedProgressWriter,
5    },
6    session::DownloadSession,
7    RETRY_BACKOFF_SECS,
8};
9use eyre::Result;
10use reqwest::{
11    blocking::Client as BlockingClient,
12    header::{HeaderMap, CONTENT_RANGE, RANGE},
13    StatusCode,
14};
15use reth_cli_util::cancellation::CancellationToken;
16use reth_fs_util as fs;
17use std::{
18    any::Any,
19    collections::{BTreeMap, VecDeque},
20    fs::{File, OpenOptions},
21    io::{self, BufWriter, Read, Write},
22    os::unix::fs::FileExt,
23    path::{Path, PathBuf},
24    sync::{
25        atomic::{AtomicBool, AtomicU64, Ordering},
26        Arc, Condvar, Mutex, MutexGuard,
27    },
28    time::{Duration, Instant},
29};
30use tracing::{info, warn};
31use url::Url;
32
33/// Maximum retry attempts for a single download segment.
34const SEGMENT_RETRY_ATTEMPTS: u32 = 3;
35
36/// Minimum archive size that benefits from segmented downloads.
37const SEGMENTED_DOWNLOAD_MIN_FILE_SIZE: u64 = 128 * 1024 * 1024;
38
39/// Piece sizes are large so big downloads do not create too many requests while
40/// still giving multiple workers enough work to do.
41const SEGMENTED_DOWNLOAD_SMALL_PIECE_SIZE: u64 = 32 * 1024 * 1024;
42const SEGMENTED_DOWNLOAD_LARGE_PIECE_SIZE: u64 = 64 * 1024 * 1024;
43
44/// Cap exponential piece retry backoff to avoid overly long stalls.
45const SEGMENTED_DOWNLOAD_MAX_BACKOFF_SECS: u64 = 30;
46
47/// Segmented piece requests should time out quickly enough to recover from slow or stalled
48/// requests.
49const SEGMENTED_DOWNLOAD_REQUEST_TIMEOUT_SECS: u64 = 120;
50
51/// Bytes a piece download buffers before each write to the shared `.part` file.
52///
53/// Filesystems such as ext4 take an exclusive per-inode lock for every buffered write, so many
54/// pieces writing small chunks into one file contend on that lock instead of the disk.
55const SEGMENTED_DOWNLOAD_WRITE_BUFFER_SIZE: usize = 8 * 1024 * 1024;
56
57/// Paths for one downloaded archive and its `.part` file.
58#[derive(Debug, Clone)]
59struct DownloadPaths {
60    /// User-facing archive file name derived from the URL.
61    file_name: String,
62    /// Final path for the completed archive file.
63    final_path: PathBuf,
64    /// Temporary path used while the archive is still downloading.
65    part_path: PathBuf,
66}
67
68impl DownloadPaths {
69    /// Builds the final and partial download paths from the archive URL.
70    fn from_url(url: &str, target_dir: &Path) -> Self {
71        let file_name = Url::parse(url)
72            .ok()
73            .and_then(|u| u.path_segments()?.next_back().map(|s| s.to_string()))
74            .unwrap_or_else(|| "snapshot.tar".to_string());
75
76        Self {
77            final_path: target_dir.join(&file_name),
78            part_path: target_dir.join(format!("{file_name}.part")),
79            file_name,
80        }
81    }
82
83    /// Returns the user-facing file name derived from the archive URL.
84    fn file_name(&self) -> &str {
85        &self.file_name
86    }
87
88    /// Returns the final on-disk path for the completed archive.
89    fn final_path(&self) -> &Path {
90        &self.final_path
91    }
92
93    /// Returns the partial download path used while the archive is still in flight.
94    fn part_path(&self) -> &Path {
95        &self.part_path
96    }
97
98    /// Promotes the partial file into the final archive path.
99    fn finalize(&self) -> Result<()> {
100        fs::rename(&self.part_path, &self.final_path)?;
101        Ok(())
102    }
103
104    /// Removes only the partial `.part` file for the current archive.
105    fn cleanup_partial(&self) {
106        let _ = fs::remove_file(&self.part_path);
107    }
108
109    /// Removes both final and partial archive files so a fresh attempt can restart cleanly.
110    fn cleanup_all(&self) {
111        let _ = fs::remove_file(&self.final_path);
112        self.cleanup_partial();
113    }
114}
115
116/// Fetches one archive to disk and chooses sequential or segmented download.
117pub(crate) struct ArchiveFetcher {
118    /// Remote archive URL.
119    url: String,
120    /// On-disk paths used for this archive download.
121    paths: DownloadPaths,
122    /// Shared command-scoped download state.
123    session: DownloadSession,
124    /// Archive size declared by the manifest. `None` trusts the size the server reports.
125    expected_size: Option<u64>,
126}
127
128impl ArchiveFetcher {
129    /// Creates a fetcher for one archive URL under the given target directory.
130    ///
131    /// When `expected_size` is set, the download fails if the server reports any other size.
132    pub(crate) fn new(
133        url: impl Into<String>,
134        target_dir: &Path,
135        session: DownloadSession,
136        expected_size: Option<u64>,
137    ) -> Self {
138        let url = url.into();
139        let paths = DownloadPaths::from_url(&url, target_dir);
140        Self { url, paths, session, expected_size }
141    }
142
143    /// Downloads the archive using the best strategy supported by the remote source.
144    ///
145    /// When `availability` is set, the downloaded bytes are published to it so the archive can
146    /// be read while it downloads. Segmented downloads publish the contiguous prefix as pieces
147    /// land; every other path publishes the whole archive once it is on disk.
148    pub(crate) fn download(
149        &self,
150        download_progress: Option<&mut ArchiveDownloadProgress<'_>>,
151        availability: Option<&ArchiveAvailability>,
152    ) -> Result<DownloadedArchive> {
153        let downloaded = self.download_archive(download_progress, availability)?;
154        if let Some(availability) = availability {
155            availability.complete(&downloaded)?;
156        }
157        Ok(downloaded)
158    }
159
160    /// Downloads the archive, publishing progress to `availability` only on the segmented path.
161    fn download_archive(
162        &self,
163        download_progress: Option<&mut ArchiveDownloadProgress<'_>>,
164        availability: Option<&ArchiveAvailability>,
165    ) -> Result<DownloadedArchive> {
166        if let Some(path) = archive_file_url_path(&self.url)? {
167            let size = fs::metadata(&path)?.len();
168            self.check_total_size(size)?;
169            if !self.quiet() {
170                info!(target: "reth::cli",
171                    file = %path.display(),
172                    size = %DownloadProgress::format_size(size),
173                    "Using local archive"
174                );
175            }
176            return Ok(DownloadedArchive { path, size })
177        }
178
179        let Some(request_limiter) = self.session.request_limiter() else {
180            return self.download_sequential(super::MAX_DOWNLOAD_RETRIES, download_progress)
181        };
182
183        let client = BlockingClient::builder().connect_timeout(Duration::from_secs(30)).build()?;
184        let probe = self.probe(&client)?;
185
186        match choose_fetch_strategy(probe, request_limiter.max_concurrency()) {
187            FetchStrategy::Sequential(reason) => {
188                self.log_sequential_fallback(reason, probe.total_size);
189                self.download_sequential(super::MAX_DOWNLOAD_RETRIES, download_progress)
190            }
191            FetchStrategy::Segmented(plan) => {
192                self.download_segmented(probe.total_size, plan, download_progress, availability)
193            }
194        }
195    }
196
197    /// Removes any archive files created by this fetcher.
198    pub(crate) fn cleanup_downloaded_files(&self) {
199        self.paths.cleanup_all();
200    }
201
202    /// Probes the remote source for file size and HTTP range support.
203    fn probe(&self, client: &BlockingClient) -> Result<RemoteArchiveProbe> {
204        let mut attempt = 1;
205        let probe = loop {
206            let probe = client
207                .get(&self.url)
208                .header(RANGE, "bytes=0-0")
209                .send()
210                .and_then(|response| response.error_for_status());
211            // A transient failure here would permanently downgrade the archive to one stream. CDNs
212            // also answer the first range request for a cold object with the whole file, so a 200
213            // for a file large enough to segment is retried as well.
214            let retry = match &probe {
215                Ok(response) => {
216                    response.status() == StatusCode::OK &&
217                        self.expected_size
218                            .or(response.content_length())
219                            .is_some_and(|size| size >= SEGMENTED_DOWNLOAD_MIN_FILE_SIZE)
220                }
221                Err(_) => true,
222            };
223            if !retry || attempt == SEGMENT_RETRY_ATTEMPTS {
224                break probe
225            }
226            // Closes a full-file response before the backoff instead of leaving it open.
227            drop(probe);
228            std::thread::sleep(self.session.retry_delay(piece_retry_backoff(attempt, false)));
229            attempt += 1;
230        };
231
232        let (supports_ranges, reported_size) = match probe {
233            Ok(response) if response.status() == StatusCode::PARTIAL_CONTENT => {
234                (true, content_range(response.headers()).and_then(|range| range.total))
235            }
236            _ if self.expected_size.is_some() => (false, None),
237            _ => (false, client.head(&self.url).send()?.error_for_status()?.content_length()),
238        };
239        if let Some(size) = reported_size {
240            self.check_total_size(size)?;
241        }
242
243        Ok(RemoteArchiveProbe {
244            total_size: self
245                .expected_size
246                .or(reported_size)
247                .ok_or_else(|| eyre::eyre!("Server did not return file size"))?,
248            supports_ranges,
249        })
250    }
251
252    /// Fails when the server-reported archive size differs from the manifest-declared size.
253    fn check_total_size(&self, total_size: u64) -> Result<()> {
254        if let Some(expected) = self.expected_size &&
255            expected != total_size
256        {
257            eyre::bail!(
258                "Archive size mismatch: manifest declares {expected} bytes, server reported {total_size}"
259            )
260        }
261        Ok(())
262    }
263
264    /// Downloads the archive as a single resumable stream using one request at a time.
265    fn download_sequential(
266        &self,
267        max_download_retries: u32,
268        mut download_progress: Option<&mut ArchiveDownloadProgress<'_>>,
269    ) -> Result<DownloadedArchive> {
270        let quiet = self.quiet();
271
272        if !quiet {
273            info!(target: "reth::cli", file = %self.paths.file_name(), "Connecting to download server");
274        }
275
276        let client = BlockingClient::builder().timeout(Duration::from_secs(30)).build()?;
277        let mut total_size: Option<u64> = None;
278        let mut last_error: Option<eyre::Error> = None;
279
280        let mut attempt = 0;
281        while attempt < max_download_retries {
282            attempt += 1;
283            let existing_size =
284                fs::metadata(self.paths.part_path()).map(|meta| meta.len()).unwrap_or(0);
285
286            if let Some(total) = total_size &&
287                existing_size >= total
288            {
289                return self.finalize_download(total)
290            }
291
292            if attempt > 1 {
293                info!(target: "reth::cli",
294                    file = %self.paths.file_name(),
295                    "Retry attempt {}/{} - resuming from {} bytes",
296                    attempt, max_download_retries, existing_size
297                );
298            }
299
300            let mut request = client.get(&self.url);
301            if existing_size > 0 {
302                request = request.header(RANGE, format!("bytes={existing_size}-"));
303                if !quiet && attempt == 1 {
304                    info!(target: "reth::cli", file = %self.paths.file_name(), "Resuming from {} bytes", existing_size);
305                }
306            }
307
308            let _request_permit = self
309                .session
310                .request_limiter()
311                .map(|limiter| {
312                    limiter.acquire(self.session.progress(), self.session.cancel_token())
313                })
314                .transpose()?;
315
316            let response = match request.send().and_then(|response| response.error_for_status()) {
317                Ok(response) => response,
318                Err(error) => {
319                    last_error = Some(error.into());
320                    if attempt < max_download_retries {
321                        info!(target: "reth::cli",
322                            file = %self.paths.file_name(),
323                            retry_delay = ?self.session.retry_delay(Duration::from_secs(RETRY_BACKOFF_SECS)),
324                            "Download failed, retrying"
325                        );
326                        std::thread::sleep(
327                            self.session.retry_delay(Duration::from_secs(RETRY_BACKOFF_SECS)),
328                        );
329                    }
330                    continue;
331                }
332            };
333
334            let is_partial = response.status() == StatusCode::PARTIAL_CONTENT;
335            let range = content_range(response.headers());
336            let size = if is_partial {
337                range.and_then(|range| range.total)
338            } else {
339                response.content_length()
340            };
341            if let Some(size) = size {
342                self.check_total_size(size)?;
343            }
344
345            // Appending a range that starts elsewhere would silently corrupt the `.part` file.
346            let range_start = range.map(|range| range.start);
347            if self.expected_size.is_some() && is_partial && range_start != Some(existing_size) {
348                eyre::bail!(
349                    "Server resumed {} at byte {} instead of requested offset {existing_size}",
350                    self.paths.file_name(),
351                    range_start.map_or_else(|| "unknown".to_string(), |start| start.to_string())
352                )
353            }
354
355            if total_size.is_none() {
356                total_size = self.expected_size.or(size);
357                if !quiet && let Some(size) = size {
358                    info!(target: "reth::cli",
359                        file = %self.paths.file_name(),
360                        size = %DownloadProgress::format_size(size),
361                        "Downloading"
362                    );
363                }
364            }
365
366            let current_total = total_size.ok_or_else(|| {
367                eyre::eyre!("Server did not provide Content-Length or Content-Range header")
368            })?;
369
370            let file = if is_partial && existing_size > 0 {
371                OpenOptions::new()
372                    .append(true)
373                    .open(self.paths.part_path())
374                    .map_err(|error| fs::FsPathError::open(error, self.paths.part_path()))?
375            } else {
376                fs::create_file(self.paths.part_path())?
377            };
378
379            let start_offset = if is_partial { existing_size } else { 0 };
380            // Without a manifest size, keep the legacy URL path's unbounded copy.
381            let limit =
382                self.expected_size.map_or(u64::MAX, |size| size.saturating_sub(start_offset));
383            let mut reader = response.take(limit);
384
385            let copy_result;
386            let flush_result;
387
388            if let Some(progress) = self.session.progress() {
389                let mut on_written = |bytes| {
390                    if let Some(download_progress) = download_progress.as_deref_mut() {
391                        download_progress.record_downloaded(bytes);
392                    }
393                };
394                let mut writer = SharedProgressWriter {
395                    inner: BufWriter::new(file),
396                    progress: Arc::clone(progress),
397                    on_written: Some(&mut on_written),
398                };
399                copy_result = io::copy(&mut reader, &mut writer);
400                flush_result = writer.inner.flush();
401            } else {
402                let mut progress = DownloadProgress::new(current_total);
403                progress.downloaded = start_offset;
404                let mut writer = ProgressWriter {
405                    inner: BufWriter::new(file),
406                    progress,
407                    cancel_token: self.session.cancel_token().clone(),
408                };
409                copy_result = io::copy(&mut reader, &mut writer);
410                flush_result = writer.inner.flush();
411                println!();
412            }
413
414            if let Err(error) = copy_result.and(flush_result) {
415                last_error = Some(error.into());
416                if attempt < max_download_retries {
417                    info!(target: "reth::cli",
418                        file = %self.paths.file_name(),
419                        retry_delay = ?self.session.retry_delay(Duration::from_secs(RETRY_BACKOFF_SECS)),
420                        "Download interrupted, retrying"
421                    );
422                    std::thread::sleep(
423                        self.session.retry_delay(Duration::from_secs(RETRY_BACKOFF_SECS)),
424                    );
425                }
426                continue;
427            }
428
429            let downloaded = fs::metadata(self.paths.part_path())?.len();
430            if self.expected_size.is_some() && downloaded < current_total {
431                // A server may cap open-ended ranges. Only attempts without progress use retries.
432                if downloaded > existing_size {
433                    attempt -= 1;
434                }
435                last_error = Some(eyre::eyre!(
436                    "Download of {} ended at {downloaded} of {current_total} bytes",
437                    self.paths.file_name()
438                ));
439                continue;
440            }
441
442            return self.finalize_download(current_total)
443        }
444
445        Err(last_error.unwrap_or_else(|| {
446            eyre::eyre!("Download failed after {} attempts", max_download_retries)
447        }))
448    }
449
450    /// Downloads the archive by splitting it into large range-request pieces.
451    fn download_segmented(
452        &self,
453        total_size: u64,
454        plan: SegmentedDownloadPlan,
455        download_progress: Option<&mut ArchiveDownloadProgress<'_>>,
456        availability: Option<&ArchiveAvailability>,
457    ) -> Result<DownloadedArchive> {
458        let request_limiter = self.session.require_request_limiter()?;
459        info!(target: "reth::cli",
460            total_size = %DownloadProgress::format_size(total_size),
461            piece_size = %DownloadProgress::format_size(plan.piece_size),
462            pieces = plan.piece_count,
463            workers = plan.worker_count,
464            max_concurrent_requests = request_limiter.max_concurrency(),
465            "Starting queued segmented download"
466        );
467
468        SegmentedDownload::new(
469            self.url.clone(),
470            self.paths.clone(),
471            total_size,
472            plan,
473            self.session.clone(),
474            download_progress,
475        )
476        .run(availability)
477    }
478
479    /// Logs why this archive must fall back to the sequential fetch path.
480    fn log_sequential_fallback(&self, reason: SequentialDownloadFallback, total_size: u64) {
481        match reason {
482            SequentialDownloadFallback::NoRangeSupport => {
483                info!(target: "reth::cli",
484                    file = %self.paths.file_name(),
485                    "Server does not support Range requests, falling back to sequential download"
486                );
487            }
488            SequentialDownloadFallback::EmptyFile => {
489                info!(target: "reth::cli",
490                    file = %self.paths.file_name(),
491                    "Remote archive is empty, falling back to sequential download"
492                );
493            }
494            SequentialDownloadFallback::TooSmall => {
495                let _ = total_size;
496            }
497        }
498    }
499
500    /// Finalizes the downloaded archive and returns its on-disk location and size.
501    ///
502    /// Fails when the `.part` file does not hold exactly the manifest-declared size, if present.
503    fn finalize_download(&self, size: u64) -> Result<DownloadedArchive> {
504        if let Some(expected) = self.expected_size &&
505            let downloaded = fs::metadata(self.paths.part_path())?.len() &&
506            downloaded != expected
507        {
508            eyre::bail!(
509                "Downloaded {} has {downloaded} bytes, expected {expected}",
510                self.paths.file_name()
511            )
512        }
513        self.paths.finalize()?;
514        if !self.quiet() {
515            info!(target: "reth::cli", file = %self.paths.file_name(), "Download complete");
516        }
517        Ok(DownloadedArchive { path: self.paths.final_path().to_path_buf(), size })
518    }
519
520    /// Returns `true` when this fetch should stay quiet because shared progress is active.
521    fn quiet(&self) -> bool {
522        self.session.progress().is_some()
523    }
524}
525
526/// The parsed `Content-Range` header of a byte-range response.
527#[derive(Debug, Clone, Copy, PartialEq, Eq)]
528struct ContentRange {
529    /// First byte of the range in the archive.
530    start: u64,
531    /// Last byte of the range in the archive, inclusive.
532    end: u64,
533    /// Total archive size, or `None` when the server sends `*`.
534    total: Option<u64>,
535}
536
537/// Parses a `bytes <start>-<end>/<total>` `Content-Range` header, with a case-insensitive unit.
538///
539/// Returns `None` when the header is missing or malformed: a bad number, `start > end`, or
540/// `end >= total`. Only a literal `*` total means the size is unknown.
541fn content_range(headers: &HeaderMap) -> Option<ContentRange> {
542    let value = headers.get(CONTENT_RANGE)?.to_str().ok()?.trim();
543    let (unit, range) = value.split_once(' ')?;
544    if !unit.eq_ignore_ascii_case("bytes") {
545        return None
546    }
547    let (range, total) = range.trim().split_once('/')?;
548    let (start, end) = range.split_once('-')?;
549    let (start, end) = (start.trim().parse().ok()?, end.trim().parse().ok()?);
550    let total = match total.trim() {
551        "*" => None,
552        total => Some(total.parse().ok()?),
553    };
554    (start <= end && total.is_none_or(|total| end < total)).then_some(ContentRange {
555        start,
556        end,
557        total,
558    })
559}
560
561/// Resolves a `file://` archive URL to its local path.
562fn archive_file_url_path(url: &str) -> Result<Option<PathBuf>> {
563    let Ok(parsed) = Url::parse(url) else { return Ok(None) };
564    if parsed.scheme() != "file" {
565        return Ok(None)
566    }
567
568    parsed
569        .to_file_path()
570        .map(Some)
571        .map_err(|_| eyre::eyre!("Invalid file:// archive URL path: {url}"))
572}
573
574/// The final path and size of one archive fetched to disk.
575#[derive(Debug, Clone)]
576pub(crate) struct DownloadedArchive {
577    /// Final on-disk path for the downloaded archive.
578    pub(crate) path: PathBuf,
579    /// Total archive size in bytes.
580    pub(crate) size: u64,
581}
582
583/// The prefix of an archive that a fetch has written to disk, so extraction can read the
584/// archive while it is still downloading.
585#[derive(Default)]
586pub(crate) struct ArchiveAvailability {
587    /// Current fetch state.
588    state: Mutex<AvailabilityState>,
589    /// Wakes readers when the state changes.
590    changed: Condvar,
591}
592
593/// Fetch state shared between one archive download and its reader.
594#[derive(Default)]
595enum AvailabilityState {
596    /// The fetch has not opened the archive file yet.
597    #[default]
598    Pending,
599    /// The first `available` of `total` bytes of `file` are written.
600    Open {
601        /// Archive file, shared with readers so a later rename or delete does not affect them.
602        file: Arc<File>,
603        /// Length of the written prefix.
604        available: u64,
605        /// Total archive size.
606        total: u64,
607    },
608    /// No more bytes will arrive, because the fetch or the reader failed.
609    Aborted,
610}
611
612impl ArchiveAvailability {
613    /// Shares the archive file once it is created, with nothing written yet.
614    fn open(&self, file: File, total: u64) {
615        let mut state = self.lock();
616        if !matches!(*state, AvailabilityState::Aborted) {
617            *state = AvailabilityState::Open { file: Arc::new(file), available: 0, total };
618            self.changed.notify_all();
619        }
620    }
621
622    /// Publishes that the first `len` bytes are written. The prefix never shrinks.
623    fn publish(&self, len: u64) {
624        let mut state = self.lock();
625        if let AvailabilityState::Open { available, total, .. } = &mut *state &&
626            len > *available
627        {
628            *available = len.min(*total);
629            self.changed.notify_all();
630        }
631    }
632
633    /// Publishes the whole downloaded archive, opening it if the fetch path never did.
634    fn complete(&self, downloaded: &DownloadedArchive) -> Result<()> {
635        if matches!(*self.lock(), AvailabilityState::Pending) {
636            self.open(fs::open(&downloaded.path)?, downloaded.size);
637        }
638        self.publish(downloaded.size);
639        Ok(())
640    }
641
642    /// Fails readers and stops the fetch because the archive will not complete.
643    ///
644    /// Returns `true` if this call aborted the archive, and `false` if it was already aborted or
645    /// fully published.
646    pub(crate) fn abort(&self) -> bool {
647        let mut state = self.lock();
648        match *state {
649            AvailabilityState::Aborted => false,
650            AvailabilityState::Open { available, total, .. } if available == total => false,
651            _ => {
652                *state = AvailabilityState::Aborted;
653                self.changed.notify_all();
654                true
655            }
656        }
657    }
658
659    /// Returns a guard that aborts this availability when dropped, so a reader never blocks
660    /// after the fetch returns early or unwinds.
661    pub(crate) fn abort_on_drop(&self) -> ArchiveAvailabilityAbortGuard<'_> {
662        ArchiveAvailabilityAbortGuard(self)
663    }
664
665    /// Returns whether the archive was aborted.
666    fn is_aborted(&self) -> bool {
667        matches!(*self.lock(), AvailabilityState::Aborted)
668    }
669
670    /// Blocks until bytes past `position` are written, then returns the file and the written
671    /// length, which equals `position` only at the end of the archive.
672    fn wait_past(&self, position: u64) -> io::Result<(Arc<File>, u64)> {
673        let mut state = self.lock();
674        loop {
675            match &*state {
676                AvailabilityState::Aborted => {
677                    return Err(io::Error::other("archive download stopped before completing"))
678                }
679                AvailabilityState::Open { file, available, total }
680                    if *available > position || available == total =>
681                {
682                    return Ok((Arc::clone(file), *available))
683                }
684                _ => state = self.changed.wait(state).unwrap_or_else(|e| e.into_inner()),
685            }
686        }
687    }
688
689    fn lock(&self) -> MutexGuard<'_, AvailabilityState> {
690        self.state.lock().unwrap_or_else(|e| e.into_inner())
691    }
692}
693
694/// Aborts an [`ArchiveAvailability`] when dropped.
695pub(crate) struct ArchiveAvailabilityAbortGuard<'a>(&'a ArchiveAvailability);
696
697impl Drop for ArchiveAvailabilityAbortGuard<'_> {
698    fn drop(&mut self) {
699        self.0.abort();
700    }
701}
702
703/// Reads the published prefix of an archive, blocking at its end until more is written.
704pub(crate) struct ArchiveAvailabilityReader<'a> {
705    /// Availability published by the fetch.
706    availability: &'a ArchiveAvailability,
707    /// Next archive offset to read.
708    position: u64,
709}
710
711impl<'a> ArchiveAvailabilityReader<'a> {
712    /// Creates a reader starting at the beginning of the archive.
713    pub(crate) const fn new(availability: &'a ArchiveAvailability) -> Self {
714        Self { availability, position: 0 }
715    }
716}
717
718impl Read for ArchiveAvailabilityReader<'_> {
719    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
720        if buf.is_empty() {
721            return Ok(0)
722        }
723
724        let (file, available) = self.availability.wait_past(self.position)?;
725        let readable = usize::try_from(available - self.position).unwrap_or(usize::MAX);
726        if readable == 0 {
727            return Ok(0)
728        }
729
730        let len = buf.len().min(readable);
731        let read = file.read_at(&mut buf[..len], self.position)?;
732        if read == 0 {
733            return Err(io::Error::new(
734                io::ErrorKind::UnexpectedEof,
735                "archive is shorter than its published length",
736            ))
737        }
738        self.position += read as u64;
739        Ok(read)
740    }
741}
742
743/// Remote metadata used to choose between sequential and segmented download.
744#[derive(Debug, Clone, Copy)]
745struct RemoteArchiveProbe {
746    /// Total archive size reported by the remote source.
747    total_size: u64,
748    /// Whether the remote source supports byte-range requests.
749    supports_ranges: bool,
750}
751
752/// Reasons the fetcher may choose the sequential download path.
753#[derive(Debug, Clone, Copy, PartialEq, Eq)]
754enum SequentialDownloadFallback {
755    /// The remote source does not support byte-range requests.
756    NoRangeSupport,
757    /// The remote source reported an empty archive.
758    EmptyFile,
759    /// The archive is too small to benefit from segmented download.
760    TooSmall,
761}
762
763/// The fetch strategy chosen after probing the remote source.
764#[derive(Debug)]
765enum FetchStrategy {
766    /// Use the single-stream download path.
767    Sequential(SequentialDownloadFallback),
768    /// Use the segmented download path.
769    Segmented(SegmentedDownloadPlan),
770}
771
772/// Chooses the fetch strategy from the remote probe and available worker budget.
773fn choose_fetch_strategy(probe: RemoteArchiveProbe, max_workers: usize) -> FetchStrategy {
774    if !probe.supports_ranges {
775        return FetchStrategy::Sequential(SequentialDownloadFallback::NoRangeSupport)
776    }
777
778    if probe.total_size == 0 {
779        return FetchStrategy::Sequential(SequentialDownloadFallback::EmptyFile)
780    }
781
782    plan_segmented_download(probe.total_size, max_workers)
783        .map(FetchStrategy::Segmented)
784        .unwrap_or(FetchStrategy::Sequential(SequentialDownloadFallback::TooSmall))
785}
786
787/// Wrapper that tracks download progress while writing data.
788/// Used with [`io::copy`] to display progress during downloads.
789struct ProgressWriter<W> {
790    /// Wrapped writer receiving downloaded bytes.
791    inner: W,
792    /// Per-download progress tracker for the legacy path.
793    progress: DownloadProgress,
794    /// Cancellation token checked between writes.
795    cancel_token: CancellationToken,
796}
797
798impl<W: Write> Write for ProgressWriter<W> {
799    /// Writes bytes, checks cancellation, and updates local download progress.
800    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
801        if self.cancel_token.is_cancelled() {
802            return Err(io::Error::new(io::ErrorKind::Interrupted, "download cancelled"));
803        }
804        let n = self.inner.write(buf)?;
805        let _ = self.progress.update(n as u64);
806        Ok(n)
807    }
808
809    /// Flushes the wrapped writer.
810    fn flush(&mut self) -> io::Result<()> {
811        self.inner.flush()
812    }
813}
814
815/// One queued byte range for a segmented archive download.
816#[derive(Debug, Clone, Copy, PartialEq, Eq)]
817struct DownloadPiece {
818    /// Inclusive start byte for this piece.
819    start: u64,
820    /// Inclusive end byte for this piece.
821    end: u64,
822}
823
824/// Fixed plan for a segmented archive: piece size, piece count, and worker count.
825#[derive(Debug)]
826struct SegmentedDownloadPlan {
827    /// Bytes assigned to each piece, except possibly the last.
828    piece_size: u64,
829    /// Number of pieces created for this archive.
830    piece_count: usize,
831    /// Number of worker threads used for this archive.
832    worker_count: usize,
833    /// Queue of pieces to download.
834    pieces: VecDeque<DownloadPiece>,
835}
836
837/// Runs the segmented download workers and piece retries for one archive.
838struct SegmentedDownload {
839    /// Remote archive URL.
840    url: String,
841    /// On-disk paths used for this archive download.
842    paths: DownloadPaths,
843    /// Total archive size in bytes.
844    total_size: u64,
845    /// Piece and worker plan for this archive.
846    plan: SegmentedDownloadPlan,
847    /// Shared command-scoped download state.
848    session: DownloadSession,
849}
850
851/// Shared inputs each segmented download worker needs while draining the piece queue.
852#[derive(Clone, Copy)]
853struct SegmentedWorkerContext<'a> {
854    /// Remote archive URL.
855    url: &'a str,
856    /// Partial file path where pieces are written.
857    part_path: &'a Path,
858    /// Shared progress counters for the whole command, when enabled.
859    shared: Option<&'a Arc<SharedProgress>>,
860    /// Shared cap for in-flight HTTP requests.
861    request_limiter: &'a DownloadRequestLimiter,
862    /// Cancellation token shared by the whole command.
863    cancel_token: &'a CancellationToken,
864    /// Session carrying the retry-delay override.
865    session: &'a DownloadSession,
866    /// Receives the contiguous downloaded prefix, when the archive is read while downloading.
867    availability: Option<&'a ArchiveAvailability>,
868}
869
870impl SegmentedWorkerContext<'_> {
871    /// Returns why workers must stop: the command was cancelled, or the archive reader aborted.
872    fn stop_error(&self) -> Option<eyre::Error> {
873        if self.cancel_token.is_cancelled() {
874            return Some(eyre::eyre!("Download cancelled"))
875        }
876        self.availability
877            .is_some_and(ArchiveAvailability::is_aborted)
878            .then(|| eyre::eyre!("Archive reader stopped before the download completed"))
879    }
880
881    /// Sleeps for `delay`, waking every 100ms to return early once workers must stop.
882    fn backoff(&self, delay: Duration) {
883        let deadline = Instant::now() + delay;
884        while self.stop_error().is_none() {
885            let remaining = deadline.saturating_duration_since(Instant::now());
886            if remaining.is_zero() {
887                return
888            }
889            std::thread::sleep(remaining.min(Duration::from_millis(100)));
890        }
891    }
892}
893
894impl SegmentedDownload {
895    /// Creates the segmented download state for one archive.
896    fn new(
897        url: String,
898        paths: DownloadPaths,
899        total_size: u64,
900        plan: SegmentedDownloadPlan,
901        session: DownloadSession,
902        _download_progress: Option<&mut ArchiveDownloadProgress<'_>>,
903    ) -> Self {
904        Self { url, paths, total_size, plan, session }
905    }
906
907    /// Runs the segmented download to completion or returns the first fatal error.
908    ///
909    /// Publishes the contiguous downloaded prefix to `availability` as pieces land, and stops
910    /// early once `availability` is aborted.
911    fn run(self, availability: Option<&ArchiveAvailability>) -> Result<DownloadedArchive> {
912        let Self { url, paths, total_size, plan, session } = self;
913        {
914            let file = fs::create_file(paths.part_path())?;
915            file.set_len(total_size)?;
916        }
917        if let Some(availability) = availability {
918            availability.open(fs::open(paths.part_path())?, total_size);
919        }
920
921        let worker_count = plan.worker_count;
922        let state = Arc::new(SegmentedDownloadState::new(plan.pieces));
923        let terminal_failure = Arc::new(TerminalFailure::default());
924        let piece_progress_bytes = Arc::new(AtomicU64::new(0));
925        let worker_client = BlockingClient::builder()
926            .connect_timeout(Duration::from_secs(30))
927            .timeout(Duration::from_secs(SEGMENTED_DOWNLOAD_REQUEST_TIMEOUT_SECS))
928            .build()?;
929        let request_limiter = Arc::clone(session.require_request_limiter()?);
930        let shared = session.progress();
931        let cancel_token = session.cancel_token();
932        let url = url.as_str();
933        let worker_context = SegmentedWorkerContext {
934            url,
935            part_path: paths.part_path(),
936            session: &session,
937            shared,
938            request_limiter: request_limiter.as_ref(),
939            cancel_token,
940            availability,
941        };
942
943        std::thread::scope(|scope| {
944            let mut handles = Vec::with_capacity(worker_count);
945
946            for _ in 0..worker_count {
947                let state = Arc::clone(&state);
948                let terminal_failure = Arc::clone(&terminal_failure);
949                let piece_progress_bytes = Arc::clone(&piece_progress_bytes);
950                let client = worker_client.clone();
951
952                handles.push(scope.spawn(move || {
953                    Self::worker_loop(
954                        &client,
955                        worker_context,
956                        state,
957                        terminal_failure,
958                        piece_progress_bytes,
959                    );
960                }));
961            }
962
963            for handle in handles {
964                if let Err(payload) = handle.join() {
965                    state.note_terminal_failure();
966                    terminal_failure.record(eyre::eyre!(
967                        "Segmented download worker panicked: {}",
968                        panic_payload_message(payload)
969                    ));
970                }
971            }
972        });
973
974        // Workers that stop between pieces exit without recording an error, so the file may be
975        // incomplete even when no worker failed.
976        let error = terminal_failure.take().or_else(|| worker_context.stop_error());
977        if let Some(error) = error {
978            if let Some(shared) = shared {
979                shared.sub_active_download_bytes(piece_progress_bytes.load(Ordering::Relaxed));
980            }
981            paths.cleanup_partial();
982            return Err(error.wrap_err("Parallel download failed"))
983        }
984
985        if let Some(shared) = shared {
986            shared.sub_active_download_bytes(piece_progress_bytes.load(Ordering::Relaxed));
987            shared.record_archive_download_complete(total_size);
988        }
989
990        paths.finalize()?;
991        info!(target: "reth::cli", file = %paths.file_name(), "Download complete");
992        Ok(DownloadedArchive { path: paths.final_path().to_path_buf(), size: total_size })
993    }
994
995    /// Runs one worker until there are no pieces left or another worker fails.
996    fn worker_loop(
997        client: &BlockingClient,
998        context: SegmentedWorkerContext<'_>,
999        state: Arc<SegmentedDownloadState>,
1000        terminal_failure: Arc<TerminalFailure>,
1001        piece_progress_bytes: Arc<AtomicU64>,
1002    ) {
1003        let file = match OpenOptions::new().write(true).open(context.part_path) {
1004            Ok(file) => file,
1005            Err(error) => {
1006                state.note_terminal_failure();
1007                terminal_failure.record(error.into());
1008                return;
1009            }
1010        };
1011
1012        while !context.availability.is_some_and(ArchiveAvailability::is_aborted) &&
1013            let Some(piece) = state.next_piece(context.cancel_token)
1014        {
1015            match Self::download_piece_with_retries(
1016                client,
1017                context,
1018                &file,
1019                piece,
1020                &piece_progress_bytes,
1021            ) {
1022                Ok(()) => {
1023                    let prefix = state.complete(piece);
1024                    if let Some(availability) = context.availability {
1025                        availability.publish(prefix);
1026                    }
1027                }
1028                Err(PieceAttemptFailure::Retryable { error, .. }) if state.requeue(piece) => {
1029                    warn!(target: "reth::cli",
1030                        start = piece.start,
1031                        end = piece.end,
1032                        %error,
1033                        "Piece download failed, requeued"
1034                    );
1035                }
1036                Err(
1037                    PieceAttemptFailure::Retryable { error, .. } |
1038                    PieceAttemptFailure::Terminal(error),
1039                ) => {
1040                    state.note_terminal_failure();
1041                    terminal_failure.record(error);
1042                    return;
1043                }
1044            }
1045        }
1046    }
1047
1048    /// Downloads one queued piece with per-piece retry/backoff.
1049    ///
1050    /// Each attempt acquires a permit from the shared request limit so whole-file and
1051    /// piece downloads use the same fixed number of HTTP request slots. Stops between attempts,
1052    /// and during backoff, once the download is cancelled or the archive reader aborts.
1053    fn download_piece_with_retries(
1054        client: &BlockingClient,
1055        context: SegmentedWorkerContext<'_>,
1056        file: &std::fs::File,
1057        piece: DownloadPiece,
1058        piece_progress_bytes: &AtomicU64,
1059    ) -> std::result::Result<(), PieceAttemptFailure> {
1060        let SegmentedWorkerContext { url, shared, request_limiter, cancel_token, session, .. } =
1061            context;
1062        for attempt in 1..=SEGMENT_RETRY_ATTEMPTS {
1063            if let Some(error) = context.stop_error() {
1064                return Err(PieceAttemptFailure::Terminal(error))
1065            }
1066
1067            let _request_permit = request_limiter
1068                .acquire(shared, cancel_token)
1069                .map_err(PieceAttemptFailure::Terminal)?;
1070            match Self::download_piece_once(
1071                client,
1072                url,
1073                file,
1074                piece,
1075                shared,
1076                piece_progress_bytes,
1077                cancel_token,
1078            ) {
1079                Ok(()) => return Ok(()),
1080                Err(PieceAttemptFailure::Retryable { error: _, throttled })
1081                    if attempt < SEGMENT_RETRY_ATTEMPTS =>
1082                {
1083                    context.backoff(session.retry_delay(piece_retry_backoff(attempt, throttled)));
1084                }
1085                Err(failure) => return Err(failure),
1086            }
1087        }
1088
1089        Err(PieceAttemptFailure::Terminal(eyre::eyre!(
1090            "Piece download failed after {SEGMENT_RETRY_ATTEMPTS} attempts"
1091        )))
1092    }
1093
1094    /// Downloads one queued piece once.
1095    fn download_piece_once(
1096        client: &BlockingClient,
1097        url: &str,
1098        file: &std::fs::File,
1099        piece: DownloadPiece,
1100        shared: Option<&Arc<SharedProgress>>,
1101        piece_progress_bytes: &AtomicU64,
1102        cancel_token: &CancellationToken,
1103    ) -> std::result::Result<(), PieceAttemptFailure> {
1104        let expected_len = piece.end - piece.start + 1;
1105
1106        let response = match client
1107            .get(url)
1108            .header(RANGE, format!("bytes={}-{}", piece.start, piece.end))
1109            .send()
1110        {
1111            Ok(response) if response.status() == StatusCode::PARTIAL_CONTENT => {
1112                // Bytes of another range written at `piece.start` would corrupt the archive.
1113                if content_range(response.headers()).map(|range| (range.start, range.end)) !=
1114                    Some((piece.start, piece.end))
1115                {
1116                    return Err(PieceAttemptFailure::Terminal(eyre::eyre!(
1117                        "Server returned Content-Range {:?} for piece {}-{}",
1118                        response.headers().get(CONTENT_RANGE),
1119                        piece.start,
1120                        piece.end
1121                    )))
1122                }
1123                response
1124            }
1125            Ok(response) if should_retry_piece_status(response.status()) => {
1126                return Err(PieceAttemptFailure::Retryable {
1127                    error: eyre::eyre!(
1128                        "Server returned {} for piece {}-{}",
1129                        response.status(),
1130                        piece.start,
1131                        piece.end
1132                    ),
1133                    throttled: is_throttle_piece_status(response.status()),
1134                });
1135            }
1136            Ok(response) => {
1137                return Err(PieceAttemptFailure::Terminal(eyre::eyre!(
1138                    "Server returned {} instead of 206 for Range request",
1139                    response.status()
1140                )));
1141            }
1142            Err(error) => {
1143                return Err(PieceAttemptFailure::Retryable {
1144                    throttled: is_throttle_piece_error(&error),
1145                    error: error.into(),
1146                });
1147            }
1148        };
1149
1150        let mut buf = vec![0u8; SEGMENTED_DOWNLOAD_WRITE_BUFFER_SIZE];
1151        let mut filled = 0;
1152        let mut reader = response.take(expected_len);
1153        // File offset of `buf[0]`.
1154        let mut offset = piece.start;
1155
1156        loop {
1157            if cancel_token.is_cancelled() {
1158                return Err(PieceAttemptFailure::Terminal(eyre::eyre!("Download cancelled")));
1159            }
1160
1161            match reader.read(&mut buf[filled..]) {
1162                Ok(0) => break,
1163                Ok(n) => {
1164                    filled += n;
1165                    if filled == buf.len() {
1166                        file.write_all_at(&buf, offset)
1167                            .map_err(|error| PieceAttemptFailure::Terminal(error.into()))?;
1168                        offset += filled as u64;
1169                        filled = 0;
1170                    }
1171                    if let Some(progress) = shared {
1172                        progress.record_session_fetched_bytes(n as u64);
1173                    }
1174                }
1175                Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
1176                Err(error) => {
1177                    return Err(PieceAttemptFailure::Retryable {
1178                        throttled: error.kind() == io::ErrorKind::TimedOut,
1179                        error: error.into(),
1180                    });
1181                }
1182            }
1183        }
1184        file.write_all_at(&buf[..filled], offset)
1185            .map_err(|error| PieceAttemptFailure::Terminal(error.into()))?;
1186        offset += filled as u64;
1187
1188        let downloaded_len = offset - piece.start;
1189        if downloaded_len == expected_len {
1190            if let Some(progress) = shared {
1191                progress.add_active_download_bytes(expected_len);
1192            }
1193            piece_progress_bytes.fetch_add(expected_len, Ordering::Relaxed);
1194            return Ok(())
1195        }
1196
1197        Err(PieceAttemptFailure::Retryable {
1198            error: eyre::eyre!(
1199                "Piece {}-{} ended early: expected {} bytes, downloaded {}",
1200                piece.start,
1201                piece.end,
1202                expected_len,
1203                downloaded_len
1204            ),
1205            throttled: false,
1206        })
1207    }
1208}
1209
1210/// Shared queue state for one segmented archive download.
1211///
1212/// Workers pull pieces until the queue is empty or one worker fails the whole attempt.
1213struct SegmentedDownloadState {
1214    /// Remaining pieces waiting to be downloaded.
1215    pieces: Mutex<VecDeque<DownloadPiece>>,
1216    /// Set once a worker hits a fatal error.
1217    failed: AtomicBool,
1218    /// Remaining number of times a piece that exhausted its retries may be requeued.
1219    requeues_left: AtomicU64,
1220    /// Downloaded pieces and the contiguous prefix they form.
1221    completed: Mutex<CompletedPieces>,
1222}
1223
1224/// Downloaded pieces of one segmented archive.
1225#[derive(Default)]
1226struct CompletedPieces {
1227    /// Length of the archive prefix made only of downloaded pieces.
1228    prefix: u64,
1229    /// Exclusive end byte of each downloaded piece past `prefix`, keyed by start byte.
1230    pending: BTreeMap<u64, u64>,
1231}
1232
1233impl SegmentedDownloadState {
1234    /// Creates the shared queue state for one segmented archive attempt.
1235    fn new(pieces: VecDeque<DownloadPiece>) -> Self {
1236        let requeues_left = AtomicU64::new(pieces.len() as u64);
1237        Self {
1238            pieces: Mutex::new(pieces),
1239            failed: AtomicBool::new(false),
1240            requeues_left,
1241            completed: Mutex::default(),
1242        }
1243    }
1244
1245    /// Puts a piece back on the queue, returning `false` once the requeue budget is spent.
1246    ///
1247    /// The piece goes to the front so the contiguous prefix that extraction reads is not held
1248    /// back until the end of the archive.
1249    fn requeue(&self, piece: DownloadPiece) -> bool {
1250        if self
1251            .requeues_left
1252            .try_update(Ordering::Relaxed, Ordering::Relaxed, |left| left.checked_sub(1))
1253            .is_err()
1254        {
1255            return false
1256        }
1257        self.pieces.lock().unwrap().push_front(piece);
1258        true
1259    }
1260
1261    /// Records a downloaded piece and returns the length of the contiguous downloaded prefix.
1262    fn complete(&self, piece: DownloadPiece) -> u64 {
1263        let mut guard = self.completed.lock().unwrap();
1264        let completed = &mut *guard;
1265        completed.pending.insert(piece.start, piece.end + 1);
1266        while let Some(end) = completed.pending.remove(&completed.prefix) {
1267            completed.prefix = end;
1268        }
1269        completed.prefix
1270    }
1271
1272    /// Returns the next piece unless cancellation or a fatal error stopped the attempt.
1273    fn next_piece(&self, cancel_token: &CancellationToken) -> Option<DownloadPiece> {
1274        if cancel_token.is_cancelled() || self.failed.load(Ordering::Relaxed) {
1275            return None;
1276        }
1277
1278        self.pieces.lock().unwrap().pop_front()
1279    }
1280
1281    /// Marks the entire segmented attempt as failed so workers stop taking more pieces.
1282    fn note_terminal_failure(&self) {
1283        self.failed.store(true, Ordering::Relaxed);
1284    }
1285}
1286
1287/// Stores the first fatal error seen across segmented download workers.
1288#[derive(Default)]
1289struct TerminalFailure {
1290    /// First fatal worker error, if any.
1291    error: Mutex<Option<eyre::Error>>,
1292}
1293
1294impl TerminalFailure {
1295    /// Stores the first fatal error and ignores later ones from other workers.
1296    fn record(&self, error: eyre::Error) {
1297        let mut slot = self.error.lock().unwrap();
1298        if slot.is_none() {
1299            *slot = Some(error);
1300        }
1301    }
1302
1303    /// Returns the stored fatal error after worker execution finishes.
1304    fn take(&self) -> Option<eyre::Error> {
1305        self.error.lock().unwrap().take()
1306    }
1307}
1308
1309/// Splits an archive into contiguous byte ranges for segmented download.
1310fn build_download_pieces(total_size: u64, piece_size: u64) -> VecDeque<DownloadPiece> {
1311    let mut pieces = VecDeque::new();
1312    let mut start = 0;
1313
1314    while start < total_size {
1315        let end = (start + piece_size).min(total_size) - 1;
1316        pieces.push_back(DownloadPiece { start, end });
1317        start = end + 1;
1318    }
1319
1320    pieces
1321}
1322
1323/// Chooses the fixed piece size for a large archive.
1324///
1325/// Smaller large files use 32 MiB pieces so there are enough pieces for several workers.
1326/// Very large files use 64 MiB pieces to keep the request count down.
1327fn segmented_piece_size(total_size: u64) -> u64 {
1328    if total_size < 2 * 1024 * 1024 * 1024 {
1329        SEGMENTED_DOWNLOAD_SMALL_PIECE_SIZE
1330    } else {
1331        SEGMENTED_DOWNLOAD_LARGE_PIECE_SIZE
1332    }
1333}
1334
1335/// Builds the segmented download plan for one archive.
1336///
1337/// Small files stay single-stream. Larger files are split into fixed pieces and
1338/// can use up to the shared request limit.
1339fn plan_segmented_download(total_size: u64, max_workers: usize) -> Option<SegmentedDownloadPlan> {
1340    if max_workers == 0 || total_size < SEGMENTED_DOWNLOAD_MIN_FILE_SIZE {
1341        return None;
1342    }
1343
1344    let piece_size = segmented_piece_size(total_size);
1345    if total_size <= piece_size {
1346        return None;
1347    }
1348
1349    let pieces = build_download_pieces(total_size, piece_size);
1350    let piece_count = pieces.len();
1351    let worker_count = max_workers.min(piece_count).max(1);
1352
1353    Some(SegmentedDownloadPlan { piece_size, piece_count, worker_count, pieces })
1354}
1355
1356/// Returns the retry backoff for one piece attempt.
1357fn piece_retry_backoff(attempt: u32, throttled: bool) -> Duration {
1358    let base = if throttled { 2 } else { RETRY_BACKOFF_SECS };
1359    let multiplier = 1u64 << attempt.saturating_sub(1).min(3);
1360    Duration::from_secs(base.saturating_mul(multiplier).min(SEGMENTED_DOWNLOAD_MAX_BACKOFF_SECS))
1361}
1362
1363/// Returns whether an HTTP status should retry the current piece.
1364fn is_retryable_piece_status(status: StatusCode) -> bool {
1365    matches!(status, StatusCode::REQUEST_TIMEOUT | StatusCode::TOO_MANY_REQUESTS) ||
1366        status.is_server_error()
1367}
1368
1369/// Returns whether a piece request should retry after the given status.
1370fn should_retry_piece_status(status: StatusCode) -> bool {
1371    status == StatusCode::OK || is_retryable_piece_status(status)
1372}
1373
1374/// Returns whether an HTTP status looks like throttling or timeout.
1375fn is_throttle_piece_status(status: StatusCode) -> bool {
1376    matches!(
1377        status,
1378        StatusCode::REQUEST_TIMEOUT |
1379            StatusCode::TOO_MANY_REQUESTS |
1380            StatusCode::SERVICE_UNAVAILABLE |
1381            StatusCode::GATEWAY_TIMEOUT
1382    )
1383}
1384
1385/// Returns whether a reqwest error looks like throttling or timeout.
1386fn is_throttle_piece_error(error: &reqwest::Error) -> bool {
1387    error.is_timeout() || matches!(error.status(), Some(status) if is_throttle_piece_status(status))
1388}
1389
1390/// The result of one piece download attempt.
1391enum PieceAttemptFailure {
1392    /// The piece can be retried.
1393    Retryable { error: eyre::Error, throttled: bool },
1394    /// The piece failed in a way that should stop the archive.
1395    Terminal(eyre::Error),
1396}
1397
1398/// Converts a thread panic payload into a readable message.
1399pub(crate) fn panic_payload_message(payload: Box<dyn Any + Send + 'static>) -> String {
1400    if let Some(message) = payload.downcast_ref::<&'static str>() {
1401        (*message).to_string()
1402    } else if let Some(message) = payload.downcast_ref::<String>() {
1403        message.clone()
1404    } else {
1405        "unknown panic payload".to_string()
1406    }
1407}
1408
1409#[cfg(test)]
1410pub(super) mod tests {
1411    use super::*;
1412    use reqwest::StatusCode;
1413    use reth_cli_util::cancellation::CancellationToken;
1414    use std::{
1415        io::{BufRead, Write},
1416        net::TcpListener,
1417    };
1418
1419    #[test]
1420    fn segmented_plan_skips_small_files() {
1421        assert!(plan_segmented_download(SEGMENTED_DOWNLOAD_MIN_FILE_SIZE - 1, 16).is_none());
1422    }
1423
1424    #[test]
1425    fn segmented_plan_uses_large_pieces_and_adaptive_workers() {
1426        let total_size = 512 * 1024 * 1024;
1427        let plan = plan_segmented_download(total_size, 32).unwrap();
1428
1429        assert_eq!(plan.piece_size, SEGMENTED_DOWNLOAD_SMALL_PIECE_SIZE);
1430        assert_eq!(plan.piece_count, 16);
1431        assert_eq!(plan.worker_count, 16);
1432    }
1433
1434    #[test]
1435    fn build_download_pieces_covers_entire_file() {
1436        let pieces = build_download_pieces(10, 4).into_iter().collect::<Vec<_>>();
1437
1438        assert_eq!(
1439            pieces,
1440            vec![
1441                DownloadPiece { start: 0, end: 3 },
1442                DownloadPiece { start: 4, end: 7 },
1443                DownloadPiece { start: 8, end: 9 },
1444            ]
1445        );
1446    }
1447
1448    #[test]
1449    fn piece_status_retry_policy_retries_200_ok() {
1450        assert!(should_retry_piece_status(StatusCode::OK));
1451        assert!(should_retry_piece_status(StatusCode::TOO_MANY_REQUESTS));
1452        assert!(should_retry_piece_status(StatusCode::from_u16(520).unwrap()));
1453        assert!(!should_retry_piece_status(StatusCode::NOT_FOUND));
1454    }
1455
1456    #[test]
1457    fn choose_fetch_strategy_uses_segmented_when_ranges_are_supported() {
1458        let strategy = choose_fetch_strategy(
1459            RemoteArchiveProbe { total_size: 512 * 1024 * 1024, supports_ranges: true },
1460            16,
1461        );
1462
1463        assert!(matches!(strategy, FetchStrategy::Segmented(_)));
1464    }
1465
1466    #[test]
1467    fn choose_fetch_strategy_falls_back_without_ranges() {
1468        let strategy = choose_fetch_strategy(
1469            RemoteArchiveProbe { total_size: 512 * 1024 * 1024, supports_ranges: false },
1470            16,
1471        );
1472
1473        assert!(matches!(
1474            strategy,
1475            FetchStrategy::Sequential(SequentialDownloadFallback::NoRangeSupport)
1476        ));
1477    }
1478
1479    #[test]
1480    fn archive_fetcher_uses_file_url_archive_directly() {
1481        let dir = tempfile::tempdir().unwrap();
1482        let archive_path = dir.path().join("state.tar.zst");
1483        {
1484            let mut archive = std::fs::File::create(&archive_path).unwrap();
1485            archive.write_all(b"local archive bytes").unwrap();
1486        }
1487
1488        let cache_dir = dir.path().join("cache");
1489        std::fs::create_dir(&cache_dir).unwrap();
1490        let url = Url::from_file_path(&archive_path).unwrap().to_string();
1491        let session = DownloadSession::new(None, None, CancellationToken::new());
1492        let fetcher = ArchiveFetcher::new(url, &cache_dir, session, None);
1493
1494        let downloaded = fetcher.download(None, None).unwrap();
1495
1496        assert_eq!(downloaded.path, archive_path);
1497        assert_eq!(downloaded.size, b"local archive bytes".len() as u64);
1498        assert!(!cache_dir.join("state.tar.zst").exists());
1499        assert!(!cache_dir.join("state.tar.zst.part").exists());
1500
1501        let fetcher = ArchiveFetcher { expected_size: Some(10), ..fetcher };
1502        assert_eq!(
1503            format!("{:#}", fetcher.download(None, None).unwrap_err()),
1504            "Archive size mismatch: manifest declares 10 bytes, server reported 19"
1505        );
1506    }
1507
1508    #[test]
1509    fn segmented_state_requeues_failed_pieces_within_budget() {
1510        let state = SegmentedDownloadState::new(build_download_pieces(8, 4));
1511        let token = CancellationToken::new();
1512        let first = state.next_piece(&token).unwrap();
1513
1514        assert!(state.requeue(first));
1515        assert!(state.requeue(first));
1516        assert!(!state.requeue(first));
1517        assert_eq!(state.pieces.lock().unwrap().front(), Some(&first));
1518    }
1519
1520    #[test]
1521    fn segmented_state_prefix_stops_at_first_missing_piece() {
1522        let pieces = build_download_pieces(10, 4).into_iter().collect::<Vec<_>>();
1523        let state = SegmentedDownloadState::new(VecDeque::new());
1524
1525        assert_eq!(state.complete(pieces[2]), 0);
1526        assert_eq!(state.complete(pieces[0]), 4);
1527        assert_eq!(state.complete(pieces[1]), 10);
1528    }
1529
1530    #[test]
1531    fn availability_reader_follows_published_prefix() {
1532        let dir = tempfile::tempdir().unwrap();
1533        let path = dir.path().join("archive.part");
1534        let data = (0..=255u8).cycle().take(1000).collect::<Vec<_>>();
1535        std::fs::write(&path, &data).unwrap();
1536        let availability = ArchiveAvailability::default();
1537
1538        let read = std::thread::scope(|scope| {
1539            let reader = scope.spawn(|| {
1540                let mut read = Vec::new();
1541                ArchiveAvailabilityReader::new(&availability).read_to_end(&mut read).map(|_| read)
1542            });
1543            availability.open(fs::open(&path).unwrap(), data.len() as u64);
1544            for len in [300, 299, 1000] {
1545                availability.publish(len);
1546            }
1547            reader.join().unwrap()
1548        });
1549
1550        assert_eq!(read.unwrap(), data);
1551        assert!(!availability.abort(), "a fully published archive stays readable");
1552    }
1553
1554    #[test]
1555    fn availability_reader_fails_when_download_aborts() {
1556        let dir = tempfile::tempdir().unwrap();
1557        let path = dir.path().join("archive.part");
1558        std::fs::write(&path, [7u8; 100]).unwrap();
1559        let availability = ArchiveAvailability::default();
1560        availability.open(fs::open(&path).unwrap(), 100);
1561        availability.publish(40);
1562
1563        let mut reader = ArchiveAvailabilityReader::new(&availability);
1564        let mut buf = [0u8; 100];
1565        assert_eq!(reader.read(&mut buf).unwrap(), 40);
1566        assert!(availability.abort());
1567
1568        let error = reader.read(&mut buf).unwrap_err();
1569        assert_eq!(error.to_string(), "archive download stopped before completing");
1570    }
1571
1572    #[test]
1573    fn segmented_download_publishes_downloaded_prefix() {
1574        let data = (0..=255u8).cycle().take(1024 * 1024 + 123).collect::<Vec<_>>();
1575        let (url, _) = spawn_range_server(data.clone(), false);
1576        let dir = tempfile::tempdir().unwrap();
1577        let availability = ArchiveAvailability::default();
1578
1579        let (downloaded, read) = std::thread::scope(|scope| {
1580            let reader = scope.spawn(|| {
1581                let mut read = Vec::new();
1582                ArchiveAvailabilityReader::new(&availability).read_to_end(&mut read).map(|_| read)
1583            });
1584            let downloaded = {
1585                let _abort_guard = availability.abort_on_drop();
1586                test_segmented_download(&url, dir.path(), data.len() as u64, test_session())
1587                    .run(Some(&availability))
1588            };
1589            (downloaded, reader.join().unwrap())
1590        });
1591
1592        assert_eq!(downloaded.unwrap().size, data.len() as u64);
1593        assert_eq!(read.unwrap(), data);
1594    }
1595
1596    #[test]
1597    fn segmented_download_stops_once_reader_aborted() {
1598        let (url, requests) = spawn_range_server(vec![0; 1024 * 1024], false);
1599        let dir = tempfile::tempdir().unwrap();
1600        let availability = ArchiveAvailability::default();
1601        assert!(availability.abort());
1602
1603        let error = test_segmented_download(&url, dir.path(), 1024 * 1024, test_session())
1604            .run(Some(&availability))
1605            .unwrap_err();
1606
1607        assert_eq!(
1608            format!("{error:#}"),
1609            "Parallel download failed: Archive reader stopped before the download completed"
1610        );
1611        assert_eq!(requests.load(Ordering::SeqCst), 0);
1612    }
1613
1614    #[test]
1615    fn segmented_download_backoff_stops_once_reader_aborts() {
1616        let (url, requests) = spawn_range_server(Vec::new(), true);
1617        let dir = tempfile::tempdir().unwrap();
1618        let session = test_session().with_retry_backoff(Some(Duration::from_secs(30)));
1619        let availability = ArchiveAvailability::default();
1620        let started = Instant::now();
1621
1622        let result = std::thread::scope(|scope| {
1623            let download = scope.spawn(|| {
1624                test_segmented_download(&url, dir.path(), 1024 * 1024, session)
1625                    .run(Some(&availability))
1626            });
1627            while requests.load(Ordering::SeqCst) == 0 {
1628                std::thread::sleep(Duration::from_millis(1));
1629            }
1630            assert!(availability.abort());
1631            download.join().unwrap()
1632        });
1633
1634        assert_eq!(
1635            format!("{:#}", result.unwrap_err()),
1636            "Parallel download failed: Archive reader stopped before the download completed"
1637        );
1638        // Without stopping during backoff, workers would sleep through two 30s retry delays.
1639        assert!(started.elapsed() < Duration::from_secs(10));
1640    }
1641
1642    #[test]
1643    fn sequential_download_rejects_size_other_than_expected() {
1644        let response = b"HTTP/1.1 200 OK\r\nContent-Length: 20\r\nConnection: close\r\n\r\n\
1645                         01234567890123456789";
1646        let url = spawn_response_server(vec![response]);
1647        let dir = tempfile::tempdir().unwrap();
1648        let session = DownloadSession::new(None, None, CancellationToken::new());
1649        let fetcher = ArchiveFetcher::new(url, dir.path(), session, Some(10));
1650
1651        let error = fetcher.download(None, None).unwrap_err();
1652
1653        assert_eq!(
1654            format!("{error:#}"),
1655            "Archive size mismatch: manifest declares 10 bytes, server reported 20"
1656        );
1657        assert!(!dir.path().join("archive.tar.zst").exists());
1658    }
1659
1660    #[test]
1661    fn sequential_resume_rejects_wrong_offset() {
1662        let url = spawn_response_server(vec![
1663            b"HTTP/1.1 206 Partial Content\r\nContent-Range: bytes 0-9/10\r\n\
1664              Content-Length: 10\r\nConnection: close\r\n\r\nXXXXXXXXXX",
1665        ]);
1666        let dir = tempfile::tempdir().unwrap();
1667        std::fs::write(dir.path().join("archive.tar.zst.part"), b"01234").unwrap();
1668        let session = DownloadSession::new(None, None, CancellationToken::new())
1669            .with_retry_backoff(Some(Duration::ZERO));
1670        let fetcher = ArchiveFetcher::new(url, dir.path(), session, Some(10));
1671
1672        let error = fetcher.download(None, None).unwrap_err();
1673
1674        assert_eq!(
1675            format!("{error:#}"),
1676            "Server resumed archive.tar.zst at byte 0 instead of requested offset 5"
1677        );
1678        assert_eq!(std::fs::read(dir.path().join("archive.tar.zst.part")).unwrap(), b"01234");
1679    }
1680
1681    #[test]
1682    fn sequential_resume_full_response_restarts_from_zero() {
1683        let url = spawn_response_server(vec![
1684            b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\nConnection: close\r\n\r\n0123456789",
1685        ]);
1686        let dir = tempfile::tempdir().unwrap();
1687        std::fs::write(dir.path().join("archive.tar.zst.part"), b"01234").unwrap();
1688        let session = DownloadSession::new(None, None, CancellationToken::new());
1689        let fetcher = ArchiveFetcher::new(url, dir.path(), session, Some(10));
1690
1691        let downloaded = fetcher.download(None, None).unwrap();
1692
1693        assert_eq!(std::fs::read(downloaded.path).unwrap(), b"0123456789");
1694    }
1695
1696    #[test]
1697    fn sequential_download_stops_at_declared_size() {
1698        let response = b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\
1699                         Connection: close\r\n\r\n14\r\n01234567890123456789\r\n0\r\n\r\n";
1700        let url = spawn_response_server(vec![response]);
1701        let dir = tempfile::tempdir().unwrap();
1702        let session = DownloadSession::new(None, None, CancellationToken::new());
1703        let fetcher = ArchiveFetcher::new(url, dir.path(), session, Some(10));
1704
1705        let downloaded = fetcher.download(None, None).unwrap();
1706
1707        assert_eq!(std::fs::read(downloaded.path).unwrap(), b"0123456789");
1708    }
1709
1710    #[test]
1711    fn sequential_download_accepts_declared_zero_size() {
1712        let url = spawn_response_server(vec![
1713            b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
1714        ]);
1715        let dir = tempfile::tempdir().unwrap();
1716        let session = DownloadSession::new(None, None, CancellationToken::new());
1717        let fetcher = ArchiveFetcher::new(url, dir.path(), session, Some(0));
1718
1719        let downloaded = fetcher.download(None, None).unwrap();
1720
1721        assert!(std::fs::read(downloaded.path).unwrap().is_empty());
1722    }
1723
1724    #[test]
1725    fn download_ending_at_expected_size_without_content_length_succeeds() {
1726        // A chunked body and a close-delimited body, both exactly the expected size.
1727        let url = spawn_response_server(vec![
1728            b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n\
1729              a\r\n0123456789\r\n0\r\n\r\n",
1730            b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n0123456789",
1731        ]);
1732        for _ in 0..2 {
1733            let dir = tempfile::tempdir().unwrap();
1734            let session = DownloadSession::new(None, None, CancellationToken::new());
1735            let fetcher = ArchiveFetcher::new(url.clone(), dir.path(), session, Some(10));
1736
1737            let downloaded = fetcher.download(None, None).unwrap();
1738
1739            assert_eq!(std::fs::read(downloaded.path).unwrap(), b"0123456789");
1740        }
1741    }
1742
1743    #[test]
1744    fn download_without_range_support_accepts_expected_size() {
1745        let response =
1746            b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\nConnection: close\r\n\r\n0123456789";
1747        let url = spawn_response_server(vec![response]);
1748        let dir = tempfile::tempdir().unwrap();
1749        let fetcher = ArchiveFetcher::new(url, dir.path(), test_session(), Some(10));
1750
1751        let probe = fetcher.probe(&BlockingClient::new()).unwrap();
1752        assert_eq!(probe.total_size, 10);
1753        assert!(!probe.supports_ranges);
1754
1755        let downloaded = fetcher.download(None, None).unwrap();
1756
1757        assert_eq!(std::fs::read(downloaded.path).unwrap(), b"0123456789");
1758    }
1759
1760    #[test]
1761    fn probe_rejects_size_other_than_expected() {
1762        let response = b"HTTP/1.1 206 Partial Content\r\nContent-Range: bytes 0-0/20\r\n\
1763                         Content-Length: 1\r\nConnection: close\r\n\r\n0";
1764        let url = spawn_response_server(vec![response]);
1765        let dir = tempfile::tempdir().unwrap();
1766        let fetcher = ArchiveFetcher::new(url, dir.path(), test_session(), Some(10));
1767
1768        let error = fetcher.download(None, None).unwrap_err();
1769
1770        assert_eq!(
1771            format!("{error:#}"),
1772            "Archive size mismatch: manifest declares 10 bytes, server reported 20"
1773        );
1774        assert!(!dir.path().join("archive.tar.zst").exists());
1775    }
1776
1777    #[test]
1778    fn content_range_rejects_invalid_intervals() {
1779        let parse = |value: &str| {
1780            let mut headers = HeaderMap::new();
1781            headers.insert(CONTENT_RANGE, value.parse().unwrap());
1782            content_range(&headers)
1783        };
1784
1785        assert_eq!(parse("Bytes 2-5/10"), Some(ContentRange { start: 2, end: 5, total: Some(10) }));
1786        assert_eq!(parse("bytes 2-5/*"), Some(ContentRange { start: 2, end: 5, total: None }));
1787        for bad in ["bytes 5-2/10", "bytes 2-10/10", "bytes 2-5/ten", "bytes 2-/10", "bytes */10"] {
1788            assert_eq!(parse(bad), None, "{bad}");
1789        }
1790    }
1791
1792    #[test]
1793    fn sequential_resume_progress_does_not_use_retries() {
1794        // Six valid one-byte responses must finish even with a budget of three failed attempts.
1795        let responses = (2..8)
1796            .map(|i| {
1797                format!(
1798                    "HTTP/1.1 206 Partial Content\r\nContent-Range: bytes {i}-{i}/8\r\n\
1799                     Content-Length: 1\r\nConnection: close\r\n\r\n{i}"
1800                )
1801                .leak()
1802                .as_bytes()
1803            })
1804            .collect();
1805        let url = spawn_response_server(responses);
1806        let dir = tempfile::tempdir().unwrap();
1807        std::fs::write(dir.path().join("archive.tar.zst.part"), b"01").unwrap();
1808        let session = DownloadSession::new(None, None, CancellationToken::new())
1809            .with_retry_backoff(Some(Duration::ZERO));
1810        let fetcher = ArchiveFetcher::new(url, dir.path(), session, Some(8));
1811
1812        let downloaded = fetcher.download_sequential(3, None).unwrap();
1813
1814        assert_eq!(std::fs::read(downloaded.path).unwrap(), b"01234567");
1815    }
1816
1817    #[test]
1818    fn probe_with_unknown_total_uses_expected_size() {
1819        let url = spawn_response_server(vec![
1820            b"HTTP/1.1 206 Partial Content\r\nContent-Range: bytes 0-0/*\r\n\
1821              Content-Length: 1\r\nConnection: close\r\n\r\n0",
1822            b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\nConnection: close\r\n\r\n0123456789",
1823        ]);
1824        let dir = tempfile::tempdir().unwrap();
1825        let fetcher = ArchiveFetcher::new(url, dir.path(), test_session(), Some(10));
1826
1827        let downloaded = fetcher.download(None, None).unwrap();
1828
1829        assert_eq!(std::fs::read(downloaded.path).unwrap(), b"0123456789");
1830    }
1831
1832    #[test]
1833    fn segmented_download_rejects_piece_for_other_range() {
1834        let total = 128 * 1024;
1835        let header = format!(
1836            "HTTP/1.1 206 Partial Content\r\nContent-Range: bytes 0-65535/{total}\r\n\
1837             Content-Length: 65536\r\nConnection: close\r\n\r\n"
1838        );
1839        let response = [header.as_bytes(), &[7u8; 65536]].concat().leak();
1840        let url = spawn_response_server(vec![response]);
1841        let dir = tempfile::tempdir().unwrap();
1842
1843        let error =
1844            test_segmented_download(&url, dir.path(), total, test_session()).run(None).unwrap_err();
1845
1846        assert_eq!(
1847            format!("{error:#}"),
1848            format!(
1849                "Parallel download failed: Server returned Content-Range \
1850                 Some(\"bytes 0-65535/{total}\") for piece 65536-131071"
1851            )
1852        );
1853    }
1854
1855    #[test]
1856    fn probe_retries_full_responses_for_segmentable_files() {
1857        let size = SEGMENTED_DOWNLOAD_MIN_FILE_SIZE;
1858        let without_length = b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n".as_slice();
1859        for (full, expected_size) in
1860            [(probe_full_response(size), None), (without_length, Some(size))]
1861        {
1862            let url = spawn_response_server(vec![full, probe_partial_response(size)]);
1863            let dir = tempfile::tempdir().unwrap();
1864            let fetcher = ArchiveFetcher::new(url, dir.path(), probe_session(), expected_size);
1865
1866            let probe = fetcher.probe(&BlockingClient::new()).unwrap();
1867
1868            assert!(probe.supports_ranges);
1869            assert_eq!(probe.total_size, size);
1870        }
1871    }
1872
1873    #[test]
1874    fn probe_accepts_full_responses_for_small_files() {
1875        let size = SEGMENTED_DOWNLOAD_MIN_FILE_SIZE - 1;
1876        let url =
1877            spawn_response_server(vec![probe_full_response(size), probe_partial_response(size)]);
1878        let dir = tempfile::tempdir().unwrap();
1879        let fetcher = ArchiveFetcher::new(url, dir.path(), probe_session(), Some(size));
1880
1881        let probe = fetcher.probe(&BlockingClient::new()).unwrap();
1882
1883        assert!(!probe.supports_ranges);
1884        assert_eq!(probe.total_size, size);
1885    }
1886
1887    #[test]
1888    fn probe_falls_back_after_full_responses_on_every_attempt() {
1889        let size = SEGMENTED_DOWNLOAD_MIN_FILE_SIZE;
1890        let url = spawn_response_server(vec![probe_full_response(size)]);
1891        let dir = tempfile::tempdir().unwrap();
1892        let fetcher = ArchiveFetcher::new(url, dir.path(), probe_session(), Some(size));
1893
1894        let probe = fetcher.probe(&BlockingClient::new()).unwrap();
1895
1896        assert!(!probe.supports_ranges);
1897        assert_eq!(probe.total_size, size);
1898    }
1899
1900    /// Returns a session that retries range probes without waiting.
1901    fn probe_session() -> DownloadSession {
1902        DownloadSession::new(None, None, CancellationToken::new())
1903            .with_retry_backoff(Some(Duration::ZERO))
1904    }
1905
1906    /// Returns the headers of a full `size`-byte response that ignores the probe's `Range`.
1907    ///
1908    /// The body is omitted because the probe never reads it.
1909    fn probe_full_response(size: u64) -> &'static [u8] {
1910        format!("HTTP/1.1 200 OK\r\nContent-Length: {size}\r\nConnection: close\r\n\r\n")
1911            .leak()
1912            .as_bytes()
1913    }
1914
1915    /// Returns a `bytes=0-0` range response for a `size`-byte archive.
1916    fn probe_partial_response(size: u64) -> &'static [u8] {
1917        format!(
1918            "HTTP/1.1 206 Partial Content\r\nContent-Range: bytes 0-0/{size}\r\n\
1919             Content-Length: 1\r\nConnection: close\r\n\r\n0"
1920        )
1921        .leak()
1922        .as_bytes()
1923    }
1924
1925    fn test_session() -> DownloadSession {
1926        DownloadSession::new(None, Some(DownloadRequestLimiter::new(4)), CancellationToken::new())
1927    }
1928
1929    /// Plans 64 KiB pieces so a small archive still exercises several workers.
1930    fn test_segmented_download(
1931        url: &str,
1932        dir: &Path,
1933        total_size: u64,
1934        session: DownloadSession,
1935    ) -> SegmentedDownload {
1936        let piece_size = 64 * 1024;
1937        let pieces = build_download_pieces(total_size, piece_size);
1938        let plan = SegmentedDownloadPlan {
1939            piece_size,
1940            piece_count: pieces.len(),
1941            worker_count: 4,
1942            pieces,
1943        };
1944        SegmentedDownload::new(
1945            url.to_string(),
1946            DownloadPaths::from_url(url, dir),
1947            total_size,
1948            plan,
1949            session,
1950            None,
1951        )
1952    }
1953
1954    /// Serves `data` over HTTP on localhost with range support, or answers every request with
1955    /// 503 when `unavailable` is set. Returns the URL and the number of requests received.
1956    fn spawn_range_server(data: Vec<u8>, unavailable: bool) -> (String, Arc<AtomicU64>) {
1957        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1958        let url = format!("http://{}/archive.tar.zst", listener.local_addr().unwrap());
1959        let data = Arc::new(data);
1960        let requests = Arc::new(AtomicU64::new(0));
1961        let received = Arc::clone(&requests);
1962        std::thread::spawn(move || {
1963            for stream in listener.incoming() {
1964                let (data, received) = (Arc::clone(&data), Arc::clone(&received));
1965                std::thread::spawn(move || {
1966                    let mut stream = stream.unwrap();
1967                    let mut request = io::BufReader::new(stream.try_clone().unwrap());
1968                    let mut range = None;
1969                    loop {
1970                        let mut line = String::new();
1971                        if request.read_line(&mut line).unwrap() == 0 || line == "\r\n" {
1972                            break
1973                        }
1974                        if let Some(value) = line.to_ascii_lowercase().strip_prefix("range: bytes=")
1975                        {
1976                            let (start, end) = value.trim().split_once('-').unwrap();
1977                            range = Some((
1978                                start.parse::<usize>().unwrap(),
1979                                end.parse::<usize>().unwrap(),
1980                            ));
1981                        }
1982                    }
1983                    received.fetch_add(1, Ordering::SeqCst);
1984
1985                    if unavailable {
1986                        stream
1987                            .write_all(
1988                                b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\n\
1989                                  Connection: close\r\n\r\n",
1990                            )
1991                            .unwrap();
1992                        return
1993                    }
1994                    let (start, end) = range.unwrap();
1995                    let body = &data[start..=end];
1996                    write!(
1997                        stream,
1998                        "HTTP/1.1 206 Partial Content\r\nContent-Range: bytes {start}-{end}/{}\r\n\
1999                         Content-Length: {}\r\nConnection: close\r\n\r\n",
2000                        data.len(),
2001                        body.len()
2002                    )
2003                    .unwrap();
2004                    stream.write_all(body).unwrap();
2005                });
2006            }
2007        });
2008        (url, requests)
2009    }
2010
2011    /// Answers successive HTTP requests on localhost with `responses` in order, repeating the last
2012    /// one for any later request, and returns the URL.
2013    pub(crate) fn spawn_response_server(responses: Vec<&'static [u8]>) -> String {
2014        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2015        let url = format!("http://{}/archive.tar.zst", listener.local_addr().unwrap());
2016        std::thread::spawn(move || {
2017            let last = *responses.last().unwrap();
2018            let responses = responses.into_iter().chain(std::iter::repeat(last));
2019            for (stream, response) in listener.incoming().zip(responses) {
2020                let mut stream = stream.unwrap();
2021                let mut request = io::BufReader::new(stream.try_clone().unwrap());
2022                loop {
2023                    let mut line = String::new();
2024                    if request.read_line(&mut line).unwrap() == 0 || line == "\r\n" {
2025                        break
2026                    }
2027                }
2028                stream.write_all(response).unwrap();
2029            }
2030        });
2031        url
2032    }
2033}