Skip to main content

grit_lib/odb/store/
mod.rs

1//! Pluggable object storage backends and the [`ObjectStore`] trait surface.
2//!
3//! Backends implement read, metadata, streaming, iteration, and (optionally) write
4//! operations without allocating error strings on cache misses: a missing object
5//! is `Ok(None)`, not [`crate::error::ObjectError::NotFound`].
6//!
7//! Thread safety: [`ObjectStore`] requires `Send + Sync` so repositories can share
8//! a store across threads; individual methods may take internal locks.
9
10mod composite;
11mod files;
12#[cfg(test)]
13pub(crate) mod flaky;
14pub(crate) mod loose;
15mod midx;
16mod packs;
17
18pub use composite::CompositeStore;
19pub use files::{FilesSource, FilesSourceOpenOptions};
20pub use loose::{enumerate_loose_objects, read_loose_object_info, LooseStore};
21pub(crate) use loose::{LooseNegativeCache, SharedLooseNegativeCache};
22pub use midx::{MidxObjects, MidxObjectsStatus};
23pub(crate) use packs::touch_pack_mtime;
24pub use packs::{PackFilter, PackedObjects};
25
26use crate::error::ObjectError;
27use std::io::{self, Cursor, Read};
28use std::ops::ControlFlow;
29use std::sync::{Arc, RwLock};
30use std::time::SystemTime;
31
32use std::path::Path;
33
34use crate::error::{Error, Result};
35use crate::hash;
36use crate::objects::{
37    oid_hash_map, HashAlgo, Object, ObjectId, ObjectIdPrefix, ObjectInfo, ObjectKind, OidHashMap,
38};
39use crate::odb::WriteOptions;
40use crate::pack;
41
42type MemoryObjectEntry = (ObjectKind, Arc<[u8]>);
43
44/// An object read only when its payload is no larger than a caller's limit.
45#[derive(Debug)]
46pub(crate) enum BoundedRead {
47    /// The whole object; its payload is within the limit.
48    Object(Object),
49    /// The payload exceeds the limit and was not read.
50    Larger,
51}
52
53/// Where [`FilesSource::read_unless_larger`] found an object.
54#[derive(Debug)]
55pub(crate) enum LocalSizedRead {
56    /// In a local pack but not read: the payload size when the pack stores it whole, `None`
57    /// when it is stored as a delta (sizing it would mean inflating the delta).
58    Packed(Option<u64>),
59    /// A loose object, read or sized against the limit.
60    Loose(BoundedRead),
61    /// In neither a local pack nor the loose store.
62    Missing,
63}
64
65/// Streaming handle for a single object's uncompressed payload.
66///
67/// The reader yields bytes after the Git object header (`"<kind> <size>\\0"`).
68pub struct ObjectStream<'a> {
69    /// Resolved object type.
70    pub kind: ObjectKind,
71    /// Uncompressed payload length in bytes.
72    pub size: u64,
73    /// Payload bytes; must not include the object header.
74    pub reader: Box<dyn Read + Send + 'a>,
75}
76
77/// Read-only object storage: lookup, metadata, streaming, and enumeration.
78///
79/// Implementations must be safe to share across threads (`Send + Sync`). Missing
80/// objects are reported as `Ok(None)`, not as errors.
81///
82/// A store used as a repository's primary can give history walks a commit-graph so they
83/// skip commit reads altogether: build one with [`Maintenance::build_commit_graph`](crate::maintenance::Maintenance::build_commit_graph),
84/// persist its bytes, and attach it with
85/// [`OdbBuilder::commit_graph`](crate::odb::OdbBuilder::commit_graph). Graph files under
86/// `objects/info/` are never read for a custom primary.
87pub trait ObjectStore: Send + Sync + std::fmt::Debug {
88    /// Hash algorithm for objects written through this store.
89    fn hash_algo(&self) -> HashAlgo;
90
91    /// Load the full object, if present.
92    ///
93    /// # Errors
94    ///
95    /// Returns I/O or corruption errors from the backend; never [`crate::error::ObjectError::NotFound`].
96    fn read(&self, oid: &ObjectId) -> Result<Option<Object>>;
97
98    /// Load object payload into `buf`, reusing its capacity when possible.
99    ///
100    /// History walks (rev-list, merge-base, path-limited log) read commits through this
101    /// method into one reused buffer, so it is the hot path for a custom backend. The
102    /// default implementation delegates to [`Self::read`], which allocates an owned
103    /// [`Object`] per call, and copies into `buf`. Backends should override it to decode
104    /// or copy their stored bytes straight into `buf`.
105    ///
106    /// # Errors
107    ///
108    /// Same as [`Self::read`].
109    fn read_into(&self, oid: &ObjectId, buf: &mut Vec<u8>) -> Result<Option<ObjectKind>> {
110        let Some(obj) = self.read(oid)? else {
111            return Ok(None);
112        };
113        buf.clear();
114        buf.extend_from_slice(&obj.data);
115        Ok(Some(obj.kind))
116    }
117
118    /// Object kind and size without loading the full payload.
119    ///
120    /// # Errors
121    ///
122    /// Same as [`Self::read`].
123    fn read_info(&self, oid: &ObjectId) -> Result<Option<ObjectInfo>>;
124
125    /// Whether `oid` is stored in this backend (without reading the payload).
126    ///
127    /// # Errors
128    ///
129    /// Propagates backend failures other than "not found".
130    fn contains(&self, oid: &ObjectId) -> Result<bool> {
131        Ok(self.read_info(oid)?.is_some())
132    }
133
134    /// For each id in `oids`, whether it is stored in this backend; the result has
135    /// one entry per input id, in input order.
136    ///
137    /// Callers that need to check many objects at once (for example write-tree
138    /// confirming that every reusable cached subtree still exists) use this instead
139    /// of one [`Self::contains`] call per id. The default implementation calls
140    /// [`Self::contains`] for each id. A database- or network-backed store should
141    /// override it to answer the whole batch in a single round trip.
142    ///
143    /// # Errors
144    ///
145    /// Propagates the first backend failure, like [`Self::contains`].
146    fn contains_many(&self, oids: &[ObjectId]) -> Result<Vec<bool>> {
147        oids.iter().map(|oid| self.contains(oid)).collect()
148    }
149
150    /// Open a stream over the object's uncompressed payload.
151    ///
152    /// Default implementation buffers via [`Self::read`].
153    ///
154    /// # Errors
155    ///
156    /// Same as [`Self::read`].
157    fn open_stream(&self, oid: &ObjectId) -> Result<Option<ObjectStream<'_>>> {
158        let Some(obj) = self.read(oid)? else {
159            return Ok(None);
160        };
161        let size = u64::try_from(obj.data.len()).map_err(|_| {
162            Error::Object(ObjectError::Corrupt {
163                detail: format!("object size overflow for {}", oid.to_hex()),
164            })
165        })?;
166        Ok(Some(ObjectStream {
167            kind: obj.kind,
168            size,
169            reader: Box::new(Cursor::new(obj.data)),
170        }))
171    }
172
173    /// Invoke `f` for every object id in this store until `f` returns [`ControlFlow::Break`].
174    ///
175    /// # Errors
176    ///
177    /// Propagates backend enumeration failures.
178    fn for_each_object(&self, f: &mut dyn FnMut(&ObjectId) -> ControlFlow<()>) -> Result<()>;
179
180    /// Fill `out` with object ids whose hex form starts with `prefix` (case-insensitive).
181    ///
182    /// At most `limit` ids are appended (0 means no limit). When more than one object
183    /// matches and `limit` is 1, callers treat the result as ambiguous if `out` would
184    /// have held multiple matches.
185    ///
186    /// The default implementation parses `prefix` once into an [`ObjectIdPrefix`] and
187    /// compares it against the raw bytes of every id from [`Self::for_each_object`]: one
188    /// allocation-free pass over the whole store per call. Abbreviating ids and resolving
189    /// short ids call this once per id, so a store with many objects and a cheaper way to
190    /// find ids by leading bytes (a sorted index, an ordered key-value range from
191    /// [`ObjectIdPrefix::lowest`] to [`ObjectIdPrefix::highest`]) should override it.
192    ///
193    /// # Errors
194    ///
195    /// Returns [`crate::error::ObjectError::InvalidId`] when `prefix` is not valid hex or is longer
196    /// than a full object id for this store's hash algorithm.
197    fn lookup_prefix(&self, prefix: &str, limit: usize, out: &mut Vec<ObjectId>) -> Result<()> {
198        let prefix = ObjectIdPrefix::from_hex(prefix, self.hash_algo())?;
199        let mut count = 0usize;
200        self.for_each_object(&mut |oid| {
201            if prefix.matches(oid) {
202                out.push(*oid);
203                count += 1;
204                if limit != 0 && count >= limit {
205                    return ControlFlow::Break(());
206                }
207            }
208            ControlFlow::Continue(())
209        })
210    }
211
212    /// Reload indexes or caches after on-disk changes (packs, alternates, MIDX).
213    ///
214    /// Returns `true` when the store's view of objects changed. Default is no-op.
215    ///
216    /// # Errors
217    ///
218    /// Propagates backend refresh failures.
219    fn refresh(&self) -> Result<bool> {
220        Ok(false)
221    }
222}
223
224/// Object storage that supports inserting new objects.
225pub trait WritableObjectStore: ObjectStore {
226    /// Store canonical object bytes and return the object id.
227    ///
228    /// If the object already exists, returns the existing id without replacing
229    /// stored bytes (Git loose-store idempotence).
230    ///
231    /// # Errors
232    ///
233    /// Returns I/O, hashing, or validation errors from the backend.
234    fn write(&self, kind: ObjectKind, data: &[u8], options: WriteOptions) -> Result<ObjectId>;
235
236    /// Store an object from a byte stream of known uncompressed size.
237    ///
238    /// Default implementation reads the stream into memory and calls [`Self::write`].
239    ///
240    /// # Errors
241    ///
242    /// Same as [`Self::write`], plus stream read failures.
243    fn write_stream(
244        &self,
245        kind: ObjectKind,
246        size: u64,
247        reader: &mut dyn Read,
248        options: WriteOptions,
249    ) -> Result<ObjectId> {
250        let size_usize = usize::try_from(size).map_err(|_| {
251            Error::Object(ObjectError::Corrupt {
252                detail: format!("object size {size} exceeds address space"),
253            })
254        })?;
255        let mut buf = vec![0u8; size_usize];
256        reader.read_exact(&mut buf).map_err(Error::Io)?;
257        self.write(kind, &buf, options)
258    }
259
260    /// Mark `oid` as recently used so retention policies keep it (Git `freshen`).
261    ///
262    /// Returns `true` when the object was present and the backend recorded the touch.
263    ///
264    /// # Errors
265    ///
266    /// Propagates backend failures.
267    fn freshen(&self, oid: &ObjectId) -> Result<bool>;
268
269    /// Make prior successful [`Self::write`] calls durable (commit a transaction, fsync, …).
270    ///
271    /// Grit calls this after bulk ingest and before ref updates that publish new commits.
272    /// Reads on this store must observe every write that returned `Ok` even before
273    /// [`Self::flush`]; flush is the durability barrier for crash recovery.
274    ///
275    /// Default is a no-op. Do not flush automatically from [`Self::write`]; backends batch
276    /// many writes between flush calls.
277    ///
278    /// # Errors
279    ///
280    /// Propagates backend persistence failures.
281    fn flush(&self) -> Result<()> {
282        Ok(())
283    }
284
285    /// Like [`Self::flush`], but rolls back the current batch when flush fails.
286    ///
287    /// # Errors
288    ///
289    /// Propagates flush failures after attempting [`Self::rollback`].
290    fn flush_for_publish(&self) -> Result<()> {
291        if let Err(err) = self.flush() {
292            let _ = self.rollback();
293            return Err(err);
294        }
295        Ok(())
296    }
297
298    /// Discard unflushed writes from the current batch after a failed ingest or similar.
299    ///
300    /// Default is a no-op. After a successful [`Self::flush`], rollback is a no-op.
301    ///
302    /// # Errors
303    ///
304    /// Propagates backend failures while aborting the batch.
305    fn rollback(&self) -> Result<()> {
306        Ok(())
307    }
308
309    /// This store's [`PrunableObjectStore`] capability, when it can delete objects.
310    ///
311    /// Garbage collection and pruning on a repository whose primary is this store call it
312    /// to find out whether unreachable objects can be removed. The default is `None`: such
313    /// a store is never pruned, and those operations fail with
314    /// [`RepositoryError::UnsupportedObjectStore`](crate::repo::RepositoryError::UnsupportedObjectStore)
315    /// naming [`FilesOnlyOperation::Prune`](crate::repo::error::FilesOnlyOperation::Prune).
316    /// A store that implements [`PrunableObjectStore`] returns `Some(self)`.
317    fn as_prunable(&self) -> Option<&dyn PrunableObjectStore> {
318        None
319    }
320}
321
322/// Object storage that can delete objects, so garbage collection can reclaim them.
323///
324/// Implement it next to [`WritableObjectStore`] and return `Some(self)` from
325/// [`WritableObjectStore::as_prunable`]. Then
326/// [`maintenance::prune_loose_objects`](crate::maintenance::prune_loose_objects),
327/// [`maintenance::gc`](crate::maintenance::gc) and [`Odb::gc`](crate::odb::Odb::gc) work on
328/// a repository whose primary is this store: they walk everything reachable from the
329/// repository's refs, reflogs, indexes and worktrees, list the store's objects with
330/// [`ObjectStore::for_each_object`], and pass the unreachable ones to [`Self::remove`] in
331/// batches, then call [`WritableObjectStore::flush`].
332///
333/// # Examples
334///
335/// ```
336/// use grit_lib::objects::{HashAlgo, ObjectKind};
337/// use grit_lib::objects::odb::store::{
338///     MemoryStore, ObjectStore, PrunableObjectStore, WritableObjectStore,
339/// };
340/// use grit_lib::objects::odb::WriteOptions;
341///
342/// let store = MemoryStore::new(HashAlgo::Sha1);
343/// let oid = store.write(ObjectKind::Blob, b"scratch", WriteOptions::default())?;
344/// let prunable = store.as_prunable().expect("MemoryStore can delete objects");
345/// assert_eq!(prunable.remove(&[oid])?, 1);
346/// assert!(!store.contains(&oid)?);
347/// # Ok::<(), grit_lib::error::Error>(())
348/// ```
349pub trait PrunableObjectStore: WritableObjectStore {
350    /// Delete every object in `oids` that this store holds, and return how many it deleted.
351    ///
352    /// Ids the store does not hold are skipped, not errors: another process may have
353    /// pruned them already. Deletions may be batched like writes; garbage collection calls
354    /// [`WritableObjectStore::flush`] after its last batch.
355    ///
356    /// # Errors
357    ///
358    /// Propagates backend failures. Objects deleted before the failure stay deleted.
359    fn remove(&self, oids: &[ObjectId]) -> Result<usize>;
360
361    /// When `oid` was last written or [freshened](WritableObjectStore::freshen), if this
362    /// store records it.
363    ///
364    /// Pruning keeps unreachable objects newer than the grace period (`gc.pruneExpire`,
365    /// two weeks by default, or [`PruneOptions::older_than`](crate::maintenance::PruneOptions::older_than)),
366    /// because a concurrent operation may be about to reference them. An object without a
367    /// known time cannot be proven old, so it is kept whenever a grace period applies and
368    /// removed only when the period is `now` (or `all`). The default returns `None` for
369    /// every object.
370    ///
371    /// # Errors
372    ///
373    /// Propagates backend failures.
374    fn object_mtime(&self, oid: &ObjectId) -> Result<Option<SystemTime>> {
375        let _ = oid;
376        Ok(None)
377    }
378}
379
380/// Forward both traits through a pointer type so a store behind `Arc`, `Box` or `&` is
381/// itself a store: a decorator generic over `S: ObjectStore` can wrap a shared
382/// `Arc<dyn ObjectStore>` and still be passed on as one. Every method forwards, so the
383/// pointee's overrides (batched `contains_many`, native `read_into`, ...) are kept.
384macro_rules! forward_object_store {
385    ($pointer:ty) => {
386        impl<T: ObjectStore + ?Sized> ObjectStore for $pointer {
387            fn hash_algo(&self) -> HashAlgo {
388                (**self).hash_algo()
389            }
390
391            fn read(&self, oid: &ObjectId) -> Result<Option<Object>> {
392                (**self).read(oid)
393            }
394
395            fn read_into(&self, oid: &ObjectId, buf: &mut Vec<u8>) -> Result<Option<ObjectKind>> {
396                (**self).read_into(oid, buf)
397            }
398
399            fn read_info(&self, oid: &ObjectId) -> Result<Option<ObjectInfo>> {
400                (**self).read_info(oid)
401            }
402
403            fn contains(&self, oid: &ObjectId) -> Result<bool> {
404                (**self).contains(oid)
405            }
406
407            fn contains_many(&self, oids: &[ObjectId]) -> Result<Vec<bool>> {
408                (**self).contains_many(oids)
409            }
410
411            fn open_stream(&self, oid: &ObjectId) -> Result<Option<ObjectStream<'_>>> {
412                (**self).open_stream(oid)
413            }
414
415            fn for_each_object(
416                &self,
417                f: &mut dyn FnMut(&ObjectId) -> ControlFlow<()>,
418            ) -> Result<()> {
419                (**self).for_each_object(f)
420            }
421
422            fn lookup_prefix(
423                &self,
424                prefix: &str,
425                limit: usize,
426                out: &mut Vec<ObjectId>,
427            ) -> Result<()> {
428                (**self).lookup_prefix(prefix, limit, out)
429            }
430
431            fn refresh(&self) -> Result<bool> {
432                (**self).refresh()
433            }
434        }
435
436        impl<T: WritableObjectStore + ?Sized> WritableObjectStore for $pointer {
437            fn write(
438                &self,
439                kind: ObjectKind,
440                data: &[u8],
441                options: WriteOptions,
442            ) -> Result<ObjectId> {
443                (**self).write(kind, data, options)
444            }
445
446            fn write_stream(
447                &self,
448                kind: ObjectKind,
449                size: u64,
450                reader: &mut dyn Read,
451                options: WriteOptions,
452            ) -> Result<ObjectId> {
453                (**self).write_stream(kind, size, reader, options)
454            }
455
456            fn freshen(&self, oid: &ObjectId) -> Result<bool> {
457                (**self).freshen(oid)
458            }
459
460            fn flush(&self) -> Result<()> {
461                (**self).flush()
462            }
463
464            fn flush_for_publish(&self) -> Result<()> {
465                (**self).flush_for_publish()
466            }
467
468            fn rollback(&self) -> Result<()> {
469                (**self).rollback()
470            }
471
472            fn as_prunable(&self) -> Option<&dyn PrunableObjectStore> {
473                (**self).as_prunable()
474            }
475        }
476
477        impl<T: PrunableObjectStore + ?Sized> PrunableObjectStore for $pointer {
478            fn remove(&self, oids: &[ObjectId]) -> Result<usize> {
479                (**self).remove(oids)
480            }
481
482            fn object_mtime(&self, oid: &ObjectId) -> Result<Option<SystemTime>> {
483                (**self).object_mtime(oid)
484            }
485        }
486    };
487}
488
489forward_object_store!(Arc<T>);
490forward_object_store!(Box<T>);
491forward_object_store!(&T);
492
493/// True when `oid` is stored as loose or in a non-promisor pack under `objects_dir`.
494pub(crate) fn local_object_materialized(objects_dir: &Path, oid: &ObjectId) -> bool {
495    if local_object_materialized_without_rescan(objects_dir, oid) {
496        return true;
497    }
498    if pack::reprepare_pack_directory_on_miss(objects_dir).ok() == Some(true) {
499        return object_in_local_packs(objects_dir, oid);
500    }
501    false
502}
503
504/// Like [`local_object_materialized`], but trusts the cached pack listing instead of
505/// rescanning `pack/` when the object is not found.
506pub(crate) fn local_object_materialized_without_rescan(objects_dir: &Path, oid: &ObjectId) -> bool {
507    object_in_local_packs(objects_dir, oid) || oid.loose_path_in(objects_dir).is_file()
508}
509
510fn object_in_local_packs(objects_dir: &Path, oid: &ObjectId) -> bool {
511    object_in_non_promisor_pack(objects_dir, oid)
512}
513
514/// Whether `oid` is listed in a non-promisor pack index under `objects_dir` (not loose).
515pub(crate) fn object_in_non_promisor_pack(objects_dir: &Path, oid: &ObjectId) -> bool {
516    let Ok(indexes) = pack::read_local_pack_indexes_cached(objects_dir) else {
517        return false;
518    };
519    for idx in &indexes {
520        if idx.is_promisor {
521            continue;
522        }
523        if idx.contains(oid).unwrap_or(false) {
524            return true;
525        }
526    }
527    false
528}
529
530/// True when `oid` is present as loose or in any local pack index (including promisor).
531///
532/// Does not consult alternates, trigger lazy fetch, or rescan `pack/` on miss beyond the
533/// cached index listing (same as [`local_object_materialized_without_rescan`]).
534pub(crate) fn local_object_stored_without_rescan(objects_dir: &Path, oid: &ObjectId) -> bool {
535    let Ok(indexes) = pack::read_local_pack_indexes_cached(objects_dir) else {
536        return oid.loose_path_in(objects_dir).is_file();
537    };
538    for idx in &indexes {
539        if idx.contains(oid).unwrap_or(false) {
540            return true;
541        }
542    }
543    oid.loose_path_in(objects_dir).is_file()
544}
545
546/// Like [`local_object_stored_without_rescan`], but rescan `pack/` once on miss.
547pub(crate) fn local_object_stored(objects_dir: &Path, oid: &ObjectId) -> bool {
548    if local_object_stored_without_rescan(objects_dir, oid) {
549        return true;
550    }
551    if pack::reprepare_pack_directory_on_miss(objects_dir).ok() == Some(true) {
552        return local_object_stored_without_rescan(objects_dir, oid);
553    }
554    false
555}
556
557/// In-memory object map keyed by [`ObjectId`].
558///
559/// Intended to replace the legacy [`Odb`](super::Odb) overlay hash map in a later step.
560#[derive(Debug)]
561pub struct MemoryStore {
562    algo: HashAlgo,
563    objects: RwLock<OidHashMap<MemoryObjectEntry>>,
564}
565
566impl MemoryStore {
567    /// Create an empty store using `algo` for [`WritableObjectStore::write`].
568    #[must_use]
569    pub fn new(algo: HashAlgo) -> Self {
570        Self {
571            algo,
572            objects: RwLock::new(oid_hash_map()),
573        }
574    }
575
576    /// Insert `oid` without re-hashing (overlay and tests).
577    pub(crate) fn insert_object(&self, oid: ObjectId, kind: ObjectKind, data: Arc<[u8]>) {
578        if let Ok(mut guard) = self.objects.write() {
579            guard.entry(oid).or_insert((kind, data));
580        }
581    }
582}
583
584impl ObjectStore for MemoryStore {
585    fn hash_algo(&self) -> HashAlgo {
586        self.algo
587    }
588
589    fn read(&self, oid: &ObjectId) -> Result<Option<Object>> {
590        let guard = self
591            .objects
592            .read()
593            .map_err(|e| Error::Io(io::Error::other(e.to_string())))?;
594        Ok(guard.get(oid).map(|(kind, data)| Object {
595            kind: *kind,
596            data: data.to_vec(),
597        }))
598    }
599
600    fn read_into(&self, oid: &ObjectId, buf: &mut Vec<u8>) -> Result<Option<ObjectKind>> {
601        let guard = self
602            .objects
603            .read()
604            .map_err(|e| Error::Io(io::Error::other(e.to_string())))?;
605        Ok(guard.get(oid).map(|(kind, data)| {
606            buf.clear();
607            buf.extend_from_slice(data);
608            *kind
609        }))
610    }
611
612    fn read_info(&self, oid: &ObjectId) -> Result<Option<ObjectInfo>> {
613        let guard = self
614            .objects
615            .read()
616            .map_err(|e| Error::Io(io::Error::other(e.to_string())))?;
617        Ok(guard.get(oid).map(|(kind, data)| ObjectInfo {
618            kind: *kind,
619            size: u64::try_from(data.len()).unwrap_or(u64::MAX),
620        }))
621    }
622
623    fn contains(&self, oid: &ObjectId) -> Result<bool> {
624        let guard = self
625            .objects
626            .read()
627            .map_err(|e| Error::Io(io::Error::other(e.to_string())))?;
628        Ok(guard.contains_key(oid))
629    }
630
631    fn contains_many(&self, oids: &[ObjectId]) -> Result<Vec<bool>> {
632        let guard = self
633            .objects
634            .read()
635            .map_err(|e| Error::Io(io::Error::other(e.to_string())))?;
636        Ok(oids.iter().map(|oid| guard.contains_key(oid)).collect())
637    }
638
639    fn open_stream(&self, oid: &ObjectId) -> Result<Option<ObjectStream<'_>>> {
640        let guard = self
641            .objects
642            .read()
643            .map_err(|e| Error::Io(io::Error::other(e.to_string())))?;
644        let Some((kind, data)) = guard.get(oid) else {
645            return Ok(None);
646        };
647        let size = u64::try_from(data.len()).map_err(|_| {
648            Error::Object(ObjectError::Corrupt {
649                detail: format!("object size overflow for {}", oid.to_hex()),
650            })
651        })?;
652        Ok(Some(ObjectStream {
653            kind: *kind,
654            size,
655            reader: Box::new(Cursor::new(Arc::clone(data))),
656        }))
657    }
658
659    fn for_each_object(&self, f: &mut dyn FnMut(&ObjectId) -> ControlFlow<()>) -> Result<()> {
660        let guard = self
661            .objects
662            .read()
663            .map_err(|e| Error::Io(io::Error::other(e.to_string())))?;
664        for oid in guard.keys() {
665            if f(oid).is_break() {
666                break;
667            }
668        }
669        Ok(())
670    }
671
672    fn lookup_prefix(&self, prefix: &str, limit: usize, out: &mut Vec<ObjectId>) -> Result<()> {
673        let prefix = ObjectIdPrefix::from_hex(prefix, self.hash_algo())?;
674        let guard = self
675            .objects
676            .read()
677            .map_err(|e| Error::Io(io::Error::other(e.to_string())))?;
678        let matches = guard.keys().filter(|oid| prefix.matches(oid)).copied();
679        if limit == 0 {
680            out.extend(matches);
681        } else {
682            out.extend(matches.take(limit));
683        }
684        Ok(())
685    }
686}
687
688impl WritableObjectStore for MemoryStore {
689    fn write(&self, kind: ObjectKind, data: &[u8], _options: WriteOptions) -> Result<ObjectId> {
690        let oid = hash::hash_object(self.algo, kind, data)?;
691        let mut guard = self
692            .objects
693            .write()
694            .map_err(|e| Error::Io(io::Error::other(e.to_string())))?;
695        guard
696            .entry(oid)
697            .or_insert_with(|| (kind, Arc::from(data.to_owned())));
698        Ok(oid)
699    }
700
701    fn freshen(&self, oid: &ObjectId) -> Result<bool> {
702        let guard = self
703            .objects
704            .read()
705            .map_err(|e| Error::Io(io::Error::other(e.to_string())))?;
706        Ok(guard.contains_key(oid))
707    }
708
709    fn as_prunable(&self) -> Option<&dyn PrunableObjectStore> {
710        Some(self)
711    }
712}
713
714/// Records no write times, so a grace period keeps every unreachable object: only a
715/// `now` prune removes them.
716impl PrunableObjectStore for MemoryStore {
717    fn remove(&self, oids: &[ObjectId]) -> Result<usize> {
718        let mut guard = self
719            .objects
720            .write()
721            .map_err(|e| Error::Io(io::Error::other(e.to_string())))?;
722        Ok(oids
723            .iter()
724            .filter(|oid| guard.remove(*oid).is_some())
725            .count())
726    }
727}
728
729/// Ask `probe` about the ids of `oids` indexed by `pending`; mark each hit in `present` and
730/// drop it from `pending`, so the next source is only asked about what is still missing.
731///
732/// Does nothing when `pending` is empty. A short answer from `probe` counts as "absent".
733pub(crate) fn resolve_pending(
734    oids: &[ObjectId],
735    present: &mut [bool],
736    pending: &mut Vec<usize>,
737    probe: impl FnOnce(&[ObjectId]) -> Result<Vec<bool>>,
738) -> Result<()> {
739    if pending.is_empty() {
740        return Ok(());
741    }
742    let batch: Vec<ObjectId> = pending.iter().map(|&i| oids[i]).collect();
743    let mut found = probe(&batch)?.into_iter();
744    pending.retain(|&i| {
745        let hit = found.next().unwrap_or(false);
746        present[i] |= hit;
747        !hit
748    });
749    Ok(())
750}
751
752/// Run `store.for_each_object` and stop visiting further stores when `f` returns [`ControlFlow::Break`].
753pub(crate) fn for_each_propagate_break(
754    store: &dyn ObjectStore,
755    f: &mut dyn FnMut(&ObjectId) -> ControlFlow<()>,
756) -> Result<bool> {
757    let mut stop = false;
758    store.for_each_object(&mut |oid| {
759        if stop {
760            return ControlFlow::Break(());
761        }
762        match f(oid) {
763            ControlFlow::Break(()) => {
764                stop = true;
765                ControlFlow::Break(())
766            }
767            ControlFlow::Continue(()) => ControlFlow::Continue(()),
768        }
769    })?;
770    Ok(stop)
771}
772
773#[cfg(test)]
774mod tests {
775    use super::*;
776    use std::io::Read;
777
778    #[test]
779    fn read_hit_and_miss() {
780        let store = MemoryStore::new(HashAlgo::Sha1);
781        let data = b"hello";
782        let oid = store
783            .write(ObjectKind::Blob, data, WriteOptions::default())
784            .unwrap();
785        let obj = store.read(&oid).unwrap().expect("hit");
786        assert_eq!(obj.kind, ObjectKind::Blob);
787        assert_eq!(obj.data, data);
788        assert!(store.read(&ObjectId::zero()).unwrap().is_none());
789        let mut buf = b"stale bytes".to_vec();
790        assert_eq!(
791            store.read_into(&oid, &mut buf).unwrap(),
792            Some(ObjectKind::Blob)
793        );
794        assert_eq!(buf, data);
795        assert_eq!(store.read_into(&ObjectId::zero(), &mut buf).unwrap(), None);
796        assert_eq!(buf, data, "a miss leaves the buffer alone");
797        assert!(store.read_info(&ObjectId::zero()).unwrap().is_none());
798        assert!(!store.contains(&ObjectId::zero()).unwrap());
799        assert!(store.contains(&oid).unwrap());
800        assert_eq!(
801            store.contains_many(&[oid, ObjectId::zero(), oid]).unwrap(),
802            vec![true, false, true]
803        );
804        assert!(store.contains_many(&[]).unwrap().is_empty());
805    }
806
807    #[test]
808    fn resolve_pending_marks_hits_and_keeps_misses() {
809        let ids: Vec<ObjectId> = (1u8..=3)
810            .map(|b| ObjectId::from_bytes(&[b; 20]).unwrap())
811            .collect();
812        let mut present = vec![false; 3];
813        let mut pending = vec![0, 2];
814        resolve_pending(&ids, &mut present, &mut pending, |batch| {
815            assert_eq!(batch, [ids[0], ids[2]]);
816            Ok(vec![false, true])
817        })
818        .unwrap();
819        assert_eq!(present, [false, false, true]);
820        assert_eq!(pending, [0]);
821
822        resolve_pending(&ids, &mut present, &mut pending, |_| Ok(Vec::new())).unwrap();
823        assert_eq!(pending, [0], "a short answer counts as absent");
824
825        pending.clear();
826        resolve_pending(&ids, &mut present, &mut pending, |_| {
827            panic!("no probe when nothing is pending")
828        })
829        .unwrap();
830    }
831
832    #[test]
833    fn stream_four_mib_blob_in_sixty_four_kib_chunks() {
834        let store = MemoryStore::new(HashAlgo::Sha1);
835        let payload = vec![0xABu8; 4 * 1024 * 1024];
836        let oid = store
837            .write(ObjectKind::Blob, &payload, WriteOptions::default())
838            .unwrap();
839        let mut stream = store.open_stream(&oid).unwrap().expect("stream");
840        assert_eq!(stream.kind, ObjectKind::Blob);
841        assert_eq!(stream.size, payload.len() as u64);
842        let mut out = Vec::with_capacity(payload.len());
843        let mut chunk = [0u8; 64 * 1024];
844        loop {
845            let n = stream.reader.read(&mut chunk).unwrap();
846            if n == 0 {
847                break;
848            }
849            out.extend_from_slice(&chunk[..n]);
850        }
851        assert_eq!(out, payload);
852    }
853
854    #[test]
855    fn for_each_object_stops_on_break() {
856        let store = MemoryStore::new(HashAlgo::Sha1);
857        for i in 0u8..5 {
858            store
859                .write(ObjectKind::Blob, &[i], WriteOptions::default())
860                .unwrap();
861        }
862        let mut seen = 0usize;
863        store
864            .for_each_object(&mut |_| {
865                seen += 1;
866                ControlFlow::Break(())
867            })
868            .unwrap();
869        assert_eq!(seen, 1);
870    }
871
872    #[test]
873    fn lookup_prefix_unique_ambiguous_and_none() {
874        let store = MemoryStore::new(HashAlgo::Sha1);
875        let a = store
876            .write(ObjectKind::Blob, b"a", WriteOptions::default())
877            .unwrap();
878        let b = store
879            .write(ObjectKind::Blob, b"b", WriteOptions::default())
880            .unwrap();
881        let hex_a = a.to_hex();
882        let unique_prefix = &hex_a[..12];
883        let mut out = Vec::new();
884        store.lookup_prefix(unique_prefix, 0, &mut out).unwrap();
885        assert_eq!(out, vec![a]);
886
887        let mut ambiguous = Vec::new();
888        store.lookup_prefix("", 2, &mut ambiguous).unwrap();
889        assert_eq!(ambiguous.len(), 2);
890        assert!(ambiguous.contains(&a));
891        assert!(ambiguous.contains(&b));
892
893        let mut none = Vec::new();
894        store
895            .lookup_prefix("ffffffffffffffffffffffffffffffffffffffff", 0, &mut none)
896            .unwrap();
897        assert!(none.is_empty());
898    }
899
900    #[test]
901    fn lookup_prefix_odd_even_empty_and_full_length() {
902        let store = MemoryStore::new(HashAlgo::Sha1);
903        let ids: Vec<ObjectId> = [
904            "abcdef0123000000000000000000000000000000",
905            "abcdef0124000000000000000000000000000000",
906            "abd0000000000000000000000000000000000000",
907        ]
908        .iter()
909        .map(|hex| ObjectId::from_hex(hex).unwrap())
910        .collect();
911        for id in &ids {
912            store.insert_object(*id, ObjectKind::Blob, Arc::from(Vec::new()));
913        }
914        let lookup = |prefix: &str, limit: usize| {
915            let mut out = Vec::new();
916            store.lookup_prefix(prefix, limit, &mut out).unwrap();
917            out.sort();
918            out
919        };
920        assert_eq!(lookup("", 0), ids);
921        assert_eq!(lookup("ab", 1).len(), 1);
922        assert_eq!(lookup("abc", 0), ids[..2]);
923        assert_eq!(lookup("abcdef012", 0), ids[..2]);
924        assert_eq!(lookup("ABCDEF0124", 0), ids[1..2]);
925        assert_eq!(lookup(&ids[2].to_hex(), 0), ids[2..]);
926        assert!(lookup("abe", 0).is_empty());
927        let mut out = Vec::new();
928        assert!(matches!(
929            store.lookup_prefix("xyz", 0, &mut out),
930            Err(Error::Object(ObjectError::InvalidId { .. }))
931        ));
932    }
933
934    #[test]
935    fn write_idempotent() {
936        let store = MemoryStore::new(HashAlgo::Sha1);
937        let data = b"same";
938        let oid1 = store
939            .write(ObjectKind::Blob, data, WriteOptions::default())
940            .unwrap();
941        let oid2 = store
942            .write(ObjectKind::Blob, data, WriteOptions::default())
943            .unwrap();
944        assert_eq!(oid1, oid2);
945        let guard = store.objects.read().unwrap();
946        assert_eq!(guard.len(), 1);
947    }
948
949    #[test]
950    fn write_stream_default_and_freshen() {
951        let store = MemoryStore::new(HashAlgo::Sha1);
952        let payload = b"streamed";
953        let mut cursor = Cursor::new(*payload);
954        let oid = store
955            .write_stream(
956                ObjectKind::Blob,
957                payload.len() as u64,
958                &mut cursor,
959                WriteOptions::default(),
960            )
961            .unwrap();
962        assert_eq!(
963            store.read(&oid).unwrap().expect("written").data,
964            payload.as_slice()
965        );
966        assert!(store.freshen(&oid).unwrap());
967        assert!(!store.freshen(&ObjectId::zero()).unwrap());
968    }
969
970    #[test]
971    fn memory_store_removes_held_objects_and_skips_the_rest() {
972        let store = MemoryStore::new(HashAlgo::Sha1);
973        let a = store
974            .write(ObjectKind::Blob, b"a", WriteOptions::default())
975            .unwrap();
976        let b = store
977            .write(ObjectKind::Blob, b"b", WriteOptions::default())
978            .unwrap();
979        let prunable = store.as_prunable().expect("MemoryStore is prunable");
980        assert_eq!(prunable.remove(&[a, ObjectId::zero(), a]).unwrap(), 1);
981        assert!(!store.contains(&a).unwrap());
982        assert!(store.contains(&b).unwrap());
983        assert_eq!(prunable.remove(&[]).unwrap(), 0);
984        assert_eq!(prunable.object_mtime(&b).unwrap(), None);
985    }
986
987    #[test]
988    fn pointers_forward_the_prune_capability() {
989        let shared = Arc::new(MemoryStore::new(HashAlgo::Sha1));
990        let oid = shared
991            .write(ObjectKind::Blob, b"x", WriteOptions::default())
992            .unwrap();
993        let as_dyn: Arc<dyn WritableObjectStore> = shared.clone();
994        let boxed: Box<dyn WritableObjectStore> = Box::new(Arc::clone(&shared));
995        let borrowed: &dyn WritableObjectStore = &as_dyn;
996        assert!(as_dyn.as_prunable().is_some());
997        assert!(boxed.as_prunable().is_some());
998        assert!(borrowed.as_prunable().is_some());
999        assert_eq!(PrunableObjectStore::remove(&shared, &[oid]).unwrap(), 1);
1000        assert!(!as_dyn.contains(&oid).unwrap());
1001    }
1002
1003    #[test]
1004    fn writable_store_is_not_prunable_by_default() {
1005        #[derive(Debug)]
1006        struct WriteOnly(MemoryStore);
1007
1008        impl ObjectStore for WriteOnly {
1009            fn hash_algo(&self) -> HashAlgo {
1010                self.0.hash_algo()
1011            }
1012
1013            fn read(&self, oid: &ObjectId) -> Result<Option<Object>> {
1014                self.0.read(oid)
1015            }
1016
1017            fn read_info(&self, oid: &ObjectId) -> Result<Option<ObjectInfo>> {
1018                self.0.read_info(oid)
1019            }
1020
1021            fn for_each_object(
1022                &self,
1023                f: &mut dyn FnMut(&ObjectId) -> ControlFlow<()>,
1024            ) -> Result<()> {
1025                self.0.for_each_object(f)
1026            }
1027        }
1028
1029        impl WritableObjectStore for WriteOnly {
1030            fn write(
1031                &self,
1032                kind: ObjectKind,
1033                data: &[u8],
1034                options: WriteOptions,
1035            ) -> Result<ObjectId> {
1036                self.0.write(kind, data, options)
1037            }
1038
1039            fn freshen(&self, oid: &ObjectId) -> Result<bool> {
1040                self.0.freshen(oid)
1041            }
1042        }
1043
1044        let store: Arc<dyn WritableObjectStore> =
1045            Arc::new(WriteOnly(MemoryStore::new(HashAlgo::Sha1)));
1046        assert!(store.as_prunable().is_none());
1047    }
1048
1049    #[test]
1050    fn refresh_default_false() {
1051        let store = MemoryStore::new(HashAlgo::Sha1);
1052        assert!(!store.refresh().unwrap());
1053    }
1054
1055    #[test]
1056    fn trait_defaults_via_blanket_test_store() {
1057        struct DefaultsOnly {
1058            inner: MemoryStore,
1059        }
1060
1061        impl std::fmt::Debug for DefaultsOnly {
1062            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1063                self.inner.fmt(f)
1064            }
1065        }
1066
1067        impl ObjectStore for DefaultsOnly {
1068            fn hash_algo(&self) -> HashAlgo {
1069                self.inner.hash_algo()
1070            }
1071
1072            fn read(&self, oid: &ObjectId) -> Result<Option<Object>> {
1073                self.inner.read(oid)
1074            }
1075
1076            fn read_info(&self, oid: &ObjectId) -> Result<Option<ObjectInfo>> {
1077                self.inner.read_info(oid)
1078            }
1079
1080            fn for_each_object(
1081                &self,
1082                f: &mut dyn FnMut(&ObjectId) -> ControlFlow<()>,
1083            ) -> Result<()> {
1084                self.inner.for_each_object(f)
1085            }
1086        }
1087
1088        let store = DefaultsOnly {
1089            inner: MemoryStore::new(HashAlgo::Sha1),
1090        };
1091        let oid = WritableObjectStore::write(
1092            &store.inner,
1093            ObjectKind::Blob,
1094            b"x",
1095            WriteOptions::default(),
1096        )
1097        .unwrap();
1098        assert!(ObjectStore::contains(&store, &oid).unwrap());
1099        assert_eq!(
1100            ObjectStore::contains_many(&store, &[ObjectId::zero(), oid]).unwrap(),
1101            vec![false, true]
1102        );
1103        assert!(ObjectStore::open_stream(&store, &oid).unwrap().is_some());
1104        let mut prefixed = Vec::new();
1105        ObjectStore::lookup_prefix(&store, &oid.to_hex()[..6], 0, &mut prefixed).unwrap();
1106        assert_eq!(prefixed, vec![oid]);
1107    }
1108}