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