OXYGENHUB

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

2011 of 2137 lines run, 317 of 458 functions · run #321 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.
867994×
fn put_new_or_existing(backend: &Backend, key: &str, bytes: &[u8]) -> Result<()> {
877994×
    match backend.put_new(key, bytes) {
887994×
        Ok(()) | Err(BackendError::Exists(_)) => Ok(()),
890×
        Err(e) => Err(backend_err(e)),
90
    }
917994×
}
92
93
/// `get` as an option: `None` when there is no such key.
9456234×
fn get_optional(backend: &Backend, key: &str) -> Result<Option<Vec<u8>>> {
9556234×
    match backend.get(key) {
9648720×
        Ok(b) => Ok(Some(b)),
977514×
        Err(BackendError::NotFound(_)) => Ok(None),
980×
        Err(e) => Err(backend_err(e)),
99
    }
10056234×
}
101
1023176×
fn delete(backend: &Backend, key: &str) -> Result<()> {
1033176×
    backend.delete(key).map_err(backend_err)
1043176×
}
105
106
/// `loose/<hh>/<rest>`.
10789752×
fn loose_key(r: &ObjectRef) -> String {
10889752×
    let h = r.to_hex();
10989752×
    format!("loose/{}/{}", &h[..2], &h[2..])
11089752×
}
111
112
/// The object a loose key names, if it is one.
11317327×
fn loose_ref(key: &str) -> Option<ObjectRef> {
11417327×
    let rest = key.strip_prefix("loose/")?;
11517327×
    let (hh, tail) = rest.split_once('/')?;
11617327×
    if hh.len() != 2 || tail.contains('/') {
1170×
        return None;
11817327×
    }
11917327×
    ObjectRef::from_hex(&format!("{hh}{tail}"))
12017327×
}
121
122
/// `<index>/<hh>/<rest>/` for the entries kept under an object.
1235932×
fn fanout_prefix(index: &str, r: &ObjectRef) -> String {
1245932×
    let h = r.to_hex();
1255932×
    format!("{index}/{}/{}/", &h[..2], &h[2..])
1265932×
}
127
128
/// `<index>/<hh>/<rest>`: the one-file-per-object layout of older stores.
1295153×
fn legacy_key(index: &str, r: &ObjectRef) -> String {
1305153×
    let h = r.to_hex();
1315153×
    format!("{index}/{}/{}", &h[..2], &h[2..])
1325153×
}
133
13423×
fn now_ms() -> u64 {
13523×
    std::time::SystemTime::now()
13623×
        .duration_since(std::time::UNIX_EPOCH)
13723×
        .map(|d| d.as_millis() as u64)
13823×
        .unwrap_or(0)
13923×
}
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.
17115860×
fn decode_entry(
17215860×
    r: &ObjectRef,
17315860×
    e: PackEntry,
17415860×
    stored: Vec<u8>,
17515860×
    dict: Option<&Arc<zstd::dict::DecoderDictionary<'static>>>,
17615860×
) -> Result<Object> {
17715860×
    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}")))?
18411359×
    } else if e.flags & FLAG_ZSTD != 0 {
1856491×
        zstd::bulk::decompress(&stored, e.raw_len as usize)
1866491×
            .map_err(|err| StoreError::Corrupt(*r, format!("zstd: {err}")))?
187
    } else {
1884868×
        stored
189
    };
19015855×
    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×
        ));
19515736×
    }
19615736×
    Ok((e.ty, body))
19715860×
}
198
199
impl PackIndex {
2001142×
    fn load(backend: &Backend, idx_key: &str, pack_key: &str) -> Result<PackIndex> {
2011142×
        let data = backend.get(idx_key).map_err(backend_err)?;
2021142×
        let bad = |m: &str| StoreError::Corrupt(ObjectRef::ZERO, format!("{idx_key}: {m}"));
2031142×
        if data.len() < 12 || &data[..8] != IDX_MAGIC {
2042×
            return Err(bad("bad index header"));
2051140×
        }
2061140×
        let count = u32::from_le_bytes(data[8..12].try_into().unwrap()) as usize;
2071140×
        if data.len() != 12 + count * IDX_ENTRY {
20842×
            return Err(bad("index length mismatch"));
2091098×
        }
2101098×
        let pack_len = backend
2111098×
            .stat(pack_key)
2121098×
            .map_err(backend_err)?
2131098×
            .ok_or_else(|| bad("the index names a pack that is not there"))?
214
            .size;
2151098×
        let mut refs = Vec::with_capacity(count);
2161098×
        let mut entries = Vec::with_capacity(count);
21726375×
        for i in 0..count {
21826375×
            let e = &data[12 + i * IDX_ENTRY..12 + (i + 1) * IDX_ENTRY];
21926375×
            let r = ObjectRef::from_slice(&e[..32]).unwrap();
22026375×
            if let Some(prev) = refs.last() {
22125277×
                if r <= *prev {
2223×
                    return Err(bad("index not sorted"));
22325274×
                }
2241098×
            }
22526372×
            refs.push(r);
22626367×
            let entry = PackEntry {
22726372×
                offset: u64::from_le_bytes(e[32..40].try_into().unwrap()),
22826372×
                stored_len: u32::from_le_bytes(e[40..44].try_into().unwrap()),
22926372×
                raw_len: u32::from_le_bytes(e[44..48].try_into().unwrap()),
23026372×
                ty: ObjectType::ALL
23126372×
                    .get(e[48] as usize)
23226372×
                    .copied()
23326372×
                    .ok_or_else(|| bad("unknown object type"))?,
23426367×
                flags: e[49],
235
            };
23626367×
            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×
                ));
24426364×
            }
24526364×
            if entry.offset.saturating_add(entry.stored_len as u64) > pack_len {
24654×
                return Err(bad("index entry points outside the pack"));
24726310×
            }
24826310×
            entries.push(entry);
249
        }
2501033×
        let dict_key = format!("{}.dict", pack_key.trim_end_matches(".pack"));
2511033×
        let dict = get_optional(backend, &dict_key)?
2521033×
            .map(|d| Arc::new(zstd::dict::DecoderDictionary::copy(&d)));
2531033×
        Ok(PackIndex {
2541033×
            key: pack_key.to_string(),
2551033×
            refs,
2561033×
            entries,
2571033×
            dict,
2581033×
        })
2591142×
    }
260
26118540×
    fn find(&self, r: &ObjectRef) -> Option<PackEntry> {
26218540×
        self.refs.binary_search(r).ok().map(|i| self.entries[i])
26318540×
    }
264
265
    /// Read one entry from the pack: one ranged read, then decode.
26615378×
    fn fetch(&self, backend: &Backend, r: &ObjectRef, e: PackEntry) -> Result<Object> {
26715378×
        let stored = backend
26815378×
            .get_range(&self.key, e.offset..e.offset + e.stored_len as u64)
26915378×
            .map_err(|err| match err {
2700×
                BackendError::NotFound(_) => StoreError::NotFound(*r),
2710×
                other => backend_err(other),
2720×
            })?;
27315378×
        decode_entry(r, e, stored, self.dict.as_ref())
27415378×
    }
275
}
276
27712038×
fn type_index(ty: ObjectType) -> u8 {
27817716×
    ObjectType::ALL.iter().position(|t| *t == ty).unwrap() as u8
27912038×
}
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<'_> {
3862738×
    pub fn finish(mut self) -> Result<()> {
3872738×
        self.done = true;
3882738×
        self.store.finish_batch()
3892738×
    }
390
}
391
392
impl Drop for Batch<'_> {
3932740×
    fn drop(&mut self) {
3942740×
        if !self.done {
3952×
            let _ = self.store.finish_batch();
3962738×
        }
3972740×
    }
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.
43378×
fn fresh_id() -> String {
43478×
    let mut nonce = [0u8; 8];
43578×
    rand::rngs::OsRng.fill_bytes(&mut nonce);
43678×
    hex::encode(nonce)
43778×
}
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.
4432793×
fn memory_backend_for(dir: &Path) -> Option<Arc<Backend>> {
444
    use std::collections::HashMap;
445
    use std::sync::{Mutex, OnceLock};
4462793×
    if std::env::var_os("OXY_STORE_BACKEND").as_deref() != Some(std::ffi::OsStr::new("memory")) {
4472793×
        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)
4602793×
}
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.
4722797×
    pub fn open(dir: impl Into<PathBuf>) -> io::Result<Store> {
4732797×
        let dir = dir.into();
4742797×
        fs::create_dir_all(dir.join("loose"))?;
475
        #[cfg(test)]
4761227×
        if let Some(backend) = TEST_BACKEND.with(|t| t.borrow().clone()) {
4774×
            return Store::open_on(backend, dir);
4781223×
        }
4792793×
        if let Some(backend) = memory_backend_for(&dir) {
4800×
            return Store::open_on(backend, dir);
4812793×
        }
4822793×
        let backend: Arc<Backend> =
4832793×
            Arc::new(LocalStore::open(&dir).map_err(|e| io::Error::other(e.to_string()))?);
4842793×
        let mut store = Store::open_on(backend, dir)?;
4852684×
        store.local = true;
4862684×
        Ok(store)
4872797×
    }
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.
4912813×
    pub fn open_on(backend: Arc<Backend>, scratch: impl Into<PathBuf>) -> io::Result<Store> {
4922813×
        let scratch = scratch.into();
4932813×
        fs::create_dir_all(&scratch)?;
4942813×
        let store = Store {
4952813×
            backend,
4962813×
            scratch,
4972813×
            local: false,
4982813×
            packs: RefCell::new(Vec::new()),
4992813×
            pending: RefCell::new(None),
5002813×
            batch_depth: std::cell::Cell::new(0),
5012813×
            metas: RefCell::new(None),
5022813×
        };
5032813×
        store
5042813×
            .reload_packs()
5052813×
            .map_err(|e| io::Error::other(e.to_string()))?;
5062704×
        Ok(store)
5072813×
    }
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.
51623855×
    pub fn is_local(&self) -> bool {
51723855×
        self.local
51823855×
    }
519
5202964×
    fn reload_packs(&self) -> Result<()> {
5212964×
        let listed = self.backend.list("pack-").map_err(backend_err)?;
5222964×
        let mut idx_keys: Vec<&str> = listed
5232964×
            .iter()
5242964×
            .map(|e| e.key.as_str())
5252964×
            .filter(|k| k.ends_with(".idx"))
5262964×
            .collect();
5272964×
        idx_keys.sort();
5282964×
        let mut packs = Vec::new();
5292964×
        for idx in idx_keys {
5301142×
            let pack = format!("{}.pack", idx.trim_end_matches(".idx"));
53110761×
            if listed.iter().any(|e| e.key == pack) {
5321142×
                packs.push(PackIndex::load(self.backend.as_ref(), idx, &pack)?);
5330×
            }
534
        }
5352855×
        *self.packs.borrow_mut() = packs;
5362855×
        Ok(())
5372964×
    }
538
53915×
    pub fn pack_count(&self) -> usize {
54015×
        self.packs.borrow().len()
54115×
    }
542
54381934×
    fn find_packed(&self, r: &ObjectRef) -> Option<(usize, PackEntry)> {
54481934×
        self.packs
54581934×
            .borrow()
54681934×
            .iter()
54781934×
            .enumerate()
54881934×
            .find_map(|(i, p)| p.find(r).map(|e| (i, e)))
54981934×
    }
550
551
    /// Loose objects, with their keys and ages.
552850×
    fn loose_objects(&self) -> Result<Vec<(ObjectRef, strata::Entry)>> {
553850×
        let mut out: Vec<(ObjectRef, strata::Entry)> = self
554850×
            .backend
555850×
            .list("loose/")
556850×
            .map_err(backend_err)?
557850×
            .into_iter()
55817327×
            .filter_map(|e| loose_ref(&e.key).map(|r| (r, e)))
559850×
            .collect();
560850×
        out.sort_by_key(|(r, _)| *r);
561850×
        Ok(out)
562850×
    }
563
564675×
    pub fn loose_count(&self) -> io::Result<usize> {
565675×
        self.loose_objects()
566675×
            .map(|l| l.len())
567675×
            .map_err(|e| io::Error::other(e.to_string()))
568675×
    }
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.
59121×
    pub fn repack_all_with(&self, level: i32, progress: Progress) -> Result<(PackReport, usize)> {
59221×
        let loose = self.loose_objects()?;
59321×
        let (mut refs, keys, trained): (Vec<ObjectRef>, Vec<String>, bool) = {
59421×
            let packs = self.packs.borrow();
595
            (
59621×
                packs.iter().flat_map(|p| p.refs.iter().copied()).collect(),
59721×
                packs.iter().map(|p| p.key.clone()).collect(),
59821×
                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.
60521×
        if loose.is_empty() && keys.len() <= 1 && (level == ZSTD_LEVEL || trained) {
6061×
            return Ok((PackReport::default(), 0));
60720×
        }
60820×
        refs.extend(loose.iter().map(|(r, _)| *r));
60920×
        let loose_keys: Vec<String> = loose.into_iter().map(|(_, e)| e.key).collect();
61020×
        let n = keys.len();
61120×
        let report = self.write_pack(&refs, &loose_keys, &keys, level, progress)?;
61220×
        Ok((report, n))
61321×
    }
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.
64723×
    pub fn prune_with(
64823×
        &self,
64923×
        keep: &std::collections::HashSet<ObjectRef>,
65023×
        grace: std::time::Duration,
65123×
        progress: Progress,
65223×
    ) -> Result<PruneReport> {
65323×
        progress("pruning loose objects");
65423×
        let now = now_ms();
65523×
        let grace_ms = grace.as_millis() as u64;
656
        // An object whose age the store does not know is old enough.
65723×
        let old_enough =
65837×
            |modified: Option<u64>| modified.is_none_or(|t| now.saturating_sub(t) >= grace_ms);
65923×
        let mut report = PruneReport::default();
660
        // Loose objects.
661320×
        for (r, entry) in self.loose_objects()? {
662320×
            if keep.contains(&r) {
663292×
                continue;
66428×
            }
66528×
            if !old_enough(entry.modified_ms) {
6664×
                report.deferred += 1;
6674×
                continue;
66824×
            }
66924×
            report.bytes += entry.size;
67024×
            report.objects += 1;
67124×
            delete(self.backend.as_ref(), &entry.key)?;
67224×
            self.remove_sidecars(&r)?;
673
        }
674
        // Packs: rewrite those that hold unreachable objects.
67523×
        let mut keep_refs: Vec<ObjectRef> = Vec::new();
67623×
        let mut old_keys: Vec<String> = Vec::new();
67723×
        let mut rewrite = false;
67823×
        progress("pruning packs");
67923×
        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
        }
70423×
        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
            }
71817×
        }
71923×
        Ok(report)
72023×
    }
721
722
    /// Everything kept beside an object: its signatures and the seal and
723
    /// receipt entries under it, in both layouts.
72465×
    fn remove_sidecars(&self, r: &ObjectRef) -> Result<()> {
725195×
        for index in ["sigs", "seals", "receipts"] {
726195×
            delete(self.backend.as_ref(), &legacy_key(index, r))?;
727
        }
728195×
        for index in ["sig", "seal", "receipt"] {
729195×
            for e in self
730195×
                .backend
731195×
                .list(&fanout_prefix(index, r))
732195×
                .map_err(backend_err)?
733
            {
73412×
                delete(self.backend.as_ref(), &e.key)?;
735
            }
736
        }
73765×
        Ok(())
73865×
    }
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.
74378×
    fn finish_pack_files(
74478×
        &self,
74578×
        id: &str,
74678×
        tmp_pack: &Path,
74778×
        index: &[(ObjectRef, PackEntry)],
74878×
    ) -> Result<()> {
74978×
        let mut idx = Vec::with_capacity(12 + index.len() * IDX_ENTRY);
75078×
        idx.extend_from_slice(IDX_MAGIC);
75178×
        idx.extend_from_slice(&(index.len() as u32).to_le_bytes());
7526019×
        for (r, e) in index {
7536019×
            idx.extend_from_slice(&r.0);
7546019×
            idx.extend_from_slice(&e.offset.to_le_bytes());
7556019×
            idx.extend_from_slice(&e.stored_len.to_le_bytes());
7566019×
            idx.extend_from_slice(&e.raw_len.to_le_bytes());
7576019×
            idx.extend_from_slice(&[type_index(e.ty), e.flags]);
7586019×
        }
75978×
        let put = self
76078×
            .backend
76178×
            .put_new_file(&format!("pack-{id}.pack"), tmp_pack)
76278×
            .map_err(backend_err);
763
        // A store on another disk copied it; the one in this directory
764
        // moved it and this finds nothing.
76578×
        let _ = fs::remove_file(tmp_pack);
76678×
        put?;
76778×
        self.backend
76878×
            .put_new(&format!("pack-{id}.idx"), &idx)
76978×
            .map_err(backend_err)?;
77078×
        self.reload_packs()
77178×
    }
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`.
78273×
    fn write_pack(
78373×
        &self,
78473×
        refs: &[ObjectRef],
78573×
        loose_keys: &[String],
78673×
        old_packs: &[String],
78773×
        level: i32,
78873×
        progress: Progress,
78973×
    ) -> Result<PackReport> {
79073×
        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());
79673×
        }
79773×
        let mut refs: Vec<ObjectRef> = refs.to_vec();
79873×
        refs.sort();
79973×
        refs.dedup();
80073×
        let id = fresh_id();
80173×
        let tmp_pack = self.scratch.join(format!(".tmp-{id}.pack"));
80273×
        let mut report = PackReport::default();
80373×
        let mut index: Vec<(ObjectRef, PackEntry)> = Vec::with_capacity(refs.len());
804
        // A full repack of enough objects trains a dictionary for them.
80573×
        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 {
81071×
            None
811
        };
81273×
        let encoder = dict
81373×
            .as_ref()
81473×
            .map(|d| zstd::dict::EncoderDictionary::copy(d, level));
81573×
        let nocompress = self.nocompress_set()?;
816
        {
81773×
            let mut f = io::BufWriter::new(fs::File::create(&tmp_pack)?);
81873×
            f.write_all(PACK_MAGIC)?;
81973×
            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.
82273×
            let mut batches = refs.chunks(1024);
82373×
            let mut compressed_batch = Vec::new();
82473×
            let total = refs.len();
82573×
            let mut reported = usize::MAX;
826
            loop {
8273992×
                if compressed_batch.is_empty() {
828148×
                    let Some(batch) = batches.next() else { break };
829
                    // Every tenth, and the first batch.
83075×
                    let tenth = report.objects * 10 / total.max(1);
83175×
                    if tenth != reported {
83275×
                        reported = tenth;
83375×
                        progress(&format!("packing {} of {total} objects", report.objects));
83475×
                    }
83575×
                    let mut read: Vec<(ObjectRef, ObjectType, Vec<u8>, bool)> =
83675×
                        Vec::with_capacity(batch.len());
8373919×
                    for r in batch {
8383919×
                        let (ty, body) = self.get(r)?;
8393919×
                        read.push((*r, ty, body, nocompress.contains(r)));
840
                    }
841
                    use rayon::prelude::*;
84275×
                    compressed_batch = read
84375×
                        .into_par_iter()
84475×
                        .map_init(
8451045×
                            || {
8461045×
                                encoder.as_ref().and_then(|e| {
847385×
                                    zstd::bulk::Compressor::with_prepared_dictionary(e).ok()
848385×
                                })
8491045×
                            },
8503919×
                            |with_dict, (r, ty, body, raw)| {
8513919×
                                let packed = if raw {
8522×
                                    None
853
                                } else {
854
                                    // Small objects with the dictionary;
855
                                    // a large one has context enough.
8563917×
                                    let dicted = with_dict
8573917×
                                        .as_mut()
8583917×
                                        .filter(|_| body.len() <= DICT_OBJECT_MAX)
8593917×
                                        .and_then(|c| c.compress(&body).ok())
8603917×
                                        .map(|c| (FLAG_ZSTD | FLAG_DICT, c));
8613917×
                                    dicted
8623917×
                                        .or_else(|| {
863916×
                                            zstd::bulk::compress(&body, level)
864916×
                                                .ok()
865916×
                                                .map(|c| (FLAG_ZSTD, c))
866916×
                                        })
8673917×
                                        .filter(|(_, c)| c.len() < body.len())
868
                                };
8693919×
                                (r, ty, body, packed)
8703919×
                            },
871
                        )
87275×
                        .collect::<Vec<_>>();
87375×
                    compressed_batch.reverse();
8743844×
                }
8753919×
                let Some((r, ty, body, packed)) = compressed_batch.pop() else {
8760×
                    continue;
877
                };
8783919×
                let r = &r;
8793919×
                let (flags, stored) = match packed {
8803386×
                    Some(c) => c,
881533×
                    None => (0, body.clone()),
882
                };
8833919×
                let header_len = 1 + 1 + 4 + 4 + 32;
8843919×
                f.write_all(&[type_index(ty), flags])?;
8853919×
                f.write_all(&(stored.len() as u32).to_le_bytes())?;
8863919×
                f.write_all(&(body.len() as u32).to_le_bytes())?;
8873919×
                f.write_all(&r.0)?;
8883919×
                f.write_all(&stored)?;
8893919×
                index.push((
8903919×
                    *r,
8913919×
                    PackEntry {
8923919×
                        offset: offset + header_len,
8933919×
                        stored_len: stored.len() as u32,
8943919×
                        raw_len: body.len() as u32,
8953919×
                        ty,
8963919×
                        flags,
8973919×
                    },
8983919×
                ));
8993919×
                offset += header_len + stored.len() as u64;
9003919×
                report.objects += 1;
9013919×
                report.raw_bytes += body.len() as u64;
9023919×
                report.packed_bytes += stored.len() as u64;
903
            }
90473×
            f.flush()?;
90573×
            f.get_ref().sync_all()?;
906
        }
907
        // The dictionary before the pack that needs it becomes visible.
90873×
        if let Some(d) = &dict {
9092×
            self.backend
9102×
                .put_new(&format!("pack-{id}.dict"), d)
9112×
                .map_err(backend_err)?;
91271×
        }
91373×
        progress(&format!("writing the index of {} objects", index.len()));
91473×
        self.finish_pack_files(&id, &tmp_pack, &index)?;
91573×
        for p in old_packs {
91649×
            self.remove_pack(p)?;
917
        }
91873×
        self.reload_packs()?;
9192219×
        for key in loose_keys {
9202219×
            delete(self.backend.as_ref(), key)?;
921
        }
92273×
        Ok(report)
92373×
    }
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
97011949×
    pub fn has(&self, r: &ObjectRef) -> bool {
97111949×
        self.backend.has(&loose_key(r)).unwrap_or(false)
9721298×
            || self.find_packed(r).is_some()
973923×
            || self
974923×
                .pending
975923×
                .borrow()
976923×
                .as_ref()
977923×
                .is_some_and(|p| p.lookup.contains_key(r))
97811949×
    }
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.
9842741×
    pub fn begin_batch(&self) -> Result<Batch<'_>> {
9852741×
        let depth = self.batch_depth.get();
9862741×
        if depth == 0 {
9872230×
            *self.pending.borrow_mut() = Some(Pending {
9882230×
                buffered: vec![],
9892230×
                buffered_bytes: 0,
9902230×
                lookup: Default::default(),
9912230×
                pack: None,
9922230×
                report: PackReport::default(),
9932230×
            });
9942230×
        }
9952741×
        self.batch_depth.set(depth + 1);
9962741×
        Ok(Batch {
9972741×
            store: self,
9982741×
            done: false,
9992741×
        })
10002741×
    }
1001
10022740×
    fn finish_batch(&self) -> Result<()> {
10032740×
        let depth = self.batch_depth.get();
10042740×
        if depth == 0 {
10050×
            return Ok(());
10062740×
        }
10072740×
        self.batch_depth.set(depth - 1);
10082740×
        if depth > 1 {
1009511×
            return Ok(());
10102229×
        }
10112229×
        let Some(pending) = self.pending.borrow_mut().take() else {
10122×
            return Ok(());
1013
        };
10142227×
        self.write_pending(pending)
10152740×
    }
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.
10203440×
    pub fn flush(&self) -> Result<()> {
10213440×
        let Some(pending) = self.pending.borrow_mut().take() else {
10222429×
            return Ok(());
1023
        };
10241011×
        self.write_pending(pending)?;
10251009×
        *self.pending.borrow_mut() = Some(Pending {
10261009×
            buffered: vec![],
10271009×
            buffered_bytes: 0,
10281009×
            lookup: Default::default(),
10291009×
            pack: None,
10301009×
            report: PackReport::default(),
10311009×
        });
10321009×
        Ok(())
10333440×
    }
1034
10353238×
    fn write_pending(&self, pending: Pending) -> Result<()> {
10363238×
        match pending.pack {
1037
            None => {
10383234×
                let objects: Vec<(ObjectType, &[u8])> = pending
10393234×
                    .buffered
10403234×
                    .iter()
10415150×
                    .map(|(ty, body)| (*ty, body.as_slice()))
10423234×
                    .collect();
10433234×
                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
        }
10543238×
    }
1055
1056
    /// Whether a batch is open and holds `r`.
1057959×
    fn pending_get(&self, r: &ObjectRef) -> Option<Result<Object>> {
1058959×
        let mut guard = self.pending.borrow_mut();
1059959×
        let pending = guard.as_mut()?;
1060852×
        let entry = *pending.lookup.get(r)?;
1061852×
        Some(match entry {
1062670×
            PendingEntry::Buffered(i) => {
1063670×
                let (ty, body) = &pending.buffered[i];
1064670×
                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
        })
1082959×
    }
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
11077165×
    fn put_pending(&self, r: ObjectRef, ty: ObjectType, body: &[u8]) -> Result<()> {
11087165×
        let mut guard = self.pending.borrow_mut();
11097165×
        let pending = guard.as_mut().expect("batch open");
11107165×
        if pending.lookup.contains_key(&r) {
1111115×
            return Ok(());
11127050×
        }
11137050×
        if pending.pack.is_none()
11146084×
            && pending.buffered.len() < SPILL_OBJECTS
11156082×
            && pending.buffered_bytes + body.len() <= SPILL_BYTES
1116
        {
11176080×
            pending.buffered.push((ty, body.to_vec()));
11186080×
            pending.buffered_bytes += body.len();
11196080×
            pending
11206080×
                .lookup
11216080×
                .insert(r, PendingEntry::Buffered(pending.buffered.len() - 1));
11226080×
            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(())
11317165×
    }
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.
1166784×
    pub fn put_many(&self, objects: &[(ObjectType, &[u8])]) -> Result<Vec<ObjectRef>> {
1167
        use rayon::prelude::*;
1168823×
        let total: usize = objects.iter().map(|(_, b)| b.len()).sum();
1169784×
        if self.pending.borrow().is_none() || total < SPILL_BYTES {
1170783×
            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)
1228784×
    }
1229
1230
    /// Store `body` as an object of type `ty`; idempotent.
123115886×
    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.
123515886×
        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×
            });
124115885×
        }
124215885×
        let r = hash_object(ty, body);
124315885×
        if self.find_packed(&r).is_some() || self.backend.has(&loose_key(&r)).unwrap_or(false) {
12441789×
            return Ok(r);
124514096×
        }
124614096×
        if self.pending.borrow().is_some() {
12477165×
            self.put_pending(r, ty, body)?;
12487165×
            return Ok(r);
12496931×
        }
12506931×
        self.put_loose(ty, body)?;
12516926×
        Ok(r)
125215886×
    }
1253
1254
    /// Write one loose object, durable when this returns.
12557120×
    fn put_loose(&self, ty: ObjectType, body: &[u8]) -> Result<ObjectRef> {
12567120×
        let r = hash_object(ty, body);
12577120×
        let mut bytes = header(ty, body.len());
12587120×
        bytes.extend_from_slice(body);
12597120×
        crate::durable::step("write loose object")?;
12607115×
        put_new_or_existing(self.backend.as_ref(), &loose_key(&r), &bytes)?;
12617115×
        Ok(r)
12627120×
    }
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).
12683234×
    fn put_loose_many(&self, objects: &[(ObjectType, &[u8])]) -> Result<()> {
12693234×
        if objects.len() <= 1 {
12701831×
            for (ty, body) in objects {
1271189×
                self.put_loose(*ty, body)?;
1272
            }
12731831×
            return Ok(());
12741403×
        }
12751403×
        let mut seen = std::collections::HashSet::new();
12761403×
        let items: Vec<(String, Vec<u8>)> = objects
12771403×
            .iter()
12784961×
            .filter_map(|(ty, body)| {
12794961×
                let r = hash_object(*ty, body);
12804961×
                seen.insert(r).then(|| {
12814961×
                    let mut bytes = header(*ty, body.len());
12824961×
                    bytes.extend_from_slice(body);
12834961×
                    (loose_key(&r), bytes)
12844961×
                })
12854961×
            })
12861403×
            .collect();
12871403×
        self.backend.put_many_new(&items).map_err(backend_err)
12883234×
    }
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).
129463047×
    pub fn get(&self, r: &ObjectRef) -> Result<Object> {
129563047×
        if let Some((i, e)) = self.find_packed(r) {
129615244×
            return self.packs.borrow()[i].fetch(self.backend.as_ref(), r, e);
129747803×
        }
129847803×
        match get_optional(self.backend.as_ref(), &loose_key(r))? {
129946851×
            Some(bytes) => parse_loose(&bytes, r),
1300952×
            None => self.pending_get(r).unwrap_or(Err(StoreError::NotFound(*r))),
1301
        }
130263047×
    }
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`.
1307957×
    pub fn get_many(&self, refs: &[ObjectRef]) -> Vec<Result<Object>> {
1308
        use rayon::prelude::*;
1309957×
        let backend = self.backend.as_ref();
1310957×
        let packs = self.packs.borrow();
1311957×
        let place: Vec<Option<(usize, PackEntry)>> = refs
1312957×
            .iter()
13131974×
            .map(|r| {
13141974×
                packs
13151974×
                    .iter()
13161974×
                    .enumerate()
13171974×
                    .find_map(|(p, pack)| pack.find(r).map(|e| (p, e)))
13181974×
            })
1319957×
            .collect();
1320957×
        let indexes: &[PackIndex] = &packs;
1321957×
        let found: Vec<Option<Result<Object>>> = refs
1322957×
            .par_iter()
1323957×
            .zip(place.par_iter())
13241974×
            .map(|(r, at)| match at {
1325133×
                Some((p, e)) => Some(indexes[*p].fetch(backend, r, *e)),
13261841×
                None => match get_optional(backend, &loose_key(r)) {
13271834×
                    Ok(Some(bytes)) => Some(parse_loose(&bytes, r)),
13287×
                    Ok(None) => None,
13290×
                    Err(e) => Some(Err(e)),
1330
                },
13311974×
            })
1332957×
            .collect();
1333957×
        drop(packs);
1334957×
        found
1335957×
            .into_iter()
1336957×
            .zip(refs)
13371974×
            .map(|(f, r)| {
13381974×
                f.unwrap_or_else(|| self.pending_get(r).unwrap_or(Err(StoreError::NotFound(*r))))
13391974×
            })
1340957×
            .collect()
1341957×
    }
1342
134343718×
    pub fn get_typed(&self, r: &ObjectRef, want: ObjectType) -> Result<Vec<u8>> {
134443718×
        let (ty, body) = self.get(r)?;
134543685×
        if ty != want {
13461×
            return Err(StoreError::WrongType(*r, ty.name(), want.name()));
134743684×
        }
134843684×
        Ok(body)
134943718×
    }
1350
1351
    /// Store a change and the text blobs (and their chunks) its large
1352
    /// inserts are stored as (spec §6.1).
13532948×
    pub fn put_change(&self, c: &Change) -> Result<ObjectRef> {
13542948×
        let encoding = crate::timing::phase("store: encode the change and its texts");
13552948×
        let bytes = c.encode_streaming(|batch| self.put_texts(&batch))?;
13562948×
        drop(encoding);
13572948×
        let _t = crate::timing::phase("store: put the encoding");
13582948×
        self.put(ObjectType::Change, &bytes)
13592948×
    }
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
13814572×
    pub fn get_change(&self, r: &ObjectRef) -> Result<Change> {
13824572×
        Ok(self.get_change_parts(r)?.0)
13834572×
    }
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.
13874691×
    pub fn get_change_parts(&self, r: &ObjectRef) -> Result<(Change, Vec<ObjectRef>)> {
13884691×
        let bytes = self.get_typed(r, ObjectType::Change)?;
13894679×
        let mut parts = Vec::new();
13904679×
        let mut failed = None;
13914679×
        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×
        });
14084679×
        match (decoded, failed) {
14094678×
            (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
        }
14164691×
    }
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.
14344495×
    pub fn get_change_meta(&self, r: &ObjectRef) -> Result<crate::state::ChangeMeta> {
14354495×
        if self.metas.borrow().is_none() {
1436932×
            *self.metas.borrow_mut() = Some(self.read_metas_cache());
14373563×
        }
14384495×
        let cached = self.metas.borrow().as_ref().and_then(|m| m.get(r).cloned());
14394495×
        if let Some(meta) = cached {
14403204×
            if self.has(r) {
1441
                #[cfg(test)]
14421737×
                assert_eq!(
1443
                    meta,
14441737×
                    Change::decode_meta(&self.get_typed(r, ObjectType::Change)?).unwrap(),
1445
                    "the metadata cache holds a change's metadata"
1446
                );
14473204×
                return Ok(meta);
14480×
            }
14491291×
        }
14501291×
        let bytes = self.get_typed(r, ObjectType::Change)?;
14511291×
        let meta =
14521291×
            Change::decode_meta(&bytes).map_err(|e| StoreError::Corrupt(*r, e.to_string()))?;
14531291×
        self.remember_meta(r, &meta);
14541291×
        Ok(meta)
14554495×
    }
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.
1462932×
    fn read_metas_cache(&self) -> crate::fasthash::FastMap<ObjectRef, crate::state::ChangeMeta> {
1463932×
        let mut out = crate::fasthash::FastMap::default();
1464932×
        let Ok(bytes) = fs::read(self.scratch.join("metas")) else {
1465361×
            return out;
1466
        };
1467571×
        let mut r = crate::flat::Reader::new(&bytes);
1468571×
        let mut good = 0;
14692069×
        while !r.at_end() {
14701499×
            let mut record = || -> std::result::Result<_, ObjectError> {
14711499×
                let h = r.object()?;
14721498×
                let body = r.bytes()?;
14731498×
                let check = r.fixed::<8>()?;
14741498×
                Ok((h, body, check))
14751499×
            };
14761499×
            let Ok((h, body, check)) = record() else {
14771×
                break;
1478
            };
14791498×
            let mut sum = blake3::Hasher::new();
14801498×
            sum.update(&h.0).update(body);
14811498×
            if sum.finalize().as_bytes()[..8] != check {
14820×
                break;
14831498×
            }
14841498×
            match crate::state::ChangeMeta::read_flat(&mut crate::flat::Reader::new(body)) {
14851498×
                Ok(m) => out.insert(h, m),
14860×
                Err(_) => break,
1487
            };
14881498×
            good += 32 + 4 + body.len() + 8;
1489
        }
1490
        // Cut a bad tail, so records appended later are read.
1491571×
        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));
1496570×
        }
1497571×
        out
1498932×
    }
1499
1500
    /// Add a change's metadata to the cache; quietly nothing when it
1501
    /// cannot be written (it is only a cache).
15021291×
    fn remember_meta(&self, r: &ObjectRef, meta: &crate::state::ChangeMeta) {
15031291×
        let mut body = crate::flat::Writer::default();
15041291×
        meta.write_flat(&mut body);
15051291×
        let mut w = crate::flat::Writer::default();
15061291×
        w.object(r);
15071291×
        w.bytes(&body.0);
15081291×
        let mut sum = blake3::Hasher::new();
15091291×
        sum.update(&r.0).update(&body.0);
15101291×
        w.fixed(&sum.finalize().as_bytes()[..8]);
15111291×
        let _ = fs::OpenOptions::new()
15121291×
            .create(true)
15131291×
            .append(true)
15141291×
            .open(self.scratch.join("metas"))
15151291×
            .and_then(|mut f| f.write_all(&w.0));
15161291×
        if let Some(m) = self.metas.borrow_mut().as_mut() {
15171291×
            m.insert(*r, meta.clone());
15181291×
        }
15191291×
    }
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.
155274×
    fn nocompress_set(&self) -> Result<std::collections::HashSet<ObjectRef>> {
155374×
        Ok(self
155474×
            .backend
155574×
            .list("nocompress/")
155674×
            .map_err(backend_err)?
155774×
            .into_iter()
155874×
            .filter_map(|e| ObjectRef::from_hex(e.key.trim_start_matches("nocompress/")))
155974×
            .collect())
156074×
    }
1561
15622931×
    pub fn put_state(&self, st: &StateObject) -> Result<ObjectRef> {
15632931×
        self.put(ObjectType::State, &st.encode())
15642931×
    }
1565
15665254×
    pub fn get_state(&self, r: &ObjectRef) -> Result<StateObject> {
15675254×
        Ok(StateObject::decode(&self.get_typed(r, ObjectType::State)?)?)
15685254×
    }
1569
1570389×
    pub fn put_attest(&self, a: &Attest) -> Result<ObjectRef> {
1571389×
        self.put(ObjectType::Attest, &a.encode())
1572389×
    }
1573
1574619×
    pub fn get_attest(&self, r: &ObjectRef) -> Result<Attest> {
1575619×
        Ok(Attest::decode(&self.get_typed(r, ObjectType::Attest)?)?)
1576619×
    }
1577
15783×
    pub fn put_receipt(&self, r: &Receipt) -> Result<ObjectRef> {
15793×
        self.put(ObjectType::Receipt, &r.encode())
15803×
    }
1581
158212×
    pub fn get_receipt(&self, r: &ObjectRef) -> Result<Receipt> {
158312×
        Ok(Receipt::decode(&self.get_typed(r, ObjectType::Receipt)?)?)
158412×
    }
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.
1588180×
    fn index_add(&self, index: &str, key: &ObjectRef, value: &ObjectRef) -> Result<()> {
1589180×
        let entry = format!("{}{}", fanout_prefix(index, key), value.to_hex());
1590180×
        put_new_or_existing(self.backend.as_ref(), &entry, b"")
1591180×
    }
1592
1593
    /// The values recorded under `key` in `index`, with those an older
1594
    /// store kept as one list in `legacy`, sorted.
15952134×
    fn index_get(&self, index: &str, legacy: &str, key: &ObjectRef) -> Result<Vec<ObjectRef>> {
15962134×
        let mut values: Vec<ObjectRef> = self
15972134×
            .backend
15982134×
            .list(&fanout_prefix(index, key))
15992134×
            .map_err(backend_err)?
16002134×
            .into_iter()
16012134×
            .filter_map(|e| e.key.rsplit('/').next().and_then(ObjectRef::from_hex))
16022134×
            .collect();
16032134×
        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×
            );
16092131×
        }
16102134×
        values.sort();
16112134×
        values.dedup();
16122134×
        Ok(values)
16132134×
    }
1614
1615
    /// Record that seal attestation `attest` covers `change`.
1616151×
    pub fn index_seal(&self, change: &ObjectRef, attest: &ObjectRef) -> Result<()> {
1617151×
        self.index_add("seal", change, attest)
1618151×
    }
1619
1620
    /// Seal attestations known to cover `change`.
16211421×
    pub fn seals_for(&self, change: &ObjectRef) -> Result<Vec<ObjectRef>> {
16221421×
        self.index_get("seal", "seals", change)
16231421×
    }
1624
1625
    /// Record receipt attestation `attest` for `state` (spec §14.6).
1626
    /// Keep a short-lived key's certificate (spec §14.7), with its issuer's
1627
    /// signature, indexed by the key it certifies.
162822×
    pub fn put_certificate(&self, c: &crate::cert::SignedCertificate) -> Result<ObjectRef> {
162922×
        let r = self.put(ObjectType::Certificate, &c.cert.encode())?;
163022×
        self.put_signature(&r, &c.sig)?;
163122×
        self.index_add("cert", &c.cert.key_id(), &r)?;
163222×
        Ok(r)
163322×
    }
1634
1635
    /// A kept certificate with its issuer's signature.
163661×
    pub fn get_certificate(&self, r: &ObjectRef) -> Result<crate::cert::SignedCertificate> {
163761×
        let cert = crate::cert::Certificate::decode(&self.get_typed(r, ObjectType::Certificate)?)?;
163861×
        let sig = self
163961×
            .signatures(r)?
164061×
            .into_iter()
164161×
            .find(|s| s.key == cert.issuer)
164261×
            .ok_or(StoreError::NotFound(*r))?;
164361×
        Ok(crate::cert::SignedCertificate { cert, sig })
164461×
    }
1645
1646
    /// The certificate kept for short-lived key `key`, if any.
1647569×
    pub fn certificate_of(&self, key: &ObjectRef) -> Result<Option<ObjectRef>> {
1648569×
        Ok(self
1649569×
            .index_get("cert", "certs", key)?
1650569×
            .into_iter()
1651569×
            .find(|r| self.has(r)))
1652569×
    }
1653
1654
    /// Record `value` under `key` in index `index` (for repository code).
16551×
    pub(crate) fn index_add_pub(
16561×
        &self,
16571×
        index: &str,
16581×
        key: &ObjectRef,
16591×
        value: &ObjectRef,
16601×
    ) -> Result<()> {
16611×
        self.index_add(index, key, value)
16621×
    }
1663
1664
    /// The values recorded under `key` in index `index` (which has no
1665
    /// older one-list form: the legacy name only has to differ from it).
1666127×
    pub(crate) fn index_get_pub(&self, index: &str, key: &ObjectRef) -> Result<Vec<ObjectRef>> {
1667127×
        self.index_get(index, &format!("{index}-lists"), key)
1668127×
    }
1669
16705×
    pub fn index_receipt(&self, state: &ObjectRef, attest: &ObjectRef) -> Result<()> {
16715×
        self.index_add("receipt", state, attest)
16725×
    }
1673
1674
    /// Receipt attestations recorded for `state`.
167514×
    pub fn receipts_for(&self, state: &ObjectRef) -> Result<Vec<ObjectRef>> {
167614×
        self.index_get("receipt", "receipts", state)
167714×
    }
1678
16791×
    pub fn index_approval(&self, state: &ObjectRef, attest: &ObjectRef) -> Result<()> {
16801×
        self.index_add("approval", state, attest)
16811×
    }
1682
1683
    /// Approval attestations recorded for `state` (OxygenFlow approval
1684
    /// gates, oxygenhub#235).
16853×
    pub fn approvals_for(&self, state: &ObjectRef) -> Result<Vec<ObjectRef>> {
16863×
        self.index_get("approval", "approvals", state)
16873×
    }
1688
1689
    /// Every state with an approval, for garbage collection.
169018×
    pub fn approval_states(&self) -> Result<Vec<ObjectRef>> {
169118×
        self.indexed_states("approval", "approvals")
169218×
    }
1693
1694
    /// Every state with a receipt, for garbage collection.
169524×
    pub fn receipt_states(&self) -> Result<Vec<ObjectRef>> {
169624×
        self.indexed_states("receipt", "receipts")
169724×
    }
1698
1699
    /// The states an index (`one/<hh>/<rest>/<attest>` entries, and the
1700
    /// packed `many/<hh>/<rest>` lists) holds attestations for.
170142×
    fn indexed_states(&self, one: &str, many: &str) -> Result<Vec<ObjectRef>> {
170242×
        let mut out: Vec<ObjectRef> = Vec::new();
170342×
        for e in self.backend.list(&format!("{one}/")).map_err(backend_err)? {
1704
            // receipt/<hh>/<rest>/<attest>
17055×
            let mut parts = e.key.splitn(4, '/');
17065×
            let (Some(_), Some(hh), Some(rest), Some(_)) =
17075×
                (parts.next(), parts.next(), parts.next(), parts.next())
1708
            else {
17090×
                continue;
1710
            };
17115×
            out.extend(ObjectRef::from_hex(&format!("{hh}{rest}")));
1712
        }
171342×
        for e in self
171442×
            .backend
171542×
            .list(&format!("{many}/"))
171642×
            .map_err(backend_err)?
1717
        {
17181×
            let mut parts = e.key.splitn(3, '/');
17191×
            let (Some(_), Some(hh), Some(rest)) = (parts.next(), parts.next(), parts.next()) else {
17200×
                continue;
1721
            };
17221×
            out.extend(ObjectRef::from_hex(&format!("{hh}{rest}")));
1723
        }
172442×
        out.sort();
172542×
        out.dedup();
172642×
        Ok(out)
172742×
    }
1728
1729296×
    pub fn put_identity(&self, id: &Identity) -> Result<ObjectRef> {
1730296×
        self.put(ObjectType::Identity, &id.encode())
1731296×
    }
1732
1733785×
    pub fn get_identity(&self, r: &ObjectRef) -> Result<Identity> {
1734785×
        Ok(Identity::decode(&self.get_typed(r, ObjectType::Identity)?)?)
1735785×
    }
1736
1737
    /// Signatures stored alongside object `r` (spec §5.4), one per signing
1738
    /// key, sorted by key. Empty if none.
17392824×
    pub fn signatures(&self, r: &ObjectRef) -> Result<Vec<Signature>> {
17402824×
        let mut sigs: Vec<Signature> = Vec::new();
17412824×
        for e in self
17422824×
            .backend
17432824×
            .list(&fanout_prefix("sig", r))
17442824×
            .map_err(backend_err)?
1745
        {
17461593×
            let bytes = self.backend.get(&e.key).map_err(backend_err)?;
17471593×
            sigs.extend(Signature::decode_list(&bytes)?);
1748
        }
1749
        // An older store's one list per object; a signer kept there and
1750
        // here counts once, as written here.
17512824×
        if let Some(bytes) = get_optional(self.backend.as_ref(), &legacy_key("sigs", r))? {
17522×
            for sig in Signature::decode_list(&bytes)? {
17532×
                if !sigs.iter().any(|s| s.key == sig.key) {
17541×
                    sigs.push(sig);
17551×
                }
1756
            }
17572822×
        }
17582824×
        sigs.sort_by_key(|s| s.key);
17592824×
        sigs.dedup_by_key(|s| s.key);
17602824×
        Ok(sigs)
17612824×
    }
1762
1763
    /// Attach a signature to object `r`, replacing any earlier one by the
1764
    /// same key: one entry per signer, so the latest by a key is the one
1765
    /// kept, and two signers never touch each other's.
1766599×
    pub fn put_signature(&self, r: &ObjectRef, sig: &Signature) -> Result<()> {
1767599×
        let key = format!("{}{}", fanout_prefix("sig", r), sig.key.to_hex());
1768599×
        let bytes = Signature::encode_list(std::slice::from_ref(sig));
1769599×
        if get_optional(self.backend.as_ref(), &key)?.as_deref() == Some(bytes.as_slice()) {
177023×
            return Ok(());
1771576×
        }
1772576×
        delete(self.backend.as_ref(), &key)?;
1773576×
        put_new_or_existing(self.backend.as_ref(), &key, &bytes)
1774599×
    }
1775
1776
    /// Finish packs a writer left unfinished: a batch writes its objects to
1777
    /// `.tmp-ID.pack` and only indexes it at the end, so a process that
1778
    /// stopped part way (an import killed after hours) leaves every object
1779
    /// in a pack nothing can read. Each such pack untouched for `min_age`
1780
    /// is read through: every whole entry checked against its reference,
1781
    /// a torn last one cut off, then indexed as a pack of the store.
1782
    /// Returns the packs and objects adopted.
17832×
    pub fn adopt_unfinished_packs(
17842×
        &self,
17852×
        min_age: std::time::Duration,
17862×
        progress: &dyn Fn(&str),
17872×
    ) -> Result<(usize, usize)> {
1788
        use std::io::{BufReader, Read};
17892×
        let mut packs = 0;
17902×
        let mut objects = 0;
17912×
        let Ok(dir) = fs::read_dir(&self.scratch) else {
17920×
            return Ok((0, 0));
1793
        };
17944×
        for entry in dir.flatten() {
17954×
            let name = entry.file_name().to_string_lossy().to_string();
17964×
            let Some(id) = name
17974×
                .strip_prefix(".tmp-")
17984×
                .and_then(|n| n.strip_suffix(".pack"))
1799
            else {
18002×
                continue;
1801
            };
18022×
            let path = entry.path();
18032×
            let meta = fs::metadata(&path)?;
18042×
            let age = meta
18052×
                .modified()
18062×
                .ok()
18072×
                .and_then(|m| m.elapsed().ok())
18082×
                .unwrap_or_default();
18092×
            if age < min_age {
18101×
                progress(&format!(
18111×
                    "{name}: written to {}s ago, left alone",
18121×
                    age.as_secs()
18131×
                ));
18141×
                continue;
18151×
            }
18161×
            let mut f = BufReader::with_capacity(1 << 20, fs::File::open(&path)?);
18171×
            let mut magic = [0u8; 8];
18181×
            if f.read_exact(&mut magic).is_err() || &magic != PACK_MAGIC {
18190×
                progress(&format!("{name}: not a pack, left alone"));
18200×
                continue;
18211×
            }
18221×
            let mut offset = PACK_MAGIC.len() as u64;
18231×
            let mut index: Vec<(ObjectRef, PackEntry)> = Vec::new();
1824
            loop {
1825301×
                let mut head = [0u8; 42];
1826301×
                if f.read_exact(&mut head).is_err() {
18270×
                    break;
1828301×
                }
1829301×
                let Some(ty) = ObjectType::ALL.get(head[0] as usize).copied() else {
18300×
                    break;
1831
                };
1832301×
                let flags = head[1];
1833301×
                let stored_len = u32::from_le_bytes(head[2..6].try_into().unwrap());
1834301×
                let raw_len = u32::from_le_bytes(head[6..10].try_into().unwrap());
1835301×
                let r = ObjectRef(head[10..42].try_into().unwrap());
1836301×
                let mut stored = vec![0u8; stored_len as usize];
1837301×
                if flags & FLAG_DICT != 0 || f.read_exact(&mut stored).is_err() {
18381×
                    break;
1839300×
                }
1840300×
                let e = PackEntry {
1841300×
                    offset: offset + 42,
1842300×
                    stored_len,
1843300×
                    raw_len,
1844300×
                    ty,
1845300×
                    flags,
1846300×
                };
1847300×
                if decode_entry(&r, e, stored, None).is_err() {
18480×
                    break;
1849300×
                }
1850300×
                index.push((r, e));
1851300×
                offset += 42 + stored_len as u64;
1852300×
                if index.len().is_multiple_of(200_000) {
18530×
                    progress(&format!(
18540×
                        "{name}: {} objects checked, {} MiB",
18550×
                        index.len(),
18560×
                        offset >> 20
18570×
                    ));
1858300×
                }
1859
            }
18601×
            if index.is_empty() {
18610×
                progress(&format!("{name}: no whole object, left alone"));
18620×
                continue;
18631×
            }
18641×
            if offset < meta.len() {
18651×
                progress(&format!(
18661×
                    "{name}: {} torn bytes at the end cut off",
18671×
                    meta.len() - offset
18681×
                ));
18691×
                fs::OpenOptions::new()
18701×
                    .write(true)
18711×
                    .open(&path)?
18721×
                    .set_len(offset)?;
18730×
            }
18741×
            index.sort_by_key(|(r, _)| *r);
18751×
            index.dedup_by_key(|(r, _)| *r);
18761×
            objects += index.len();
18771×
            packs += 1;
18781×
            progress(&format!("{name}: {} objects indexed", index.len()));
18791×
            self.finish_pack_files(id, &path, &index)?;
1880
        }
18812×
        Ok((packs, objects))
18822×
    }
1883
1884
    /// Every object reference in the store, loose and packed (slow; for gc and tests).
188586×
    pub fn list(&self) -> io::Result<Vec<ObjectRef>> {
188686×
        let mut out: Vec<ObjectRef> = self
188786×
            .loose_objects()
188886×
            .map_err(|e| io::Error::other(e.to_string()))?
188986×
            .into_iter()
189086×
            .map(|(r, _)| r)
189186×
            .collect();
189286×
        for p in self.packs.borrow().iter() {
189310×
            out.extend(p.refs.iter().copied());
189410×
        }
189586×
        out.sort();
189686×
        out.dedup();
189786×
        Ok(out)
189886×
    }
1899
}
1900
1901
/// A loose object's bytes, verified against `r`.
190248685×
fn parse_loose(data: &[u8], r: &ObjectRef) -> Result<Object> {
190348685×
    let nul = data
190448685×
        .iter()
1905693428×
        .position(|&b| b == 0)
190648685×
        .ok_or_else(|| StoreError::Corrupt(*r, "no header".into()))?;
190748685×
    let head = std::str::from_utf8(&data[..nul])
190848685×
        .map_err(|_| StoreError::Corrupt(*r, "header not UTF-8".into()))?;
190948685×
    let mut parts = head.split(' ');
191048685×
    let (Some("oxy1"), Some(ty), Some(len), None) =
191148685×
        (parts.next(), parts.next(), parts.next(), parts.next())
1912
    else {
19130×
        return Err(StoreError::Corrupt(*r, format!("bad header {head:?}")));
1914
    };
191548685×
    let ty = ObjectType::from_name(ty)
191648685×
        .ok_or_else(|| StoreError::Corrupt(*r, format!("unknown type {ty}")))?;
191748685×
    let len: usize = len
191848685×
        .parse()
191948685×
        .map_err(|_| StoreError::Corrupt(*r, "bad length".into()))?;
192048685×
    let body = &data[nul + 1..];
192148685×
    if body.len() != len {
19220×
        return Err(StoreError::Corrupt(
19230×
            *r,
19240×
            format!("length {} != header {len}", body.len()),
19250×
        ));
192648685×
    }
192748685×
    if hash_object(ty, body) != *r {
19284×
        return Err(StoreError::Corrupt(*r, "hash mismatch".into()));
192948681×
    }
193048681×
    Ok((ty, body.to_vec()))
193148685×
}
1932
1933
/// Whether the objects are files that a test may tamper with: not under
1934
/// `OXY_STORE_BACKEND=memory`.
1935
#[cfg(test)]
19366×
fn files_on_disk() -> bool {
19376×
    std::env::var_os("OXY_STORE_BACKEND").is_none()
19386×
}
1939
1940
#[cfg(test)]
1941
mod tests {
1942
    use super::*;
1943
1944
    /// The store under test twice: in a directory, and on a store in
1945
    /// memory with a scratch directory, as over a bucket.
19466×
    fn each_store(dir: &Path, f: impl Fn(&str, Store)) {
19476×
        f("directory", Store::open(dir.join("objects")).unwrap());
19486×
        f(
19496×
            "memory",
19506×
            Store::open_on(Arc::new(MemoryStore::new()), dir.join("scratch")).unwrap(),
19516×
        );
19526×
    }
1953
1954
    #[test]
19551×
    fn put_get_verify() {
19561×
        if !super::files_on_disk() {
19570×
            return;
19581×
        }
19591×
        let dir = tempfile::tempdir().unwrap();
19601×
        let s = Store::open(dir.path().join("objects")).unwrap();
19611×
        let r = s.put(ObjectType::Chunk, b"hello").unwrap();
19621×
        assert!(s.has(&r));
19631×
        assert_eq!(s.get(&r).unwrap(), (ObjectType::Chunk, b"hello".to_vec()));
19641×
        assert_eq!(s.put(ObjectType::Chunk, b"hello").unwrap(), r);
19651×
        assert_eq!(s.list().unwrap(), vec![r]);
19661×
        assert!(matches!(
19671×
            s.get_typed(&r, ObjectType::Blob),
1968
            Err(StoreError::WrongType(..))
1969
        ));
19701×
        assert!(matches!(
19711×
            s.get(&ObjectRef([9; 32])),
1972
            Err(StoreError::NotFound(_))
1973
        ));
1974
1975
        // Tamper: flip a byte, read must fail.
19761×
        let path = s.path_for(&r);
19771×
        let mut data = fs::read(&path).unwrap();
19781×
        let last = data.len() - 1;
19791×
        data[last] ^= 1;
19801×
        fs::write(&path, data).unwrap();
19811×
        assert!(matches!(s.get(&r), Err(StoreError::Corrupt(..))));
19821×
    }
1983
1984
    #[test]
19851×
    fn packing_keeps_every_object_readable() {
19861×
        if !super::files_on_disk() {
19870×
            return;
19881×
        }
19891×
        let dir = tempfile::tempdir().unwrap();
19901×
        let s = Store::open(dir.path()).unwrap();
19911×
        let mut refs = Vec::new();
1992300×
        for i in 0..300u32 {
1993300×
            let body = format!("object {i} ").repeat(1 + (i % 7) as usize);
1994300×
            refs.push((s.put(ObjectType::Chunk, body.as_bytes()).unwrap(), body));
1995300×
        }
19961×
        let c = crate::objects::tests::sample_change();
19971×
        let cr = s.put_change(&c).unwrap();
19981×
        assert_eq!(s.loose_count().unwrap(), 301);
19991×
        let report = s.pack_loose().unwrap();
20001×
        assert_eq!(report.objects, 301);
20011×
        assert!(report.packed_bytes < report.raw_bytes, "{report:?}");
20021×
        assert_eq!(s.loose_count().unwrap(), 0);
20031×
        assert_eq!(s.pack_count(), 1);
2004300×
        for (r, body) in &refs {
2005300×
            assert!(s.has(r));
2006300×
            assert_eq!(
2007300×
                s.get(r).unwrap(),
2008300×
                (ObjectType::Chunk, body.as_bytes().to_vec())
2009
            );
2010
        }
20111×
        assert_eq!(s.get_change(&cr).unwrap(), c);
20121×
        assert_eq!(s.list().unwrap().len(), 301);
2013
        // Re-putting a packed object is a no-op; new objects go loose and a
2014
        // second pack coexists with the first.
20151×
        assert_eq!(
20161×
            s.put(ObjectType::Chunk, refs[0].1.as_bytes()).unwrap(),
20171×
            refs[0].0
2018
        );
20191×
        assert_eq!(s.loose_count().unwrap(), 0);
20201×
        let extra = s.put(ObjectType::Chunk, b"after packing").unwrap();
20211×
        s.pack_loose().unwrap();
20221×
        assert_eq!(s.pack_count(), 2);
20231×
        assert_eq!(s.get(&extra).unwrap().1, b"after packing");
2024
        // A reopened store sees the packs.
20251×
        let s2 = Store::open(dir.path()).unwrap();
20261×
        assert_eq!(s2.pack_count(), 2);
20271×
        assert_eq!(s2.get(&refs[5].0).unwrap().1, refs[5].1.as_bytes());
20281×
        assert!(matches!(
20291×
            s2.get(&ObjectRef([9; 32])),
2030
            Err(StoreError::NotFound(_))
2031
        ));
2032
        // Corrupting an object's body inside the pack is detected on read.
20331×
        let target = refs[5].0;
20341×
        let (pack_path, offset) = {
20351×
            let packs = s2.packs.borrow();
20361×
            let (i, e) = s2.find_packed(&target).unwrap();
20371×
            (dir.path().join(&packs[i].key), e.offset as usize)
20381×
        };
20391×
        let mut data = fs::read(&pack_path).unwrap();
20401×
        data[offset] ^= 0xff;
20411×
        fs::write(&pack_path, data).unwrap();
20421×
        let s3 = Store::open(dir.path()).unwrap();
20431×
        assert!(matches!(s3.get(&target), Err(StoreError::Corrupt(..))));
20441×
        assert_eq!(
20451×
            s3.get(&refs[6].0).unwrap().1,
20461×
            refs[6].1.as_bytes(),
2047
            "other objects are unaffected"
2048
        );
20491×
    }
2050
2051
    #[test]
20521×
    fn a_full_repack_trains_a_dictionary_and_reads_back() {
20531×
        if !super::files_on_disk() {
20540×
            return;
20551×
        }
20561×
        let dir = tempfile::tempdir().unwrap();
20571×
        let s = Store::open(dir.path()).unwrap();
2058
        // Many small, alike files: what a dictionary is for.
20591×
        let bodies: Vec<Vec<u8>> = (0..1500)
20601500×
            .map(|i| {
20611500×
                format!(
2062
                    "// SPDX-License-Identifier: GPL-2.0\n#include <linux/module.h>\n\
2063
                     static int probe_{i}(struct device *dev)\n{{\n\treturn {i};\n}}\n"
2064
                )
20651500×
                .into_bytes()
20661500×
            })
20671×
            .collect();
20681×
        let refs: Vec<ObjectRef> = bodies
20691×
            .iter()
20701500×
            .map(|b| s.put(ObjectType::Chunk, b).unwrap())
20711×
            .collect();
20721×
        s.repack_all(REPACK_ZSTD_LEVEL).unwrap();
20731×
        let dicts = fs::read_dir(dir.path())
20741×
            .unwrap()
20751×
            .flatten()
20763×
            .filter(|e| e.path().extension().is_some_and(|x| x == "dict"))
20771×
            .count();
20781×
        assert_eq!(dicts, 1, "the pack has a dictionary");
20791×
        let with_dict = refs
20801×
            .iter()
20811500×
            .filter(|r| s.find_packed(r).unwrap().1.flags & FLAG_DICT != 0)
20821×
            .count();
20831×
        assert!(with_dict > 1000, "most use it: {with_dict}");
20841×
        let again = Store::open(dir.path()).unwrap();
20851500×
        for (r, b) in refs.iter().zip(&bodies) {
20861500×
            assert_eq!(&again.get(r).unwrap().1, b);
2087
        }
20883×
        let packs = |dir: &Path| {
20893×
            let mut v: Vec<String> = fs::read_dir(dir)
20903×
                .unwrap()
20913×
                .flatten()
209211×
                .map(|e| e.file_name().to_string_lossy().into_owned())
209311×
                .filter(|n| n.starts_with("pack-"))
20943×
                .collect();
20953×
            v.sort();
20963×
            v
20973×
        };
2098
        // With nothing new, a repack leaves that pack as it is: it would
2099
        // only write the same again.
21001×
        let before = packs(dir.path());
21011×
        let (report, merged) = again.repack_all(REPACK_ZSTD_LEVEL).unwrap();
21021×
        assert_eq!((report.objects, merged), (0, 0));
21031×
        assert_eq!(packs(dir.path()), before);
2104
        // One new object: a repack replaces the pack and its dictionary.
21051×
        let extra = again.put(ObjectType::Chunk, b"one more\n").unwrap();
21061×
        again.repack_all(REPACK_ZSTD_LEVEL).unwrap();
21071×
        let files = packs(dir.path());
21081×
        assert_eq!(files.len(), 3, "one pack, index and dictionary: {files:?}");
21091×
        assert_ne!(files, before);
21101×
        assert_eq!(&again.get(&refs[7]).unwrap().1, &bodies[7]);
21111×
        assert_eq!(again.get(&extra).unwrap().1, b"one more\n");
21121×
    }
2113
2114
    #[test]
21151×
    fn nocompress_chunks_pack_raw() {
21161×
        let dir = tempfile::tempdir().unwrap();
21171×
        let s = Store::open(dir.path()).unwrap();
21181×
        let body = vec![b'a'; 10_000];
21191×
        let raw = s.put_chunk_nocompress(&body).unwrap();
21201×
        let compressible = s.put(ObjectType::Chunk, &vec![b'b'; 10_000]).unwrap();
21211×
        s.pack_loose().unwrap();
21221×
        let packs = s.packs.borrow();
21231×
        let (i, e) = s.find_packed(&raw).unwrap();
21241×
        assert_eq!((e.flags, e.stored_len as usize), (0, 10_000));
21251×
        let (_, c) = s.find_packed(&compressible).unwrap();
21261×
        assert_eq!(c.flags, FLAG_ZSTD);
21271×
        assert!(c.stored_len < 10_000);
21281×
        assert_eq!(packs[i].fetch(s.backend.as_ref(), &raw, e).unwrap().1, body);
21291×
    }
2130
2131
    #[test]
21321×
    fn many_packs_merge_into_one() {
21331×
        let dir = tempfile::tempdir().unwrap();
21342×
        each_store(dir.path(), |which, s| {
21352×
            let mut refs = Vec::new();
213636×
            for i in 0..(MAX_PACKS + 2) {
213736×
                refs.push(
213836×
                    s.put(ObjectType::Chunk, format!("pack {i}").as_bytes())
213936×
                        .unwrap(),
214036×
                );
214136×
                s.pack_loose().unwrap();
214236×
            }
21432×
            assert_eq!(s.pack_count(), MAX_PACKS + 2, "{which}");
21442×
            assert_eq!(s.merge_packs().unwrap(), MAX_PACKS + 2);
21452×
            assert_eq!(s.pack_count(), 1);
21462×
            assert_eq!(s.merge_packs().unwrap(), 0);
214736×
            for (i, r) in refs.iter().enumerate() {
214836×
                assert_eq!(s.get(r).unwrap().1, format!("pack {i}").as_bytes());
2149
            }
21502×
            let again = Store::open_on(s.backend().clone(), s.dir()).unwrap();
21512×
            assert_eq!(again.pack_count(), 1, "{which}: reopened");
21522×
        });
21531×
    }
2154
2155
    #[test]
21561×
    fn prune_removes_unreachable_loose_and_packed_objects() {
2157
        use std::collections::HashSet;
21581×
        let dir = tempfile::tempdir().unwrap();
21592×
        each_store(dir.path(), |which, s| {
21602×
            let keep_a = s.put(ObjectType::Chunk, b"keep a").unwrap();
21612×
            let drop_a = s.put(ObjectType::Chunk, b"drop a").unwrap();
21622×
            s.pack_loose().unwrap();
21632×
            let keep_b = s.put(ObjectType::Chunk, b"keep b").unwrap();
21642×
            let drop_b = s.put(ObjectType::Chunk, b"drop b").unwrap();
21652×
            let sk = crate::identity::SecretKey {
21662×
                ed_seed: [1; 32],
21672×
                ml_seed: [2; 32],
21682×
            };
21692×
            let id = sk.identity("a", "b", 0);
21702×
            let key = s.put_identity(&id).unwrap();
21712×
            s.put_signature(
21722×
                &drop_b,
21732×
                &sk.sign(crate::identity::Domain::Change, &key, &drop_b),
2174
            )
21752×
            .unwrap();
21762×
            s.index_seal(&drop_a, &ObjectRef([3; 32])).unwrap();
21772×
            let keep: HashSet<ObjectRef> = [keep_a, keep_b, key].into_iter().collect();
2178
            // Everything is too young under a grace period.
21792×
            let r = s
21802×
                .prune(&keep, std::time::Duration::from_secs(3600))
21812×
                .unwrap();
21822×
            assert_eq!((r.objects, r.deferred), (0, 2), "{which}");
21832×
            let r = s.prune(&keep, std::time::Duration::ZERO).unwrap();
21842×
            assert_eq!(r.objects, 2, "{which}: {r:?}");
21852×
            assert!(s.has(&keep_a) && s.has(&keep_b) && s.has(&key));
21862×
            assert!(!s.has(&drop_a) && !s.has(&drop_b));
21872×
            assert!(s.signatures(&drop_b).unwrap().is_empty());
21882×
            assert!(s.seals_for(&drop_a).unwrap().is_empty());
21892×
            assert_eq!(s.pack_count(), 1);
21902×
            assert_eq!(s.get(&keep_a).unwrap().1, b"keep a");
21912×
            assert_eq!(s.list().unwrap().len(), 3);
21922×
        });
21931×
    }
2194
2195
    #[test]
21961×
    fn signatures_are_stored_beside_objects() {
2197
        use crate::identity::{Domain, SecretKey};
21981×
        let dir = tempfile::tempdir().unwrap();
21992×
        each_store(dir.path(), |which, s| {
22002×
            let r = s.put(ObjectType::Chunk, b"x").unwrap();
22012×
            assert!(s.signatures(&r).unwrap().is_empty());
22022×
            let sk = SecretKey {
22032×
                ed_seed: [1; 32],
22042×
                ml_seed: [2; 32],
22052×
            };
22062×
            let id = sk.identity("a", "b", 0);
22072×
            let key = s.put_identity(&id).unwrap();
22082×
            assert_eq!(s.get_identity(&key).unwrap(), id);
22092×
            let sig = sk.sign(Domain::Change, &key, &r);
22102×
            s.put_signature(&r, &sig).unwrap();
22112×
            s.put_signature(&r, &sig).unwrap();
22122×
            assert_eq!(s.signatures(&r).unwrap(), vec![sig.clone()], "{which}");
2213
            // A second signer is kept beside the first, sorted by key.
22142×
            let sk2 = SecretKey {
22152×
                ed_seed: [3; 32],
22162×
                ml_seed: [4; 32],
22172×
            };
22182×
            let key2 = s.put_identity(&sk2.identity("c", "d", 0)).unwrap();
22192×
            let sig2 = sk2.sign(Domain::Change, &key2, &r);
22202×
            s.put_signature(&r, &sig2).unwrap();
22212×
            let mut both = vec![sig.clone(), sig2.clone()];
22222×
            both.sort_by_key(|s| s.key);
22232×
            assert_eq!(s.signatures(&r).unwrap(), both);
2224
            // The object itself is untouched by its signatures.
22252×
            assert_eq!(s.get(&r).unwrap().1, b"x");
2226
            // Seal and receipt entries, and the states with receipts.
22272×
            s.index_seal(&r, &ObjectRef([5; 32])).unwrap();
22282×
            s.index_seal(&r, &ObjectRef([4; 32])).unwrap();
22292×
            s.index_seal(&r, &ObjectRef([5; 32])).unwrap();
22302×
            assert_eq!(
22312×
                s.seals_for(&r).unwrap(),
22322×
                vec![ObjectRef([4; 32]), ObjectRef([5; 32])]
2233
            );
22342×
            let st = ObjectRef([6; 32]);
22352×
            s.index_receipt(&st, &ObjectRef([7; 32])).unwrap();
22362×
            assert_eq!(s.receipts_for(&st).unwrap(), vec![ObjectRef([7; 32])]);
22372×
            assert_eq!(s.receipt_states().unwrap(), vec![st]);
22382×
        });
22391×
    }
2240
2241
    /// A store written before signatures, seals and receipts were one
2242
    /// entry each (`sigs/`, `seals/`, `receipts/` lists) still reads, and
2243
    /// what is written now sits beside what was there.
2244
    #[test]
22451×
    fn an_older_store_s_sidecar_lists_are_still_read() {
22461×
        if !super::files_on_disk() {
22470×
            return;
22481×
        }
2249
        use crate::identity::{Domain, SecretKey};
22501×
        let dir = tempfile::tempdir().unwrap();
22511×
        let s = Store::open(dir.path()).unwrap();
22521×
        let r = s.put(ObjectType::Chunk, b"old").unwrap();
22531×
        let h = r.to_hex();
22541×
        let sk = SecretKey {
22551×
            ed_seed: [1; 32],
22561×
            ml_seed: [2; 32],
22571×
        };
22581×
        let key = s.put_identity(&sk.identity("a", "b", 0)).unwrap();
22591×
        let sig = sk.sign(Domain::Change, &key, &r);
22601×
        let legacy = dir.path().join("sigs").join(&h[..2]);
22611×
        fs::create_dir_all(&legacy).unwrap();
22621×
        fs::write(
22631×
            legacy.join(&h[2..]),
22641×
            Signature::encode_list(std::slice::from_ref(&sig)),
2265
        )
22661×
        .unwrap();
22671×
        let seals = dir.path().join("seals").join(&h[..2]);
22681×
        fs::create_dir_all(&seals).unwrap();
22691×
        fs::write(
22701×
            seals.join(&h[2..]),
22711×
            format!("{}\n", ObjectRef([9; 32]).to_hex()),
2272
        )
22731×
        .unwrap();
22741×
        let receipts = dir.path().join("receipts").join(&h[..2]);
22751×
        fs::create_dir_all(&receipts).unwrap();
22761×
        fs::write(
22771×
            receipts.join(&h[2..]),
22781×
            format!("{}\n", ObjectRef([8; 32]).to_hex()),
2279
        )
22801×
        .unwrap();
2281
22821×
        assert_eq!(s.signatures(&r).unwrap(), vec![sig.clone()]);
22831×
        assert_eq!(s.seals_for(&r).unwrap(), vec![ObjectRef([9; 32])]);
22841×
        assert_eq!(s.receipts_for(&r).unwrap(), vec![ObjectRef([8; 32])]);
22851×
        assert_eq!(s.receipt_states().unwrap(), vec![r]);
2286
        // New entries join the old ones; the same signer is not doubled.
22871×
        s.put_signature(&r, &sig).unwrap();
22881×
        s.index_seal(&r, &ObjectRef([1; 32])).unwrap();
22891×
        assert_eq!(s.signatures(&r).unwrap().len(), 1);
22901×
        assert_eq!(
22911×
            s.seals_for(&r).unwrap(),
22921×
            vec![ObjectRef([1; 32]), ObjectRef([9; 32])]
2293
        );
2294
        // Pruning the object takes both layouts with it.
22951×
        let r2 = s.put(ObjectType::Chunk, b"kept").unwrap();
22961×
        let keep = [r2, key].into_iter().collect();
22971×
        s.prune(&keep, std::time::Duration::ZERO).unwrap();
22981×
        assert!(s.signatures(&r).unwrap().is_empty());
22991×
        assert!(s.seals_for(&r).unwrap().is_empty());
23001×
        assert!(s.receipt_states().unwrap().is_empty());
23011×
    }
2302
2303
    #[test]
23041×
    fn change_round_trip_through_store() {
23051×
        let dir = tempfile::tempdir().unwrap();
23062×
        each_store(dir.path(), |which, s| {
23072×
            let c = crate::objects::tests::sample_change();
23082×
            let r = s.put_change(&c).unwrap();
23092×
            assert_eq!(r, c.hash(), "{which}");
23102×
            assert_eq!(s.get_change(&r).unwrap(), c);
23112×
            assert_eq!(s.get_change_meta(&r).unwrap().message, c.message);
23122×
        });
23131×
    }
2314
23158057203×
    fn xorshift(state: &mut u64) -> u64 {
23168057203×
        *state ^= *state << 13;
23178057203×
        *state ^= *state >> 7;
23188057203×
        *state ^= *state << 17;
23198057203×
        *state
23208057203×
    }
2321
2322
    /// Random corruption of pack and index files never panics: reads fail
2323
    /// with an error or the store refuses to open, and untouched objects
2324
    /// stay readable when the index survives.
2325
    #[test]
23261×
    fn corrupted_packs_and_indexes_fail_cleanly() {
23271×
        if !super::files_on_disk() {
23280×
            return;
23291×
        }
23301×
        let dir = tempfile::tempdir().unwrap();
23311×
        let objects = dir.path().join("objects");
23321×
        let s = Store::open(&objects).unwrap();
23331×
        let mut refs = Vec::new();
23341×
        let mut seed = 0x9e3779b97f4a7c15u64;
233540×
        for i in 0..40u32 {
233640×
            let len = (xorshift(&mut seed) % 5000) as usize;
233740×
            let mut body = vec![0u8; len];
2338104686×
            for b in body.iter_mut() {
2339104686×
                *b = if i % 2 == 0 {
234056338×
                    (xorshift(&mut seed) & 0xff) as u8
2341
                } else {
234248348×
                    b'a' + (i % 26) as u8
2343
                };
2344
            }
234540×
            refs.push(s.put(ObjectType::Chunk, &body).unwrap());
2346
        }
23471×
        s.pack_loose().unwrap();
23481×
        let pack = fs::read_dir(&objects)
23491×
            .unwrap()
23502×
            .filter_map(|e| e.ok().map(|e| e.path()))
23512×
            .find(|p| p.extension().is_some_and(|x| x == "pack"))
23521×
            .unwrap();
23531×
        let idx = pack.with_extension("idx");
23541×
        let pristine_pack = fs::read(&pack).unwrap();
23551×
        let pristine_idx = fs::read(&idx).unwrap();
2356
2357300×
        for round in 0..300u32 {
2358300×
            let (path, pristine) = if round % 2 == 0 {
2359150×
                (&pack, &pristine_pack)
2360
            } else {
2361150×
                (&idx, &pristine_idx)
2362
            };
2363300×
            let mut data = pristine.clone();
2364300×
            match xorshift(&mut seed) % 4 {
236581×
                0 => {
236681×
                    let at = (xorshift(&mut seed) as usize) % data.len();
236781×
                    data[at] ^= 1 << (xorshift(&mut seed) % 8);
236881×
                }
236973×
                1 => {
237073×
                    let at = (xorshift(&mut seed) as usize) % data.len();
237173×
                    data[at] = (xorshift(&mut seed) & 0xff) as u8;
237273×
                }
237375×
                2 => {
237475×
                    let keep = (xorshift(&mut seed) as usize) % data.len();
237575×
                    data.truncate(keep);
237675×
                }
2377
                _ => {
237871×
                    let at = (xorshift(&mut seed) as usize) % data.len();
237971×
                    let n = ((xorshift(&mut seed) % 8) + 1) as usize;
2380324×
                    for k in 0..n.min(data.len() - at) {
2381324×
                        data[at + k] = 0xff;
2382324×
                    }
2383
                }
2384
            }
2385300×
            fs::write(path, &data).unwrap();
2386
            // Opening may refuse a broken index; a store that opens must
2387
            // either return each object intact or report it corrupt/missing.
2388300×
            if let Ok(s2) = Store::open(&objects) {
23897640×
                for r in &refs {
23907640×
                    match s2.get(r) {
23917452×
                        Ok((ty, body)) => assert_eq!(
23927452×
                            hash_object(ty, &body),
2393
                            *r,
2394
                            "a returned object always matches its reference"
2395
                        ),
2396
                        Err(StoreError::Corrupt(..))
2397
                        | Err(StoreError::NotFound(_))
2398188×
                        | Err(StoreError::Io(_)) => {}
23990×
                        Err(e) => panic!("unexpected error {e}"),
2400
                    }
2401
                }
2402109×
            }
2403300×
            fs::write(path, pristine).unwrap();
2404
        }
2405
        // Restored files read back in full.
24061×
        let s3 = Store::open(&objects).unwrap();
240740×
        for r in &refs {
240840×
            let (ty, body) = s3.get(r).unwrap();
240940×
            assert_eq!(hash_object(ty, &body), *r);
2410
        }
24111×
    }
2412
2413
    /// A small batch becomes loose objects; a large one becomes a single
2414
    /// pack. Objects are readable while pending, and batches nest.
2415
    #[test]
24161×
    fn batches_write_loose_or_one_pack() {
24171×
        let dir = tempfile::tempdir().unwrap();
24182×
        each_store(dir.path(), |which, s| {
24192×
            let outer = s.begin_batch().unwrap();
24202×
            let a = s.put(ObjectType::Chunk, b"small a").unwrap();
2421
            {
24222×
                let inner = s.begin_batch().unwrap();
24232×
                let b = s.put(ObjectType::Chunk, b"small b").unwrap();
24242×
                assert!(s.has(&b));
24252×
                assert_eq!(s.get(&b).unwrap().1, b"small b");
24262×
                inner.finish().unwrap();
24272×
                assert_eq!(
24282×
                    s.loose_count().unwrap(),
2429
                    0,
2430
                    "{which}: the inner batch defers to the outer one"
2431
                );
2432
            }
24332×
            assert_eq!(s.get(&a).unwrap().1, b"small a");
24342×
            assert_eq!(
24352×
                s.put(ObjectType::Chunk, b"small a").unwrap(),
2436
                a,
2437
                "idempotent while pending"
2438
            );
24392×
            outer.finish().unwrap();
24402×
            assert_eq!(s.loose_count().unwrap(), 2);
24412×
            assert_eq!(s.pack_count(), 0);
24422×
            assert_eq!(s.get(&a).unwrap().1, b"small a");
2443
2444
            // Large: spills into one pack, readable during and after.
24452×
            let big = s.begin_batch().unwrap();
24462×
            let mut refs = Vec::new();
24472×
            let mut seed = 7u64;
2448600×
            for i in 0..300u32 {
2449600×
                let mut body = vec![b'z'; 40_000];
2450600×
                if i % 3 == 0 {
24518000000×
                    for b in body.iter_mut() {
24528000000×
                        *b = (xorshift(&mut seed) & 0xff) as u8;
24538000000×
                    }
2454400×
                }
2455600×
                body[..4].copy_from_slice(&i.to_le_bytes());
2456600×
                let r = if i % 5 == 0 {
2457120×
                    s.put_chunk_nocompress(&body).unwrap()
2458
                } else {
2459480×
                    s.put(ObjectType::Chunk, &body).unwrap()
2460
                };
2461600×
                assert_eq!(
2462600×
                    s.get(&r).unwrap().1,
2463
                    body,
2464
                    "readable while pending (object {i})"
2465
                );
2466600×
                refs.push((r, body));
2467
            }
24682×
            assert!(s.has(&refs[0].0));
24692×
            big.finish().unwrap();
24702×
            assert_eq!(s.pack_count(), 1);
24712×
            assert_eq!(
24722×
                s.loose_count().unwrap(),
2473
                2,
2474
                "nothing from the big batch is loose"
2475
            );
24762×
            assert!(fs::read_dir(s.dir())
24772×
                .unwrap()
24782×
                .flatten()
24794×
                .all(|e| !e.file_name().to_string_lossy().contains("tmp-")));
24802×
            let s2 = Store::open_on(s.backend().clone(), s.dir()).unwrap();
2481600×
            for (r, body) in &refs {
2482600×
                assert_eq!(s2.get(r).unwrap().1, *body);
2483
            }
2484
            // A dropped batch still writes its objects.
24852×
            {
24862×
                let _b = s2.begin_batch().unwrap();
24872×
                s2.put(ObjectType::Chunk, b"dropped").unwrap();
24882×
            }
24892×
            assert_eq!(
24902×
                s2.get(&hash_object(ObjectType::Chunk, b"dropped"))
24912×
                    .unwrap()
2492
                    .1,
2493
                b"dropped"
2494
            );
24952×
        });
24961×
    }
2497
2498
    #[test]
24991×
    fn get_many_reads_loose_and_packed_objects_in_order() {
25001×
        let dir = tempfile::tempdir().unwrap();
25012×
        each_store(dir.path(), |which, s| {
25022×
            let packed: Vec<ObjectRef> = (0..20)
250340×
                .map(|i| {
250440×
                    s.put(ObjectType::Chunk, format!("packed {i}").as_bytes())
250540×
                        .unwrap()
250640×
                })
25072×
                .collect();
25082×
            s.pack_loose().unwrap();
25092×
            let loose: Vec<ObjectRef> = (0..20)
251040×
                .map(|i| {
251140×
                    s.put(ObjectType::Chunk, format!("loose {i}").as_bytes())
251240×
                        .unwrap()
251340×
                })
25142×
                .collect();
25152×
            let missing = hash_object(ObjectType::Chunk, b"never stored");
25162×
            let mut refs: Vec<ObjectRef> = Vec::new();
251740×
            for i in 0..20 {
251840×
                refs.push(loose[i]);
251940×
                refs.push(packed[i]);
252040×
            }
25212×
            refs.push(missing);
25222×
            let got = s.get_many(&refs);
25232×
            assert_eq!(got.len(), refs.len());
252480×
            for (i, r) in refs.iter().enumerate().take(40) {
252580×
                let want = if i % 2 == 0 {
252640×
                    format!("loose {}", i / 2)
2527
                } else {
252840×
                    format!("packed {}", i / 2)
2529
                };
253080×
                let (ty, body) = got[i].as_ref().unwrap();
253180×
                assert_eq!(
253280×
                    (*ty, body.as_slice()),
253380×
                    (ObjectType::Chunk, want.as_bytes()),
2534
                    "{which}: {r:?}"
2535
                );
2536
            }
25372×
            assert!(matches!(got[40], Err(StoreError::NotFound(_))));
25382×
        });
25391×
    }
2540
2541
    /// A packed object is read from its pack without first asking the
2542
    /// backend for a loose copy (oxygenhub#228: on a bucket each such ask
2543
    /// was a request that found nothing, every time).
2544
    #[test]
25451×
    fn packed_objects_cost_no_loose_lookups() {
2546
        use std::sync::atomic::{AtomicUsize, Ordering};
2547
        struct Counting(MemoryStore, AtomicUsize);
2548
        impl crate::strata::Store for Counting {
25490×
            fn describe(&self) -> String {
25500×
                "counting".into()
25510×
            }
255210×
            fn has(&self, k: &str) -> crate::strata::Result<bool> {
255310×
                self.0.has(k)
255410×
            }
255517×
            fn get(&self, k: &str) -> crate::strata::Result<Vec<u8>> {
255617×
                if k.starts_with("loose/") {
255711×
                    self.1.fetch_add(1, Ordering::Relaxed);
255811×
                }
255917×
                self.0.get(k)
256017×
            }
256120×
            fn get_range(
256220×
                &self,
256320×
                k: &str,
256420×
                r: std::ops::Range<u64>,
256520×
            ) -> crate::strata::Result<Vec<u8>> {
256620×
                self.0.get_range(k, r)
256720×
            }
256812×
            fn put_new(&self, k: &str, b: &[u8]) -> crate::strata::Result<()> {
256912×
                self.0.put_new(k, b)
257012×
            }
25719×
            fn list(&self, p: &str) -> crate::strata::Result<Vec<crate::strata::Entry>> {
25729×
                self.0.list(p)
25739×
            }
257410×
            fn delete(&self, k: &str) -> crate::strata::Result<()> {
257510×
                self.0.delete(k)
257610×
            }
25770×
            fn read_ref(
25780×
                &self,
25790×
                k: &str,
25800×
            ) -> crate::strata::Result<Option<(Vec<u8>, crate::strata::Version)>> {
25810×
                self.0.read_ref(k)
25820×
            }
25830×
            fn write_ref(
25840×
                &self,
25850×
                k: &str,
25860×
                b: &[u8],
25870×
                e: Option<&crate::strata::Version>,
25880×
            ) -> crate::strata::Result<crate::strata::Version> {
25890×
                self.0.write_ref(k, b, e)
25900×
            }
2591
        }
25921×
        let dir = tempfile::tempdir().unwrap();
25931×
        let backend = Arc::new(Counting(MemoryStore::new(), AtomicUsize::new(0)));
25941×
        let s = Store::open_on(backend.clone(), dir.path().join("scratch")).unwrap();
25951×
        let refs: Vec<ObjectRef> = (0..10)
259610×
            .map(|i| {
259710×
                s.put(ObjectType::Chunk, format!("p {i}").as_bytes())
259810×
                    .unwrap()
259910×
            })
26001×
            .collect();
26011×
        s.pack_loose().unwrap();
26021×
        let s = Store::open_on(backend.clone(), dir.path().join("scratch")).unwrap();
26031×
        backend.1.store(0, Ordering::Relaxed);
260410×
        for r in &refs {
260510×
            assert!(s.get(r).is_ok());
2606
        }
260710×
        assert!(s.get_many(&refs).iter().all(|g| g.is_ok()));
26081×
        assert_eq!(backend.1.load(Ordering::Relaxed), 0, "no loose lookups");
2609
        // An object no pack holds is still looked for loose.
26101×
        let missing = hash_object(ObjectType::Chunk, b"never stored");
26111×
        assert!(matches!(s.get(&missing), Err(StoreError::NotFound(_))));
26121×
        assert!(backend.1.load(Ordering::Relaxed) > 0);
26131×
    }
2614
}
2615
2616
#[cfg(test)]
2617
mod batch_tests {
2618
    use super::*;
2619
2620
    #[test]
26211×
    fn a_large_batch_packs_every_object_and_indexes_them_all() {
26221×
        let dir = tempfile::tempdir().unwrap();
26231×
        let store = Store::open(dir.path()).unwrap();
26241×
        let mut refs = Vec::new();
2625
        {
26261×
            let batch = store.begin_batch().unwrap();
26271000×
            for i in 0..1000u32 {
26281000×
                let body = format!("object {i} {}", "x".repeat(20_000 + i as usize)).into_bytes();
26291000×
                refs.push(store.put(ObjectType::Blob, &body).unwrap());
26301000×
            }
26311×
            batch.finish().unwrap();
2632
        }
26331×
        let again = Store::open(dir.path()).unwrap();
26341000×
        for r in &refs {
26351000×
            again
26361000×
                .get(r)
26371000×
                .unwrap_or_else(|e| panic!("{}: {e}", r.short(12)));
2638
        }
26391×
    }
2640
2641
    #[test]
26421×
    fn a_pack_a_stopped_batch_left_is_adopted_and_its_torn_end_cut() {
2643
        // oxygen#79: a batch never finished (a process killed part way)
2644
        // leaves its objects in an unindexed .tmp pack.
26451×
        let dir = tempfile::tempdir().unwrap();
26461×
        let mut refs = Vec::new();
2647
        {
26481×
            let store = Store::open(dir.path()).unwrap();
26491×
            let batch = store.begin_batch().unwrap();
2650300×
            for i in 0..300u32 {
2651300×
                let body = format!("object {i} {}", "y".repeat(20_000 + i as usize)).into_bytes();
2652300×
                refs.push(store.put(ObjectType::Blob, &body).unwrap());
2653300×
            }
26541×
            std::mem::forget(batch);
2655
        }
26561×
        let tmp: Vec<_> = fs::read_dir(dir.path())
26571×
            .unwrap()
26581×
            .flatten()
26592×
            .filter(|e| e.file_name().to_string_lossy().starts_with(".tmp-"))
26601×
            .map(|e| e.path())
26611×
            .collect();
26621×
        assert_eq!(tmp.len(), 1, "one unfinished pack");
2663
        // A torn last entry: a header and part of its body.
26641×
        let mut f = fs::OpenOptions::new().append(true).open(&tmp[0]).unwrap();
26651×
        f.write_all(&[0, 1, 0xff, 0, 0, 0, 9, 9, 0, 0]).unwrap();
26661×
        f.write_all(&[7; 40]).unwrap();
26671×
        drop(f);
26681×
        let store = Store::open(dir.path()).unwrap();
26691×
        assert!(store.get(&refs[0]).is_err(), "unreadable before");
26701×
        let young = store
26711×
            .adopt_unfinished_packs(std::time::Duration::from_secs(3600), &|_| {})
26721×
            .unwrap();
26731×
        assert_eq!(young, (0, 0), "a pack written to lately is left alone");
26741×
        let (packs, objects) = store
26752×
            .adopt_unfinished_packs(std::time::Duration::ZERO, &|_| {})
26761×
            .unwrap();
26771×
        assert_eq!((packs, objects), (1, 300));
2678300×
        for r in &refs {
2679300×
            store
2680300×
                .get(r)
2681300×
                .unwrap_or_else(|e| panic!("{}: {e}", r.short(12)));
2682
        }
26831×
        let again = Store::open(dir.path()).unwrap();
26841×
        assert!(again.get(&refs[299]).is_ok(), "indexed for good");
26851×
    }
2686
}
2687
2688
#[cfg(test)]
2689
mod size_tests {
2690
    use super::*;
2691
2692
    #[test]
26931×
    fn an_object_over_the_limit_is_refused_and_nothing_is_written() {
26941×
        let dir = tempfile::tempdir().unwrap();
26951×
        let store = Store::open(dir.path()).unwrap();
26961×
        let big = vec![b'x'; MAX_OBJECT_LEN as usize + 1];
2697
        {
26981×
            let batch = store.begin_batch().unwrap();
26991×
            store.put(ObjectType::Blob, b"small").unwrap();
27001×
            let e = store.put(ObjectType::Change, &big).unwrap_err();
27011×
            assert!(
27021×
                matches!(e, StoreError::TooLarge { kind: "change", .. }),
2703
                "{e}"
2704
            );
27051×
            assert!(e.to_string().contains("commit it in parts"), "{e}");
27061×
            batch.finish().unwrap();
2707
        }
2708
        // The store still opens and reads what was written.
27091×
        let again = Store::open(dir.path()).unwrap();
27101×
        again.get(&hash_object(ObjectType::Blob, b"small")).unwrap();
27111×
    }
2712
}
2713
2714
#[cfg(test)]
2715
mod text_tests {
2716
    use super::*;
2717
    use crate::objects::{AtomRef, Edit, CHANGE_VERSION};
2718
27192×
    fn large_change() -> Change {
27202×
        let mut c = crate::objects::tests::sample_change();
27212×
        assert_eq!(c.version, CHANGE_VERSION);
27222×
        c.edits[0] = Edit::Insert {
27232×
            node: crate::ids::NodeId([7; 16]),
27242×
            after: AtomRef::Start,
27252×
            before: AtomRef::End,
27262×
            lines: (0..2000)
27274000×
                .map(|i| format!("line {i}\n").into_bytes())
27282×
                .collect(),
2729
        };
27302×
        c
27312×
    }
2732
2733
    #[test]
27341×
    fn a_large_insert_is_stored_beside_its_change_and_read_back() {
27351×
        let dir = tempfile::tempdir().unwrap();
27361×
        let s = Store::open(dir.path()).unwrap();
27371×
        let c = large_change();
27381×
        let r = s.put_change(&c).unwrap();
27391×
        assert_eq!(r, c.hash());
27401×
        let (_, body) = s.get(&r).unwrap();
27411×
        assert!(
27421×
            body.len() < 1024,
2743
            "the change holds a reference, not {} bytes of lines",
27440×
            body.len()
2745
        );
27461×
        let (back, parts) = s.get_change_parts(&r).unwrap();
27471×
        assert_eq!(back, c);
2748
        // The text blob and its chunk.
27491×
        assert_eq!(parts.len(), 2);
27502×
        for p in &parts {
27512×
            assert!(s.has(p));
2752
        }
2753
        // Storing it again writes nothing new.
27541×
        let n = s.list().unwrap().len();
27551×
        s.put_change(&c).unwrap();
27561×
        assert_eq!(s.list().unwrap().len(), n);
27571×
    }
2758
2759
    #[test]
27601×
    fn a_change_whose_text_blob_is_missing_is_reported_not_misread() {
27611×
        if !super::files_on_disk() {
27620×
            return;
27631×
        }
27641×
        let dir = tempfile::tempdir().unwrap();
27651×
        let s = Store::open(dir.path()).unwrap();
27661×
        let c = large_change();
27671×
        let r = s.put_change(&c).unwrap();
27681×
        let (_, parts) = s.get_change_parts(&r).unwrap();
27691×
        fs::remove_file(s.path_for(&parts[0])).unwrap();
27701×
        let e = s.get_change(&r).unwrap_err();
27711×
        assert!(
27721×
            matches!(&e, StoreError::Corrupt(h, why) if *h == r && why.contains("missing")),
2773
            "{e}"
2774
        );
27751×
    }
2776
}
2777
2778
#[cfg(test)]
2779
mod put_many_tests {
2780
    use super::*;
2781
2782
    #[test]
27831×
    fn many_objects_in_a_batch_are_compressed_together_and_all_read_back() {
27841×
        let dir = tempfile::tempdir().unwrap();
27851×
        let s = Store::open(dir.path()).unwrap();
27861×
        let before = s.put(ObjectType::Chunk, b"already here").unwrap();
27871×
        let bodies: Vec<Vec<u8>> = (0..200u32)
2788200×
            .map(|i| format!("chunk {i} ").repeat(6000).into_bytes())
27891×
            .collect();
27901×
        let mut objects: Vec<(ObjectType, &[u8])> = bodies
27911×
            .iter()
2792200×
            .map(|b| (ObjectType::Chunk, b.as_slice()))
27931×
            .collect();
27941×
        objects.push((ObjectType::Chunk, bodies[0].as_slice()));
27951×
        objects.push((ObjectType::Chunk, b"already here"));
27961×
        let refs = {
27971×
            let batch = s.begin_batch().unwrap();
27981×
            let refs = s.put_many(&objects).unwrap();
27991×
            batch.finish().unwrap();
28001×
            refs
2801
        };
28021×
        assert_eq!(refs.len(), objects.len());
28031×
        assert_eq!(refs[200], refs[0], "a repeat is the same object");
28041×
        assert_eq!(refs[201], before);
28051×
        let again = Store::open(dir.path()).unwrap();
2806202×
        for (r, b) in refs.iter().zip(&objects) {
2807202×
            assert_eq!(again.get(r).unwrap().1, b.1);
2808
        }
28091×
    }
2810
}