OXYGENHUB
◆ show-stat oxygen / crates / oxy-core / src / strata.rs
47.1 KiB · Rust · last changed Caching store: keep the ranges read of large objects, and their sizes 19 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
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.
300
    fn link_into_place(&self, key: &str, tmp: &Path, path: &Path) -> Result<()> {
301
        let linked = fs::hard_link(tmp, path);
302
        let _ = fs::remove_file(tmp);
303
        match linked {
304
            Ok(()) => {
305
                if let Some(dir) = path.parent() {
306
                    crate::durable::sync_dir(dir)?;
307
                }
308
                Ok(())
309
            }
310
            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
311
                Err(Error::Exists(key.to_string()))
312
            }
313
            Err(e) => Err(e.into()),
314
        }
315
    }
316
317
    /// Create `path`'s directory, syncing the first directory that was
318
    /// made so its entry is durable too.
319
    fn ensure_dir(&self, path: &Path) -> Result<()> {
320
        let Some(dir) = path.parent() else {
321
            return Ok(());
322
        };
323
        if dir.is_dir() {
324
            return Ok(());
325
        }
326
        let mut made = dir.to_path_buf();
327
        while let Some(parent) = made.parent() {
328
            if parent.is_dir() || parent == self.root {
329
                break;
330
            }
331
            made = parent.to_path_buf();
332
        }
333
        fs::create_dir_all(dir)?;
334
        if let Some(parent) = made.parent() {
335
            crate::durable::sync_dir(parent)?;
336
        }
337
        Ok(())
338
    }
339
}
340
341
impl Store for LocalStore {
342
    fn describe(&self) -> String {
343
        self.root.display().to_string()
344
    }
345
346
    fn stat(&self, key: &str) -> Result<Option<Entry>> {
347
        match fs::metadata(self.path(key)?) {
348
            Ok(m) if m.is_file() => Ok(Some(Entry {
349
                key: key.to_string(),
350
                size: m.len(),
351
                modified_ms: modified_ms(&m),
352
            })),
353
            Ok(_) => Ok(None),
354
            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
355
            Err(e) => Err(e.into()),
356
        }
357
    }
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.
362
    fn put_many_new(&self, objects: &[(String, Vec<u8>)]) -> Result<()> {
363
        use rayon::prelude::*;
364
        let mut todo: Vec<(PathBuf, PathBuf, &[u8])> = Vec::new();
365
        for (key, bytes) in objects {
366
            let path = self.path(key)?;
367
            if path.exists() || todo.iter().any(|(p, ..)| *p == path) {
368
                continue;
369
            }
370
            self.ensure_dir(&path)?;
371
            todo.push((path.clone(), self.temp_beside(&path), bytes));
372
        }
373
        if todo.is_empty() {
374
            return Ok(());
375
        }
376
        crate::durable::step("write loose objects")?;
377
        todo.par_iter()
378
            .try_for_each(|(_, tmp, bytes)| -> io::Result<()> {
379
                let mut f = fs::File::create(tmp)?;
380
                f.write_all(bytes)?;
381
                f.sync_all()
382
            })?;
383
        crate::durable::step("rename loose objects")?;
384
        let mut dirs: std::collections::BTreeSet<PathBuf> = std::collections::BTreeSet::new();
385
        for (path, tmp, _) in &todo {
386
            let linked = fs::hard_link(tmp, path);
387
            let _ = fs::remove_file(tmp);
388
            match linked {
389
                Ok(()) => {
390
                    if let Some(d) = path.parent() {
391
                        dirs.insert(d.to_path_buf());
392
                    }
393
                }
394
                Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
395
                Err(e) => return Err(e.into()),
396
            }
397
        }
398
        dirs.par_iter()
399
            .try_for_each(|d| crate::durable::sync_dir(d))?;
400
        Ok(())
401
    }
402
403
    /// The file is linked into place when it is on this file system,
404
    /// else copied; it is removed either way.
405
    fn put_new_file(&self, key: &str, file: &Path) -> Result<()> {
406
        let path = self.path(key)?;
407
        if path.exists() {
408
            let _ = fs::remove_file(file);
409
            return Err(Error::Exists(key.to_string()));
410
        }
411
        self.ensure_dir(&path)?;
412
        match fs::hard_link(file, &path) {
413
            Ok(()) => {
414
                let _ = fs::remove_file(file);
415
                if let Some(dir) = path.parent() {
416
                    crate::durable::sync_dir(dir)?;
417
                }
418
                Ok(())
419
            }
420
            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
421
                let _ = fs::remove_file(file);
422
                Err(Error::Exists(key.to_string()))
423
            }
424
            Err(_) => {
425
                // Another file system: copy beside the name, then link.
426
                let tmp = self.temp_beside(&path);
427
                let copied = (|| {
428
                    let mut src = fs::File::open(file)?;
429
                    let mut dst = fs::File::create(&tmp)?;
430
                    io::copy(&mut src, &mut dst)?;
431
                    dst.sync_all()
432
                })();
433
                let _ = fs::remove_file(file);
434
                copied?;
435
                self.link_into_place(key, &tmp, &path)
436
            }
437
        }
438
    }
439
440
    fn has(&self, key: &str) -> Result<bool> {
441
        Ok(self.path(key)?.is_file())
442
    }
443
444
    fn get(&self, key: &str) -> Result<Vec<u8>> {
445
        let path = self.path(key)?;
446
        match fs::read(&path) {
447
            Ok(b) => Ok(b),
448
            Err(e) if e.kind() == io::ErrorKind::NotFound => Err(Error::NotFound(key.to_string())),
449
            Err(e) => Err(e.into()),
450
        }
451
    }
452
453
    fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>> {
454
        let path = self.path(key)?;
455
        let mut f = match fs::File::open(&path) {
456
            Ok(f) => f,
457
            Err(e) if e.kind() == io::ErrorKind::NotFound => {
458
                return Err(Error::NotFound(key.to_string()))
459
            }
460
            Err(e) => return Err(e.into()),
461
        };
462
        let len = f.metadata()?.len();
463
        if range.end > len || range.start > range.end {
464
            return Err(Error::Backend(format!(
465
                "{key}: bytes {}..{} asked of an object of {len} bytes",
466
                range.start, range.end
467
            )));
468
        }
469
        f.seek(SeekFrom::Start(range.start))?;
470
        let mut out = vec![0u8; (range.end - range.start) as usize];
471
        f.read_exact(&mut out)?;
472
        Ok(out)
473
    }
474
475
    fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()> {
476
        let path = self.path(key)?;
477
        if path.exists() {
478
            return Err(Error::Exists(key.to_string()));
479
        }
480
        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.
483
        let tmp = self.temp_beside(&path);
484
        let written = (|| {
485
            let mut f = fs::File::create(&tmp)?;
486
            f.write_all(bytes)?;
487
            f.sync_all()
488
        })();
489
        if let Err(e) = written {
490
            let _ = fs::remove_file(&tmp);
491
            return Err(e.into());
492
        }
493
        self.link_into_place(key, &tmp, &path)
494
    }
495
496
    fn list(&self, prefix: &str) -> Result<Vec<Entry>> {
497
        let mut out = Vec::new();
498
        self.list_dir(&self.root, "", prefix, &mut out)?;
499
        out.sort_by(|a, b| a.key.cmp(&b.key));
500
        Ok(out)
501
    }
502
503
    fn delete(&self, key: &str) -> Result<()> {
504
        let path = self.path(key)?;
505
        match fs::remove_file(&path) {
506
            Ok(()) => {}
507
            Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
508
            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.
512
        let mut dir = path.parent();
513
        while let Some(d) = dir {
514
            if d == self.root || fs::remove_dir(d).is_err() {
515
                break;
516
            }
517
            dir = d.parent();
518
        }
519
        Ok(())
520
    }
521
522
    fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> {
523
        let path = self.path(key)?;
524
        match fs::read(&path) {
525
            Ok(b) => {
526
                let v = content_version(&b);
527
                Ok(Some((b, v)))
528
            }
529
            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
530
            Err(e) => Err(e.into()),
531
        }
532
    }
533
534
    fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> {
535
        let path = self.path(key)?;
536
        if let Some(dir) = path.parent() {
537
            fs::create_dir_all(dir)?;
538
        }
539
        let lock = self.lock(key, &path)?;
540
        let result = (|| {
541
            let current = self.read_ref(key)?.map(|(_, v)| v);
542
            check_expected(key, current.as_ref(), expected)?;
543
            crate::durable::write_atomic(&path, bytes)?;
544
            Ok(content_version(bytes))
545
        })();
546
        let _ = fs::remove_file(&lock);
547
        result
548
    }
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
560
fn now_ms() -> u64 {
561
    std::time::SystemTime::now()
562
        .duration_since(std::time::UNIX_EPOCH)
563
        .map(|d| d.as_millis() as u64)
564
        .unwrap_or(0)
565
}
566
567
impl MemoryStore {
568
    pub fn new() -> MemoryStore {
569
        MemoryStore::default()
570
    }
571
572
    fn map(&self) -> std::sync::MutexGuard<'_, BTreeMap<String, (Vec<u8>, u64)>> {
573
        self.objects.lock().unwrap_or_else(|p| p.into_inner())
574
    }
575
576
    /// Pretend `key` was written `age` ago (for grace-period tests).
577
    pub fn age(&self, key: &str, age: Duration) {
578
        if let Some(entry) = self.map().get_mut(key) {
579
            entry.1 = now_ms().saturating_sub(age.as_millis() as u64);
580
        }
581
    }
582
}
583
584
impl Store for MemoryStore {
585
    fn describe(&self) -> String {
586
        "memory".into()
587
    }
588
589
    fn has(&self, key: &str) -> Result<bool> {
590
        check_key(key)?;
591
        Ok(self.map().contains_key(key))
592
    }
593
594
    fn get(&self, key: &str) -> Result<Vec<u8>> {
595
        check_key(key)?;
596
        self.map()
597
            .get(key)
598
            .map(|(b, _)| b.clone())
599
            .ok_or_else(|| Error::NotFound(key.to_string()))
600
    }
601
602
    fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>> {
603
        let all = self.get(key)?;
604
        let len = all.len() as u64;
605
        if range.end > len || range.start > range.end {
606
            return Err(Error::Backend(format!(
607
                "{key}: bytes {}..{} asked of an object of {len} bytes",
608
                range.start, range.end
609
            )));
610
        }
611
        Ok(all[range.start as usize..range.end as usize].to_vec())
612
    }
613
614
    fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()> {
615
        check_key(key)?;
616
        let mut map = self.map();
617
        if map.contains_key(key) {
618
            return Err(Error::Exists(key.to_string()));
619
        }
620
        map.insert(key.to_string(), (bytes.to_vec(), now_ms()));
621
        Ok(())
622
    }
623
624
    fn list(&self, prefix: &str) -> Result<Vec<Entry>> {
625
        Ok(self
626
            .map()
627
            .range(prefix.to_string()..)
628
            .take_while(|(k, _)| k.starts_with(prefix))
629
            .map(|(k, (v, t))| Entry {
630
                key: k.clone(),
631
                size: v.len() as u64,
632
                modified_ms: Some(*t),
633
            })
634
            .collect())
635
    }
636
637
    fn delete(&self, key: &str) -> Result<()> {
638
        check_key(key)?;
639
        self.map().remove(key);
640
        Ok(())
641
    }
642
643
    fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> {
644
        check_key(key)?;
645
        Ok(self
646
            .map()
647
            .get(key)
648
            .map(|(b, _)| (b.clone(), content_version(b))))
649
    }
650
651
    fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> {
652
        check_key(key)?;
653
        let mut map = self.map();
654
        let current = map.get(key).map(|(b, _)| content_version(b));
655
        check_expected(key, current.as_ref(), expected)?;
656
        map.insert(key.to_string(), (bytes.to_vec(), now_ms()));
657
        Ok(content_version(bytes))
658
    }
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.
691
    pub fn open(
692
        remote: std::sync::Arc<dyn Store>,
693
        dir: impl Into<PathBuf>,
694
        limit: u64,
695
    ) -> Result<CachingStore> {
696
        Ok(CachingStore {
697
            cache: LocalStore::open(dir)?,
698
            remote,
699
            limit,
700
            used: Mutex::new(None),
701
        })
702
    }
703
704
    pub fn remote(&self) -> &std::sync::Arc<dyn Store> {
705
        &self.remote
706
    }
707
708
    /// Bytes the cache holds now.
709
    pub fn cached_bytes(&self) -> Result<u64> {
710
        let mut used = self.used.lock().unwrap_or_else(|p| p.into_inner());
711
        if used.is_none() {
712
            *used = Some(self.cache.list("")?.iter().map(|e| e.size).sum());
713
        }
714
        Ok(used.unwrap_or(0))
715
    }
716
717
    /// Whether an object of `size` bytes is kept in the cache at all.
718
    fn cacheable(&self, size: u64) -> bool {
719
        size <= self.limit / 8
720
    }
721
722
    /// Keep a copy of an object the remote holds.
723
    fn keep(&self, key: &str, bytes: &[u8]) -> Result<()> {
724
        if !self.cacheable(bytes.len() as u64) {
725
            return Ok(());
726
        }
727
        match self.cache.put_new(key, bytes) {
728
            Ok(()) => self.added(bytes.len() as u64),
729
            Err(Error::Exists(_)) => Ok(()),
730
            Err(e) => Err(e),
731
        }
732
    }
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.
736
    fn added(&self, n: u64) -> Result<()> {
737
        let total = {
738
            let mut used = self.used.lock().unwrap_or_else(|p| p.into_inner());
739
            let total = match *used {
740
                Some(u) => u + n,
741
                // Counted now, with the new object already in place.
742
                None => self.cache.list("")?.iter().map(|e| e.size).sum(),
743
            };
744
            *used = Some(total);
745
            total
746
        };
747
        if total <= self.limit {
748
            return Ok(());
749
        }
750
        let mut entries = self.cache.list("")?;
751
        entries.sort_by_key(|e| e.modified_ms.unwrap_or(0));
752
        let mut left: u64 = entries.iter().map(|e| e.size).sum();
753
        let target = self.limit / 10 * 9;
754
        for e in entries {
755
            if left <= target {
756
                break;
757
            }
758
            self.cache.delete(&e.key)?;
759
            left -= e.size;
760
        }
761
        *self.used.lock().unwrap_or_else(|p| p.into_inner()) = Some(left);
762
        Ok(())
763
    }
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.
767
    fn size_of(&self, key: &str) -> Result<Option<u64>> {
768
        let skey = format!("{SIZES}/{key}");
769
        if let Some(n) = self
770
            .cache
771
            .get(&skey)
772
            .ok()
773
            .and_then(|b| String::from_utf8(b).ok())
774
            .and_then(|t| t.parse().ok())
775
        {
776
            return Ok(Some(n));
777
        }
778
        let size = self.remote.stat(key)?.map(|e| e.size);
779
        if let Some(n) = size {
780
            self.keep(&skey, n.to_string().as_bytes())?;
781
        }
782
        Ok(size)
783
    }
784
785
    /// Mark a cached object used now, at most once a minute.
786
    fn touch(&self, key: &str) {
787
        let Ok(path) = self.cache.path(key) else {
788
            return;
789
        };
790
        let stale = fs::metadata(&path)
791
            .and_then(|m| m.modified())
792
            .ok()
793
            .and_then(|t| t.elapsed().ok())
794
            .is_some_and(|age| age > TOUCH_AFTER);
795
        if stale {
796
            if let Ok(f) = fs::File::options().append(true).open(&path) {
797
                let _ = f.set_modified(std::time::SystemTime::now());
798
            }
799
        }
800
    }
801
}
802
803
impl Store for CachingStore {
804
    fn describe(&self) -> String {
805
        format!(
806
            "{} (cached in {})",
807
            self.remote.describe(),
808
            self.cache.root().display()
809
        )
810
    }
811
812
    fn has(&self, key: &str) -> Result<bool> {
813
        Ok(self.cache.has(key)? || self.remote.has(key)?)
814
    }
815
816
    fn get(&self, key: &str) -> Result<Vec<u8>> {
817
        match self.cache.get(key) {
818
            Ok(bytes) => {
819
                self.touch(key);
820
                return Ok(bytes);
821
            }
822
            // Not cached, or removed by another process's eviction meanwhile.
823
            Err(Error::NotFound(_)) => {}
824
            Err(e) => return Err(e),
825
        }
826
        let bytes = self.remote.get(key)?;
827
        self.keep(key, &bytes)?;
828
        Ok(bytes)
829
    }
830
831
    fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>> {
832
        match self.cache.get_range(key, range.clone()) {
833
            Ok(bytes) => {
834
                self.touch(key);
835
                return Ok(bytes);
836
            }
837
            Err(Error::NotFound(_)) => {}
838
            Err(e) if self.cache.has(key)? => return Err(e),
839
            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.
844
        let rkey = format!("{RANGES}/{key}/{}-{}", range.start, range.end);
845
        if let Ok(bytes) = self.cache.get(&rkey) {
846
            self.touch(&rkey);
847
            return Ok(bytes);
848
        }
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.
852
        match self.size_of(key)? {
853
            Some(size) if self.cacheable(size) => {
854
                let bytes = self.get(key)?;
855
                let len = bytes.len() as u64;
856
                if range.end > len || range.start > range.end {
857
                    return Err(Error::Backend(format!(
858
                        "{key}: bytes {}..{} asked of an object of {len} bytes",
859
                        range.start, range.end
860
                    )));
861
                }
862
                Ok(bytes[range.start as usize..range.end as usize].to_vec())
863
            }
864
            Some(_) => {
865
                let bytes = self.remote.get_range(key, range)?;
866
                self.keep(&rkey, &bytes)?;
867
                Ok(bytes)
868
            }
869
            None => Err(Error::NotFound(key.to_string())),
870
        }
871
    }
872
873
    fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()> {
874
        self.remote.put_new(key, bytes)?;
875
        self.keep(key, bytes)
876
    }
877
878
    fn put_many_new(&self, objects: &[(String, Vec<u8>)]) -> Result<()> {
879
        self.remote.put_many_new(objects)?;
880
        for (key, bytes) in objects {
881
            self.keep(key, bytes)?;
882
        }
883
        Ok(())
884
    }
885
886
    fn put_new_file(&self, key: &str, path: &Path) -> Result<()> {
887
        let size = fs::metadata(path)?.len();
888
        let copy = if self.cacheable(size) {
889
            Some(fs::read(path)?)
890
        } else {
891
            None
892
        };
893
        self.remote.put_new_file(key, path)?;
894
        match copy {
895
            Some(bytes) => self.keep(key, &bytes),
896
            None => Ok(()),
897
        }
898
    }
899
900
    fn list(&self, prefix: &str) -> Result<Vec<Entry>> {
901
        self.remote.list(prefix)
902
    }
903
904
    fn stat(&self, key: &str) -> Result<Option<Entry>> {
905
        self.remote.stat(key)
906
    }
907
908
    fn delete(&self, key: &str) -> Result<()> {
909
        self.remote.delete(key)?;
910
        // Its kept ranges and size go with it.
911
        let mut extra = self.cache.list(&format!("{RANGES}/{key}/"))?;
912
        extra.extend(self.cache.stat(&format!("{SIZES}/{key}"))?);
913
        for e in extra {
914
            self.cache.delete(&e.key)?;
915
            let mut used = self.used.lock().unwrap_or_else(|p| p.into_inner());
916
            if let Some(u) = used.as_mut() {
917
                *u = u.saturating_sub(e.size);
918
            }
919
        }
920
        let size = self.cache.stat(key)?.map(|e| e.size);
921
        self.cache.delete(key)?;
922
        if let Some(n) = size {
923
            let mut used = self.used.lock().unwrap_or_else(|p| p.into_inner());
924
            if let Some(u) = used.as_mut() {
925
                *u = u.saturating_sub(n);
926
            }
927
        }
928
        Ok(())
929
    }
930
931
    fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> {
932
        self.remote.read_ref(key)
933
    }
934
935
    fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> {
936
        self.remote.write_ref(key, bytes, expected)
937
    }
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.
947
pub fn conformance(store: &dyn Store, prefix: &str) -> Result<Vec<&'static str>> {
948
    let mut passed = Vec::new();
949
    let key = |name: &str| format!("{prefix}/{name}");
950
    let fail = |what: &str| Error::Backend(format!("{}: {what}", store.describe()));
951
    let expect = |ok: bool, what: &str| if ok { Ok(()) } else { Err(fail(what)) };
952
953
    expect(
954
        store.list(prefix)?.is_empty(),
955
        "the probe prefix is not empty",
956
    )?;
957
    expect(
958
        !store.has(&key("a"))?,
959
        "has() of a missing object says true",
960
    )?;
961
    expect(
962
        matches!(store.get(&key("a")), Err(Error::NotFound(_))),
963
        "get() of a missing object is not NotFound",
964
    )?;
965
    passed.push("missing objects are reported missing");
966
967
    let a: Vec<u8> = (0..256u32 * 1024).map(|i| (i % 251) as u8).collect();
968
    store.put_new(&key("a"), &a)?;
969
    expect(store.has(&key("a"))?, "has() after put_new says false")?;
970
    expect(
971
        store.get(&key("a"))? == a,
972
        "get() returns other bytes than put_new wrote",
973
    )?;
974
    passed.push("an object round-trips");
975
976
    expect(
977
        store.get_range(&key("a"), 1000..1500)? == a[1000..1500],
978
        "get_range() returns the wrong bytes",
979
    )?;
980
    expect(
981
        store.get_range(&key("a"), 0..0)?.is_empty(),
982
        "an empty range is not empty",
983
    )?;
984
    expect(
985
        store.get_range(&key("a"), 0..a.len() as u64 + 1).is_err(),
986
        "a range past the end is not refused",
987
    )?;
988
    passed.push("ranges read correctly and are bounded");
989
990
    expect(
991
        matches!(store.put_new(&key("a"), b"other"), Err(Error::Exists(_))),
992
        "put_new() over an existing object is not refused",
993
    )?;
994
    expect(
995
        store.get(&key("a"))? == a,
996
        "a refused put_new() changed the object",
997
    )?;
998
    passed.push("objects are written once");
999
1000
    store.put_new(&key("dir/b"), b"bb")?;
1001
    let listed: Vec<(String, u64)> = store
1002
        .list(prefix)?
1003
        .into_iter()
1004
        .map(|e| (e.key, e.size))
1005
        .collect();
1006
    expect(
1007
        listed == vec![(key("a"), a.len() as u64), (key("dir/b"), 2)],
1008
        "list() does not return the two objects, sorted, with their sizes",
1009
    )?;
1010
    expect(
1011
        store
1012
            .stat(&key("dir/b"))?
1013
            .is_some_and(|e| e.key == key("dir/b") && e.size == 2)
1014
            && store.stat(&key("dir/c"))?.is_none(),
1015
        "stat() does not describe one object, or describes a missing one",
1016
    )?;
1017
    expect(
1018
        store
1019
            .list(&key("dir/"))?
1020
            .into_iter()
1021
            .map(|e| (e.key, e.size))
1022
            .collect::<Vec<_>>()
1023
            == vec![(key("dir/b"), 2)],
1024
        "list() of a sub-prefix is wrong",
1025
    )?;
1026
    expect(
1027
        store.list(&key("nothing/"))?.is_empty(),
1028
        "list() of an unused prefix is not empty",
1029
    )?;
1030
    passed.push("listing by prefix");
1031
1032
    store.delete(&key("dir/b"))?;
1033
    expect(
1034
        !store.has(&key("dir/b"))?,
1035
        "an object is still there after delete()",
1036
    )?;
1037
    store.delete(&key("dir/b"))?;
1038
    passed.push("deletion, and deleting again, succeed");
1039
1040
    let r = key("refs");
1041
    expect(
1042
        store.read_ref(&r)?.is_none(),
1043
        "an unwritten reference reads as something",
1044
    )?;
1045
    let v1 = store.write_ref(&r, b"one", None)?;
1046
    expect(
1047
        matches!(store.write_ref(&r, b"again", None), Err(Error::Conflict(_))),
1048
        "a second create-only write of the reference is not refused",
1049
    )?;
1050
    let (bytes, seen) = store
1051
        .read_ref(&r)?
1052
        .ok_or_else(|| fail("the reference vanished"))?;
1053
    expect(
1054
        bytes == b"one" && seen == v1,
1055
        "the reference reads back wrong",
1056
    )?;
1057
    let v2 = store.write_ref(&r, b"two", Some(&v1))?;
1058
    expect(v2 != v1, "the version did not change on write")?;
1059
    expect(
1060
        matches!(
1061
            store.write_ref(&r, b"three", Some(&v1)),
1062
            Err(Error::Conflict(_))
1063
        ),
1064
        "a write with a stale version is not refused",
1065
    )?;
1066
    let (bytes, seen) = store
1067
        .read_ref(&r)?
1068
        .ok_or_else(|| fail("the reference vanished"))?;
1069
    expect(
1070
        bytes == b"two" && seen == v2,
1071
        "a refused write changed the reference",
1072
    )?;
1073
    passed.push("references update by compare-and-swap");
1074
1075
    store.delete(&key("a"))?;
1076
    store.delete(&r)?;
1077
    expect(
1078
        store.list(prefix)?.is_empty(),
1079
        "the probe prefix is not empty after cleanup",
1080
    )?;
1081
    passed.push("cleanup");
1082
    Ok(passed)
1083
}
1084
1085
#[cfg(test)]
1086
mod tests {
1087
    use super::*;
1088
    use std::sync::Arc;
1089
1090
    #[test]
1091
    fn keys_are_plain_relative_paths() {
1092
        for ok in ["a", "packs/ab.pack", "a-b_c.d/e"] {
1093
            check_key(ok).unwrap();
1094
        }
1095
        for bad in [
1096
            "", "/a", "a/", "a//b", "..", "a/../b", "./a", "a b", "a\\b", "ä",
1097
        ] {
1098
            assert!(check_key(bad).is_err(), "{bad:?}");
1099
        }
1100
        assert!(check_key(&"x".repeat(MAX_KEY_LEN + 1)).is_err());
1101
    }
1102
1103
    #[test]
1104
    fn a_caching_store_conforms_and_reads_and_writes_through() {
1105
        let dir = tempfile::tempdir().unwrap();
1106
        let remote: Arc<dyn Store> = Arc::new(MemoryStore::new());
1107
        let store = CachingStore::open(remote.clone(), dir.path().join("cache"), 8 << 20).unwrap();
1108
        assert_eq!(conformance(&store, "probe").unwrap().len(), 8);
1109
        assert_eq!(
1110
            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.
1116
        store.put_new("loose/aa", b"written").unwrap();
1117
        assert_eq!(remote.get("loose/aa").unwrap(), b"written");
1118
        assert!(store.cache.has("loose/aa").unwrap());
1119
        // Read through: an object only the remote has is kept on first read.
1120
        remote.put_new("loose/bb", b"remote only").unwrap();
1121
        assert!(!store.cache.has("loose/bb").unwrap());
1122
        assert_eq!(store.get_range("loose/bb", 0..6).unwrap(), b"remote");
1123
        assert!(store.cache.has("loose/bb").unwrap());
1124
        // A cached object read after the remote lost it is still served.
1125
        remote.delete("loose/bb").unwrap();
1126
        assert_eq!(store.get("loose/bb").unwrap(), b"remote only");
1127
        // References are always the remote's.
1128
        let v = remote.write_ref("refs", b"one", None).unwrap();
1129
        assert_eq!(
1130
            store.read_ref("refs").unwrap(),
1131
            Some((b"one".to_vec(), v.clone()))
1132
        );
1133
        remote.write_ref("refs", b"two", Some(&v)).unwrap();
1134
        assert_eq!(store.read_ref("refs").unwrap().unwrap().0, b"two");
1135
        assert!(matches!(
1136
            store.write_ref("refs", b"three", Some(&v)),
1137
            Err(Error::Conflict(_))
1138
        ));
1139
        assert!(!store.cache.has("refs").unwrap());
1140
    }
1141
1142
    /// A remote that answers nothing: what is read through it was cached.
1143
    struct Unreachable;
1144
1145
    impl Store for Unreachable {
1146
        fn describe(&self) -> String {
1147
            "unreachable".into()
1148
        }
1149
        fn has(&self, _: &str) -> Result<bool> {
1150
            Err(Error::Backend("asked the remote".into()))
1151
        }
1152
        fn get(&self, _: &str) -> Result<Vec<u8>> {
1153
            Err(Error::Backend("asked the remote".into()))
1154
        }
1155
        fn get_range(&self, _: &str, _: Range<u64>) -> Result<Vec<u8>> {
1156
            Err(Error::Backend("asked the remote".into()))
1157
        }
1158
        fn put_new(&self, _: &str, _: &[u8]) -> Result<()> {
1159
            Err(Error::Backend("asked the remote".into()))
1160
        }
1161
        fn list(&self, _: &str) -> Result<Vec<Entry>> {
1162
            Err(Error::Backend("asked the remote".into()))
1163
        }
1164
        fn delete(&self, _: &str) -> Result<()> {
1165
            Err(Error::Backend("asked the remote".into()))
1166
        }
1167
        fn stat(&self, _: &str) -> Result<Option<Entry>> {
1168
            Err(Error::Backend("asked the remote".into()))
1169
        }
1170
        fn read_ref(&self, _: &str) -> Result<Option<(Vec<u8>, Version)>> {
1171
            Err(Error::Backend("asked the remote".into()))
1172
        }
1173
        fn write_ref(&self, _: &str, _: &[u8], _: Option<&Version>) -> Result<Version> {
1174
            Err(Error::Backend("asked the remote".into()))
1175
        }
1176
    }
1177
1178
    #[test]
1179
    fn a_caching_store_stays_within_its_limit() {
1180
        let dir = tempfile::tempdir().unwrap();
1181
        let remote: Arc<dyn Store> = Arc::new(MemoryStore::new());
1182
        let store = CachingStore::open(remote.clone(), dir.path().join("cache"), 8000).unwrap();
1183
        for i in 0..20 {
1184
            store
1185
                .put_new(&format!("loose/{i:02}"), &[i as u8; 900])
1186
                .unwrap();
1187
            assert!(store.cached_bytes().unwrap() <= 8000);
1188
        }
1189
        assert_eq!(
1190
            remote.list("loose/").unwrap().len(),
1191
            20,
1192
            "the remote holds everything"
1193
        );
1194
        let cached = store.cache.list("loose/").unwrap();
1195
        assert!(cached.len() < 20 && cached.len() >= 7, "{}", cached.len());
1196
        assert!(
1197
            cached.iter().any(|e| e.key == "loose/19"),
1198
            "the newest is kept"
1199
        );
1200
        for i in 0..20 {
1201
            assert_eq!(
1202
                store.get(&format!("loose/{i:02}")).unwrap(),
1203
                vec![i as u8; 900]
1204
            );
1205
        }
1206
        // An object over an eighth of the limit is read by range, not kept.
1207
        remote.put_new("pack-big", &[7u8; 2000]).unwrap();
1208
        assert_eq!(store.get_range("pack-big", 10..20).unwrap(), vec![7u8; 10]);
1209
        assert_eq!(store.get("pack-big").unwrap().len(), 2000);
1210
        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.
1213
        let again =
1214
            CachingStore::open(Arc::new(Unreachable), dir.path().join("cache"), 8000).unwrap();
1215
        assert_eq!(again.get_range("pack-big", 10..20).unwrap(), vec![7u8; 10]);
1216
        // Counting from scratch agrees with what was kept track of.
1217
        let fresh = CachingStore::open(remote, dir.path().join("cache"), 8000).unwrap();
1218
        assert_eq!(fresh.cached_bytes().unwrap(), store.cached_bytes().unwrap());
1219
        // Deleting it takes its ranges and size too.
1220
        store.delete("pack-big").unwrap();
1221
        assert!(
1222
            store.cache.list("cached-range/").unwrap().is_empty()
1223
                && store.cache.list("cached-size/").unwrap().is_empty()
1224
        );
1225
    }
1226
1227
    #[test]
1228
    fn the_memory_store_conforms() {
1229
        let store = MemoryStore::new();
1230
        let passed = conformance(&store, "probe").unwrap();
1231
        assert_eq!(passed.len(), 8, "{passed:?}");
1232
    }
1233
1234
    #[test]
1235
    fn the_directory_store_conforms() {
1236
        let dir = tempfile::tempdir().unwrap();
1237
        let store = LocalStore::open(dir.path().join("bucket")).unwrap();
1238
        let passed = conformance(&store, "repos/one").unwrap();
1239
        assert_eq!(passed.len(), 8, "{passed:?}");
1240
        // Nothing but the (empty) directories and no stray temporaries.
1241
        let stray: Vec<_> = walkdir(dir.path())
1242
            .into_iter()
1243
            .filter(|p| p.is_file())
1244
            .collect();
1245
        assert!(stray.is_empty(), "{stray:?}");
1246
        assert_eq!(
1247
            fs::read_dir(dir.path().join("bucket")).unwrap().count(),
1248
            0,
1249
            "no empty directories left"
1250
        );
1251
    }
1252
1253
    fn walkdir(dir: &Path) -> Vec<PathBuf> {
1254
        let mut out = vec![];
1255
        if let Ok(rd) = fs::read_dir(dir) {
1256
            for e in rd.flatten() {
1257
                let p = e.path();
1258
                if p.is_dir() {
1259
                    out.extend(walkdir(&p));
1260
                } else {
1261
                    out.push(p);
1262
                }
1263
            }
1264
        }
1265
        out
1266
    }
1267
1268
    #[test]
1269
    fn a_directory_store_refuses_keys_that_leave_its_root() {
1270
        let dir = tempfile::tempdir().unwrap();
1271
        let store = LocalStore::open(dir.path().join("bucket")).unwrap();
1272
        assert!(matches!(
1273
            store.put_new("../escape", b"x"),
1274
            Err(Error::Key(..))
1275
        ));
1276
        assert!(matches!(store.get("/etc/passwd"), Err(Error::Key(..))));
1277
        assert!(!dir.path().join("escape").exists());
1278
    }
1279
1280
    /// Many threads race to move a reference from the same version: exactly
1281
    /// one wins each round, on both stores.
1282
    #[test]
1283
    fn compare_and_swap_admits_one_writer_per_round() {
1284
        let dir = tempfile::tempdir().unwrap();
1285
        let local: Arc<dyn Store> = Arc::new(LocalStore::open(dir.path()).unwrap());
1286
        let memory: Arc<dyn Store> = Arc::new(MemoryStore::new());
1287
        for store in [local, memory] {
1288
            let v0 = store.write_ref("refs", b"0", None).unwrap();
1289
            let wins: Vec<bool> = (0..8)
1290
                .map(|i| {
1291
                    let store = store.clone();
1292
                    let v0 = v0.clone();
1293
                    std::thread::spawn(move || {
1294
                        store
1295
                            .write_ref("refs", format!("{}", i + 1).as_bytes(), Some(&v0))
1296
                            .is_ok()
1297
                    })
1298
                })
1299
                .collect::<Vec<_>>()
1300
                .into_iter()
1301
                .map(|h| h.join().unwrap())
1302
                .collect();
1303
            assert_eq!(
1304
                wins.iter().filter(|w| **w).count(),
1305
                1,
1306
                "{}: {wins:?}",
1307
                store.describe()
1308
            );
1309
            let (bytes, _) = store.read_ref("refs").unwrap().unwrap();
1310
            assert_ne!(bytes, b"0");
1311
        }
1312
    }
1313
1314
    #[test]
1315
    fn a_stale_lock_is_broken_and_a_live_one_waited_for() {
1316
        let dir = tempfile::tempdir().unwrap();
1317
        let store = LocalStore::open(dir.path()).unwrap();
1318
        let lock = dir.path().join(".refs.lock");
1319
        fs::write(&lock, "dead").unwrap();
1320
        let old = std::time::SystemTime::now() - LOCK_STALE - Duration::from_secs(5);
1321
        fs::File::open(&lock).unwrap().set_modified(old).unwrap();
1322
        store.write_ref("refs", b"after a crash", None).unwrap();
1323
        assert!(!lock.exists());
1324
    }
1325
1326
    #[test]
1327
    fn temporaries_and_locks_are_not_listed() {
1328
        let dir = tempfile::tempdir().unwrap();
1329
        let store = LocalStore::open(dir.path()).unwrap();
1330
        store.put_new("packs/a", b"a").unwrap();
1331
        fs::write(dir.path().join("packs/.a.tmp-ffffff"), "junk").unwrap();
1332
        fs::write(dir.path().join(".refs.lock"), "1").unwrap();
1333
        let keys: Vec<String> = store.list("").unwrap().into_iter().map(|e| e.key).collect();
1334
        assert_eq!(keys, ["packs/a"]);
1335
    }
1336
}