OXYGENHUB

Coverage / crates/oxy-core/src/strata.rs 84.6%

804 of 950 lines run, 151 of 262 functions · run #333 on main · run missed

1
//! Oxygen Strata (docs/stores.md): the storage a repository can be kept
2
//! on, as a trait, so that a bucket, a directory or a hub's disk all look
3
//! the same to the code that pushes to and fetches from them.
4
//!
5
//! A store has two halves. **Objects** are written once and never
6
//! change: packs and their indexes, named by content, which any store
7
//! can hold safely. **References** are the one mutable record (bookmarks,
8
//! tags, the policy), updated only by compare-and-swap on a version the
9
//! store hands out: an ETag on S3, a generation on GCS, a content hash on
10
//! a directory. Two writers can therefore share a store with no lock
11
//! server: the loser of a race reads again, merges, and tries again.
12
//!
13
//! A repository's own objects (`.oxy/objects`, see [`crate::store`]) are
14
//! kept on a store too, a directory one, with the same keys a bucket
15
//! would hold; a remote is a store as well. This module holds the trait,
16
//! a directory store, an in-memory store for tests, and the conformance
17
//! check every store must pass. Cloud stores live in a crate of their
18
//! own, because of what they pull in.
19
20
use std::collections::BTreeMap;
21
use std::fs;
22
use std::io::{self, Read, Seek, SeekFrom, Write};
23
use std::ops::Range;
24
use std::path::{Path, PathBuf};
25
use std::sync::Mutex;
26
use std::time::{Duration, Instant};
27
28
/// The version of a reference record as the store reports it: opaque,
29
/// compared only for equality, and only ever valid for the store that
30
/// issued it. Writing the same bytes again may keep the version (S3's
31
/// ETag and a directory's content hash are both of the content): a
32
/// compare-and-swap guards against losing a *different* record, which is
33
/// all it needs to.
34
#[derive(Clone, Debug, PartialEq, Eq)]
35
pub struct Version(pub String);
36
37
/// One key in a listing.
38
#[derive(Clone, Debug, PartialEq, Eq)]
39
pub struct Entry {
40
    pub key: String,
41
    pub size: u64,
42
    /// When the object was written, in wall milliseconds, where the store
43
    /// knows (garbage collection's grace period reads it).
44
    pub modified_ms: Option<u64>,
45
}
46
47
#[derive(Debug, thiserror::Error)]
48
pub enum Error {
49
    #[error("{0}: not in the store")]
50
    NotFound(String),
51
    #[error("{0}: already in the store")]
52
    Exists(String),
53
    #[error("{0}: changed since it was read")]
54
    Conflict(String),
55
    #[error("bad store key {0:?}: {1}")]
56
    Key(String, &'static str),
57
    #[error("{0}: busy (another writer holds it)")]
58
    Busy(String),
59
    #[error(transparent)]
60
    Io(#[from] io::Error),
61
    #[error("{0}")]
62
    Backend(String),
63
}
64
65
pub type Result<T> = std::result::Result<T, Error>;
66
67
/// Longest key a store accepts; S3 allows 1024 bytes.
68
pub const MAX_KEY_LEN: usize = 1024;
69
70
/// Refuse a key that is not a plain relative path: `/`-separated
71
/// segments of `[A-Za-z0-9._-]`, none empty, none `.` or `..`. The same
72
/// rule on every store, so a key written to one can be read from another,
73
/// and so a key can never escape a directory store's root.
74123446×
pub fn check_key(key: &str) -> Result<()> {
75123446×
    let bad = |why| Error::Key(key.to_string(), why);
76123446×
    if key.is_empty() {
771×
        return Err(bad("empty"));
78123445×
    }
79123445×
    if key.len() > MAX_KEY_LEN {
801×
        return Err(bad("longer than 1024 bytes"));
81123444×
    }
82331134×
    for seg in key.split('/') {
83331134×
        if seg.is_empty() {
844×
            return Err(bad(
854×
                "an empty segment (a leading, trailing or doubled slash)",
864×
            ));
87331130×
        }
88331130×
        if seg == "." || seg == ".." {
894×
            return Err(bad("a . or .. segment"));
90331126×
        }
91331126×
        if !seg
92331126×
            .bytes()
937862670×
            .all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'_' || b == b'-')
94
        {
953×
            return Err(bad("a character outside A-Z a-z 0-9 . _ -"));
96331123×
        }
97
    }
98123433×
    Ok(())
99123446×
}
100
101
/// Where a repository's packs and references are kept. Every method is
102
/// synchronous and may be called from several threads at once.
103
pub trait Store: Send + Sync {
104
    /// A name for messages: the URL, or the directory.
105
    fn describe(&self) -> String;
106
107
    // ---- objects: written once, never changed
108
109
    fn has(&self, key: &str) -> Result<bool>;
110
    /// The whole object; `NotFound` when there is none.
111
    fn get(&self, key: &str) -> Result<Vec<u8>>;
112
    /// Bytes `range` of an object; an error when the range runs past its end.
113
    fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>>;
114
    /// Write an object that does not exist yet; `Exists` when it does, and
115
    /// then nothing is changed. Readers never see a partial object.
116
    fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()>;
117
    /// Every key under `prefix` (a key prefix, not necessarily a whole
118
    /// segment), sorted, with sizes.
119
    fn list(&self, prefix: &str) -> Result<Vec<Entry>>;
120
    /// Remove an object; fine when it is already gone.
121
    fn delete(&self, key: &str) -> Result<()>;
122
    /// One object's listing entry without listing its neighbours; `None`
123
    /// when there is none.
1248×
    fn stat(&self, key: &str) -> Result<Option<Entry>> {
1258×
        Ok(self.list(key)?.into_iter().find(|e| e.key == key))
1268×
    }
127
    /// Write several objects that do not exist yet; one that does is left
128
    /// as it is, which is not an error (objects are named by content). A
129
    /// store that can batch its syncs does; this does them one at a time.
1302×
    fn put_many_new(&self, objects: &[(String, Vec<u8>)]) -> Result<()> {
1316×
        for (key, bytes) in objects {
1326×
            match self.put_new(key, bytes) {
1336×
                Ok(()) | Err(Error::Exists(_)) => {}
1340×
                Err(e) => return Err(e),
135
            }
136
        }
1372×
        Ok(())
1382×
    }
139
    /// `put_new` of a file's contents: a store on the same disk can move
140
    /// the file into place instead of copying it.
14139×
    fn put_new_file(&self, key: &str, path: &Path) -> Result<()> {
14239×
        self.put_new(key, &fs::read(path)?)
14339×
    }
144
145
    // ---- references: one small record, updated by compare-and-swap
146
147
    /// The record and its current version, or `None` when it was never
148
    /// written.
149
    fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>>;
150
    /// Replace the record only if its version is still `expected`
151
    /// (`None`: only if it does not exist yet). `Conflict` otherwise, and
152
    /// then nothing is changed. Returns the new version.
153
    fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version>;
154
}
155
156
/// A reference record's version on stores that have no native one: the
157
/// hash of its bytes, which two different records never share.
1581167×
fn content_version(bytes: &[u8]) -> Version {
1591167×
    Version(blake3::hash(bytes).to_hex().to_string())
1601167×
}
161
162213×
fn check_expected(key: &str, current: Option<&Version>, expected: Option<&Version>) -> Result<()> {
163213×
    if current == expected {
164181×
        Ok(())
165
    } else {
16632×
        Err(Error::Conflict(key.to_string()))
167
    }
168213×
}
169
170
// ---------------------------------------------------------------- directory
171
172
/// A store in a directory: each key a file under the root. Create-only
173
/// writes go through a hard link, which the file system refuses when the
174
/// name is taken, and a reference is updated under a lock file beside it.
175
/// Several processes on one machine can share it; it is also what the
176
/// tests and `oxy remote check` use.
177
pub struct LocalStore {
178
    root: PathBuf,
179
}
180
181
/// How long a reference's lock may be held before it counts as abandoned
182
/// by a process that died, and how long a writer waits for it.
183
const LOCK_STALE: Duration = Duration::from_secs(60);
184
const LOCK_WAIT: Duration = Duration::from_secs(10);
185
186
impl LocalStore {
187
    /// Open the store at `root`, creating the directory if needed.
1882875×
    pub fn open(root: impl Into<PathBuf>) -> Result<LocalStore> {
1892875×
        let root = root.into();
1902875×
        fs::create_dir_all(&root)?;
1912875×
        Ok(LocalStore { root })
1922875×
    }
193
1941×
    pub fn root(&self) -> &Path {
1951×
        &self.root
1961×
    }
197
198118670×
    fn path(&self, key: &str) -> Result<PathBuf> {
199118670×
        check_key(key)?;
200118668×
        Ok(self.root.join(key))
201118670×
    }
202
20312902×
    fn temp_beside(&self, path: &Path) -> PathBuf {
20412902×
        let mut nonce = [0u8; 6];
20512902×
        rand::RngCore::fill_bytes(&mut rand::rngs::OsRng, &mut nonce);
20612902×
        let name = path
20712902×
            .file_name()
20812902×
            .map(|n| n.to_string_lossy().into_owned())
20912902×
            .unwrap_or_default();
21012902×
        path.with_file_name(format!(".{name}.tmp-{}", hex::encode(nonce)))
21112902×
    }
212
21335254×
    fn list_dir(&self, dir: &Path, rel: &str, prefix: &str, out: &mut Vec<Entry>) -> Result<()> {
21435254×
        let entries = match fs::read_dir(dir) {
21535254×
            Ok(e) => e,
2160×
            Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
2170×
            Err(e) => return Err(e.into()),
218
        };
21986541×
        for entry in entries {
22086541×
            let entry = entry?;
22186541×
            let name = entry.file_name().to_string_lossy().into_owned();
222
            // Temporary and lock files are not objects.
22386541×
            if name.starts_with('.') {
22443×
                continue;
22586498×
            }
22686498×
            let key = if rel.is_empty() {
22732727×
                name.clone()
228
            } else {
22953771×
                format!("{rel}/{name}")
230
            };
23186498×
            let ty = entry.file_type()?;
23286498×
            if ty.is_dir() {
233
                // Descend only where the prefix could still match.
23448225×
                let dir_prefix = format!("{key}/");
23548225×
                if prefix.starts_with(&dir_prefix) || dir_prefix.starts_with(prefix) {
23623610×
                    self.list_dir(&entry.path(), &key, prefix, out)?;
23724615×
                }
23838273×
            } else if ty.is_file() && key.starts_with(prefix) {
23927954×
                let meta = entry.metadata()?;
24027954×
                out.push(Entry {
24127954×
                    key,
24227954×
                    size: meta.len(),
24327954×
                    modified_ms: modified_ms(&meta),
24427954×
                });
24510319×
            }
246
        }
24735254×
        Ok(())
24835254×
    }
249
250
    /// Take `path.lock`, waiting for another writer, and removing a lock
251
    /// a dead process left behind.
252128×
    fn lock(&self, key: &str, path: &Path) -> Result<PathBuf> {
253128×
        let lock = path.with_file_name(format!(
254
            ".{}.lock",
255128×
            path.file_name()
256128×
                .map(|n| n.to_string_lossy().into_owned())
257128×
                .unwrap_or_default()
258
        ));
259128×
        let started = Instant::now();
260
        loop {
261129×
            match fs::OpenOptions::new()
262129×
                .write(true)
263129×
                .create_new(true)
264129×
                .open(&lock)
265
            {
266128×
                Ok(mut f) => {
267128×
                    let _ = writeln!(f, "{}", std::process::id());
268128×
                    return Ok(lock);
269
                }
2701×
                Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
2711×
                    if let Ok(m) = fs::metadata(&lock) {
2721×
                        let age = m.modified().ok().and_then(|t| t.elapsed().ok());
2731×
                        if age.is_some_and(|a| a > LOCK_STALE) {
2741×
                            let _ = fs::remove_file(&lock);
2751×
                            continue;
2760×
                        }
2770×
                    }
2780×
                    if started.elapsed() > LOCK_WAIT {
2790×
                        return Err(Error::Busy(key.to_string()));
2800×
                    }
2810×
                    std::thread::sleep(Duration::from_millis(10));
282
                }
2830×
                Err(e) => return Err(e.into()),
284
            }
285
        }
286128×
    }
287
}
288
289
/// A file's modification time as wall milliseconds.
29027968×
fn modified_ms(meta: &fs::Metadata) -> Option<u64> {
29127968×
    meta.modified()
29227968×
        .ok()
29327968×
        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
29427968×
        .map(|d| d.as_millis() as u64)
29527968×
}
296
297
impl LocalStore {
298
    /// Link `tmp` into `path`, create-only; the directory is synced and
299
    /// `tmp` removed either way. `Exists` when the name is taken.
3008142×
    fn link_into_place(&self, key: &str, tmp: &Path, path: &Path) -> Result<()> {
3018142×
        let linked = fs::hard_link(tmp, path);
3028142×
        let _ = fs::remove_file(tmp);
3030×
        match linked {
304
            Ok(()) => {
3058142×
                if let Some(dir) = path.parent() {
3068142×
                    crate::durable::sync_dir(dir)?;
3070×
                }
3088142×
                Ok(())
309
            }
3100×
            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
3110×
                Err(Error::Exists(key.to_string()))
312
            }
3130×
            Err(e) => Err(e.into()),
314
        }
3158142×
    }
316
317
    /// Create `path`'s directory, syncing the first directory that was
318
    /// made so its entry is durable too.
31912971×
    fn ensure_dir(&self, path: &Path) -> Result<()> {
32012971×
        let Some(dir) = path.parent() else {
3210×
            return Ok(());
322
        };
32312971×
        if dir.is_dir() {
3242133×
            return Ok(());
32510838×
        }
32610838×
        let mut made = dir.to_path_buf();
32711690×
        while let Some(parent) = made.parent() {
32811690×
            if parent.is_dir() || parent == self.root {
32910838×
                break;
330852×
            }
331852×
            made = parent.to_path_buf();
332
        }
33310838×
        fs::create_dir_all(dir)?;
33410838×
        if let Some(parent) = made.parent() {
33510838×
            crate::durable::sync_dir(parent)?;
3360×
        }
33710838×
        Ok(())
33812971×
    }
339
}
340
341
impl Store for LocalStore {
34286×
    fn describe(&self) -> String {
34386×
        self.root.display().to_string()
34486×
    }
345
34625×
    fn stat(&self, key: &str) -> Result<Option<Entry>> {
34725×
        match fs::metadata(self.path(key)?) {
34814×
            Ok(m) if m.is_file() => Ok(Some(Entry {
34914×
                key: key.to_string(),
35014×
                size: m.len(),
35114×
                modified_ms: modified_ms(&m),
35214×
            })),
3530×
            Ok(_) => Ok(None),
35411×
            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
3550×
            Err(e) => Err(e.into()),
356
        }
35725×
    }
358
359
    /// Every file written and synced (on every core), then each linked
360
    /// into place and each directory synced once: durable when this
361
    /// returns, as one at a time would be, with far fewer waits.
3621355×
    fn put_many_new(&self, objects: &[(String, Vec<u8>)]) -> Result<()> {
363
        use rayon::prelude::*;
3641355×
        let mut todo: Vec<(PathBuf, PathBuf, &[u8])> = Vec::new();
3654760×
        for (key, bytes) in objects {
3664760×
            let path = self.path(key)?;
3677587×
            if path.exists() || todo.iter().any(|(p, ..)| *p == path) {
3680×
                continue;
3694760×
            }
3704760×
            self.ensure_dir(&path)?;
3714760×
            todo.push((path.clone(), self.temp_beside(&path), bytes));
372
        }
3731355×
        if todo.is_empty() {
3740×
            return Ok(());
3751355×
        }
3761355×
        crate::durable::step("write loose objects")?;
3771353×
        todo.par_iter()
3784747×
            .try_for_each(|(_, tmp, bytes)| -> io::Result<()> {
3794747×
                let mut f = fs::File::create(tmp)?;
3804747×
                f.write_all(bytes)?;
3814747×
                f.sync_all()
3824747×
            })?;
3831353×
        crate::durable::step("rename loose objects")?;
3841351×
        let mut dirs: std::collections::BTreeSet<PathBuf> = std::collections::BTreeSet::new();
3854734×
        for (path, tmp, _) in &todo {
3864734×
            let linked = fs::hard_link(tmp, path);
3874734×
            let _ = fs::remove_file(tmp);
3880×
            match linked {
389
                Ok(()) => {
3904734×
                    if let Some(d) = path.parent() {
3914734×
                        dirs.insert(d.to_path_buf());
3924734×
                    }
393
                }
3940×
                Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
3950×
                Err(e) => return Err(e.into()),
396
            }
397
        }
3981351×
        dirs.par_iter()
3994707×
            .try_for_each(|d| crate::durable::sync_dir(d))?;
4001351×
        Ok(())
4011355×
    }
402
403
    /// The file is linked into place when it is on this file system,
404
    /// else copied; it is removed either way.
40569×
    fn put_new_file(&self, key: &str, file: &Path) -> Result<()> {
40669×
        let path = self.path(key)?;
40769×
        if path.exists() {
4080×
            let _ = fs::remove_file(file);
4090×
            return Err(Error::Exists(key.to_string()));
41069×
        }
41169×
        self.ensure_dir(&path)?;
41269×
        match fs::hard_link(file, &path) {
413
            Ok(()) => {
41469×
                let _ = fs::remove_file(file);
41569×
                if let Some(dir) = path.parent() {
41669×
                    crate::durable::sync_dir(dir)?;
4170×
                }
41869×
                Ok(())
419
            }
4200×
            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
4210×
                let _ = fs::remove_file(file);
4220×
                Err(Error::Exists(key.to_string()))
423
            }
424
            Err(_) => {
425
                // Another file system: copy beside the name, then link.
4260×
                let tmp = self.temp_beside(&path);
4270×
                let copied = (|| {
4280×
                    let mut src = fs::File::open(file)?;
4290×
                    let mut dst = fs::File::create(&tmp)?;
4300×
                    io::copy(&mut src, &mut dst)?;
4310×
                    dst.sync_all()
432
                })();
4330×
                let _ = fs::remove_file(file);
4340×
                copied?;
4350×
                self.link_into_place(key, &tmp, &path)
436
            }
437
        }
43869×
    }
439
44029094×
    fn has(&self, key: &str) -> Result<bool> {
44129094×
        Ok(self.path(key)?.is_file())
44229094×
    }
443
44457053×
    fn get(&self, key: &str) -> Result<Vec<u8>> {
44557053×
        let path = self.path(key)?;
44657052×
        match fs::read(&path) {
44750655×
            Ok(b) => Ok(b),
4486397×
            Err(e) if e.kind() == io::ErrorKind::NotFound => Err(Error::NotFound(key.to_string())),
4490×
            Err(e) => Err(e.into()),
450
        }
45157053×
    }
452
45316005×
    fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>> {
45416005×
        let path = self.path(key)?;
45516005×
        let mut f = match fs::File::open(&path) {
45615921×
            Ok(f) => f,
45784×
            Err(e) if e.kind() == io::ErrorKind::NotFound => {
45884×
                return Err(Error::NotFound(key.to_string()))
459
            }
4600×
            Err(e) => return Err(e.into()),
461
        };
46215921×
        let len = f.metadata()?.len();
46315921×
        if range.end > len || range.start > range.end {
4645×
            return Err(Error::Backend(format!(
4655×
                "{key}: bytes {}..{} asked of an object of {len} bytes",
4665×
                range.start, range.end
4675×
            )));
46815916×
        }
46915916×
        f.seek(SeekFrom::Start(range.start))?;
47015916×
        let mut out = vec![0u8; (range.end - range.start) as usize];
47115916×
        f.read_exact(&mut out)?;
47215916×
        Ok(out)
47316005×
    }
474
4758163×
    fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()> {
4768163×
        let path = self.path(key)?;
4778162×
        if path.exists() {
47820×
            return Err(Error::Exists(key.to_string()));
4798142×
        }
4808142×
        self.ensure_dir(&path)?;
481
        // Written beside its name, then linked into it: the link fails if
482
        // the name was taken meanwhile, and a reader never sees a part.
4838142×
        let tmp = self.temp_beside(&path);
4848142×
        let written = (|| {
4858142×
            let mut f = fs::File::create(&tmp)?;
4868142×
            f.write_all(bytes)?;
4878142×
            f.sync_all()
488
        })();
4898142×
        if let Err(e) = written {
4900×
            let _ = fs::remove_file(&tmp);
4910×
            return Err(e.into());
4928142×
        }
4938142×
        self.link_into_place(key, &tmp, &path)
4948163×
    }
495
49611644×
    fn list(&self, prefix: &str) -> Result<Vec<Entry>> {
49711644×
        let mut out = Vec::new();
49811644×
        self.list_dir(&self.root, "", prefix, &mut out)?;
499157116×
        out.sort_by(|a, b| a.key.cmp(&b.key));
50011644×
        Ok(out)
50111644×
    }
502
5032541×
    fn delete(&self, key: &str) -> Result<()> {
5042541×
        let path = self.path(key)?;
5052541×
        match fs::remove_file(&path) {
5061767×
            Ok(()) => {}
507774×
            Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
5080×
            Err(e) => return Err(e.into()),
509
        }
510
        // A directory left empty goes too, up to the root, so the store
511
        // holds nothing but its objects.
5121767×
        let mut dir = path.parent();
5132237×
        while let Some(d) = dir {
5142237×
            if d == self.root || fs::remove_dir(d).is_err() {
5151767×
                break;
516470×
            }
517470×
            dir = d.parent();
518
        }
5191767×
        Ok(())
5202541×
    }
521
522801×
    fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> {
523801×
        let path = self.path(key)?;
524801×
        match fs::read(&path) {
525727×
            Ok(b) => {
526727×
                let v = content_version(&b);
527727×
                Ok(Some((b, v)))
528
            }
52974×
            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
5300×
            Err(e) => Err(e.into()),
531
        }
532801×
    }
533
534128×
    fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> {
535128×
        let path = self.path(key)?;
536128×
        if let Some(dir) = path.parent() {
537128×
            fs::create_dir_all(dir)?;
5380×
        }
539128×
        let lock = self.lock(key, &path)?;
540128×
        let result = (|| {
541128×
            let current = self.read_ref(key)?.map(|(_, v)| v);
542128×
            check_expected(key, current.as_ref(), expected)?;
543112×
            crate::durable::write_atomic(&path, bytes)?;
544112×
            Ok(content_version(bytes))
545
        })();
546128×
        let _ = fs::remove_file(&lock);
547128×
        result
548128×
    }
549
}
550
551
// ---------------------------------------------------------------- memory
552
553
/// A store in memory, for tests: the conditional writes behave as the
554
/// cloud stores' do.
555
#[derive(Default)]
556
pub struct MemoryStore {
557
    objects: Mutex<BTreeMap<String, (Vec<u8>, u64)>>,
558
}
559
560455×
fn now_ms() -> u64 {
561455×
    std::time::SystemTime::now()
562455×
        .duration_since(std::time::UNIX_EPOCH)
563455×
        .map(|d| d.as_millis() as u64)
564455×
        .unwrap_or(0)
565455×
}
566
567
impl MemoryStore {
56824×
    pub fn new() -> MemoryStore {
56924×
        MemoryStore::default()
57024×
    }
571
5725127×
    fn map(&self) -> std::sync::MutexGuard<'_, BTreeMap<String, (Vec<u8>, u64)>> {
5735127×
        self.objects.lock().unwrap_or_else(|p| p.into_inner())
5745127×
    }
575
576
    /// Pretend `key` was written `age` ago (for grace-period tests).
5770×
    pub fn age(&self, key: &str, age: Duration) {
5780×
        if let Some(entry) = self.map().get_mut(key) {
5790×
            entry.1 = now_ms().saturating_sub(age.as_millis() as u64);
5800×
        }
5810×
    }
582
}
583
584
impl Store for MemoryStore {
5851×
    fn describe(&self) -> String {
5861×
        "memory".into()
5871×
    }
588
5891945×
    fn has(&self, key: &str) -> Result<bool> {
5901945×
        check_key(key)?;
5911945×
        Ok(self.map().contains_key(key))
5921945×
    }
593
5941993×
    fn get(&self, key: &str) -> Result<Vec<u8>> {
5951993×
        check_key(key)?;
5961993×
        self.map()
5971993×
            .get(key)
5981993×
            .map(|(b, _)| b.clone())
5991993×
            .ok_or_else(|| Error::NotFound(key.to_string()))
6001993×
    }
601
6021212×
    fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>> {
6031212×
        let all = self.get(key)?;
6041131×
        let len = all.len() as u64;
6051131×
        if range.end > len || range.start > range.end {
6061×
            return Err(Error::Backend(format!(
6071×
                "{key}: bytes {}..{} asked of an object of {len} bytes",
6081×
                range.start, range.end
6091×
            )));
6101130×
        }
6111130×
        Ok(all[range.start as usize..range.end as usize].to_vec())
6121212×
    }
613
614389×
    fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()> {
615389×
        check_key(key)?;
616389×
        let mut map = self.map();
617389×
        if map.contains_key(key) {
6183×
            return Err(Error::Exists(key.to_string()));
619386×
        }
620386×
        map.insert(key.to_string(), (bytes.to_vec(), now_ms()));
621386×
        Ok(())
622389×
    }
623
624365×
    fn list(&self, prefix: &str) -> Result<Vec<Entry>> {
625365×
        Ok(self
626365×
            .map()
627365×
            .range(prefix.to_string()..)
6282210×
            .take_while(|(k, _)| k.starts_with(prefix))
629365×
            .map(|(k, (v, t))| Entry {
6302095×
                key: k.clone(),
6312095×
                size: v.len() as u64,
6322095×
                modified_ms: Some(*t),
6332095×
            })
634365×
            .collect())
635365×
    }
636
637139×
    fn delete(&self, key: &str) -> Result<()> {
638139×
        check_key(key)?;
639139×
        self.map().remove(key);
640139×
        Ok(())
641139×
    }
642
643211×
    fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> {
644211×
        check_key(key)?;
645211×
        Ok(self
646211×
            .map()
647211×
            .get(key)
648211×
            .map(|(b, _)| (b.clone(), content_version(b))))
649211×
    }
650
65185×
    fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> {
65285×
        check_key(key)?;
65385×
        let mut map = self.map();
65485×
        let current = map.get(key).map(|(b, _)| content_version(b));
65585×
        check_expected(key, current.as_ref(), expected)?;
65669×
        map.insert(key.to_string(), (bytes.to_vec(), now_ms()));
65769×
        Ok(content_version(bytes))
65885×
    }
659
}
660
661
// ---------------------------------------------------------------- caching
662
663
/// A store in front of another (oxygen#68): objects are read through a
664
/// local directory and written through it, to the remote first, so the
665
/// remote always holds everything and the cache can be dropped at any
666
/// time. Objects never change, so a cached one is always right (and every
667
/// read is hashed again above this layer). The cache is bounded: past its
668
/// limit the objects used least recently are removed. An object larger
669
/// than an eighth of the limit is not cached; it is read by range from
670
/// the remote. References are never cached: they are read from and
671
/// written to the remote every time, so compare-and-swap is the remote's.
672
pub struct CachingStore {
673
    cache: LocalStore,
674
    remote: std::sync::Arc<dyn Store>,
675
    limit: u64,
676
    /// Bytes in the cache, counted on first need and kept up to date.
677
    used: Mutex<Option<u64>>,
678
}
679
680
/// Where a caching store keeps the ranges it read of objects too large to
681
/// keep whole, and those objects' sizes: apart from every object key.
682
const RANGES: &str = "cached-range";
683
const SIZES: &str = "cached-size";
684
685
/// How stale a cached object's use time may get before a read renews it.
686
const TOUCH_AFTER: Duration = Duration::from_secs(60);
687
688
impl CachingStore {
689
    /// `remote` behind a cache in the directory `dir` of at most `limit`
690
    /// bytes.
6918×
    pub fn open(
6928×
        remote: std::sync::Arc<dyn Store>,
6938×
        dir: impl Into<PathBuf>,
6948×
        limit: u64,
6958×
    ) -> Result<CachingStore> {
696
        Ok(CachingStore {
6978×
            cache: LocalStore::open(dir)?,
6988×
            remote,
6998×
            limit,
7008×
            used: Mutex::new(None),
701
        })
7028×
    }
703
7040×
    pub fn remote(&self) -> &std::sync::Arc<dyn Store> {
7050×
        &self.remote
7060×
    }
707
708
    /// Bytes the cache holds now.
70923×
    pub fn cached_bytes(&self) -> Result<u64> {
71023×
        let mut used = self.used.lock().unwrap_or_else(|p| p.into_inner());
71123×
        if used.is_none() {
7121×
            *used = Some(self.cache.list("")?.iter().map(|e| e.size).sum());
71322×
        }
71423×
        Ok(used.unwrap_or(0))
71523×
    }
716
717
    /// Whether an object of `size` bytes is kept in the cache at all.
71869×
    fn cacheable(&self, size: u64) -> bool {
71969×
        size <= self.limit / 8
72069×
    }
721
722
    /// Keep a copy of an object the remote holds.
72367×
    fn keep(&self, key: &str, bytes: &[u8]) -> Result<()> {
72467×
        if !self.cacheable(bytes.len() as u64) {
7251×
            return Ok(());
72666×
        }
72766×
        match self.cache.put_new(key, bytes) {
72866×
            Ok(()) => self.added(bytes.len() as u64),
7290×
            Err(Error::Exists(_)) => Ok(()),
7300×
            Err(e) => Err(e),
731
        }
73267×
    }
733
734
    /// Count `n` new bytes, and remove the least recently used objects
735
    /// once the cache is past its limit, down to nine tenths of it.
73666×
    fn added(&self, n: u64) -> Result<()> {
73766×
        let total = {
73866×
            let mut used = self.used.lock().unwrap_or_else(|p| p.into_inner());
73966×
            let total = match *used {
74061×
                Some(u) => u + n,
741
                // Counted now, with the new object already in place.
7425×
                None => self.cache.list("")?.iter().map(|e| e.size).sum(),
743
            };
74466×
            *used = Some(total);
74566×
            total
746
        };
74766×
        if total <= self.limit {
74834×
            return Ok(());
74932×
        }
75032×
        let mut entries = self.cache.list("")?;
751736×
        entries.sort_by_key(|e| e.modified_ms.unwrap_or(0));
75232×
        let mut left: u64 = entries.iter().map(|e| e.size).sum();
75332×
        let target = self.limit / 10 * 9;
75464×
        for e in entries {
75564×
            if left <= target {
75632×
                break;
75732×
            }
75832×
            self.cache.delete(&e.key)?;
75932×
            left -= e.size;
760
        }
76132×
        *self.used.lock().unwrap_or_else(|p| p.into_inner()) = Some(left);
76232×
        Ok(())
76366×
    }
764
765
    /// An object's size: kept on disk once the remote has said it (objects
766
    /// never change), so it is asked once. `None` when there is no object.
7672×
    fn size_of(&self, key: &str) -> Result<Option<u64>> {
7682×
        let skey = format!("{SIZES}/{key}");
7692×
        if let Some(n) = self
7702×
            .cache
7712×
            .get(&skey)
7722×
            .ok()
7732×
            .and_then(|b| String::from_utf8(b).ok())
7742×
            .and_then(|t| t.parse().ok())
775
        {
7760×
            return Ok(Some(n));
7772×
        }
7782×
        let size = self.remote.stat(key)?.map(|e| e.size);
7792×
        if let Some(n) = size {
7802×
            self.keep(&skey, n.to_string().as_bytes())?;
7810×
        }
7822×
        Ok(size)
7832×
    }
784
785
    /// Mark a cached object used now, at most once a minute.
78631×
    fn touch(&self, key: &str) {
78731×
        let Ok(path) = self.cache.path(key) else {
7880×
            return;
789
        };
79031×
        let stale = fs::metadata(&path)
79131×
            .and_then(|m| m.modified())
79231×
            .ok()
79331×
            .and_then(|t| t.elapsed().ok())
79431×
            .is_some_and(|age| age > TOUCH_AFTER);
79531×
        if stale {
7960×
            if let Ok(f) = fs::File::options().append(true).open(&path) {
7970×
                let _ = f.set_modified(std::time::SystemTime::now());
7980×
            }
79931×
        }
80031×
    }
801
}
802
803
impl Store for CachingStore {
8041×
    fn describe(&self) -> String {
8051×
        format!(
806
            "{} (cached in {})",
8071×
            self.remote.describe(),
8081×
            self.cache.root().display()
809
        )
8101×
    }
811
81217×
    fn has(&self, key: &str) -> Result<bool> {
81317×
        Ok(self.cache.has(key)? || self.remote.has(key)?)
81417×
    }
815
81657×
    fn get(&self, key: &str) -> Result<Vec<u8>> {
81757×
        match self.cache.get(key) {
81828×
            Ok(bytes) => {
81928×
                self.touch(key);
82028×
                return Ok(bytes);
821
            }
822
            // Not cached, or removed by another process's eviction meanwhile.
82329×
            Err(Error::NotFound(_)) => {}
8240×
            Err(e) => return Err(e),
825
        }
82629×
        let bytes = self.remote.get(key)?;
82728×
        self.keep(key, &bytes)?;
82828×
        Ok(bytes)
82957×
    }
830
8316×
    fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>> {
8326×
        match self.cache.get_range(key, range.clone()) {
8332×
            Ok(bytes) => {
8342×
                self.touch(key);
8352×
                return Ok(bytes);
836
            }
8373×
            Err(Error::NotFound(_)) => {}
8381×
            Err(e) if self.cache.has(key)? => return Err(e),
8390×
            Err(_) => {}
840
        }
841
        // A large object's ranges are kept as they are read (packs never
842
        // change, oxygenhub#234): a server opens the store again for every
843
        // request, so only what is on disk carries over.
8443×
        let rkey = format!("{RANGES}/{key}/{}-{}", range.start, range.end);
8453×
        if let Ok(bytes) = self.cache.get(&rkey) {
8461×
            self.touch(&rkey);
8471×
            return Ok(bytes);
8482×
        }
849
        // A small object is fetched whole and kept; a large one is read by
850
        // range and the range kept. Its size is kept too, so the remote is
851
        // asked it once.
8522×
        match self.size_of(key)? {
8532×
            Some(size) if self.cacheable(size) => {
8541×
                let bytes = self.get(key)?;
8551×
                let len = bytes.len() as u64;
8561×
                if range.end > len || range.start > range.end {
8570×
                    return Err(Error::Backend(format!(
8580×
                        "{key}: bytes {}..{} asked of an object of {len} bytes",
8590×
                        range.start, range.end
8600×
                    )));
8611×
                }
8621×
                Ok(bytes[range.start as usize..range.end as usize].to_vec())
863
            }
864
            Some(_) => {
8651×
                let bytes = self.remote.get_range(key, range)?;
8661×
                self.keep(&rkey, &bytes)?;
8671×
                Ok(bytes)
868
            }
8690×
            None => Err(Error::NotFound(key.to_string())),
870
        }
8716×
    }
872
87329×
    fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()> {
87429×
        self.remote.put_new(key, bytes)?;
87528×
        self.keep(key, bytes)
87629×
    }
877
8782×
    fn put_many_new(&self, objects: &[(String, Vec<u8>)]) -> Result<()> {
8792×
        self.remote.put_many_new(objects)?;
8808×
        for (key, bytes) in objects {
8818×
            self.keep(key, bytes)?;
882
        }
8832×
        Ok(())
8842×
    }
885
8860×
    fn put_new_file(&self, key: &str, path: &Path) -> Result<()> {
8870×
        let size = fs::metadata(path)?.len();
8880×
        let copy = if self.cacheable(size) {
8890×
            Some(fs::read(path)?)
890
        } else {
8910×
            None
892
        };
8930×
        self.remote.put_new_file(key, path)?;
8940×
        match copy {
8950×
            Some(bytes) => self.keep(key, &bytes),
8960×
            None => Ok(()),
897
        }
8980×
    }
899
90015×
    fn list(&self, prefix: &str) -> Result<Vec<Entry>> {
90115×
        self.remote.list(prefix)
90215×
    }
903
9042×
    fn stat(&self, key: &str) -> Result<Option<Entry>> {
9052×
        self.remote.stat(key)
9062×
    }
907
9085×
    fn delete(&self, key: &str) -> Result<()> {
9095×
        self.remote.delete(key)?;
910
        // Its kept ranges and size go with it.
9115×
        let mut extra = self.cache.list(&format!("{RANGES}/{key}/"))?;
9125×
        extra.extend(self.cache.stat(&format!("{SIZES}/{key}"))?);
9135×
        for e in extra {
9142×
            self.cache.delete(&e.key)?;
9152×
            let mut used = self.used.lock().unwrap_or_else(|p| p.into_inner());
9162×
            if let Some(u) = used.as_mut() {
9172×
                *u = u.saturating_sub(e.size);
9182×
            }
919
        }
9205×
        let size = self.cache.stat(key)?.map(|e| e.size);
9215×
        self.cache.delete(key)?;
9225×
        if let Some(n) = size {
9232×
            let mut used = self.used.lock().unwrap_or_else(|p| p.into_inner());
9242×
            if let Some(u) = used.as_mut() {
9252×
                *u = u.saturating_sub(n);
9262×
            }
9273×
        }
9285×
        Ok(())
9295×
    }
930
93111×
    fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> {
93211×
        self.remote.read_ref(key)
93311×
    }
934
9359×
    fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> {
9369×
        self.remote.write_ref(key, bytes, expected)
9379×
    }
938
}
939
940
// ---------------------------------------------------------------- conformance
941
942
/// Exercise a store under `prefix` (which must be free, and is left
943
/// empty) and report what passed: object round trips, ranges, create-only
944
/// refusal, listing, deletion, and compare-and-swap on a reference. Every
945
/// store runs this in its tests, and `oxy remote check` runs it against a
946
/// remote before trusting it with a repository.
9476×
pub fn conformance(store: &dyn Store, prefix: &str) -> Result<Vec<&'static str>> {
9486×
    let mut passed = Vec::new();
949144×
    let key = |name: &str| format!("{prefix}/{name}");
9506×
    let fail = |what: &str| Error::Backend(format!("{}: {what}", store.describe()));
951132×
    let expect = |ok: bool, what: &str| if ok { Ok(()) } else { Err(fail(what)) };
952
9536×
    expect(
9546×
        store.list(prefix)?.is_empty(),
9556×
        "the probe prefix is not empty",
9560×
    )?;
9576×
    expect(
9586×
        !store.has(&key("a"))?,
9596×
        "has() of a missing object says true",
9600×
    )?;
9616×
    expect(
9626×
        matches!(store.get(&key("a")), Err(Error::NotFound(_))),
9636×
        "get() of a missing object is not NotFound",
9640×
    )?;
9656×
    passed.push("missing objects are reported missing");
966
9671572864×
    let a: Vec<u8> = (0..256u32 * 1024).map(|i| (i % 251) as u8).collect();
9686×
    store.put_new(&key("a"), &a)?;
9696×
    expect(store.has(&key("a"))?, "has() after put_new says false")?;
9706×
    expect(
9716×
        store.get(&key("a"))? == a,
9726×
        "get() returns other bytes than put_new wrote",
9730×
    )?;
9746×
    passed.push("an object round-trips");
975
9766×
    expect(
9776×
        store.get_range(&key("a"), 1000..1500)? == a[1000..1500],
9786×
        "get_range() returns the wrong bytes",
9790×
    )?;
9806×
    expect(
9816×
        store.get_range(&key("a"), 0..0)?.is_empty(),
9826×
        "an empty range is not empty",
9830×
    )?;
9846×
    expect(
9856×
        store.get_range(&key("a"), 0..a.len() as u64 + 1).is_err(),
9866×
        "a range past the end is not refused",
9876×
    )?;
9886×
    passed.push("ranges read correctly and are bounded");
989
9906×
    expect(
9916×
        matches!(store.put_new(&key("a"), b"other"), Err(Error::Exists(_))),
9926×
        "put_new() over an existing object is not refused",
9930×
    )?;
9946×
    expect(
9956×
        store.get(&key("a"))? == a,
9966×
        "a refused put_new() changed the object",
9970×
    )?;
9986×
    passed.push("objects are written once");
999
10006×
    store.put_new(&key("dir/b"), b"bb")?;
10016×
    let listed: Vec<(String, u64)> = store
10026×
        .list(prefix)?
10036×
        .into_iter()
100412×
        .map(|e| (e.key, e.size))
10056×
        .collect();
10066×
    expect(
10076×
        listed == vec![(key("a"), a.len() as u64), (key("dir/b"), 2)],
10086×
        "list() does not return the two objects, sorted, with their sizes",
10096×
    )?;
10106×
    expect(
10116×
        store
10126×
            .stat(&key("dir/b"))?
10136×
            .is_some_and(|e| e.key == key("dir/b") && e.size == 2)
10146×
            && store.stat(&key("dir/c"))?.is_none(),
10156×
        "stat() does not describe one object, or describes a missing one",
10160×
    )?;
10176×
    expect(
10186×
        store
10196×
            .list(&key("dir/"))?
10206×
            .into_iter()
10216×
            .map(|e| (e.key, e.size))
10226×
            .collect::<Vec<_>>()
10236×
            == vec![(key("dir/b"), 2)],
10246×
        "list() of a sub-prefix is wrong",
10250×
    )?;
10266×
    expect(
10276×
        store.list(&key("nothing/"))?.is_empty(),
10286×
        "list() of an unused prefix is not empty",
10290×
    )?;
10306×
    passed.push("listing by prefix");
1031
10326×
    store.delete(&key("dir/b"))?;
10336×
    expect(
10346×
        !store.has(&key("dir/b"))?,
10356×
        "an object is still there after delete()",
10360×
    )?;
10376×
    store.delete(&key("dir/b"))?;
10386×
    passed.push("deletion, and deleting again, succeed");
1039
10406×
    let r = key("refs");
10416×
    expect(
10426×
        store.read_ref(&r)?.is_none(),
10436×
        "an unwritten reference reads as something",
10440×
    )?;
10456×
    let v1 = store.write_ref(&r, b"one", None)?;
10466×
    expect(
10476×
        matches!(store.write_ref(&r, b"again", None), Err(Error::Conflict(_))),
10486×
        "a second create-only write of the reference is not refused",
10490×
    )?;
10506×
    let (bytes, seen) = store
10516×
        .read_ref(&r)?
10526×
        .ok_or_else(|| fail("the reference vanished"))?;
10536×
    expect(
10546×
        bytes == b"one" && seen == v1,
10556×
        "the reference reads back wrong",
10560×
    )?;
10576×
    let v2 = store.write_ref(&r, b"two", Some(&v1))?;
10586×
    expect(v2 != v1, "the version did not change on write")?;
10596×
    expect(
10600×
        matches!(
10616×
            store.write_ref(&r, b"three", Some(&v1)),
1062
            Err(Error::Conflict(_))
1063
        ),
10646×
        "a write with a stale version is not refused",
10650×
    )?;
10666×
    let (bytes, seen) = store
10676×
        .read_ref(&r)?
10686×
        .ok_or_else(|| fail("the reference vanished"))?;
10696×
    expect(
10706×
        bytes == b"two" && seen == v2,
10716×
        "a refused write changed the reference",
10720×
    )?;
10736×
    passed.push("references update by compare-and-swap");
1074
10756×
    store.delete(&key("a"))?;
10766×
    store.delete(&r)?;
10776×
    expect(
10786×
        store.list(prefix)?.is_empty(),
10796×
        "the probe prefix is not empty after cleanup",
10800×
    )?;
10816×
    passed.push("cleanup");
10826×
    Ok(passed)
10836×
}
1084
1085
#[cfg(test)]
1086
mod tests {
1087
    use super::*;
1088
    use std::sync::Arc;
1089
1090
    #[test]
10911×
    fn keys_are_plain_relative_paths() {
10923×
        for ok in ["a", "packs/ab.pack", "a-b_c.d/e"] {
10933×
            check_key(ok).unwrap();
10943×
        }
109510×
        for bad in [
10961×
            "", "/a", "a/", "a//b", "..", "a/../b", "./a", "a b", "a\\b", "ä",
10971×
        ] {
109810×
            assert!(check_key(bad).is_err(), "{bad:?}");
1099
        }
11001×
        assert!(check_key(&"x".repeat(MAX_KEY_LEN + 1)).is_err());
11011×
    }
1102
1103
    #[test]
11041×
    fn a_caching_store_conforms_and_reads_and_writes_through() {
11051×
        let dir = tempfile::tempdir().unwrap();
11061×
        let remote: Arc<dyn Store> = Arc::new(MemoryStore::new());
11071×
        let store = CachingStore::open(remote.clone(), dir.path().join("cache"), 8 << 20).unwrap();
11081×
        assert_eq!(conformance(&store, "probe").unwrap().len(), 8);
11091×
        assert_eq!(
11101×
            store.cached_bytes().unwrap(),
1111
            0,
1112
            "the probe left nothing cached"
1113
        );
1114
1115
        // Written through: the remote has it, and so does the cache.
11161×
        store.put_new("loose/aa", b"written").unwrap();
11171×
        assert_eq!(remote.get("loose/aa").unwrap(), b"written");
11181×
        assert!(store.cache.has("loose/aa").unwrap());
1119
        // Read through: an object only the remote has is kept on first read.
11201×
        remote.put_new("loose/bb", b"remote only").unwrap();
11211×
        assert!(!store.cache.has("loose/bb").unwrap());
11221×
        assert_eq!(store.get_range("loose/bb", 0..6).unwrap(), b"remote");
11231×
        assert!(store.cache.has("loose/bb").unwrap());
1124
        // A cached object read after the remote lost it is still served.
11251×
        remote.delete("loose/bb").unwrap();
11261×
        assert_eq!(store.get("loose/bb").unwrap(), b"remote only");
1127
        // References are always the remote's.
11281×
        let v = remote.write_ref("refs", b"one", None).unwrap();
11291×
        assert_eq!(
11301×
            store.read_ref("refs").unwrap(),
11311×
            Some((b"one".to_vec(), v.clone()))
1132
        );
11331×
        remote.write_ref("refs", b"two", Some(&v)).unwrap();
11341×
        assert_eq!(store.read_ref("refs").unwrap().unwrap().0, b"two");
11351×
        assert!(matches!(
11361×
            store.write_ref("refs", b"three", Some(&v)),
1137
            Err(Error::Conflict(_))
1138
        ));
11391×
        assert!(!store.cache.has("refs").unwrap());
11401×
    }
1141
1142
    /// A remote that answers nothing: what is read through it was cached.
1143
    struct Unreachable;
1144
1145
    impl Store for Unreachable {
11460×
        fn describe(&self) -> String {
11470×
            "unreachable".into()
11480×
        }
11490×
        fn has(&self, _: &str) -> Result<bool> {
11500×
            Err(Error::Backend("asked the remote".into()))
11510×
        }
11520×
        fn get(&self, _: &str) -> Result<Vec<u8>> {
11530×
            Err(Error::Backend("asked the remote".into()))
11540×
        }
11550×
        fn get_range(&self, _: &str, _: Range<u64>) -> Result<Vec<u8>> {
11560×
            Err(Error::Backend("asked the remote".into()))
11570×
        }
11580×
        fn put_new(&self, _: &str, _: &[u8]) -> Result<()> {
11590×
            Err(Error::Backend("asked the remote".into()))
11600×
        }
11610×
        fn list(&self, _: &str) -> Result<Vec<Entry>> {
11620×
            Err(Error::Backend("asked the remote".into()))
11630×
        }
11640×
        fn delete(&self, _: &str) -> Result<()> {
11650×
            Err(Error::Backend("asked the remote".into()))
11660×
        }
11670×
        fn stat(&self, _: &str) -> Result<Option<Entry>> {
11680×
            Err(Error::Backend("asked the remote".into()))
11690×
        }
11700×
        fn read_ref(&self, _: &str) -> Result<Option<(Vec<u8>, Version)>> {
11710×
            Err(Error::Backend("asked the remote".into()))
11720×
        }
11730×
        fn write_ref(&self, _: &str, _: &[u8], _: Option<&Version>) -> Result<Version> {
11740×
            Err(Error::Backend("asked the remote".into()))
11750×
        }
1176
    }
1177
1178
    #[test]
11791×
    fn a_caching_store_stays_within_its_limit() {
11801×
        let dir = tempfile::tempdir().unwrap();
11811×
        let remote: Arc<dyn Store> = Arc::new(MemoryStore::new());
11821×
        let store = CachingStore::open(remote.clone(), dir.path().join("cache"), 8000).unwrap();
118320×
        for i in 0..20 {
118420×
            store
118520×
                .put_new(&format!("loose/{i:02}"), &[i as u8; 900])
118620×
                .unwrap();
118720×
            assert!(store.cached_bytes().unwrap() <= 8000);
1188
        }
11891×
        assert_eq!(
11901×
            remote.list("loose/").unwrap().len(),
1191
            20,
1192
            "the remote holds everything"
1193
        );
11941×
        let cached = store.cache.list("loose/").unwrap();
11951×
        assert!(cached.len() < 20 && cached.len() >= 7, "{}", cached.len());
11961×
        assert!(
11978×
            cached.iter().any(|e| e.key == "loose/19"),
1198
            "the newest is kept"
1199
        );
120020×
        for i in 0..20 {
120120×
            assert_eq!(
120220×
                store.get(&format!("loose/{i:02}")).unwrap(),
120320×
                vec![i as u8; 900]
1204
            );
1205
        }
1206
        // An object over an eighth of the limit is read by range, not kept.
12071×
        remote.put_new("pack-big", &[7u8; 2000]).unwrap();
12081×
        assert_eq!(store.get_range("pack-big", 10..20).unwrap(), vec![7u8; 10]);
12091×
        assert_eq!(store.get("pack-big").unwrap().len(), 2000);
12101×
        assert!(!store.cache.has("pack-big").unwrap());
1211
        // Its ranges are kept as read, and its size, so a store opened
1212
        // again (a server's next request) asks the remote nothing.
12131×
        let again =
12141×
            CachingStore::open(Arc::new(Unreachable), dir.path().join("cache"), 8000).unwrap();
12151×
        assert_eq!(again.get_range("pack-big", 10..20).unwrap(), vec![7u8; 10]);
1216
        // Counting from scratch agrees with what was kept track of.
12171×
        let fresh = CachingStore::open(remote, dir.path().join("cache"), 8000).unwrap();
12181×
        assert_eq!(fresh.cached_bytes().unwrap(), store.cached_bytes().unwrap());
1219
        // Deleting it takes its ranges and size too.
12201×
        store.delete("pack-big").unwrap();
12211×
        assert!(
12221×
            store.cache.list("cached-range/").unwrap().is_empty()
12231×
                && store.cache.list("cached-size/").unwrap().is_empty()
1224
        );
12251×
    }
1226
1227
    #[test]
12281×
    fn the_memory_store_conforms() {
12291×
        let store = MemoryStore::new();
12301×
        let passed = conformance(&store, "probe").unwrap();
12311×
        assert_eq!(passed.len(), 8, "{passed:?}");
12321×
    }
1233
1234
    #[test]
12351×
    fn the_directory_store_conforms() {
12361×
        let dir = tempfile::tempdir().unwrap();
12371×
        let store = LocalStore::open(dir.path().join("bucket")).unwrap();
12381×
        let passed = conformance(&store, "repos/one").unwrap();
12391×
        assert_eq!(passed.len(), 8, "{passed:?}");
1240
        // Nothing but the (empty) directories and no stray temporaries.
12411×
        let stray: Vec<_> = walkdir(dir.path())
12421×
            .into_iter()
12431×
            .filter(|p| p.is_file())
12441×
            .collect();
12451×
        assert!(stray.is_empty(), "{stray:?}");
12461×
        assert_eq!(
12471×
            fs::read_dir(dir.path().join("bucket")).unwrap().count(),
1248
            0,
1249
            "no empty directories left"
1250
        );
12511×
    }
1252
12532×
    fn walkdir(dir: &Path) -> Vec<PathBuf> {
12542×
        let mut out = vec![];
12552×
        if let Ok(rd) = fs::read_dir(dir) {
12562×
            for e in rd.flatten() {
12571×
                let p = e.path();
12581×
                if p.is_dir() {
12591×
                    out.extend(walkdir(&p));
12601×
                } else {
12610×
                    out.push(p);
12620×
                }
1263
            }
12640×
        }
12652×
        out
12662×
    }
1267
1268
    #[test]
12691×
    fn a_directory_store_refuses_keys_that_leave_its_root() {
12701×
        let dir = tempfile::tempdir().unwrap();
12711×
        let store = LocalStore::open(dir.path().join("bucket")).unwrap();
12721×
        assert!(matches!(
12731×
            store.put_new("../escape", b"x"),
1274
            Err(Error::Key(..))
1275
        ));
12761×
        assert!(matches!(store.get("/etc/passwd"), Err(Error::Key(..))));
12771×
        assert!(!dir.path().join("escape").exists());
12781×
    }
1279
1280
    /// Many threads race to move a reference from the same version: exactly
1281
    /// one wins each round, on both stores.
1282
    #[test]
12831×
    fn compare_and_swap_admits_one_writer_per_round() {
12841×
        let dir = tempfile::tempdir().unwrap();
12851×
        let local: Arc<dyn Store> = Arc::new(LocalStore::open(dir.path()).unwrap());
12861×
        let memory: Arc<dyn Store> = Arc::new(MemoryStore::new());
12872×
        for store in [local, memory] {
12882×
            let v0 = store.write_ref("refs", b"0", None).unwrap();
12892×
            let wins: Vec<bool> = (0..8)
129016×
                .map(|i| {
129116×
                    let store = store.clone();
129216×
                    let v0 = v0.clone();
129316×
                    std::thread::spawn(move || {
129416×
                        store
129516×
                            .write_ref("refs", format!("{}", i + 1).as_bytes(), Some(&v0))
129616×
                            .is_ok()
129716×
                    })
129816×
                })
12992×
                .collect::<Vec<_>>()
13002×
                .into_iter()
130116×
                .map(|h| h.join().unwrap())
13022×
                .collect();
13032×
            assert_eq!(
13042×
                wins.iter().filter(|w| **w).count(),
1305
                1,
1306
                "{}: {wins:?}",
13070×
                store.describe()
1308
            );
13092×
            let (bytes, _) = store.read_ref("refs").unwrap().unwrap();
13102×
            assert_ne!(bytes, b"0");
1311
        }
13121×
    }
1313
1314
    #[test]
13151×
    fn a_stale_lock_is_broken_and_a_live_one_waited_for() {
13161×
        let dir = tempfile::tempdir().unwrap();
13171×
        let store = LocalStore::open(dir.path()).unwrap();
13181×
        let lock = dir.path().join(".refs.lock");
13191×
        fs::write(&lock, "dead").unwrap();
13201×
        let old = std::time::SystemTime::now() - LOCK_STALE - Duration::from_secs(5);
13211×
        fs::File::open(&lock).unwrap().set_modified(old).unwrap();
13221×
        store.write_ref("refs", b"after a crash", None).unwrap();
13231×
        assert!(!lock.exists());
13241×
    }
1325
1326
    #[test]
13271×
    fn temporaries_and_locks_are_not_listed() {
13281×
        let dir = tempfile::tempdir().unwrap();
13291×
        let store = LocalStore::open(dir.path()).unwrap();
13301×
        store.put_new("packs/a", b"a").unwrap();
13311×
        fs::write(dir.path().join("packs/.a.tmp-ffffff"), "junk").unwrap();
13321×
        fs::write(dir.path().join(".refs.lock"), "1").unwrap();
13331×
        let keys: Vec<String> = store.list("").unwrap().into_iter().map(|e| e.key).collect();
13341×
        assert_eq!(keys, ["packs/a"]);
13351×
    }
1336
}