Skip to main content

gix_pack/index/traverse/
with_index.rs

1use gix_error::Result;
2use std::sync::atomic::{AtomicBool, Ordering};
3
4use gix_parallel as parallel;
5use gix_utils::progress::DynNestedProgress;
6
7use crate::{
8    cache::delta::traverse,
9    index::{self, traverse::Outcome, util::index_entries_sorted_by_offset_ascending},
10};
11
12/// Traversal options for [`traverse_with_index()`][index::File::traverse_with_index()]
13#[derive(Default)]
14pub struct Options {
15    /// If `Some`, only use the given number of threads. Otherwise, the number of threads to use will be selected based on
16    /// the number of available logical cores.
17    pub thread_limit: Option<usize>,
18    /// The kinds of safety checks to perform.
19    pub check: crate::index::traverse::SafetyCheck,
20    /// If `Some`, rejects individual allocations above the given number of bytes while resolving decoded object and
21    /// delta result buffers. `Some(0)` rejects all non-empty allocations.
22    pub alloc_limit_bytes: Option<usize>,
23}
24
25/// The progress ids used in [`index::File::traverse_with_index()`].
26///
27/// Use this information to selectively extract the progress of interest in case the parent application has custom visualization.
28#[derive(Debug, Copy, Clone)]
29pub enum ProgressId {
30    /// The amount of bytes currently processed to generate a checksum of the *pack data file*.
31    HashPackDataBytes,
32    /// The amount of bytes currently processed to generate a checksum of the *pack index file*.
33    HashPackIndexBytes,
34    /// Collect all object hashes into a vector and sort it by their pack offset.
35    CollectSortedIndexEntries,
36    /// Count the objects processed when building a cache tree from all objects in a pack index.
37    TreeFromOffsetsObjects,
38    /// The amount of objects which were decoded.
39    DecodedObjects,
40    /// The amount of bytes that were decoded in total, as the sum of all bytes to represent all decoded objects.
41    DecodedBytes,
42}
43
44impl From<ProgressId> for gix_utils::progress::Id {
45    fn from(v: ProgressId) -> Self {
46        match v {
47            ProgressId::HashPackDataBytes => *b"PTHP",
48            ProgressId::HashPackIndexBytes => *b"PTHI",
49            ProgressId::CollectSortedIndexEntries => *b"PTCE",
50            ProgressId::TreeFromOffsetsObjects => *b"PTDI",
51            ProgressId::DecodedObjects => *b"PTRO",
52            ProgressId::DecodedBytes => *b"PTDB",
53        }
54    }
55}
56
57/// Traversal with index
58impl<T> index::File<T>
59where
60    T: crate::FileData + Sync,
61{
62    /// Iterate through all _decoded objects_ in the given `pack` and handle them with a `Processor`, using an index to reduce waste
63    /// at the cost of memory.
64    ///
65    /// For more details, see the documentation on the [`traverse()`][index::File::traverse()] method.
66    pub fn traverse_with_index<Processor, D>(
67        &self,
68        pack: &crate::data::File<D>,
69        mut processor: Processor,
70        progress: &mut dyn DynNestedProgress,
71        should_interrupt: &AtomicBool,
72        Options {
73            check,
74            thread_limit,
75            alloc_limit_bytes,
76        }: Options,
77    ) -> Result<Outcome>
78    where
79        Processor:
80            FnMut(gix_object::Kind, &[u8], &index::Entry, &dyn gix_utils::progress::Progress) -> Result + Send + Clone,
81        D: crate::FileData + Send + Sync,
82    {
83        let (verify_result, traversal_result) = parallel::join(
84            {
85                let mut pack_progress = progress.add_child_with_id(
86                    format!("Hash of pack \"{}\"", crate::source_name(pack.path())),
87                    ProgressId::HashPackDataBytes.into(),
88                );
89                let mut index_progress = progress.add_child_with_id(
90                    format!("Hash of index \"{}\"", crate::source_name(&self.path)),
91                    ProgressId::HashPackIndexBytes.into(),
92                );
93                move || {
94                    let res =
95                        self.possibly_verify(pack, check, &mut pack_progress, &mut index_progress, should_interrupt);
96                    if res.is_err() {
97                        should_interrupt.store(true, Ordering::SeqCst);
98                    }
99                    res
100                }
101            },
102            || -> Result<_> {
103                let sorted_entries = index_entries_sorted_by_offset_ascending(
104                    self,
105                    &mut progress.add_child_with_id(
106                        "collecting sorted index".into(),
107                        ProgressId::CollectSortedIndexEntries.into(),
108                    ),
109                ); /* Pack Traverse Collect sorted Entries */
110                let tree = crate::cache::delta::Tree::from_offsets_in_pack(
111                    pack.path(),
112                    sorted_entries.into_iter().map(Entry::from),
113                    &|e| e.index_entry.pack_offset,
114                    &|id| Ok(self.lookup(id).map(|idx| self.pack_offset_at_index(idx))),
115                    &mut progress.add_child_with_id("indexing".into(), ProgressId::TreeFromOffsetsObjects.into()),
116                    should_interrupt,
117                    self.object_hash,
118                )?;
119                let mut outcome = digest_statistics(tree.traverse(
120                    |slice, pack| pack.entry_slice(slice),
121                    pack,
122                    pack.pack_end() as u64,
123                    move |data,
124                          progress,
125                          traverse::Context {
126                              entry: pack_entry,
127                              entry_end,
128                              decompressed: bytes,
129                              level,
130                          }| {
131                        let object_kind = pack_entry.header.as_kind().expect("non-delta object");
132                        data.level = level;
133                        data.decompressed_size = pack_entry.decompressed_size;
134                        data.object_kind = object_kind;
135                        data.compressed_size = entry_end - pack_entry.data_offset;
136                        data.object_size = bytes.len() as u64;
137                        index::traverse::process_entry(
138                            check,
139                            object_kind,
140                            bytes,
141                            &data.index_entry,
142                            || {
143                                // TODO: Fix this - we overwrite the header of 'data' which also changes the computed entry size,
144                                // causing index and pack to seemingly mismatch. This is surprising, and should be done differently.
145                                // debug_assert_eq!(&data.index_entry.pack_offset, &pack_entry.pack_offset());
146                                crc32fast::hash(
147                                    pack.entry_slice(data.index_entry.pack_offset..entry_end)
148                                        .expect("slice pointing into the pack (by now data is verified)"),
149                                )
150                            },
151                            progress,
152                            &mut processor,
153                        )
154                    },
155                    traverse::Options {
156                        object_progress: Box::new(
157                            progress.add_child_with_id("Resolving".into(), ProgressId::DecodedObjects.into()),
158                        ),
159                        size_progress:
160                            &mut progress.add_child_with_id("Decoding".into(), ProgressId::DecodedBytes.into()),
161                        thread_limit,
162                        should_interrupt,
163                        object_hash: self.object_hash,
164                        alloc_limit_bytes,
165                    },
166                )?);
167                outcome.pack_size = pack.data_len() as u64;
168                Ok(outcome)
169            },
170        );
171        Ok(Outcome {
172            actual_index_checksum: verify_result?,
173            statistics: traversal_result?,
174        })
175    }
176}
177
178struct Entry {
179    index_entry: crate::index::Entry,
180    object_kind: gix_object::Kind,
181    object_size: u64,
182    decompressed_size: u64,
183    compressed_size: u64,
184    level: u16,
185}
186
187impl From<crate::index::Entry> for Entry {
188    fn from(index_entry: crate::index::Entry) -> Self {
189        Entry {
190            index_entry,
191            level: 0,
192            object_kind: gix_object::Kind::Tree,
193            object_size: 0,
194            decompressed_size: 0,
195            compressed_size: 0,
196        }
197    }
198}
199
200fn digest_statistics(traverse::Outcome { roots, children }: traverse::Outcome<Entry>) -> index::traverse::Statistics {
201    let mut res = index::traverse::Statistics::default();
202    let average = &mut res.average;
203    for item in roots.iter().chain(children.iter()) {
204        res.total_compressed_entries_size += item.data.compressed_size;
205        res.total_decompressed_entries_size += item.data.decompressed_size;
206        res.total_object_size += item.data.object_size;
207        *res.objects_per_chain_length
208            .entry(u32::from(item.data.level))
209            .or_insert(0) += 1;
210
211        average.decompressed_size += item.data.decompressed_size;
212        average.compressed_size += item.data.compressed_size as usize;
213        average.object_size += item.data.object_size;
214        average.num_deltas += u32::from(item.data.level);
215        use gix_object::Kind::*;
216        match item.data.object_kind {
217            Blob => res.num_blobs += 1,
218            Tree => res.num_trees += 1,
219            Tag => res.num_tags += 1,
220            Commit => res.num_commits += 1,
221        }
222    }
223
224    let num_nodes = roots.len() + children.len();
225    average.decompressed_size /= num_nodes as u64;
226    average.compressed_size /= num_nodes;
227    average.object_size /= num_nodes as u64;
228    average.num_deltas /= num_nodes as u32;
229
230    res
231}