Skip to main content

gix_pack/index/traverse/
mod.rs

1use gix_error::{Result, corruption};
2use std::sync::atomic::AtomicBool;
3
4use gix_error::{ErrorExt, ResultExt, bail, message};
5use gix_parallel as parallel;
6use gix_utils::progress::Progress;
7
8use crate::index;
9
10mod reduce;
11///
12pub mod with_index;
13///
14pub mod with_lookup;
15use reduce::Reducer;
16
17use gix_utils::progress::DynNestedProgress;
18
19mod types;
20pub use types::{Algorithm, ProgressId, SafetyCheck, Statistics};
21
22/// Traversal options for [`index::File::traverse()`].
23#[derive(Debug, Clone)]
24pub struct Options<F> {
25    /// The algorithm to employ.
26    pub traversal: Algorithm,
27    /// If `Some`, only use the given number of threads. Otherwise, the number of threads to use will be selected based on
28    /// the number of available logical cores.
29    pub thread_limit: Option<usize>,
30    /// The kinds of safety checks to perform.
31    pub check: SafetyCheck,
32    /// If `Some`, rejects individual allocations above the given number of bytes while resolving decoded object and
33    /// delta result buffers during delta-tree traversal. `Some(0)` rejects all non-empty allocations.
34    pub alloc_limit_bytes: Option<usize>,
35    /// A function to create a pack cache
36    pub make_pack_lookup_cache: F,
37}
38
39impl Default for Options<fn() -> crate::cache::Never> {
40    fn default() -> Self {
41        Options {
42            check: Default::default(),
43            traversal: Default::default(),
44            thread_limit: None,
45            alloc_limit_bytes: None,
46            make_pack_lookup_cache: || crate::cache::Never,
47        }
48    }
49}
50
51/// The outcome of the [`traverse()`][index::File::traverse()] method.
52pub struct Outcome {
53    /// The checksum obtained when hashing the file, which matched the checksum contained within the file.
54    pub actual_index_checksum: gix_hash::ObjectId,
55    /// The statistics obtained during traversal.
56    pub statistics: Statistics,
57}
58
59/// Traversal of pack data files using an index file
60impl<T> index::File<T>
61where
62    T: crate::FileData + Sync,
63{
64    /// Iterate through all _decoded objects_ in the given `pack` and handle them with a `Processor`.
65    /// The return value is (pack-checksum, [`Outcome`], `progress`), thus the pack traversal will always verify
66    /// the whole packs checksum to assure it was correct. In case of bit-rod, the operation will abort early without
67    /// verifying all objects using the [interrupt mechanism][gix_utils::interrupt] mechanism.
68    ///
69    /// # Algorithms
70    ///
71    /// Using the [`Options::traversal`] field one can chose between two algorithms providing different tradeoffs. Both invoke
72    /// `new_processor()` to create functions receiving decoded objects, their object kind, index entry and a progress instance to provide
73    /// progress information.
74    ///
75    /// * [`Algorithm::DeltaTreeLookup`] builds an index to avoid any unnecessary computation while resolving objects, avoiding
76    ///   the need for a cache entirely, rendering `new_cache()` unused.
77    ///   One could also call [`traverse_with_index()`][index::File::traverse_with_index()] directly.
78    /// * [`Algorithm::Lookup`] uses a cache created by `new_cache()` to avoid having to re-compute all bases of a delta-chain while
79    ///   decoding objects.
80    ///   One could also call [`traverse_with_lookup()`][index::File::traverse_with_lookup()] directly.
81    ///
82    /// Use [`thread_limit`][Options::thread_limit] to further control parallelism and [`check`][SafetyCheck] to define how much the passed
83    /// objects shall be verified beforehand.
84    pub fn traverse<C, Processor, F, D>(
85        &self,
86        pack: &crate::data::File<D>,
87        progress: &mut dyn DynNestedProgress,
88        should_interrupt: &AtomicBool,
89        processor: Processor,
90        Options {
91            traversal,
92            thread_limit,
93            check,
94            alloc_limit_bytes,
95            make_pack_lookup_cache,
96        }: Options<F>,
97    ) -> Result<Outcome>
98    where
99        C: crate::cache::DecodeEntry,
100        Processor: FnMut(gix_object::Kind, &[u8], &index::Entry, &dyn Progress) -> Result + Send + Clone,
101        F: Fn() -> C + Send + Clone,
102        D: crate::FileData + Send + Sync,
103    {
104        match traversal {
105            Algorithm::Lookup => self.traverse_with_lookup(
106                processor,
107                pack,
108                progress,
109                should_interrupt,
110                with_lookup::Options {
111                    thread_limit,
112                    check,
113                    make_pack_lookup_cache,
114                },
115            ),
116            Algorithm::DeltaTreeLookup => self.traverse_with_index(
117                pack,
118                processor,
119                progress,
120                should_interrupt,
121                with_index::Options {
122                    check,
123                    thread_limit,
124                    alloc_limit_bytes,
125                },
126            ),
127        }
128    }
129
130    fn possibly_verify<D>(
131        &self,
132        pack: &crate::data::File<D>,
133        check: SafetyCheck,
134        pack_progress: &mut dyn Progress,
135        index_progress: &mut dyn Progress,
136        should_interrupt: &AtomicBool,
137    ) -> Result<gix_hash::ObjectId>
138    where
139        D: crate::FileData + Send + Sync,
140    {
141        Ok(if check.file_checksum() {
142            pack.checksum()
143                .verify(&self.pack_checksum())
144                .or_raise(|| corruption("Pack checksum differs from index"))?;
145            let (pack_res, id) = parallel::join(
146                move || pack.verify_checksum(pack_progress, should_interrupt),
147                move || self.verify_checksum(index_progress, should_interrupt),
148            );
149            pack_res?;
150            id?
151        } else {
152            self.index_checksum()
153        })
154    }
155
156    #[expect(clippy::too_many_arguments)]
157    fn decode_and_process_entry<C, D>(
158        &self,
159        check: SafetyCheck,
160        pack: &crate::data::File<D>,
161        cache: &mut C,
162        buf: &mut Vec<u8>,
163        inflate: &mut gix_zlib::Inflate,
164        progress: &mut dyn Progress,
165        index_entry: &index::Entry,
166        processor: &mut impl FnMut(gix_object::Kind, &[u8], &index::Entry, &dyn Progress) -> Result,
167    ) -> Result<Option<crate::data::decode::entry::Outcome>>
168    where
169        C: crate::cache::DecodeEntry,
170        D: crate::FileData + Send + Sync,
171    {
172        let pack_entry = pack.entry(index_entry.pack_offset)?;
173        let pack_entry_data_offset = pack_entry.data_offset;
174        let entry_stats = match pack.decode_entry(
175            pack_entry,
176            buf,
177            inflate,
178            &|id, _| {
179                self.lookup(id)
180                    .map(|index| {
181                        pack.entry(self.pack_offset_at_index(index))
182                            .map(crate::data::decode::entry::ResolvedBase::InPack)
183                    })
184                    .transpose()
185            },
186            cache,
187        ) {
188            Ok(stats) => stats,
189            Err(err) if !check.fatal_decode_error() => {
190                progress.info(format!(
191                    "Ignoring decode error for object {} at offset {}: {err}",
192                    index_entry.oid, index_entry.pack_offset
193                ));
194                return Ok(None);
195            }
196            Err(err) => {
197                return Err(err.and_raise(message!(
198                    "Object {} at offset {} could not be decoded",
199                    index_entry.oid,
200                    index_entry.pack_offset
201                )));
202            }
203        };
204        let object_kind = entry_stats.kind;
205        let header_size = (pack_entry_data_offset - index_entry.pack_offset) as usize;
206        let entry_len = header_size + entry_stats.compressed_size;
207
208        process_entry(
209            check,
210            object_kind,
211            buf,
212            index_entry,
213            || pack.entry_crc32(index_entry.pack_offset, entry_len),
214            progress,
215            processor,
216        )?;
217        Ok(Some(entry_stats))
218    }
219}
220
221fn process_entry(
222    check: SafetyCheck,
223    object_kind: gix_object::Kind,
224    decompressed: &[u8],
225    index_entry: &index::Entry,
226    pack_entry_crc32: impl FnOnce() -> u32,
227    progress: &dyn Progress,
228    processor: &mut impl FnMut(gix_object::Kind, &[u8], &index::Entry, &dyn Progress) -> Result,
229) -> Result {
230    if check.object_checksum() {
231        gix_object::Data::new(decompressed, object_kind, index_entry.oid.kind())
232            .verify_checksum(&index_entry.oid)
233            .or_raise(|| {
234                corruption(format!(
235                    "Error verifying object at offset {} against checksum in the index file",
236                    index_entry.pack_offset
237                ))
238            })?;
239        if let Some(desired_crc32) = index_entry.crc32 {
240            let actual_crc32 = pack_entry_crc32();
241            if actual_crc32 != desired_crc32 {
242                bail!(
243                    "The CRC32 of {object_kind} object at offset {} didn't match the checksum in the index file: expected {desired_crc32}, got {actual_crc32}".corrupted(),
244                    index_entry.pack_offset
245                );
246            }
247        }
248    }
249    processor(object_kind, decompressed, index_entry, progress)
250}