Skip to main content

reth_cli_commands/download/
archive.rs

1use super::{
2    extract::{extract_archive_hashed, streaming_download_and_extract, CompressionFormat},
3    fetch::{
4        panic_payload_message, ArchiveAvailability, ArchiveAvailabilityReader, ArchiveFetcher,
5    },
6    manifest::SnapshotArchive,
7    planning::{CheckedDownloads, PlannedArchive},
8    progress::{
9        spawn_progress_display, ArchiveDownloadProgress, ArchiveExtractionProgress,
10        ArchiveVerificationProgress, DownloadRequestLimiter, SharedProgress,
11    },
12    session::{ArchiveProcessContext, DownloadSession},
13    verify::{ExtractedHashes, OutputVerifier},
14    MAX_DOWNLOAD_RETRIES, RETRY_BACKOFF_SECS,
15};
16use eyre::Result;
17use futures::stream::{self, StreamExt};
18use reth_cli_util::cancellation::CancellationToken;
19use reth_fs_util as fs;
20use std::{
21    collections::HashSet,
22    io::BufReader,
23    panic::{self, AssertUnwindSafe},
24    path::Path,
25    sync::Arc,
26    thread,
27    time::Duration,
28};
29use tracing::{debug, info, warn};
30
31const DOWNLOAD_CACHE_DIR: &str = ".download-cache";
32
33/// Read buffer between the cached archive and the decompressor, so each read of the growing
34/// archive takes the availability lock once per MiB instead of once per decoder read.
35const EXTRACTION_READ_BUFFER_SIZE: usize = 1 << 20;
36
37/// Runs all planned modular archive downloads for one command invocation.
38pub(crate) async fn run_modular_downloads(
39    planned_downloads: CheckedDownloads,
40    target_dir: &Path,
41    static_files_dir: Option<&Path>,
42    download_concurrency: usize,
43    cancel_token: CancellationToken,
44    retry_backoff: Option<Duration>,
45) -> Result<()> {
46    let download_cache_dir = target_dir.join(DOWNLOAD_CACHE_DIR);
47    fs::create_dir_all(&download_cache_dir)?;
48
49    let shared = SharedProgress::new(
50        planned_downloads.total_download_size,
51        planned_downloads.total_output_size,
52        planned_downloads.total_archives() as u64,
53        cancel_token.clone(),
54    );
55    let session = DownloadSession::new(
56        Some(Arc::clone(&shared)),
57        Some(DownloadRequestLimiter::new(download_concurrency)),
58        cancel_token,
59    )
60    .with_retry_backoff(retry_backoff);
61    let ctx = ArchiveProcessContext::new(
62        target_dir.to_path_buf(),
63        static_files_dir.map(Path::to_path_buf),
64        Some(download_cache_dir),
65        session,
66    );
67
68    ModularDownloadJob::new(ctx, download_concurrency).run(planned_downloads).await
69}
70
71/// Schedules modular archive work for one run of `reth download`.
72struct ModularDownloadJob {
73    /// Shared paths and session state for each archive in this job.
74    ctx: ArchiveProcessContext,
75    /// Maximum number of archives processed at once.
76    archive_concurrency: usize,
77}
78
79impl ModularDownloadJob {
80    /// Creates the modular download job for one command run.
81    const fn new(ctx: ArchiveProcessContext, archive_concurrency: usize) -> Self {
82        Self { ctx, archive_concurrency }
83    }
84
85    /// Runs all planned archives and waits for the shared progress task to finish.
86    async fn run(self, planned_downloads: CheckedDownloads) -> Result<()> {
87        let shared = Arc::clone(
88            self.ctx.session().progress().expect("modular downloads always use shared progress"),
89        );
90        let progress_handle = spawn_progress_display(Arc::clone(&shared));
91        for reused in &planned_downloads.reused {
92            info!(target: "reth::cli", file = %reused.archive.file_name, component = %reused.component, "Skipping already verified plain files");
93            shared.record_reused_archive(
94                reused.archive.size.unwrap_or_default(),
95                reused.archive.output_size(),
96            );
97        }
98        let ctx = self.ctx.clone();
99        let results: Vec<Result<()>> = stream::iter(planned_downloads.pending)
100            .map(move |archive| {
101                let ctx = ctx.clone();
102                async move { Self::process_archive(ctx, archive).await }
103            })
104            .buffer_unordered(self.archive_concurrency)
105            .collect()
106            .await;
107
108        shared.done.notify_one();
109        let _ = progress_handle.await;
110
111        for result in results {
112            result?;
113        }
114
115        Ok(())
116    }
117
118    /// Runs one archive on the blocking pool so fetch and extraction stay off the async executor.
119    async fn process_archive(ctx: ArchiveProcessContext, archive: PlannedArchive) -> Result<()> {
120        reth_tasks::spawn_blocking(move || ArchiveProcessor::new(archive, ctx).run()).await??;
121        Ok(())
122    }
123}
124
125/// Explicit retry states for one modular archive.
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127enum ArchiveAttemptState {
128    /// Start or restart one full archive attempt.
129    RunAttempt,
130    /// Check whether the extracted outputs verify.
131    VerifyOutputs,
132    /// Wait and decide whether another full attempt should run.
133    RetryAttempt,
134    /// Finish successfully.
135    Complete,
136    /// Stop with an error after retries are exhausted.
137    Fail,
138}
139
140/// Processes one modular archive through fetch, extraction, and verification.
141struct ArchiveProcessor {
142    /// The concrete archive and component being processed.
143    archive: PlannedArchive,
144    /// Shared paths and session state for this archive attempt.
145    ctx: ArchiveProcessContext,
146}
147
148impl ArchiveProcessor {
149    /// Creates a processor for one archive and the shared download context.
150    fn new(archive: PlannedArchive, ctx: ArchiveProcessContext) -> Self {
151        Self { archive, ctx }
152    }
153
154    /// Runs the archive retry state machine until outputs are verified or retries are exhausted.
155    ///
156    /// Callers only pass archives that failed the startup reuse check.
157    fn run(self) -> Result<()> {
158        let archive = self.archive();
159        let mode = ArchiveMode::new(&self.ctx)?;
160        let format = CompressionFormat::from_url(&archive.file_name)?;
161        let mut attempt = 1;
162        let mut last_error: Option<eyre::Error> = None;
163        let mut state = ArchiveAttemptState::RunAttempt;
164        let mut extracted = None;
165
166        loop {
167            match state {
168                ArchiveAttemptState::RunAttempt => {
169                    self.cleanup_outputs();
170
171                    if attempt > 1 {
172                        info!(target: "reth::cli",
173                            file = %archive.file_name,
174                            component = %self.archive.component,
175                            attempt,
176                            max = MAX_DOWNLOAD_RETRIES,
177                            "Retrying archive from scratch"
178                        );
179                    }
180
181                    match self.run_attempt(mode, format) {
182                        Ok(hashes) => {
183                            extracted = hashes;
184                            state = ArchiveAttemptState::VerifyOutputs;
185                        }
186                        Err(error) if mode.retries_fetch_errors() => {
187                            warn!(target: "reth::cli",
188                                file = %archive.file_name,
189                                component = %self.archive.component,
190                                attempt,
191                                err = %format_args!("{error:#}"),
192                                "Archive attempt failed, retrying from scratch"
193                            );
194                            last_error = Some(error);
195                            state = ArchiveAttemptState::RetryAttempt;
196                        }
197                        Err(error) => return Err(error),
198                    }
199                }
200                ArchiveAttemptState::VerifyOutputs => {
201                    if self.verify_outputs_with_progress(extracted.as_ref())? {
202                        state = ArchiveAttemptState::Complete;
203                    } else {
204                        warn!(target: "reth::cli", file = %archive.file_name, component = %self.archive.component, attempt, "Archive extracted, but output verification failed, retrying");
205                        state = ArchiveAttemptState::RetryAttempt;
206                    }
207                }
208                ArchiveAttemptState::RetryAttempt => {
209                    if attempt >= MAX_DOWNLOAD_RETRIES {
210                        state = ArchiveAttemptState::Fail;
211                    } else {
212                        std::thread::sleep(
213                            self.ctx.session().retry_delay(Duration::from_secs(RETRY_BACKOFF_SECS)),
214                        );
215                        attempt += 1;
216                        state = ArchiveAttemptState::RunAttempt;
217                    }
218                }
219                ArchiveAttemptState::Complete => return Ok(()),
220                ArchiveAttemptState::Fail => {
221                    if let Some(error) = last_error {
222                        return Err(error.wrap_err(format!(
223                            "Failed after {} attempts for {}",
224                            MAX_DOWNLOAD_RETRIES, archive.file_name
225                        )));
226                    }
227
228                    eyre::bail!(
229                        "Failed integrity validation after {} attempts for {}",
230                        MAX_DOWNLOAD_RETRIES,
231                        archive.file_name
232                    );
233                }
234            }
235        }
236    }
237
238    /// Returns the concrete archive being fetched or verified.
239    fn archive(&self) -> &SnapshotArchive {
240        &self.archive.archive
241    }
242
243    /// Returns the verifier for this archive's output files.
244    fn output_verifier(&self) -> OutputVerifier<'_> {
245        OutputVerifier::new(self.ctx.target_dir(), self.ctx.static_files_dir())
246    }
247
248    /// Removes any partial outputs before a fresh archive attempt.
249    fn cleanup_outputs(&self) {
250        self.output_verifier().cleanup(&self.archive().output_files);
251    }
252
253    /// Executes one archive attempt according to the selected cache-vs-stream mode.
254    ///
255    /// Returns the hashes of outputs computed while extracting, when the mode computes them.
256    fn run_attempt(
257        &self,
258        mode: ArchiveMode,
259        format: CompressionFormat,
260    ) -> Result<Option<ExtractedHashes>> {
261        mode.execute(self, format)
262    }
263
264    /// Downloads the archive into the cache while extracting the downloaded prefix of the cached
265    /// file.
266    fn run_cached_attempt(&self, format: CompressionFormat) -> Result<Option<ExtractedHashes>> {
267        let cache_dir =
268            self.ctx.cache_dir().ok_or_else(|| eyre::eyre!("Missing download cache directory"))?;
269        let fetcher = ArchiveFetcher::new(
270            self.archive().url.clone(),
271            cache_dir,
272            self.ctx.session().clone(),
273            self.archive().size,
274        );
275
276        if self.archive.ty == super::manifest::SnapshotComponentType::State {
277            debug!(target: "reth::cli", url = %self.archive().url, "Downloading state snapshot archive");
278        }
279
280        let availability = ArchiveAvailability::default();
281        let (download_result, extraction) = thread::scope(|scope| {
282            let extraction = scope.spawn(|| {
283                // Stops the download, which no longer has a reader. An unpack failure stops it
284                // before extraction waits for the decoder, which may be waiting on the download.
285                let mut stopped_download = false;
286                // A panic must also stop the download instead of letting it run to completion.
287                let result = panic::catch_unwind(AssertUnwindSafe(|| {
288                    self.extract_cached_archive(&availability, format, || {
289                        stopped_download = availability.abort()
290                    })
291                }))
292                .unwrap_or_else(|payload| {
293                    Err(eyre::eyre!(
294                        "Archive extraction panicked: {}",
295                        panic_payload_message(payload)
296                    ))
297                });
298                let stopped_download =
299                    stopped_download || (result.is_err() && availability.abort());
300                (result, stopped_download)
301            });
302
303            let download_result = {
304                let _abort_guard = availability.abort_on_drop();
305                let mut download_progress =
306                    ArchiveDownloadProgress::new(self.ctx.session().progress());
307                let result = fetcher.download(Some(&mut download_progress), Some(&availability));
308                if let Ok(downloaded) = &result {
309                    if download_progress.has_tracked_bytes() {
310                        download_progress.complete(downloaded.size);
311                    }
312                    info!(target: "reth::cli",
313                        file = %self.archive().file_name,
314                        component = %self.archive.component,
315                        size = %super::progress::DownloadProgress::format_size(downloaded.size),
316                        "Archive download complete"
317                    );
318                }
319                result
320            };
321            let extraction = extraction
322                .join()
323                .unwrap_or_else(|_| (Err(eyre::eyre!("Archive extraction panicked")), false));
324            (download_result, extraction)
325        });
326        fetcher.cleanup_downloaded_files();
327
328        // Report the side that failed first: an aborted download fails extraction and vice versa.
329        let (extract_result, extraction_stopped_download) = extraction;
330        if extraction_stopped_download {
331            return extract_result.map(Some)
332        }
333        download_result?;
334        extract_result.map(Some)
335    }
336
337    /// Streams the archive directly into extraction without keeping a cached copy.
338    fn run_streaming_attempt(&self, format: CompressionFormat) -> Result<Option<ExtractedHashes>> {
339        let _download_progress = ArchiveDownloadProgress::new(self.ctx.session().progress());
340        streaming_download_and_extract(
341            &self.archive().url,
342            format,
343            self.ctx.target_dir(),
344            self.ctx.static_files_dir(),
345            self.ctx.session(),
346        )?;
347        Ok(None)
348    }
349
350    /// Extracts the cached archive as its download publishes it, while updating shared extraction
351    /// activity, and returns the hashes of the regular files it wrote. `on_unpack_error` runs as
352    /// described by [`extract_archive_hashed`].
353    fn extract_cached_archive(
354        &self,
355        availability: &ArchiveAvailability,
356        format: CompressionFormat,
357        on_unpack_error: impl FnOnce(),
358    ) -> Result<ExtractedHashes> {
359        let verifier = self.output_verifier();
360        let outputs = self
361            .archive()
362            .output_files
363            .iter()
364            .map(|output| verifier.output_path(output))
365            .collect::<Result<HashSet<_>>>()?;
366        let mut extraction_progress = ArchiveExtractionProgress::new(self.ctx.session().progress());
367        let reader = BufReader::with_capacity(
368            EXTRACTION_READ_BUFFER_SIZE,
369            ArchiveAvailabilityReader::new(availability),
370        );
371        let result = extract_archive_hashed(
372            reader,
373            format,
374            self.ctx.target_dir(),
375            self.ctx.static_files_dir(),
376            outputs,
377            Some(&mut extraction_progress),
378            on_unpack_error,
379        );
380        extraction_progress.finish();
381        result
382    }
383
384    /// Returns `true` if all declared plain outputs verify while updating shared verification
385    /// progress. Outputs with a hash in `extracted` are not read back.
386    fn verify_outputs_with_progress(&self, extracted: Option<&ExtractedHashes>) -> Result<bool> {
387        let mut verification_progress =
388            ArchiveVerificationProgress::new(self.ctx.session().progress());
389        let verified = self.output_verifier().verify_with_progress(
390            &self.archive().output_files,
391            Some(&verification_progress),
392            extracted,
393        )?;
394        if verified {
395            verification_progress.complete(self.archive().output_size());
396        }
397        Ok(verified)
398    }
399}
400
401/// Chooses whether an archive attempt uses the cache or streams directly.
402#[derive(Debug, Clone, Copy, PartialEq, Eq)]
403enum ArchiveMode {
404    /// Download the archive to the cache, then extract it.
405    Cached,
406    /// Stream the archive directly into extraction.
407    Streaming,
408}
409
410impl ArchiveMode {
411    /// Picks the archive mode from the process context.
412    fn new(ctx: &ArchiveProcessContext) -> Result<Self> {
413        if ctx.cache_dir().is_some() {
414            ctx.session().require_request_limiter()?;
415            return Ok(Self::Cached)
416        }
417
418        Ok(Self::Streaming)
419    }
420
421    /// Returns `true` when fetch failures should retry the whole archive attempt.
422    const fn retries_fetch_errors(&self) -> bool {
423        matches!(self, Self::Cached)
424    }
425
426    /// Runs the selected archive mode for a single attempt.
427    fn execute(
428        &self,
429        processor: &ArchiveProcessor,
430        format: CompressionFormat,
431    ) -> Result<Option<ExtractedHashes>> {
432        match self {
433            Self::Cached => processor.run_cached_attempt(format),
434            Self::Streaming => processor.run_streaming_attempt(format),
435        }
436    }
437}