OXYGENHUB
◆ push-notes oxygen / crates / oxy-core / src / strata.rs
49.0 KiB · Rust · last changed renameat2's flags are unsigned on Android (refs #141) 10 days ago source blame history raw
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.
74
pub fn check_key(key: &str) -> Result<()> {
75
    let bad = |why| Error::Key(key.to_string(), why);
76
    if key.is_empty() {
77
        return Err(bad("empty"));
78
    }
79
    if key.len() > MAX_KEY_LEN {
80
        return Err(bad("longer than 1024 bytes"));
81
    }
82
    for seg in key.split('/') {
83
        if seg.is_empty() {
84
            return Err(bad(
85
                "an empty segment (a leading, trailing or doubled slash)",
86
            ));
87
        }
88
        if seg == "." || seg == ".." {
89
            return Err(bad("a . or .. segment"));
90
        }
91
        if !seg
92
            .bytes()
93
            .all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'_' || b == b'-')
94
        {
95
            return Err(bad("a character outside A-Z a-z 0-9 . _ -"));
96
        }
97
    }
98
    Ok(())
99
}
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.
124
    fn stat(&self, key: &str) -> Result<Option<Entry>> {
125
        Ok(self.list(key)?.into_iter().find(|e| e.key == key))
126
    }
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.
130
    fn put_many_new(&self, objects: &[(String, Vec<u8>)]) -> Result<()> {
131
        for (key, bytes) in objects {
132
            match self.put_new(key, bytes) {
133
                Ok(()) | Err(Error::Exists(_)) => {}
134
                Err(e) => return Err(e),
135
            }
136
        }
137
        Ok(())
138
    }
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.
141
    fn put_new_file(&self, key: &str, path: &Path) -> Result<()> {
142
        self.put_new(key, &fs::read(path)?)
143
    }
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.
158
fn content_version(bytes: &[u8]) -> Version {
159
    Version(blake3::hash(bytes).to_hex().to_string())
160
}
161
162
fn check_expected(key: &str, current: Option<&Version>, expected: Option<&Version>) -> Result<()> {
163
    if current == expected {
164
        Ok(())
165
    } else {
166
        Err(Error::Conflict(key.to_string()))
167
    }
168
}
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.
188
    pub fn open(root: impl Into<PathBuf>) -> Result<LocalStore> {
189
        let root = root.into();
190
        fs::create_dir_all(&root)?;
191
        Ok(LocalStore { root })
192
    }
193
194
    pub fn root(&self) -> &Path {
195
        &self.root
196
    }
197
198
    fn path(&self, key: &str) -> Result<PathBuf> {
199
        check_key(key)?;
200
        Ok(self.root.join(key))
201
    }
202
203
    fn temp_beside(&self, path: &Path) -> PathBuf {
204
        let mut nonce = [0u8; 6];
205
        rand::RngCore::fill_bytes(&mut rand::rngs::OsRng, &mut nonce);
206
        let name = path
207
            .file_name()
208
            .map(|n| n.to_string_lossy().into_owned())
209
            .unwrap_or_default();
210
        path.with_file_name(format!(".{name}.tmp-{}", hex::encode(nonce)))
211
    }
212
213
    fn list_dir(&self, dir: &Path, rel: &str, prefix: &str, out: &mut Vec<Entry>) -> Result<()> {
214
        let entries = match fs::read_dir(dir) {
215
            Ok(e) => e,
216
            Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
217
            Err(e) => return Err(e.into()),
218
        };
219
        for entry in entries {
220
            let entry = entry?;
221
            let name = entry.file_name().to_string_lossy().into_owned();
222
            // Temporary and lock files are not objects.
223
            if name.starts_with('.') {
224
                continue;
225
            }
226
            let key = if rel.is_empty() {
227
                name.clone()
228
            } else {
229
                format!("{rel}/{name}")
230
            };
231
            let ty = entry.file_type()?;
232
            if ty.is_dir() {
233
                // Descend only where the prefix could still match.
234
                let dir_prefix = format!("{key}/");
235
                if prefix.starts_with(&dir_prefix) || dir_prefix.starts_with(prefix) {
236
                    self.list_dir(&entry.path(), &key, prefix, out)?;
237
                }
238
            } else if ty.is_file() && key.starts_with(prefix) {
239
                let meta = entry.metadata()?;
240
                out.push(Entry {
241
                    key,
242
                    size: meta.len(),
243
                    modified_ms: modified_ms(&meta),
244
                });
245
            }
246
        }
247
        Ok(())
248
    }
249
250
    /// Take `path.lock`, waiting for another writer, and removing a lock
251
    /// a dead process left behind.
252
    fn lock(&self, key: &str, path: &Path) -> Result<PathBuf> {
253
        let lock = path.with_file_name(format!(
254
            ".{}.lock",
255
            path.file_name()
256
                .map(|n| n.to_string_lossy().into_owned())
257
                .unwrap_or_default()
258
        ));
259
        let started = Instant::now();
260
        loop {
261
            match fs::OpenOptions::new()
262
                .write(true)
263
                .create_new(true)
264
                .open(&lock)
265
            {
266
                Ok(mut f) => {
267
                    let _ = writeln!(f, "{}", std::process::id());
268
                    return Ok(lock);
269
                }
270
                Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
271
                    if let Ok(m) = fs::metadata(&lock) {
272
                        let age = m.modified().ok().and_then(|t| t.elapsed().ok());
273
                        if age.is_some_and(|a| a > LOCK_STALE) {
274
                            let _ = fs::remove_file(&lock);
275
                            continue;
276
                        }
277
                    }
278
                    if started.elapsed() > LOCK_WAIT {
279
                        return Err(Error::Busy(key.to_string()));
280
                    }
281
                    std::thread::sleep(Duration::from_millis(10));
282
                }
283
                Err(e) => return Err(e.into()),
284
            }
285
        }
286
    }
287
}
288
289
/// A file's modification time as wall milliseconds.
290
fn modified_ms(meta: &fs::Metadata) -> Option<u64> {
291
    meta.modified()
292
        .ok()
293
        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
294
        .map(|d| d.as_millis() as u64)
295
}
296
297
/// Put `tmp` at `path` only if `path` is free, as `fs::hard_link` does
298
/// (`tmp` may remain). Android forbids apps hard links in their own data
299
/// (oxygen#141): there a create-only rename does the same, atomically.
300
fn place_new(tmp: &Path, path: &Path) -> io::Result<()> {
301
    match fs::hard_link(tmp, path) {
302
        Err(e) if e.kind() == io::ErrorKind::PermissionDenied => rename_new(tmp, path),
303
        r => r,
304
    }
305
}
306
307
#[cfg(any(target_os = "linux", target_os = "android"))]
308
fn rename_new(tmp: &Path, path: &Path) -> io::Result<()> {
309
    use std::ffi::CString;
310
    use std::os::unix::ffi::OsStrExt;
311
    let from = CString::new(tmp.as_os_str().as_bytes())?;
312
    let to = CString::new(path.as_os_str().as_bytes())?;
313
    let r = unsafe {
314
        libc::renameat2(
315
            libc::AT_FDCWD,
316
            from.as_ptr(),
317
            libc::AT_FDCWD,
318
            to.as_ptr(),
319
            libc::RENAME_NOREPLACE as _,
320
        )
321
    };
322
    if r == 0 {
323
        Ok(())
324
    } else {
325
        Err(io::Error::last_os_error())
326
    }
327
}
328
329
#[cfg(not(any(target_os = "linux", target_os = "android")))]
330
fn rename_new(tmp: &Path, path: &Path) -> io::Result<()> {
331
    if path.exists() {
332
        return Err(io::ErrorKind::AlreadyExists.into());
333
    }
334
    fs::rename(tmp, path)
335
}
336
337
impl LocalStore {
338
    /// Link `tmp` into `path`, create-only; the directory is synced and
339
    /// `tmp` removed either way. `Exists` when the name is taken.
340
    fn link_into_place(&self, key: &str, tmp: &Path, path: &Path) -> Result<()> {
341
        let linked = place_new(tmp, path);
342
        let _ = fs::remove_file(tmp);
343
        match linked {
344
            Ok(()) => {
345
                if let Some(dir) = path.parent() {
346
                    crate::durable::sync_dir(dir)?;
347
                }
348
                Ok(())
349
            }
350
            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
351
                Err(Error::Exists(key.to_string()))
352
            }
353
            Err(e) => Err(e.into()),
354
        }
355
    }
356
357
    /// Create `path`'s directory, syncing the first directory that was
358
    /// made so its entry is durable too.
359
    fn ensure_dir(&self, path: &Path) -> Result<()> {
360
        let Some(dir) = path.parent() else {
361
            return Ok(());
362
        };
363
        if dir.is_dir() {
364
            return Ok(());
365
        }
366
        let mut made = dir.to_path_buf();
367
        while let Some(parent) = made.parent() {
368
            if parent.is_dir() || parent == self.root {
369
                break;
370
            }
371
            made = parent.to_path_buf();
372
        }
373
        fs::create_dir_all(dir)?;
374
        if let Some(parent) = made.parent() {
375
            crate::durable::sync_dir(parent)?;
376
        }
377
        Ok(())
378
    }
379
}
380
381
impl Store for LocalStore {
382
    fn describe(&self) -> String {
383
        self.root.display().to_string()
384
    }
385
386
    fn stat(&self, key: &str) -> Result<Option<Entry>> {
387
        match fs::metadata(self.path(key)?) {
388
            Ok(m) if m.is_file() => Ok(Some(Entry {
389
                key: key.to_string(),
390
                size: m.len(),
391
                modified_ms: modified_ms(&m),
392
            })),
393
            Ok(_) => Ok(None),
394
            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
395
            Err(e) => Err(e.into()),
396
        }
397
    }
398
399
    /// Every file written and synced (on every core), then each linked
400
    /// into place and each directory synced once: durable when this
401
    /// returns, as one at a time would be, with far fewer waits.
402
    fn put_many_new(&self, objects: &[(String, Vec<u8>)]) -> Result<()> {
403
        use rayon::prelude::*;
404
        let mut todo: Vec<(PathBuf, PathBuf, &[u8])> = Vec::new();
405
        for (key, bytes) in objects {
406
            let path = self.path(key)?;
407
            if path.exists() || todo.iter().any(|(p, ..)| *p == path) {
408
                continue;
409
            }
410
            self.ensure_dir(&path)?;
411
            todo.push((path.clone(), self.temp_beside(&path), bytes));
412
        }
413
        if todo.is_empty() {
414
            return Ok(());
415
        }
416
        crate::durable::step("write loose objects")?;
417
        todo.par_iter()
418
            .try_for_each(|(_, tmp, bytes)| -> io::Result<()> {
419
                let mut f = fs::File::create(tmp)?;
420
                f.write_all(bytes)?;
421
                f.sync_all()
422
            })?;
423
        crate::durable::step("rename loose objects")?;
424
        let mut dirs: std::collections::BTreeSet<PathBuf> = std::collections::BTreeSet::new();
425
        for (path, tmp, _) in &todo {
426
            let linked = place_new(tmp, path);
427
            let _ = fs::remove_file(tmp);
428
            match linked {
429
                Ok(()) => {
430
                    if let Some(d) = path.parent() {
431
                        dirs.insert(d.to_path_buf());
432
                    }
433
                }
434
                Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
435
                Err(e) => return Err(e.into()),
436
            }
437
        }
438
        dirs.par_iter()
439
            .try_for_each(|d| crate::durable::sync_dir(d))?;
440
        Ok(())
441
    }
442
443
    /// The file is linked into place when it is on this file system,
444
    /// else copied; it is removed either way.
445
    fn put_new_file(&self, key: &str, file: &Path) -> Result<()> {
446
        let path = self.path(key)?;
447
        if path.exists() {
448
            let _ = fs::remove_file(file);
449
            return Err(Error::Exists(key.to_string()));
450
        }
451
        self.ensure_dir(&path)?;
452
        match place_new(file, &path) {
453
            Ok(()) => {
454
                let _ = fs::remove_file(file);
455
                if let Some(dir) = path.parent() {
456
                    crate::durable::sync_dir(dir)?;
457
                }
458
                Ok(())
459
            }
460
            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
461
                let _ = fs::remove_file(file);
462
                Err(Error::Exists(key.to_string()))
463
            }
464
            Err(_) => {
465
                // Another file system: copy beside the name, then link.
466
                let tmp = self.temp_beside(&path);
467
                let copied = (|| {
468
                    let mut src = fs::File::open(file)?;
469
                    let mut dst = fs::File::create(&tmp)?;
470
                    io::copy(&mut src, &mut dst)?;
471
                    dst.sync_all()
472
                })();
473
                let _ = fs::remove_file(file);
474
                copied?;
475
                self.link_into_place(key, &tmp, &path)
476
            }
477
        }
478
    }
479
480
    fn has(&self, key: &str) -> Result<bool> {
481
        Ok(self.path(key)?.is_file())
482
    }
483
484
    fn get(&self, key: &str) -> Result<Vec<u8>> {
485
        let path = self.path(key)?;
486
        match fs::read(&path) {
487
            Ok(b) => Ok(b),
488
            Err(e) if e.kind() == io::ErrorKind::NotFound => Err(Error::NotFound(key.to_string())),
489
            Err(e) => Err(e.into()),
490
        }
491
    }
492
493
    fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>> {
494
        let path = self.path(key)?;
495
        let mut f = match fs::File::open(&path) {
496
            Ok(f) => f,
497
            Err(e) if e.kind() == io::ErrorKind::NotFound => {
498
                return Err(Error::NotFound(key.to_string()))
499
            }
500
            Err(e) => return Err(e.into()),
501
        };
502
        let len = f.metadata()?.len();
503
        if range.end > len || range.start > range.end {
504
            return Err(Error::Backend(format!(
505
                "{key}: bytes {}..{} asked of an object of {len} bytes",
506
                range.start, range.end
507
            )));
508
        }
509
        f.seek(SeekFrom::Start(range.start))?;
510
        let mut out = vec![0u8; (range.end - range.start) as usize];
511
        f.read_exact(&mut out)?;
512
        Ok(out)
513
    }
514
515
    fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()> {
516
        let path = self.path(key)?;
517
        if path.exists() {
518
            return Err(Error::Exists(key.to_string()));
519
        }
520
        self.ensure_dir(&path)?;
521
        // Written beside its name, then linked into it: the link fails if
522
        // the name was taken meanwhile, and a reader never sees a part.
523
        let tmp = self.temp_beside(&path);
524
        let written = (|| {
525
            let mut f = fs::File::create(&tmp)?;
526
            f.write_all(bytes)?;
527
            f.sync_all()
528
        })();
529
        if let Err(e) = written {
530
            let _ = fs::remove_file(&tmp);
531
            return Err(e.into());
532
        }
533
        self.link_into_place(key, &tmp, &path)
534
    }
535
536
    fn list(&self, prefix: &str) -> Result<Vec<Entry>> {
537
        let mut out = Vec::new();
538
        self.list_dir(&self.root, "", prefix, &mut out)?;
539
        out.sort_by(|a, b| a.key.cmp(&b.key));
540
        Ok(out)
541
    }
542
543
    fn delete(&self, key: &str) -> Result<()> {
544
        let path = self.path(key)?;
545
        match fs::remove_file(&path) {
546
            Ok(()) => {}
547
            Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
548
            Err(e) => return Err(e.into()),
549
        }
550
        // A directory left empty goes too, up to the root, so the store
551
        // holds nothing but its objects.
552
        let mut dir = path.parent();
553
        while let Some(d) = dir {
554
            if d == self.root || fs::remove_dir(d).is_err() {
555
                break;
556
            }
557
            dir = d.parent();
558
        }
559
        Ok(())
560
    }
561
562
    fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> {
563
        let path = self.path(key)?;
564
        match fs::read(&path) {
565
            Ok(b) => {
566
                let v = content_version(&b);
567
                Ok(Some((b, v)))
568
            }
569
            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
570
            Err(e) => Err(e.into()),
571
        }
572
    }
573
574
    fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> {
575
        let path = self.path(key)?;
576
        if let Some(dir) = path.parent() {
577
            fs::create_dir_all(dir)?;
578
        }
579
        let lock = self.lock(key, &path)?;
580
        let result = (|| {
581
            let current = self.read_ref(key)?.map(|(_, v)| v);
582
            check_expected(key, current.as_ref(), expected)?;
583
            crate::durable::write_atomic(&path, bytes)?;
584
            Ok(content_version(bytes))
585
        })();
586
        let _ = fs::remove_file(&lock);
587
        result
588
    }
589
}
590
591
// ---------------------------------------------------------------- memory
592
593
/// A store in memory, for tests: the conditional writes behave as the
594
/// cloud stores' do.
595
#[derive(Default)]
596
pub struct MemoryStore {
597
    objects: Mutex<BTreeMap<String, (Vec<u8>, u64)>>,
598
}
599
600
fn now_ms() -> u64 {
601
    std::time::SystemTime::now()
602
        .duration_since(std::time::UNIX_EPOCH)
603
        .map(|d| d.as_millis() as u64)
604
        .unwrap_or(0)
605
}
606
607
impl MemoryStore {
608
    pub fn new() -> MemoryStore {
609
        MemoryStore::default()
610
    }
611
612
    fn map(&self) -> std::sync::MutexGuard<'_, BTreeMap<String, (Vec<u8>, u64)>> {
613
        self.objects.lock().unwrap_or_else(|p| p.into_inner())
614
    }
615
616
    /// Pretend `key` was written `age` ago (for grace-period tests).
617
    pub fn age(&self, key: &str, age: Duration) {
618
        if let Some(entry) = self.map().get_mut(key) {
619
            entry.1 = now_ms().saturating_sub(age.as_millis() as u64);
620
        }
621
    }
622
}
623
624
impl Store for MemoryStore {
625
    fn describe(&self) -> String {
626
        "memory".into()
627
    }
628
629
    fn has(&self, key: &str) -> Result<bool> {
630
        check_key(key)?;
631
        Ok(self.map().contains_key(key))
632
    }
633
634
    fn get(&self, key: &str) -> Result<Vec<u8>> {
635
        check_key(key)?;
636
        self.map()
637
            .get(key)
638
            .map(|(b, _)| b.clone())
639
            .ok_or_else(|| Error::NotFound(key.to_string()))
640
    }
641
642
    fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>> {
643
        let all = self.get(key)?;
644
        let len = all.len() as u64;
645
        if range.end > len || range.start > range.end {
646
            return Err(Error::Backend(format!(
647
                "{key}: bytes {}..{} asked of an object of {len} bytes",
648
                range.start, range.end
649
            )));
650
        }
651
        Ok(all[range.start as usize..range.end as usize].to_vec())
652
    }
653
654
    fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()> {
655
        check_key(key)?;
656
        let mut map = self.map();
657
        if map.contains_key(key) {
658
            return Err(Error::Exists(key.to_string()));
659
        }
660
        map.insert(key.to_string(), (bytes.to_vec(), now_ms()));
661
        Ok(())
662
    }
663
664
    fn list(&self, prefix: &str) -> Result<Vec<Entry>> {
665
        Ok(self
666
            .map()
667
            .range(prefix.to_string()..)
668
            .take_while(|(k, _)| k.starts_with(prefix))
669
            .map(|(k, (v, t))| Entry {
670
                key: k.clone(),
671
                size: v.len() as u64,
672
                modified_ms: Some(*t),
673
            })
674
            .collect())
675
    }
676
677
    fn delete(&self, key: &str) -> Result<()> {
678
        check_key(key)?;
679
        self.map().remove(key);
680
        Ok(())
681
    }
682
683
    fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> {
684
        check_key(key)?;
685
        Ok(self
686
            .map()
687
            .get(key)
688
            .map(|(b, _)| (b.clone(), content_version(b))))
689
    }
690
691
    fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> {
692
        check_key(key)?;
693
        let mut map = self.map();
694
        let current = map.get(key).map(|(b, _)| content_version(b));
695
        check_expected(key, current.as_ref(), expected)?;
696
        map.insert(key.to_string(), (bytes.to_vec(), now_ms()));
697
        Ok(content_version(bytes))
698
    }
699
}
700
701
// ---------------------------------------------------------------- caching
702
703
/// A store in front of another (oxygen#68): objects are read through a
704
/// local directory and written through it, to the remote first, so the
705
/// remote always holds everything and the cache can be dropped at any
706
/// time. Objects never change, so a cached one is always right (and every
707
/// read is hashed again above this layer). The cache is bounded: past its
708
/// limit the objects used least recently are removed. An object larger
709
/// than an eighth of the limit is not cached; it is read by range from
710
/// the remote. References are never cached: they are read from and
711
/// written to the remote every time, so compare-and-swap is the remote's.
712
pub struct CachingStore {
713
    cache: LocalStore,
714
    remote: std::sync::Arc<dyn Store>,
715
    limit: u64,
716
    /// Bytes in the cache, counted on first need and kept up to date.
717
    used: Mutex<Option<u64>>,
718
}
719
720
/// Where a caching store keeps the ranges it read of objects too large to
721
/// keep whole, and those objects' sizes: apart from every object key.
722
const RANGES: &str = "cached-range";
723
const SIZES: &str = "cached-size";
724
725
/// How stale a cached object's use time may get before a read renews it.
726
const TOUCH_AFTER: Duration = Duration::from_secs(60);
727
728
impl CachingStore {
729
    /// `remote` behind a cache in the directory `dir` of at most `limit`
730
    /// bytes.
731
    pub fn open(
732
        remote: std::sync::Arc<dyn Store>,
733
        dir: impl Into<PathBuf>,
734
        limit: u64,
735
    ) -> Result<CachingStore> {
736
        Ok(CachingStore {
737
            cache: LocalStore::open(dir)?,
738
            remote,
739
            limit,
740
            used: Mutex::new(None),
741
        })
742
    }
743
744
    pub fn remote(&self) -> &std::sync::Arc<dyn Store> {
745
        &self.remote
746
    }
747
748
    /// Bytes the cache holds now.
749
    pub fn cached_bytes(&self) -> Result<u64> {
750
        let mut used = self.used.lock().unwrap_or_else(|p| p.into_inner());
751
        if used.is_none() {
752
            *used = Some(self.cache.list("")?.iter().map(|e| e.size).sum());
753
        }
754
        Ok(used.unwrap_or(0))
755
    }
756
757
    /// Whether an object of `size` bytes is kept in the cache at all.
758
    fn cacheable(&self, size: u64) -> bool {
759
        size <= self.limit / 8
760
    }
761
762
    /// Keep a copy of an object the remote holds.
763
    fn keep(&self, key: &str, bytes: &[u8]) -> Result<()> {
764
        if !self.cacheable(bytes.len() as u64) {
765
            return Ok(());
766
        }
767
        match self.cache.put_new(key, bytes) {
768
            Ok(()) => self.added(bytes.len() as u64),
769
            Err(Error::Exists(_)) => Ok(()),
770
            Err(e) => Err(e),
771
        }
772
    }
773
774
    /// Count `n` new bytes, and remove the least recently used objects
775
    /// once the cache is past its limit, down to nine tenths of it.
776
    fn added(&self, n: u64) -> Result<()> {
777
        let total = {
778
            let mut used = self.used.lock().unwrap_or_else(|p| p.into_inner());
779
            let total = match *used {
780
                Some(u) => u + n,
781
                // Counted now, with the new object already in place.
782
                None => self.cache.list("")?.iter().map(|e| e.size).sum(),
783
            };
784
            *used = Some(total);
785
            total
786
        };
787
        if total <= self.limit {
788
            return Ok(());
789
        }
790
        let mut entries = self.cache.list("")?;
791
        entries.sort_by_key(|e| e.modified_ms.unwrap_or(0));
792
        let mut left: u64 = entries.iter().map(|e| e.size).sum();
793
        let target = self.limit / 10 * 9;
794
        for e in entries {
795
            if left <= target {
796
                break;
797
            }
798
            self.cache.delete(&e.key)?;
799
            left -= e.size;
800
        }
801
        *self.used.lock().unwrap_or_else(|p| p.into_inner()) = Some(left);
802
        Ok(())
803
    }
804
805
    /// An object's size: kept on disk once the remote has said it (objects
806
    /// never change), so it is asked once. `None` when there is no object.
807
    fn size_of(&self, key: &str) -> Result<Option<u64>> {
808
        let skey = format!("{SIZES}/{key}");
809
        if let Some(n) = self
810
            .cache
811
            .get(&skey)
812
            .ok()
813
            .and_then(|b| String::from_utf8(b).ok())
814
            .and_then(|t| t.parse().ok())
815
        {
816
            return Ok(Some(n));
817
        }
818
        let size = self.remote.stat(key)?.map(|e| e.size);
819
        if let Some(n) = size {
820
            self.keep(&skey, n.to_string().as_bytes())?;
821
        }
822
        Ok(size)
823
    }
824
825
    /// Mark a cached object used now, at most once a minute.
826
    fn touch(&self, key: &str) {
827
        let Ok(path) = self.cache.path(key) else {
828
            return;
829
        };
830
        let stale = fs::metadata(&path)
831
            .and_then(|m| m.modified())
832
            .ok()
833
            .and_then(|t| t.elapsed().ok())
834
            .is_some_and(|age| age > TOUCH_AFTER);
835
        if stale {
836
            if let Ok(f) = fs::File::options().append(true).open(&path) {
837
                let _ = f.set_modified(std::time::SystemTime::now());
838
            }
839
        }
840
    }
841
}
842
843
impl Store for CachingStore {
844
    fn describe(&self) -> String {
845
        format!(
846
            "{} (cached in {})",
847
            self.remote.describe(),
848
            self.cache.root().display()
849
        )
850
    }
851
852
    fn has(&self, key: &str) -> Result<bool> {
853
        Ok(self.cache.has(key)? || self.remote.has(key)?)
854
    }
855
856
    fn get(&self, key: &str) -> Result<Vec<u8>> {
857
        match self.cache.get(key) {
858
            Ok(bytes) => {
859
                self.touch(key);
860
                return Ok(bytes);
861
            }
862
            // Not cached, or removed by another process's eviction meanwhile.
863
            Err(Error::NotFound(_)) => {}
864
            Err(e) => return Err(e),
865
        }
866
        let bytes = self.remote.get(key)?;
867
        self.keep(key, &bytes)?;
868
        Ok(bytes)
869
    }
870
871
    fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>> {
872
        match self.cache.get_range(key, range.clone()) {
873
            Ok(bytes) => {
874
                self.touch(key);
875
                return Ok(bytes);
876
            }
877
            Err(Error::NotFound(_)) => {}
878
            Err(e) if self.cache.has(key)? => return Err(e),
879
            Err(_) => {}
880
        }
881
        // A large object's ranges are kept as they are read (packs never
882
        // change, oxygenhub#234): a server opens the store again for every
883
        // request, so only what is on disk carries over.
884
        let rkey = format!("{RANGES}/{key}/{}-{}", range.start, range.end);
885
        if let Ok(bytes) = self.cache.get(&rkey) {
886
            self.touch(&rkey);
887
            return Ok(bytes);
888
        }
889
        // A small object is fetched whole and kept; a large one is read by
890
        // range and the range kept. Its size is kept too, so the remote is
891
        // asked it once.
892
        match self.size_of(key)? {
893
            Some(size) if self.cacheable(size) => {
894
                let bytes = self.get(key)?;
895
                let len = bytes.len() as u64;
896
                if range.end > len || range.start > range.end {
897
                    return Err(Error::Backend(format!(
898
                        "{key}: bytes {}..{} asked of an object of {len} bytes",
899
                        range.start, range.end
900
                    )));
901
                }
902
                Ok(bytes[range.start as usize..range.end as usize].to_vec())
903
            }
904
            Some(_) => {
905
                let bytes = self.remote.get_range(key, range)?;
906
                self.keep(&rkey, &bytes)?;
907
                Ok(bytes)
908
            }
909
            None => Err(Error::NotFound(key.to_string())),
910
        }
911
    }
912
913
    fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()> {
914
        self.remote.put_new(key, bytes)?;
915
        self.keep(key, bytes)
916
    }
917
918
    fn put_many_new(&self, objects: &[(String, Vec<u8>)]) -> Result<()> {
919
        self.remote.put_many_new(objects)?;
920
        for (key, bytes) in objects {
921
            self.keep(key, bytes)?;
922
        }
923
        Ok(())
924
    }
925
926
    fn put_new_file(&self, key: &str, path: &Path) -> Result<()> {
927
        let size = fs::metadata(path)?.len();
928
        let copy = if self.cacheable(size) {
929
            Some(fs::read(path)?)
930
        } else {
931
            None
932
        };
933
        self.remote.put_new_file(key, path)?;
934
        match copy {
935
            Some(bytes) => self.keep(key, &bytes),
936
            None => Ok(()),
937
        }
938
    }
939
940
    fn list(&self, prefix: &str) -> Result<Vec<Entry>> {
941
        self.remote.list(prefix)
942
    }
943
944
    fn stat(&self, key: &str) -> Result<Option<Entry>> {
945
        self.remote.stat(key)
946
    }
947
948
    fn delete(&self, key: &str) -> Result<()> {
949
        self.remote.delete(key)?;
950
        // Its kept ranges and size go with it.
951
        let mut extra = self.cache.list(&format!("{RANGES}/{key}/"))?;
952
        extra.extend(self.cache.stat(&format!("{SIZES}/{key}"))?);
953
        for e in extra {
954
            self.cache.delete(&e.key)?;
955
            let mut used = self.used.lock().unwrap_or_else(|p| p.into_inner());
956
            if let Some(u) = used.as_mut() {
957
                *u = u.saturating_sub(e.size);
958
            }
959
        }
960
        let size = self.cache.stat(key)?.map(|e| e.size);
961
        self.cache.delete(key)?;
962
        if let Some(n) = size {
963
            let mut used = self.used.lock().unwrap_or_else(|p| p.into_inner());
964
            if let Some(u) = used.as_mut() {
965
                *u = u.saturating_sub(n);
966
            }
967
        }
968
        Ok(())
969
    }
970
971
    fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> {
972
        self.remote.read_ref(key)
973
    }
974
975
    fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> {
976
        self.remote.write_ref(key, bytes, expected)
977
    }
978
}
979
980
// ---------------------------------------------------------------- conformance
981
982
/// Exercise a store under `prefix` (which must be free, and is left
983
/// empty) and report what passed: object round trips, ranges, create-only
984
/// refusal, listing, deletion, and compare-and-swap on a reference. Every
985
/// store runs this in its tests, and `oxy remote check` runs it against a
986
/// remote before trusting it with a repository.
987
pub fn conformance(store: &dyn Store, prefix: &str) -> Result<Vec<&'static str>> {
988
    let mut passed = Vec::new();
989
    let key = |name: &str| format!("{prefix}/{name}");
990
    let fail = |what: &str| Error::Backend(format!("{}: {what}", store.describe()));
991
    let expect = |ok: bool, what: &str| if ok { Ok(()) } else { Err(fail(what)) };
992
993
    expect(
994
        store.list(prefix)?.is_empty(),
995
        "the probe prefix is not empty",
996
    )?;
997
    expect(
998
        !store.has(&key("a"))?,
999
        "has() of a missing object says true",
1000
    )?;
1001
    expect(
1002
        matches!(store.get(&key("a")), Err(Error::NotFound(_))),
1003
        "get() of a missing object is not NotFound",
1004
    )?;
1005
    passed.push("missing objects are reported missing");
1006
1007
    let a: Vec<u8> = (0..256u32 * 1024).map(|i| (i % 251) as u8).collect();
1008
    store.put_new(&key("a"), &a)?;
1009
    expect(store.has(&key("a"))?, "has() after put_new says false")?;
1010
    expect(
1011
        store.get(&key("a"))? == a,
1012
        "get() returns other bytes than put_new wrote",
1013
    )?;
1014
    passed.push("an object round-trips");
1015
1016
    expect(
1017
        store.get_range(&key("a"), 1000..1500)? == a[1000..1500],
1018
        "get_range() returns the wrong bytes",
1019
    )?;
1020
    expect(
1021
        store.get_range(&key("a"), 0..0)?.is_empty(),
1022
        "an empty range is not empty",
1023
    )?;
1024
    expect(
1025
        store.get_range(&key("a"), 0..a.len() as u64 + 1).is_err(),
1026
        "a range past the end is not refused",
1027
    )?;
1028
    passed.push("ranges read correctly and are bounded");
1029
1030
    expect(
1031
        matches!(store.put_new(&key("a"), b"other"), Err(Error::Exists(_))),
1032
        "put_new() over an existing object is not refused",
1033
    )?;
1034
    expect(
1035
        store.get(&key("a"))? == a,
1036
        "a refused put_new() changed the object",
1037
    )?;
1038
    passed.push("objects are written once");
1039
1040
    store.put_new(&key("dir/b"), b"bb")?;
1041
    let listed: Vec<(String, u64)> = store
1042
        .list(prefix)?
1043
        .into_iter()
1044
        .map(|e| (e.key, e.size))
1045
        .collect();
1046
    expect(
1047
        listed == vec![(key("a"), a.len() as u64), (key("dir/b"), 2)],
1048
        "list() does not return the two objects, sorted, with their sizes",
1049
    )?;
1050
    expect(
1051
        store
1052
            .stat(&key("dir/b"))?
1053
            .is_some_and(|e| e.key == key("dir/b") && e.size == 2)
1054
            && store.stat(&key("dir/c"))?.is_none(),
1055
        "stat() does not describe one object, or describes a missing one",
1056
    )?;
1057
    expect(
1058
        store
1059
            .list(&key("dir/"))?
1060
            .into_iter()
1061
            .map(|e| (e.key, e.size))
1062
            .collect::<Vec<_>>()
1063
            == vec![(key("dir/b"), 2)],
1064
        "list() of a sub-prefix is wrong",
1065
    )?;
1066
    expect(
1067
        store.list(&key("nothing/"))?.is_empty(),
1068
        "list() of an unused prefix is not empty",
1069
    )?;
1070
    passed.push("listing by prefix");
1071
1072
    store.delete(&key("dir/b"))?;
1073
    expect(
1074
        !store.has(&key("dir/b"))?,
1075
        "an object is still there after delete()",
1076
    )?;
1077
    store.delete(&key("dir/b"))?;
1078
    passed.push("deletion, and deleting again, succeed");
1079
1080
    let r = key("refs");
1081
    expect(
1082
        store.read_ref(&r)?.is_none(),
1083
        "an unwritten reference reads as something",
1084
    )?;
1085
    let v1 = store.write_ref(&r, b"one", None)?;
1086
    expect(
1087
        matches!(store.write_ref(&r, b"again", None), Err(Error::Conflict(_))),
1088
        "a second create-only write of the reference is not refused",
1089
    )?;
1090
    let (bytes, seen) = store
1091
        .read_ref(&r)?
1092
        .ok_or_else(|| fail("the reference vanished"))?;
1093
    expect(
1094
        bytes == b"one" && seen == v1,
1095
        "the reference reads back wrong",
1096
    )?;
1097
    let v2 = store.write_ref(&r, b"two", Some(&v1))?;
1098
    expect(v2 != v1, "the version did not change on write")?;
1099
    expect(
1100
        matches!(
1101
            store.write_ref(&r, b"three", Some(&v1)),
1102
            Err(Error::Conflict(_))
1103
        ),
1104
        "a write with a stale version is not refused",
1105
    )?;
1106
    let (bytes, seen) = store
1107
        .read_ref(&r)?
1108
        .ok_or_else(|| fail("the reference vanished"))?;
1109
    expect(
1110
        bytes == b"two" && seen == v2,
1111
        "a refused write changed the reference",
1112
    )?;
1113
    passed.push("references update by compare-and-swap");
1114
1115
    store.delete(&key("a"))?;
1116
    store.delete(&r)?;
1117
    expect(
1118
        store.list(prefix)?.is_empty(),
1119
        "the probe prefix is not empty after cleanup",
1120
    )?;
1121
    passed.push("cleanup");
1122
    Ok(passed)
1123
}
1124
1125
#[cfg(test)]
1126
mod tests {
1127
    use super::*;
1128
    use std::sync::Arc;
1129
1130
    /// Where hard links are refused (Android, oxygen#141), objects are
1131
    /// renamed into place, still never over a name that is taken.
1132
    #[test]
1133
    fn a_create_only_rename_never_replaces() {
1134
        let dir = tempfile::tempdir().unwrap();
1135
        let (a, b, to) = (
1136
            dir.path().join("a"),
1137
            dir.path().join("b"),
1138
            dir.path().join("to"),
1139
        );
1140
        fs::write(&a, b"first").unwrap();
1141
        fs::write(&b, b"second").unwrap();
1142
        rename_new(&a, &to).unwrap();
1143
        assert_eq!(
1144
            rename_new(&b, &to).unwrap_err().kind(),
1145
            io::ErrorKind::AlreadyExists
1146
        );
1147
        assert_eq!(fs::read(&to).unwrap(), b"first");
1148
        assert!(!a.exists() && b.exists());
1149
    }
1150
1151
    #[test]
1152
    fn keys_are_plain_relative_paths() {
1153
        for ok in ["a", "packs/ab.pack", "a-b_c.d/e"] {
1154
            check_key(ok).unwrap();
1155
        }
1156
        for bad in [
1157
            "", "/a", "a/", "a//b", "..", "a/../b", "./a", "a b", "a\\b", "ä",
1158
        ] {
1159
            assert!(check_key(bad).is_err(), "{bad:?}");
1160
        }
1161
        assert!(check_key(&"x".repeat(MAX_KEY_LEN + 1)).is_err());
1162
    }
1163
1164
    #[test]
1165
    fn a_caching_store_conforms_and_reads_and_writes_through() {
1166
        let dir = tempfile::tempdir().unwrap();
1167
        let remote: Arc<dyn Store> = Arc::new(MemoryStore::new());
1168
        let store = CachingStore::open(remote.clone(), dir.path().join("cache"), 8 << 20).unwrap();
1169
        assert_eq!(conformance(&store, "probe").unwrap().len(), 8);
1170
        assert_eq!(
1171
            store.cached_bytes().unwrap(),
1172
            0,
1173
            "the probe left nothing cached"
1174
        );
1175
1176
        // Written through: the remote has it, and so does the cache.
1177
        store.put_new("loose/aa", b"written").unwrap();
1178
        assert_eq!(remote.get("loose/aa").unwrap(), b"written");
1179
        assert!(store.cache.has("loose/aa").unwrap());
1180
        // Read through: an object only the remote has is kept on first read.
1181
        remote.put_new("loose/bb", b"remote only").unwrap();
1182
        assert!(!store.cache.has("loose/bb").unwrap());
1183
        assert_eq!(store.get_range("loose/bb", 0..6).unwrap(), b"remote");
1184
        assert!(store.cache.has("loose/bb").unwrap());
1185
        // A cached object read after the remote lost it is still served.
1186
        remote.delete("loose/bb").unwrap();
1187
        assert_eq!(store.get("loose/bb").unwrap(), b"remote only");
1188
        // References are always the remote's.
1189
        let v = remote.write_ref("refs", b"one", None).unwrap();
1190
        assert_eq!(
1191
            store.read_ref("refs").unwrap(),
1192
            Some((b"one".to_vec(), v.clone()))
1193
        );
1194
        remote.write_ref("refs", b"two", Some(&v)).unwrap();
1195
        assert_eq!(store.read_ref("refs").unwrap().unwrap().0, b"two");
1196
        assert!(matches!(
1197
            store.write_ref("refs", b"three", Some(&v)),
1198
            Err(Error::Conflict(_))
1199
        ));
1200
        assert!(!store.cache.has("refs").unwrap());
1201
    }
1202
1203
    /// A remote that answers nothing: what is read through it was cached.
1204
    struct Unreachable;
1205
1206
    impl Store for Unreachable {
1207
        fn describe(&self) -> String {
1208
            "unreachable".into()
1209
        }
1210
        fn has(&self, _: &str) -> Result<bool> {
1211
            Err(Error::Backend("asked the remote".into()))
1212
        }
1213
        fn get(&self, _: &str) -> Result<Vec<u8>> {
1214
            Err(Error::Backend("asked the remote".into()))
1215
        }
1216
        fn get_range(&self, _: &str, _: Range<u64>) -> Result<Vec<u8>> {
1217
            Err(Error::Backend("asked the remote".into()))
1218
        }
1219
        fn put_new(&self, _: &str, _: &[u8]) -> Result<()> {
1220
            Err(Error::Backend("asked the remote".into()))
1221
        }
1222
        fn list(&self, _: &str) -> Result<Vec<Entry>> {
1223
            Err(Error::Backend("asked the remote".into()))
1224
        }
1225
        fn delete(&self, _: &str) -> Result<()> {
1226
            Err(Error::Backend("asked the remote".into()))
1227
        }
1228
        fn stat(&self, _: &str) -> Result<Option<Entry>> {
1229
            Err(Error::Backend("asked the remote".into()))
1230
        }
1231
        fn read_ref(&self, _: &str) -> Result<Option<(Vec<u8>, Version)>> {
1232
            Err(Error::Backend("asked the remote".into()))
1233
        }
1234
        fn write_ref(&self, _: &str, _: &[u8], _: Option<&Version>) -> Result<Version> {
1235
            Err(Error::Backend("asked the remote".into()))
1236
        }
1237
    }
1238
1239
    #[test]
1240
    fn a_caching_store_stays_within_its_limit() {
1241
        let dir = tempfile::tempdir().unwrap();
1242
        let remote: Arc<dyn Store> = Arc::new(MemoryStore::new());
1243
        let store = CachingStore::open(remote.clone(), dir.path().join("cache"), 8000).unwrap();
1244
        for i in 0..20 {
1245
            store
1246
                .put_new(&format!("loose/{i:02}"), &[i as u8; 900])
1247
                .unwrap();
1248
            assert!(store.cached_bytes().unwrap() <= 8000);
1249
        }
1250
        assert_eq!(
1251
            remote.list("loose/").unwrap().len(),
1252
            20,
1253
            "the remote holds everything"
1254
        );
1255
        let cached = store.cache.list("loose/").unwrap();
1256
        assert!(cached.len() < 20 && cached.len() >= 7, "{}", cached.len());
1257
        assert!(
1258
            cached.iter().any(|e| e.key == "loose/19"),
1259
            "the newest is kept"
1260
        );
1261
        for i in 0..20 {
1262
            assert_eq!(
1263
                store.get(&format!("loose/{i:02}")).unwrap(),
1264
                vec![i as u8; 900]
1265
            );
1266
        }
1267
        // An object over an eighth of the limit is read by range, not kept.
1268
        remote.put_new("pack-big", &[7u8; 2000]).unwrap();
1269
        assert_eq!(store.get_range("pack-big", 10..20).unwrap(), vec![7u8; 10]);
1270
        assert_eq!(store.get("pack-big").unwrap().len(), 2000);
1271
        assert!(!store.cache.has("pack-big").unwrap());
1272
        // Its ranges are kept as read, and its size, so a store opened
1273
        // again (a server's next request) asks the remote nothing.
1274
        let again =
1275
            CachingStore::open(Arc::new(Unreachable), dir.path().join("cache"), 8000).unwrap();
1276
        assert_eq!(again.get_range("pack-big", 10..20).unwrap(), vec![7u8; 10]);
1277
        // Counting from scratch agrees with what was kept track of.
1278
        let fresh = CachingStore::open(remote, dir.path().join("cache"), 8000).unwrap();
1279
        assert_eq!(fresh.cached_bytes().unwrap(), store.cached_bytes().unwrap());
1280
        // Deleting it takes its ranges and size too.
1281
        store.delete("pack-big").unwrap();
1282
        assert!(
1283
            store.cache.list("cached-range/").unwrap().is_empty()
1284
                && store.cache.list("cached-size/").unwrap().is_empty()
1285
        );
1286
    }
1287
1288
    #[test]
1289
    fn the_memory_store_conforms() {
1290
        let store = MemoryStore::new();
1291
        let passed = conformance(&store, "probe").unwrap();
1292
        assert_eq!(passed.len(), 8, "{passed:?}");
1293
    }
1294
1295
    #[test]
1296
    fn the_directory_store_conforms() {
1297
        let dir = tempfile::tempdir().unwrap();
1298
        let store = LocalStore::open(dir.path().join("bucket")).unwrap();
1299
        let passed = conformance(&store, "repos/one").unwrap();
1300
        assert_eq!(passed.len(), 8, "{passed:?}");
1301
        // Nothing but the (empty) directories and no stray temporaries.
1302
        let stray: Vec<_> = walkdir(dir.path())
1303
            .into_iter()
1304
            .filter(|p| p.is_file())
1305
            .collect();
1306
        assert!(stray.is_empty(), "{stray:?}");
1307
        assert_eq!(
1308
            fs::read_dir(dir.path().join("bucket")).unwrap().count(),
1309
            0,
1310
            "no empty directories left"
1311
        );
1312
    }
1313
1314
    fn walkdir(dir: &Path) -> Vec<PathBuf> {
1315
        let mut out = vec![];
1316
        if let Ok(rd) = fs::read_dir(dir) {
1317
            for e in rd.flatten() {
1318
                let p = e.path();
1319
                if p.is_dir() {
1320
                    out.extend(walkdir(&p));
1321
                } else {
1322
                    out.push(p);
1323
                }
1324
            }
1325
        }
1326
        out
1327
    }
1328
1329
    #[test]
1330
    fn a_directory_store_refuses_keys_that_leave_its_root() {
1331
        let dir = tempfile::tempdir().unwrap();
1332
        let store = LocalStore::open(dir.path().join("bucket")).unwrap();
1333
        assert!(matches!(
1334
            store.put_new("../escape", b"x"),
1335
            Err(Error::Key(..))
1336
        ));
1337
        assert!(matches!(store.get("/etc/passwd"), Err(Error::Key(..))));
1338
        assert!(!dir.path().join("escape").exists());
1339
    }
1340
1341
    /// Many threads race to move a reference from the same version: exactly
1342
    /// one wins each round, on both stores.
1343
    #[test]
1344
    fn compare_and_swap_admits_one_writer_per_round() {
1345
        let dir = tempfile::tempdir().unwrap();
1346
        let local: Arc<dyn Store> = Arc::new(LocalStore::open(dir.path()).unwrap());
1347
        let memory: Arc<dyn Store> = Arc::new(MemoryStore::new());
1348
        for store in [local, memory] {
1349
            let v0 = store.write_ref("refs", b"0", None).unwrap();
1350
            let wins: Vec<bool> = (0..8)
1351
                .map(|i| {
1352
                    let store = store.clone();
1353
                    let v0 = v0.clone();
1354
                    std::thread::spawn(move || {
1355
                        store
1356
                            .write_ref("refs", format!("{}", i + 1).as_bytes(), Some(&v0))
1357
                            .is_ok()
1358
                    })
1359
                })
1360
                .collect::<Vec<_>>()
1361
                .into_iter()
1362
                .map(|h| h.join().unwrap())
1363
                .collect();
1364
            assert_eq!(
1365
                wins.iter().filter(|w| **w).count(),
1366
                1,
1367
                "{}: {wins:?}",
1368
                store.describe()
1369
            );
1370
            let (bytes, _) = store.read_ref("refs").unwrap().unwrap();
1371
            assert_ne!(bytes, b"0");
1372
        }
1373
    }
1374
1375
    #[test]
1376
    fn a_stale_lock_is_broken_and_a_live_one_waited_for() {
1377
        let dir = tempfile::tempdir().unwrap();
1378
        let store = LocalStore::open(dir.path()).unwrap();
1379
        let lock = dir.path().join(".refs.lock");
1380
        fs::write(&lock, "dead").unwrap();
1381
        let old = std::time::SystemTime::now() - LOCK_STALE - Duration::from_secs(5);
1382
        fs::File::open(&lock).unwrap().set_modified(old).unwrap();
1383
        store.write_ref("refs", b"after a crash", None).unwrap();
1384
        assert!(!lock.exists());
1385
    }
1386
1387
    #[test]
1388
    fn temporaries_and_locks_are_not_listed() {
1389
        let dir = tempfile::tempdir().unwrap();
1390
        let store = LocalStore::open(dir.path()).unwrap();
1391
        store.put_new("packs/a", b"a").unwrap();
1392
        fs::write(dir.path().join("packs/.a.tmp-ffffff"), "junk").unwrap();
1393
        fs::write(dir.path().join(".refs.lock"), "1").unwrap();
1394
        let keys: Vec<String> = store.list("").unwrap().into_iter().map(|e| e.key).collect();
1395
        assert_eq!(keys, ["packs/a"]);
1396
    }
1397
}