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