OXYGENHUB
# c6cec7822aff oxygen / crates / oxy-core / src / strata.rs
33.8 KiB · Rust · last changed The object store works where hard links are refused (closes #141) 10 days ago source blame history raw
1
//! Oxygen Strata (docs/stores.md): the storage a repository can be kept
2
//! on, as a trait, so that a bucket, a directory or a hub's disk all look
3
//! the same to the code that pushes to and fetches from them.
4
//!
5
//! A store has two halves. **Objects** are written once and never
6
//! change: packs and their indexes, named by content, which any store
7
//! can hold safely. **References** are the one mutable record (bookmarks,
8
//! tags, the policy), updated only by compare-and-swap on a version the
9
//! store hands out: an ETag on S3, a generation on GCS, a content hash on
10
//! a directory. Two writers can therefore share a store with no lock
11
//! server: the loser of a race reads again, merges, and tries again.
12
//!
13
//! A repository's own objects (`.oxy/objects`, see [`crate::store`]) are
14
//! kept on a store too, a directory one, with the same keys a bucket
15
//! would hold; a remote is a store as well. This module holds the trait,
16
//! a directory store, an in-memory store for tests, and the conformance
17
//! check every store must pass. Cloud stores live in a crate of their
18
//! own, because of what they pull in.
19
20
use std::collections::BTreeMap;
21
use std::fs;
22
use std::io::{self, Read, Seek, SeekFrom, Write};
23
use std::ops::Range;
24
use std::path::{Path, PathBuf};
25
use std::sync::Mutex;
26
use std::time::{Duration, Instant};
27
28
/// The version of a reference record as the store reports it: opaque,
29
/// compared only for equality, and only ever valid for the store that
30
/// issued it. Writing the same bytes again may keep the version (S3's
31
/// ETag and a directory's content hash are both of the content): a
32
/// compare-and-swap guards against losing a *different* record, which is
33
/// all it needs to.
34
#[derive(Clone, Debug, PartialEq, Eq)]
35
pub struct Version(pub String);
36
37
/// One key in a listing.
38
#[derive(Clone, Debug, PartialEq, Eq)]
39
pub struct Entry {
40
    pub key: String,
41
    pub size: u64,
42
    /// When the object was written, in wall milliseconds, where the store
43
    /// knows (garbage collection's grace period reads it).
44
    pub modified_ms: Option<u64>,
45
}
46
47
#[derive(Debug, thiserror::Error)]
48
pub enum Error {
49
    #[error("{0}: not in the store")]
50
    NotFound(String),
51
    #[error("{0}: already in the store")]
52
    Exists(String),
53
    #[error("{0}: changed since it was read")]
54
    Conflict(String),
55
    #[error("bad store key {0:?}: {1}")]
56
    Key(String, &'static str),
57
    #[error("{0}: busy (another writer holds it)")]
58
    Busy(String),
59
    #[error(transparent)]
60
    Io(#[from] io::Error),
61
    #[error("{0}")]
62
    Backend(String),
63
}
64
65
pub type Result<T> = std::result::Result<T, Error>;
66
67
/// Longest key a store accepts; S3 allows 1024 bytes.
68
pub const MAX_KEY_LEN: usize = 1024;
69
70
/// Refuse a key that is not a plain relative path: `/`-separated
71
/// segments of `[A-Za-z0-9._-]`, none empty, none `.` or `..`. The same
72
/// rule on every store, so a key written to one can be read from another,
73
/// and so a key can never escape a directory store's root.
74
pub fn check_key(key: &str) -> Result<()> {
75
    let bad = |why| Error::Key(key.to_string(), why);
76
    if key.is_empty() {
77
        return Err(bad("empty"));
78
    }
79
    if key.len() > MAX_KEY_LEN {
80
        return Err(bad("longer than 1024 bytes"));
81
    }
82
    for seg in key.split('/') {
83
        if seg.is_empty() {
84
            return Err(bad(
85
                "an empty segment (a leading, trailing or doubled slash)",
86
            ));
87
        }
88
        if seg == "." || seg == ".." {
89
            return Err(bad("a . or .. segment"));
90
        }
91
        if !seg
92
            .bytes()
93
            .all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'_' || b == b'-')
94
        {
95
            return Err(bad("a character outside A-Z a-z 0-9 . _ -"));
96
        }
97
    }
98
    Ok(())
99
}
100
101
/// Where a repository's packs and references are kept. Every method is
102
/// synchronous and may be called from several threads at once.
103
pub trait Store: Send + Sync {
104
    /// A name for messages: the URL, or the directory.
105
    fn describe(&self) -> String;
106
107
    // ---- objects: written once, never changed
108
109
    fn has(&self, key: &str) -> Result<bool>;
110
    /// The whole object; `NotFound` when there is none.
111
    fn get(&self, key: &str) -> Result<Vec<u8>>;
112
    /// Bytes `range` of an object; an error when the range runs past its end.
113
    fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>>;
114
    /// Write an object that does not exist yet; `Exists` when it does, and
115
    /// then nothing is changed. Readers never see a partial object.
116
    fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()>;
117
    /// Every key under `prefix` (a key prefix, not necessarily a whole
118
    /// segment), sorted, with sizes.
119
    fn list(&self, prefix: &str) -> Result<Vec<Entry>>;
120
    /// Remove an object; fine when it is already gone.
121
    fn delete(&self, key: &str) -> Result<()>;
122
    /// One object's listing entry without listing its neighbours; `None`
123
    /// when there is none.
124
    fn stat(&self, key: &str) -> Result<Option<Entry>> {
125
        Ok(self.list(key)?.into_iter().find(|e| e.key == key))
126
    }
127
    /// Write several objects that do not exist yet; one that does is left
128
    /// as it is, which is not an error (objects are named by content). A
129
    /// store that can batch its syncs does; this does them one at a time.
130
    fn put_many_new(&self, objects: &[(String, Vec<u8>)]) -> Result<()> {
131
        for (key, bytes) in objects {
132
            match self.put_new(key, bytes) {
133
                Ok(()) | Err(Error::Exists(_)) => {}
134
                Err(e) => return Err(e),
135
            }
136
        }
137
        Ok(())
138
    }
139
    /// `put_new` of a file's contents: a store on the same disk can move
140
    /// the file into place instead of copying it.
141
    fn put_new_file(&self, key: &str, path: &Path) -> Result<()> {
142
        self.put_new(key, &fs::read(path)?)
143
    }
144
145
    // ---- references: one small record, updated by compare-and-swap
146
147
    /// The record and its current version, or `None` when it was never
148
    /// written.
149
    fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>>;
150
    /// Replace the record only if its version is still `expected`
151
    /// (`None`: only if it does not exist yet). `Conflict` otherwise, and
152
    /// then nothing is changed. Returns the new version.
153
    fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version>;
154
}
155
156
/// A reference record's version on stores that have no native one: the
157
/// hash of its bytes, which two different records never share.
158
fn content_version(bytes: &[u8]) -> Version {
159
    Version(blake3::hash(bytes).to_hex().to_string())
160
}
161
162
fn check_expected(key: &str, current: Option<&Version>, expected: Option<&Version>) -> Result<()> {
163
    if current == expected {
164
        Ok(())
165
    } else {
166
        Err(Error::Conflict(key.to_string()))
167
    }
168
}
169
170
// ---------------------------------------------------------------- directory
171
172
/// A store in a directory: each key a file under the root. Create-only
173
/// writes go through a hard link, which the file system refuses when the
174
/// name is taken, and a reference is updated under a lock file beside it.
175
/// Several processes on one machine can share it; it is also what the
176
/// tests and `oxy remote check` use.
177
pub struct LocalStore {
178
    root: PathBuf,
179
}
180
181
/// How long a reference's lock may be held before it counts as abandoned
182
/// by a process that died, and how long a writer waits for it.
183
const LOCK_STALE: Duration = Duration::from_secs(60);
184
const LOCK_WAIT: Duration = Duration::from_secs(10);
185
186
impl LocalStore {
187
    /// Open the store at `root`, creating the directory if needed.
188
    pub fn open(root: impl Into<PathBuf>) -> Result<LocalStore> {
189
        let root = root.into();
190
        fs::create_dir_all(&root)?;
191
        Ok(LocalStore { root })
192
    }
193
194
    pub fn root(&self) -> &Path {
195
        &self.root
196
    }
197
198
    fn path(&self, key: &str) -> Result<PathBuf> {
199
        check_key(key)?;
200
        Ok(self.root.join(key))
201
    }
202
203
    fn temp_beside(&self, path: &Path) -> PathBuf {
204
        let mut nonce = [0u8; 6];
205
        rand::RngCore::fill_bytes(&mut rand::rngs::OsRng, &mut nonce);
206
        let name = path
207
            .file_name()
208
            .map(|n| n.to_string_lossy().into_owned())
209
            .unwrap_or_default();
210
        path.with_file_name(format!(".{name}.tmp-{}", hex::encode(nonce)))
211
    }
212
213
    fn list_dir(&self, dir: &Path, rel: &str, prefix: &str, out: &mut Vec<Entry>) -> Result<()> {
214
        let entries = match fs::read_dir(dir) {
215
            Ok(e) => e,
216
            Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
217
            Err(e) => return Err(e.into()),
218
        };
219
        for entry in entries {
220
            let entry = entry?;
221
            let name = entry.file_name().to_string_lossy().into_owned();
222
            // Temporary and lock files are not objects.
223
            if name.starts_with('.') {
224
                continue;
225
            }
226
            let key = if rel.is_empty() {
227
                name.clone()
228
            } else {
229
                format!("{rel}/{name}")
230
            };
231
            let ty = entry.file_type()?;
232
            if ty.is_dir() {
233
                // Descend only where the prefix could still match.
234
                let dir_prefix = format!("{key}/");
235
                if prefix.starts_with(&dir_prefix) || dir_prefix.starts_with(prefix) {
236
                    self.list_dir(&entry.path(), &key, prefix, out)?;
237
                }
238
            } else if ty.is_file() && key.starts_with(prefix) {
239
                let meta = entry.metadata()?;
240
                out.push(Entry {
241
                    key,
242
                    size: meta.len(),
243
                    modified_ms: modified_ms(&meta),
244
                });
245
            }
246
        }
247
        Ok(())
248
    }
249
250
    /// Take `path.lock`, waiting for another writer, and removing a lock
251
    /// a dead process left behind.
252
    fn lock(&self, key: &str, path: &Path) -> Result<PathBuf> {
253
        let lock = path.with_file_name(format!(
254
            ".{}.lock",
255
            path.file_name()
256
                .map(|n| n.to_string_lossy().into_owned())
257
                .unwrap_or_default()
258
        ));
259
        let started = Instant::now();
260
        loop {
261
            match fs::OpenOptions::new()
262
                .write(true)
263
                .create_new(true)
264
                .open(&lock)
265
            {
266
                Ok(mut f) => {
267
                    let _ = writeln!(f, "{}", std::process::id());
268
                    return Ok(lock);
269
                }
270
                Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
271
                    if let Ok(m) = fs::metadata(&lock) {
272
                        let age = m.modified().ok().and_then(|t| t.elapsed().ok());
273
                        if age.is_some_and(|a| a > LOCK_STALE) {
274
                            let _ = fs::remove_file(&lock);
275
                            continue;
276
                        }
277
                    }
278
                    if started.elapsed() > LOCK_WAIT {
279
                        return Err(Error::Busy(key.to_string()));
280
                    }
281
                    std::thread::sleep(Duration::from_millis(10));
282
                }
283
                Err(e) => return Err(e.into()),
284
            }
285
        }
286
    }
287
}
288
289
/// A file's modification time as wall milliseconds.
290
fn modified_ms(meta: &fs::Metadata) -> Option<u64> {
291
    meta.modified()
292
        .ok()
293
        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
294
        .map(|d| d.as_millis() as u64)
295
}
296
297
/// Put `tmp` at `path` only if `path` is free, as `fs::hard_link` does
298
/// (`tmp` may remain). Android forbids apps hard links in their own data
299
/// (oxygen#141): there a create-only rename does the same, atomically.
300
fn place_new(tmp: &Path, path: &Path) -> io::Result<()> {
301
    match fs::hard_link(tmp, path) {
302
        Err(e) if e.kind() == io::ErrorKind::PermissionDenied => rename_new(tmp, path),
303
        r => r,
304
    }
305
}
306
307
#[cfg(any(target_os = "linux", target_os = "android"))]
308
fn rename_new(tmp: &Path, path: &Path) -> io::Result<()> {
309
    use std::ffi::CString;
310
    use std::os::unix::ffi::OsStrExt;
311
    let from = CString::new(tmp.as_os_str().as_bytes())?;
312
    let to = CString::new(path.as_os_str().as_bytes())?;
313
    let r = unsafe {
314
        libc::renameat2(
315
            libc::AT_FDCWD,
316
            from.as_ptr(),
317
            libc::AT_FDCWD,
318
            to.as_ptr(),
319
            libc::RENAME_NOREPLACE,
320
        )
321
    };
322
    if r == 0 {
323
        Ok(())
324
    } else {
325
        Err(io::Error::last_os_error())
326
    }
327
}
328
329
#[cfg(not(any(target_os = "linux", target_os = "android")))]
330
fn rename_new(tmp: &Path, path: &Path) -> io::Result<()> {
331
    if path.exists() {
332
        return Err(io::ErrorKind::AlreadyExists.into());
333
    }
334
    fs::rename(tmp, path)
335
}
336
337
impl LocalStore {
338
    /// Link `tmp` into `path`, create-only; the directory is synced and
339
    /// `tmp` removed either way. `Exists` when the name is taken.
340
    fn link_into_place(&self, key: &str, tmp: &Path, path: &Path) -> Result<()> {
341
        let linked = place_new(tmp, path);
342
        let _ = fs::remove_file(tmp);
343
        match linked {
344
            Ok(()) => {
345
                if let Some(dir) = path.parent() {
346
                    crate::durable::sync_dir(dir)?;
347
                }
348
                Ok(())
349
            }
350
            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
351
                Err(Error::Exists(key.to_string()))
352
            }
353
            Err(e) => Err(e.into()),
354
        }
355
    }
356
357
    /// Create `path`'s directory, syncing the first directory that was
358
    /// made so its entry is durable too.
359
    fn ensure_dir(&self, path: &Path) -> Result<()> {
360
        let Some(dir) = path.parent() else {
361
            return Ok(());
362
        };
363
        if dir.is_dir() {
364
            return Ok(());
365
        }
366
        let mut made = dir.to_path_buf();
367
        while let Some(parent) = made.parent() {
368
            if parent.is_dir() || parent == self.root {
369
                break;
370
            }
371
            made = parent.to_path_buf();
372
        }
373
        fs::create_dir_all(dir)?;
374
        if let Some(parent) = made.parent() {
375
            crate::durable::sync_dir(parent)?;
376
        }
377
        Ok(())
378
    }
379
}
380
381
impl Store for LocalStore {
382
    fn describe(&self) -> String {
383
        self.root.display().to_string()
384
    }
385
386
    fn stat(&self, key: &str) -> Result<Option<Entry>> {
387
        match fs::metadata(self.path(key)?) {
388
            Ok(m) if m.is_file() => Ok(Some(Entry {
389
                key: key.to_string(),
390
                size: m.len(),
391
                modified_ms: modified_ms(&m),
392
            })),
393
            Ok(_) => Ok(None),
394
            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
395
            Err(e) => Err(e.into()),
396
        }
397
    }
398
399
    /// Every file written and synced (on every core), then each linked
400
    /// into place and each directory synced once: durable when this
401
    /// returns, as one at a time would be, with far fewer waits.
402
    fn put_many_new(&self, objects: &[(String, Vec<u8>)]) -> Result<()> {
403
        use rayon::prelude::*;
404
        let mut todo: Vec<(PathBuf, PathBuf, &[u8])> = Vec::new();
405
        for (key, bytes) in objects {
406
            let path = self.path(key)?;
407
            if path.exists() || todo.iter().any(|(p, ..)| *p == path) {
408
                continue;
409
            }
410
            self.ensure_dir(&path)?;
411
            todo.push((path.clone(), self.temp_beside(&path), bytes));
412
        }
413
        if todo.is_empty() {
414
            return Ok(());
415
        }
416
        crate::durable::step("write loose objects")?;
417
        todo.par_iter()
418
            .try_for_each(|(_, tmp, bytes)| -> io::Result<()> {
419
                let mut f = fs::File::create(tmp)?;
420
                f.write_all(bytes)?;
421
                f.sync_all()
422
            })?;
423
        crate::durable::step("rename loose objects")?;
424
        let mut dirs: std::collections::BTreeSet<PathBuf> = std::collections::BTreeSet::new();
425
        for (path, tmp, _) in &todo {
426
            let linked = place_new(tmp, path);
427
            let _ = fs::remove_file(tmp);
428
            match linked {
429
                Ok(()) => {
430
                    if let Some(d) = path.parent() {
431
                        dirs.insert(d.to_path_buf());
432
                    }
433
                }
434
                Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
435
                Err(e) => return Err(e.into()),
436
            }
437
        }
438
        dirs.par_iter()
439
            .try_for_each(|d| crate::durable::sync_dir(d))?;
440
        Ok(())
441
    }
442
443
    /// The file is linked into place when it is on this file system,
444
    /// else copied; it is removed either way.
445
    fn put_new_file(&self, key: &str, file: &Path) -> Result<()> {
446
        let path = self.path(key)?;
447
        if path.exists() {
448
            let _ = fs::remove_file(file);
449
            return Err(Error::Exists(key.to_string()));
450
        }
451
        self.ensure_dir(&path)?;
452
        match place_new(file, &path) {
453
            Ok(()) => {
454
                let _ = fs::remove_file(file);
455
                if let Some(dir) = path.parent() {
456
                    crate::durable::sync_dir(dir)?;
457
                }
458
                Ok(())
459
            }
460
            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
461
                let _ = fs::remove_file(file);
462
                Err(Error::Exists(key.to_string()))
463
            }
464
            Err(_) => {
465
                // Another file system: copy beside the name, then link.
466
                let tmp = self.temp_beside(&path);
467
                let copied = (|| {
468
                    let mut src = fs::File::open(file)?;
469
                    let mut dst = fs::File::create(&tmp)?;
470
                    io::copy(&mut src, &mut dst)?;
471
                    dst.sync_all()
472
                })();
473
                let _ = fs::remove_file(file);
474
                copied?;
475
                self.link_into_place(key, &tmp, &path)
476
            }
477
        }
478
    }
479
480
    fn has(&self, key: &str) -> Result<bool> {
481
        Ok(self.path(key)?.is_file())
482
    }
483
484
    fn get(&self, key: &str) -> Result<Vec<u8>> {
485
        let path = self.path(key)?;
486
        match fs::read(&path) {
487
            Ok(b) => Ok(b),
488
            Err(e) if e.kind() == io::ErrorKind::NotFound => Err(Error::NotFound(key.to_string())),
489
            Err(e) => Err(e.into()),
490
        }
491
    }
492
493
    fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>> {
494
        let path = self.path(key)?;
495
        let mut f = match fs::File::open(&path) {
496
            Ok(f) => f,
497
            Err(e) if e.kind() == io::ErrorKind::NotFound => {
498
                return Err(Error::NotFound(key.to_string()))
499
            }
500
            Err(e) => return Err(e.into()),
501
        };
502
        let len = f.metadata()?.len();
503
        if range.end > len || range.start > range.end {
504
            return Err(Error::Backend(format!(
505
                "{key}: bytes {}..{} asked of an object of {len} bytes",
506
                range.start, range.end
507
            )));
508
        }
509
        f.seek(SeekFrom::Start(range.start))?;
510
        let mut out = vec![0u8; (range.end - range.start) as usize];
511
        f.read_exact(&mut out)?;
512
        Ok(out)
513
    }
514
515
    fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()> {
516
        let path = self.path(key)?;
517
        if path.exists() {
518
            return Err(Error::Exists(key.to_string()));
519
        }
520
        self.ensure_dir(&path)?;
521
        // Written beside its name, then linked into it: the link fails if
522
        // the name was taken meanwhile, and a reader never sees a part.
523
        let tmp = self.temp_beside(&path);
524
        let written = (|| {
525
            let mut f = fs::File::create(&tmp)?;
526
            f.write_all(bytes)?;
527
            f.sync_all()
528
        })();
529
        if let Err(e) = written {
530
            let _ = fs::remove_file(&tmp);
531
            return Err(e.into());
532
        }
533
        self.link_into_place(key, &tmp, &path)
534
    }
535
536
    fn list(&self, prefix: &str) -> Result<Vec<Entry>> {
537
        let mut out = Vec::new();
538
        self.list_dir(&self.root, "", prefix, &mut out)?;
539
        out.sort_by(|a, b| a.key.cmp(&b.key));
540
        Ok(out)
541
    }
542
543
    fn delete(&self, key: &str) -> Result<()> {
544
        let path = self.path(key)?;
545
        match fs::remove_file(&path) {
546
            Ok(()) => Ok(()),
547
            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
548
            Err(e) => Err(e.into()),
549
        }
550
    }
551
552
    fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> {
553
        let path = self.path(key)?;
554
        match fs::read(&path) {
555
            Ok(b) => {
556
                let v = content_version(&b);
557
                Ok(Some((b, v)))
558
            }
559
            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
560
            Err(e) => Err(e.into()),
561
        }
562
    }
563
564
    fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> {
565
        let path = self.path(key)?;
566
        if let Some(dir) = path.parent() {
567
            fs::create_dir_all(dir)?;
568
        }
569
        let lock = self.lock(key, &path)?;
570
        let result = (|| {
571
            let current = self.read_ref(key)?.map(|(_, v)| v);
572
            check_expected(key, current.as_ref(), expected)?;
573
            crate::durable::write_atomic(&path, bytes)?;
574
            Ok(content_version(bytes))
575
        })();
576
        let _ = fs::remove_file(&lock);
577
        result
578
    }
579
}
580
581
// ---------------------------------------------------------------- memory
582
583
/// A store in memory, for tests: the conditional writes behave as the
584
/// cloud stores' do.
585
#[derive(Default)]
586
pub struct MemoryStore {
587
    objects: Mutex<BTreeMap<String, (Vec<u8>, u64)>>,
588
}
589
590
fn now_ms() -> u64 {
591
    std::time::SystemTime::now()
592
        .duration_since(std::time::UNIX_EPOCH)
593
        .map(|d| d.as_millis() as u64)
594
        .unwrap_or(0)
595
}
596
597
impl MemoryStore {
598
    pub fn new() -> MemoryStore {
599
        MemoryStore::default()
600
    }
601
602
    fn map(&self) -> std::sync::MutexGuard<'_, BTreeMap<String, (Vec<u8>, u64)>> {
603
        self.objects.lock().unwrap_or_else(|p| p.into_inner())
604
    }
605
606
    /// Pretend `key` was written `age` ago (for grace-period tests).
607
    pub fn age(&self, key: &str, age: Duration) {
608
        if let Some(entry) = self.map().get_mut(key) {
609
            entry.1 = now_ms().saturating_sub(age.as_millis() as u64);
610
        }
611
    }
612
}
613
614
impl Store for MemoryStore {
615
    fn describe(&self) -> String {
616
        "memory".into()
617
    }
618
619
    fn has(&self, key: &str) -> Result<bool> {
620
        check_key(key)?;
621
        Ok(self.map().contains_key(key))
622
    }
623
624
    fn get(&self, key: &str) -> Result<Vec<u8>> {
625
        check_key(key)?;
626
        self.map()
627
            .get(key)
628
            .map(|(b, _)| b.clone())
629
            .ok_or_else(|| Error::NotFound(key.to_string()))
630
    }
631
632
    fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>> {
633
        let all = self.get(key)?;
634
        let len = all.len() as u64;
635
        if range.end > len || range.start > range.end {
636
            return Err(Error::Backend(format!(
637
                "{key}: bytes {}..{} asked of an object of {len} bytes",
638
                range.start, range.end
639
            )));
640
        }
641
        Ok(all[range.start as usize..range.end as usize].to_vec())
642
    }
643
644
    fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()> {
645
        check_key(key)?;
646
        let mut map = self.map();
647
        if map.contains_key(key) {
648
            return Err(Error::Exists(key.to_string()));
649
        }
650
        map.insert(key.to_string(), (bytes.to_vec(), now_ms()));
651
        Ok(())
652
    }
653
654
    fn list(&self, prefix: &str) -> Result<Vec<Entry>> {
655
        Ok(self
656
            .map()
657
            .range(prefix.to_string()..)
658
            .take_while(|(k, _)| k.starts_with(prefix))
659
            .map(|(k, (v, t))| Entry {
660
                key: k.clone(),
661
                size: v.len() as u64,
662
                modified_ms: Some(*t),
663
            })
664
            .collect())
665
    }
666
667
    fn delete(&self, key: &str) -> Result<()> {
668
        check_key(key)?;
669
        self.map().remove(key);
670
        Ok(())
671
    }
672
673
    fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> {
674
        check_key(key)?;
675
        Ok(self
676
            .map()
677
            .get(key)
678
            .map(|(b, _)| (b.clone(), content_version(b))))
679
    }
680
681
    fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> {
682
        check_key(key)?;
683
        let mut map = self.map();
684
        let current = map.get(key).map(|(b, _)| content_version(b));
685
        check_expected(key, current.as_ref(), expected)?;
686
        map.insert(key.to_string(), (bytes.to_vec(), now_ms()));
687
        Ok(content_version(bytes))
688
    }
689
}
690
691
// ---------------------------------------------------------------- conformance
692
693
/// Exercise a store under `prefix` (which must be free, and is left
694
/// empty) and report what passed: object round trips, ranges, create-only
695
/// refusal, listing, deletion, and compare-and-swap on a reference. Every
696
/// store runs this in its tests, and `oxy remote check` runs it against a
697
/// remote before trusting it with a repository.
698
pub fn conformance(store: &dyn Store, prefix: &str) -> Result<Vec<&'static str>> {
699
    let mut passed = Vec::new();
700
    let key = |name: &str| format!("{prefix}/{name}");
701
    let fail = |what: &str| Error::Backend(format!("{}: {what}", store.describe()));
702
    let expect = |ok: bool, what: &str| if ok { Ok(()) } else { Err(fail(what)) };
703
704
    expect(
705
        store.list(prefix)?.is_empty(),
706
        "the probe prefix is not empty",
707
    )?;
708
    expect(
709
        !store.has(&key("a"))?,
710
        "has() of a missing object says true",
711
    )?;
712
    expect(
713
        matches!(store.get(&key("a")), Err(Error::NotFound(_))),
714
        "get() of a missing object is not NotFound",
715
    )?;
716
    passed.push("missing objects are reported missing");
717
718
    let a: Vec<u8> = (0..256u32 * 1024).map(|i| (i % 251) as u8).collect();
719
    store.put_new(&key("a"), &a)?;
720
    expect(store.has(&key("a"))?, "has() after put_new says false")?;
721
    expect(
722
        store.get(&key("a"))? == a,
723
        "get() returns other bytes than put_new wrote",
724
    )?;
725
    passed.push("an object round-trips");
726
727
    expect(
728
        store.get_range(&key("a"), 1000..1500)? == a[1000..1500],
729
        "get_range() returns the wrong bytes",
730
    )?;
731
    expect(
732
        store.get_range(&key("a"), 0..0)?.is_empty(),
733
        "an empty range is not empty",
734
    )?;
735
    expect(
736
        store.get_range(&key("a"), 0..a.len() as u64 + 1).is_err(),
737
        "a range past the end is not refused",
738
    )?;
739
    passed.push("ranges read correctly and are bounded");
740
741
    expect(
742
        matches!(store.put_new(&key("a"), b"other"), Err(Error::Exists(_))),
743
        "put_new() over an existing object is not refused",
744
    )?;
745
    expect(
746
        store.get(&key("a"))? == a,
747
        "a refused put_new() changed the object",
748
    )?;
749
    passed.push("objects are written once");
750
751
    store.put_new(&key("dir/b"), b"bb")?;
752
    let listed: Vec<(String, u64)> = store
753
        .list(prefix)?
754
        .into_iter()
755
        .map(|e| (e.key, e.size))
756
        .collect();
757
    expect(
758
        listed == vec![(key("a"), a.len() as u64), (key("dir/b"), 2)],
759
        "list() does not return the two objects, sorted, with their sizes",
760
    )?;
761
    expect(
762
        store
763
            .stat(&key("dir/b"))?
764
            .is_some_and(|e| e.key == key("dir/b") && e.size == 2)
765
            && store.stat(&key("dir/c"))?.is_none(),
766
        "stat() does not describe one object, or describes a missing one",
767
    )?;
768
    expect(
769
        store
770
            .list(&key("dir/"))?
771
            .into_iter()
772
            .map(|e| (e.key, e.size))
773
            .collect::<Vec<_>>()
774
            == vec![(key("dir/b"), 2)],
775
        "list() of a sub-prefix is wrong",
776
    )?;
777
    expect(
778
        store.list(&key("nothing/"))?.is_empty(),
779
        "list() of an unused prefix is not empty",
780
    )?;
781
    passed.push("listing by prefix");
782
783
    store.delete(&key("dir/b"))?;
784
    expect(
785
        !store.has(&key("dir/b"))?,
786
        "an object is still there after delete()",
787
    )?;
788
    store.delete(&key("dir/b"))?;
789
    passed.push("deletion, and deleting again, succeed");
790
791
    let r = key("refs");
792
    expect(
793
        store.read_ref(&r)?.is_none(),
794
        "an unwritten reference reads as something",
795
    )?;
796
    let v1 = store.write_ref(&r, b"one", None)?;
797
    expect(
798
        matches!(store.write_ref(&r, b"again", None), Err(Error::Conflict(_))),
799
        "a second create-only write of the reference is not refused",
800
    )?;
801
    let (bytes, seen) = store
802
        .read_ref(&r)?
803
        .ok_or_else(|| fail("the reference vanished"))?;
804
    expect(
805
        bytes == b"one" && seen == v1,
806
        "the reference reads back wrong",
807
    )?;
808
    let v2 = store.write_ref(&r, b"two", Some(&v1))?;
809
    expect(v2 != v1, "the version did not change on write")?;
810
    expect(
811
        matches!(
812
            store.write_ref(&r, b"three", Some(&v1)),
813
            Err(Error::Conflict(_))
814
        ),
815
        "a write with a stale version is not refused",
816
    )?;
817
    let (bytes, seen) = store
818
        .read_ref(&r)?
819
        .ok_or_else(|| fail("the reference vanished"))?;
820
    expect(
821
        bytes == b"two" && seen == v2,
822
        "a refused write changed the reference",
823
    )?;
824
    passed.push("references update by compare-and-swap");
825
826
    store.delete(&key("a"))?;
827
    store.delete(&r)?;
828
    expect(
829
        store.list(prefix)?.is_empty(),
830
        "the probe prefix is not empty after cleanup",
831
    )?;
832
    passed.push("cleanup");
833
    Ok(passed)
834
}
835
836
#[cfg(test)]
837
mod tests {
838
    use super::*;
839
    use std::sync::Arc;
840
841
    /// Where hard links are refused (Android, oxygen#141), objects are
842
    /// renamed into place, still never over a name that is taken.
843
    #[test]
844
    fn a_create_only_rename_never_replaces() {
845
        let dir = tempfile::tempdir().unwrap();
846
        let (a, b, to) = (
847
            dir.path().join("a"),
848
            dir.path().join("b"),
849
            dir.path().join("to"),
850
        );
851
        fs::write(&a, b"first").unwrap();
852
        fs::write(&b, b"second").unwrap();
853
        rename_new(&a, &to).unwrap();
854
        assert_eq!(
855
            rename_new(&b, &to).unwrap_err().kind(),
856
            io::ErrorKind::AlreadyExists
857
        );
858
        assert_eq!(fs::read(&to).unwrap(), b"first");
859
        assert!(!a.exists() && b.exists());
860
    }
861
862
    #[test]
863
    fn keys_are_plain_relative_paths() {
864
        for ok in ["a", "packs/ab.pack", "a-b_c.d/e"] {
865
            check_key(ok).unwrap();
866
        }
867
        for bad in [
868
            "", "/a", "a/", "a//b", "..", "a/../b", "./a", "a b", "a\\b", "ä",
869
        ] {
870
            assert!(check_key(bad).is_err(), "{bad:?}");
871
        }
872
        assert!(check_key(&"x".repeat(MAX_KEY_LEN + 1)).is_err());
873
    }
874
875
    #[test]
876
    fn the_memory_store_conforms() {
877
        let store = MemoryStore::new();
878
        let passed = conformance(&store, "probe").unwrap();
879
        assert_eq!(passed.len(), 8, "{passed:?}");
880
    }
881
882
    #[test]
883
    fn the_directory_store_conforms() {
884
        let dir = tempfile::tempdir().unwrap();
885
        let store = LocalStore::open(dir.path().join("bucket")).unwrap();
886
        let passed = conformance(&store, "repos/one").unwrap();
887
        assert_eq!(passed.len(), 8, "{passed:?}");
888
        // Nothing but the (empty) directories and no stray temporaries.
889
        let stray: Vec<_> = walkdir(dir.path())
890
            .into_iter()
891
            .filter(|p| p.is_file())
892
            .collect();
893
        assert!(stray.is_empty(), "{stray:?}");
894
    }
895
896
    fn walkdir(dir: &Path) -> Vec<PathBuf> {
897
        let mut out = vec![];
898
        if let Ok(rd) = fs::read_dir(dir) {
899
            for e in rd.flatten() {
900
                let p = e.path();
901
                if p.is_dir() {
902
                    out.extend(walkdir(&p));
903
                } else {
904
                    out.push(p);
905
                }
906
            }
907
        }
908
        out
909
    }
910
911
    #[test]
912
    fn a_directory_store_refuses_keys_that_leave_its_root() {
913
        let dir = tempfile::tempdir().unwrap();
914
        let store = LocalStore::open(dir.path().join("bucket")).unwrap();
915
        assert!(matches!(
916
            store.put_new("../escape", b"x"),
917
            Err(Error::Key(..))
918
        ));
919
        assert!(matches!(store.get("/etc/passwd"), Err(Error::Key(..))));
920
        assert!(!dir.path().join("escape").exists());
921
    }
922
923
    /// Many threads race to move a reference from the same version: exactly
924
    /// one wins each round, on both stores.
925
    #[test]
926
    fn compare_and_swap_admits_one_writer_per_round() {
927
        let dir = tempfile::tempdir().unwrap();
928
        let local: Arc<dyn Store> = Arc::new(LocalStore::open(dir.path()).unwrap());
929
        let memory: Arc<dyn Store> = Arc::new(MemoryStore::new());
930
        for store in [local, memory] {
931
            let v0 = store.write_ref("refs", b"0", None).unwrap();
932
            let wins: Vec<bool> = (0..8)
933
                .map(|i| {
934
                    let store = store.clone();
935
                    let v0 = v0.clone();
936
                    std::thread::spawn(move || {
937
                        store
938
                            .write_ref("refs", format!("{}", i + 1).as_bytes(), Some(&v0))
939
                            .is_ok()
940
                    })
941
                })
942
                .collect::<Vec<_>>()
943
                .into_iter()
944
                .map(|h| h.join().unwrap())
945
                .collect();
946
            assert_eq!(
947
                wins.iter().filter(|w| **w).count(),
948
                1,
949
                "{}: {wins:?}",
950
                store.describe()
951
            );
952
            let (bytes, _) = store.read_ref("refs").unwrap().unwrap();
953
            assert_ne!(bytes, b"0");
954
        }
955
    }
956
957
    #[test]
958
    fn a_stale_lock_is_broken_and_a_live_one_waited_for() {
959
        let dir = tempfile::tempdir().unwrap();
960
        let store = LocalStore::open(dir.path()).unwrap();
961
        let lock = dir.path().join(".refs.lock");
962
        fs::write(&lock, "dead").unwrap();
963
        let old = std::time::SystemTime::now() - LOCK_STALE - Duration::from_secs(5);
964
        fs::File::open(&lock).unwrap().set_modified(old).unwrap();
965
        store.write_ref("refs", b"after a crash", None).unwrap();
966
        assert!(!lock.exists());
967
    }
968
969
    #[test]
970
    fn temporaries_and_locks_are_not_listed() {
971
        let dir = tempfile::tempdir().unwrap();
972
        let store = LocalStore::open(dir.path()).unwrap();
973
        store.put_new("packs/a", b"a").unwrap();
974
        fs::write(dir.path().join("packs/.a.tmp-ffffff"), "junk").unwrap();
975
        fs::write(dir.path().join(".refs.lock"), "1").unwrap();
976
        let keys: Vec<String> = store.list("").unwrap().into_iter().map(|e| e.key).collect();
977
        assert_eq!(keys, ["packs/a"]);
978
    }
979
}