OXYGENHUB
# a67914bced23 oxygen / crates / oxy-core / src / store.rs
93.6 KiB · Rust · last changed gc leaves a store that is already one full pack as it is 19 days ago source blame history raw
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
72
fn silent() -> impl FnMut(&str) {
73
    |_| {}
74
}
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.
78
fn backend_err(e: BackendError) -> StoreError {
79
    match e {
80
        BackendError::Io(e) => StoreError::Io(e),
81
        other => StoreError::Io(io::Error::other(other.to_string())),
82
    }
83
}
84
85
/// `put_new` where an object already there is what we wanted.
86
fn put_new_or_existing(backend: &Backend, key: &str, bytes: &[u8]) -> Result<()> {
87
    match backend.put_new(key, bytes) {
88
        Ok(()) | Err(BackendError::Exists(_)) => Ok(()),
89
        Err(e) => Err(backend_err(e)),
90
    }
91
}
92
93
/// `get` as an option: `None` when there is no such key.
94
fn get_optional(backend: &Backend, key: &str) -> Result<Option<Vec<u8>>> {
95
    match backend.get(key) {
96
        Ok(b) => Ok(Some(b)),
97
        Err(BackendError::NotFound(_)) => Ok(None),
98
        Err(e) => Err(backend_err(e)),
99
    }
100
}
101
102
fn delete(backend: &Backend, key: &str) -> Result<()> {
103
    backend.delete(key).map_err(backend_err)
104
}
105
106
/// `loose/<hh>/<rest>`.
107
fn loose_key(r: &ObjectRef) -> String {
108
    let h = r.to_hex();
109
    format!("loose/{}/{}", &h[..2], &h[2..])
110
}
111
112
/// The object a loose key names, if it is one.
113
fn loose_ref(key: &str) -> Option<ObjectRef> {
114
    let rest = key.strip_prefix("loose/")?;
115
    let (hh, tail) = rest.split_once('/')?;
116
    if hh.len() != 2 || tail.contains('/') {
117
        return None;
118
    }
119
    ObjectRef::from_hex(&format!("{hh}{tail}"))
120
}
121
122
/// `<index>/<hh>/<rest>/` for the entries kept under an object.
123
fn fanout_prefix(index: &str, r: &ObjectRef) -> String {
124
    let h = r.to_hex();
125
    format!("{index}/{}/{}/", &h[..2], &h[2..])
126
}
127
128
/// `<index>/<hh>/<rest>`: the one-file-per-object layout of older stores.
129
fn legacy_key(index: &str, r: &ObjectRef) -> String {
130
    let h = r.to_hex();
131
    format!("{index}/{}/{}", &h[..2], &h[2..])
132
}
133
134
fn now_ms() -> u64 {
135
    std::time::SystemTime::now()
136
        .duration_since(std::time::UNIX_EPOCH)
137
        .map(|d| d.as_millis() as u64)
138
        .unwrap_or(0)
139
}
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 {
161
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
162
        f.debug_struct("PackIndex")
163
            .field("key", &self.key)
164
            .field("objects", &self.refs.len())
165
            .field("dict", &self.dict.is_some())
166
            .finish()
167
    }
168
}
169
170
/// Decode a stored pack entry and check it against its reference.
171
fn decode_entry(
172
    r: &ObjectRef,
173
    e: PackEntry,
174
    stored: Vec<u8>,
175
    dict: Option<&Arc<zstd::dict::DecoderDictionary<'static>>>,
176
) -> Result<Object> {
177
    let body = if e.flags & FLAG_DICT != 0 {
178
        let dict = dict.ok_or_else(|| {
179
            StoreError::Corrupt(*r, "packed with a dictionary the pack lacks".into())
180
        })?;
181
        zstd::bulk::Decompressor::with_prepared_dictionary(dict)
182
            .and_then(|mut d| d.decompress(&stored, e.raw_len as usize))
183
            .map_err(|err| StoreError::Corrupt(*r, format!("zstd: {err}")))?
184
    } else if e.flags & FLAG_ZSTD != 0 {
185
        zstd::bulk::decompress(&stored, e.raw_len as usize)
186
            .map_err(|err| StoreError::Corrupt(*r, format!("zstd: {err}")))?
187
    } else {
188
        stored
189
    };
190
    if body.len() != e.raw_len as usize || hash_object(e.ty, &body) != *r {
191
        return Err(StoreError::Corrupt(
192
            *r,
193
            "packed object does not match its reference".into(),
194
        ));
195
    }
196
    Ok((e.ty, body))
197
}
198
199
impl PackIndex {
200
    fn load(backend: &Backend, idx_key: &str, pack_key: &str) -> Result<PackIndex> {
201
        let data = backend.get(idx_key).map_err(backend_err)?;
202
        let bad = |m: &str| StoreError::Corrupt(ObjectRef::ZERO, format!("{idx_key}: {m}"));
203
        if data.len() < 12 || &data[..8] != IDX_MAGIC {
204
            return Err(bad("bad index header"));
205
        }
206
        let count = u32::from_le_bytes(data[8..12].try_into().unwrap()) as usize;
207
        if data.len() != 12 + count * IDX_ENTRY {
208
            return Err(bad("index length mismatch"));
209
        }
210
        let pack_len = backend
211
            .stat(pack_key)
212
            .map_err(backend_err)?
213
            .ok_or_else(|| bad("the index names a pack that is not there"))?
214
            .size;
215
        let mut refs = Vec::with_capacity(count);
216
        let mut entries = Vec::with_capacity(count);
217
        for i in 0..count {
218
            let e = &data[12 + i * IDX_ENTRY..12 + (i + 1) * IDX_ENTRY];
219
            let r = ObjectRef::from_slice(&e[..32]).unwrap();
220
            if let Some(prev) = refs.last() {
221
                if r <= *prev {
222
                    return Err(bad("index not sorted"));
223
                }
224
            }
225
            refs.push(r);
226
            let entry = PackEntry {
227
                offset: u64::from_le_bytes(e[32..40].try_into().unwrap()),
228
                stored_len: u32::from_le_bytes(e[40..44].try_into().unwrap()),
229
                raw_len: u32::from_le_bytes(e[44..48].try_into().unwrap()),
230
                ty: ObjectType::ALL
231
                    .get(e[48] as usize)
232
                    .copied()
233
                    .ok_or_else(|| bad("unknown object type"))?,
234
                flags: e[49],
235
            };
236
            if entry.stored_len > MAX_OBJECT_LEN || entry.raw_len > MAX_OBJECT_LEN {
237
                return Err(StoreError::Corrupt(
238
                    r,
239
                    format!(
240
                        "{idx_key}: the index claims an object of {} bytes ({} stored), more than the {MAX_OBJECT_LEN} an object may be",
241
                        entry.raw_len, entry.stored_len
242
                    ),
243
                ));
244
            }
245
            if entry.offset.saturating_add(entry.stored_len as u64) > pack_len {
246
                return Err(bad("index entry points outside the pack"));
247
            }
248
            entries.push(entry);
249
        }
250
        let dict_key = format!("{}.dict", pack_key.trim_end_matches(".pack"));
251
        let dict = get_optional(backend, &dict_key)?
252
            .map(|d| Arc::new(zstd::dict::DecoderDictionary::copy(&d)));
253
        Ok(PackIndex {
254
            key: pack_key.to_string(),
255
            refs,
256
            entries,
257
            dict,
258
        })
259
    }
260
261
    fn find(&self, r: &ObjectRef) -> Option<PackEntry> {
262
        self.refs.binary_search(r).ok().map(|i| self.entries[i])
263
    }
264
265
    /// Read one entry from the pack: one ranged read, then decode.
266
    fn fetch(&self, backend: &Backend, r: &ObjectRef, e: PackEntry) -> Result<Object> {
267
        let stored = backend
268
            .get_range(&self.key, e.offset..e.offset + e.stored_len as u64)
269
            .map_err(|err| match err {
270
                BackendError::NotFound(_) => StoreError::NotFound(*r),
271
                other => backend_err(other),
272
            })?;
273
        decode_entry(r, e, stored, self.dict.as_ref())
274
    }
275
}
276
277
fn type_index(ty: ObjectType) -> u8 {
278
    ObjectType::ALL.iter().position(|t| *t == ty).unwrap() as u8
279
}
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 {
340
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
341
        f.debug_struct("Store")
342
            .field("backend", &self.backend.describe())
343
            .field("scratch", &self.scratch)
344
            .field("packs", &self.packs.borrow().len())
345
            .finish()
346
    }
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<'_> {
386
    pub fn finish(mut self) -> Result<()> {
387
        self.done = true;
388
        self.store.finish_batch()
389
    }
390
}
391
392
impl Drop for Batch<'_> {
393
    fn drop(&mut self) {
394
        if !self.done {
395
            let _ = self.store.finish_batch();
396
        }
397
    }
398
}
399
400
/// Append one stored object to a pending pack and index it.
401
fn write_pack_entry(
402
    pack: &mut PendingPack,
403
    r: &ObjectRef,
404
    ty: ObjectType,
405
    raw_len: usize,
406
    flags: u8,
407
    stored: &[u8],
408
    report: &mut PackReport,
409
) -> Result<PackEntry> {
410
    let header_len = 1 + 1 + 4 + 4 + 32;
411
    pack.writer.write_all(&[type_index(ty), flags])?;
412
    pack.writer
413
        .write_all(&(stored.len() as u32).to_le_bytes())?;
414
    pack.writer.write_all(&(raw_len as u32).to_le_bytes())?;
415
    pack.writer.write_all(&r.0)?;
416
    pack.writer.write_all(stored)?;
417
    let entry = PackEntry {
418
        offset: pack.offset + header_len,
419
        stored_len: stored.len() as u32,
420
        raw_len: raw_len as u32,
421
        ty,
422
        flags,
423
    };
424
    pack.offset += header_len + stored.len() as u64;
425
    pack.index.push((*r, entry));
426
    report.objects += 1;
427
    report.raw_bytes += raw_len as u64;
428
    report.packed_bytes += stored.len() as u64;
429
    Ok(entry)
430
}
431
432
/// A random name for a temporary file or a pack.
433
fn fresh_id() -> String {
434
    let mut nonce = [0u8; 8];
435
    rand::rngs::OsRng.fill_bytes(&mut nonce);
436
    hex::encode(nonce)
437
}
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.
443
fn memory_backend_for(dir: &Path) -> Option<Arc<Backend>> {
444
    use std::collections::HashMap;
445
    use std::sync::{Mutex, OnceLock};
446
    if std::env::var_os("OXY_STORE_BACKEND").as_deref() != Some(std::ffi::OsStr::new("memory")) {
447
        return None;
448
    }
449
    static STORES: OnceLock<Mutex<HashMap<PathBuf, Arc<MemoryStore>>>> = OnceLock::new();
450
    let key = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf());
451
    let mut map = STORES
452
        .get_or_init(Default::default)
453
        .lock()
454
        .unwrap_or_else(|p| p.into_inner());
455
    let store = map
456
        .entry(key)
457
        .or_insert_with(|| Arc::new(MemoryStore::new()))
458
        .clone();
459
    Some(store)
460
}
461
462
impl Store {
463
    /// Open the store in `dir`, which is also its scratch directory.
464
    pub fn open(dir: impl Into<PathBuf>) -> io::Result<Store> {
465
        let dir = dir.into();
466
        fs::create_dir_all(dir.join("loose"))?;
467
        if let Some(backend) = memory_backend_for(&dir) {
468
            return Store::open_on(backend, dir);
469
        }
470
        let backend: Arc<Backend> =
471
            Arc::new(LocalStore::open(&dir).map_err(|e| io::Error::other(e.to_string()))?);
472
        let mut store = Store::open_on(backend, dir)?;
473
        store.local = true;
474
        Ok(store)
475
    }
476
477
    /// Open the store kept on `backend`, with `scratch` for what must be
478
    /// on this disk: a pack while it is being written, and caches.
479
    pub fn open_on(backend: Arc<Backend>, scratch: impl Into<PathBuf>) -> io::Result<Store> {
480
        let scratch = scratch.into();
481
        fs::create_dir_all(&scratch)?;
482
        let store = Store {
483
            backend,
484
            scratch,
485
            local: false,
486
            packs: RefCell::new(Vec::new()),
487
            pending: RefCell::new(None),
488
            batch_depth: std::cell::Cell::new(0),
489
            metas: RefCell::new(None),
490
        };
491
        store
492
            .reload_packs()
493
            .map_err(|e| io::Error::other(e.to_string()))?;
494
        Ok(store)
495
    }
496
497
    /// The storage under this store.
498
    pub fn backend(&self) -> &Arc<Backend> {
499
        &self.backend
500
    }
501
502
    /// Whether the store is the directory `dir()` names, where every key
503
    /// is a file.
504
    pub fn is_local(&self) -> bool {
505
        self.local
506
    }
507
508
    fn reload_packs(&self) -> Result<()> {
509
        let listed = self.backend.list("pack-").map_err(backend_err)?;
510
        let mut idx_keys: Vec<&str> = listed
511
            .iter()
512
            .map(|e| e.key.as_str())
513
            .filter(|k| k.ends_with(".idx"))
514
            .collect();
515
        idx_keys.sort();
516
        let mut packs = Vec::new();
517
        for idx in idx_keys {
518
            let pack = format!("{}.pack", idx.trim_end_matches(".idx"));
519
            if listed.iter().any(|e| e.key == pack) {
520
                packs.push(PackIndex::load(self.backend.as_ref(), idx, &pack)?);
521
            }
522
        }
523
        *self.packs.borrow_mut() = packs;
524
        Ok(())
525
    }
526
527
    pub fn pack_count(&self) -> usize {
528
        self.packs.borrow().len()
529
    }
530
531
    fn find_packed(&self, r: &ObjectRef) -> Option<(usize, PackEntry)> {
532
        self.packs
533
            .borrow()
534
            .iter()
535
            .enumerate()
536
            .find_map(|(i, p)| p.find(r).map(|e| (i, e)))
537
    }
538
539
    /// Loose objects, with their keys and ages.
540
    fn loose_objects(&self) -> Result<Vec<(ObjectRef, strata::Entry)>> {
541
        let mut out: Vec<(ObjectRef, strata::Entry)> = self
542
            .backend
543
            .list("loose/")
544
            .map_err(backend_err)?
545
            .into_iter()
546
            .filter_map(|e| loose_ref(&e.key).map(|r| (r, e)))
547
            .collect();
548
        out.sort_by_key(|(r, _)| *r);
549
        Ok(out)
550
    }
551
552
    pub fn loose_count(&self) -> io::Result<usize> {
553
        self.loose_objects()
554
            .map(|l| l.len())
555
            .map_err(|e| io::Error::other(e.to_string()))
556
    }
557
558
    /// Move every loose object into a new pack (spec §13.4). Loose objects
559
    /// are deleted only after the pack and its index are durable.
560
    pub fn pack_loose(&self) -> Result<PackReport> {
561
        let loose = self.loose_objects()?;
562
        self.write_pack(
563
            &loose.iter().map(|(r, _)| *r).collect::<Vec<_>>(),
564
            &loose.iter().map(|(_, e)| e.key.clone()).collect::<Vec<_>>(),
565
            &[],
566
            ZSTD_LEVEL,
567
            &mut silent(),
568
        )
569
    }
570
571
    /// Fold every pack and loose object into one pack compressed at
572
    /// `level` (spec §13.4): what an explicit `oxy gc` does, as `git gc`
573
    /// repacks. Returns the report and how many packs were folded in.
574
    pub fn repack_all(&self, level: i32) -> Result<(PackReport, usize)> {
575
        self.repack_all_with(level, &mut silent())
576
    }
577
578
    /// [`Store::repack_all`], reporting progress.
579
    pub fn repack_all_with(&self, level: i32, progress: Progress) -> Result<(PackReport, usize)> {
580
        let loose = self.loose_objects()?;
581
        let (mut refs, keys, trained): (Vec<ObjectRef>, Vec<String>, bool) = {
582
            let packs = self.packs.borrow();
583
            (
584
                packs.iter().flat_map(|p| p.refs.iter().copied()).collect(),
585
                packs.iter().map(|p| p.key.clone()).collect(),
586
                packs.first().is_some_and(|p| p.dict.is_some()),
587
            )
588
        };
589
        // Nothing loose and one pack already made by a full repack (only
590
        // such a pack has a trained dictionary): rewriting it would give
591
        // the same pack. A hub's nightly gc rewrote andymccall/oxygen's
592
        // 48 000 objects (37 s under its write lock) every time.
593
        if loose.is_empty() && keys.len() <= 1 && (level == ZSTD_LEVEL || trained) {
594
            return Ok((PackReport::default(), 0));
595
        }
596
        refs.extend(loose.iter().map(|(r, _)| *r));
597
        let loose_keys: Vec<String> = loose.into_iter().map(|(_, e)| e.key).collect();
598
        let n = keys.len();
599
        let report = self.write_pack(&refs, &loose_keys, &keys, level, progress)?;
600
        Ok((report, n))
601
    }
602
603
    /// Fold every pack into one when there are more than `MAX_PACKS`
604
    /// (spec §13.4). Returns how many packs were merged.
605
    pub fn merge_packs(&self) -> Result<usize> {
606
        let (refs, keys): (Vec<ObjectRef>, Vec<String>) = {
607
            let packs = self.packs.borrow();
608
            if packs.len() <= MAX_PACKS {
609
                return Ok(0);
610
            }
611
            (
612
                packs.iter().flat_map(|p| p.refs.iter().copied()).collect(),
613
                packs.iter().map(|p| p.key.clone()).collect(),
614
            )
615
        };
616
        let n = keys.len();
617
        self.write_pack(&refs, &[], &keys, ZSTD_LEVEL, &mut silent())?;
618
        Ok(n)
619
    }
620
621
    /// Delete every object not in `keep` (spec §21). Loose objects and packs
622
    /// younger than `grace` are left alone, since a concurrent writer may not
623
    /// have recorded its references yet. Packs holding unreachable objects
624
    /// are rewritten without them. Signatures, seal and receipt entries of
625
    /// deleted objects go too.
626
    pub fn prune(
627
        &self,
628
        keep: &std::collections::HashSet<ObjectRef>,
629
        grace: std::time::Duration,
630
    ) -> Result<PruneReport> {
631
        self.prune_with(keep, grace, &mut silent())
632
    }
633
634
    /// [`Store::prune`], reporting progress.
635
    pub fn prune_with(
636
        &self,
637
        keep: &std::collections::HashSet<ObjectRef>,
638
        grace: std::time::Duration,
639
        progress: Progress,
640
    ) -> Result<PruneReport> {
641
        progress("pruning loose objects");
642
        let now = now_ms();
643
        let grace_ms = grace.as_millis() as u64;
644
        // An object whose age the store does not know is old enough.
645
        let old_enough =
646
            |modified: Option<u64>| modified.is_none_or(|t| now.saturating_sub(t) >= grace_ms);
647
        let mut report = PruneReport::default();
648
        // Loose objects.
649
        for (r, entry) in self.loose_objects()? {
650
            if keep.contains(&r) {
651
                continue;
652
            }
653
            if !old_enough(entry.modified_ms) {
654
                report.deferred += 1;
655
                continue;
656
            }
657
            report.bytes += entry.size;
658
            report.objects += 1;
659
            delete(self.backend.as_ref(), &entry.key)?;
660
            self.remove_sidecars(&r)?;
661
        }
662
        // Packs: rewrite those that hold unreachable objects.
663
        let mut keep_refs: Vec<ObjectRef> = Vec::new();
664
        let mut old_keys: Vec<String> = Vec::new();
665
        let mut rewrite = false;
666
        progress("pruning packs");
667
        for p in self.packs.borrow().iter() {
668
            let unreachable = p.refs.iter().filter(|r| !keep.contains(r)).count();
669
            if unreachable == 0 {
670
                continue;
671
            }
672
            let modified = self
673
                .backend
674
                .stat(&p.key)
675
                .map_err(backend_err)?
676
                .and_then(|e| e.modified_ms);
677
            if !old_enough(modified) {
678
                report.deferred += unreachable;
679
                continue;
680
            }
681
            rewrite = true;
682
            old_keys.push(p.key.clone());
683
            for (r, e) in p.refs.iter().zip(p.entries.iter()) {
684
                if keep.contains(r) {
685
                    keep_refs.push(*r);
686
                } else {
687
                    report.objects += 1;
688
                    report.bytes += e.stored_len as u64;
689
                }
690
            }
691
        }
692
        if rewrite {
693
            let dropped: Vec<ObjectRef> = {
694
                let packs = self.packs.borrow();
695
                packs
696
                    .iter()
697
                    .filter(|p| old_keys.contains(&p.key))
698
                    .flat_map(|p| p.refs.iter().copied())
699
                    .filter(|r| !keep.contains(r))
700
                    .collect()
701
            };
702
            self.write_pack(&keep_refs, &[], &old_keys, ZSTD_LEVEL, progress)?;
703
            for r in dropped {
704
                self.remove_sidecars(&r)?;
705
            }
706
        }
707
        Ok(report)
708
    }
709
710
    /// Everything kept beside an object: its signatures and the seal and
711
    /// receipt entries under it, in both layouts.
712
    fn remove_sidecars(&self, r: &ObjectRef) -> Result<()> {
713
        for index in ["sigs", "seals", "receipts"] {
714
            delete(self.backend.as_ref(), &legacy_key(index, r))?;
715
        }
716
        for index in ["sig", "seal", "receipt"] {
717
            for e in self
718
                .backend
719
                .list(&fanout_prefix(index, r))
720
                .map_err(backend_err)?
721
            {
722
                delete(self.backend.as_ref(), &e.key)?;
723
            }
724
        }
725
        Ok(())
726
    }
727
728
    /// Put a complete, synced temporary pack file and its index into the
729
    /// store; `index` must be sorted by ObjectRef. The pack goes first: an
730
    /// index never names a pack that is not there.
731
    fn finish_pack_files(
732
        &self,
733
        id: &str,
734
        tmp_pack: &Path,
735
        index: &[(ObjectRef, PackEntry)],
736
    ) -> Result<()> {
737
        let mut idx = Vec::with_capacity(12 + index.len() * IDX_ENTRY);
738
        idx.extend_from_slice(IDX_MAGIC);
739
        idx.extend_from_slice(&(index.len() as u32).to_le_bytes());
740
        for (r, e) in index {
741
            idx.extend_from_slice(&r.0);
742
            idx.extend_from_slice(&e.offset.to_le_bytes());
743
            idx.extend_from_slice(&e.stored_len.to_le_bytes());
744
            idx.extend_from_slice(&e.raw_len.to_le_bytes());
745
            idx.extend_from_slice(&[type_index(e.ty), e.flags]);
746
        }
747
        let put = self
748
            .backend
749
            .put_new_file(&format!("pack-{id}.pack"), tmp_pack)
750
            .map_err(backend_err);
751
        // A store on another disk copied it; the one in this directory
752
        // moved it and this finds nothing.
753
        let _ = fs::remove_file(tmp_pack);
754
        put?;
755
        self.backend
756
            .put_new(&format!("pack-{id}.idx"), &idx)
757
            .map_err(backend_err)?;
758
        self.reload_packs()
759
    }
760
761
    /// Remove a pack with its index and dictionary.
762
    fn remove_pack(&self, pack_key: &str) -> Result<()> {
763
        let stem = pack_key.trim_end_matches(".pack");
764
        delete(self.backend.as_ref(), pack_key)?;
765
        delete(self.backend.as_ref(), &format!("{stem}.idx"))?;
766
        delete(self.backend.as_ref(), &format!("{stem}.dict"))
767
    }
768
769
    /// Write `refs` into a new pack, then delete `loose_keys` and `old_packs`.
770
    fn write_pack(
771
        &self,
772
        refs: &[ObjectRef],
773
        loose_keys: &[String],
774
        old_packs: &[String],
775
        level: i32,
776
        progress: Progress,
777
    ) -> Result<PackReport> {
778
        if refs.is_empty() {
779
            for p in old_packs {
780
                self.remove_pack(p)?;
781
            }
782
            self.reload_packs()?;
783
            return Ok(PackReport::default());
784
        }
785
        let mut refs: Vec<ObjectRef> = refs.to_vec();
786
        refs.sort();
787
        refs.dedup();
788
        let id = fresh_id();
789
        let tmp_pack = self.scratch.join(format!(".tmp-{id}.pack"));
790
        let mut report = PackReport::default();
791
        let mut index: Vec<(ObjectRef, PackEntry)> = Vec::with_capacity(refs.len());
792
        // A full repack of enough objects trains a dictionary for them.
793
        let dict = if level == REPACK_ZSTD_LEVEL && refs.len() >= DICT_MIN_OBJECTS {
794
            let _t = crate::timing::phase("pack: train a dictionary");
795
            progress(&format!("training a dictionary on {} objects", refs.len()));
796
            self.train_dictionary(&refs)
797
        } else {
798
            None
799
        };
800
        let encoder = dict
801
            .as_ref()
802
            .map(|d| zstd::dict::EncoderDictionary::copy(d, level));
803
        let nocompress = self.nocompress_set()?;
804
        {
805
            let mut f = io::BufWriter::new(fs::File::create(&tmp_pack)?);
806
            f.write_all(PACK_MAGIC)?;
807
            let mut offset = PACK_MAGIC.len() as u64;
808
            // Read a batch (the store is not shared between threads),
809
            // compress it on every core, write it in order.
810
            let mut batches = refs.chunks(1024);
811
            let mut compressed_batch = Vec::new();
812
            let total = refs.len();
813
            let mut reported = usize::MAX;
814
            loop {
815
                if compressed_batch.is_empty() {
816
                    let Some(batch) = batches.next() else { break };
817
                    // Every tenth, and the first batch.
818
                    let tenth = report.objects * 10 / total.max(1);
819
                    if tenth != reported {
820
                        reported = tenth;
821
                        progress(&format!("packing {} of {total} objects", report.objects));
822
                    }
823
                    let mut read: Vec<(ObjectRef, ObjectType, Vec<u8>, bool)> =
824
                        Vec::with_capacity(batch.len());
825
                    for r in batch {
826
                        let (ty, body) = self.get(r)?;
827
                        read.push((*r, ty, body, nocompress.contains(r)));
828
                    }
829
                    use rayon::prelude::*;
830
                    compressed_batch = read
831
                        .into_par_iter()
832
                        .map_init(
833
                            || {
834
                                encoder.as_ref().and_then(|e| {
835
                                    zstd::bulk::Compressor::with_prepared_dictionary(e).ok()
836
                                })
837
                            },
838
                            |with_dict, (r, ty, body, raw)| {
839
                                let packed = if raw {
840
                                    None
841
                                } else {
842
                                    // Small objects with the dictionary;
843
                                    // a large one has context enough.
844
                                    let dicted = with_dict
845
                                        .as_mut()
846
                                        .filter(|_| body.len() <= DICT_OBJECT_MAX)
847
                                        .and_then(|c| c.compress(&body).ok())
848
                                        .map(|c| (FLAG_ZSTD | FLAG_DICT, c));
849
                                    dicted
850
                                        .or_else(|| {
851
                                            zstd::bulk::compress(&body, level)
852
                                                .ok()
853
                                                .map(|c| (FLAG_ZSTD, c))
854
                                        })
855
                                        .filter(|(_, c)| c.len() < body.len())
856
                                };
857
                                (r, ty, body, packed)
858
                            },
859
                        )
860
                        .collect::<Vec<_>>();
861
                    compressed_batch.reverse();
862
                }
863
                let Some((r, ty, body, packed)) = compressed_batch.pop() else {
864
                    continue;
865
                };
866
                let r = &r;
867
                let (flags, stored) = match packed {
868
                    Some(c) => c,
869
                    None => (0, body.clone()),
870
                };
871
                let header_len = 1 + 1 + 4 + 4 + 32;
872
                f.write_all(&[type_index(ty), flags])?;
873
                f.write_all(&(stored.len() as u32).to_le_bytes())?;
874
                f.write_all(&(body.len() as u32).to_le_bytes())?;
875
                f.write_all(&r.0)?;
876
                f.write_all(&stored)?;
877
                index.push((
878
                    *r,
879
                    PackEntry {
880
                        offset: offset + header_len,
881
                        stored_len: stored.len() as u32,
882
                        raw_len: body.len() as u32,
883
                        ty,
884
                        flags,
885
                    },
886
                ));
887
                offset += header_len + stored.len() as u64;
888
                report.objects += 1;
889
                report.raw_bytes += body.len() as u64;
890
                report.packed_bytes += stored.len() as u64;
891
            }
892
            f.flush()?;
893
            f.get_ref().sync_all()?;
894
        }
895
        // The dictionary before the pack that needs it becomes visible.
896
        if let Some(d) = &dict {
897
            self.backend
898
                .put_new(&format!("pack-{id}.dict"), d)
899
                .map_err(backend_err)?;
900
        }
901
        progress(&format!("writing the index of {} objects", index.len()));
902
        self.finish_pack_files(&id, &tmp_pack, &index)?;
903
        for p in old_packs {
904
            self.remove_pack(p)?;
905
        }
906
        self.reload_packs()?;
907
        for key in loose_keys {
908
            delete(self.backend.as_ref(), key)?;
909
        }
910
        Ok(report)
911
    }
912
913
    /// A dictionary for these objects, trained on a sample of them (at
914
    /// most 10 000, 32 MB); `None` when training fails.
915
    fn train_dictionary(&self, refs: &[ObjectRef]) -> Option<Vec<u8>> {
916
        let step = (refs.len() / 10_000).max(1);
917
        let mut samples: Vec<Vec<u8>> = Vec::new();
918
        let mut total = 0usize;
919
        for r in refs.iter().step_by(step) {
920
            if total > 32 << 20 {
921
                break;
922
            }
923
            let Ok((ty, body)) = self.get(r) else {
924
                continue;
925
            };
926
            if matches!(
927
                ty,
928
                ObjectType::Chunk | ObjectType::Blob | ObjectType::Change
929
            ) && !body.is_empty()
930
                && body.len() < 1 << 20
931
            {
932
                total += body.len();
933
                samples.push(body);
934
            }
935
        }
936
        zstd::dict::from_samples(&samples, DICT_BYTES).ok()
937
    }
938
939
    /// The scratch directory: for a store in a directory, that directory.
940
    pub fn dir(&self) -> &Path {
941
        &self.scratch
942
    }
943
944
    /// Where a loose object is kept, for a store in a directory (tests
945
    /// tamper with and remove objects there).
946
    #[cfg(test)]
947
    pub(crate) fn path_for(&self, r: &ObjectRef) -> PathBuf {
948
        self.scratch.join(loose_key(r))
949
    }
950
951
    /// Remove a loose object, whatever the store is on (tests make an
952
    /// object go missing).
953
    #[cfg(test)]
954
    pub(crate) fn remove_loose_for_test(&self, r: &ObjectRef) -> Result<()> {
955
        delete(self.backend.as_ref(), &loose_key(r))
956
    }
957
958
    pub fn has(&self, r: &ObjectRef) -> bool {
959
        self.backend.has(&loose_key(r)).unwrap_or(false)
960
            || self.find_packed(r).is_some()
961
            || self
962
                .pending
963
                .borrow()
964
                .as_ref()
965
                .is_some_and(|p| p.lookup.contains_key(r))
966
    }
967
968
    /// Start a write batch: until the matching `finish`, `put` collects
969
    /// objects and writes them out together, with one `fsync` for a large
970
    /// batch (a pack) instead of one per object. Batches nest; only the
971
    /// outermost does the work. Objects are readable while pending.
972
    pub fn begin_batch(&self) -> Result<Batch<'_>> {
973
        let depth = self.batch_depth.get();
974
        if depth == 0 {
975
            *self.pending.borrow_mut() = Some(Pending {
976
                buffered: vec![],
977
                buffered_bytes: 0,
978
                lookup: Default::default(),
979
                pack: None,
980
                report: PackReport::default(),
981
            });
982
        }
983
        self.batch_depth.set(depth + 1);
984
        Ok(Batch {
985
            store: self,
986
            done: false,
987
        })
988
    }
989
990
    fn finish_batch(&self) -> Result<()> {
991
        let depth = self.batch_depth.get();
992
        if depth == 0 {
993
            return Ok(());
994
        }
995
        self.batch_depth.set(depth - 1);
996
        if depth > 1 {
997
            return Ok(());
998
        }
999
        let Some(pending) = self.pending.borrow_mut().take() else {
1000
            return Ok(());
1001
        };
1002
        self.write_pending(pending)
1003
    }
1004
1005
    /// Make every object written so far durable, even inside an open
1006
    /// batch, which stays open. Call before a reference that names them
1007
    /// is moved (spec §13.6): the operation head, a bookmark pointer.
1008
    pub fn flush(&self) -> Result<()> {
1009
        let Some(pending) = self.pending.borrow_mut().take() else {
1010
            return Ok(());
1011
        };
1012
        self.write_pending(pending)?;
1013
        *self.pending.borrow_mut() = Some(Pending {
1014
            buffered: vec![],
1015
            buffered_bytes: 0,
1016
            lookup: Default::default(),
1017
            pack: None,
1018
            report: PackReport::default(),
1019
        });
1020
        Ok(())
1021
    }
1022
1023
    fn write_pending(&self, pending: Pending) -> Result<()> {
1024
        match pending.pack {
1025
            None => {
1026
                let objects: Vec<(ObjectType, &[u8])> = pending
1027
                    .buffered
1028
                    .iter()
1029
                    .map(|(ty, body)| (*ty, body.as_slice()))
1030
                    .collect();
1031
                self.put_loose_many(&objects)
1032
            }
1033
            Some(mut pack) => {
1034
                pack.writer.flush()?;
1035
                pack.writer.get_ref().sync_all()?;
1036
                drop(pack.writer);
1037
                pack.index.sort_by_key(|(r, _)| *r);
1038
                self.finish_pack_files(&pack.id, &pack.tmp_path, &pack.index)?;
1039
                Ok(())
1040
            }
1041
        }
1042
    }
1043
1044
    /// Whether a batch is open and holds `r`.
1045
    fn pending_get(&self, r: &ObjectRef) -> Option<Result<Object>> {
1046
        let mut guard = self.pending.borrow_mut();
1047
        let pending = guard.as_mut()?;
1048
        let entry = *pending.lookup.get(r)?;
1049
        Some(match entry {
1050
            PendingEntry::Buffered(i) => {
1051
                let (ty, body) = &pending.buffered[i];
1052
                Ok((*ty, body.clone()))
1053
            }
1054
            PendingEntry::Packed(e) => {
1055
                let Some(pack) = pending.pack.as_mut() else {
1056
                    return Some(Err(StoreError::NotFound(*r)));
1057
                };
1058
                // Read from the pack file being written, on this disk.
1059
                (|| {
1060
                    pack.writer.flush()?;
1061
                    use std::io::{Read, Seek, SeekFrom};
1062
                    let mut f = fs::File::open(&pack.tmp_path)?;
1063
                    f.seek(SeekFrom::Start(e.offset))?;
1064
                    let mut stored = vec![0u8; e.stored_len as usize];
1065
                    f.read_exact(&mut stored)?;
1066
                    decode_entry(r, e, stored, None)
1067
                })()
1068
            }
1069
        })
1070
    }
1071
1072
    /// Append one object to the pending pack file.
1073
    fn pending_pack_write(
1074
        &self,
1075
        pack: &mut PendingPack,
1076
        r: &ObjectRef,
1077
        ty: ObjectType,
1078
        body: &[u8],
1079
        report: &mut PackReport,
1080
    ) -> Result<PackEntry> {
1081
        let (flags, stored) = if self.is_nocompress(r) {
1082
            (0, body.to_vec())
1083
        } else {
1084
            let compressed = zstd::bulk::compress(body, ZSTD_LEVEL)
1085
                .map_err(|e| StoreError::Corrupt(*r, format!("zstd: {e}")))?;
1086
            if compressed.len() < body.len() {
1087
                (FLAG_ZSTD, compressed)
1088
            } else {
1089
                (0, body.to_vec())
1090
            }
1091
        };
1092
        write_pack_entry(pack, r, ty, body.len(), flags, &stored, report)
1093
    }
1094
1095
    fn put_pending(&self, r: ObjectRef, ty: ObjectType, body: &[u8]) -> Result<()> {
1096
        let mut guard = self.pending.borrow_mut();
1097
        let pending = guard.as_mut().expect("batch open");
1098
        if pending.lookup.contains_key(&r) {
1099
            return Ok(());
1100
        }
1101
        if pending.pack.is_none()
1102
            && pending.buffered.len() < SPILL_OBJECTS
1103
            && pending.buffered_bytes + body.len() <= SPILL_BYTES
1104
        {
1105
            pending.buffered.push((ty, body.to_vec()));
1106
            pending.buffered_bytes += body.len();
1107
            pending
1108
                .lookup
1109
                .insert(r, PendingEntry::Buffered(pending.buffered.len() - 1));
1110
            return Ok(());
1111
        }
1112
        self.ensure_pack(pending)?;
1113
        let mut report = std::mem::take(&mut pending.report);
1114
        let pack = pending.pack.as_mut().unwrap();
1115
        let e = self.pending_pack_write(pack, &r, ty, body, &mut report)?;
1116
        pending.report = report;
1117
        pending.lookup.insert(r, PendingEntry::Packed(e));
1118
        Ok(())
1119
    }
1120
1121
    /// Open the pending batch's pack, moving the objects buffered so far
1122
    /// into it (a spill).
1123
    fn ensure_pack(&self, pending: &mut Pending) -> Result<()> {
1124
        if pending.pack.is_none() {
1125
            // Spill: open the pack and move the buffered objects into it.
1126
            let id = fresh_id();
1127
            let tmp_path = self.scratch.join(format!(".tmp-{id}.pack"));
1128
            let mut writer = io::BufWriter::new(fs::File::create(&tmp_path)?);
1129
            writer.write_all(PACK_MAGIC)?;
1130
            let mut pack = PendingPack {
1131
                id,
1132
                tmp_path,
1133
                writer,
1134
                offset: PACK_MAGIC.len() as u64,
1135
                index: vec![],
1136
            };
1137
            let buffered = std::mem::take(&mut pending.buffered);
1138
            pending.buffered_bytes = 0;
1139
            let mut report = std::mem::take(&mut pending.report);
1140
            for (bty, bbody) in &buffered {
1141
                let br = hash_object(*bty, bbody);
1142
                let e = self.pending_pack_write(&mut pack, &br, *bty, bbody, &mut report)?;
1143
                pending.lookup.insert(br, PendingEntry::Packed(e));
1144
            }
1145
            pending.report = report;
1146
            pending.pack = Some(pack);
1147
        }
1148
        Ok(())
1149
    }
1150
1151
    /// Store many objects at once. Inside a large write batch they are
1152
    /// compressed on every core and appended in order; otherwise each is
1153
    /// stored as [`Store::put`] does.
1154
    pub fn put_many(&self, objects: &[(ObjectType, &[u8])]) -> Result<Vec<ObjectRef>> {
1155
        use rayon::prelude::*;
1156
        let total: usize = objects.iter().map(|(_, b)| b.len()).sum();
1157
        if self.pending.borrow().is_none() || total < SPILL_BYTES {
1158
            return objects.iter().map(|(ty, b)| self.put(*ty, b)).collect();
1159
        }
1160
        for (ty, b) in objects {
1161
            if b.len() > MAX_OBJECT_LEN as usize {
1162
                return Err(StoreError::TooLarge {
1163
                    kind: ty.name(),
1164
                    size: b.len(),
1165
                    limit: MAX_OBJECT_LEN,
1166
                });
1167
            }
1168
        }
1169
        let refs: Vec<ObjectRef> = objects
1170
            .par_iter()
1171
            .map(|(ty, b)| hash_object(*ty, b))
1172
            .collect();
1173
        // What is new: not stored already, not earlier in this call.
1174
        let mut seen: std::collections::HashSet<ObjectRef> = std::collections::HashSet::new();
1175
        let mut todo: Vec<usize> = Vec::new();
1176
        for (i, r) in refs.iter().enumerate() {
1177
            let known = self
1178
                .pending
1179
                .borrow()
1180
                .as_ref()
1181
                .is_some_and(|p| p.lookup.contains_key(r));
1182
            if seen.insert(*r)
1183
                && !known
1184
                && self.find_packed(r).is_none()
1185
                && !self.backend.has(&loose_key(r)).unwrap_or(false)
1186
            {
1187
                todo.push(i);
1188
            }
1189
        }
1190
        let raw = self.nocompress_set()?;
1191
        let packed: Vec<(u8, Vec<u8>)> = todo
1192
            .par_iter()
1193
            .map(|i| {
1194
                let body = objects[*i].1;
1195
                if raw.contains(&refs[*i]) {
1196
                    return (0, body.to_vec());
1197
                }
1198
                match zstd::bulk::compress(body, ZSTD_LEVEL) {
1199
                    Ok(c) if c.len() < body.len() => (FLAG_ZSTD, c),
1200
                    _ => (0, body.to_vec()),
1201
                }
1202
            })
1203
            .collect();
1204
        let mut guard = self.pending.borrow_mut();
1205
        let pending = guard.as_mut().expect("batch open");
1206
        self.ensure_pack(pending)?;
1207
        let mut report = std::mem::take(&mut pending.report);
1208
        let pack = pending.pack.as_mut().unwrap();
1209
        for (i, (flags, stored)) in todo.iter().zip(packed) {
1210
            let (ty, body) = objects[*i];
1211
            let e = write_pack_entry(pack, &refs[*i], ty, body.len(), flags, &stored, &mut report)?;
1212
            pending.lookup.insert(refs[*i], PendingEntry::Packed(e));
1213
        }
1214
        pending.report = report;
1215
        Ok(refs)
1216
    }
1217
1218
    /// Store `body` as an object of type `ty`; idempotent.
1219
    pub fn put(&self, ty: ObjectType, body: &[u8]) -> Result<ObjectRef> {
1220
        // Refuse what the store could not read back (spec §13.2), before
1221
        // anything is written: a pack must never hold an entry its index
1222
        // would reject.
1223
        if body.len() > MAX_OBJECT_LEN as usize {
1224
            return Err(StoreError::TooLarge {
1225
                kind: ty.name(),
1226
                size: body.len(),
1227
                limit: MAX_OBJECT_LEN,
1228
            });
1229
        }
1230
        let r = hash_object(ty, body);
1231
        if self.find_packed(&r).is_some() || self.backend.has(&loose_key(&r)).unwrap_or(false) {
1232
            return Ok(r);
1233
        }
1234
        if self.pending.borrow().is_some() {
1235
            self.put_pending(r, ty, body)?;
1236
            return Ok(r);
1237
        }
1238
        self.put_loose(ty, body)?;
1239
        Ok(r)
1240
    }
1241
1242
    /// Write one loose object, durable when this returns.
1243
    fn put_loose(&self, ty: ObjectType, body: &[u8]) -> Result<ObjectRef> {
1244
        let r = hash_object(ty, body);
1245
        let mut bytes = header(ty, body.len());
1246
        bytes.extend_from_slice(body);
1247
        crate::durable::step("write loose object")?;
1248
        put_new_or_existing(self.backend.as_ref(), &loose_key(&r), &bytes)?;
1249
        Ok(r)
1250
    }
1251
1252
    /// Write several loose objects with as few waits on the disk as the
1253
    /// guarantees allow (a directory store writes them all, then syncs
1254
    /// each directory once). Durable when this returns, as `put_loose`
1255
    /// one at a time would be (spec §13.6).
1256
    fn put_loose_many(&self, objects: &[(ObjectType, &[u8])]) -> Result<()> {
1257
        if objects.len() <= 1 {
1258
            for (ty, body) in objects {
1259
                self.put_loose(*ty, body)?;
1260
            }
1261
            return Ok(());
1262
        }
1263
        let mut seen = std::collections::HashSet::new();
1264
        let items: Vec<(String, Vec<u8>)> = objects
1265
            .iter()
1266
            .filter_map(|(ty, body)| {
1267
                let r = hash_object(*ty, body);
1268
                seen.insert(r).then(|| {
1269
                    let mut bytes = header(*ty, body.len());
1270
                    bytes.extend_from_slice(body);
1271
                    (loose_key(&r), bytes)
1272
                })
1273
            })
1274
            .collect();
1275
        self.backend.put_many_new(&items).map_err(backend_err)
1276
    }
1277
1278
    /// Read and verify an object, loose, packed, or pending in a batch.
1279
    pub fn get(&self, r: &ObjectRef) -> Result<Object> {
1280
        match get_optional(self.backend.as_ref(), &loose_key(r))? {
1281
            Some(bytes) => parse_loose(&bytes, r),
1282
            None => match self.find_packed(r) {
1283
                Some((i, e)) => self.packs.borrow()[i].fetch(self.backend.as_ref(), r, e),
1284
                None => self.pending_get(r).unwrap_or(Err(StoreError::NotFound(*r))),
1285
            },
1286
        }
1287
    }
1288
1289
    /// Many objects at once: loose ones are read and verified in parallel,
1290
    /// then packed ones in parallel, then what is pending in a batch.
1291
    /// Results are in the order of `refs`.
1292
    pub fn get_many(&self, refs: &[ObjectRef]) -> Vec<Result<Object>> {
1293
        use rayon::prelude::*;
1294
        let backend = self.backend.as_ref();
1295
        let mut found: Vec<Option<Result<Object>>> = refs
1296
            .par_iter()
1297
            .map(|r| match get_optional(backend, &loose_key(r)) {
1298
                Ok(Some(bytes)) => Some(parse_loose(&bytes, r)),
1299
                Ok(None) => None,
1300
                Err(e) => Some(Err(e)),
1301
            })
1302
            .collect();
1303
        // Packed ones: look them up in order, then read them in parallel.
1304
        let packs = self.packs.borrow();
1305
        let packed: Vec<(usize, usize, PackEntry)> = found
1306
            .iter()
1307
            .enumerate()
1308
            .filter(|(_, f)| f.is_none())
1309
            .filter_map(|(i, _)| {
1310
                packs
1311
                    .iter()
1312
                    .enumerate()
1313
                    .find_map(|(p, pack)| pack.find(&refs[i]).map(|e| (i, p, e)))
1314
            })
1315
            .collect();
1316
        let indexes: &[PackIndex] = &packs;
1317
        let read: Vec<(usize, Result<Object>)> = packed
1318
            .par_iter()
1319
            .map(|(i, p, e)| (*i, indexes[*p].fetch(backend, &refs[*i], *e)))
1320
            .collect();
1321
        drop(packs);
1322
        for (i, r) in read {
1323
            found[i] = Some(r);
1324
        }
1325
        found
1326
            .into_iter()
1327
            .zip(refs)
1328
            .map(|(f, r)| match f {
1329
                Some(f) => f,
1330
                None => self.get(r),
1331
            })
1332
            .collect()
1333
    }
1334
1335
    pub fn get_typed(&self, r: &ObjectRef, want: ObjectType) -> Result<Vec<u8>> {
1336
        let (ty, body) = self.get(r)?;
1337
        if ty != want {
1338
            return Err(StoreError::WrongType(*r, ty.name(), want.name()));
1339
        }
1340
        Ok(body)
1341
    }
1342
1343
    /// Store a change and the text blobs (and their chunks) its large
1344
    /// inserts are stored as (spec §6.1).
1345
    pub fn put_change(&self, c: &Change) -> Result<ObjectRef> {
1346
        let bytes = c.encode_streaming(|batch| self.put_texts(&batch))?;
1347
        self.put(ObjectType::Change, &bytes)
1348
    }
1349
1350
    /// Store text blobs and their chunks: every chunk at once (compressed
1351
    /// on every core in a large batch), then the blobs.
1352
    pub fn put_texts(&self, texts: &[crate::objects::StoredText]) -> Result<()> {
1353
        let mut chunks: Vec<(ObjectType, &[u8])> = Vec::new();
1354
        for t in texts {
1355
            if !self.has(&t.blob.hash()) {
1356
                chunks.extend(
1357
                    crate::chunk::chunks(&t.content)
1358
                        .into_iter()
1359
                        .map(|c| (ObjectType::Chunk, c)),
1360
                );
1361
            }
1362
        }
1363
        self.put_many(&chunks)?;
1364
        for t in texts {
1365
            self.put(ObjectType::Blob, &t.blob.encode())?;
1366
        }
1367
        Ok(())
1368
    }
1369
1370
    pub fn get_change(&self, r: &ObjectRef) -> Result<Change> {
1371
        Ok(self.get_change_parts(r)?.0)
1372
    }
1373
1374
    /// A change and the objects its stored inserts are made of: each text
1375
    /// blob and its chunks, which travel and are kept with it.
1376
    pub fn get_change_parts(&self, r: &ObjectRef) -> Result<(Change, Vec<ObjectRef>)> {
1377
        let bytes = self.get_typed(r, ObjectType::Change)?;
1378
        let mut parts = Vec::new();
1379
        let mut failed = None;
1380
        let decoded = Change::decode_with(&bytes, &mut |text, count, form| match self
1381
            .read_text(text)
1382
        {
1383
            Ok((blob, content)) => {
1384
                parts.push(*text);
1385
                parts.extend(blob.chunks);
1386
                crate::objects::text_lines(&content, count, form)
1387
            }
1388
            Err(e) => {
1389
                let why = e.to_string();
1390
                failed = Some(e);
1391
                Err(ObjectError::Schema(format!(
1392
                    "text blob {}: {why}",
1393
                    text.short(12)
1394
                )))
1395
            }
1396
        });
1397
        match (decoded, failed) {
1398
            (Ok(c), _) => Ok((c, parts)),
1399
            (Err(_), Some(StoreError::NotFound(t))) => Err(StoreError::Corrupt(
1400
                *r,
1401
                format!("its text blob {} is missing", t.short(12)),
1402
            )),
1403
            (Err(e), _) => Err(StoreError::Corrupt(*r, e.to_string())),
1404
        }
1405
    }
1406
1407
    /// A change with every insert left without its lines (empty
1408
    /// placeholders), and where each one's lines are, in order: for
1409
    /// history-only states, which read text only for the graphs they build
1410
    /// (see [`Change::decode_skeleton`]).
1411
    pub fn get_change_lazy(&self, r: &ObjectRef) -> Result<(Change, Vec<crate::objects::TextRef>)> {
1412
        let bytes = self.get_typed(r, ObjectType::Change)?;
1413
        Change::decode_skeleton(&bytes, *r).map_err(|e| StoreError::Corrupt(*r, e.to_string()))
1414
    }
1415
1416
    /// A change's metadata (id, dependencies, author, clock, message, kind)
1417
    /// without its contents: read from its skeleton, so neither its text
1418
    /// blobs nor its inline lines are read (spec §11).
1419
    ///
1420
    /// Served from the `metas` cache when this store read it before (a
1421
    /// change object can be as large as the tree it adds), as long as the
1422
    /// store still has the change.
1423
    pub fn get_change_meta(&self, r: &ObjectRef) -> Result<crate::state::ChangeMeta> {
1424
        if self.metas.borrow().is_none() {
1425
            *self.metas.borrow_mut() = Some(self.read_metas_cache());
1426
        }
1427
        let cached = self.metas.borrow().as_ref().and_then(|m| m.get(r).cloned());
1428
        if let Some(meta) = cached {
1429
            if self.has(r) {
1430
                #[cfg(test)]
1431
                assert_eq!(
1432
                    meta,
1433
                    Change::decode_meta(&self.get_typed(r, ObjectType::Change)?).unwrap(),
1434
                    "the metadata cache holds a change's metadata"
1435
                );
1436
                return Ok(meta);
1437
            }
1438
        }
1439
        let bytes = self.get_typed(r, ObjectType::Change)?;
1440
        let meta =
1441
            Change::decode_meta(&bytes).map_err(|e| StoreError::Corrupt(*r, e.to_string()))?;
1442
        self.remember_meta(r, &meta);
1443
        Ok(meta)
1444
    }
1445
1446
    /// The metadata cache: records of a change hash, its metadata in the
1447
    /// flat layout, and the first 8 bytes of BLAKE3 over both, each
1448
    /// appended in one write. Derived only: a record that does not check
1449
    /// ends the reading (a torn write), and the cache can be deleted. It
1450
    /// lives in the scratch directory, on this disk.
1451
    fn read_metas_cache(&self) -> crate::fasthash::FastMap<ObjectRef, crate::state::ChangeMeta> {
1452
        let mut out = crate::fasthash::FastMap::default();
1453
        let Ok(bytes) = fs::read(self.scratch.join("metas")) else {
1454
            return out;
1455
        };
1456
        let mut r = crate::flat::Reader::new(&bytes);
1457
        let mut good = 0;
1458
        while !r.at_end() {
1459
            let mut record = || -> std::result::Result<_, ObjectError> {
1460
                let h = r.object()?;
1461
                let body = r.bytes()?;
1462
                let check = r.fixed::<8>()?;
1463
                Ok((h, body, check))
1464
            };
1465
            let Ok((h, body, check)) = record() else {
1466
                break;
1467
            };
1468
            let mut sum = blake3::Hasher::new();
1469
            sum.update(&h.0).update(body);
1470
            if sum.finalize().as_bytes()[..8] != check {
1471
                break;
1472
            }
1473
            match crate::state::ChangeMeta::read_flat(&mut crate::flat::Reader::new(body)) {
1474
                Ok(m) => out.insert(h, m),
1475
                Err(_) => break,
1476
            };
1477
            good += 32 + 4 + body.len() + 8;
1478
        }
1479
        // Cut a bad tail, so records appended later are read.
1480
        if good < bytes.len() {
1481
            let _ = fs::OpenOptions::new()
1482
                .write(true)
1483
                .open(self.scratch.join("metas"))
1484
                .and_then(|f| f.set_len(good as u64));
1485
        }
1486
        out
1487
    }
1488
1489
    /// Add a change's metadata to the cache; quietly nothing when it
1490
    /// cannot be written (it is only a cache).
1491
    fn remember_meta(&self, r: &ObjectRef, meta: &crate::state::ChangeMeta) {
1492
        let mut body = crate::flat::Writer::default();
1493
        meta.write_flat(&mut body);
1494
        let mut w = crate::flat::Writer::default();
1495
        w.object(r);
1496
        w.bytes(&body.0);
1497
        let mut sum = blake3::Hasher::new();
1498
        sum.update(&r.0).update(&body.0);
1499
        w.fixed(&sum.finalize().as_bytes()[..8]);
1500
        let _ = fs::OpenOptions::new()
1501
            .create(true)
1502
            .append(true)
1503
            .open(self.scratch.join("metas"))
1504
            .and_then(|mut f| f.write_all(&w.0));
1505
        if let Some(m) = self.metas.borrow_mut().as_mut() {
1506
            m.insert(*r, meta.clone());
1507
        }
1508
    }
1509
1510
    fn read_text(&self, r: &ObjectRef) -> Result<(Blob, Vec<u8>)> {
1511
        let blob = Blob::decode(&self.get_typed(r, ObjectType::Blob)?)?;
1512
        let mut content = Vec::with_capacity(blob.length as usize);
1513
        for c in &blob.chunks {
1514
            content.extend(self.get_typed(c, ObjectType::Chunk)?);
1515
        }
1516
        Ok((blob, content))
1517
    }
1518
1519
    pub fn put_chunk(&self, bytes: &[u8]) -> Result<ObjectRef> {
1520
        self.put(ObjectType::Chunk, bytes)
1521
    }
1522
1523
    /// Store a chunk that packs will keep uncompressed (`nocompress`, spec §13.3).
1524
    pub fn put_chunk_nocompress(&self, bytes: &[u8]) -> Result<ObjectRef> {
1525
        let r = hash_object(ObjectType::Chunk, bytes);
1526
        put_new_or_existing(
1527
            self.backend.as_ref(),
1528
            &format!("nocompress/{}", r.to_hex()),
1529
            b"",
1530
        )?;
1531
        self.put(ObjectType::Chunk, bytes)
1532
    }
1533
1534
    fn is_nocompress(&self, r: &ObjectRef) -> bool {
1535
        self.backend
1536
            .has(&format!("nocompress/{}", r.to_hex()))
1537
            .unwrap_or(false)
1538
    }
1539
1540
    /// Every chunk marked to be kept raw.
1541
    fn nocompress_set(&self) -> Result<std::collections::HashSet<ObjectRef>> {
1542
        Ok(self
1543
            .backend
1544
            .list("nocompress/")
1545
            .map_err(backend_err)?
1546
            .into_iter()
1547
            .filter_map(|e| ObjectRef::from_hex(e.key.trim_start_matches("nocompress/")))
1548
            .collect())
1549
    }
1550
1551
    pub fn put_state(&self, st: &StateObject) -> Result<ObjectRef> {
1552
        self.put(ObjectType::State, &st.encode())
1553
    }
1554
1555
    pub fn get_state(&self, r: &ObjectRef) -> Result<StateObject> {
1556
        Ok(StateObject::decode(&self.get_typed(r, ObjectType::State)?)?)
1557
    }
1558
1559
    pub fn put_attest(&self, a: &Attest) -> Result<ObjectRef> {
1560
        self.put(ObjectType::Attest, &a.encode())
1561
    }
1562
1563
    pub fn get_attest(&self, r: &ObjectRef) -> Result<Attest> {
1564
        Ok(Attest::decode(&self.get_typed(r, ObjectType::Attest)?)?)
1565
    }
1566
1567
    pub fn put_receipt(&self, r: &Receipt) -> Result<ObjectRef> {
1568
        self.put(ObjectType::Receipt, &r.encode())
1569
    }
1570
1571
    pub fn get_receipt(&self, r: &ObjectRef) -> Result<Receipt> {
1572
        Ok(Receipt::decode(&self.get_typed(r, ObjectType::Receipt)?)?)
1573
    }
1574
1575
    /// Record `value` under `key` in `index`: one write-once entry, so two
1576
    /// writers of a shared store never lose each other's.
1577
    fn index_add(&self, index: &str, key: &ObjectRef, value: &ObjectRef) -> Result<()> {
1578
        let entry = format!("{}{}", fanout_prefix(index, key), value.to_hex());
1579
        put_new_or_existing(self.backend.as_ref(), &entry, b"")
1580
    }
1581
1582
    /// The values recorded under `key` in `index`, with those an older
1583
    /// store kept as one list in `legacy`, sorted.
1584
    fn index_get(&self, index: &str, legacy: &str, key: &ObjectRef) -> Result<Vec<ObjectRef>> {
1585
        let mut values: Vec<ObjectRef> = self
1586
            .backend
1587
            .list(&fanout_prefix(index, key))
1588
            .map_err(backend_err)?
1589
            .into_iter()
1590
            .filter_map(|e| e.key.rsplit('/').next().and_then(ObjectRef::from_hex))
1591
            .collect();
1592
        if let Some(bytes) = get_optional(self.backend.as_ref(), &legacy_key(legacy, key))? {
1593
            values.extend(
1594
                String::from_utf8_lossy(&bytes)
1595
                    .lines()
1596
                    .filter_map(ObjectRef::from_hex),
1597
            );
1598
        }
1599
        values.sort();
1600
        values.dedup();
1601
        Ok(values)
1602
    }
1603
1604
    /// Record that seal attestation `attest` covers `change`.
1605
    pub fn index_seal(&self, change: &ObjectRef, attest: &ObjectRef) -> Result<()> {
1606
        self.index_add("seal", change, attest)
1607
    }
1608
1609
    /// Seal attestations known to cover `change`.
1610
    pub fn seals_for(&self, change: &ObjectRef) -> Result<Vec<ObjectRef>> {
1611
        self.index_get("seal", "seals", change)
1612
    }
1613
1614
    /// Record receipt attestation `attest` for `state` (spec §14.6).
1615
    pub fn index_receipt(&self, state: &ObjectRef, attest: &ObjectRef) -> Result<()> {
1616
        self.index_add("receipt", state, attest)
1617
    }
1618
1619
    /// Receipt attestations recorded for `state`.
1620
    pub fn receipts_for(&self, state: &ObjectRef) -> Result<Vec<ObjectRef>> {
1621
        self.index_get("receipt", "receipts", state)
1622
    }
1623
1624
    /// Every state with a receipt, for garbage collection.
1625
    pub fn receipt_states(&self) -> Result<Vec<ObjectRef>> {
1626
        let mut out: Vec<ObjectRef> = Vec::new();
1627
        for e in self.backend.list("receipt/").map_err(backend_err)? {
1628
            // receipt/<hh>/<rest>/<attest>
1629
            let mut parts = e.key.splitn(4, '/');
1630
            let (Some(_), Some(hh), Some(rest), Some(_)) =
1631
                (parts.next(), parts.next(), parts.next(), parts.next())
1632
            else {
1633
                continue;
1634
            };
1635
            out.extend(ObjectRef::from_hex(&format!("{hh}{rest}")));
1636
        }
1637
        for e in self.backend.list("receipts/").map_err(backend_err)? {
1638
            let mut parts = e.key.splitn(3, '/');
1639
            let (Some(_), Some(hh), Some(rest)) = (parts.next(), parts.next(), parts.next()) else {
1640
                continue;
1641
            };
1642
            out.extend(ObjectRef::from_hex(&format!("{hh}{rest}")));
1643
        }
1644
        out.sort();
1645
        out.dedup();
1646
        Ok(out)
1647
    }
1648
1649
    pub fn put_identity(&self, id: &Identity) -> Result<ObjectRef> {
1650
        self.put(ObjectType::Identity, &id.encode())
1651
    }
1652
1653
    pub fn get_identity(&self, r: &ObjectRef) -> Result<Identity> {
1654
        Ok(Identity::decode(&self.get_typed(r, ObjectType::Identity)?)?)
1655
    }
1656
1657
    /// Signatures stored alongside object `r` (spec §5.4), one per signing
1658
    /// key, sorted by key. Empty if none.
1659
    pub fn signatures(&self, r: &ObjectRef) -> Result<Vec<Signature>> {
1660
        let mut sigs: Vec<Signature> = Vec::new();
1661
        for e in self
1662
            .backend
1663
            .list(&fanout_prefix("sig", r))
1664
            .map_err(backend_err)?
1665
        {
1666
            let bytes = self.backend.get(&e.key).map_err(backend_err)?;
1667
            sigs.extend(Signature::decode_list(&bytes)?);
1668
        }
1669
        // An older store's one list per object; a signer kept there and
1670
        // here counts once, as written here.
1671
        if let Some(bytes) = get_optional(self.backend.as_ref(), &legacy_key("sigs", r))? {
1672
            for sig in Signature::decode_list(&bytes)? {
1673
                if !sigs.iter().any(|s| s.key == sig.key) {
1674
                    sigs.push(sig);
1675
                }
1676
            }
1677
        }
1678
        sigs.sort_by_key(|s| s.key);
1679
        sigs.dedup_by_key(|s| s.key);
1680
        Ok(sigs)
1681
    }
1682
1683
    /// Attach a signature to object `r`, replacing any earlier one by the
1684
    /// same key: one entry per signer, so the latest by a key is the one
1685
    /// kept, and two signers never touch each other's.
1686
    pub fn put_signature(&self, r: &ObjectRef, sig: &Signature) -> Result<()> {
1687
        let key = format!("{}{}", fanout_prefix("sig", r), sig.key.to_hex());
1688
        let bytes = Signature::encode_list(std::slice::from_ref(sig));
1689
        if get_optional(self.backend.as_ref(), &key)?.as_deref() == Some(bytes.as_slice()) {
1690
            return Ok(());
1691
        }
1692
        delete(self.backend.as_ref(), &key)?;
1693
        put_new_or_existing(self.backend.as_ref(), &key, &bytes)
1694
    }
1695
1696
    /// Every object reference in the store, loose and packed (slow; for gc and tests).
1697
    pub fn list(&self) -> io::Result<Vec<ObjectRef>> {
1698
        let mut out: Vec<ObjectRef> = self
1699
            .loose_objects()
1700
            .map_err(|e| io::Error::other(e.to_string()))?
1701
            .into_iter()
1702
            .map(|(r, _)| r)
1703
            .collect();
1704
        for p in self.packs.borrow().iter() {
1705
            out.extend(p.refs.iter().copied());
1706
        }
1707
        out.sort();
1708
        out.dedup();
1709
        Ok(out)
1710
    }
1711
}
1712
1713
/// A loose object's bytes, verified against `r`.
1714
fn parse_loose(data: &[u8], r: &ObjectRef) -> Result<Object> {
1715
    let nul = data
1716
        .iter()
1717
        .position(|&b| b == 0)
1718
        .ok_or_else(|| StoreError::Corrupt(*r, "no header".into()))?;
1719
    let head = std::str::from_utf8(&data[..nul])
1720
        .map_err(|_| StoreError::Corrupt(*r, "header not UTF-8".into()))?;
1721
    let mut parts = head.split(' ');
1722
    let (Some("oxy1"), Some(ty), Some(len), None) =
1723
        (parts.next(), parts.next(), parts.next(), parts.next())
1724
    else {
1725
        return Err(StoreError::Corrupt(*r, format!("bad header {head:?}")));
1726
    };
1727
    let ty = ObjectType::from_name(ty)
1728
        .ok_or_else(|| StoreError::Corrupt(*r, format!("unknown type {ty}")))?;
1729
    let len: usize = len
1730
        .parse()
1731
        .map_err(|_| StoreError::Corrupt(*r, "bad length".into()))?;
1732
    let body = &data[nul + 1..];
1733
    if body.len() != len {
1734
        return Err(StoreError::Corrupt(
1735
            *r,
1736
            format!("length {} != header {len}", body.len()),
1737
        ));
1738
    }
1739
    if hash_object(ty, body) != *r {
1740
        return Err(StoreError::Corrupt(*r, "hash mismatch".into()));
1741
    }
1742
    Ok((ty, body.to_vec()))
1743
}
1744
1745
/// Whether the objects are files that a test may tamper with: not under
1746
/// `OXY_STORE_BACKEND=memory`.
1747
#[cfg(test)]
1748
fn files_on_disk() -> bool {
1749
    std::env::var_os("OXY_STORE_BACKEND").is_none()
1750
}
1751
1752
#[cfg(test)]
1753
mod tests {
1754
    use super::*;
1755
1756
    /// The store under test twice: in a directory, and on a store in
1757
    /// memory with a scratch directory, as over a bucket.
1758
    fn each_store(dir: &Path, f: impl Fn(&str, Store)) {
1759
        f("directory", Store::open(dir.join("objects")).unwrap());
1760
        f(
1761
            "memory",
1762
            Store::open_on(Arc::new(MemoryStore::new()), dir.join("scratch")).unwrap(),
1763
        );
1764
    }
1765
1766
    #[test]
1767
    fn put_get_verify() {
1768
        if !super::files_on_disk() {
1769
            return;
1770
        }
1771
        let dir = tempfile::tempdir().unwrap();
1772
        let s = Store::open(dir.path().join("objects")).unwrap();
1773
        let r = s.put(ObjectType::Chunk, b"hello").unwrap();
1774
        assert!(s.has(&r));
1775
        assert_eq!(s.get(&r).unwrap(), (ObjectType::Chunk, b"hello".to_vec()));
1776
        assert_eq!(s.put(ObjectType::Chunk, b"hello").unwrap(), r);
1777
        assert_eq!(s.list().unwrap(), vec![r]);
1778
        assert!(matches!(
1779
            s.get_typed(&r, ObjectType::Blob),
1780
            Err(StoreError::WrongType(..))
1781
        ));
1782
        assert!(matches!(
1783
            s.get(&ObjectRef([9; 32])),
1784
            Err(StoreError::NotFound(_))
1785
        ));
1786
1787
        // Tamper: flip a byte, read must fail.
1788
        let path = s.path_for(&r);
1789
        let mut data = fs::read(&path).unwrap();
1790
        let last = data.len() - 1;
1791
        data[last] ^= 1;
1792
        fs::write(&path, data).unwrap();
1793
        assert!(matches!(s.get(&r), Err(StoreError::Corrupt(..))));
1794
    }
1795
1796
    #[test]
1797
    fn packing_keeps_every_object_readable() {
1798
        if !super::files_on_disk() {
1799
            return;
1800
        }
1801
        let dir = tempfile::tempdir().unwrap();
1802
        let s = Store::open(dir.path()).unwrap();
1803
        let mut refs = Vec::new();
1804
        for i in 0..300u32 {
1805
            let body = format!("object {i} ").repeat(1 + (i % 7) as usize);
1806
            refs.push((s.put(ObjectType::Chunk, body.as_bytes()).unwrap(), body));
1807
        }
1808
        let c = crate::objects::tests::sample_change();
1809
        let cr = s.put_change(&c).unwrap();
1810
        assert_eq!(s.loose_count().unwrap(), 301);
1811
        let report = s.pack_loose().unwrap();
1812
        assert_eq!(report.objects, 301);
1813
        assert!(report.packed_bytes < report.raw_bytes, "{report:?}");
1814
        assert_eq!(s.loose_count().unwrap(), 0);
1815
        assert_eq!(s.pack_count(), 1);
1816
        for (r, body) in &refs {
1817
            assert!(s.has(r));
1818
            assert_eq!(
1819
                s.get(r).unwrap(),
1820
                (ObjectType::Chunk, body.as_bytes().to_vec())
1821
            );
1822
        }
1823
        assert_eq!(s.get_change(&cr).unwrap(), c);
1824
        assert_eq!(s.list().unwrap().len(), 301);
1825
        // Re-putting a packed object is a no-op; new objects go loose and a
1826
        // second pack coexists with the first.
1827
        assert_eq!(
1828
            s.put(ObjectType::Chunk, refs[0].1.as_bytes()).unwrap(),
1829
            refs[0].0
1830
        );
1831
        assert_eq!(s.loose_count().unwrap(), 0);
1832
        let extra = s.put(ObjectType::Chunk, b"after packing").unwrap();
1833
        s.pack_loose().unwrap();
1834
        assert_eq!(s.pack_count(), 2);
1835
        assert_eq!(s.get(&extra).unwrap().1, b"after packing");
1836
        // A reopened store sees the packs.
1837
        let s2 = Store::open(dir.path()).unwrap();
1838
        assert_eq!(s2.pack_count(), 2);
1839
        assert_eq!(s2.get(&refs[5].0).unwrap().1, refs[5].1.as_bytes());
1840
        assert!(matches!(
1841
            s2.get(&ObjectRef([9; 32])),
1842
            Err(StoreError::NotFound(_))
1843
        ));
1844
        // Corrupting an object's body inside the pack is detected on read.
1845
        let target = refs[5].0;
1846
        let (pack_path, offset) = {
1847
            let packs = s2.packs.borrow();
1848
            let (i, e) = s2.find_packed(&target).unwrap();
1849
            (dir.path().join(&packs[i].key), e.offset as usize)
1850
        };
1851
        let mut data = fs::read(&pack_path).unwrap();
1852
        data[offset] ^= 0xff;
1853
        fs::write(&pack_path, data).unwrap();
1854
        let s3 = Store::open(dir.path()).unwrap();
1855
        assert!(matches!(s3.get(&target), Err(StoreError::Corrupt(..))));
1856
        assert_eq!(
1857
            s3.get(&refs[6].0).unwrap().1,
1858
            refs[6].1.as_bytes(),
1859
            "other objects are unaffected"
1860
        );
1861
    }
1862
1863
    #[test]
1864
    fn a_full_repack_trains_a_dictionary_and_reads_back() {
1865
        if !super::files_on_disk() {
1866
            return;
1867
        }
1868
        let dir = tempfile::tempdir().unwrap();
1869
        let s = Store::open(dir.path()).unwrap();
1870
        // Many small, alike files: what a dictionary is for.
1871
        let bodies: Vec<Vec<u8>> = (0..1500)
1872
            .map(|i| {
1873
                format!(
1874
                    "// SPDX-License-Identifier: GPL-2.0\n#include <linux/module.h>\n\
1875
                     static int probe_{i}(struct device *dev)\n{{\n\treturn {i};\n}}\n"
1876
                )
1877
                .into_bytes()
1878
            })
1879
            .collect();
1880
        let refs: Vec<ObjectRef> = bodies
1881
            .iter()
1882
            .map(|b| s.put(ObjectType::Chunk, b).unwrap())
1883
            .collect();
1884
        s.repack_all(REPACK_ZSTD_LEVEL).unwrap();
1885
        let dicts = fs::read_dir(dir.path())
1886
            .unwrap()
1887
            .flatten()
1888
            .filter(|e| e.path().extension().is_some_and(|x| x == "dict"))
1889
            .count();
1890
        assert_eq!(dicts, 1, "the pack has a dictionary");
1891
        let with_dict = refs
1892
            .iter()
1893
            .filter(|r| s.find_packed(r).unwrap().1.flags & FLAG_DICT != 0)
1894
            .count();
1895
        assert!(with_dict > 1000, "most use it: {with_dict}");
1896
        let again = Store::open(dir.path()).unwrap();
1897
        for (r, b) in refs.iter().zip(&bodies) {
1898
            assert_eq!(&again.get(r).unwrap().1, b);
1899
        }
1900
        let packs = |dir: &Path| {
1901
            let mut v: Vec<String> = fs::read_dir(dir)
1902
                .unwrap()
1903
                .flatten()
1904
                .map(|e| e.file_name().to_string_lossy().into_owned())
1905
                .filter(|n| n.starts_with("pack-"))
1906
                .collect();
1907
            v.sort();
1908
            v
1909
        };
1910
        // With nothing new, a repack leaves that pack as it is: it would
1911
        // only write the same again.
1912
        let before = packs(dir.path());
1913
        let (report, merged) = again.repack_all(REPACK_ZSTD_LEVEL).unwrap();
1914
        assert_eq!((report.objects, merged), (0, 0));
1915
        assert_eq!(packs(dir.path()), before);
1916
        // One new object: a repack replaces the pack and its dictionary.
1917
        let extra = again.put(ObjectType::Chunk, b"one more\n").unwrap();
1918
        again.repack_all(REPACK_ZSTD_LEVEL).unwrap();
1919
        let files = packs(dir.path());
1920
        assert_eq!(files.len(), 3, "one pack, index and dictionary: {files:?}");
1921
        assert_ne!(files, before);
1922
        assert_eq!(&again.get(&refs[7]).unwrap().1, &bodies[7]);
1923
        assert_eq!(again.get(&extra).unwrap().1, b"one more\n");
1924
    }
1925
1926
    #[test]
1927
    fn nocompress_chunks_pack_raw() {
1928
        let dir = tempfile::tempdir().unwrap();
1929
        let s = Store::open(dir.path()).unwrap();
1930
        let body = vec![b'a'; 10_000];
1931
        let raw = s.put_chunk_nocompress(&body).unwrap();
1932
        let compressible = s.put(ObjectType::Chunk, &vec![b'b'; 10_000]).unwrap();
1933
        s.pack_loose().unwrap();
1934
        let packs = s.packs.borrow();
1935
        let (i, e) = s.find_packed(&raw).unwrap();
1936
        assert_eq!((e.flags, e.stored_len as usize), (0, 10_000));
1937
        let (_, c) = s.find_packed(&compressible).unwrap();
1938
        assert_eq!(c.flags, FLAG_ZSTD);
1939
        assert!(c.stored_len < 10_000);
1940
        assert_eq!(packs[i].fetch(s.backend.as_ref(), &raw, e).unwrap().1, body);
1941
    }
1942
1943
    #[test]
1944
    fn many_packs_merge_into_one() {
1945
        let dir = tempfile::tempdir().unwrap();
1946
        each_store(dir.path(), |which, s| {
1947
            let mut refs = Vec::new();
1948
            for i in 0..(MAX_PACKS + 2) {
1949
                refs.push(
1950
                    s.put(ObjectType::Chunk, format!("pack {i}").as_bytes())
1951
                        .unwrap(),
1952
                );
1953
                s.pack_loose().unwrap();
1954
            }
1955
            assert_eq!(s.pack_count(), MAX_PACKS + 2, "{which}");
1956
            assert_eq!(s.merge_packs().unwrap(), MAX_PACKS + 2);
1957
            assert_eq!(s.pack_count(), 1);
1958
            assert_eq!(s.merge_packs().unwrap(), 0);
1959
            for (i, r) in refs.iter().enumerate() {
1960
                assert_eq!(s.get(r).unwrap().1, format!("pack {i}").as_bytes());
1961
            }
1962
            let again = Store::open_on(s.backend().clone(), s.dir()).unwrap();
1963
            assert_eq!(again.pack_count(), 1, "{which}: reopened");
1964
        });
1965
    }
1966
1967
    #[test]
1968
    fn prune_removes_unreachable_loose_and_packed_objects() {
1969
        use std::collections::HashSet;
1970
        let dir = tempfile::tempdir().unwrap();
1971
        each_store(dir.path(), |which, s| {
1972
            let keep_a = s.put(ObjectType::Chunk, b"keep a").unwrap();
1973
            let drop_a = s.put(ObjectType::Chunk, b"drop a").unwrap();
1974
            s.pack_loose().unwrap();
1975
            let keep_b = s.put(ObjectType::Chunk, b"keep b").unwrap();
1976
            let drop_b = s.put(ObjectType::Chunk, b"drop b").unwrap();
1977
            let sk = crate::identity::SecretKey {
1978
                ed_seed: [1; 32],
1979
                ml_seed: [2; 32],
1980
            };
1981
            let id = sk.identity("a", "b", 0);
1982
            let key = s.put_identity(&id).unwrap();
1983
            s.put_signature(
1984
                &drop_b,
1985
                &sk.sign(crate::identity::Domain::Change, &key, &drop_b),
1986
            )
1987
            .unwrap();
1988
            s.index_seal(&drop_a, &ObjectRef([3; 32])).unwrap();
1989
            let keep: HashSet<ObjectRef> = [keep_a, keep_b, key].into_iter().collect();
1990
            // Everything is too young under a grace period.
1991
            let r = s
1992
                .prune(&keep, std::time::Duration::from_secs(3600))
1993
                .unwrap();
1994
            assert_eq!((r.objects, r.deferred), (0, 2), "{which}");
1995
            let r = s.prune(&keep, std::time::Duration::ZERO).unwrap();
1996
            assert_eq!(r.objects, 2, "{which}: {r:?}");
1997
            assert!(s.has(&keep_a) && s.has(&keep_b) && s.has(&key));
1998
            assert!(!s.has(&drop_a) && !s.has(&drop_b));
1999
            assert!(s.signatures(&drop_b).unwrap().is_empty());
2000
            assert!(s.seals_for(&drop_a).unwrap().is_empty());
2001
            assert_eq!(s.pack_count(), 1);
2002
            assert_eq!(s.get(&keep_a).unwrap().1, b"keep a");
2003
            assert_eq!(s.list().unwrap().len(), 3);
2004
        });
2005
    }
2006
2007
    #[test]
2008
    fn signatures_are_stored_beside_objects() {
2009
        use crate::identity::{Domain, SecretKey};
2010
        let dir = tempfile::tempdir().unwrap();
2011
        each_store(dir.path(), |which, s| {
2012
            let r = s.put(ObjectType::Chunk, b"x").unwrap();
2013
            assert!(s.signatures(&r).unwrap().is_empty());
2014
            let sk = SecretKey {
2015
                ed_seed: [1; 32],
2016
                ml_seed: [2; 32],
2017
            };
2018
            let id = sk.identity("a", "b", 0);
2019
            let key = s.put_identity(&id).unwrap();
2020
            assert_eq!(s.get_identity(&key).unwrap(), id);
2021
            let sig = sk.sign(Domain::Change, &key, &r);
2022
            s.put_signature(&r, &sig).unwrap();
2023
            s.put_signature(&r, &sig).unwrap();
2024
            assert_eq!(s.signatures(&r).unwrap(), vec![sig.clone()], "{which}");
2025
            // A second signer is kept beside the first, sorted by key.
2026
            let sk2 = SecretKey {
2027
                ed_seed: [3; 32],
2028
                ml_seed: [4; 32],
2029
            };
2030
            let key2 = s.put_identity(&sk2.identity("c", "d", 0)).unwrap();
2031
            let sig2 = sk2.sign(Domain::Change, &key2, &r);
2032
            s.put_signature(&r, &sig2).unwrap();
2033
            let mut both = vec![sig.clone(), sig2.clone()];
2034
            both.sort_by_key(|s| s.key);
2035
            assert_eq!(s.signatures(&r).unwrap(), both);
2036
            // The object itself is untouched by its signatures.
2037
            assert_eq!(s.get(&r).unwrap().1, b"x");
2038
            // Seal and receipt entries, and the states with receipts.
2039
            s.index_seal(&r, &ObjectRef([5; 32])).unwrap();
2040
            s.index_seal(&r, &ObjectRef([4; 32])).unwrap();
2041
            s.index_seal(&r, &ObjectRef([5; 32])).unwrap();
2042
            assert_eq!(
2043
                s.seals_for(&r).unwrap(),
2044
                vec![ObjectRef([4; 32]), ObjectRef([5; 32])]
2045
            );
2046
            let st = ObjectRef([6; 32]);
2047
            s.index_receipt(&st, &ObjectRef([7; 32])).unwrap();
2048
            assert_eq!(s.receipts_for(&st).unwrap(), vec![ObjectRef([7; 32])]);
2049
            assert_eq!(s.receipt_states().unwrap(), vec![st]);
2050
        });
2051
    }
2052
2053
    /// A store written before signatures, seals and receipts were one
2054
    /// entry each (`sigs/`, `seals/`, `receipts/` lists) still reads, and
2055
    /// what is written now sits beside what was there.
2056
    #[test]
2057
    fn an_older_store_s_sidecar_lists_are_still_read() {
2058
        if !super::files_on_disk() {
2059
            return;
2060
        }
2061
        use crate::identity::{Domain, SecretKey};
2062
        let dir = tempfile::tempdir().unwrap();
2063
        let s = Store::open(dir.path()).unwrap();
2064
        let r = s.put(ObjectType::Chunk, b"old").unwrap();
2065
        let h = r.to_hex();
2066
        let sk = SecretKey {
2067
            ed_seed: [1; 32],
2068
            ml_seed: [2; 32],
2069
        };
2070
        let key = s.put_identity(&sk.identity("a", "b", 0)).unwrap();
2071
        let sig = sk.sign(Domain::Change, &key, &r);
2072
        let legacy = dir.path().join("sigs").join(&h[..2]);
2073
        fs::create_dir_all(&legacy).unwrap();
2074
        fs::write(
2075
            legacy.join(&h[2..]),
2076
            Signature::encode_list(std::slice::from_ref(&sig)),
2077
        )
2078
        .unwrap();
2079
        let seals = dir.path().join("seals").join(&h[..2]);
2080
        fs::create_dir_all(&seals).unwrap();
2081
        fs::write(
2082
            seals.join(&h[2..]),
2083
            format!("{}\n", ObjectRef([9; 32]).to_hex()),
2084
        )
2085
        .unwrap();
2086
        let receipts = dir.path().join("receipts").join(&h[..2]);
2087
        fs::create_dir_all(&receipts).unwrap();
2088
        fs::write(
2089
            receipts.join(&h[2..]),
2090
            format!("{}\n", ObjectRef([8; 32]).to_hex()),
2091
        )
2092
        .unwrap();
2093
2094
        assert_eq!(s.signatures(&r).unwrap(), vec![sig.clone()]);
2095
        assert_eq!(s.seals_for(&r).unwrap(), vec![ObjectRef([9; 32])]);
2096
        assert_eq!(s.receipts_for(&r).unwrap(), vec![ObjectRef([8; 32])]);
2097
        assert_eq!(s.receipt_states().unwrap(), vec![r]);
2098
        // New entries join the old ones; the same signer is not doubled.
2099
        s.put_signature(&r, &sig).unwrap();
2100
        s.index_seal(&r, &ObjectRef([1; 32])).unwrap();
2101
        assert_eq!(s.signatures(&r).unwrap().len(), 1);
2102
        assert_eq!(
2103
            s.seals_for(&r).unwrap(),
2104
            vec![ObjectRef([1; 32]), ObjectRef([9; 32])]
2105
        );
2106
        // Pruning the object takes both layouts with it.
2107
        let r2 = s.put(ObjectType::Chunk, b"kept").unwrap();
2108
        let keep = [r2, key].into_iter().collect();
2109
        s.prune(&keep, std::time::Duration::ZERO).unwrap();
2110
        assert!(s.signatures(&r).unwrap().is_empty());
2111
        assert!(s.seals_for(&r).unwrap().is_empty());
2112
        assert!(s.receipt_states().unwrap().is_empty());
2113
    }
2114
2115
    #[test]
2116
    fn change_round_trip_through_store() {
2117
        let dir = tempfile::tempdir().unwrap();
2118
        each_store(dir.path(), |which, s| {
2119
            let c = crate::objects::tests::sample_change();
2120
            let r = s.put_change(&c).unwrap();
2121
            assert_eq!(r, c.hash(), "{which}");
2122
            assert_eq!(s.get_change(&r).unwrap(), c);
2123
            assert_eq!(s.get_change_meta(&r).unwrap().message, c.message);
2124
        });
2125
    }
2126
2127
    fn xorshift(state: &mut u64) -> u64 {
2128
        *state ^= *state << 13;
2129
        *state ^= *state >> 7;
2130
        *state ^= *state << 17;
2131
        *state
2132
    }
2133
2134
    /// Random corruption of pack and index files never panics: reads fail
2135
    /// with an error or the store refuses to open, and untouched objects
2136
    /// stay readable when the index survives.
2137
    #[test]
2138
    fn corrupted_packs_and_indexes_fail_cleanly() {
2139
        if !super::files_on_disk() {
2140
            return;
2141
        }
2142
        let dir = tempfile::tempdir().unwrap();
2143
        let objects = dir.path().join("objects");
2144
        let s = Store::open(&objects).unwrap();
2145
        let mut refs = Vec::new();
2146
        let mut seed = 0x9e3779b97f4a7c15u64;
2147
        for i in 0..40u32 {
2148
            let len = (xorshift(&mut seed) % 5000) as usize;
2149
            let mut body = vec![0u8; len];
2150
            for b in body.iter_mut() {
2151
                *b = if i % 2 == 0 {
2152
                    (xorshift(&mut seed) & 0xff) as u8
2153
                } else {
2154
                    b'a' + (i % 26) as u8
2155
                };
2156
            }
2157
            refs.push(s.put(ObjectType::Chunk, &body).unwrap());
2158
        }
2159
        s.pack_loose().unwrap();
2160
        let pack = fs::read_dir(&objects)
2161
            .unwrap()
2162
            .filter_map(|e| e.ok().map(|e| e.path()))
2163
            .find(|p| p.extension().is_some_and(|x| x == "pack"))
2164
            .unwrap();
2165
        let idx = pack.with_extension("idx");
2166
        let pristine_pack = fs::read(&pack).unwrap();
2167
        let pristine_idx = fs::read(&idx).unwrap();
2168
2169
        for round in 0..300u32 {
2170
            let (path, pristine) = if round % 2 == 0 {
2171
                (&pack, &pristine_pack)
2172
            } else {
2173
                (&idx, &pristine_idx)
2174
            };
2175
            let mut data = pristine.clone();
2176
            match xorshift(&mut seed) % 4 {
2177
                0 => {
2178
                    let at = (xorshift(&mut seed) as usize) % data.len();
2179
                    data[at] ^= 1 << (xorshift(&mut seed) % 8);
2180
                }
2181
                1 => {
2182
                    let at = (xorshift(&mut seed) as usize) % data.len();
2183
                    data[at] = (xorshift(&mut seed) & 0xff) as u8;
2184
                }
2185
                2 => {
2186
                    let keep = (xorshift(&mut seed) as usize) % data.len();
2187
                    data.truncate(keep);
2188
                }
2189
                _ => {
2190
                    let at = (xorshift(&mut seed) as usize) % data.len();
2191
                    let n = ((xorshift(&mut seed) % 8) + 1) as usize;
2192
                    for k in 0..n.min(data.len() - at) {
2193
                        data[at + k] = 0xff;
2194
                    }
2195
                }
2196
            }
2197
            fs::write(path, &data).unwrap();
2198
            // Opening may refuse a broken index; a store that opens must
2199
            // either return each object intact or report it corrupt/missing.
2200
            if let Ok(s2) = Store::open(&objects) {
2201
                for r in &refs {
2202
                    match s2.get(r) {
2203
                        Ok((ty, body)) => assert_eq!(
2204
                            hash_object(ty, &body),
2205
                            *r,
2206
                            "a returned object always matches its reference"
2207
                        ),
2208
                        Err(StoreError::Corrupt(..))
2209
                        | Err(StoreError::NotFound(_))
2210
                        | Err(StoreError::Io(_)) => {}
2211
                        Err(e) => panic!("unexpected error {e}"),
2212
                    }
2213
                }
2214
            }
2215
            fs::write(path, pristine).unwrap();
2216
        }
2217
        // Restored files read back in full.
2218
        let s3 = Store::open(&objects).unwrap();
2219
        for r in &refs {
2220
            let (ty, body) = s3.get(r).unwrap();
2221
            assert_eq!(hash_object(ty, &body), *r);
2222
        }
2223
    }
2224
2225
    /// A small batch becomes loose objects; a large one becomes a single
2226
    /// pack. Objects are readable while pending, and batches nest.
2227
    #[test]
2228
    fn batches_write_loose_or_one_pack() {
2229
        let dir = tempfile::tempdir().unwrap();
2230
        each_store(dir.path(), |which, s| {
2231
            let outer = s.begin_batch().unwrap();
2232
            let a = s.put(ObjectType::Chunk, b"small a").unwrap();
2233
            {
2234
                let inner = s.begin_batch().unwrap();
2235
                let b = s.put(ObjectType::Chunk, b"small b").unwrap();
2236
                assert!(s.has(&b));
2237
                assert_eq!(s.get(&b).unwrap().1, b"small b");
2238
                inner.finish().unwrap();
2239
                assert_eq!(
2240
                    s.loose_count().unwrap(),
2241
                    0,
2242
                    "{which}: the inner batch defers to the outer one"
2243
                );
2244
            }
2245
            assert_eq!(s.get(&a).unwrap().1, b"small a");
2246
            assert_eq!(
2247
                s.put(ObjectType::Chunk, b"small a").unwrap(),
2248
                a,
2249
                "idempotent while pending"
2250
            );
2251
            outer.finish().unwrap();
2252
            assert_eq!(s.loose_count().unwrap(), 2);
2253
            assert_eq!(s.pack_count(), 0);
2254
            assert_eq!(s.get(&a).unwrap().1, b"small a");
2255
2256
            // Large: spills into one pack, readable during and after.
2257
            let big = s.begin_batch().unwrap();
2258
            let mut refs = Vec::new();
2259
            let mut seed = 7u64;
2260
            for i in 0..300u32 {
2261
                let mut body = vec![b'z'; 40_000];
2262
                if i % 3 == 0 {
2263
                    for b in body.iter_mut() {
2264
                        *b = (xorshift(&mut seed) & 0xff) as u8;
2265
                    }
2266
                }
2267
                body[..4].copy_from_slice(&i.to_le_bytes());
2268
                let r = if i % 5 == 0 {
2269
                    s.put_chunk_nocompress(&body).unwrap()
2270
                } else {
2271
                    s.put(ObjectType::Chunk, &body).unwrap()
2272
                };
2273
                assert_eq!(
2274
                    s.get(&r).unwrap().1,
2275
                    body,
2276
                    "readable while pending (object {i})"
2277
                );
2278
                refs.push((r, body));
2279
            }
2280
            assert!(s.has(&refs[0].0));
2281
            big.finish().unwrap();
2282
            assert_eq!(s.pack_count(), 1);
2283
            assert_eq!(
2284
                s.loose_count().unwrap(),
2285
                2,
2286
                "nothing from the big batch is loose"
2287
            );
2288
            assert!(fs::read_dir(s.dir())
2289
                .unwrap()
2290
                .flatten()
2291
                .all(|e| !e.file_name().to_string_lossy().contains("tmp-")));
2292
            let s2 = Store::open_on(s.backend().clone(), s.dir()).unwrap();
2293
            for (r, body) in &refs {
2294
                assert_eq!(s2.get(r).unwrap().1, *body);
2295
            }
2296
            // A dropped batch still writes its objects.
2297
            {
2298
                let _b = s2.begin_batch().unwrap();
2299
                s2.put(ObjectType::Chunk, b"dropped").unwrap();
2300
            }
2301
            assert_eq!(
2302
                s2.get(&hash_object(ObjectType::Chunk, b"dropped"))
2303
                    .unwrap()
2304
                    .1,
2305
                b"dropped"
2306
            );
2307
        });
2308
    }
2309
2310
    #[test]
2311
    fn get_many_reads_loose_and_packed_objects_in_order() {
2312
        let dir = tempfile::tempdir().unwrap();
2313
        each_store(dir.path(), |which, s| {
2314
            let packed: Vec<ObjectRef> = (0..20)
2315
                .map(|i| {
2316
                    s.put(ObjectType::Chunk, format!("packed {i}").as_bytes())
2317
                        .unwrap()
2318
                })
2319
                .collect();
2320
            s.pack_loose().unwrap();
2321
            let loose: Vec<ObjectRef> = (0..20)
2322
                .map(|i| {
2323
                    s.put(ObjectType::Chunk, format!("loose {i}").as_bytes())
2324
                        .unwrap()
2325
                })
2326
                .collect();
2327
            let missing = hash_object(ObjectType::Chunk, b"never stored");
2328
            let mut refs: Vec<ObjectRef> = Vec::new();
2329
            for i in 0..20 {
2330
                refs.push(loose[i]);
2331
                refs.push(packed[i]);
2332
            }
2333
            refs.push(missing);
2334
            let got = s.get_many(&refs);
2335
            assert_eq!(got.len(), refs.len());
2336
            for (i, r) in refs.iter().enumerate().take(40) {
2337
                let want = if i % 2 == 0 {
2338
                    format!("loose {}", i / 2)
2339
                } else {
2340
                    format!("packed {}", i / 2)
2341
                };
2342
                let (ty, body) = got[i].as_ref().unwrap();
2343
                assert_eq!(
2344
                    (*ty, body.as_slice()),
2345
                    (ObjectType::Chunk, want.as_bytes()),
2346
                    "{which}: {r:?}"
2347
                );
2348
            }
2349
            assert!(matches!(got[40], Err(StoreError::NotFound(_))));
2350
        });
2351
    }
2352
}
2353
2354
#[cfg(test)]
2355
mod batch_tests {
2356
    use super::*;
2357
2358
    #[test]
2359
    fn a_large_batch_packs_every_object_and_indexes_them_all() {
2360
        let dir = tempfile::tempdir().unwrap();
2361
        let store = Store::open(dir.path()).unwrap();
2362
        let mut refs = Vec::new();
2363
        {
2364
            let batch = store.begin_batch().unwrap();
2365
            for i in 0..1000u32 {
2366
                let body = format!("object {i} {}", "x".repeat(20_000 + i as usize)).into_bytes();
2367
                refs.push(store.put(ObjectType::Blob, &body).unwrap());
2368
            }
2369
            batch.finish().unwrap();
2370
        }
2371
        let again = Store::open(dir.path()).unwrap();
2372
        for r in &refs {
2373
            again
2374
                .get(r)
2375
                .unwrap_or_else(|e| panic!("{}: {e}", r.short(12)));
2376
        }
2377
    }
2378
}
2379
2380
#[cfg(test)]
2381
mod size_tests {
2382
    use super::*;
2383
2384
    #[test]
2385
    fn an_object_over_the_limit_is_refused_and_nothing_is_written() {
2386
        let dir = tempfile::tempdir().unwrap();
2387
        let store = Store::open(dir.path()).unwrap();
2388
        let big = vec![b'x'; MAX_OBJECT_LEN as usize + 1];
2389
        {
2390
            let batch = store.begin_batch().unwrap();
2391
            store.put(ObjectType::Blob, b"small").unwrap();
2392
            let e = store.put(ObjectType::Change, &big).unwrap_err();
2393
            assert!(
2394
                matches!(e, StoreError::TooLarge { kind: "change", .. }),
2395
                "{e}"
2396
            );
2397
            assert!(e.to_string().contains("commit it in parts"), "{e}");
2398
            batch.finish().unwrap();
2399
        }
2400
        // The store still opens and reads what was written.
2401
        let again = Store::open(dir.path()).unwrap();
2402
        again.get(&hash_object(ObjectType::Blob, b"small")).unwrap();
2403
    }
2404
}
2405
2406
#[cfg(test)]
2407
mod text_tests {
2408
    use super::*;
2409
    use crate::objects::{AtomRef, Edit, CHANGE_VERSION};
2410
2411
    fn large_change() -> Change {
2412
        let mut c = crate::objects::tests::sample_change();
2413
        assert_eq!(c.version, CHANGE_VERSION);
2414
        c.edits[0] = Edit::Insert {
2415
            node: crate::ids::NodeId([7; 16]),
2416
            after: AtomRef::Start,
2417
            before: AtomRef::End,
2418
            lines: (0..2000)
2419
                .map(|i| format!("line {i}\n").into_bytes())
2420
                .collect(),
2421
        };
2422
        c
2423
    }
2424
2425
    #[test]
2426
    fn a_large_insert_is_stored_beside_its_change_and_read_back() {
2427
        let dir = tempfile::tempdir().unwrap();
2428
        let s = Store::open(dir.path()).unwrap();
2429
        let c = large_change();
2430
        let r = s.put_change(&c).unwrap();
2431
        assert_eq!(r, c.hash());
2432
        let (_, body) = s.get(&r).unwrap();
2433
        assert!(
2434
            body.len() < 1024,
2435
            "the change holds a reference, not {} bytes of lines",
2436
            body.len()
2437
        );
2438
        let (back, parts) = s.get_change_parts(&r).unwrap();
2439
        assert_eq!(back, c);
2440
        // The text blob and its chunk.
2441
        assert_eq!(parts.len(), 2);
2442
        for p in &parts {
2443
            assert!(s.has(p));
2444
        }
2445
        // Storing it again writes nothing new.
2446
        let n = s.list().unwrap().len();
2447
        s.put_change(&c).unwrap();
2448
        assert_eq!(s.list().unwrap().len(), n);
2449
    }
2450
2451
    #[test]
2452
    fn a_change_whose_text_blob_is_missing_is_reported_not_misread() {
2453
        if !super::files_on_disk() {
2454
            return;
2455
        }
2456
        let dir = tempfile::tempdir().unwrap();
2457
        let s = Store::open(dir.path()).unwrap();
2458
        let c = large_change();
2459
        let r = s.put_change(&c).unwrap();
2460
        let (_, parts) = s.get_change_parts(&r).unwrap();
2461
        fs::remove_file(s.path_for(&parts[0])).unwrap();
2462
        let e = s.get_change(&r).unwrap_err();
2463
        assert!(
2464
            matches!(&e, StoreError::Corrupt(h, why) if *h == r && why.contains("missing")),
2465
            "{e}"
2466
        );
2467
    }
2468
}
2469
2470
#[cfg(test)]
2471
mod put_many_tests {
2472
    use super::*;
2473
2474
    #[test]
2475
    fn many_objects_in_a_batch_are_compressed_together_and_all_read_back() {
2476
        let dir = tempfile::tempdir().unwrap();
2477
        let s = Store::open(dir.path()).unwrap();
2478
        let before = s.put(ObjectType::Chunk, b"already here").unwrap();
2479
        let bodies: Vec<Vec<u8>> = (0..200u32)
2480
            .map(|i| format!("chunk {i} ").repeat(6000).into_bytes())
2481
            .collect();
2482
        let mut objects: Vec<(ObjectType, &[u8])> = bodies
2483
            .iter()
2484
            .map(|b| (ObjectType::Chunk, b.as_slice()))
2485
            .collect();
2486
        objects.push((ObjectType::Chunk, bodies[0].as_slice()));
2487
        objects.push((ObjectType::Chunk, b"already here"));
2488
        let refs = {
2489
            let batch = s.begin_batch().unwrap();
2490
            let refs = s.put_many(&objects).unwrap();
2491
            batch.finish().unwrap();
2492
            refs
2493
        };
2494
        assert_eq!(refs.len(), objects.len());
2495
        assert_eq!(refs[200], refs[0], "a repeat is the same object");
2496
        assert_eq!(refs[201], before);
2497
        let again = Store::open(dir.path()).unwrap();
2498
        for (r, b) in refs.iter().zip(&objects) {
2499
            assert_eq!(again.get(r).unwrap().1, b.1);
2500
        }
2501
    }
2502
}