OXYGENHUB

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

1920 of 2030 lines run, 298 of 431 functions · run #298 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.
867633×
fn put_new_or_existing(backend: &Backend, key: &str, bytes: &[u8]) -> Result<()> {
877633×
    match backend.put_new(key, bytes) {
887633×
        Ok(()) | Err(BackendError::Exists(_)) => Ok(()),
890×
        Err(e) => Err(backend_err(e)),
90
    }
917633×
}
92
93
/// `get` as an option: `None` when there is no such key.
9468645×
fn get_optional(backend: &Backend, key: &str) -> Result<Option<Vec<u8>>> {
9568645×
    match backend.get(key) {
9647244×
        Ok(b) => Ok(Some(b)),
9721401×
        Err(BackendError::NotFound(_)) => Ok(None),
980×
        Err(e) => Err(backend_err(e)),
99
    }
10068645×
}
101
1023023×
fn delete(backend: &Backend, key: &str) -> Result<()> {
1033023×
    backend.delete(key).map_err(backend_err)
1043023×
}
105
106
/// `loose/<hh>/<rest>`.
107101774×
fn loose_key(r: &ObjectRef) -> String {
108101774×
    let h = r.to_hex();
109101774×
    format!("loose/{}/{}", &h[..2], &h[2..])
110101774×
}
111
112
/// The object a loose key names, if it is one.
11316898×
fn loose_ref(key: &str) -> Option<ObjectRef> {
11416898×
    let rest = key.strip_prefix("loose/")?;
11516898×
    let (hh, tail) = rest.split_once('/')?;
11616898×
    if hh.len() != 2 || tail.contains('/') {
1170×
        return None;
11816898×
    }
11916898×
    ObjectRef::from_hex(&format!("{hh}{tail}"))
12016898×
}
121
122
/// `<index>/<hh>/<rest>/` for the entries kept under an object.
1234556×
fn fanout_prefix(index: &str, r: &ObjectRef) -> String {
1244556×
    let h = r.to_hex();
1254556×
    format!("{index}/{}/{}/", &h[..2], &h[2..])
1264556×
}
127
128
/// `<index>/<hh>/<rest>`: the one-file-per-object layout of older stores.
1293939×
fn legacy_key(index: &str, r: &ObjectRef) -> String {
1303939×
    let h = r.to_hex();
1313939×
    format!("{index}/{}/{}", &h[..2], &h[2..])
1323939×
}
133
13422×
fn now_ms() -> u64 {
13522×
    std::time::SystemTime::now()
13622×
        .duration_since(std::time::UNIX_EPOCH)
13722×
        .map(|d| d.as_millis() as u64)
13822×
        .unwrap_or(0)
13922×
}
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.
17115721×
fn decode_entry(
17215721×
    r: &ObjectRef,
17315721×
    e: PackEntry,
17415721×
    stored: Vec<u8>,
17515721×
    dict: Option<&Arc<zstd::dict::DecoderDictionary<'static>>>,
17615721×
) -> Result<Object> {
17715721×
    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}")))?
18411220×
    } else if e.flags & FLAG_ZSTD != 0 {
1856447×
        zstd::bulk::decompress(&stored, e.raw_len as usize)
1866447×
            .map_err(|err| StoreError::Corrupt(*r, format!("zstd: {err}")))?
187
    } else {
1884773×
        stored
189
    };
19015716×
    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×
        ));
19515597×
    }
19615597×
    Ok((e.ty, body))
19715721×
}
198
199
impl PackIndex {
2001129×
    fn load(backend: &Backend, idx_key: &str, pack_key: &str) -> Result<PackIndex> {
2011129×
        let data = backend.get(idx_key).map_err(backend_err)?;
2021129×
        let bad = |m: &str| StoreError::Corrupt(ObjectRef::ZERO, format!("{idx_key}: {m}"));
2031129×
        if data.len() < 12 || &data[..8] != IDX_MAGIC {
2042×
            return Err(bad("bad index header"));
2051127×
        }
2061127×
        let count = u32::from_le_bytes(data[8..12].try_into().unwrap()) as usize;
2071127×
        if data.len() != 12 + count * IDX_ENTRY {
20842×
            return Err(bad("index length mismatch"));
2091085×
        }
2101085×
        let pack_len = backend
2111085×
            .stat(pack_key)
2121085×
            .map_err(backend_err)?
2131085×
            .ok_or_else(|| bad("the index names a pack that is not there"))?
214
            .size;
2151085×
        let mut refs = Vec::with_capacity(count);
2161085×
        let mut entries = Vec::with_capacity(count);
21726113×
        for i in 0..count {
21826113×
            let e = &data[12 + i * IDX_ENTRY..12 + (i + 1) * IDX_ENTRY];
21926113×
            let r = ObjectRef::from_slice(&e[..32]).unwrap();
22026113×
            if let Some(prev) = refs.last() {
22125028×
                if r <= *prev {
2223×
                    return Err(bad("index not sorted"));
22325025×
                }
2241085×
            }
22526110×
            refs.push(r);
22626105×
            let entry = PackEntry {
22726110×
                offset: u64::from_le_bytes(e[32..40].try_into().unwrap()),
22826110×
                stored_len: u32::from_le_bytes(e[40..44].try_into().unwrap()),
22926110×
                raw_len: u32::from_le_bytes(e[44..48].try_into().unwrap()),
23026110×
                ty: ObjectType::ALL
23126110×
                    .get(e[48] as usize)
23226110×
                    .copied()
23326110×
                    .ok_or_else(|| bad("unknown object type"))?,
23426105×
                flags: e[49],
235
            };
23626105×
            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×
                ));
24426102×
            }
24526102×
            if entry.offset.saturating_add(entry.stored_len as u64) > pack_len {
24654×
                return Err(bad("index entry points outside the pack"));
24726048×
            }
24826048×
            entries.push(entry);
249
        }
2501020×
        let dict_key = format!("{}.dict", pack_key.trim_end_matches(".pack"));
2511020×
        let dict = get_optional(backend, &dict_key)?
2521020×
            .map(|d| Arc::new(zstd::dict::DecoderDictionary::copy(&d)));
2531020×
        Ok(PackIndex {
2541020×
            key: pack_key.to_string(),
2551020×
            refs,
2561020×
            entries,
2571020×
            dict,
2581020×
        })
2591129×
    }
260
26117880×
    fn find(&self, r: &ObjectRef) -> Option<PackEntry> {
26217880×
        self.refs.binary_search(r).ok().map(|i| self.entries[i])
26317880×
    }
264
265
    /// Read one entry from the pack: one ranged read, then decode.
26615239×
    fn fetch(&self, backend: &Backend, r: &ObjectRef, e: PackEntry) -> Result<Object> {
26715239×
        let stored = backend
26815239×
            .get_range(&self.key, e.offset..e.offset + e.stored_len as u64)
26915239×
            .map_err(|err| match err {
2700×
                BackendError::NotFound(_) => StoreError::NotFound(*r),
2710×
                other => backend_err(other),
2720×
            })?;
27315239×
        decode_entry(r, e, stored, self.dict.as_ref())
27415239×
    }
275
}
276
27711962×
fn type_index(ty: ObjectType) -> u8 {
27817336×
    ObjectType::ALL.iter().position(|t| *t == ty).unwrap() as u8
27911962×
}
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<'_> {
3862662×
    pub fn finish(mut self) -> Result<()> {
3872662×
        self.done = true;
3882662×
        self.store.finish_batch()
3892662×
    }
390
}
391
392
impl Drop for Batch<'_> {
3932664×
    fn drop(&mut self) {
3942664×
        if !self.done {
3952×
            let _ = self.store.finish_batch();
3962662×
        }
3972664×
    }
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.
43376×
fn fresh_id() -> String {
43476×
    let mut nonce = [0u8; 8];
43576×
    rand::rngs::OsRng.fill_bytes(&mut nonce);
43676×
    hex::encode(nonce)
43776×
}
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.
4432723×
fn memory_backend_for(dir: &Path) -> Option<Arc<Backend>> {
444
    use std::collections::HashMap;
445
    use std::sync::{Mutex, OnceLock};
4462723×
    if std::env::var_os("OXY_STORE_BACKEND").as_deref() != Some(std::ffi::OsStr::new("memory")) {
4472723×
        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)
4602723×
}
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.
4722727×
    pub fn open(dir: impl Into<PathBuf>) -> io::Result<Store> {
4732727×
        let dir = dir.into();
4742727×
        fs::create_dir_all(dir.join("loose"))?;
475
        #[cfg(test)]
4761172×
        if let Some(backend) = TEST_BACKEND.with(|t| t.borrow().clone()) {
4774×
            return Store::open_on(backend, dir);
4781168×
        }
4792723×
        if let Some(backend) = memory_backend_for(&dir) {
4800×
            return Store::open_on(backend, dir);
4812723×
        }
4822723×
        let backend: Arc<Backend> =
4832723×
            Arc::new(LocalStore::open(&dir).map_err(|e| io::Error::other(e.to_string()))?);
4842723×
        let mut store = Store::open_on(backend, dir)?;
4852614×
        store.local = true;
4862614×
        Ok(store)
4872727×
    }
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.
4912741×
    pub fn open_on(backend: Arc<Backend>, scratch: impl Into<PathBuf>) -> io::Result<Store> {
4922741×
        let scratch = scratch.into();
4932741×
        fs::create_dir_all(&scratch)?;
4942741×
        let store = Store {
4952741×
            backend,
4962741×
            scratch,
4972741×
            local: false,
4982741×
            packs: RefCell::new(Vec::new()),
4992741×
            pending: RefCell::new(None),
5002741×
            batch_depth: std::cell::Cell::new(0),
5012741×
            metas: RefCell::new(None),
5022741×
        };
5032741×
        store
5042741×
            .reload_packs()
5052741×
            .map_err(|e| io::Error::other(e.to_string()))?;
5062632×
        Ok(store)
5072741×
    }
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.
51623171×
    pub fn is_local(&self) -> bool {
51723171×
        self.local
51823171×
    }
519
5202888×
    fn reload_packs(&self) -> Result<()> {
5212888×
        let listed = self.backend.list("pack-").map_err(backend_err)?;
5222888×
        let mut idx_keys: Vec<&str> = listed
5232888×
            .iter()
5242888×
            .map(|e| e.key.as_str())
5252888×
            .filter(|k| k.ends_with(".idx"))
5262888×
            .collect();
5272888×
        idx_keys.sort();
5282888×
        let mut packs = Vec::new();
5292888×
        for idx in idx_keys {
5301129×
            let pack = format!("{}.pack", idx.trim_end_matches(".idx"));
53110735×
            if listed.iter().any(|e| e.key == pack) {
5321129×
                packs.push(PackIndex::load(self.backend.as_ref(), idx, &pack)?);
5330×
            }
534
        }
5352779×
        *self.packs.borrow_mut() = packs;
5362779×
        Ok(())
5372888×
    }
538
53915×
    pub fn pack_count(&self) -> usize {
54015×
        self.packs.borrow().len()
54115×
    }
542
54334351×
    fn find_packed(&self, r: &ObjectRef) -> Option<(usize, PackEntry)> {
54434351×
        self.packs
54534351×
            .borrow()
54634351×
            .iter()
54734351×
            .enumerate()
54834351×
            .find_map(|(i, p)| p.find(r).map(|e| (i, e)))
54934351×
    }
550
551
    /// Loose objects, with their keys and ages.
552825×
    fn loose_objects(&self) -> Result<Vec<(ObjectRef, strata::Entry)>> {
553825×
        let mut out: Vec<(ObjectRef, strata::Entry)> = self
554825×
            .backend
555825×
            .list("loose/")
556825×
            .map_err(backend_err)?
557825×
            .into_iter()
55816898×
            .filter_map(|e| loose_ref(&e.key).map(|r| (r, e)))
559825×
            .collect();
560825×
        out.sort_by_key(|(r, _)| *r);
561825×
        Ok(out)
562825×
    }
563
564654×
    pub fn loose_count(&self) -> io::Result<usize> {
565654×
        self.loose_objects()
566654×
            .map(|l| l.len())
567654×
            .map_err(|e| io::Error::other(e.to_string()))
568654×
    }
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.
59119×
    pub fn repack_all_with(&self, level: i32, progress: Progress) -> Result<(PackReport, usize)> {
59219×
        let loose = self.loose_objects()?;
59319×
        let (mut refs, keys): (Vec<ObjectRef>, Vec<String>) = {
59419×
            let packs = self.packs.borrow();
595
            (
59619×
                packs.iter().flat_map(|p| p.refs.iter().copied()).collect(),
59719×
                packs.iter().map(|p| p.key.clone()).collect(),
598
            )
599
        };
60019×
        if loose.is_empty() && keys.len() <= 1 && level == ZSTD_LEVEL {
6010×
            return Ok((PackReport::default(), 0));
60219×
        }
60319×
        refs.extend(loose.iter().map(|(r, _)| *r));
60419×
        let loose_keys: Vec<String> = loose.into_iter().map(|(_, e)| e.key).collect();
60519×
        let n = keys.len();
60619×
        let report = self.write_pack(&refs, &loose_keys, &keys, level, progress)?;
60719×
        Ok((report, n))
60819×
    }
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.
64222×
    pub fn prune_with(
64322×
        &self,
64422×
        keep: &std::collections::HashSet<ObjectRef>,
64522×
        grace: std::time::Duration,
64622×
        progress: Progress,
64722×
    ) -> Result<PruneReport> {
64822×
        progress("pruning loose objects");
64922×
        let now = now_ms();
65022×
        let grace_ms = grace.as_millis() as u64;
651
        // An object whose age the store does not know is old enough.
65222×
        let old_enough =
65335×
            |modified: Option<u64>| modified.is_none_or(|t| now.saturating_sub(t) >= grace_ms);
65422×
        let mut report = PruneReport::default();
655
        // Loose objects.
656291×
        for (r, entry) in self.loose_objects()? {
657291×
            if keep.contains(&r) {
658265×
                continue;
65926×
            }
66026×
            if !old_enough(entry.modified_ms) {
6614×
                report.deferred += 1;
6624×
                continue;
66322×
            }
66422×
            report.bytes += entry.size;
66522×
            report.objects += 1;
66622×
            delete(self.backend.as_ref(), &entry.key)?;
66722×
            self.remove_sidecars(&r)?;
668
        }
669
        // Packs: rewrite those that hold unreachable objects.
67022×
        let mut keep_refs: Vec<ObjectRef> = Vec::new();
67122×
        let mut old_keys: Vec<String> = Vec::new();
67222×
        let mut rewrite = false;
67322×
        progress("pruning packs");
67422×
        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
        }
69922×
        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
            }
71316×
        }
71422×
        Ok(report)
71522×
    }
716
717
    /// Everything kept beside an object: its signatures and the seal and
718
    /// receipt entries under it, in both layouts.
71963×
    fn remove_sidecars(&self, r: &ObjectRef) -> Result<()> {
720189×
        for index in ["sigs", "seals", "receipts"] {
721189×
            delete(self.backend.as_ref(), &legacy_key(index, r))?;
722
        }
723189×
        for index in ["sig", "seal", "receipt"] {
724189×
            for e in self
725189×
                .backend
726189×
                .list(&fanout_prefix(index, r))
727189×
                .map_err(backend_err)?
728
            {
72910×
                delete(self.backend.as_ref(), &e.key)?;
730
            }
731
        }
73263×
        Ok(())
73363×
    }
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.
73876×
    fn finish_pack_files(
73976×
        &self,
74076×
        id: &str,
74176×
        tmp_pack: &Path,
74276×
        index: &[(ObjectRef, PackEntry)],
74376×
    ) -> Result<()> {
74476×
        let mut idx = Vec::with_capacity(12 + index.len() * IDX_ENTRY);
74576×
        idx.extend_from_slice(IDX_MAGIC);
74676×
        idx.extend_from_slice(&(index.len() as u32).to_le_bytes());
7475981×
        for (r, e) in index {
7485981×
            idx.extend_from_slice(&r.0);
7495981×
            idx.extend_from_slice(&e.offset.to_le_bytes());
7505981×
            idx.extend_from_slice(&e.stored_len.to_le_bytes());
7515981×
            idx.extend_from_slice(&e.raw_len.to_le_bytes());
7525981×
            idx.extend_from_slice(&[type_index(e.ty), e.flags]);
7535981×
        }
75476×
        let put = self
75576×
            .backend
75676×
            .put_new_file(&format!("pack-{id}.pack"), tmp_pack)
75776×
            .map_err(backend_err);
758
        // A store on another disk copied it; the one in this directory
759
        // moved it and this finds nothing.
76076×
        let _ = fs::remove_file(tmp_pack);
76176×
        put?;
76276×
        self.backend
76376×
            .put_new(&format!("pack-{id}.idx"), &idx)
76476×
            .map_err(backend_err)?;
76576×
        self.reload_packs()
76676×
    }
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`.
77771×
    fn write_pack(
77871×
        &self,
77971×
        refs: &[ObjectRef],
78071×
        loose_keys: &[String],
78171×
        old_packs: &[String],
78271×
        level: i32,
78371×
        progress: Progress,
78471×
    ) -> Result<PackReport> {
78571×
        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());
79171×
        }
79271×
        let mut refs: Vec<ObjectRef> = refs.to_vec();
79371×
        refs.sort();
79471×
        refs.dedup();
79571×
        let id = fresh_id();
79671×
        let tmp_pack = self.scratch.join(format!(".tmp-{id}.pack"));
79771×
        let mut report = PackReport::default();
79871×
        let mut index: Vec<(ObjectRef, PackEntry)> = Vec::with_capacity(refs.len());
799
        // A full repack of enough objects trains a dictionary for them.
80071×
        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 {
80569×
            None
806
        };
80771×
        let encoder = dict
80871×
            .as_ref()
80971×
            .map(|d| zstd::dict::EncoderDictionary::copy(d, level));
81071×
        let nocompress = self.nocompress_set()?;
811
        {
81271×
            let mut f = io::BufWriter::new(fs::File::create(&tmp_pack)?);
81371×
            f.write_all(PACK_MAGIC)?;
81471×
            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.
81771×
            let mut batches = refs.chunks(1024);
81871×
            let mut compressed_batch = Vec::new();
81971×
            let total = refs.len();
82071×
            let mut reported = usize::MAX;
821
            loop {
8223952×
                if compressed_batch.is_empty() {
823144×
                    let Some(batch) = batches.next() else { break };
824
                    // Every tenth, and the first batch.
82573×
                    let tenth = report.objects * 10 / total.max(1);
82673×
                    if tenth != reported {
82773×
                        reported = tenth;
82873×
                        progress(&format!("packing {} of {total} objects", report.objects));
82973×
                    }
83073×
                    let mut read: Vec<(ObjectRef, ObjectType, Vec<u8>, bool)> =
83173×
                        Vec::with_capacity(batch.len());
8323881×
                    for r in batch {
8333881×
                        let (ty, body) = self.get(r)?;
8343881×
                        read.push((*r, ty, body, nocompress.contains(r)));
835
                    }
836
                    use rayon::prelude::*;
83773×
                    compressed_batch = read
83873×
                        .into_par_iter()
83973×
                        .map_init(
8401094×
                            || {
8411094×
                                encoder.as_ref().and_then(|e| {
842503×
                                    zstd::bulk::Compressor::with_prepared_dictionary(e).ok()
843503×
                                })
8441094×
                            },
8453881×
                            |with_dict, (r, ty, body, raw)| {
8463881×
                                let packed = if raw {
8472×
                                    None
848
                                } else {
849
                                    // Small objects with the dictionary;
850
                                    // a large one has context enough.
8513879×
                                    let dicted = with_dict
8523879×
                                        .as_mut()
8533879×
                                        .filter(|_| body.len() <= DICT_OBJECT_MAX)
8543879×
                                        .and_then(|c| c.compress(&body).ok())
8553879×
                                        .map(|c| (FLAG_ZSTD | FLAG_DICT, c));
8563879×
                                    dicted
8573879×
                                        .or_else(|| {
858879×
                                            zstd::bulk::compress(&body, level)
859879×
                                                .ok()
860879×
                                                .map(|c| (FLAG_ZSTD, c))
861879×
                                        })
8623879×
                                        .filter(|(_, c)| c.len() < body.len())
863
                                };
8643881×
                                (r, ty, body, packed)
8653881×
                            },
866
                        )
86773×
                        .collect::<Vec<_>>();
86873×
                    compressed_batch.reverse();
8693808×
                }
8703881×
                let Some((r, ty, body, packed)) = compressed_batch.pop() else {
8710×
                    continue;
872
                };
8733881×
                let r = &r;
8743881×
                let (flags, stored) = match packed {
8753379×
                    Some(c) => c,
876502×
                    None => (0, body.clone()),
877
                };
8783881×
                let header_len = 1 + 1 + 4 + 4 + 32;
8793881×
                f.write_all(&[type_index(ty), flags])?;
8803881×
                f.write_all(&(stored.len() as u32).to_le_bytes())?;
8813881×
                f.write_all(&(body.len() as u32).to_le_bytes())?;
8823881×
                f.write_all(&r.0)?;
8833881×
                f.write_all(&stored)?;
8843881×
                index.push((
8853881×
                    *r,
8863881×
                    PackEntry {
8873881×
                        offset: offset + header_len,
8883881×
                        stored_len: stored.len() as u32,
8893881×
                        raw_len: body.len() as u32,
8903881×
                        ty,
8913881×
                        flags,
8923881×
                    },
8933881×
                ));
8943881×
                offset += header_len + stored.len() as u64;
8953881×
                report.objects += 1;
8963881×
                report.raw_bytes += body.len() as u64;
8973881×
                report.packed_bytes += stored.len() as u64;
898
            }
89971×
            f.flush()?;
90071×
            f.get_ref().sync_all()?;
901
        }
902
        // The dictionary before the pack that needs it becomes visible.
90371×
        if let Some(d) = &dict {
9042×
            self.backend
9052×
                .put_new(&format!("pack-{id}.dict"), d)
9062×
                .map_err(backend_err)?;
90769×
        }
90871×
        progress(&format!("writing the index of {} objects", index.len()));
90971×
        self.finish_pack_files(&id, &tmp_pack, &index)?;
91071×
        for p in old_packs {
91149×
            self.remove_pack(p)?;
912
        }
91371×
        self.reload_packs()?;
9142181×
        for key in loose_keys {
9152181×
            delete(self.backend.as_ref(), key)?;
916
        }
91771×
        Ok(report)
91871×
    }
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
96511191×
    pub fn has(&self, r: &ObjectRef) -> bool {
96611191×
        self.backend.has(&loose_key(r)).unwrap_or(false)
9671248×
            || self.find_packed(r).is_some()
968908×
            || self
969908×
                .pending
970908×
                .borrow()
971908×
                .as_ref()
972908×
                .is_some_and(|p| p.lookup.contains_key(r))
97311191×
    }
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.
9792665×
    pub fn begin_batch(&self) -> Result<Batch<'_>> {
9802665×
        let depth = self.batch_depth.get();
9812665×
        if depth == 0 {
9822164×
            *self.pending.borrow_mut() = Some(Pending {
9832164×
                buffered: vec![],
9842164×
                buffered_bytes: 0,
9852164×
                lookup: Default::default(),
9862164×
                pack: None,
9872164×
                report: PackReport::default(),
9882164×
            });
9892164×
        }
9902665×
        self.batch_depth.set(depth + 1);
9912665×
        Ok(Batch {
9922665×
            store: self,
9932665×
            done: false,
9942665×
        })
9952665×
    }
996
9972664×
    fn finish_batch(&self) -> Result<()> {
9982664×
        let depth = self.batch_depth.get();
9992664×
        if depth == 0 {
10000×
            return Ok(());
10012664×
        }
10022664×
        self.batch_depth.set(depth - 1);
10032664×
        if depth > 1 {
1004501×
            return Ok(());
10052163×
        }
10062163×
        let Some(pending) = self.pending.borrow_mut().take() else {
10072×
            return Ok(());
1008
        };
10092161×
        self.write_pending(pending)
10102664×
    }
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.
10153352×
    pub fn flush(&self) -> Result<()> {
10163352×
        let Some(pending) = self.pending.borrow_mut().take() else {
10172361×
            return Ok(());
1018
        };
1019991×
        self.write_pending(pending)?;
1020989×
        *self.pending.borrow_mut() = Some(Pending {
1021989×
            buffered: vec![],
1022989×
            buffered_bytes: 0,
1023989×
            lookup: Default::default(),
1024989×
            pack: None,
1025989×
            report: PackReport::default(),
1026989×
        });
1027989×
        Ok(())
10283352×
    }
1029
10303152×
    fn write_pending(&self, pending: Pending) -> Result<()> {
10313152×
        match pending.pack {
1032
            None => {
10333148×
                let objects: Vec<(ObjectType, &[u8])> = pending
10343148×
                    .buffered
10353148×
                    .iter()
10364937×
                    .map(|(ty, body)| (*ty, body.as_slice()))
10373148×
                    .collect();
10383148×
                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
        }
10493152×
    }
1050
1051
    /// Whether a batch is open and holds `r`.
1052927×
    fn pending_get(&self, r: &ObjectRef) -> Option<Result<Object>> {
1053927×
        let mut guard = self.pending.borrow_mut();
1054927×
        let pending = guard.as_mut()?;
1055821×
        let entry = *pending.lookup.get(r)?;
1056821×
        Some(match entry {
1057639×
            PendingEntry::Buffered(i) => {
1058639×
                let (ty, body) = &pending.buffered[i];
1059639×
                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
        })
1077927×
    }
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
11026938×
    fn put_pending(&self, r: ObjectRef, ty: ObjectType, body: &[u8]) -> Result<()> {
11036938×
        let mut guard = self.pending.borrow_mut();
11046938×
        let pending = guard.as_mut().expect("batch open");
11056938×
        if pending.lookup.contains_key(&r) {
1106101×
            return Ok(());
11076837×
        }
11086837×
        if pending.pack.is_none()
11095871×
            && pending.buffered.len() < SPILL_OBJECTS
11105869×
            && pending.buffered_bytes + body.len() <= SPILL_BYTES
1111
        {
11125867×
            pending.buffered.push((ty, body.to_vec()));
11135867×
            pending.buffered_bytes += body.len();
11145867×
            pending
11155867×
                .lookup
11165867×
                .insert(r, PendingEntry::Buffered(pending.buffered.len() - 1));
11175867×
            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(())
11266938×
    }
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.
1161763×
    pub fn put_many(&self, objects: &[(ObjectType, &[u8])]) -> Result<Vec<ObjectRef>> {
1162
        use rayon::prelude::*;
1163768×
        let total: usize = objects.iter().map(|(_, b)| b.len()).sum();
1164763×
        if self.pending.borrow().is_none() || total < SPILL_BYTES {
1165762×
            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)
1223763×
    }
1224
1225
    /// Store `body` as an object of type `ty`; idempotent.
122615353×
    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.
123015353×
        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×
            });
123615352×
        }
123715352×
        let r = hash_object(ty, body);
123815352×
        if self.find_packed(&r).is_some() || self.backend.has(&loose_key(&r)).unwrap_or(false) {
12391699×
            return Ok(r);
124013653×
        }
124113653×
        if self.pending.borrow().is_some() {
12426938×
            self.put_pending(r, ty, body)?;
12436938×
            return Ok(r);
12446715×
        }
12456715×
        self.put_loose(ty, body)?;
12466710×
        Ok(r)
124715353×
    }
1248
1249
    /// Write one loose object, durable when this returns.
12506920×
    fn put_loose(&self, ty: ObjectType, body: &[u8]) -> Result<ObjectRef> {
12516920×
        let r = hash_object(ty, body);
12526920×
        let mut bytes = header(ty, body.len());
12536920×
        bytes.extend_from_slice(body);
12546920×
        crate::durable::step("write loose object")?;
12556915×
        put_new_or_existing(self.backend.as_ref(), &loose_key(&r), &bytes)?;
12566915×
        Ok(r)
12576920×
    }
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).
12633148×
    fn put_loose_many(&self, objects: &[(ObjectType, &[u8])]) -> Result<()> {
12643148×
        if objects.len() <= 1 {
12651797×
            for (ty, body) in objects {
1266205×
                self.put_loose(*ty, body)?;
1267
            }
12681797×
            return Ok(());
12691351×
        }
12701351×
        let mut seen = std::collections::HashSet::new();
12711351×
        let items: Vec<(String, Vec<u8>)> = objects
12721351×
            .iter()
12734732×
            .filter_map(|(ty, body)| {
12744732×
                let r = hash_object(*ty, body);
12754732×
                seen.insert(r).then(|| {
12764732×
                    let mut bytes = header(*ty, body.len());
12774732×
                    bytes.extend_from_slice(body);
12784732×
                    (loose_key(&r), bytes)
12794732×
                })
12804732×
            })
12811351×
            .collect();
12821351×
        self.backend.put_many_new(&items).map_err(backend_err)
12833148×
    }
1284
1285
    /// Read and verify an object, loose, packed, or pending in a batch.
128661412×
    pub fn get(&self, r: &ObjectRef) -> Result<Object> {
128761412×
        match get_optional(self.backend.as_ref(), &loose_key(r))? {
128845365×
            Some(bytes) => parse_loose(&bytes, r),
128916047×
            None => match self.find_packed(r) {
129015120×
                Some((i, e)) => self.packs.borrow()[i].fetch(self.backend.as_ref(), r, e),
1291927×
                None => self.pending_get(r).unwrap_or(Err(StoreError::NotFound(*r))),
1292
            },
1293
        }
129461412×
    }
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`.
1299940×
    pub fn get_many(&self, refs: &[ObjectRef]) -> Vec<Result<Object>> {
1300
        use rayon::prelude::*;
1301940×
        let backend = self.backend.as_ref();
1302940×
        let mut found: Vec<Option<Result<Object>>> = refs
1303940×
            .par_iter()
13041970×
            .map(|r| match get_optional(backend, &loose_key(r)) {
13051845×
                Ok(Some(bytes)) => Some(parse_loose(&bytes, r)),
1306125×
                Ok(None) => None,
13070×
                Err(e) => Some(Err(e)),
13081970×
            })
1309940×
            .collect();
1310
        // Packed ones: look them up in order, then read them in parallel.
1311940×
        let packs = self.packs.borrow();
1312940×
        let packed: Vec<(usize, usize, PackEntry)> = found
1313940×
            .iter()
1314940×
            .enumerate()
13151970×
            .filter(|(_, f)| f.is_none())
1316940×
            .filter_map(|(i, _)| {
1317125×
                packs
1318125×
                    .iter()
1319125×
                    .enumerate()
1320125×
                    .find_map(|(p, pack)| pack.find(&refs[i]).map(|e| (i, p, e)))
1321125×
            })
1322940×
            .collect();
1323940×
        let indexes: &[PackIndex] = &packs;
1324940×
        let read: Vec<(usize, Result<Object>)> = packed
1325940×
            .par_iter()
1326940×
            .map(|(i, p, e)| (*i, indexes[*p].fetch(backend, &refs[*i], *e)))
1327940×
            .collect();
1328940×
        drop(packs);
1329940×
        for (i, r) in read {
1330118×
            found[i] = Some(r);
1331118×
        }
1332940×
        found
1333940×
            .into_iter()
1334940×
            .zip(refs)
13351970×
            .map(|(f, r)| match f {
13361963×
                Some(f) => f,
13377×
                None => self.get(r),
13381970×
            })
1339940×
            .collect()
1340940×
    }
1341
134242155×
    pub fn get_typed(&self, r: &ObjectRef, want: ObjectType) -> Result<Vec<u8>> {
134342155×
        let (ty, body) = self.get(r)?;
134442122×
        if ty != want {
13451×
            return Err(StoreError::WrongType(*r, ty.name(), want.name()));
134642121×
        }
134742121×
        Ok(body)
134842155×
    }
1349
1350
    /// Store a change and the text blobs (and their chunks) its large
1351
    /// inserts are stored as (spec §6.1).
13522864×
    pub fn put_change(&self, c: &Change) -> Result<ObjectRef> {
13532864×
        let encoding = crate::timing::phase("store: encode the change and its texts");
13542864×
        let bytes = c.encode_streaming(|batch| self.put_texts(&batch))?;
13552864×
        drop(encoding);
13562864×
        let _t = crate::timing::phase("store: put the encoding");
13572864×
        self.put(ObjectType::Change, &bytes)
13582864×
    }
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
13804596×
    pub fn get_change(&self, r: &ObjectRef) -> Result<Change> {
13814596×
        Ok(self.get_change_parts(r)?.0)
13824596×
    }
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.
13864712×
    pub fn get_change_parts(&self, r: &ObjectRef) -> Result<(Change, Vec<ObjectRef>)> {
13874712×
        let bytes = self.get_typed(r, ObjectType::Change)?;
13884700×
        let mut parts = Vec::new();
13894700×
        let mut failed = None;
13904700×
        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×
        });
14074700×
        match (decoded, failed) {
14084699×
            (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
        }
14154712×
    }
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`]).
1421537×
    pub fn get_change_lazy(&self, r: &ObjectRef) -> Result<(Change, Vec<crate::objects::TextRef>)> {
1422537×
        let bytes = self.get_typed(r, ObjectType::Change)?;
1423535×
        Change::decode_skeleton(&bytes, *r).map_err(|e| StoreError::Corrupt(*r, e.to_string()))
1424537×
    }
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.
14334258×
    pub fn get_change_meta(&self, r: &ObjectRef) -> Result<crate::state::ChangeMeta> {
14344258×
        if self.metas.borrow().is_none() {
1435909×
            *self.metas.borrow_mut() = Some(self.read_metas_cache());
14363349×
        }
14374258×
        let cached = self.metas.borrow().as_ref().and_then(|m| m.get(r).cloned());
14384258×
        if let Some(meta) = cached {
14393031×
            if self.has(r) {
1440
                #[cfg(test)]
14411649×
                assert_eq!(
1442
                    meta,
14431649×
                    Change::decode_meta(&self.get_typed(r, ObjectType::Change)?).unwrap(),
1444
                    "the metadata cache holds a change's metadata"
1445
                );
14463031×
                return Ok(meta);
14470×
            }
14481227×
        }
14491227×
        let bytes = self.get_typed(r, ObjectType::Change)?;
14501227×
        let meta =
14511227×
            Change::decode_meta(&bytes).map_err(|e| StoreError::Corrupt(*r, e.to_string()))?;
14521227×
        self.remember_meta(r, &meta);
14531227×
        Ok(meta)
14544258×
    }
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.
1461909×
    fn read_metas_cache(&self) -> crate::fasthash::FastMap<ObjectRef, crate::state::ChangeMeta> {
1462909×
        let mut out = crate::fasthash::FastMap::default();
1463909×
        let Ok(bytes) = fs::read(self.scratch.join("metas")) else {
1464353×
            return out;
1465
        };
1466556×
        let mut r = crate::flat::Reader::new(&bytes);
1467556×
        let mut good = 0;
14681919×
        while !r.at_end() {
14691364×
            let mut record = || -> std::result::Result<_, ObjectError> {
14701364×
                let h = r.object()?;
14711363×
                let body = r.bytes()?;
14721363×
                let check = r.fixed::<8>()?;
14731363×
                Ok((h, body, check))
14741364×
            };
14751364×
            let Ok((h, body, check)) = record() else {
14761×
                break;
1477
            };
14781363×
            let mut sum = blake3::Hasher::new();
14791363×
            sum.update(&h.0).update(body);
14801363×
            if sum.finalize().as_bytes()[..8] != check {
14810×
                break;
14821363×
            }
14831363×
            match crate::state::ChangeMeta::read_flat(&mut crate::flat::Reader::new(body)) {
14841363×
                Ok(m) => out.insert(h, m),
14850×
                Err(_) => break,
1486
            };
14871363×
            good += 32 + 4 + body.len() + 8;
1488
        }
1489
        // Cut a bad tail, so records appended later are read.
1490556×
        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));
1495555×
        }
1496556×
        out
1497909×
    }
1498
1499
    /// Add a change's metadata to the cache; quietly nothing when it
1500
    /// cannot be written (it is only a cache).
15011227×
    fn remember_meta(&self, r: &ObjectRef, meta: &crate::state::ChangeMeta) {
15021227×
        let mut body = crate::flat::Writer::default();
15031227×
        meta.write_flat(&mut body);
15041227×
        let mut w = crate::flat::Writer::default();
15051227×
        w.object(r);
15061227×
        w.bytes(&body.0);
15071227×
        let mut sum = blake3::Hasher::new();
15081227×
        sum.update(&r.0).update(&body.0);
15091227×
        w.fixed(&sum.finalize().as_bytes()[..8]);
15101227×
        let _ = fs::OpenOptions::new()
15111227×
            .create(true)
15121227×
            .append(true)
15131227×
            .open(self.scratch.join("metas"))
15141227×
            .and_then(|mut f| f.write_all(&w.0));
15151227×
        if let Some(m) = self.metas.borrow_mut().as_mut() {
15161227×
            m.insert(*r, meta.clone());
15171227×
        }
15181227×
    }
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
1529194×
    pub fn put_chunk(&self, bytes: &[u8]) -> Result<ObjectRef> {
1530194×
        self.put(ObjectType::Chunk, bytes)
1531194×
    }
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.
155172×
    fn nocompress_set(&self) -> Result<std::collections::HashSet<ObjectRef>> {
155272×
        Ok(self
155372×
            .backend
155472×
            .list("nocompress/")
155572×
            .map_err(backend_err)?
155672×
            .into_iter()
155772×
            .filter_map(|e| ObjectRef::from_hex(e.key.trim_start_matches("nocompress/")))
155872×
            .collect())
155972×
    }
1560
15612868×
    pub fn put_state(&self, st: &StateObject) -> Result<ObjectRef> {
15622868×
        self.put(ObjectType::State, &st.encode())
15632868×
    }
1564
15655159×
    pub fn get_state(&self, r: &ObjectRef) -> Result<StateObject> {
15665159×
        Ok(StateObject::decode(&self.get_typed(r, ObjectType::State)?)?)
15675159×
    }
1568
1569328×
    pub fn put_attest(&self, a: &Attest) -> Result<ObjectRef> {
1570328×
        self.put(ObjectType::Attest, &a.encode())
1571328×
    }
1572
1573531×
    pub fn get_attest(&self, r: &ObjectRef) -> Result<Attest> {
1574531×
        Ok(Attest::decode(&self.get_typed(r, ObjectType::Attest)?)?)
1575531×
    }
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.
1587124×
    fn index_add(&self, index: &str, key: &ObjectRef, value: &ObjectRef) -> Result<()> {
1588124×
        let entry = format!("{}{}", fanout_prefix(index, key), value.to_hex());
1589124×
        put_new_or_existing(self.backend.as_ref(), &entry, b"")
1590124×
    }
1591
1592
    /// The values recorded under `key` in `index`, with those an older
1593
    /// store kept as one list in `legacy`, sorted.
15941345×
    fn index_get(&self, index: &str, legacy: &str, key: &ObjectRef) -> Result<Vec<ObjectRef>> {
15951345×
        let mut values: Vec<ObjectRef> = self
15961345×
            .backend
15971345×
            .list(&fanout_prefix(index, key))
15981345×
            .map_err(backend_err)?
15991345×
            .into_iter()
16001345×
            .filter_map(|e| e.key.rsplit('/').next().and_then(ObjectRef::from_hex))
16011345×
            .collect();
16021345×
        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×
            );
16081342×
        }
16091345×
        values.sort();
16101345×
        values.dedup();
16111345×
        Ok(values)
16121345×
    }
1613
1614
    /// Record that seal attestation `attest` covers `change`.
1615119×
    pub fn index_seal(&self, change: &ObjectRef, attest: &ObjectRef) -> Result<()> {
1616119×
        self.index_add("seal", change, attest)
1617119×
    }
1618
1619
    /// Seal attestations known to cover `change`.
16201331×
    pub fn seals_for(&self, change: &ObjectRef) -> Result<Vec<ObjectRef>> {
16211331×
        self.index_get("seal", "seals", change)
16221331×
    }
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
16341×
    pub fn index_approval(&self, state: &ObjectRef, attest: &ObjectRef) -> Result<()> {
16351×
        self.index_add("approval", state, attest)
16361×
    }
1637
1638
    /// Approval attestations recorded for `state` (OxygenFlow approval
1639
    /// gates, oxygenhub#235).
16403×
    pub fn approvals_for(&self, state: &ObjectRef) -> Result<Vec<ObjectRef>> {
16413×
        self.index_get("approval", "approvals", state)
16423×
    }
1643
1644
    /// Every state with an approval, for garbage collection.
164517×
    pub fn approval_states(&self) -> Result<Vec<ObjectRef>> {
164617×
        self.indexed_states("approval", "approvals")
164717×
    }
1648
1649
    /// Every state with a receipt, for garbage collection.
165023×
    pub fn receipt_states(&self) -> Result<Vec<ObjectRef>> {
165123×
        self.indexed_states("receipt", "receipts")
165223×
    }
1653
1654
    /// The states an index (`one/<hh>/<rest>/<attest>` entries, and the
1655
    /// packed `many/<hh>/<rest>` lists) holds attestations for.
165640×
    fn indexed_states(&self, one: &str, many: &str) -> Result<Vec<ObjectRef>> {
165740×
        let mut out: Vec<ObjectRef> = Vec::new();
165840×
        for e in self.backend.list(&format!("{one}/")).map_err(backend_err)? {
1659
            // receipt/<hh>/<rest>/<attest>
16604×
            let mut parts = e.key.splitn(4, '/');
16614×
            let (Some(_), Some(hh), Some(rest), Some(_)) =
16624×
                (parts.next(), parts.next(), parts.next(), parts.next())
1663
            else {
16640×
                continue;
1665
            };
16664×
            out.extend(ObjectRef::from_hex(&format!("{hh}{rest}")));
1667
        }
166840×
        for e in self
166940×
            .backend
167040×
            .list(&format!("{many}/"))
167140×
            .map_err(backend_err)?
1672
        {
16731×
            let mut parts = e.key.splitn(3, '/');
16741×
            let (Some(_), Some(hh), Some(rest)) = (parts.next(), parts.next(), parts.next()) else {
16750×
                continue;
1676
            };
16771×
            out.extend(ObjectRef::from_hex(&format!("{hh}{rest}")));
1678
        }
167940×
        out.sort();
168040×
        out.dedup();
168140×
        Ok(out)
168240×
    }
1683
1684226×
    pub fn put_identity(&self, id: &Identity) -> Result<ObjectRef> {
1685226×
        self.put(ObjectType::Identity, &id.encode())
1686226×
    }
1687
1688677×
    pub fn get_identity(&self, r: &ObjectRef) -> Result<Identity> {
1689677×
        Ok(Identity::decode(&self.get_typed(r, ObjectType::Identity)?)?)
1690677×
    }
1691
1692
    /// Signatures stored alongside object `r` (spec §5.4), one per signing
1693
    /// key, sorted by key. Empty if none.
16942405×
    pub fn signatures(&self, r: &ObjectRef) -> Result<Vec<Signature>> {
16952405×
        let mut sigs: Vec<Signature> = Vec::new();
16962405×
        for e in self
16972405×
            .backend
16982405×
            .list(&fanout_prefix("sig", r))
16992405×
            .map_err(backend_err)?
1700
        {
17011263×
            let bytes = self.backend.get(&e.key).map_err(backend_err)?;
17021263×
            sigs.extend(Signature::decode_list(&bytes)?);
1703
        }
1704
        // An older store's one list per object; a signer kept there and
1705
        // here counts once, as written here.
17062405×
        if let Some(bytes) = get_optional(self.backend.as_ref(), &legacy_key("sigs", r))? {
17072×
            for sig in Signature::decode_list(&bytes)? {
17082×
                if !sigs.iter().any(|s| s.key == sig.key) {
17091×
                    sigs.push(sig);
17101×
                }
1711
            }
17122403×
        }
17132405×
        sigs.sort_by_key(|s| s.key);
17142405×
        sigs.dedup_by_key(|s| s.key);
17152405×
        Ok(sigs)
17162405×
    }
1717
1718
    /// Attach a signature to object `r`, replacing any earlier one by the
1719
    /// same key: one entry per signer, so the latest by a key is the one
1720
    /// kept, and two signers never touch each other's.
1721493×
    pub fn put_signature(&self, r: &ObjectRef, sig: &Signature) -> Result<()> {
1722493×
        let key = format!("{}{}", fanout_prefix("sig", r), sig.key.to_hex());
1723493×
        let bytes = Signature::encode_list(std::slice::from_ref(sig));
1724493×
        if get_optional(self.backend.as_ref(), &key)?.as_deref() == Some(bytes.as_slice()) {
172522×
            return Ok(());
1726471×
        }
1727471×
        delete(self.backend.as_ref(), &key)?;
1728471×
        put_new_or_existing(self.backend.as_ref(), &key, &bytes)
1729493×
    }
1730
1731
    /// Finish packs a writer left unfinished: a batch writes its objects to
1732
    /// `.tmp-ID.pack` and only indexes it at the end, so a process that
1733
    /// stopped part way (an import killed after hours) leaves every object
1734
    /// in a pack nothing can read. Each such pack untouched for `min_age`
1735
    /// is read through: every whole entry checked against its reference,
1736
    /// a torn last one cut off, then indexed as a pack of the store.
1737
    /// Returns the packs and objects adopted.
17382×
    pub fn adopt_unfinished_packs(
17392×
        &self,
17402×
        min_age: std::time::Duration,
17412×
        progress: &dyn Fn(&str),
17422×
    ) -> Result<(usize, usize)> {
1743
        use std::io::{BufReader, Read};
17442×
        let mut packs = 0;
17452×
        let mut objects = 0;
17462×
        let Ok(dir) = fs::read_dir(&self.scratch) else {
17470×
            return Ok((0, 0));
1748
        };
17494×
        for entry in dir.flatten() {
17504×
            let name = entry.file_name().to_string_lossy().to_string();
17514×
            let Some(id) = name
17524×
                .strip_prefix(".tmp-")
17534×
                .and_then(|n| n.strip_suffix(".pack"))
1754
            else {
17552×
                continue;
1756
            };
17572×
            let path = entry.path();
17582×
            let meta = fs::metadata(&path)?;
17592×
            let age = meta
17602×
                .modified()
17612×
                .ok()
17622×
                .and_then(|m| m.elapsed().ok())
17632×
                .unwrap_or_default();
17642×
            if age < min_age {
17651×
                progress(&format!(
17661×
                    "{name}: written to {}s ago, left alone",
17671×
                    age.as_secs()
17681×
                ));
17691×
                continue;
17701×
            }
17711×
            let mut f = BufReader::with_capacity(1 << 20, fs::File::open(&path)?);
17721×
            let mut magic = [0u8; 8];
17731×
            if f.read_exact(&mut magic).is_err() || &magic != PACK_MAGIC {
17740×
                progress(&format!("{name}: not a pack, left alone"));
17750×
                continue;
17761×
            }
17771×
            let mut offset = PACK_MAGIC.len() as u64;
17781×
            let mut index: Vec<(ObjectRef, PackEntry)> = Vec::new();
1779
            loop {
1780301×
                let mut head = [0u8; 42];
1781301×
                if f.read_exact(&mut head).is_err() {
17820×
                    break;
1783301×
                }
1784301×
                let Some(ty) = ObjectType::ALL.get(head[0] as usize).copied() else {
17850×
                    break;
1786
                };
1787301×
                let flags = head[1];
1788301×
                let stored_len = u32::from_le_bytes(head[2..6].try_into().unwrap());
1789301×
                let raw_len = u32::from_le_bytes(head[6..10].try_into().unwrap());
1790301×
                let r = ObjectRef(head[10..42].try_into().unwrap());
1791301×
                let mut stored = vec![0u8; stored_len as usize];
1792301×
                if flags & FLAG_DICT != 0 || f.read_exact(&mut stored).is_err() {
17931×
                    break;
1794300×
                }
1795300×
                let e = PackEntry {
1796300×
                    offset: offset + 42,
1797300×
                    stored_len,
1798300×
                    raw_len,
1799300×
                    ty,
1800300×
                    flags,
1801300×
                };
1802300×
                if decode_entry(&r, e, stored, None).is_err() {
18030×
                    break;
1804300×
                }
1805300×
                index.push((r, e));
1806300×
                offset += 42 + stored_len as u64;
1807300×
                if index.len().is_multiple_of(200_000) {
18080×
                    progress(&format!(
18090×
                        "{name}: {} objects checked, {} MiB",
18100×
                        index.len(),
18110×
                        offset >> 20
18120×
                    ));
1813300×
                }
1814
            }
18151×
            if index.is_empty() {
18160×
                progress(&format!("{name}: no whole object, left alone"));
18170×
                continue;
18181×
            }
18191×
            if offset < meta.len() {
18201×
                progress(&format!(
18211×
                    "{name}: {} torn bytes at the end cut off",
18221×
                    meta.len() - offset
18231×
                ));
18241×
                fs::OpenOptions::new()
18251×
                    .write(true)
18261×
                    .open(&path)?
18271×
                    .set_len(offset)?;
18280×
            }
18291×
            index.sort_by_key(|(r, _)| *r);
18301×
            index.dedup_by_key(|(r, _)| *r);
18311×
            objects += index.len();
18321×
            packs += 1;
18331×
            progress(&format!("{name}: {} objects indexed", index.len()));
18341×
            self.finish_pack_files(id, &path, &index)?;
1835
        }
18362×
        Ok((packs, objects))
18372×
    }
1838
1839
    /// Every object reference in the store, loose and packed (slow; for gc and tests).
184086×
    pub fn list(&self) -> io::Result<Vec<ObjectRef>> {
184186×
        let mut out: Vec<ObjectRef> = self
184286×
            .loose_objects()
184386×
            .map_err(|e| io::Error::other(e.to_string()))?
184486×
            .into_iter()
184586×
            .map(|(r, _)| r)
184686×
            .collect();
184786×
        for p in self.packs.borrow().iter() {
184810×
            out.extend(p.refs.iter().copied());
184910×
        }
185086×
        out.sort();
185186×
        out.dedup();
185286×
        Ok(out)
185386×
    }
1854
}
1855
1856
/// A loose object's bytes, verified against `r`.
185747210×
fn parse_loose(data: &[u8], r: &ObjectRef) -> Result<Object> {
185847210×
    let nul = data
185947210×
        .iter()
1860670939×
        .position(|&b| b == 0)
186147210×
        .ok_or_else(|| StoreError::Corrupt(*r, "no header".into()))?;
186247210×
    let head = std::str::from_utf8(&data[..nul])
186347210×
        .map_err(|_| StoreError::Corrupt(*r, "header not UTF-8".into()))?;
186447210×
    let mut parts = head.split(' ');
186547210×
    let (Some("oxy1"), Some(ty), Some(len), None) =
186647210×
        (parts.next(), parts.next(), parts.next(), parts.next())
1867
    else {
18680×
        return Err(StoreError::Corrupt(*r, format!("bad header {head:?}")));
1869
    };
187047210×
    let ty = ObjectType::from_name(ty)
187147210×
        .ok_or_else(|| StoreError::Corrupt(*r, format!("unknown type {ty}")))?;
187247210×
    let len: usize = len
187347210×
        .parse()
187447210×
        .map_err(|_| StoreError::Corrupt(*r, "bad length".into()))?;
187547210×
    let body = &data[nul + 1..];
187647210×
    if body.len() != len {
18770×
        return Err(StoreError::Corrupt(
18780×
            *r,
18790×
            format!("length {} != header {len}", body.len()),
18800×
        ));
188147210×
    }
188247210×
    if hash_object(ty, body) != *r {
18834×
        return Err(StoreError::Corrupt(*r, "hash mismatch".into()));
188447206×
    }
188547206×
    Ok((ty, body.to_vec()))
188647210×
}
1887
1888
/// Whether the objects are files that a test may tamper with: not under
1889
/// `OXY_STORE_BACKEND=memory`.
1890
#[cfg(test)]
18916×
fn files_on_disk() -> bool {
18926×
    std::env::var_os("OXY_STORE_BACKEND").is_none()
18936×
}
1894
1895
#[cfg(test)]
1896
mod tests {
1897
    use super::*;
1898
1899
    /// The store under test twice: in a directory, and on a store in
1900
    /// memory with a scratch directory, as over a bucket.
19016×
    fn each_store(dir: &Path, f: impl Fn(&str, Store)) {
19026×
        f("directory", Store::open(dir.join("objects")).unwrap());
19036×
        f(
19046×
            "memory",
19056×
            Store::open_on(Arc::new(MemoryStore::new()), dir.join("scratch")).unwrap(),
19066×
        );
19076×
    }
1908
1909
    #[test]
19101×
    fn put_get_verify() {
19111×
        if !super::files_on_disk() {
19120×
            return;
19131×
        }
19141×
        let dir = tempfile::tempdir().unwrap();
19151×
        let s = Store::open(dir.path().join("objects")).unwrap();
19161×
        let r = s.put(ObjectType::Chunk, b"hello").unwrap();
19171×
        assert!(s.has(&r));
19181×
        assert_eq!(s.get(&r).unwrap(), (ObjectType::Chunk, b"hello".to_vec()));
19191×
        assert_eq!(s.put(ObjectType::Chunk, b"hello").unwrap(), r);
19201×
        assert_eq!(s.list().unwrap(), vec![r]);
19211×
        assert!(matches!(
19221×
            s.get_typed(&r, ObjectType::Blob),
1923
            Err(StoreError::WrongType(..))
1924
        ));
19251×
        assert!(matches!(
19261×
            s.get(&ObjectRef([9; 32])),
1927
            Err(StoreError::NotFound(_))
1928
        ));
1929
1930
        // Tamper: flip a byte, read must fail.
19311×
        let path = s.path_for(&r);
19321×
        let mut data = fs::read(&path).unwrap();
19331×
        let last = data.len() - 1;
19341×
        data[last] ^= 1;
19351×
        fs::write(&path, data).unwrap();
19361×
        assert!(matches!(s.get(&r), Err(StoreError::Corrupt(..))));
19371×
    }
1938
1939
    #[test]
19401×
    fn packing_keeps_every_object_readable() {
19411×
        if !super::files_on_disk() {
19420×
            return;
19431×
        }
19441×
        let dir = tempfile::tempdir().unwrap();
19451×
        let s = Store::open(dir.path()).unwrap();
19461×
        let mut refs = Vec::new();
1947300×
        for i in 0..300u32 {
1948300×
            let body = format!("object {i} ").repeat(1 + (i % 7) as usize);
1949300×
            refs.push((s.put(ObjectType::Chunk, body.as_bytes()).unwrap(), body));
1950300×
        }
19511×
        let c = crate::objects::tests::sample_change();
19521×
        let cr = s.put_change(&c).unwrap();
19531×
        assert_eq!(s.loose_count().unwrap(), 301);
19541×
        let report = s.pack_loose().unwrap();
19551×
        assert_eq!(report.objects, 301);
19561×
        assert!(report.packed_bytes < report.raw_bytes, "{report:?}");
19571×
        assert_eq!(s.loose_count().unwrap(), 0);
19581×
        assert_eq!(s.pack_count(), 1);
1959300×
        for (r, body) in &refs {
1960300×
            assert!(s.has(r));
1961300×
            assert_eq!(
1962300×
                s.get(r).unwrap(),
1963300×
                (ObjectType::Chunk, body.as_bytes().to_vec())
1964
            );
1965
        }
19661×
        assert_eq!(s.get_change(&cr).unwrap(), c);
19671×
        assert_eq!(s.list().unwrap().len(), 301);
1968
        // Re-putting a packed object is a no-op; new objects go loose and a
1969
        // second pack coexists with the first.
19701×
        assert_eq!(
19711×
            s.put(ObjectType::Chunk, refs[0].1.as_bytes()).unwrap(),
19721×
            refs[0].0
1973
        );
19741×
        assert_eq!(s.loose_count().unwrap(), 0);
19751×
        let extra = s.put(ObjectType::Chunk, b"after packing").unwrap();
19761×
        s.pack_loose().unwrap();
19771×
        assert_eq!(s.pack_count(), 2);
19781×
        assert_eq!(s.get(&extra).unwrap().1, b"after packing");
1979
        // A reopened store sees the packs.
19801×
        let s2 = Store::open(dir.path()).unwrap();
19811×
        assert_eq!(s2.pack_count(), 2);
19821×
        assert_eq!(s2.get(&refs[5].0).unwrap().1, refs[5].1.as_bytes());
19831×
        assert!(matches!(
19841×
            s2.get(&ObjectRef([9; 32])),
1985
            Err(StoreError::NotFound(_))
1986
        ));
1987
        // Corrupting an object's body inside the pack is detected on read.
19881×
        let target = refs[5].0;
19891×
        let (pack_path, offset) = {
19901×
            let packs = s2.packs.borrow();
19911×
            let (i, e) = s2.find_packed(&target).unwrap();
19921×
            (dir.path().join(&packs[i].key), e.offset as usize)
19931×
        };
19941×
        let mut data = fs::read(&pack_path).unwrap();
19951×
        data[offset] ^= 0xff;
19961×
        fs::write(&pack_path, data).unwrap();
19971×
        let s3 = Store::open(dir.path()).unwrap();
19981×
        assert!(matches!(s3.get(&target), Err(StoreError::Corrupt(..))));
19991×
        assert_eq!(
20001×
            s3.get(&refs[6].0).unwrap().1,
20011×
            refs[6].1.as_bytes(),
2002
            "other objects are unaffected"
2003
        );
20041×
    }
2005
2006
    #[test]
20071×
    fn a_full_repack_trains_a_dictionary_and_reads_back() {
20081×
        if !super::files_on_disk() {
20090×
            return;
20101×
        }
20111×
        let dir = tempfile::tempdir().unwrap();
20121×
        let s = Store::open(dir.path()).unwrap();
2013
        // Many small, alike files: what a dictionary is for.
20141×
        let bodies: Vec<Vec<u8>> = (0..1500)
20151500×
            .map(|i| {
20161500×
                format!(
2017
                    "// SPDX-License-Identifier: GPL-2.0\n#include <linux/module.h>\n\
2018
                     static int probe_{i}(struct device *dev)\n{{\n\treturn {i};\n}}\n"
2019
                )
20201500×
                .into_bytes()
20211500×
            })
20221×
            .collect();
20231×
        let refs: Vec<ObjectRef> = bodies
20241×
            .iter()
20251500×
            .map(|b| s.put(ObjectType::Chunk, b).unwrap())
20261×
            .collect();
20271×
        s.repack_all(REPACK_ZSTD_LEVEL).unwrap();
20281×
        let dicts = fs::read_dir(dir.path())
20291×
            .unwrap()
20301×
            .flatten()
20313×
            .filter(|e| e.path().extension().is_some_and(|x| x == "dict"))
20321×
            .count();
20331×
        assert_eq!(dicts, 1, "the pack has a dictionary");
20341×
        let with_dict = refs
20351×
            .iter()
20361500×
            .filter(|r| s.find_packed(r).unwrap().1.flags & FLAG_DICT != 0)
20371×
            .count();
20381×
        assert!(with_dict > 1000, "most use it: {with_dict}");
20391×
        let again = Store::open(dir.path()).unwrap();
20401500×
        for (r, b) in refs.iter().zip(&bodies) {
20411500×
            assert_eq!(&again.get(r).unwrap().1, b);
2042
        }
2043
        // A repack after that replaces the pack and its dictionary.
20441×
        again.repack_all(REPACK_ZSTD_LEVEL).unwrap();
20451×
        let files: Vec<String> = fs::read_dir(dir.path())
20461×
            .unwrap()
20471×
            .flatten()
20484×
            .map(|e| e.file_name().to_string_lossy().into_owned())
20494×
            .filter(|n| n.starts_with("pack-"))
20501×
            .collect();
20511×
        assert_eq!(files.len(), 3, "one pack, index and dictionary: {files:?}");
20521×
        assert_eq!(&again.get(&refs[7]).unwrap().1, &bodies[7]);
20531×
    }
2054
2055
    #[test]
20561×
    fn nocompress_chunks_pack_raw() {
20571×
        let dir = tempfile::tempdir().unwrap();
20581×
        let s = Store::open(dir.path()).unwrap();
20591×
        let body = vec![b'a'; 10_000];
20601×
        let raw = s.put_chunk_nocompress(&body).unwrap();
20611×
        let compressible = s.put(ObjectType::Chunk, &vec![b'b'; 10_000]).unwrap();
20621×
        s.pack_loose().unwrap();
20631×
        let packs = s.packs.borrow();
20641×
        let (i, e) = s.find_packed(&raw).unwrap();
20651×
        assert_eq!((e.flags, e.stored_len as usize), (0, 10_000));
20661×
        let (_, c) = s.find_packed(&compressible).unwrap();
20671×
        assert_eq!(c.flags, FLAG_ZSTD);
20681×
        assert!(c.stored_len < 10_000);
20691×
        assert_eq!(packs[i].fetch(s.backend.as_ref(), &raw, e).unwrap().1, body);
20701×
    }
2071
2072
    #[test]
20731×
    fn many_packs_merge_into_one() {
20741×
        let dir = tempfile::tempdir().unwrap();
20752×
        each_store(dir.path(), |which, s| {
20762×
            let mut refs = Vec::new();
207736×
            for i in 0..(MAX_PACKS + 2) {
207836×
                refs.push(
207936×
                    s.put(ObjectType::Chunk, format!("pack {i}").as_bytes())
208036×
                        .unwrap(),
208136×
                );
208236×
                s.pack_loose().unwrap();
208336×
            }
20842×
            assert_eq!(s.pack_count(), MAX_PACKS + 2, "{which}");
20852×
            assert_eq!(s.merge_packs().unwrap(), MAX_PACKS + 2);
20862×
            assert_eq!(s.pack_count(), 1);
20872×
            assert_eq!(s.merge_packs().unwrap(), 0);
208836×
            for (i, r) in refs.iter().enumerate() {
208936×
                assert_eq!(s.get(r).unwrap().1, format!("pack {i}").as_bytes());
2090
            }
20912×
            let again = Store::open_on(s.backend().clone(), s.dir()).unwrap();
20922×
            assert_eq!(again.pack_count(), 1, "{which}: reopened");
20932×
        });
20941×
    }
2095
2096
    #[test]
20971×
    fn prune_removes_unreachable_loose_and_packed_objects() {
2098
        use std::collections::HashSet;
20991×
        let dir = tempfile::tempdir().unwrap();
21002×
        each_store(dir.path(), |which, s| {
21012×
            let keep_a = s.put(ObjectType::Chunk, b"keep a").unwrap();
21022×
            let drop_a = s.put(ObjectType::Chunk, b"drop a").unwrap();
21032×
            s.pack_loose().unwrap();
21042×
            let keep_b = s.put(ObjectType::Chunk, b"keep b").unwrap();
21052×
            let drop_b = s.put(ObjectType::Chunk, b"drop b").unwrap();
21062×
            let sk = crate::identity::SecretKey {
21072×
                ed_seed: [1; 32],
21082×
                ml_seed: [2; 32],
21092×
            };
21102×
            let id = sk.identity("a", "b", 0);
21112×
            let key = s.put_identity(&id).unwrap();
21122×
            s.put_signature(
21132×
                &drop_b,
21142×
                &sk.sign(crate::identity::Domain::Change, &key, &drop_b),
2115
            )
21162×
            .unwrap();
21172×
            s.index_seal(&drop_a, &ObjectRef([3; 32])).unwrap();
21182×
            let keep: HashSet<ObjectRef> = [keep_a, keep_b, key].into_iter().collect();
2119
            // Everything is too young under a grace period.
21202×
            let r = s
21212×
                .prune(&keep, std::time::Duration::from_secs(3600))
21222×
                .unwrap();
21232×
            assert_eq!((r.objects, r.deferred), (0, 2), "{which}");
21242×
            let r = s.prune(&keep, std::time::Duration::ZERO).unwrap();
21252×
            assert_eq!(r.objects, 2, "{which}: {r:?}");
21262×
            assert!(s.has(&keep_a) && s.has(&keep_b) && s.has(&key));
21272×
            assert!(!s.has(&drop_a) && !s.has(&drop_b));
21282×
            assert!(s.signatures(&drop_b).unwrap().is_empty());
21292×
            assert!(s.seals_for(&drop_a).unwrap().is_empty());
21302×
            assert_eq!(s.pack_count(), 1);
21312×
            assert_eq!(s.get(&keep_a).unwrap().1, b"keep a");
21322×
            assert_eq!(s.list().unwrap().len(), 3);
21332×
        });
21341×
    }
2135
2136
    #[test]
21371×
    fn signatures_are_stored_beside_objects() {
2138
        use crate::identity::{Domain, SecretKey};
21391×
        let dir = tempfile::tempdir().unwrap();
21402×
        each_store(dir.path(), |which, s| {
21412×
            let r = s.put(ObjectType::Chunk, b"x").unwrap();
21422×
            assert!(s.signatures(&r).unwrap().is_empty());
21432×
            let sk = SecretKey {
21442×
                ed_seed: [1; 32],
21452×
                ml_seed: [2; 32],
21462×
            };
21472×
            let id = sk.identity("a", "b", 0);
21482×
            let key = s.put_identity(&id).unwrap();
21492×
            assert_eq!(s.get_identity(&key).unwrap(), id);
21502×
            let sig = sk.sign(Domain::Change, &key, &r);
21512×
            s.put_signature(&r, &sig).unwrap();
21522×
            s.put_signature(&r, &sig).unwrap();
21532×
            assert_eq!(s.signatures(&r).unwrap(), vec![sig.clone()], "{which}");
2154
            // A second signer is kept beside the first, sorted by key.
21552×
            let sk2 = SecretKey {
21562×
                ed_seed: [3; 32],
21572×
                ml_seed: [4; 32],
21582×
            };
21592×
            let key2 = s.put_identity(&sk2.identity("c", "d", 0)).unwrap();
21602×
            let sig2 = sk2.sign(Domain::Change, &key2, &r);
21612×
            s.put_signature(&r, &sig2).unwrap();
21622×
            let mut both = vec![sig.clone(), sig2.clone()];
21632×
            both.sort_by_key(|s| s.key);
21642×
            assert_eq!(s.signatures(&r).unwrap(), both);
2165
            // The object itself is untouched by its signatures.
21662×
            assert_eq!(s.get(&r).unwrap().1, b"x");
2167
            // Seal and receipt entries, and the states with receipts.
21682×
            s.index_seal(&r, &ObjectRef([5; 32])).unwrap();
21692×
            s.index_seal(&r, &ObjectRef([4; 32])).unwrap();
21702×
            s.index_seal(&r, &ObjectRef([5; 32])).unwrap();
21712×
            assert_eq!(
21722×
                s.seals_for(&r).unwrap(),
21732×
                vec![ObjectRef([4; 32]), ObjectRef([5; 32])]
2174
            );
21752×
            let st = ObjectRef([6; 32]);
21762×
            s.index_receipt(&st, &ObjectRef([7; 32])).unwrap();
21772×
            assert_eq!(s.receipts_for(&st).unwrap(), vec![ObjectRef([7; 32])]);
21782×
            assert_eq!(s.receipt_states().unwrap(), vec![st]);
21792×
        });
21801×
    }
2181
2182
    /// A store written before signatures, seals and receipts were one
2183
    /// entry each (`sigs/`, `seals/`, `receipts/` lists) still reads, and
2184
    /// what is written now sits beside what was there.
2185
    #[test]
21861×
    fn an_older_store_s_sidecar_lists_are_still_read() {
21871×
        if !super::files_on_disk() {
21880×
            return;
21891×
        }
2190
        use crate::identity::{Domain, SecretKey};
21911×
        let dir = tempfile::tempdir().unwrap();
21921×
        let s = Store::open(dir.path()).unwrap();
21931×
        let r = s.put(ObjectType::Chunk, b"old").unwrap();
21941×
        let h = r.to_hex();
21951×
        let sk = SecretKey {
21961×
            ed_seed: [1; 32],
21971×
            ml_seed: [2; 32],
21981×
        };
21991×
        let key = s.put_identity(&sk.identity("a", "b", 0)).unwrap();
22001×
        let sig = sk.sign(Domain::Change, &key, &r);
22011×
        let legacy = dir.path().join("sigs").join(&h[..2]);
22021×
        fs::create_dir_all(&legacy).unwrap();
22031×
        fs::write(
22041×
            legacy.join(&h[2..]),
22051×
            Signature::encode_list(std::slice::from_ref(&sig)),
2206
        )
22071×
        .unwrap();
22081×
        let seals = dir.path().join("seals").join(&h[..2]);
22091×
        fs::create_dir_all(&seals).unwrap();
22101×
        fs::write(
22111×
            seals.join(&h[2..]),
22121×
            format!("{}\n", ObjectRef([9; 32]).to_hex()),
2213
        )
22141×
        .unwrap();
22151×
        let receipts = dir.path().join("receipts").join(&h[..2]);
22161×
        fs::create_dir_all(&receipts).unwrap();
22171×
        fs::write(
22181×
            receipts.join(&h[2..]),
22191×
            format!("{}\n", ObjectRef([8; 32]).to_hex()),
2220
        )
22211×
        .unwrap();
2222
22231×
        assert_eq!(s.signatures(&r).unwrap(), vec![sig.clone()]);
22241×
        assert_eq!(s.seals_for(&r).unwrap(), vec![ObjectRef([9; 32])]);
22251×
        assert_eq!(s.receipts_for(&r).unwrap(), vec![ObjectRef([8; 32])]);
22261×
        assert_eq!(s.receipt_states().unwrap(), vec![r]);
2227
        // New entries join the old ones; the same signer is not doubled.
22281×
        s.put_signature(&r, &sig).unwrap();
22291×
        s.index_seal(&r, &ObjectRef([1; 32])).unwrap();
22301×
        assert_eq!(s.signatures(&r).unwrap().len(), 1);
22311×
        assert_eq!(
22321×
            s.seals_for(&r).unwrap(),
22331×
            vec![ObjectRef([1; 32]), ObjectRef([9; 32])]
2234
        );
2235
        // Pruning the object takes both layouts with it.
22361×
        let r2 = s.put(ObjectType::Chunk, b"kept").unwrap();
22371×
        let keep = [r2, key].into_iter().collect();
22381×
        s.prune(&keep, std::time::Duration::ZERO).unwrap();
22391×
        assert!(s.signatures(&r).unwrap().is_empty());
22401×
        assert!(s.seals_for(&r).unwrap().is_empty());
22411×
        assert!(s.receipt_states().unwrap().is_empty());
22421×
    }
2243
2244
    #[test]
22451×
    fn change_round_trip_through_store() {
22461×
        let dir = tempfile::tempdir().unwrap();
22472×
        each_store(dir.path(), |which, s| {
22482×
            let c = crate::objects::tests::sample_change();
22492×
            let r = s.put_change(&c).unwrap();
22502×
            assert_eq!(r, c.hash(), "{which}");
22512×
            assert_eq!(s.get_change(&r).unwrap(), c);
22522×
            assert_eq!(s.get_change_meta(&r).unwrap().message, c.message);
22532×
        });
22541×
    }
2255
22568057203×
    fn xorshift(state: &mut u64) -> u64 {
22578057203×
        *state ^= *state << 13;
22588057203×
        *state ^= *state >> 7;
22598057203×
        *state ^= *state << 17;
22608057203×
        *state
22618057203×
    }
2262
2263
    /// Random corruption of pack and index files never panics: reads fail
2264
    /// with an error or the store refuses to open, and untouched objects
2265
    /// stay readable when the index survives.
2266
    #[test]
22671×
    fn corrupted_packs_and_indexes_fail_cleanly() {
22681×
        if !super::files_on_disk() {
22690×
            return;
22701×
        }
22711×
        let dir = tempfile::tempdir().unwrap();
22721×
        let objects = dir.path().join("objects");
22731×
        let s = Store::open(&objects).unwrap();
22741×
        let mut refs = Vec::new();
22751×
        let mut seed = 0x9e3779b97f4a7c15u64;
227640×
        for i in 0..40u32 {
227740×
            let len = (xorshift(&mut seed) % 5000) as usize;
227840×
            let mut body = vec![0u8; len];
2279104686×
            for b in body.iter_mut() {
2280104686×
                *b = if i % 2 == 0 {
228156338×
                    (xorshift(&mut seed) & 0xff) as u8
2282
                } else {
228348348×
                    b'a' + (i % 26) as u8
2284
                };
2285
            }
228640×
            refs.push(s.put(ObjectType::Chunk, &body).unwrap());
2287
        }
22881×
        s.pack_loose().unwrap();
22891×
        let pack = fs::read_dir(&objects)
22901×
            .unwrap()
22912×
            .filter_map(|e| e.ok().map(|e| e.path()))
22922×
            .find(|p| p.extension().is_some_and(|x| x == "pack"))
22931×
            .unwrap();
22941×
        let idx = pack.with_extension("idx");
22951×
        let pristine_pack = fs::read(&pack).unwrap();
22961×
        let pristine_idx = fs::read(&idx).unwrap();
2297
2298300×
        for round in 0..300u32 {
2299300×
            let (path, pristine) = if round % 2 == 0 {
2300150×
                (&pack, &pristine_pack)
2301
            } else {
2302150×
                (&idx, &pristine_idx)
2303
            };
2304300×
            let mut data = pristine.clone();
2305300×
            match xorshift(&mut seed) % 4 {
230681×
                0 => {
230781×
                    let at = (xorshift(&mut seed) as usize) % data.len();
230881×
                    data[at] ^= 1 << (xorshift(&mut seed) % 8);
230981×
                }
231073×
                1 => {
231173×
                    let at = (xorshift(&mut seed) as usize) % data.len();
231273×
                    data[at] = (xorshift(&mut seed) & 0xff) as u8;
231373×
                }
231475×
                2 => {
231575×
                    let keep = (xorshift(&mut seed) as usize) % data.len();
231675×
                    data.truncate(keep);
231775×
                }
2318
                _ => {
231971×
                    let at = (xorshift(&mut seed) as usize) % data.len();
232071×
                    let n = ((xorshift(&mut seed) % 8) + 1) as usize;
2321324×
                    for k in 0..n.min(data.len() - at) {
2322324×
                        data[at + k] = 0xff;
2323324×
                    }
2324
                }
2325
            }
2326300×
            fs::write(path, &data).unwrap();
2327
            // Opening may refuse a broken index; a store that opens must
2328
            // either return each object intact or report it corrupt/missing.
2329300×
            if let Ok(s2) = Store::open(&objects) {
23307640×
                for r in &refs {
23317640×
                    match s2.get(r) {
23327452×
                        Ok((ty, body)) => assert_eq!(
23337452×
                            hash_object(ty, &body),
2334
                            *r,
2335
                            "a returned object always matches its reference"
2336
                        ),
2337
                        Err(StoreError::Corrupt(..))
2338
                        | Err(StoreError::NotFound(_))
2339188×
                        | Err(StoreError::Io(_)) => {}
23400×
                        Err(e) => panic!("unexpected error {e}"),
2341
                    }
2342
                }
2343109×
            }
2344300×
            fs::write(path, pristine).unwrap();
2345
        }
2346
        // Restored files read back in full.
23471×
        let s3 = Store::open(&objects).unwrap();
234840×
        for r in &refs {
234940×
            let (ty, body) = s3.get(r).unwrap();
235040×
            assert_eq!(hash_object(ty, &body), *r);
2351
        }
23521×
    }
2353
2354
    /// A small batch becomes loose objects; a large one becomes a single
2355
    /// pack. Objects are readable while pending, and batches nest.
2356
    #[test]
23571×
    fn batches_write_loose_or_one_pack() {
23581×
        let dir = tempfile::tempdir().unwrap();
23592×
        each_store(dir.path(), |which, s| {
23602×
            let outer = s.begin_batch().unwrap();
23612×
            let a = s.put(ObjectType::Chunk, b"small a").unwrap();
2362
            {
23632×
                let inner = s.begin_batch().unwrap();
23642×
                let b = s.put(ObjectType::Chunk, b"small b").unwrap();
23652×
                assert!(s.has(&b));
23662×
                assert_eq!(s.get(&b).unwrap().1, b"small b");
23672×
                inner.finish().unwrap();
23682×
                assert_eq!(
23692×
                    s.loose_count().unwrap(),
2370
                    0,
2371
                    "{which}: the inner batch defers to the outer one"
2372
                );
2373
            }
23742×
            assert_eq!(s.get(&a).unwrap().1, b"small a");
23752×
            assert_eq!(
23762×
                s.put(ObjectType::Chunk, b"small a").unwrap(),
2377
                a,
2378
                "idempotent while pending"
2379
            );
23802×
            outer.finish().unwrap();
23812×
            assert_eq!(s.loose_count().unwrap(), 2);
23822×
            assert_eq!(s.pack_count(), 0);
23832×
            assert_eq!(s.get(&a).unwrap().1, b"small a");
2384
2385
            // Large: spills into one pack, readable during and after.
23862×
            let big = s.begin_batch().unwrap();
23872×
            let mut refs = Vec::new();
23882×
            let mut seed = 7u64;
2389600×
            for i in 0..300u32 {
2390600×
                let mut body = vec![b'z'; 40_000];
2391600×
                if i % 3 == 0 {
23928000000×
                    for b in body.iter_mut() {
23938000000×
                        *b = (xorshift(&mut seed) & 0xff) as u8;
23948000000×
                    }
2395400×
                }
2396600×
                body[..4].copy_from_slice(&i.to_le_bytes());
2397600×
                let r = if i % 5 == 0 {
2398120×
                    s.put_chunk_nocompress(&body).unwrap()
2399
                } else {
2400480×
                    s.put(ObjectType::Chunk, &body).unwrap()
2401
                };
2402600×
                assert_eq!(
2403600×
                    s.get(&r).unwrap().1,
2404
                    body,
2405
                    "readable while pending (object {i})"
2406
                );
2407600×
                refs.push((r, body));
2408
            }
24092×
            assert!(s.has(&refs[0].0));
24102×
            big.finish().unwrap();
24112×
            assert_eq!(s.pack_count(), 1);
24122×
            assert_eq!(
24132×
                s.loose_count().unwrap(),
2414
                2,
2415
                "nothing from the big batch is loose"
2416
            );
24172×
            assert!(fs::read_dir(s.dir())
24182×
                .unwrap()
24192×
                .flatten()
24204×
                .all(|e| !e.file_name().to_string_lossy().contains("tmp-")));
24212×
            let s2 = Store::open_on(s.backend().clone(), s.dir()).unwrap();
2422600×
            for (r, body) in &refs {
2423600×
                assert_eq!(s2.get(r).unwrap().1, *body);
2424
            }
2425
            // A dropped batch still writes its objects.
24262×
            {
24272×
                let _b = s2.begin_batch().unwrap();
24282×
                s2.put(ObjectType::Chunk, b"dropped").unwrap();
24292×
            }
24302×
            assert_eq!(
24312×
                s2.get(&hash_object(ObjectType::Chunk, b"dropped"))
24322×
                    .unwrap()
2433
                    .1,
2434
                b"dropped"
2435
            );
24362×
        });
24371×
    }
2438
2439
    #[test]
24401×
    fn get_many_reads_loose_and_packed_objects_in_order() {
24411×
        let dir = tempfile::tempdir().unwrap();
24422×
        each_store(dir.path(), |which, s| {
24432×
            let packed: Vec<ObjectRef> = (0..20)
244440×
                .map(|i| {
244540×
                    s.put(ObjectType::Chunk, format!("packed {i}").as_bytes())
244640×
                        .unwrap()
244740×
                })
24482×
                .collect();
24492×
            s.pack_loose().unwrap();
24502×
            let loose: Vec<ObjectRef> = (0..20)
245140×
                .map(|i| {
245240×
                    s.put(ObjectType::Chunk, format!("loose {i}").as_bytes())
245340×
                        .unwrap()
245440×
                })
24552×
                .collect();
24562×
            let missing = hash_object(ObjectType::Chunk, b"never stored");
24572×
            let mut refs: Vec<ObjectRef> = Vec::new();
245840×
            for i in 0..20 {
245940×
                refs.push(loose[i]);
246040×
                refs.push(packed[i]);
246140×
            }
24622×
            refs.push(missing);
24632×
            let got = s.get_many(&refs);
24642×
            assert_eq!(got.len(), refs.len());
246580×
            for (i, r) in refs.iter().enumerate().take(40) {
246680×
                let want = if i % 2 == 0 {
246740×
                    format!("loose {}", i / 2)
2468
                } else {
246940×
                    format!("packed {}", i / 2)
2470
                };
247180×
                let (ty, body) = got[i].as_ref().unwrap();
247280×
                assert_eq!(
247380×
                    (*ty, body.as_slice()),
247480×
                    (ObjectType::Chunk, want.as_bytes()),
2475
                    "{which}: {r:?}"
2476
                );
2477
            }
24782×
            assert!(matches!(got[40], Err(StoreError::NotFound(_))));
24792×
        });
24801×
    }
2481
}
2482
2483
#[cfg(test)]
2484
mod batch_tests {
2485
    use super::*;
2486
2487
    #[test]
24881×
    fn a_large_batch_packs_every_object_and_indexes_them_all() {
24891×
        let dir = tempfile::tempdir().unwrap();
24901×
        let store = Store::open(dir.path()).unwrap();
24911×
        let mut refs = Vec::new();
2492
        {
24931×
            let batch = store.begin_batch().unwrap();
24941000×
            for i in 0..1000u32 {
24951000×
                let body = format!("object {i} {}", "x".repeat(20_000 + i as usize)).into_bytes();
24961000×
                refs.push(store.put(ObjectType::Blob, &body).unwrap());
24971000×
            }
24981×
            batch.finish().unwrap();
2499
        }
25001×
        let again = Store::open(dir.path()).unwrap();
25011000×
        for r in &refs {
25021000×
            again
25031000×
                .get(r)
25041000×
                .unwrap_or_else(|e| panic!("{}: {e}", r.short(12)));
2505
        }
25061×
    }
2507
2508
    #[test]
25091×
    fn a_pack_a_stopped_batch_left_is_adopted_and_its_torn_end_cut() {
2510
        // oxygen#79: a batch never finished (a process killed part way)
2511
        // leaves its objects in an unindexed .tmp pack.
25121×
        let dir = tempfile::tempdir().unwrap();
25131×
        let mut refs = Vec::new();
2514
        {
25151×
            let store = Store::open(dir.path()).unwrap();
25161×
            let batch = store.begin_batch().unwrap();
2517300×
            for i in 0..300u32 {
2518300×
                let body = format!("object {i} {}", "y".repeat(20_000 + i as usize)).into_bytes();
2519300×
                refs.push(store.put(ObjectType::Blob, &body).unwrap());
2520300×
            }
25211×
            std::mem::forget(batch);
2522
        }
25231×
        let tmp: Vec<_> = fs::read_dir(dir.path())
25241×
            .unwrap()
25251×
            .flatten()
25262×
            .filter(|e| e.file_name().to_string_lossy().starts_with(".tmp-"))
25271×
            .map(|e| e.path())
25281×
            .collect();
25291×
        assert_eq!(tmp.len(), 1, "one unfinished pack");
2530
        // A torn last entry: a header and part of its body.
25311×
        let mut f = fs::OpenOptions::new().append(true).open(&tmp[0]).unwrap();
25321×
        f.write_all(&[0, 1, 0xff, 0, 0, 0, 9, 9, 0, 0]).unwrap();
25331×
        f.write_all(&[7; 40]).unwrap();
25341×
        drop(f);
25351×
        let store = Store::open(dir.path()).unwrap();
25361×
        assert!(store.get(&refs[0]).is_err(), "unreadable before");
25371×
        let young = store
25381×
            .adopt_unfinished_packs(std::time::Duration::from_secs(3600), &|_| {})
25391×
            .unwrap();
25401×
        assert_eq!(young, (0, 0), "a pack written to lately is left alone");
25411×
        let (packs, objects) = store
25422×
            .adopt_unfinished_packs(std::time::Duration::ZERO, &|_| {})
25431×
            .unwrap();
25441×
        assert_eq!((packs, objects), (1, 300));
2545300×
        for r in &refs {
2546300×
            store
2547300×
                .get(r)
2548300×
                .unwrap_or_else(|e| panic!("{}: {e}", r.short(12)));
2549
        }
25501×
        let again = Store::open(dir.path()).unwrap();
25511×
        assert!(again.get(&refs[299]).is_ok(), "indexed for good");
25521×
    }
2553
}
2554
2555
#[cfg(test)]
2556
mod size_tests {
2557
    use super::*;
2558
2559
    #[test]
25601×
    fn an_object_over_the_limit_is_refused_and_nothing_is_written() {
25611×
        let dir = tempfile::tempdir().unwrap();
25621×
        let store = Store::open(dir.path()).unwrap();
25631×
        let big = vec![b'x'; MAX_OBJECT_LEN as usize + 1];
2564
        {
25651×
            let batch = store.begin_batch().unwrap();
25661×
            store.put(ObjectType::Blob, b"small").unwrap();
25671×
            let e = store.put(ObjectType::Change, &big).unwrap_err();
25681×
            assert!(
25691×
                matches!(e, StoreError::TooLarge { kind: "change", .. }),
2570
                "{e}"
2571
            );
25721×
            assert!(e.to_string().contains("commit it in parts"), "{e}");
25731×
            batch.finish().unwrap();
2574
        }
2575
        // The store still opens and reads what was written.
25761×
        let again = Store::open(dir.path()).unwrap();
25771×
        again.get(&hash_object(ObjectType::Blob, b"small")).unwrap();
25781×
    }
2579
}
2580
2581
#[cfg(test)]
2582
mod text_tests {
2583
    use super::*;
2584
    use crate::objects::{AtomRef, Edit, CHANGE_VERSION};
2585
25862×
    fn large_change() -> Change {
25872×
        let mut c = crate::objects::tests::sample_change();
25882×
        assert_eq!(c.version, CHANGE_VERSION);
25892×
        c.edits[0] = Edit::Insert {
25902×
            node: crate::ids::NodeId([7; 16]),
25912×
            after: AtomRef::Start,
25922×
            before: AtomRef::End,
25932×
            lines: (0..2000)
25944000×
                .map(|i| format!("line {i}\n").into_bytes())
25952×
                .collect(),
2596
        };
25972×
        c
25982×
    }
2599
2600
    #[test]
26011×
    fn a_large_insert_is_stored_beside_its_change_and_read_back() {
26021×
        let dir = tempfile::tempdir().unwrap();
26031×
        let s = Store::open(dir.path()).unwrap();
26041×
        let c = large_change();
26051×
        let r = s.put_change(&c).unwrap();
26061×
        assert_eq!(r, c.hash());
26071×
        let (_, body) = s.get(&r).unwrap();
26081×
        assert!(
26091×
            body.len() < 1024,
2610
            "the change holds a reference, not {} bytes of lines",
26110×
            body.len()
2612
        );
26131×
        let (back, parts) = s.get_change_parts(&r).unwrap();
26141×
        assert_eq!(back, c);
2615
        // The text blob and its chunk.
26161×
        assert_eq!(parts.len(), 2);
26172×
        for p in &parts {
26182×
            assert!(s.has(p));
2619
        }
2620
        // Storing it again writes nothing new.
26211×
        let n = s.list().unwrap().len();
26221×
        s.put_change(&c).unwrap();
26231×
        assert_eq!(s.list().unwrap().len(), n);
26241×
    }
2625
2626
    #[test]
26271×
    fn a_change_whose_text_blob_is_missing_is_reported_not_misread() {
26281×
        if !super::files_on_disk() {
26290×
            return;
26301×
        }
26311×
        let dir = tempfile::tempdir().unwrap();
26321×
        let s = Store::open(dir.path()).unwrap();
26331×
        let c = large_change();
26341×
        let r = s.put_change(&c).unwrap();
26351×
        let (_, parts) = s.get_change_parts(&r).unwrap();
26361×
        fs::remove_file(s.path_for(&parts[0])).unwrap();
26371×
        let e = s.get_change(&r).unwrap_err();
26381×
        assert!(
26391×
            matches!(&e, StoreError::Corrupt(h, why) if *h == r && why.contains("missing")),
2640
            "{e}"
2641
        );
26421×
    }
2643
}
2644
2645
#[cfg(test)]
2646
mod put_many_tests {
2647
    use super::*;
2648
2649
    #[test]
26501×
    fn many_objects_in_a_batch_are_compressed_together_and_all_read_back() {
26511×
        let dir = tempfile::tempdir().unwrap();
26521×
        let s = Store::open(dir.path()).unwrap();
26531×
        let before = s.put(ObjectType::Chunk, b"already here").unwrap();
26541×
        let bodies: Vec<Vec<u8>> = (0..200u32)
2655200×
            .map(|i| format!("chunk {i} ").repeat(6000).into_bytes())
26561×
            .collect();
26571×
        let mut objects: Vec<(ObjectType, &[u8])> = bodies
26581×
            .iter()
2659200×
            .map(|b| (ObjectType::Chunk, b.as_slice()))
26601×
            .collect();
26611×
        objects.push((ObjectType::Chunk, bodies[0].as_slice()));
26621×
        objects.push((ObjectType::Chunk, b"already here"));
26631×
        let refs = {
26641×
            let batch = s.begin_batch().unwrap();
26651×
            let refs = s.put_many(&objects).unwrap();
26661×
            batch.finish().unwrap();
26671×
            refs
2668
        };
26691×
        assert_eq!(refs.len(), objects.len());
26701×
        assert_eq!(refs[200], refs[0], "a repeat is the same object");
26711×
        assert_eq!(refs[201], before);
26721×
        let again = Store::open(dir.path()).unwrap();
2673202×
        for (r, b) in refs.iter().zip(&objects) {
2674202×
            assert_eq!(again.get(r).unwrap().1, b.1);
2675
        }
26761×
    }
2677
}