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