OXYGENHUB
◆ agents-in-readme oxygen / crates / oxy-core / src / store.rs
92.8 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 encoding = crate::timing::phase("store: encode the change and its texts");
1342
        let bytes = c.encode_streaming(|batch| self.put_texts(&batch))?;
1343
        drop(encoding);
1344
        let _t = crate::timing::phase("store: put the encoding");
1345
        self.put(ObjectType::Change, &bytes)
1346
    }
1347
1348
    /// Store text blobs and their chunks: every chunk at once (compressed
1349
    /// on every core in a large batch), then the blobs.
1350
    pub fn put_texts(&self, texts: &[crate::objects::StoredText]) -> Result<()> {
1351
        let mut chunks: Vec<(ObjectType, &[u8])> = Vec::new();
1352
        for t in texts {
1353
            if !self.has(&t.blob.hash()) {
1354
                chunks.extend(
1355
                    crate::chunk::chunks(&t.content)
1356
                        .into_iter()
1357
                        .map(|c| (ObjectType::Chunk, c)),
1358
                );
1359
            }
1360
        }
1361
        self.put_many(&chunks)?;
1362
        for t in texts {
1363
            self.put(ObjectType::Blob, &t.blob.encode())?;
1364
        }
1365
        Ok(())
1366
    }
1367
1368
    pub fn get_change(&self, r: &ObjectRef) -> Result<Change> {
1369
        Ok(self.get_change_parts(r)?.0)
1370
    }
1371
1372
    /// A change and the objects its stored inserts are made of: each text
1373
    /// blob and its chunks, which travel and are kept with it.
1374
    pub fn get_change_parts(&self, r: &ObjectRef) -> Result<(Change, Vec<ObjectRef>)> {
1375
        let bytes = self.get_typed(r, ObjectType::Change)?;
1376
        let mut parts = Vec::new();
1377
        let mut failed = None;
1378
        let decoded = Change::decode_with(&bytes, &mut |text, count, form| match self
1379
            .read_text(text)
1380
        {
1381
            Ok((blob, content)) => {
1382
                parts.push(*text);
1383
                parts.extend(blob.chunks);
1384
                crate::objects::text_lines(&content, count, form)
1385
            }
1386
            Err(e) => {
1387
                let why = e.to_string();
1388
                failed = Some(e);
1389
                Err(ObjectError::Schema(format!(
1390
                    "text blob {}: {why}",
1391
                    text.short(12)
1392
                )))
1393
            }
1394
        });
1395
        match (decoded, failed) {
1396
            (Ok(c), _) => Ok((c, parts)),
1397
            (Err(_), Some(StoreError::NotFound(t))) => Err(StoreError::Corrupt(
1398
                *r,
1399
                format!("its text blob {} is missing", t.short(12)),
1400
            )),
1401
            (Err(e), _) => Err(StoreError::Corrupt(*r, e.to_string())),
1402
        }
1403
    }
1404
1405
    /// A change with every insert left without its lines (empty
1406
    /// placeholders), and where each one's lines are, in order: for
1407
    /// history-only states, which read text only for the graphs they build
1408
    /// (see [`Change::decode_skeleton`]).
1409
    pub fn get_change_lazy(&self, r: &ObjectRef) -> Result<(Change, Vec<crate::objects::TextRef>)> {
1410
        let bytes = self.get_typed(r, ObjectType::Change)?;
1411
        Change::decode_skeleton(&bytes, *r).map_err(|e| StoreError::Corrupt(*r, e.to_string()))
1412
    }
1413
1414
    /// A change's metadata (id, dependencies, author, clock, message, kind)
1415
    /// without its contents: read from its skeleton, so neither its text
1416
    /// blobs nor its inline lines are read (spec §11).
1417
    ///
1418
    /// Served from the `metas` cache when this store read it before (a
1419
    /// change object can be as large as the tree it adds), as long as the
1420
    /// store still has the change.
1421
    pub fn get_change_meta(&self, r: &ObjectRef) -> Result<crate::state::ChangeMeta> {
1422
        if self.metas.borrow().is_none() {
1423
            *self.metas.borrow_mut() = Some(self.read_metas_cache());
1424
        }
1425
        let cached = self.metas.borrow().as_ref().and_then(|m| m.get(r).cloned());
1426
        if let Some(meta) = cached {
1427
            if self.has(r) {
1428
                #[cfg(test)]
1429
                assert_eq!(
1430
                    meta,
1431
                    Change::decode_meta(&self.get_typed(r, ObjectType::Change)?).unwrap(),
1432
                    "the metadata cache holds a change's metadata"
1433
                );
1434
                return Ok(meta);
1435
            }
1436
        }
1437
        let bytes = self.get_typed(r, ObjectType::Change)?;
1438
        let meta =
1439
            Change::decode_meta(&bytes).map_err(|e| StoreError::Corrupt(*r, e.to_string()))?;
1440
        self.remember_meta(r, &meta);
1441
        Ok(meta)
1442
    }
1443
1444
    /// The metadata cache: records of a change hash, its metadata in the
1445
    /// flat layout, and the first 8 bytes of BLAKE3 over both, each
1446
    /// appended in one write. Derived only: a record that does not check
1447
    /// ends the reading (a torn write), and the cache can be deleted. It
1448
    /// lives in the scratch directory, on this disk.
1449
    fn read_metas_cache(&self) -> crate::fasthash::FastMap<ObjectRef, crate::state::ChangeMeta> {
1450
        let mut out = crate::fasthash::FastMap::default();
1451
        let Ok(bytes) = fs::read(self.scratch.join("metas")) else {
1452
            return out;
1453
        };
1454
        let mut r = crate::flat::Reader::new(&bytes);
1455
        let mut good = 0;
1456
        while !r.at_end() {
1457
            let mut record = || -> std::result::Result<_, ObjectError> {
1458
                let h = r.object()?;
1459
                let body = r.bytes()?;
1460
                let check = r.fixed::<8>()?;
1461
                Ok((h, body, check))
1462
            };
1463
            let Ok((h, body, check)) = record() else {
1464
                break;
1465
            };
1466
            let mut sum = blake3::Hasher::new();
1467
            sum.update(&h.0).update(body);
1468
            if sum.finalize().as_bytes()[..8] != check {
1469
                break;
1470
            }
1471
            match crate::state::ChangeMeta::read_flat(&mut crate::flat::Reader::new(body)) {
1472
                Ok(m) => out.insert(h, m),
1473
                Err(_) => break,
1474
            };
1475
            good += 32 + 4 + body.len() + 8;
1476
        }
1477
        // Cut a bad tail, so records appended later are read.
1478
        if good < bytes.len() {
1479
            let _ = fs::OpenOptions::new()
1480
                .write(true)
1481
                .open(self.scratch.join("metas"))
1482
                .and_then(|f| f.set_len(good as u64));
1483
        }
1484
        out
1485
    }
1486
1487
    /// Add a change's metadata to the cache; quietly nothing when it
1488
    /// cannot be written (it is only a cache).
1489
    fn remember_meta(&self, r: &ObjectRef, meta: &crate::state::ChangeMeta) {
1490
        let mut body = crate::flat::Writer::default();
1491
        meta.write_flat(&mut body);
1492
        let mut w = crate::flat::Writer::default();
1493
        w.object(r);
1494
        w.bytes(&body.0);
1495
        let mut sum = blake3::Hasher::new();
1496
        sum.update(&r.0).update(&body.0);
1497
        w.fixed(&sum.finalize().as_bytes()[..8]);
1498
        let _ = fs::OpenOptions::new()
1499
            .create(true)
1500
            .append(true)
1501
            .open(self.scratch.join("metas"))
1502
            .and_then(|mut f| f.write_all(&w.0));
1503
        if let Some(m) = self.metas.borrow_mut().as_mut() {
1504
            m.insert(*r, meta.clone());
1505
        }
1506
    }
1507
1508
    fn read_text(&self, r: &ObjectRef) -> Result<(Blob, Vec<u8>)> {
1509
        let blob = Blob::decode(&self.get_typed(r, ObjectType::Blob)?)?;
1510
        let mut content = Vec::with_capacity(blob.length as usize);
1511
        for c in &blob.chunks {
1512
            content.extend(self.get_typed(c, ObjectType::Chunk)?);
1513
        }
1514
        Ok((blob, content))
1515
    }
1516
1517
    pub fn put_chunk(&self, bytes: &[u8]) -> Result<ObjectRef> {
1518
        self.put(ObjectType::Chunk, bytes)
1519
    }
1520
1521
    /// Store a chunk that packs will keep uncompressed (`nocompress`, spec §13.3).
1522
    pub fn put_chunk_nocompress(&self, bytes: &[u8]) -> Result<ObjectRef> {
1523
        let r = hash_object(ObjectType::Chunk, bytes);
1524
        put_new_or_existing(
1525
            self.backend.as_ref(),
1526
            &format!("nocompress/{}", r.to_hex()),
1527
            b"",
1528
        )?;
1529
        self.put(ObjectType::Chunk, bytes)
1530
    }
1531
1532
    fn is_nocompress(&self, r: &ObjectRef) -> bool {
1533
        self.backend
1534
            .has(&format!("nocompress/{}", r.to_hex()))
1535
            .unwrap_or(false)
1536
    }
1537
1538
    /// Every chunk marked to be kept raw.
1539
    fn nocompress_set(&self) -> Result<std::collections::HashSet<ObjectRef>> {
1540
        Ok(self
1541
            .backend
1542
            .list("nocompress/")
1543
            .map_err(backend_err)?
1544
            .into_iter()
1545
            .filter_map(|e| ObjectRef::from_hex(e.key.trim_start_matches("nocompress/")))
1546
            .collect())
1547
    }
1548
1549
    pub fn put_state(&self, st: &StateObject) -> Result<ObjectRef> {
1550
        self.put(ObjectType::State, &st.encode())
1551
    }
1552
1553
    pub fn get_state(&self, r: &ObjectRef) -> Result<StateObject> {
1554
        Ok(StateObject::decode(&self.get_typed(r, ObjectType::State)?)?)
1555
    }
1556
1557
    pub fn put_attest(&self, a: &Attest) -> Result<ObjectRef> {
1558
        self.put(ObjectType::Attest, &a.encode())
1559
    }
1560
1561
    pub fn get_attest(&self, r: &ObjectRef) -> Result<Attest> {
1562
        Ok(Attest::decode(&self.get_typed(r, ObjectType::Attest)?)?)
1563
    }
1564
1565
    pub fn put_receipt(&self, r: &Receipt) -> Result<ObjectRef> {
1566
        self.put(ObjectType::Receipt, &r.encode())
1567
    }
1568
1569
    pub fn get_receipt(&self, r: &ObjectRef) -> Result<Receipt> {
1570
        Ok(Receipt::decode(&self.get_typed(r, ObjectType::Receipt)?)?)
1571
    }
1572
1573
    /// Record `value` under `key` in `index`: one write-once entry, so two
1574
    /// writers of a shared store never lose each other's.
1575
    fn index_add(&self, index: &str, key: &ObjectRef, value: &ObjectRef) -> Result<()> {
1576
        let entry = format!("{}{}", fanout_prefix(index, key), value.to_hex());
1577
        put_new_or_existing(self.backend.as_ref(), &entry, b"")
1578
    }
1579
1580
    /// The values recorded under `key` in `index`, with those an older
1581
    /// store kept as one list in `legacy`, sorted.
1582
    fn index_get(&self, index: &str, legacy: &str, key: &ObjectRef) -> Result<Vec<ObjectRef>> {
1583
        let mut values: Vec<ObjectRef> = self
1584
            .backend
1585
            .list(&fanout_prefix(index, key))
1586
            .map_err(backend_err)?
1587
            .into_iter()
1588
            .filter_map(|e| e.key.rsplit('/').next().and_then(ObjectRef::from_hex))
1589
            .collect();
1590
        if let Some(bytes) = get_optional(self.backend.as_ref(), &legacy_key(legacy, key))? {
1591
            values.extend(
1592
                String::from_utf8_lossy(&bytes)
1593
                    .lines()
1594
                    .filter_map(ObjectRef::from_hex),
1595
            );
1596
        }
1597
        values.sort();
1598
        values.dedup();
1599
        Ok(values)
1600
    }
1601
1602
    /// Record that seal attestation `attest` covers `change`.
1603
    pub fn index_seal(&self, change: &ObjectRef, attest: &ObjectRef) -> Result<()> {
1604
        self.index_add("seal", change, attest)
1605
    }
1606
1607
    /// Seal attestations known to cover `change`.
1608
    pub fn seals_for(&self, change: &ObjectRef) -> Result<Vec<ObjectRef>> {
1609
        self.index_get("seal", "seals", change)
1610
    }
1611
1612
    /// Record receipt attestation `attest` for `state` (spec §14.6).
1613
    pub fn index_receipt(&self, state: &ObjectRef, attest: &ObjectRef) -> Result<()> {
1614
        self.index_add("receipt", state, attest)
1615
    }
1616
1617
    /// Receipt attestations recorded for `state`.
1618
    pub fn receipts_for(&self, state: &ObjectRef) -> Result<Vec<ObjectRef>> {
1619
        self.index_get("receipt", "receipts", state)
1620
    }
1621
1622
    /// Every state with a receipt, for garbage collection.
1623
    pub fn receipt_states(&self) -> Result<Vec<ObjectRef>> {
1624
        let mut out: Vec<ObjectRef> = Vec::new();
1625
        for e in self.backend.list("receipt/").map_err(backend_err)? {
1626
            // receipt/<hh>/<rest>/<attest>
1627
            let mut parts = e.key.splitn(4, '/');
1628
            let (Some(_), Some(hh), Some(rest), Some(_)) =
1629
                (parts.next(), parts.next(), parts.next(), parts.next())
1630
            else {
1631
                continue;
1632
            };
1633
            out.extend(ObjectRef::from_hex(&format!("{hh}{rest}")));
1634
        }
1635
        for e in self.backend.list("receipts/").map_err(backend_err)? {
1636
            let mut parts = e.key.splitn(3, '/');
1637
            let (Some(_), Some(hh), Some(rest)) = (parts.next(), parts.next(), parts.next()) else {
1638
                continue;
1639
            };
1640
            out.extend(ObjectRef::from_hex(&format!("{hh}{rest}")));
1641
        }
1642
        out.sort();
1643
        out.dedup();
1644
        Ok(out)
1645
    }
1646
1647
    pub fn put_identity(&self, id: &Identity) -> Result<ObjectRef> {
1648
        self.put(ObjectType::Identity, &id.encode())
1649
    }
1650
1651
    pub fn get_identity(&self, r: &ObjectRef) -> Result<Identity> {
1652
        Ok(Identity::decode(&self.get_typed(r, ObjectType::Identity)?)?)
1653
    }
1654
1655
    /// Signatures stored alongside object `r` (spec §5.4), one per signing
1656
    /// key, sorted by key. Empty if none.
1657
    pub fn signatures(&self, r: &ObjectRef) -> Result<Vec<Signature>> {
1658
        let mut sigs: Vec<Signature> = Vec::new();
1659
        for e in self
1660
            .backend
1661
            .list(&fanout_prefix("sig", r))
1662
            .map_err(backend_err)?
1663
        {
1664
            let bytes = self.backend.get(&e.key).map_err(backend_err)?;
1665
            sigs.extend(Signature::decode_list(&bytes)?);
1666
        }
1667
        // An older store's one list per object; a signer kept there and
1668
        // here counts once, as written here.
1669
        if let Some(bytes) = get_optional(self.backend.as_ref(), &legacy_key("sigs", r))? {
1670
            for sig in Signature::decode_list(&bytes)? {
1671
                if !sigs.iter().any(|s| s.key == sig.key) {
1672
                    sigs.push(sig);
1673
                }
1674
            }
1675
        }
1676
        sigs.sort_by_key(|s| s.key);
1677
        sigs.dedup_by_key(|s| s.key);
1678
        Ok(sigs)
1679
    }
1680
1681
    /// Attach a signature to object `r`, replacing any earlier one by the
1682
    /// same key: one entry per signer, so the latest by a key is the one
1683
    /// kept, and two signers never touch each other's.
1684
    pub fn put_signature(&self, r: &ObjectRef, sig: &Signature) -> Result<()> {
1685
        let key = format!("{}{}", fanout_prefix("sig", r), sig.key.to_hex());
1686
        let bytes = Signature::encode_list(std::slice::from_ref(sig));
1687
        if get_optional(self.backend.as_ref(), &key)?.as_deref() == Some(bytes.as_slice()) {
1688
            return Ok(());
1689
        }
1690
        delete(self.backend.as_ref(), &key)?;
1691
        put_new_or_existing(self.backend.as_ref(), &key, &bytes)
1692
    }
1693
1694
    /// Every object reference in the store, loose and packed (slow; for gc and tests).
1695
    pub fn list(&self) -> io::Result<Vec<ObjectRef>> {
1696
        let mut out: Vec<ObjectRef> = self
1697
            .loose_objects()
1698
            .map_err(|e| io::Error::other(e.to_string()))?
1699
            .into_iter()
1700
            .map(|(r, _)| r)
1701
            .collect();
1702
        for p in self.packs.borrow().iter() {
1703
            out.extend(p.refs.iter().copied());
1704
        }
1705
        out.sort();
1706
        out.dedup();
1707
        Ok(out)
1708
    }
1709
}
1710
1711
/// A loose object's bytes, verified against `r`.
1712
fn parse_loose(data: &[u8], r: &ObjectRef) -> Result<Object> {
1713
    let nul = data
1714
        .iter()
1715
        .position(|&b| b == 0)
1716
        .ok_or_else(|| StoreError::Corrupt(*r, "no header".into()))?;
1717
    let head = std::str::from_utf8(&data[..nul])
1718
        .map_err(|_| StoreError::Corrupt(*r, "header not UTF-8".into()))?;
1719
    let mut parts = head.split(' ');
1720
    let (Some("oxy1"), Some(ty), Some(len), None) =
1721
        (parts.next(), parts.next(), parts.next(), parts.next())
1722
    else {
1723
        return Err(StoreError::Corrupt(*r, format!("bad header {head:?}")));
1724
    };
1725
    let ty = ObjectType::from_name(ty)
1726
        .ok_or_else(|| StoreError::Corrupt(*r, format!("unknown type {ty}")))?;
1727
    let len: usize = len
1728
        .parse()
1729
        .map_err(|_| StoreError::Corrupt(*r, "bad length".into()))?;
1730
    let body = &data[nul + 1..];
1731
    if body.len() != len {
1732
        return Err(StoreError::Corrupt(
1733
            *r,
1734
            format!("length {} != header {len}", body.len()),
1735
        ));
1736
    }
1737
    if hash_object(ty, body) != *r {
1738
        return Err(StoreError::Corrupt(*r, "hash mismatch".into()));
1739
    }
1740
    Ok((ty, body.to_vec()))
1741
}
1742
1743
/// Whether the objects are files that a test may tamper with: not under
1744
/// `OXY_STORE_BACKEND=memory`.
1745
#[cfg(test)]
1746
fn files_on_disk() -> bool {
1747
    std::env::var_os("OXY_STORE_BACKEND").is_none()
1748
}
1749
1750
#[cfg(test)]
1751
mod tests {
1752
    use super::*;
1753
1754
    /// The store under test twice: in a directory, and on a store in
1755
    /// memory with a scratch directory, as over a bucket.
1756
    fn each_store(dir: &Path, f: impl Fn(&str, Store)) {
1757
        f("directory", Store::open(dir.join("objects")).unwrap());
1758
        f(
1759
            "memory",
1760
            Store::open_on(Arc::new(MemoryStore::new()), dir.join("scratch")).unwrap(),
1761
        );
1762
    }
1763
1764
    #[test]
1765
    fn put_get_verify() {
1766
        if !super::files_on_disk() {
1767
            return;
1768
        }
1769
        let dir = tempfile::tempdir().unwrap();
1770
        let s = Store::open(dir.path().join("objects")).unwrap();
1771
        let r = s.put(ObjectType::Chunk, b"hello").unwrap();
1772
        assert!(s.has(&r));
1773
        assert_eq!(s.get(&r).unwrap(), (ObjectType::Chunk, b"hello".to_vec()));
1774
        assert_eq!(s.put(ObjectType::Chunk, b"hello").unwrap(), r);
1775
        assert_eq!(s.list().unwrap(), vec![r]);
1776
        assert!(matches!(
1777
            s.get_typed(&r, ObjectType::Blob),
1778
            Err(StoreError::WrongType(..))
1779
        ));
1780
        assert!(matches!(
1781
            s.get(&ObjectRef([9; 32])),
1782
            Err(StoreError::NotFound(_))
1783
        ));
1784
1785
        // Tamper: flip a byte, read must fail.
1786
        let path = s.path_for(&r);
1787
        let mut data = fs::read(&path).unwrap();
1788
        let last = data.len() - 1;
1789
        data[last] ^= 1;
1790
        fs::write(&path, data).unwrap();
1791
        assert!(matches!(s.get(&r), Err(StoreError::Corrupt(..))));
1792
    }
1793
1794
    #[test]
1795
    fn packing_keeps_every_object_readable() {
1796
        if !super::files_on_disk() {
1797
            return;
1798
        }
1799
        let dir = tempfile::tempdir().unwrap();
1800
        let s = Store::open(dir.path()).unwrap();
1801
        let mut refs = Vec::new();
1802
        for i in 0..300u32 {
1803
            let body = format!("object {i} ").repeat(1 + (i % 7) as usize);
1804
            refs.push((s.put(ObjectType::Chunk, body.as_bytes()).unwrap(), body));
1805
        }
1806
        let c = crate::objects::tests::sample_change();
1807
        let cr = s.put_change(&c).unwrap();
1808
        assert_eq!(s.loose_count().unwrap(), 301);
1809
        let report = s.pack_loose().unwrap();
1810
        assert_eq!(report.objects, 301);
1811
        assert!(report.packed_bytes < report.raw_bytes, "{report:?}");
1812
        assert_eq!(s.loose_count().unwrap(), 0);
1813
        assert_eq!(s.pack_count(), 1);
1814
        for (r, body) in &refs {
1815
            assert!(s.has(r));
1816
            assert_eq!(
1817
                s.get(r).unwrap(),
1818
                (ObjectType::Chunk, body.as_bytes().to_vec())
1819
            );
1820
        }
1821
        assert_eq!(s.get_change(&cr).unwrap(), c);
1822
        assert_eq!(s.list().unwrap().len(), 301);
1823
        // Re-putting a packed object is a no-op; new objects go loose and a
1824
        // second pack coexists with the first.
1825
        assert_eq!(
1826
            s.put(ObjectType::Chunk, refs[0].1.as_bytes()).unwrap(),
1827
            refs[0].0
1828
        );
1829
        assert_eq!(s.loose_count().unwrap(), 0);
1830
        let extra = s.put(ObjectType::Chunk, b"after packing").unwrap();
1831
        s.pack_loose().unwrap();
1832
        assert_eq!(s.pack_count(), 2);
1833
        assert_eq!(s.get(&extra).unwrap().1, b"after packing");
1834
        // A reopened store sees the packs.
1835
        let s2 = Store::open(dir.path()).unwrap();
1836
        assert_eq!(s2.pack_count(), 2);
1837
        assert_eq!(s2.get(&refs[5].0).unwrap().1, refs[5].1.as_bytes());
1838
        assert!(matches!(
1839
            s2.get(&ObjectRef([9; 32])),
1840
            Err(StoreError::NotFound(_))
1841
        ));
1842
        // Corrupting an object's body inside the pack is detected on read.
1843
        let target = refs[5].0;
1844
        let (pack_path, offset) = {
1845
            let packs = s2.packs.borrow();
1846
            let (i, e) = s2.find_packed(&target).unwrap();
1847
            (dir.path().join(&packs[i].key), e.offset as usize)
1848
        };
1849
        let mut data = fs::read(&pack_path).unwrap();
1850
        data[offset] ^= 0xff;
1851
        fs::write(&pack_path, data).unwrap();
1852
        let s3 = Store::open(dir.path()).unwrap();
1853
        assert!(matches!(s3.get(&target), Err(StoreError::Corrupt(..))));
1854
        assert_eq!(
1855
            s3.get(&refs[6].0).unwrap().1,
1856
            refs[6].1.as_bytes(),
1857
            "other objects are unaffected"
1858
        );
1859
    }
1860
1861
    #[test]
1862
    fn a_full_repack_trains_a_dictionary_and_reads_back() {
1863
        if !super::files_on_disk() {
1864
            return;
1865
        }
1866
        let dir = tempfile::tempdir().unwrap();
1867
        let s = Store::open(dir.path()).unwrap();
1868
        // Many small, alike files: what a dictionary is for.
1869
        let bodies: Vec<Vec<u8>> = (0..1500)
1870
            .map(|i| {
1871
                format!(
1872
                    "// SPDX-License-Identifier: GPL-2.0\n#include <linux/module.h>\n\
1873
                     static int probe_{i}(struct device *dev)\n{{\n\treturn {i};\n}}\n"
1874
                )
1875
                .into_bytes()
1876
            })
1877
            .collect();
1878
        let refs: Vec<ObjectRef> = bodies
1879
            .iter()
1880
            .map(|b| s.put(ObjectType::Chunk, b).unwrap())
1881
            .collect();
1882
        s.repack_all(REPACK_ZSTD_LEVEL).unwrap();
1883
        let dicts = fs::read_dir(dir.path())
1884
            .unwrap()
1885
            .flatten()
1886
            .filter(|e| e.path().extension().is_some_and(|x| x == "dict"))
1887
            .count();
1888
        assert_eq!(dicts, 1, "the pack has a dictionary");
1889
        let with_dict = refs
1890
            .iter()
1891
            .filter(|r| s.find_packed(r).unwrap().1.flags & FLAG_DICT != 0)
1892
            .count();
1893
        assert!(with_dict > 1000, "most use it: {with_dict}");
1894
        let again = Store::open(dir.path()).unwrap();
1895
        for (r, b) in refs.iter().zip(&bodies) {
1896
            assert_eq!(&again.get(r).unwrap().1, b);
1897
        }
1898
        // A repack after that replaces the pack and its dictionary.
1899
        again.repack_all(REPACK_ZSTD_LEVEL).unwrap();
1900
        let files: Vec<String> = fs::read_dir(dir.path())
1901
            .unwrap()
1902
            .flatten()
1903
            .map(|e| e.file_name().to_string_lossy().into_owned())
1904
            .filter(|n| n.starts_with("pack-"))
1905
            .collect();
1906
        assert_eq!(files.len(), 3, "one pack, index and dictionary: {files:?}");
1907
        assert_eq!(&again.get(&refs[7]).unwrap().1, &bodies[7]);
1908
    }
1909
1910
    #[test]
1911
    fn nocompress_chunks_pack_raw() {
1912
        let dir = tempfile::tempdir().unwrap();
1913
        let s = Store::open(dir.path()).unwrap();
1914
        let body = vec![b'a'; 10_000];
1915
        let raw = s.put_chunk_nocompress(&body).unwrap();
1916
        let compressible = s.put(ObjectType::Chunk, &vec![b'b'; 10_000]).unwrap();
1917
        s.pack_loose().unwrap();
1918
        let packs = s.packs.borrow();
1919
        let (i, e) = s.find_packed(&raw).unwrap();
1920
        assert_eq!((e.flags, e.stored_len as usize), (0, 10_000));
1921
        let (_, c) = s.find_packed(&compressible).unwrap();
1922
        assert_eq!(c.flags, FLAG_ZSTD);
1923
        assert!(c.stored_len < 10_000);
1924
        assert_eq!(packs[i].fetch(s.backend.as_ref(), &raw, e).unwrap().1, body);
1925
    }
1926
1927
    #[test]
1928
    fn many_packs_merge_into_one() {
1929
        let dir = tempfile::tempdir().unwrap();
1930
        each_store(dir.path(), |which, s| {
1931
            let mut refs = Vec::new();
1932
            for i in 0..(MAX_PACKS + 2) {
1933
                refs.push(
1934
                    s.put(ObjectType::Chunk, format!("pack {i}").as_bytes())
1935
                        .unwrap(),
1936
                );
1937
                s.pack_loose().unwrap();
1938
            }
1939
            assert_eq!(s.pack_count(), MAX_PACKS + 2, "{which}");
1940
            assert_eq!(s.merge_packs().unwrap(), MAX_PACKS + 2);
1941
            assert_eq!(s.pack_count(), 1);
1942
            assert_eq!(s.merge_packs().unwrap(), 0);
1943
            for (i, r) in refs.iter().enumerate() {
1944
                assert_eq!(s.get(r).unwrap().1, format!("pack {i}").as_bytes());
1945
            }
1946
            let again = Store::open_on(s.backend().clone(), s.dir()).unwrap();
1947
            assert_eq!(again.pack_count(), 1, "{which}: reopened");
1948
        });
1949
    }
1950
1951
    #[test]
1952
    fn prune_removes_unreachable_loose_and_packed_objects() {
1953
        use std::collections::HashSet;
1954
        let dir = tempfile::tempdir().unwrap();
1955
        each_store(dir.path(), |which, s| {
1956
            let keep_a = s.put(ObjectType::Chunk, b"keep a").unwrap();
1957
            let drop_a = s.put(ObjectType::Chunk, b"drop a").unwrap();
1958
            s.pack_loose().unwrap();
1959
            let keep_b = s.put(ObjectType::Chunk, b"keep b").unwrap();
1960
            let drop_b = s.put(ObjectType::Chunk, b"drop b").unwrap();
1961
            let sk = crate::identity::SecretKey {
1962
                ed_seed: [1; 32],
1963
                ml_seed: [2; 32],
1964
            };
1965
            let id = sk.identity("a", "b", 0);
1966
            let key = s.put_identity(&id).unwrap();
1967
            s.put_signature(
1968
                &drop_b,
1969
                &sk.sign(crate::identity::Domain::Change, &key, &drop_b),
1970
            )
1971
            .unwrap();
1972
            s.index_seal(&drop_a, &ObjectRef([3; 32])).unwrap();
1973
            let keep: HashSet<ObjectRef> = [keep_a, keep_b, key].into_iter().collect();
1974
            // Everything is too young under a grace period.
1975
            let r = s
1976
                .prune(&keep, std::time::Duration::from_secs(3600))
1977
                .unwrap();
1978
            assert_eq!((r.objects, r.deferred), (0, 2), "{which}");
1979
            let r = s.prune(&keep, std::time::Duration::ZERO).unwrap();
1980
            assert_eq!(r.objects, 2, "{which}: {r:?}");
1981
            assert!(s.has(&keep_a) && s.has(&keep_b) && s.has(&key));
1982
            assert!(!s.has(&drop_a) && !s.has(&drop_b));
1983
            assert!(s.signatures(&drop_b).unwrap().is_empty());
1984
            assert!(s.seals_for(&drop_a).unwrap().is_empty());
1985
            assert_eq!(s.pack_count(), 1);
1986
            assert_eq!(s.get(&keep_a).unwrap().1, b"keep a");
1987
            assert_eq!(s.list().unwrap().len(), 3);
1988
        });
1989
    }
1990
1991
    #[test]
1992
    fn signatures_are_stored_beside_objects() {
1993
        use crate::identity::{Domain, SecretKey};
1994
        let dir = tempfile::tempdir().unwrap();
1995
        each_store(dir.path(), |which, s| {
1996
            let r = s.put(ObjectType::Chunk, b"x").unwrap();
1997
            assert!(s.signatures(&r).unwrap().is_empty());
1998
            let sk = SecretKey {
1999
                ed_seed: [1; 32],
2000
                ml_seed: [2; 32],
2001
            };
2002
            let id = sk.identity("a", "b", 0);
2003
            let key = s.put_identity(&id).unwrap();
2004
            assert_eq!(s.get_identity(&key).unwrap(), id);
2005
            let sig = sk.sign(Domain::Change, &key, &r);
2006
            s.put_signature(&r, &sig).unwrap();
2007
            s.put_signature(&r, &sig).unwrap();
2008
            assert_eq!(s.signatures(&r).unwrap(), vec![sig.clone()], "{which}");
2009
            // A second signer is kept beside the first, sorted by key.
2010
            let sk2 = SecretKey {
2011
                ed_seed: [3; 32],
2012
                ml_seed: [4; 32],
2013
            };
2014
            let key2 = s.put_identity(&sk2.identity("c", "d", 0)).unwrap();
2015
            let sig2 = sk2.sign(Domain::Change, &key2, &r);
2016
            s.put_signature(&r, &sig2).unwrap();
2017
            let mut both = vec![sig.clone(), sig2.clone()];
2018
            both.sort_by_key(|s| s.key);
2019
            assert_eq!(s.signatures(&r).unwrap(), both);
2020
            // The object itself is untouched by its signatures.
2021
            assert_eq!(s.get(&r).unwrap().1, b"x");
2022
            // Seal and receipt entries, and the states with receipts.
2023
            s.index_seal(&r, &ObjectRef([5; 32])).unwrap();
2024
            s.index_seal(&r, &ObjectRef([4; 32])).unwrap();
2025
            s.index_seal(&r, &ObjectRef([5; 32])).unwrap();
2026
            assert_eq!(
2027
                s.seals_for(&r).unwrap(),
2028
                vec![ObjectRef([4; 32]), ObjectRef([5; 32])]
2029
            );
2030
            let st = ObjectRef([6; 32]);
2031
            s.index_receipt(&st, &ObjectRef([7; 32])).unwrap();
2032
            assert_eq!(s.receipts_for(&st).unwrap(), vec![ObjectRef([7; 32])]);
2033
            assert_eq!(s.receipt_states().unwrap(), vec![st]);
2034
        });
2035
    }
2036
2037
    /// A store written before signatures, seals and receipts were one
2038
    /// entry each (`sigs/`, `seals/`, `receipts/` lists) still reads, and
2039
    /// what is written now sits beside what was there.
2040
    #[test]
2041
    fn an_older_store_s_sidecar_lists_are_still_read() {
2042
        if !super::files_on_disk() {
2043
            return;
2044
        }
2045
        use crate::identity::{Domain, SecretKey};
2046
        let dir = tempfile::tempdir().unwrap();
2047
        let s = Store::open(dir.path()).unwrap();
2048
        let r = s.put(ObjectType::Chunk, b"old").unwrap();
2049
        let h = r.to_hex();
2050
        let sk = SecretKey {
2051
            ed_seed: [1; 32],
2052
            ml_seed: [2; 32],
2053
        };
2054
        let key = s.put_identity(&sk.identity("a", "b", 0)).unwrap();
2055
        let sig = sk.sign(Domain::Change, &key, &r);
2056
        let legacy = dir.path().join("sigs").join(&h[..2]);
2057
        fs::create_dir_all(&legacy).unwrap();
2058
        fs::write(
2059
            legacy.join(&h[2..]),
2060
            Signature::encode_list(std::slice::from_ref(&sig)),
2061
        )
2062
        .unwrap();
2063
        let seals = dir.path().join("seals").join(&h[..2]);
2064
        fs::create_dir_all(&seals).unwrap();
2065
        fs::write(
2066
            seals.join(&h[2..]),
2067
            format!("{}\n", ObjectRef([9; 32]).to_hex()),
2068
        )
2069
        .unwrap();
2070
        let receipts = dir.path().join("receipts").join(&h[..2]);
2071
        fs::create_dir_all(&receipts).unwrap();
2072
        fs::write(
2073
            receipts.join(&h[2..]),
2074
            format!("{}\n", ObjectRef([8; 32]).to_hex()),
2075
        )
2076
        .unwrap();
2077
2078
        assert_eq!(s.signatures(&r).unwrap(), vec![sig.clone()]);
2079
        assert_eq!(s.seals_for(&r).unwrap(), vec![ObjectRef([9; 32])]);
2080
        assert_eq!(s.receipts_for(&r).unwrap(), vec![ObjectRef([8; 32])]);
2081
        assert_eq!(s.receipt_states().unwrap(), vec![r]);
2082
        // New entries join the old ones; the same signer is not doubled.
2083
        s.put_signature(&r, &sig).unwrap();
2084
        s.index_seal(&r, &ObjectRef([1; 32])).unwrap();
2085
        assert_eq!(s.signatures(&r).unwrap().len(), 1);
2086
        assert_eq!(
2087
            s.seals_for(&r).unwrap(),
2088
            vec![ObjectRef([1; 32]), ObjectRef([9; 32])]
2089
        );
2090
        // Pruning the object takes both layouts with it.
2091
        let r2 = s.put(ObjectType::Chunk, b"kept").unwrap();
2092
        let keep = [r2, key].into_iter().collect();
2093
        s.prune(&keep, std::time::Duration::ZERO).unwrap();
2094
        assert!(s.signatures(&r).unwrap().is_empty());
2095
        assert!(s.seals_for(&r).unwrap().is_empty());
2096
        assert!(s.receipt_states().unwrap().is_empty());
2097
    }
2098
2099
    #[test]
2100
    fn change_round_trip_through_store() {
2101
        let dir = tempfile::tempdir().unwrap();
2102
        each_store(dir.path(), |which, s| {
2103
            let c = crate::objects::tests::sample_change();
2104
            let r = s.put_change(&c).unwrap();
2105
            assert_eq!(r, c.hash(), "{which}");
2106
            assert_eq!(s.get_change(&r).unwrap(), c);
2107
            assert_eq!(s.get_change_meta(&r).unwrap().message, c.message);
2108
        });
2109
    }
2110
2111
    fn xorshift(state: &mut u64) -> u64 {
2112
        *state ^= *state << 13;
2113
        *state ^= *state >> 7;
2114
        *state ^= *state << 17;
2115
        *state
2116
    }
2117
2118
    /// Random corruption of pack and index files never panics: reads fail
2119
    /// with an error or the store refuses to open, and untouched objects
2120
    /// stay readable when the index survives.
2121
    #[test]
2122
    fn corrupted_packs_and_indexes_fail_cleanly() {
2123
        if !super::files_on_disk() {
2124
            return;
2125
        }
2126
        let dir = tempfile::tempdir().unwrap();
2127
        let objects = dir.path().join("objects");
2128
        let s = Store::open(&objects).unwrap();
2129
        let mut refs = Vec::new();
2130
        let mut seed = 0x9e3779b97f4a7c15u64;
2131
        for i in 0..40u32 {
2132
            let len = (xorshift(&mut seed) % 5000) as usize;
2133
            let mut body = vec![0u8; len];
2134
            for b in body.iter_mut() {
2135
                *b = if i % 2 == 0 {
2136
                    (xorshift(&mut seed) & 0xff) as u8
2137
                } else {
2138
                    b'a' + (i % 26) as u8
2139
                };
2140
            }
2141
            refs.push(s.put(ObjectType::Chunk, &body).unwrap());
2142
        }
2143
        s.pack_loose().unwrap();
2144
        let pack = fs::read_dir(&objects)
2145
            .unwrap()
2146
            .filter_map(|e| e.ok().map(|e| e.path()))
2147
            .find(|p| p.extension().is_some_and(|x| x == "pack"))
2148
            .unwrap();
2149
        let idx = pack.with_extension("idx");
2150
        let pristine_pack = fs::read(&pack).unwrap();
2151
        let pristine_idx = fs::read(&idx).unwrap();
2152
2153
        for round in 0..300u32 {
2154
            let (path, pristine) = if round % 2 == 0 {
2155
                (&pack, &pristine_pack)
2156
            } else {
2157
                (&idx, &pristine_idx)
2158
            };
2159
            let mut data = pristine.clone();
2160
            match xorshift(&mut seed) % 4 {
2161
                0 => {
2162
                    let at = (xorshift(&mut seed) as usize) % data.len();
2163
                    data[at] ^= 1 << (xorshift(&mut seed) % 8);
2164
                }
2165
                1 => {
2166
                    let at = (xorshift(&mut seed) as usize) % data.len();
2167
                    data[at] = (xorshift(&mut seed) & 0xff) as u8;
2168
                }
2169
                2 => {
2170
                    let keep = (xorshift(&mut seed) as usize) % data.len();
2171
                    data.truncate(keep);
2172
                }
2173
                _ => {
2174
                    let at = (xorshift(&mut seed) as usize) % data.len();
2175
                    let n = ((xorshift(&mut seed) % 8) + 1) as usize;
2176
                    for k in 0..n.min(data.len() - at) {
2177
                        data[at + k] = 0xff;
2178
                    }
2179
                }
2180
            }
2181
            fs::write(path, &data).unwrap();
2182
            // Opening may refuse a broken index; a store that opens must
2183
            // either return each object intact or report it corrupt/missing.
2184
            if let Ok(s2) = Store::open(&objects) {
2185
                for r in &refs {
2186
                    match s2.get(r) {
2187
                        Ok((ty, body)) => assert_eq!(
2188
                            hash_object(ty, &body),
2189
                            *r,
2190
                            "a returned object always matches its reference"
2191
                        ),
2192
                        Err(StoreError::Corrupt(..))
2193
                        | Err(StoreError::NotFound(_))
2194
                        | Err(StoreError::Io(_)) => {}
2195
                        Err(e) => panic!("unexpected error {e}"),
2196
                    }
2197
                }
2198
            }
2199
            fs::write(path, pristine).unwrap();
2200
        }
2201
        // Restored files read back in full.
2202
        let s3 = Store::open(&objects).unwrap();
2203
        for r in &refs {
2204
            let (ty, body) = s3.get(r).unwrap();
2205
            assert_eq!(hash_object(ty, &body), *r);
2206
        }
2207
    }
2208
2209
    /// A small batch becomes loose objects; a large one becomes a single
2210
    /// pack. Objects are readable while pending, and batches nest.
2211
    #[test]
2212
    fn batches_write_loose_or_one_pack() {
2213
        let dir = tempfile::tempdir().unwrap();
2214
        each_store(dir.path(), |which, s| {
2215
            let outer = s.begin_batch().unwrap();
2216
            let a = s.put(ObjectType::Chunk, b"small a").unwrap();
2217
            {
2218
                let inner = s.begin_batch().unwrap();
2219
                let b = s.put(ObjectType::Chunk, b"small b").unwrap();
2220
                assert!(s.has(&b));
2221
                assert_eq!(s.get(&b).unwrap().1, b"small b");
2222
                inner.finish().unwrap();
2223
                assert_eq!(
2224
                    s.loose_count().unwrap(),
2225
                    0,
2226
                    "{which}: the inner batch defers to the outer one"
2227
                );
2228
            }
2229
            assert_eq!(s.get(&a).unwrap().1, b"small a");
2230
            assert_eq!(
2231
                s.put(ObjectType::Chunk, b"small a").unwrap(),
2232
                a,
2233
                "idempotent while pending"
2234
            );
2235
            outer.finish().unwrap();
2236
            assert_eq!(s.loose_count().unwrap(), 2);
2237
            assert_eq!(s.pack_count(), 0);
2238
            assert_eq!(s.get(&a).unwrap().1, b"small a");
2239
2240
            // Large: spills into one pack, readable during and after.
2241
            let big = s.begin_batch().unwrap();
2242
            let mut refs = Vec::new();
2243
            let mut seed = 7u64;
2244
            for i in 0..300u32 {
2245
                let mut body = vec![b'z'; 40_000];
2246
                if i % 3 == 0 {
2247
                    for b in body.iter_mut() {
2248
                        *b = (xorshift(&mut seed) & 0xff) as u8;
2249
                    }
2250
                }
2251
                body[..4].copy_from_slice(&i.to_le_bytes());
2252
                let r = if i % 5 == 0 {
2253
                    s.put_chunk_nocompress(&body).unwrap()
2254
                } else {
2255
                    s.put(ObjectType::Chunk, &body).unwrap()
2256
                };
2257
                assert_eq!(
2258
                    s.get(&r).unwrap().1,
2259
                    body,
2260
                    "readable while pending (object {i})"
2261
                );
2262
                refs.push((r, body));
2263
            }
2264
            assert!(s.has(&refs[0].0));
2265
            big.finish().unwrap();
2266
            assert_eq!(s.pack_count(), 1);
2267
            assert_eq!(
2268
                s.loose_count().unwrap(),
2269
                2,
2270
                "nothing from the big batch is loose"
2271
            );
2272
            assert!(fs::read_dir(s.dir())
2273
                .unwrap()
2274
                .flatten()
2275
                .all(|e| !e.file_name().to_string_lossy().contains("tmp-")));
2276
            let s2 = Store::open_on(s.backend().clone(), s.dir()).unwrap();
2277
            for (r, body) in &refs {
2278
                assert_eq!(s2.get(r).unwrap().1, *body);
2279
            }
2280
            // A dropped batch still writes its objects.
2281
            {
2282
                let _b = s2.begin_batch().unwrap();
2283
                s2.put(ObjectType::Chunk, b"dropped").unwrap();
2284
            }
2285
            assert_eq!(
2286
                s2.get(&hash_object(ObjectType::Chunk, b"dropped"))
2287
                    .unwrap()
2288
                    .1,
2289
                b"dropped"
2290
            );
2291
        });
2292
    }
2293
2294
    #[test]
2295
    fn get_many_reads_loose_and_packed_objects_in_order() {
2296
        let dir = tempfile::tempdir().unwrap();
2297
        each_store(dir.path(), |which, s| {
2298
            let packed: Vec<ObjectRef> = (0..20)
2299
                .map(|i| {
2300
                    s.put(ObjectType::Chunk, format!("packed {i}").as_bytes())
2301
                        .unwrap()
2302
                })
2303
                .collect();
2304
            s.pack_loose().unwrap();
2305
            let loose: Vec<ObjectRef> = (0..20)
2306
                .map(|i| {
2307
                    s.put(ObjectType::Chunk, format!("loose {i}").as_bytes())
2308
                        .unwrap()
2309
                })
2310
                .collect();
2311
            let missing = hash_object(ObjectType::Chunk, b"never stored");
2312
            let mut refs: Vec<ObjectRef> = Vec::new();
2313
            for i in 0..20 {
2314
                refs.push(loose[i]);
2315
                refs.push(packed[i]);
2316
            }
2317
            refs.push(missing);
2318
            let got = s.get_many(&refs);
2319
            assert_eq!(got.len(), refs.len());
2320
            for (i, r) in refs.iter().enumerate().take(40) {
2321
                let want = if i % 2 == 0 {
2322
                    format!("loose {}", i / 2)
2323
                } else {
2324
                    format!("packed {}", i / 2)
2325
                };
2326
                let (ty, body) = got[i].as_ref().unwrap();
2327
                assert_eq!(
2328
                    (*ty, body.as_slice()),
2329
                    (ObjectType::Chunk, want.as_bytes()),
2330
                    "{which}: {r:?}"
2331
                );
2332
            }
2333
            assert!(matches!(got[40], Err(StoreError::NotFound(_))));
2334
        });
2335
    }
2336
}
2337
2338
#[cfg(test)]
2339
mod batch_tests {
2340
    use super::*;
2341
2342
    #[test]
2343
    fn a_large_batch_packs_every_object_and_indexes_them_all() {
2344
        let dir = tempfile::tempdir().unwrap();
2345
        let store = Store::open(dir.path()).unwrap();
2346
        let mut refs = Vec::new();
2347
        {
2348
            let batch = store.begin_batch().unwrap();
2349
            for i in 0..1000u32 {
2350
                let body = format!("object {i} {}", "x".repeat(20_000 + i as usize)).into_bytes();
2351
                refs.push(store.put(ObjectType::Blob, &body).unwrap());
2352
            }
2353
            batch.finish().unwrap();
2354
        }
2355
        let again = Store::open(dir.path()).unwrap();
2356
        for r in &refs {
2357
            again
2358
                .get(r)
2359
                .unwrap_or_else(|e| panic!("{}: {e}", r.short(12)));
2360
        }
2361
    }
2362
}
2363
2364
#[cfg(test)]
2365
mod size_tests {
2366
    use super::*;
2367
2368
    #[test]
2369
    fn an_object_over_the_limit_is_refused_and_nothing_is_written() {
2370
        let dir = tempfile::tempdir().unwrap();
2371
        let store = Store::open(dir.path()).unwrap();
2372
        let big = vec![b'x'; MAX_OBJECT_LEN as usize + 1];
2373
        {
2374
            let batch = store.begin_batch().unwrap();
2375
            store.put(ObjectType::Blob, b"small").unwrap();
2376
            let e = store.put(ObjectType::Change, &big).unwrap_err();
2377
            assert!(
2378
                matches!(e, StoreError::TooLarge { kind: "change", .. }),
2379
                "{e}"
2380
            );
2381
            assert!(e.to_string().contains("commit it in parts"), "{e}");
2382
            batch.finish().unwrap();
2383
        }
2384
        // The store still opens and reads what was written.
2385
        let again = Store::open(dir.path()).unwrap();
2386
        again.get(&hash_object(ObjectType::Blob, b"small")).unwrap();
2387
    }
2388
}
2389
2390
#[cfg(test)]
2391
mod text_tests {
2392
    use super::*;
2393
    use crate::objects::{AtomRef, Edit, CHANGE_VERSION};
2394
2395
    fn large_change() -> Change {
2396
        let mut c = crate::objects::tests::sample_change();
2397
        assert_eq!(c.version, CHANGE_VERSION);
2398
        c.edits[0] = Edit::Insert {
2399
            node: crate::ids::NodeId([7; 16]),
2400
            after: AtomRef::Start,
2401
            before: AtomRef::End,
2402
            lines: (0..2000)
2403
                .map(|i| format!("line {i}\n").into_bytes())
2404
                .collect(),
2405
        };
2406
        c
2407
    }
2408
2409
    #[test]
2410
    fn a_large_insert_is_stored_beside_its_change_and_read_back() {
2411
        let dir = tempfile::tempdir().unwrap();
2412
        let s = Store::open(dir.path()).unwrap();
2413
        let c = large_change();
2414
        let r = s.put_change(&c).unwrap();
2415
        assert_eq!(r, c.hash());
2416
        let (_, body) = s.get(&r).unwrap();
2417
        assert!(
2418
            body.len() < 1024,
2419
            "the change holds a reference, not {} bytes of lines",
2420
            body.len()
2421
        );
2422
        let (back, parts) = s.get_change_parts(&r).unwrap();
2423
        assert_eq!(back, c);
2424
        // The text blob and its chunk.
2425
        assert_eq!(parts.len(), 2);
2426
        for p in &parts {
2427
            assert!(s.has(p));
2428
        }
2429
        // Storing it again writes nothing new.
2430
        let n = s.list().unwrap().len();
2431
        s.put_change(&c).unwrap();
2432
        assert_eq!(s.list().unwrap().len(), n);
2433
    }
2434
2435
    #[test]
2436
    fn a_change_whose_text_blob_is_missing_is_reported_not_misread() {
2437
        if !super::files_on_disk() {
2438
            return;
2439
        }
2440
        let dir = tempfile::tempdir().unwrap();
2441
        let s = Store::open(dir.path()).unwrap();
2442
        let c = large_change();
2443
        let r = s.put_change(&c).unwrap();
2444
        let (_, parts) = s.get_change_parts(&r).unwrap();
2445
        fs::remove_file(s.path_for(&parts[0])).unwrap();
2446
        let e = s.get_change(&r).unwrap_err();
2447
        assert!(
2448
            matches!(&e, StoreError::Corrupt(h, why) if *h == r && why.contains("missing")),
2449
            "{e}"
2450
        );
2451
    }
2452
}
2453
2454
#[cfg(test)]
2455
mod put_many_tests {
2456
    use super::*;
2457
2458
    #[test]
2459
    fn many_objects_in_a_batch_are_compressed_together_and_all_read_back() {
2460
        let dir = tempfile::tempdir().unwrap();
2461
        let s = Store::open(dir.path()).unwrap();
2462
        let before = s.put(ObjectType::Chunk, b"already here").unwrap();
2463
        let bodies: Vec<Vec<u8>> = (0..200u32)
2464
            .map(|i| format!("chunk {i} ").repeat(6000).into_bytes())
2465
            .collect();
2466
        let mut objects: Vec<(ObjectType, &[u8])> = bodies
2467
            .iter()
2468
            .map(|b| (ObjectType::Chunk, b.as_slice()))
2469
            .collect();
2470
        objects.push((ObjectType::Chunk, bodies[0].as_slice()));
2471
        objects.push((ObjectType::Chunk, b"already here"));
2472
        let refs = {
2473
            let batch = s.begin_batch().unwrap();
2474
            let refs = s.put_many(&objects).unwrap();
2475
            batch.finish().unwrap();
2476
            refs
2477
        };
2478
        assert_eq!(refs.len(), objects.len());
2479
        assert_eq!(refs[200], refs[0], "a repeat is the same object");
2480
        assert_eq!(refs[201], before);
2481
        let again = Store::open(dir.path()).unwrap();
2482
        for (r, b) in refs.iter().zip(&objects) {
2483
            assert_eq!(again.get(r).unwrap().1, b.1);
2484
        }
2485
    }
2486
}