OXYGENHUB
# ff6987682725 oxygen / crates / oxy-core / src / strata.rs
43.3 KiB · Rust · last changed A caching store in front of any store 1 month 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
/// How stale a cached object's use time may get before a read renews it.
681
const TOUCH_AFTER: Duration = Duration::from_secs(60);
682
683
impl CachingStore {
684
    /// `remote` behind a cache in the directory `dir` of at most `limit`
685
    /// bytes.
686
    pub fn open(
687
        remote: std::sync::Arc<dyn Store>,
688
        dir: impl Into<PathBuf>,
689
        limit: u64,
690
    ) -> Result<CachingStore> {
691
        Ok(CachingStore {
692
            cache: LocalStore::open(dir)?,
693
            remote,
694
            limit,
695
            used: Mutex::new(None),
696
        })
697
    }
698
699
    pub fn remote(&self) -> &std::sync::Arc<dyn Store> {
700
        &self.remote
701
    }
702
703
    /// Bytes the cache holds now.
704
    pub fn cached_bytes(&self) -> Result<u64> {
705
        let mut used = self.used.lock().unwrap_or_else(|p| p.into_inner());
706
        if used.is_none() {
707
            *used = Some(self.cache.list("")?.iter().map(|e| e.size).sum());
708
        }
709
        Ok(used.unwrap_or(0))
710
    }
711
712
    /// Whether an object of `size` bytes is kept in the cache at all.
713
    fn cacheable(&self, size: u64) -> bool {
714
        size <= self.limit / 8
715
    }
716
717
    /// Keep a copy of an object the remote holds.
718
    fn keep(&self, key: &str, bytes: &[u8]) -> Result<()> {
719
        if !self.cacheable(bytes.len() as u64) {
720
            return Ok(());
721
        }
722
        match self.cache.put_new(key, bytes) {
723
            Ok(()) => self.added(bytes.len() as u64),
724
            Err(Error::Exists(_)) => Ok(()),
725
            Err(e) => Err(e),
726
        }
727
    }
728
729
    /// Count `n` new bytes, and remove the least recently used objects
730
    /// once the cache is past its limit, down to nine tenths of it.
731
    fn added(&self, n: u64) -> Result<()> {
732
        let total = {
733
            let mut used = self.used.lock().unwrap_or_else(|p| p.into_inner());
734
            let total = match *used {
735
                Some(u) => u + n,
736
                // Counted now, with the new object already in place.
737
                None => self.cache.list("")?.iter().map(|e| e.size).sum(),
738
            };
739
            *used = Some(total);
740
            total
741
        };
742
        if total <= self.limit {
743
            return Ok(());
744
        }
745
        let mut entries = self.cache.list("")?;
746
        entries.sort_by_key(|e| e.modified_ms.unwrap_or(0));
747
        let mut left: u64 = entries.iter().map(|e| e.size).sum();
748
        let target = self.limit / 10 * 9;
749
        for e in entries {
750
            if left <= target {
751
                break;
752
            }
753
            self.cache.delete(&e.key)?;
754
            left -= e.size;
755
        }
756
        *self.used.lock().unwrap_or_else(|p| p.into_inner()) = Some(left);
757
        Ok(())
758
    }
759
760
    /// Mark a cached object used now, at most once a minute.
761
    fn touch(&self, key: &str) {
762
        let Ok(path) = self.cache.path(key) else {
763
            return;
764
        };
765
        let stale = fs::metadata(&path)
766
            .and_then(|m| m.modified())
767
            .ok()
768
            .and_then(|t| t.elapsed().ok())
769
            .is_some_and(|age| age > TOUCH_AFTER);
770
        if stale {
771
            if let Ok(f) = fs::File::options().append(true).open(&path) {
772
                let _ = f.set_modified(std::time::SystemTime::now());
773
            }
774
        }
775
    }
776
}
777
778
impl Store for CachingStore {
779
    fn describe(&self) -> String {
780
        format!(
781
            "{} (cached in {})",
782
            self.remote.describe(),
783
            self.cache.root().display()
784
        )
785
    }
786
787
    fn has(&self, key: &str) -> Result<bool> {
788
        Ok(self.cache.has(key)? || self.remote.has(key)?)
789
    }
790
791
    fn get(&self, key: &str) -> Result<Vec<u8>> {
792
        match self.cache.get(key) {
793
            Ok(bytes) => {
794
                self.touch(key);
795
                return Ok(bytes);
796
            }
797
            // Not cached, or removed by another process's eviction meanwhile.
798
            Err(Error::NotFound(_)) => {}
799
            Err(e) => return Err(e),
800
        }
801
        let bytes = self.remote.get(key)?;
802
        self.keep(key, &bytes)?;
803
        Ok(bytes)
804
    }
805
806
    fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>> {
807
        match self.cache.get_range(key, range.clone()) {
808
            Ok(bytes) => {
809
                self.touch(key);
810
                return Ok(bytes);
811
            }
812
            Err(Error::NotFound(_)) => {}
813
            Err(e) if self.cache.has(key)? => return Err(e),
814
            Err(_) => {}
815
        }
816
        // A small object is fetched whole and kept; a large one is read by
817
        // range, every time.
818
        match self.remote.stat(key)? {
819
            Some(e) if self.cacheable(e.size) => {
820
                let bytes = self.get(key)?;
821
                let len = bytes.len() as u64;
822
                if range.end > len || range.start > range.end {
823
                    return Err(Error::Backend(format!(
824
                        "{key}: bytes {}..{} asked of an object of {len} bytes",
825
                        range.start, range.end
826
                    )));
827
                }
828
                Ok(bytes[range.start as usize..range.end as usize].to_vec())
829
            }
830
            Some(_) => self.remote.get_range(key, range),
831
            None => Err(Error::NotFound(key.to_string())),
832
        }
833
    }
834
835
    fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()> {
836
        self.remote.put_new(key, bytes)?;
837
        self.keep(key, bytes)
838
    }
839
840
    fn put_many_new(&self, objects: &[(String, Vec<u8>)]) -> Result<()> {
841
        self.remote.put_many_new(objects)?;
842
        for (key, bytes) in objects {
843
            self.keep(key, bytes)?;
844
        }
845
        Ok(())
846
    }
847
848
    fn put_new_file(&self, key: &str, path: &Path) -> Result<()> {
849
        let size = fs::metadata(path)?.len();
850
        let copy = if self.cacheable(size) {
851
            Some(fs::read(path)?)
852
        } else {
853
            None
854
        };
855
        self.remote.put_new_file(key, path)?;
856
        match copy {
857
            Some(bytes) => self.keep(key, &bytes),
858
            None => Ok(()),
859
        }
860
    }
861
862
    fn list(&self, prefix: &str) -> Result<Vec<Entry>> {
863
        self.remote.list(prefix)
864
    }
865
866
    fn stat(&self, key: &str) -> Result<Option<Entry>> {
867
        self.remote.stat(key)
868
    }
869
870
    fn delete(&self, key: &str) -> Result<()> {
871
        self.remote.delete(key)?;
872
        let size = self.cache.stat(key)?.map(|e| e.size);
873
        self.cache.delete(key)?;
874
        if let Some(n) = size {
875
            let mut used = self.used.lock().unwrap_or_else(|p| p.into_inner());
876
            if let Some(u) = used.as_mut() {
877
                *u = u.saturating_sub(n);
878
            }
879
        }
880
        Ok(())
881
    }
882
883
    fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> {
884
        self.remote.read_ref(key)
885
    }
886
887
    fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> {
888
        self.remote.write_ref(key, bytes, expected)
889
    }
890
}
891
892
// ---------------------------------------------------------------- conformance
893
894
/// Exercise a store under `prefix` (which must be free, and is left
895
/// empty) and report what passed: object round trips, ranges, create-only
896
/// refusal, listing, deletion, and compare-and-swap on a reference. Every
897
/// store runs this in its tests, and `oxy remote check` runs it against a
898
/// remote before trusting it with a repository.
899
pub fn conformance(store: &dyn Store, prefix: &str) -> Result<Vec<&'static str>> {
900
    let mut passed = Vec::new();
901
    let key = |name: &str| format!("{prefix}/{name}");
902
    let fail = |what: &str| Error::Backend(format!("{}: {what}", store.describe()));
903
    let expect = |ok: bool, what: &str| if ok { Ok(()) } else { Err(fail(what)) };
904
905
    expect(
906
        store.list(prefix)?.is_empty(),
907
        "the probe prefix is not empty",
908
    )?;
909
    expect(
910
        !store.has(&key("a"))?,
911
        "has() of a missing object says true",
912
    )?;
913
    expect(
914
        matches!(store.get(&key("a")), Err(Error::NotFound(_))),
915
        "get() of a missing object is not NotFound",
916
    )?;
917
    passed.push("missing objects are reported missing");
918
919
    let a: Vec<u8> = (0..256u32 * 1024).map(|i| (i % 251) as u8).collect();
920
    store.put_new(&key("a"), &a)?;
921
    expect(store.has(&key("a"))?, "has() after put_new says false")?;
922
    expect(
923
        store.get(&key("a"))? == a,
924
        "get() returns other bytes than put_new wrote",
925
    )?;
926
    passed.push("an object round-trips");
927
928
    expect(
929
        store.get_range(&key("a"), 1000..1500)? == a[1000..1500],
930
        "get_range() returns the wrong bytes",
931
    )?;
932
    expect(
933
        store.get_range(&key("a"), 0..0)?.is_empty(),
934
        "an empty range is not empty",
935
    )?;
936
    expect(
937
        store.get_range(&key("a"), 0..a.len() as u64 + 1).is_err(),
938
        "a range past the end is not refused",
939
    )?;
940
    passed.push("ranges read correctly and are bounded");
941
942
    expect(
943
        matches!(store.put_new(&key("a"), b"other"), Err(Error::Exists(_))),
944
        "put_new() over an existing object is not refused",
945
    )?;
946
    expect(
947
        store.get(&key("a"))? == a,
948
        "a refused put_new() changed the object",
949
    )?;
950
    passed.push("objects are written once");
951
952
    store.put_new(&key("dir/b"), b"bb")?;
953
    let listed: Vec<(String, u64)> = store
954
        .list(prefix)?
955
        .into_iter()
956
        .map(|e| (e.key, e.size))
957
        .collect();
958
    expect(
959
        listed == vec![(key("a"), a.len() as u64), (key("dir/b"), 2)],
960
        "list() does not return the two objects, sorted, with their sizes",
961
    )?;
962
    expect(
963
        store
964
            .stat(&key("dir/b"))?
965
            .is_some_and(|e| e.key == key("dir/b") && e.size == 2)
966
            && store.stat(&key("dir/c"))?.is_none(),
967
        "stat() does not describe one object, or describes a missing one",
968
    )?;
969
    expect(
970
        store
971
            .list(&key("dir/"))?
972
            .into_iter()
973
            .map(|e| (e.key, e.size))
974
            .collect::<Vec<_>>()
975
            == vec![(key("dir/b"), 2)],
976
        "list() of a sub-prefix is wrong",
977
    )?;
978
    expect(
979
        store.list(&key("nothing/"))?.is_empty(),
980
        "list() of an unused prefix is not empty",
981
    )?;
982
    passed.push("listing by prefix");
983
984
    store.delete(&key("dir/b"))?;
985
    expect(
986
        !store.has(&key("dir/b"))?,
987
        "an object is still there after delete()",
988
    )?;
989
    store.delete(&key("dir/b"))?;
990
    passed.push("deletion, and deleting again, succeed");
991
992
    let r = key("refs");
993
    expect(
994
        store.read_ref(&r)?.is_none(),
995
        "an unwritten reference reads as something",
996
    )?;
997
    let v1 = store.write_ref(&r, b"one", None)?;
998
    expect(
999
        matches!(store.write_ref(&r, b"again", None), Err(Error::Conflict(_))),
1000
        "a second create-only write of the reference is not refused",
1001
    )?;
1002
    let (bytes, seen) = store
1003
        .read_ref(&r)?
1004
        .ok_or_else(|| fail("the reference vanished"))?;
1005
    expect(
1006
        bytes == b"one" && seen == v1,
1007
        "the reference reads back wrong",
1008
    )?;
1009
    let v2 = store.write_ref(&r, b"two", Some(&v1))?;
1010
    expect(v2 != v1, "the version did not change on write")?;
1011
    expect(
1012
        matches!(
1013
            store.write_ref(&r, b"three", Some(&v1)),
1014
            Err(Error::Conflict(_))
1015
        ),
1016
        "a write with a stale version is not refused",
1017
    )?;
1018
    let (bytes, seen) = store
1019
        .read_ref(&r)?
1020
        .ok_or_else(|| fail("the reference vanished"))?;
1021
    expect(
1022
        bytes == b"two" && seen == v2,
1023
        "a refused write changed the reference",
1024
    )?;
1025
    passed.push("references update by compare-and-swap");
1026
1027
    store.delete(&key("a"))?;
1028
    store.delete(&r)?;
1029
    expect(
1030
        store.list(prefix)?.is_empty(),
1031
        "the probe prefix is not empty after cleanup",
1032
    )?;
1033
    passed.push("cleanup");
1034
    Ok(passed)
1035
}
1036
1037
#[cfg(test)]
1038
mod tests {
1039
    use super::*;
1040
    use std::sync::Arc;
1041
1042
    #[test]
1043
    fn keys_are_plain_relative_paths() {
1044
        for ok in ["a", "packs/ab.pack", "a-b_c.d/e"] {
1045
            check_key(ok).unwrap();
1046
        }
1047
        for bad in [
1048
            "", "/a", "a/", "a//b", "..", "a/../b", "./a", "a b", "a\\b", "ä",
1049
        ] {
1050
            assert!(check_key(bad).is_err(), "{bad:?}");
1051
        }
1052
        assert!(check_key(&"x".repeat(MAX_KEY_LEN + 1)).is_err());
1053
    }
1054
1055
    #[test]
1056
    fn a_caching_store_conforms_and_reads_and_writes_through() {
1057
        let dir = tempfile::tempdir().unwrap();
1058
        let remote: Arc<dyn Store> = Arc::new(MemoryStore::new());
1059
        let store = CachingStore::open(remote.clone(), dir.path().join("cache"), 8 << 20).unwrap();
1060
        assert_eq!(conformance(&store, "probe").unwrap().len(), 8);
1061
        assert_eq!(
1062
            store.cached_bytes().unwrap(),
1063
            0,
1064
            "the probe left nothing cached"
1065
        );
1066
1067
        // Written through: the remote has it, and so does the cache.
1068
        store.put_new("loose/aa", b"written").unwrap();
1069
        assert_eq!(remote.get("loose/aa").unwrap(), b"written");
1070
        assert!(store.cache.has("loose/aa").unwrap());
1071
        // Read through: an object only the remote has is kept on first read.
1072
        remote.put_new("loose/bb", b"remote only").unwrap();
1073
        assert!(!store.cache.has("loose/bb").unwrap());
1074
        assert_eq!(store.get_range("loose/bb", 0..6).unwrap(), b"remote");
1075
        assert!(store.cache.has("loose/bb").unwrap());
1076
        // A cached object read after the remote lost it is still served.
1077
        remote.delete("loose/bb").unwrap();
1078
        assert_eq!(store.get("loose/bb").unwrap(), b"remote only");
1079
        // References are always the remote's.
1080
        let v = remote.write_ref("refs", b"one", None).unwrap();
1081
        assert_eq!(
1082
            store.read_ref("refs").unwrap(),
1083
            Some((b"one".to_vec(), v.clone()))
1084
        );
1085
        remote.write_ref("refs", b"two", Some(&v)).unwrap();
1086
        assert_eq!(store.read_ref("refs").unwrap().unwrap().0, b"two");
1087
        assert!(matches!(
1088
            store.write_ref("refs", b"three", Some(&v)),
1089
            Err(Error::Conflict(_))
1090
        ));
1091
        assert!(!store.cache.has("refs").unwrap());
1092
    }
1093
1094
    #[test]
1095
    fn a_caching_store_stays_within_its_limit() {
1096
        let dir = tempfile::tempdir().unwrap();
1097
        let remote: Arc<dyn Store> = Arc::new(MemoryStore::new());
1098
        let store = CachingStore::open(remote.clone(), dir.path().join("cache"), 8000).unwrap();
1099
        for i in 0..20 {
1100
            store
1101
                .put_new(&format!("loose/{i:02}"), &[i as u8; 900])
1102
                .unwrap();
1103
            assert!(store.cached_bytes().unwrap() <= 8000);
1104
        }
1105
        assert_eq!(
1106
            remote.list("loose/").unwrap().len(),
1107
            20,
1108
            "the remote holds everything"
1109
        );
1110
        let cached = store.cache.list("loose/").unwrap();
1111
        assert!(cached.len() < 20 && cached.len() >= 7, "{}", cached.len());
1112
        assert!(
1113
            cached.iter().any(|e| e.key == "loose/19"),
1114
            "the newest is kept"
1115
        );
1116
        for i in 0..20 {
1117
            assert_eq!(
1118
                store.get(&format!("loose/{i:02}")).unwrap(),
1119
                vec![i as u8; 900]
1120
            );
1121
        }
1122
        // An object over an eighth of the limit is read by range, not kept.
1123
        remote.put_new("pack-big", &[7u8; 2000]).unwrap();
1124
        assert_eq!(store.get_range("pack-big", 10..20).unwrap(), vec![7u8; 10]);
1125
        assert_eq!(store.get("pack-big").unwrap().len(), 2000);
1126
        assert!(!store.cache.has("pack-big").unwrap());
1127
        // Counting from scratch agrees with what was kept track of.
1128
        let fresh = CachingStore::open(remote, dir.path().join("cache"), 8000).unwrap();
1129
        assert_eq!(fresh.cached_bytes().unwrap(), store.cached_bytes().unwrap());
1130
    }
1131
1132
    #[test]
1133
    fn the_memory_store_conforms() {
1134
        let store = MemoryStore::new();
1135
        let passed = conformance(&store, "probe").unwrap();
1136
        assert_eq!(passed.len(), 8, "{passed:?}");
1137
    }
1138
1139
    #[test]
1140
    fn the_directory_store_conforms() {
1141
        let dir = tempfile::tempdir().unwrap();
1142
        let store = LocalStore::open(dir.path().join("bucket")).unwrap();
1143
        let passed = conformance(&store, "repos/one").unwrap();
1144
        assert_eq!(passed.len(), 8, "{passed:?}");
1145
        // Nothing but the (empty) directories and no stray temporaries.
1146
        let stray: Vec<_> = walkdir(dir.path())
1147
            .into_iter()
1148
            .filter(|p| p.is_file())
1149
            .collect();
1150
        assert!(stray.is_empty(), "{stray:?}");
1151
        assert_eq!(
1152
            fs::read_dir(dir.path().join("bucket")).unwrap().count(),
1153
            0,
1154
            "no empty directories left"
1155
        );
1156
    }
1157
1158
    fn walkdir(dir: &Path) -> Vec<PathBuf> {
1159
        let mut out = vec![];
1160
        if let Ok(rd) = fs::read_dir(dir) {
1161
            for e in rd.flatten() {
1162
                let p = e.path();
1163
                if p.is_dir() {
1164
                    out.extend(walkdir(&p));
1165
                } else {
1166
                    out.push(p);
1167
                }
1168
            }
1169
        }
1170
        out
1171
    }
1172
1173
    #[test]
1174
    fn a_directory_store_refuses_keys_that_leave_its_root() {
1175
        let dir = tempfile::tempdir().unwrap();
1176
        let store = LocalStore::open(dir.path().join("bucket")).unwrap();
1177
        assert!(matches!(
1178
            store.put_new("../escape", b"x"),
1179
            Err(Error::Key(..))
1180
        ));
1181
        assert!(matches!(store.get("/etc/passwd"), Err(Error::Key(..))));
1182
        assert!(!dir.path().join("escape").exists());
1183
    }
1184
1185
    /// Many threads race to move a reference from the same version: exactly
1186
    /// one wins each round, on both stores.
1187
    #[test]
1188
    fn compare_and_swap_admits_one_writer_per_round() {
1189
        let dir = tempfile::tempdir().unwrap();
1190
        let local: Arc<dyn Store> = Arc::new(LocalStore::open(dir.path()).unwrap());
1191
        let memory: Arc<dyn Store> = Arc::new(MemoryStore::new());
1192
        for store in [local, memory] {
1193
            let v0 = store.write_ref("refs", b"0", None).unwrap();
1194
            let wins: Vec<bool> = (0..8)
1195
                .map(|i| {
1196
                    let store = store.clone();
1197
                    let v0 = v0.clone();
1198
                    std::thread::spawn(move || {
1199
                        store
1200
                            .write_ref("refs", format!("{}", i + 1).as_bytes(), Some(&v0))
1201
                            .is_ok()
1202
                    })
1203
                })
1204
                .collect::<Vec<_>>()
1205
                .into_iter()
1206
                .map(|h| h.join().unwrap())
1207
                .collect();
1208
            assert_eq!(
1209
                wins.iter().filter(|w| **w).count(),
1210
                1,
1211
                "{}: {wins:?}",
1212
                store.describe()
1213
            );
1214
            let (bytes, _) = store.read_ref("refs").unwrap().unwrap();
1215
            assert_ne!(bytes, b"0");
1216
        }
1217
    }
1218
1219
    #[test]
1220
    fn a_stale_lock_is_broken_and_a_live_one_waited_for() {
1221
        let dir = tempfile::tempdir().unwrap();
1222
        let store = LocalStore::open(dir.path()).unwrap();
1223
        let lock = dir.path().join(".refs.lock");
1224
        fs::write(&lock, "dead").unwrap();
1225
        let old = std::time::SystemTime::now() - LOCK_STALE - Duration::from_secs(5);
1226
        fs::File::open(&lock).unwrap().set_modified(old).unwrap();
1227
        store.write_ref("refs", b"after a crash", None).unwrap();
1228
        assert!(!lock.exists());
1229
    }
1230
1231
    #[test]
1232
    fn temporaries_and_locks_are_not_listed() {
1233
        let dir = tempfile::tempdir().unwrap();
1234
        let store = LocalStore::open(dir.path()).unwrap();
1235
        store.put_new("packs/a", b"a").unwrap();
1236
        fs::write(dir.path().join("packs/.a.tmp-ffffff"), "junk").unwrap();
1237
        fs::write(dir.path().join(".refs.lock"), "1").unwrap();
1238
        let keys: Vec<String> = store.list("").unwrap().into_iter().map(|e| e.key).collect();
1239
        assert_eq!(keys, ["packs/a"]);
1240
    }
1241
}