OXYGENHUB
◆ v0.2.0 oxygen / crates / oxy-core / src / store.rs
77.9 KiB · Rust · last changed gc: a trained zstd dictionary per pack (refs #41) 1 month ago source blame history raw
1
//! Object store (spec §13.1, §13.3, §13.4): loose objects, one file per
2
//! object under `objects/loose/<hh>/<rest>`, and packs, `pack-<id>.pack`
3
//! with a sorted `pack-<id>.idx`, holding zstd-compressed objects. Reads
4
//! check loose objects first, then every pack; every read re-hashes.
5
//!
6
//! Pack file: `OXYPACK1` then entries of
7
//! `type u8 | flags u8 (bit 0: zstd) | stored_len u32 | raw_len u32 | ref 32 | body`.
8
//! Index file: `OXYIDX01` then `count u32` then sorted entries of
9
//! `ref 32 | offset u64 | stored_len u32 | raw_len u32 | type u8 | flags u8`.
10
11
use crate::attest::Attest;
12
use crate::hash::{hash_object, header, ObjectRef, ObjectType};
13
use crate::identity::{Identity, Signature};
14
use crate::objects::{Blob, Change, ObjectError, StateObject};
15
use crate::receipt::Receipt;
16
use rand::RngCore;
17
use std::cell::RefCell;
18
use std::fs;
19
use std::io::{self, Read, Seek, SeekFrom, Write};
20
use std::path::{Path, PathBuf};
21
22
const PACK_MAGIC: &[u8; 8] = b"OXYPACK1";
23
const IDX_MAGIC: &[u8; 8] = b"OXYIDX01";
24
const IDX_ENTRY: usize = 32 + 8 + 4 + 4 + 1 + 1;
25
const FLAG_ZSTD: u8 = 1;
26
/// Compressed with the pack's trained dictionary (`pack-ID.dict`), which a
27
/// full repack makes from a sample of the objects it packs: small files
28
/// share most of their vocabulary, which each one alone cannot use.
29
const FLAG_DICT: u8 = 2;
30
/// The size of a pack's dictionary, and the least a repack must pack for
31
/// one to pay.
32
const DICT_BYTES: usize = 110 << 10;
33
const DICT_MIN_OBJECTS: usize = 1000;
34
/// Objects up to this size are compressed with the dictionary.
35
const DICT_OBJECT_MAX: usize = 64 << 10;
36
const ZSTD_LEVEL: i32 = 3;
37
/// The level of a full repack (`oxy gc`): slower, once, for a smaller store.
38
pub const REPACK_ZSTD_LEVEL: i32 = 9;
39
/// Largest object a pack entry may claim; anything bigger is corruption,
40
/// and refusing it keeps a bad index from driving huge allocations.
41
const MAX_OBJECT_LEN: u32 = 1 << 30;
42
43
/// An object read from the store: its type and body.
44
pub type Object = (ObjectType, Vec<u8>);
45
46
#[derive(Clone, Copy, Debug)]
47
struct PackEntry {
48
    offset: u64,
49
    stored_len: u32,
50
    raw_len: u32,
51
    ty: ObjectType,
52
    flags: u8,
53
}
54
55
/// One pack's index, fully in memory and sorted by ObjectRef.
56
struct PackIndex {
57
    path: PathBuf,
58
    refs: Vec<ObjectRef>,
59
    entries: Vec<PackEntry>,
60
    /// The pack's dictionary, prepared once, when it has one.
61
    dict: Option<std::sync::Arc<zstd::dict::DecoderDictionary<'static>>>,
62
}
63
64
impl std::fmt::Debug for PackIndex {
65
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66
        f.debug_struct("PackIndex")
67
            .field("path", &self.path)
68
            .field("objects", &self.refs.len())
69
            .field("dict", &self.dict.is_some())
70
            .finish()
71
    }
72
}
73
74
impl PackIndex {
75
    fn load(idx_path: &Path, pack_path: &Path) -> Result<PackIndex> {
76
        let data = fs::read(idx_path)?;
77
        let bad =
78
            |m: &str| StoreError::Corrupt(ObjectRef::ZERO, format!("{}: {m}", idx_path.display()));
79
        if data.len() < 12 || &data[..8] != IDX_MAGIC {
80
            return Err(bad("bad index header"));
81
        }
82
        let count = u32::from_le_bytes(data[8..12].try_into().unwrap()) as usize;
83
        if data.len() != 12 + count * IDX_ENTRY {
84
            return Err(bad("index length mismatch"));
85
        }
86
        let pack_len = fs::metadata(pack_path)?.len();
87
        let mut refs = Vec::with_capacity(count);
88
        let mut entries = Vec::with_capacity(count);
89
        for i in 0..count {
90
            let e = &data[12 + i * IDX_ENTRY..12 + (i + 1) * IDX_ENTRY];
91
            let r = ObjectRef::from_slice(&e[..32]).unwrap();
92
            if let Some(prev) = refs.last() {
93
                if r <= *prev {
94
                    return Err(bad("index not sorted"));
95
                }
96
            }
97
            refs.push(r);
98
            let entry = PackEntry {
99
                offset: u64::from_le_bytes(e[32..40].try_into().unwrap()),
100
                stored_len: u32::from_le_bytes(e[40..44].try_into().unwrap()),
101
                raw_len: u32::from_le_bytes(e[44..48].try_into().unwrap()),
102
                ty: ObjectType::ALL
103
                    .get(e[48] as usize)
104
                    .copied()
105
                    .ok_or_else(|| bad("unknown object type"))?,
106
                flags: e[49],
107
            };
108
            if entry.stored_len > MAX_OBJECT_LEN || entry.raw_len > MAX_OBJECT_LEN {
109
                return Err(StoreError::Corrupt(
110
                    r,
111
                    format!(
112
                        "{}: the index claims an object of {} bytes ({} stored), more than the {MAX_OBJECT_LEN} an object may be",
113
                        idx_path.display(),
114
                        entry.raw_len,
115
                        entry.stored_len
116
                    ),
117
                ));
118
            }
119
            if entry.offset.saturating_add(entry.stored_len as u64) > pack_len {
120
                return Err(bad("index entry points outside the pack"));
121
            }
122
            entries.push(entry);
123
        }
124
        let dict = match fs::read(pack_path.with_extension("dict")) {
125
            Ok(d) => Some(std::sync::Arc::new(zstd::dict::DecoderDictionary::copy(&d))),
126
            Err(e) if e.kind() == io::ErrorKind::NotFound => None,
127
            Err(e) => return Err(e.into()),
128
        };
129
        Ok(PackIndex {
130
            path: pack_path.to_path_buf(),
131
            refs,
132
            entries,
133
            dict,
134
        })
135
    }
136
137
    fn find(&self, r: &ObjectRef) -> Option<PackEntry> {
138
        self.refs.binary_search(r).ok().map(|i| self.entries[i])
139
    }
140
141
    fn read(&self, r: &ObjectRef, e: PackEntry) -> Result<(ObjectType, Vec<u8>)> {
142
        let mut f = fs::File::open(&self.path)?;
143
        f.seek(SeekFrom::Start(e.offset))?;
144
        let mut stored = vec![0u8; e.stored_len as usize];
145
        f.read_exact(&mut stored)?;
146
        let body = if e.flags & FLAG_DICT != 0 {
147
            let dict = self.dict.as_ref().ok_or_else(|| {
148
                StoreError::Corrupt(*r, "packed with a dictionary the pack lacks".into())
149
            })?;
150
            zstd::bulk::Decompressor::with_prepared_dictionary(dict)
151
                .and_then(|mut d| d.decompress(&stored, e.raw_len as usize))
152
                .map_err(|err| StoreError::Corrupt(*r, format!("zstd: {err}")))?
153
        } else if e.flags & FLAG_ZSTD != 0 {
154
            zstd::bulk::decompress(&stored, e.raw_len as usize)
155
                .map_err(|err| StoreError::Corrupt(*r, format!("zstd: {err}")))?
156
        } else {
157
            stored
158
        };
159
        if body.len() != e.raw_len as usize || hash_object(e.ty, &body) != *r {
160
            return Err(StoreError::Corrupt(
161
                *r,
162
                "packed object does not match its reference".into(),
163
            ));
164
        }
165
        Ok((e.ty, body))
166
    }
167
}
168
169
fn type_index(ty: ObjectType) -> u8 {
170
    ObjectType::ALL.iter().position(|t| *t == ty).unwrap() as u8
171
}
172
173
/// What `pack_loose` did.
174
#[derive(Debug, Clone, Default, PartialEq, Eq)]
175
pub struct PackReport {
176
    pub objects: usize,
177
    pub raw_bytes: u64,
178
    pub packed_bytes: u64,
179
}
180
181
/// Packs tolerated before `merge_packs` folds them into one (spec §13.4).
182
pub const MAX_PACKS: usize = 16;
183
184
/// What `prune` did.
185
#[derive(Debug, Clone, Default, PartialEq, Eq)]
186
pub struct PruneReport {
187
    pub objects: usize,
188
    pub bytes: u64,
189
    /// Unreachable objects left alone because they are younger than the grace period.
190
    pub deferred: usize,
191
}
192
193
#[derive(Debug, thiserror::Error)]
194
pub enum StoreError {
195
    #[error("io: {0}")]
196
    Io(#[from] io::Error),
197
    #[error("corrupt object {0}: {1}")]
198
    Corrupt(ObjectRef, String),
199
    #[error("object {0}")]
200
    Object(#[from] ObjectError),
201
    #[error("object {0} is a {1}, expected {2}")]
202
    WrongType(ObjectRef, &'static str, &'static str),
203
    #[error("object {0} not found")]
204
    NotFound(ObjectRef),
205
    #[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)")]
206
    TooLarge {
207
        kind: &'static str,
208
        size: usize,
209
        limit: u32,
210
    },
211
}
212
213
pub type Result<T> = std::result::Result<T, StoreError>;
214
215
#[derive(Debug)]
216
pub struct Store {
217
    dir: PathBuf,
218
    packs: RefCell<Vec<PackIndex>>,
219
    /// An open write batch (spec §13.4): objects go here instead of to loose
220
    /// files, and are written out with one `fsync` when the batch finishes.
221
    pending: RefCell<Option<Pending>>,
222
    batch_depth: std::cell::Cell<u32>,
223
    /// Change metadata already read, from the `metas` cache file.
224
    metas: RefCell<Option<crate::fasthash::FastMap<ObjectRef, crate::state::ChangeMeta>>>,
225
}
226
227
/// Objects written since `begin_batch`. Small batches stay in memory and
228
/// become loose objects; once `SPILL_OBJECTS` or `SPILL_BYTES` is exceeded
229
/// the batch streams into a pack file instead.
230
#[derive(Debug)]
231
struct Pending {
232
    buffered: Vec<(ObjectType, Vec<u8>)>,
233
    buffered_bytes: usize,
234
    lookup: std::collections::HashMap<ObjectRef, PendingEntry>,
235
    pack: Option<PendingPack>,
236
    report: PackReport,
237
}
238
239
#[derive(Debug, Clone, Copy)]
240
enum PendingEntry {
241
    Buffered(usize),
242
    Packed(PackEntry),
243
}
244
245
#[derive(Debug)]
246
struct PendingPack {
247
    id: String,
248
    tmp_path: PathBuf,
249
    writer: io::BufWriter<fs::File>,
250
    offset: u64,
251
    index: Vec<(ObjectRef, PackEntry)>,
252
}
253
254
const SPILL_OBJECTS: usize = 256;
255
const SPILL_BYTES: usize = 8 << 20;
256
257
/// Finishes the enclosing batch when dropped; call `finish` to see errors.
258
pub struct Batch<'a> {
259
    store: &'a Store,
260
    done: bool,
261
}
262
263
impl Batch<'_> {
264
    pub fn finish(mut self) -> Result<()> {
265
        self.done = true;
266
        self.store.finish_batch()
267
    }
268
}
269
270
impl Drop for Batch<'_> {
271
    fn drop(&mut self) {
272
        if !self.done {
273
            let _ = self.store.finish_batch();
274
        }
275
    }
276
}
277
278
/// Append one stored object to a pending pack and index it.
279
fn write_pack_entry(
280
    pack: &mut PendingPack,
281
    r: &ObjectRef,
282
    ty: ObjectType,
283
    raw_len: usize,
284
    flags: u8,
285
    stored: &[u8],
286
    report: &mut PackReport,
287
) -> Result<PackEntry> {
288
    let header_len = 1 + 1 + 4 + 4 + 32;
289
    pack.writer.write_all(&[type_index(ty), flags])?;
290
    pack.writer
291
        .write_all(&(stored.len() as u32).to_le_bytes())?;
292
    pack.writer.write_all(&(raw_len as u32).to_le_bytes())?;
293
    pack.writer.write_all(&r.0)?;
294
    pack.writer.write_all(stored)?;
295
    let entry = PackEntry {
296
        offset: pack.offset + header_len,
297
        stored_len: stored.len() as u32,
298
        raw_len: raw_len as u32,
299
        ty,
300
        flags,
301
    };
302
    pack.offset += header_len + stored.len() as u64;
303
    pack.index.push((*r, entry));
304
    report.objects += 1;
305
    report.raw_bytes += raw_len as u64;
306
    report.packed_bytes += stored.len() as u64;
307
    Ok(entry)
308
}
309
310
impl Store {
311
    pub fn open(dir: impl Into<PathBuf>) -> io::Result<Store> {
312
        let dir = dir.into();
313
        fs::create_dir_all(dir.join("loose"))?;
314
        let store = Store {
315
            dir,
316
            packs: RefCell::new(Vec::new()),
317
            pending: RefCell::new(None),
318
            batch_depth: std::cell::Cell::new(0),
319
            metas: RefCell::new(None),
320
        };
321
        store
322
            .reload_packs()
323
            .map_err(|e| io::Error::other(e.to_string()))?;
324
        Ok(store)
325
    }
326
327
    fn reload_packs(&self) -> Result<()> {
328
        let mut packs = Vec::new();
329
        let mut names: Vec<PathBuf> = fs::read_dir(&self.dir)?
330
            .filter_map(|e| e.ok().map(|e| e.path()))
331
            .filter(|p| {
332
                p.extension().is_some_and(|x| x == "idx")
333
                    && p.file_name()
334
                        .is_some_and(|n| n.to_string_lossy().starts_with("pack-"))
335
            })
336
            .collect();
337
        names.sort();
338
        for idx in names {
339
            let pack = idx.with_extension("pack");
340
            if pack.is_file() {
341
                packs.push(PackIndex::load(&idx, &pack)?);
342
            }
343
        }
344
        *self.packs.borrow_mut() = packs;
345
        Ok(())
346
    }
347
348
    pub fn pack_count(&self) -> usize {
349
        self.packs.borrow().len()
350
    }
351
352
    fn find_packed(&self, r: &ObjectRef) -> Option<(usize, PackEntry)> {
353
        self.packs
354
            .borrow()
355
            .iter()
356
            .enumerate()
357
            .find_map(|(i, p)| p.find(r).map(|e| (i, e)))
358
    }
359
360
    /// Loose objects on disk, with their paths.
361
    fn loose_objects(&self) -> io::Result<Vec<(ObjectRef, PathBuf)>> {
362
        let mut out = Vec::new();
363
        let loose = self.dir.join("loose");
364
        for d in fs::read_dir(&loose)? {
365
            let d = d?;
366
            if !d.file_type()?.is_dir() {
367
                continue;
368
            }
369
            let prefix = d.file_name().to_string_lossy().to_string();
370
            for f in fs::read_dir(d.path())? {
371
                let f = f?;
372
                let name = f.file_name().to_string_lossy().to_string();
373
                if let Some(r) = ObjectRef::from_hex(&format!("{prefix}{name}")) {
374
                    out.push((r, f.path()));
375
                }
376
            }
377
        }
378
        out.sort();
379
        Ok(out)
380
    }
381
382
    pub fn loose_count(&self) -> io::Result<usize> {
383
        Ok(self.loose_objects()?.len())
384
    }
385
386
    /// Move every loose object into a new pack (spec §13.4). Loose files are
387
    /// deleted only after the pack and its index are durable.
388
    pub fn pack_loose(&self) -> Result<PackReport> {
389
        let loose = self.loose_objects()?;
390
        self.write_pack(
391
            &loose.iter().map(|(r, _)| *r).collect::<Vec<_>>(),
392
            &loose.iter().map(|(_, p)| p.clone()).collect::<Vec<_>>(),
393
            &[],
394
            ZSTD_LEVEL,
395
        )
396
    }
397
398
    /// Fold every pack and loose object into one pack compressed at
399
    /// `level` (spec §13.4): what an explicit `oxy gc` does, as `git gc`
400
    /// repacks. Returns the report and how many packs were folded in.
401
    pub fn repack_all(&self, level: i32) -> Result<(PackReport, usize)> {
402
        let loose = self.loose_objects()?;
403
        let (mut refs, paths): (Vec<ObjectRef>, Vec<PathBuf>) = {
404
            let packs = self.packs.borrow();
405
            (
406
                packs.iter().flat_map(|p| p.refs.iter().copied()).collect(),
407
                packs.iter().map(|p| p.path.clone()).collect(),
408
            )
409
        };
410
        if loose.is_empty() && paths.len() <= 1 && level == ZSTD_LEVEL {
411
            return Ok((PackReport::default(), 0));
412
        }
413
        refs.extend(loose.iter().map(|(r, _)| *r));
414
        let loose_paths: Vec<PathBuf> = loose.into_iter().map(|(_, p)| p).collect();
415
        let n = paths.len();
416
        let report = self.write_pack(&refs, &loose_paths, &paths, level)?;
417
        Ok((report, n))
418
    }
419
420
    /// Fold every pack into one when there are more than `MAX_PACKS`
421
    /// (spec §13.4). Returns how many packs were merged.
422
    pub fn merge_packs(&self) -> Result<usize> {
423
        let (refs, paths): (Vec<ObjectRef>, Vec<PathBuf>) = {
424
            let packs = self.packs.borrow();
425
            if packs.len() <= MAX_PACKS {
426
                return Ok(0);
427
            }
428
            (
429
                packs.iter().flat_map(|p| p.refs.iter().copied()).collect(),
430
                packs.iter().map(|p| p.path.clone()).collect(),
431
            )
432
        };
433
        let n = paths.len();
434
        self.write_pack(&refs, &[], &paths, ZSTD_LEVEL)?;
435
        Ok(n)
436
    }
437
438
    /// Delete every object not in `keep` (spec §21). Loose objects and packs
439
    /// younger than `grace` are left alone, since a concurrent writer may not
440
    /// have recorded its references yet. Packs holding unreachable objects
441
    /// are rewritten without them. Signature sidecars and seal-index entries
442
    /// of deleted objects go too.
443
    pub fn prune(
444
        &self,
445
        keep: &std::collections::HashSet<ObjectRef>,
446
        grace: std::time::Duration,
447
    ) -> Result<PruneReport> {
448
        let now = std::time::SystemTime::now();
449
        let old_enough = |m: &fs::Metadata| {
450
            m.modified()
451
                .map(|t| now.duration_since(t).unwrap_or_default() >= grace)
452
                .unwrap_or(true)
453
        };
454
        let mut report = PruneReport::default();
455
        // Loose objects.
456
        for (r, path) in self.loose_objects()? {
457
            if keep.contains(&r) {
458
                continue;
459
            }
460
            let meta = fs::metadata(&path)?;
461
            if !old_enough(&meta) {
462
                report.deferred += 1;
463
                continue;
464
            }
465
            report.bytes += meta.len();
466
            report.objects += 1;
467
            fs::remove_file(&path)?;
468
            let _ = fs::remove_dir(path.parent().unwrap());
469
            self.remove_sidecars(&r)?;
470
        }
471
        // Packs: rewrite those that hold unreachable objects.
472
        let mut keep_refs: Vec<ObjectRef> = Vec::new();
473
        let mut old_paths: Vec<PathBuf> = Vec::new();
474
        let mut rewrite = false;
475
        for p in self.packs.borrow().iter() {
476
            let meta = fs::metadata(&p.path)?;
477
            let unreachable = p.refs.iter().filter(|r| !keep.contains(r)).count();
478
            if unreachable == 0 {
479
                continue;
480
            }
481
            if !old_enough(&meta) {
482
                report.deferred += unreachable;
483
                continue;
484
            }
485
            rewrite = true;
486
            old_paths.push(p.path.clone());
487
            for (r, e) in p.refs.iter().zip(p.entries.iter()) {
488
                if keep.contains(r) {
489
                    keep_refs.push(*r);
490
                } else {
491
                    report.objects += 1;
492
                    report.bytes += e.stored_len as u64;
493
                }
494
            }
495
        }
496
        if rewrite {
497
            let dropped: Vec<ObjectRef> = {
498
                let packs = self.packs.borrow();
499
                packs
500
                    .iter()
501
                    .filter(|p| old_paths.contains(&p.path))
502
                    .flat_map(|p| p.refs.iter().copied())
503
                    .filter(|r| !keep.contains(r))
504
                    .collect()
505
            };
506
            self.write_pack(&keep_refs, &[], &old_paths, ZSTD_LEVEL)?;
507
            for r in dropped {
508
                self.remove_sidecars(&r)?;
509
            }
510
        }
511
        Ok(report)
512
    }
513
514
    fn remove_sidecars(&self, r: &ObjectRef) -> Result<()> {
515
        let sidecars = [
516
            self.sig_path(r),
517
            self.index_path("seals", r),
518
            self.index_path("receipts", r),
519
        ];
520
        for path in sidecars {
521
            match fs::remove_file(&path) {
522
                Ok(()) => {
523
                    let _ = fs::remove_dir(path.parent().unwrap());
524
                }
525
                Err(e) if e.kind() == io::ErrorKind::NotFound => {}
526
                Err(e) => return Err(e.into()),
527
            }
528
        }
529
        Ok(())
530
    }
531
532
    /// Write `refs` into a new pack, then delete `loose_paths` and `old_packs`.
533
    /// Write the index for a complete, synced temporary pack file and move
534
    /// both into place; `index` must be sorted by ObjectRef.
535
    fn finish_pack_files(
536
        &self,
537
        id: &str,
538
        tmp_pack: &Path,
539
        index: &[(ObjectRef, PackEntry)],
540
    ) -> Result<()> {
541
        let pack_path = self.dir.join(format!("pack-{id}.pack"));
542
        let idx_path = self.dir.join(format!("pack-{id}.idx"));
543
        let tmp_idx = self.dir.join(format!("tmp-{id}.idx"));
544
        {
545
            let mut f = io::BufWriter::new(fs::File::create(&tmp_idx)?);
546
            f.write_all(IDX_MAGIC)?;
547
            f.write_all(&(index.len() as u32).to_le_bytes())?;
548
            for (r, e) in index {
549
                f.write_all(&r.0)?;
550
                f.write_all(&e.offset.to_le_bytes())?;
551
                f.write_all(&e.stored_len.to_le_bytes())?;
552
                f.write_all(&e.raw_len.to_le_bytes())?;
553
                f.write_all(&[type_index(e.ty), e.flags])?;
554
            }
555
            f.flush()?;
556
            f.get_ref().sync_all()?;
557
        }
558
        // The pack first: an index never names a pack that is not there.
559
        crate::durable::rename(tmp_pack, &pack_path)?;
560
        crate::durable::rename(&tmp_idx, &idx_path)?;
561
        self.reload_packs()
562
    }
563
564
    fn write_pack(
565
        &self,
566
        refs: &[ObjectRef],
567
        loose_paths: &[PathBuf],
568
        old_packs: &[PathBuf],
569
        level: i32,
570
    ) -> Result<PackReport> {
571
        if refs.is_empty() {
572
            for p in old_packs {
573
                remove_pack_files(p)?;
574
            }
575
            self.reload_packs()?;
576
            return Ok(PackReport::default());
577
        }
578
        let mut refs: Vec<ObjectRef> = refs.to_vec();
579
        refs.sort();
580
        refs.dedup();
581
        let mut nonce = [0u8; 8];
582
        rand::rngs::OsRng.fill_bytes(&mut nonce);
583
        let id = hex::encode(nonce);
584
        let tmp_pack = self.dir.join(format!("tmp-{id}.pack"));
585
        let mut report = PackReport::default();
586
        let mut index: Vec<(ObjectRef, PackEntry)> = Vec::with_capacity(refs.len());
587
        // A full repack of enough objects trains a dictionary for them.
588
        let dict = if level == REPACK_ZSTD_LEVEL && refs.len() >= DICT_MIN_OBJECTS {
589
            let _t = crate::timing::phase("pack: train a dictionary");
590
            self.train_dictionary(&refs)
591
        } else {
592
            None
593
        };
594
        let encoder = dict
595
            .as_ref()
596
            .map(|d| zstd::dict::EncoderDictionary::copy(d, level));
597
        {
598
            let mut f = io::BufWriter::new(fs::File::create(&tmp_pack)?);
599
            f.write_all(PACK_MAGIC)?;
600
            let mut offset = PACK_MAGIC.len() as u64;
601
            // Read a batch (the store is not shared between threads),
602
            // compress it on every core, write it in order.
603
            let mut batches = refs.chunks(1024);
604
            let mut compressed_batch = Vec::new();
605
            loop {
606
                if compressed_batch.is_empty() {
607
                    let Some(batch) = batches.next() else { break };
608
                    let mut read: Vec<(ObjectRef, ObjectType, Vec<u8>, bool)> =
609
                        Vec::with_capacity(batch.len());
610
                    for r in batch {
611
                        let (ty, body) = self.get(r)?;
612
                        read.push((*r, ty, body, self.is_nocompress(r)));
613
                    }
614
                    use rayon::prelude::*;
615
                    compressed_batch = read
616
                        .into_par_iter()
617
                        .map_init(
618
                            || {
619
                                encoder.as_ref().and_then(|e| {
620
                                    zstd::bulk::Compressor::with_prepared_dictionary(e).ok()
621
                                })
622
                            },
623
                            |with_dict, (r, ty, body, raw)| {
624
                                let packed = if raw {
625
                                    None
626
                                } else {
627
                                    // Small objects with the dictionary;
628
                                    // a large one has context enough.
629
                                    let dicted = with_dict
630
                                        .as_mut()
631
                                        .filter(|_| body.len() <= DICT_OBJECT_MAX)
632
                                        .and_then(|c| c.compress(&body).ok())
633
                                        .map(|c| (FLAG_ZSTD | FLAG_DICT, c));
634
                                    dicted
635
                                        .or_else(|| {
636
                                            zstd::bulk::compress(&body, level)
637
                                                .ok()
638
                                                .map(|c| (FLAG_ZSTD, c))
639
                                        })
640
                                        .filter(|(_, c)| c.len() < body.len())
641
                                };
642
                                (r, ty, body, packed)
643
                            },
644
                        )
645
                        .collect::<Vec<_>>();
646
                    compressed_batch.reverse();
647
                }
648
                let Some((r, ty, body, packed)) = compressed_batch.pop() else {
649
                    continue;
650
                };
651
                let r = &r;
652
                let (flags, stored) = match packed {
653
                    Some(c) => c,
654
                    None => (0, body.clone()),
655
                };
656
                let header_len = 1 + 1 + 4 + 4 + 32;
657
                f.write_all(&[type_index(ty), flags])?;
658
                f.write_all(&(stored.len() as u32).to_le_bytes())?;
659
                f.write_all(&(body.len() as u32).to_le_bytes())?;
660
                f.write_all(&r.0)?;
661
                f.write_all(&stored)?;
662
                index.push((
663
                    *r,
664
                    PackEntry {
665
                        offset: offset + header_len,
666
                        stored_len: stored.len() as u32,
667
                        raw_len: body.len() as u32,
668
                        ty,
669
                        flags,
670
                    },
671
                ));
672
                offset += header_len + stored.len() as u64;
673
                report.objects += 1;
674
                report.raw_bytes += body.len() as u64;
675
                report.packed_bytes += stored.len() as u64;
676
            }
677
            f.flush()?;
678
            f.get_ref().sync_all()?;
679
        }
680
        // The dictionary before the pack that needs it becomes visible.
681
        if let Some(d) = &dict {
682
            crate::durable::write_atomic(&self.dir.join(format!("pack-{id}.dict")), d)?;
683
        }
684
        self.finish_pack_files(&id, &tmp_pack, &index)?;
685
        for p in old_packs {
686
            remove_pack_files(p)?;
687
        }
688
        self.reload_packs()?;
689
        for path in loose_paths {
690
            fs::remove_file(path)?;
691
            if let Some(dir) = path.parent() {
692
                let _ = fs::remove_dir(dir);
693
            }
694
        }
695
        Ok(report)
696
    }
697
698
    /// A dictionary for these objects, trained on a sample of them (at
699
    /// most 10 000, 32 MB); `None` when training fails.
700
    fn train_dictionary(&self, refs: &[ObjectRef]) -> Option<Vec<u8>> {
701
        let step = (refs.len() / 10_000).max(1);
702
        let mut samples: Vec<Vec<u8>> = Vec::new();
703
        let mut total = 0usize;
704
        for r in refs.iter().step_by(step) {
705
            if total > 32 << 20 {
706
                break;
707
            }
708
            let Ok((ty, body)) = self.get(r) else {
709
                continue;
710
            };
711
            if matches!(
712
                ty,
713
                ObjectType::Chunk | ObjectType::Blob | ObjectType::Change
714
            ) && !body.is_empty()
715
                && body.len() < 1 << 20
716
            {
717
                total += body.len();
718
                samples.push(body);
719
            }
720
        }
721
        zstd::dict::from_samples(&samples, DICT_BYTES).ok()
722
    }
723
724
    pub fn dir(&self) -> &Path {
725
        &self.dir
726
    }
727
728
    pub(crate) fn path_for(&self, r: &ObjectRef) -> PathBuf {
729
        let h = r.to_hex();
730
        self.dir.join("loose").join(&h[..2]).join(&h[2..])
731
    }
732
733
    pub fn has(&self, r: &ObjectRef) -> bool {
734
        self.path_for(r).is_file()
735
            || self.find_packed(r).is_some()
736
            || self
737
                .pending
738
                .borrow()
739
                .as_ref()
740
                .is_some_and(|p| p.lookup.contains_key(r))
741
    }
742
743
    /// Start a write batch: until the matching `finish`, `put` collects
744
    /// objects and writes them out together, with one `fsync` for a large
745
    /// batch (a pack) instead of one per object. Batches nest; only the
746
    /// outermost does the work. Objects are readable while pending.
747
    pub fn begin_batch(&self) -> Result<Batch<'_>> {
748
        let depth = self.batch_depth.get();
749
        if depth == 0 {
750
            *self.pending.borrow_mut() = Some(Pending {
751
                buffered: vec![],
752
                buffered_bytes: 0,
753
                lookup: Default::default(),
754
                pack: None,
755
                report: PackReport::default(),
756
            });
757
        }
758
        self.batch_depth.set(depth + 1);
759
        Ok(Batch {
760
            store: self,
761
            done: false,
762
        })
763
    }
764
765
    fn finish_batch(&self) -> Result<()> {
766
        let depth = self.batch_depth.get();
767
        if depth == 0 {
768
            return Ok(());
769
        }
770
        self.batch_depth.set(depth - 1);
771
        if depth > 1 {
772
            return Ok(());
773
        }
774
        let Some(pending) = self.pending.borrow_mut().take() else {
775
            return Ok(());
776
        };
777
        self.write_pending(pending)
778
    }
779
780
    /// Make every object written so far durable, even inside an open
781
    /// batch, which stays open. Call before a reference that names them
782
    /// is moved (spec §13.6): the operation head, a bookmark pointer.
783
    pub fn flush(&self) -> Result<()> {
784
        let Some(pending) = self.pending.borrow_mut().take() else {
785
            return Ok(());
786
        };
787
        self.write_pending(pending)?;
788
        *self.pending.borrow_mut() = Some(Pending {
789
            buffered: vec![],
790
            buffered_bytes: 0,
791
            lookup: Default::default(),
792
            pack: None,
793
            report: PackReport::default(),
794
        });
795
        Ok(())
796
    }
797
798
    fn write_pending(&self, pending: Pending) -> Result<()> {
799
        match pending.pack {
800
            None => {
801
                for (ty, body) in &pending.buffered {
802
                    self.put_loose(*ty, body)?;
803
                }
804
                Ok(())
805
            }
806
            Some(mut pack) => {
807
                pack.writer.flush()?;
808
                pack.writer.get_ref().sync_all()?;
809
                drop(pack.writer);
810
                pack.index.sort_by_key(|(r, _)| *r);
811
                self.finish_pack_files(&pack.id, &pack.tmp_path, &pack.index)?;
812
                Ok(())
813
            }
814
        }
815
    }
816
817
    /// Whether a batch is open and holds `r`.
818
    fn pending_get(&self, r: &ObjectRef) -> Option<Result<(ObjectType, Vec<u8>)>> {
819
        let mut guard = self.pending.borrow_mut();
820
        let pending = guard.as_mut()?;
821
        let entry = *pending.lookup.get(r)?;
822
        Some(match entry {
823
            PendingEntry::Buffered(i) => {
824
                let (ty, body) = &pending.buffered[i];
825
                Ok((*ty, body.clone()))
826
            }
827
            PendingEntry::Packed(e) => {
828
                let Some(pack) = pending.pack.as_mut() else {
829
                    return Some(Err(StoreError::NotFound(*r)));
830
                };
831
                match pack.writer.flush() {
832
                    Ok(()) => PackIndex {
833
                        path: pack.tmp_path.clone(),
834
                        refs: vec![],
835
                        entries: vec![],
836
                        dict: None,
837
                    }
838
                    .read(r, e),
839
                    Err(err) => Err(err.into()),
840
                }
841
            }
842
        })
843
    }
844
845
    /// Append one object to the pending pack file.
846
    fn pending_pack_write(
847
        &self,
848
        pack: &mut PendingPack,
849
        r: &ObjectRef,
850
        ty: ObjectType,
851
        body: &[u8],
852
        report: &mut PackReport,
853
    ) -> Result<PackEntry> {
854
        let (flags, stored) = if self.is_nocompress(r) {
855
            (0, body.to_vec())
856
        } else {
857
            let compressed = zstd::bulk::compress(body, ZSTD_LEVEL)
858
                .map_err(|e| StoreError::Corrupt(*r, format!("zstd: {e}")))?;
859
            if compressed.len() < body.len() {
860
                (FLAG_ZSTD, compressed)
861
            } else {
862
                (0, body.to_vec())
863
            }
864
        };
865
        write_pack_entry(pack, r, ty, body.len(), flags, &stored, report)
866
    }
867
868
    fn put_pending(&self, r: ObjectRef, ty: ObjectType, body: &[u8]) -> Result<()> {
869
        let mut guard = self.pending.borrow_mut();
870
        let pending = guard.as_mut().expect("batch open");
871
        if pending.lookup.contains_key(&r) {
872
            return Ok(());
873
        }
874
        if pending.pack.is_none()
875
            && pending.buffered.len() < SPILL_OBJECTS
876
            && pending.buffered_bytes + body.len() <= SPILL_BYTES
877
        {
878
            pending.buffered.push((ty, body.to_vec()));
879
            pending.buffered_bytes += body.len();
880
            pending
881
                .lookup
882
                .insert(r, PendingEntry::Buffered(pending.buffered.len() - 1));
883
            return Ok(());
884
        }
885
        self.ensure_pack(pending)?;
886
        let mut report = std::mem::take(&mut pending.report);
887
        let pack = pending.pack.as_mut().unwrap();
888
        let e = self.pending_pack_write(pack, &r, ty, body, &mut report)?;
889
        pending.report = report;
890
        pending.lookup.insert(r, PendingEntry::Packed(e));
891
        Ok(())
892
    }
893
894
    /// Open the pending batch's pack, moving the objects buffered so far
895
    /// into it (a spill).
896
    fn ensure_pack(&self, pending: &mut Pending) -> Result<()> {
897
        if pending.pack.is_none() {
898
            // Spill: open the pack and move the buffered objects into it.
899
            let mut nonce = [0u8; 8];
900
            rand::rngs::OsRng.fill_bytes(&mut nonce);
901
            let id = hex::encode(nonce);
902
            let tmp_path = self.dir.join(format!("tmp-{id}.pack"));
903
            let mut writer = io::BufWriter::new(fs::File::create(&tmp_path)?);
904
            writer.write_all(PACK_MAGIC)?;
905
            let mut pack = PendingPack {
906
                id,
907
                tmp_path,
908
                writer,
909
                offset: PACK_MAGIC.len() as u64,
910
                index: vec![],
911
            };
912
            let buffered = std::mem::take(&mut pending.buffered);
913
            pending.buffered_bytes = 0;
914
            let mut report = std::mem::take(&mut pending.report);
915
            for (bty, bbody) in &buffered {
916
                let br = hash_object(*bty, bbody);
917
                let e = self.pending_pack_write(&mut pack, &br, *bty, bbody, &mut report)?;
918
                pending.lookup.insert(br, PendingEntry::Packed(e));
919
            }
920
            pending.report = report;
921
            pending.pack = Some(pack);
922
        }
923
        Ok(())
924
    }
925
926
    /// Store many objects at once. Inside a large write batch they are
927
    /// compressed on every core and appended in order; otherwise each is
928
    /// stored as [`Store::put`] does.
929
    pub fn put_many(&self, objects: &[(ObjectType, &[u8])]) -> Result<Vec<ObjectRef>> {
930
        use rayon::prelude::*;
931
        let total: usize = objects.iter().map(|(_, b)| b.len()).sum();
932
        if self.pending.borrow().is_none() || total < SPILL_BYTES {
933
            return objects.iter().map(|(ty, b)| self.put(*ty, b)).collect();
934
        }
935
        for (ty, b) in objects {
936
            if b.len() > MAX_OBJECT_LEN as usize {
937
                return Err(StoreError::TooLarge {
938
                    kind: ty.name(),
939
                    size: b.len(),
940
                    limit: MAX_OBJECT_LEN,
941
                });
942
            }
943
        }
944
        let refs: Vec<ObjectRef> = objects
945
            .par_iter()
946
            .map(|(ty, b)| hash_object(*ty, b))
947
            .collect();
948
        // What is new: not stored already, not earlier in this call.
949
        let mut seen: std::collections::HashSet<ObjectRef> = std::collections::HashSet::new();
950
        let mut todo: Vec<usize> = Vec::new();
951
        for (i, r) in refs.iter().enumerate() {
952
            let known = self
953
                .pending
954
                .borrow()
955
                .as_ref()
956
                .is_some_and(|p| p.lookup.contains_key(r));
957
            if seen.insert(*r)
958
                && !known
959
                && !self.path_for(r).is_file()
960
                && self.find_packed(r).is_none()
961
            {
962
                todo.push(i);
963
            }
964
        }
965
        let raw: std::collections::HashSet<ObjectRef> =
966
            match fs::read_dir(self.dir.join("nocompress")) {
967
                Ok(rd) => rd
968
                    .flatten()
969
                    .filter_map(|e| ObjectRef::from_hex(&e.file_name().to_string_lossy()))
970
                    .collect(),
971
                Err(_) => std::collections::HashSet::new(),
972
            };
973
        let packed: Vec<(u8, Vec<u8>)> = todo
974
            .par_iter()
975
            .map(|i| {
976
                let body = objects[*i].1;
977
                if raw.contains(&refs[*i]) {
978
                    return (0, body.to_vec());
979
                }
980
                match zstd::bulk::compress(body, ZSTD_LEVEL) {
981
                    Ok(c) if c.len() < body.len() => (FLAG_ZSTD, c),
982
                    _ => (0, body.to_vec()),
983
                }
984
            })
985
            .collect();
986
        let mut guard = self.pending.borrow_mut();
987
        let pending = guard.as_mut().expect("batch open");
988
        self.ensure_pack(pending)?;
989
        let mut report = std::mem::take(&mut pending.report);
990
        let pack = pending.pack.as_mut().unwrap();
991
        for (i, (flags, stored)) in todo.iter().zip(packed) {
992
            let (ty, body) = objects[*i];
993
            let e = write_pack_entry(pack, &refs[*i], ty, body.len(), flags, &stored, &mut report)?;
994
            pending.lookup.insert(refs[*i], PendingEntry::Packed(e));
995
        }
996
        pending.report = report;
997
        Ok(refs)
998
    }
999
1000
    /// Store `body` as an object of type `ty`; idempotent.
1001
    pub fn put(&self, ty: ObjectType, body: &[u8]) -> Result<ObjectRef> {
1002
        // Refuse what the store could not read back (spec §13.2), before
1003
        // anything is written: a pack must never hold an entry its index
1004
        // would reject.
1005
        if body.len() > MAX_OBJECT_LEN as usize {
1006
            return Err(StoreError::TooLarge {
1007
                kind: ty.name(),
1008
                size: body.len(),
1009
                limit: MAX_OBJECT_LEN,
1010
            });
1011
        }
1012
        let r = hash_object(ty, body);
1013
        let path = self.path_for(&r);
1014
        if path.is_file() || self.find_packed(&r).is_some() {
1015
            return Ok(r);
1016
        }
1017
        if self.pending.borrow().is_some() {
1018
            self.put_pending(r, ty, body)?;
1019
            return Ok(r);
1020
        }
1021
        self.put_loose(ty, body)?;
1022
        Ok(r)
1023
    }
1024
1025
    /// Write one loose object atomically with its own `fsync`.
1026
    fn put_loose(&self, ty: ObjectType, body: &[u8]) -> Result<ObjectRef> {
1027
        let r = hash_object(ty, body);
1028
        let path = self.path_for(&r);
1029
        if path.is_file() {
1030
            return Ok(r);
1031
        }
1032
        let fanout = path.parent().unwrap();
1033
        if !fanout.is_dir() {
1034
            fs::create_dir_all(fanout)?;
1035
            crate::durable::sync_dir(&self.dir.join("loose"))?;
1036
        }
1037
        let mut nonce = [0u8; 8];
1038
        rand::rngs::OsRng.fill_bytes(&mut nonce);
1039
        let tmp = self
1040
            .dir
1041
            .join("loose")
1042
            .join(format!("tmp-{}", hex::encode(nonce)));
1043
        crate::durable::step("write loose object")?;
1044
        {
1045
            let mut f = fs::File::create(&tmp)?;
1046
            f.write_all(&header(ty, body.len()))?;
1047
            f.write_all(body)?;
1048
            f.sync_all()?;
1049
        }
1050
        crate::durable::rename(&tmp, &path)?;
1051
        Ok(r)
1052
    }
1053
1054
    /// Read and verify an object, loose, packed, or pending in a batch.
1055
    pub fn get(&self, r: &ObjectRef) -> Result<(ObjectType, Vec<u8>)> {
1056
        match read_loose_at(&self.path_for(r), r) {
1057
            Some(found) => found,
1058
            None => match self.find_packed(r) {
1059
                Some((i, e)) => self.packs.borrow()[i].read(r, e),
1060
                None => self.pending_get(r).unwrap_or(Err(StoreError::NotFound(*r))),
1061
            },
1062
        }
1063
    }
1064
1065
    /// Many objects at once: loose ones are read and verified in parallel,
1066
    /// the rest (packed, or pending in a batch) one by one. Results are in
1067
    /// the order of `refs`.
1068
    pub fn get_many(&self, refs: &[ObjectRef]) -> Vec<Result<Object>> {
1069
        use rayon::prelude::*;
1070
        let paths: Vec<(ObjectRef, PathBuf)> =
1071
            refs.iter().map(|r| (*r, self.path_for(r))).collect();
1072
        let mut found: Vec<Option<Result<Object>>> =
1073
            paths.par_iter().map(|(r, p)| read_loose_at(p, r)).collect();
1074
        // Packed ones: look them up in order, then read them in parallel.
1075
        let packs = self.packs.borrow();
1076
        let packed: Vec<(usize, usize, PackEntry)> = found
1077
            .iter()
1078
            .enumerate()
1079
            .filter(|(_, f)| f.is_none())
1080
            .filter_map(|(i, _)| {
1081
                packs
1082
                    .iter()
1083
                    .enumerate()
1084
                    .find_map(|(p, pack)| pack.find(&refs[i]).map(|e| (i, p, e)))
1085
            })
1086
            .collect();
1087
        let indexes: &[PackIndex] = &packs;
1088
        let read: Vec<(usize, Result<Object>)> = packed
1089
            .par_iter()
1090
            .map(|(i, p, e)| (*i, indexes[*p].read(&refs[*i], *e)))
1091
            .collect();
1092
        drop(packs);
1093
        for (i, r) in read {
1094
            found[i] = Some(r);
1095
        }
1096
        found
1097
            .into_iter()
1098
            .zip(refs)
1099
            .map(|(f, r)| match f {
1100
                Some(f) => f,
1101
                None => self.get(r),
1102
            })
1103
            .collect()
1104
    }
1105
1106
    pub fn get_typed(&self, r: &ObjectRef, want: ObjectType) -> Result<Vec<u8>> {
1107
        let (ty, body) = self.get(r)?;
1108
        if ty != want {
1109
            return Err(StoreError::WrongType(*r, ty.name(), want.name()));
1110
        }
1111
        Ok(body)
1112
    }
1113
1114
    /// Store a change and the text blobs (and their chunks) its large
1115
    /// inserts are stored as (spec §6.1).
1116
    pub fn put_change(&self, c: &Change) -> Result<ObjectRef> {
1117
        let bytes = c.encode_streaming(|batch| self.put_texts(&batch))?;
1118
        self.put(ObjectType::Change, &bytes)
1119
    }
1120
1121
    /// Store text blobs and their chunks: every chunk at once (compressed
1122
    /// on every core in a large batch), then the blobs.
1123
    pub fn put_texts(&self, texts: &[crate::objects::StoredText]) -> Result<()> {
1124
        let mut chunks: Vec<(ObjectType, &[u8])> = Vec::new();
1125
        for t in texts {
1126
            if !self.has(&t.blob.hash()) {
1127
                chunks.extend(
1128
                    crate::chunk::chunks(&t.content)
1129
                        .into_iter()
1130
                        .map(|c| (ObjectType::Chunk, c)),
1131
                );
1132
            }
1133
        }
1134
        self.put_many(&chunks)?;
1135
        for t in texts {
1136
            self.put(ObjectType::Blob, &t.blob.encode())?;
1137
        }
1138
        Ok(())
1139
    }
1140
1141
    pub fn get_change(&self, r: &ObjectRef) -> Result<Change> {
1142
        Ok(self.get_change_parts(r)?.0)
1143
    }
1144
1145
    /// A change and the objects its stored inserts are made of: each text
1146
    /// blob and its chunks, which travel and are kept with it.
1147
    pub fn get_change_parts(&self, r: &ObjectRef) -> Result<(Change, Vec<ObjectRef>)> {
1148
        let bytes = self.get_typed(r, ObjectType::Change)?;
1149
        let mut parts = Vec::new();
1150
        let mut failed = None;
1151
        let decoded = Change::decode_with(&bytes, &mut |text, count, form| match self
1152
            .read_text(text)
1153
        {
1154
            Ok((blob, content)) => {
1155
                parts.push(*text);
1156
                parts.extend(blob.chunks);
1157
                crate::objects::text_lines(&content, count, form)
1158
            }
1159
            Err(e) => {
1160
                let why = e.to_string();
1161
                failed = Some(e);
1162
                Err(ObjectError::Schema(format!(
1163
                    "text blob {}: {why}",
1164
                    text.short(12)
1165
                )))
1166
            }
1167
        });
1168
        match (decoded, failed) {
1169
            (Ok(c), _) => Ok((c, parts)),
1170
            (Err(_), Some(StoreError::NotFound(t))) => Err(StoreError::Corrupt(
1171
                *r,
1172
                format!("its text blob {} is missing", t.short(12)),
1173
            )),
1174
            (Err(e), _) => Err(StoreError::Corrupt(*r, e.to_string())),
1175
        }
1176
    }
1177
1178
    /// A change with every insert left without its lines (empty
1179
    /// placeholders), and where each one's lines are, in order: for
1180
    /// history-only states, which read text only for the graphs they build
1181
    /// (see [`Change::decode_skeleton`]).
1182
    pub fn get_change_lazy(&self, r: &ObjectRef) -> Result<(Change, Vec<crate::objects::TextRef>)> {
1183
        let bytes = self.get_typed(r, ObjectType::Change)?;
1184
        Change::decode_skeleton(&bytes, *r).map_err(|e| StoreError::Corrupt(*r, e.to_string()))
1185
    }
1186
1187
    /// A change's metadata (id, dependencies, author, clock, message, kind)
1188
    /// without its contents: read from its skeleton, so neither its text
1189
    /// blobs nor its inline lines are read (spec §11).
1190
    ///
1191
    /// Served from the `metas` cache when this store read it before (a
1192
    /// change object can be as large as the tree it adds), as long as the
1193
    /// store still has the change.
1194
    pub fn get_change_meta(&self, r: &ObjectRef) -> Result<crate::state::ChangeMeta> {
1195
        if self.metas.borrow().is_none() {
1196
            *self.metas.borrow_mut() = Some(self.read_metas_cache());
1197
        }
1198
        let cached = self.metas.borrow().as_ref().and_then(|m| m.get(r).cloned());
1199
        if let Some(meta) = cached {
1200
            if self.has(r) {
1201
                #[cfg(test)]
1202
                assert_eq!(
1203
                    meta,
1204
                    Change::decode_meta(&self.get_typed(r, ObjectType::Change)?).unwrap(),
1205
                    "the metadata cache holds a change's metadata"
1206
                );
1207
                return Ok(meta);
1208
            }
1209
        }
1210
        let bytes = self.get_typed(r, ObjectType::Change)?;
1211
        let meta =
1212
            Change::decode_meta(&bytes).map_err(|e| StoreError::Corrupt(*r, e.to_string()))?;
1213
        self.remember_meta(r, &meta);
1214
        Ok(meta)
1215
    }
1216
1217
    /// The metadata cache: records of a change hash, its metadata in the
1218
    /// flat layout, and the first 8 bytes of BLAKE3 over both, each
1219
    /// appended in one write. Derived only: a record that does not check
1220
    /// ends the reading (a torn write), and the cache can be deleted.
1221
    fn read_metas_cache(&self) -> crate::fasthash::FastMap<ObjectRef, crate::state::ChangeMeta> {
1222
        let mut out = crate::fasthash::FastMap::default();
1223
        let Ok(bytes) = fs::read(self.dir.join("metas")) else {
1224
            return out;
1225
        };
1226
        let mut r = crate::flat::Reader::new(&bytes);
1227
        let mut good = 0;
1228
        while !r.at_end() {
1229
            let mut record = || -> std::result::Result<_, ObjectError> {
1230
                let h = r.object()?;
1231
                let body = r.bytes()?;
1232
                let check = r.fixed::<8>()?;
1233
                Ok((h, body, check))
1234
            };
1235
            let Ok((h, body, check)) = record() else {
1236
                break;
1237
            };
1238
            let mut sum = blake3::Hasher::new();
1239
            sum.update(&h.0).update(body);
1240
            if sum.finalize().as_bytes()[..8] != check {
1241
                break;
1242
            }
1243
            match crate::state::ChangeMeta::read_flat(&mut crate::flat::Reader::new(body)) {
1244
                Ok(m) => out.insert(h, m),
1245
                Err(_) => break,
1246
            };
1247
            good += 32 + 4 + body.len() + 8;
1248
        }
1249
        // Cut a bad tail, so records appended later are read.
1250
        if good < bytes.len() {
1251
            let _ = fs::OpenOptions::new()
1252
                .write(true)
1253
                .open(self.dir.join("metas"))
1254
                .and_then(|f| f.set_len(good as u64));
1255
        }
1256
        out
1257
    }
1258
1259
    /// Add a change's metadata to the cache; quietly nothing when it
1260
    /// cannot be written (it is only a cache).
1261
    fn remember_meta(&self, r: &ObjectRef, meta: &crate::state::ChangeMeta) {
1262
        let mut body = crate::flat::Writer::default();
1263
        meta.write_flat(&mut body);
1264
        let mut w = crate::flat::Writer::default();
1265
        w.object(r);
1266
        w.bytes(&body.0);
1267
        let mut sum = blake3::Hasher::new();
1268
        sum.update(&r.0).update(&body.0);
1269
        w.fixed(&sum.finalize().as_bytes()[..8]);
1270
        let _ = fs::OpenOptions::new()
1271
            .create(true)
1272
            .append(true)
1273
            .open(self.dir.join("metas"))
1274
            .and_then(|mut f| f.write_all(&w.0));
1275
        if let Some(m) = self.metas.borrow_mut().as_mut() {
1276
            m.insert(*r, meta.clone());
1277
        }
1278
    }
1279
1280
    fn read_text(&self, r: &ObjectRef) -> Result<(Blob, Vec<u8>)> {
1281
        let blob = Blob::decode(&self.get_typed(r, ObjectType::Blob)?)?;
1282
        let mut content = Vec::with_capacity(blob.length as usize);
1283
        for c in &blob.chunks {
1284
            content.extend(self.get_typed(c, ObjectType::Chunk)?);
1285
        }
1286
        Ok((blob, content))
1287
    }
1288
1289
    pub fn put_chunk(&self, bytes: &[u8]) -> Result<ObjectRef> {
1290
        self.put(ObjectType::Chunk, bytes)
1291
    }
1292
1293
    /// Store a chunk that packs will keep uncompressed (`nocompress`, spec §13.3).
1294
    pub fn put_chunk_nocompress(&self, bytes: &[u8]) -> Result<ObjectRef> {
1295
        let r = hash_object(ObjectType::Chunk, bytes);
1296
        let dir = self.dir.join("nocompress");
1297
        fs::create_dir_all(&dir)?;
1298
        let _ = fs::File::create(dir.join(r.to_hex()));
1299
        self.put(ObjectType::Chunk, bytes)
1300
    }
1301
1302
    fn is_nocompress(&self, r: &ObjectRef) -> bool {
1303
        self.dir.join("nocompress").join(r.to_hex()).exists()
1304
    }
1305
1306
    pub fn put_state(&self, st: &StateObject) -> Result<ObjectRef> {
1307
        self.put(ObjectType::State, &st.encode())
1308
    }
1309
1310
    pub fn get_state(&self, r: &ObjectRef) -> Result<StateObject> {
1311
        Ok(StateObject::decode(&self.get_typed(r, ObjectType::State)?)?)
1312
    }
1313
1314
    pub fn put_attest(&self, a: &Attest) -> Result<ObjectRef> {
1315
        self.put(ObjectType::Attest, &a.encode())
1316
    }
1317
1318
    pub fn get_attest(&self, r: &ObjectRef) -> Result<Attest> {
1319
        Ok(Attest::decode(&self.get_typed(r, ObjectType::Attest)?)?)
1320
    }
1321
1322
    pub fn put_receipt(&self, r: &Receipt) -> Result<ObjectRef> {
1323
        self.put(ObjectType::Receipt, &r.encode())
1324
    }
1325
1326
    pub fn get_receipt(&self, r: &ObjectRef) -> Result<Receipt> {
1327
        Ok(Receipt::decode(&self.get_typed(r, ObjectType::Receipt)?)?)
1328
    }
1329
1330
    fn index_path(&self, index: &str, key: &ObjectRef) -> PathBuf {
1331
        let h = key.to_hex();
1332
        self.dir.join(index).join(&h[..2]).join(&h[2..])
1333
    }
1334
1335
    /// Add `value` to the sorted list kept for `key` in `index`.
1336
    fn index_add(&self, index: &str, key: &ObjectRef, value: &ObjectRef) -> Result<()> {
1337
        let mut values = self.index_get(index, key)?;
1338
        if values.contains(value) {
1339
            return Ok(());
1340
        }
1341
        values.push(*value);
1342
        values.sort();
1343
        let path = self.index_path(index, key);
1344
        fs::create_dir_all(path.parent().unwrap())?;
1345
        let text: String = values.iter().map(|s| format!("{}\n", s.to_hex())).collect();
1346
        crate::durable::write_atomic(&path, text.as_bytes())?;
1347
        Ok(())
1348
    }
1349
1350
    fn index_get(&self, index: &str, key: &ObjectRef) -> Result<Vec<ObjectRef>> {
1351
        match fs::read_to_string(self.index_path(index, key)) {
1352
            Ok(t) => Ok(t.lines().filter_map(ObjectRef::from_hex).collect()),
1353
            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(vec![]),
1354
            Err(e) => Err(e.into()),
1355
        }
1356
    }
1357
1358
    /// Record that seal attestation `attest` covers `change`.
1359
    pub fn index_seal(&self, change: &ObjectRef, attest: &ObjectRef) -> Result<()> {
1360
        self.index_add("seals", change, attest)
1361
    }
1362
1363
    /// Seal attestations known to cover `change`.
1364
    pub fn seals_for(&self, change: &ObjectRef) -> Result<Vec<ObjectRef>> {
1365
        self.index_get("seals", change)
1366
    }
1367
1368
    /// Record receipt attestation `attest` for `state` (spec §14.6).
1369
    pub fn index_receipt(&self, state: &ObjectRef, attest: &ObjectRef) -> Result<()> {
1370
        self.index_add("receipts", state, attest)
1371
    }
1372
1373
    /// Receipt attestations recorded for `state`.
1374
    pub fn receipts_for(&self, state: &ObjectRef) -> Result<Vec<ObjectRef>> {
1375
        self.index_get("receipts", state)
1376
    }
1377
1378
    /// Every state with a receipt, for garbage collection.
1379
    pub fn receipt_states(&self) -> Result<Vec<ObjectRef>> {
1380
        let mut out = Vec::new();
1381
        let dir = self.dir.join("receipts");
1382
        let top = match fs::read_dir(&dir) {
1383
            Ok(d) => d,
1384
            Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(out),
1385
            Err(e) => return Err(e.into()),
1386
        };
1387
        for d in top {
1388
            let d = d?;
1389
            let prefix = d.file_name().to_string_lossy().into_owned();
1390
            for f in fs::read_dir(d.path())? {
1391
                let name = f?.file_name().to_string_lossy().into_owned();
1392
                if let Some(r) = ObjectRef::from_hex(&format!("{prefix}{name}")) {
1393
                    out.push(r);
1394
                }
1395
            }
1396
        }
1397
        out.sort();
1398
        Ok(out)
1399
    }
1400
1401
    pub fn put_identity(&self, id: &Identity) -> Result<ObjectRef> {
1402
        self.put(ObjectType::Identity, &id.encode())
1403
    }
1404
1405
    pub fn get_identity(&self, r: &ObjectRef) -> Result<Identity> {
1406
        Ok(Identity::decode(&self.get_typed(r, ObjectType::Identity)?)?)
1407
    }
1408
1409
    fn sig_path(&self, r: &ObjectRef) -> PathBuf {
1410
        let h = r.to_hex();
1411
        self.dir.join("sigs").join(&h[..2]).join(&h[2..])
1412
    }
1413
1414
    /// Signatures stored alongside object `r` (spec §5.4). Empty if none.
1415
    pub fn signatures(&self, r: &ObjectRef) -> Result<Vec<Signature>> {
1416
        match fs::read(self.sig_path(r)) {
1417
            Ok(b) => Ok(Signature::decode_list(&b)?),
1418
            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(vec![]),
1419
            Err(e) => Err(e.into()),
1420
        }
1421
    }
1422
1423
    /// Attach a signature to object `r`, replacing any earlier one by the same key.
1424
    pub fn put_signature(&self, r: &ObjectRef, sig: &Signature) -> Result<()> {
1425
        let mut sigs = self.signatures(r)?;
1426
        sigs.retain(|s| s.key != sig.key);
1427
        sigs.push(sig.clone());
1428
        sigs.sort_by_key(|s| s.key);
1429
        let path = self.sig_path(r);
1430
        fs::create_dir_all(path.parent().unwrap())?;
1431
        let mut nonce = [0u8; 8];
1432
        rand::rngs::OsRng.fill_bytes(&mut nonce);
1433
        let tmp = self.dir.join(format!("sigs-tmp-{}", hex::encode(nonce)));
1434
        {
1435
            let mut f = fs::File::create(&tmp)?;
1436
            f.write_all(&Signature::encode_list(&sigs))?;
1437
            f.sync_all()?;
1438
        }
1439
        crate::durable::rename(&tmp, &path)?;
1440
        Ok(())
1441
    }
1442
1443
    /// Every object reference in the store, loose and packed (slow; for gc and tests).
1444
    pub fn list(&self) -> io::Result<Vec<ObjectRef>> {
1445
        let mut out: Vec<ObjectRef> = self.loose_objects()?.into_iter().map(|(r, _)| r).collect();
1446
        for p in self.packs.borrow().iter() {
1447
            out.extend(p.refs.iter().copied());
1448
        }
1449
        out.sort();
1450
        out.dedup();
1451
        Ok(out)
1452
    }
1453
}
1454
1455
/// A loose object at `path`, verified against `r`; `None` when there is no
1456
/// such file (it may be packed).
1457
fn read_loose_at(path: &Path, r: &ObjectRef) -> Option<Result<Object>> {
1458
    let data = match fs::read(path) {
1459
        Ok(d) => d,
1460
        Err(e) if e.kind() == io::ErrorKind::NotFound => return None,
1461
        Err(e) => return Some(Err(e.into())),
1462
    };
1463
    Some((|| {
1464
        let nul = data
1465
            .iter()
1466
            .position(|&b| b == 0)
1467
            .ok_or_else(|| StoreError::Corrupt(*r, "no header".into()))?;
1468
        let head = std::str::from_utf8(&data[..nul])
1469
            .map_err(|_| StoreError::Corrupt(*r, "header not UTF-8".into()))?;
1470
        let mut parts = head.split(' ');
1471
        let (Some("oxy1"), Some(ty), Some(len), None) =
1472
            (parts.next(), parts.next(), parts.next(), parts.next())
1473
        else {
1474
            return Err(StoreError::Corrupt(*r, format!("bad header {head:?}")));
1475
        };
1476
        let ty = ObjectType::from_name(ty)
1477
            .ok_or_else(|| StoreError::Corrupt(*r, format!("unknown type {ty}")))?;
1478
        let len: usize = len
1479
            .parse()
1480
            .map_err(|_| StoreError::Corrupt(*r, "bad length".into()))?;
1481
        let body = &data[nul + 1..];
1482
        if body.len() != len {
1483
            return Err(StoreError::Corrupt(
1484
                *r,
1485
                format!("length {} != header {len}", body.len()),
1486
            ));
1487
        }
1488
        if hash_object(ty, body) != *r {
1489
            return Err(StoreError::Corrupt(*r, "hash mismatch".into()));
1490
        }
1491
        Ok((ty, body.to_vec()))
1492
    })())
1493
}
1494
1495
#[cfg(test)]
1496
mod tests {
1497
    use super::*;
1498
1499
    #[test]
1500
    fn put_get_verify() {
1501
        let dir = tempfile::tempdir().unwrap();
1502
        let s = Store::open(dir.path().join("objects")).unwrap();
1503
        let r = s.put(ObjectType::Chunk, b"hello").unwrap();
1504
        assert!(s.has(&r));
1505
        assert_eq!(s.get(&r).unwrap(), (ObjectType::Chunk, b"hello".to_vec()));
1506
        assert_eq!(s.put(ObjectType::Chunk, b"hello").unwrap(), r);
1507
        assert_eq!(s.list().unwrap(), vec![r]);
1508
        assert!(matches!(
1509
            s.get_typed(&r, ObjectType::Blob),
1510
            Err(StoreError::WrongType(..))
1511
        ));
1512
        assert!(matches!(
1513
            s.get(&ObjectRef([9; 32])),
1514
            Err(StoreError::NotFound(_))
1515
        ));
1516
1517
        // Tamper: flip a byte, read must fail.
1518
        let path = s.path_for(&r);
1519
        let mut data = fs::read(&path).unwrap();
1520
        let last = data.len() - 1;
1521
        data[last] ^= 1;
1522
        fs::write(&path, data).unwrap();
1523
        assert!(matches!(s.get(&r), Err(StoreError::Corrupt(..))));
1524
    }
1525
1526
    #[test]
1527
    fn packing_keeps_every_object_readable() {
1528
        let dir = tempfile::tempdir().unwrap();
1529
        let s = Store::open(dir.path()).unwrap();
1530
        let mut refs = Vec::new();
1531
        for i in 0..300u32 {
1532
            let body = format!("object {i} ").repeat(1 + (i % 7) as usize);
1533
            refs.push((s.put(ObjectType::Chunk, body.as_bytes()).unwrap(), body));
1534
        }
1535
        let c = crate::objects::tests::sample_change();
1536
        let cr = s.put_change(&c).unwrap();
1537
        assert_eq!(s.loose_count().unwrap(), 301);
1538
        let report = s.pack_loose().unwrap();
1539
        assert_eq!(report.objects, 301);
1540
        assert!(report.packed_bytes < report.raw_bytes, "{report:?}");
1541
        assert_eq!(s.loose_count().unwrap(), 0);
1542
        assert_eq!(s.pack_count(), 1);
1543
        for (r, body) in &refs {
1544
            assert!(s.has(r));
1545
            assert_eq!(
1546
                s.get(r).unwrap(),
1547
                (ObjectType::Chunk, body.as_bytes().to_vec())
1548
            );
1549
        }
1550
        assert_eq!(s.get_change(&cr).unwrap(), c);
1551
        assert_eq!(s.list().unwrap().len(), 301);
1552
        // Re-putting a packed object is a no-op; new objects go loose and a
1553
        // second pack coexists with the first.
1554
        assert_eq!(
1555
            s.put(ObjectType::Chunk, refs[0].1.as_bytes()).unwrap(),
1556
            refs[0].0
1557
        );
1558
        assert_eq!(s.loose_count().unwrap(), 0);
1559
        let extra = s.put(ObjectType::Chunk, b"after packing").unwrap();
1560
        s.pack_loose().unwrap();
1561
        assert_eq!(s.pack_count(), 2);
1562
        assert_eq!(s.get(&extra).unwrap().1, b"after packing");
1563
        // A reopened store sees the packs.
1564
        let s2 = Store::open(dir.path()).unwrap();
1565
        assert_eq!(s2.pack_count(), 2);
1566
        assert_eq!(s2.get(&refs[5].0).unwrap().1, refs[5].1.as_bytes());
1567
        assert!(matches!(
1568
            s2.get(&ObjectRef([9; 32])),
1569
            Err(StoreError::NotFound(_))
1570
        ));
1571
        // Corrupting an object's body inside the pack is detected on read.
1572
        let target = refs[5].0;
1573
        let (pack_path, offset) = {
1574
            let packs = s2.packs.borrow();
1575
            let (i, e) = s2.find_packed(&target).unwrap();
1576
            (packs[i].path.clone(), e.offset as usize)
1577
        };
1578
        let mut data = fs::read(&pack_path).unwrap();
1579
        data[offset] ^= 0xff;
1580
        fs::write(&pack_path, data).unwrap();
1581
        let s3 = Store::open(dir.path()).unwrap();
1582
        assert!(matches!(s3.get(&target), Err(StoreError::Corrupt(..))));
1583
        assert_eq!(
1584
            s3.get(&refs[6].0).unwrap().1,
1585
            refs[6].1.as_bytes(),
1586
            "other objects are unaffected"
1587
        );
1588
    }
1589
1590
    #[test]
1591
    fn a_full_repack_trains_a_dictionary_and_reads_back() {
1592
        let dir = tempfile::tempdir().unwrap();
1593
        let s = Store::open(dir.path()).unwrap();
1594
        // Many small, alike files: what a dictionary is for.
1595
        let bodies: Vec<Vec<u8>> = (0..1500)
1596
            .map(|i| {
1597
                format!(
1598
                    "// SPDX-License-Identifier: GPL-2.0\n#include <linux/module.h>\n\
1599
                     static int probe_{i}(struct device *dev)\n{{\n\treturn {i};\n}}\n"
1600
                )
1601
                .into_bytes()
1602
            })
1603
            .collect();
1604
        let refs: Vec<ObjectRef> = bodies
1605
            .iter()
1606
            .map(|b| s.put(ObjectType::Chunk, b).unwrap())
1607
            .collect();
1608
        s.repack_all(REPACK_ZSTD_LEVEL).unwrap();
1609
        let dicts = fs::read_dir(dir.path())
1610
            .unwrap()
1611
            .flatten()
1612
            .filter(|e| e.path().extension().is_some_and(|x| x == "dict"))
1613
            .count();
1614
        assert_eq!(dicts, 1, "the pack has a dictionary");
1615
        let with_dict = refs
1616
            .iter()
1617
            .filter(|r| s.find_packed(r).unwrap().1.flags & FLAG_DICT != 0)
1618
            .count();
1619
        assert!(with_dict > 1000, "most use it: {with_dict}");
1620
        let again = Store::open(dir.path()).unwrap();
1621
        for (r, b) in refs.iter().zip(&bodies) {
1622
            assert_eq!(&again.get(r).unwrap().1, b);
1623
        }
1624
        // A repack after that replaces the pack and its dictionary.
1625
        again.repack_all(REPACK_ZSTD_LEVEL).unwrap();
1626
        let files: Vec<String> = fs::read_dir(dir.path())
1627
            .unwrap()
1628
            .flatten()
1629
            .map(|e| e.file_name().to_string_lossy().into_owned())
1630
            .filter(|n| n.starts_with("pack-"))
1631
            .collect();
1632
        assert_eq!(files.len(), 3, "one pack, index and dictionary: {files:?}");
1633
        assert_eq!(&again.get(&refs[7]).unwrap().1, &bodies[7]);
1634
    }
1635
1636
    #[test]
1637
    fn nocompress_chunks_pack_raw() {
1638
        let dir = tempfile::tempdir().unwrap();
1639
        let s = Store::open(dir.path()).unwrap();
1640
        let body = vec![b'a'; 10_000];
1641
        let raw = s.put_chunk_nocompress(&body).unwrap();
1642
        let compressible = s.put(ObjectType::Chunk, &vec![b'b'; 10_000]).unwrap();
1643
        s.pack_loose().unwrap();
1644
        let packs = s.packs.borrow();
1645
        let (i, e) = s.find_packed(&raw).unwrap();
1646
        assert_eq!((e.flags, e.stored_len as usize), (0, 10_000));
1647
        let (_, c) = s.find_packed(&compressible).unwrap();
1648
        assert_eq!(c.flags, FLAG_ZSTD);
1649
        assert!(c.stored_len < 10_000);
1650
        assert_eq!(packs[i].read(&raw, e).unwrap().1, body);
1651
    }
1652
1653
    #[test]
1654
    fn many_packs_merge_into_one() {
1655
        let dir = tempfile::tempdir().unwrap();
1656
        let s = Store::open(dir.path()).unwrap();
1657
        let mut refs = Vec::new();
1658
        for i in 0..(MAX_PACKS + 2) {
1659
            refs.push(
1660
                s.put(ObjectType::Chunk, format!("pack {i}").as_bytes())
1661
                    .unwrap(),
1662
            );
1663
            s.pack_loose().unwrap();
1664
        }
1665
        assert_eq!(s.pack_count(), MAX_PACKS + 2);
1666
        assert_eq!(s.merge_packs().unwrap(), MAX_PACKS + 2);
1667
        assert_eq!(s.pack_count(), 1);
1668
        assert_eq!(s.merge_packs().unwrap(), 0);
1669
        for (i, r) in refs.iter().enumerate() {
1670
            assert_eq!(s.get(r).unwrap().1, format!("pack {i}").as_bytes());
1671
        }
1672
        assert_eq!(Store::open(dir.path()).unwrap().pack_count(), 1);
1673
    }
1674
1675
    #[test]
1676
    fn prune_removes_unreachable_loose_and_packed_objects() {
1677
        use std::collections::HashSet;
1678
        let dir = tempfile::tempdir().unwrap();
1679
        let s = Store::open(dir.path()).unwrap();
1680
        let keep_a = s.put(ObjectType::Chunk, b"keep a").unwrap();
1681
        let drop_a = s.put(ObjectType::Chunk, b"drop a").unwrap();
1682
        s.pack_loose().unwrap();
1683
        let keep_b = s.put(ObjectType::Chunk, b"keep b").unwrap();
1684
        let drop_b = s.put(ObjectType::Chunk, b"drop b").unwrap();
1685
        let sk = crate::identity::SecretKey {
1686
            ed_seed: [1; 32],
1687
            ml_seed: [2; 32],
1688
        };
1689
        let id = sk.identity("a", "b", 0);
1690
        let key = s.put_identity(&id).unwrap();
1691
        s.put_signature(
1692
            &drop_b,
1693
            &sk.sign(crate::identity::Domain::Change, &key, &drop_b),
1694
        )
1695
        .unwrap();
1696
        s.index_seal(&drop_a, &ObjectRef([3; 32])).unwrap();
1697
        let keep: HashSet<ObjectRef> = [keep_a, keep_b, key].into_iter().collect();
1698
        // Everything is too young under a grace period.
1699
        let r = s
1700
            .prune(&keep, std::time::Duration::from_secs(3600))
1701
            .unwrap();
1702
        assert_eq!((r.objects, r.deferred), (0, 2));
1703
        let r = s.prune(&keep, std::time::Duration::ZERO).unwrap();
1704
        assert_eq!(r.objects, 2, "{r:?}");
1705
        assert!(s.has(&keep_a) && s.has(&keep_b) && s.has(&key));
1706
        assert!(!s.has(&drop_a) && !s.has(&drop_b));
1707
        assert!(s.signatures(&drop_b).unwrap().is_empty());
1708
        assert!(s.seals_for(&drop_a).unwrap().is_empty());
1709
        assert_eq!(s.pack_count(), 1);
1710
        assert_eq!(s.get(&keep_a).unwrap().1, b"keep a");
1711
        assert_eq!(s.list().unwrap().len(), 3);
1712
    }
1713
1714
    #[test]
1715
    fn signatures_are_stored_beside_objects() {
1716
        use crate::identity::{Domain, SecretKey};
1717
        let dir = tempfile::tempdir().unwrap();
1718
        let s = Store::open(dir.path()).unwrap();
1719
        let r = s.put(ObjectType::Chunk, b"x").unwrap();
1720
        assert!(s.signatures(&r).unwrap().is_empty());
1721
        let sk = SecretKey {
1722
            ed_seed: [1; 32],
1723
            ml_seed: [2; 32],
1724
        };
1725
        let id = sk.identity("a", "b", 0);
1726
        let key = s.put_identity(&id).unwrap();
1727
        assert_eq!(s.get_identity(&key).unwrap(), id);
1728
        let sig = sk.sign(Domain::Change, &key, &r);
1729
        s.put_signature(&r, &sig).unwrap();
1730
        s.put_signature(&r, &sig).unwrap();
1731
        assert_eq!(s.signatures(&r).unwrap(), vec![sig]);
1732
        // The object itself is untouched by its signatures.
1733
        assert_eq!(s.get(&r).unwrap().1, b"x");
1734
    }
1735
1736
    #[test]
1737
    fn change_round_trip_through_store() {
1738
        let dir = tempfile::tempdir().unwrap();
1739
        let s = Store::open(dir.path()).unwrap();
1740
        let c = crate::objects::tests::sample_change();
1741
        let r = s.put_change(&c).unwrap();
1742
        assert_eq!(r, c.hash());
1743
        assert_eq!(s.get_change(&r).unwrap(), c);
1744
    }
1745
1746
    fn xorshift(state: &mut u64) -> u64 {
1747
        *state ^= *state << 13;
1748
        *state ^= *state >> 7;
1749
        *state ^= *state << 17;
1750
        *state
1751
    }
1752
1753
    /// Random corruption of pack and index files never panics: reads fail
1754
    /// with an error or the store refuses to open, and untouched objects
1755
    /// stay readable when the index survives.
1756
    #[test]
1757
    fn corrupted_packs_and_indexes_fail_cleanly() {
1758
        let dir = tempfile::tempdir().unwrap();
1759
        let objects = dir.path().join("objects");
1760
        let s = Store::open(&objects).unwrap();
1761
        let mut refs = Vec::new();
1762
        let mut seed = 0x9e3779b97f4a7c15u64;
1763
        for i in 0..40u32 {
1764
            let len = (xorshift(&mut seed) % 5000) as usize;
1765
            let mut body = vec![0u8; len];
1766
            for b in body.iter_mut() {
1767
                *b = if i % 2 == 0 {
1768
                    (xorshift(&mut seed) & 0xff) as u8
1769
                } else {
1770
                    b'a' + (i % 26) as u8
1771
                };
1772
            }
1773
            refs.push(s.put(ObjectType::Chunk, &body).unwrap());
1774
        }
1775
        s.pack_loose().unwrap();
1776
        let pack = fs::read_dir(&objects)
1777
            .unwrap()
1778
            .filter_map(|e| e.ok().map(|e| e.path()))
1779
            .find(|p| p.extension().is_some_and(|x| x == "pack"))
1780
            .unwrap();
1781
        let idx = pack.with_extension("idx");
1782
        let pristine_pack = fs::read(&pack).unwrap();
1783
        let pristine_idx = fs::read(&idx).unwrap();
1784
1785
        for round in 0..300u32 {
1786
            let (path, pristine) = if round % 2 == 0 {
1787
                (&pack, &pristine_pack)
1788
            } else {
1789
                (&idx, &pristine_idx)
1790
            };
1791
            let mut data = pristine.clone();
1792
            match xorshift(&mut seed) % 4 {
1793
                0 => {
1794
                    let at = (xorshift(&mut seed) as usize) % data.len();
1795
                    data[at] ^= 1 << (xorshift(&mut seed) % 8);
1796
                }
1797
                1 => {
1798
                    let at = (xorshift(&mut seed) as usize) % data.len();
1799
                    data[at] = (xorshift(&mut seed) & 0xff) as u8;
1800
                }
1801
                2 => {
1802
                    let keep = (xorshift(&mut seed) as usize) % data.len();
1803
                    data.truncate(keep);
1804
                }
1805
                _ => {
1806
                    let at = (xorshift(&mut seed) as usize) % data.len();
1807
                    let n = ((xorshift(&mut seed) % 8) + 1) as usize;
1808
                    for k in 0..n.min(data.len() - at) {
1809
                        data[at + k] = 0xff;
1810
                    }
1811
                }
1812
            }
1813
            fs::write(path, &data).unwrap();
1814
            // Opening may refuse a broken index; a store that opens must
1815
            // either return each object intact or report it corrupt/missing.
1816
            if let Ok(s2) = Store::open(&objects) {
1817
                for r in &refs {
1818
                    match s2.get(r) {
1819
                        Ok((ty, body)) => assert_eq!(
1820
                            hash_object(ty, &body),
1821
                            *r,
1822
                            "a returned object always matches its reference"
1823
                        ),
1824
                        Err(StoreError::Corrupt(..))
1825
                        | Err(StoreError::NotFound(_))
1826
                        | Err(StoreError::Io(_)) => {}
1827
                        Err(e) => panic!("unexpected error {e}"),
1828
                    }
1829
                }
1830
            }
1831
            fs::write(path, pristine).unwrap();
1832
        }
1833
        // Restored files read back in full.
1834
        let s3 = Store::open(&objects).unwrap();
1835
        for r in &refs {
1836
            let (ty, body) = s3.get(r).unwrap();
1837
            assert_eq!(hash_object(ty, &body), *r);
1838
        }
1839
    }
1840
1841
    /// A small batch becomes loose objects; a large one becomes a single
1842
    /// pack. Objects are readable while pending, and batches nest.
1843
    #[test]
1844
    fn batches_write_loose_or_one_pack() {
1845
        let dir = tempfile::tempdir().unwrap();
1846
        let s = Store::open(dir.path().join("objects")).unwrap();
1847
        let outer = s.begin_batch().unwrap();
1848
        let a = s.put(ObjectType::Chunk, b"small a").unwrap();
1849
        {
1850
            let inner = s.begin_batch().unwrap();
1851
            let b = s.put(ObjectType::Chunk, b"small b").unwrap();
1852
            assert!(s.has(&b));
1853
            assert_eq!(s.get(&b).unwrap().1, b"small b");
1854
            inner.finish().unwrap();
1855
            assert_eq!(
1856
                s.loose_count().unwrap(),
1857
                0,
1858
                "the inner batch defers to the outer one"
1859
            );
1860
        }
1861
        assert_eq!(s.get(&a).unwrap().1, b"small a");
1862
        assert_eq!(
1863
            s.put(ObjectType::Chunk, b"small a").unwrap(),
1864
            a,
1865
            "idempotent while pending"
1866
        );
1867
        outer.finish().unwrap();
1868
        assert_eq!(s.loose_count().unwrap(), 2);
1869
        assert_eq!(s.pack_count(), 0);
1870
        assert_eq!(s.get(&a).unwrap().1, b"small a");
1871
1872
        // Large: spills into one pack, readable during and after.
1873
        let big = s.begin_batch().unwrap();
1874
        let mut refs = Vec::new();
1875
        let mut seed = 7u64;
1876
        for i in 0..300u32 {
1877
            let mut body = vec![b'z'; 40_000];
1878
            if i % 3 == 0 {
1879
                for b in body.iter_mut() {
1880
                    *b = (xorshift(&mut seed) & 0xff) as u8;
1881
                }
1882
            }
1883
            body[..4].copy_from_slice(&i.to_le_bytes());
1884
            let r = if i % 5 == 0 {
1885
                s.put_chunk_nocompress(&body).unwrap()
1886
            } else {
1887
                s.put(ObjectType::Chunk, &body).unwrap()
1888
            };
1889
            assert_eq!(
1890
                s.get(&r).unwrap().1,
1891
                body,
1892
                "readable while pending (object {i})"
1893
            );
1894
            refs.push((r, body));
1895
        }
1896
        assert!(s.has(&refs[0].0));
1897
        big.finish().unwrap();
1898
        assert_eq!(s.pack_count(), 1);
1899
        assert_eq!(
1900
            s.loose_count().unwrap(),
1901
            2,
1902
            "nothing from the big batch is loose"
1903
        );
1904
        assert!(fs::read_dir(dir.path().join("objects"))
1905
            .unwrap()
1906
            .flatten()
1907
            .all(|e| !e.file_name().to_string_lossy().starts_with("tmp-")));
1908
        let s2 = Store::open(dir.path().join("objects")).unwrap();
1909
        for (r, body) in &refs {
1910
            assert_eq!(s2.get(r).unwrap().1, *body);
1911
        }
1912
        // A dropped batch still writes its objects.
1913
        {
1914
            let _b = s2.begin_batch().unwrap();
1915
            s2.put(ObjectType::Chunk, b"dropped").unwrap();
1916
        }
1917
        assert_eq!(
1918
            s2.get(&hash_object(ObjectType::Chunk, b"dropped"))
1919
                .unwrap()
1920
                .1,
1921
            b"dropped"
1922
        );
1923
    }
1924
1925
    #[test]
1926
    fn get_many_reads_loose_and_packed_objects_in_order() {
1927
        let dir = tempfile::tempdir().unwrap();
1928
        let s = Store::open(dir.path().join("objects")).unwrap();
1929
        let packed: Vec<ObjectRef> = (0..20)
1930
            .map(|i| {
1931
                s.put(ObjectType::Chunk, format!("packed {i}").as_bytes())
1932
                    .unwrap()
1933
            })
1934
            .collect();
1935
        s.pack_loose().unwrap();
1936
        let loose: Vec<ObjectRef> = (0..20)
1937
            .map(|i| {
1938
                s.put(ObjectType::Chunk, format!("loose {i}").as_bytes())
1939
                    .unwrap()
1940
            })
1941
            .collect();
1942
        let missing = hash_object(ObjectType::Chunk, b"never stored");
1943
        let mut refs: Vec<ObjectRef> = Vec::new();
1944
        for i in 0..20 {
1945
            refs.push(loose[i]);
1946
            refs.push(packed[i]);
1947
        }
1948
        refs.push(missing);
1949
        let got = s.get_many(&refs);
1950
        assert_eq!(got.len(), refs.len());
1951
        for (i, r) in refs.iter().enumerate().take(40) {
1952
            let want = if i % 2 == 0 {
1953
                format!("loose {}", i / 2)
1954
            } else {
1955
                format!("packed {}", i / 2)
1956
            };
1957
            let (ty, body) = got[i].as_ref().unwrap();
1958
            assert_eq!(
1959
                (*ty, body.as_slice()),
1960
                (ObjectType::Chunk, want.as_bytes()),
1961
                "{r:?}"
1962
            );
1963
        }
1964
        assert!(matches!(got[40], Err(StoreError::NotFound(_))));
1965
    }
1966
}
1967
1968
#[cfg(test)]
1969
mod batch_tests {
1970
    use super::*;
1971
1972
    #[test]
1973
    fn a_large_batch_packs_every_object_and_indexes_them_all() {
1974
        let dir = tempfile::tempdir().unwrap();
1975
        let store = Store::open(dir.path()).unwrap();
1976
        let mut refs = Vec::new();
1977
        {
1978
            let batch = store.begin_batch().unwrap();
1979
            for i in 0..1000u32 {
1980
                let body = format!("object {i} {}", "x".repeat(20_000 + i as usize)).into_bytes();
1981
                refs.push(store.put(ObjectType::Blob, &body).unwrap());
1982
            }
1983
            batch.finish().unwrap();
1984
        }
1985
        let again = Store::open(dir.path()).unwrap();
1986
        for r in &refs {
1987
            again
1988
                .get(r)
1989
                .unwrap_or_else(|e| panic!("{}: {e}", r.short(12)));
1990
        }
1991
    }
1992
}
1993
1994
#[cfg(test)]
1995
mod size_tests {
1996
    use super::*;
1997
1998
    #[test]
1999
    fn an_object_over_the_limit_is_refused_and_nothing_is_written() {
2000
        let dir = tempfile::tempdir().unwrap();
2001
        let store = Store::open(dir.path()).unwrap();
2002
        let big = vec![b'x'; MAX_OBJECT_LEN as usize + 1];
2003
        {
2004
            let batch = store.begin_batch().unwrap();
2005
            store.put(ObjectType::Blob, b"small").unwrap();
2006
            let e = store.put(ObjectType::Change, &big).unwrap_err();
2007
            assert!(
2008
                matches!(e, StoreError::TooLarge { kind: "change", .. }),
2009
                "{e}"
2010
            );
2011
            assert!(e.to_string().contains("commit it in parts"), "{e}");
2012
            batch.finish().unwrap();
2013
        }
2014
        // The store still opens and reads what was written.
2015
        let again = Store::open(dir.path()).unwrap();
2016
        again.get(&hash_object(ObjectType::Blob, b"small")).unwrap();
2017
    }
2018
}
2019
2020
#[cfg(test)]
2021
mod text_tests {
2022
    use super::*;
2023
    use crate::objects::{AtomRef, Edit, CHANGE_VERSION};
2024
2025
    fn large_change() -> Change {
2026
        let mut c = crate::objects::tests::sample_change();
2027
        assert_eq!(c.version, CHANGE_VERSION);
2028
        c.edits[0] = Edit::Insert {
2029
            node: crate::ids::NodeId([7; 16]),
2030
            after: AtomRef::Start,
2031
            before: AtomRef::End,
2032
            lines: (0..2000)
2033
                .map(|i| format!("line {i}\n").into_bytes())
2034
                .collect(),
2035
        };
2036
        c
2037
    }
2038
2039
    #[test]
2040
    fn a_large_insert_is_stored_beside_its_change_and_read_back() {
2041
        let dir = tempfile::tempdir().unwrap();
2042
        let s = Store::open(dir.path()).unwrap();
2043
        let c = large_change();
2044
        let r = s.put_change(&c).unwrap();
2045
        assert_eq!(r, c.hash());
2046
        let (_, body) = s.get(&r).unwrap();
2047
        assert!(
2048
            body.len() < 1024,
2049
            "the change holds a reference, not {} bytes of lines",
2050
            body.len()
2051
        );
2052
        let (back, parts) = s.get_change_parts(&r).unwrap();
2053
        assert_eq!(back, c);
2054
        // The text blob and its chunk.
2055
        assert_eq!(parts.len(), 2);
2056
        for p in &parts {
2057
            assert!(s.has(p));
2058
        }
2059
        // Storing it again writes nothing new.
2060
        let n = s.list().unwrap().len();
2061
        s.put_change(&c).unwrap();
2062
        assert_eq!(s.list().unwrap().len(), n);
2063
    }
2064
2065
    #[test]
2066
    fn a_change_whose_text_blob_is_missing_is_reported_not_misread() {
2067
        let dir = tempfile::tempdir().unwrap();
2068
        let s = Store::open(dir.path()).unwrap();
2069
        let c = large_change();
2070
        let r = s.put_change(&c).unwrap();
2071
        let (_, parts) = s.get_change_parts(&r).unwrap();
2072
        fs::remove_file(s.path_for(&parts[0])).unwrap();
2073
        let e = s.get_change(&r).unwrap_err();
2074
        assert!(
2075
            matches!(&e, StoreError::Corrupt(h, why) if *h == r && why.contains("missing")),
2076
            "{e}"
2077
        );
2078
    }
2079
}
2080
2081
#[cfg(test)]
2082
mod put_many_tests {
2083
    use super::*;
2084
2085
    #[test]
2086
    fn many_objects_in_a_batch_are_compressed_together_and_all_read_back() {
2087
        let dir = tempfile::tempdir().unwrap();
2088
        let s = Store::open(dir.path()).unwrap();
2089
        let before = s.put(ObjectType::Chunk, b"already here").unwrap();
2090
        let bodies: Vec<Vec<u8>> = (0..200u32)
2091
            .map(|i| format!("chunk {i} ").repeat(6000).into_bytes())
2092
            .collect();
2093
        let mut objects: Vec<(ObjectType, &[u8])> = bodies
2094
            .iter()
2095
            .map(|b| (ObjectType::Chunk, b.as_slice()))
2096
            .collect();
2097
        objects.push((ObjectType::Chunk, bodies[0].as_slice()));
2098
        objects.push((ObjectType::Chunk, b"already here"));
2099
        let refs = {
2100
            let batch = s.begin_batch().unwrap();
2101
            let refs = s.put_many(&objects).unwrap();
2102
            batch.finish().unwrap();
2103
            refs
2104
        };
2105
        assert_eq!(refs.len(), objects.len());
2106
        assert_eq!(refs[200], refs[0], "a repeat is the same object");
2107
        assert_eq!(refs[201], before);
2108
        let again = Store::open(dir.path()).unwrap();
2109
        for (r, b) in refs.iter().zip(&objects) {
2110
            assert_eq!(again.get(r).unwrap().1, b.1);
2111
        }
2112
    }
2113
}
2114
2115
/// Remove a pack with its index and dictionary.
2116
fn remove_pack_files(pack: &Path) -> io::Result<()> {
2117
    fs::remove_file(pack)?;
2118
    fs::remove_file(pack.with_extension("idx"))?;
2119
    match fs::remove_file(pack.with_extension("dict")) {
2120
        Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e),
2121
        _ => Ok(()),
2122
    }
2123
}