Skip to main content

vole_document/store/
mod.rs

1//! Content-addressed object store (Phase 9).
2//!
3//! A `.voldoc` descriptor's object table is a single ordered sequence. Each
4//! entry is either an inline byte object (`OBJECT`, tag `0x10`) or a reference
5//! to an object held by an [`ObjectStore`] (`EXTERNAL_REF`, tag `0x80`). Inline
6//! and external objects share one id space, so equal bytes are equal ids
7//! regardless of which document they came from.
8//!
9//! ## Two digests, two roles
10//!
11//! | digest | role | authority |
12//! |---|---|---|
13//! | SHA-256 | whole reconstructed source; archival identity | parse/materialize/verify |
14//! | BLAKE3-256 ([`Id`]) | one object's bytes; store namespace | relational/advisory |
15//!
16//! An [`Id`] is an *ephemeral, relational* name for a shareable object. It is
17//! never a substitute for the source digest and never appears in `INTEGRITY`.
18//!
19//! ## Verification rule
20//!
21//! [`ObjectStore::get`] **must** re-hash the returned bytes and reject with
22//! [`crate::ErrorClass::IntegrityMismatch`] unless `BLAKE3(bytes) == id`.
23//! [`ObjectStore::get_range`] cannot re-verify the whole object; exactness for a
24//! store-backed materialization therefore rests on the `EXTERNAL_REF` declared
25//! length and the descriptor's `INTEGRITY` SHA-256 checked by `materialize`.
26
27use core::fmt;
28use std::collections::BTreeSet;
29
30use crate::container::{Descriptor, ObjectSource};
31use crate::error::{Error, Result};
32
33mod io;
34pub use io::{IoCounters, IoSnapshot};
35
36#[cfg(feature = "store")]
37mod embedded;
38#[cfg(feature = "store")]
39pub use embedded::{EmbeddedStore, STORE_FORMAT_VERSION, STORE_MAGIC};
40
41#[cfg(feature = "store")]
42mod account;
43#[cfg(feature = "store")]
44pub use account::{AccountReport, RootAccount, account};
45
46#[cfg(feature = "entropyfs-store")]
47mod entropyfs;
48#[cfg(feature = "entropyfs-store")]
49pub use entropyfs::EntropyFsStore;
50// The engine-error mapper and the engine-backed seed methods are used only by the
51// field backend; gating the re-export on both features avoids an unused import in
52// an `entropyfs-store`-without-`field` build.
53#[cfg(all(feature = "entropyfs-store", feature = "field"))]
54pub(crate) use entropyfs::map_engine_error;
55
56#[cfg(feature = "field")]
57mod seed;
58#[cfg(feature = "field")]
59pub use seed::{
60    FsSeedStore, NodeId, SEED_FORMAT_VERSION, SEED_NODE_DOMAIN, SeedStore, SeedStoreStats,
61    closure as seed_closure,
62};
63
64/// Size accounting reported by a backend.
65///
66/// `total_bytes` is the sum of raw unique-object lengths (the backend-independent
67/// headline); `stored_bytes` is what the backend physically writes (equal to
68/// `total_bytes` for [`EmbeddedStore`], which stores raw; smaller for a
69/// compressing backend).
70#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
71pub struct StoreStats {
72    /// Unique ids present.
73    pub object_count: u64,
74    /// Sum of object file lengths (raw).
75    pub total_bytes: u64,
76    /// On-disk bytes (`== total_bytes` for a raw backend).
77    pub stored_bytes: u64,
78}
79
80/// Outcome of a mark-and-sweep GC pass.
81#[derive(Debug, Clone, Default, PartialEq, Eq)]
82pub struct GcReport {
83    /// Number of distinct external ids reachable from the roots.
84    pub reachable: u64,
85    /// Number of stored objects removed.
86    pub swept: u64,
87    /// Raw bytes reclaimed by the sweep.
88    pub bytes_reclaimed: u64,
89    /// Reachable ids the store does not contain (must be empty for a valid
90    /// closure; a non-empty list is a live `MissingExternalObject`).
91    pub dangling: Vec<Id>,
92}
93
94/// `Id` is a newtype over the 32 raw bytes of `BLAKE3-256(object_bytes)`, with no
95/// domain prefix. Hex is lower-case.
96#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
97pub struct Id([u8; 32]);
98
99impl Id {
100    /// Wrap 32 raw digest bytes.
101    pub const fn from_bytes(b: [u8; 32]) -> Self {
102        Id(b)
103    }
104
105    /// The raw digest bytes.
106    pub const fn as_bytes(&self) -> &[u8; 32] {
107        &self.0
108    }
109
110    /// Content id of `bytes`: `BLAKE3-256(bytes)`.
111    #[cfg(feature = "store")]
112    pub fn of(bytes: &[u8]) -> Self {
113        Id(*blake3::hash(bytes).as_bytes())
114    }
115
116    /// Lower-case hex rendering (64 characters).
117    pub fn to_hex(&self) -> String {
118        crate::integrity::to_hex(&self.0)
119    }
120
121    /// Parse exactly 64 lower- or upper-case hex characters.
122    pub fn from_hex(s: &str) -> Result<Self> {
123        let raw = s.as_bytes();
124        if raw.len() != 64 {
125            return Err(Error::usage(format!(
126                "object id must be 64 hex characters, got {}",
127                raw.len()
128            )));
129        }
130        let nib = |c: u8| -> Option<u8> {
131            match c {
132                b'0'..=b'9' => Some(c - b'0'),
133                b'a'..=b'f' => Some(c - b'a' + 10),
134                b'A'..=b'F' => Some(c - b'A' + 10),
135                _ => None,
136            }
137        };
138        let mut out = [0u8; 32];
139        for (i, byte) in out.iter_mut().enumerate() {
140            let hi =
141                nib(raw[2 * i]).ok_or_else(|| Error::usage("object id has a non-hex character"))?;
142            let lo = nib(raw[2 * i + 1])
143                .ok_or_else(|| Error::usage("object id has a non-hex character"))?;
144            *byte = (hi << 4) | lo;
145        }
146        Ok(Id(out))
147    }
148}
149
150impl fmt::Display for Id {
151    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152        f.write_str(&self.to_hex())
153    }
154}
155
156/// A content-addressed store keyed by `BLAKE3-256` of the object bytes.
157///
158/// The object namespace is the descriptor's object table: the raw, uncompressed
159/// bytes a DRA `EMIT_OBJECT`/`DEFLATE_REPLAY` op consumes. Inline and external
160/// objects share one id space, so equal bytes are equal ids regardless of which
161/// document they came from.
162///
163/// `put` takes `&mut self` (ids are content-derived, so retries are idempotent).
164/// `list`/`remove` support mark-and-sweep GC; both decline by default so a
165/// backend that exposes no enumeration or per-object delete (EntropyFS) fails
166/// closed rather than reporting a fake sweep.
167pub trait ObjectStore {
168    /// Store `bytes`, returning its content id.
169    ///
170    /// Idempotent and at-least-once: identical bytes always return the same id
171    /// and are stored once; a retry after a crash is a no-op. A returned id
172    /// guarantees the bytes are durable under [`ObjectStore::get`].
173    fn put(&mut self, bytes: &[u8]) -> Result<Id>;
174
175    /// Fetch the exact bytes for `id`.
176    ///
177    /// MUST verify `BLAKE3(bytes) == id` before returning.
178    /// - absent id        -> [`crate::ErrorClass::MissingExternalObject`]
179    /// - bytes hash != id -> [`crate::ErrorClass::IntegrityMismatch`]
180    fn get(&self, id: &Id) -> Result<Vec<u8>>;
181
182    /// Fetch `len` bytes of `id` starting at `offset`.
183    ///
184    /// STRICT: a request for `offset + len > stored_len(id)` is a typed error,
185    /// never a silent EOF clip. Range reads carry no whole-object hash gate.
186    fn get_range(&self, id: &Id, offset: u64, len: u64) -> Result<Vec<u8>>;
187
188    /// Whether `id` is present. `EmbeddedStore` overrides it with a stat.
189    fn contains(&self, id: &Id) -> Result<bool> {
190        let _ = id;
191        Err(Error::unsupported_feature(
192            "contains is not implemented by this backend",
193        ))
194    }
195
196    /// Every stored `(id, raw_len)`, for closure checking and GC.
197    ///
198    /// The default declines, so a backend without enumeration never reports a
199    /// fake closure.
200    fn list(&self) -> Result<Vec<(Id, u64)>> {
201        Err(Error::unsupported_feature(
202            "object enumeration is not implemented by this backend",
203        ))
204    }
205
206    /// Delete `id`, returning the raw bytes reclaimed (0 if absent).
207    ///
208    /// The default declines: a backend that exposes no per-object delete must
209    /// not appear to have swept anything.
210    fn remove(&self, id: &Id) -> Result<u64> {
211        let _ = id;
212        Err(Error::unsupported_feature(
213            "per-object delete is not implemented by this backend",
214        ))
215    }
216}
217
218/// The resolver consumed by store-backed materialization. A blanket impl makes
219/// every [`ObjectStore`] a resolver, so callers pass `&store`.
220pub trait ObjectResolver {
221    /// Fetch `id`, verifying that its length is exactly `len`.
222    fn get(&self, id: &Id, len: u64) -> Result<Vec<u8>>;
223}
224
225impl<T: ObjectStore> ObjectResolver for T {
226    fn get(&self, id: &Id, len: u64) -> Result<Vec<u8>> {
227        let bytes = ObjectStore::get(self, id)?;
228        if bytes.len() as u64 != len {
229            return Err(Error::integrity_mismatch(format!(
230                "external object {id} has {} bytes, EXTERNAL_REF declared {len}",
231                bytes.len()
232            )));
233        }
234        Ok(bytes)
235    }
236}
237
238/// A resolver that resolves nothing; used by the standalone `materialize`.
239pub struct NullResolver;
240
241impl ObjectResolver for NullResolver {
242    fn get(&self, id: &Id, _len: u64) -> Result<Vec<u8>> {
243        Err(Error::missing_external_object(format!(
244            "no store supplied to resolve object {id}"
245        )))
246    }
247}
248
249/// Inline → external: put every object's bytes into `store`, replacing it with
250/// an [`ObjectSource::External`] reference.
251///
252/// Objects already external are resolved through `resolver` (so a reference the
253/// resolver cannot satisfy fails closed) and re-put into `store`, so every
254/// object ends up in the destination store. Identical objects collapse to one
255/// store entry by content addressing (refcount > 1 is one stored object).
256pub fn externalize<R: ObjectResolver + ?Sized>(
257    d: &mut Descriptor,
258    resolver: &R,
259    store: &mut impl ObjectStore,
260) -> Result<()> {
261    let mut out: Vec<ObjectSource> = Vec::with_capacity(d.objects.len());
262    for src in &d.objects {
263        let bytes: Vec<u8> = match src {
264            ObjectSource::Inline(bytes) => bytes.clone(),
265            ObjectSource::External { id, len } => resolver.get(id, *len)?,
266        };
267        let len = bytes.len() as u64;
268        let id = store.put(&bytes)?;
269        out.push(ObjectSource::External { id, len });
270    }
271    d.objects = out;
272    Ok(())
273}
274
275/// External → inline: resolve every reference through `resolver` (verifying id
276/// and length) and replace it with [`ObjectSource::Inline`]. The external
277/// feature bit clears automatically because `required_features()` is derived.
278pub fn hydrate<R: ObjectResolver>(d: &mut Descriptor, resolver: &R) -> Result<()> {
279    let mut out: Vec<ObjectSource> = Vec::with_capacity(d.objects.len());
280    for src in &d.objects {
281        match src {
282            ObjectSource::Inline(bytes) => out.push(ObjectSource::Inline(bytes.clone())),
283            ObjectSource::External { id, len } => {
284                out.push(ObjectSource::Inline(resolver.get(id, *len)?));
285            }
286        }
287    }
288    d.objects = out;
289    Ok(())
290}
291
292/// Mark-and-sweep garbage collection over a set of root descriptors.
293///
294/// *Mark*: the union of every root's external ids. *Sweep*: `stored \ mark`.
295/// `dangling` is `mark \ stored` and must be empty for a valid closure.
296pub fn gc<R: ObjectResolver + ObjectStore>(roots: &[Descriptor], store: &R) -> Result<GcReport> {
297    let mut mark: BTreeSet<Id> = BTreeSet::new();
298    for root in roots {
299        for src in &root.objects {
300            if let ObjectSource::External { id, .. } = src {
301                mark.insert(*id);
302            }
303        }
304    }
305
306    let stored = store.list()?;
307    let stored_ids: BTreeSet<Id> = stored.iter().map(|(id, _)| *id).collect();
308
309    let mut dangling: Vec<Id> = mark
310        .iter()
311        .filter(|id| !stored_ids.contains(id))
312        .copied()
313        .collect();
314    dangling.sort_unstable();
315
316    let mut swept: u64 = 0;
317    let mut bytes_reclaimed: u64 = 0;
318    for (id, _len) in &stored {
319        if !mark.contains(id) {
320            bytes_reclaimed += store.remove(id)?;
321            swept += 1;
322        }
323    }
324
325    Ok(GcReport {
326        reachable: mark.len() as u64,
327        swept,
328        bytes_reclaimed,
329        dangling,
330    })
331}