OXYGENHUB

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

1977 of 2103 lines run, 308 of 444 functions · run #306 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
7255×
fn silent() -> impl FnMut(&str) {
73116×
    |_| {}
7455×
}
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.
867583×
fn put_new_or_existing(backend: &Backend, key: &str, bytes: &[u8]) -> Result<()> {
877583×
    match backend.put_new(key, bytes) {
887583×
        Ok(()) | Err(BackendError::Exists(_)) => Ok(()),
890×
        Err(e) => Err(backend_err(e)),
90
    }
917583×
}
92
93
/// `get` as an option: `None` when there is no such key.
9452919×
fn get_optional(backend: &Backend, key: &str) -> Result<Option<Vec<u8>>> {
9552919×
    match backend.get(key) {
9646796×
        Ok(b) => Ok(Some(b)),
976123×
        Err(BackendError::NotFound(_)) => Ok(None),
980×
        Err(e) => Err(backend_err(e)),
99
    }
10052919×
}
101
1023034×
fn delete(backend: &Backend, key: &str) -> Result<()> {
1033034×
    backend.delete(key).map_err(backend_err)
1043034×
}
105
106
/// `loose/<hh>/<rest>`.
10785901×
fn loose_key(r: &ObjectRef) -> String {
10885901×
    let h = r.to_hex();
10985901×
    format!("loose/{}/{}", &h[..2], &h[2..])
11085901×
}
111
112
/// The object a loose key names, if it is one.
11316846×
fn loose_ref(key: &str) -> Option<ObjectRef> {
11416846×
    let rest = key.strip_prefix("loose/")?;
11516846×
    let (hh, tail) = rest.split_once('/')?;
11616846×
    if hh.len() != 2 || tail.contains('/') {
1170×
        return None;
11816846×
    }
11916846×
    ObjectRef::from_hex(&format!("{hh}{tail}"))
12016846×
}
121
122
/// `<index>/<hh>/<rest>/` for the entries kept under an object.
1234522×
fn fanout_prefix(index: &str, r: &ObjectRef) -> String {
1244522×
    let h = r.to_hex();
1254522×
    format!("{index}/{}/{}/", &h[..2], &h[2..])
1264522×
}
127
128
/// `<index>/<hh>/<rest>`: the one-file-per-object layout of older stores.
1293905×
fn legacy_key(index: &str, r: &ObjectRef) -> String {
1303905×
    let h = r.to_hex();
1313905×
    format!("{index}/{}/{}", &h[..2], &h[2..])
1323905×
}
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.
17115742×
fn decode_entry(
17215742×
    r: &ObjectRef,
17315742×
    e: PackEntry,
17415742×
    stored: Vec<u8>,
17515742×
    dict: Option<&Arc<zstd::dict::DecoderDictionary<'static>>>,
17615742×
) -> Result<Object> {
17715742×
    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}")))?
18411241×
    } 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 {
1884794×
        stored
189
    };
19015737×
    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×
        ));
19515618×
    }
19615618×
    Ok((e.ty, body))
19715742×
}
198
199
impl PackIndex {
2001132×
    fn load(backend: &Backend, idx_key: &str, pack_key: &str) -> Result<PackIndex> {
2011132×
        let data = backend.get(idx_key).map_err(backend_err)?;
2021132×
        let bad = |m: &str| StoreError::Corrupt(ObjectRef::ZERO, format!("{idx_key}: {m}"));
2031132×
        if data.len() < 12 || &data[..8] != IDX_MAGIC {
2042×
            return Err(bad("bad index header"));
2051130×
        }
2061130×
        let count = u32::from_le_bytes(data[8..12].try_into().unwrap()) as usize;
2071130×
        if data.len() != 12 + count * IDX_ENTRY {
20842×
            return Err(bad("index length mismatch"));
2091088×
        }
2101088×
        let pack_len = backend
2111088×
            .stat(pack_key)
2121088×
            .map_err(backend_err)?
2131088×
            .ok_or_else(|| bad("the index names a pack that is not there"))?
214
            .size;
2151088×
        let mut refs = Vec::with_capacity(count);
2161088×
        let mut entries = Vec::with_capacity(count);
21726145×
        for i in 0..count {
21826145×
            let e = &data[12 + i * IDX_ENTRY..12 + (i + 1) * IDX_ENTRY];
21926145×
            let r = ObjectRef::from_slice(&e[..32]).unwrap();
22026145×
            if let Some(prev) = refs.last() {
22125057×
                if r <= *prev {
2223×
                    return Err(bad("index not sorted"));
22325054×
                }
2241088×
            }
22526142×
            refs.push(r);
22626137×
            let entry = PackEntry {
22726142×
                offset: u64::from_le_bytes(e[32..40].try_into().unwrap()),
22826142×
                stored_len: u32::from_le_bytes(e[40..44].try_into().unwrap()),
22926142×
                raw_len: u32::from_le_bytes(e[44..48].try_into().unwrap()),
23026142×
                ty: ObjectType::ALL
23126142×
                    .get(e[48] as usize)
23226142×
                    .copied()
23326142×
                    .ok_or_else(|| bad("unknown object type"))?,
23426137×
                flags: e[49],
235
            };
23626137×
            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×
                ));
24426134×
            }
24526134×
            if entry.offset.saturating_add(entry.stored_len as u64) > pack_len {
24654×
                return Err(bad("index entry points outside the pack"));
24726080×
            }
24826080×
            entries.push(entry);
249
        }
2501023×
        let dict_key = format!("{}.dict", pack_key.trim_end_matches(".pack"));
2511023×
        let dict = get_optional(backend, &dict_key)?
2521023×
            .map(|d| Arc::new(zstd::dict::DecoderDictionary::copy(&d)));
2531023×
        Ok(PackIndex {
2541023×
            key: pack_key.to_string(),
2551023×
            refs,
2561023×
            entries,
2571023×
            dict,
2581023×
        })
2591132×
    }
260
26118353×
    fn find(&self, r: &ObjectRef) -> Option<PackEntry> {
26218353×
        self.refs.binary_search(r).ok().map(|i| self.entries[i])
26318353×
    }
264
265
    /// Read one entry from the pack: one ranged read, then decode.
26615260×
    fn fetch(&self, backend: &Backend, r: &ObjectRef, e: PackEntry) -> Result<Object> {
26715260×
        let stored = backend
26815260×
            .get_range(&self.key, e.offset..e.offset + e.stored_len as u64)
26915260×
            .map_err(|err| match err {
2700×
                BackendError::NotFound(_) => StoreError::NotFound(*r),
2710×
                other => backend_err(other),
2720×
            })?;
27315260×
        decode_entry(r, e, stored, self.dict.as_ref())
27415260×
    }
275
}
276
27711984×
fn type_index(ty: ObjectType) -> u8 {
27817358×
    ObjectType::ALL.iter().position(|t| *t == ty).unwrap() as u8
27911984×
}
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<'_> {
3862626×
    pub fn finish(mut self) -> Result<()> {
3872626×
        self.done = true;
3882626×
        self.store.finish_batch()
3892626×
    }
390
}
391
392
impl Drop for Batch<'_> {
3932628×
    fn drop(&mut self) {
3942628×
        if !self.done {
3952×
            let _ = self.store.finish_batch();
3962626×
        }
3972628×
    }
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.
43377×
fn fresh_id() -> String {
43477×
    let mut nonce = [0u8; 8];
43577×
    rand::rngs::OsRng.fill_bytes(&mut nonce);
43677×
    hex::encode(nonce)
43777×
}
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.
4432696×
fn memory_backend_for(dir: &Path) -> Option<Arc<Backend>> {
444
    use std::collections::HashMap;
445
    use std::sync::{Mutex, OnceLock};
4462696×
    if std::env::var_os("OXY_STORE_BACKEND").as_deref() != Some(std::ffi::OsStr::new("memory")) {
4472696×
        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)
4602696×
}
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.
4722700×
    pub fn open(dir: impl Into<PathBuf>) -> io::Result<Store> {
4732700×
        let dir = dir.into();
4742700×
        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×
        }
4792696×
        if let Some(backend) = memory_backend_for(&dir) {
4800×
            return Store::open_on(backend, dir);
4812696×
        }
4822696×
        let backend: Arc<Backend> =
4832696×
            Arc::new(LocalStore::open(&dir).map_err(|e| io::Error::other(e.to_string()))?);
4842696×
        let mut store = Store::open_on(backend, dir)?;
4852587×
        store.local = true;
4862587×
        Ok(store)
4872700×
    }
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.
4912716×
    pub fn open_on(backend: Arc<Backend>, scratch: impl Into<PathBuf>) -> io::Result<Store> {
4922716×
        let scratch = scratch.into();
4932716×
        fs::create_dir_all(&scratch)?;
4942716×
        let store = Store {
4952716×
            backend,
4962716×
            scratch,
4972716×
            local: false,
4982716×
            packs: RefCell::new(Vec::new()),
4992716×
            pending: RefCell::new(None),
5002716×
            batch_depth: std::cell::Cell::new(0),
5012716×
            metas: RefCell::new(None),
5022716×
        };
5032716×
        store
5042716×
            .reload_packs()
5052716×
            .map_err(|e| io::Error::other(e.to_string()))?;
5062607×
        Ok(store)
5072716×
    }
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.
51622848×
    pub fn is_local(&self) -> bool {
51722848×
        self.local
51822848×
    }
519
5202865×
    fn reload_packs(&self) -> Result<()> {
5212865×
        let listed = self.backend.list("pack-").map_err(backend_err)?;
5222865×
        let mut idx_keys: Vec<&str> = listed
5232865×
            .iter()
5242865×
            .map(|e| e.key.as_str())
5252865×
            .filter(|k| k.ends_with(".idx"))
5262865×
            .collect();
5272865×
        idx_keys.sort();
5282865×
        let mut packs = Vec::new();
5292865×
        for idx in idx_keys {
5301132×
            let pack = format!("{}.pack", idx.trim_end_matches(".idx"));
53110741×
            if listed.iter().any(|e| e.key == pack) {
5321132×
                packs.push(PackIndex::load(self.backend.as_ref(), idx, &pack)?);
5330×
            }
534
        }
5352756×
        *self.packs.borrow_mut() = packs;
5362756×
        Ok(())
5372865×
    }
538
53915×
    pub fn pack_count(&self) -> usize {
54015×
        self.packs.borrow().len()
54115×
    }
542
54379102×
    fn find_packed(&self, r: &ObjectRef) -> Option<(usize, PackEntry)> {
54479102×
        self.packs
54579102×
            .borrow()
54679102×
            .iter()
54779102×
            .enumerate()
54879102×
            .find_map(|(i, p)| p.find(r).map(|e| (i, e)))
54979102×
    }
550
551
    /// Loose objects, with their keys and ages.
552818×
    fn loose_objects(&self) -> Result<Vec<(ObjectRef, strata::Entry)>> {
553818×
        let mut out: Vec<(ObjectRef, strata::Entry)> = self
554818×
            .backend
555818×
            .list("loose/")
556818×
            .map_err(backend_err)?
557818×
            .into_iter()
55816846×
            .filter_map(|e| loose_ref(&e.key).map(|r| (r, e)))
559818×
            .collect();
560818×
        out.sort_by_key(|(r, _)| *r);
561818×
        Ok(out)
562818×
    }
563
564645×
    pub fn loose_count(&self) -> io::Result<usize> {
565645×
        self.loose_objects()
566645×
            .map(|l| l.len())
567645×
            .map_err(|e| io::Error::other(e.to_string()))
568645×
    }
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.
57245×
    pub fn pack_loose(&self) -> Result<PackReport> {
57345×
        let loose = self.loose_objects()?;
57445×
        self.write_pack(
57545×
            &loose.iter().map(|(r, _)| *r).collect::<Vec<_>>(),
576434×
            &loose.iter().map(|(_, e)| e.key.clone()).collect::<Vec<_>>(),
57745×
            &[],
578
            ZSTD_LEVEL,
57945×
            &mut silent(),
580
        )
58145×
    }
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.
5863×
    pub fn repack_all(&self, level: i32) -> Result<(PackReport, usize)> {
5873×
        self.repack_all_with(level, &mut silent())
5883×
    }
589
590
    /// [`Store::repack_all`], reporting progress.
59120×
    pub fn repack_all_with(&self, level: i32, progress: Progress) -> Result<(PackReport, usize)> {
59220×
        let loose = self.loose_objects()?;
59320×
        let (mut refs, keys, trained): (Vec<ObjectRef>, Vec<String>, bool) = {
59420×
            let packs = self.packs.borrow();
595
            (
59620×
                packs.iter().flat_map(|p| p.refs.iter().copied()).collect(),
59720×
                packs.iter().map(|p| p.key.clone()).collect(),
59820×
                packs.first().is_some_and(|p| p.dict.is_some()),
599
            )
600
        };
601
        // Nothing loose and one pack already made by a full repack (only
602
        // such a pack has a trained dictionary): rewriting it would give
603
        // the same pack. A hub's nightly gc rewrote andymccall/oxygen's
604
        // 48 000 objects (37 s under its write lock) every time.
60520×
        if loose.is_empty() && keys.len() <= 1 && (level == ZSTD_LEVEL || trained) {
6061×
            return Ok((PackReport::default(), 0));
60719×
        }
60819×
        refs.extend(loose.iter().map(|(r, _)| *r));
60919×
        let loose_keys: Vec<String> = loose.into_iter().map(|(_, e)| e.key).collect();
61019×
        let n = keys.len();
61119×
        let report = self.write_pack(&refs, &loose_keys, &keys, level, progress)?;
61219×
        Ok((report, n))
61320×
    }
614
615
    /// Fold every pack into one when there are more than `MAX_PACKS`
616
    /// (spec §13.4). Returns how many packs were merged.
6174×
    pub fn merge_packs(&self) -> Result<usize> {
6182×
        let (refs, keys): (Vec<ObjectRef>, Vec<String>) = {
6194×
            let packs = self.packs.borrow();
6204×
            if packs.len() <= MAX_PACKS {
6212×
                return Ok(0);
6222×
            }
623
            (
62436×
                packs.iter().flat_map(|p| p.refs.iter().copied()).collect(),
62536×
                packs.iter().map(|p| p.key.clone()).collect(),
626
            )
627
        };
6282×
        let n = keys.len();
6292×
        self.write_pack(&refs, &[], &keys, ZSTD_LEVEL, &mut silent())?;
6302×
        Ok(n)
6314×
    }
632
633
    /// Delete every object not in `keep` (spec §21). Loose objects and packs
634
    /// younger than `grace` are left alone, since a concurrent writer may not
635
    /// have recorded its references yet. Packs holding unreachable objects
636
    /// are rewritten without them. Signatures, seal and receipt entries of
637
    /// deleted objects go too.
6385×
    pub fn prune(
6395×
        &self,
6405×
        keep: &std::collections::HashSet<ObjectRef>,
6415×
        grace: std::time::Duration,
6425×
    ) -> Result<PruneReport> {
6435×
        self.prune_with(keep, grace, &mut silent())
6445×
    }
645
646
    /// [`Store::prune`], reporting progress.
64722×
    pub fn prune_with(
64822×
        &self,
64922×
        keep: &std::collections::HashSet<ObjectRef>,
65022×
        grace: std::time::Duration,
65122×
        progress: Progress,
65222×
    ) -> Result<PruneReport> {
65322×
        progress("pruning loose objects");
65422×
        let now = now_ms();
65522×
        let grace_ms = grace.as_millis() as u64;
656
        // An object whose age the store does not know is old enough.
65722×
        let old_enough =
65835×
            |modified: Option<u64>| modified.is_none_or(|t| now.saturating_sub(t) >= grace_ms);
65922×
        let mut report = PruneReport::default();
660
        // Loose objects.
661291×
        for (r, entry) in self.loose_objects()? {
662291×
            if keep.contains(&r) {
663265×
                continue;
66426×
            }
66526×
            if !old_enough(entry.modified_ms) {
6664×
                report.deferred += 1;
6674×
                continue;
66822×
            }
66922×
            report.bytes += entry.size;
67022×
            report.objects += 1;
67122×
            delete(self.backend.as_ref(), &entry.key)?;
67222×
            self.remove_sidecars(&r)?;
673
        }
674
        // Packs: rewrite those that hold unreachable objects.
67522×
        let mut keep_refs: Vec<ObjectRef> = Vec::new();
67622×
        let mut old_keys: Vec<String> = Vec::new();
67722×
        let mut rewrite = false;
67822×
        progress("pruning packs");
67922×
        for p in self.packs.borrow().iter() {
680150×
            let unreachable = p.refs.iter().filter(|r| !keep.contains(r)).count();
68110×
            if unreachable == 0 {
6821×
                continue;
6839×
            }
6849×
            let modified = self
6859×
                .backend
6869×
                .stat(&p.key)
6879×
                .map_err(backend_err)?
6889×
                .and_then(|e| e.modified_ms);
6899×
            if !old_enough(modified) {
6903×
                report.deferred += unreachable;
6913×
                continue;
6926×
            }
6936×
            rewrite = true;
6946×
            old_keys.push(p.key.clone());
695102×
            for (r, e) in p.refs.iter().zip(p.entries.iter()) {
696102×
                if keep.contains(r) {
69761×
                    keep_refs.push(*r);
69861×
                } else {
69941×
                    report.objects += 1;
70041×
                    report.bytes += e.stored_len as u64;
70141×
                }
702
            }
703
        }
70422×
        if rewrite {
7056×
            let dropped: Vec<ObjectRef> = {
7066×
                let packs = self.packs.borrow();
7076×
                packs
7086×
                    .iter()
7096×
                    .filter(|p| old_keys.contains(&p.key))
7106×
                    .flat_map(|p| p.refs.iter().copied())
711102×
                    .filter(|r| !keep.contains(r))
7126×
                    .collect()
713
            };
7146×
            self.write_pack(&keep_refs, &[], &old_keys, ZSTD_LEVEL, progress)?;
71541×
            for r in dropped {
71641×
                self.remove_sidecars(&r)?;
717
            }
71816×
        }
71922×
        Ok(report)
72022×
    }
721
722
    /// Everything kept beside an object: its signatures and the seal and
723
    /// receipt entries under it, in both layouts.
72463×
    fn remove_sidecars(&self, r: &ObjectRef) -> Result<()> {
725189×
        for index in ["sigs", "seals", "receipts"] {
726189×
            delete(self.backend.as_ref(), &legacy_key(index, r))?;
727
        }
728189×
        for index in ["sig", "seal", "receipt"] {
729189×
            for e in self
730189×
                .backend
731189×
                .list(&fanout_prefix(index, r))
732189×
                .map_err(backend_err)?
733
            {
73410×
                delete(self.backend.as_ref(), &e.key)?;
735
            }
736
        }
73763×
        Ok(())
73863×
    }
739
740
    /// Put a complete, synced temporary pack file and its index into the
741
    /// store; `index` must be sorted by ObjectRef. The pack goes first: an
742
    /// index never names a pack that is not there.
74377×
    fn finish_pack_files(
74477×
        &self,
74577×
        id: &str,
74677×
        tmp_pack: &Path,
74777×
        index: &[(ObjectRef, PackEntry)],
74877×
    ) -> Result<()> {
74977×
        let mut idx = Vec::with_capacity(12 + index.len() * IDX_ENTRY);
75077×
        idx.extend_from_slice(IDX_MAGIC);
75177×
        idx.extend_from_slice(&(index.len() as u32).to_le_bytes());
7525992×
        for (r, e) in index {
7535992×
            idx.extend_from_slice(&r.0);
7545992×
            idx.extend_from_slice(&e.offset.to_le_bytes());
7555992×
            idx.extend_from_slice(&e.stored_len.to_le_bytes());
7565992×
            idx.extend_from_slice(&e.raw_len.to_le_bytes());
7575992×
            idx.extend_from_slice(&[type_index(e.ty), e.flags]);
7585992×
        }
75977×
        let put = self
76077×
            .backend
76177×
            .put_new_file(&format!("pack-{id}.pack"), tmp_pack)
76277×
            .map_err(backend_err);
763
        // A store on another disk copied it; the one in this directory
764
        // moved it and this finds nothing.
76577×
        let _ = fs::remove_file(tmp_pack);
76677×
        put?;
76777×
        self.backend
76877×
            .put_new(&format!("pack-{id}.idx"), &idx)
76977×
            .map_err(backend_err)?;
77077×
        self.reload_packs()
77177×
    }
772
773
    /// Remove a pack with its index and dictionary.
77449×
    fn remove_pack(&self, pack_key: &str) -> Result<()> {
77549×
        let stem = pack_key.trim_end_matches(".pack");
77649×
        delete(self.backend.as_ref(), pack_key)?;
77749×
        delete(self.backend.as_ref(), &format!("{stem}.idx"))?;
77849×
        delete(self.backend.as_ref(), &format!("{stem}.dict"))
77949×
    }
780
781
    /// Write `refs` into a new pack, then delete `loose_keys` and `old_packs`.
78272×
    fn write_pack(
78372×
        &self,
78472×
        refs: &[ObjectRef],
78572×
        loose_keys: &[String],
78672×
        old_packs: &[String],
78772×
        level: i32,
78872×
        progress: Progress,
78972×
    ) -> Result<PackReport> {
79072×
        if refs.is_empty() {
7910×
            for p in old_packs {
7920×
                self.remove_pack(p)?;
793
            }
7940×
            self.reload_packs()?;
7950×
            return Ok(PackReport::default());
79672×
        }
79772×
        let mut refs: Vec<ObjectRef> = refs.to_vec();
79872×
        refs.sort();
79972×
        refs.dedup();
80072×
        let id = fresh_id();
80172×
        let tmp_pack = self.scratch.join(format!(".tmp-{id}.pack"));
80272×
        let mut report = PackReport::default();
80372×
        let mut index: Vec<(ObjectRef, PackEntry)> = Vec::with_capacity(refs.len());
804
        // A full repack of enough objects trains a dictionary for them.
80572×
        let dict = if level == REPACK_ZSTD_LEVEL && refs.len() >= DICT_MIN_OBJECTS {
8062×
            let _t = crate::timing::phase("pack: train a dictionary");
8072×
            progress(&format!("training a dictionary on {} objects", refs.len()));
8082×
            self.train_dictionary(&refs)
809
        } else {
81070×
            None
811
        };
81272×
        let encoder = dict
81372×
            .as_ref()
81472×
            .map(|d| zstd::dict::EncoderDictionary::copy(d, level));
81572×
        let nocompress = self.nocompress_set()?;
816
        {
81772×
            let mut f = io::BufWriter::new(fs::File::create(&tmp_pack)?);
81872×
            f.write_all(PACK_MAGIC)?;
81972×
            let mut offset = PACK_MAGIC.len() as u64;
820
            // Read a batch (the store is not shared between threads),
821
            // compress it on every core, write it in order.
82272×
            let mut batches = refs.chunks(1024);
82372×
            let mut compressed_batch = Vec::new();
82472×
            let total = refs.len();
82572×
            let mut reported = usize::MAX;
826
            loop {
8273964×
                if compressed_batch.is_empty() {
828146×
                    let Some(batch) = batches.next() else { break };
829
                    // Every tenth, and the first batch.
83074×
                    let tenth = report.objects * 10 / total.max(1);
83174×
                    if tenth != reported {
83274×
                        reported = tenth;
83374×
                        progress(&format!("packing {} of {total} objects", report.objects));
83474×
                    }
83574×
                    let mut read: Vec<(ObjectRef, ObjectType, Vec<u8>, bool)> =
83674×
                        Vec::with_capacity(batch.len());
8373892×
                    for r in batch {
8383892×
                        let (ty, body) = self.get(r)?;
8393892×
                        read.push((*r, ty, body, nocompress.contains(r)));
840
                    }
841
                    use rayon::prelude::*;
84274×
                    compressed_batch = read
84374×
                        .into_par_iter()
84474×
                        .map_init(
845939×
                            || {
846939×
                                encoder.as_ref().and_then(|e| {
847347×
                                    zstd::bulk::Compressor::with_prepared_dictionary(e).ok()
848347×
                                })
849939×
                            },
8503892×
                            |with_dict, (r, ty, body, raw)| {
8513892×
                                let packed = if raw {
8522×
                                    None
853
                                } else {
854
                                    // Small objects with the dictionary;
855
                                    // a large one has context enough.
8563890×
                                    let dicted = with_dict
8573890×
                                        .as_mut()
8583890×
                                        .filter(|_| body.len() <= DICT_OBJECT_MAX)
8593890×
                                        .and_then(|c| c.compress(&body).ok())
8603890×
                                        .map(|c| (FLAG_ZSTD | FLAG_DICT, c));
8613890×
                                    dicted
8623890×
                                        .or_else(|| {
863889×
                                            zstd::bulk::compress(&body, level)
864889×
                                                .ok()
865889×
                                                .map(|c| (FLAG_ZSTD, c))
866889×
                                        })
8673890×
                                        .filter(|(_, c)| c.len() < body.len())
868
                                };
8693892×
                                (r, ty, body, packed)
8703892×
                            },
871
                        )
87274×
                        .collect::<Vec<_>>();
87374×
                    compressed_batch.reverse();
8743818×
                }
8753892×
                let Some((r, ty, body, packed)) = compressed_batch.pop() else {
8760×
                    continue;
877
                };
8783892×
                let r = &r;
8793892×
                let (flags, stored) = match packed {
8803379×
                    Some(c) => c,
881513×
                    None => (0, body.clone()),
882
                };
8833892×
                let header_len = 1 + 1 + 4 + 4 + 32;
8843892×
                f.write_all(&[type_index(ty), flags])?;
8853892×
                f.write_all(&(stored.len() as u32).to_le_bytes())?;
8863892×
                f.write_all(&(body.len() as u32).to_le_bytes())?;
8873892×
                f.write_all(&r.0)?;
8883892×
                f.write_all(&stored)?;
8893892×
                index.push((
8903892×
                    *r,
8913892×
                    PackEntry {
8923892×
                        offset: offset + header_len,
8933892×
                        stored_len: stored.len() as u32,
8943892×
                        raw_len: body.len() as u32,
8953892×
                        ty,
8963892×
                        flags,
8973892×
                    },
8983892×
                ));
8993892×
                offset += header_len + stored.len() as u64;
9003892×
                report.objects += 1;
9013892×
                report.raw_bytes += body.len() as u64;
9023892×
                report.packed_bytes += stored.len() as u64;
903
            }
90472×
            f.flush()?;
90572×
            f.get_ref().sync_all()?;
906
        }
907
        // The dictionary before the pack that needs it becomes visible.
90872×
        if let Some(d) = &dict {
9092×
            self.backend
9102×
                .put_new(&format!("pack-{id}.dict"), d)
9112×
                .map_err(backend_err)?;
91270×
        }
91372×
        progress(&format!("writing the index of {} objects", index.len()));
91472×
        self.finish_pack_files(&id, &tmp_pack, &index)?;
91572×
        for p in old_packs {
91649×
            self.remove_pack(p)?;
917
        }
91872×
        self.reload_packs()?;
9192192×
        for key in loose_keys {
9202192×
            delete(self.backend.as_ref(), key)?;
921
        }
92272×
        Ok(report)
92372×
    }
924
925
    /// A dictionary for these objects, trained on a sample of them (at
926
    /// most 10 000, 32 MB); `None` when training fails.
9272×
    fn train_dictionary(&self, refs: &[ObjectRef]) -> Option<Vec<u8>> {
9282×
        let step = (refs.len() / 10_000).max(1);
9292×
        let mut samples: Vec<Vec<u8>> = Vec::new();
9302×
        let mut total = 0usize;
9313001×
        for r in refs.iter().step_by(step) {
9323001×
            if total > 32 << 20 {
9330×
                break;
9343001×
            }
9353001×
            let Ok((ty, body)) = self.get(r) else {
9360×
                continue;
937
            };
9380×
            if matches!(
9393001×
                ty,
940
                ObjectType::Chunk | ObjectType::Blob | ObjectType::Change
9413001×
            ) && !body.is_empty()
9423001×
                && body.len() < 1 << 20
9433001×
            {
9443001×
                total += body.len();
9453001×
                samples.push(body);
9463001×
            }
947
        }
9482×
        zstd::dict::from_samples(&samples, DICT_BYTES).ok()
9492×
    }
950
951
    /// The scratch directory: for a store in a directory, that directory.
9527×
    pub fn dir(&self) -> &Path {
9537×
        &self.scratch
9547×
    }
955
956
    /// Where a loose object is kept, for a store in a directory (tests
957
    /// tamper with and remove objects there).
958
    #[cfg(test)]
9594×
    pub(crate) fn path_for(&self, r: &ObjectRef) -> PathBuf {
9604×
        self.scratch.join(loose_key(r))
9614×
    }
962
963
    /// Remove a loose object, whatever the store is on (tests make an
964
    /// object go missing).
965
    #[cfg(test)]
9663×
    pub(crate) fn remove_loose_for_test(&self, r: &ObjectRef) -> Result<()> {
9673×
        delete(self.backend.as_ref(), &loose_key(r))
9683×
    }
969
97011268×
    pub fn has(&self, r: &ObjectRef) -> bool {
97111268×
        self.backend.has(&loose_key(r)).unwrap_or(false)
9721221×
            || self.find_packed(r).is_some()
973881×
            || self
974881×
                .pending
975881×
                .borrow()
976881×
                .as_ref()
977881×
                .is_some_and(|p| p.lookup.contains_key(r))
97811268×
    }
979
980
    /// Start a write batch: until the matching `finish`, `put` collects
981
    /// objects and writes them out together, with one `fsync` for a large
982
    /// batch (a pack) instead of one per object. Batches nest; only the
983
    /// outermost does the work. Objects are readable while pending.
9842629×
    pub fn begin_batch(&self) -> Result<Batch<'_>> {
9852629×
        let depth = self.batch_depth.get();
9862629×
        if depth == 0 {
9872127×
            *self.pending.borrow_mut() = Some(Pending {
9882127×
                buffered: vec![],
9892127×
                buffered_bytes: 0,
9902127×
                lookup: Default::default(),
9912127×
                pack: None,
9922127×
                report: PackReport::default(),
9932127×
            });
9942127×
        }
9952629×
        self.batch_depth.set(depth + 1);
9962629×
        Ok(Batch {
9972629×
            store: self,
9982629×
            done: false,
9992629×
        })
10002629×
    }
1001
10022628×
    fn finish_batch(&self) -> Result<()> {
10032628×
        let depth = self.batch_depth.get();
10042628×
        if depth == 0 {
10050×
            return Ok(());
10062628×
        }
10072628×
        self.batch_depth.set(depth - 1);
10082628×
        if depth > 1 {
1009502×
            return Ok(());
10102126×
        }
10112126×
        let Some(pending) = self.pending.borrow_mut().take() else {
10122×
            return Ok(());
1013
        };
10142124×
        self.write_pending(pending)
10152628×
    }
1016
1017
    /// Make every object written so far durable, even inside an open
1018
    /// batch, which stays open. Call before a reference that names them
1019
    /// is moved (spec §13.6): the operation head, a bookmark pointer.
10203306×
    pub fn flush(&self) -> Result<()> {
10213306×
        let Some(pending) = self.pending.borrow_mut().take() else {
10222332×
            return Ok(());
1023
        };
1024974×
        self.write_pending(pending)?;
1025972×
        *self.pending.borrow_mut() = Some(Pending {
1026972×
            buffered: vec![],
1027972×
            buffered_bytes: 0,
1028972×
            lookup: Default::default(),
1029972×
            pack: None,
1030972×
            report: PackReport::default(),
1031972×
        });
1032972×
        Ok(())
10333306×
    }
1034
10353098×
    fn write_pending(&self, pending: Pending) -> Result<()> {
10363098×
        match pending.pack {
1037
            None => {
10383094×
                let objects: Vec<(ObjectType, &[u8])> = pending
10393094×
                    .buffered
10403094×
                    .iter()
10414861×
                    .map(|(ty, body)| (*ty, body.as_slice()))
10423094×
                    .collect();
10433094×
                self.put_loose_many(&objects)
1044
            }
10454×
            Some(mut pack) => {
10464×
                pack.writer.flush()?;
10474×
                pack.writer.get_ref().sync_all()?;
10484×
                drop(pack.writer);
10494×
                pack.index.sort_by_key(|(r, _)| *r);
10504×
                self.finish_pack_files(&pack.id, &pack.tmp_path, &pack.index)?;
10514×
                Ok(())
1052
            }
1053
        }
10543098×
    }
1055
1056
    /// Whether a batch is open and holds `r`.
1057925×
    fn pending_get(&self, r: &ObjectRef) -> Option<Result<Object>> {
1058925×
        let mut guard = self.pending.borrow_mut();
1059925×
        let pending = guard.as_mut()?;
1060818×
        let entry = *pending.lookup.get(r)?;
1061818×
        Some(match entry {
1062636×
            PendingEntry::Buffered(i) => {
1063636×
                let (ty, body) = &pending.buffered[i];
1064636×
                Ok((*ty, body.clone()))
1065
            }
1066182×
            PendingEntry::Packed(e) => {
1067182×
                let Some(pack) = pending.pack.as_mut() else {
10680×
                    return Some(Err(StoreError::NotFound(*r)));
1069
                };
1070
                // Read from the pack file being written, on this disk.
1071182×
                (|| {
1072182×
                    pack.writer.flush()?;
1073
                    use std::io::{Read, Seek, SeekFrom};
1074182×
                    let mut f = fs::File::open(&pack.tmp_path)?;
1075182×
                    f.seek(SeekFrom::Start(e.offset))?;
1076182×
                    let mut stored = vec![0u8; e.stored_len as usize];
1077182×
                    f.read_exact(&mut stored)?;
1078182×
                    decode_entry(r, e, stored, None)
1079
                })()
1080
            }
1081
        })
1082925×
    }
1083
1084
    /// Append one object to the pending pack file.
10851900×
    fn pending_pack_write(
10861900×
        &self,
10871900×
        pack: &mut PendingPack,
10881900×
        r: &ObjectRef,
10891900×
        ty: ObjectType,
10901900×
        body: &[u8],
10911900×
        report: &mut PackReport,
10921900×
    ) -> Result<PackEntry> {
10931900×
        let (flags, stored) = if self.is_nocompress(r) {
1094120×
            (0, body.to_vec())
1095
        } else {
10961780×
            let compressed = zstd::bulk::compress(body, ZSTD_LEVEL)
10971780×
                .map_err(|e| StoreError::Corrupt(*r, format!("zstd: {e}")))?;
10981780×
            if compressed.len() < body.len() {
10991620×
                (FLAG_ZSTD, compressed)
1100
            } else {
1101160×
                (0, body.to_vec())
1102
            }
1103
        };
11041900×
        write_pack_entry(pack, r, ty, body.len(), flags, &stored, report)
11051900×
    }
1106
11076862×
    fn put_pending(&self, r: ObjectRef, ty: ObjectType, body: &[u8]) -> Result<()> {
11086862×
        let mut guard = self.pending.borrow_mut();
11096862×
        let pending = guard.as_mut().expect("batch open");
11106862×
        if pending.lookup.contains_key(&r) {
1111101×
            return Ok(());
11126761×
        }
11136761×
        if pending.pack.is_none()
11145795×
            && pending.buffered.len() < SPILL_OBJECTS
11155793×
            && pending.buffered_bytes + body.len() <= SPILL_BYTES
1116
        {
11175791×
            pending.buffered.push((ty, body.to_vec()));
11185791×
            pending.buffered_bytes += body.len();
11195791×
            pending
11205791×
                .lookup
11215791×
                .insert(r, PendingEntry::Buffered(pending.buffered.len() - 1));
11225791×
            return Ok(());
1123970×
        }
1124970×
        self.ensure_pack(pending)?;
1125970×
        let mut report = std::mem::take(&mut pending.report);
1126970×
        let pack = pending.pack.as_mut().unwrap();
1127970×
        let e = self.pending_pack_write(pack, &r, ty, body, &mut report)?;
1128970×
        pending.report = report;
1129970×
        pending.lookup.insert(r, PendingEntry::Packed(e));
1130970×
        Ok(())
11316862×
    }
1132
1133
    /// Open the pending batch's pack, moving the objects buffered so far
1134
    /// into it (a spill).
1135971×
    fn ensure_pack(&self, pending: &mut Pending) -> Result<()> {
1136971×
        if pending.pack.is_none() {
1137
            // Spill: open the pack and move the buffered objects into it.
11385×
            let id = fresh_id();
11395×
            let tmp_path = self.scratch.join(format!(".tmp-{id}.pack"));
11405×
            let mut writer = io::BufWriter::new(fs::File::create(&tmp_path)?);
11415×
            writer.write_all(PACK_MAGIC)?;
11425×
            let mut pack = PendingPack {
11435×
                id,
11445×
                tmp_path,
11455×
                writer,
11465×
                offset: PACK_MAGIC.len() as u64,
11475×
                index: vec![],
11485×
            };
11495×
            let buffered = std::mem::take(&mut pending.buffered);
11505×
            pending.buffered_bytes = 0;
11515×
            let mut report = std::mem::take(&mut pending.report);
1152930×
            for (bty, bbody) in &buffered {
1153930×
                let br = hash_object(*bty, bbody);
1154930×
                let e = self.pending_pack_write(&mut pack, &br, *bty, bbody, &mut report)?;
1155930×
                pending.lookup.insert(br, PendingEntry::Packed(e));
1156
            }
11575×
            pending.report = report;
11585×
            pending.pack = Some(pack);
1159966×
        }
1160971×
        Ok(())
1161971×
    }
1162
1163
    /// Store many objects at once. Inside a large write batch they are
1164
    /// compressed on every core and appended in order; otherwise each is
1165
    /// stored as [`Store::put`] does.
1166750×
    pub fn put_many(&self, objects: &[(ObjectType, &[u8])]) -> Result<Vec<ObjectRef>> {
1167
        use rayon::prelude::*;
1168762×
        let total: usize = objects.iter().map(|(_, b)| b.len()).sum();
1169750×
        if self.pending.borrow().is_none() || total < SPILL_BYTES {
1170749×
            return objects.iter().map(|(ty, b)| self.put(*ty, b)).collect();
11711×
        }
1172202×
        for (ty, b) in objects {
1173202×
            if b.len() > MAX_OBJECT_LEN as usize {
11740×
                return Err(StoreError::TooLarge {
11750×
                    kind: ty.name(),
11760×
                    size: b.len(),
11770×
                    limit: MAX_OBJECT_LEN,
11780×
                });
1179202×
            }
1180
        }
11811×
        let refs: Vec<ObjectRef> = objects
11821×
            .par_iter()
1183202×
            .map(|(ty, b)| hash_object(*ty, b))
11841×
            .collect();
1185
        // What is new: not stored already, not earlier in this call.
11861×
        let mut seen: std::collections::HashSet<ObjectRef> = std::collections::HashSet::new();
11871×
        let mut todo: Vec<usize> = Vec::new();
1188202×
        for (i, r) in refs.iter().enumerate() {
1189202×
            let known = self
1190202×
                .pending
1191202×
                .borrow()
1192202×
                .as_ref()
1193202×
                .is_some_and(|p| p.lookup.contains_key(r));
1194202×
            if seen.insert(*r)
1195201×
                && !known
1196201×
                && self.find_packed(r).is_none()
1197201×
                && !self.backend.has(&loose_key(r)).unwrap_or(false)
1198200×
            {
1199200×
                todo.push(i);
1200200×
            }
1201
        }
12021×
        let raw = self.nocompress_set()?;
12031×
        let packed: Vec<(u8, Vec<u8>)> = todo
12041×
            .par_iter()
1205200×
            .map(|i| {
1206200×
                let body = objects[*i].1;
1207200×
                if raw.contains(&refs[*i]) {
12080×
                    return (0, body.to_vec());
1209200×
                }
1210200×
                match zstd::bulk::compress(body, ZSTD_LEVEL) {
1211200×
                    Ok(c) if c.len() < body.len() => (FLAG_ZSTD, c),
12120×
                    _ => (0, body.to_vec()),
1213
                }
1214200×
            })
12151×
            .collect();
12161×
        let mut guard = self.pending.borrow_mut();
12171×
        let pending = guard.as_mut().expect("batch open");
12181×
        self.ensure_pack(pending)?;
12191×
        let mut report = std::mem::take(&mut pending.report);
12201×
        let pack = pending.pack.as_mut().unwrap();
1221200×
        for (i, (flags, stored)) in todo.iter().zip(packed) {
1222200×
            let (ty, body) = objects[*i];
1223200×
            let e = write_pack_entry(pack, &refs[*i], ty, body.len(), flags, &stored, &mut report)?;
1224200×
            pending.lookup.insert(refs[*i], PendingEntry::Packed(e));
1225
        }
12261×
        pending.report = report;
12271×
        Ok(refs)
1228750×
    }
1229
1230
    /// Store `body` as an object of type `ty`; idempotent.
123115214×
    pub fn put(&self, ty: ObjectType, body: &[u8]) -> Result<ObjectRef> {
1232
        // Refuse what the store could not read back (spec §13.2), before
1233
        // anything is written: a pack must never hold an entry its index
1234
        // would reject.
123515214×
        if body.len() > MAX_OBJECT_LEN as usize {
12361×
            return Err(StoreError::TooLarge {
12371×
                kind: ty.name(),
12381×
                size: body.len(),
12391×
                limit: MAX_OBJECT_LEN,
12401×
            });
124115213×
        }
124215213×
        let r = hash_object(ty, body);
124315213×
        if self.find_packed(&r).is_some() || self.backend.has(&loose_key(&r)).unwrap_or(false) {
12441676×
            return Ok(r);
124513537×
        }
124613537×
        if self.pending.borrow().is_some() {
12476862×
            self.put_pending(r, ty, body)?;
12486862×
            return Ok(r);
12496675×
        }
12506675×
        self.put_loose(ty, body)?;
12516670×
        Ok(r)
125215214×
    }
1253
1254
    /// Write one loose object, durable when this returns.
12556870×
    fn put_loose(&self, ty: ObjectType, body: &[u8]) -> Result<ObjectRef> {
12566870×
        let r = hash_object(ty, body);
12576870×
        let mut bytes = header(ty, body.len());
12586870×
        bytes.extend_from_slice(body);
12596870×
        crate::durable::step("write loose object")?;
12606865×
        put_new_or_existing(self.backend.as_ref(), &loose_key(&r), &bytes)?;
12616865×
        Ok(r)
12626870×
    }
1263
1264
    /// Write several loose objects with as few waits on the disk as the
1265
    /// guarantees allow (a directory store writes them all, then syncs
1266
    /// each directory once). Durable when this returns, as `put_loose`
1267
    /// one at a time would be (spec §13.6).
12683094×
    fn put_loose_many(&self, objects: &[(ObjectType, &[u8])]) -> Result<()> {
12693094×
        if objects.len() <= 1 {
12701763×
            for (ty, body) in objects {
1271195×
                self.put_loose(*ty, body)?;
1272
            }
12731763×
            return Ok(());
12741331×
        }
12751331×
        let mut seen = std::collections::HashSet::new();
12761331×
        let items: Vec<(String, Vec<u8>)> = objects
12771331×
            .iter()
12784666×
            .filter_map(|(ty, body)| {
12794666×
                let r = hash_object(*ty, body);
12804666×
                seen.insert(r).then(|| {
12814666×
                    let mut bytes = header(*ty, body.len());
12824666×
                    bytes.extend_from_slice(body);
12834666×
                    (loose_key(&r), bytes)
12844666×
                })
12854666×
            })
12861331×
            .collect();
12871331×
        self.backend.put_many_new(&items).map_err(backend_err)
12883094×
    }
1289
1290
    /// Read and verify an object, packed, loose, or pending in a batch.
1291
    /// The packs' indexes are in memory, so they are asked first: asking
1292
    /// for a loose copy of a packed object costs a request that finds
1293
    /// nothing on a store in a bucket, every time (oxygenhub#228).
129460964×
    pub fn get(&self, r: &ObjectRef) -> Result<Object> {
129560964×
        if let Some((i, e)) = self.find_packed(r) {
129615131×
            return self.packs.borrow()[i].fetch(self.backend.as_ref(), r, e);
129745833×
        }
129845833×
        match get_optional(self.backend.as_ref(), &loose_key(r))? {
129944915×
            Some(bytes) => parse_loose(&bytes, r),
1300918×
            None => self.pending_get(r).unwrap_or(Err(StoreError::NotFound(*r))),
1301
        }
130260964×
    }
1303
1304
    /// Many objects at once, read and verified in parallel: packed ones
1305
    /// from their packs, the others loose (as [`Store::get`], packs first),
1306
    /// then what is pending in a batch. Results are in the order of `refs`.
1307927×
    pub fn get_many(&self, refs: &[ObjectRef]) -> Vec<Result<Object>> {
1308
        use rayon::prelude::*;
1309927×
        let backend = self.backend.as_ref();
1310927×
        let packs = self.packs.borrow();
1311927×
        let place: Vec<Option<(usize, PackEntry)>> = refs
1312927×
            .iter()
13131982×
            .map(|r| {
13141982×
                packs
13151982×
                    .iter()
13161982×
                    .enumerate()
13171982×
                    .find_map(|(p, pack)| pack.find(r).map(|e| (p, e)))
13181982×
            })
1319927×
            .collect();
1320927×
        let indexes: &[PackIndex] = &packs;
1321927×
        let found: Vec<Option<Result<Object>>> = refs
1322927×
            .par_iter()
1323927×
            .zip(place.par_iter())
13241982×
            .map(|(r, at)| match at {
1325128×
                Some((p, e)) => Some(indexes[*p].fetch(backend, r, *e)),
13261854×
                None => match get_optional(backend, &loose_key(r)) {
13271847×
                    Ok(Some(bytes)) => Some(parse_loose(&bytes, r)),
13287×
                    Ok(None) => None,
13290×
                    Err(e) => Some(Err(e)),
1330
                },
13311982×
            })
1332927×
            .collect();
1333927×
        drop(packs);
1334927×
        found
1335927×
            .into_iter()
1336927×
            .zip(refs)
13371982×
            .map(|(f, r)| {
13381982×
                f.unwrap_or_else(|| self.pending_get(r).unwrap_or(Err(StoreError::NotFound(*r))))
13391982×
            })
1340927×
            .collect()
1341927×
    }
1342
134341690×
    pub fn get_typed(&self, r: &ObjectRef, want: ObjectType) -> Result<Vec<u8>> {
134441690×
        let (ty, body) = self.get(r)?;
134541657×
        if ty != want {
13461×
            return Err(StoreError::WrongType(*r, ty.name(), want.name()));
134741656×
        }
134841656×
        Ok(body)
134941690×
    }
1350
1351
    /// Store a change and the text blobs (and their chunks) its large
1352
    /// inserts are stored as (spec §6.1).
13532824×
    pub fn put_change(&self, c: &Change) -> Result<ObjectRef> {
13542824×
        let encoding = crate::timing::phase("store: encode the change and its texts");
13552824×
        let bytes = c.encode_streaming(|batch| self.put_texts(&batch))?;
13562824×
        drop(encoding);
13572824×
        let _t = crate::timing::phase("store: put the encoding");
13582824×
        self.put(ObjectType::Change, &bytes)
13592824×
    }
1360
1361
    /// Store text blobs and their chunks: every chunk at once (compressed
1362
    /// on every core in a large batch), then the blobs.
136362×
    pub fn put_texts(&self, texts: &[crate::objects::StoredText]) -> Result<()> {
136462×
        let mut chunks: Vec<(ObjectType, &[u8])> = Vec::new();
136563×
        for t in texts {
136663×
            if !self.has(&t.blob.hash()) {
136752×
                chunks.extend(
136852×
                    crate::chunk::chunks(&t.content)
136952×
                        .into_iter()
137093×
                        .map(|c| (ObjectType::Chunk, c)),
1371
                );
137211×
            }
1373
        }
137462×
        self.put_many(&chunks)?;
137563×
        for t in texts {
137663×
            self.put(ObjectType::Blob, &t.blob.encode())?;
1377
        }
137862×
        Ok(())
137962×
    }
1380
13814496×
    pub fn get_change(&self, r: &ObjectRef) -> Result<Change> {
13824496×
        Ok(self.get_change_parts(r)?.0)
13834496×
    }
1384
1385
    /// A change and the objects its stored inserts are made of: each text
1386
    /// blob and its chunks, which travel and are kept with it.
13874612×
    pub fn get_change_parts(&self, r: &ObjectRef) -> Result<(Change, Vec<ObjectRef>)> {
13884612×
        let bytes = self.get_typed(r, ObjectType::Change)?;
13894600×
        let mut parts = Vec::new();
13904600×
        let mut failed = None;
13914600×
        let decoded = Change::decode_with(&bytes, &mut |text, count, form| match self
139259×
            .read_text(text)
1393
        {
139458×
            Ok((blob, content)) => {
139558×
                parts.push(*text);
139658×
                parts.extend(blob.chunks);
139758×
                crate::objects::text_lines(&content, count, form)
1398
            }
13991×
            Err(e) => {
14001×
                let why = e.to_string();
14011×
                failed = Some(e);
14021×
                Err(ObjectError::Schema(format!(
14031×
                    "text blob {}: {why}",
14041×
                    text.short(12)
14051×
                )))
1406
            }
140759×
        });
14084600×
        match (decoded, failed) {
14094599×
            (Ok(c), _) => Ok((c, parts)),
14101×
            (Err(_), Some(StoreError::NotFound(t))) => Err(StoreError::Corrupt(
14111×
                *r,
14121×
                format!("its text blob {} is missing", t.short(12)),
14131×
            )),
14140×
            (Err(e), _) => Err(StoreError::Corrupt(*r, e.to_string())),
1415
        }
14164612×
    }
1417
1418
    /// A change with every insert left without its lines (empty
1419
    /// placeholders), and where each one's lines are, in order: for
1420
    /// history-only states, which read text only for the graphs they build
1421
    /// (see [`Change::decode_skeleton`]).
1422537×
    pub fn get_change_lazy(&self, r: &ObjectRef) -> Result<(Change, Vec<crate::objects::TextRef>)> {
1423537×
        let bytes = self.get_typed(r, ObjectType::Change)?;
1424535×
        Change::decode_skeleton(&bytes, *r).map_err(|e| StoreError::Corrupt(*r, e.to_string()))
1425537×
    }
1426
1427
    /// A change's metadata (id, dependencies, author, clock, message, kind)
1428
    /// without its contents: read from its skeleton, so neither its text
1429
    /// blobs nor its inline lines are read (spec §11).
1430
    ///
1431
    /// Served from the `metas` cache when this store read it before (a
1432
    /// change object can be as large as the tree it adds), as long as the
1433
    /// store still has the change.
14344277×
    pub fn get_change_meta(&self, r: &ObjectRef) -> Result<crate::state::ChangeMeta> {
14354277×
        if self.metas.borrow().is_none() {
1436896×
            *self.metas.borrow_mut() = Some(self.read_metas_cache());
14373381×
        }
14384277×
        let cached = self.metas.borrow().as_ref().and_then(|m| m.get(r).cloned());
14394277×
        if let Some(meta) = cached {
14403068×
            if self.has(r) {
1441
                #[cfg(test)]
14421709×
                assert_eq!(
1443
                    meta,
14441709×
                    Change::decode_meta(&self.get_typed(r, ObjectType::Change)?).unwrap(),
1445
                    "the metadata cache holds a change's metadata"
1446
                );
14473068×
                return Ok(meta);
14480×
            }
14491209×
        }
14501209×
        let bytes = self.get_typed(r, ObjectType::Change)?;
14511209×
        let meta =
14521209×
            Change::decode_meta(&bytes).map_err(|e| StoreError::Corrupt(*r, e.to_string()))?;
14531209×
        self.remember_meta(r, &meta);
14541209×
        Ok(meta)
14554277×
    }
1456
1457
    /// The metadata cache: records of a change hash, its metadata in the
1458
    /// flat layout, and the first 8 bytes of BLAKE3 over both, each
1459
    /// appended in one write. Derived only: a record that does not check
1460
    /// ends the reading (a torn write), and the cache can be deleted. It
1461
    /// lives in the scratch directory, on this disk.
1462896×
    fn read_metas_cache(&self) -> crate::fasthash::FastMap<ObjectRef, crate::state::ChangeMeta> {
1463896×
        let mut out = crate::fasthash::FastMap::default();
1464896×
        let Ok(bytes) = fs::read(self.scratch.join("metas")) else {
1465349×
            return out;
1466
        };
1467547×
        let mut r = crate::flat::Reader::new(&bytes);
1468547×
        let mut good = 0;
14691882×
        while !r.at_end() {
14701336×
            let mut record = || -> std::result::Result<_, ObjectError> {
14711336×
                let h = r.object()?;
14721335×
                let body = r.bytes()?;
14731335×
                let check = r.fixed::<8>()?;
14741335×
                Ok((h, body, check))
14751336×
            };
14761336×
            let Ok((h, body, check)) = record() else {
14771×
                break;
1478
            };
14791335×
            let mut sum = blake3::Hasher::new();
14801335×
            sum.update(&h.0).update(body);
14811335×
            if sum.finalize().as_bytes()[..8] != check {
14820×
                break;
14831335×
            }
14841335×
            match crate::state::ChangeMeta::read_flat(&mut crate::flat::Reader::new(body)) {
14851335×
                Ok(m) => out.insert(h, m),
14860×
                Err(_) => break,
1487
            };
14881335×
            good += 32 + 4 + body.len() + 8;
1489
        }
1490
        // Cut a bad tail, so records appended later are read.
1491547×
        if good < bytes.len() {
14921×
            let _ = fs::OpenOptions::new()
14931×
                .write(true)
14941×
                .open(self.scratch.join("metas"))
14951×
                .and_then(|f| f.set_len(good as u64));
1496546×
        }
1497547×
        out
1498896×
    }
1499
1500
    /// Add a change's metadata to the cache; quietly nothing when it
1501
    /// cannot be written (it is only a cache).
15021209×
    fn remember_meta(&self, r: &ObjectRef, meta: &crate::state::ChangeMeta) {
15031209×
        let mut body = crate::flat::Writer::default();
15041209×
        meta.write_flat(&mut body);
15051209×
        let mut w = crate::flat::Writer::default();
15061209×
        w.object(r);
15071209×
        w.bytes(&body.0);
15081209×
        let mut sum = blake3::Hasher::new();
15091209×
        sum.update(&r.0).update(&body.0);
15101209×
        w.fixed(&sum.finalize().as_bytes()[..8]);
15111209×
        let _ = fs::OpenOptions::new()
15121209×
            .create(true)
15131209×
            .append(true)
15141209×
            .open(self.scratch.join("metas"))
15151209×
            .and_then(|mut f| f.write_all(&w.0));
15161209×
        if let Some(m) = self.metas.borrow_mut().as_mut() {
15171209×
            m.insert(*r, meta.clone());
15181209×
        }
15191209×
    }
1520
152159×
    fn read_text(&self, r: &ObjectRef) -> Result<(Blob, Vec<u8>)> {
152259×
        let blob = Blob::decode(&self.get_typed(r, ObjectType::Blob)?)?;
152358×
        let mut content = Vec::with_capacity(blob.length as usize);
152498×
        for c in &blob.chunks {
152598×
            content.extend(self.get_typed(c, ObjectType::Chunk)?);
1526
        }
152758×
        Ok((blob, content))
152859×
    }
1529
1530194×
    pub fn put_chunk(&self, bytes: &[u8]) -> Result<ObjectRef> {
1531194×
        self.put(ObjectType::Chunk, bytes)
1532194×
    }
1533
1534
    /// Store a chunk that packs will keep uncompressed (`nocompress`, spec §13.3).
1535123×
    pub fn put_chunk_nocompress(&self, bytes: &[u8]) -> Result<ObjectRef> {
1536123×
        let r = hash_object(ObjectType::Chunk, bytes);
1537123×
        put_new_or_existing(
1538123×
            self.backend.as_ref(),
1539123×
            &format!("nocompress/{}", r.to_hex()),
1540123×
            b"",
15410×
        )?;
1542123×
        self.put(ObjectType::Chunk, bytes)
1543123×
    }
1544
15451900×
    fn is_nocompress(&self, r: &ObjectRef) -> bool {
15461900×
        self.backend
15471900×
            .has(&format!("nocompress/{}", r.to_hex()))
15481900×
            .unwrap_or(false)
15491900×
    }
1550
1551
    /// Every chunk marked to be kept raw.
155273×
    fn nocompress_set(&self) -> Result<std::collections::HashSet<ObjectRef>> {
155373×
        Ok(self
155473×
            .backend
155573×
            .list("nocompress/")
155673×
            .map_err(backend_err)?
155773×
            .into_iter()
155873×
            .filter_map(|e| ObjectRef::from_hex(e.key.trim_start_matches("nocompress/")))
155973×
            .collect())
156073×
    }
1561
15622826×
    pub fn put_state(&self, st: &StateObject) -> Result<ObjectRef> {
15632826×
        self.put(ObjectType::State, &st.encode())
15642826×
    }
1565
15665091×
    pub fn get_state(&self, r: &ObjectRef) -> Result<StateObject> {
15675091×
        Ok(StateObject::decode(&self.get_typed(r, ObjectType::State)?)?)
15685091×
    }
1569
1570328×
    pub fn put_attest(&self, a: &Attest) -> Result<ObjectRef> {
1571328×
        self.put(ObjectType::Attest, &a.encode())
1572328×
    }
1573
1574533×
    pub fn get_attest(&self, r: &ObjectRef) -> Result<Attest> {
1575533×
        Ok(Attest::decode(&self.get_typed(r, ObjectType::Attest)?)?)
1576533×
    }
1577
15782×
    pub fn put_receipt(&self, r: &Receipt) -> Result<ObjectRef> {
15792×
        self.put(ObjectType::Receipt, &r.encode())
15802×
    }
1581
15828×
    pub fn get_receipt(&self, r: &ObjectRef) -> Result<Receipt> {
15838×
        Ok(Receipt::decode(&self.get_typed(r, ObjectType::Receipt)?)?)
15848×
    }
1585
1586
    /// Record `value` under `key` in `index`: one write-once entry, so two
1587
    /// writers of a shared store never lose each other's.
1588124×
    fn index_add(&self, index: &str, key: &ObjectRef, value: &ObjectRef) -> Result<()> {
1589124×
        let entry = format!("{}{}", fanout_prefix(index, key), value.to_hex());
1590124×
        put_new_or_existing(self.backend.as_ref(), &entry, b"")
1591124×
    }
1592
1593
    /// The values recorded under `key` in `index`, with those an older
1594
    /// store kept as one list in `legacy`, sorted.
15951328×
    fn index_get(&self, index: &str, legacy: &str, key: &ObjectRef) -> Result<Vec<ObjectRef>> {
15961328×
        let mut values: Vec<ObjectRef> = self
15971328×
            .backend
15981328×
            .list(&fanout_prefix(index, key))
15991328×
            .map_err(backend_err)?
16001328×
            .into_iter()
16011328×
            .filter_map(|e| e.key.rsplit('/').next().and_then(ObjectRef::from_hex))
16021328×
            .collect();
16031328×
        if let Some(bytes) = get_optional(self.backend.as_ref(), &legacy_key(legacy, key))? {
16043×
            values.extend(
16053×
                String::from_utf8_lossy(&bytes)
16063×
                    .lines()
16073×
                    .filter_map(ObjectRef::from_hex),
16083×
            );
16091325×
        }
16101328×
        values.sort();
16111328×
        values.dedup();
16121328×
        Ok(values)
16131328×
    }
1614
1615
    /// Record that seal attestation `attest` covers `change`.
1616119×
    pub fn index_seal(&self, change: &ObjectRef, attest: &ObjectRef) -> Result<()> {
1617119×
        self.index_add("seal", change, attest)
1618119×
    }
1619
1620
    /// Seal attestations known to cover `change`.
16211312×
    pub fn seals_for(&self, change: &ObjectRef) -> Result<Vec<ObjectRef>> {
16221312×
        self.index_get("seal", "seals", change)
16231312×
    }
1624
1625
    /// Record receipt attestation `attest` for `state` (spec §14.6).
16264×
    pub fn index_receipt(&self, state: &ObjectRef, attest: &ObjectRef) -> Result<()> {
16274×
        self.index_add("receipt", state, attest)
16284×
    }
1629
1630
    /// Receipt attestations recorded for `state`.
163113×
    pub fn receipts_for(&self, state: &ObjectRef) -> Result<Vec<ObjectRef>> {
163213×
        self.index_get("receipt", "receipts", state)
163313×
    }
1634
16351×
    pub fn index_approval(&self, state: &ObjectRef, attest: &ObjectRef) -> Result<()> {
16361×
        self.index_add("approval", state, attest)
16371×
    }
1638
1639
    /// Approval attestations recorded for `state` (OxygenFlow approval
1640
    /// gates, oxygenhub#235).
16413×
    pub fn approvals_for(&self, state: &ObjectRef) -> Result<Vec<ObjectRef>> {
16423×
        self.index_get("approval", "approvals", state)
16433×
    }
1644
1645
    /// Every state with an approval, for garbage collection.
164617×
    pub fn approval_states(&self) -> Result<Vec<ObjectRef>> {
164717×
        self.indexed_states("approval", "approvals")
164817×
    }
1649
1650
    /// Every state with a receipt, for garbage collection.
165123×
    pub fn receipt_states(&self) -> Result<Vec<ObjectRef>> {
165223×
        self.indexed_states("receipt", "receipts")
165323×
    }
1654
1655
    /// The states an index (`one/<hh>/<rest>/<attest>` entries, and the
1656
    /// packed `many/<hh>/<rest>` lists) holds attestations for.
165740×
    fn indexed_states(&self, one: &str, many: &str) -> Result<Vec<ObjectRef>> {
165840×
        let mut out: Vec<ObjectRef> = Vec::new();
165940×
        for e in self.backend.list(&format!("{one}/")).map_err(backend_err)? {
1660
            // receipt/<hh>/<rest>/<attest>
16614×
            let mut parts = e.key.splitn(4, '/');
16624×
            let (Some(_), Some(hh), Some(rest), Some(_)) =
16634×
                (parts.next(), parts.next(), parts.next(), parts.next())
1664
            else {
16650×
                continue;
1666
            };
16674×
            out.extend(ObjectRef::from_hex(&format!("{hh}{rest}")));
1668
        }
166940×
        for e in self
167040×
            .backend
167140×
            .list(&format!("{many}/"))
167240×
            .map_err(backend_err)?
1673
        {
16741×
            let mut parts = e.key.splitn(3, '/');
16751×
            let (Some(_), Some(hh), Some(rest)) = (parts.next(), parts.next(), parts.next()) else {
16760×
                continue;
1677
            };
16781×
            out.extend(ObjectRef::from_hex(&format!("{hh}{rest}")));
1679
        }
168040×
        out.sort();
168140×
        out.dedup();
168240×
        Ok(out)
168340×
    }
1684
1685227×
    pub fn put_identity(&self, id: &Identity) -> Result<ObjectRef> {
1686227×
        self.put(ObjectType::Identity, &id.encode())
1687227×
    }
1688
1689681×
    pub fn get_identity(&self, r: &ObjectRef) -> Result<Identity> {
1690681×
        Ok(Identity::decode(&self.get_typed(r, ObjectType::Identity)?)?)
1691681×
    }
1692
1693
    /// Signatures stored alongside object `r` (spec §5.4), one per signing
1694
    /// key, sorted by key. Empty if none.
16952388×
    pub fn signatures(&self, r: &ObjectRef) -> Result<Vec<Signature>> {
16962388×
        let mut sigs: Vec<Signature> = Vec::new();
16972388×
        for e in self
16982388×
            .backend
16992388×
            .list(&fanout_prefix("sig", r))
17002388×
            .map_err(backend_err)?
1701
        {
17021265×
            let bytes = self.backend.get(&e.key).map_err(backend_err)?;
17031265×
            sigs.extend(Signature::decode_list(&bytes)?);
1704
        }
1705
        // An older store's one list per object; a signer kept there and
1706
        // here counts once, as written here.
17072388×
        if let Some(bytes) = get_optional(self.backend.as_ref(), &legacy_key("sigs", r))? {
17082×
            for sig in Signature::decode_list(&bytes)? {
17092×
                if !sigs.iter().any(|s| s.key == sig.key) {
17101×
                    sigs.push(sig);
17111×
                }
1712
            }
17132386×
        }
17142388×
        sigs.sort_by_key(|s| s.key);
17152388×
        sigs.dedup_by_key(|s| s.key);
17162388×
        Ok(sigs)
17172388×
    }
1718
1719
    /// Attach a signature to object `r`, replacing any earlier one by the
1720
    /// same key: one entry per signer, so the latest by a key is the one
1721
    /// kept, and two signers never touch each other's.
1722493×
    pub fn put_signature(&self, r: &ObjectRef, sig: &Signature) -> Result<()> {
1723493×
        let key = format!("{}{}", fanout_prefix("sig", r), sig.key.to_hex());
1724493×
        let bytes = Signature::encode_list(std::slice::from_ref(sig));
1725493×
        if get_optional(self.backend.as_ref(), &key)?.as_deref() == Some(bytes.as_slice()) {
172622×
            return Ok(());
1727471×
        }
1728471×
        delete(self.backend.as_ref(), &key)?;
1729471×
        put_new_or_existing(self.backend.as_ref(), &key, &bytes)
1730493×
    }
1731
1732
    /// Finish packs a writer left unfinished: a batch writes its objects to
1733
    /// `.tmp-ID.pack` and only indexes it at the end, so a process that
1734
    /// stopped part way (an import killed after hours) leaves every object
1735
    /// in a pack nothing can read. Each such pack untouched for `min_age`
1736
    /// is read through: every whole entry checked against its reference,
1737
    /// a torn last one cut off, then indexed as a pack of the store.
1738
    /// Returns the packs and objects adopted.
17392×
    pub fn adopt_unfinished_packs(
17402×
        &self,
17412×
        min_age: std::time::Duration,
17422×
        progress: &dyn Fn(&str),
17432×
    ) -> Result<(usize, usize)> {
1744
        use std::io::{BufReader, Read};
17452×
        let mut packs = 0;
17462×
        let mut objects = 0;
17472×
        let Ok(dir) = fs::read_dir(&self.scratch) else {
17480×
            return Ok((0, 0));
1749
        };
17504×
        for entry in dir.flatten() {
17514×
            let name = entry.file_name().to_string_lossy().to_string();
17524×
            let Some(id) = name
17534×
                .strip_prefix(".tmp-")
17544×
                .and_then(|n| n.strip_suffix(".pack"))
1755
            else {
17562×
                continue;
1757
            };
17582×
            let path = entry.path();
17592×
            let meta = fs::metadata(&path)?;
17602×
            let age = meta
17612×
                .modified()
17622×
                .ok()
17632×
                .and_then(|m| m.elapsed().ok())
17642×
                .unwrap_or_default();
17652×
            if age < min_age {
17661×
                progress(&format!(
17671×
                    "{name}: written to {}s ago, left alone",
17681×
                    age.as_secs()
17691×
                ));
17701×
                continue;
17711×
            }
17721×
            let mut f = BufReader::with_capacity(1 << 20, fs::File::open(&path)?);
17731×
            let mut magic = [0u8; 8];
17741×
            if f.read_exact(&mut magic).is_err() || &magic != PACK_MAGIC {
17750×
                progress(&format!("{name}: not a pack, left alone"));
17760×
                continue;
17771×
            }
17781×
            let mut offset = PACK_MAGIC.len() as u64;
17791×
            let mut index: Vec<(ObjectRef, PackEntry)> = Vec::new();
1780
            loop {
1781301×
                let mut head = [0u8; 42];
1782301×
                if f.read_exact(&mut head).is_err() {
17830×
                    break;
1784301×
                }
1785301×
                let Some(ty) = ObjectType::ALL.get(head[0] as usize).copied() else {
17860×
                    break;
1787
                };
1788301×
                let flags = head[1];
1789301×
                let stored_len = u32::from_le_bytes(head[2..6].try_into().unwrap());
1790301×
                let raw_len = u32::from_le_bytes(head[6..10].try_into().unwrap());
1791301×
                let r = ObjectRef(head[10..42].try_into().unwrap());
1792301×
                let mut stored = vec![0u8; stored_len as usize];
1793301×
                if flags & FLAG_DICT != 0 || f.read_exact(&mut stored).is_err() {
17941×
                    break;
1795300×
                }
1796300×
                let e = PackEntry {
1797300×
                    offset: offset + 42,
1798300×
                    stored_len,
1799300×
                    raw_len,
1800300×
                    ty,
1801300×
                    flags,
1802300×
                };
1803300×
                if decode_entry(&r, e, stored, None).is_err() {
18040×
                    break;
1805300×
                }
1806300×
                index.push((r, e));
1807300×
                offset += 42 + stored_len as u64;
1808300×
                if index.len().is_multiple_of(200_000) {
18090×
                    progress(&format!(
18100×
                        "{name}: {} objects checked, {} MiB",
18110×
                        index.len(),
18120×
                        offset >> 20
18130×
                    ));
1814300×
                }
1815
            }
18161×
            if index.is_empty() {
18170×
                progress(&format!("{name}: no whole object, left alone"));
18180×
                continue;
18191×
            }
18201×
            if offset < meta.len() {
18211×
                progress(&format!(
18221×
                    "{name}: {} torn bytes at the end cut off",
18231×
                    meta.len() - offset
18241×
                ));
18251×
                fs::OpenOptions::new()
18261×
                    .write(true)
18271×
                    .open(&path)?
18281×
                    .set_len(offset)?;
18290×
            }
18301×
            index.sort_by_key(|(r, _)| *r);
18311×
            index.dedup_by_key(|(r, _)| *r);
18321×
            objects += index.len();
18331×
            packs += 1;
18341×
            progress(&format!("{name}: {} objects indexed", index.len()));
18351×
            self.finish_pack_files(id, &path, &index)?;
1836
        }
18372×
        Ok((packs, objects))
18382×
    }
1839
1840
    /// Every object reference in the store, loose and packed (slow; for gc and tests).
184186×
    pub fn list(&self) -> io::Result<Vec<ObjectRef>> {
184286×
        let mut out: Vec<ObjectRef> = self
184386×
            .loose_objects()
184486×
            .map_err(|e| io::Error::other(e.to_string()))?
184586×
            .into_iter()
184686×
            .map(|(r, _)| r)
184786×
            .collect();
184886×
        for p in self.packs.borrow().iter() {
184910×
            out.extend(p.refs.iter().copied());
185010×
        }
185186×
        out.sort();
185286×
        out.dedup();
185386×
        Ok(out)
185486×
    }
1855
}
1856
1857
/// A loose object's bytes, verified against `r`.
185846762×
fn parse_loose(data: &[u8], r: &ObjectRef) -> Result<Object> {
185946762×
    let nul = data
186046762×
        .iter()
1861664800×
        .position(|&b| b == 0)
186246762×
        .ok_or_else(|| StoreError::Corrupt(*r, "no header".into()))?;
186346762×
    let head = std::str::from_utf8(&data[..nul])
186446762×
        .map_err(|_| StoreError::Corrupt(*r, "header not UTF-8".into()))?;
186546762×
    let mut parts = head.split(' ');
186646762×
    let (Some("oxy1"), Some(ty), Some(len), None) =
186746762×
        (parts.next(), parts.next(), parts.next(), parts.next())
1868
    else {
18690×
        return Err(StoreError::Corrupt(*r, format!("bad header {head:?}")));
1870
    };
187146762×
    let ty = ObjectType::from_name(ty)
187246762×
        .ok_or_else(|| StoreError::Corrupt(*r, format!("unknown type {ty}")))?;
187346762×
    let len: usize = len
187446762×
        .parse()
187546762×
        .map_err(|_| StoreError::Corrupt(*r, "bad length".into()))?;
187646762×
    let body = &data[nul + 1..];
187746762×
    if body.len() != len {
18780×
        return Err(StoreError::Corrupt(
18790×
            *r,
18800×
            format!("length {} != header {len}", body.len()),
18810×
        ));
188246762×
    }
188346762×
    if hash_object(ty, body) != *r {
18844×
        return Err(StoreError::Corrupt(*r, "hash mismatch".into()));
188546758×
    }
188646758×
    Ok((ty, body.to_vec()))
188746762×
}
1888
1889
/// Whether the objects are files that a test may tamper with: not under
1890
/// `OXY_STORE_BACKEND=memory`.
1891
#[cfg(test)]
18926×
fn files_on_disk() -> bool {
18936×
    std::env::var_os("OXY_STORE_BACKEND").is_none()
18946×
}
1895
1896
#[cfg(test)]
1897
mod tests {
1898
    use super::*;
1899
1900
    /// The store under test twice: in a directory, and on a store in
1901
    /// memory with a scratch directory, as over a bucket.
19026×
    fn each_store(dir: &Path, f: impl Fn(&str, Store)) {
19036×
        f("directory", Store::open(dir.join("objects")).unwrap());
19046×
        f(
19056×
            "memory",
19066×
            Store::open_on(Arc::new(MemoryStore::new()), dir.join("scratch")).unwrap(),
19076×
        );
19086×
    }
1909
1910
    #[test]
19111×
    fn put_get_verify() {
19121×
        if !super::files_on_disk() {
19130×
            return;
19141×
        }
19151×
        let dir = tempfile::tempdir().unwrap();
19161×
        let s = Store::open(dir.path().join("objects")).unwrap();
19171×
        let r = s.put(ObjectType::Chunk, b"hello").unwrap();
19181×
        assert!(s.has(&r));
19191×
        assert_eq!(s.get(&r).unwrap(), (ObjectType::Chunk, b"hello".to_vec()));
19201×
        assert_eq!(s.put(ObjectType::Chunk, b"hello").unwrap(), r);
19211×
        assert_eq!(s.list().unwrap(), vec![r]);
19221×
        assert!(matches!(
19231×
            s.get_typed(&r, ObjectType::Blob),
1924
            Err(StoreError::WrongType(..))
1925
        ));
19261×
        assert!(matches!(
19271×
            s.get(&ObjectRef([9; 32])),
1928
            Err(StoreError::NotFound(_))
1929
        ));
1930
1931
        // Tamper: flip a byte, read must fail.
19321×
        let path = s.path_for(&r);
19331×
        let mut data = fs::read(&path).unwrap();
19341×
        let last = data.len() - 1;
19351×
        data[last] ^= 1;
19361×
        fs::write(&path, data).unwrap();
19371×
        assert!(matches!(s.get(&r), Err(StoreError::Corrupt(..))));
19381×
    }
1939
1940
    #[test]
19411×
    fn packing_keeps_every_object_readable() {
19421×
        if !super::files_on_disk() {
19430×
            return;
19441×
        }
19451×
        let dir = tempfile::tempdir().unwrap();
19461×
        let s = Store::open(dir.path()).unwrap();
19471×
        let mut refs = Vec::new();
1948300×
        for i in 0..300u32 {
1949300×
            let body = format!("object {i} ").repeat(1 + (i % 7) as usize);
1950300×
            refs.push((s.put(ObjectType::Chunk, body.as_bytes()).unwrap(), body));
1951300×
        }
19521×
        let c = crate::objects::tests::sample_change();
19531×
        let cr = s.put_change(&c).unwrap();
19541×
        assert_eq!(s.loose_count().unwrap(), 301);
19551×
        let report = s.pack_loose().unwrap();
19561×
        assert_eq!(report.objects, 301);
19571×
        assert!(report.packed_bytes < report.raw_bytes, "{report:?}");
19581×
        assert_eq!(s.loose_count().unwrap(), 0);
19591×
        assert_eq!(s.pack_count(), 1);
1960300×
        for (r, body) in &refs {
1961300×
            assert!(s.has(r));
1962300×
            assert_eq!(
1963300×
                s.get(r).unwrap(),
1964300×
                (ObjectType::Chunk, body.as_bytes().to_vec())
1965
            );
1966
        }
19671×
        assert_eq!(s.get_change(&cr).unwrap(), c);
19681×
        assert_eq!(s.list().unwrap().len(), 301);
1969
        // Re-putting a packed object is a no-op; new objects go loose and a
1970
        // second pack coexists with the first.
19711×
        assert_eq!(
19721×
            s.put(ObjectType::Chunk, refs[0].1.as_bytes()).unwrap(),
19731×
            refs[0].0
1974
        );
19751×
        assert_eq!(s.loose_count().unwrap(), 0);
19761×
        let extra = s.put(ObjectType::Chunk, b"after packing").unwrap();
19771×
        s.pack_loose().unwrap();
19781×
        assert_eq!(s.pack_count(), 2);
19791×
        assert_eq!(s.get(&extra).unwrap().1, b"after packing");
1980
        // A reopened store sees the packs.
19811×
        let s2 = Store::open(dir.path()).unwrap();
19821×
        assert_eq!(s2.pack_count(), 2);
19831×
        assert_eq!(s2.get(&refs[5].0).unwrap().1, refs[5].1.as_bytes());
19841×
        assert!(matches!(
19851×
            s2.get(&ObjectRef([9; 32])),
1986
            Err(StoreError::NotFound(_))
1987
        ));
1988
        // Corrupting an object's body inside the pack is detected on read.
19891×
        let target = refs[5].0;
19901×
        let (pack_path, offset) = {
19911×
            let packs = s2.packs.borrow();
19921×
            let (i, e) = s2.find_packed(&target).unwrap();
19931×
            (dir.path().join(&packs[i].key), e.offset as usize)
19941×
        };
19951×
        let mut data = fs::read(&pack_path).unwrap();
19961×
        data[offset] ^= 0xff;
19971×
        fs::write(&pack_path, data).unwrap();
19981×
        let s3 = Store::open(dir.path()).unwrap();
19991×
        assert!(matches!(s3.get(&target), Err(StoreError::Corrupt(..))));
20001×
        assert_eq!(
20011×
            s3.get(&refs[6].0).unwrap().1,
20021×
            refs[6].1.as_bytes(),
2003
            "other objects are unaffected"
2004
        );
20051×
    }
2006
2007
    #[test]
20081×
    fn a_full_repack_trains_a_dictionary_and_reads_back() {
20091×
        if !super::files_on_disk() {
20100×
            return;
20111×
        }
20121×
        let dir = tempfile::tempdir().unwrap();
20131×
        let s = Store::open(dir.path()).unwrap();
2014
        // Many small, alike files: what a dictionary is for.
20151×
        let bodies: Vec<Vec<u8>> = (0..1500)
20161500×
            .map(|i| {
20171500×
                format!(
2018
                    "// SPDX-License-Identifier: GPL-2.0\n#include <linux/module.h>\n\
2019
                     static int probe_{i}(struct device *dev)\n{{\n\treturn {i};\n}}\n"
2020
                )
20211500×
                .into_bytes()
20221500×
            })
20231×
            .collect();
20241×
        let refs: Vec<ObjectRef> = bodies
20251×
            .iter()
20261500×
            .map(|b| s.put(ObjectType::Chunk, b).unwrap())
20271×
            .collect();
20281×
        s.repack_all(REPACK_ZSTD_LEVEL).unwrap();
20291×
        let dicts = fs::read_dir(dir.path())
20301×
            .unwrap()
20311×
            .flatten()
20323×
            .filter(|e| e.path().extension().is_some_and(|x| x == "dict"))
20331×
            .count();
20341×
        assert_eq!(dicts, 1, "the pack has a dictionary");
20351×
        let with_dict = refs
20361×
            .iter()
20371500×
            .filter(|r| s.find_packed(r).unwrap().1.flags & FLAG_DICT != 0)
20381×
            .count();
20391×
        assert!(with_dict > 1000, "most use it: {with_dict}");
20401×
        let again = Store::open(dir.path()).unwrap();
20411500×
        for (r, b) in refs.iter().zip(&bodies) {
20421500×
            assert_eq!(&again.get(r).unwrap().1, b);
2043
        }
20443×
        let packs = |dir: &Path| {
20453×
            let mut v: Vec<String> = fs::read_dir(dir)
20463×
                .unwrap()
20473×
                .flatten()
204811×
                .map(|e| e.file_name().to_string_lossy().into_owned())
204911×
                .filter(|n| n.starts_with("pack-"))
20503×
                .collect();
20513×
            v.sort();
20523×
            v
20533×
        };
2054
        // With nothing new, a repack leaves that pack as it is: it would
2055
        // only write the same again.
20561×
        let before = packs(dir.path());
20571×
        let (report, merged) = again.repack_all(REPACK_ZSTD_LEVEL).unwrap();
20581×
        assert_eq!((report.objects, merged), (0, 0));
20591×
        assert_eq!(packs(dir.path()), before);
2060
        // One new object: a repack replaces the pack and its dictionary.
20611×
        let extra = again.put(ObjectType::Chunk, b"one more\n").unwrap();
20621×
        again.repack_all(REPACK_ZSTD_LEVEL).unwrap();
20631×
        let files = packs(dir.path());
20641×
        assert_eq!(files.len(), 3, "one pack, index and dictionary: {files:?}");
20651×
        assert_ne!(files, before);
20661×
        assert_eq!(&again.get(&refs[7]).unwrap().1, &bodies[7]);
20671×
        assert_eq!(again.get(&extra).unwrap().1, b"one more\n");
20681×
    }
2069
2070
    #[test]
20711×
    fn nocompress_chunks_pack_raw() {
20721×
        let dir = tempfile::tempdir().unwrap();
20731×
        let s = Store::open(dir.path()).unwrap();
20741×
        let body = vec![b'a'; 10_000];
20751×
        let raw = s.put_chunk_nocompress(&body).unwrap();
20761×
        let compressible = s.put(ObjectType::Chunk, &vec![b'b'; 10_000]).unwrap();
20771×
        s.pack_loose().unwrap();
20781×
        let packs = s.packs.borrow();
20791×
        let (i, e) = s.find_packed(&raw).unwrap();
20801×
        assert_eq!((e.flags, e.stored_len as usize), (0, 10_000));
20811×
        let (_, c) = s.find_packed(&compressible).unwrap();
20821×
        assert_eq!(c.flags, FLAG_ZSTD);
20831×
        assert!(c.stored_len < 10_000);
20841×
        assert_eq!(packs[i].fetch(s.backend.as_ref(), &raw, e).unwrap().1, body);
20851×
    }
2086
2087
    #[test]
20881×
    fn many_packs_merge_into_one() {
20891×
        let dir = tempfile::tempdir().unwrap();
20902×
        each_store(dir.path(), |which, s| {
20912×
            let mut refs = Vec::new();
209236×
            for i in 0..(MAX_PACKS + 2) {
209336×
                refs.push(
209436×
                    s.put(ObjectType::Chunk, format!("pack {i}").as_bytes())
209536×
                        .unwrap(),
209636×
                );
209736×
                s.pack_loose().unwrap();
209836×
            }
20992×
            assert_eq!(s.pack_count(), MAX_PACKS + 2, "{which}");
21002×
            assert_eq!(s.merge_packs().unwrap(), MAX_PACKS + 2);
21012×
            assert_eq!(s.pack_count(), 1);
21022×
            assert_eq!(s.merge_packs().unwrap(), 0);
210336×
            for (i, r) in refs.iter().enumerate() {
210436×
                assert_eq!(s.get(r).unwrap().1, format!("pack {i}").as_bytes());
2105
            }
21062×
            let again = Store::open_on(s.backend().clone(), s.dir()).unwrap();
21072×
            assert_eq!(again.pack_count(), 1, "{which}: reopened");
21082×
        });
21091×
    }
2110
2111
    #[test]
21121×
    fn prune_removes_unreachable_loose_and_packed_objects() {
2113
        use std::collections::HashSet;
21141×
        let dir = tempfile::tempdir().unwrap();
21152×
        each_store(dir.path(), |which, s| {
21162×
            let keep_a = s.put(ObjectType::Chunk, b"keep a").unwrap();
21172×
            let drop_a = s.put(ObjectType::Chunk, b"drop a").unwrap();
21182×
            s.pack_loose().unwrap();
21192×
            let keep_b = s.put(ObjectType::Chunk, b"keep b").unwrap();
21202×
            let drop_b = s.put(ObjectType::Chunk, b"drop b").unwrap();
21212×
            let sk = crate::identity::SecretKey {
21222×
                ed_seed: [1; 32],
21232×
                ml_seed: [2; 32],
21242×
            };
21252×
            let id = sk.identity("a", "b", 0);
21262×
            let key = s.put_identity(&id).unwrap();
21272×
            s.put_signature(
21282×
                &drop_b,
21292×
                &sk.sign(crate::identity::Domain::Change, &key, &drop_b),
2130
            )
21312×
            .unwrap();
21322×
            s.index_seal(&drop_a, &ObjectRef([3; 32])).unwrap();
21332×
            let keep: HashSet<ObjectRef> = [keep_a, keep_b, key].into_iter().collect();
2134
            // Everything is too young under a grace period.
21352×
            let r = s
21362×
                .prune(&keep, std::time::Duration::from_secs(3600))
21372×
                .unwrap();
21382×
            assert_eq!((r.objects, r.deferred), (0, 2), "{which}");
21392×
            let r = s.prune(&keep, std::time::Duration::ZERO).unwrap();
21402×
            assert_eq!(r.objects, 2, "{which}: {r:?}");
21412×
            assert!(s.has(&keep_a) && s.has(&keep_b) && s.has(&key));
21422×
            assert!(!s.has(&drop_a) && !s.has(&drop_b));
21432×
            assert!(s.signatures(&drop_b).unwrap().is_empty());
21442×
            assert!(s.seals_for(&drop_a).unwrap().is_empty());
21452×
            assert_eq!(s.pack_count(), 1);
21462×
            assert_eq!(s.get(&keep_a).unwrap().1, b"keep a");
21472×
            assert_eq!(s.list().unwrap().len(), 3);
21482×
        });
21491×
    }
2150
2151
    #[test]
21521×
    fn signatures_are_stored_beside_objects() {
2153
        use crate::identity::{Domain, SecretKey};
21541×
        let dir = tempfile::tempdir().unwrap();
21552×
        each_store(dir.path(), |which, s| {
21562×
            let r = s.put(ObjectType::Chunk, b"x").unwrap();
21572×
            assert!(s.signatures(&r).unwrap().is_empty());
21582×
            let sk = SecretKey {
21592×
                ed_seed: [1; 32],
21602×
                ml_seed: [2; 32],
21612×
            };
21622×
            let id = sk.identity("a", "b", 0);
21632×
            let key = s.put_identity(&id).unwrap();
21642×
            assert_eq!(s.get_identity(&key).unwrap(), id);
21652×
            let sig = sk.sign(Domain::Change, &key, &r);
21662×
            s.put_signature(&r, &sig).unwrap();
21672×
            s.put_signature(&r, &sig).unwrap();
21682×
            assert_eq!(s.signatures(&r).unwrap(), vec![sig.clone()], "{which}");
2169
            // A second signer is kept beside the first, sorted by key.
21702×
            let sk2 = SecretKey {
21712×
                ed_seed: [3; 32],
21722×
                ml_seed: [4; 32],
21732×
            };
21742×
            let key2 = s.put_identity(&sk2.identity("c", "d", 0)).unwrap();
21752×
            let sig2 = sk2.sign(Domain::Change, &key2, &r);
21762×
            s.put_signature(&r, &sig2).unwrap();
21772×
            let mut both = vec![sig.clone(), sig2.clone()];
21782×
            both.sort_by_key(|s| s.key);
21792×
            assert_eq!(s.signatures(&r).unwrap(), both);
2180
            // The object itself is untouched by its signatures.
21812×
            assert_eq!(s.get(&r).unwrap().1, b"x");
2182
            // Seal and receipt entries, and the states with receipts.
21832×
            s.index_seal(&r, &ObjectRef([5; 32])).unwrap();
21842×
            s.index_seal(&r, &ObjectRef([4; 32])).unwrap();
21852×
            s.index_seal(&r, &ObjectRef([5; 32])).unwrap();
21862×
            assert_eq!(
21872×
                s.seals_for(&r).unwrap(),
21882×
                vec![ObjectRef([4; 32]), ObjectRef([5; 32])]
2189
            );
21902×
            let st = ObjectRef([6; 32]);
21912×
            s.index_receipt(&st, &ObjectRef([7; 32])).unwrap();
21922×
            assert_eq!(s.receipts_for(&st).unwrap(), vec![ObjectRef([7; 32])]);
21932×
            assert_eq!(s.receipt_states().unwrap(), vec![st]);
21942×
        });
21951×
    }
2196
2197
    /// A store written before signatures, seals and receipts were one
2198
    /// entry each (`sigs/`, `seals/`, `receipts/` lists) still reads, and
2199
    /// what is written now sits beside what was there.
2200
    #[test]
22011×
    fn an_older_store_s_sidecar_lists_are_still_read() {
22021×
        if !super::files_on_disk() {
22030×
            return;
22041×
        }
2205
        use crate::identity::{Domain, SecretKey};
22061×
        let dir = tempfile::tempdir().unwrap();
22071×
        let s = Store::open(dir.path()).unwrap();
22081×
        let r = s.put(ObjectType::Chunk, b"old").unwrap();
22091×
        let h = r.to_hex();
22101×
        let sk = SecretKey {
22111×
            ed_seed: [1; 32],
22121×
            ml_seed: [2; 32],
22131×
        };
22141×
        let key = s.put_identity(&sk.identity("a", "b", 0)).unwrap();
22151×
        let sig = sk.sign(Domain::Change, &key, &r);
22161×
        let legacy = dir.path().join("sigs").join(&h[..2]);
22171×
        fs::create_dir_all(&legacy).unwrap();
22181×
        fs::write(
22191×
            legacy.join(&h[2..]),
22201×
            Signature::encode_list(std::slice::from_ref(&sig)),
2221
        )
22221×
        .unwrap();
22231×
        let seals = dir.path().join("seals").join(&h[..2]);
22241×
        fs::create_dir_all(&seals).unwrap();
22251×
        fs::write(
22261×
            seals.join(&h[2..]),
22271×
            format!("{}\n", ObjectRef([9; 32]).to_hex()),
2228
        )
22291×
        .unwrap();
22301×
        let receipts = dir.path().join("receipts").join(&h[..2]);
22311×
        fs::create_dir_all(&receipts).unwrap();
22321×
        fs::write(
22331×
            receipts.join(&h[2..]),
22341×
            format!("{}\n", ObjectRef([8; 32]).to_hex()),
2235
        )
22361×
        .unwrap();
2237
22381×
        assert_eq!(s.signatures(&r).unwrap(), vec![sig.clone()]);
22391×
        assert_eq!(s.seals_for(&r).unwrap(), vec![ObjectRef([9; 32])]);
22401×
        assert_eq!(s.receipts_for(&r).unwrap(), vec![ObjectRef([8; 32])]);
22411×
        assert_eq!(s.receipt_states().unwrap(), vec![r]);
2242
        // New entries join the old ones; the same signer is not doubled.
22431×
        s.put_signature(&r, &sig).unwrap();
22441×
        s.index_seal(&r, &ObjectRef([1; 32])).unwrap();
22451×
        assert_eq!(s.signatures(&r).unwrap().len(), 1);
22461×
        assert_eq!(
22471×
            s.seals_for(&r).unwrap(),
22481×
            vec![ObjectRef([1; 32]), ObjectRef([9; 32])]
2249
        );
2250
        // Pruning the object takes both layouts with it.
22511×
        let r2 = s.put(ObjectType::Chunk, b"kept").unwrap();
22521×
        let keep = [r2, key].into_iter().collect();
22531×
        s.prune(&keep, std::time::Duration::ZERO).unwrap();
22541×
        assert!(s.signatures(&r).unwrap().is_empty());
22551×
        assert!(s.seals_for(&r).unwrap().is_empty());
22561×
        assert!(s.receipt_states().unwrap().is_empty());
22571×
    }
2258
2259
    #[test]
22601×
    fn change_round_trip_through_store() {
22611×
        let dir = tempfile::tempdir().unwrap();
22622×
        each_store(dir.path(), |which, s| {
22632×
            let c = crate::objects::tests::sample_change();
22642×
            let r = s.put_change(&c).unwrap();
22652×
            assert_eq!(r, c.hash(), "{which}");
22662×
            assert_eq!(s.get_change(&r).unwrap(), c);
22672×
            assert_eq!(s.get_change_meta(&r).unwrap().message, c.message);
22682×
        });
22691×
    }
2270
22718057203×
    fn xorshift(state: &mut u64) -> u64 {
22728057203×
        *state ^= *state << 13;
22738057203×
        *state ^= *state >> 7;
22748057203×
        *state ^= *state << 17;
22758057203×
        *state
22768057203×
    }
2277
2278
    /// Random corruption of pack and index files never panics: reads fail
2279
    /// with an error or the store refuses to open, and untouched objects
2280
    /// stay readable when the index survives.
2281
    #[test]
22821×
    fn corrupted_packs_and_indexes_fail_cleanly() {
22831×
        if !super::files_on_disk() {
22840×
            return;
22851×
        }
22861×
        let dir = tempfile::tempdir().unwrap();
22871×
        let objects = dir.path().join("objects");
22881×
        let s = Store::open(&objects).unwrap();
22891×
        let mut refs = Vec::new();
22901×
        let mut seed = 0x9e3779b97f4a7c15u64;
229140×
        for i in 0..40u32 {
229240×
            let len = (xorshift(&mut seed) % 5000) as usize;
229340×
            let mut body = vec![0u8; len];
2294104686×
            for b in body.iter_mut() {
2295104686×
                *b = if i % 2 == 0 {
229656338×
                    (xorshift(&mut seed) & 0xff) as u8
2297
                } else {
229848348×
                    b'a' + (i % 26) as u8
2299
                };
2300
            }
230140×
            refs.push(s.put(ObjectType::Chunk, &body).unwrap());
2302
        }
23031×
        s.pack_loose().unwrap();
23041×
        let pack = fs::read_dir(&objects)
23051×
            .unwrap()
23062×
            .filter_map(|e| e.ok().map(|e| e.path()))
23072×
            .find(|p| p.extension().is_some_and(|x| x == "pack"))
23081×
            .unwrap();
23091×
        let idx = pack.with_extension("idx");
23101×
        let pristine_pack = fs::read(&pack).unwrap();
23111×
        let pristine_idx = fs::read(&idx).unwrap();
2312
2313300×
        for round in 0..300u32 {
2314300×
            let (path, pristine) = if round % 2 == 0 {
2315150×
                (&pack, &pristine_pack)
2316
            } else {
2317150×
                (&idx, &pristine_idx)
2318
            };
2319300×
            let mut data = pristine.clone();
2320300×
            match xorshift(&mut seed) % 4 {
232181×
                0 => {
232281×
                    let at = (xorshift(&mut seed) as usize) % data.len();
232381×
                    data[at] ^= 1 << (xorshift(&mut seed) % 8);
232481×
                }
232573×
                1 => {
232673×
                    let at = (xorshift(&mut seed) as usize) % data.len();
232773×
                    data[at] = (xorshift(&mut seed) & 0xff) as u8;
232873×
                }
232975×
                2 => {
233075×
                    let keep = (xorshift(&mut seed) as usize) % data.len();
233175×
                    data.truncate(keep);
233275×
                }
2333
                _ => {
233471×
                    let at = (xorshift(&mut seed) as usize) % data.len();
233571×
                    let n = ((xorshift(&mut seed) % 8) + 1) as usize;
2336324×
                    for k in 0..n.min(data.len() - at) {
2337324×
                        data[at + k] = 0xff;
2338324×
                    }
2339
                }
2340
            }
2341300×
            fs::write(path, &data).unwrap();
2342
            // Opening may refuse a broken index; a store that opens must
2343
            // either return each object intact or report it corrupt/missing.
2344300×
            if let Ok(s2) = Store::open(&objects) {
23457640×
                for r in &refs {
23467640×
                    match s2.get(r) {
23477452×
                        Ok((ty, body)) => assert_eq!(
23487452×
                            hash_object(ty, &body),
2349
                            *r,
2350
                            "a returned object always matches its reference"
2351
                        ),
2352
                        Err(StoreError::Corrupt(..))
2353
                        | Err(StoreError::NotFound(_))
2354188×
                        | Err(StoreError::Io(_)) => {}
23550×
                        Err(e) => panic!("unexpected error {e}"),
2356
                    }
2357
                }
2358109×
            }
2359300×
            fs::write(path, pristine).unwrap();
2360
        }
2361
        // Restored files read back in full.
23621×
        let s3 = Store::open(&objects).unwrap();
236340×
        for r in &refs {
236440×
            let (ty, body) = s3.get(r).unwrap();
236540×
            assert_eq!(hash_object(ty, &body), *r);
2366
        }
23671×
    }
2368
2369
    /// A small batch becomes loose objects; a large one becomes a single
2370
    /// pack. Objects are readable while pending, and batches nest.
2371
    #[test]
23721×
    fn batches_write_loose_or_one_pack() {
23731×
        let dir = tempfile::tempdir().unwrap();
23742×
        each_store(dir.path(), |which, s| {
23752×
            let outer = s.begin_batch().unwrap();
23762×
            let a = s.put(ObjectType::Chunk, b"small a").unwrap();
2377
            {
23782×
                let inner = s.begin_batch().unwrap();
23792×
                let b = s.put(ObjectType::Chunk, b"small b").unwrap();
23802×
                assert!(s.has(&b));
23812×
                assert_eq!(s.get(&b).unwrap().1, b"small b");
23822×
                inner.finish().unwrap();
23832×
                assert_eq!(
23842×
                    s.loose_count().unwrap(),
2385
                    0,
2386
                    "{which}: the inner batch defers to the outer one"
2387
                );
2388
            }
23892×
            assert_eq!(s.get(&a).unwrap().1, b"small a");
23902×
            assert_eq!(
23912×
                s.put(ObjectType::Chunk, b"small a").unwrap(),
2392
                a,
2393
                "idempotent while pending"
2394
            );
23952×
            outer.finish().unwrap();
23962×
            assert_eq!(s.loose_count().unwrap(), 2);
23972×
            assert_eq!(s.pack_count(), 0);
23982×
            assert_eq!(s.get(&a).unwrap().1, b"small a");
2399
2400
            // Large: spills into one pack, readable during and after.
24012×
            let big = s.begin_batch().unwrap();
24022×
            let mut refs = Vec::new();
24032×
            let mut seed = 7u64;
2404600×
            for i in 0..300u32 {
2405600×
                let mut body = vec![b'z'; 40_000];
2406600×
                if i % 3 == 0 {
24078000000×
                    for b in body.iter_mut() {
24088000000×
                        *b = (xorshift(&mut seed) & 0xff) as u8;
24098000000×
                    }
2410400×
                }
2411600×
                body[..4].copy_from_slice(&i.to_le_bytes());
2412600×
                let r = if i % 5 == 0 {
2413120×
                    s.put_chunk_nocompress(&body).unwrap()
2414
                } else {
2415480×
                    s.put(ObjectType::Chunk, &body).unwrap()
2416
                };
2417600×
                assert_eq!(
2418600×
                    s.get(&r).unwrap().1,
2419
                    body,
2420
                    "readable while pending (object {i})"
2421
                );
2422600×
                refs.push((r, body));
2423
            }
24242×
            assert!(s.has(&refs[0].0));
24252×
            big.finish().unwrap();
24262×
            assert_eq!(s.pack_count(), 1);
24272×
            assert_eq!(
24282×
                s.loose_count().unwrap(),
2429
                2,
2430
                "nothing from the big batch is loose"
2431
            );
24322×
            assert!(fs::read_dir(s.dir())
24332×
                .unwrap()
24342×
                .flatten()
24354×
                .all(|e| !e.file_name().to_string_lossy().contains("tmp-")));
24362×
            let s2 = Store::open_on(s.backend().clone(), s.dir()).unwrap();
2437600×
            for (r, body) in &refs {
2438600×
                assert_eq!(s2.get(r).unwrap().1, *body);
2439
            }
2440
            // A dropped batch still writes its objects.
24412×
            {
24422×
                let _b = s2.begin_batch().unwrap();
24432×
                s2.put(ObjectType::Chunk, b"dropped").unwrap();
24442×
            }
24452×
            assert_eq!(
24462×
                s2.get(&hash_object(ObjectType::Chunk, b"dropped"))
24472×
                    .unwrap()
2448
                    .1,
2449
                b"dropped"
2450
            );
24512×
        });
24521×
    }
2453
2454
    #[test]
24551×
    fn get_many_reads_loose_and_packed_objects_in_order() {
24561×
        let dir = tempfile::tempdir().unwrap();
24572×
        each_store(dir.path(), |which, s| {
24582×
            let packed: Vec<ObjectRef> = (0..20)
245940×
                .map(|i| {
246040×
                    s.put(ObjectType::Chunk, format!("packed {i}").as_bytes())
246140×
                        .unwrap()
246240×
                })
24632×
                .collect();
24642×
            s.pack_loose().unwrap();
24652×
            let loose: Vec<ObjectRef> = (0..20)
246640×
                .map(|i| {
246740×
                    s.put(ObjectType::Chunk, format!("loose {i}").as_bytes())
246840×
                        .unwrap()
246940×
                })
24702×
                .collect();
24712×
            let missing = hash_object(ObjectType::Chunk, b"never stored");
24722×
            let mut refs: Vec<ObjectRef> = Vec::new();
247340×
            for i in 0..20 {
247440×
                refs.push(loose[i]);
247540×
                refs.push(packed[i]);
247640×
            }
24772×
            refs.push(missing);
24782×
            let got = s.get_many(&refs);
24792×
            assert_eq!(got.len(), refs.len());
248080×
            for (i, r) in refs.iter().enumerate().take(40) {
248180×
                let want = if i % 2 == 0 {
248240×
                    format!("loose {}", i / 2)
2483
                } else {
248440×
                    format!("packed {}", i / 2)
2485
                };
248680×
                let (ty, body) = got[i].as_ref().unwrap();
248780×
                assert_eq!(
248880×
                    (*ty, body.as_slice()),
248980×
                    (ObjectType::Chunk, want.as_bytes()),
2490
                    "{which}: {r:?}"
2491
                );
2492
            }
24932×
            assert!(matches!(got[40], Err(StoreError::NotFound(_))));
24942×
        });
24951×
    }
2496
2497
    /// A packed object is read from its pack without first asking the
2498
    /// backend for a loose copy (oxygenhub#228: on a bucket each such ask
2499
    /// was a request that found nothing, every time).
2500
    #[test]
25011×
    fn packed_objects_cost_no_loose_lookups() {
2502
        use std::sync::atomic::{AtomicUsize, Ordering};
2503
        struct Counting(MemoryStore, AtomicUsize);
2504
        impl crate::strata::Store for Counting {
25050×
            fn describe(&self) -> String {
25060×
                "counting".into()
25070×
            }
250810×
            fn has(&self, k: &str) -> crate::strata::Result<bool> {
250910×
                self.0.has(k)
251010×
            }
251117×
            fn get(&self, k: &str) -> crate::strata::Result<Vec<u8>> {
251217×
                if k.starts_with("loose/") {
251311×
                    self.1.fetch_add(1, Ordering::Relaxed);
251411×
                }
251517×
                self.0.get(k)
251617×
            }
251720×
            fn get_range(
251820×
                &self,
251920×
                k: &str,
252020×
                r: std::ops::Range<u64>,
252120×
            ) -> crate::strata::Result<Vec<u8>> {
252220×
                self.0.get_range(k, r)
252320×
            }
252412×
            fn put_new(&self, k: &str, b: &[u8]) -> crate::strata::Result<()> {
252512×
                self.0.put_new(k, b)
252612×
            }
25279×
            fn list(&self, p: &str) -> crate::strata::Result<Vec<crate::strata::Entry>> {
25289×
                self.0.list(p)
25299×
            }
253010×
            fn delete(&self, k: &str) -> crate::strata::Result<()> {
253110×
                self.0.delete(k)
253210×
            }
25330×
            fn read_ref(
25340×
                &self,
25350×
                k: &str,
25360×
            ) -> crate::strata::Result<Option<(Vec<u8>, crate::strata::Version)>> {
25370×
                self.0.read_ref(k)
25380×
            }
25390×
            fn write_ref(
25400×
                &self,
25410×
                k: &str,
25420×
                b: &[u8],
25430×
                e: Option<&crate::strata::Version>,
25440×
            ) -> crate::strata::Result<crate::strata::Version> {
25450×
                self.0.write_ref(k, b, e)
25460×
            }
2547
        }
25481×
        let dir = tempfile::tempdir().unwrap();
25491×
        let backend = Arc::new(Counting(MemoryStore::new(), AtomicUsize::new(0)));
25501×
        let s = Store::open_on(backend.clone(), dir.path().join("scratch")).unwrap();
25511×
        let refs: Vec<ObjectRef> = (0..10)
255210×
            .map(|i| {
255310×
                s.put(ObjectType::Chunk, format!("p {i}").as_bytes())
255410×
                    .unwrap()
255510×
            })
25561×
            .collect();
25571×
        s.pack_loose().unwrap();
25581×
        let s = Store::open_on(backend.clone(), dir.path().join("scratch")).unwrap();
25591×
        backend.1.store(0, Ordering::Relaxed);
256010×
        for r in &refs {
256110×
            assert!(s.get(r).is_ok());
2562
        }
256310×
        assert!(s.get_many(&refs).iter().all(|g| g.is_ok()));
25641×
        assert_eq!(backend.1.load(Ordering::Relaxed), 0, "no loose lookups");
2565
        // An object no pack holds is still looked for loose.
25661×
        let missing = hash_object(ObjectType::Chunk, b"never stored");
25671×
        assert!(matches!(s.get(&missing), Err(StoreError::NotFound(_))));
25681×
        assert!(backend.1.load(Ordering::Relaxed) > 0);
25691×
    }
2570
}
2571
2572
#[cfg(test)]
2573
mod batch_tests {
2574
    use super::*;
2575
2576
    #[test]
25771×
    fn a_large_batch_packs_every_object_and_indexes_them_all() {
25781×
        let dir = tempfile::tempdir().unwrap();
25791×
        let store = Store::open(dir.path()).unwrap();
25801×
        let mut refs = Vec::new();
2581
        {
25821×
            let batch = store.begin_batch().unwrap();
25831000×
            for i in 0..1000u32 {
25841000×
                let body = format!("object {i} {}", "x".repeat(20_000 + i as usize)).into_bytes();
25851000×
                refs.push(store.put(ObjectType::Blob, &body).unwrap());
25861000×
            }
25871×
            batch.finish().unwrap();
2588
        }
25891×
        let again = Store::open(dir.path()).unwrap();
25901000×
        for r in &refs {
25911000×
            again
25921000×
                .get(r)
25931000×
                .unwrap_or_else(|e| panic!("{}: {e}", r.short(12)));
2594
        }
25951×
    }
2596
2597
    #[test]
25981×
    fn a_pack_a_stopped_batch_left_is_adopted_and_its_torn_end_cut() {
2599
        // oxygen#79: a batch never finished (a process killed part way)
2600
        // leaves its objects in an unindexed .tmp pack.
26011×
        let dir = tempfile::tempdir().unwrap();
26021×
        let mut refs = Vec::new();
2603
        {
26041×
            let store = Store::open(dir.path()).unwrap();
26051×
            let batch = store.begin_batch().unwrap();
2606300×
            for i in 0..300u32 {
2607300×
                let body = format!("object {i} {}", "y".repeat(20_000 + i as usize)).into_bytes();
2608300×
                refs.push(store.put(ObjectType::Blob, &body).unwrap());
2609300×
            }
26101×
            std::mem::forget(batch);
2611
        }
26121×
        let tmp: Vec<_> = fs::read_dir(dir.path())
26131×
            .unwrap()
26141×
            .flatten()
26152×
            .filter(|e| e.file_name().to_string_lossy().starts_with(".tmp-"))
26161×
            .map(|e| e.path())
26171×
            .collect();
26181×
        assert_eq!(tmp.len(), 1, "one unfinished pack");
2619
        // A torn last entry: a header and part of its body.
26201×
        let mut f = fs::OpenOptions::new().append(true).open(&tmp[0]).unwrap();
26211×
        f.write_all(&[0, 1, 0xff, 0, 0, 0, 9, 9, 0, 0]).unwrap();
26221×
        f.write_all(&[7; 40]).unwrap();
26231×
        drop(f);
26241×
        let store = Store::open(dir.path()).unwrap();
26251×
        assert!(store.get(&refs[0]).is_err(), "unreadable before");
26261×
        let young = store
26271×
            .adopt_unfinished_packs(std::time::Duration::from_secs(3600), &|_| {})
26281×
            .unwrap();
26291×
        assert_eq!(young, (0, 0), "a pack written to lately is left alone");
26301×
        let (packs, objects) = store
26312×
            .adopt_unfinished_packs(std::time::Duration::ZERO, &|_| {})
26321×
            .unwrap();
26331×
        assert_eq!((packs, objects), (1, 300));
2634300×
        for r in &refs {
2635300×
            store
2636300×
                .get(r)
2637300×
                .unwrap_or_else(|e| panic!("{}: {e}", r.short(12)));
2638
        }
26391×
        let again = Store::open(dir.path()).unwrap();
26401×
        assert!(again.get(&refs[299]).is_ok(), "indexed for good");
26411×
    }
2642
}
2643
2644
#[cfg(test)]
2645
mod size_tests {
2646
    use super::*;
2647
2648
    #[test]
26491×
    fn an_object_over_the_limit_is_refused_and_nothing_is_written() {
26501×
        let dir = tempfile::tempdir().unwrap();
26511×
        let store = Store::open(dir.path()).unwrap();
26521×
        let big = vec![b'x'; MAX_OBJECT_LEN as usize + 1];
2653
        {
26541×
            let batch = store.begin_batch().unwrap();
26551×
            store.put(ObjectType::Blob, b"small").unwrap();
26561×
            let e = store.put(ObjectType::Change, &big).unwrap_err();
26571×
            assert!(
26581×
                matches!(e, StoreError::TooLarge { kind: "change", .. }),
2659
                "{e}"
2660
            );
26611×
            assert!(e.to_string().contains("commit it in parts"), "{e}");
26621×
            batch.finish().unwrap();
2663
        }
2664
        // The store still opens and reads what was written.
26651×
        let again = Store::open(dir.path()).unwrap();
26661×
        again.get(&hash_object(ObjectType::Blob, b"small")).unwrap();
26671×
    }
2668
}
2669
2670
#[cfg(test)]
2671
mod text_tests {
2672
    use super::*;
2673
    use crate::objects::{AtomRef, Edit, CHANGE_VERSION};
2674
26752×
    fn large_change() -> Change {
26762×
        let mut c = crate::objects::tests::sample_change();
26772×
        assert_eq!(c.version, CHANGE_VERSION);
26782×
        c.edits[0] = Edit::Insert {
26792×
            node: crate::ids::NodeId([7; 16]),
26802×
            after: AtomRef::Start,
26812×
            before: AtomRef::End,
26822×
            lines: (0..2000)
26834000×
                .map(|i| format!("line {i}\n").into_bytes())
26842×
                .collect(),
2685
        };
26862×
        c
26872×
    }
2688
2689
    #[test]
26901×
    fn a_large_insert_is_stored_beside_its_change_and_read_back() {
26911×
        let dir = tempfile::tempdir().unwrap();
26921×
        let s = Store::open(dir.path()).unwrap();
26931×
        let c = large_change();
26941×
        let r = s.put_change(&c).unwrap();
26951×
        assert_eq!(r, c.hash());
26961×
        let (_, body) = s.get(&r).unwrap();
26971×
        assert!(
26981×
            body.len() < 1024,
2699
            "the change holds a reference, not {} bytes of lines",
27000×
            body.len()
2701
        );
27021×
        let (back, parts) = s.get_change_parts(&r).unwrap();
27031×
        assert_eq!(back, c);
2704
        // The text blob and its chunk.
27051×
        assert_eq!(parts.len(), 2);
27062×
        for p in &parts {
27072×
            assert!(s.has(p));
2708
        }
2709
        // Storing it again writes nothing new.
27101×
        let n = s.list().unwrap().len();
27111×
        s.put_change(&c).unwrap();
27121×
        assert_eq!(s.list().unwrap().len(), n);
27131×
    }
2714
2715
    #[test]
27161×
    fn a_change_whose_text_blob_is_missing_is_reported_not_misread() {
27171×
        if !super::files_on_disk() {
27180×
            return;
27191×
        }
27201×
        let dir = tempfile::tempdir().unwrap();
27211×
        let s = Store::open(dir.path()).unwrap();
27221×
        let c = large_change();
27231×
        let r = s.put_change(&c).unwrap();
27241×
        let (_, parts) = s.get_change_parts(&r).unwrap();
27251×
        fs::remove_file(s.path_for(&parts[0])).unwrap();
27261×
        let e = s.get_change(&r).unwrap_err();
27271×
        assert!(
27281×
            matches!(&e, StoreError::Corrupt(h, why) if *h == r && why.contains("missing")),
2729
            "{e}"
2730
        );
27311×
    }
2732
}
2733
2734
#[cfg(test)]
2735
mod put_many_tests {
2736
    use super::*;
2737
2738
    #[test]
27391×
    fn many_objects_in_a_batch_are_compressed_together_and_all_read_back() {
27401×
        let dir = tempfile::tempdir().unwrap();
27411×
        let s = Store::open(dir.path()).unwrap();
27421×
        let before = s.put(ObjectType::Chunk, b"already here").unwrap();
27431×
        let bodies: Vec<Vec<u8>> = (0..200u32)
2744200×
            .map(|i| format!("chunk {i} ").repeat(6000).into_bytes())
27451×
            .collect();
27461×
        let mut objects: Vec<(ObjectType, &[u8])> = bodies
27471×
            .iter()
2748200×
            .map(|b| (ObjectType::Chunk, b.as_slice()))
27491×
            .collect();
27501×
        objects.push((ObjectType::Chunk, bodies[0].as_slice()));
27511×
        objects.push((ObjectType::Chunk, b"already here"));
27521×
        let refs = {
27531×
            let batch = s.begin_batch().unwrap();
27541×
            let refs = s.put_many(&objects).unwrap();
27551×
            batch.finish().unwrap();
27561×
            refs
2757
        };
27581×
        assert_eq!(refs.len(), objects.len());
27591×
        assert_eq!(refs[200], refs[0], "a repeat is the same object");
27601×
        assert_eq!(refs[201], before);
27611×
        let again = Store::open(dir.path()).unwrap();
2762202×
        for (r, b) in refs.iter().zip(&objects) {
2763202×
            assert_eq!(again.get(r).unwrap().1, b.1);
2764
        }
27651×
    }
2766
}