OXYGENHUB
# 771661aa50f4 oxygen / crates / oxy-core / src / store.rs
178.1 KiB · Rust · last changed Entries stay fresh in a long-lived handle: re-read after the pack listing's 30 s 17 days ago source blame history raw
64818938 Andy McCall ↶ 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.
d02e545d Andy McCall ↶ 5
//!
64818938 Andy McCall ↶ 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
//!
d02e545d Andy McCall ↶ 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`.
64818938 Andy McCall ↶ 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.
767ac6cd Andy McCall 27
//! `pack-retired` records the packs and loose objects a repack replaced,
28
//! which stay for readers until a collection an hour later (oxygenhub#249).
ef7d4ea6 Andy McCall ↶ 29
//!
30
//! A store that is not this disk's directory, where finding an object's
31
//! entries is a LIST request, also keeps every entry key in the
32
//! `pack-entries` journal and, once a collection folds them, in entry
33
//! lists (`pack-<id>.entries`), read once per open (spec §13.7, #116).
ff0af1ee unknown 34
5b9c6ad4 Andy McCall ↶ 35
use crate::attest::Attest;
ff0af1ee unknown 36
use crate::hash::{hash_object, header, ObjectRef, ObjectType};
1983686f Andy McCall ↶ 37
use crate::identity::{Identity, Signature};
6f8aeb99 Andy McCall ↶ 38
use crate::objects::{Blob, Change, ObjectError, StateObject};
fc1a466a Andy McCall ↶ 39
use crate::receipt::Receipt;
64818938 Andy McCall ↶ 40
use crate::strata::{self, Error as BackendError, LocalStore, MemoryStore};
ff0af1ee unknown 41
use rand::RngCore;
d02e545d Andy McCall ↶ 42
use std::cell::RefCell;
ff0af1ee unknown 43
use std::fs;
64818938 Andy McCall ↶ 44
use std::io::{self, Write};
ff0af1ee unknown 45
use std::path::{Path, PathBuf};
64818938 Andy McCall ↶ 46
use std::sync::Arc;
ff0af1ee unknown 47
d02e545d Andy McCall ↶ 48
const PACK_MAGIC: &[u8; 8] = b"OXYPACK1";
49
const IDX_MAGIC: &[u8; 8] = b"OXYIDX01";
50
const IDX_ENTRY: usize = 32 + 8 + 4 + 4 + 1 + 1;
51
const FLAG_ZSTD: u8 = 1;
a17fc622 Andy McCall ↶ 52
/// Compressed with the pack's trained dictionary (`pack-ID.dict`), which a
53
/// full repack makes from a sample of the objects it packs: small files
54
/// share most of their vocabulary, which each one alone cannot use.
55
const FLAG_DICT: u8 = 2;
56
/// The size of a pack's dictionary, and the least a repack must pack for
57
/// one to pay.
58
const DICT_BYTES: usize = 110 << 10;
59
const DICT_MIN_OBJECTS: usize = 1000;
60
/// Objects up to this size are compressed with the dictionary.
61
const DICT_OBJECT_MAX: usize = 64 << 10;
d02e545d Andy McCall ↶ 62
const ZSTD_LEVEL: i32 = 3;
da652d63 Andy McCall ↶ 63
/// The level of a full repack (`oxy gc`): slower, once, for a smaller store.
64
pub const REPACK_ZSTD_LEVEL: i32 = 9;
2b872d07 Andy McCall ↶ 65
/// Largest object a pack entry may claim; anything bigger is corruption,
66
/// and refusing it keeps a bad index from driving huge allocations.
67
const MAX_OBJECT_LEN: u32 = 1 << 30;
767ac6cd Andy McCall 68
/// What reading an entry of a pack whose dictionary is gone says. A pack
69
/// being deleted can lose its dictionary first, so a read that meets this
70
/// looks at the packs again before it is believed.
71
const NO_DICT: &str = "packed with a dictionary the pack lacks";
d02e545d Andy McCall ↶ 72
767ac6cd Andy McCall 73
/// The record of what repacks replaced (oxygenhub#249): packs and loose
74
/// objects whose contents a newer pack holds, kept for readers that
75
/// still use them until garbage collection deletes them, at least
76
/// [`RETIRED_FOR`] later. One line per key, `<retired at, wall ms> <key>`.
77
/// It is a reference record (updated by compare-and-swap, so concurrent
78
/// repacks and collections never lose each other's lines), named under
79
/// `pack-` so the pack listing every open makes shows whether it holds
80
/// anything.
81
const RETIRED_KEY: &str = "pack-retired";
82
/// How long a retired pack or loose object stays in the store: a reader
83
/// that loaded its list of packs before a repack reads on from the old
84
/// packs this long, and after that finds the objects in the new pack by
85
/// looking again (see [`Store::get`]).
86
pub const RETIRED_FOR: std::time::Duration = std::time::Duration::from_secs(60 * 60);
87
/// Compare-and-swap rounds for the retired record before giving up.
88
const RETIRED_TRIES: usize = 32;
89
/// After a look at the pack listing found nothing new, how long a missed
90
/// [`Store::has`] answers without looking again: a writer probing for
91
/// thousands of objects it is about to store would otherwise list the
92
/// packs for each.
93
const HAS_RELIST_AFTER: std::time::Duration = std::time::Duration::from_secs(1);
ef7d4ea6 Andy McCall ↶ 94
95
/// The journal of signatures and index entries (spec §13.7): every entry
96
/// key a writer on a store that is not this disk's directory wrote since
97
/// the last fold, one line each, `<folded at, wall ms; 0 until folded>
98
/// <key>`, as the retired record's lines are. A reference record updated
99
/// by compare-and-swap, so concurrent writers never lose each other's
100
/// lines; read once per open, instead of a listing per lookup.
101
pub const JOURNAL_KEY: &str = "pack-entries";
102
/// A complete entry list (spec §13.7): every entry a fold found.
103
const LIST_SUFFIX: &str = ".entries";
104
/// A partial entry list: journal lines a writer folded out.
105
const PART_SUFFIX: &str = ".entries-part";
106
/// The first line of an entry list.
107
const LIST_MAGIC: &str = "oxy-entries 1";
108
/// Written once a collection has copied the older one-list keys into
109
/// per-object entries: readers stop looking for them.
110
const LEGACY_FOLDED_KEY: &str = "pack-legacy-folded";
111
/// Unfolded journal lines a writer lets the journal hold before it folds
112
/// them into a partial list.
113
const JOURNAL_FOLD_AT: usize = 1000;
771661aa Andy McCall ↶ 114
/// How long a handle answers lookups from the entries it read before it
115
/// reads the pack listing and the journal again (spec §13.7): the
116
/// interval a cloud client keeps the pack listing for, so another
117
/// writer's entry is seen as soon as its pack would be.
118
pub const ENTRIES_FRESH: std::time::Duration = std::time::Duration::from_secs(30);
ef7d4ea6 Andy McCall ↶ 119
/// The per-object entry indexes, each with the one-list name older
120
/// stores kept it under.
121
const ENTRY_INDEXES: [(&str, &str); 6] = [
122
    ("sig", "sigs"),
123
    ("seal", "seals"),
124
    ("receipt", "receipts"),
125
    ("approval", "approvals"),
126
    ("cert", "certs"),
127
    ("accepted", "accepted-lists"),
128
];
767ac6cd Andy McCall 129
130
/// A pack listing as compared: each key with its size and time.
131
type Listed = Vec<(String, u64, Option<u64>)>;
132
133
/// The retired record's lines: each key with the time it was retired.
134
fn parse_retired(bytes: &[u8]) -> std::collections::BTreeMap<String, u64> {
135
    String::from_utf8_lossy(bytes)
136
        .lines()
137
        .filter_map(|l| {
138
            let (t, k) = l.split_once(' ')?;
139
            Some((k.to_string(), t.parse().ok()?))
140
        })
141
        .collect()
142
}
143
144
fn encode_retired(m: &std::collections::BTreeMap<String, u64>) -> Vec<u8> {
145
    m.iter()
146
        .map(|(k, t)| format!("{t} {k}\n"))
147
        .collect::<String>()
148
        .into_bytes()
149
}
150
151
/// What deleting retired packs and loose objects did.
152
#[derive(Debug, Clone, Default, PartialEq, Eq)]
153
pub struct RetiredReport {
154
    /// Retired packs deleted, each with its index and dictionary.
155
    pub packs: usize,
156
    /// Retired loose objects deleted.
157
    pub loose: usize,
158
    /// Retired entries younger than [`RETIRED_FOR`], left for the next
159
    /// collection.
160
    pub kept: usize,
161
}
162
afaba5f1 Andy McCall ↶ 163
/// An object read from the store: its type and body.
164
pub type Object = (ObjectType, Vec<u8>);
165
9ae4d15a Andy McCall ↶ 166
/// Where a long operation reports what it is doing (oxygen#66): a phase,
167
/// or a count within one, as a line for a spinner or a log.
168
pub type Progress<'a> = &'a mut dyn FnMut(&str);
64818938 Andy McCall ↶ 169
170
/// The storage under a store: objects by key, see [`crate::strata`].
171
pub type Backend = dyn strata::Store;
9ae4d15a Andy McCall ↶ 172
173
fn silent() -> impl FnMut(&str) {
174
    |_| {}
64818938 Andy McCall ↶ 175
}
176
177
/// A backend error as a store error: what is not found or already there
178
/// is handled where it matters; the rest is an I/O failure.
179
fn backend_err(e: BackendError) -> StoreError {
180
    match e {
181
        BackendError::Io(e) => StoreError::Io(e),
182
        other => StoreError::Io(io::Error::other(other.to_string())),
183
    }
184
}
185
186
/// `put_new` where an object already there is what we wanted.
187
fn put_new_or_existing(backend: &Backend, key: &str, bytes: &[u8]) -> Result<()> {
188
    match backend.put_new(key, bytes) {
189
        Ok(()) | Err(BackendError::Exists(_)) => Ok(()),
190
        Err(e) => Err(backend_err(e)),
191
    }
192
}
193
194
/// `get` as an option: `None` when there is no such key.
195
fn get_optional(backend: &Backend, key: &str) -> Result<Option<Vec<u8>>> {
196
    match backend.get(key) {
197
        Ok(b) => Ok(Some(b)),
198
        Err(BackendError::NotFound(_)) => Ok(None),
199
        Err(e) => Err(backend_err(e)),
200
    }
201
}
202
203
fn delete(backend: &Backend, key: &str) -> Result<()> {
204
    backend.delete(key).map_err(backend_err)
205
}
206
207
/// `loose/<hh>/<rest>`.
208
fn loose_key(r: &ObjectRef) -> String {
209
    let h = r.to_hex();
210
    format!("loose/{}/{}", &h[..2], &h[2..])
211
}
212
213
/// The object a loose key names, if it is one.
214
fn loose_ref(key: &str) -> Option<ObjectRef> {
215
    let rest = key.strip_prefix("loose/")?;
216
    let (hh, tail) = rest.split_once('/')?;
217
    if hh.len() != 2 || tail.contains('/') {
218
        return None;
219
    }
220
    ObjectRef::from_hex(&format!("{hh}{tail}"))
221
}
222
223
/// `<index>/<hh>/<rest>/` for the entries kept under an object.
224
fn fanout_prefix(index: &str, r: &ObjectRef) -> String {
225
    let h = r.to_hex();
226
    format!("{index}/{}/{}/", &h[..2], &h[2..])
ef7d4ea6 Andy McCall ↶ 227
}
228
229
/// Whether a key names an entry list (spec §13.7), complete or partial.
230
fn is_entry_list(key: &str) -> bool {
231
    key.starts_with("pack-") && (key.ends_with(LIST_SUFFIX) || key.ends_with(PART_SUFFIX))
232
}
233
234
/// An entry list's bytes: zstd-compressed text, [`LIST_MAGIC`] and then
235
/// one key per line, sorted.
236
fn encode_entry_list<'a>(keys: impl Iterator<Item = &'a String>) -> Result<Vec<u8>> {
237
    let mut text = String::from(LIST_MAGIC);
238
    text.push('\n');
239
    for k in keys {
240
        text.push_str(k);
241
        text.push('\n');
242
    }
243
    Ok(zstd::bulk::compress(text.as_bytes(), ZSTD_LEVEL)?)
244
}
245
246
/// The keys an entry list holds.
247
fn decode_entry_list(key: &str, bytes: &[u8]) -> Result<Vec<String>> {
248
    let bad = |why: &str| StoreError::Io(io::Error::other(format!("{key}: {why}")));
249
    let text = zstd::stream::decode_all(bytes).map_err(|_| bad("not zstd"))?;
250
    let text = String::from_utf8(text).map_err(|_| bad("not UTF-8"))?;
251
    let mut lines = text.lines();
252
    if lines.next() != Some(LIST_MAGIC) {
253
        return Err(bad("not an entry list"));
254
    }
255
    Ok(lines
256
        .filter(|l| !l.is_empty())
257
        .map(str::to_string)
258
        .collect())
64818938 Andy McCall ↶ 259
}
260
ef7d4ea6 Andy McCall ↶ 261
/// Drop journal lines folded at least [`RETIRED_FOR`] before `now`:
262
/// every reader that could need them has a list holding them by then.
263
fn expire_folded(m: &mut std::collections::BTreeMap<String, u64>, now: u64) {
264
    let hour = RETIRED_FOR.as_millis() as u64;
265
    m.retain(|_, t| *t == 0 || now.saturating_sub(*t) < hour);
266
}
267
64818938 Andy McCall ↶ 268
/// `<index>/<hh>/<rest>`: the one-file-per-object layout of older stores.
269
fn legacy_key(index: &str, r: &ObjectRef) -> String {
270
    let h = r.to_hex();
271
    format!("{index}/{}/{}", &h[..2], &h[2..])
9ae4d15a Andy McCall ↶ 272
}
273
64818938 Andy McCall ↶ 274
fn now_ms() -> u64 {
275
    std::time::SystemTime::now()
276
        .duration_since(std::time::UNIX_EPOCH)
277
        .map(|d| d.as_millis() as u64)
278
        .unwrap_or(0)
279
}
280
d02e545d Andy McCall ↶ 281
#[derive(Clone, Copy, Debug)]
282
struct PackEntry {
283
    offset: u64,
284
    stored_len: u32,
285
    raw_len: u32,
286
    ty: ObjectType,
287
    flags: u8,
288
}
289
290
/// One pack's index, fully in memory and sorted by ObjectRef.
291
struct PackIndex {
64818938 Andy McCall ↶ 292
    /// The pack's key, `pack-<id>.pack`.
293
    key: String,
d02e545d Andy McCall ↶ 294
    refs: Vec<ObjectRef>,
295
    entries: Vec<PackEntry>,
a17fc622 Andy McCall ↶ 296
    /// The pack's dictionary, prepared once, when it has one.
64818938 Andy McCall ↶ 297
    dict: Option<Arc<zstd::dict::DecoderDictionary<'static>>>,
d02e545d Andy McCall ↶ 298
}
299
a17fc622 Andy McCall ↶ 300
impl std::fmt::Debug for PackIndex {
301
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
302
        f.debug_struct("PackIndex")
64818938 Andy McCall ↶ 303
            .field("key", &self.key)
a17fc622 Andy McCall ↶ 304
            .field("objects", &self.refs.len())
305
            .field("dict", &self.dict.is_some())
306
            .finish()
64818938 Andy McCall ↶ 307
    }
308
}
309
310
/// Decode a stored pack entry and check it against its reference.
311
fn decode_entry(
312
    r: &ObjectRef,
313
    e: PackEntry,
314
    stored: Vec<u8>,
315
    dict: Option<&Arc<zstd::dict::DecoderDictionary<'static>>>,
316
) -> Result<Object> {
317
    let body = if e.flags & FLAG_DICT != 0 {
767ac6cd Andy McCall 318
        let dict = dict.ok_or_else(|| StoreError::Corrupt(*r, NO_DICT.into()))?;
64818938 Andy McCall ↶ 319
        zstd::bulk::Decompressor::with_prepared_dictionary(dict)
320
            .and_then(|mut d| d.decompress(&stored, e.raw_len as usize))
321
            .map_err(|err| StoreError::Corrupt(*r, format!("zstd: {err}")))?
322
    } else if e.flags & FLAG_ZSTD != 0 {
323
        zstd::bulk::decompress(&stored, e.raw_len as usize)
324
            .map_err(|err| StoreError::Corrupt(*r, format!("zstd: {err}")))?
325
    } else {
326
        stored
327
    };
328
    if body.len() != e.raw_len as usize || hash_object(e.ty, &body) != *r {
329
        return Err(StoreError::Corrupt(
330
            *r,
331
            "packed object does not match its reference".into(),
332
        ));
a17fc622 Andy McCall ↶ 333
    }
64818938 Andy McCall ↶ 334
    Ok((e.ty, body))
a17fc622 Andy McCall ↶ 335
}
336
d02e545d Andy McCall ↶ 337
impl PackIndex {
7e0e8e5a Andy McCall ↶ 338
    /// Load a pack's index; `pack_len` is the pack's size, from the listing
767ac6cd Andy McCall 339
    /// that found it (a stat of it would be a request of its own). `None`
340
    /// when the index is gone since the listing: the pack was deleted.
341
    fn load(
342
        backend: &Backend,
343
        idx_key: &str,
344
        pack_key: &str,
345
        pack_len: u64,
346
    ) -> Result<Option<PackIndex>> {
347
        let data = match backend.get(idx_key) {
348
            Ok(d) => d,
349
            Err(BackendError::NotFound(_)) => return Ok(None),
350
            Err(e) => return Err(backend_err(e)),
351
        };
64818938 Andy McCall ↶ 352
        let bad = |m: &str| StoreError::Corrupt(ObjectRef::ZERO, format!("{idx_key}: {m}"));
d02e545d Andy McCall ↶ 353
        if data.len() < 12 || &data[..8] != IDX_MAGIC {
354
            return Err(bad("bad index header"));
355
        }
356
        let count = u32::from_le_bytes(data[8..12].try_into().unwrap()) as usize;
357
        if data.len() != 12 + count * IDX_ENTRY {
358
            return Err(bad("index length mismatch"));
359
        }
360
        let mut refs = Vec::with_capacity(count);
361
        let mut entries = Vec::with_capacity(count);
362
        for i in 0..count {
363
            let e = &data[12 + i * IDX_ENTRY..12 + (i + 1) * IDX_ENTRY];
364
            let r = ObjectRef::from_slice(&e[..32]).unwrap();
365
            if let Some(prev) = refs.last() {
366
                if r <= *prev {
367
                    return Err(bad("index not sorted"));
368
                }
369
            }
370
            refs.push(r);
2b872d07 Andy McCall ↶ 371
            let entry = PackEntry {
d02e545d Andy McCall ↶ 372
                offset: u64::from_le_bytes(e[32..40].try_into().unwrap()),
373
                stored_len: u32::from_le_bytes(e[40..44].try_into().unwrap()),
374
                raw_len: u32::from_le_bytes(e[44..48].try_into().unwrap()),
75167672 Andy McCall 375
                ty: ObjectType::ALL
376
                    .get(e[48] as usize)
377
                    .copied()
378
                    .ok_or_else(|| bad("unknown object type"))?,
d02e545d Andy McCall ↶ 379
                flags: e[49],
2b872d07 Andy McCall ↶ 380
            };
a9f686ed Andy McCall ↶ 381
            if entry.stored_len > MAX_OBJECT_LEN || entry.raw_len > MAX_OBJECT_LEN {
382
                return Err(StoreError::Corrupt(
383
                    r,
384
                    format!(
64818938 Andy McCall ↶ 385
                        "{idx_key}: the index claims an object of {} bytes ({} stored), more than the {MAX_OBJECT_LEN} an object may be",
386
                        entry.raw_len, entry.stored_len
a9f686ed Andy McCall ↶ 387
                    ),
388
                ));
389
            }
390
            if entry.offset.saturating_add(entry.stored_len as u64) > pack_len {
2b872d07 Andy McCall ↶ 391
                return Err(bad("index entry points outside the pack"));
392
            }
393
            entries.push(entry);
d02e545d Andy McCall ↶ 394
        }
64818938 Andy McCall ↶ 395
        let dict_key = format!("{}.dict", pack_key.trim_end_matches(".pack"));
396
        let dict = get_optional(backend, &dict_key)?
397
            .map(|d| Arc::new(zstd::dict::DecoderDictionary::copy(&d)));
767ac6cd Andy McCall 398
        Ok(Some(PackIndex {
64818938 Andy McCall ↶ 399
            key: pack_key.to_string(),
75167672 Andy McCall 400
            refs,
401
            entries,
a17fc622 Andy McCall ↶ 402
            dict,
767ac6cd Andy McCall 403
        }))
d02e545d Andy McCall ↶ 404
    }
405
406
    fn find(&self, r: &ObjectRef) -> Option<PackEntry> {
407
        self.refs.binary_search(r).ok().map(|i| self.entries[i])
408
    }
409
64818938 Andy McCall ↶ 410
    /// Read one entry from the pack: one ranged read, then decode.
411
    fn fetch(&self, backend: &Backend, r: &ObjectRef, e: PackEntry) -> Result<Object> {
412
        let stored = backend
413
            .get_range(&self.key, e.offset..e.offset + e.stored_len as u64)
414
            .map_err(|err| match err {
415
                BackendError::NotFound(_) => StoreError::NotFound(*r),
416
                other => backend_err(other),
a17fc622 Andy McCall ↶ 417
            })?;
64818938 Andy McCall ↶ 418
        decode_entry(r, e, stored, self.dict.as_ref())
d02e545d Andy McCall ↶ 419
    }
420
}
421
422
fn type_index(ty: ObjectType) -> u8 {
423
    ObjectType::ALL.iter().position(|t| *t == ty).unwrap() as u8
424
}
425
426
/// What `pack_loose` did.
427
#[derive(Debug, Clone, Default, PartialEq, Eq)]
428
pub struct PackReport {
429
    pub objects: usize,
430
    pub raw_bytes: u64,
431
    pub packed_bytes: u64,
432
}
433
135212de Andy McCall ↶ 434
/// Packs tolerated before `merge_packs` folds them into one (spec §13.4).
435
pub const MAX_PACKS: usize = 16;
436
ba160f60 Andy McCall ↶ 437
/// What `prune` did.
438
#[derive(Debug, Clone, Default, PartialEq, Eq)]
439
pub struct PruneReport {
440
    pub objects: usize,
441
    pub bytes: u64,
442
    /// Unreachable objects left alone because they are younger than the grace period.
443
    pub deferred: usize,
444
}
445
ff0af1ee unknown 446
#[derive(Debug, thiserror::Error)]
447
pub enum StoreError {
448
    #[error("io: {0}")]
449
    Io(#[from] io::Error),
450
    #[error("corrupt object {0}: {1}")]
451
    Corrupt(ObjectRef, String),
452
    #[error("object {0}")]
453
    Object(#[from] ObjectError),
454
    #[error("object {0} is a {1}, expected {2}")]
455
    WrongType(ObjectRef, &'static str, &'static str),
456
    #[error("object {0} not found")]
457
    NotFound(ObjectRef),
6f8aeb99 Andy McCall ↶ 458
    #[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)")]
a9f686ed Andy McCall ↶ 459
    TooLarge {
460
        kind: &'static str,
461
        size: usize,
462
        limit: u32,
463
    },
ff0af1ee unknown 464
}
465
466
pub type Result<T> = std::result::Result<T, StoreError>;
467
468
pub struct Store {
64818938 Andy McCall ↶ 469
    backend: Arc<Backend>,
470
    /// Temporary files (a pack being streamed) and derived caches (`metas`).
471
    /// For a store in a directory it is that directory.
472
    scratch: PathBuf,
473
    /// The backend is that directory, so the old file paths still hold.
474
    local: bool,
767ac6cd Andy McCall 475
    packs: RefCell<Vec<Arc<PackIndex>>>,
476
    /// The pack listing `packs` was loaded from (key, size, time), to tell
477
    /// whether a look at the store would find anything new.
478
    packs_listed: RefCell<Listed>,
479
    /// When a look at the pack listing for a missed [`Store::has`] last
480
    /// found nothing new.
481
    has_relisted: std::cell::Cell<Option<std::time::Instant>>,
8f10a07a Andy McCall ↶ 482
    /// An open write batch (spec §13.4): objects go here instead of to loose
483
    /// files, and are written out with one `fsync` when the batch finishes.
484
    pending: RefCell<Option<Pending>>,
485
    batch_depth: std::cell::Cell<u32>,
ce14f0d6 Andy McCall ↶ 486
    /// Change metadata already read, from the `metas` cache file.
487
    metas: RefCell<Option<crate::fasthash::FastMap<ObjectRef, crate::state::ChangeMeta>>>,
ef7d4ea6 Andy McCall ↶ 488
    /// The live entry lists (spec §13.7) the pack listing showed: listed
489
    /// and not retired.
490
    entry_lists: RefCell<Vec<String>>,
491
    /// Whether the store is folded: a live entry list is complete.
492
    folded: std::cell::Cell<bool>,
493
    /// Whether the pack listing showed `pack-legacy-folded`.
494
    legacy_folded: std::cell::Cell<bool>,
495
    /// The entry keys of a folded store, read from its lists and journal
496
    /// on the first lookup after the packs were loaded.
497
    entries: RefCell<Option<std::collections::BTreeSet<String>>>,
771661aa Andy McCall ↶ 498
    /// When `entries` was read; past [`ENTRIES_FRESH`] it is read again.
499
    entries_read: std::cell::Cell<Option<std::time::Instant>>,
500
    /// Entry lists already read, by key: written once, so never read
501
    /// twice; those no longer live are let go.
502
    lists_read: RefCell<std::collections::HashMap<String, Arc<Vec<String>>>>,
ef7d4ea6 Andy McCall ↶ 503
    /// Entry keys written in an open batch, added to the journal when the
504
    /// batch is flushed.
505
    journal_queue: RefCell<Vec<String>>,
8f10a07a Andy McCall ↶ 506
}
507
64818938 Andy McCall ↶ 508
impl std::fmt::Debug for Store {
509
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
510
        f.debug_struct("Store")
511
            .field("backend", &self.backend.describe())
512
            .field("scratch", &self.scratch)
513
            .field("packs", &self.packs.borrow().len())
514
            .finish()
515
    }
516
}
517
8f10a07a Andy McCall ↶ 518
/// Objects written since `begin_batch`. Small batches stay in memory and
519
/// become loose objects; once `SPILL_OBJECTS` or `SPILL_BYTES` is exceeded
520
/// the batch streams into a pack file instead.
521
#[derive(Debug)]
522
struct Pending {
523
    buffered: Vec<(ObjectType, Vec<u8>)>,
524
    buffered_bytes: usize,
525
    lookup: std::collections::HashMap<ObjectRef, PendingEntry>,
526
    pack: Option<PendingPack>,
527
    report: PackReport,
ff0af1ee unknown 528
}
529
8f10a07a Andy McCall ↶ 530
#[derive(Debug, Clone, Copy)]
531
enum PendingEntry {
532
    Buffered(usize),
533
    Packed(PackEntry),
534
}
535
536
#[derive(Debug)]
537
struct PendingPack {
538
    id: String,
539
    tmp_path: PathBuf,
540
    writer: io::BufWriter<fs::File>,
541
    offset: u64,
542
    index: Vec<(ObjectRef, PackEntry)>,
543
}
544
545
const SPILL_OBJECTS: usize = 256;
546
const SPILL_BYTES: usize = 8 << 20;
547
548
/// Finishes the enclosing batch when dropped; call `finish` to see errors.
549
pub struct Batch<'a> {
550
    store: &'a Store,
551
    done: bool,
552
}
553
554
impl Batch<'_> {
555
    pub fn finish(mut self) -> Result<()> {
556
        self.done = true;
557
        self.store.finish_batch()
558
    }
559
}
560
561
impl Drop for Batch<'_> {
562
    fn drop(&mut self) {
563
        if !self.done {
564
            let _ = self.store.finish_batch();
565
        }
566
    }
567
}
568
192fad1e Andy McCall ↶ 569
/// Append one stored object to a pending pack and index it.
570
fn write_pack_entry(
571
    pack: &mut PendingPack,
572
    r: &ObjectRef,
573
    ty: ObjectType,
574
    raw_len: usize,
575
    flags: u8,
576
    stored: &[u8],
577
    report: &mut PackReport,
578
) -> Result<PackEntry> {
579
    let header_len = 1 + 1 + 4 + 4 + 32;
580
    pack.writer.write_all(&[type_index(ty), flags])?;
581
    pack.writer
582
        .write_all(&(stored.len() as u32).to_le_bytes())?;
583
    pack.writer.write_all(&(raw_len as u32).to_le_bytes())?;
584
    pack.writer.write_all(&r.0)?;
585
    pack.writer.write_all(stored)?;
586
    let entry = PackEntry {
587
        offset: pack.offset + header_len,
588
        stored_len: stored.len() as u32,
589
        raw_len: raw_len as u32,
590
        ty,
591
        flags,
592
    };
593
    pack.offset += header_len + stored.len() as u64;
594
    pack.index.push((*r, entry));
595
    report.objects += 1;
596
    report.raw_bytes += raw_len as u64;
597
    report.packed_bytes += stored.len() as u64;
598
    Ok(entry)
64818938 Andy McCall ↶ 599
}
600
601
/// A random name for a temporary file or a pack.
602
fn fresh_id() -> String {
603
    let mut nonce = [0u8; 8];
604
    rand::rngs::OsRng.fill_bytes(&mut nonce);
605
    hex::encode(nonce)
606
}
607
608
/// Under `OXY_STORE_BACKEND=memory` every store opens on a store in
609
/// memory shared by directory, so the whole test suite can run without a
610
/// directory store, as it would over a bucket. Objects live for the
611
/// process.
612
fn memory_backend_for(dir: &Path) -> Option<Arc<Backend>> {
613
    use std::collections::HashMap;
614
    use std::sync::{Mutex, OnceLock};
615
    if std::env::var_os("OXY_STORE_BACKEND").as_deref() != Some(std::ffi::OsStr::new("memory")) {
616
        return None;
617
    }
618
    static STORES: OnceLock<Mutex<HashMap<PathBuf, Arc<MemoryStore>>>> = OnceLock::new();
619
    let key = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf());
620
    let mut map = STORES
621
        .get_or_init(Default::default)
622
        .lock()
623
        .unwrap_or_else(|p| p.into_inner());
624
    let store = map
625
        .entry(key)
626
        .or_insert_with(|| Arc::new(MemoryStore::new()))
627
        .clone();
628
    Some(store)
192fad1e Andy McCall ↶ 629
}
630
dd21fd82 Andy McCall ↶ 631
#[cfg(test)]
632
thread_local! {
633
    /// A backend every store opened on this thread uses instead of its
634
    /// directory: tests of a repository kept on a store that is not this
635
    /// disk's directory, with several handles on one store.
636
    pub(crate) static TEST_BACKEND: RefCell<Option<Arc<Backend>>> = const { RefCell::new(None) };
637
}
638
ff0af1ee unknown 639
impl Store {
64818938 Andy McCall ↶ 640
    /// Open the store in `dir`, which is also its scratch directory.
ff0af1ee unknown 641
    pub fn open(dir: impl Into<PathBuf>) -> io::Result<Store> {
642
        let dir = dir.into();
643
        fs::create_dir_all(dir.join("loose"))?;
dd21fd82 Andy McCall ↶ 644
        #[cfg(test)]
645
        if let Some(backend) = TEST_BACKEND.with(|t| t.borrow().clone()) {
646
            return Store::open_on(backend, dir);
647
        }
64818938 Andy McCall ↶ 648
        if let Some(backend) = memory_backend_for(&dir) {
649
            return Store::open_on(backend, dir);
650
        }
651
        let backend: Arc<Backend> =
652
            Arc::new(LocalStore::open(&dir).map_err(|e| io::Error::other(e.to_string()))?);
653
        let mut store = Store::open_on(backend, dir)?;
654
        store.local = true;
655
        Ok(store)
656
    }
657
658
    /// Open the store kept on `backend`, with `scratch` for what must be
659
    /// on this disk: a pack while it is being written, and caches.
660
    pub fn open_on(backend: Arc<Backend>, scratch: impl Into<PathBuf>) -> io::Result<Store> {
661
        let scratch = scratch.into();
662
        fs::create_dir_all(&scratch)?;
75167672 Andy McCall 663
        let store = Store {
64818938 Andy McCall ↶ 664
            backend,
665
            scratch,
666
            local: false,
75167672 Andy McCall 667
            packs: RefCell::new(Vec::new()),
767ac6cd Andy McCall 668
            packs_listed: RefCell::new(Vec::new()),
669
            has_relisted: std::cell::Cell::new(None),
75167672 Andy McCall 670
            pending: RefCell::new(None),
671
            batch_depth: std::cell::Cell::new(0),
ce14f0d6 Andy McCall ↶ 672
            metas: RefCell::new(None),
ef7d4ea6 Andy McCall ↶ 673
            entry_lists: RefCell::new(Vec::new()),
674
            folded: std::cell::Cell::new(false),
675
            legacy_folded: std::cell::Cell::new(false),
676
            entries: RefCell::new(None),
771661aa Andy McCall ↶ 677
            entries_read: std::cell::Cell::new(None),
678
            lists_read: RefCell::new(Default::default()),
ef7d4ea6 Andy McCall ↶ 679
            journal_queue: RefCell::new(Vec::new()),
75167672 Andy McCall 680
        };
681
        store
682
            .reload_packs()
683
            .map_err(|e| io::Error::other(e.to_string()))?;
d02e545d Andy McCall ↶ 684
        Ok(store)
64818938 Andy McCall ↶ 685
    }
686
687
    /// The storage under this store.
688
    pub fn backend(&self) -> &Arc<Backend> {
689
        &self.backend
d02e545d Andy McCall ↶ 690
    }
691
64818938 Andy McCall ↶ 692
    /// Whether the store is the directory `dir()` names, where every key
693
    /// is a file.
694
    pub fn is_local(&self) -> bool {
695
        self.local
767ac6cd Andy McCall 696
    }
697
698
    /// Load the list of packs again, from a new listing: what other
699
    /// writers packed since becomes readable, and packs since retired or
700
    /// deleted are let go. Packs already loaded are kept, not read again.
701
    pub fn refresh(&self) -> Result<()> {
ef7d4ea6 Andy McCall ↶ 702
        *self.entries.borrow_mut() = None;
767ac6cd Andy McCall 703
        self.reload_packs()
704
    }
705
706
    /// The pack listing, with how `packs_listed` records it.
707
    fn list_packs(&self) -> Result<(Vec<strata::Entry>, Listed)> {
708
        let listed = self.backend.list("pack-").map_err(backend_err)?;
709
        let sig = listed
710
            .iter()
711
            .map(|e| (e.key.clone(), e.size, e.modified_ms))
712
            .collect();
713
        Ok((listed, sig))
64818938 Andy McCall ↶ 714
    }
715
767ac6cd Andy McCall 716
    /// Load every pack the listing names that is not retired. An index
717
    /// that is gone by the time it is read (its pack deleted after the
718
    /// listing) is passed over, and the store listed once more, since
719
    /// what replaced it may be new since the first listing.
d02e545d Andy McCall ↶ 720
    fn reload_packs(&self) -> Result<()> {
767ac6cd Andy McCall 721
        let (listed, sig) = self.list_packs()?;
722
        self.load_listed(listed, sig)
723
    }
724
725
    fn load_listed(&self, mut listed: Vec<strata::Entry>, mut sig: Listed) -> Result<()> {
726
        let had: std::collections::HashMap<String, Arc<PackIndex>> = self
727
            .packs
728
            .borrow()
729
            .iter()
730
            .map(|p| (p.key.clone(), p.clone()))
731
            .collect();
732
        let mut loaded: std::collections::HashMap<String, Arc<PackIndex>> = Default::default();
733
        for attempt in 0..2 {
734
            let retired = self.retired_in(&listed)?;
735
            let mut idx_keys: Vec<&str> = listed
736
                .iter()
737
                .map(|e| e.key.as_str())
738
                .filter(|k| k.ends_with(".idx"))
739
                .collect();
740
            idx_keys.sort();
741
            let mut packs = Vec::new();
742
            let mut vanished = false;
743
            for idx in idx_keys {
744
                let pack = format!("{}.pack", idx.trim_end_matches(".idx"));
745
                if retired.contains_key(&pack) {
746
                    continue;
747
                }
748
                let Some(p) = listed.iter().find(|e| e.key == pack) else {
749
                    continue;
750
                };
751
                if let Some(kept) = had.get(&pack).or_else(|| loaded.get(&pack)) {
752
                    packs.push(kept.clone());
753
                    continue;
754
                }
755
                match PackIndex::load(self.backend.as_ref(), idx, &pack, p.size)? {
756
                    Some(index) => {
757
                        let index = Arc::new(index);
758
                        loaded.insert(pack, index.clone());
759
                        packs.push(index);
760
                    }
761
                    None => vanished = true,
762
                }
763
            }
764
            if vanished && attempt == 0 {
765
                (listed, sig) = self.list_packs()?;
766
                continue;
767
            }
ef7d4ea6 Andy McCall ↶ 768
            let lists: Vec<String> = listed
769
                .iter()
770
                .map(|e| e.key.as_str())
771
                .filter(|k| is_entry_list(k) && !retired.contains_key(*k))
772
                .map(str::to_string)
773
                .collect();
774
            self.folded
775
                .set(lists.iter().any(|k| k.ends_with(LIST_SUFFIX)));
776
            self.legacy_folded
777
                .set(listed.iter().any(|e| e.key == LEGACY_FOLDED_KEY));
778
            *self.entry_lists.borrow_mut() = lists;
779
            if *self.packs_listed.borrow() != sig {
780
                *self.entries.borrow_mut() = None;
781
            }
767ac6cd Andy McCall 782
            *self.packs.borrow_mut() = packs;
783
            *self.packs_listed.borrow_mut() = sig;
784
            return Ok(());
785
        }
786
        unreachable!("the second round always returns")
787
    }
788
789
    /// Load the packs again when the pack listing differs from the one
790
    /// they were loaded from; whether it did. What a miss calls before it
791
    /// is believed (oxygenhub#249): another writer may have packed the
792
    /// object, or a repack moved it, since this store loaded its packs.
793
    fn reload_if_changed(&self) -> Result<bool> {
794
        let (listed, sig) = self.list_packs()?;
795
        if *self.packs_listed.borrow() == sig {
796
            return Ok(false);
797
        }
798
        self.load_listed(listed, sig)?;
799
        Ok(true)
800
    }
801
802
    /// The retired record, read when `listed` (a pack listing) shows it
803
    /// holds anything.
804
    fn retired_in(
805
        &self,
806
        listed: &[strata::Entry],
807
    ) -> Result<std::collections::BTreeMap<String, u64>> {
808
        match listed.iter().find(|e| e.key == RETIRED_KEY) {
809
            Some(e) if e.size > 0 => Ok(self.read_retired()?.0),
810
            _ => Ok(Default::default()),
811
        }
812
    }
813
814
    /// The retired record and its version (`None`: never written).
815
    fn read_retired(
ef7d4ea6 Andy McCall ↶ 816
        &self,
817
    ) -> Result<(
818
        std::collections::BTreeMap<String, u64>,
819
        Option<strata::Version>,
820
    )> {
821
        self.read_record(RETIRED_KEY)
822
    }
823
824
    /// A record of `<wall ms> <key>` lines (the retired record, the
825
    /// journal) and its version (`None`: never written).
826
    fn read_record(
767ac6cd Andy McCall 827
        &self,
ef7d4ea6 Andy McCall ↶ 828
        key: &str,
767ac6cd Andy McCall 829
    ) -> Result<(
830
        std::collections::BTreeMap<String, u64>,
831
        Option<strata::Version>,
832
    )> {
ef7d4ea6 Andy McCall ↶ 833
        match self.backend.read_ref(key).map_err(backend_err)? {
767ac6cd Andy McCall 834
            Some((bytes, v)) => Ok((parse_retired(&bytes), Some(v))),
835
            None => Ok((Default::default(), None)),
836
        }
837
    }
838
839
    /// Change the retired record by compare-and-swap, reading it again
840
    /// whenever another writer changed it first. `edit` must give the
841
    /// same result however often it runs.
842
    fn update_retired(
ef7d4ea6 Andy McCall ↶ 843
        &self,
844
        edit: impl FnMut(&mut std::collections::BTreeMap<String, u64>),
845
    ) -> Result<()> {
846
        self.update_record(RETIRED_KEY, "the record of retired packs", edit)
847
    }
848
849
    /// Change a record of `<wall ms> <key>` lines by compare-and-swap, as
850
    /// [`Store::update_retired`] does; `what` names it in the error when
851
    /// other writers kept winning.
852
    fn update_record(
767ac6cd Andy McCall 853
        &self,
ef7d4ea6 Andy McCall ↶ 854
        key: &str,
855
        what: &str,
767ac6cd Andy McCall 856
        mut edit: impl FnMut(&mut std::collections::BTreeMap<String, u64>),
857
    ) -> Result<()> {
858
        for _ in 0..RETIRED_TRIES {
ef7d4ea6 Andy McCall ↶ 859
            let (mut m, version) = self.read_record(key)?;
767ac6cd Andy McCall 860
            let before = m.clone();
861
            edit(&mut m);
ef7d4ea6 Andy McCall ↶ 862
            // Unchanged; a record never written stays unwritten.
863
            if m == before && (version.is_some() || m.is_empty()) {
767ac6cd Andy McCall 864
                return Ok(());
865
            }
866
            match self
867
                .backend
ef7d4ea6 Andy McCall ↶ 868
                .write_ref(key, &encode_retired(&m), version.as_ref())
767ac6cd Andy McCall 869
            {
870
                Ok(_) => return Ok(()),
871
                Err(BackendError::Conflict(_)) => continue,
872
                Err(e) => return Err(backend_err(e)),
873
            }
874
        }
ef7d4ea6 Andy McCall ↶ 875
        Err(StoreError::Io(io::Error::other(format!(
876
            "other writers kept changing {what}; run the command again"
877
        ))))
767ac6cd Andy McCall 878
    }
879
880
    /// Record `keys` (packs, by their `.pack` key, and loose objects) as
881
    /// retired now: kept for the readers still using them, and deleted by
882
    /// a collection at least [`RETIRED_FOR`] later. A key already retired
883
    /// keeps its first time.
884
    fn retire(&self, keys: &[String]) -> Result<()> {
885
        if keys.is_empty() {
886
            return Ok(());
887
        }
888
        let now = now_ms();
889
        self.update_retired(|m| {
890
            for k in keys {
891
                m.entry(k.clone()).or_insert(now);
892
            }
893
        })
894
    }
895
896
    /// Delete what was retired at least `older_than` ago (a collection
897
    /// does, with [`RETIRED_FOR`]): each pack with its index and
898
    /// dictionary, and each loose object a pack now holds. A retired loose
899
    /// object no pack holds any more (the pack that had it was pruned, and
900
    /// the object stored again since) is kept, as an ordinary loose object.
901
    pub fn expire_retired(
902
        &self,
903
        older_than: std::time::Duration,
904
        progress: Progress,
905
    ) -> Result<RetiredReport> {
906
        let (listed, _) = self.list_packs()?;
907
        let retired = self.retired_in(&listed)?;
908
        let mut report = RetiredReport::default();
909
        if retired.is_empty() {
910
            return Ok(report);
911
        }
912
        let now = now_ms();
913
        let older_than = older_than.as_millis() as u64;
914
        let due: Vec<(String, u64)> = retired
64818938 Andy McCall ↶ 915
            .iter()
767ac6cd Andy McCall 916
            .filter(|(_, t)| now.saturating_sub(**t) >= older_than)
917
            .map(|(k, t)| (k.clone(), *t))
d02e545d Andy McCall ↶ 918
            .collect();
767ac6cd Andy McCall 919
        report.kept = retired.len() - due.len();
920
        if due.is_empty() {
921
            return Ok(report);
922
        }
923
        progress(&format!("deleting {} retired files", due.len()));
924
        // Which objects the live packs hold.
925
        self.reload_packs()?;
926
        for (key, _) in &due {
927
            if key.ends_with(".pack") {
928
                self.remove_pack(key)?;
929
                report.packs += 1;
ef7d4ea6 Andy McCall ↶ 930
            } else if is_entry_list(key) {
931
                // An entry list a fold replaced (spec §13.7).
932
                delete(self.backend.as_ref(), key)?;
767ac6cd Andy McCall 933
            } else if let Some(r) = loose_ref(key) {
934
                if self.find_packed(&r).is_some() {
935
                    delete(self.backend.as_ref(), key)?;
936
                    report.loose += 1;
937
                }
d02e545d Andy McCall ↶ 938
            }
939
        }
767ac6cd Andy McCall 940
        self.update_retired(|m| {
941
            for (k, t) in &due {
942
                if m.get(k) == Some(t) {
943
                    m.remove(k);
944
                }
945
            }
946
        })?;
947
        self.reload_packs()?;
948
        Ok(report)
d02e545d Andy McCall ↶ 949
    }
950
767ac6cd Andy McCall 951
    /// The loose objects retired and not yet deleted, by key.
952
    fn retired_loose(&self) -> Result<std::collections::HashSet<String>> {
953
        let (listed, _) = self.list_packs()?;
954
        Ok(self
955
            .retired_in(&listed)?
956
            .into_keys()
957
            .filter(|k| k.starts_with("loose/"))
958
            .collect())
959
    }
960
d02e545d Andy McCall ↶ 961
    pub fn pack_count(&self) -> usize {
962
        self.packs.borrow().len()
963
    }
964
965
    fn find_packed(&self, r: &ObjectRef) -> Option<(usize, PackEntry)> {
75167672 Andy McCall 966
        self.packs
967
            .borrow()
968
            .iter()
969
            .enumerate()
970
            .find_map(|(i, p)| p.find(r).map(|e| (i, e)))
d02e545d Andy McCall ↶ 971
    }
972
767ac6cd Andy McCall 973
    /// Loose objects, with their keys and ages; not those retired, whose
974
    /// objects a pack holds.
64818938 Andy McCall ↶ 975
    fn loose_objects(&self) -> Result<Vec<(ObjectRef, strata::Entry)>> {
767ac6cd Andy McCall 976
        let retired = self.retired_loose()?;
977
        let mut out = self.loose_objects_all()?;
978
        out.retain(|(_, e)| !retired.contains(&e.key));
979
        Ok(out)
980
    }
981
982
    /// Every loose object, retired or not.
983
    fn loose_objects_all(&self) -> Result<Vec<(ObjectRef, strata::Entry)>> {
64818938 Andy McCall ↶ 984
        let mut out: Vec<(ObjectRef, strata::Entry)> = self
985
            .backend
986
            .list("loose/")
987
            .map_err(backend_err)?
988
            .into_iter()
989
            .filter_map(|e| loose_ref(&e.key).map(|r| (r, e)))
990
            .collect();
991
        out.sort_by_key(|(r, _)| *r);
d02e545d Andy McCall ↶ 992
        Ok(out)
993
    }
994
995
    pub fn loose_count(&self) -> io::Result<usize> {
64818938 Andy McCall ↶ 996
        self.loose_objects()
997
            .map(|l| l.len())
998
            .map_err(|e| io::Error::other(e.to_string()))
d02e545d Andy McCall ↶ 999
    }
1000
64818938 Andy McCall ↶ 1001
    /// Move every loose object into a new pack (spec §13.4). Loose objects
1002
    /// are deleted only after the pack and its index are durable.
d02e545d Andy McCall ↶ 1003
    pub fn pack_loose(&self) -> Result<PackReport> {
1004
        let loose = self.loose_objects()?;
75167672 Andy McCall 1005
        self.write_pack(
1006
            &loose.iter().map(|(r, _)| *r).collect::<Vec<_>>(),
64818938 Andy McCall ↶ 1007
            &loose.iter().map(|(_, e)| e.key.clone()).collect::<Vec<_>>(),
75167672 Andy McCall 1008
            &[],
da652d63 Andy McCall ↶ 1009
            ZSTD_LEVEL,
9ae4d15a Andy McCall ↶ 1010
            &mut silent(),
75167672 Andy McCall 1011
        )
da652d63 Andy McCall ↶ 1012
    }
1013
1014
    /// Fold every pack and loose object into one pack compressed at
1015
    /// `level` (spec §13.4): what an explicit `oxy gc` does, as `git gc`
1016
    /// repacks. Returns the report and how many packs were folded in.
1017
    pub fn repack_all(&self, level: i32) -> Result<(PackReport, usize)> {
9ae4d15a Andy McCall ↶ 1018
        self.repack_all_with(level, &mut silent())
1019
    }
1020
1021
    /// [`Store::repack_all`], reporting progress.
1022
    pub fn repack_all_with(&self, level: i32, progress: Progress) -> Result<(PackReport, usize)> {
da652d63 Andy McCall ↶ 1023
        let loose = self.loose_objects()?;
a67914bc Andy McCall ↶ 1024
        let (mut refs, keys, trained): (Vec<ObjectRef>, Vec<String>, bool) = {
da652d63 Andy McCall ↶ 1025
            let packs = self.packs.borrow();
1026
            (
1027
                packs.iter().flat_map(|p| p.refs.iter().copied()).collect(),
64818938 Andy McCall ↶ 1028
                packs.iter().map(|p| p.key.clone()).collect(),
a67914bc Andy McCall ↶ 1029
                packs.first().is_some_and(|p| p.dict.is_some()),
da652d63 Andy McCall ↶ 1030
            )
1031
        };
a67914bc Andy McCall ↶ 1032
        // Nothing loose and one pack already made by a full repack (only
1033
        // such a pack has a trained dictionary): rewriting it would give
1034
        // the same pack. A hub's nightly gc rewrote andymccall/oxygen's
1035
        // 48 000 objects (37 s under its write lock) every time.
1036
        if loose.is_empty() && keys.len() <= 1 && (level == ZSTD_LEVEL || trained) {
da652d63 Andy McCall ↶ 1037
            return Ok((PackReport::default(), 0));
1038
        }
1039
        refs.extend(loose.iter().map(|(r, _)| *r));
64818938 Andy McCall ↶ 1040
        let loose_keys: Vec<String> = loose.into_iter().map(|(_, e)| e.key).collect();
1041
        let n = keys.len();
1042
        let report = self.write_pack(&refs, &loose_keys, &keys, level, progress)?;
da652d63 Andy McCall ↶ 1043
        Ok((report, n))
ba160f60 Andy McCall ↶ 1044
    }
1045
135212de Andy McCall ↶ 1046
    /// Fold every pack into one when there are more than `MAX_PACKS`
1047
    /// (spec §13.4). Returns how many packs were merged.
1048
    pub fn merge_packs(&self) -> Result<usize> {
64818938 Andy McCall ↶ 1049
        let (refs, keys): (Vec<ObjectRef>, Vec<String>) = {
135212de Andy McCall ↶ 1050
            let packs = self.packs.borrow();
1051
            if packs.len() <= MAX_PACKS {
1052
                return Ok(0);
1053
            }
75167672 Andy McCall 1054
            (
1055
                packs.iter().flat_map(|p| p.refs.iter().copied()).collect(),
64818938 Andy McCall ↶ 1056
                packs.iter().map(|p| p.key.clone()).collect(),
75167672 Andy McCall 1057
            )
135212de Andy McCall ↶ 1058
        };
64818938 Andy McCall ↶ 1059
        let n = keys.len();
1060
        self.write_pack(&refs, &[], &keys, ZSTD_LEVEL, &mut silent())?;
135212de Andy McCall ↶ 1061
        Ok(n)
1062
    }
1063
ba160f60 Andy McCall ↶ 1064
    /// Delete every object not in `keep` (spec §21). Loose objects and packs
1065
    /// younger than `grace` are left alone, since a concurrent writer may not
1066
    /// have recorded its references yet. Packs holding unreachable objects
64818938 Andy McCall ↶ 1067
    /// are rewritten without them. Signatures, seal and receipt entries of
1068
    /// deleted objects go too.
75167672 Andy McCall 1069
    pub fn prune(
9ae4d15a Andy McCall ↶ 1070
        &self,
1071
        keep: &std::collections::HashSet<ObjectRef>,
1072
        grace: std::time::Duration,
1073
    ) -> Result<PruneReport> {
1074
        self.prune_with(keep, grace, &mut silent())
1075
    }
1076
1077
    /// [`Store::prune`], reporting progress.
1078
    pub fn prune_with(
75167672 Andy McCall 1079
        &self,
1080
        keep: &std::collections::HashSet<ObjectRef>,
1081
        grace: std::time::Duration,
9ae4d15a Andy McCall ↶ 1082
        progress: Progress,
75167672 Andy McCall 1083
    ) -> Result<PruneReport> {
9ae4d15a Andy McCall ↶ 1084
        progress("pruning loose objects");
64818938 Andy McCall ↶ 1085
        let now = now_ms();
1086
        let grace_ms = grace.as_millis() as u64;
1087
        // An object whose age the store does not know is old enough.
1088
        let old_enough =
1089
            |modified: Option<u64>| modified.is_none_or(|t| now.saturating_sub(t) >= grace_ms);
ba160f60 Andy McCall ↶ 1090
        let mut report = PruneReport::default();
ef7d4ea6 Andy McCall ↶ 1091
        let mut gone: Vec<String> = Vec::new();
767ac6cd Andy McCall 1092
        // Loose objects. A retired one (its object packed) whose object is
1093
        // unreachable goes with it, uncounted: the pack's copy is counted.
1094
        let retired = self.retired_loose()?;
1095
        let mut unretired: Vec<String> = Vec::new();
1096
        for (r, entry) in self.loose_objects_all()? {
ba160f60 Andy McCall ↶ 1097
            if keep.contains(&r) {
1098
                continue;
1099
            }
767ac6cd Andy McCall 1100
            if retired.contains(&entry.key) {
1101
                if old_enough(entry.modified_ms) {
1102
                    delete(self.backend.as_ref(), &entry.key)?;
1103
                    unretired.push(entry.key);
1104
                }
1105
                continue;
1106
            }
64818938 Andy McCall ↶ 1107
            if !old_enough(entry.modified_ms) {
ba160f60 Andy McCall ↶ 1108
                report.deferred += 1;
1109
                continue;
1110
            }
64818938 Andy McCall ↶ 1111
            report.bytes += entry.size;
ba160f60 Andy McCall ↶ 1112
            report.objects += 1;
64818938 Andy McCall ↶ 1113
            delete(self.backend.as_ref(), &entry.key)?;
ef7d4ea6 Andy McCall ↶ 1114
            self.remove_sidecars(&r, &mut gone)?;
767ac6cd Andy McCall 1115
        }
1116
        if !unretired.is_empty() {
1117
            self.update_retired(|m| {
1118
                for k in &unretired {
1119
                    m.remove(k);
1120
                }
1121
            })?;
ba160f60 Andy McCall ↶ 1122
        }
1123
        // Packs: rewrite those that hold unreachable objects.
1124
        let mut keep_refs: Vec<ObjectRef> = Vec::new();
64818938 Andy McCall ↶ 1125
        let mut old_keys: Vec<String> = Vec::new();
ba160f60 Andy McCall ↶ 1126
        let mut rewrite = false;
9ae4d15a Andy McCall ↶ 1127
        progress("pruning packs");
ba160f60 Andy McCall ↶ 1128
        for p in self.packs.borrow().iter() {
1129
            let unreachable = p.refs.iter().filter(|r| !keep.contains(r)).count();
1130
            if unreachable == 0 {
1131
                continue;
1132
            }
64818938 Andy McCall ↶ 1133
            let modified = self
1134
                .backend
1135
                .stat(&p.key)
1136
                .map_err(backend_err)?
1137
                .and_then(|e| e.modified_ms);
1138
            if !old_enough(modified) {
ba160f60 Andy McCall ↶ 1139
                report.deferred += unreachable;
1140
                continue;
1141
            }
1142
            rewrite = true;
64818938 Andy McCall ↶ 1143
            old_keys.push(p.key.clone());
ba160f60 Andy McCall ↶ 1144
            for (r, e) in p.refs.iter().zip(p.entries.iter()) {
1145
                if keep.contains(r) {
1146
                    keep_refs.push(*r);
1147
                } else {
1148
                    report.objects += 1;
1149
                    report.bytes += e.stored_len as u64;
1150
                }
1151
            }
1152
        }
1153
        if rewrite {
1154
            let dropped: Vec<ObjectRef> = {
1155
                let packs = self.packs.borrow();
75167672 Andy McCall 1156
                packs
1157
                    .iter()
64818938 Andy McCall ↶ 1158
                    .filter(|p| old_keys.contains(&p.key))
75167672 Andy McCall 1159
                    .flat_map(|p| p.refs.iter().copied())
1160
                    .filter(|r| !keep.contains(r))
1161
                    .collect()
ba160f60 Andy McCall ↶ 1162
            };
64818938 Andy McCall ↶ 1163
            self.write_pack(&keep_refs, &[], &old_keys, ZSTD_LEVEL, progress)?;
ba160f60 Andy McCall ↶ 1164
            for r in dropped {
ef7d4ea6 Andy McCall ↶ 1165
                self.remove_sidecars(&r, &mut gone)?;
ba160f60 Andy McCall ↶ 1166
            }
1167
        }
ef7d4ea6 Andy McCall ↶ 1168
        self.journal_forget(&gone)?;
ba160f60 Andy McCall ↶ 1169
        Ok(report)
1170
    }
1171
64818938 Andy McCall ↶ 1172
    /// Everything kept beside an object: its signatures and the seal and
1173
    /// receipt entries under it, in both layouts.
ef7d4ea6 Andy McCall ↶ 1174
    /// The entry keys deleted are added to `gone`, for the journal.
1175
    fn remove_sidecars(&self, r: &ObjectRef, gone: &mut Vec<String>) -> Result<()> {
64818938 Andy McCall ↶ 1176
        for index in ["sigs", "seals", "receipts"] {
1177
            delete(self.backend.as_ref(), &legacy_key(index, r))?;
1178
        }
1179
        for index in ["sig", "seal", "receipt"] {
1180
            for e in self
1181
                .backend
1182
                .list(&fanout_prefix(index, r))
1183
                .map_err(backend_err)?
1184
            {
1185
                delete(self.backend.as_ref(), &e.key)?;
ef7d4ea6 Andy McCall ↶ 1186
                gone.push(e.key);
ba160f60 Andy McCall ↶ 1187
            }
1188
        }
1189
        Ok(())
1190
    }
1191
ef7d4ea6 Andy McCall ↶ 1192
    /// Take entry keys a collection deleted out of the journal, so the
1193
    /// next complete fold leaves them out (spec §13.7).
1194
    fn journal_forget(&self, gone: &[String]) -> Result<()> {
1195
        if self.local || gone.is_empty() {
1196
            return Ok(());
1197
        }
1198
        if let Some(set) = self.entries.borrow_mut().as_mut() {
1199
            for k in gone {
1200
                set.remove(k);
1201
            }
1202
        }
1203
        self.update_record(JOURNAL_KEY, "the journal of entries", |m| {
1204
            for k in gone {
1205
                m.remove(k);
1206
            }
1207
        })
1208
    }
1209
64818938 Andy McCall ↶ 1210
    /// Put a complete, synced temporary pack file and its index into the
1211
    /// store; `index` must be sorted by ObjectRef. The pack goes first: an
1212
    /// index never names a pack that is not there.
75167672 Andy McCall 1213
    fn finish_pack_files(
1214
        &self,
1215
        id: &str,
1216
        tmp_pack: &Path,
1217
        index: &[(ObjectRef, PackEntry)],
1218
    ) -> Result<()> {
64818938 Andy McCall ↶ 1219
        let mut idx = Vec::with_capacity(12 + index.len() * IDX_ENTRY);
1220
        idx.extend_from_slice(IDX_MAGIC);
1221
        idx.extend_from_slice(&(index.len() as u32).to_le_bytes());
1222
        for (r, e) in index {
1223
            idx.extend_from_slice(&r.0);
1224
            idx.extend_from_slice(&e.offset.to_le_bytes());
1225
            idx.extend_from_slice(&e.stored_len.to_le_bytes());
1226
            idx.extend_from_slice(&e.raw_len.to_le_bytes());
1227
            idx.extend_from_slice(&[type_index(e.ty), e.flags]);
8f10a07a Andy McCall ↶ 1228
        }
64818938 Andy McCall ↶ 1229
        let put = self
1230
            .backend
1231
            .put_new_file(&format!("pack-{id}.pack"), tmp_pack)
1232
            .map_err(backend_err);
1233
        // A store on another disk copied it; the one in this directory
1234
        // moved it and this finds nothing.
1235
        let _ = fs::remove_file(tmp_pack);
1236
        put?;
1237
        self.backend
1238
            .put_new(&format!("pack-{id}.idx"), &idx)
1239
            .map_err(backend_err)?;
8f10a07a Andy McCall ↶ 1240
        self.reload_packs()
64818938 Andy McCall ↶ 1241
    }
1242
767ac6cd Andy McCall 1243
    /// Remove a pack with its index and dictionary: the index first, so
1244
    /// a store opened meanwhile does not load a pack that is going.
64818938 Andy McCall ↶ 1245
    fn remove_pack(&self, pack_key: &str) -> Result<()> {
1246
        let stem = pack_key.trim_end_matches(".pack");
767ac6cd Andy McCall 1247
        delete(self.backend.as_ref(), &format!("{stem}.idx"))?;
64818938 Andy McCall ↶ 1248
        delete(self.backend.as_ref(), pack_key)?;
1249
        delete(self.backend.as_ref(), &format!("{stem}.dict"))
8f10a07a Andy McCall ↶ 1250
    }
1251
767ac6cd Andy McCall 1252
    /// Write `refs` into a new pack, then retire `loose_keys` and
1253
    /// `old_packs`: they stay in the store, unused by stores opened from
1254
    /// now on, until a collection [`RETIRED_FOR`] later deletes them, so a
1255
    /// reader that loaded its packs before goes on reading (oxygenhub#249).
75167672 Andy McCall 1256
    fn write_pack(
1257
        &self,
1258
        refs: &[ObjectRef],
64818938 Andy McCall ↶ 1259
        loose_keys: &[String],
1260
        old_packs: &[String],
da652d63 Andy McCall ↶ 1261
        level: i32,
9ae4d15a Andy McCall ↶ 1262
        progress: Progress,
75167672 Andy McCall 1263
    ) -> Result<PackReport> {
ba160f60 Andy McCall ↶ 1264
        if refs.is_empty() {
767ac6cd Andy McCall 1265
            self.retire(old_packs)?;
ba160f60 Andy McCall ↶ 1266
            self.reload_packs()?;
d02e545d Andy McCall ↶ 1267
            return Ok(PackReport::default());
1268
        }
ba160f60 Andy McCall ↶ 1269
        let mut refs: Vec<ObjectRef> = refs.to_vec();
1270
        refs.sort();
1271
        refs.dedup();
64818938 Andy McCall ↶ 1272
        let id = fresh_id();
1273
        let tmp_pack = self.scratch.join(format!(".tmp-{id}.pack"));
d02e545d Andy McCall ↶ 1274
        let mut report = PackReport::default();
ba160f60 Andy McCall ↶ 1275
        let mut index: Vec<(ObjectRef, PackEntry)> = Vec::with_capacity(refs.len());
a17fc622 Andy McCall ↶ 1276
        // A full repack of enough objects trains a dictionary for them.
1277
        let dict = if level == REPACK_ZSTD_LEVEL && refs.len() >= DICT_MIN_OBJECTS {
1278
            let _t = crate::timing::phase("pack: train a dictionary");
9ae4d15a Andy McCall ↶ 1279
            progress(&format!("training a dictionary on {} objects", refs.len()));
a17fc622 Andy McCall ↶ 1280
            self.train_dictionary(&refs)
1281
        } else {
1282
            None
1283
        };
1284
        let encoder = dict
1285
            .as_ref()
1286
            .map(|d| zstd::dict::EncoderDictionary::copy(d, level));
64818938 Andy McCall ↶ 1287
        let nocompress = self.nocompress_set()?;
d02e545d Andy McCall ↶ 1288
        {
1289
            let mut f = io::BufWriter::new(fs::File::create(&tmp_pack)?);
1290
            f.write_all(PACK_MAGIC)?;
1291
            let mut offset = PACK_MAGIC.len() as u64;
da652d63 Andy McCall ↶ 1292
            // Read a batch (the store is not shared between threads),
1293
            // compress it on every core, write it in order.
1294
            let mut batches = refs.chunks(1024);
1295
            let mut compressed_batch = Vec::new();
9ae4d15a Andy McCall ↶ 1296
            let total = refs.len();
1297
            let mut reported = usize::MAX;
da652d63 Andy McCall ↶ 1298
            loop {
1299
                if compressed_batch.is_empty() {
1300
                    let Some(batch) = batches.next() else { break };
9ae4d15a Andy McCall ↶ 1301
                    // Every tenth, and the first batch.
1302
                    let tenth = report.objects * 10 / total.max(1);
1303
                    if tenth != reported {
1304
                        reported = tenth;
1305
                        progress(&format!("packing {} of {total} objects", report.objects));
1306
                    }
da652d63 Andy McCall ↶ 1307
                    let mut read: Vec<(ObjectRef, ObjectType, Vec<u8>, bool)> =
1308
                        Vec::with_capacity(batch.len());
1309
                    for r in batch {
1310
                        let (ty, body) = self.get(r)?;
64818938 Andy McCall ↶ 1311
                        read.push((*r, ty, body, nocompress.contains(r)));
75167672 Andy McCall 1312
                    }
da652d63 Andy McCall ↶ 1313
                    use rayon::prelude::*;
1314
                    compressed_batch = read
1315
                        .into_par_iter()
a17fc622 Andy McCall ↶ 1316
                        .map_init(
1317
                            || {
1318
                                encoder.as_ref().and_then(|e| {
1319
                                    zstd::bulk::Compressor::with_prepared_dictionary(e).ok()
1320
                                })
1321
                            },
1322
                            |with_dict, (r, ty, body, raw)| {
1323
                                let packed = if raw {
1324
                                    None
1325
                                } else {
1326
                                    // Small objects with the dictionary;
1327
                                    // a large one has context enough.
1328
                                    let dicted = with_dict
1329
                                        .as_mut()
1330
                                        .filter(|_| body.len() <= DICT_OBJECT_MAX)
1331
                                        .and_then(|c| c.compress(&body).ok())
1332
                                        .map(|c| (FLAG_ZSTD | FLAG_DICT, c));
1333
                                    dicted
1334
                                        .or_else(|| {
1335
                                            zstd::bulk::compress(&body, level)
1336
                                                .ok()
1337
                                                .map(|c| (FLAG_ZSTD, c))
1338
                                        })
1339
                                        .filter(|(_, c)| c.len() < body.len())
1340
                                };
1341
                                (r, ty, body, packed)
1342
                            },
1343
                        )
da652d63 Andy McCall ↶ 1344
                        .collect::<Vec<_>>();
1345
                    compressed_batch.reverse();
1346
                }
1347
                let Some((r, ty, body, packed)) = compressed_batch.pop() else {
1348
                    continue;
1349
                };
1350
                let r = &r;
1351
                let (flags, stored) = match packed {
a17fc622 Andy McCall ↶ 1352
                    Some(c) => c,
da652d63 Andy McCall ↶ 1353
                    None => (0, body.clone()),
cdb5beba Andy McCall ↶ 1354
                };
d02e545d Andy McCall ↶ 1355
                let header_len = 1 + 1 + 4 + 4 + 32;
1356
                f.write_all(&[type_index(ty), flags])?;
1357
                f.write_all(&(stored.len() as u32).to_le_bytes())?;
1358
                f.write_all(&(body.len() as u32).to_le_bytes())?;
1359
                f.write_all(&r.0)?;
1360
                f.write_all(&stored)?;
75167672 Andy McCall 1361
                index.push((
1362
                    *r,
1363
                    PackEntry {
1364
                        offset: offset + header_len,
1365
                        stored_len: stored.len() as u32,
1366
                        raw_len: body.len() as u32,
1367
                        ty,
1368
                        flags,
1369
                    },
1370
                ));
d02e545d Andy McCall ↶ 1371
                offset += header_len + stored.len() as u64;
1372
                report.objects += 1;
1373
                report.raw_bytes += body.len() as u64;
1374
                report.packed_bytes += stored.len() as u64;
1375
            }
1376
            f.flush()?;
1377
            f.get_ref().sync_all()?;
a17fc622 Andy McCall ↶ 1378
        }
1379
        // The dictionary before the pack that needs it becomes visible.
1380
        if let Some(d) = &dict {
64818938 Andy McCall ↶ 1381
            self.backend
1382
                .put_new(&format!("pack-{id}.dict"), d)
1383
                .map_err(backend_err)?;
d02e545d Andy McCall ↶ 1384
        }
9ae4d15a Andy McCall ↶ 1385
        progress(&format!("writing the index of {} objects", index.len()));
8f10a07a Andy McCall ↶ 1386
        self.finish_pack_files(&id, &tmp_pack, &index)?;
767ac6cd Andy McCall 1387
        let mut retired = old_packs.to_vec();
1388
        retired.extend_from_slice(loose_keys);
1389
        self.retire(&retired)?;
d02e545d Andy McCall ↶ 1390
        self.reload_packs()?;
1391
        Ok(report)
ff0af1ee unknown 1392
    }
1393
a17fc622 Andy McCall ↶ 1394
    /// A dictionary for these objects, trained on a sample of them (at
1395
    /// most 10 000, 32 MB); `None` when training fails.
1396
    fn train_dictionary(&self, refs: &[ObjectRef]) -> Option<Vec<u8>> {
1397
        let step = (refs.len() / 10_000).max(1);
1398
        let mut samples: Vec<Vec<u8>> = Vec::new();
1399
        let mut total = 0usize;
1400
        for r in refs.iter().step_by(step) {
1401
            if total > 32 << 20 {
1402
                break;
1403
            }
1404
            let Ok((ty, body)) = self.get(r) else {
1405
                continue;
1406
            };
1407
            if matches!(
1408
                ty,
1409
                ObjectType::Chunk | ObjectType::Blob | ObjectType::Change
1410
            ) && !body.is_empty()
1411
                && body.len() < 1 << 20
1412
            {
1413
                total += body.len();
1414
                samples.push(body);
1415
            }
1416
        }
1417
        zstd::dict::from_samples(&samples, DICT_BYTES).ok()
1418
    }
1419
64818938 Andy McCall ↶ 1420
    /// The scratch directory: for a store in a directory, that directory.
ff0af1ee unknown 1421
    pub fn dir(&self) -> &Path {
64818938 Andy McCall ↶ 1422
        &self.scratch
ff0af1ee unknown 1423
    }
1424
64818938 Andy McCall ↶ 1425
    /// Where a loose object is kept, for a store in a directory (tests
1426
    /// tamper with and remove objects there).
1427
    #[cfg(test)]
387335ff Andy McCall ↶ 1428
    pub(crate) fn path_for(&self, r: &ObjectRef) -> PathBuf {
64818938 Andy McCall ↶ 1429
        self.scratch.join(loose_key(r))
1430
    }
1431
1432
    /// Remove a loose object, whatever the store is on (tests make an
1433
    /// object go missing).
1434
    #[cfg(test)]
1435
    pub(crate) fn remove_loose_for_test(&self, r: &ObjectRef) -> Result<()> {
1436
        delete(self.backend.as_ref(), &loose_key(r))
ff0af1ee unknown 1437
    }
1438
767ac6cd Andy McCall 1439
    /// Whether the store holds `r`. A miss looks at the pack listing
1440
    /// again before it is believed, as [`Store::get`]'s does; a writer
1441
    /// asking about many objects it is about to store looks at most once
1442
    /// in [`HAS_RELIST_AFTER`] while nothing new turns up.
ff0af1ee unknown 1443
    pub fn has(&self, r: &ObjectRef) -> bool {
767ac6cd Andy McCall 1444
        if self.has_now(r) {
1445
            return true;
1446
        }
1447
        let recent = self
1448
            .has_relisted
1449
            .get()
1450
            .is_some_and(|t| t.elapsed() < HAS_RELIST_AFTER);
1451
        if recent {
1452
            return false;
1453
        }
1454
        match self.reload_if_changed() {
1455
            Ok(true) => {
1456
                self.has_relisted.set(None);
1457
                self.has_now(r)
1458
            }
1459
            _ => {
1460
                self.has_relisted.set(Some(std::time::Instant::now()));
1461
                false
1462
            }
1463
        }
1464
    }
1465
1466
    /// [`Store::has`] against the packs as loaded.
1467
    fn has_now(&self, r: &ObjectRef) -> bool {
1468
        self.find_packed(r).is_some()
75167672 Andy McCall 1469
            || self
1470
                .pending
1471
                .borrow()
1472
                .as_ref()
1473
                .is_some_and(|p| p.lookup.contains_key(r))
767ac6cd Andy McCall 1474
            || self.backend.has(&loose_key(r)).unwrap_or(false)
ff0af1ee unknown 1475
    }
1476
8f10a07a Andy McCall ↶ 1477
    /// Start a write batch: until the matching `finish`, `put` collects
1478
    /// objects and writes them out together, with one `fsync` for a large
1479
    /// batch (a pack) instead of one per object. Batches nest; only the
1480
    /// outermost does the work. Objects are readable while pending.
1481
    pub fn begin_batch(&self) -> Result<Batch<'_>> {
1482
        let depth = self.batch_depth.get();
1483
        if depth == 0 {
75167672 Andy McCall 1484
            *self.pending.borrow_mut() = Some(Pending {
1485
                buffered: vec![],
1486
                buffered_bytes: 0,
1487
                lookup: Default::default(),
1488
                pack: None,
1489
                report: PackReport::default(),
1490
            });
8f10a07a Andy McCall ↶ 1491
        }
1492
        self.batch_depth.set(depth + 1);
75167672 Andy McCall 1493
        Ok(Batch {
1494
            store: self,
1495
            done: false,
1496
        })
8f10a07a Andy McCall ↶ 1497
    }
1498
1499
    fn finish_batch(&self) -> Result<()> {
1500
        let depth = self.batch_depth.get();
1501
        if depth == 0 {
1502
            return Ok(());
1503
        }
1504
        self.batch_depth.set(depth - 1);
1505
        if depth > 1 {
1506
            return Ok(());
1507
        }
75167672 Andy McCall 1508
        let Some(pending) = self.pending.borrow_mut().take() else {
ef7d4ea6 Andy McCall ↶ 1509
            return self.flush_journal();
75167672 Andy McCall 1510
        };
ef7d4ea6 Andy McCall ↶ 1511
        self.write_pending(pending)?;
1512
        self.flush_journal()
4dcb8c09 Andy McCall ↶ 1513
    }
1514
1515
    /// Make every object written so far durable, even inside an open
1516
    /// batch, which stays open. Call before a reference that names them
1517
    /// is moved (spec §13.6): the operation head, a bookmark pointer.
1518
    pub fn flush(&self) -> Result<()> {
1519
        let Some(pending) = self.pending.borrow_mut().take() else {
ef7d4ea6 Andy McCall ↶ 1520
            return self.flush_journal();
4dcb8c09 Andy McCall ↶ 1521
        };
1522
        self.write_pending(pending)?;
ef7d4ea6 Andy McCall ↶ 1523
        self.flush_journal()?;
4dcb8c09 Andy McCall ↶ 1524
        *self.pending.borrow_mut() = Some(Pending {
1525
            buffered: vec![],
1526
            buffered_bytes: 0,
1527
            lookup: Default::default(),
1528
            pack: None,
1529
            report: PackReport::default(),
1530
        });
1531
        Ok(())
1532
    }
1533
1534
    fn write_pending(&self, pending: Pending) -> Result<()> {
8f10a07a Andy McCall ↶ 1535
        match pending.pack {
1536
            None => {
b30a880f Andy McCall ↶ 1537
                let objects: Vec<(ObjectType, &[u8])> = pending
1538
                    .buffered
1539
                    .iter()
1540
                    .map(|(ty, body)| (*ty, body.as_slice()))
1541
                    .collect();
1542
                self.put_loose_many(&objects)
8f10a07a Andy McCall ↶ 1543
            }
1544
            Some(mut pack) => {
1545
                pack.writer.flush()?;
1546
                pack.writer.get_ref().sync_all()?;
1547
                drop(pack.writer);
1548
                pack.index.sort_by_key(|(r, _)| *r);
1549
                self.finish_pack_files(&pack.id, &pack.tmp_path, &pack.index)?;
1550
                Ok(())
1551
            }
1552
        }
1553
    }
1554
1555
    /// Whether a batch is open and holds `r`.
64818938 Andy McCall ↶ 1556
    fn pending_get(&self, r: &ObjectRef) -> Option<Result<Object>> {
8f10a07a Andy McCall ↶ 1557
        let mut guard = self.pending.borrow_mut();
1558
        let pending = guard.as_mut()?;
1559
        let entry = *pending.lookup.get(r)?;
1560
        Some(match entry {
1561
            PendingEntry::Buffered(i) => {
1562
                let (ty, body) = &pending.buffered[i];
1563
                Ok((*ty, body.clone()))
1564
            }
1565
            PendingEntry::Packed(e) => {
75167672 Andy McCall 1566
                let Some(pack) = pending.pack.as_mut() else {
1567
                    return Some(Err(StoreError::NotFound(*r)));
1568
                };
64818938 Andy McCall ↶ 1569
                // Read from the pack file being written, on this disk.
1570
                (|| {
1571
                    pack.writer.flush()?;
1572
                    use std::io::{Read, Seek, SeekFrom};
1573
                    let mut f = fs::File::open(&pack.tmp_path)?;
1574
                    f.seek(SeekFrom::Start(e.offset))?;
1575
                    let mut stored = vec![0u8; e.stored_len as usize];
1576
                    f.read_exact(&mut stored)?;
1577
                    decode_entry(r, e, stored, None)
1578
                })()
8f10a07a Andy McCall ↶ 1579
            }
1580
        })
1581
    }
1582
1583
    /// Append one object to the pending pack file.
75167672 Andy McCall 1584
    fn pending_pack_write(
1585
        &self,
1586
        pack: &mut PendingPack,
1587
        r: &ObjectRef,
1588
        ty: ObjectType,
1589
        body: &[u8],
1590
        report: &mut PackReport,
1591
    ) -> Result<PackEntry> {
8f10a07a Andy McCall ↶ 1592
        let (flags, stored) = if self.is_nocompress(r) {
1593
            (0, body.to_vec())
1594
        } else {
75167672 Andy McCall 1595
            let compressed = zstd::bulk::compress(body, ZSTD_LEVEL)
1596
                .map_err(|e| StoreError::Corrupt(*r, format!("zstd: {e}")))?;
1597
            if compressed.len() < body.len() {
1598
                (FLAG_ZSTD, compressed)
1599
            } else {
1600
                (0, body.to_vec())
1601
            }
8f10a07a Andy McCall ↶ 1602
        };
192fad1e Andy McCall ↶ 1603
        write_pack_entry(pack, r, ty, body.len(), flags, &stored, report)
8f10a07a Andy McCall ↶ 1604
    }
1605
1606
    fn put_pending(&self, r: ObjectRef, ty: ObjectType, body: &[u8]) -> Result<()> {
1607
        let mut guard = self.pending.borrow_mut();
1608
        let pending = guard.as_mut().expect("batch open");
1609
        if pending.lookup.contains_key(&r) {
1610
            return Ok(());
1611
        }
75167672 Andy McCall 1612
        if pending.pack.is_none()
1613
            && pending.buffered.len() < SPILL_OBJECTS
1614
            && pending.buffered_bytes + body.len() <= SPILL_BYTES
1615
        {
8f10a07a Andy McCall ↶ 1616
            pending.buffered.push((ty, body.to_vec()));
1617
            pending.buffered_bytes += body.len();
75167672 Andy McCall 1618
            pending
1619
                .lookup
1620
                .insert(r, PendingEntry::Buffered(pending.buffered.len() - 1));
8f10a07a Andy McCall ↶ 1621
            return Ok(());
1622
        }
192fad1e Andy McCall ↶ 1623
        self.ensure_pack(pending)?;
1624
        let mut report = std::mem::take(&mut pending.report);
1625
        let pack = pending.pack.as_mut().unwrap();
1626
        let e = self.pending_pack_write(pack, &r, ty, body, &mut report)?;
1627
        pending.report = report;
1628
        pending.lookup.insert(r, PendingEntry::Packed(e));
1629
        Ok(())
1630
    }
1631
1632
    /// Open the pending batch's pack, moving the objects buffered so far
1633
    /// into it (a spill).
1634
    fn ensure_pack(&self, pending: &mut Pending) -> Result<()> {
8f10a07a Andy McCall ↶ 1635
        if pending.pack.is_none() {
1636
            // Spill: open the pack and move the buffered objects into it.
64818938 Andy McCall ↶ 1637
            let id = fresh_id();
1638
            let tmp_path = self.scratch.join(format!(".tmp-{id}.pack"));
8f10a07a Andy McCall ↶ 1639
            let mut writer = io::BufWriter::new(fs::File::create(&tmp_path)?);
1640
            writer.write_all(PACK_MAGIC)?;
75167672 Andy McCall 1641
            let mut pack = PendingPack {
1642
                id,
1643
                tmp_path,
1644
                writer,
1645
                offset: PACK_MAGIC.len() as u64,
1646
                index: vec![],
1647
            };
8f10a07a Andy McCall ↶ 1648
            let buffered = std::mem::take(&mut pending.buffered);
1649
            pending.buffered_bytes = 0;
1650
            let mut report = std::mem::take(&mut pending.report);
1651
            for (bty, bbody) in &buffered {
1652
                let br = hash_object(*bty, bbody);
1653
                let e = self.pending_pack_write(&mut pack, &br, *bty, bbody, &mut report)?;
1654
                pending.lookup.insert(br, PendingEntry::Packed(e));
1655
            }
1656
            pending.report = report;
1657
            pending.pack = Some(pack);
192fad1e Andy McCall ↶ 1658
        }
1659
        Ok(())
1660
    }
1661
1662
    /// Store many objects at once. Inside a large write batch they are
1663
    /// compressed on every core and appended in order; otherwise each is
1664
    /// stored as [`Store::put`] does.
1665
    pub fn put_many(&self, objects: &[(ObjectType, &[u8])]) -> Result<Vec<ObjectRef>> {
1666
        use rayon::prelude::*;
1667
        let total: usize = objects.iter().map(|(_, b)| b.len()).sum();
1668
        if self.pending.borrow().is_none() || total < SPILL_BYTES {
1669
            return objects.iter().map(|(ty, b)| self.put(*ty, b)).collect();
1670
        }
1671
        for (ty, b) in objects {
1672
            if b.len() > MAX_OBJECT_LEN as usize {
1673
                return Err(StoreError::TooLarge {
1674
                    kind: ty.name(),
1675
                    size: b.len(),
1676
                    limit: MAX_OBJECT_LEN,
1677
                });
1678
            }
8f10a07a Andy McCall ↶ 1679
        }
192fad1e Andy McCall ↶ 1680
        let refs: Vec<ObjectRef> = objects
1681
            .par_iter()
1682
            .map(|(ty, b)| hash_object(*ty, b))
1683
            .collect();
1684
        // What is new: not stored already, not earlier in this call.
1685
        let mut seen: std::collections::HashSet<ObjectRef> = std::collections::HashSet::new();
1686
        let mut todo: Vec<usize> = Vec::new();
1687
        for (i, r) in refs.iter().enumerate() {
1688
            let known = self
1689
                .pending
1690
                .borrow()
1691
                .as_ref()
1692
                .is_some_and(|p| p.lookup.contains_key(r));
1693
            if seen.insert(*r)
1694
                && !known
1695
                && self.find_packed(r).is_none()
64818938 Andy McCall ↶ 1696
                && !self.backend.has(&loose_key(r)).unwrap_or(false)
192fad1e Andy McCall ↶ 1697
            {
1698
                todo.push(i);
1699
            }
1700
        }
64818938 Andy McCall ↶ 1701
        let raw = self.nocompress_set()?;
192fad1e Andy McCall ↶ 1702
        let packed: Vec<(u8, Vec<u8>)> = todo
1703
            .par_iter()
1704
            .map(|i| {
1705
                let body = objects[*i].1;
1706
                if raw.contains(&refs[*i]) {
1707
                    return (0, body.to_vec());
1708
                }
1709
                match zstd::bulk::compress(body, ZSTD_LEVEL) {
1710
                    Ok(c) if c.len() < body.len() => (FLAG_ZSTD, c),
1711
                    _ => (0, body.to_vec()),
1712
                }
1713
            })
1714
            .collect();
1715
        let mut guard = self.pending.borrow_mut();
1716
        let pending = guard.as_mut().expect("batch open");
1717
        self.ensure_pack(pending)?;
8f10a07a Andy McCall ↶ 1718
        let mut report = std::mem::take(&mut pending.report);
1719
        let pack = pending.pack.as_mut().unwrap();
192fad1e Andy McCall ↶ 1720
        for (i, (flags, stored)) in todo.iter().zip(packed) {
1721
            let (ty, body) = objects[*i];
1722
            let e = write_pack_entry(pack, &refs[*i], ty, body.len(), flags, &stored, &mut report)?;
1723
            pending.lookup.insert(refs[*i], PendingEntry::Packed(e));
1724
        }
8f10a07a Andy McCall ↶ 1725
        pending.report = report;
192fad1e Andy McCall ↶ 1726
        Ok(refs)
8f10a07a Andy McCall ↶ 1727
    }
1728
ff0af1ee unknown 1729
    /// Store `body` as an object of type `ty`; idempotent.
1730
    pub fn put(&self, ty: ObjectType, body: &[u8]) -> Result<ObjectRef> {
a9f686ed Andy McCall ↶ 1731
        // Refuse what the store could not read back (spec §13.2), before
1732
        // anything is written: a pack must never hold an entry its index
1733
        // would reject.
1734
        if body.len() > MAX_OBJECT_LEN as usize {
1735
            return Err(StoreError::TooLarge {
1736
                kind: ty.name(),
1737
                size: body.len(),
1738
                limit: MAX_OBJECT_LEN,
1739
            });
1740
        }
ff0af1ee unknown 1741
        let r = hash_object(ty, body);
64818938 Andy McCall ↶ 1742
        if self.find_packed(&r).is_some() || self.backend.has(&loose_key(&r)).unwrap_or(false) {
ff0af1ee unknown 1743
            return Ok(r);
1744
        }
8f10a07a Andy McCall ↶ 1745
        if self.pending.borrow().is_some() {
1746
            self.put_pending(r, ty, body)?;
1747
            return Ok(r);
1748
        }
1749
        self.put_loose(ty, body)?;
1750
        Ok(r)
1751
    }
1752
64818938 Andy McCall ↶ 1753
    /// Write one loose object, durable when this returns.
8f10a07a Andy McCall ↶ 1754
    fn put_loose(&self, ty: ObjectType, body: &[u8]) -> Result<ObjectRef> {
1755
        let r = hash_object(ty, body);
64818938 Andy McCall ↶ 1756
        let mut bytes = header(ty, body.len());
1757
        bytes.extend_from_slice(body);
4dcb8c09 Andy McCall ↶ 1758
        crate::durable::step("write loose object")?;
64818938 Andy McCall ↶ 1759
        put_new_or_existing(self.backend.as_ref(), &loose_key(&r), &bytes)?;
ff0af1ee unknown 1760
        Ok(r)
b30a880f Andy McCall ↶ 1761
    }
1762
1763
    /// Write several loose objects with as few waits on the disk as the
64818938 Andy McCall ↶ 1764
    /// guarantees allow (a directory store writes them all, then syncs
1765
    /// each directory once). Durable when this returns, as `put_loose`
1766
    /// one at a time would be (spec §13.6).
b30a880f Andy McCall ↶ 1767
    fn put_loose_many(&self, objects: &[(ObjectType, &[u8])]) -> Result<()> {
1768
        if objects.len() <= 1 {
1769
            for (ty, body) in objects {
1770
                self.put_loose(*ty, body)?;
1771
            }
1772
            return Ok(());
1773
        }
1774
        let mut seen = std::collections::HashSet::new();
64818938 Andy McCall ↶ 1775
        let items: Vec<(String, Vec<u8>)> = objects
b30a880f Andy McCall ↶ 1776
            .iter()
1777
            .filter_map(|(ty, body)| {
1778
                let r = hash_object(*ty, body);
64818938 Andy McCall ↶ 1779
                seen.insert(r).then(|| {
1780
                    let mut bytes = header(*ty, body.len());
1781
                    bytes.extend_from_slice(body);
1782
                    (loose_key(&r), bytes)
b30a880f Andy McCall ↶ 1783
                })
1784
            })
1785
            .collect();
64818938 Andy McCall ↶ 1786
        self.backend.put_many_new(&items).map_err(backend_err)
ff0af1ee unknown 1787
    }
1788
09245702 Andy McCall ↶ 1789
    /// Read and verify an object, packed, loose, or pending in a batch.
1790
    /// The packs' indexes are in memory, so they are asked first: asking
1791
    /// for a loose copy of a packed object costs a request that finds
1792
    /// nothing on a store in a bucket, every time (oxygenhub#228).
767ac6cd Andy McCall 1793
    ///
1794
    /// A miss is not believed at once (oxygenhub#249): when the pack it
1795
    /// was in is gone (deleted after a repack retired it) the packs are
1796
    /// loaded again, and when the object is nowhere the pack listing is
1797
    /// looked at, and the packs loaded again if it changed (another
1798
    /// writer packed it, or a repack moved it); then it is read once more.
64818938 Andy McCall ↶ 1799
    pub fn get(&self, r: &ObjectRef) -> Result<Object> {
767ac6cd Andy McCall 1800
        match self.get_now(r) {
1801
            Err(e) if is_miss(&e) => {
1802
                // Read from a pack this store loaded, which is gone.
1803
                let packed_miss =
1804
                    !matches!(e, StoreError::NotFound(_)) || self.find_packed(r).is_some();
1805
                let changed = if packed_miss {
1806
                    self.reload_packs()?;
1807
                    true
1808
                } else {
1809
                    self.reload_if_changed()?
1810
                };
1811
                if changed {
1812
                    self.get_now(r)
1813
                } else {
1814
                    Err(e)
1815
                }
1816
            }
1817
            other => other,
1818
        }
1819
    }
1820
1821
    /// [`Store::get`] against the packs as loaded.
1822
    fn get_now(&self, r: &ObjectRef) -> Result<Object> {
09245702 Andy McCall ↶ 1823
        if let Some((i, e)) = self.find_packed(r) {
767ac6cd Andy McCall 1824
            let pack = self.packs.borrow()[i].clone();
1825
            return pack.fetch(self.backend.as_ref(), r, e);
09245702 Andy McCall ↶ 1826
        }
64818938 Andy McCall ↶ 1827
        match get_optional(self.backend.as_ref(), &loose_key(r))? {
1828
            Some(bytes) => parse_loose(&bytes, r),
09245702 Andy McCall ↶ 1829
            None => self.pending_get(r).unwrap_or(Err(StoreError::NotFound(*r))),
afaba5f1 Andy McCall ↶ 1830
        }
1831
    }
1832
09245702 Andy McCall ↶ 1833
    /// Many objects at once, read and verified in parallel: packed ones
1834
    /// from their packs, the others loose (as [`Store::get`], packs first),
1835
    /// then what is pending in a batch. Results are in the order of `refs`.
767ac6cd Andy McCall 1836
    ///
1837
    /// Misses are looked for again as [`Store::get`]'s are, together.
afaba5f1 Andy McCall ↶ 1838
    pub fn get_many(&self, refs: &[ObjectRef]) -> Vec<Result<Object>> {
767ac6cd Andy McCall 1839
        let mut out = self.get_many_now(refs);
1840
        let missed: Vec<usize> = out
1841
            .iter()
1842
            .enumerate()
1843
            .filter(|(_, g)| g.as_ref().is_err_and(is_miss))
1844
            .map(|(i, _)| i)
1845
            .collect();
1846
        if missed.is_empty() {
1847
            return out;
1848
        }
1849
        let packed_miss = missed.iter().any(|i| {
1850
            !matches!(out[*i], Err(StoreError::NotFound(_)))
1851
                || self.find_packed(&refs[*i]).is_some()
1852
        });
1853
        let changed = if packed_miss {
1854
            self.reload_packs().map(|_| true)
1855
        } else {
1856
            self.reload_if_changed()
1857
        };
1858
        match changed {
1859
            Ok(true) => {
1860
                let again: Vec<ObjectRef> = missed.iter().map(|i| refs[*i]).collect();
1861
                for (i, g) in missed.into_iter().zip(self.get_many_now(&again)) {
1862
                    out[i] = g;
1863
                }
1864
            }
1865
            Ok(false) => {}
1866
            Err(e) => {
1867
                let why = e.to_string();
1868
                for i in missed {
1869
                    out[i] = Err(StoreError::Io(io::Error::other(why.clone())));
1870
                }
1871
            }
1872
        }
1873
        out
1874
    }
1875
1876
    /// [`Store::get_many`] against the packs as loaded.
1877
    fn get_many_now(&self, refs: &[ObjectRef]) -> Vec<Result<Object>> {
afaba5f1 Andy McCall ↶ 1878
        use rayon::prelude::*;
64818938 Andy McCall ↶ 1879
        let backend = self.backend.as_ref();
afaba5f1 Andy McCall ↶ 1880
        let packs = self.packs.borrow();
09245702 Andy McCall ↶ 1881
        let place: Vec<Option<(usize, PackEntry)>> = refs
75167672 Andy McCall 1882
            .iter()
09245702 Andy McCall ↶ 1883
            .map(|r| {
afaba5f1 Andy McCall ↶ 1884
                packs
1885
                    .iter()
1886
                    .enumerate()
09245702 Andy McCall ↶ 1887
                    .find_map(|(p, pack)| pack.find(r).map(|e| (p, e)))
afaba5f1 Andy McCall ↶ 1888
            })
1889
            .collect();
767ac6cd Andy McCall 1890
        let indexes: &[Arc<PackIndex>] = &packs;
09245702 Andy McCall ↶ 1891
        let found: Vec<Option<Result<Object>>> = refs
afaba5f1 Andy McCall ↶ 1892
            .par_iter()
09245702 Andy McCall ↶ 1893
            .zip(place.par_iter())
1894
            .map(|(r, at)| match at {
1895
                Some((p, e)) => Some(indexes[*p].fetch(backend, r, *e)),
1896
                None => match get_optional(backend, &loose_key(r)) {
1897
                    Ok(Some(bytes)) => Some(parse_loose(&bytes, r)),
1898
                    Ok(None) => None,
1899
                    Err(e) => Some(Err(e)),
1900
                },
1901
            })
afaba5f1 Andy McCall ↶ 1902
            .collect();
1903
        drop(packs);
1904
        found
1905
            .into_iter()
1906
            .zip(refs)
09245702 Andy McCall ↶ 1907
            .map(|(f, r)| {
1908
                f.unwrap_or_else(|| self.pending_get(r).unwrap_or(Err(StoreError::NotFound(*r))))
afaba5f1 Andy McCall ↶ 1909
            })
1910
            .collect()
ff0af1ee unknown 1911
    }
1912
1913
    pub fn get_typed(&self, r: &ObjectRef, want: ObjectType) -> Result<Vec<u8>> {
1914
        let (ty, body) = self.get(r)?;
1915
        if ty != want {
1916
            return Err(StoreError::WrongType(*r, ty.name(), want.name()));
1917
        }
1918
        Ok(body)
1919
    }
1920
6f8aeb99 Andy McCall ↶ 1921
    /// Store a change and the text blobs (and their chunks) its large
1922
    /// inserts are stored as (spec §6.1).
ff0af1ee unknown 1923
    pub fn put_change(&self, c: &Change) -> Result<ObjectRef> {
5b4c5130 Andy McCall ↶ 1924
        let encoding = crate::timing::phase("store: encode the change and its texts");
17f94b13 Andy McCall ↶ 1925
        let bytes = c.encode_streaming(|batch| self.put_texts(&batch))?;
5b4c5130 Andy McCall ↶ 1926
        drop(encoding);
1927
        let _t = crate::timing::phase("store: put the encoding");
17f94b13 Andy McCall ↶ 1928
        self.put(ObjectType::Change, &bytes)
6f8aeb99 Andy McCall ↶ 1929
    }
1930
17f94b13 Andy McCall ↶ 1931
    /// Store text blobs and their chunks: every chunk at once (compressed
1932
    /// on every core in a large batch), then the blobs.
1933
    pub fn put_texts(&self, texts: &[crate::objects::StoredText]) -> Result<()> {
192fad1e Andy McCall ↶ 1934
        let mut chunks: Vec<(ObjectType, &[u8])> = Vec::new();
1935
        for t in texts {
1936
            if !self.has(&t.blob.hash()) {
1937
                chunks.extend(
1938
                    crate::chunk::chunks(&t.content)
1939
                        .into_iter()
1940
                        .map(|c| (ObjectType::Chunk, c)),
1941
                );
1942
            }
6f8aeb99 Andy McCall ↶ 1943
        }
192fad1e Andy McCall ↶ 1944
        self.put_many(&chunks)?;
1945
        for t in texts {
1946
            self.put(ObjectType::Blob, &t.blob.encode())?;
6f8aeb99 Andy McCall ↶ 1947
        }
17f94b13 Andy McCall ↶ 1948
        Ok(())
ff0af1ee unknown 1949
    }
1950
1951
    pub fn get_change(&self, r: &ObjectRef) -> Result<Change> {
6f8aeb99 Andy McCall ↶ 1952
        Ok(self.get_change_parts(r)?.0)
1953
    }
1954
1955
    /// A change and the objects its stored inserts are made of: each text
1956
    /// blob and its chunks, which travel and are kept with it.
1957
    pub fn get_change_parts(&self, r: &ObjectRef) -> Result<(Change, Vec<ObjectRef>)> {
1958
        let bytes = self.get_typed(r, ObjectType::Change)?;
1959
        let mut parts = Vec::new();
1960
        let mut failed = None;
0f93f49c Andy McCall ↶ 1961
        let decoded = Change::decode_with(&bytes, &mut |text, count, form| match self
1962
            .read_text(text)
1963
        {
6f8aeb99 Andy McCall ↶ 1964
            Ok((blob, content)) => {
1965
                parts.push(*text);
1966
                parts.extend(blob.chunks);
0f93f49c Andy McCall ↶ 1967
                crate::objects::text_lines(&content, count, form)
6f8aeb99 Andy McCall ↶ 1968
            }
1969
            Err(e) => {
1970
                let why = e.to_string();
1971
                failed = Some(e);
1972
                Err(ObjectError::Schema(format!(
1973
                    "text blob {}: {why}",
1974
                    text.short(12)
1975
                )))
1976
            }
1977
        });
1978
        match (decoded, failed) {
1979
            (Ok(c), _) => Ok((c, parts)),
1980
            (Err(_), Some(StoreError::NotFound(t))) => Err(StoreError::Corrupt(
1981
                *r,
1982
                format!("its text blob {} is missing", t.short(12)),
1983
            )),
1984
            (Err(e), _) => Err(StoreError::Corrupt(*r, e.to_string())),
1985
        }
1986
    }
1987
a4fad5b0 Andy McCall ↶ 1988
    /// A change with every insert left without its lines (empty
1989
    /// placeholders), and where each one's lines are, in order: for
1990
    /// history-only states, which read text only for the graphs they build
1991
    /// (see [`Change::decode_skeleton`]).
1992
    pub fn get_change_lazy(&self, r: &ObjectRef) -> Result<(Change, Vec<crate::objects::TextRef>)> {
86e1824f Andy McCall ↶ 1993
        let bytes = self.get_typed(r, ObjectType::Change)?;
a4fad5b0 Andy McCall ↶ 1994
        Change::decode_skeleton(&bytes, *r).map_err(|e| StoreError::Corrupt(*r, e.to_string()))
86e1824f Andy McCall ↶ 1995
    }
1996
69816d68 Andy McCall ↶ 1997
    /// A change's metadata (id, dependencies, author, clock, message, kind)
1998
    /// without its contents: read from its skeleton, so neither its text
1999
    /// blobs nor its inline lines are read (spec §11).
ce14f0d6 Andy McCall ↶ 2000
    ///
2001
    /// Served from the `metas` cache when this store read it before (a
2002
    /// change object can be as large as the tree it adds), as long as the
2003
    /// store still has the change.
69816d68 Andy McCall ↶ 2004
    pub fn get_change_meta(&self, r: &ObjectRef) -> Result<crate::state::ChangeMeta> {
ce14f0d6 Andy McCall ↶ 2005
        if self.metas.borrow().is_none() {
2006
            *self.metas.borrow_mut() = Some(self.read_metas_cache());
2007
        }
2008
        let cached = self.metas.borrow().as_ref().and_then(|m| m.get(r).cloned());
2009
        if let Some(meta) = cached {
2010
            if self.has(r) {
2011
                #[cfg(test)]
2012
                assert_eq!(
2013
                    meta,
2014
                    Change::decode_meta(&self.get_typed(r, ObjectType::Change)?).unwrap(),
2015
                    "the metadata cache holds a change's metadata"
2016
                );
2017
                return Ok(meta);
2018
            }
2019
        }
4d6c9c1b Andy McCall ↶ 2020
        let bytes = self.get_typed(r, ObjectType::Change)?;
ce14f0d6 Andy McCall ↶ 2021
        let meta =
2022
            Change::decode_meta(&bytes).map_err(|e| StoreError::Corrupt(*r, e.to_string()))?;
2023
        self.remember_meta(r, &meta);
2024
        Ok(meta)
2025
    }
2026
2027
    /// The metadata cache: records of a change hash, its metadata in the
2028
    /// flat layout, and the first 8 bytes of BLAKE3 over both, each
2029
    /// appended in one write. Derived only: a record that does not check
64818938 Andy McCall ↶ 2030
    /// ends the reading (a torn write), and the cache can be deleted. It
2031
    /// lives in the scratch directory, on this disk.
ce14f0d6 Andy McCall ↶ 2032
    fn read_metas_cache(&self) -> crate::fasthash::FastMap<ObjectRef, crate::state::ChangeMeta> {
2033
        let mut out = crate::fasthash::FastMap::default();
64818938 Andy McCall ↶ 2034
        let Ok(bytes) = fs::read(self.scratch.join("metas")) else {
ce14f0d6 Andy McCall ↶ 2035
            return out;
2036
        };
2037
        let mut r = crate::flat::Reader::new(&bytes);
2038
        let mut good = 0;
2039
        while !r.at_end() {
2040
            let mut record = || -> std::result::Result<_, ObjectError> {
2041
                let h = r.object()?;
2042
                let body = r.bytes()?;
2043
                let check = r.fixed::<8>()?;
2044
                Ok((h, body, check))
2045
            };
2046
            let Ok((h, body, check)) = record() else {
2047
                break;
2048
            };
2049
            let mut sum = blake3::Hasher::new();
2050
            sum.update(&h.0).update(body);
2051
            if sum.finalize().as_bytes()[..8] != check {
2052
                break;
2053
            }
2054
            match crate::state::ChangeMeta::read_flat(&mut crate::flat::Reader::new(body)) {
2055
                Ok(m) => out.insert(h, m),
2056
                Err(_) => break,
2057
            };
2058
            good += 32 + 4 + body.len() + 8;
2059
        }
2060
        // Cut a bad tail, so records appended later are read.
2061
        if good < bytes.len() {
2062
            let _ = fs::OpenOptions::new()
2063
                .write(true)
64818938 Andy McCall ↶ 2064
                .open(self.scratch.join("metas"))
ce14f0d6 Andy McCall ↶ 2065
                .and_then(|f| f.set_len(good as u64));
2066
        }
2067
        out
2068
    }
2069
2070
    /// Add a change's metadata to the cache; quietly nothing when it
2071
    /// cannot be written (it is only a cache).
2072
    fn remember_meta(&self, r: &ObjectRef, meta: &crate::state::ChangeMeta) {
2073
        let mut body = crate::flat::Writer::default();
2074
        meta.write_flat(&mut body);
2075
        let mut w = crate::flat::Writer::default();
2076
        w.object(r);
2077
        w.bytes(&body.0);
2078
        let mut sum = blake3::Hasher::new();
2079
        sum.update(&r.0).update(&body.0);
2080
        w.fixed(&sum.finalize().as_bytes()[..8]);
2081
        let _ = fs::OpenOptions::new()
2082
            .create(true)
2083
            .append(true)
64818938 Andy McCall ↶ 2084
            .open(self.scratch.join("metas"))
ce14f0d6 Andy McCall ↶ 2085
            .and_then(|mut f| f.write_all(&w.0));
2086
        if let Some(m) = self.metas.borrow_mut().as_mut() {
2087
            m.insert(*r, meta.clone());
2088
        }
69816d68 Andy McCall ↶ 2089
    }
2090
6f8aeb99 Andy McCall ↶ 2091
    fn read_text(&self, r: &ObjectRef) -> Result<(Blob, Vec<u8>)> {
2092
        let blob = Blob::decode(&self.get_typed(r, ObjectType::Blob)?)?;
2093
        let mut content = Vec::with_capacity(blob.length as usize);
2094
        for c in &blob.chunks {
2095
            content.extend(self.get_typed(c, ObjectType::Chunk)?);
2096
        }
2097
        Ok((blob, content))
ff0af1ee unknown 2098
    }
2099
2100
    pub fn put_chunk(&self, bytes: &[u8]) -> Result<ObjectRef> {
2101
        self.put(ObjectType::Chunk, bytes)
2102
    }
2103
cdb5beba Andy McCall ↶ 2104
    /// Store a chunk that packs will keep uncompressed (`nocompress`, spec §13.3).
2105
    pub fn put_chunk_nocompress(&self, bytes: &[u8]) -> Result<ObjectRef> {
8f10a07a Andy McCall ↶ 2106
        let r = hash_object(ObjectType::Chunk, bytes);
64818938 Andy McCall ↶ 2107
        put_new_or_existing(
2108
            self.backend.as_ref(),
2109
            &format!("nocompress/{}", r.to_hex()),
2110
            b"",
2111
        )?;
8f10a07a Andy McCall ↶ 2112
        self.put(ObjectType::Chunk, bytes)
cdb5beba Andy McCall ↶ 2113
    }
2114
2115
    fn is_nocompress(&self, r: &ObjectRef) -> bool {
64818938 Andy McCall ↶ 2116
        self.backend
2117
            .has(&format!("nocompress/{}", r.to_hex()))
2118
            .unwrap_or(false)
2119
    }
2120
2121
    /// Every chunk marked to be kept raw.
2122
    fn nocompress_set(&self) -> Result<std::collections::HashSet<ObjectRef>> {
2123
        Ok(self
2124
            .backend
2125
            .list("nocompress/")
2126
            .map_err(backend_err)?
2127
            .into_iter()
2128
            .filter_map(|e| ObjectRef::from_hex(e.key.trim_start_matches("nocompress/")))
2129
            .collect())
cdb5beba Andy McCall ↶ 2130
    }
2131
86e682c2 Andy McCall ↶ 2132
    pub fn put_state(&self, st: &StateObject) -> Result<ObjectRef> {
2133
        self.put(ObjectType::State, &st.encode())
2134
    }
2135
2136
    pub fn get_state(&self, r: &ObjectRef) -> Result<StateObject> {
2137
        Ok(StateObject::decode(&self.get_typed(r, ObjectType::State)?)?)
2138
    }
2139
5b9c6ad4 Andy McCall ↶ 2140
    pub fn put_attest(&self, a: &Attest) -> Result<ObjectRef> {
2141
        self.put(ObjectType::Attest, &a.encode())
2142
    }
2143
2144
    pub fn get_attest(&self, r: &ObjectRef) -> Result<Attest> {
2145
        Ok(Attest::decode(&self.get_typed(r, ObjectType::Attest)?)?)
fc1a466a Andy McCall ↶ 2146
    }
2147
2148
    pub fn put_receipt(&self, r: &Receipt) -> Result<ObjectRef> {
2149
        self.put(ObjectType::Receipt, &r.encode())
5b9c6ad4 Andy McCall ↶ 2150
    }
2151
fc1a466a Andy McCall ↶ 2152
    pub fn get_receipt(&self, r: &ObjectRef) -> Result<Receipt> {
2153
        Ok(Receipt::decode(&self.get_typed(r, ObjectType::Receipt)?)?)
5b9c6ad4 Andy McCall ↶ 2154
    }
2155
64818938 Andy McCall ↶ 2156
    /// Record `value` under `key` in `index`: one write-once entry, so two
2157
    /// writers of a shared store never lose each other's.
2158
    fn index_add(&self, index: &str, key: &ObjectRef, value: &ObjectRef) -> Result<()> {
ef7d4ea6 Andy McCall ↶ 2159
        debug_assert!(ENTRY_INDEXES.iter().any(|(i, _)| *i == index));
64818938 Andy McCall ↶ 2160
        let entry = format!("{}{}", fanout_prefix(index, key), value.to_hex());
ef7d4ea6 Andy McCall ↶ 2161
        put_new_or_existing(self.backend.as_ref(), &entry, b"")?;
2162
        self.journal_add(entry)
fc1a466a Andy McCall ↶ 2163
    }
2164
64818938 Andy McCall ↶ 2165
    /// The values recorded under `key` in `index`, with those an older
2166
    /// store kept as one list in `legacy`, sorted.
2167
    fn index_get(&self, index: &str, legacy: &str, key: &ObjectRef) -> Result<Vec<ObjectRef>> {
2168
        let mut values: Vec<ObjectRef> = self
ef7d4ea6 Andy McCall ↶ 2169
            .entry_keys(&fanout_prefix(index, key))?
64818938 Andy McCall ↶ 2170
            .into_iter()
ef7d4ea6 Andy McCall ↶ 2171
            .filter_map(|k| k.rsplit('/').next().and_then(ObjectRef::from_hex))
64818938 Andy McCall ↶ 2172
            .collect();
ef7d4ea6 Andy McCall ↶ 2173
        if !self.reads_legacy() {
2174
            // Older lists folded into entries (spec §13.7).
2175
        } else if let Some(bytes) = get_optional(self.backend.as_ref(), &legacy_key(legacy, key))? {
64818938 Andy McCall ↶ 2176
            values.extend(
2177
                String::from_utf8_lossy(&bytes)
2178
                    .lines()
2179
                    .filter_map(ObjectRef::from_hex),
2180
            );
5b9c6ad4 Andy McCall ↶ 2181
        }
fc1a466a Andy McCall ↶ 2182
        values.sort();
64818938 Andy McCall ↶ 2183
        values.dedup();
2184
        Ok(values)
5b9c6ad4 Andy McCall ↶ 2185
    }
2186
fc1a466a Andy McCall ↶ 2187
    /// Record that seal attestation `attest` covers `change`.
2188
    pub fn index_seal(&self, change: &ObjectRef, attest: &ObjectRef) -> Result<()> {
64818938 Andy McCall ↶ 2189
        self.index_add("seal", change, attest)
fc1a466a Andy McCall ↶ 2190
    }
2191
2192
    /// Seal attestations known to cover `change`.
2193
    pub fn seals_for(&self, change: &ObjectRef) -> Result<Vec<ObjectRef>> {
64818938 Andy McCall ↶ 2194
        self.index_get("seal", "seals", change)
fc1a466a Andy McCall ↶ 2195
    }
2196
2197
    /// Record receipt attestation `attest` for `state` (spec §14.6).
c63fed2e Andy McCall ↶ 2198
    /// Keep a short-lived key's certificate (spec §14.7), with its issuer's
2199
    /// signature, indexed by the key it certifies.
2200
    pub fn put_certificate(&self, c: &crate::cert::SignedCertificate) -> Result<ObjectRef> {
2201
        let r = self.put(ObjectType::Certificate, &c.cert.encode())?;
2202
        self.put_signature(&r, &c.sig)?;
2203
        self.index_add("cert", &c.cert.key_id(), &r)?;
2204
        Ok(r)
2205
    }
2206
2207
    /// A kept certificate with its issuer's signature.
2208
    pub fn get_certificate(&self, r: &ObjectRef) -> Result<crate::cert::SignedCertificate> {
2209
        let cert = crate::cert::Certificate::decode(&self.get_typed(r, ObjectType::Certificate)?)?;
2210
        let sig = self
2211
            .signatures(r)?
2212
            .into_iter()
2213
            .find(|s| s.key == cert.issuer)
2214
            .ok_or(StoreError::NotFound(*r))?;
2215
        Ok(crate::cert::SignedCertificate { cert, sig })
2216
    }
2217
2218
    /// The certificate kept for short-lived key `key`, if any.
2219
    pub fn certificate_of(&self, key: &ObjectRef) -> Result<Option<ObjectRef>> {
2220
        Ok(self
2221
            .index_get("cert", "certs", key)?
2222
            .into_iter()
2223
            .find(|r| self.has(r)))
2224
    }
2225
f53cbe7a Andy McCall ↶ 2226
    /// Record `value` under `key` in index `index` (for repository code).
2227
    pub(crate) fn index_add_pub(
2228
        &self,
2229
        index: &str,
2230
        key: &ObjectRef,
2231
        value: &ObjectRef,
2232
    ) -> Result<()> {
2233
        self.index_add(index, key, value)
2234
    }
2235
2236
    /// The values recorded under `key` in index `index` (which has no
2237
    /// older one-list form: the legacy name only has to differ from it).
2238
    pub(crate) fn index_get_pub(&self, index: &str, key: &ObjectRef) -> Result<Vec<ObjectRef>> {
2239
        self.index_get(index, &format!("{index}-lists"), key)
2240
    }
2241
fc1a466a Andy McCall ↶ 2242
    pub fn index_receipt(&self, state: &ObjectRef, attest: &ObjectRef) -> Result<()> {
64818938 Andy McCall ↶ 2243
        self.index_add("receipt", state, attest)
fc1a466a Andy McCall ↶ 2244
    }
2245
2246
    /// Receipt attestations recorded for `state`.
2247
    pub fn receipts_for(&self, state: &ObjectRef) -> Result<Vec<ObjectRef>> {
64818938 Andy McCall ↶ 2248
        self.index_get("receipt", "receipts", state)
fc1a466a Andy McCall ↶ 2249
    }
2250
3a4b3e01 Andy McCall ↶ 2251
    pub fn index_approval(&self, state: &ObjectRef, attest: &ObjectRef) -> Result<()> {
2252
        self.index_add("approval", state, attest)
2253
    }
2254
2255
    /// Approval attestations recorded for `state` (OxygenFlow approval
2256
    /// gates, oxygenhub#235).
2257
    pub fn approvals_for(&self, state: &ObjectRef) -> Result<Vec<ObjectRef>> {
2258
        self.index_get("approval", "approvals", state)
2259
    }
2260
2261
    /// Every state with an approval, for garbage collection.
2262
    pub fn approval_states(&self) -> Result<Vec<ObjectRef>> {
2263
        self.indexed_states("approval", "approvals")
2264
    }
2265
fc1a466a Andy McCall ↶ 2266
    /// Every state with a receipt, for garbage collection.
2267
    pub fn receipt_states(&self) -> Result<Vec<ObjectRef>> {
3a4b3e01 Andy McCall ↶ 2268
        self.indexed_states("receipt", "receipts")
2269
    }
2270
2271
    /// The states an index (`one/<hh>/<rest>/<attest>` entries, and the
2272
    /// packed `many/<hh>/<rest>` lists) holds attestations for.
2273
    fn indexed_states(&self, one: &str, many: &str) -> Result<Vec<ObjectRef>> {
64818938 Andy McCall ↶ 2274
        let mut out: Vec<ObjectRef> = Vec::new();
ef7d4ea6 Andy McCall ↶ 2275
        for key in self.entry_keys(&format!("{one}/"))? {
64818938 Andy McCall ↶ 2276
            // receipt/<hh>/<rest>/<attest>
ef7d4ea6 Andy McCall ↶ 2277
            let mut parts = key.splitn(4, '/');
64818938 Andy McCall ↶ 2278
            let (Some(_), Some(hh), Some(rest), Some(_)) =
2279
                (parts.next(), parts.next(), parts.next(), parts.next())
2280
            else {
2281
                continue;
2282
            };
2283
            out.extend(ObjectRef::from_hex(&format!("{hh}{rest}")));
fc1a466a Andy McCall ↶ 2284
        }
ef7d4ea6 Andy McCall ↶ 2285
        let legacy = if self.reads_legacy() {
2286
            self.backend
2287
                .list(&format!("{many}/"))
2288
                .map_err(backend_err)?
2289
        } else {
2290
            Vec::new()
2291
        };
2292
        for e in legacy {
64818938 Andy McCall ↶ 2293
            let mut parts = e.key.splitn(3, '/');
2294
            let (Some(_), Some(hh), Some(rest)) = (parts.next(), parts.next(), parts.next()) else {
2295
                continue;
2296
            };
2297
            out.extend(ObjectRef::from_hex(&format!("{hh}{rest}")));
2298
        }
fc1a466a Andy McCall ↶ 2299
        out.sort();
64818938 Andy McCall ↶ 2300
        out.dedup();
fc1a466a Andy McCall ↶ 2301
        Ok(out)
5b9c6ad4 Andy McCall ↶ 2302
    }
2303
1983686f Andy McCall ↶ 2304
    pub fn put_identity(&self, id: &Identity) -> Result<ObjectRef> {
2305
        self.put(ObjectType::Identity, &id.encode())
2306
    }
2307
2308
    pub fn get_identity(&self, r: &ObjectRef) -> Result<Identity> {
2309
        Ok(Identity::decode(&self.get_typed(r, ObjectType::Identity)?)?)
2310
    }
2311
64818938 Andy McCall ↶ 2312
    /// Signatures stored alongside object `r` (spec §5.4), one per signing
2313
    /// key, sorted by key. Empty if none.
1983686f Andy McCall ↶ 2314
    pub fn signatures(&self, r: &ObjectRef) -> Result<Vec<Signature>> {
64818938 Andy McCall ↶ 2315
        let mut sigs: Vec<Signature> = Vec::new();
ef7d4ea6 Andy McCall ↶ 2316
        for key in self.entry_keys(&fanout_prefix("sig", r))? {
2317
            // Gone since it was listed or journalled: a collection deleted
2318
            // it with its object, or a new signature by the same signer is
2319
            // replacing it.
2320
            let Some(bytes) = get_optional(self.backend.as_ref(), &key)? else {
2321
                continue;
2322
            };
64818938 Andy McCall ↶ 2323
            sigs.extend(Signature::decode_list(&bytes)?);
1983686f Andy McCall ↶ 2324
        }
64818938 Andy McCall ↶ 2325
        // An older store's one list per object; a signer kept there and
2326
        // here counts once, as written here.
ef7d4ea6 Andy McCall ↶ 2327
        let legacy = if self.reads_legacy() {
2328
            get_optional(self.backend.as_ref(), &legacy_key("sigs", r))?
2329
        } else {
2330
            None
2331
        };
2332
        if let Some(bytes) = legacy {
64818938 Andy McCall ↶ 2333
            for sig in Signature::decode_list(&bytes)? {
2334
                if !sigs.iter().any(|s| s.key == sig.key) {
2335
                    sigs.push(sig);
2336
                }
2337
            }
2338
        }
2339
        sigs.sort_by_key(|s| s.key);
2340
        sigs.dedup_by_key(|s| s.key);
2341
        Ok(sigs)
1983686f Andy McCall ↶ 2342
    }
2343
64818938 Andy McCall ↶ 2344
    /// Attach a signature to object `r`, replacing any earlier one by the
2345
    /// same key: one entry per signer, so the latest by a key is the one
2346
    /// kept, and two signers never touch each other's.
1983686f Andy McCall ↶ 2347
    pub fn put_signature(&self, r: &ObjectRef, sig: &Signature) -> Result<()> {
64818938 Andy McCall ↶ 2348
        let key = format!("{}{}", fanout_prefix("sig", r), sig.key.to_hex());
2349
        let bytes = Signature::encode_list(std::slice::from_ref(sig));
ef7d4ea6 Andy McCall ↶ 2350
        if get_optional(self.backend.as_ref(), &key)?.as_deref() != Some(bytes.as_slice()) {
2351
            delete(self.backend.as_ref(), &key)?;
2352
            put_new_or_existing(self.backend.as_ref(), &key, &bytes)?;
2353
        }
2354
        // Journalled even when the key was there: an older writer's
2355
        // entry is not in the journal or any list.
2356
        self.journal_add(key)
2357
    }
2358
2359
    // ---- the journal and entry lists (spec §13.7, #116)
2360
8156967b Andy McCall ↶ 2361
    /// Whether lookups still read the one-list keys of older stores: until
2362
    /// a complete fold has copied them into per-object entries and the
2363
    /// pack listing shows its marker (spec §13.7).
ef7d4ea6 Andy McCall ↶ 2364
    fn reads_legacy(&self) -> bool {
8156967b Andy McCall ↶ 2365
        !self.legacy_folded.get()
ef7d4ea6 Andy McCall ↶ 2366
    }
2367
8156967b Andy McCall ↶ 2368
    /// Copy every older one-list key's contents into per-object entries,
2369
    /// keeping an entry already there, then write the marker that tells
2370
    /// readers to stop reading those keys. The keys themselves are left
2371
    /// for older readers. A list that cannot be read is passed over, and
2372
    /// said.
2373
    fn fold_legacy(&self, progress: Progress) -> Result<()> {
2374
        let mut copied = 0usize;
2375
        for (index, legacy) in ENTRY_INDEXES {
2376
            for e in self
2377
                .backend
2378
                .list(&format!("{legacy}/"))
2379
                .map_err(backend_err)?
2380
            {
2381
                // <legacy>/<hh>/<rest>
2382
                let mut parts = e.key.splitn(3, '/');
2383
                let (Some(_), Some(hh), Some(rest)) = (parts.next(), parts.next(), parts.next())
2384
                else {
2385
                    continue;
2386
                };
2387
                let Some(r) = ObjectRef::from_hex(&format!("{hh}{rest}")) else {
2388
                    continue;
2389
                };
2390
                let Some(bytes) = get_optional(self.backend.as_ref(), &e.key)? else {
2391
                    continue;
2392
                };
2393
                if index == "sig" {
2394
                    let Ok(sigs) = Signature::decode_list(&bytes) else {
2395
                        progress(&format!("{}: not a list of signatures, passed over", e.key));
2396
                        continue;
2397
                    };
2398
                    for sig in sigs {
2399
                        let key = format!("{}{}", fanout_prefix("sig", &r), sig.key.to_hex());
2400
                        let one = Signature::encode_list(std::slice::from_ref(&sig));
2401
                        put_new_or_existing(self.backend.as_ref(), &key, &one)?;
2402
                        copied += 1;
2403
                    }
2404
                } else {
2405
                    for v in String::from_utf8_lossy(&bytes)
2406
                        .lines()
2407
                        .filter_map(ObjectRef::from_hex)
2408
                    {
2409
                        let key = format!("{}{}", fanout_prefix(index, &r), v.to_hex());
2410
                        put_new_or_existing(self.backend.as_ref(), &key, b"")?;
2411
                        copied += 1;
2412
                    }
2413
                }
2414
            }
2415
        }
2416
        if copied > 0 {
2417
            progress(&format!("{copied} entries copied out of older lists"));
2418
        }
2419
        put_new_or_existing(
2420
            self.backend.as_ref(),
2421
            LEGACY_FOLDED_KEY,
2422
            format!("{}\n", now_ms()).as_bytes(),
2423
        )?;
2424
        self.legacy_folded.set(true);
2425
        Ok(())
2426
    }
2427
ef7d4ea6 Andy McCall ↶ 2428
    /// The entry keys under `prefix` (an index's `<index>/` or one
2429
    /// object's `<index>/<hh>/<rest>/`), sorted: on a folded store from
2430
    /// its lists and journal, with no request; otherwise by listing.
2431
    fn entry_keys(&self, prefix: &str) -> Result<Vec<String>> {
2432
        if let Some(keys) = self.with_entries(|set| {
2433
            set.range(prefix.to_string()..)
2434
                .take_while(|k| k.starts_with(prefix))
2435
                .cloned()
2436
                .collect::<Vec<String>>()
2437
        })? {
2438
            return Ok(keys);
2439
        }
2440
        Ok(self
2441
            .backend
2442
            .list(prefix)
2443
            .map_err(backend_err)?
2444
            .into_iter()
2445
            .map(|e| e.key)
2446
            .collect())
2447
    }
2448
2449
    /// `f` over a folded store's entry keys, read on first use; `None`
2450
    /// when the store is not folded (or is this disk's directory), and
2451
    /// lookups list.
2452
    fn with_entries<T>(
2453
        &self,
2454
        f: impl FnOnce(&std::collections::BTreeSet<String>) -> T,
2455
    ) -> Result<Option<T>> {
2456
        if self.local || !self.folded.get() {
2457
            return Ok(None);
2458
        }
771661aa Andy McCall ↶ 2459
        // Read over the interval ago: list the packs again (a cloud
2460
        // client keeps that listing as long), loading what changed, and
2461
        // read the journal again, so another writer's entry is seen as
2462
        // its pack would be.
2463
        if self
2464
            .entries_read
2465
            .get()
2466
            .is_some_and(|t| t.elapsed() >= ENTRIES_FRESH)
2467
        {
2468
            *self.entries.borrow_mut() = None;
2469
            self.reload_if_changed()?;
2470
            if !self.folded.get() {
2471
                return Ok(None);
2472
            }
2473
        }
ef7d4ea6 Andy McCall ↶ 2474
        if self.entries.borrow().is_none() {
2475
            let Some(set) = self.read_entries()? else {
2476
                return Ok(None);
2477
            };
2478
            *self.entries.borrow_mut() = Some(set);
2479
        }
2480
        Ok(self.entries.borrow().as_ref().map(f))
2481
    }
2482
2483
    /// Every live entry list's keys and every journal line's, folded or
2484
    /// not, with what this handle has queued. A list deleted since the
2485
    /// packs were listed (retired over an hour ago) has the packs listed
2486
    /// again; `None` when one is still missing then, or the store is no
2487
    /// longer folded: lookups list.
2488
    fn read_entries(&self) -> Result<Option<std::collections::BTreeSet<String>>> {
2489
        'attempt: for attempt in 0..2 {
2490
            if !self.folded.get() {
2491
                return Ok(None);
2492
            }
2493
            let mut set = std::collections::BTreeSet::new();
2494
            let lists = self.entry_lists.borrow().clone();
771661aa Andy McCall ↶ 2495
            self.lists_read
2496
                .borrow_mut()
2497
                .retain(|k, _| lists.contains(k));
ef7d4ea6 Andy McCall ↶ 2498
            for key in &lists {
771661aa Andy McCall ↶ 2499
                let known = self.lists_read.borrow().get(key).cloned();
2500
                let keys = match known {
2501
                    Some(keys) => keys,
2502
                    None => match get_optional(self.backend.as_ref(), key)? {
2503
                        Some(bytes) => {
2504
                            let keys = Arc::new(decode_entry_list(key, &bytes)?);
2505
                            self.lists_read
2506
                                .borrow_mut()
2507
                                .insert(key.clone(), keys.clone());
2508
                            keys
2509
                        }
2510
                        None if attempt == 0 => {
2511
                            self.reload_packs()?;
2512
                            continue 'attempt;
2513
                        }
2514
                        None => return Ok(None),
2515
                    },
2516
                };
2517
                set.extend(keys.iter().cloned());
ef7d4ea6 Andy McCall ↶ 2518
            }
2519
            set.extend(self.read_record(JOURNAL_KEY)?.0.into_keys());
2520
            set.extend(self.journal_queue.borrow().iter().cloned());
771661aa Andy McCall ↶ 2521
            self.entries_read.set(Some(std::time::Instant::now()));
ef7d4ea6 Andy McCall ↶ 2522
            return Ok(Some(set));
2523
        }
2524
        Ok(None)
2525
    }
2526
2527
    /// Add an entry key this handle wrote to the journal: at once, or
2528
    /// when the open batch is flushed. One the handle already knows from
2529
    /// the lists or the journal is not added again. Nothing on this
2530
    /// disk's directory.
2531
    fn journal_add(&self, key: String) -> Result<()> {
2532
        if self.local {
2533
            return Ok(());
2534
        }
2535
        if let Some(set) = self.entries.borrow_mut().as_mut() {
2536
            if !set.insert(key.clone()) {
2537
                return Ok(());
2538
            }
2539
        }
2540
        if self.batch_depth.get() > 0 {
2541
            self.journal_queue.borrow_mut().push(key);
2542
            return Ok(());
2543
        }
2544
        self.journal_append(std::slice::from_ref(&key))
2545
    }
2546
2547
    /// Add what the open batch queued to the journal.
2548
    fn flush_journal(&self) -> Result<()> {
2549
        let queued = std::mem::take(&mut *self.journal_queue.borrow_mut());
2550
        self.journal_append(&queued)
2551
    }
2552
2553
    /// Add `keys` to the journal, unfolded, in one compare-and-swap
2554
    /// update, dropping lines folded over an hour ago; past
2555
    /// [`JOURNAL_FOLD_AT`] unfolded lines, fold them into a partial list.
2556
    fn journal_append(&self, keys: &[String]) -> Result<()> {
2557
        if keys.is_empty() {
64818938 Andy McCall ↶ 2558
            return Ok(());
ef7d4ea6 Andy McCall ↶ 2559
        }
2560
        let now = now_ms();
2561
        let mut unfolded = 0;
2562
        self.update_record(JOURNAL_KEY, "the journal of entries", |m| {
2563
            expire_folded(m, now);
2564
            for k in keys {
2565
                m.entry(k.clone()).or_insert(0);
2566
            }
2567
            unfolded = m.values().filter(|t| **t == 0).count();
2568
        })?;
2569
        if unfolded > JOURNAL_FOLD_AT {
2570
            self.fold_journal()?;
2571
        }
2572
        Ok(())
2573
    }
2574
2575
    /// Fold the journal's unfolded lines into a partial entry list, and
2576
    /// mark them folded. Lines added meanwhile stay unfolded.
2577
    fn fold_journal(&self) -> Result<()> {
2578
        let (journal, _) = self.read_record(JOURNAL_KEY)?;
2579
        let keys: Vec<String> = journal
2580
            .into_iter()
2581
            .filter(|(_, t)| *t == 0)
2582
            .map(|(k, _)| k)
2583
            .collect();
2584
        if keys.is_empty() {
2585
            return Ok(());
2586
        }
2587
        self.put_entry_list(PART_SUFFIX, keys.iter())?;
2588
        self.mark_folded(&keys)
2589
    }
2590
2591
    /// Mark these journal lines folded now, if they are not yet; drop
2592
    /// those folded over an hour ago.
2593
    fn mark_folded(&self, keys: &[String]) -> Result<()> {
2594
        let now = now_ms();
2595
        self.update_record(JOURNAL_KEY, "the journal of entries", |m| {
2596
            expire_folded(m, now);
2597
            for k in keys {
2598
                if let Some(t) = m.get_mut(k) {
2599
                    if *t == 0 {
2600
                        *t = now;
2601
                    }
2602
                }
2603
            }
2604
        })
2605
    }
2606
2607
    /// Write a new entry list of `keys` (sorted), complete or partial by
2608
    /// `suffix`; its key.
2609
    fn put_entry_list<'a>(
2610
        &self,
2611
        suffix: &str,
2612
        keys: impl Iterator<Item = &'a String>,
2613
    ) -> Result<String> {
2614
        let key = format!("pack-{}{suffix}", fresh_id());
2615
        let bytes = encode_entry_list(keys)?;
2616
        self.backend.put_new(&key, &bytes).map_err(backend_err)?;
2617
        Ok(key)
2618
    }
2619
2620
    /// Fold every signature and index entry into one complete entry list
8156967b Andy McCall ↶ 2621
    /// (spec §13.7), what a collection does last: first the older
2622
    /// one-list keys into per-object entries, once; then the journal's lines and
ef7d4ea6 Andy McCall ↶ 2623
    /// a listing of every entry prefix, written as a new list, every list
2624
    /// the packs' listing showed retired, and the journal lines read
2625
    /// marked folded. Nothing when the store is this disk's directory, or
2626
    /// when the one live list already holds exactly these entries and the
2627
    /// journal has nothing unfolded. Whether a list was written.
2628
    pub fn fold_entries(&self, progress: Progress) -> Result<bool> {
2629
        if self.local {
2630
            return Ok(false);
1983686f Andy McCall ↶ 2631
        }
ef7d4ea6 Andy McCall ↶ 2632
        self.reload_packs()?;
8156967b Andy McCall ↶ 2633
        if !self.legacy_folded.get() {
2634
            progress("folding older lists of signatures and index entries");
2635
            self.fold_legacy(progress)?;
2636
        }
ef7d4ea6 Andy McCall ↶ 2637
        let (journal, _) = self.read_record(JOURNAL_KEY)?;
2638
        progress("folding signatures and index entries");
2639
        let mut all: std::collections::BTreeSet<String> = journal.keys().cloned().collect();
2640
        for (index, _) in ENTRY_INDEXES {
2641
            for e in self
2642
                .backend
2643
                .list(&format!("{index}/"))
2644
                .map_err(backend_err)?
2645
            {
2646
                all.insert(e.key);
2647
            }
2648
        }
2649
        let lists = self.entry_lists.borrow().clone();
2650
        let unfolded: Vec<String> = journal
2651
            .iter()
2652
            .filter(|(_, t)| **t == 0)
2653
            .map(|(k, _)| k.clone())
2654
            .collect();
2655
        if unfolded.is_empty() && lists.len() == 1 && lists[0].ends_with(LIST_SUFFIX) {
2656
            if let Some(bytes) = get_optional(self.backend.as_ref(), &lists[0])? {
2657
                let held: std::collections::BTreeSet<String> =
2658
                    decode_entry_list(&lists[0], &bytes)?.into_iter().collect();
2659
                if held == all {
2660
                    return Ok(false);
2661
                }
2662
            }
2663
        }
2664
        self.put_entry_list(LIST_SUFFIX, all.iter())?;
2665
        self.retire(&lists)?;
2666
        if !unfolded.is_empty() {
2667
            self.mark_folded(&unfolded)?;
2668
        }
2669
        *self.entries.borrow_mut() = None;
2670
        self.reload_packs()?;
2671
        Ok(true)
1983686f Andy McCall ↶ 2672
    }
2673
54e2e630 Andy McCall ↶ 2674
    /// Finish packs a writer left unfinished: a batch writes its objects to
2675
    /// `.tmp-ID.pack` and only indexes it at the end, so a process that
2676
    /// stopped part way (an import killed after hours) leaves every object
2677
    /// in a pack nothing can read. Each such pack untouched for `min_age`
2678
    /// is read through: every whole entry checked against its reference,
2679
    /// a torn last one cut off, then indexed as a pack of the store.
2680
    /// Returns the packs and objects adopted.
2681
    pub fn adopt_unfinished_packs(
2682
        &self,
2683
        min_age: std::time::Duration,
2684
        progress: &dyn Fn(&str),
2685
    ) -> Result<(usize, usize)> {
2686
        use std::io::{BufReader, Read};
2687
        let mut packs = 0;
2688
        let mut objects = 0;
2689
        let Ok(dir) = fs::read_dir(&self.scratch) else {
2690
            return Ok((0, 0));
2691
        };
2692
        for entry in dir.flatten() {
2693
            let name = entry.file_name().to_string_lossy().to_string();
2694
            let Some(id) = name
2695
                .strip_prefix(".tmp-")
2696
                .and_then(|n| n.strip_suffix(".pack"))
2697
            else {
2698
                continue;
2699
            };
2700
            let path = entry.path();
2701
            let meta = fs::metadata(&path)?;
2702
            let age = meta
2703
                .modified()
2704
                .ok()
2705
                .and_then(|m| m.elapsed().ok())
2706
                .unwrap_or_default();
2707
            if age < min_age {
2708
                progress(&format!(
2709
                    "{name}: written to {}s ago, left alone",
2710
                    age.as_secs()
2711
                ));
2712
                continue;
2713
            }
2714
            let mut f = BufReader::with_capacity(1 << 20, fs::File::open(&path)?);
2715
            let mut magic = [0u8; 8];
2716
            if f.read_exact(&mut magic).is_err() || &magic != PACK_MAGIC {
2717
                progress(&format!("{name}: not a pack, left alone"));
2718
                continue;
2719
            }
2720
            let mut offset = PACK_MAGIC.len() as u64;
2721
            let mut index: Vec<(ObjectRef, PackEntry)> = Vec::new();
2722
            loop {
2723
                let mut head = [0u8; 42];
2724
                if f.read_exact(&mut head).is_err() {
2725
                    break;
2726
                }
2727
                let Some(ty) = ObjectType::ALL.get(head[0] as usize).copied() else {
2728
                    break;
2729
                };
2730
                let flags = head[1];
2731
                let stored_len = u32::from_le_bytes(head[2..6].try_into().unwrap());
2732
                let raw_len = u32::from_le_bytes(head[6..10].try_into().unwrap());
2733
                let r = ObjectRef(head[10..42].try_into().unwrap());
2734
                let mut stored = vec![0u8; stored_len as usize];
2735
                if flags & FLAG_DICT != 0 || f.read_exact(&mut stored).is_err() {
2736
                    break;
2737
                }
2738
                let e = PackEntry {
2739
                    offset: offset + 42,
2740
                    stored_len,
2741
                    raw_len,
2742
                    ty,
2743
                    flags,
2744
                };
2745
                if decode_entry(&r, e, stored, None).is_err() {
2746
                    break;
2747
                }
2748
                index.push((r, e));
2749
                offset += 42 + stored_len as u64;
2750
                if index.len().is_multiple_of(200_000) {
2751
                    progress(&format!(
2752
                        "{name}: {} objects checked, {} MiB",
2753
                        index.len(),
2754
                        offset >> 20
2755
                    ));
2756
                }
2757
            }
2758
            if index.is_empty() {
2759
                progress(&format!("{name}: no whole object, left alone"));
2760
                continue;
2761
            }
2762
            if offset < meta.len() {
2763
                progress(&format!(
2764
                    "{name}: {} torn bytes at the end cut off",
2765
                    meta.len() - offset
2766
                ));
2767
                fs::OpenOptions::new()
2768
                    .write(true)
2769
                    .open(&path)?
2770
                    .set_len(offset)?;
2771
            }
2772
            index.sort_by_key(|(r, _)| *r);
2773
            index.dedup_by_key(|(r, _)| *r);
2774
            objects += index.len();
2775
            packs += 1;
2776
            progress(&format!("{name}: {} objects indexed", index.len()));
2777
            self.finish_pack_files(id, &path, &index)?;
2778
        }
2779
        Ok((packs, objects))
2780
    }
2781
d02e545d Andy McCall ↶ 2782
    /// Every object reference in the store, loose and packed (slow; for gc and tests).
ff0af1ee unknown 2783
    pub fn list(&self) -> io::Result<Vec<ObjectRef>> {
64818938 Andy McCall ↶ 2784
        let mut out: Vec<ObjectRef> = self
2785
            .loose_objects()
2786
            .map_err(|e| io::Error::other(e.to_string()))?
2787
            .into_iter()
2788
            .map(|(r, _)| r)
2789
            .collect();
d02e545d Andy McCall ↶ 2790
        for p in self.packs.borrow().iter() {
2791
            out.extend(p.refs.iter().copied());
ff0af1ee unknown 2792
        }
2793
        out.sort();
d02e545d Andy McCall ↶ 2794
        out.dedup();
ff0af1ee unknown 2795
        Ok(out)
767ac6cd Andy McCall 2796
    }
2797
}
2798
2799
/// Whether a read failed in a way a newer list of packs may cure: the
2800
/// object was not found, or its pack's dictionary is gone.
2801
fn is_miss(e: &StoreError) -> bool {
2802
    match e {
2803
        StoreError::NotFound(_) => true,
2804
        StoreError::Corrupt(_, why) => why == NO_DICT,
2805
        _ => false,
ff0af1ee unknown 2806
    }
afaba5f1 Andy McCall ↶ 2807
}
2808
64818938 Andy McCall ↶ 2809
/// A loose object's bytes, verified against `r`.
2810
fn parse_loose(data: &[u8], r: &ObjectRef) -> Result<Object> {
2811
    let nul = data
2812
        .iter()
2813
        .position(|&b| b == 0)
2814
        .ok_or_else(|| StoreError::Corrupt(*r, "no header".into()))?;
2815
    let head = std::str::from_utf8(&data[..nul])
2816
        .map_err(|_| StoreError::Corrupt(*r, "header not UTF-8".into()))?;
2817
    let mut parts = head.split(' ');
2818
    let (Some("oxy1"), Some(ty), Some(len), None) =
2819
        (parts.next(), parts.next(), parts.next(), parts.next())
2820
    else {
2821
        return Err(StoreError::Corrupt(*r, format!("bad header {head:?}")));
afaba5f1 Andy McCall ↶ 2822
    };
64818938 Andy McCall ↶ 2823
    let ty = ObjectType::from_name(ty)
2824
        .ok_or_else(|| StoreError::Corrupt(*r, format!("unknown type {ty}")))?;
2825
    let len: usize = len
2826
        .parse()
2827
        .map_err(|_| StoreError::Corrupt(*r, "bad length".into()))?;
2828
    let body = &data[nul + 1..];
2829
    if body.len() != len {
2830
        return Err(StoreError::Corrupt(
2831
            *r,
2832
            format!("length {} != header {len}", body.len()),
2833
        ));
2834
    }
2835
    if hash_object(ty, body) != *r {
2836
        return Err(StoreError::Corrupt(*r, "hash mismatch".into()));
2837
    }
2838
    Ok((ty, body.to_vec()))
2839
}
2840
2841
/// Whether the objects are files that a test may tamper with: not under
2842
/// `OXY_STORE_BACKEND=memory`.
2843
#[cfg(test)]
2844
fn files_on_disk() -> bool {
2845
    std::env::var_os("OXY_STORE_BACKEND").is_none()
ff0af1ee unknown 2846
}
2847
2848
#[cfg(test)]
2849
mod tests {
2850
    use super::*;
64818938 Andy McCall ↶ 2851
2852
    /// The store under test twice: in a directory, and on a store in
2853
    /// memory with a scratch directory, as over a bucket.
2854
    fn each_store(dir: &Path, f: impl Fn(&str, Store)) {
2855
        f("directory", Store::open(dir.join("objects")).unwrap());
2856
        f(
2857
            "memory",
2858
            Store::open_on(Arc::new(MemoryStore::new()), dir.join("scratch")).unwrap(),
2859
        );
2860
    }
ff0af1ee unknown 2861
2862
    #[test]
2863
    fn put_get_verify() {
64818938 Andy McCall ↶ 2864
        if !super::files_on_disk() {
2865
            return;
2866
        }
ff0af1ee unknown 2867
        let dir = tempfile::tempdir().unwrap();
2868
        let s = Store::open(dir.path().join("objects")).unwrap();
2869
        let r = s.put(ObjectType::Chunk, b"hello").unwrap();
2870
        assert!(s.has(&r));
2871
        assert_eq!(s.get(&r).unwrap(), (ObjectType::Chunk, b"hello".to_vec()));
2872
        assert_eq!(s.put(ObjectType::Chunk, b"hello").unwrap(), r);
2873
        assert_eq!(s.list().unwrap(), vec![r]);
75167672 Andy McCall 2874
        assert!(matches!(
2875
            s.get_typed(&r, ObjectType::Blob),
2876
            Err(StoreError::WrongType(..))
2877
        ));
2878
        assert!(matches!(
2879
            s.get(&ObjectRef([9; 32])),
2880
            Err(StoreError::NotFound(_))
2881
        ));
ff0af1ee unknown 2882
2883
        // Tamper: flip a byte, read must fail.
2884
        let path = s.path_for(&r);
2885
        let mut data = fs::read(&path).unwrap();
2886
        let last = data.len() - 1;
2887
        data[last] ^= 1;
2888
        fs::write(&path, data).unwrap();
2889
        assert!(matches!(s.get(&r), Err(StoreError::Corrupt(..))));
2890
    }
2891
2892
    #[test]
d02e545d Andy McCall ↶ 2893
    fn packing_keeps_every_object_readable() {
64818938 Andy McCall ↶ 2894
        if !super::files_on_disk() {
2895
            return;
2896
        }
d02e545d Andy McCall ↶ 2897
        let dir = tempfile::tempdir().unwrap();
2898
        let s = Store::open(dir.path()).unwrap();
2899
        let mut refs = Vec::new();
2900
        for i in 0..300u32 {
2901
            let body = format!("object {i} ").repeat(1 + (i % 7) as usize);
2902
            refs.push((s.put(ObjectType::Chunk, body.as_bytes()).unwrap(), body));
2903
        }
2904
        let c = crate::objects::tests::sample_change();
2905
        let cr = s.put_change(&c).unwrap();
2906
        assert_eq!(s.loose_count().unwrap(), 301);
2907
        let report = s.pack_loose().unwrap();
2908
        assert_eq!(report.objects, 301);
2909
        assert!(report.packed_bytes < report.raw_bytes, "{report:?}");
2910
        assert_eq!(s.loose_count().unwrap(), 0);
2911
        assert_eq!(s.pack_count(), 1);
2912
        for (r, body) in &refs {
2913
            assert!(s.has(r));
75167672 Andy McCall 2914
            assert_eq!(
2915
                s.get(r).unwrap(),
2916
                (ObjectType::Chunk, body.as_bytes().to_vec())
2917
            );
d02e545d Andy McCall ↶ 2918
        }
2919
        assert_eq!(s.get_change(&cr).unwrap(), c);
2920
        assert_eq!(s.list().unwrap().len(), 301);
2921
        // Re-putting a packed object is a no-op; new objects go loose and a
2922
        // second pack coexists with the first.
75167672 Andy McCall 2923
        assert_eq!(
2924
            s.put(ObjectType::Chunk, refs[0].1.as_bytes()).unwrap(),
2925
            refs[0].0
2926
        );
d02e545d Andy McCall ↶ 2927
        assert_eq!(s.loose_count().unwrap(), 0);
2928
        let extra = s.put(ObjectType::Chunk, b"after packing").unwrap();
2929
        s.pack_loose().unwrap();
2930
        assert_eq!(s.pack_count(), 2);
2931
        assert_eq!(s.get(&extra).unwrap().1, b"after packing");
2932
        // A reopened store sees the packs.
2933
        let s2 = Store::open(dir.path()).unwrap();
2934
        assert_eq!(s2.pack_count(), 2);
2935
        assert_eq!(s2.get(&refs[5].0).unwrap().1, refs[5].1.as_bytes());
75167672 Andy McCall 2936
        assert!(matches!(
2937
            s2.get(&ObjectRef([9; 32])),
2938
            Err(StoreError::NotFound(_))
2939
        ));
d02e545d Andy McCall ↶ 2940
        // Corrupting an object's body inside the pack is detected on read.
2941
        let target = refs[5].0;
2942
        let (pack_path, offset) = {
2943
            let packs = s2.packs.borrow();
2944
            let (i, e) = s2.find_packed(&target).unwrap();
64818938 Andy McCall ↶ 2945
            (dir.path().join(&packs[i].key), e.offset as usize)
d02e545d Andy McCall ↶ 2946
        };
2947
        let mut data = fs::read(&pack_path).unwrap();
2948
        data[offset] ^= 0xff;
2949
        fs::write(&pack_path, data).unwrap();
2950
        let s3 = Store::open(dir.path()).unwrap();
2951
        assert!(matches!(s3.get(&target), Err(StoreError::Corrupt(..))));
75167672 Andy McCall 2952
        assert_eq!(
2953
            s3.get(&refs[6].0).unwrap().1,
2954
            refs[6].1.as_bytes(),
2955
            "other objects are unaffected"
2956
        );
a17fc622 Andy McCall ↶ 2957
    }
2958
2959
    #[test]
2960
    fn a_full_repack_trains_a_dictionary_and_reads_back() {
64818938 Andy McCall ↶ 2961
        if !super::files_on_disk() {
2962
            return;
2963
        }
a17fc622 Andy McCall ↶ 2964
        let dir = tempfile::tempdir().unwrap();
2965
        let s = Store::open(dir.path()).unwrap();
2966
        // Many small, alike files: what a dictionary is for.
2967
        let bodies: Vec<Vec<u8>> = (0..1500)
2968
            .map(|i| {
2969
                format!(
2970
                    "// SPDX-License-Identifier: GPL-2.0\n#include <linux/module.h>\n\
2971
                     static int probe_{i}(struct device *dev)\n{{\n\treturn {i};\n}}\n"
2972
                )
2973
                .into_bytes()
2974
            })
2975
            .collect();
2976
        let refs: Vec<ObjectRef> = bodies
2977
            .iter()
2978
            .map(|b| s.put(ObjectType::Chunk, b).unwrap())
2979
            .collect();
2980
        s.repack_all(REPACK_ZSTD_LEVEL).unwrap();
2981
        let dicts = fs::read_dir(dir.path())
2982
            .unwrap()
2983
            .flatten()
2984
            .filter(|e| e.path().extension().is_some_and(|x| x == "dict"))
2985
            .count();
2986
        assert_eq!(dicts, 1, "the pack has a dictionary");
2987
        let with_dict = refs
2988
            .iter()
2989
            .filter(|r| s.find_packed(r).unwrap().1.flags & FLAG_DICT != 0)
2990
            .count();
2991
        assert!(with_dict > 1000, "most use it: {with_dict}");
2992
        let again = Store::open(dir.path()).unwrap();
2993
        for (r, b) in refs.iter().zip(&bodies) {
2994
            assert_eq!(&again.get(r).unwrap().1, b);
2995
        }
a67914bc Andy McCall ↶ 2996
        let packs = |dir: &Path| {
2997
            let mut v: Vec<String> = fs::read_dir(dir)
2998
                .unwrap()
2999
                .flatten()
3000
                .map(|e| e.file_name().to_string_lossy().into_owned())
3001
                .filter(|n| n.starts_with("pack-"))
3002
                .collect();
3003
            v.sort();
3004
            v
3005
        };
3006
        // With nothing new, a repack leaves that pack as it is: it would
3007
        // only write the same again.
3008
        let before = packs(dir.path());
3009
        let (report, merged) = again.repack_all(REPACK_ZSTD_LEVEL).unwrap();
3010
        assert_eq!((report.objects, merged), (0, 0));
3011
        assert_eq!(packs(dir.path()), before);
767ac6cd Andy McCall 3012
        // One new object: a repack replaces the pack and its dictionary,
3013
        // retiring the old ones, which a collection an hour on deletes.
a67914bc Andy McCall ↶ 3014
        let extra = again.put(ObjectType::Chunk, b"one more\n").unwrap();
a17fc622 Andy McCall ↶ 3015
        again.repack_all(REPACK_ZSTD_LEVEL).unwrap();
a67914bc Andy McCall ↶ 3016
        let files = packs(dir.path());
767ac6cd Andy McCall 3017
        assert_eq!(
3018
            files.len(),
3019
            7,
3020
            "two of pack, index and dictionary, and the retired record: {files:?}"
3021
        );
3022
        assert_eq!(again.pack_count(), 1, "the old pack is not read");
a17fc622 Andy McCall ↶ 3023
        assert_eq!(&again.get(&refs[7]).unwrap().1, &bodies[7]);
a67914bc Andy McCall ↶ 3024
        assert_eq!(again.get(&extra).unwrap().1, b"one more\n");
767ac6cd Andy McCall 3025
        again
3026
            .expire_retired(std::time::Duration::ZERO, &mut silent())
3027
            .unwrap();
3028
        let files = packs(dir.path());
3029
        assert_eq!(files.len(), 4, "one pack, index, dictionary: {files:?}");
3030
        assert!(before
3031
            .iter()
3032
            .filter(|f| *f != RETIRED_KEY)
3033
            .all(|f| !files.contains(f)));
3034
        assert_eq!(&again.get(&refs[8]).unwrap().1, &bodies[8]);
d02e545d Andy McCall ↶ 3035
    }
3036
3037
    #[test]
cdb5beba Andy McCall ↶ 3038
    fn nocompress_chunks_pack_raw() {
3039
        let dir = tempfile::tempdir().unwrap();
3040
        let s = Store::open(dir.path()).unwrap();
3041
        let body = vec![b'a'; 10_000];
3042
        let raw = s.put_chunk_nocompress(&body).unwrap();
3043
        let compressible = s.put(ObjectType::Chunk, &vec![b'b'; 10_000]).unwrap();
3044
        s.pack_loose().unwrap();
3045
        let packs = s.packs.borrow();
3046
        let (i, e) = s.find_packed(&raw).unwrap();
3047
        assert_eq!((e.flags, e.stored_len as usize), (0, 10_000));
3048
        let (_, c) = s.find_packed(&compressible).unwrap();
3049
        assert_eq!(c.flags, FLAG_ZSTD);
3050
        assert!(c.stored_len < 10_000);
64818938 Andy McCall ↶ 3051
        assert_eq!(packs[i].fetch(s.backend.as_ref(), &raw, e).unwrap().1, body);
cdb5beba Andy McCall ↶ 3052
    }
3053
3054
    #[test]
135212de Andy McCall ↶ 3055
    fn many_packs_merge_into_one() {
3056
        let dir = tempfile::tempdir().unwrap();
64818938 Andy McCall ↶ 3057
        each_store(dir.path(), |which, s| {
3058
            let mut refs = Vec::new();
3059
            for i in 0..(MAX_PACKS + 2) {
3060
                refs.push(
3061
                    s.put(ObjectType::Chunk, format!("pack {i}").as_bytes())
3062
                        .unwrap(),
3063
                );
3064
                s.pack_loose().unwrap();
3065
            }
3066
            assert_eq!(s.pack_count(), MAX_PACKS + 2, "{which}");
3067
            assert_eq!(s.merge_packs().unwrap(), MAX_PACKS + 2);
3068
            assert_eq!(s.pack_count(), 1);
3069
            assert_eq!(s.merge_packs().unwrap(), 0);
3070
            for (i, r) in refs.iter().enumerate() {
3071
                assert_eq!(s.get(r).unwrap().1, format!("pack {i}").as_bytes());
3072
            }
3073
            let again = Store::open_on(s.backend().clone(), s.dir()).unwrap();
3074
            assert_eq!(again.pack_count(), 1, "{which}: reopened");
3075
        });
135212de Andy McCall ↶ 3076
    }
3077
3078
    #[test]
ba160f60 Andy McCall ↶ 3079
    fn prune_removes_unreachable_loose_and_packed_objects() {
3080
        use std::collections::HashSet;
3081
        let dir = tempfile::tempdir().unwrap();
64818938 Andy McCall ↶ 3082
        each_store(dir.path(), |which, s| {
3083
            let keep_a = s.put(ObjectType::Chunk, b"keep a").unwrap();
3084
            let drop_a = s.put(ObjectType::Chunk, b"drop a").unwrap();
3085
            s.pack_loose().unwrap();
3086
            let keep_b = s.put(ObjectType::Chunk, b"keep b").unwrap();
3087
            let drop_b = s.put(ObjectType::Chunk, b"drop b").unwrap();
3088
            let sk = crate::identity::SecretKey {
3089
                ed_seed: [1; 32],
3090
                ml_seed: [2; 32],
3091
            };
3092
            let id = sk.identity("a", "b", 0);
3093
            let key = s.put_identity(&id).unwrap();
3094
            s.put_signature(
3095
                &drop_b,
3096
                &sk.sign(crate::identity::Domain::Change, &key, &drop_b),
3097
            )
75167672 Andy McCall 3098
            .unwrap();
64818938 Andy McCall ↶ 3099
            s.index_seal(&drop_a, &ObjectRef([3; 32])).unwrap();
3100
            let keep: HashSet<ObjectRef> = [keep_a, keep_b, key].into_iter().collect();
3101
            // Everything is too young under a grace period.
3102
            let r = s
3103
                .prune(&keep, std::time::Duration::from_secs(3600))
3104
                .unwrap();
3105
            assert_eq!((r.objects, r.deferred), (0, 2), "{which}");
3106
            let r = s.prune(&keep, std::time::Duration::ZERO).unwrap();
3107
            assert_eq!(r.objects, 2, "{which}: {r:?}");
3108
            assert!(s.has(&keep_a) && s.has(&keep_b) && s.has(&key));
3109
            assert!(!s.has(&drop_a) && !s.has(&drop_b));
3110
            assert!(s.signatures(&drop_b).unwrap().is_empty());
3111
            assert!(s.seals_for(&drop_a).unwrap().is_empty());
3112
            assert_eq!(s.pack_count(), 1);
3113
            assert_eq!(s.get(&keep_a).unwrap().1, b"keep a");
3114
            assert_eq!(s.list().unwrap().len(), 3);
3115
        });
ba160f60 Andy McCall ↶ 3116
    }
3117
3118
    #[test]
1983686f Andy McCall ↶ 3119
    fn signatures_are_stored_beside_objects() {
64818938 Andy McCall ↶ 3120
        use crate::identity::{Domain, SecretKey};
3121
        let dir = tempfile::tempdir().unwrap();
3122
        each_store(dir.path(), |which, s| {
3123
            let r = s.put(ObjectType::Chunk, b"x").unwrap();
3124
            assert!(s.signatures(&r).unwrap().is_empty());
3125
            let sk = SecretKey {
3126
                ed_seed: [1; 32],
3127
                ml_seed: [2; 32],
3128
            };
3129
            let id = sk.identity("a", "b", 0);
3130
            let key = s.put_identity(&id).unwrap();
3131
            assert_eq!(s.get_identity(&key).unwrap(), id);
3132
            let sig = sk.sign(Domain::Change, &key, &r);
3133
            s.put_signature(&r, &sig).unwrap();
3134
            s.put_signature(&r, &sig).unwrap();
3135
            assert_eq!(s.signatures(&r).unwrap(), vec![sig.clone()], "{which}");
3136
            // A second signer is kept beside the first, sorted by key.
3137
            let sk2 = SecretKey {
3138
                ed_seed: [3; 32],
3139
                ml_seed: [4; 32],
3140
            };
3141
            let key2 = s.put_identity(&sk2.identity("c", "d", 0)).unwrap();
3142
            let sig2 = sk2.sign(Domain::Change, &key2, &r);
3143
            s.put_signature(&r, &sig2).unwrap();
3144
            let mut both = vec![sig.clone(), sig2.clone()];
3145
            both.sort_by_key(|s| s.key);
3146
            assert_eq!(s.signatures(&r).unwrap(), both);
3147
            // The object itself is untouched by its signatures.
3148
            assert_eq!(s.get(&r).unwrap().1, b"x");
3149
            // Seal and receipt entries, and the states with receipts.
3150
            s.index_seal(&r, &ObjectRef([5; 32])).unwrap();
3151
            s.index_seal(&r, &ObjectRef([4; 32])).unwrap();
3152
            s.index_seal(&r, &ObjectRef([5; 32])).unwrap();
3153
            assert_eq!(
3154
                s.seals_for(&r).unwrap(),
3155
                vec![ObjectRef([4; 32]), ObjectRef([5; 32])]
3156
            );
3157
            let st = ObjectRef([6; 32]);
3158
            s.index_receipt(&st, &ObjectRef([7; 32])).unwrap();
3159
            assert_eq!(s.receipts_for(&st).unwrap(), vec![ObjectRef([7; 32])]);
3160
            assert_eq!(s.receipt_states().unwrap(), vec![st]);
3161
        });
3162
    }
3163
3164
    /// A store written before signatures, seals and receipts were one
3165
    /// entry each (`sigs/`, `seals/`, `receipts/` lists) still reads, and
3166
    /// what is written now sits beside what was there.
3167
    #[test]
3168
    fn an_older_store_s_sidecar_lists_are_still_read() {
3169
        if !super::files_on_disk() {
3170
            return;
3171
        }
1983686f Andy McCall ↶ 3172
        use crate::identity::{Domain, SecretKey};
3173
        let dir = tempfile::tempdir().unwrap();
3174
        let s = Store::open(dir.path()).unwrap();
64818938 Andy McCall ↶ 3175
        let r = s.put(ObjectType::Chunk, b"old").unwrap();
3176
        let h = r.to_hex();
75167672 Andy McCall 3177
        let sk = SecretKey {
3178
            ed_seed: [1; 32],
3179
            ml_seed: [2; 32],
3180
        };
64818938 Andy McCall ↶ 3181
        let key = s.put_identity(&sk.identity("a", "b", 0)).unwrap();
1983686f Andy McCall ↶ 3182
        let sig = sk.sign(Domain::Change, &key, &r);
64818938 Andy McCall ↶ 3183
        let legacy = dir.path().join("sigs").join(&h[..2]);
3184
        fs::create_dir_all(&legacy).unwrap();
3185
        fs::write(
3186
            legacy.join(&h[2..]),
3187
            Signature::encode_list(std::slice::from_ref(&sig)),
3188
        )
3189
        .unwrap();
3190
        let seals = dir.path().join("seals").join(&h[..2]);
3191
        fs::create_dir_all(&seals).unwrap();
3192
        fs::write(
3193
            seals.join(&h[2..]),
3194
            format!("{}\n", ObjectRef([9; 32]).to_hex()),
3195
        )
3196
        .unwrap();
3197
        let receipts = dir.path().join("receipts").join(&h[..2]);
3198
        fs::create_dir_all(&receipts).unwrap();
3199
        fs::write(
3200
            receipts.join(&h[2..]),
3201
            format!("{}\n", ObjectRef([8; 32]).to_hex()),
3202
        )
3203
        .unwrap();
3204
3205
        assert_eq!(s.signatures(&r).unwrap(), vec![sig.clone()]);
3206
        assert_eq!(s.seals_for(&r).unwrap(), vec![ObjectRef([9; 32])]);
3207
        assert_eq!(s.receipts_for(&r).unwrap(), vec![ObjectRef([8; 32])]);
3208
        assert_eq!(s.receipt_states().unwrap(), vec![r]);
3209
        // New entries join the old ones; the same signer is not doubled.
1983686f Andy McCall ↶ 3210
        s.put_signature(&r, &sig).unwrap();
64818938 Andy McCall ↶ 3211
        s.index_seal(&r, &ObjectRef([1; 32])).unwrap();
3212
        assert_eq!(s.signatures(&r).unwrap().len(), 1);
3213
        assert_eq!(
3214
            s.seals_for(&r).unwrap(),
3215
            vec![ObjectRef([1; 32]), ObjectRef([9; 32])]
3216
        );
3217
        // Pruning the object takes both layouts with it.
3218
        let r2 = s.put(ObjectType::Chunk, b"kept").unwrap();
3219
        let keep = [r2, key].into_iter().collect();
3220
        s.prune(&keep, std::time::Duration::ZERO).unwrap();
3221
        assert!(s.signatures(&r).unwrap().is_empty());
3222
        assert!(s.seals_for(&r).unwrap().is_empty());
3223
        assert!(s.receipt_states().unwrap().is_empty());
1983686f Andy McCall ↶ 3224
    }
3225
3226
    #[test]
ff0af1ee unknown 3227
    fn change_round_trip_through_store() {
3228
        let dir = tempfile::tempdir().unwrap();
64818938 Andy McCall ↶ 3229
        each_store(dir.path(), |which, s| {
3230
            let c = crate::objects::tests::sample_change();
3231
            let r = s.put_change(&c).unwrap();
3232
            assert_eq!(r, c.hash(), "{which}");
3233
            assert_eq!(s.get_change(&r).unwrap(), c);
3234
            assert_eq!(s.get_change_meta(&r).unwrap().message, c.message);
3235
        });
ff0af1ee unknown 3236
    }
2b872d07 Andy McCall ↶ 3237
3238
    fn xorshift(state: &mut u64) -> u64 {
3239
        *state ^= *state << 13;
3240
        *state ^= *state >> 7;
3241
        *state ^= *state << 17;
3242
        *state
3243
    }
3244
3245
    /// Random corruption of pack and index files never panics: reads fail
3246
    /// with an error or the store refuses to open, and untouched objects
3247
    /// stay readable when the index survives.
3248
    #[test]
3249
    fn corrupted_packs_and_indexes_fail_cleanly() {
64818938 Andy McCall ↶ 3250
        if !super::files_on_disk() {
3251
            return;
3252
        }
2b872d07 Andy McCall ↶ 3253
        let dir = tempfile::tempdir().unwrap();
3254
        let objects = dir.path().join("objects");
3255
        let s = Store::open(&objects).unwrap();
3256
        let mut refs = Vec::new();
3257
        let mut seed = 0x9e3779b97f4a7c15u64;
3258
        for i in 0..40u32 {
3259
            let len = (xorshift(&mut seed) % 5000) as usize;
3260
            let mut body = vec![0u8; len];
3261
            for b in body.iter_mut() {
75167672 Andy McCall 3262
                *b = if i % 2 == 0 {
3263
                    (xorshift(&mut seed) & 0xff) as u8
3264
                } else {
3265
                    b'a' + (i % 26) as u8
3266
                };
2b872d07 Andy McCall ↶ 3267
            }
3268
            refs.push(s.put(ObjectType::Chunk, &body).unwrap());
3269
        }
3270
        s.pack_loose().unwrap();
75167672 Andy McCall 3271
        let pack = fs::read_dir(&objects)
3272
            .unwrap()
3273
            .filter_map(|e| e.ok().map(|e| e.path()))
3274
            .find(|p| p.extension().is_some_and(|x| x == "pack"))
3275
            .unwrap();
2b872d07 Andy McCall ↶ 3276
        let idx = pack.with_extension("idx");
3277
        let pristine_pack = fs::read(&pack).unwrap();
3278
        let pristine_idx = fs::read(&idx).unwrap();
3279
3280
        for round in 0..300u32 {
75167672 Andy McCall 3281
            let (path, pristine) = if round % 2 == 0 {
3282
                (&pack, &pristine_pack)
3283
            } else {
3284
                (&idx, &pristine_idx)
3285
            };
2b872d07 Andy McCall ↶ 3286
            let mut data = pristine.clone();
3287
            match xorshift(&mut seed) % 4 {
3288
                0 => {
3289
                    let at = (xorshift(&mut seed) as usize) % data.len();
3290
                    data[at] ^= 1 << (xorshift(&mut seed) % 8);
3291
                }
3292
                1 => {
3293
                    let at = (xorshift(&mut seed) as usize) % data.len();
3294
                    data[at] = (xorshift(&mut seed) & 0xff) as u8;
3295
                }
3296
                2 => {
3297
                    let keep = (xorshift(&mut seed) as usize) % data.len();
3298
                    data.truncate(keep);
3299
                }
3300
                _ => {
3301
                    let at = (xorshift(&mut seed) as usize) % data.len();
3302
                    let n = ((xorshift(&mut seed) % 8) + 1) as usize;
3303
                    for k in 0..n.min(data.len() - at) {
3304
                        data[at + k] = 0xff;
3305
                    }
3306
                }
3307
            }
3308
            fs::write(path, &data).unwrap();
3309
            // Opening may refuse a broken index; a store that opens must
3310
            // either return each object intact or report it corrupt/missing.
3311
            if let Ok(s2) = Store::open(&objects) {
3312
                for r in &refs {
3313
                    match s2.get(r) {
75167672 Andy McCall 3314
                        Ok((ty, body)) => assert_eq!(
3315
                            hash_object(ty, &body),
3316
                            *r,
3317
                            "a returned object always matches its reference"
3318
                        ),
3319
                        Err(StoreError::Corrupt(..))
3320
                        | Err(StoreError::NotFound(_))
3321
                        | Err(StoreError::Io(_)) => {}
2b872d07 Andy McCall ↶ 3322
                        Err(e) => panic!("unexpected error {e}"),
3323
                    }
3324
                }
3325
            }
3326
            fs::write(path, pristine).unwrap();
3327
        }
3328
        // Restored files read back in full.
3329
        let s3 = Store::open(&objects).unwrap();
3330
        for r in &refs {
3331
            let (ty, body) = s3.get(r).unwrap();
3332
            assert_eq!(hash_object(ty, &body), *r);
3333
        }
3334
    }
8f10a07a Andy McCall ↶ 3335
3336
    /// A small batch becomes loose objects; a large one becomes a single
3337
    /// pack. Objects are readable while pending, and batches nest.
3338
    #[test]
3339
    fn batches_write_loose_or_one_pack() {
3340
        let dir = tempfile::tempdir().unwrap();
64818938 Andy McCall ↶ 3341
        each_store(dir.path(), |which, s| {
3342
            let outer = s.begin_batch().unwrap();
3343
            let a = s.put(ObjectType::Chunk, b"small a").unwrap();
3344
            {
3345
                let inner = s.begin_batch().unwrap();
3346
                let b = s.put(ObjectType::Chunk, b"small b").unwrap();
3347
                assert!(s.has(&b));
3348
                assert_eq!(s.get(&b).unwrap().1, b"small b");
3349
                inner.finish().unwrap();
3350
                assert_eq!(
3351
                    s.loose_count().unwrap(),
3352
                    0,
3353
                    "{which}: the inner batch defers to the outer one"
3354
                );
3355
            }
3356
            assert_eq!(s.get(&a).unwrap().1, b"small a");
75167672 Andy McCall 3357
            assert_eq!(
64818938 Andy McCall ↶ 3358
                s.put(ObjectType::Chunk, b"small a").unwrap(),
3359
                a,
3360
                "idempotent while pending"
75167672 Andy McCall 3361
            );
64818938 Andy McCall ↶ 3362
            outer.finish().unwrap();
3363
            assert_eq!(s.loose_count().unwrap(), 2);
3364
            assert_eq!(s.pack_count(), 0);
3365
            assert_eq!(s.get(&a).unwrap().1, b"small a");
8f10a07a Andy McCall ↶ 3366
64818938 Andy McCall ↶ 3367
            // Large: spills into one pack, readable during and after.
3368
            let big = s.begin_batch().unwrap();
3369
            let mut refs = Vec::new();
3370
            let mut seed = 7u64;
3371
            for i in 0..300u32 {
3372
                let mut body = vec![b'z'; 40_000];
3373
                if i % 3 == 0 {
3374
                    for b in body.iter_mut() {
3375
                        *b = (xorshift(&mut seed) & 0xff) as u8;
3376
                    }
8f10a07a Andy McCall ↶ 3377
                }
64818938 Andy McCall ↶ 3378
                body[..4].copy_from_slice(&i.to_le_bytes());
3379
                let r = if i % 5 == 0 {
3380
                    s.put_chunk_nocompress(&body).unwrap()
3381
                } else {
3382
                    s.put(ObjectType::Chunk, &body).unwrap()
3383
                };
3384
                assert_eq!(
3385
                    s.get(&r).unwrap().1,
3386
                    body,
3387
                    "readable while pending (object {i})"
3388
                );
3389
                refs.push((r, body));
8f10a07a Andy McCall ↶ 3390
            }
64818938 Andy McCall ↶ 3391
            assert!(s.has(&refs[0].0));
3392
            big.finish().unwrap();
3393
            assert_eq!(s.pack_count(), 1);
75167672 Andy McCall 3394
            assert_eq!(
64818938 Andy McCall ↶ 3395
                s.loose_count().unwrap(),
3396
                2,
3397
                "nothing from the big batch is loose"
75167672 Andy McCall 3398
            );
64818938 Andy McCall ↶ 3399
            assert!(fs::read_dir(s.dir())
75167672 Andy McCall 3400
                .unwrap()
64818938 Andy McCall ↶ 3401
                .flatten()
3402
                .all(|e| !e.file_name().to_string_lossy().contains("tmp-")));
3403
            let s2 = Store::open_on(s.backend().clone(), s.dir()).unwrap();
3404
            for (r, body) in &refs {
3405
                assert_eq!(s2.get(r).unwrap().1, *body);
3406
            }
3407
            // A dropped batch still writes its objects.
3408
            {
3409
                let _b = s2.begin_batch().unwrap();
3410
                s2.put(ObjectType::Chunk, b"dropped").unwrap();
3411
            }
3412
            assert_eq!(
3413
                s2.get(&hash_object(ObjectType::Chunk, b"dropped"))
3414
                    .unwrap()
3415
                    .1,
3416
                b"dropped"
3417
            );
3418
        });
afaba5f1 Andy McCall ↶ 3419
    }
3420
3421
    #[test]
3422
    fn get_many_reads_loose_and_packed_objects_in_order() {
3423
        let dir = tempfile::tempdir().unwrap();
64818938 Andy McCall ↶ 3424
        each_store(dir.path(), |which, s| {
3425
            let packed: Vec<ObjectRef> = (0..20)
3426
                .map(|i| {
3427
                    s.put(ObjectType::Chunk, format!("packed {i}").as_bytes())
3428
                        .unwrap()
3429
                })
3430
                .collect();
3431
            s.pack_loose().unwrap();
3432
            let loose: Vec<ObjectRef> = (0..20)
3433
                .map(|i| {
3434
                    s.put(ObjectType::Chunk, format!("loose {i}").as_bytes())
3435
                        .unwrap()
3436
                })
3437
                .collect();
3438
            let missing = hash_object(ObjectType::Chunk, b"never stored");
3439
            let mut refs: Vec<ObjectRef> = Vec::new();
3440
            for i in 0..20 {
3441
                refs.push(loose[i]);
3442
                refs.push(packed[i]);
3443
            }
3444
            refs.push(missing);
3445
            let got = s.get_many(&refs);
3446
            assert_eq!(got.len(), refs.len());
3447
            for (i, r) in refs.iter().enumerate().take(40) {
3448
                let want = if i % 2 == 0 {
3449
                    format!("loose {}", i / 2)
3450
                } else {
3451
                    format!("packed {}", i / 2)
3452
                };
3453
                let (ty, body) = got[i].as_ref().unwrap();
3454
                assert_eq!(
3455
                    (*ty, body.as_slice()),
3456
                    (ObjectType::Chunk, want.as_bytes()),
3457
                    "{which}: {r:?}"
3458
                );
3459
            }
3460
            assert!(matches!(got[40], Err(StoreError::NotFound(_))));
3461
        });
09245702 Andy McCall ↶ 3462
    }
3463
3464
    /// A packed object is read from its pack without first asking the
3465
    /// backend for a loose copy (oxygenhub#228: on a bucket each such ask
3466
    /// was a request that found nothing, every time).
3467
    #[test]
3468
    fn packed_objects_cost_no_loose_lookups() {
3469
        use std::sync::atomic::{AtomicUsize, Ordering};
3470
        struct Counting(MemoryStore, AtomicUsize);
3471
        impl crate::strata::Store for Counting {
3472
            fn describe(&self) -> String {
3473
                "counting".into()
3474
            }
3475
            fn has(&self, k: &str) -> crate::strata::Result<bool> {
3476
                self.0.has(k)
3477
            }
3478
            fn get(&self, k: &str) -> crate::strata::Result<Vec<u8>> {
3479
                if k.starts_with("loose/") {
3480
                    self.1.fetch_add(1, Ordering::Relaxed);
3481
                }
3482
                self.0.get(k)
3483
            }
3484
            fn get_range(
3485
                &self,
3486
                k: &str,
3487
                r: std::ops::Range<u64>,
3488
            ) -> crate::strata::Result<Vec<u8>> {
3489
                self.0.get_range(k, r)
3490
            }
3491
            fn put_new(&self, k: &str, b: &[u8]) -> crate::strata::Result<()> {
3492
                self.0.put_new(k, b)
3493
            }
3494
            fn list(&self, p: &str) -> crate::strata::Result<Vec<crate::strata::Entry>> {
3495
                self.0.list(p)
3496
            }
3497
            fn delete(&self, k: &str) -> crate::strata::Result<()> {
3498
                self.0.delete(k)
3499
            }
3500
            fn read_ref(
3501
                &self,
3502
                k: &str,
3503
            ) -> crate::strata::Result<Option<(Vec<u8>, crate::strata::Version)>> {
3504
                self.0.read_ref(k)
3505
            }
3506
            fn write_ref(
3507
                &self,
3508
                k: &str,
3509
                b: &[u8],
3510
                e: Option<&crate::strata::Version>,
3511
            ) -> crate::strata::Result<crate::strata::Version> {
3512
                self.0.write_ref(k, b, e)
3513
            }
3514
        }
3515
        let dir = tempfile::tempdir().unwrap();
3516
        let backend = Arc::new(Counting(MemoryStore::new(), AtomicUsize::new(0)));
3517
        let s = Store::open_on(backend.clone(), dir.path().join("scratch")).unwrap();
3518
        let refs: Vec<ObjectRef> = (0..10)
3519
            .map(|i| {
3520
                s.put(ObjectType::Chunk, format!("p {i}").as_bytes())
3521
                    .unwrap()
3522
            })
3523
            .collect();
3524
        s.pack_loose().unwrap();
3525
        let s = Store::open_on(backend.clone(), dir.path().join("scratch")).unwrap();
3526
        backend.1.store(0, Ordering::Relaxed);
3527
        for r in &refs {
3528
            assert!(s.get(r).is_ok());
3529
        }
3530
        assert!(s.get_many(&refs).iter().all(|g| g.is_ok()));
3531
        assert_eq!(backend.1.load(Ordering::Relaxed), 0, "no loose lookups");
3532
        // An object no pack holds is still looked for loose.
3533
        let missing = hash_object(ObjectType::Chunk, b"never stored");
3534
        assert!(matches!(s.get(&missing), Err(StoreError::NotFound(_))));
3535
        assert!(backend.1.load(Ordering::Relaxed) > 0);
767ac6cd Andy McCall 3536
    }
3537
}
3538
3539
/// Readers never wait (oxygenhub#249): a store keeps reading while other
3540
/// handles repack, collect and push into the store under it.
3541
#[cfg(test)]
3542
pub(crate) mod reader_tests {
3543
    use super::*;
3544
3545
    fn chunk(i: usize) -> Vec<u8> {
3546
        format!("object {i} ").repeat(1 + i % 5).into_bytes()
3547
    }
3548
3549
    /// Two handles on one store: a writer, and a reader opened at once.
3550
    fn each_pair(f: impl Fn(&str, Store, Store)) {
3551
        let dir = tempfile::tempdir().unwrap();
3552
        let s = Store::open(dir.path().join("objects")).unwrap();
3553
        let r = Store::open(dir.path().join("objects")).unwrap();
3554
        f("directory", s, r);
3555
        let m: Arc<Backend> = Arc::new(MemoryStore::new());
3556
        let s = Store::open_on(m.clone(), dir.path().join("scratch")).unwrap();
3557
        let r = Store::open_on(m, dir.path().join("scratch-r")).unwrap();
3558
        f("memory", s, r);
3559
    }
3560
3561
    /// Set every retired entry's time back by `by`, as if retired then.
3562
    pub(crate) fn age_retired(s: &Store, by: std::time::Duration) {
3563
        s.update_retired(|m| {
3564
            for t in m.values_mut() {
3565
                *t = t.saturating_sub(by.as_millis() as u64);
3566
            }
3567
        })
3568
        .unwrap();
3569
    }
3570
3571
    fn retired_keys(s: &Store) -> Vec<String> {
3572
        s.read_retired().unwrap().0.into_keys().collect()
3573
    }
3574
3575
    #[test]
3576
    fn a_reader_opened_before_a_repack_reads_every_object_after_it() {
3577
        each_pair(|which, writer, _| {
3578
            let mut refs = Vec::new();
3579
            for i in 0..40 {
3580
                refs.push(writer.put(ObjectType::Chunk, &chunk(i)).unwrap());
3581
            }
3582
            writer.pack_loose().unwrap();
3583
            for i in 40..80 {
3584
                refs.push(writer.put(ObjectType::Chunk, &chunk(i)).unwrap());
3585
            }
3586
            // Opened now: one pack and forty loose objects.
3587
            let reader = Store::open_on(writer.backend().clone(), writer.dir()).unwrap();
3588
            assert_eq!(reader.pack_count(), 1, "{which}");
3589
            let (_, merged) = writer.repack_all(REPACK_ZSTD_LEVEL).unwrap();
3590
            assert_eq!(merged, 1);
3591
            // The old pack and the loose objects are retired, not deleted.
3592
            let retired = retired_keys(&writer);
3593
            assert_eq!(retired.len(), 81, "{which}: {retired:?}");
3594
            assert_eq!(writer.loose_count().unwrap(), 0, "retired is not loose");
3595
            // The reader reads on from what it loaded.
3596
            for (i, r) in refs.iter().enumerate() {
3597
                assert_eq!(reader.get(r).unwrap().1, chunk(i), "{which}: {i}");
3598
            }
3599
            assert_eq!(reader.pack_count(), 1);
3600
            // A store opened now reads the new pack only.
3601
            let fresh = Store::open_on(writer.backend().clone(), writer.dir()).unwrap();
3602
            assert_eq!(fresh.pack_count(), 1);
3603
            assert_ne!(fresh.packs.borrow()[0].key, reader.packs.borrow()[0].key);
3604
            // Once the retired files are deleted, the reader finds every
3605
            // object in the new pack, by get, get_many and has alike.
3606
            let report = writer
3607
                .expire_retired(std::time::Duration::ZERO, &mut silent())
3608
                .unwrap();
3609
            assert_eq!((report.packs, report.loose), (1, 80), "{which}");
3610
            assert!(retired_keys(&writer).is_empty());
3611
            for (i, r) in refs.iter().enumerate() {
3612
                assert_eq!(reader.get(r).unwrap().1, chunk(i), "{which}: {i}");
3613
            }
3614
            let other = Store::open_on(writer.backend().clone(), writer.dir()).unwrap();
3615
            let before = other.packs.borrow()[0].key.clone();
3616
            writer.put(ObjectType::Chunk, b"new").unwrap();
3617
            writer.repack_all(REPACK_ZSTD_LEVEL).unwrap();
3618
            writer
3619
                .expire_retired(std::time::Duration::ZERO, &mut silent())
3620
                .unwrap();
3621
            assert!(other.get_many(&refs).iter().all(|g| g.is_ok()), "{which}");
3622
            assert_ne!(other.packs.borrow()[0].key, before);
3623
            let third = Store::open_on(writer.backend().clone(), writer.dir()).unwrap();
3624
            writer.put(ObjectType::Chunk, b"newer").unwrap();
3625
            writer.repack_all(REPACK_ZSTD_LEVEL).unwrap();
3626
            writer
3627
                .expire_retired(std::time::Duration::ZERO, &mut silent())
3628
                .unwrap();
3629
            assert!(refs.iter().all(|r| third.has(r)), "{which}");
3630
            assert!(!third.has(&hash_object(ObjectType::Chunk, b"never")));
3631
        });
3632
    }
3633
3634
    #[test]
3635
    fn a_reader_opened_before_a_spilled_batch_reads_its_objects() {
3636
        each_pair(|which, writer, reader| {
3637
            assert_eq!(reader.pack_count(), 0);
3638
            let mut refs = Vec::new();
3639
            {
3640
                let batch = writer.begin_batch().unwrap();
3641
                for i in 0..(SPILL_OBJECTS + 50) {
3642
                    refs.push(writer.put(ObjectType::Chunk, &chunk(i)).unwrap());
3643
                }
3644
                batch.finish().unwrap();
3645
            }
3646
            assert_eq!(writer.pack_count(), 1, "{which}: the batch spilled");
3647
            assert_eq!(reader.get(&refs[0]).unwrap().1, chunk(0), "{which}");
3648
            assert_eq!(reader.pack_count(), 1, "the miss loaded the new pack");
3649
            let got = reader.get_many(&refs);
3650
            assert!(got.iter().all(|g| g.is_ok()), "{which}");
3651
            // has, too, from another reader.
3652
            let late = Store::open_on(writer.backend().clone(), writer.dir()).unwrap();
3653
            {
3654
                let batch = writer.begin_batch().unwrap();
3655
                for i in 1000..(1000 + SPILL_OBJECTS + 1) {
3656
                    writer.put(ObjectType::Chunk, &chunk(i)).unwrap();
3657
                }
3658
                batch.finish().unwrap();
3659
            }
3660
            assert!(late.has(&hash_object(ObjectType::Chunk, &chunk(1000))));
3661
        });
3662
    }
3663
3664
    #[test]
3665
    fn retired_entries_expire_after_the_hour_and_are_never_loaded() {
3666
        each_pair(|which, s, _| {
3667
            for i in 0..10 {
3668
                s.put(ObjectType::Chunk, &chunk(i)).unwrap();
3669
            }
3670
            s.pack_loose().unwrap();
3671
            s.put(ObjectType::Chunk, &chunk(10)).unwrap();
3672
            s.repack_all(ZSTD_LEVEL).unwrap();
3673
            // Retired over an hour ago: the first pack and 10 loose objects.
3674
            age_retired(&s, RETIRED_FOR + std::time::Duration::from_secs(60));
3675
            let old = retired_keys(&s);
3676
            assert_eq!(old.len(), 12, "{which}: {old:?}");
3677
            // Retired just now: the second pack.
3678
            s.put(ObjectType::Chunk, &chunk(11)).unwrap();
3679
            s.repack_all(ZSTD_LEVEL).unwrap();
3680
            assert_eq!(retired_keys(&s).len(), 14);
3681
            let listed = s
3682
                .backend()
3683
                .list("pack-")
3684
                .unwrap()
3685
                .into_iter()
3686
                .filter(|e| e.key.ends_with(".idx"))
3687
                .count();
3688
            assert_eq!(listed, 3, "{which}");
3689
            let fresh = Store::open_on(s.backend().clone(), s.dir()).unwrap();
3690
            assert_eq!(
3691
                fresh.pack_count(),
3692
                1,
3693
                "{which}: retired packs are not loaded"
3694
            );
3695
            let report = s.expire_retired(RETIRED_FOR, &mut silent()).unwrap();
3696
            assert_eq!(
3697
                report,
3698
                RetiredReport {
3699
                    packs: 1,
3700
                    loose: 11,
3701
                    kept: 2
3702
                },
3703
                "{which}"
3704
            );
3705
            let young = retired_keys(&s);
3706
            assert_eq!(young.len(), 2, "{which}: {young:?}");
3707
            assert!(young.iter().all(|k| !old.contains(k)));
3708
            for k in old.iter().filter(|k| k.ends_with(".pack")) {
3709
                assert!(!s.backend().has(k).unwrap(), "{which}: {k}");
3710
            }
3711
            for k in &young {
3712
                assert!(s.backend().has(k).unwrap(), "{which}: {k} kept");
3713
            }
3714
            for i in 0..12 {
3715
                let r = hash_object(ObjectType::Chunk, &chunk(i));
3716
                assert_eq!(fresh.get(&r).unwrap().1, chunk(i), "{which}");
3717
            }
3718
        });
3719
    }
3720
3721
    /// A retired loose object whose pack copy was pruned since is not
3722
    /// lost when the retired files go: it is loose again.
3723
    #[test]
3724
    fn a_retired_loose_object_no_pack_holds_is_kept() {
3725
        each_pair(|which, s, _| {
3726
            let a = s.put(ObjectType::Chunk, b"a").unwrap();
3727
            let b = s.put(ObjectType::Chunk, b"b").unwrap();
3728
            s.pack_loose().unwrap();
3729
            assert_eq!(s.loose_count().unwrap(), 0);
3730
            // The pack rewritten without b, as pruning does.
3731
            let first = s.packs.borrow()[0].key.clone();
3732
            s.write_pack(&[a], &[], &[first], ZSTD_LEVEL, &mut silent())
3733
                .unwrap();
3734
            let report = s
3735
                .expire_retired(std::time::Duration::ZERO, &mut silent())
3736
                .unwrap();
3737
            assert_eq!((report.packs, report.loose), (1, 1), "{which}: a's copy");
3738
            assert!(retired_keys(&s).is_empty());
3739
            assert_eq!(s.get(&b).unwrap().1, b"b", "{which}");
3740
            assert_eq!(s.get(&a).unwrap().1, b"a");
3741
            assert_eq!(s.loose_count().unwrap(), 1, "b is loose again");
3742
            // And pruning it, unreachable, deletes it.
3743
            let keep = [a].into_iter().collect();
3744
            let r = s.prune(&keep, std::time::Duration::ZERO).unwrap();
3745
            assert_eq!(r.objects, 1);
3746
            assert!(!s.has(&b));
3747
        });
3748
    }
3749
3750
    /// A backend whose first pack listing names an index that is deleted
3751
    /// before it is read, as a collection running meanwhile would.
3752
    pub(crate) struct Racing {
3753
        inner: MemoryStore,
3754
        lists: std::sync::atomic::AtomicUsize,
3755
        /// Deleted right after the first listing returns.
3756
        pub(crate) doomed: std::sync::Mutex<Option<String>>,
3757
        /// Named in every listing, never stored.
3758
        ghost: bool,
3759
    }
3760
3761
    impl crate::strata::Store for Racing {
3762
        fn describe(&self) -> String {
3763
            "racing".into()
3764
        }
3765
        fn has(&self, k: &str) -> crate::strata::Result<bool> {
3766
            self.inner.has(k)
3767
        }
3768
        fn get(&self, k: &str) -> crate::strata::Result<Vec<u8>> {
3769
            self.inner.get(k)
3770
        }
3771
        fn get_range(&self, k: &str, r: std::ops::Range<u64>) -> crate::strata::Result<Vec<u8>> {
3772
            self.inner.get_range(k, r)
3773
        }
3774
        fn put_new(&self, k: &str, b: &[u8]) -> crate::strata::Result<()> {
3775
            self.inner.put_new(k, b)
3776
        }
3777
        fn list(&self, p: &str) -> crate::strata::Result<Vec<crate::strata::Entry>> {
3778
            let mut out = self.inner.list(p)?;
3779
            if p == "pack-" {
3780
                self.lists
3781
                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3782
                if let Some(k) = self.doomed.lock().unwrap().take() {
3783
                    self.inner.delete(&k)?;
3784
                }
3785
                if self.ghost {
3786
                    for k in ["pack-0000.idx", "pack-0000.pack"] {
3787
                        out.push(crate::strata::Entry {
3788
                            key: k.into(),
3789
                            size: 100,
3790
                            modified_ms: None,
3791
                        });
3792
                    }
3793
                    out.sort_by(|a, b| a.key.cmp(&b.key));
3794
                }
3795
            }
3796
            Ok(out)
3797
        }
3798
        fn delete(&self, k: &str) -> crate::strata::Result<()> {
3799
            self.inner.delete(k)
3800
        }
3801
        fn read_ref(
3802
            &self,
3803
            k: &str,
3804
        ) -> crate::strata::Result<Option<(Vec<u8>, crate::strata::Version)>> {
3805
            self.inner.read_ref(k)
3806
        }
3807
        fn write_ref(
3808
            &self,
3809
            k: &str,
3810
            b: &[u8],
3811
            e: Option<&crate::strata::Version>,
3812
        ) -> crate::strata::Result<crate::strata::Version> {
3813
            self.inner.write_ref(k, b, e)
3814
        }
3815
    }
3816
3817
    pub(crate) fn racing(ghost: bool) -> Arc<Racing> {
3818
        Arc::new(Racing {
3819
            inner: MemoryStore::new(),
3820
            lists: Default::default(),
3821
            doomed: Default::default(),
3822
            ghost,
3823
        })
3824
    }
3825
3826
    #[test]
3827
    fn an_index_deleted_between_listing_and_loading_is_passed_over() {
3828
        let dir = tempfile::tempdir().unwrap();
3829
        let backend = racing(false);
3830
        let s = Store::open_on(backend.clone(), dir.path()).unwrap();
3831
        let a = s.put(ObjectType::Chunk, b"a").unwrap();
3832
        s.pack_loose().unwrap();
3833
        let b = s.put(ObjectType::Chunk, b"b").unwrap();
3834
        s.pack_loose().unwrap();
3835
        let idx = {
3836
            let packs = s.packs.borrow();
3837
            let (i, _) = s.find_packed(&a).unwrap();
3838
            format!("{}.idx", packs[i].key.trim_end_matches(".pack"))
3839
        };
3840
        *backend.doomed.lock().unwrap() = Some(idx);
3841
        let before = backend.lists.load(std::sync::atomic::Ordering::Relaxed);
3842
        let again = Store::open_on(backend.clone(), dir.path()).unwrap();
3843
        assert_eq!(again.pack_count(), 1, "the deleted one is passed over");
3844
        assert_eq!(
3845
            backend.lists.load(std::sync::atomic::Ordering::Relaxed) - before,
3846
            2,
3847
            "and the store listed again"
3848
        );
3849
        assert_eq!(again.get(&b).unwrap().1, b"b");
3850
        // A listing that names an index never there opens too.
3851
        let ghosted = racing(true);
3852
        let s = Store::open_on(ghosted.clone(), dir.path().join("g")).unwrap();
3853
        let c = s.put(ObjectType::Chunk, b"c").unwrap();
3854
        s.pack_loose().unwrap();
3855
        let again = Store::open_on(ghosted, dir.path().join("g")).unwrap();
3856
        assert_eq!(again.pack_count(), 1);
3857
        assert_eq!(again.get(&c).unwrap().1, b"c");
a9f686ed Andy McCall ↶ 3858
    }
3859
}
3860
3861
#[cfg(test)]
3862
mod batch_tests {
3863
    use super::*;
3864
3865
    #[test]
3866
    fn a_large_batch_packs_every_object_and_indexes_them_all() {
3867
        let dir = tempfile::tempdir().unwrap();
3868
        let store = Store::open(dir.path()).unwrap();
3869
        let mut refs = Vec::new();
3870
        {
3871
            let batch = store.begin_batch().unwrap();
3872
            for i in 0..1000u32 {
3873
                let body = format!("object {i} {}", "x".repeat(20_000 + i as usize)).into_bytes();
3874
                refs.push(store.put(ObjectType::Blob, &body).unwrap());
3875
            }
3876
            batch.finish().unwrap();
3877
        }
3878
        let again = Store::open(dir.path()).unwrap();
3879
        for r in &refs {
3880
            again
54e2e630 Andy McCall ↶ 3881
                .get(r)
3882
                .unwrap_or_else(|e| panic!("{}: {e}", r.short(12)));
3883
        }
3884
    }
3885
3886
    #[test]
3887
    fn a_pack_a_stopped_batch_left_is_adopted_and_its_torn_end_cut() {
3888
        // oxygen#79: a batch never finished (a process killed part way)
3889
        // leaves its objects in an unindexed .tmp pack.
3890
        let dir = tempfile::tempdir().unwrap();
3891
        let mut refs = Vec::new();
3892
        {
3893
            let store = Store::open(dir.path()).unwrap();
3894
            let batch = store.begin_batch().unwrap();
3895
            for i in 0..300u32 {
3896
                let body = format!("object {i} {}", "y".repeat(20_000 + i as usize)).into_bytes();
3897
                refs.push(store.put(ObjectType::Blob, &body).unwrap());
3898
            }
3899
            std::mem::forget(batch);
3900
        }
3901
        let tmp: Vec<_> = fs::read_dir(dir.path())
3902
            .unwrap()
3903
            .flatten()
3904
            .filter(|e| e.file_name().to_string_lossy().starts_with(".tmp-"))
3905
            .map(|e| e.path())
3906
            .collect();
3907
        assert_eq!(tmp.len(), 1, "one unfinished pack");
3908
        // A torn last entry: a header and part of its body.
3909
        let mut f = fs::OpenOptions::new().append(true).open(&tmp[0]).unwrap();
3910
        f.write_all(&[0, 1, 0xff, 0, 0, 0, 9, 9, 0, 0]).unwrap();
3911
        f.write_all(&[7; 40]).unwrap();
3912
        drop(f);
3913
        let store = Store::open(dir.path()).unwrap();
3914
        assert!(store.get(&refs[0]).is_err(), "unreadable before");
3915
        let young = store
3916
            .adopt_unfinished_packs(std::time::Duration::from_secs(3600), &|_| {})
3917
            .unwrap();
3918
        assert_eq!(young, (0, 0), "a pack written to lately is left alone");
3919
        let (packs, objects) = store
3920
            .adopt_unfinished_packs(std::time::Duration::ZERO, &|_| {})
3921
            .unwrap();
3922
        assert_eq!((packs, objects), (1, 300));
3923
        for r in &refs {
3924
            store
a9f686ed Andy McCall ↶ 3925
                .get(r)
3926
                .unwrap_or_else(|e| panic!("{}: {e}", r.short(12)));
3927
        }
54e2e630 Andy McCall ↶ 3928
        let again = Store::open(dir.path()).unwrap();
3929
        assert!(again.get(&refs[299]).is_ok(), "indexed for good");
a9f686ed Andy McCall ↶ 3930
    }
3931
}
3932
3933
#[cfg(test)]
3934
mod size_tests {
3935
    use super::*;
3936
3937
    #[test]
3938
    fn an_object_over_the_limit_is_refused_and_nothing_is_written() {
3939
        let dir = tempfile::tempdir().unwrap();
3940
        let store = Store::open(dir.path()).unwrap();
3941
        let big = vec![b'x'; MAX_OBJECT_LEN as usize + 1];
3942
        {
3943
            let batch = store.begin_batch().unwrap();
3944
            store.put(ObjectType::Blob, b"small").unwrap();
3945
            let e = store.put(ObjectType::Change, &big).unwrap_err();
3946
            assert!(
3947
                matches!(e, StoreError::TooLarge { kind: "change", .. }),
3948
                "{e}"
3949
            );
3950
            assert!(e.to_string().contains("commit it in parts"), "{e}");
3951
            batch.finish().unwrap();
3952
        }
3953
        // The store still opens and reads what was written.
3954
        let again = Store::open(dir.path()).unwrap();
3955
        again.get(&hash_object(ObjectType::Blob, b"small")).unwrap();
6f8aeb99 Andy McCall ↶ 3956
    }
3957
}
3958
3959
#[cfg(test)]
3960
mod text_tests {
3961
    use super::*;
3962
    use crate::objects::{AtomRef, Edit, CHANGE_VERSION};
3963
3964
    fn large_change() -> Change {
3965
        let mut c = crate::objects::tests::sample_change();
3966
        assert_eq!(c.version, CHANGE_VERSION);
3967
        c.edits[0] = Edit::Insert {
3968
            node: crate::ids::NodeId([7; 16]),
3969
            after: AtomRef::Start,
3970
            before: AtomRef::End,
3971
            lines: (0..2000)
3972
                .map(|i| format!("line {i}\n").into_bytes())
3973
                .collect(),
3974
        };
3975
        c
3976
    }
3977
3978
    #[test]
3979
    fn a_large_insert_is_stored_beside_its_change_and_read_back() {
3980
        let dir = tempfile::tempdir().unwrap();
3981
        let s = Store::open(dir.path()).unwrap();
3982
        let c = large_change();
3983
        let r = s.put_change(&c).unwrap();
3984
        assert_eq!(r, c.hash());
3985
        let (_, body) = s.get(&r).unwrap();
3986
        assert!(
3987
            body.len() < 1024,
3988
            "the change holds a reference, not {} bytes of lines",
3989
            body.len()
3990
        );
3991
        let (back, parts) = s.get_change_parts(&r).unwrap();
3992
        assert_eq!(back, c);
3993
        // The text blob and its chunk.
3994
        assert_eq!(parts.len(), 2);
3995
        for p in &parts {
3996
            assert!(s.has(p));
3997
        }
3998
        // Storing it again writes nothing new.
3999
        let n = s.list().unwrap().len();
4000
        s.put_change(&c).unwrap();
4001
        assert_eq!(s.list().unwrap().len(), n);
4002
    }
4003
4004
    #[test]
4005
    fn a_change_whose_text_blob_is_missing_is_reported_not_misread() {
64818938 Andy McCall ↶ 4006
        if !super::files_on_disk() {
4007
            return;
4008
        }
6f8aeb99 Andy McCall ↶ 4009
        let dir = tempfile::tempdir().unwrap();
4010
        let s = Store::open(dir.path()).unwrap();
4011
        let c = large_change();
4012
        let r = s.put_change(&c).unwrap();
4013
        let (_, parts) = s.get_change_parts(&r).unwrap();
4014
        fs::remove_file(s.path_for(&parts[0])).unwrap();
4015
        let e = s.get_change(&r).unwrap_err();
4016
        assert!(
4017
            matches!(&e, StoreError::Corrupt(h, why) if *h == r && why.contains("missing")),
4018
            "{e}"
4019
        );
192fad1e Andy McCall ↶ 4020
    }
4021
}
4022
4023
#[cfg(test)]
4024
mod put_many_tests {
4025
    use super::*;
4026
4027
    #[test]
4028
    fn many_objects_in_a_batch_are_compressed_together_and_all_read_back() {
4029
        let dir = tempfile::tempdir().unwrap();
4030
        let s = Store::open(dir.path()).unwrap();
4031
        let before = s.put(ObjectType::Chunk, b"already here").unwrap();
4032
        let bodies: Vec<Vec<u8>> = (0..200u32)
4033
            .map(|i| format!("chunk {i} ").repeat(6000).into_bytes())
4034
            .collect();
4035
        let mut objects: Vec<(ObjectType, &[u8])> = bodies
4036
            .iter()
4037
            .map(|b| (ObjectType::Chunk, b.as_slice()))
4038
            .collect();
4039
        objects.push((ObjectType::Chunk, bodies[0].as_slice()));
4040
        objects.push((ObjectType::Chunk, b"already here"));
4041
        let refs = {
4042
            let batch = s.begin_batch().unwrap();
4043
            let refs = s.put_many(&objects).unwrap();
4044
            batch.finish().unwrap();
4045
            refs
4046
        };
4047
        assert_eq!(refs.len(), objects.len());
4048
        assert_eq!(refs[200], refs[0], "a repeat is the same object");
4049
        assert_eq!(refs[201], before);
4050
        let again = Store::open(dir.path()).unwrap();
4051
        for (r, b) in refs.iter().zip(&objects) {
4052
            assert_eq!(again.get(r).unwrap().1, b.1);
ef7d4ea6 Andy McCall ↶ 4053
        }
4054
    }
4055
}
4056
4057
/// Signatures and index entries on a store that is not this disk's
4058
/// directory: the journal and the entry lists (spec §13.7, #116).
4059
#[cfg(test)]
4060
mod entry_tests {
4061
    use super::*;
4062
    use crate::identity::{Domain, SecretKey};
4063
    use crate::strata::Store as _;
4064
    use std::collections::HashMap;
4065
    use std::sync::atomic::{AtomicBool, Ordering};
4066
    use std::sync::Mutex;
4067
4068
    /// A store in memory that counts its requests by kind, as a bucket
4069
    /// store's /health counters do; it can also slip a competing journal
4070
    /// line in just before a write of the journal, as another process
4071
    /// would.
4072
    #[derive(Default)]
4073
    struct Counted {
4074
        inner: MemoryStore,
4075
        counts: Mutex<HashMap<&'static str, usize>>,
4076
        interfere: AtomicBool,
4077
    }
4078
4079
    impl Counted {
4080
        fn count(&self, kind: &'static str) {
4081
            *self.counts.lock().unwrap().entry(kind).or_default() += 1;
4082
        }
4083
        fn n(&self, kind: &str) -> usize {
4084
            self.counts.lock().unwrap().get(kind).copied().unwrap_or(0)
192fad1e Andy McCall ↶ 4085
        }
ef7d4ea6 Andy McCall ↶ 4086
        fn reset(&self) {
4087
            self.counts.lock().unwrap().clear();
4088
        }
4089
        fn total(&self) -> usize {
4090
            self.counts.lock().unwrap().values().sum()
4091
        }
4092
        fn summary(&self) -> String {
4093
            let c = self.counts.lock().unwrap();
4094
            let mut v: Vec<String> = c.iter().map(|(k, n)| format!("{k} {n}")).collect();
4095
            v.sort();
4096
            v.join(", ")
4097
        }
4098
    }
4099
4100
    impl crate::strata::Store for Counted {
4101
        fn describe(&self) -> String {
4102
            "counted".into()
4103
        }
4104
        fn has(&self, k: &str) -> crate::strata::Result<bool> {
4105
            self.count("has");
4106
            self.inner.has(k)
4107
        }
4108
        fn get(&self, k: &str) -> crate::strata::Result<Vec<u8>> {
4109
            self.count(if is_legacy(k) { "get_legacy" } else { "get" });
4110
            self.inner.get(k)
4111
        }
4112
        fn get_range(&self, k: &str, r: std::ops::Range<u64>) -> crate::strata::Result<Vec<u8>> {
4113
            self.count("range");
4114
            self.inner.get_range(k, r)
4115
        }
4116
        fn put_new(&self, k: &str, b: &[u8]) -> crate::strata::Result<()> {
4117
            self.count("put");
4118
            self.inner.put_new(k, b)
4119
        }
4120
        fn list(&self, p: &str) -> crate::strata::Result<Vec<crate::strata::Entry>> {
4121
            self.count(if p == "pack-" {
4122
                "list_packs"
4123
            } else if is_legacy(p) {
4124
                "list_legacy"
4125
            } else {
4126
                "list"
4127
            });
4128
            self.inner.list(p)
4129
        }
4130
        fn delete(&self, k: &str) -> crate::strata::Result<()> {
4131
            self.count("delete");
4132
            self.inner.delete(k)
4133
        }
4134
        fn read_ref(
4135
            &self,
4136
            k: &str,
4137
        ) -> crate::strata::Result<Option<(Vec<u8>, crate::strata::Version)>> {
4138
            self.count(if k == JOURNAL_KEY {
4139
                "read_journal"
4140
            } else {
4141
                "read_ref"
4142
            });
4143
            self.inner.read_ref(k)
4144
        }
4145
        fn write_ref(
4146
            &self,
4147
            k: &str,
4148
            b: &[u8],
4149
            e: Option<&crate::strata::Version>,
4150
        ) -> crate::strata::Result<crate::strata::Version> {
4151
            self.count("write_ref");
4152
            if k == JOURNAL_KEY && self.interfere.swap(false, Ordering::SeqCst) {
4153
                let (mut m, v) = match self.inner.read_ref(k)? {
4154
                    Some((bytes, v)) => (parse_retired(&bytes), Some(v)),
4155
                    None => (Default::default(), None),
4156
                };
4157
                m.insert(
4158
                    format!("seal/{}", "c".repeat(64)) + "/" + &"d".repeat(64),
4159
                    0,
4160
                );
4161
                self.inner.write_ref(k, &encode_retired(&m), v.as_ref())?;
4162
            }
4163
            self.inner.write_ref(k, b, e)
4164
        }
4165
    }
4166
4167
    /// Whether a key or prefix is under an older one-list layout.
4168
    fn is_legacy(k: &str) -> bool {
4169
        ENTRY_INDEXES
4170
            .iter()
4171
            .any(|(_, legacy)| k.starts_with(&format!("{legacy}/")))
4172
    }
4173
4174
    struct Fixture {
4175
        backend: Arc<Counted>,
4176
        dir: tempfile::TempDir,
4177
        handles: std::cell::Cell<usize>,
4178
    }
4179
4180
    impl Fixture {
4181
        fn new() -> Fixture {
4182
            Fixture {
4183
                backend: Arc::new(Counted::default()),
4184
                dir: tempfile::tempdir().unwrap(),
4185
                handles: Default::default(),
4186
            }
4187
        }
4188
        /// Another handle on the store, as another process opens it.
4189
        fn open(&self) -> Store {
4190
            let n = self.handles.get() + 1;
4191
            self.handles.set(n);
4192
            Store::open_on(self.backend.clone(), self.dir.path().join(format!("s{n}"))).unwrap()
4193
        }
4194
    }
4195
4196
    fn signer(n: u8) -> SecretKey {
4197
        SecretKey {
4198
            ed_seed: [n; 32],
4199
            ml_seed: [n + 100; 32],
4200
        }
4201
    }
4202
4203
    fn sign(s: &Store, r: &ObjectRef, n: u8) -> Signature {
4204
        let sk = signer(n);
4205
        let key = s.put_identity(&sk.identity("a", "b", 0)).unwrap();
4206
        let sig = sk.sign(Domain::Change, &key, r);
4207
        s.put_signature(r, &sig).unwrap();
4208
        sig
4209
    }
4210
4211
    fn journal(s: &Store) -> std::collections::BTreeMap<String, u64> {
4212
        s.read_record(JOURNAL_KEY).unwrap().0
4213
    }
4214
4215
    fn fold(s: &Store) -> bool {
4216
        s.fold_entries(&mut silent()).unwrap()
4217
    }
4218
4219
    /// What 0.4.6 writes for a signature: its own key, and nothing else.
4220
    fn old_writer_signs(f: &Fixture, r: &ObjectRef, n: u8) -> Signature {
4221
        let sk = signer(n);
4222
        let sig = sk.sign(Domain::Change, &ObjectRef([n; 32]), r);
4223
        f.backend
4224
            .put_new(
4225
                &format!("{}{}", fanout_prefix("sig", r), sig.key.to_hex()),
4226
                &Signature::encode_list(std::slice::from_ref(&sig)),
4227
            )
4228
            .unwrap();
4229
        sig
4230
    }
4231
4232
    /// After a fold, a signature or seal another handle writes is found
4233
    /// by a store opened later through the journal, with no listing; a
4234
    /// handle that already read the entries sees it once refreshed.
4235
    #[test]
4236
    fn an_entry_written_after_a_fold_is_found_through_the_journal() {
4237
        let f = Fixture::new();
4238
        let w = f.open();
4239
        let r1 = w.put(ObjectType::Chunk, b"one").unwrap();
4240
        let s1 = sign(&w, &r1, 1);
4241
        assert!(fold(&w));
4242
        assert!(!fold(&w), "nothing new: no second list");
4243
4244
        let early = f.open();
4245
        assert_eq!(early.signatures(&r1).unwrap(), vec![s1.clone()]);
4246
4247
        let w2 = f.open();
4248
        let r2 = w2.put(ObjectType::Chunk, b"two").unwrap();
4249
        let s2 = sign(&w2, &r2, 2);
4250
        w2.index_seal(&r2, &ObjectRef([9; 32])).unwrap();
4251
        w2.index_receipt(&r2, &ObjectRef([8; 32])).unwrap();
4252
        // Its own writes, at once.
4253
        assert_eq!(w2.signatures(&r2).unwrap(), vec![s2.clone()]);
4254
4255
        let later = f.open();
4256
        f.backend.reset();
4257
        assert_eq!(later.signatures(&r1).unwrap(), vec![s1]);
4258
        assert_eq!(later.signatures(&r2).unwrap(), vec![s2.clone()]);
4259
        assert_eq!(later.seals_for(&r2).unwrap(), vec![ObjectRef([9; 32])]);
4260
        assert_eq!(later.receipts_for(&r2).unwrap(), vec![ObjectRef([8; 32])]);
4261
        assert_eq!(later.receipt_states().unwrap(), vec![r2]);
4262
        assert!(later.seals_for(&r1).unwrap().is_empty());
4263
        assert_eq!(f.backend.n("list"), 0, "{}", f.backend.summary());
4264
        assert_eq!(f.backend.n("read_journal"), 1, "{}", f.backend.summary());
4265
4266
        // The handle that read the entries before keeps its view until
4267
        // it is refreshed, as it keeps its operation head.
4268
        assert!(early.signatures(&r2).unwrap().is_empty());
4269
        early.refresh().unwrap();
4270
        assert_eq!(early.signatures(&r2).unwrap(), vec![s2]);
4271
    }
4272
4273
    /// A fold marks the journal's lines rather than dropping them, so a
4274
    /// reader whose listing predates it still finds every entry; an hour
4275
    /// on, the old list is deleted and the lines dropped, and readers
4276
    /// find everything in the new list.
4277
    #[test]
4278
    fn a_fold_keeps_the_journal_for_the_hour_readers_may_need_it() {
4279
        let f = Fixture::new();
4280
        let w = f.open();
4281
        let r1 = w.put(ObjectType::Chunk, b"one").unwrap();
4282
        let s1 = sign(&w, &r1, 1);
4283
        assert!(fold(&w));
4284
        let r2 = w.put(ObjectType::Chunk, b"two").unwrap();
4285
        let s2 = sign(&w, &r2, 2);
4286
        assert!(journal(&w).values().any(|t| *t == 0));
4287
4288
        // Opened before the second fold: lists the first list only.
4289
        let stale = f.open();
4290
        let stale_after_expiry = f.open();
4291
        assert!(fold(&w));
4292
        assert!(
4293
            journal(&w).values().all(|t| *t != 0),
4294
            "every line is marked folded"
4295
        );
4296
        assert!(journal(&w).len() >= 2, "and kept");
4297
        assert_eq!(stale.signatures(&r1).unwrap(), vec![s1.clone()]);
4298
        assert_eq!(stale.signatures(&r2).unwrap(), vec![s2.clone()]);
4299
4300
        // An hour later: the first list goes with the next collection,
4301
        // and the next journal update drops the folded lines.
4302
        reader_tests::age_retired(&w, RETIRED_FOR * 2);
4303
        w.update_record(JOURNAL_KEY, "test", |m| {
4304
            for t in m.values_mut() {
4305
                *t = t.saturating_sub(2 * RETIRED_FOR.as_millis() as u64);
4306
            }
4307
        })
4308
        .unwrap();
4309
        w.expire_retired(RETIRED_FOR, &mut silent()).unwrap();
4310
        let lists: Vec<String> = f
4311
            .backend
4312
            .inner
4313
            .list("pack-")
4314
            .unwrap()
4315
            .into_iter()
4316
            .map(|e| e.key)
4317
            .filter(|k| is_entry_list(k))
4318
            .collect();
4319
        assert_eq!(lists.len(), 1, "the replaced list is deleted: {lists:?}");
4320
        let r3 = w.put(ObjectType::Chunk, b"three").unwrap();
4321
        let s3 = sign(&w, &r3, 3);
4322
        let j = journal(&w);
4323
        assert_eq!(j.len(), 1, "only the new line is left: {j:?}");
4324
        assert!(j.keys().all(|k| k.starts_with(&fanout_prefix("sig", &r3))));
4325
4326
        // A handle whose listing named the deleted list lists again.
4327
        assert_eq!(
4328
            stale_after_expiry.signatures(&r1).unwrap(),
4329
            vec![s1.clone()]
4330
        );
4331
        assert_eq!(
4332
            stale_after_expiry.signatures(&r3).unwrap(),
4333
            vec![s3.clone()]
4334
        );
4335
        let fresh = f.open();
4336
        f.backend.reset();
4337
        assert_eq!(fresh.signatures(&r1).unwrap(), vec![s1]);
4338
        assert_eq!(fresh.signatures(&r2).unwrap(), vec![s2]);
4339
        assert_eq!(fresh.signatures(&r3).unwrap(), vec![s3]);
4340
        assert_eq!(f.backend.n("list"), 0);
4341
    }
4342
4343
    /// A store no fold has touched (as 0.4.6 left it: per-object keys and
4344
    /// older one-list keys, no journal, no lists) reads by listing, and
4345
    /// reads the same once folded. An older writer's entry after the
4346
    /// fold is missed until the next fold: the trade-off of §13.7.
4347
    #[test]
4348
    fn an_old_layout_store_reads_before_and_after_its_first_fold() {
4349
        let f = Fixture::new();
4350
        let w = f.open();
4351
        let r1 = w.put(ObjectType::Chunk, b"one").unwrap();
4352
        let r2 = w.put(ObjectType::Chunk, b"two").unwrap();
4353
        let s1 = old_writer_signs(&f, &r1, 1);
4354
        let s2 = SecretKey {
4355
            ed_seed: [2; 32],
4356
            ml_seed: [3; 32],
4357
        }
4358
        .sign(Domain::Change, &ObjectRef([2; 32]), &r2);
4359
        f.backend
4360
            .put_new(
4361
                &legacy_key("sigs", &r2),
4362
                &Signature::encode_list(std::slice::from_ref(&s2)),
4363
            )
4364
            .unwrap();
4365
        f.backend
4366
            .put_new(
4367
                &format!("{}{}", fanout_prefix("seal", &r1), "ab".repeat(32)),
4368
                b"",
4369
            )
4370
            .unwrap();
4371
        f.backend
4372
            .put_new(
4373
                &legacy_key("receipts", &r2),
4374
                format!("{}\n", ObjectRef([7; 32]).to_hex()).as_bytes(),
4375
            )
4376
            .unwrap();
4377
        let check = |s: &Store| {
4378
            assert_eq!(s.signatures(&r1).unwrap(), vec![s1.clone()]);
4379
            assert_eq!(s.signatures(&r2).unwrap(), vec![s2.clone()]);
4380
            assert_eq!(s.seals_for(&r1).unwrap(), vec![ObjectRef([0xab; 32])]);
4381
            assert_eq!(s.receipts_for(&r2).unwrap(), vec![ObjectRef([7; 32])]);
4382
            assert_eq!(s.receipt_states().unwrap(), vec![r2]);
4383
        };
4384
        let reader = f.open();
4385
        assert!(!reader.folded.get());
4386
        check(&reader);
4387
        assert!(f.backend.inner.read_ref(JOURNAL_KEY).unwrap().is_none());
4388
4389
        assert!(fold(&w));
4390
        let reader = f.open();
4391
        assert!(reader.folded.get());
4392
        check(&reader);
8156967b Andy McCall ↶ 4393
4394
        // The older lists' entries are per-object entries now, and the
4395
        // marker is there.
4396
        assert!(f.backend.inner.has(LEGACY_FOLDED_KEY).unwrap());
4397
        assert!(f
4398
            .backend
4399
            .inner
4400
            .has(&format!("{}{}", fanout_prefix("sig", &r2), s2.key.to_hex()))
4401
            .unwrap());
4402
        assert!(f
4403
            .backend
4404
            .inner
4405
            .has(&format!(
4406
                "{}{}",
4407
                fanout_prefix("receipt", &r2),
4408
                ObjectRef([7; 32]).to_hex()
4409
            ))
4410
            .unwrap());
ef7d4ea6 Andy McCall ↶ 4411
4412
        // An older writer after the fold: missed until the next one.
4413
        let r3 = w.put(ObjectType::Chunk, b"three").unwrap();
4414
        let s3 = old_writer_signs(&f, &r3, 3);
4415
        assert!(f.open().signatures(&r3).unwrap().is_empty());
4416
        assert!(fold(&w));
4417
        assert_eq!(f.open().signatures(&r3).unwrap(), vec![s3]);
4418
    }
4419
4420
    /// Writers racing on the journal never lose a line: a lost
4421
    /// compare-and-swap reads the journal again and retries.
4422
    #[test]
4423
    fn concurrent_journal_appends_lose_nothing() {
4424
        let f = Fixture::new();
4425
        // One race, made to happen.
4426
        let w = f.open();
4427
        f.backend.interfere.store(true, Ordering::SeqCst);
4428
        w.index_seal(&ObjectRef([1; 32]), &ObjectRef([2; 32]))
4429
            .unwrap();
4430
        let j = journal(&w);
4431
        assert_eq!(j.len(), 2, "the competitor's line and ours: {j:?}");
4432
        // Many, from threads, each its own handle.
4433
        let backend: Arc<Backend> = f.backend.clone();
4434
        std::thread::scope(|scope| {
4435
            for t in 0..8u8 {
4436
                let backend = backend.clone();
4437
                let dir = f.dir.path().join(format!("t{t}"));
4438
                scope.spawn(move || {
4439
                    let s = Store::open_on(backend, dir).unwrap();
4440
                    for i in 0..25u8 {
4441
                        s.index_seal(&ObjectRef([t + 10; 32]), &ObjectRef([i; 32]))
4442
                            .unwrap();
4443
                    }
4444
                });
4445
            }
4446
        });
4447
        assert_eq!(journal(&w).len(), 2 + 8 * 25);
4448
        assert!(fold(&w));
4449
        let r = f.open();
4450
        for t in 0..8u8 {
4451
            assert_eq!(r.seals_for(&ObjectRef([t + 10; 32])).unwrap().len(), 25);
4452
        }
4453
    }
4454
4455
    /// A batch adds its entries to the journal in one update when it is
4456
    /// flushed; past the limit the writer folds them into a partial list.
4457
    #[test]
4458
    fn a_long_journal_is_folded_into_a_partial_list() {
4459
        let f = Fixture::new();
4460
        let w = f.open();
4461
        assert!(fold(&w), "folded, with nothing yet");
4462
        let key = ObjectRef([5; 32]);
4463
        f.backend.reset();
4464
        let batch = w.begin_batch().unwrap();
4465
        for i in 0..=JOURNAL_FOLD_AT as u32 {
4466
            let mut v = [0u8; 32];
4467
            v[..4].copy_from_slice(&i.to_le_bytes());
4468
            w.index_seal(&key, &ObjectRef(v)).unwrap();
4469
        }
4470
        assert_eq!(f.backend.n("write_ref"), 0, "nothing until the flush");
4471
        batch.finish().unwrap();
4472
        let parts = f
4473
            .backend
4474
            .inner
4475
            .list("pack-")
4476
            .unwrap()
4477
            .into_iter()
4478
            .filter(|e| e.key.ends_with(PART_SUFFIX))
4479
            .count();
4480
        assert_eq!(parts, 1);
4481
        assert!(journal(&w).values().all(|t| *t != 0), "all folded");
4482
        let r = f.open();
4483
        assert_eq!(r.seals_for(&key).unwrap().len(), JOURNAL_FOLD_AT + 1);
4484
        // The next complete fold takes the partial list in.
4485
        assert!(fold(&w));
4486
        let lists: Vec<String> = f.open().entry_lists.borrow().clone();
4487
        assert_eq!(lists.len(), 1);
4488
        assert!(lists[0].ends_with(LIST_SUFFIX));
4489
        assert_eq!(f.open().seals_for(&key).unwrap().len(), JOURNAL_FOLD_AT + 1);
4490
    }
4491
4492
    /// A collection that deletes an object takes its entries out of the
4493
    /// journal too, so the next fold leaves them out.
4494
    #[test]
4495
    fn pruned_objects_leave_the_journal() {
4496
        let f = Fixture::new();
4497
        let w = f.open();
4498
        let gone = w.put(ObjectType::Chunk, b"gone").unwrap();
4499
        let kept = w.put(ObjectType::Chunk, b"kept").unwrap();
4500
        sign(&w, &gone, 1);
4501
        let s = sign(&w, &kept, 2);
4502
        assert!(fold(&w));
4503
        let keep: std::collections::HashSet<ObjectRef> = w
4504
            .list()
4505
            .unwrap()
4506
            .into_iter()
4507
            .filter(|r| *r != gone)
4508
            .collect();
4509
        w.prune(&keep, std::time::Duration::ZERO).unwrap();
4510
        assert!(journal(&w).keys().all(|k| !k.contains(&gone.to_hex()[2..])));
4511
        fold(&w);
4512
        let r = f.open();
4513
        assert!(r.signatures(&gone).unwrap().is_empty());
4514
        assert_eq!(r.signatures(&kept).unwrap(), vec![s]);
4515
        let all = r.with_entries(|e| e.clone()).unwrap().unwrap();
4516
        assert!(
4517
            all.iter().all(|k| !k.contains(&gone.to_hex()[2..])),
4518
            "{all:?}"
4519
        );
4520
    }
4521
4522
    /// Requests per lookup, before and after the fold (#116): twenty
4523
    /// objects, five of them signed, each looked up for its signatures
4524
    /// and its seals, as a fetch does.
4525
    #[test]
4526
    fn a_folded_store_looks_up_entries_without_listing() {
4527
        let f = Fixture::new();
4528
        let w = f.open();
4529
        let refs: Vec<ObjectRef> = (0..20)
4530
            .map(|i| {
4531
                w.put(ObjectType::Chunk, format!("o {i}").as_bytes())
4532
                    .unwrap()
4533
            })
4534
            .collect();
4535
        for r in &refs[..5] {
4536
            sign(&w, r, 1);
4537
        }
4538
        let lookups = |s: &Store| {
4539
            for r in &refs {
4540
                s.signatures(r).unwrap();
4541
                s.seals_for(r).unwrap();
4542
            }
4543
        };
4544
        let before = f.open();
4545
        f.backend.reset();
4546
        lookups(&before);
4547
        let (before_total, before_list) = (f.backend.total(), f.backend.n("list"));
4548
        eprintln!("40 lookups before the fold: {}", f.backend.summary());
4549
4550
        assert!(fold(&w));
4551
        let after = f.open();
4552
        f.backend.reset();
4553
        lookups(&after);
4554
        eprintln!("40 lookups after the fold: {}", f.backend.summary());
4555
        assert_eq!(before_list, 40);
4556
        assert_eq!(f.backend.n("list"), 0);
8156967b Andy McCall ↶ 4557
        assert_eq!(f.backend.n("get_legacy"), 0, "the older lists are folded");
ef7d4ea6 Andy McCall ↶ 4558
        assert_eq!(f.backend.n("read_journal"), 1);
4559
        assert!(
8156967b Andy McCall ↶ 4560
            f.backend.total() < before_total / 10,
ef7d4ea6 Andy McCall ↶ 4561
            "{}",
4562
            f.backend.summary()
4563
        );
8156967b Andy McCall ↶ 4564
    }
4565
4566
    /// Once a fold has copied the older lists into per-object entries and
4567
    /// written its marker, readers stop reading them, folded or not; the
4568
    /// answers are the same.
4569
    #[test]
4570
    fn the_legacy_marker_stops_reads_of_the_older_lists() {
4571
        let f = Fixture::new();
4572
        let w = f.open();
4573
        let r = w.put(ObjectType::Chunk, b"old").unwrap();
4574
        let sig = SecretKey {
4575
            ed_seed: [4; 32],
4576
            ml_seed: [5; 32],
4577
        }
4578
        .sign(Domain::Change, &ObjectRef([4; 32]), &r);
4579
        f.backend
4580
            .put_new(
4581
                &legacy_key("sigs", &r),
4582
                &Signature::encode_list(std::slice::from_ref(&sig)),
4583
            )
4584
            .unwrap();
4585
        for (legacy, v) in [("seals", 9u8), ("certs", 8), ("accepted-lists", 6)] {
4586
            f.backend
4587
                .put_new(
4588
                    &legacy_key(legacy, &r),
4589
                    format!("{}\n", ObjectRef([v; 32]).to_hex()).as_bytes(),
4590
                )
4591
                .unwrap();
4592
        }
4593
        let check = |s: &Store| {
4594
            assert_eq!(s.signatures(&r).unwrap(), vec![sig.clone()]);
4595
            assert_eq!(s.seals_for(&r).unwrap(), vec![ObjectRef([9; 32])]);
4596
            assert_eq!(
4597
                s.index_get("cert", "certs", &r).unwrap(),
4598
                vec![ObjectRef([8; 32])]
4599
            );
4600
            assert_eq!(
4601
                s.index_get_pub("accepted", &r).unwrap(),
4602
                vec![ObjectRef([6; 32])]
4603
            );
4604
        };
4605
        let before = f.open();
4606
        f.backend.reset();
4607
        check(&before);
4608
        assert_eq!(f.backend.n("get_legacy"), 4, "{}", f.backend.summary());
4609
4610
        assert!(fold(&w));
4611
        let folded = f.open();
4612
        f.backend.reset();
4613
        check(&folded);
4614
        assert_eq!(f.backend.n("get_legacy") + f.backend.n("list"), 0);
4615
4616
        // Not folded (its lists gone), but marked: per-object listings,
4617
        // still no older lists.
4618
        for e in f.backend.inner.list("pack-").unwrap() {
4619
            if is_entry_list(&e.key) {
4620
                f.backend.inner.delete(&e.key).unwrap();
4621
            }
4622
        }
4623
        let marked = f.open();
4624
        assert!(!marked.folded.get() && marked.legacy_folded.get());
4625
        f.backend.reset();
4626
        check(&marked);
4627
        assert_eq!(f.backend.n("get_legacy"), 0, "{}", f.backend.summary());
4628
        assert_eq!(f.backend.n("list"), 4);
771661aa Andy McCall ↶ 4629
    }
4630
4631
    /// A handle that has read the entries finds another process's new
4632
    /// signature once the pack listing's interval has passed, with no
4633
    /// refresh, at the cost of one pack listing and one journal read.
4634
    #[test]
4635
    fn a_long_lived_handle_sees_new_entries_within_the_interval() {
4636
        let f = Fixture::new();
4637
        let w = f.open();
4638
        let r1 = w.put(ObjectType::Chunk, b"one").unwrap();
4639
        let s1 = sign(&w, &r1, 1);
4640
        assert!(fold(&w));
4641
        let a = f.open();
4642
        assert_eq!(a.signatures(&r1).unwrap(), vec![s1]);
4643
4644
        let b = f.open();
4645
        let r2 = b.put(ObjectType::Chunk, b"two").unwrap();
4646
        let s2 = sign(&b, &r2, 2);
4647
        b.index_approval(&r2, &ObjectRef([3; 32])).unwrap();
4648
        // Within the interval: answered from what was read.
4649
        assert!(a.signatures(&r2).unwrap().is_empty());
4650
4651
        // The interval passes, as the pack listing's does.
4652
        let t = a.entries_read.get().unwrap();
4653
        a.entries_read.set(t.checked_sub(ENTRIES_FRESH));
4654
        f.backend.reset();
4655
        assert_eq!(a.signatures(&r2).unwrap(), vec![s2]);
4656
        assert_eq!(a.approvals_for(&r2).unwrap(), vec![ObjectRef([3; 32])]);
4657
        assert_eq!(f.backend.n("read_journal"), 1, "{}", f.backend.summary());
4658
        assert_eq!(f.backend.n("list_packs"), 1, "{}", f.backend.summary());
4659
        assert_eq!(f.backend.n("list"), 0, "{}", f.backend.summary());
4660
        assert_eq!(
4661
            f.backend.n("get"),
4662
            1,
4663
            "the signature; the list already read is not read again: {}",
4664
            f.backend.summary()
4665
        );
8f10a07a Andy McCall ↶ 4666
    }
ff0af1ee unknown 4667
}