Skip to main content

reth_cli_commands/download/
progress.rs

1use eyre::Result;
2use reth_cli_util::cancellation::CancellationToken;
3use std::{
4    collections::VecDeque,
5    io::{self, Read, Write},
6    sync::{
7        atomic::{AtomicBool, AtomicU64, Ordering},
8        Arc, Mutex,
9    },
10    thread::{self, Thread},
11    time::{Duration, Instant},
12};
13use tokio::sync::Notify;
14use tracing::info;
15
16const BYTE_UNITS: [&str; 4] = ["B", "KB", "MB", "GB"];
17
18/// Tracks download progress and throttles display updates to every 100ms.
19pub(crate) struct DownloadProgress {
20    /// Bytes copied so far for this single download.
21    pub(crate) downloaded: u64,
22    /// Total bytes expected for this single download.
23    total_size: u64,
24    /// Time when the progress line was last printed.
25    last_displayed: Instant,
26    /// Time when this progress tracker started.
27    started_at: Instant,
28}
29
30impl DownloadProgress {
31    /// Creates new progress tracker with given total size
32    pub(crate) fn new(total_size: u64) -> Self {
33        let now = Instant::now();
34        Self { downloaded: 0, total_size, last_displayed: now, started_at: now }
35    }
36
37    /// Converts bytes to human readable format (B, KB, MB, GB)
38    pub(crate) fn format_size(size: u64) -> String {
39        let mut size = size as f64;
40        let mut unit_index = 0;
41
42        while size >= 1024.0 && unit_index < BYTE_UNITS.len() - 1 {
43            size /= 1024.0;
44            unit_index += 1;
45        }
46
47        format!("{:.2} {}", size, BYTE_UNITS[unit_index])
48    }
49
50    /// Format duration as human readable string
51    pub(crate) fn format_duration(duration: Duration) -> String {
52        let secs = duration.as_secs();
53        if secs < 60 {
54            format!("{secs}s")
55        } else if secs < 3600 {
56            format!("{}m {}s", secs / 60, secs % 60)
57        } else {
58            format!("{}h {}m", secs / 3600, (secs % 3600) / 60)
59        }
60    }
61
62    /// Updates progress bar (for single-archive legacy downloads)
63    pub(crate) fn update(&mut self, chunk_size: u64) -> Result<()> {
64        self.downloaded += chunk_size;
65
66        if self.last_displayed.elapsed() >= Duration::from_millis(100) {
67            let formatted_downloaded = Self::format_size(self.downloaded);
68            let formatted_total = Self::format_size(self.total_size);
69            let progress = (self.downloaded as f64 / self.total_size as f64) * 100.0;
70
71            let elapsed = self.started_at.elapsed();
72            let eta = if self.downloaded > 0 {
73                let remaining = self.total_size.saturating_sub(self.downloaded);
74                let speed = self.downloaded as f64 / elapsed.as_secs_f64();
75                if speed > 0.0 {
76                    Duration::from_secs_f64(remaining as f64 / speed)
77                } else {
78                    Duration::ZERO
79                }
80            } else {
81                Duration::ZERO
82            };
83            let eta_str = Self::format_duration(eta);
84
85            print!(
86                "\rDownloading and extracting... {progress:.2}% ({formatted_downloaded} / {formatted_total}) ETA: {eta_str}     ",
87            );
88            io::stdout().flush()?;
89            self.last_displayed = Instant::now();
90        }
91
92        Ok(())
93    }
94}
95
96#[derive(Debug, Clone, Copy)]
97struct PhaseStart {
98    started_at: Instant,
99    baseline_bytes: u64,
100}
101
102/// Shared progress counters for parallel downloads.
103pub(crate) struct SharedProgress {
104    /// Raw HTTP bytes fetched during this session, including retries.
105    pub(crate) session_fetched_bytes: AtomicU64,
106    /// Compressed bytes from archives that have fully downloaded.
107    pub(crate) completed_download_bytes: AtomicU64,
108    /// Compressed bytes written for currently active archive download attempts.
109    pub(crate) active_download_bytes: AtomicU64,
110    /// Total compressed bytes expected across all planned archives.
111    pub(crate) total_download_bytes: u64,
112    /// Plain-output bytes from archives that have fully verified.
113    pub(crate) completed_output_bytes: AtomicU64,
114    /// Plain-output bytes unpacked by currently active extractions.
115    pub(crate) active_extracted_output_bytes: AtomicU64,
116    /// Plain-output bytes hashed by currently active verifications.
117    pub(crate) active_verified_output_bytes: AtomicU64,
118    /// Total plain-output bytes expected across all planned archives.
119    pub(crate) total_output_bytes: u64,
120    /// Total number of planned archives.
121    pub(crate) total_archives: u64,
122    /// Time when the modular download job started.
123    pub(crate) started_at: Instant,
124    /// Time and baseline when the current extraction phase started.
125    extraction_phase: Mutex<Option<PhaseStart>>,
126    /// Time and baseline when the current verification phase started.
127    verification_phase: Mutex<Option<PhaseStart>>,
128    /// Number of archives that have fully finished.
129    pub(crate) archives_done: AtomicU64,
130    /// Number of archives currently in the fetch phase.
131    pub(crate) active_downloads: AtomicU64,
132    /// Number of in-flight HTTP requests.
133    pub(crate) active_download_requests: AtomicU64,
134    /// Number of archives currently extracting.
135    pub(crate) active_extractions: AtomicU64,
136    /// Number of archives currently verifying extracted outputs.
137    pub(crate) active_verifications: AtomicU64,
138    /// Wakes the background progress task to print the final summary and exit.
139    pub(crate) done: Notify,
140    /// Cancellation token shared by the whole command.
141    cancel_token: CancellationToken,
142}
143
144impl SharedProgress {
145    /// Creates the shared progress state for a modular download job.
146    pub(crate) fn new(
147        total_download_bytes: u64,
148        total_output_bytes: u64,
149        total_archives: u64,
150        cancel_token: CancellationToken,
151    ) -> Arc<Self> {
152        Arc::new(Self {
153            session_fetched_bytes: AtomicU64::new(0),
154            completed_download_bytes: AtomicU64::new(0),
155            active_download_bytes: AtomicU64::new(0),
156            total_download_bytes,
157            completed_output_bytes: AtomicU64::new(0),
158            active_extracted_output_bytes: AtomicU64::new(0),
159            active_verified_output_bytes: AtomicU64::new(0),
160            total_output_bytes,
161            total_archives,
162            started_at: Instant::now(),
163            extraction_phase: Mutex::new(None),
164            verification_phase: Mutex::new(None),
165            archives_done: AtomicU64::new(0),
166            active_downloads: AtomicU64::new(0),
167            active_download_requests: AtomicU64::new(0),
168            active_extractions: AtomicU64::new(0),
169            active_verifications: AtomicU64::new(0),
170            done: Notify::new(),
171            cancel_token,
172        })
173    }
174
175    /// Returns whether the whole command has been cancelled.
176    pub(crate) fn is_cancelled(&self) -> bool {
177        self.cancel_token.is_cancelled()
178    }
179
180    /// Adds raw session traffic bytes without affecting logical progress.
181    pub(crate) fn record_session_fetched_bytes(&self, bytes: u64) {
182        self.session_fetched_bytes.fetch_add(bytes, Ordering::Relaxed);
183    }
184
185    pub(crate) fn add_active_download_bytes(&self, bytes: u64) {
186        self.active_download_bytes.fetch_add(bytes, Ordering::Relaxed);
187    }
188
189    pub(crate) fn sub_active_download_bytes(&self, bytes: u64) {
190        sub_bytes(&self.active_download_bytes, bytes);
191    }
192
193    fn add_active_extracted_output_bytes(&self, bytes: u64) {
194        self.active_extracted_output_bytes.fetch_add(bytes, Ordering::Relaxed);
195    }
196
197    fn sub_active_extracted_output_bytes(&self, bytes: u64) {
198        sub_bytes(&self.active_extracted_output_bytes, bytes);
199    }
200
201    fn add_active_verified_output_bytes(&self, bytes: u64) {
202        self.active_verified_output_bytes.fetch_add(bytes, Ordering::Relaxed);
203    }
204
205    fn sub_active_verified_output_bytes(&self, bytes: u64) {
206        sub_bytes(&self.active_verified_output_bytes, bytes);
207    }
208
209    /// Records an archive whose outputs were already present locally.
210    pub(crate) fn record_reused_archive(&self, download_bytes: u64, output_bytes: u64) {
211        self.completed_download_bytes.fetch_add(download_bytes, Ordering::Relaxed);
212        self.completed_output_bytes.fetch_add(output_bytes, Ordering::Relaxed);
213        self.archives_done.fetch_add(1, Ordering::Relaxed);
214    }
215
216    /// Records an archive whose compressed download completed successfully.
217    pub(crate) fn record_archive_download_complete(&self, bytes: u64) {
218        self.completed_download_bytes.fetch_add(bytes, Ordering::Relaxed);
219    }
220
221    /// Records an archive whose extracted outputs have fully verified.
222    pub(crate) fn record_archive_output_complete(&self, bytes: u64) {
223        self.completed_output_bytes.fetch_add(bytes, Ordering::Relaxed);
224        self.archives_done.fetch_add(1, Ordering::Relaxed);
225    }
226
227    /// Returns logical compressed download progress.
228    pub(crate) fn logical_downloaded_bytes(&self) -> u64 {
229        (self.completed_download_bytes.load(Ordering::Relaxed) +
230            self.active_download_bytes.load(Ordering::Relaxed))
231        .min(self.total_download_bytes)
232    }
233
234    /// Returns verified plain-output bytes.
235    pub(crate) fn verified_output_bytes(&self) -> u64 {
236        self.completed_output_bytes.load(Ordering::Relaxed).min(self.total_output_bytes)
237    }
238
239    /// Returns plain-output bytes currently represented by extraction progress.
240    pub(crate) fn extracting_output_bytes(&self) -> u64 {
241        (self.completed_output_bytes.load(Ordering::Relaxed) +
242            self.active_extracted_output_bytes.load(Ordering::Relaxed))
243        .min(self.total_output_bytes)
244    }
245
246    /// Returns plain-output bytes currently represented by verification progress.
247    pub(crate) fn verifying_output_bytes(&self) -> u64 {
248        (self.completed_output_bytes.load(Ordering::Relaxed) +
249            self.active_verified_output_bytes.load(Ordering::Relaxed))
250        .min(self.total_output_bytes)
251    }
252
253    fn restart_phase(slot: &Mutex<Option<PhaseStart>>, baseline_bytes: u64) {
254        *slot.lock().unwrap() = Some(PhaseStart { started_at: Instant::now(), baseline_bytes });
255    }
256
257    fn phase_eta(
258        slot: &Mutex<Option<PhaseStart>>,
259        current_bytes: u64,
260        total_bytes: u64,
261    ) -> Option<Duration> {
262        let phase = *slot.lock().unwrap();
263        let phase = phase?;
264        let done = current_bytes.saturating_sub(phase.baseline_bytes);
265        let total = total_bytes.saturating_sub(phase.baseline_bytes);
266        eta_from_progress(phase.started_at.elapsed(), done, total)
267    }
268
269    fn extraction_eta(&self, current_bytes: u64) -> Option<Duration> {
270        Self::phase_eta(&self.extraction_phase, current_bytes, self.total_output_bytes)
271    }
272
273    fn verification_eta(&self, current_bytes: u64) -> Option<Duration> {
274        Self::phase_eta(&self.verification_phase, current_bytes, self.total_output_bytes)
275    }
276
277    /// Marks one archive as actively downloading.
278    pub(crate) fn download_started(&self) {
279        self.active_downloads.fetch_add(1, Ordering::Relaxed);
280    }
281
282    /// Marks one archive download as finished.
283    pub(crate) fn download_finished(&self) {
284        sub_bytes(&self.active_downloads, 1);
285    }
286
287    /// Marks one HTTP request as in flight.
288    pub(crate) fn request_started(&self) {
289        self.active_download_requests.fetch_add(1, Ordering::Relaxed);
290    }
291
292    /// Marks one HTTP request as finished.
293    pub(crate) fn request_finished(&self) {
294        sub_bytes(&self.active_download_requests, 1);
295    }
296
297    /// Marks one archive as actively extracting.
298    pub(crate) fn extraction_started(&self) {
299        if self.active_extractions.fetch_add(1, Ordering::Relaxed) == 0 {
300            Self::restart_phase(
301                &self.extraction_phase,
302                self.completed_output_bytes.load(Ordering::Relaxed),
303            );
304        }
305    }
306
307    /// Marks one archive extraction as finished.
308    pub(crate) fn extraction_finished(&self) {
309        sub_bytes(&self.active_extractions, 1);
310    }
311
312    /// Marks one archive as actively verifying outputs.
313    pub(crate) fn verification_started(&self) {
314        if self.active_verifications.fetch_add(1, Ordering::Relaxed) == 0 {
315            Self::restart_phase(
316                &self.verification_phase,
317                self.completed_output_bytes.load(Ordering::Relaxed),
318            );
319        }
320    }
321
322    /// Marks one archive verification as finished.
323    pub(crate) fn verification_finished(&self) {
324        sub_bytes(&self.active_verifications, 1);
325    }
326}
327
328fn sub_bytes(counter: &AtomicU64, bytes: u64) {
329    let _ = counter.try_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
330        Some(current.saturating_sub(bytes))
331    });
332}
333
334fn eta_from_progress(elapsed: Duration, done: u64, total: u64) -> Option<Duration> {
335    if done == 0 || done >= total {
336        return None;
337    }
338
339    let secs = elapsed.as_secs_f64();
340    if secs <= 0.0 {
341        return None;
342    }
343
344    let speed = done as f64 / secs;
345    if speed <= 0.0 {
346        return None;
347    }
348
349    Some(Duration::from_secs_f64((total - done) as f64 / speed))
350}
351
352fn format_percent(done: u64, total: u64) -> String {
353    if total == 0 {
354        return "100.0%".to_string();
355    }
356
357    format!("{:.1}%", (done as f64 / total as f64) * 100.0)
358}
359
360fn format_eta(eta: Option<Duration>) -> String {
361    eta.map(DownloadProgress::format_duration).unwrap_or_else(|| "unknown".to_string())
362}
363
364/// Global request limit for the blocking downloader.
365///
366/// The segmented path runs blocking reqwest clients on OS threads, so waiters park their
367/// thread. Slots are granted in arrival order: otherwise a worker that releases a slot takes
368/// it straight back before a woken waiter runs, and the waiter's piece can starve while it
369/// holds back an archive's contiguous downloaded prefix. A released slot is handed directly
370/// to the oldest waiter and only that thread is woken, because thousands of workers can wait
371/// here at high concurrency.
372pub(crate) struct DownloadRequestLimiter {
373    /// Maximum number of in-flight HTTP requests.
374    limit: usize,
375    /// Acquired slots and the waiters queued for one.
376    state: Mutex<RequestLimiterState>,
377}
378
379/// Slot accounting and the FIFO wait queue for [`DownloadRequestLimiter`].
380#[derive(Default)]
381struct RequestLimiterState {
382    /// Acquired request slots, including slots handed to waiters that have not woken yet.
383    active: usize,
384    /// Callers waiting for a slot, oldest first.
385    waiters: VecDeque<Arc<RequestWaiter>>,
386}
387
388/// A caller blocked in [`DownloadRequestLimiter::acquire`].
389struct RequestWaiter {
390    /// Set, while holding the limiter lock, when a released slot is handed to this waiter.
391    granted: AtomicBool,
392    /// Thread to unpark once the slot is handed over.
393    thread: Thread,
394}
395
396impl DownloadRequestLimiter {
397    /// Creates the shared request limiter.
398    pub(crate) fn new(limit: usize) -> Arc<Self> {
399        Arc::new(Self { limit: limit.max(1), state: Mutex::default() })
400    }
401
402    /// Returns the configured request limit.
403    pub(crate) fn max_concurrency(&self) -> usize {
404        self.limit
405    }
406
407    pub(crate) fn acquire<'a>(
408        &'a self,
409        progress: Option<&'a Arc<SharedProgress>>,
410        cancel_token: &CancellationToken,
411    ) -> Result<DownloadRequestPermit<'a>> {
412        if cancel_token.is_cancelled() {
413            return Err(eyre::eyre!("Download cancelled"));
414        }
415
416        let mut state = self.state.lock().unwrap();
417        if state.waiters.is_empty() && state.active < self.limit {
418            state.active += 1;
419            drop(state);
420            return Ok(DownloadRequestPermit::new(self, progress));
421        }
422
423        let waiter =
424            Arc::new(RequestWaiter { granted: AtomicBool::new(false), thread: thread::current() });
425        state.waiters.push_back(Arc::clone(&waiter));
426        drop(state);
427
428        loop {
429            if waiter.granted.load(Ordering::Acquire) {
430                return Ok(DownloadRequestPermit::new(self, progress));
431            }
432
433            if cancel_token.is_cancelled() {
434                let mut state = self.state.lock().unwrap();
435                if waiter.granted.load(Ordering::Acquire) {
436                    // A slot was handed over before the lock was taken, so pass it on.
437                    drop(state);
438                    self.release();
439                } else {
440                    state.waiters.retain(|queued| !Arc::ptr_eq(queued, &waiter));
441                }
442                return Err(eyre::eyre!("Download cancelled"));
443            }
444
445            // Wake periodically so cancellation can interrupt waiters even if
446            // no request finishes.
447            thread::park_timeout(Duration::from_millis(100));
448        }
449    }
450
451    /// Hands a released slot to the oldest waiter, or frees it if nobody is waiting.
452    fn release(&self) {
453        let mut state = self.state.lock().unwrap();
454        if let Some(waiter) = state.waiters.pop_front() {
455            // The slot moves to the waiter, so `active` stays the same. The flag is set under the
456            // lock so a waiter that is cancelling sees either the grant or its queue entry.
457            waiter.granted.store(true, Ordering::Release);
458            drop(state);
459            waiter.thread.unpark();
460        } else {
461            state.active = state.active.saturating_sub(1);
462        }
463    }
464}
465
466/// RAII permit for one in-flight HTTP request.
467///
468/// Dropping the permit releases a slot in the shared request limit and updates
469/// the live progress counters.
470pub(crate) struct DownloadRequestPermit<'a> {
471    /// Limiter that owns the request slot.
472    limiter: &'a DownloadRequestLimiter,
473    /// Shared progress counters updated when the permit drops.
474    progress: Option<&'a Arc<SharedProgress>>,
475}
476
477impl<'a> DownloadRequestPermit<'a> {
478    /// Wraps a slot already counted in `limiter` and marks the request as started.
479    fn new(limiter: &'a DownloadRequestLimiter, progress: Option<&'a Arc<SharedProgress>>) -> Self {
480        if let Some(progress) = progress {
481            progress.request_started();
482        }
483        Self { limiter, progress }
484    }
485}
486
487impl Drop for DownloadRequestPermit<'_> {
488    /// Releases the request slot and updates shared progress counters.
489    fn drop(&mut self) {
490        self.limiter.release();
491
492        if let Some(progress) = self.progress {
493            progress.request_finished();
494        }
495    }
496}
497
498/// Tracks one active archive download attempt.
499pub(crate) struct ArchiveDownloadProgress<'a> {
500    progress: Option<&'a Arc<SharedProgress>>,
501    downloaded: u64,
502    completed: bool,
503}
504
505impl<'a> ArchiveDownloadProgress<'a> {
506    /// Starts tracking one archive download attempt.
507    pub(crate) fn new(progress: Option<&'a Arc<SharedProgress>>) -> Self {
508        if let Some(progress) = progress {
509            progress.download_started();
510        }
511        Self { progress, downloaded: 0, completed: false }
512    }
513
514    /// Adds logical compressed bytes written by this attempt.
515    pub(crate) fn record_downloaded(&mut self, bytes: u64) {
516        self.downloaded += bytes;
517        if let Some(progress) = self.progress {
518            progress.add_active_download_bytes(bytes);
519        }
520    }
521
522    /// Returns whether this tracker has recorded any logical bytes itself.
523    pub(crate) fn has_tracked_bytes(&self) -> bool {
524        self.downloaded > 0
525    }
526
527    /// Moves this archive from active download bytes into completed download bytes.
528    pub(crate) fn complete(&mut self, total_bytes: u64) {
529        if self.completed {
530            return;
531        }
532        if let Some(progress) = self.progress {
533            progress.sub_active_download_bytes(self.downloaded);
534            progress.record_archive_download_complete(total_bytes);
535        }
536        self.downloaded = 0;
537        self.completed = true;
538    }
539}
540
541impl Drop for ArchiveDownloadProgress<'_> {
542    fn drop(&mut self) {
543        if let Some(progress) = self.progress {
544            progress.sub_active_download_bytes(self.downloaded);
545            progress.download_finished();
546        }
547    }
548}
549
550/// Tracks one active archive extraction attempt.
551pub(crate) struct ArchiveExtractionProgress {
552    progress: Option<Arc<SharedProgress>>,
553    extracted: Arc<AtomicU64>,
554    finished: bool,
555}
556
557/// Cloneable handle for reporting extracted bytes from background monitoring.
558#[derive(Clone)]
559pub(crate) struct ArchiveExtractionProgressHandle {
560    progress: Arc<SharedProgress>,
561    extracted: Arc<AtomicU64>,
562}
563
564impl ArchiveExtractionProgress {
565    /// Starts tracking one archive extraction attempt.
566    pub(crate) fn new(progress: Option<&Arc<SharedProgress>>) -> Self {
567        if let Some(progress) = progress {
568            progress.extraction_started();
569        }
570        Self {
571            progress: progress.cloned(),
572            extracted: Arc::new(AtomicU64::new(0)),
573            finished: false,
574        }
575    }
576
577    /// Returns a cloneable handle that can report extraction progress from another thread.
578    pub(crate) fn handle(&self) -> Option<ArchiveExtractionProgressHandle> {
579        Some(ArchiveExtractionProgressHandle {
580            progress: Arc::clone(self.progress.as_ref()?),
581            extracted: Arc::clone(&self.extracted),
582        })
583    }
584
585    /// Adds plain-output bytes extracted by this attempt.
586    pub(crate) fn record_extracted(&mut self, bytes: u64) {
587        if let Some(handle) = self.handle() {
588            handle.record_extracted(bytes);
589        }
590    }
591
592    /// Ends extraction tracking before verification begins.
593    pub(crate) fn finish(&mut self) {
594        if self.finished {
595            return;
596        }
597        if let Some(progress) = &self.progress {
598            progress.sub_active_extracted_output_bytes(self.extracted.swap(0, Ordering::Relaxed));
599        }
600        self.finished = true;
601    }
602}
603
604impl Drop for ArchiveExtractionProgress {
605    fn drop(&mut self) {
606        if let Some(progress) = &self.progress {
607            progress.sub_active_extracted_output_bytes(self.extracted.swap(0, Ordering::Relaxed));
608            progress.extraction_finished();
609        }
610    }
611}
612
613impl ArchiveExtractionProgressHandle {
614    /// Adds plain-output bytes extracted by this attempt.
615    pub(crate) fn record_extracted(&self, bytes: u64) {
616        self.extracted.fetch_add(bytes, Ordering::Relaxed);
617        self.progress.add_active_extracted_output_bytes(bytes);
618    }
619}
620
621/// Tracks one active archive verification attempt.
622///
623/// Bytes are recorded through a shared reference because output files are hashed in parallel.
624pub(crate) struct ArchiveVerificationProgress<'a> {
625    progress: Option<&'a Arc<SharedProgress>>,
626    verified: AtomicU64,
627    completed: bool,
628}
629
630impl<'a> ArchiveVerificationProgress<'a> {
631    /// Starts tracking one archive verification attempt.
632    pub(crate) fn new(progress: Option<&'a Arc<SharedProgress>>) -> Self {
633        if let Some(progress) = progress {
634            progress.verification_started();
635        }
636        Self { progress, verified: AtomicU64::new(0), completed: false }
637    }
638
639    /// Adds plain-output bytes hashed by this verification attempt.
640    pub(crate) fn record_verified(&self, bytes: u64) {
641        self.verified.fetch_add(bytes, Ordering::Relaxed);
642        if let Some(progress) = self.progress {
643            progress.add_active_verified_output_bytes(bytes);
644        }
645    }
646
647    /// Moves this archive from active verification bytes into completed output bytes.
648    pub(crate) fn complete(&mut self, total_bytes: u64) {
649        if self.completed {
650            return;
651        }
652        let verified = std::mem::take(self.verified.get_mut());
653        if let Some(progress) = self.progress {
654            progress.sub_active_verified_output_bytes(verified);
655            progress.record_archive_output_complete(total_bytes);
656        }
657        self.completed = true;
658    }
659}
660
661impl Drop for ArchiveVerificationProgress<'_> {
662    fn drop(&mut self) {
663        if let Some(progress) = self.progress {
664            progress.sub_active_verified_output_bytes(*self.verified.get_mut());
665            progress.verification_finished();
666        }
667    }
668}
669
670/// Adapter to track progress while reading (used for extraction in legacy path)
671pub(crate) struct ProgressReader<R> {
672    /// Wrapped reader that provides archive bytes.
673    reader: R,
674    /// Per-download progress tracker for legacy paths.
675    progress: DownloadProgress,
676    /// Cancellation token checked between reads.
677    cancel_token: CancellationToken,
678}
679
680impl<R: Read> ProgressReader<R> {
681    /// Wraps a reader with per-download progress tracking.
682    pub(crate) fn new(reader: R, total_size: u64, cancel_token: CancellationToken) -> Self {
683        Self { reader, progress: DownloadProgress::new(total_size), cancel_token }
684    }
685}
686
687impl<R: Read> Read for ProgressReader<R> {
688    /// Reads bytes, checks cancellation, and updates the local progress bar.
689    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
690        if self.cancel_token.is_cancelled() {
691            return Err(io::Error::new(io::ErrorKind::Interrupted, "download cancelled"));
692        }
693        let bytes = self.reader.read(buf)?;
694        if bytes > 0 &&
695            let Err(error) = self.progress.update(bytes as u64)
696        {
697            return Err(io::Error::other(error));
698        }
699        Ok(bytes)
700    }
701}
702
703/// Wrapper that bumps a shared atomic counter while writing data.
704/// Used for parallel downloads where a single display task shows aggregated progress.
705pub(crate) struct SharedProgressWriter<'a, W> {
706    /// Wrapped writer receiving downloaded bytes.
707    pub(crate) inner: W,
708    /// Shared counters updated as bytes are written.
709    pub(crate) progress: Arc<SharedProgress>,
710    /// Optional callback for logical bytes written by the current archive attempt.
711    pub(crate) on_written: Option<&'a mut dyn FnMut(u64)>,
712}
713
714impl<W: Write> Write for SharedProgressWriter<'_, W> {
715    /// Writes bytes and records them in shared progress.
716    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
717        if self.progress.is_cancelled() {
718            return Err(io::Error::new(io::ErrorKind::Interrupted, "download cancelled"));
719        }
720        let n = self.inner.write(buf)?;
721        self.progress.record_session_fetched_bytes(n as u64);
722        if let Some(on_written) = self.on_written.as_deref_mut() {
723            on_written(n as u64);
724        }
725        Ok(n)
726    }
727
728    /// Flushes the wrapped writer.
729    fn flush(&mut self) -> io::Result<()> {
730        self.inner.flush()
731    }
732}
733
734/// Wrapper that bumps a shared atomic counter while reading data.
735/// Used for streaming downloads where a single display task shows aggregated progress.
736pub(crate) struct SharedProgressReader<R> {
737    /// Wrapped reader producing streamed bytes.
738    pub(crate) inner: R,
739    /// Shared counters updated as bytes are read.
740    pub(crate) progress: Arc<SharedProgress>,
741}
742
743impl<R: Read> Read for SharedProgressReader<R> {
744    /// Reads bytes and records them in shared progress.
745    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
746        if self.progress.is_cancelled() {
747            return Err(io::Error::new(io::ErrorKind::Interrupted, "download cancelled"));
748        }
749        let n = self.inner.read(buf)?;
750        self.progress.record_session_fetched_bytes(n as u64);
751        Ok(n)
752    }
753}
754
755/// Spawns a background task that prints aggregated download progress.
756/// Returns a handle; drop it (or call `.abort()`) to stop.
757pub(crate) fn spawn_progress_display(progress: Arc<SharedProgress>) -> tokio::task::JoinHandle<()> {
758    tokio::spawn(async move {
759        let mut interval = tokio::time::interval(Duration::from_secs(3));
760        interval.tick().await;
761        loop {
762            tokio::select! {
763                _ = interval.tick() => {}
764                _ = progress.done.notified() => break,
765            }
766
767            let download_total = progress.total_download_bytes;
768            let output_total = progress.total_output_bytes;
769            if download_total == 0 && output_total == 0 {
770                continue;
771            }
772
773            let done = progress.archives_done.load(Ordering::Relaxed);
774            let all = progress.total_archives;
775            let active_downloads = progress.active_downloads.load(Ordering::Relaxed);
776            let active_requests = progress.active_download_requests.load(Ordering::Relaxed);
777            let active_extractions = progress.active_extractions.load(Ordering::Relaxed);
778            let active_verifications = progress.active_verifications.load(Ordering::Relaxed);
779            let downloaded = progress.logical_downloaded_bytes();
780            let extracted = progress.extracting_output_bytes();
781            let verified = progress.verifying_output_bytes();
782            let elapsed = DownloadProgress::format_duration(progress.started_at.elapsed());
783            let download_total_display = DownloadProgress::format_size(download_total);
784            let output_total_display = DownloadProgress::format_size(output_total);
785            let downloaded_display = DownloadProgress::format_size(downloaded);
786            let extracted_display = DownloadProgress::format_size(extracted);
787            let active_download_phase = active_downloads > 0 || active_requests > 0;
788
789            if active_download_phase {
790                info!(target: "reth::cli",
791                    archives = format_args!("{done}/{all}"),
792                    progress = %format_percent(downloaded, download_total),
793                    elapsed = %elapsed,
794                    eta = %format_eta(eta_from_progress(progress.started_at.elapsed(), downloaded, download_total)),
795                    bytes = format_args!("{downloaded_display}/{download_total_display}"),
796                    "Downloading snapshot archives"
797                );
798            } else if active_extractions > 0 {
799                info!(target: "reth::cli",
800                    archives = format_args!("{done}/{all}"),
801                    progress = %format_percent(extracted, output_total),
802                    elapsed = %elapsed,
803                    eta = %format_eta(progress.extraction_eta(extracted)),
804                    bytes = format_args!("{extracted_display}/{output_total_display}"),
805                    "Extracting snapshot archives"
806                );
807            } else if active_verifications > 0 {
808                info!(target: "reth::cli",
809                    archives = format_args!("{done}/{all}"),
810                    progress = %format_percent(verified, output_total),
811                    elapsed = %elapsed,
812                    eta = %format_eta(progress.verification_eta(verified)),
813                    bytes = format_args!("{}/{output_total_display}", DownloadProgress::format_size(verified)),
814                    "Verifying snapshot archives"
815                );
816            } else {
817                continue;
818            }
819        }
820
821        let completed = progress.verified_output_bytes();
822        let completed_display = DownloadProgress::format_size(completed);
823        let output_total = DownloadProgress::format_size(progress.total_output_bytes);
824        info!(target: "reth::cli",
825            archives = format_args!("{}/{}", progress.total_archives, progress.total_archives),
826            progress = "100.0%",
827            elapsed = %DownloadProgress::format_duration(progress.started_at.elapsed()),
828            eta = "0s",
829            bytes = format_args!("{completed_display}/{output_total}"),
830            "Snapshot archive processing complete"
831        );
832    })
833}
834
835#[cfg(test)]
836mod tests {
837    use super::*;
838    use std::sync::atomic::Ordering;
839
840    #[test]
841    fn shared_progress_separates_session_fetch_from_logical_progress() {
842        let progress = SharedProgress::new(10, 20, 1, CancellationToken::new());
843
844        progress.record_session_fetched_bytes(10);
845        progress.record_session_fetched_bytes(10);
846        progress.record_archive_download_complete(10);
847        progress.record_archive_output_complete(20);
848
849        assert_eq!(progress.session_fetched_bytes.load(Ordering::Relaxed), 20);
850        assert_eq!(progress.logical_downloaded_bytes(), 10);
851        assert_eq!(progress.verified_output_bytes(), 20);
852        assert_eq!(progress.archives_done.load(Ordering::Relaxed), 1);
853    }
854
855    #[test]
856    fn archive_download_progress_rolls_back_unfinished_attempts() {
857        let progress = SharedProgress::new(10, 20, 1, CancellationToken::new());
858
859        {
860            let mut download = ArchiveDownloadProgress::new(Some(&progress));
861            download.record_downloaded(4);
862            assert_eq!(progress.logical_downloaded_bytes(), 4);
863        }
864
865        assert_eq!(progress.logical_downloaded_bytes(), 0);
866        assert_eq!(progress.active_downloads.load(Ordering::Relaxed), 0);
867    }
868
869    #[test]
870    fn extraction_phase_baseline_restarts_after_idle() {
871        let progress = SharedProgress::new(10, 100, 1, CancellationToken::new());
872
873        progress.extraction_started();
874        assert_eq!(progress.extraction_phase.lock().unwrap().as_ref().unwrap().baseline_bytes, 0);
875
876        progress.completed_output_bytes.store(25, Ordering::Relaxed);
877        progress.extraction_started();
878        assert_eq!(progress.extraction_phase.lock().unwrap().as_ref().unwrap().baseline_bytes, 0);
879
880        progress.extraction_finished();
881        progress.extraction_finished();
882        progress.extraction_started();
883        assert_eq!(progress.extraction_phase.lock().unwrap().as_ref().unwrap().baseline_bytes, 25);
884    }
885
886    #[test]
887    fn verification_phase_baseline_restarts_after_idle() {
888        let progress = SharedProgress::new(10, 100, 1, CancellationToken::new());
889
890        progress.verification_started();
891        assert_eq!(progress.verification_phase.lock().unwrap().as_ref().unwrap().baseline_bytes, 0);
892
893        progress.completed_output_bytes.store(40, Ordering::Relaxed);
894        progress.verification_started();
895        assert_eq!(progress.verification_phase.lock().unwrap().as_ref().unwrap().baseline_bytes, 0);
896
897        progress.verification_finished();
898        progress.verification_finished();
899        progress.verification_started();
900        assert_eq!(
901            progress.verification_phase.lock().unwrap().as_ref().unwrap().baseline_bytes,
902            40
903        );
904    }
905
906    #[tokio::test]
907    async fn progress_display_exits_when_done() {
908        let progress = SharedProgress::new(10, 20, 1, CancellationToken::new());
909        let handle = spawn_progress_display(Arc::clone(&progress));
910
911        progress.done.notify_one();
912
913        // The task must exit right away instead of on its next 3s progress tick.
914        tokio::time::timeout(Duration::from_secs(1), handle).await.unwrap().unwrap();
915    }
916
917    #[test]
918    fn request_limiter_serves_waiters_before_a_releasing_caller() {
919        let limiter = DownloadRequestLimiter::new(1);
920        let token = CancellationToken::new();
921        let order = Mutex::new(Vec::new());
922
923        std::thread::scope(|scope| {
924            let held = limiter.acquire(None, &token).unwrap();
925            scope.spawn(|| {
926                let _permit = limiter.acquire(None, &token).unwrap();
927                order.lock().unwrap().push("waiter");
928            });
929            while limiter.state.lock().unwrap().waiters.is_empty() {
930                std::thread::yield_now();
931            }
932
933            // Re-acquiring right after a release must not jump ahead of the queued waiter.
934            drop(held);
935            let _permit = limiter.acquire(None, &token).unwrap();
936            order.lock().unwrap().push("releaser");
937        });
938
939        assert_eq!(*order.lock().unwrap(), ["waiter", "releaser"]);
940    }
941
942    #[test]
943    fn request_limiter_cancelled_waiter_leaves_the_queue() {
944        let limiter = DownloadRequestLimiter::new(1);
945        let token = CancellationToken::new();
946        let cancelled = CancellationToken::new();
947
948        std::thread::scope(|scope| {
949            let held = limiter.acquire(None, &token).unwrap();
950            let waiter = scope.spawn(|| limiter.acquire(None, &cancelled).map(drop));
951            while limiter.state.lock().unwrap().waiters.is_empty() {
952                std::thread::yield_now();
953            }
954
955            cancelled.cancel();
956            let error = waiter.join().unwrap().unwrap_err();
957            assert_eq!(error.to_string(), "Download cancelled");
958            assert!(limiter.state.lock().unwrap().waiters.is_empty());
959
960            // The cancelled waiter must not hold back the slot or later callers.
961            drop(held);
962            drop(limiter.acquire(None, &token).unwrap());
963        });
964
965        let state = limiter.state.lock().unwrap();
966        assert_eq!(state.active, 0);
967        assert!(state.waiters.is_empty());
968    }
969
970    #[test]
971    fn request_limiter_never_exceeds_its_limit() {
972        let limiter = DownloadRequestLimiter::new(3);
973        let token = CancellationToken::new();
974        let in_flight = AtomicU64::new(0);
975        let max_in_flight = AtomicU64::new(0);
976
977        std::thread::scope(|scope| {
978            for _ in 0..32 {
979                scope.spawn(|| {
980                    for _ in 0..50 {
981                        let _permit = limiter.acquire(None, &token).unwrap();
982                        let now = in_flight.fetch_add(1, Ordering::SeqCst) + 1;
983                        max_in_flight.fetch_max(now, Ordering::SeqCst);
984                        std::thread::yield_now();
985                        in_flight.fetch_sub(1, Ordering::SeqCst);
986                    }
987                });
988            }
989        });
990
991        assert!(max_in_flight.load(Ordering::SeqCst) <= 3);
992        let state = limiter.state.lock().unwrap();
993        assert_eq!(state.active, 0);
994        assert!(state.waiters.is_empty());
995    }
996}