OXYGENHUB

Coverage / crates/oxy-core/src/store.rs 94.5%

1905 of 2015 lines run, 294 of 423 functions · run #285 on main · run missed

1
//! Object store (spec §13.1, §13.3, §13.4): loose objects, one per key
2
//! under `loose/<hh>/<rest>`, and packs, `pack-<id>.pack` with a sorted
3
//! `pack-<id>.idx`, holding zstd-compressed objects. Reads check loose
4
//! objects first, then every pack; every read re-hashes.
5
//!
6
//! Everything is kept on a [`crate::strata::Store`] (docs/stores.md): a
7
//! directory, which is what `.oxy/objects` is, or a bucket, which is how a
8
//! repository lives in its owner's region with the hub as one client of
9
//! it. The keys are the same wherever the store is, so a bucket holds
10
//! exactly what a directory would, and a directory store is as fast as
11
//! the files were before there was a trait: a loose object is one file, a
12
//! packed one is one ranged read of the pack. What must be local, the
13
//! pack being streamed out and the derived `metas` cache, lives in a
14
//! scratch directory.
15
//!
16
//! Pack file: `OXYPACK1` then entries of
17
//! `type u8 | flags u8 (bit 0: zstd) | stored_len u32 | raw_len u32 | ref 32 | body`.
18
//! Index file: `OXYIDX01` then `count u32` then sorted entries of
19
//! `ref 32 | offset u64 | stored_len u32 | raw_len u32 | type u8 | flags u8`.
20
//!
21
//! Beside the objects: `nocompress/<hex>` marks a chunk packs keep raw;
22
//! `sig/<hh>/<rest>/<key>` holds one signature over an object, written
23
//! once per signer; `seal/<hh>/<rest>/<attest>` and
24
//! `receipt/<hh>/<rest>/<attest>` index the seals covering a change and
25
//! the receipts on a state. Older stores hold these as one list per
26
//! object (`sigs/`, `seals/`, `receipts/`), which are still read.
27
28
use crate::attest::Attest;
29
use crate::hash::{hash_object, header, ObjectRef, ObjectType};
30
use crate::identity::{Identity, Signature};
31
use crate::objects::{Blob, Change, ObjectError, StateObject};
32
use crate::receipt::Receipt;
33
use crate::strata::{self, Error as BackendError, LocalStore, MemoryStore};
34
use rand::RngCore;
35
use std::cell::RefCell;
36
use std::fs;
37
use std::io::{self, Write};
38
use std::path::{Path, PathBuf};
39
use std::sync::Arc;
40
41
const PACK_MAGIC: &[u8; 8] = b"OXYPACK1";
42
const IDX_MAGIC: &[u8; 8] = b"OXYIDX01";
43
const IDX_ENTRY: usize = 32 + 8 + 4 + 4 + 1 + 1;
44
const FLAG_ZSTD: u8 = 1;
45
/// Compressed with the pack's trained dictionary (`pack-ID.dict`), which a
46
/// full repack makes from a sample of the objects it packs: small files
47
/// share most of their vocabulary, which each one alone cannot use.
48
const FLAG_DICT: u8 = 2;
49
/// The size of a pack's dictionary, and the least a repack must pack for
50
/// one to pay.
51
const DICT_BYTES: usize = 110 << 10;
52
const DICT_MIN_OBJECTS: usize = 1000;
53
/// Objects up to this size are compressed with the dictionary.
54
const DICT_OBJECT_MAX: usize = 64 << 10;
55
const ZSTD_LEVEL: i32 = 3;
56
/// The level of a full repack (`oxy gc`): slower, once, for a smaller store.
57
pub const REPACK_ZSTD_LEVEL: i32 = 9;
58
/// Largest object a pack entry may claim; anything bigger is corruption,
59
/// and refusing it keeps a bad index from driving huge allocations.
60
const MAX_OBJECT_LEN: u32 = 1 << 30;
61
62
/// An object read from the store: its type and body.
63
pub type Object = (ObjectType, Vec<u8>);
64
65
/// Where a long operation reports what it is doing (oxygen#66): a phase,
66
/// or a count within one, as a line for a spinner or a log.
67
pub type Progress<'a> = &'a mut dyn FnMut(&str);
68
69
/// The storage under a store: objects by key, see [`crate::strata`].
70
pub type Backend = dyn strata::Store;
71
7253×
fn silent() -> impl FnMut(&str) {
73114×
    |_| {}
7453×
}
75
76
/// A backend error as a store error: what is not found or already there
77
/// is handled where it matters; the rest is an I/O failure.
784×
fn backend_err(e: BackendError) -> StoreError {
794×
    match e {
804×
        BackendError::Io(e) => StoreError::Io(e),
810×
        other => StoreError::Io(io::Error::other(other.to_string())),
82
    }
834×
}
84
85
/// `put_new` where an object already there is what we wanted.
867507×
fn put_new_or_existing(backend: &Backend, key: &str, bytes: &[u8]) -> Result<()> {
877507×
    match backend.put_new(key, bytes) {
887507×
        Ok(()) | Err(BackendError::Exists(_)) => Ok(()),
890×
        Err(e) => Err(backend_err(e)),
90
    }
917507×
}
92
93
/// `get` as an option: `None` when there is no such key.
9468062×
fn get_optional(backend: &Backend, key: &str) -> Result<Option<Vec<u8>>> {
9568062×
    match backend.get(key) {
9646832×
        Ok(b) => Ok(Some(b)),
9721230×
        Err(BackendError::NotFound(_)) => Ok(None),
980×
        Err(e) => Err(backend_err(e)),
99
    }
10068062×
}
101
1022975×
fn delete(backend: &Backend, key: &str) -> Result<()> {
1032975×
    backend.delete(key).map_err(backend_err)
1042975×
}
105
106
/// `loose/<hh>/<rest>`.
107101309×
fn loose_key(r: &ObjectRef) -> String {
108101309×
    let h = r.to_hex();
109101309×
    format!("loose/{}/{}", &h[..2], &h[2..])
110101309×
}
111
112
/// The object a loose key names, if it is one.
11316729×
fn loose_ref(key: &str) -> Option<ObjectRef> {
11416729×
    let rest = key.strip_prefix("loose/")?;
11516729×
    let (hh, tail) = rest.split_once('/')?;
11616729×
    if hh.len() != 2 || tail.contains('/') {
1170×
        return None;
11816729×
    }
11916729×
    ObjectRef::from_hex(&format!("{hh}{tail}"))
12016729×
}
121
122
/// `<index>/<hh>/<rest>/` for the entries kept under an object.
1234426×
fn fanout_prefix(index: &str, r: &ObjectRef) -> String {
1244426×
    let h = r.to_hex();
1254426×
    format!("{index}/{}/{}/", &h[..2], &h[2..])
1264426×
}
127
128
/// `<index>/<hh>/<rest>`: the one-file-per-object layout of older stores.
1293844×
fn legacy_key(index: &str, r: &ObjectRef) -> String {
1303844×
    let h = r.to_hex();
1313844×
    format!("{index}/{}/{}", &h[..2], &h[2..])
1323844×
}
133
13421×
fn now_ms() -> u64 {
13521×
    std::time::SystemTime::now()
13621×
        .duration_since(std::time::UNIX_EPOCH)
13721×
        .map(|d| d.as_millis() as u64)
13821×
        .unwrap_or(0)
13921×
}
140
141
#[derive(Clone, Copy, Debug)]
142
struct PackEntry {
143
    offset: u64,
144
    stored_len: u32,
145
    raw_len: u32,
146
    ty: ObjectType,
147
    flags: u8,
148
}
149
150
/// One pack's index, fully in memory and sorted by ObjectRef.
151
struct PackIndex {
152
    /// The pack's key, `pack-<id>.pack`.
153
    key: String,
154
    refs: Vec<ObjectRef>,
155
    entries: Vec<PackEntry>,
156
    /// The pack's dictionary, prepared once, when it has one.
157
    dict: Option<Arc<zstd::dict::DecoderDictionary<'static>>>,
158
}
159
160
impl std::fmt::Debug for PackIndex {
1610×
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1620×
        f.debug_struct("PackIndex")
1630×
            .field("key", &self.key)
1640×
            .field("objects", &self.refs.len())
1650×
            .field("dict", &self.dict.is_some())
1660×
            .finish()
1670×
    }
168
}
169
170
/// Decode a stored pack entry and check it against its reference.
17115674×
fn decode_entry(
17215674×
    r: &ObjectRef,
17315674×
    e: PackEntry,
17415674×
    stored: Vec<u8>,
17515674×
    dict: Option<&Arc<zstd::dict::DecoderDictionary<'static>>>,
17615674×
) -> Result<Object> {
17715674×
    let body = if e.flags & FLAG_DICT != 0 {
1784501×
        let dict = dict.ok_or_else(|| {
1790×
            StoreError::Corrupt(*r, "packed with a dictionary the pack lacks".into())
1800×
        })?;
1814501×
        zstd::bulk::Decompressor::with_prepared_dictionary(dict)
1824501×
            .and_then(|mut d| d.decompress(&stored, e.raw_len as usize))
1834501×
            .map_err(|err| StoreError::Corrupt(*r, format!("zstd: {err}")))?
18411173×
    } else if e.flags & FLAG_ZSTD != 0 {
1856429×
        zstd::bulk::decompress(&stored, e.raw_len as usize)
1866429×
            .map_err(|err| StoreError::Corrupt(*r, format!("zstd: {err}")))?
187
    } else {
1884744×
        stored
189
    };
19015669×
    if body.len() != e.raw_len as usize || hash_object(e.ty, &body) != *r {
191119×
        return Err(StoreError::Corrupt(
192119×
            *r,
193119×
            "packed object does not match its reference".into(),
194119×
        ));
19515550×
    }
19615550×
    Ok((e.ty, body))
19715674×
}
198
199
impl PackIndex {
2001127×
    fn load(backend: &Backend, idx_key: &str, pack_key: &str) -> Result<PackIndex> {
2011127×
        let data = backend.get(idx_key).map_err(backend_err)?;
2021127×
        let bad = |m: &str| StoreError::Corrupt(ObjectRef::ZERO, format!("{idx_key}: {m}"));
2031127×
        if data.len() < 12 || &data[..8] != IDX_MAGIC {
2042×
            return Err(bad("bad index header"));
2051125×
        }
2061125×
        let count = u32::from_le_bytes(data[8..12].try_into().unwrap()) as usize;
2071125×
        if data.len() != 12 + count * IDX_ENTRY {
20842×
            return Err(bad("index length mismatch"));
2091083×
        }
2101083×
        let pack_len = backend
2111083×
            .stat(pack_key)
2121083×
            .map_err(backend_err)?
2131083×
            .ok_or_else(|| bad("the index names a pack that is not there"))?
214
            .size;
2151083×
        let mut refs = Vec::with_capacity(count);
2161083×
        let mut entries = Vec::with_capacity(count);
21726095×
        for i in 0..count {
21826095×
            let e = &data[12 + i * IDX_ENTRY..12 + (i + 1) * IDX_ENTRY];
21926095×
            let r = ObjectRef::from_slice(&e[..32]).unwrap();
22026095×
            if let Some(prev) = refs.last() {
22125012×
                if r <= *prev {
2223×
                    return Err(bad("index not sorted"));
22325009×
                }
2241083×
            }
22526092×
            refs.push(r);
22626087×
            let entry = PackEntry {
22726092×
                offset: u64::from_le_bytes(e[32..40].try_into().unwrap()),
22826092×
                stored_len: u32::from_le_bytes(e[40..44].try_into().unwrap()),
22926092×
                raw_len: u32::from_le_bytes(e[44..48].try_into().unwrap()),
23026092×
                ty: ObjectType::ALL
23126092×
                    .get(e[48] as usize)
23226092×
                    .copied()
23326092×
                    .ok_or_else(|| bad("unknown object type"))?,
23426087×
                flags: e[49],
235
            };
23626087×
            if entry.stored_len > MAX_OBJECT_LEN || entry.raw_len > MAX_OBJECT_LEN {
2373×
                return Err(StoreError::Corrupt(
2383×
                    r,
2393×
                    format!(
2403×
                        "{idx_key}: the index claims an object of {} bytes ({} stored), more than the {MAX_OBJECT_LEN} an object may be",
2413×
                        entry.raw_len, entry.stored_len
2423×
                    ),
2433×
                ));
24426084×
            }
24526084×
            if entry.offset.saturating_add(entry.stored_len as u64) > pack_len {
24654×
                return Err(bad("index entry points outside the pack"));
24726030×
            }
24826030×
            entries.push(entry);
249
        }
2501018×
        let dict_key = format!("{}.dict", pack_key.trim_end_matches(".pack"));
2511018×
        let dict = get_optional(backend, &dict_key)?
2521018×
            .map(|d| Arc::new(zstd::dict::DecoderDictionary::copy(&d)));
2531018×
        Ok(PackIndex {
2541018×
            key: pack_key.to_string(),
2551018×
            refs,
2561018×
            entries,
2571018×
            dict,
2581018×
        })
2591127×
    }
260
26117812×
    fn find(&self, r: &ObjectRef) -> Option<PackEntry> {
26217812×
        self.refs.binary_search(r).ok().map(|i| self.entries[i])
26317812×
    }
264
265
    /// Read one entry from the pack: one ranged read, then decode.
26615192×
    fn fetch(&self, backend: &Backend, r: &ObjectRef, e: PackEntry) -> Result<Object> {
26715192×
        let stored = backend
26815192×
            .get_range(&self.key, e.offset..e.offset + e.stored_len as u64)
26915192×
            .map_err(|err| match err {
2700×
                BackendError::NotFound(_) => StoreError::NotFound(*r),
2710×
                other => backend_err(other),
2720×
            })?;
27315192×
        decode_entry(r, e, stored, self.dict.as_ref())
27415192×
    }
275
}
276
27711944×
fn type_index(ty: ObjectType) -> u8 {
27817236×
    ObjectType::ALL.iter().position(|t| *t == ty).unwrap() as u8
27911944×
}
280
281
/// What `pack_loose` did.
282
#[derive(Debug, Clone, Default, PartialEq, Eq)]
283
pub struct PackReport {
284
    pub objects: usize,
285
    pub raw_bytes: u64,
286
    pub packed_bytes: u64,
287
}
288
289
/// Packs tolerated before `merge_packs` folds them into one (spec §13.4).
290
pub const MAX_PACKS: usize = 16;
291
292
/// What `prune` did.
293
#[derive(Debug, Clone, Default, PartialEq, Eq)]
294
pub struct PruneReport {
295
    pub objects: usize,
296
    pub bytes: u64,
297
    /// Unreachable objects left alone because they are younger than the grace period.
298
    pub deferred: usize,
299
}
300
301
#[derive(Debug, thiserror::Error)]
302
pub enum StoreError {
303
    #[error("io: {0}")]
304
    Io(#[from] io::Error),
305
    #[error("corrupt object {0}: {1}")]
306
    Corrupt(ObjectRef, String),
307
    #[error("object {0}")]
308
    Object(#[from] ObjectError),
309
    #[error("object {0} is a {1}, expected {2}")]
310
    WrongType(ObjectRef, &'static str, &'static str),
311
    #[error("object {0} not found")]
312
    NotFound(ObjectRef),
313
    #[error("a {kind} object of {size} bytes is larger than the {limit} bytes an object may be; nothing was stored. A change this large adds or touches too many files at once: commit it in parts (a directory at a time)")]
314
    TooLarge {
315
        kind: &'static str,
316
        size: usize,
317
        limit: u32,
318
    },
319
}
320
321
pub type Result<T> = std::result::Result<T, StoreError>;
322
323
pub struct Store {
324
    backend: Arc<Backend>,
325
    /// Temporary files (a pack being streamed) and derived caches (`metas`).
326
    /// For a store in a directory it is that directory.
327
    scratch: PathBuf,
328
    /// The backend is that directory, so the old file paths still hold.
329
    local: bool,
330
    packs: RefCell<Vec<PackIndex>>,
331
    /// An open write batch (spec §13.4): objects go here instead of to loose
332
    /// files, and are written out with one `fsync` when the batch finishes.
333
    pending: RefCell<Option<Pending>>,
334
    batch_depth: std::cell::Cell<u32>,
335
    /// Change metadata already read, from the `metas` cache file.
336
    metas: RefCell<Option<crate::fasthash::FastMap<ObjectRef, crate::state::ChangeMeta>>>,
337
}
338
339
impl std::fmt::Debug for Store {
3400×
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3410×
        f.debug_struct("Store")
3420×
            .field("backend", &self.backend.describe())
3430×
            .field("scratch", &self.scratch)
3440×
            .field("packs", &self.packs.borrow().len())
3450×
            .finish()
3460×
    }
347
}
348
349
/// Objects written since `begin_batch`. Small batches stay in memory and
350
/// become loose objects; once `SPILL_OBJECTS` or `SPILL_BYTES` is exceeded
351
/// the batch streams into a pack file instead.
352
#[derive(Debug)]
353
struct Pending {
354
    buffered: Vec<(ObjectType, Vec<u8>)>,
355
    buffered_bytes: usize,
356
    lookup: std::collections::HashMap<ObjectRef, PendingEntry>,
357
    pack: Option<PendingPack>,
358
    report: PackReport,
359
}
360
361
#[derive(Debug, Clone, Copy)]
362
enum PendingEntry {
363
    Buffered(usize),
364
    Packed(PackEntry),
365
}
366
367
#[derive(Debug)]
368
struct PendingPack {
369
    id: String,
370
    tmp_path: PathBuf,
371
    writer: io::BufWriter<fs::File>,
372
    offset: u64,
373
    index: Vec<(ObjectRef, PackEntry)>,
374
}
375
376
const SPILL_OBJECTS: usize = 256;
377
const SPILL_BYTES: usize = 8 << 20;
378
379
/// Finishes the enclosing batch when dropped; call `finish` to see errors.
380
pub struct Batch<'a> {
381
    store: &'a Store,
382
    done: bool,
383
}
384
385
impl Batch<'_> {
3862660×
    pub fn finish(mut self) -> Result<()> {
3872660×
        self.done = true;
3882660×
        self.store.finish_batch()
3892660×
    }
390
}
391
392
impl Drop for Batch<'_> {
3932662×
    fn drop(&mut self) {
3942662×
        if !self.done {
3952×
            let _ = self.store.finish_batch();
3962660×
        }
3972662×
    }
398
}
399
400
/// Append one stored object to a pending pack and index it.
4012100×
fn write_pack_entry(
4022100×
    pack: &mut PendingPack,
4032100×
    r: &ObjectRef,
4042100×
    ty: ObjectType,
4052100×
    raw_len: usize,
4062100×
    flags: u8,
4072100×
    stored: &[u8],
4082100×
    report: &mut PackReport,
4092100×
) -> Result<PackEntry> {
4102100×
    let header_len = 1 + 1 + 4 + 4 + 32;
4112100×
    pack.writer.write_all(&[type_index(ty), flags])?;
4122100×
    pack.writer
4132100×
        .write_all(&(stored.len() as u32).to_le_bytes())?;
4142100×
    pack.writer.write_all(&(raw_len as u32).to_le_bytes())?;
4152100×
    pack.writer.write_all(&r.0)?;
4162100×
    pack.writer.write_all(stored)?;
4172100×
    let entry = PackEntry {
4182100×
        offset: pack.offset + header_len,
4192100×
        stored_len: stored.len() as u32,
4202100×
        raw_len: raw_len as u32,
4212100×
        ty,
4222100×
        flags,
4232100×
    };
4242100×
    pack.offset += header_len + stored.len() as u64;
4252100×
    pack.index.push((*r, entry));
4262100×
    report.objects += 1;
4272100×
    report.raw_bytes += raw_len as u64;
4282100×
    report.packed_bytes += stored.len() as u64;
4292100×
    Ok(entry)
4302100×
}
431
432
/// A random name for a temporary file or a pack.
43375×
fn fresh_id() -> String {
43475×
    let mut nonce = [0u8; 8];
43575×
    rand::rngs::OsRng.fill_bytes(&mut nonce);
43675×
    hex::encode(nonce)
43775×
}
438
439
/// Under `OXY_STORE_BACKEND=memory` every store opens on a store in
440
/// memory shared by directory, so the whole test suite can run without a
441
/// directory store, as it would over a bucket. Objects live for the
442
/// process.
4432706×
fn memory_backend_for(dir: &Path) -> Option<Arc<Backend>> {
444
    use std::collections::HashMap;
445
    use std::sync::{Mutex, OnceLock};
4462706×
    if std::env::var_os("OXY_STORE_BACKEND").as_deref() != Some(std::ffi::OsStr::new("memory")) {
4472706×
        return None;
4480×
    }
449
    static STORES: OnceLock<Mutex<HashMap<PathBuf, Arc<MemoryStore>>>> = OnceLock::new();
4500×
    let key = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf());
4510×
    let mut map = STORES
4520×
        .get_or_init(Default::default)
4530×
        .lock()
4540×
        .unwrap_or_else(|p| p.into_inner());
4550×
    let store = map
4560×
        .entry(key)
4570×
        .or_insert_with(|| Arc::new(MemoryStore::new()))
4580×
        .clone();
4590×
    Some(store)
4602706×
}
461
462
#[cfg(test)]
463
thread_local! {
464
    /// A backend every store opened on this thread uses instead of its
465
    /// directory: tests of a repository kept on a store that is not this
466
    /// disk's directory, with several handles on one store.
467
    pub(crate) static TEST_BACKEND: RefCell<Option<Arc<Backend>>> = const { RefCell::new(None) };
468
}
469
470
impl Store {
471
    /// Open the store in `dir`, which is also its scratch directory.
4722710×
    pub fn open(dir: impl Into<PathBuf>) -> io::Result<Store> {
4732710×
        let dir = dir.into();
4742710×
        fs::create_dir_all(dir.join("loose"))?;
475
        #[cfg(test)]
4761158×
        if let Some(backend) = TEST_BACKEND.with(|t| t.borrow().clone()) {
4774×
            return Store::open_on(backend, dir);
4781154×
        }
4792706×
        if let Some(backend) = memory_backend_for(&dir) {
4800×
            return Store::open_on(backend, dir);
4812706×
        }
4822706×
        let backend: Arc<Backend> =
4832706×
            Arc::new(LocalStore::open(&dir).map_err(|e| io::Error::other(e.to_string()))?);
4842706×
        let mut store = Store::open_on(backend, dir)?;
4852597×
        store.local = true;
4862597×
        Ok(store)
4872710×
    }
488
489
    /// Open the store kept on `backend`, with `scratch` for what must be
490
    /// on this disk: a pack while it is being written, and caches.
4912724×
    pub fn open_on(backend: Arc<Backend>, scratch: impl Into<PathBuf>) -> io::Result<Store> {
4922724×
        let scratch = scratch.into();
4932724×
        fs::create_dir_all(&scratch)?;
4942724×
        let store = Store {
4952724×
            backend,
4962724×
            scratch,
4972724×
            local: false,
4982724×
            packs: RefCell::new(Vec::new()),
4992724×
            pending: RefCell::new(None),
5002724×
            batch_depth: std::cell::Cell::new(0),
5012724×
            metas: RefCell::new(None),
5022724×
        };
5032724×
        store
5042724×
            .reload_packs()
5052724×
            .map_err(|e| io::Error::other(e.to_string()))?;
5062615×
        Ok(store)
5072724×
    }
508
509
    /// The storage under this store.
51035×
    pub fn backend(&self) -> &Arc<Backend> {
51135×
        &self.backend
51235×
    }
513
514
    /// Whether the store is the directory `dir()` names, where every key
515
    /// is a file.
51622990×
    pub fn is_local(&self) -> bool {
51722990×
        self.local
51822990×
    }
519
5202869×
    fn reload_packs(&self) -> Result<()> {
5212869×
        let listed = self.backend.list("pack-").map_err(backend_err)?;
5222869×
        let mut idx_keys: Vec<&str> = listed
5232869×
            .iter()
5242869×
            .map(|e| e.key.as_str())
5252869×
            .filter(|k| k.ends_with(".idx"))
5262869×
            .collect();
5272869×
        idx_keys.sort();
5282869×
        let mut packs = Vec::new();
5292869×
        for idx in idx_keys {
5301127×
            let pack = format!("{}.pack", idx.trim_end_matches(".idx"));
53110731×
            if listed.iter().any(|e| e.key == pack) {
5321127×
                packs.push(PackIndex::load(self.backend.as_ref(), idx, &pack)?);
5330×
            }
534
        }
5352760×
        *self.packs.borrow_mut() = packs;
5362760×
        Ok(())
5372869×
    }
538
53915×
    pub fn pack_count(&self) -> usize {
54015×
        self.packs.borrow().len()
54115×
    }
542
54334134×
    fn find_packed(&self, r: &ObjectRef) -> Option<(usize, PackEntry)> {
54434134×
        self.packs
54534134×
            .borrow()
54634134×
            .iter()
54734134×
            .enumerate()
54834134×
            .find_map(|(i, p)| p.find(r).map(|e| (i, e)))
54934134×
    }
550
551
    /// Loose objects, with their keys and ages.
552820×
    fn loose_objects(&self) -> Result<Vec<(ObjectRef, strata::Entry)>> {
553820×
        let mut out: Vec<(ObjectRef, strata::Entry)> = self
554820×
            .backend
555820×
            .list("loose/")
556820×
            .map_err(backend_err)?
557820×
            .into_iter()
55816729×
            .filter_map(|e| loose_ref(&e.key).map(|r| (r, e)))
559820×
            .collect();
560820×
        out.sort_by_key(|(r, _)| *r);
561820×
        Ok(out)
562820×
    }
563
564652×
    pub fn loose_count(&self) -> io::Result<usize> {
565652×
        self.loose_objects()
566652×
            .map(|l| l.len())
567652×
            .map_err(|e| io::Error::other(e.to_string()))
568652×
    }
569
570
    /// Move every loose object into a new pack (spec §13.4). Loose objects
571
    /// are deleted only after the pack and its index are durable.
57244×
    pub fn pack_loose(&self) -> Result<PackReport> {
57344×
        let loose = self.loose_objects()?;
57444×
        self.write_pack(
57544×
            &loose.iter().map(|(r, _)| *r).collect::<Vec<_>>(),
576424×
            &loose.iter().map(|(_, e)| e.key.clone()).collect::<Vec<_>>(),
57744×
            &[],
578
            ZSTD_LEVEL,
57944×
            &mut silent(),
580
        )
58144×
    }
582
583
    /// Fold every pack and loose object into one pack compressed at
584
    /// `level` (spec §13.4): what an explicit `oxy gc` does, as `git gc`
585
    /// repacks. Returns the report and how many packs were folded in.
5862×
    pub fn repack_all(&self, level: i32) -> Result<(PackReport, usize)> {
5872×
        self.repack_all_with(level, &mut silent())
5882×
    }
589
590
    /// [`Store::repack_all`], reporting progress.
59118×
    pub fn repack_all_with(&self, level: i32, progress: Progress) -> Result<(PackReport, usize)> {
59218×
        let loose = self.loose_objects()?;
59318×
        let (mut refs, keys): (Vec<ObjectRef>, Vec<String>) = {
59418×
            let packs = self.packs.borrow();
595
            (
59618×
                packs.iter().flat_map(|p| p.refs.iter().copied()).collect(),
59718×
                packs.iter().map(|p| p.key.clone()).collect(),
598
            )
599
        };
60018×
        if loose.is_empty() && keys.len() <= 1 && level == ZSTD_LEVEL {
6010×
            return Ok((PackReport::default(), 0));
60218×
        }
60318×
        refs.extend(loose.iter().map(|(r, _)| *r));
60418×
        let loose_keys: Vec<String> = loose.into_iter().map(|(_, e)| e.key).collect();
60518×
        let n = keys.len();
60618×
        let report = self.write_pack(&refs, &loose_keys, &keys, level, progress)?;
60718×
        Ok((report, n))
60818×
    }
609
610
    /// Fold every pack into one when there are more than `MAX_PACKS`
611
    /// (spec §13.4). Returns how many packs were merged.
6124×
    pub fn merge_packs(&self) -> Result<usize> {
6132×
        let (refs, keys): (Vec<ObjectRef>, Vec<String>) = {
6144×
            let packs = self.packs.borrow();
6154×
            if packs.len() <= MAX_PACKS {
6162×
                return Ok(0);
6172×
            }
618
            (
61936×
                packs.iter().flat_map(|p| p.refs.iter().copied()).collect(),
62036×
                packs.iter().map(|p| p.key.clone()).collect(),
621
            )
622
        };
6232×
        let n = keys.len();
6242×
        self.write_pack(&refs, &[], &keys, ZSTD_LEVEL, &mut silent())?;
6252×
        Ok(n)
6264×
    }
627
628
    /// Delete every object not in `keep` (spec §21). Loose objects and packs
629
    /// younger than `grace` are left alone, since a concurrent writer may not
630
    /// have recorded its references yet. Packs holding unreachable objects
631
    /// are rewritten without them. Signatures, seal and receipt entries of
632
    /// deleted objects go too.
6335×
    pub fn prune(
6345×
        &self,
6355×
        keep: &std::collections::HashSet<ObjectRef>,
6365×
        grace: std::time::Duration,
6375×
    ) -> Result<PruneReport> {
6385×
        self.prune_with(keep, grace, &mut silent())
6395×
    }
640
641
    /// [`Store::prune`], reporting progress.
64221×
    pub fn prune_with(
64321×
        &self,
64421×
        keep: &std::collections::HashSet<ObjectRef>,
64521×
        grace: std::time::Duration,
64621×
        progress: Progress,
64721×
    ) -> Result<PruneReport> {
64821×
        progress("pruning loose objects");
64921×
        let now = now_ms();
65021×
        let grace_ms = grace.as_millis() as u64;
651
        // An object whose age the store does not know is old enough.
65221×
        let old_enough =
65333×
            |modified: Option<u64>| modified.is_none_or(|t| now.saturating_sub(t) >= grace_ms);
65421×
        let mut report = PruneReport::default();
655
        // Loose objects.
656280×
        for (r, entry) in self.loose_objects()? {
657280×
            if keep.contains(&r) {
658256×
                continue;
65924×
            }
66024×
            if !old_enough(entry.modified_ms) {
6614×
                report.deferred += 1;
6624×
                continue;
66320×
            }
66420×
            report.bytes += entry.size;
66520×
            report.objects += 1;
66620×
            delete(self.backend.as_ref(), &entry.key)?;
66720×
            self.remove_sidecars(&r)?;
668
        }
669
        // Packs: rewrite those that hold unreachable objects.
67021×
        let mut keep_refs: Vec<ObjectRef> = Vec::new();
67121×
        let mut old_keys: Vec<String> = Vec::new();
67221×
        let mut rewrite = false;
67321×
        progress("pruning packs");
67421×
        for p in self.packs.borrow().iter() {
675150×
            let unreachable = p.refs.iter().filter(|r| !keep.contains(r)).count();
67610×
            if unreachable == 0 {
6771×
                continue;
6789×
            }
6799×
            let modified = self
6809×
                .backend
6819×
                .stat(&p.key)
6829×
                .map_err(backend_err)?
6839×
                .and_then(|e| e.modified_ms);
6849×
            if !old_enough(modified) {
6853×
                report.deferred += unreachable;
6863×
                continue;
6876×
            }
6886×
            rewrite = true;
6896×
            old_keys.push(p.key.clone());
690102×
            for (r, e) in p.refs.iter().zip(p.entries.iter()) {
691102×
                if keep.contains(r) {
69261×
                    keep_refs.push(*r);
69361×
                } else {
69441×
                    report.objects += 1;
69541×
                    report.bytes += e.stored_len as u64;
69641×
                }
697
            }
698
        }
69921×
        if rewrite {
7006×
            let dropped: Vec<ObjectRef> = {
7016×
                let packs = self.packs.borrow();
7026×
                packs
7036×
                    .iter()
7046×
                    .filter(|p| old_keys.contains(&p.key))
7056×
                    .flat_map(|p| p.refs.iter().copied())
706102×
                    .filter(|r| !keep.contains(r))
7076×
                    .collect()
708
            };
7096×
            self.write_pack(&keep_refs, &[], &old_keys, ZSTD_LEVEL, progress)?;
71041×
            for r in dropped {
71141×
                self.remove_sidecars(&r)?;
712
            }
71315×
        }
71421×
        Ok(report)
71521×
    }
716
717
    /// Everything kept beside an object: its signatures and the seal and
718
    /// receipt entries under it, in both layouts.
71961×
    fn remove_sidecars(&self, r: &ObjectRef) -> Result<()> {
720183×
        for index in ["sigs", "seals", "receipts"] {
721183×
            delete(self.backend.as_ref(), &legacy_key(index, r))?;
722
        }
723183×
        for index in ["sig", "seal", "receipt"] {
724183×
            for e in self
725183×
                .backend
726183×
                .list(&fanout_prefix(index, r))
727183×
                .map_err(backend_err)?
728
            {
72910×
                delete(self.backend.as_ref(), &e.key)?;
730
            }
731
        }
73261×
        Ok(())
73361×
    }
734
735
    /// Put a complete, synced temporary pack file and its index into the
736
    /// store; `index` must be sorted by ObjectRef. The pack goes first: an
737
    /// index never names a pack that is not there.
73875×
    fn finish_pack_files(
73975×
        &self,
74075×
        id: &str,
74175×
        tmp_pack: &Path,
74275×
        index: &[(ObjectRef, PackEntry)],
74375×
    ) -> Result<()> {
74475×
        let mut idx = Vec::with_capacity(12 + index.len() * IDX_ENTRY);
74575×
        idx.extend_from_slice(IDX_MAGIC);
74675×
        idx.extend_from_slice(&(index.len() as u32).to_le_bytes());
7475972×
        for (r, e) in index {
7485972×
            idx.extend_from_slice(&r.0);
7495972×
            idx.extend_from_slice(&e.offset.to_le_bytes());
7505972×
            idx.extend_from_slice(&e.stored_len.to_le_bytes());
7515972×
            idx.extend_from_slice(&e.raw_len.to_le_bytes());
7525972×
            idx.extend_from_slice(&[type_index(e.ty), e.flags]);
7535972×
        }
75475×
        let put = self
75575×
            .backend
75675×
            .put_new_file(&format!("pack-{id}.pack"), tmp_pack)
75775×
            .map_err(backend_err);
758
        // A store on another disk copied it; the one in this directory
759
        // moved it and this finds nothing.
76075×
        let _ = fs::remove_file(tmp_pack);
76175×
        put?;
76275×
        self.backend
76375×
            .put_new(&format!("pack-{id}.idx"), &idx)
76475×
            .map_err(backend_err)?;
76575×
        self.reload_packs()
76675×
    }
767
768
    /// Remove a pack with its index and dictionary.
76949×
    fn remove_pack(&self, pack_key: &str) -> Result<()> {
77049×
        let stem = pack_key.trim_end_matches(".pack");
77149×
        delete(self.backend.as_ref(), pack_key)?;
77249×
        delete(self.backend.as_ref(), &format!("{stem}.idx"))?;
77349×
        delete(self.backend.as_ref(), &format!("{stem}.dict"))
77449×
    }
775
776
    /// Write `refs` into a new pack, then delete `loose_keys` and `old_packs`.
77770×
    fn write_pack(
77870×
        &self,
77970×
        refs: &[ObjectRef],
78070×
        loose_keys: &[String],
78170×
        old_packs: &[String],
78270×
        level: i32,
78370×
        progress: Progress,
78470×
    ) -> Result<PackReport> {
78570×
        if refs.is_empty() {
7860×
            for p in old_packs {
7870×
                self.remove_pack(p)?;
788
            }
7890×
            self.reload_packs()?;
7900×
            return Ok(PackReport::default());
79170×
        }
79270×
        let mut refs: Vec<ObjectRef> = refs.to_vec();
79370×
        refs.sort();
79470×
        refs.dedup();
79570×
        let id = fresh_id();
79670×
        let tmp_pack = self.scratch.join(format!(".tmp-{id}.pack"));
79770×
        let mut report = PackReport::default();
79870×
        let mut index: Vec<(ObjectRef, PackEntry)> = Vec::with_capacity(refs.len());
799
        // A full repack of enough objects trains a dictionary for them.
80070×
        let dict = if level == REPACK_ZSTD_LEVEL && refs.len() >= DICT_MIN_OBJECTS {
8012×
            let _t = crate::timing::phase("pack: train a dictionary");
8022×
            progress(&format!("training a dictionary on {} objects", refs.len()));
8032×
            self.train_dictionary(&refs)
804
        } else {
80568×
            None
806
        };
80770×
        let encoder = dict
80870×
            .as_ref()
80970×
            .map(|d| zstd::dict::EncoderDictionary::copy(d, level));
81070×
        let nocompress = self.nocompress_set()?;
811
        {
81270×
            let mut f = io::BufWriter::new(fs::File::create(&tmp_pack)?);
81370×
            f.write_all(PACK_MAGIC)?;
81470×
            let mut offset = PACK_MAGIC.len() as u64;
815
            // Read a batch (the store is not shared between threads),
816
            // compress it on every core, write it in order.
81770×
            let mut batches = refs.chunks(1024);
81870×
            let mut compressed_batch = Vec::new();
81970×
            let total = refs.len();
82070×
            let mut reported = usize::MAX;
821
            loop {
8223942×
                if compressed_batch.is_empty() {
823142×
                    let Some(batch) = batches.next() else { break };
824
                    // Every tenth, and the first batch.
82572×
                    let tenth = report.objects * 10 / total.max(1);
82672×
                    if tenth != reported {
82772×
                        reported = tenth;
82872×
                        progress(&format!("packing {} of {total} objects", report.objects));
82972×
                    }
83072×
                    let mut read: Vec<(ObjectRef, ObjectType, Vec<u8>, bool)> =
83172×
                        Vec::with_capacity(batch.len());
8323872×
                    for r in batch {
8333872×
                        let (ty, body) = self.get(r)?;
8343872×
                        read.push((*r, ty, body, nocompress.contains(r)));
835
                    }
836
                    use rayon::prelude::*;
83772×
                    compressed_batch = read
83872×
                        .into_par_iter()
83972×
                        .map_init(
8401017×
                            || {
8411017×
                                encoder.as_ref().and_then(|e| {
842415×
                                    zstd::bulk::Compressor::with_prepared_dictionary(e).ok()
843415×
                                })
8441017×
                            },
8453872×
                            |with_dict, (r, ty, body, raw)| {
8463872×
                                let packed = if raw {
8472×
                                    None
848
                                } else {
849
                                    // Small objects with the dictionary;
850
                                    // a large one has context enough.
8513870×
                                    let dicted = with_dict
8523870×
                                        .as_mut()
8533870×
                                        .filter(|_| body.len() <= DICT_OBJECT_MAX)
8543870×
                                        .and_then(|c| c.compress(&body).ok())
8553870×
                                        .map(|c| (FLAG_ZSTD | FLAG_DICT, c));
8563870×
                                    dicted
8573870×
                                        .or_else(|| {
858870×
                                            zstd::bulk::compress(&body, level)
859870×
                                                .ok()
860870×
                                                .map(|c| (FLAG_ZSTD, c))
861870×
                                        })
8623870×
                                        .filter(|(_, c)| c.len() < body.len())
863
                                };
8643872×
                                (r, ty, body, packed)
8653872×
                            },
866
                        )
86772×
                        .collect::<Vec<_>>();
86872×
                    compressed_batch.reverse();
8693800×
                }
8703872×
                let Some((r, ty, body, packed)) = compressed_batch.pop() else {
8710×
                    continue;
872
                };
8733872×
                let r = &r;
8743872×
                let (flags, stored) = match packed {
8753375×
                    Some(c) => c,
876497×
                    None => (0, body.clone()),
877
                };
8783872×
                let header_len = 1 + 1 + 4 + 4 + 32;
8793872×
                f.write_all(&[type_index(ty), flags])?;
8803872×
                f.write_all(&(stored.len() as u32).to_le_bytes())?;
8813872×
                f.write_all(&(body.len() as u32).to_le_bytes())?;
8823872×
                f.write_all(&r.0)?;
8833872×
                f.write_all(&stored)?;
8843872×
                index.push((
8853872×
                    *r,
8863872×
                    PackEntry {
8873872×
                        offset: offset + header_len,
8883872×
                        stored_len: stored.len() as u32,
8893872×
                        raw_len: body.len() as u32,
8903872×
                        ty,
8913872×
                        flags,
8923872×
                    },
8933872×
                ));
8943872×
                offset += header_len + stored.len() as u64;
8953872×
                report.objects += 1;
8963872×
                report.raw_bytes += body.len() as u64;
8973872×
                report.packed_bytes += stored.len() as u64;
898
            }
89970×
            f.flush()?;
90070×
            f.get_ref().sync_all()?;
901
        }
902
        // The dictionary before the pack that needs it becomes visible.
90370×
        if let Some(d) = &dict {
9042×
            self.backend
9052×
                .put_new(&format!("pack-{id}.dict"), d)
9062×
                .map_err(backend_err)?;
90768×
        }
90870×
        progress(&format!("writing the index of {} objects", index.len()));
90970×
        self.finish_pack_files(&id, &tmp_pack, &index)?;
91070×
        for p in old_packs {
91149×
            self.remove_pack(p)?;
912
        }
91370×
        self.reload_packs()?;
9142172×
        for key in loose_keys {
9152172×
            delete(self.backend.as_ref(), key)?;
916
        }
91770×
        Ok(report)
91870×
    }
919
920
    /// A dictionary for these objects, trained on a sample of them (at
921
    /// most 10 000, 32 MB); `None` when training fails.
9222×
    fn train_dictionary(&self, refs: &[ObjectRef]) -> Option<Vec<u8>> {
9232×
        let step = (refs.len() / 10_000).max(1);
9242×
        let mut samples: Vec<Vec<u8>> = Vec::new();
9252×
        let mut total = 0usize;
9263000×
        for r in refs.iter().step_by(step) {
9273000×
            if total > 32 << 20 {
9280×
                break;
9293000×
            }
9303000×
            let Ok((ty, body)) = self.get(r) else {
9310×
                continue;
932
            };
9330×
            if matches!(
9343000×
                ty,
935
                ObjectType::Chunk | ObjectType::Blob | ObjectType::Change
9363000×
            ) && !body.is_empty()
9373000×
                && body.len() < 1 << 20
9383000×
            {
9393000×
                total += body.len();
9403000×
                samples.push(body);
9413000×
            }
942
        }
9432×
        zstd::dict::from_samples(&samples, DICT_BYTES).ok()
9442×
    }
945
946
    /// The scratch directory: for a store in a directory, that directory.
9477×
    pub fn dir(&self) -> &Path {
9487×
        &self.scratch
9497×
    }
950
951
    /// Where a loose object is kept, for a store in a directory (tests
952
    /// tamper with and remove objects there).
953
    #[cfg(test)]
9544×
    pub(crate) fn path_for(&self, r: &ObjectRef) -> PathBuf {
9554×
        self.scratch.join(loose_key(r))
9564×
    }
957
958
    /// Remove a loose object, whatever the store is on (tests make an
959
    /// object go missing).
960
    #[cfg(test)]
9613×
    pub(crate) fn remove_loose_for_test(&self, r: &ObjectRef) -> Result<()> {
9623×
        delete(self.backend.as_ref(), &loose_key(r))
9633×
    }
964
96511422×
    pub fn has(&self, r: &ObjectRef) -> bool {
96611422×
        self.backend.has(&loose_key(r)).unwrap_or(false)
9671209×
            || self.find_packed(r).is_some()
968880×
            || self
969880×
                .pending
970880×
                .borrow()
971880×
                .as_ref()
972880×
                .is_some_and(|p| p.lookup.contains_key(r))
97311422×
    }
974
975
    /// Start a write batch: until the matching `finish`, `put` collects
976
    /// objects and writes them out together, with one `fsync` for a large
977
    /// batch (a pack) instead of one per object. Batches nest; only the
978
    /// outermost does the work. Objects are readable while pending.
9792663×
    pub fn begin_batch(&self) -> Result<Batch<'_>> {
9802663×
        let depth = self.batch_depth.get();
9812663×
        if depth == 0 {
9822166×
            *self.pending.borrow_mut() = Some(Pending {
9832166×
                buffered: vec![],
9842166×
                buffered_bytes: 0,
9852166×
                lookup: Default::default(),
9862166×
                pack: None,
9872166×
                report: PackReport::default(),
9882166×
            });
9892166×
        }
9902663×
        self.batch_depth.set(depth + 1);
9912663×
        Ok(Batch {
9922663×
            store: self,
9932663×
            done: false,
9942663×
        })
9952663×
    }
996
9972662×
    fn finish_batch(&self) -> Result<()> {
9982662×
        let depth = self.batch_depth.get();
9992662×
        if depth == 0 {
10000×
            return Ok(());
10012662×
        }
10022662×
        self.batch_depth.set(depth - 1);
10032662×
        if depth > 1 {
1004497×
            return Ok(());
10052165×
        }
10062165×
        let Some(pending) = self.pending.borrow_mut().take() else {
10072×
            return Ok(());
1008
        };
10092163×
        self.write_pending(pending)
10102662×
    }
1011
1012
    /// Make every object written so far durable, even inside an open
1013
    /// batch, which stays open. Call before a reference that names them
1014
    /// is moved (spec §13.6): the operation head, a bookmark pointer.
10153310×
    pub fn flush(&self) -> Result<()> {
10163310×
        let Some(pending) = self.pending.borrow_mut().take() else {
10172326×
            return Ok(());
1018
        };
1019984×
        self.write_pending(pending)?;
1020982×
        *self.pending.borrow_mut() = Some(Pending {
1021982×
            buffered: vec![],
1022982×
            buffered_bytes: 0,
1023982×
            lookup: Default::default(),
1024982×
            pack: None,
1025982×
            report: PackReport::default(),
1026982×
        });
1027982×
        Ok(())
10283310×
    }
1029
10303147×
    fn write_pending(&self, pending: Pending) -> Result<()> {
10313147×
        match pending.pack {
1032
            None => {
10333143×
                let objects: Vec<(ObjectType, &[u8])> = pending
10343143×
                    .buffered
10353143×
                    .iter()
10364924×
                    .map(|(ty, body)| (*ty, body.as_slice()))
10373143×
                    .collect();
10383143×
                self.put_loose_many(&objects)
1039
            }
10404×
            Some(mut pack) => {
10414×
                pack.writer.flush()?;
10424×
                pack.writer.get_ref().sync_all()?;
10434×
                drop(pack.writer);
10444×
                pack.index.sort_by_key(|(r, _)| *r);
10454×
                self.finish_pack_files(&pack.id, &pack.tmp_path, &pack.index)?;
10464×
                Ok(())
1047
            }
1048
        }
10493147×
    }
1050
1051
    /// Whether a batch is open and holds `r`.
1052925×
    fn pending_get(&self, r: &ObjectRef) -> Option<Result<Object>> {
1053925×
        let mut guard = self.pending.borrow_mut();
1054925×
        let pending = guard.as_mut()?;
1055820×
        let entry = *pending.lookup.get(r)?;
1056820×
        Some(match entry {
1057638×
            PendingEntry::Buffered(i) => {
1058638×
                let (ty, body) = &pending.buffered[i];
1059638×
                Ok((*ty, body.clone()))
1060
            }
1061182×
            PendingEntry::Packed(e) => {
1062182×
                let Some(pack) = pending.pack.as_mut() else {
10630×
                    return Some(Err(StoreError::NotFound(*r)));
1064
                };
1065
                // Read from the pack file being written, on this disk.
1066182×
                (|| {
1067182×
                    pack.writer.flush()?;
1068
                    use std::io::{Read, Seek, SeekFrom};
1069182×
                    let mut f = fs::File::open(&pack.tmp_path)?;
1070182×
                    f.seek(SeekFrom::Start(e.offset))?;
1071182×
                    let mut stored = vec![0u8; e.stored_len as usize];
1072182×
                    f.read_exact(&mut stored)?;
1073182×
                    decode_entry(r, e, stored, None)
1074
                })()
1075
            }
1076
        })
1077925×
    }
1078
1079
    /// Append one object to the pending pack file.
10801900×
    fn pending_pack_write(
10811900×
        &self,
10821900×
        pack: &mut PendingPack,
10831900×
        r: &ObjectRef,
10841900×
        ty: ObjectType,
10851900×
        body: &[u8],
10861900×
        report: &mut PackReport,
10871900×
    ) -> Result<PackEntry> {
10881900×
        let (flags, stored) = if self.is_nocompress(r) {
1089120×
            (0, body.to_vec())
1090
        } else {
10911780×
            let compressed = zstd::bulk::compress(body, ZSTD_LEVEL)
10921780×
                .map_err(|e| StoreError::Corrupt(*r, format!("zstd: {e}")))?;
10931780×
            if compressed.len() < body.len() {
10941620×
                (FLAG_ZSTD, compressed)
1095
            } else {
1096160×
                (0, body.to_vec())
1097
            }
1098
        };
10991900×
        write_pack_entry(pack, r, ty, body.len(), flags, &stored, report)
11001900×
    }
1101
11026925×
    fn put_pending(&self, r: ObjectRef, ty: ObjectType, body: &[u8]) -> Result<()> {
11036925×
        let mut guard = self.pending.borrow_mut();
11046925×
        let pending = guard.as_mut().expect("batch open");
11056925×
        if pending.lookup.contains_key(&r) {
1106101×
            return Ok(());
11076824×
        }
11086824×
        if pending.pack.is_none()
11095858×
            && pending.buffered.len() < SPILL_OBJECTS
11105856×
            && pending.buffered_bytes + body.len() <= SPILL_BYTES
1111
        {
11125854×
            pending.buffered.push((ty, body.to_vec()));
11135854×
            pending.buffered_bytes += body.len();
11145854×
            pending
11155854×
                .lookup
11165854×
                .insert(r, PendingEntry::Buffered(pending.buffered.len() - 1));
11175854×
            return Ok(());
1118970×
        }
1119970×
        self.ensure_pack(pending)?;
1120970×
        let mut report = std::mem::take(&mut pending.report);
1121970×
        let pack = pending.pack.as_mut().unwrap();
1122970×
        let e = self.pending_pack_write(pack, &r, ty, body, &mut report)?;
1123970×
        pending.report = report;
1124970×
        pending.lookup.insert(r, PendingEntry::Packed(e));
1125970×
        Ok(())
11266925×
    }
1127
1128
    /// Open the pending batch's pack, moving the objects buffered so far
1129
    /// into it (a spill).
1130971×
    fn ensure_pack(&self, pending: &mut Pending) -> Result<()> {
1131971×
        if pending.pack.is_none() {
1132
            // Spill: open the pack and move the buffered objects into it.
11335×
            let id = fresh_id();
11345×
            let tmp_path = self.scratch.join(format!(".tmp-{id}.pack"));
11355×
            let mut writer = io::BufWriter::new(fs::File::create(&tmp_path)?);
11365×
            writer.write_all(PACK_MAGIC)?;
11375×
            let mut pack = PendingPack {
11385×
                id,
11395×
                tmp_path,
11405×
                writer,
11415×
                offset: PACK_MAGIC.len() as u64,
11425×
                index: vec![],
11435×
            };
11445×
            let buffered = std::mem::take(&mut pending.buffered);
11455×
            pending.buffered_bytes = 0;
11465×
            let mut report = std::mem::take(&mut pending.report);
1147930×
            for (bty, bbody) in &buffered {
1148930×
                let br = hash_object(*bty, bbody);
1149930×
                let e = self.pending_pack_write(&mut pack, &br, *bty, bbody, &mut report)?;
1150930×
                pending.lookup.insert(br, PendingEntry::Packed(e));
1151
            }
11525×
            pending.report = report;
11535×
            pending.pack = Some(pack);
1154966×
        }
1155971×
        Ok(())
1156971×
    }
1157
1158
    /// Store many objects at once. Inside a large write batch they are
1159
    /// compressed on every core and appended in order; otherwise each is
1160
    /// stored as [`Store::put`] does.
1161761×
    pub fn put_many(&self, objects: &[(ObjectType, &[u8])]) -> Result<Vec<ObjectRef>> {
1162
        use rayon::prelude::*;
1163761×
        let total: usize = objects.iter().map(|(_, b)| b.len()).sum();
1164761×
        if self.pending.borrow().is_none() || total < SPILL_BYTES {
1165760×
            return objects.iter().map(|(ty, b)| self.put(*ty, b)).collect();
11661×
        }
1167202×
        for (ty, b) in objects {
1168202×
            if b.len() > MAX_OBJECT_LEN as usize {
11690×
                return Err(StoreError::TooLarge {
11700×
                    kind: ty.name(),
11710×
                    size: b.len(),
11720×
                    limit: MAX_OBJECT_LEN,
11730×
                });
1174202×
            }
1175
        }
11761×
        let refs: Vec<ObjectRef> = objects
11771×
            .par_iter()
1178202×
            .map(|(ty, b)| hash_object(*ty, b))
11791×
            .collect();
1180
        // What is new: not stored already, not earlier in this call.
11811×
        let mut seen: std::collections::HashSet<ObjectRef> = std::collections::HashSet::new();
11821×
        let mut todo: Vec<usize> = Vec::new();
1183202×
        for (i, r) in refs.iter().enumerate() {
1184202×
            let known = self
1185202×
                .pending
1186202×
                .borrow()
1187202×
                .as_ref()
1188202×
                .is_some_and(|p| p.lookup.contains_key(r));
1189202×
            if seen.insert(*r)
1190201×
                && !known
1191201×
                && self.find_packed(r).is_none()
1192201×
                && !self.backend.has(&loose_key(r)).unwrap_or(false)
1193200×
            {
1194200×
                todo.push(i);
1195200×
            }
1196
        }
11971×
        let raw = self.nocompress_set()?;
11981×
        let packed: Vec<(u8, Vec<u8>)> = todo
11991×
            .par_iter()
1200200×
            .map(|i| {
1201200×
                let body = objects[*i].1;
1202200×
                if raw.contains(&refs[*i]) {
12030×
                    return (0, body.to_vec());
1204200×
                }
1205200×
                match zstd::bulk::compress(body, ZSTD_LEVEL) {
1206200×
                    Ok(c) if c.len() < body.len() => (FLAG_ZSTD, c),
12070×
                    _ => (0, body.to_vec()),
1208
                }
1209200×
            })
12101×
            .collect();
12111×
        let mut guard = self.pending.borrow_mut();
12121×
        let pending = guard.as_mut().expect("batch open");
12131×
        self.ensure_pack(pending)?;
12141×
        let mut report = std::mem::take(&mut pending.report);
12151×
        let pack = pending.pack.as_mut().unwrap();
1216200×
        for (i, (flags, stored)) in todo.iter().zip(packed) {
1217200×
            let (ty, body) = objects[*i];
1218200×
            let e = write_pack_entry(pack, &refs[*i], ty, body.len(), flags, &stored, &mut report)?;
1219200×
            pending.lookup.insert(refs[*i], PendingEntry::Packed(e));
1220
        }
12211×
        pending.report = report;
12221×
        Ok(refs)
1223761×
    }
1224
1225
    /// Store `body` as an object of type `ty`; idempotent.
122615215×
    pub fn put(&self, ty: ObjectType, body: &[u8]) -> Result<ObjectRef> {
1227
        // Refuse what the store could not read back (spec §13.2), before
1228
        // anything is written: a pack must never hold an entry its index
1229
        // would reject.
123015215×
        if body.len() > MAX_OBJECT_LEN as usize {
12311×
            return Err(StoreError::TooLarge {
12321×
                kind: ty.name(),
12331×
                size: body.len(),
12341×
                limit: MAX_OBJECT_LEN,
12351×
            });
123615214×
        }
123715214×
        let r = hash_object(ty, body);
123815214×
        if self.find_packed(&r).is_some() || self.backend.has(&loose_key(&r)).unwrap_or(false) {
12391662×
            return Ok(r);
124013552×
        }
124113552×
        if self.pending.borrow().is_some() {
12426925×
            self.put_pending(r, ty, body)?;
12436925×
            return Ok(r);
12446627×
        }
12456627×
        self.put_loose(ty, body)?;
12466622×
        Ok(r)
124715215×
    }
1248
1249
    /// Write one loose object, durable when this returns.
12506828×
    fn put_loose(&self, ty: ObjectType, body: &[u8]) -> Result<ObjectRef> {
12516828×
        let r = hash_object(ty, body);
12526828×
        let mut bytes = header(ty, body.len());
12536828×
        bytes.extend_from_slice(body);
12546828×
        crate::durable::step("write loose object")?;
12556823×
        put_new_or_existing(self.backend.as_ref(), &loose_key(&r), &bytes)?;
12566823×
        Ok(r)
12576828×
    }
1258
1259
    /// Write several loose objects with as few waits on the disk as the
1260
    /// guarantees allow (a directory store writes them all, then syncs
1261
    /// each directory once). Durable when this returns, as `put_loose`
1262
    /// one at a time would be (spec §13.6).
12633143×
    fn put_loose_many(&self, objects: &[(ObjectType, &[u8])]) -> Result<()> {
12643143×
        if objects.len() <= 1 {
12651796×
            for (ty, body) in objects {
1266201×
                self.put_loose(*ty, body)?;
1267
            }
12681796×
            return Ok(());
12691347×
        }
12701347×
        let mut seen = std::collections::HashSet::new();
12711347×
        let items: Vec<(String, Vec<u8>)> = objects
12721347×
            .iter()
12734723×
            .filter_map(|(ty, body)| {
12744723×
                let r = hash_object(*ty, body);
12754723×
                seen.insert(r).then(|| {
12764723×
                    let mut bytes = header(*ty, body.len());
12774723×
                    bytes.extend_from_slice(body);
12784723×
                    (loose_key(&r), bytes)
12794723×
                })
12804723×
            })
12811347×
            .collect();
12821347×
        self.backend.put_many_new(&items).map_err(backend_err)
12833143×
    }
1284
1285
    /// Read and verify an object, loose, packed, or pending in a batch.
128660971×
    pub fn get(&self, r: &ObjectRef) -> Result<Object> {
128760971×
        match get_optional(self.backend.as_ref(), &loose_key(r))? {
128844964×
            Some(bytes) => parse_loose(&bytes, r),
128916007×
            None => match self.find_packed(r) {
129015082×
                Some((i, e)) => self.packs.borrow()[i].fetch(self.backend.as_ref(), r, e),
1291925×
                None => self.pending_get(r).unwrap_or(Err(StoreError::NotFound(*r))),
1292
            },
1293
        }
129460971×
    }
1295
1296
    /// Many objects at once: loose ones are read and verified in parallel,
1297
    /// then packed ones in parallel, then what is pending in a batch.
1298
    /// Results are in the order of `refs`.
1299943×
    pub fn get_many(&self, refs: &[ObjectRef]) -> Vec<Result<Object>> {
1300
        use rayon::prelude::*;
1301943×
        let backend = self.backend.as_ref();
1302943×
        let mut found: Vec<Option<Result<Object>>> = refs
1303943×
            .par_iter()
13041951×
            .map(|r| match get_optional(backend, &loose_key(r)) {
13051835×
                Ok(Some(bytes)) => Some(parse_loose(&bytes, r)),
1306116×
                Ok(None) => None,
13070×
                Err(e) => Some(Err(e)),
13081951×
            })
1309943×
            .collect();
1310
        // Packed ones: look them up in order, then read them in parallel.
1311943×
        let packs = self.packs.borrow();
1312943×
        let packed: Vec<(usize, usize, PackEntry)> = found
1313943×
            .iter()
1314943×
            .enumerate()
13151951×
            .filter(|(_, f)| f.is_none())
1316943×
            .filter_map(|(i, _)| {
1317116×
                packs
1318116×
                    .iter()
1319116×
                    .enumerate()
1320116×
                    .find_map(|(p, pack)| pack.find(&refs[i]).map(|e| (i, p, e)))
1321116×
            })
1322943×
            .collect();
1323943×
        let indexes: &[PackIndex] = &packs;
1324943×
        let read: Vec<(usize, Result<Object>)> = packed
1325943×
            .par_iter()
1326943×
            .map(|(i, p, e)| (*i, indexes[*p].fetch(backend, &refs[*i], *e)))
1327943×
            .collect();
1328943×
        drop(packs);
1329943×
        for (i, r) in read {
1330109×
            found[i] = Some(r);
1331109×
        }
1332943×
        found
1333943×
            .into_iter()
1334943×
            .zip(refs)
13351951×
            .map(|(f, r)| match f {
13361944×
                Some(f) => f,
13377×
                None => self.get(r),
13381951×
            })
1339943×
            .collect()
1340943×
    }
1341
134241726×
    pub fn get_typed(&self, r: &ObjectRef, want: ObjectType) -> Result<Vec<u8>> {
134341726×
        let (ty, body) = self.get(r)?;
134441694×
        if ty != want {
13451×
            return Err(StoreError::WrongType(*r, ty.name(), want.name()));
134641693×
        }
134741693×
        Ok(body)
134841726×
    }
1349
1350
    /// Store a change and the text blobs (and their chunks) its large
1351
    /// inserts are stored as (spec §6.1).
13522855×
    pub fn put_change(&self, c: &Change) -> Result<ObjectRef> {
13532855×
        let encoding = crate::timing::phase("store: encode the change and its texts");
13542855×
        let bytes = c.encode_streaming(|batch| self.put_texts(&batch))?;
13552855×
        drop(encoding);
13562855×
        let _t = crate::timing::phase("store: put the encoding");
13572855×
        self.put(ObjectType::Change, &bytes)
13582855×
    }
1359
1360
    /// Store text blobs and their chunks: every chunk at once (compressed
1361
    /// on every core in a large batch), then the blobs.
136262×
    pub fn put_texts(&self, texts: &[crate::objects::StoredText]) -> Result<()> {
136362×
        let mut chunks: Vec<(ObjectType, &[u8])> = Vec::new();
136463×
        for t in texts {
136563×
            if !self.has(&t.blob.hash()) {
136652×
                chunks.extend(
136752×
                    crate::chunk::chunks(&t.content)
136852×
                        .into_iter()
136993×
                        .map(|c| (ObjectType::Chunk, c)),
1370
                );
137111×
            }
1372
        }
137362×
        self.put_many(&chunks)?;
137463×
        for t in texts {
137563×
            self.put(ObjectType::Blob, &t.blob.encode())?;
1376
        }
137762×
        Ok(())
137862×
    }
1379
13804494×
    pub fn get_change(&self, r: &ObjectRef) -> Result<Change> {
13814494×
        Ok(self.get_change_parts(r)?.0)
13824494×
    }
1383
1384
    /// A change and the objects its stored inserts are made of: each text
1385
    /// blob and its chunks, which travel and are kept with it.
13864607×
    pub fn get_change_parts(&self, r: &ObjectRef) -> Result<(Change, Vec<ObjectRef>)> {
13874607×
        let bytes = self.get_typed(r, ObjectType::Change)?;
13884595×
        let mut parts = Vec::new();
13894595×
        let mut failed = None;
13904595×
        let decoded = Change::decode_with(&bytes, &mut |text, count, form| match self
139159×
            .read_text(text)
1392
        {
139358×
            Ok((blob, content)) => {
139458×
                parts.push(*text);
139558×
                parts.extend(blob.chunks);
139658×
                crate::objects::text_lines(&content, count, form)
1397
            }
13981×
            Err(e) => {
13991×
                let why = e.to_string();
14001×
                failed = Some(e);
14011×
                Err(ObjectError::Schema(format!(
14021×
                    "text blob {}: {why}",
14031×
                    text.short(12)
14041×
                )))
1405
            }
140659×
        });
14074595×
        match (decoded, failed) {
14084594×
            (Ok(c), _) => Ok((c, parts)),
14091×
            (Err(_), Some(StoreError::NotFound(t))) => Err(StoreError::Corrupt(
14101×
                *r,
14111×
                format!("its text blob {} is missing", t.short(12)),
14121×
            )),
14130×
            (Err(e), _) => Err(StoreError::Corrupt(*r, e.to_string())),
1414
        }
14154607×
    }
1416
1417
    /// A change with every insert left without its lines (empty
1418
    /// placeholders), and where each one's lines are, in order: for
1419
    /// history-only states, which read text only for the graphs they build
1420
    /// (see [`Change::decode_skeleton`]).
1421535×
    pub fn get_change_lazy(&self, r: &ObjectRef) -> Result<(Change, Vec<crate::objects::TextRef>)> {
1422535×
        let bytes = self.get_typed(r, ObjectType::Change)?;
1423533×
        Change::decode_skeleton(&bytes, *r).map_err(|e| StoreError::Corrupt(*r, e.to_string()))
1424535×
    }
1425
1426
    /// A change's metadata (id, dependencies, author, clock, message, kind)
1427
    /// without its contents: read from its skeleton, so neither its text
1428
    /// blobs nor its inline lines are read (spec §11).
1429
    ///
1430
    /// Served from the `metas` cache when this store read it before (a
1431
    /// change object can be as large as the tree it adds), as long as the
1432
    /// store still has the change.
14334350×
    pub fn get_change_meta(&self, r: &ObjectRef) -> Result<crate::state::ChangeMeta> {
14344350×
        if self.metas.borrow().is_none() {
1435900×
            *self.metas.borrow_mut() = Some(self.read_metas_cache());
14363450×
        }
14374350×
        let cached = self.metas.borrow().as_ref().and_then(|m| m.get(r).cloned());
14384350×
        if let Some(meta) = cached {
14393129×
            if self.has(r) {
1440
                #[cfg(test)]
14411703×
                assert_eq!(
1442
                    meta,
14431703×
                    Change::decode_meta(&self.get_typed(r, ObjectType::Change)?).unwrap(),
1444
                    "the metadata cache holds a change's metadata"
1445
                );
14463129×
                return Ok(meta);
14470×
            }
14481221×
        }
14491221×
        let bytes = self.get_typed(r, ObjectType::Change)?;
14501221×
        let meta =
14511221×
            Change::decode_meta(&bytes).map_err(|e| StoreError::Corrupt(*r, e.to_string()))?;
14521221×
        self.remember_meta(r, &meta);
14531221×
        Ok(meta)
14544350×
    }
1455
1456
    /// The metadata cache: records of a change hash, its metadata in the
1457
    /// flat layout, and the first 8 bytes of BLAKE3 over both, each
1458
    /// appended in one write. Derived only: a record that does not check
1459
    /// ends the reading (a torn write), and the cache can be deleted. It
1460
    /// lives in the scratch directory, on this disk.
1461900×
    fn read_metas_cache(&self) -> crate::fasthash::FastMap<ObjectRef, crate::state::ChangeMeta> {
1462900×
        let mut out = crate::fasthash::FastMap::default();
1463900×
        let Ok(bytes) = fs::read(self.scratch.join("metas")) else {
1464347×
            return out;
1465
        };
1466553×
        let mut r = crate::flat::Reader::new(&bytes);
1467553×
        let mut good = 0;
14682017×
        while !r.at_end() {
14691465×
            let mut record = || -> std::result::Result<_, ObjectError> {
14701465×
                let h = r.object()?;
14711464×
                let body = r.bytes()?;
14721464×
                let check = r.fixed::<8>()?;
14731464×
                Ok((h, body, check))
14741465×
            };
14751465×
            let Ok((h, body, check)) = record() else {
14761×
                break;
1477
            };
14781464×
            let mut sum = blake3::Hasher::new();
14791464×
            sum.update(&h.0).update(body);
14801464×
            if sum.finalize().as_bytes()[..8] != check {
14810×
                break;
14821464×
            }
14831464×
            match crate::state::ChangeMeta::read_flat(&mut crate::flat::Reader::new(body)) {
14841464×
                Ok(m) => out.insert(h, m),
14850×
                Err(_) => break,
1486
            };
14871464×
            good += 32 + 4 + body.len() + 8;
1488
        }
1489
        // Cut a bad tail, so records appended later are read.
1490553×
        if good < bytes.len() {
14911×
            let _ = fs::OpenOptions::new()
14921×
                .write(true)
14931×
                .open(self.scratch.join("metas"))
14941×
                .and_then(|f| f.set_len(good as u64));
1495552×
        }
1496553×
        out
1497900×
    }
1498
1499
    /// Add a change's metadata to the cache; quietly nothing when it
1500
    /// cannot be written (it is only a cache).
15011221×
    fn remember_meta(&self, r: &ObjectRef, meta: &crate::state::ChangeMeta) {
15021221×
        let mut body = crate::flat::Writer::default();
15031221×
        meta.write_flat(&mut body);
15041221×
        let mut w = crate::flat::Writer::default();
15051221×
        w.object(r);
15061221×
        w.bytes(&body.0);
15071221×
        let mut sum = blake3::Hasher::new();
15081221×
        sum.update(&r.0).update(&body.0);
15091221×
        w.fixed(&sum.finalize().as_bytes()[..8]);
15101221×
        let _ = fs::OpenOptions::new()
15111221×
            .create(true)
15121221×
            .append(true)
15131221×
            .open(self.scratch.join("metas"))
15141221×
            .and_then(|mut f| f.write_all(&w.0));
15151221×
        if let Some(m) = self.metas.borrow_mut().as_mut() {
15161221×
            m.insert(*r, meta.clone());
15171221×
        }
15181221×
    }
1519
152059×
    fn read_text(&self, r: &ObjectRef) -> Result<(Blob, Vec<u8>)> {
152159×
        let blob = Blob::decode(&self.get_typed(r, ObjectType::Blob)?)?;
152258×
        let mut content = Vec::with_capacity(blob.length as usize);
152398×
        for c in &blob.chunks {
152498×
            content.extend(self.get_typed(c, ObjectType::Chunk)?);
1525
        }
152658×
        Ok((blob, content))
152759×
    }
1528
1529193×
    pub fn put_chunk(&self, bytes: &[u8]) -> Result<ObjectRef> {
1530193×
        self.put(ObjectType::Chunk, bytes)
1531193×
    }
1532
1533
    /// Store a chunk that packs will keep uncompressed (`nocompress`, spec §13.3).
1534123×
    pub fn put_chunk_nocompress(&self, bytes: &[u8]) -> Result<ObjectRef> {
1535123×
        let r = hash_object(ObjectType::Chunk, bytes);
1536123×
        put_new_or_existing(
1537123×
            self.backend.as_ref(),
1538123×
            &format!("nocompress/{}", r.to_hex()),
1539123×
            b"",
15400×
        )?;
1541123×
        self.put(ObjectType::Chunk, bytes)
1542123×
    }
1543
15441900×
    fn is_nocompress(&self, r: &ObjectRef) -> bool {
15451900×
        self.backend
15461900×
            .has(&format!("nocompress/{}", r.to_hex()))
15471900×
            .unwrap_or(false)
15481900×
    }
1549
1550
    /// Every chunk marked to be kept raw.
155171×
    fn nocompress_set(&self) -> Result<std::collections::HashSet<ObjectRef>> {
155271×
        Ok(self
155371×
            .backend
155471×
            .list("nocompress/")
155571×
            .map_err(backend_err)?
155671×
            .into_iter()
155771×
            .filter_map(|e| ObjectRef::from_hex(e.key.trim_start_matches("nocompress/")))
155871×
            .collect())
155971×
    }
1560
15612838×
    pub fn put_state(&self, st: &StateObject) -> Result<ObjectRef> {
15622838×
        self.put(ObjectType::State, &st.encode())
15632838×
    }
1564
15655092×
    pub fn get_state(&self, r: &ObjectRef) -> Result<StateObject> {
15665092×
        Ok(StateObject::decode(&self.get_typed(r, ObjectType::State)?)?)
15675092×
    }
1568
1569312×
    pub fn put_attest(&self, a: &Attest) -> Result<ObjectRef> {
1570312×
        self.put(ObjectType::Attest, &a.encode())
1571312×
    }
1572
1573498×
    pub fn get_attest(&self, r: &ObjectRef) -> Result<Attest> {
1574498×
        Ok(Attest::decode(&self.get_typed(r, ObjectType::Attest)?)?)
1575498×
    }
1576
15772×
    pub fn put_receipt(&self, r: &Receipt) -> Result<ObjectRef> {
15782×
        self.put(ObjectType::Receipt, &r.encode())
15792×
    }
1580
15816×
    pub fn get_receipt(&self, r: &ObjectRef) -> Result<Receipt> {
15826×
        Ok(Receipt::decode(&self.get_typed(r, ObjectType::Receipt)?)?)
15836×
    }
1584
1585
    /// Record `value` under `key` in `index`: one write-once entry, so two
1586
    /// writers of a shared store never lose each other's.
1587121×
    fn index_add(&self, index: &str, key: &ObjectRef, value: &ObjectRef) -> Result<()> {
1588121×
        let entry = format!("{}{}", fanout_prefix(index, key), value.to_hex());
1589121×
        put_new_or_existing(self.backend.as_ref(), &entry, b"")
1590121×
    }
1591
1592
    /// The values recorded under `key` in `index`, with those an older
1593
    /// store kept as one list in `legacy`, sorted.
15941343×
    fn index_get(&self, index: &str, legacy: &str, key: &ObjectRef) -> Result<Vec<ObjectRef>> {
15951343×
        let mut values: Vec<ObjectRef> = self
15961343×
            .backend
15971343×
            .list(&fanout_prefix(index, key))
15981343×
            .map_err(backend_err)?
15991343×
            .into_iter()
16001343×
            .filter_map(|e| e.key.rsplit('/').next().and_then(ObjectRef::from_hex))
16011343×
            .collect();
16021343×
        if let Some(bytes) = get_optional(self.backend.as_ref(), &legacy_key(legacy, key))? {
16033×
            values.extend(
16043×
                String::from_utf8_lossy(&bytes)
16053×
                    .lines()
16063×
                    .filter_map(ObjectRef::from_hex),
16073×
            );
16081340×
        }
16091343×
        values.sort();
16101343×
        values.dedup();
16111343×
        Ok(values)
16121343×
    }
1613
1614
    /// Record that seal attestation `attest` covers `change`.
1615117×
    pub fn index_seal(&self, change: &ObjectRef, attest: &ObjectRef) -> Result<()> {
1616117×
        self.index_add("seal", change, attest)
1617117×
    }
1618
1619
    /// Seal attestations known to cover `change`.
16201332×
    pub fn seals_for(&self, change: &ObjectRef) -> Result<Vec<ObjectRef>> {
16211332×
        self.index_get("seal", "seals", change)
16221332×
    }
1623
1624
    /// Record receipt attestation `attest` for `state` (spec §14.6).
16254×
    pub fn index_receipt(&self, state: &ObjectRef, attest: &ObjectRef) -> Result<()> {
16264×
        self.index_add("receipt", state, attest)
16274×
    }
1628
1629
    /// Receipt attestations recorded for `state`.
163011×
    pub fn receipts_for(&self, state: &ObjectRef) -> Result<Vec<ObjectRef>> {
163111×
        self.index_get("receipt", "receipts", state)
163211×
    }
1633
1634
    /// Every state with a receipt, for garbage collection.
163522×
    pub fn receipt_states(&self) -> Result<Vec<ObjectRef>> {
163622×
        let mut out: Vec<ObjectRef> = Vec::new();
163722×
        for e in self.backend.list("receipt/").map_err(backend_err)? {
1638
            // receipt/<hh>/<rest>/<attest>
16393×
            let mut parts = e.key.splitn(4, '/');
16403×
            let (Some(_), Some(hh), Some(rest), Some(_)) =
16413×
                (parts.next(), parts.next(), parts.next(), parts.next())
1642
            else {
16430×
                continue;
1644
            };
16453×
            out.extend(ObjectRef::from_hex(&format!("{hh}{rest}")));
1646
        }
164722×
        for e in self.backend.list("receipts/").map_err(backend_err)? {
16481×
            let mut parts = e.key.splitn(3, '/');
16491×
            let (Some(_), Some(hh), Some(rest)) = (parts.next(), parts.next(), parts.next()) else {
16500×
                continue;
1651
            };
16521×
            out.extend(ObjectRef::from_hex(&format!("{hh}{rest}")));
1653
        }
165422×
        out.sort();
165522×
        out.dedup();
165622×
        Ok(out)
165722×
    }
1658
1659207×
    pub fn put_identity(&self, id: &Identity) -> Result<ObjectRef> {
1660207×
        self.put(ObjectType::Identity, &id.encode())
1661207×
    }
1662
1663498×
    pub fn get_identity(&self, r: &ObjectRef) -> Result<Identity> {
1664498×
        Ok(Identity::decode(&self.get_typed(r, ObjectType::Identity)?)?)
1665498×
    }
1666
1667
    /// Signatures stored alongside object `r` (spec §5.4), one per signing
1668
    /// key, sorted by key. Empty if none.
16692318×
    pub fn signatures(&self, r: &ObjectRef) -> Result<Vec<Signature>> {
16702318×
        let mut sigs: Vec<Signature> = Vec::new();
16712318×
        for e in self
16722318×
            .backend
16732318×
            .list(&fanout_prefix("sig", r))
16742318×
            .map_err(backend_err)?
1675
        {
16761150×
            let bytes = self.backend.get(&e.key).map_err(backend_err)?;
16771150×
            sigs.extend(Signature::decode_list(&bytes)?);
1678
        }
1679
        // An older store's one list per object; a signer kept there and
1680
        // here counts once, as written here.
16812318×
        if let Some(bytes) = get_optional(self.backend.as_ref(), &legacy_key("sigs", r))? {
16822×
            for sig in Signature::decode_list(&bytes)? {
16832×
                if !sigs.iter().any(|s| s.key == sig.key) {
16841×
                    sigs.push(sig);
16851×
                }
1686
            }
16872316×
        }
16882318×
        sigs.sort_by_key(|s| s.key);
16892318×
        sigs.dedup_by_key(|s| s.key);
16902318×
        Ok(sigs)
16912318×
    }
1692
1693
    /// Attach a signature to object `r`, replacing any earlier one by the
1694
    /// same key: one entry per signer, so the latest by a key is the one
1695
    /// kept, and two signers never touch each other's.
1696461×
    pub fn put_signature(&self, r: &ObjectRef, sig: &Signature) -> Result<()> {
1697461×
        let key = format!("{}{}", fanout_prefix("sig", r), sig.key.to_hex());
1698461×
        let bytes = Signature::encode_list(std::slice::from_ref(sig));
1699461×
        if get_optional(self.backend.as_ref(), &key)?.as_deref() == Some(bytes.as_slice()) {
170021×
            return Ok(());
1701440×
        }
1702440×
        delete(self.backend.as_ref(), &key)?;
1703440×
        put_new_or_existing(self.backend.as_ref(), &key, &bytes)
1704461×
    }
1705
1706
    /// Finish packs a writer left unfinished: a batch writes its objects to
1707
    /// `.tmp-ID.pack` and only indexes it at the end, so a process that
1708
    /// stopped part way (an import killed after hours) leaves every object
1709
    /// in a pack nothing can read. Each such pack untouched for `min_age`
1710
    /// is read through: every whole entry checked against its reference,
1711
    /// a torn last one cut off, then indexed as a pack of the store.
1712
    /// Returns the packs and objects adopted.
17132×
    pub fn adopt_unfinished_packs(
17142×
        &self,
17152×
        min_age: std::time::Duration,
17162×
        progress: &dyn Fn(&str),
17172×
    ) -> Result<(usize, usize)> {
1718
        use std::io::{BufReader, Read};
17192×
        let mut packs = 0;
17202×
        let mut objects = 0;
17212×
        let Ok(dir) = fs::read_dir(&self.scratch) else {
17220×
            return Ok((0, 0));
1723
        };
17244×
        for entry in dir.flatten() {
17254×
            let name = entry.file_name().to_string_lossy().to_string();
17264×
            let Some(id) = name
17274×
                .strip_prefix(".tmp-")
17284×
                .and_then(|n| n.strip_suffix(".pack"))
1729
            else {
17302×
                continue;
1731
            };
17322×
            let path = entry.path();
17332×
            let meta = fs::metadata(&path)?;
17342×
            let age = meta
17352×
                .modified()
17362×
                .ok()
17372×
                .and_then(|m| m.elapsed().ok())
17382×
                .unwrap_or_default();
17392×
            if age < min_age {
17401×
                progress(&format!(
17411×
                    "{name}: written to {}s ago, left alone",
17421×
                    age.as_secs()
17431×
                ));
17441×
                continue;
17451×
            }
17461×
            let mut f = BufReader::with_capacity(1 << 20, fs::File::open(&path)?);
17471×
            let mut magic = [0u8; 8];
17481×
            if f.read_exact(&mut magic).is_err() || &magic != PACK_MAGIC {
17490×
                progress(&format!("{name}: not a pack, left alone"));
17500×
                continue;
17511×
            }
17521×
            let mut offset = PACK_MAGIC.len() as u64;
17531×
            let mut index: Vec<(ObjectRef, PackEntry)> = Vec::new();
1754
            loop {
1755301×
                let mut head = [0u8; 42];
1756301×
                if f.read_exact(&mut head).is_err() {
17570×
                    break;
1758301×
                }
1759301×
                let Some(ty) = ObjectType::ALL.get(head[0] as usize).copied() else {
17600×
                    break;
1761
                };
1762301×
                let flags = head[1];
1763301×
                let stored_len = u32::from_le_bytes(head[2..6].try_into().unwrap());
1764301×
                let raw_len = u32::from_le_bytes(head[6..10].try_into().unwrap());
1765301×
                let r = ObjectRef(head[10..42].try_into().unwrap());
1766301×
                let mut stored = vec![0u8; stored_len as usize];
1767301×
                if flags & FLAG_DICT != 0 || f.read_exact(&mut stored).is_err() {
17681×
                    break;
1769300×
                }
1770300×
                let e = PackEntry {
1771300×
                    offset: offset + 42,
1772300×
                    stored_len,
1773300×
                    raw_len,
1774300×
                    ty,
1775300×
                    flags,
1776300×
                };
1777300×
                if decode_entry(&r, e, stored, None).is_err() {
17780×
                    break;
1779300×
                }
1780300×
                index.push((r, e));
1781300×
                offset += 42 + stored_len as u64;
1782300×
                if index.len().is_multiple_of(200_000) {
17830×
                    progress(&format!(
17840×
                        "{name}: {} objects checked, {} MiB",
17850×
                        index.len(),
17860×
                        offset >> 20
17870×
                    ));
1788300×
                }
1789
            }
17901×
            if index.is_empty() {
17910×
                progress(&format!("{name}: no whole object, left alone"));
17920×
                continue;
17931×
            }
17941×
            if offset < meta.len() {
17951×
                progress(&format!(
17961×
                    "{name}: {} torn bytes at the end cut off",
17971×
                    meta.len() - offset
17981×
                ));
17991×
                fs::OpenOptions::new()
18001×
                    .write(true)
18011×
                    .open(&path)?
18021×
                    .set_len(offset)?;
18030×
            }
18041×
            index.sort_by_key(|(r, _)| *r);
18051×
            index.dedup_by_key(|(r, _)| *r);
18061×
            objects += index.len();
18071×
            packs += 1;
18081×
            progress(&format!("{name}: {} objects indexed", index.len()));
18091×
            self.finish_pack_files(id, &path, &index)?;
1810
        }
18112×
        Ok((packs, objects))
18122×
    }
1813
1814
    /// Every object reference in the store, loose and packed (slow; for gc and tests).
181585×
    pub fn list(&self) -> io::Result<Vec<ObjectRef>> {
181685×
        let mut out: Vec<ObjectRef> = self
181785×
            .loose_objects()
181885×
            .map_err(|e| io::Error::other(e.to_string()))?
181985×
            .into_iter()
182085×
            .map(|(r, _)| r)
182185×
            .collect();
182285×
        for p in self.packs.borrow().iter() {
18239×
            out.extend(p.refs.iter().copied());
18249×
        }
182585×
        out.sort();
182685×
        out.dedup();
182785×
        Ok(out)
182885×
    }
1829
}
1830
1831
/// A loose object's bytes, verified against `r`.
183246799×
fn parse_loose(data: &[u8], r: &ObjectRef) -> Result<Object> {
183346799×
    let nul = data
183446799×
        .iter()
1835664453×
        .position(|&b| b == 0)
183646799×
        .ok_or_else(|| StoreError::Corrupt(*r, "no header".into()))?;
183746799×
    let head = std::str::from_utf8(&data[..nul])
183846799×
        .map_err(|_| StoreError::Corrupt(*r, "header not UTF-8".into()))?;
183946799×
    let mut parts = head.split(' ');
184046799×
    let (Some("oxy1"), Some(ty), Some(len), None) =
184146799×
        (parts.next(), parts.next(), parts.next(), parts.next())
1842
    else {
18430×
        return Err(StoreError::Corrupt(*r, format!("bad header {head:?}")));
1844
    };
184546799×
    let ty = ObjectType::from_name(ty)
184646799×
        .ok_or_else(|| StoreError::Corrupt(*r, format!("unknown type {ty}")))?;
184746799×
    let len: usize = len
184846799×
        .parse()
184946799×
        .map_err(|_| StoreError::Corrupt(*r, "bad length".into()))?;
185046799×
    let body = &data[nul + 1..];
185146799×
    if body.len() != len {
18520×
        return Err(StoreError::Corrupt(
18530×
            *r,
18540×
            format!("length {} != header {len}", body.len()),
18550×
        ));
185646799×
    }
185746799×
    if hash_object(ty, body) != *r {
18584×
        return Err(StoreError::Corrupt(*r, "hash mismatch".into()));
185946795×
    }
186046795×
    Ok((ty, body.to_vec()))
186146799×
}
1862
1863
/// Whether the objects are files that a test may tamper with: not under
1864
/// `OXY_STORE_BACKEND=memory`.
1865
#[cfg(test)]
18666×
fn files_on_disk() -> bool {
18676×
    std::env::var_os("OXY_STORE_BACKEND").is_none()
18686×
}
1869
1870
#[cfg(test)]
1871
mod tests {
1872
    use super::*;
1873
1874
    /// The store under test twice: in a directory, and on a store in
1875
    /// memory with a scratch directory, as over a bucket.
18766×
    fn each_store(dir: &Path, f: impl Fn(&str, Store)) {
18776×
        f("directory", Store::open(dir.join("objects")).unwrap());
18786×
        f(
18796×
            "memory",
18806×
            Store::open_on(Arc::new(MemoryStore::new()), dir.join("scratch")).unwrap(),
18816×
        );
18826×
    }
1883
1884
    #[test]
18851×
    fn put_get_verify() {
18861×
        if !super::files_on_disk() {
18870×
            return;
18881×
        }
18891×
        let dir = tempfile::tempdir().unwrap();
18901×
        let s = Store::open(dir.path().join("objects")).unwrap();
18911×
        let r = s.put(ObjectType::Chunk, b"hello").unwrap();
18921×
        assert!(s.has(&r));
18931×
        assert_eq!(s.get(&r).unwrap(), (ObjectType::Chunk, b"hello".to_vec()));
18941×
        assert_eq!(s.put(ObjectType::Chunk, b"hello").unwrap(), r);
18951×
        assert_eq!(s.list().unwrap(), vec![r]);
18961×
        assert!(matches!(
18971×
            s.get_typed(&r, ObjectType::Blob),
1898
            Err(StoreError::WrongType(..))
1899
        ));
19001×
        assert!(matches!(
19011×
            s.get(&ObjectRef([9; 32])),
1902
            Err(StoreError::NotFound(_))
1903
        ));
1904
1905
        // Tamper: flip a byte, read must fail.
19061×
        let path = s.path_for(&r);
19071×
        let mut data = fs::read(&path).unwrap();
19081×
        let last = data.len() - 1;
19091×
        data[last] ^= 1;
19101×
        fs::write(&path, data).unwrap();
19111×
        assert!(matches!(s.get(&r), Err(StoreError::Corrupt(..))));
19121×
    }
1913
1914
    #[test]
19151×
    fn packing_keeps_every_object_readable() {
19161×
        if !super::files_on_disk() {
19170×
            return;
19181×
        }
19191×
        let dir = tempfile::tempdir().unwrap();
19201×
        let s = Store::open(dir.path()).unwrap();
19211×
        let mut refs = Vec::new();
1922300×
        for i in 0..300u32 {
1923300×
            let body = format!("object {i} ").repeat(1 + (i % 7) as usize);
1924300×
            refs.push((s.put(ObjectType::Chunk, body.as_bytes()).unwrap(), body));
1925300×
        }
19261×
        let c = crate::objects::tests::sample_change();
19271×
        let cr = s.put_change(&c).unwrap();
19281×
        assert_eq!(s.loose_count().unwrap(), 301);
19291×
        let report = s.pack_loose().unwrap();
19301×
        assert_eq!(report.objects, 301);
19311×
        assert!(report.packed_bytes < report.raw_bytes, "{report:?}");
19321×
        assert_eq!(s.loose_count().unwrap(), 0);
19331×
        assert_eq!(s.pack_count(), 1);
1934300×
        for (r, body) in &refs {
1935300×
            assert!(s.has(r));
1936300×
            assert_eq!(
1937300×
                s.get(r).unwrap(),
1938300×
                (ObjectType::Chunk, body.as_bytes().to_vec())
1939
            );
1940
        }
19411×
        assert_eq!(s.get_change(&cr).unwrap(), c);
19421×
        assert_eq!(s.list().unwrap().len(), 301);
1943
        // Re-putting a packed object is a no-op; new objects go loose and a
1944
        // second pack coexists with the first.
19451×
        assert_eq!(
19461×
            s.put(ObjectType::Chunk, refs[0].1.as_bytes()).unwrap(),
19471×
            refs[0].0
1948
        );
19491×
        assert_eq!(s.loose_count().unwrap(), 0);
19501×
        let extra = s.put(ObjectType::Chunk, b"after packing").unwrap();
19511×
        s.pack_loose().unwrap();
19521×
        assert_eq!(s.pack_count(), 2);
19531×
        assert_eq!(s.get(&extra).unwrap().1, b"after packing");
1954
        // A reopened store sees the packs.
19551×
        let s2 = Store::open(dir.path()).unwrap();
19561×
        assert_eq!(s2.pack_count(), 2);
19571×
        assert_eq!(s2.get(&refs[5].0).unwrap().1, refs[5].1.as_bytes());
19581×
        assert!(matches!(
19591×
            s2.get(&ObjectRef([9; 32])),
1960
            Err(StoreError::NotFound(_))
1961
        ));
1962
        // Corrupting an object's body inside the pack is detected on read.
19631×
        let target = refs[5].0;
19641×
        let (pack_path, offset) = {
19651×
            let packs = s2.packs.borrow();
19661×
            let (i, e) = s2.find_packed(&target).unwrap();
19671×
            (dir.path().join(&packs[i].key), e.offset as usize)
19681×
        };
19691×
        let mut data = fs::read(&pack_path).unwrap();
19701×
        data[offset] ^= 0xff;
19711×
        fs::write(&pack_path, data).unwrap();
19721×
        let s3 = Store::open(dir.path()).unwrap();
19731×
        assert!(matches!(s3.get(&target), Err(StoreError::Corrupt(..))));
19741×
        assert_eq!(
19751×
            s3.get(&refs[6].0).unwrap().1,
19761×
            refs[6].1.as_bytes(),
1977
            "other objects are unaffected"
1978
        );
19791×
    }
1980
1981
    #[test]
19821×
    fn a_full_repack_trains_a_dictionary_and_reads_back() {
19831×
        if !super::files_on_disk() {
19840×
            return;
19851×
        }
19861×
        let dir = tempfile::tempdir().unwrap();
19871×
        let s = Store::open(dir.path()).unwrap();
1988
        // Many small, alike files: what a dictionary is for.
19891×
        let bodies: Vec<Vec<u8>> = (0..1500)
19901500×
            .map(|i| {
19911500×
                format!(
1992
                    "// SPDX-License-Identifier: GPL-2.0\n#include <linux/module.h>\n\
1993
                     static int probe_{i}(struct device *dev)\n{{\n\treturn {i};\n}}\n"
1994
                )
19951500×
                .into_bytes()
19961500×
            })
19971×
            .collect();
19981×
        let refs: Vec<ObjectRef> = bodies
19991×
            .iter()
20001500×
            .map(|b| s.put(ObjectType::Chunk, b).unwrap())
20011×
            .collect();
20021×
        s.repack_all(REPACK_ZSTD_LEVEL).unwrap();
20031×
        let dicts = fs::read_dir(dir.path())
20041×
            .unwrap()
20051×
            .flatten()
20063×
            .filter(|e| e.path().extension().is_some_and(|x| x == "dict"))
20071×
            .count();
20081×
        assert_eq!(dicts, 1, "the pack has a dictionary");
20091×
        let with_dict = refs
20101×
            .iter()
20111500×
            .filter(|r| s.find_packed(r).unwrap().1.flags & FLAG_DICT != 0)
20121×
            .count();
20131×
        assert!(with_dict > 1000, "most use it: {with_dict}");
20141×
        let again = Store::open(dir.path()).unwrap();
20151500×
        for (r, b) in refs.iter().zip(&bodies) {
20161500×
            assert_eq!(&again.get(r).unwrap().1, b);
2017
        }
2018
        // A repack after that replaces the pack and its dictionary.
20191×
        again.repack_all(REPACK_ZSTD_LEVEL).unwrap();
20201×
        let files: Vec<String> = fs::read_dir(dir.path())
20211×
            .unwrap()
20221×
            .flatten()
20234×
            .map(|e| e.file_name().to_string_lossy().into_owned())
20244×
            .filter(|n| n.starts_with("pack-"))
20251×
            .collect();
20261×
        assert_eq!(files.len(), 3, "one pack, index and dictionary: {files:?}");
20271×
        assert_eq!(&again.get(&refs[7]).unwrap().1, &bodies[7]);
20281×
    }
2029
2030
    #[test]
20311×
    fn nocompress_chunks_pack_raw() {
20321×
        let dir = tempfile::tempdir().unwrap();
20331×
        let s = Store::open(dir.path()).unwrap();
20341×
        let body = vec![b'a'; 10_000];
20351×
        let raw = s.put_chunk_nocompress(&body).unwrap();
20361×
        let compressible = s.put(ObjectType::Chunk, &vec![b'b'; 10_000]).unwrap();
20371×
        s.pack_loose().unwrap();
20381×
        let packs = s.packs.borrow();
20391×
        let (i, e) = s.find_packed(&raw).unwrap();
20401×
        assert_eq!((e.flags, e.stored_len as usize), (0, 10_000));
20411×
        let (_, c) = s.find_packed(&compressible).unwrap();
20421×
        assert_eq!(c.flags, FLAG_ZSTD);
20431×
        assert!(c.stored_len < 10_000);
20441×
        assert_eq!(packs[i].fetch(s.backend.as_ref(), &raw, e).unwrap().1, body);
20451×
    }
2046
2047
    #[test]
20481×
    fn many_packs_merge_into_one() {
20491×
        let dir = tempfile::tempdir().unwrap();
20502×
        each_store(dir.path(), |which, s| {
20512×
            let mut refs = Vec::new();
205236×
            for i in 0..(MAX_PACKS + 2) {
205336×
                refs.push(
205436×
                    s.put(ObjectType::Chunk, format!("pack {i}").as_bytes())
205536×
                        .unwrap(),
205636×
                );
205736×
                s.pack_loose().unwrap();
205836×
            }
20592×
            assert_eq!(s.pack_count(), MAX_PACKS + 2, "{which}");
20602×
            assert_eq!(s.merge_packs().unwrap(), MAX_PACKS + 2);
20612×
            assert_eq!(s.pack_count(), 1);
20622×
            assert_eq!(s.merge_packs().unwrap(), 0);
206336×
            for (i, r) in refs.iter().enumerate() {
206436×
                assert_eq!(s.get(r).unwrap().1, format!("pack {i}").as_bytes());
2065
            }
20662×
            let again = Store::open_on(s.backend().clone(), s.dir()).unwrap();
20672×
            assert_eq!(again.pack_count(), 1, "{which}: reopened");
20682×
        });
20691×
    }
2070
2071
    #[test]
20721×
    fn prune_removes_unreachable_loose_and_packed_objects() {
2073
        use std::collections::HashSet;
20741×
        let dir = tempfile::tempdir().unwrap();
20752×
        each_store(dir.path(), |which, s| {
20762×
            let keep_a = s.put(ObjectType::Chunk, b"keep a").unwrap();
20772×
            let drop_a = s.put(ObjectType::Chunk, b"drop a").unwrap();
20782×
            s.pack_loose().unwrap();
20792×
            let keep_b = s.put(ObjectType::Chunk, b"keep b").unwrap();
20802×
            let drop_b = s.put(ObjectType::Chunk, b"drop b").unwrap();
20812×
            let sk = crate::identity::SecretKey {
20822×
                ed_seed: [1; 32],
20832×
                ml_seed: [2; 32],
20842×
            };
20852×
            let id = sk.identity("a", "b", 0);
20862×
            let key = s.put_identity(&id).unwrap();
20872×
            s.put_signature(
20882×
                &drop_b,
20892×
                &sk.sign(crate::identity::Domain::Change, &key, &drop_b),
2090
            )
20912×
            .unwrap();
20922×
            s.index_seal(&drop_a, &ObjectRef([3; 32])).unwrap();
20932×
            let keep: HashSet<ObjectRef> = [keep_a, keep_b, key].into_iter().collect();
2094
            // Everything is too young under a grace period.
20952×
            let r = s
20962×
                .prune(&keep, std::time::Duration::from_secs(3600))
20972×
                .unwrap();
20982×
            assert_eq!((r.objects, r.deferred), (0, 2), "{which}");
20992×
            let r = s.prune(&keep, std::time::Duration::ZERO).unwrap();
21002×
            assert_eq!(r.objects, 2, "{which}: {r:?}");
21012×
            assert!(s.has(&keep_a) && s.has(&keep_b) && s.has(&key));
21022×
            assert!(!s.has(&drop_a) && !s.has(&drop_b));
21032×
            assert!(s.signatures(&drop_b).unwrap().is_empty());
21042×
            assert!(s.seals_for(&drop_a).unwrap().is_empty());
21052×
            assert_eq!(s.pack_count(), 1);
21062×
            assert_eq!(s.get(&keep_a).unwrap().1, b"keep a");
21072×
            assert_eq!(s.list().unwrap().len(), 3);
21082×
        });
21091×
    }
2110
2111
    #[test]
21121×
    fn signatures_are_stored_beside_objects() {
2113
        use crate::identity::{Domain, SecretKey};
21141×
        let dir = tempfile::tempdir().unwrap();
21152×
        each_store(dir.path(), |which, s| {
21162×
            let r = s.put(ObjectType::Chunk, b"x").unwrap();
21172×
            assert!(s.signatures(&r).unwrap().is_empty());
21182×
            let sk = SecretKey {
21192×
                ed_seed: [1; 32],
21202×
                ml_seed: [2; 32],
21212×
            };
21222×
            let id = sk.identity("a", "b", 0);
21232×
            let key = s.put_identity(&id).unwrap();
21242×
            assert_eq!(s.get_identity(&key).unwrap(), id);
21252×
            let sig = sk.sign(Domain::Change, &key, &r);
21262×
            s.put_signature(&r, &sig).unwrap();
21272×
            s.put_signature(&r, &sig).unwrap();
21282×
            assert_eq!(s.signatures(&r).unwrap(), vec![sig.clone()], "{which}");
2129
            // A second signer is kept beside the first, sorted by key.
21302×
            let sk2 = SecretKey {
21312×
                ed_seed: [3; 32],
21322×
                ml_seed: [4; 32],
21332×
            };
21342×
            let key2 = s.put_identity(&sk2.identity("c", "d", 0)).unwrap();
21352×
            let sig2 = sk2.sign(Domain::Change, &key2, &r);
21362×
            s.put_signature(&r, &sig2).unwrap();
21372×
            let mut both = vec![sig.clone(), sig2.clone()];
21382×
            both.sort_by_key(|s| s.key);
21392×
            assert_eq!(s.signatures(&r).unwrap(), both);
2140
            // The object itself is untouched by its signatures.
21412×
            assert_eq!(s.get(&r).unwrap().1, b"x");
2142
            // Seal and receipt entries, and the states with receipts.
21432×
            s.index_seal(&r, &ObjectRef([5; 32])).unwrap();
21442×
            s.index_seal(&r, &ObjectRef([4; 32])).unwrap();
21452×
            s.index_seal(&r, &ObjectRef([5; 32])).unwrap();
21462×
            assert_eq!(
21472×
                s.seals_for(&r).unwrap(),
21482×
                vec![ObjectRef([4; 32]), ObjectRef([5; 32])]
2149
            );
21502×
            let st = ObjectRef([6; 32]);
21512×
            s.index_receipt(&st, &ObjectRef([7; 32])).unwrap();
21522×
            assert_eq!(s.receipts_for(&st).unwrap(), vec![ObjectRef([7; 32])]);
21532×
            assert_eq!(s.receipt_states().unwrap(), vec![st]);
21542×
        });
21551×
    }
2156
2157
    /// A store written before signatures, seals and receipts were one
2158
    /// entry each (`sigs/`, `seals/`, `receipts/` lists) still reads, and
2159
    /// what is written now sits beside what was there.
2160
    #[test]
21611×
    fn an_older_store_s_sidecar_lists_are_still_read() {
21621×
        if !super::files_on_disk() {
21630×
            return;
21641×
        }
2165
        use crate::identity::{Domain, SecretKey};
21661×
        let dir = tempfile::tempdir().unwrap();
21671×
        let s = Store::open(dir.path()).unwrap();
21681×
        let r = s.put(ObjectType::Chunk, b"old").unwrap();
21691×
        let h = r.to_hex();
21701×
        let sk = SecretKey {
21711×
            ed_seed: [1; 32],
21721×
            ml_seed: [2; 32],
21731×
        };
21741×
        let key = s.put_identity(&sk.identity("a", "b", 0)).unwrap();
21751×
        let sig = sk.sign(Domain::Change, &key, &r);
21761×
        let legacy = dir.path().join("sigs").join(&h[..2]);
21771×
        fs::create_dir_all(&legacy).unwrap();
21781×
        fs::write(
21791×
            legacy.join(&h[2..]),
21801×
            Signature::encode_list(std::slice::from_ref(&sig)),
2181
        )
21821×
        .unwrap();
21831×
        let seals = dir.path().join("seals").join(&h[..2]);
21841×
        fs::create_dir_all(&seals).unwrap();
21851×
        fs::write(
21861×
            seals.join(&h[2..]),
21871×
            format!("{}\n", ObjectRef([9; 32]).to_hex()),
2188
        )
21891×
        .unwrap();
21901×
        let receipts = dir.path().join("receipts").join(&h[..2]);
21911×
        fs::create_dir_all(&receipts).unwrap();
21921×
        fs::write(
21931×
            receipts.join(&h[2..]),
21941×
            format!("{}\n", ObjectRef([8; 32]).to_hex()),
2195
        )
21961×
        .unwrap();
2197
21981×
        assert_eq!(s.signatures(&r).unwrap(), vec![sig.clone()]);
21991×
        assert_eq!(s.seals_for(&r).unwrap(), vec![ObjectRef([9; 32])]);
22001×
        assert_eq!(s.receipts_for(&r).unwrap(), vec![ObjectRef([8; 32])]);
22011×
        assert_eq!(s.receipt_states().unwrap(), vec![r]);
2202
        // New entries join the old ones; the same signer is not doubled.
22031×
        s.put_signature(&r, &sig).unwrap();
22041×
        s.index_seal(&r, &ObjectRef([1; 32])).unwrap();
22051×
        assert_eq!(s.signatures(&r).unwrap().len(), 1);
22061×
        assert_eq!(
22071×
            s.seals_for(&r).unwrap(),
22081×
            vec![ObjectRef([1; 32]), ObjectRef([9; 32])]
2209
        );
2210
        // Pruning the object takes both layouts with it.
22111×
        let r2 = s.put(ObjectType::Chunk, b"kept").unwrap();
22121×
        let keep = [r2, key].into_iter().collect();
22131×
        s.prune(&keep, std::time::Duration::ZERO).unwrap();
22141×
        assert!(s.signatures(&r).unwrap().is_empty());
22151×
        assert!(s.seals_for(&r).unwrap().is_empty());
22161×
        assert!(s.receipt_states().unwrap().is_empty());
22171×
    }
2218
2219
    #[test]
22201×
    fn change_round_trip_through_store() {
22211×
        let dir = tempfile::tempdir().unwrap();
22222×
        each_store(dir.path(), |which, s| {
22232×
            let c = crate::objects::tests::sample_change();
22242×
            let r = s.put_change(&c).unwrap();
22252×
            assert_eq!(r, c.hash(), "{which}");
22262×
            assert_eq!(s.get_change(&r).unwrap(), c);
22272×
            assert_eq!(s.get_change_meta(&r).unwrap().message, c.message);
22282×
        });
22291×
    }
2230
22318057203×
    fn xorshift(state: &mut u64) -> u64 {
22328057203×
        *state ^= *state << 13;
22338057203×
        *state ^= *state >> 7;
22348057203×
        *state ^= *state << 17;
22358057203×
        *state
22368057203×
    }
2237
2238
    /// Random corruption of pack and index files never panics: reads fail
2239
    /// with an error or the store refuses to open, and untouched objects
2240
    /// stay readable when the index survives.
2241
    #[test]
22421×
    fn corrupted_packs_and_indexes_fail_cleanly() {
22431×
        if !super::files_on_disk() {
22440×
            return;
22451×
        }
22461×
        let dir = tempfile::tempdir().unwrap();
22471×
        let objects = dir.path().join("objects");
22481×
        let s = Store::open(&objects).unwrap();
22491×
        let mut refs = Vec::new();
22501×
        let mut seed = 0x9e3779b97f4a7c15u64;
225140×
        for i in 0..40u32 {
225240×
            let len = (xorshift(&mut seed) % 5000) as usize;
225340×
            let mut body = vec![0u8; len];
2254104686×
            for b in body.iter_mut() {
2255104686×
                *b = if i % 2 == 0 {
225656338×
                    (xorshift(&mut seed) & 0xff) as u8
2257
                } else {
225848348×
                    b'a' + (i % 26) as u8
2259
                };
2260
            }
226140×
            refs.push(s.put(ObjectType::Chunk, &body).unwrap());
2262
        }
22631×
        s.pack_loose().unwrap();
22641×
        let pack = fs::read_dir(&objects)
22651×
            .unwrap()
22662×
            .filter_map(|e| e.ok().map(|e| e.path()))
22672×
            .find(|p| p.extension().is_some_and(|x| x == "pack"))
22681×
            .unwrap();
22691×
        let idx = pack.with_extension("idx");
22701×
        let pristine_pack = fs::read(&pack).unwrap();
22711×
        let pristine_idx = fs::read(&idx).unwrap();
2272
2273300×
        for round in 0..300u32 {
2274300×
            let (path, pristine) = if round % 2 == 0 {
2275150×
                (&pack, &pristine_pack)
2276
            } else {
2277150×
                (&idx, &pristine_idx)
2278
            };
2279300×
            let mut data = pristine.clone();
2280300×
            match xorshift(&mut seed) % 4 {
228181×
                0 => {
228281×
                    let at = (xorshift(&mut seed) as usize) % data.len();
228381×
                    data[at] ^= 1 << (xorshift(&mut seed) % 8);
228481×
                }
228573×
                1 => {
228673×
                    let at = (xorshift(&mut seed) as usize) % data.len();
228773×
                    data[at] = (xorshift(&mut seed) & 0xff) as u8;
228873×
                }
228975×
                2 => {
229075×
                    let keep = (xorshift(&mut seed) as usize) % data.len();
229175×
                    data.truncate(keep);
229275×
                }
2293
                _ => {
229471×
                    let at = (xorshift(&mut seed) as usize) % data.len();
229571×
                    let n = ((xorshift(&mut seed) % 8) + 1) as usize;
2296324×
                    for k in 0..n.min(data.len() - at) {
2297324×
                        data[at + k] = 0xff;
2298324×
                    }
2299
                }
2300
            }
2301300×
            fs::write(path, &data).unwrap();
2302
            // Opening may refuse a broken index; a store that opens must
2303
            // either return each object intact or report it corrupt/missing.
2304300×
            if let Ok(s2) = Store::open(&objects) {
23057640×
                for r in &refs {
23067640×
                    match s2.get(r) {
23077452×
                        Ok((ty, body)) => assert_eq!(
23087452×
                            hash_object(ty, &body),
2309
                            *r,
2310
                            "a returned object always matches its reference"
2311
                        ),
2312
                        Err(StoreError::Corrupt(..))
2313
                        | Err(StoreError::NotFound(_))
2314188×
                        | Err(StoreError::Io(_)) => {}
23150×
                        Err(e) => panic!("unexpected error {e}"),
2316
                    }
2317
                }
2318109×
            }
2319300×
            fs::write(path, pristine).unwrap();
2320
        }
2321
        // Restored files read back in full.
23221×
        let s3 = Store::open(&objects).unwrap();
232340×
        for r in &refs {
232440×
            let (ty, body) = s3.get(r).unwrap();
232540×
            assert_eq!(hash_object(ty, &body), *r);
2326
        }
23271×
    }
2328
2329
    /// A small batch becomes loose objects; a large one becomes a single
2330
    /// pack. Objects are readable while pending, and batches nest.
2331
    #[test]
23321×
    fn batches_write_loose_or_one_pack() {
23331×
        let dir = tempfile::tempdir().unwrap();
23342×
        each_store(dir.path(), |which, s| {
23352×
            let outer = s.begin_batch().unwrap();
23362×
            let a = s.put(ObjectType::Chunk, b"small a").unwrap();
2337
            {
23382×
                let inner = s.begin_batch().unwrap();
23392×
                let b = s.put(ObjectType::Chunk, b"small b").unwrap();
23402×
                assert!(s.has(&b));
23412×
                assert_eq!(s.get(&b).unwrap().1, b"small b");
23422×
                inner.finish().unwrap();
23432×
                assert_eq!(
23442×
                    s.loose_count().unwrap(),
2345
                    0,
2346
                    "{which}: the inner batch defers to the outer one"
2347
                );
2348
            }
23492×
            assert_eq!(s.get(&a).unwrap().1, b"small a");
23502×
            assert_eq!(
23512×
                s.put(ObjectType::Chunk, b"small a").unwrap(),
2352
                a,
2353
                "idempotent while pending"
2354
            );
23552×
            outer.finish().unwrap();
23562×
            assert_eq!(s.loose_count().unwrap(), 2);
23572×
            assert_eq!(s.pack_count(), 0);
23582×
            assert_eq!(s.get(&a).unwrap().1, b"small a");
2359
2360
            // Large: spills into one pack, readable during and after.
23612×
            let big = s.begin_batch().unwrap();
23622×
            let mut refs = Vec::new();
23632×
            let mut seed = 7u64;
2364600×
            for i in 0..300u32 {
2365600×
                let mut body = vec![b'z'; 40_000];
2366600×
                if i % 3 == 0 {
23678000000×
                    for b in body.iter_mut() {
23688000000×
                        *b = (xorshift(&mut seed) & 0xff) as u8;
23698000000×
                    }
2370400×
                }
2371600×
                body[..4].copy_from_slice(&i.to_le_bytes());
2372600×
                let r = if i % 5 == 0 {
2373120×
                    s.put_chunk_nocompress(&body).unwrap()
2374
                } else {
2375480×
                    s.put(ObjectType::Chunk, &body).unwrap()
2376
                };
2377600×
                assert_eq!(
2378600×
                    s.get(&r).unwrap().1,
2379
                    body,
2380
                    "readable while pending (object {i})"
2381
                );
2382600×
                refs.push((r, body));
2383
            }
23842×
            assert!(s.has(&refs[0].0));
23852×
            big.finish().unwrap();
23862×
            assert_eq!(s.pack_count(), 1);
23872×
            assert_eq!(
23882×
                s.loose_count().unwrap(),
2389
                2,
2390
                "nothing from the big batch is loose"
2391
            );
23922×
            assert!(fs::read_dir(s.dir())
23932×
                .unwrap()
23942×
                .flatten()
23954×
                .all(|e| !e.file_name().to_string_lossy().contains("tmp-")));
23962×
            let s2 = Store::open_on(s.backend().clone(), s.dir()).unwrap();
2397600×
            for (r, body) in &refs {
2398600×
                assert_eq!(s2.get(r).unwrap().1, *body);
2399
            }
2400
            // A dropped batch still writes its objects.
24012×
            {
24022×
                let _b = s2.begin_batch().unwrap();
24032×
                s2.put(ObjectType::Chunk, b"dropped").unwrap();
24042×
            }
24052×
            assert_eq!(
24062×
                s2.get(&hash_object(ObjectType::Chunk, b"dropped"))
24072×
                    .unwrap()
2408
                    .1,
2409
                b"dropped"
2410
            );
24112×
        });
24121×
    }
2413
2414
    #[test]
24151×
    fn get_many_reads_loose_and_packed_objects_in_order() {
24161×
        let dir = tempfile::tempdir().unwrap();
24172×
        each_store(dir.path(), |which, s| {
24182×
            let packed: Vec<ObjectRef> = (0..20)
241940×
                .map(|i| {
242040×
                    s.put(ObjectType::Chunk, format!("packed {i}").as_bytes())
242140×
                        .unwrap()
242240×
                })
24232×
                .collect();
24242×
            s.pack_loose().unwrap();
24252×
            let loose: Vec<ObjectRef> = (0..20)
242640×
                .map(|i| {
242740×
                    s.put(ObjectType::Chunk, format!("loose {i}").as_bytes())
242840×
                        .unwrap()
242940×
                })
24302×
                .collect();
24312×
            let missing = hash_object(ObjectType::Chunk, b"never stored");
24322×
            let mut refs: Vec<ObjectRef> = Vec::new();
243340×
            for i in 0..20 {
243440×
                refs.push(loose[i]);
243540×
                refs.push(packed[i]);
243640×
            }
24372×
            refs.push(missing);
24382×
            let got = s.get_many(&refs);
24392×
            assert_eq!(got.len(), refs.len());
244080×
            for (i, r) in refs.iter().enumerate().take(40) {
244180×
                let want = if i % 2 == 0 {
244240×
                    format!("loose {}", i / 2)
2443
                } else {
244440×
                    format!("packed {}", i / 2)
2445
                };
244680×
                let (ty, body) = got[i].as_ref().unwrap();
244780×
                assert_eq!(
244880×
                    (*ty, body.as_slice()),
244980×
                    (ObjectType::Chunk, want.as_bytes()),
2450
                    "{which}: {r:?}"
2451
                );
2452
            }
24532×
            assert!(matches!(got[40], Err(StoreError::NotFound(_))));
24542×
        });
24551×
    }
2456
}
2457
2458
#[cfg(test)]
2459
mod batch_tests {
2460
    use super::*;
2461
2462
    #[test]
24631×
    fn a_large_batch_packs_every_object_and_indexes_them_all() {
24641×
        let dir = tempfile::tempdir().unwrap();
24651×
        let store = Store::open(dir.path()).unwrap();
24661×
        let mut refs = Vec::new();
2467
        {
24681×
            let batch = store.begin_batch().unwrap();
24691000×
            for i in 0..1000u32 {
24701000×
                let body = format!("object {i} {}", "x".repeat(20_000 + i as usize)).into_bytes();
24711000×
                refs.push(store.put(ObjectType::Blob, &body).unwrap());
24721000×
            }
24731×
            batch.finish().unwrap();
2474
        }
24751×
        let again = Store::open(dir.path()).unwrap();
24761000×
        for r in &refs {
24771000×
            again
24781000×
                .get(r)
24791000×
                .unwrap_or_else(|e| panic!("{}: {e}", r.short(12)));
2480
        }
24811×
    }
2482
2483
    #[test]
24841×
    fn a_pack_a_stopped_batch_left_is_adopted_and_its_torn_end_cut() {
2485
        // oxygen#79: a batch never finished (a process killed part way)
2486
        // leaves its objects in an unindexed .tmp pack.
24871×
        let dir = tempfile::tempdir().unwrap();
24881×
        let mut refs = Vec::new();
2489
        {
24901×
            let store = Store::open(dir.path()).unwrap();
24911×
            let batch = store.begin_batch().unwrap();
2492300×
            for i in 0..300u32 {
2493300×
                let body = format!("object {i} {}", "y".repeat(20_000 + i as usize)).into_bytes();
2494300×
                refs.push(store.put(ObjectType::Blob, &body).unwrap());
2495300×
            }
24961×
            std::mem::forget(batch);
2497
        }
24981×
        let tmp: Vec<_> = fs::read_dir(dir.path())
24991×
            .unwrap()
25001×
            .flatten()
25012×
            .filter(|e| e.file_name().to_string_lossy().starts_with(".tmp-"))
25021×
            .map(|e| e.path())
25031×
            .collect();
25041×
        assert_eq!(tmp.len(), 1, "one unfinished pack");
2505
        // A torn last entry: a header and part of its body.
25061×
        let mut f = fs::OpenOptions::new().append(true).open(&tmp[0]).unwrap();
25071×
        f.write_all(&[0, 1, 0xff, 0, 0, 0, 9, 9, 0, 0]).unwrap();
25081×
        f.write_all(&[7; 40]).unwrap();
25091×
        drop(f);
25101×
        let store = Store::open(dir.path()).unwrap();
25111×
        assert!(store.get(&refs[0]).is_err(), "unreadable before");
25121×
        let young = store
25131×
            .adopt_unfinished_packs(std::time::Duration::from_secs(3600), &|_| {})
25141×
            .unwrap();
25151×
        assert_eq!(young, (0, 0), "a pack written to lately is left alone");
25161×
        let (packs, objects) = store
25172×
            .adopt_unfinished_packs(std::time::Duration::ZERO, &|_| {})
25181×
            .unwrap();
25191×
        assert_eq!((packs, objects), (1, 300));
2520300×
        for r in &refs {
2521300×
            store
2522300×
                .get(r)
2523300×
                .unwrap_or_else(|e| panic!("{}: {e}", r.short(12)));
2524
        }
25251×
        let again = Store::open(dir.path()).unwrap();
25261×
        assert!(again.get(&refs[299]).is_ok(), "indexed for good");
25271×
    }
2528
}
2529
2530
#[cfg(test)]
2531
mod size_tests {
2532
    use super::*;
2533
2534
    #[test]
25351×
    fn an_object_over_the_limit_is_refused_and_nothing_is_written() {
25361×
        let dir = tempfile::tempdir().unwrap();
25371×
        let store = Store::open(dir.path()).unwrap();
25381×
        let big = vec![b'x'; MAX_OBJECT_LEN as usize + 1];
2539
        {
25401×
            let batch = store.begin_batch().unwrap();
25411×
            store.put(ObjectType::Blob, b"small").unwrap();
25421×
            let e = store.put(ObjectType::Change, &big).unwrap_err();
25431×
            assert!(
25441×
                matches!(e, StoreError::TooLarge { kind: "change", .. }),
2545
                "{e}"
2546
            );
25471×
            assert!(e.to_string().contains("commit it in parts"), "{e}");
25481×
            batch.finish().unwrap();
2549
        }
2550
        // The store still opens and reads what was written.
25511×
        let again = Store::open(dir.path()).unwrap();
25521×
        again.get(&hash_object(ObjectType::Blob, b"small")).unwrap();
25531×
    }
2554
}
2555
2556
#[cfg(test)]
2557
mod text_tests {
2558
    use super::*;
2559
    use crate::objects::{AtomRef, Edit, CHANGE_VERSION};
2560
25612×
    fn large_change() -> Change {
25622×
        let mut c = crate::objects::tests::sample_change();
25632×
        assert_eq!(c.version, CHANGE_VERSION);
25642×
        c.edits[0] = Edit::Insert {
25652×
            node: crate::ids::NodeId([7; 16]),
25662×
            after: AtomRef::Start,
25672×
            before: AtomRef::End,
25682×
            lines: (0..2000)
25694000×
                .map(|i| format!("line {i}\n").into_bytes())
25702×
                .collect(),
2571
        };
25722×
        c
25732×
    }
2574
2575
    #[test]
25761×
    fn a_large_insert_is_stored_beside_its_change_and_read_back() {
25771×
        let dir = tempfile::tempdir().unwrap();
25781×
        let s = Store::open(dir.path()).unwrap();
25791×
        let c = large_change();
25801×
        let r = s.put_change(&c).unwrap();
25811×
        assert_eq!(r, c.hash());
25821×
        let (_, body) = s.get(&r).unwrap();
25831×
        assert!(
25841×
            body.len() < 1024,
2585
            "the change holds a reference, not {} bytes of lines",
25860×
            body.len()
2587
        );
25881×
        let (back, parts) = s.get_change_parts(&r).unwrap();
25891×
        assert_eq!(back, c);
2590
        // The text blob and its chunk.
25911×
        assert_eq!(parts.len(), 2);
25922×
        for p in &parts {
25932×
            assert!(s.has(p));
2594
        }
2595
        // Storing it again writes nothing new.
25961×
        let n = s.list().unwrap().len();
25971×
        s.put_change(&c).unwrap();
25981×
        assert_eq!(s.list().unwrap().len(), n);
25991×
    }
2600
2601
    #[test]
26021×
    fn a_change_whose_text_blob_is_missing_is_reported_not_misread() {
26031×
        if !super::files_on_disk() {
26040×
            return;
26051×
        }
26061×
        let dir = tempfile::tempdir().unwrap();
26071×
        let s = Store::open(dir.path()).unwrap();
26081×
        let c = large_change();
26091×
        let r = s.put_change(&c).unwrap();
26101×
        let (_, parts) = s.get_change_parts(&r).unwrap();
26111×
        fs::remove_file(s.path_for(&parts[0])).unwrap();
26121×
        let e = s.get_change(&r).unwrap_err();
26131×
        assert!(
26141×
            matches!(&e, StoreError::Corrupt(h, why) if *h == r && why.contains("missing")),
2615
            "{e}"
2616
        );
26171×
    }
2618
}
2619
2620
#[cfg(test)]
2621
mod put_many_tests {
2622
    use super::*;
2623
2624
    #[test]
26251×
    fn many_objects_in_a_batch_are_compressed_together_and_all_read_back() {
26261×
        let dir = tempfile::tempdir().unwrap();
26271×
        let s = Store::open(dir.path()).unwrap();
26281×
        let before = s.put(ObjectType::Chunk, b"already here").unwrap();
26291×
        let bodies: Vec<Vec<u8>> = (0..200u32)
2630200×
            .map(|i| format!("chunk {i} ").repeat(6000).into_bytes())
26311×
            .collect();
26321×
        let mut objects: Vec<(ObjectType, &[u8])> = bodies
26331×
            .iter()
2634200×
            .map(|b| (ObjectType::Chunk, b.as_slice()))
26351×
            .collect();
26361×
        objects.push((ObjectType::Chunk, bodies[0].as_slice()));
26371×
        objects.push((ObjectType::Chunk, b"already here"));
26381×
        let refs = {
26391×
            let batch = s.begin_batch().unwrap();
26401×
            let refs = s.put_many(&objects).unwrap();
26411×
            batch.finish().unwrap();
26421×
            refs
2643
        };
26441×
        assert_eq!(refs.len(), objects.len());
26451×
        assert_eq!(refs[200], refs[0], "a repeat is the same object");
26461×
        assert_eq!(refs[201], before);
26471×
        let again = Store::open(dir.path()).unwrap();
2648202×
        for (r, b) in refs.iter().zip(&objects) {
2649202×
            assert_eq!(again.get(r).unwrap().1, b.1);
2650
        }
26511×
    }
2652
}