Skip to main content

grit_lib/odb/store/
midx.rs

1//! Multi-pack-index object backend ([`MidxObjects`]).
2//!
3//! OID membership and prefix search use the prepared MIDX chain; object bytes are read at the
4//! layer-resolved pack offset via [`PreparedMidxChain::try_read_object`].
5
6use std::collections::HashSet;
7use std::io::Cursor;
8use std::ops::ControlFlow;
9use std::sync::{Arc, RwLock};
10
11use crate::diagnostics::NullDiagnostics;
12use crate::error::{Error, Result};
13use crate::midx::{prepared_midx_chain_strict, PreparedMidxChain};
14use crate::objects::{HashAlgo, Object, ObjectId, ObjectIdPrefix, ObjectInfo};
15use crate::pack_store::PackStore;
16
17use super::{ObjectStore, ObjectStream, PackedObjects};
18
19/// Whether [`MidxObjects`] can serve reads for this repository.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum MidxObjectsStatus {
22    /// `core.multiPackIndex` was off at construction; this backend is inert.
23    Disabled,
24    /// A usable MIDX chain is loaded.
25    Active,
26    /// MIDX was requested but no layer could be loaded (missing or corrupt); fall back to packs.
27    Unusable,
28}
29
30/// MIDX-backed read-only [`ObjectStore`] for one `objects/` directory.
31///
32/// Preparation and payload reads use the supplied [`PackStore`], including calls
33/// made outside an explicit pack-read context. Strict and permissive MIDX views
34/// in that store share validated layer mappings. Checksums are checked once per
35/// layer with bounded residency; lookup pages are faulted in as needed.
36/// Independently opened stores keep independent snapshots. Call
37/// [`ObjectStore::refresh`] after replacing MIDX or pack files externally.
38pub struct MidxObjects {
39    packs: PackedObjects,
40    multi_pack_index: bool,
41    status: RwLock<MidxObjectsStatus>,
42}
43
44impl std::fmt::Debug for MidxObjects {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        f.debug_struct("MidxObjects")
47            .field("objects_dir", &self.packs.pack_store().objects_dir())
48            .field("multi_pack_index", &self.multi_pack_index)
49            .field("status", &self.status())
50            .finish()
51    }
52}
53
54impl MidxObjects {
55    /// Open MIDX reads for `store`'s `objects/` directory.
56    ///
57    /// `multi_pack_index` mirrors `core.multiPackIndex` at construction time; the store does not
58    /// read config itself.
59    ///
60    /// # Errors
61    ///
62    /// Propagates MIDX chain preparation failures other than a missing or skipped index.
63    pub fn new(store: Arc<PackStore>, multi_pack_index: bool) -> Result<Self> {
64        let packs = PackedObjects::new(Arc::clone(&store));
65        let status = if multi_pack_index {
66            PackStore::with_context(Arc::clone(&store), || {
67                classify_midx_status(store.objects_dir())
68            })?
69        } else {
70            MidxObjectsStatus::Disabled
71        };
72        Ok(Self {
73            packs,
74            multi_pack_index,
75            status: RwLock::new(status),
76        })
77    }
78
79    /// Whether MIDX-backed reads are active for this store.
80    #[must_use]
81    pub fn status(&self) -> MidxObjectsStatus {
82        self.status
83            .read()
84            .map(|g| *g)
85            .unwrap_or(MidxObjectsStatus::Unusable)
86    }
87
88    /// Pack index basenames covered by the active MIDX chain (empty when inactive).
89    ///
90    /// Callers skip these indexes in [`PackedObjects`] so MIDX-covered OIDs are not scanned twice.
91    ///
92    /// # Errors
93    ///
94    /// Propagates MIDX chain load failures.
95    pub fn covered_pack_basenames(&self) -> Result<HashSet<String>> {
96        let Some(chain) = self.active_chain()? else {
97            return Ok(HashSet::new());
98        };
99        Ok(chain.covered_pack_basenames())
100    }
101
102    /// Underlying pack backend used for object payload reads.
103    #[must_use]
104    pub fn packed_objects(&self) -> &PackedObjects {
105        &self.packs
106    }
107
108    fn active_chain(&self) -> Result<Option<Arc<PreparedMidxChain>>> {
109        if self.status() != MidxObjectsStatus::Active {
110            return Ok(None);
111        }
112        let store = self.packs.pack_store();
113        match PackStore::with_context(Arc::clone(store), || {
114            prepared_midx_chain_strict(store.objects_dir())
115        }) {
116            Ok(chain) => Ok(chain),
117            Err(Error::Midx(_)) => Ok(None),
118            Err(err) => Err(err),
119        }
120    }
121
122    fn read_via_chain(&self, oid: &ObjectId) -> Result<Option<Object>> {
123        PackStore::with_context(Arc::clone(self.packs.pack_store()), || {
124            let Some(chain) = self.active_chain()? else {
125                return Ok(None);
126            };
127            chain.try_read_object(oid, &NullDiagnostics)
128        })
129    }
130
131    fn read_info_via_chain(&self, oid: &ObjectId) -> Result<Option<ObjectInfo>> {
132        PackStore::with_context(Arc::clone(self.packs.pack_store()), || {
133            let Some(chain) = self.active_chain()? else {
134                return Ok(None);
135            };
136            chain.try_read_info(oid, &NullDiagnostics)
137        })
138    }
139}
140
141impl ObjectStore for MidxObjects {
142    fn hash_algo(&self) -> HashAlgo {
143        self.packs.hash_algo()
144    }
145
146    fn read(&self, oid: &ObjectId) -> Result<Option<Object>> {
147        self.read_via_chain(oid)
148    }
149
150    fn read_info(&self, oid: &ObjectId) -> Result<Option<ObjectInfo>> {
151        self.read_info_via_chain(oid)
152    }
153
154    fn open_stream(&self, oid: &ObjectId) -> Result<Option<ObjectStream<'_>>> {
155        let Some(info) = self.read_info(oid)? else {
156            return Ok(None);
157        };
158        if let Some(stream) = self.packs.open_stream(oid)? {
159            return Ok(Some(stream));
160        }
161        let Some(obj) = self.read(oid)? else {
162            return Ok(None);
163        };
164        let size = u64::try_from(obj.data.len()).map_err(|_| {
165            Error::CorruptObject(format!("object size overflow for {}", oid.to_hex()))
166        })?;
167        Ok(Some(ObjectStream {
168            kind: info.kind,
169            size,
170            reader: Box::new(Cursor::new(obj.data)),
171        }))
172    }
173
174    fn for_each_object(&self, f: &mut dyn FnMut(&ObjectId) -> ControlFlow<()>) -> Result<()> {
175        let Some(chain) = self.active_chain()? else {
176            return Ok(());
177        };
178        chain.for_each_listed_object(f)
179    }
180
181    fn lookup_prefix(&self, prefix: &str, limit: usize, out: &mut Vec<ObjectId>) -> Result<()> {
182        if prefix.len() > self.hash_algo().hex_len() {
183            return Ok(());
184        }
185        let Some(chain) = self.active_chain()? else {
186            return Ok(());
187        };
188        let prefix = ObjectIdPrefix::from_hex(prefix, self.hash_algo())?;
189        chain.lookup_prefix(&prefix, limit, out)
190    }
191
192    fn refresh(&self) -> Result<bool> {
193        if !self.multi_pack_index {
194            return Ok(false);
195        }
196        let store = self.packs.pack_store();
197        store.invalidate_all();
198        let new_status = PackStore::with_context(Arc::clone(store), || {
199            classify_midx_status(store.objects_dir())
200        })?;
201        let mut guard = self
202            .status
203            .write()
204            .map_err(|e| Error::Io(std::io::Error::other(e.to_string())))?;
205        let changed = *guard != new_status;
206        *guard = new_status;
207        Ok(changed)
208    }
209}
210
211fn classify_midx_status(objects_dir: &std::path::Path) -> Result<MidxObjectsStatus> {
212    match prepared_midx_chain_strict(objects_dir) {
213        Ok(Some(_)) => Ok(MidxObjectsStatus::Active),
214        Ok(None) | Err(Error::Midx(_)) | Err(Error::CorruptObject(_)) => {
215            Ok(MidxObjectsStatus::Unusable)
216        }
217        Err(err) => Err(err),
218    }
219}