Skip to main content

exarch_core/
report.rs

1//! Extraction operation reporting.
2
3use std::collections::BTreeMap;
4use std::fmt;
5use std::io;
6use std::num::NonZeroUsize;
7use std::path::Path;
8use std::path::PathBuf;
9use std::time::Duration;
10
11use crate::ArchiveError;
12use crate::Result;
13use crate::closed_enum::closed_enum;
14use crate::error::QuotaResource;
15
16closed_enum! {
17    /// Why an entry was left out of an extraction or creation.
18    ///
19    /// The string form is stable and shared by every front end (for example as
20    /// a `--json` key).
21    ///
22    /// # Examples
23    ///
24    /// ```
25    /// use exarch_core::SkipKind;
26    ///
27    /// assert_eq!(SkipKind::Duplicate.as_str(), "duplicate");
28    /// assert!(SkipKind::ALL.contains(&SkipKind::Excluded));
29    /// ```
30    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
31    #[non_exhaustive]
32    pub enum SkipKind {
33        /// A pre-existing destination entry kept under the skip-duplicates policy
34        Duplicate => "duplicate",
35        /// A file refused by the extension allowlist
36        ExtensionNotAllowed => "extension_not_allowed",
37        /// An entry matched by a creation exclude pattern
38        Excluded => "excluded",
39        /// A hidden entry left out by a creation configuration
40        Hidden => "hidden",
41        /// A file larger than the creation file size limit
42        OverMaxFileSize => "over_max_file_size",
43        /// A symlink that cannot be stored (not followed, or unsupported here)
44        SymlinkUnsupported => "symlink_unsupported",
45        /// An entry that could not be read
46        Unreadable => "unreadable",
47    }
48}
49
50/// One entry left out of an operation, with the reason.
51///
52/// # Examples
53///
54/// ```
55/// use exarch_core::Skip;
56/// use exarch_core::SkipKind;
57///
58/// let skip = Skip::new(SkipKind::Excluded, "target/debug");
59/// assert_eq!(skip.kind, SkipKind::Excluded);
60/// assert_eq!(skip.to_string(), "skipped target/debug (excluded)");
61/// ```
62#[derive(Debug, Clone, PartialEq, Eq)]
63#[non_exhaustive]
64pub struct Skip {
65    /// Why the entry was skipped.
66    pub kind: SkipKind,
67
68    /// The entry's path as the operation names it.
69    pub path: PathBuf,
70
71    /// The I/O failure behind an [`SkipKind::Unreadable`] skip.
72    pub io_kind: Option<io::ErrorKind>,
73}
74
75impl Skip {
76    /// Builds a skip of `kind` for `path`, with no I/O failure attached.
77    #[must_use]
78    pub fn new(kind: SkipKind, path: impl Into<PathBuf>) -> Self {
79        Self {
80            kind,
81            path: path.into(),
82            io_kind: None,
83        }
84    }
85
86    /// Attaches the I/O failure that caused the skip.
87    #[must_use]
88    pub const fn with_io_kind(mut self, io_kind: io::ErrorKind) -> Self {
89        self.io_kind = Some(io_kind);
90        self
91    }
92}
93
94impl fmt::Display for Skip {
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        write!(f, "skipped {} ({})", self.path.display(), self.kind)?;
97        self.io_kind
98            .map_or(Ok(()), |io_kind| write!(f, ": {io_kind}"))
99    }
100}
101
102/// Everything an operation left out: exact counts per [`SkipKind`] plus a
103/// bounded sample of the individual entries.
104///
105/// The counts are exact however many entries are skipped. The sample keeps the
106/// first [`Skips::SAMPLE_CAP`] entries, so a report stays small on an archive
107/// with millions of skipped entries (#490, #495).
108///
109/// # Examples
110///
111/// ```
112/// use exarch_core::ExtractionReport;
113///
114/// let report = ExtractionReport::new();
115/// assert_eq!(report.skipped.total(), 0);
116/// assert!(report.skipped.sample().is_empty());
117/// ```
118#[derive(Debug, Clone, Default, PartialEq, Eq)]
119pub struct Skips {
120    // Boxed so a report with nothing skipped stays small: the report rides
121    // inside `ArchiveError::PartialExtraction`.
122    detail: Option<Box<SkipDetail>>,
123}
124
125#[derive(Debug, Clone, Default, PartialEq, Eq)]
126struct SkipDetail {
127    counts: BTreeMap<SkipKind, usize>,
128    sample: Vec<Skip>,
129}
130
131impl Skips {
132    /// The most individual skips [`sample`](Self::sample) keeps.
133    pub const SAMPLE_CAP: usize = 64;
134
135    /// Returns how many entries were skipped, over all kinds.
136    #[must_use]
137    pub fn total(&self) -> usize {
138        self.detail.as_ref().map_or(0, |detail| {
139            detail
140                .counts
141                .values()
142                .fold(0, |sum, count| sum.saturating_add(*count))
143        })
144    }
145
146    /// Returns how many entries were skipped for `kind`.
147    #[must_use]
148    pub fn count(&self, kind: SkipKind) -> usize {
149        self.detail
150            .as_ref()
151            .and_then(|detail| detail.counts.get(&kind))
152            .copied()
153            .unwrap_or(0)
154    }
155
156    /// Returns the first [`SAMPLE_CAP`](Self::SAMPLE_CAP) skipped entries, in
157    /// the order they were skipped.
158    #[must_use]
159    pub fn sample(&self) -> &[Skip] {
160        self.detail
161            .as_ref()
162            .map_or(&[], |detail| detail.sample.as_slice())
163    }
164
165    /// Returns whether nothing was skipped.
166    #[must_use]
167    pub fn is_empty(&self) -> bool {
168        self.detail.is_none()
169    }
170
171    /// Counts `skip`, failing closed instead of wrapping when its kind's
172    /// counter is at its maximum (#515).
173    ///
174    /// # Errors
175    ///
176    /// Returns [`ArchiveError::QuotaExceeded`] with
177    /// [`QuotaResource::IntegerOverflow`] when the counter would overflow.
178    ///
179    /// # Examples
180    ///
181    /// ```
182    /// use exarch_core::Skip;
183    /// use exarch_core::SkipKind;
184    /// use exarch_core::Skips;
185    ///
186    /// let mut skips = Skips::default();
187    /// skips.record(Skip::new(SkipKind::Excluded, "a.tmp"))?;
188    /// assert_eq!(skips.count(SkipKind::Excluded), 1);
189    /// # Ok::<(), exarch_core::ArchiveError>(())
190    /// ```
191    pub fn record(&mut self, skip: Skip) -> Result<()> {
192        let detail = self.detail.get_or_insert_default();
193        let count = detail.counts.entry(skip.kind).or_insert(0);
194        *count = count.checked_add(1).ok_or(ArchiveError::QuotaExceeded {
195            resource: QuotaResource::IntegerOverflow,
196        })?;
197        if detail.sample.len() < Self::SAMPLE_CAP {
198            detail.sample.push(skip);
199        }
200        Ok(())
201    }
202
203    #[cfg(test)]
204    pub(crate) fn with_saturated_count(kind: SkipKind) -> Self {
205        Self {
206            detail: Some(Box::new(SkipDetail {
207                counts: BTreeMap::from([(kind, usize::MAX)]),
208                sample: Vec::new(),
209            })),
210        }
211    }
212}
213
214/// A condition of an extraction worth surfacing that is not a skipped entry.
215///
216/// # Examples
217///
218/// ```
219/// use exarch_core::ExtractionWarning;
220///
221/// let warning = ExtractionWarning::AntiItemsSkipped { count: 1 };
222/// assert_eq!(
223///     warning.to_string(),
224///     "skipped 1 7z anti-item (deletion markers are not applied)"
225/// );
226/// ```
227#[derive(Debug, Clone, PartialEq, Eq)]
228#[non_exhaustive]
229pub enum ExtractionWarning {
230    /// 7z anti-items, which mark deletions in an update archive, were not
231    /// applied.
232    AntiItemsSkipped {
233        /// How many anti-items the archive holds.
234        count: u64,
235    },
236
237    /// The backup of the original destination, kept for an atomic
238    /// replacement, could not be removed and must be cleaned up manually.
239    BackupCleanupFailed {
240        /// Where the backup remains.
241        path: PathBuf,
242        /// Whether the backup's identity could not be verified before removal.
243        identity_unverified: bool,
244        /// Why the removal failed.
245        error: String,
246    },
247}
248
249impl fmt::Display for ExtractionWarning {
250    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
251        match self {
252            Self::BackupCleanupFailed {
253                path,
254                identity_unverified,
255                error,
256            } => {
257                let qualifier = if *identity_unverified {
258                    " (its identity could not be verified on this platform)"
259                } else {
260                    ""
261                };
262                write!(
263                    f,
264                    "failed to remove backup of the original destination at {}{qualifier} \
265                     ({error}); it must be cleaned up manually",
266                    path.display()
267                )
268            }
269            Self::AntiItemsSkipped { count } => {
270                let noun = if *count == 1 {
271                    "anti-item"
272                } else {
273                    "anti-items"
274                };
275                write!(
276                    f,
277                    "skipped {count} 7z {noun} (deletion markers are not applied)"
278                )
279            }
280        }
281    }
282}
283
284/// Report of an archive extraction operation.
285///
286/// Contains statistics and metadata about the extraction process.
287#[derive(Debug, Clone, Default)]
288#[non_exhaustive]
289pub struct ExtractionReport {
290    /// Number of files successfully extracted.
291    pub files_extracted: usize,
292
293    /// Number of directories created.
294    pub directories_created: usize,
295
296    /// Number of symlinks created.
297    pub symlinks_created: usize,
298
299    /// Total bytes written to disk.
300    pub bytes_written: u64,
301
302    /// Duration of the extraction operation.
303    pub duration: Duration,
304
305    /// Entries left out of the extraction, by reason.
306    pub skipped: Skips,
307
308    /// Conditions worth surfacing that are not skipped entries.
309    pub warnings: Vec<ExtractionWarning>,
310}
311
312impl ExtractionReport {
313    /// Creates a new empty extraction report.
314    #[must_use]
315    pub fn new() -> Self {
316        Self::default()
317    }
318
319    /// Adds a warning to the report.
320    pub fn add_warning(&mut self, warning: ExtractionWarning) {
321        self.warnings.push(warning);
322    }
323
324    /// Returns how many entries were skipped, over all reasons.
325    #[must_use]
326    pub fn files_skipped(&self) -> usize {
327        self.skipped.total()
328    }
329
330    /// Returns the total number of items actually written to disk
331    /// (`files_extracted + directories_created + symlinks_created`).
332    ///
333    /// This deliberately excludes [`files_skipped`](Self::files_skipped): a
334    /// report can carry meaningful progress — skipped entries, warnings —
335    /// while this is `0`. Callers deciding whether a report is worth
336    /// surfacing (e.g. `ArchiveError::partial_or`) must check
337    /// `files_skipped`/[`has_warnings`](Self::has_warnings) too, not rely on
338    /// this alone.
339    #[must_use]
340    pub fn total_items(&self) -> usize {
341        self.files_extracted + self.directories_created + self.symlinks_created
342    }
343
344    /// Returns whether any warnings were generated.
345    #[must_use]
346    pub fn has_warnings(&self) -> bool {
347        !self.warnings.is_empty()
348    }
349}
350
351/// How many entries an operation has, when it knows.
352///
353/// A stream such as a TAR archive cannot count its entries before reading
354/// them, so it reports [`Unknown`](Self::Unknown) rather than a count a
355/// callback might divide by.
356///
357/// # Examples
358///
359/// ```
360/// use exarch_core::EntryTotal;
361///
362/// let total = EntryTotal::Known(3);
363/// assert_eq!(total.known(), Some(3));
364/// assert_eq!(EntryTotal::Unknown.known(), None);
365/// ```
366#[derive(Debug, Clone, Copy, PartialEq, Eq)]
367#[non_exhaustive]
368pub enum EntryTotal {
369    /// The operation holds exactly this many entries.
370    Known(usize),
371
372    /// The entry count is not known until the operation ends.
373    Unknown,
374}
375
376impl EntryTotal {
377    /// Returns the count when it is known.
378    #[must_use]
379    pub const fn known(self) -> Option<usize> {
380        match self {
381            Self::Known(total) => Some(total),
382            Self::Unknown => None,
383        }
384    }
385}
386
387/// Where an entry sits in the operation: its 1-based number and the total.
388///
389/// # Examples
390///
391/// ```
392/// use exarch_core::EntryPosition;
393/// use exarch_core::EntryTotal;
394///
395/// let position = EntryPosition::at_index(0, EntryTotal::Known(4));
396/// assert_eq!(position.current.get(), 1);
397/// assert_eq!(position.total, EntryTotal::Known(4));
398/// ```
399#[derive(Debug, Clone, Copy, PartialEq, Eq)]
400#[non_exhaustive]
401pub struct EntryPosition {
402    /// The entry's number, counting from 1.
403    pub current: NonZeroUsize,
404
405    /// How many entries the operation holds, when known.
406    pub total: EntryTotal,
407}
408
409impl EntryPosition {
410    /// Builds a position from its parts.
411    #[must_use]
412    pub const fn new(current: NonZeroUsize, total: EntryTotal) -> Self {
413        Self { current, total }
414    }
415
416    /// Builds the position of the entry at the 0-based `index`.
417    #[must_use]
418    pub const fn at_index(index: usize, total: EntryTotal) -> Self {
419        Self::new(NonZeroUsize::MIN.saturating_add(index), total)
420    }
421}
422
423/// Callback trait for progress reporting during archive operations.
424///
425/// Implement this trait to receive progress updates during extraction or
426/// creation. The trait requires `Send` to allow use in multi-threaded contexts.
427///
428/// # Examples
429///
430/// ```
431/// use exarch_core::EntryPosition;
432/// use exarch_core::EntryTotal;
433/// use exarch_core::ProgressCallback;
434/// use std::path::Path;
435///
436/// struct SimpleProgress;
437///
438/// impl ProgressCallback for SimpleProgress {
439///     fn on_entry_start(&mut self, path: &Path, position: EntryPosition) {
440///         match position.total {
441///             EntryTotal::Known(total) => {
442///                 println!(
443///                     "Processing {}/{}: {}",
444///                     position.current,
445///                     total,
446///                     path.display()
447///                 );
448///             }
449///             _ => println!("Processing {}: {}", position.current, path.display()),
450///         }
451///     }
452///
453///     fn on_bytes_written(&mut self, bytes: u64) {
454///         // Track bytes written
455///     }
456///
457///     fn on_entry_complete(&mut self, path: &Path) {
458///         println!("Completed: {}", path.display());
459///     }
460///
461///     fn on_complete(&mut self) {
462///         println!("Operation complete");
463///     }
464/// }
465/// ```
466pub trait ProgressCallback: Send {
467    /// Called when starting to process an entry.
468    ///
469    /// # Arguments
470    ///
471    /// * `path` - Path of the entry being processed
472    /// * `position` - The entry's 1-based number and the entry total, which is
473    ///   [`EntryTotal::Unknown`] for a stream
474    fn on_entry_start(&mut self, path: &Path, position: EntryPosition);
475
476    /// Called when bytes are written during extraction or read during creation.
477    ///
478    /// Granularity is per-entry: called once after the full entry is written.
479    /// Partial writes on failure are not reported. Not called for entries that
480    /// produce no output (directories, skipped entries).
481    ///
482    /// # Arguments
483    ///
484    /// * `bytes` - Number of bytes written/read in this update
485    fn on_bytes_written(&mut self, bytes: u64);
486
487    /// Called when an entry has been completely processed.
488    ///
489    /// Always called after [`on_entry_start`](Self::on_entry_start) for the
490    /// same entry, including when extraction of that entry fails. Callers can
491    /// rely on this pairing for cleanup or progress accounting.
492    ///
493    /// # Arguments
494    ///
495    /// * `path` - Path of the entry that was completed
496    fn on_entry_complete(&mut self, path: &Path);
497
498    /// Called when the entire operation completes successfully.
499    ///
500    /// Not called if the operation fails or results in a partial extraction.
501    /// Implementors must not rely on this method for cleanup — use `Drop`
502    /// instead.
503    fn on_complete(&mut self);
504
505    /// Whether the operation should stop, polled by archive creation between
506    /// entries and once more before the archive is published.
507    ///
508    /// The callbacks above cannot fail, so a callback that hit an error of its
509    /// own (a raising script callback, a closed channel) reports it here:
510    /// creation then stops with an [`ArchiveError::Io`] of kind
511    /// [`Interrupted`](std::io::ErrorKind::Interrupted), the staged output is
512    /// discarded and a previous archive at the output path stays untouched.
513    /// The default never cancels.
514    fn is_cancelled(&mut self) -> bool {
515        false
516    }
517}
518
519/// No-op implementation of `ProgressCallback` that does nothing.
520///
521/// Use this when you don't need progress reporting but the API requires
522/// a callback implementation.
523#[derive(Debug, Default)]
524pub struct NoopProgress;
525
526impl ProgressCallback for NoopProgress {
527    fn on_entry_start(&mut self, _path: &Path, _position: EntryPosition) {}
528
529    fn on_bytes_written(&mut self, _bytes: u64) {}
530
531    fn on_entry_complete(&mut self, _path: &Path) {}
532
533    fn on_complete(&mut self) {}
534}
535
536#[cfg(test)]
537#[allow(clippy::unwrap_used)] // Allow unwrap in tests for brevity
538mod tests {
539    use super::*;
540    use std::assert_matches;
541
542    #[test]
543    fn test_new_report() {
544        let report = ExtractionReport::new();
545        assert_eq!(report.files_extracted, 0);
546        assert_eq!(report.directories_created, 0);
547        assert_eq!(report.bytes_written, 0);
548        assert!(!report.has_warnings());
549        assert_eq!(report.files_skipped(), 0);
550    }
551
552    #[test]
553    fn test_add_warning() {
554        let mut report = ExtractionReport::new();
555        report.add_warning(ExtractionWarning::AntiItemsSkipped { count: 2 });
556        assert!(report.has_warnings());
557        assert_eq!(report.warnings.len(), 1);
558    }
559
560    #[test]
561    fn test_total_items() {
562        let mut report = ExtractionReport::new();
563        report.files_extracted = 10;
564        report.directories_created = 5;
565        report.symlinks_created = 2;
566        assert_eq!(report.total_items(), 17);
567    }
568
569    #[test]
570    fn skips_count_per_kind_and_bound_the_sample() {
571        let mut skips = Skips::default();
572        for i in 0..Skips::SAMPLE_CAP + 10 {
573            skips
574                .record(Skip::new(SkipKind::Duplicate, format!("f{i}")))
575                .unwrap();
576        }
577        skips
578            .record(Skip::new(SkipKind::Excluded, "x").with_io_kind(io::ErrorKind::NotFound))
579            .unwrap();
580        assert_eq!(skips.count(SkipKind::Duplicate), Skips::SAMPLE_CAP + 10);
581        assert_eq!(skips.count(SkipKind::Excluded), 1);
582        assert_eq!(skips.count(SkipKind::Hidden), 0);
583        assert_eq!(skips.total(), Skips::SAMPLE_CAP + 11);
584        assert_eq!(skips.sample().len(), Skips::SAMPLE_CAP);
585        assert!(!skips.is_empty());
586    }
587
588    #[test]
589    fn skips_fail_closed_at_a_saturated_counter() {
590        let mut skips = Skips::with_saturated_count(SkipKind::Duplicate);
591        let err = skips
592            .record(Skip::new(SkipKind::Duplicate, "a"))
593            .unwrap_err();
594        assert_matches!(
595            err,
596            ArchiveError::QuotaExceeded {
597                resource: QuotaResource::IntegerOverflow
598            }
599        );
600        assert_eq!(skips.count(SkipKind::Duplicate), usize::MAX);
601        assert!(skips.sample().is_empty());
602    }
603
604    #[test]
605    fn every_skip_kind_has_a_distinct_string_form() {
606        let mut seen: Vec<&str> = SkipKind::ALL.iter().map(|kind| kind.as_str()).collect();
607        seen.sort_unstable();
608        seen.dedup();
609        assert_eq!(seen.len(), SkipKind::ALL.len());
610    }
611
612    #[test]
613    fn entry_position_numbers_from_one() {
614        let position = EntryPosition::at_index(usize::MAX, EntryTotal::Unknown);
615        assert_eq!(position.current.get(), usize::MAX);
616        assert_eq!(
617            EntryPosition::at_index(0, EntryTotal::Unknown)
618                .current
619                .get(),
620            1
621        );
622    }
623}