Skip to main content

gix_pack/index/traverse/
with_lookup.rs

1use gix_error::Result;
2use std::sync::atomic::{AtomicBool, Ordering};
3
4use gix_parallel::{self as parallel, in_parallel_if};
5use gix_parallel::{Mutable, OwnShared, lock};
6use gix_utils::progress::{self, Count, DynNestedProgress, Progress};
7
8use super::Reducer;
9use crate::{
10    data, exact_vec, index,
11    index::{traverse::Outcome, util},
12};
13
14/// Traversal options for [`index::File::traverse_with_lookup()`]
15pub struct Options<F> {
16    /// If `Some`, only use the given number of threads. Otherwise, the number of threads to use will be selected based on
17    /// the number of available logical cores.
18    pub thread_limit: Option<usize>,
19    /// The kinds of safety checks to perform.
20    pub check: index::traverse::SafetyCheck,
21    /// A function to create a pack cache
22    pub make_pack_lookup_cache: F,
23}
24
25impl Default for Options<fn() -> crate::cache::Never> {
26    fn default() -> Self {
27        Options {
28            check: Default::default(),
29            thread_limit: None,
30            make_pack_lookup_cache: || crate::cache::Never,
31        }
32    }
33}
34
35/// The progress ids used in [`index::File::traverse_with_lookup()`].
36///
37/// Use this information to selectively extract the progress of interest in case the parent application has custom visualization.
38#[derive(Debug, Copy, Clone)]
39pub enum ProgressId {
40    /// The amount of bytes currently processed to generate a checksum of the *pack data file*.
41    HashPackDataBytes,
42    /// The amount of bytes currently processed to generate a checksum of the *pack index file*.
43    HashPackIndexBytes,
44    /// Collect all object hashes into a vector and sort it by their pack offset.
45    CollectSortedIndexEntries,
46    /// The amount of objects which were decoded by brute-force.
47    DecodedObjects,
48}
49
50impl From<ProgressId> for gix_utils::progress::Id {
51    fn from(v: ProgressId) -> Self {
52        match v {
53            ProgressId::HashPackDataBytes => *b"PTHP",
54            ProgressId::HashPackIndexBytes => *b"PTHI",
55            ProgressId::CollectSortedIndexEntries => *b"PTCE",
56            ProgressId::DecodedObjects => *b"PTRO",
57        }
58    }
59}
60
61/// Verify and validate the content of the index file
62impl<T> index::File<T>
63where
64    T: crate::FileData + Sync,
65{
66    /// Iterate through all _decoded objects_ in the given `pack` and handle them with a `Processor` using a cache to reduce the amount of
67    /// waste while decoding objects.
68    ///
69    /// For more details, see the documentation on the [`traverse()`][index::File::traverse()] method.
70    pub fn traverse_with_lookup<C, Processor, F, D>(
71        &self,
72        mut processor: Processor,
73        pack: &data::File<D>,
74        progress: &mut dyn DynNestedProgress,
75        should_interrupt: &AtomicBool,
76        Options {
77            thread_limit,
78            check,
79            make_pack_lookup_cache,
80        }: Options<F>,
81    ) -> Result<Outcome>
82    where
83        C: crate::cache::DecodeEntry,
84        Processor: FnMut(gix_object::Kind, &[u8], &index::Entry, &dyn Progress) -> Result + Send + Clone,
85        F: Fn() -> C + Send + Clone,
86        D: crate::FileData + Send + Sync,
87    {
88        let (verify_result, traversal_result) = parallel::join(
89            {
90                let mut pack_progress = progress.add_child_with_id(
91                    format!("Hash of pack \"{}\"", crate::source_name(pack.path())),
92                    ProgressId::HashPackDataBytes.into(),
93                );
94                let mut index_progress = progress.add_child_with_id(
95                    format!("Hash of index \"{}\"", crate::source_name(&self.path)),
96                    ProgressId::HashPackIndexBytes.into(),
97                );
98                move || {
99                    let res =
100                        self.possibly_verify(pack, check, &mut pack_progress, &mut index_progress, should_interrupt);
101                    if res.is_err() {
102                        should_interrupt.store(true, Ordering::SeqCst);
103                    }
104                    res
105                }
106            },
107            || {
108                let index_entries = util::index_entries_sorted_by_offset_ascending(
109                    self,
110                    &mut progress.add_child_with_id(
111                        "collecting sorted index".into(),
112                        ProgressId::CollectSortedIndexEntries.into(),
113                    ),
114                );
115
116                let (chunk_size, thread_limit, available_cores) =
117                    parallel::optimize_chunk_size_and_thread_limit(1000, Some(index_entries.len()), thread_limit, None);
118                let there_are_enough_entries_to_process = || index_entries.len() > chunk_size * available_cores;
119                let input_chunks = index_entries.chunks(chunk_size);
120                let reduce_progress = OwnShared::new(Mutable::new({
121                    let mut p = progress.add_child_with_id("Traversing".into(), ProgressId::DecodedObjects.into());
122                    p.init(Some(self.num_objects() as usize), progress::count("objects"));
123                    p
124                }));
125                let state_per_thread = {
126                    let reduce_progress = reduce_progress.clone();
127                    move |index| {
128                        (
129                            make_pack_lookup_cache(),
130                            Vec::with_capacity(2048), // decode buffer
131                            gix_zlib::Inflate::default(),
132                            lock(&reduce_progress)
133                                .add_child_with_id(format!("thread {index}"), gix_utils::progress::UNKNOWN), // per thread progress
134                        )
135                    }
136                };
137
138                in_parallel_if(
139                    there_are_enough_entries_to_process,
140                    input_chunks,
141                    thread_limit,
142                    state_per_thread,
143                    move |entries: &[index::Entry],
144                          (cache, buf, inflate, progress)|
145                          -> Result<Vec<data::decode::entry::Outcome>> {
146                        progress.init(
147                            Some(entries.len()),
148                            gix_utils::progress::count_with_decimals("objects", 2),
149                        );
150                        let mut stats = exact_vec(entries.len());
151                        progress.set(0);
152                        for index_entry in entries.iter() {
153                            let result = self.decode_and_process_entry(
154                                check,
155                                pack,
156                                cache,
157                                buf,
158                                inflate,
159                                progress,
160                                index_entry,
161                                &mut processor,
162                            );
163                            progress.inc();
164                            let Some(stat) = result? else { continue };
165                            stats.push(stat);
166                            if should_interrupt.load(Ordering::Relaxed) {
167                                break;
168                            }
169                        }
170                        Ok(stats)
171                    },
172                    Reducer::from_progress(reduce_progress, pack.data_len(), should_interrupt),
173                )
174            },
175        );
176        Ok(Outcome {
177            actual_index_checksum: verify_result?,
178            statistics: traversal_result?,
179        })
180    }
181}