OXYGENHUB
# d0bf2da15094 oxygen / crates / oxy-core / src / strata.rs
42.8 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(()) => Ok(()),
507
            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
508
            Err(e) => Err(e.into()),
509
        }
510
    }
511
512
    fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> {
513
        let path = self.path(key)?;
514
        match fs::read(&path) {
515
            Ok(b) => {
516
                let v = content_version(&b);
517
                Ok(Some((b, v)))
518
            }
519
            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
520
            Err(e) => Err(e.into()),
521
        }
522
    }
523
524
    fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> {
525
        let path = self.path(key)?;
526
        if let Some(dir) = path.parent() {
527
            fs::create_dir_all(dir)?;
528
        }
529
        let lock = self.lock(key, &path)?;
530
        let result = (|| {
531
            let current = self.read_ref(key)?.map(|(_, v)| v);
532
            check_expected(key, current.as_ref(), expected)?;
533
            crate::durable::write_atomic(&path, bytes)?;
534
            Ok(content_version(bytes))
535
        })();
536
        let _ = fs::remove_file(&lock);
537
        result
538
    }
539
}
540
541
// ---------------------------------------------------------------- memory
542
543
/// A store in memory, for tests: the conditional writes behave as the
544
/// cloud stores' do.
545
#[derive(Default)]
546
pub struct MemoryStore {
547
    objects: Mutex<BTreeMap<String, (Vec<u8>, u64)>>,
548
}
549
550
fn now_ms() -> u64 {
551
    std::time::SystemTime::now()
552
        .duration_since(std::time::UNIX_EPOCH)
553
        .map(|d| d.as_millis() as u64)
554
        .unwrap_or(0)
555
}
556
557
impl MemoryStore {
558
    pub fn new() -> MemoryStore {
559
        MemoryStore::default()
560
    }
561
562
    fn map(&self) -> std::sync::MutexGuard<'_, BTreeMap<String, (Vec<u8>, u64)>> {
563
        self.objects.lock().unwrap_or_else(|p| p.into_inner())
564
    }
565
566
    /// Pretend `key` was written `age` ago (for grace-period tests).
567
    pub fn age(&self, key: &str, age: Duration) {
568
        if let Some(entry) = self.map().get_mut(key) {
569
            entry.1 = now_ms().saturating_sub(age.as_millis() as u64);
570
        }
571
    }
572
}
573
574
impl Store for MemoryStore {
575
    fn describe(&self) -> String {
576
        "memory".into()
577
    }
578
579
    fn has(&self, key: &str) -> Result<bool> {
580
        check_key(key)?;
581
        Ok(self.map().contains_key(key))
582
    }
583
584
    fn get(&self, key: &str) -> Result<Vec<u8>> {
585
        check_key(key)?;
586
        self.map()
587
            .get(key)
588
            .map(|(b, _)| b.clone())
589
            .ok_or_else(|| Error::NotFound(key.to_string()))
590
    }
591
592
    fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>> {
593
        let all = self.get(key)?;
594
        let len = all.len() as u64;
595
        if range.end > len || range.start > range.end {
596
            return Err(Error::Backend(format!(
597
                "{key}: bytes {}..{} asked of an object of {len} bytes",
598
                range.start, range.end
599
            )));
600
        }
601
        Ok(all[range.start as usize..range.end as usize].to_vec())
602
    }
603
604
    fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()> {
605
        check_key(key)?;
606
        let mut map = self.map();
607
        if map.contains_key(key) {
608
            return Err(Error::Exists(key.to_string()));
609
        }
610
        map.insert(key.to_string(), (bytes.to_vec(), now_ms()));
611
        Ok(())
612
    }
613
614
    fn list(&self, prefix: &str) -> Result<Vec<Entry>> {
615
        Ok(self
616
            .map()
617
            .range(prefix.to_string()..)
618
            .take_while(|(k, _)| k.starts_with(prefix))
619
            .map(|(k, (v, t))| Entry {
620
                key: k.clone(),
621
                size: v.len() as u64,
622
                modified_ms: Some(*t),
623
            })
624
            .collect())
625
    }
626
627
    fn delete(&self, key: &str) -> Result<()> {
628
        check_key(key)?;
629
        self.map().remove(key);
630
        Ok(())
631
    }
632
633
    fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> {
634
        check_key(key)?;
635
        Ok(self
636
            .map()
637
            .get(key)
638
            .map(|(b, _)| (b.clone(), content_version(b))))
639
    }
640
641
    fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> {
642
        check_key(key)?;
643
        let mut map = self.map();
644
        let current = map.get(key).map(|(b, _)| content_version(b));
645
        check_expected(key, current.as_ref(), expected)?;
646
        map.insert(key.to_string(), (bytes.to_vec(), now_ms()));
647
        Ok(content_version(bytes))
648
    }
649
}
650
651
// ---------------------------------------------------------------- caching
652
653
/// A store in front of another (oxygen#68): objects are read through a
654
/// local directory and written through it, to the remote first, so the
655
/// remote always holds everything and the cache can be dropped at any
656
/// time. Objects never change, so a cached one is always right (and every
657
/// read is hashed again above this layer). The cache is bounded: past its
658
/// limit the objects used least recently are removed. An object larger
659
/// than an eighth of the limit is not cached; it is read by range from
660
/// the remote. References are never cached: they are read from and
661
/// written to the remote every time, so compare-and-swap is the remote's.
662
pub struct CachingStore {
663
    cache: LocalStore,
664
    remote: std::sync::Arc<dyn Store>,
665
    limit: u64,
666
    /// Bytes in the cache, counted on first need and kept up to date.
667
    used: Mutex<Option<u64>>,
668
}
669
670
/// How stale a cached object's use time may get before a read renews it.
671
const TOUCH_AFTER: Duration = Duration::from_secs(60);
672
673
impl CachingStore {
674
    /// `remote` behind a cache in the directory `dir` of at most `limit`
675
    /// bytes.
676
    pub fn open(
677
        remote: std::sync::Arc<dyn Store>,
678
        dir: impl Into<PathBuf>,
679
        limit: u64,
680
    ) -> Result<CachingStore> {
681
        Ok(CachingStore {
682
            cache: LocalStore::open(dir)?,
683
            remote,
684
            limit,
685
            used: Mutex::new(None),
686
        })
687
    }
688
689
    pub fn remote(&self) -> &std::sync::Arc<dyn Store> {
690
        &self.remote
691
    }
692
693
    /// Bytes the cache holds now.
694
    pub fn cached_bytes(&self) -> Result<u64> {
695
        let mut used = self.used.lock().unwrap_or_else(|p| p.into_inner());
696
        if used.is_none() {
697
            *used = Some(self.cache.list("")?.iter().map(|e| e.size).sum());
698
        }
699
        Ok(used.unwrap_or(0))
700
    }
701
702
    /// Whether an object of `size` bytes is kept in the cache at all.
703
    fn cacheable(&self, size: u64) -> bool {
704
        size <= self.limit / 8
705
    }
706
707
    /// Keep a copy of an object the remote holds.
708
    fn keep(&self, key: &str, bytes: &[u8]) -> Result<()> {
709
        if !self.cacheable(bytes.len() as u64) {
710
            return Ok(());
711
        }
712
        match self.cache.put_new(key, bytes) {
713
            Ok(()) => self.added(bytes.len() as u64),
714
            Err(Error::Exists(_)) => Ok(()),
715
            Err(e) => Err(e),
716
        }
717
    }
718
719
    /// Count `n` new bytes, and remove the least recently used objects
720
    /// once the cache is past its limit, down to nine tenths of it.
721
    fn added(&self, n: u64) -> Result<()> {
722
        let total = {
723
            let mut used = self.used.lock().unwrap_or_else(|p| p.into_inner());
724
            let total = match *used {
725
                Some(u) => u + n,
726
                // Counted now, with the new object already in place.
727
                None => self.cache.list("")?.iter().map(|e| e.size).sum(),
728
            };
729
            *used = Some(total);
730
            total
731
        };
732
        if total <= self.limit {
733
            return Ok(());
734
        }
735
        let mut entries = self.cache.list("")?;
736
        entries.sort_by_key(|e| e.modified_ms.unwrap_or(0));
737
        let mut left: u64 = entries.iter().map(|e| e.size).sum();
738
        let target = self.limit / 10 * 9;
739
        for e in entries {
740
            if left <= target {
741
                break;
742
            }
743
            self.cache.delete(&e.key)?;
744
            left -= e.size;
745
        }
746
        *self.used.lock().unwrap_or_else(|p| p.into_inner()) = Some(left);
747
        Ok(())
748
    }
749
750
    /// Mark a cached object used now, at most once a minute.
751
    fn touch(&self, key: &str) {
752
        let Ok(path) = self.cache.path(key) else {
753
            return;
754
        };
755
        let stale = fs::metadata(&path)
756
            .and_then(|m| m.modified())
757
            .ok()
758
            .and_then(|t| t.elapsed().ok())
759
            .is_some_and(|age| age > TOUCH_AFTER);
760
        if stale {
761
            if let Ok(f) = fs::File::options().append(true).open(&path) {
762
                let _ = f.set_modified(std::time::SystemTime::now());
763
            }
764
        }
765
    }
766
}
767
768
impl Store for CachingStore {
769
    fn describe(&self) -> String {
770
        format!(
771
            "{} (cached in {})",
772
            self.remote.describe(),
773
            self.cache.root().display()
774
        )
775
    }
776
777
    fn has(&self, key: &str) -> Result<bool> {
778
        Ok(self.cache.has(key)? || self.remote.has(key)?)
779
    }
780
781
    fn get(&self, key: &str) -> Result<Vec<u8>> {
782
        match self.cache.get(key) {
783
            Ok(bytes) => {
784
                self.touch(key);
785
                return Ok(bytes);
786
            }
787
            // Not cached, or removed by another process's eviction meanwhile.
788
            Err(Error::NotFound(_)) => {}
789
            Err(e) => return Err(e),
790
        }
791
        let bytes = self.remote.get(key)?;
792
        self.keep(key, &bytes)?;
793
        Ok(bytes)
794
    }
795
796
    fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>> {
797
        match self.cache.get_range(key, range.clone()) {
798
            Ok(bytes) => {
799
                self.touch(key);
800
                return Ok(bytes);
801
            }
802
            Err(Error::NotFound(_)) => {}
803
            Err(e) if self.cache.has(key)? => return Err(e),
804
            Err(_) => {}
805
        }
806
        // A small object is fetched whole and kept; a large one is read by
807
        // range, every time.
808
        match self.remote.stat(key)? {
809
            Some(e) if self.cacheable(e.size) => {
810
                let bytes = self.get(key)?;
811
                let len = bytes.len() as u64;
812
                if range.end > len || range.start > range.end {
813
                    return Err(Error::Backend(format!(
814
                        "{key}: bytes {}..{} asked of an object of {len} bytes",
815
                        range.start, range.end
816
                    )));
817
                }
818
                Ok(bytes[range.start as usize..range.end as usize].to_vec())
819
            }
820
            Some(_) => self.remote.get_range(key, range),
821
            None => Err(Error::NotFound(key.to_string())),
822
        }
823
    }
824
825
    fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()> {
826
        self.remote.put_new(key, bytes)?;
827
        self.keep(key, bytes)
828
    }
829
830
    fn put_many_new(&self, objects: &[(String, Vec<u8>)]) -> Result<()> {
831
        self.remote.put_many_new(objects)?;
832
        for (key, bytes) in objects {
833
            self.keep(key, bytes)?;
834
        }
835
        Ok(())
836
    }
837
838
    fn put_new_file(&self, key: &str, path: &Path) -> Result<()> {
839
        let size = fs::metadata(path)?.len();
840
        let copy = if self.cacheable(size) {
841
            Some(fs::read(path)?)
842
        } else {
843
            None
844
        };
845
        self.remote.put_new_file(key, path)?;
846
        match copy {
847
            Some(bytes) => self.keep(key, &bytes),
848
            None => Ok(()),
849
        }
850
    }
851
852
    fn list(&self, prefix: &str) -> Result<Vec<Entry>> {
853
        self.remote.list(prefix)
854
    }
855
856
    fn stat(&self, key: &str) -> Result<Option<Entry>> {
857
        self.remote.stat(key)
858
    }
859
860
    fn delete(&self, key: &str) -> Result<()> {
861
        self.remote.delete(key)?;
862
        let size = self.cache.stat(key)?.map(|e| e.size);
863
        self.cache.delete(key)?;
864
        if let Some(n) = size {
865
            let mut used = self.used.lock().unwrap_or_else(|p| p.into_inner());
866
            if let Some(u) = used.as_mut() {
867
                *u = u.saturating_sub(n);
868
            }
869
        }
870
        Ok(())
871
    }
872
873
    fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> {
874
        self.remote.read_ref(key)
875
    }
876
877
    fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> {
878
        self.remote.write_ref(key, bytes, expected)
879
    }
880
}
881
882
// ---------------------------------------------------------------- conformance
883
884
/// Exercise a store under `prefix` (which must be free, and is left
885
/// empty) and report what passed: object round trips, ranges, create-only
886
/// refusal, listing, deletion, and compare-and-swap on a reference. Every
887
/// store runs this in its tests, and `oxy remote check` runs it against a
888
/// remote before trusting it with a repository.
889
pub fn conformance(store: &dyn Store, prefix: &str) -> Result<Vec<&'static str>> {
890
    let mut passed = Vec::new();
891
    let key = |name: &str| format!("{prefix}/{name}");
892
    let fail = |what: &str| Error::Backend(format!("{}: {what}", store.describe()));
893
    let expect = |ok: bool, what: &str| if ok { Ok(()) } else { Err(fail(what)) };
894
895
    expect(
896
        store.list(prefix)?.is_empty(),
897
        "the probe prefix is not empty",
898
    )?;
899
    expect(
900
        !store.has(&key("a"))?,
901
        "has() of a missing object says true",
902
    )?;
903
    expect(
904
        matches!(store.get(&key("a")), Err(Error::NotFound(_))),
905
        "get() of a missing object is not NotFound",
906
    )?;
907
    passed.push("missing objects are reported missing");
908
909
    let a: Vec<u8> = (0..256u32 * 1024).map(|i| (i % 251) as u8).collect();
910
    store.put_new(&key("a"), &a)?;
911
    expect(store.has(&key("a"))?, "has() after put_new says false")?;
912
    expect(
913
        store.get(&key("a"))? == a,
914
        "get() returns other bytes than put_new wrote",
915
    )?;
916
    passed.push("an object round-trips");
917
918
    expect(
919
        store.get_range(&key("a"), 1000..1500)? == a[1000..1500],
920
        "get_range() returns the wrong bytes",
921
    )?;
922
    expect(
923
        store.get_range(&key("a"), 0..0)?.is_empty(),
924
        "an empty range is not empty",
925
    )?;
926
    expect(
927
        store.get_range(&key("a"), 0..a.len() as u64 + 1).is_err(),
928
        "a range past the end is not refused",
929
    )?;
930
    passed.push("ranges read correctly and are bounded");
931
932
    expect(
933
        matches!(store.put_new(&key("a"), b"other"), Err(Error::Exists(_))),
934
        "put_new() over an existing object is not refused",
935
    )?;
936
    expect(
937
        store.get(&key("a"))? == a,
938
        "a refused put_new() changed the object",
939
    )?;
940
    passed.push("objects are written once");
941
942
    store.put_new(&key("dir/b"), b"bb")?;
943
    let listed: Vec<(String, u64)> = store
944
        .list(prefix)?
945
        .into_iter()
946
        .map(|e| (e.key, e.size))
947
        .collect();
948
    expect(
949
        listed == vec![(key("a"), a.len() as u64), (key("dir/b"), 2)],
950
        "list() does not return the two objects, sorted, with their sizes",
951
    )?;
952
    expect(
953
        store
954
            .stat(&key("dir/b"))?
955
            .is_some_and(|e| e.key == key("dir/b") && e.size == 2)
956
            && store.stat(&key("dir/c"))?.is_none(),
957
        "stat() does not describe one object, or describes a missing one",
958
    )?;
959
    expect(
960
        store
961
            .list(&key("dir/"))?
962
            .into_iter()
963
            .map(|e| (e.key, e.size))
964
            .collect::<Vec<_>>()
965
            == vec![(key("dir/b"), 2)],
966
        "list() of a sub-prefix is wrong",
967
    )?;
968
    expect(
969
        store.list(&key("nothing/"))?.is_empty(),
970
        "list() of an unused prefix is not empty",
971
    )?;
972
    passed.push("listing by prefix");
973
974
    store.delete(&key("dir/b"))?;
975
    expect(
976
        !store.has(&key("dir/b"))?,
977
        "an object is still there after delete()",
978
    )?;
979
    store.delete(&key("dir/b"))?;
980
    passed.push("deletion, and deleting again, succeed");
981
982
    let r = key("refs");
983
    expect(
984
        store.read_ref(&r)?.is_none(),
985
        "an unwritten reference reads as something",
986
    )?;
987
    let v1 = store.write_ref(&r, b"one", None)?;
988
    expect(
989
        matches!(store.write_ref(&r, b"again", None), Err(Error::Conflict(_))),
990
        "a second create-only write of the reference is not refused",
991
    )?;
992
    let (bytes, seen) = store
993
        .read_ref(&r)?
994
        .ok_or_else(|| fail("the reference vanished"))?;
995
    expect(
996
        bytes == b"one" && seen == v1,
997
        "the reference reads back wrong",
998
    )?;
999
    let v2 = store.write_ref(&r, b"two", Some(&v1))?;
1000
    expect(v2 != v1, "the version did not change on write")?;
1001
    expect(
1002
        matches!(
1003
            store.write_ref(&r, b"three", Some(&v1)),
1004
            Err(Error::Conflict(_))
1005
        ),
1006
        "a write with a stale version is not refused",
1007
    )?;
1008
    let (bytes, seen) = store
1009
        .read_ref(&r)?
1010
        .ok_or_else(|| fail("the reference vanished"))?;
1011
    expect(
1012
        bytes == b"two" && seen == v2,
1013
        "a refused write changed the reference",
1014
    )?;
1015
    passed.push("references update by compare-and-swap");
1016
1017
    store.delete(&key("a"))?;
1018
    store.delete(&r)?;
1019
    expect(
1020
        store.list(prefix)?.is_empty(),
1021
        "the probe prefix is not empty after cleanup",
1022
    )?;
1023
    passed.push("cleanup");
1024
    Ok(passed)
1025
}
1026
1027
#[cfg(test)]
1028
mod tests {
1029
    use super::*;
1030
    use std::sync::Arc;
1031
1032
    #[test]
1033
    fn keys_are_plain_relative_paths() {
1034
        for ok in ["a", "packs/ab.pack", "a-b_c.d/e"] {
1035
            check_key(ok).unwrap();
1036
        }
1037
        for bad in [
1038
            "", "/a", "a/", "a//b", "..", "a/../b", "./a", "a b", "a\\b", "ä",
1039
        ] {
1040
            assert!(check_key(bad).is_err(), "{bad:?}");
1041
        }
1042
        assert!(check_key(&"x".repeat(MAX_KEY_LEN + 1)).is_err());
1043
    }
1044
1045
    #[test]
1046
    fn a_caching_store_conforms_and_reads_and_writes_through() {
1047
        let dir = tempfile::tempdir().unwrap();
1048
        let remote: Arc<dyn Store> = Arc::new(MemoryStore::new());
1049
        let store = CachingStore::open(remote.clone(), dir.path().join("cache"), 8 << 20).unwrap();
1050
        assert_eq!(conformance(&store, "probe").unwrap().len(), 8);
1051
        assert_eq!(
1052
            store.cached_bytes().unwrap(),
1053
            0,
1054
            "the probe left nothing cached"
1055
        );
1056
1057
        // Written through: the remote has it, and so does the cache.
1058
        store.put_new("loose/aa", b"written").unwrap();
1059
        assert_eq!(remote.get("loose/aa").unwrap(), b"written");
1060
        assert!(store.cache.has("loose/aa").unwrap());
1061
        // Read through: an object only the remote has is kept on first read.
1062
        remote.put_new("loose/bb", b"remote only").unwrap();
1063
        assert!(!store.cache.has("loose/bb").unwrap());
1064
        assert_eq!(store.get_range("loose/bb", 0..6).unwrap(), b"remote");
1065
        assert!(store.cache.has("loose/bb").unwrap());
1066
        // A cached object read after the remote lost it is still served.
1067
        remote.delete("loose/bb").unwrap();
1068
        assert_eq!(store.get("loose/bb").unwrap(), b"remote only");
1069
        // References are always the remote's.
1070
        let v = remote.write_ref("refs", b"one", None).unwrap();
1071
        assert_eq!(
1072
            store.read_ref("refs").unwrap(),
1073
            Some((b"one".to_vec(), v.clone()))
1074
        );
1075
        remote.write_ref("refs", b"two", Some(&v)).unwrap();
1076
        assert_eq!(store.read_ref("refs").unwrap().unwrap().0, b"two");
1077
        assert!(matches!(
1078
            store.write_ref("refs", b"three", Some(&v)),
1079
            Err(Error::Conflict(_))
1080
        ));
1081
        assert!(!store.cache.has("refs").unwrap());
1082
    }
1083
1084
    #[test]
1085
    fn a_caching_store_stays_within_its_limit() {
1086
        let dir = tempfile::tempdir().unwrap();
1087
        let remote: Arc<dyn Store> = Arc::new(MemoryStore::new());
1088
        let store = CachingStore::open(remote.clone(), dir.path().join("cache"), 8000).unwrap();
1089
        for i in 0..20 {
1090
            store
1091
                .put_new(&format!("loose/{i:02}"), &[i as u8; 900])
1092
                .unwrap();
1093
            assert!(store.cached_bytes().unwrap() <= 8000);
1094
        }
1095
        assert_eq!(
1096
            remote.list("loose/").unwrap().len(),
1097
            20,
1098
            "the remote holds everything"
1099
        );
1100
        let cached = store.cache.list("loose/").unwrap();
1101
        assert!(cached.len() < 20 && cached.len() >= 7, "{}", cached.len());
1102
        assert!(
1103
            cached.iter().any(|e| e.key == "loose/19"),
1104
            "the newest is kept"
1105
        );
1106
        for i in 0..20 {
1107
            assert_eq!(
1108
                store.get(&format!("loose/{i:02}")).unwrap(),
1109
                vec![i as u8; 900]
1110
            );
1111
        }
1112
        // An object over an eighth of the limit is read by range, not kept.
1113
        remote.put_new("pack-big", &[7u8; 2000]).unwrap();
1114
        assert_eq!(store.get_range("pack-big", 10..20).unwrap(), vec![7u8; 10]);
1115
        assert_eq!(store.get("pack-big").unwrap().len(), 2000);
1116
        assert!(!store.cache.has("pack-big").unwrap());
1117
        // Counting from scratch agrees with what was kept track of.
1118
        let fresh = CachingStore::open(remote, dir.path().join("cache"), 8000).unwrap();
1119
        assert_eq!(fresh.cached_bytes().unwrap(), store.cached_bytes().unwrap());
1120
    }
1121
1122
    #[test]
1123
    fn the_memory_store_conforms() {
1124
        let store = MemoryStore::new();
1125
        let passed = conformance(&store, "probe").unwrap();
1126
        assert_eq!(passed.len(), 8, "{passed:?}");
1127
    }
1128
1129
    #[test]
1130
    fn the_directory_store_conforms() {
1131
        let dir = tempfile::tempdir().unwrap();
1132
        let store = LocalStore::open(dir.path().join("bucket")).unwrap();
1133
        let passed = conformance(&store, "repos/one").unwrap();
1134
        assert_eq!(passed.len(), 8, "{passed:?}");
1135
        // Nothing but the (empty) directories and no stray temporaries.
1136
        let stray: Vec<_> = walkdir(dir.path())
1137
            .into_iter()
1138
            .filter(|p| p.is_file())
1139
            .collect();
1140
        assert!(stray.is_empty(), "{stray:?}");
1141
    }
1142
1143
    fn walkdir(dir: &Path) -> Vec<PathBuf> {
1144
        let mut out = vec![];
1145
        if let Ok(rd) = fs::read_dir(dir) {
1146
            for e in rd.flatten() {
1147
                let p = e.path();
1148
                if p.is_dir() {
1149
                    out.extend(walkdir(&p));
1150
                } else {
1151
                    out.push(p);
1152
                }
1153
            }
1154
        }
1155
        out
1156
    }
1157
1158
    #[test]
1159
    fn a_directory_store_refuses_keys_that_leave_its_root() {
1160
        let dir = tempfile::tempdir().unwrap();
1161
        let store = LocalStore::open(dir.path().join("bucket")).unwrap();
1162
        assert!(matches!(
1163
            store.put_new("../escape", b"x"),
1164
            Err(Error::Key(..))
1165
        ));
1166
        assert!(matches!(store.get("/etc/passwd"), Err(Error::Key(..))));
1167
        assert!(!dir.path().join("escape").exists());
1168
    }
1169
1170
    /// Many threads race to move a reference from the same version: exactly
1171
    /// one wins each round, on both stores.
1172
    #[test]
1173
    fn compare_and_swap_admits_one_writer_per_round() {
1174
        let dir = tempfile::tempdir().unwrap();
1175
        let local: Arc<dyn Store> = Arc::new(LocalStore::open(dir.path()).unwrap());
1176
        let memory: Arc<dyn Store> = Arc::new(MemoryStore::new());
1177
        for store in [local, memory] {
1178
            let v0 = store.write_ref("refs", b"0", None).unwrap();
1179
            let wins: Vec<bool> = (0..8)
1180
                .map(|i| {
1181
                    let store = store.clone();
1182
                    let v0 = v0.clone();
1183
                    std::thread::spawn(move || {
1184
                        store
1185
                            .write_ref("refs", format!("{}", i + 1).as_bytes(), Some(&v0))
1186
                            .is_ok()
1187
                    })
1188
                })
1189
                .collect::<Vec<_>>()
1190
                .into_iter()
1191
                .map(|h| h.join().unwrap())
1192
                .collect();
1193
            assert_eq!(
1194
                wins.iter().filter(|w| **w).count(),
1195
                1,
1196
                "{}: {wins:?}",
1197
                store.describe()
1198
            );
1199
            let (bytes, _) = store.read_ref("refs").unwrap().unwrap();
1200
            assert_ne!(bytes, b"0");
1201
        }
1202
    }
1203
1204
    #[test]
1205
    fn a_stale_lock_is_broken_and_a_live_one_waited_for() {
1206
        let dir = tempfile::tempdir().unwrap();
1207
        let store = LocalStore::open(dir.path()).unwrap();
1208
        let lock = dir.path().join(".refs.lock");
1209
        fs::write(&lock, "dead").unwrap();
1210
        let old = std::time::SystemTime::now() - LOCK_STALE - Duration::from_secs(5);
1211
        fs::File::open(&lock).unwrap().set_modified(old).unwrap();
1212
        store.write_ref("refs", b"after a crash", None).unwrap();
1213
        assert!(!lock.exists());
1214
    }
1215
1216
    #[test]
1217
    fn temporaries_and_locks_are_not_listed() {
1218
        let dir = tempfile::tempdir().unwrap();
1219
        let store = LocalStore::open(dir.path()).unwrap();
1220
        store.put_new("packs/a", b"a").unwrap();
1221
        fs::write(dir.path().join("packs/.a.tmp-ffffff"), "junk").unwrap();
1222
        fs::write(dir.path().join(".refs.lock"), "1").unwrap();
1223
        let keys: Vec<String> = store.list("").unwrap().into_iter().map(|e| e.key).collect();
1224
        assert_eq!(keys, ["packs/a"]);
1225
    }
1226
}