diff --git a/AGENTS.md b/AGENTS.md index b4e73665..8bdb7dc5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,6 +8,10 @@ review bots read and write at the same time, written in Rust. - `crates/origin-shared`: the object model, wire formats, and API contracts shared by every component. +- `crates/origin-platform`: everything that differs between platforms + (durable writes, file locks, copy-on-write clones, refusing network file + systems), behind traits. It is the only place that may depend on the + target OS. - `crates/origin-client`: the HTTP client, generated from the server's OpenAPI document. Never edit generated code by hand. - `apps/origin-src`: the `origin` binary, both the command line and the diff --git a/Cargo.lock b/Cargo.lock index ebbdbbdb..e31853a4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,126 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstyle", + "clap_lex", + "terminal_size", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "condtype" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf0a07a401f374238ab8e2f11a104d2851bf9ce711ec69804834de8af45c7af" + +[[package]] +name = "divan" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a405457ec78b8fe08b0e32b4a3570ab5dff6dd16eb9e76a5ee0a9d9cbd898933" +dependencies = [ + "cfg-if", + "clap", + "condtype", + "divan-macros", + "libc", + "regex-lite", +] + +[[package]] +name = "divan-macros" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9556bc800956545d6420a640173e5ba7dfa82f38d3ea5a167eb555bc69ac3323" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "libc" +version = "0.2.190" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + [[package]] name = "origin-client" version = "0.1.0" @@ -9,6 +129,17 @@ dependencies = [ "origin-shared", ] +[[package]] +name = "origin-platform" +version = "0.1.0" +dependencies = [ + "divan", + "reflink-copy", + "rustix", + "tempfile", + "thiserror", +] + [[package]] name = "origin-shared" version = "0.1.0" @@ -19,3 +150,248 @@ version = "0.1.0" dependencies = [ "origin-shared", ] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "reflink-copy" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9dd7ab4af0363d5ccfd2838d782a28196cf32a5cc2e4fe3c5dc83f2be588b8b" +dependencies = [ + "cfg-if", + "libc", + "rustix", + "windows", +] + +[[package]] +name = "regex-lite" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973" + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "terminal_size" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "230a1b821ccbd75b185820a1f1ff7b14d21da1e442e22c0863ea5f08771a8874" +dependencies = [ + "rustix", + "windows-sys", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] diff --git a/Cargo.toml b/Cargo.toml index 85f8248a..a22cd937 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,6 +3,7 @@ resolver = "3" members = [ "apps/origin-src", "crates/origin-client", + "crates/origin-platform", "crates/origin-shared", ] @@ -18,8 +19,17 @@ repository = "https://github.com/piquel-fr/origin" [workspace.dependencies] # Internal origin-client = { version = "0.1.0", path = "crates/origin-client" } +origin-platform = { version = "0.1.0", path = "crates/origin-platform" } origin-shared = { version = "0.1.0", path = "crates/origin-shared" } +# External +divan = "0.1.21" +reflink-copy = "0.1.30" +# Only in origin-platform. The version and features reflink-copy uses on Linux. +rustix = { version = "1.1.5", default-features = false, features = ["fs", "std"] } +tempfile = "3.27.0" +thiserror = "2.0.21" + [workspace.lints.rust] unsafe_code = "forbid" missing_docs = "warn" diff --git a/README.md b/README.md index 652a4253..bcf2b28a 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,8 @@ review bots read and write at the same time, written in Rust. See ## Development ```sh -just # format, lint, test, and audit dependencies +just # format, lint, test, and audit dependencies +just bench # micro-benchmarks ``` rustup installs the toolchain `rust-toolchain.toml` pins. The minimum diff --git a/crates/origin-platform/Cargo.toml b/crates/origin-platform/Cargo.toml new file mode 100644 index 00000000..bab27837 --- /dev/null +++ b/crates/origin-platform/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "origin-platform" +description = "Platform-specific file operations: durable writes, locks, copy-on-write clones and file system checks" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true + +[dependencies] +reflink-copy.workspace = true +rustix.workspace = true +thiserror.workspace = true + +[dev-dependencies] +divan.workspace = true +tempfile.workspace = true + +[[bench]] +name = "platform" +harness = false + +[lints] +workspace = true diff --git a/crates/origin-platform/benches/platform.rs b/crates/origin-platform/benches/platform.rs new file mode 100644 index 00000000..43cda408 --- /dev/null +++ b/crates/origin-platform/benches/platform.rs @@ -0,0 +1,115 @@ +//! The cost of durability and locking on the native platform: what every +//! store write and target landing pays. + +use std::path::PathBuf; +use std::thread; + +use divan::Bencher; +use divan::counter::ItemsCount; +use origin_platform::{DurableWrite, LockMode, LockedFile, Native}; + +fn main() { + divan::main(); +} + +/// The size of a typical small record. +const CONTENTS: [u8; 512] = [b'x'; 512]; + +/// Fresh paths for one durable write of `files` files, spread over +/// `shards` directories like loose objects. +fn paths(dir: &tempfile::TempDir, files: usize, shards: usize) -> impl FnMut() -> Vec { + let objects = dir.path().join("objects"); + let mut write = 0; + move || { + write += 1; + (0..files) + .map(|file| objects.join(format!("{:02x}/{write}-{file}", file % shards))) + .collect() + } +} + +/// Each file written durably on its own: a batch sync and a directory sync +/// per file. +#[divan::bench(args = [1, 16, 128], sample_count = 10, sample_size = 1)] +fn one_at_a_time(bencher: Bencher<'_, '_>, files: usize) { + let dir = tempfile::tempdir().unwrap(); + let platform = Native::default(); + bencher + .counter(ItemsCount::new(files)) + .with_inputs(paths(&dir, files, 1)) + .bench_local_values(|paths| { + for path in paths { + let write = DurableWrite::new(&platform); + write.stage(path, &CONTENTS).unwrap(); + write.commit().unwrap(); + } + }); +} + +/// One group commit: a batch sync, and one for the directory. +#[divan::bench(args = [1, 16, 128], sample_count = 10, sample_size = 1)] +fn batched(bencher: Bencher<'_, '_>, files: usize) { + let dir = tempfile::tempdir().unwrap(); + let platform = Native::default(); + bencher + .counter(ItemsCount::new(files)) + .with_inputs(paths(&dir, files, 1)) + .bench_local_values(|paths| { + let write = DurableWrite::new(&platform); + for path in paths { + write.stage(path, &CONTENTS).unwrap(); + } + write.commit().unwrap(); + }); +} + +/// One group commit of files spread over 32 directories, like loose +/// objects. +#[divan::bench(args = [128], sample_count = 10, sample_size = 1)] +fn batched_sharded(bencher: Bencher<'_, '_>, files: usize) { + let dir = tempfile::tempdir().unwrap(); + let platform = Native::default(); + bencher + .counter(ItemsCount::new(files)) + .with_inputs(paths(&dir, files, 32)) + .bench_local_values(|paths| { + let write = DurableWrite::new(&platform); + for path in paths { + write.stage(path, &CONTENTS).unwrap(); + } + write.commit().unwrap(); + }); +} + +/// One group commit staged from 8 threads, which overlaps their writes. +#[divan::bench(args = [16, 128], sample_count = 10, sample_size = 1)] +fn batched_parallel(bencher: Bencher<'_, '_>, files: usize) { + let dir = tempfile::tempdir().unwrap(); + let platform = Native::default(); + bencher + .counter(ItemsCount::new(files)) + .with_inputs(paths(&dir, files, 1)) + .bench_local_values(|paths| { + let write = DurableWrite::new(&platform); + thread::scope(|scope| { + for chunk in paths.chunks(files.div_ceil(8)) { + let write = &write; + scope.spawn(move || { + for path in chunk { + write.stage(path, &CONTENTS).unwrap(); + } + }); + } + }); + write.commit().unwrap(); + }); +} + +/// Taking and releasing an uncontended lock, as every landing does. +#[divan::bench] +fn lock(bencher: Bencher<'_, '_>) { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("lock"); + let platform = Native::default(); + bencher.bench(|| drop(LockedFile::open(&platform, &path, LockMode::Exclusive).unwrap())); +} diff --git a/crates/origin-platform/src/clone.rs b/crates/origin-platform/src/clone.rs new file mode 100644 index 00000000..2b492aeb --- /dev/null +++ b/crates/origin-platform/src/clone.rs @@ -0,0 +1,60 @@ +use std::io; +use std::path::{Path, PathBuf}; + +/// Copy-on-write clones: a new file that shares the original's storage until +/// either is modified, made in constant time whatever its size. +/// +/// Only some file systems can clone, so callers fall back to copying on +/// [`CloneError::Unsupported`]. +pub trait CloneFile { + /// Whether `error`, from a failed clone, means the file system cannot + /// clone these files, rather than that the files are unusable. Each + /// platform reports this differently. + fn cannot_clone(&self, error: &io::Error) -> bool; + + /// Clones `from` to `to`, which must not exist. + /// + /// # Errors + /// + /// Fails with [`CloneError::Unsupported`] if the file system cannot + /// clone these files, and [`CloneError::Io`] if `from` cannot be read or + /// `to` cannot be created. + fn clone_file(&self, from: &Path, to: &Path) -> Result<(), CloneError> { + reflink_copy::reflink(from, to).map_err(|source| { + // reflink-copy reports a source that isn't a regular file as + // `InvalidInput`, which can also mean the file system can't clone. + let unsupported = self.cannot_clone(&source) && from.is_file(); + let (from, to) = (from.to_owned(), to.to_owned()); + if unsupported { + CloneError::Unsupported { from, to, source } + } else { + CloneError::Io { from, to, source } + } + }) + } +} + +/// A clone that failed. +#[derive(Debug, thiserror::Error)] +pub enum CloneError { + /// The file system cannot clone these files. Copying them works instead. + #[error("the file system cannot clone {} to {}", from.display(), to.display())] + Unsupported { + /// The file to clone. + from: PathBuf, + /// The clone's path. + to: PathBuf, + /// The error the platform reported. + source: io::Error, + }, + /// The source cannot be read or the clone cannot be created. + #[error("cannot clone {} to {}", from.display(), to.display())] + Io { + /// The file to clone. + from: PathBuf, + /// The clone's path. + to: PathBuf, + /// The underlying error. + source: io::Error, + }, +} diff --git a/crates/origin-platform/src/durability.rs b/crates/origin-platform/src/durability.rs new file mode 100644 index 00000000..b7246af9 --- /dev/null +++ b/crates/origin-platform/src/durability.rs @@ -0,0 +1,476 @@ +use std::collections::BTreeSet; +use std::ffi::OsStr; +use std::fs::{self, File}; +use std::io::{self, Write}; +use std::num::NonZero; +use std::panic; +use std::path::{Path, PathBuf}; +use std::process; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Mutex, PoisonError}; +use std::thread; + +use crate::{Error, Op}; + +/// Flushes written data to stable storage, so it survives a crash or a power +/// loss. +/// +/// The default methods use the standard library, which issues each +/// platform's strongest sync. Each platform syncs batches its own way. +pub trait Durability { + /// Flushes a file's contents, and the metadata needed to read them back. + /// + /// # Errors + /// + /// Fails if the file system reports a write error. + fn sync_file(&self, file: &File) -> io::Result<()> { + file.sync_data() + } + + /// Flushes a directory's entries, making the files created in, renamed + /// into or removed from it durable. + /// + /// # Errors + /// + /// Fails if the directory cannot be opened or the file system reports a + /// write error. + fn sync_dir(&self, dir: &Path) -> io::Result<()> { + File::open(dir)?.sync_all() + } + + /// Flushes the contents of many files at once, more cheaply than + /// syncing each. The files must be on one file system. + /// + /// # Errors + /// + /// Fails if a file cannot be opened or the file system reports a write + /// error, naming the file involved. + fn sync_batch<'f>(&self, files: impl IntoIterator) -> Result<(), Error>; +} + +/// Files written durably as a group, at the cost of one batch sync and one +/// sync per directory involved. +/// +/// [`DurableWrite::stage`] writes each file under a temporary name in its +/// destination's directory, which [`DurableWrite::is_temporary`] recognizes. +/// [`DurableWrite::commit`] then makes them all durable with +/// [`Durability::sync_batch`], renames them into place from several threads +/// and syncs their directories. Readers see either the previous file or the +/// complete new one, and once `commit` returns a crash loses none of them. +/// Dropping the write before committing removes its temporary files; a crash +/// leaves them behind, so code that lists a directory written this way skips +/// them, and removes the stale ones. +/// +/// Staging beside the destination keeps each rename within one directory, +/// so writes to different directories never contend on a shared one. +/// +/// Files can be staged from several threads at once. +#[derive(Debug)] +pub struct DurableWrite<'a, P> { + platform: &'a P, + staged: Mutex, +} + +/// The files staged so far. +#[derive(Debug, Default)] +struct Staged { + /// Each temporary file and the path it's published to. + files: Vec<(PathBuf, PathBuf)>, + /// The directories whose entries change: the published files' parents. + dirs: BTreeSet, +} + +/// Distinguishes the temporary files of one process. +static NEXT_TEMP: AtomicU64 = AtomicU64::new(0); + +impl

DurableWrite<'_, P> { + /// How temporary file names start: `.tmp--`. + const TEMP_PREFIX: &str = ".tmp-"; + + /// The fewest renames worth a thread of their own in + /// [`DurableWrite::commit`]: below that, spawning costs more than it + /// saves. + const RENAMES_PER_THREAD: usize = 64; + + /// Whether `name` is the name of a temporary file: one being written, or + /// left behind by a write that crashed. + #[must_use] + pub fn is_temporary(name: &OsStr) -> bool { + name.as_encoded_bytes() + .starts_with(Self::TEMP_PREFIX.as_bytes()) + } +} + +impl<'a, P: Durability> DurableWrite<'a, P> { + /// Starts a write on `platform`. + pub fn new(platform: &'a P) -> Self { + Self { + platform, + staged: Mutex::default(), + } + } + + /// Writes `contents` as the next version of `path`, and creates its + /// missing parent directories. The file appears at `path` on + /// [`DurableWrite::commit`], replacing any file there. + /// + /// Each directory created is durable at once, whatever becomes of the + /// write, so a later write into it never relies on this one committing. + /// A directory found already there may not be: another write may have + /// just created it, or died before syncing its parent. So the write + /// syncs the parent of the deepest one it found too: at once if it + /// creates directories in it, with the batch otherwise. + /// + /// # Errors + /// + /// Fails if a directory or the temporary file cannot be created or + /// written. + pub fn stage(&self, path: impl Into, contents: &[u8]) -> Result<(), Error> { + let path = path.into(); + let relied_on = self.create_parents(&path)?; + let temp = Self::parent(&path).join(format!( + "{}{}-{}", + Self::TEMP_PREFIX, + process::id(), + NEXT_TEMP.fetch_add(1, Ordering::Relaxed) + )); + if let Err(error) = Self::write_temp(&temp, contents) { + // Best effort: the file is unusable either way. + let _ = fs::remove_file(&temp); + return Err(error); + } + let mut staged = self.staged.lock().unwrap_or_else(PoisonError::into_inner); + staged.dirs.insert(Self::parent(&path).to_owned()); + staged.dirs.extend(relied_on); + staged.files.push((temp, path)); + Ok(()) + } + + fn write_temp(temp: &Path, contents: &[u8]) -> Result<(), Error> { + File::create(temp) + .and_then(|mut file| file.write_all(contents)) + .map_err(|source| Error::new(Op::Write, temp, source)) + } + + /// Creates the missing parent directories of `path`, outermost first, + /// syncing the directory each is created in right after creating it. + /// + /// The deepest directory that already exists may not be durable yet, if + /// another write created it, so its parent is synced too: before + /// creating anything in it, so a directory this write creates is only + /// ever reachable through durable entries, or else returned, for the + /// batch to sync. + fn create_parents(&self, path: &Path) -> Result, Error> { + let mut missing = Vec::new(); + let mut dir = Self::parent(path); + while !dir.is_dir() { + missing.push(dir); + dir = Self::parent(dir); + } + let Some(holder) = Self::holder(dir) else { + return Ok(None); + }; + if missing.is_empty() { + return Ok(Some(holder.to_owned())); + } + self.platform + .sync_dir(holder) + .map_err(|source| Error::new(Op::Sync, holder, source))?; + for dir in missing.into_iter().rev() { + match fs::create_dir(dir) { + // Another write created it first, and may not have synced + // its parent yet. + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {} + result => result.map_err(|source| Error::new(Op::CreateDir, dir, source))?, + } + let parent = Self::parent(dir); + self.platform + .sync_dir(parent) + .map_err(|source| Error::new(Op::Sync, parent, source))?; + } + Ok(None) + } + + /// The directory containing `path`, which is `.` for a bare file name. + #[must_use] + pub fn parent(path: &Path) -> &Path { + match path.parent() { + Some(parent) if !parent.as_os_str().is_empty() => parent, + _ => Path::new("."), + } + } + + /// The directory holding the entry of the directory `dir`, unless it + /// can't be named: for `/`, or `.`. + fn holder(dir: &Path) -> Option<&Path> { + (dir != Path::new(".") && dir.parent().is_some()).then(|| Self::parent(dir)) + } + + /// Syncs every staged file, renames them into place, then syncs each + /// directory involved once. + /// + /// # Errors + /// + /// Fails if the files cannot be synced, in which case none is published, + /// or if a file cannot be renamed or a directory cannot be synced. Files + /// renamed before such a failure are visible but may not be durable. + pub fn commit(mut self) -> Result<(), Error> { + let staged = self + .staged + .get_mut() + .unwrap_or_else(PoisonError::into_inner); + self.platform + .sync_batch(staged.files.iter().map(|(temp, _)| temp.as_path()))?; + Self::rename_all(&staged.files)?; + // Every file is published, so dropping the write removes none. + staged.files.clear(); + for dir in &staged.dirs { + self.platform + .sync_dir(dir) + .map_err(|source| Error::new(Op::Sync, dir, source))?; + } + Ok(()) + } + + /// Renames each temporary file to its path, spread over the cores. Each + /// rename locks its directory, and a batch usually spans many. + fn rename_all(files: &[(PathBuf, PathBuf)]) -> Result<(), Error> { + let rename = |files: &[(PathBuf, PathBuf)]| { + files.iter().try_for_each(|(temp, path)| { + fs::rename(temp, path).map_err(|source| Error::new(Op::Publish, path, source)) + }) + }; + let most = files.len() / Self::RENAMES_PER_THREAD; + // Checked first: asking for the cores reads the cgroup's quota. + if most <= 1 { + return rename(files); + } + let threads = thread::available_parallelism() + .map_or(1, NonZero::get) + .min(most); + thread::scope(|scope| { + files + .chunks(files.len().div_ceil(threads)) + .map(|chunk| scope.spawn(move || rename(chunk))) + .collect::>() + .into_iter() + .try_for_each(|thread| { + thread + .join() + .unwrap_or_else(|panic| panic::resume_unwind(panic)) + }) + }) + } +} + +impl

Drop for DurableWrite<'_, P> { + /// Removes the temporary files that were not published. + fn drop(&mut self) { + let staged = self + .staged + .get_mut() + .unwrap_or_else(PoisonError::into_inner); + for (temp, _) in &staged.files { + // Best effort: a leftover is garbage that readers skip. After a + // failed rename, some of these are already published. + let _ = fs::remove_file(temp); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Records syncs instead of performing them, and fails batches when + /// asked to. + #[derive(Default)] + struct Recorder { + calls: Mutex>, + fail_batches: bool, + } + + #[derive(Debug, PartialEq, Eq)] + enum Call { + Dir(PathBuf), + /// A batch sync, with how many of its files were still unpublished + /// temporary files. + Batch(usize), + } + + impl Recorder { + fn record(&self, call: Call) { + self.calls.lock().unwrap().push(call); + } + + fn take(&self) -> Vec { + std::mem::take(&mut self.calls.lock().unwrap()) + } + } + + impl Durability for Recorder { + fn sync_dir(&self, dir: &Path) -> io::Result<()> { + self.record(Call::Dir(dir.to_owned())); + Ok(()) + } + + fn sync_batch<'f>(&self, files: impl IntoIterator) -> Result<(), Error> { + if self.fail_batches { + let source = io::Error::other("batch failed"); + return Err(Error::new(Op::Sync, Path::new("batch"), source)); + } + let unpublished = files.into_iter().filter(|temp| temp.exists()).count(); + self.record(Call::Batch(unpublished)); + Ok(()) + } + } + + /// The names in `dir`, sorted. + fn names(dir: &Path) -> Vec { + let mut names: Vec<_> = fs::read_dir(dir) + .unwrap() + .map(|entry| entry.unwrap().file_name().into_string().unwrap()) + .collect(); + names.sort(); + names + } + + #[test] + fn syncs_the_batch_before_publishing_and_each_directory_once() { + let root = tempfile::tempdir().unwrap(); + let root = root.path(); + fs::create_dir(root.join("a")).unwrap(); + let recorder = Recorder::default(); + let write = DurableWrite::new(&recorder); + + write.stage(root.join("a/1"), b"one").unwrap(); + write.stage(root.join("a/2"), b"two").unwrap(); + assert_eq!(recorder.take(), [], "staging syncs nothing"); + write.stage(root.join("b/c/3"), b"three").unwrap(); + assert_eq!( + recorder.take(), + [ + Call::Dir(root.parent().unwrap().to_owned()), + Call::Dir(root.to_owned()), + Call::Dir(root.join("b")) + ], + "but the directories it creates, at once, after the one holding \ + the directory they're created in" + ); + let staged = names(&root.join("a")); + assert_eq!(staged.len(), 2); + assert!( + staged + .iter() + .all(|name| DurableWrite::::is_temporary(name.as_ref())), + "files are staged beside their destination, under temporary names: {staged:?}" + ); + + write.commit().unwrap(); + assert_eq!( + recorder.take(), + [ + Call::Batch(3), + Call::Dir(root.to_owned()), + Call::Dir(root.join("a")), + Call::Dir(root.join("b/c")), + ], + "the whole batch is synced before any file is renamed, then each \ + changed directory once, and the one holding `a`, which it found" + ); + assert_eq!(fs::read(root.join("a/1")).unwrap(), b"one"); + assert_eq!(fs::read(root.join("b/c/3")).unwrap(), b"three"); + assert_eq!( + names(&root.join("a")), + ["1", "2"], + "no temporary file is left" + ); + assert_eq!(names(&root.join("b/c")), ["3"]); + } + + #[test] + fn directories_stay_durable_when_their_write_is_abandoned() { + let root = tempfile::tempdir().unwrap(); + let recorder = Recorder::default(); + let abandoned = DurableWrite::new(&recorder); + abandoned + .stage(root.path().join("new/file"), b"old") + .unwrap(); + drop(abandoned); + assert_eq!( + recorder.take(), + [ + Call::Dir(root.path().parent().unwrap().to_owned()), + Call::Dir(root.path().to_owned()) + ] + ); + } + + #[test] + fn writes_into_a_directory_another_made_sync_what_holds_it() { + // Another write created `new`, and may not have synced `root` yet. + let root = tempfile::tempdir().unwrap(); + let root = root.path(); + fs::create_dir(root.join("new")).unwrap(); + let recorder = Recorder::default(); + let write = DurableWrite::new(&recorder); + write.stage(root.join("new/file"), b"file").unwrap(); + assert_eq!(recorder.take(), []); + write.stage(root.join("new/sub/file"), b"deeper").unwrap(); + assert_eq!( + recorder.take(), + [Call::Dir(root.to_owned()), Call::Dir(root.join("new"))], + "before creating a directory in it" + ); + write.commit().unwrap(); + assert_eq!( + recorder.take(), + [ + Call::Batch(2), + Call::Dir(root.to_owned()), + Call::Dir(root.join("new")), + Call::Dir(root.join("new/sub")), + ], + "or with the batch" + ); + } + + #[test] + fn a_failed_batch_sync_publishes_nothing() { + let root = tempfile::tempdir().unwrap(); + let recorder = Recorder { + fail_batches: true, + ..Recorder::default() + }; + let write = DurableWrite::new(&recorder); + write.stage(root.path().join("file"), b"contents").unwrap(); + + assert_eq!(write.commit().unwrap_err().op, Op::Sync); + assert_eq!(names(root.path()), Vec::::new(), "nothing is left"); + assert_eq!(recorder.take(), [], "no directory is synced"); + } + + #[test] + fn replaces_existing_files() { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("head"); + fs::write(&path, b"old").unwrap(); + let recorder = Recorder::default(); + let write = DurableWrite::new(&recorder); + write.stage(&path, b"new").unwrap(); + write.commit().unwrap(); + assert_eq!(fs::read(&path).unwrap(), b"new"); + } + + #[test] + fn dropping_an_uncommitted_write_publishes_nothing() { + let root = tempfile::tempdir().unwrap(); + let recorder = Recorder::default(); + let write = DurableWrite::new(&recorder); + write.stage(root.path().join("file"), b"contents").unwrap(); + drop(write); + + assert_eq!(names(root.path()), Vec::::new(), "nothing is left"); + assert_eq!(recorder.take(), []); + } +} diff --git a/crates/origin-platform/src/error.rs b/crates/origin-platform/src/error.rs new file mode 100644 index 00000000..7d28fe63 --- /dev/null +++ b/crates/origin-platform/src/error.rs @@ -0,0 +1,58 @@ +use std::fmt; +use std::io; +use std::path::{Path, PathBuf}; + +/// A file operation that failed, and the path it failed on. +#[derive(Debug, thiserror::Error)] +#[error("cannot {op} {}", path.display())] +pub struct Error { + /// What was being done. + pub op: Op, + /// The file or directory involved. + pub path: PathBuf, + /// The underlying error. + pub source: io::Error, +} + +impl Error { + pub(crate) fn new(op: Op, path: &Path, source: io::Error) -> Self { + Self { + op, + path: path.to_owned(), + source, + } + } +} + +/// The operations an [`Error`] can come from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Op { + /// Creating a directory. + CreateDir, + /// Opening a file. + Open, + /// Writing a temporary file. + Write, + /// Syncing a file or directory to stable storage. + Sync, + /// Renaming a file into place. + Publish, + /// Locking a file. + Lock, + /// Finding out which file system holds a path. + Inspect, +} + +impl fmt::Display for Op { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::CreateDir => "create directory", + Self::Open => "open", + Self::Write => "write", + Self::Sync => "sync", + Self::Publish => "publish", + Self::Lock => "lock", + Self::Inspect => "inspect the file system of", + }) + } +} diff --git a/crates/origin-platform/src/file_system.rs b/crates/origin-platform/src/file_system.rs new file mode 100644 index 00000000..972449d3 --- /dev/null +++ b/crates/origin-platform/src/file_system.rs @@ -0,0 +1,74 @@ +use std::io; +use std::path::{Path, PathBuf}; + +use crate::{Error, Op}; + +/// Tells local file systems from network ones, which origin refuses to +/// write to: they lose locks and reorder or drop syncs, so a repository on +/// one can be corrupted by a crash or a concurrent writer. +/// +/// Sync services such as Dropbox and iCloud Drive keep their folders on a +/// local file system and replace files behind origin's back. Nothing in +/// `statfs` tells them apart, and origin doesn't guess from paths, so a +/// repository there is accepted. +pub trait FileSystem { + /// The kind of file system holding `path`, which must exist. + /// + /// # Errors + /// + /// Fails if `path` cannot be inspected. + fn file_system(&self, path: &Path) -> io::Result; + + /// Checks that the repository at `path` may be opened for writing: + /// refuses network file systems, and accepts the ones the platform + /// cannot identify. + /// + /// # Errors + /// + /// Fails with [`WritableError::Network`] on a network file system, and + /// [`WritableError::Io`] if `path` cannot be inspected. + fn check_writable(&self, path: &Path) -> Result<(), WritableError> { + let kind = self + .file_system(path) + .map_err(|source| Error::new(Op::Inspect, path, source))?; + match kind { + FsKind::Network(name) => Err(WritableError::Network { + path: path.to_owned(), + name, + }), + FsKind::Local | FsKind::Unknown(_) => Ok(()), + } + } +} + +/// What a file system is, as far as the platform can tell. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FsKind { + /// A disk attached to this machine. + Local, + /// A file system served by another machine, by name, such as `NFS`. + Network(&'static str), + /// A file system that could be either, such as FUSE, which serves + /// sshfs as well as local disks. + Unknown(&'static str), +} + +/// A repository that cannot be opened for writing. +#[derive(Debug, thiserror::Error)] +pub enum WritableError { + /// The repository is on a network file system. + #[error( + "{} is on {name}, a network file system; origin writes only to local \ + disks, so clone the repository to one and use this one as a remote", + path.display() + )] + Network { + /// The repository. + path: PathBuf, + /// The file system's name. + name: &'static str, + }, + /// The file system holding the repository cannot be inspected. + #[error(transparent)] + Io(#[from] Error), +} diff --git a/crates/origin-platform/src/lib.rs b/crates/origin-platform/src/lib.rs new file mode 100644 index 00000000..a81545d8 --- /dev/null +++ b/crates/origin-platform/src/lib.rs @@ -0,0 +1,31 @@ +//! File operations that differ between platforms: durable writes, file +//! locks, copy-on-write clones, and telling local file systems from network +//! ones. +//! +//! Each operation is a trait. Every supported platform implements them in its +//! own module under [`native`], and [`Native`] picks the one for the build +//! target. That selection is the only conditional compilation in origin. +//! Windows is not supported. +//! +//! Code that needs the platform takes a `P: Platform` (or one of its traits), +//! so tests can substitute an implementation that records or fails calls. + +mod clone; +mod durability; +mod error; +mod file_system; +mod lock; +pub mod native; + +pub use clone::{CloneError, CloneFile}; +pub use durability::{Durability, DurableWrite}; +pub use error::{Error, Op}; +pub use file_system::{FileSystem, FsKind, WritableError}; +pub use lock::{FileLock, LockMode, LockedFile}; +pub use native::Native; + +/// Everything origin needs from the platform it runs on, shared by all the +/// threads of a process. +pub trait Platform: Durability + FileLock + CloneFile + FileSystem + Send + Sync {} + +impl Platform for T {} diff --git a/crates/origin-platform/src/lock.rs b/crates/origin-platform/src/lock.rs new file mode 100644 index 00000000..5123df90 --- /dev/null +++ b/crates/origin-platform/src/lock.rs @@ -0,0 +1,112 @@ +use std::fs::{File, OpenOptions, TryLockError}; +use std::io; +use std::ops::Deref; +use std::path::Path; + +use crate::{Error, Op}; + +/// Advisory locks on whole files. +/// +/// A lock belongs to an open file and is released when that file is closed, +/// which the kernel also does when the process dies, so a crash never leaves +/// a stale lock behind. Two opens of the same path conflict even within one +/// process. The default methods use the standard library's locks. +pub trait FileLock { + /// Blocks until `file` is locked in `mode`. + /// + /// # Errors + /// + /// Fails if the file system cannot lock the file. + fn lock(&self, file: &File, mode: LockMode) -> io::Result<()> { + match mode { + LockMode::Shared => file.lock_shared(), + LockMode::Exclusive => file.lock(), + } + } + + /// Locks `file` in `mode` unless another holder conflicts, returning + /// whether it did. + /// + /// # Errors + /// + /// Fails if the file system cannot lock the file. + fn try_lock(&self, file: &File, mode: LockMode) -> io::Result { + let result = match mode { + LockMode::Shared => file.try_lock_shared(), + LockMode::Exclusive => file.try_lock(), + }; + match result { + Ok(()) => Ok(true), + Err(TryLockError::WouldBlock) => Ok(false), + Err(TryLockError::Error(error)) => Err(error), + } + } +} + +/// How a lock is shared. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LockMode { + /// Any number of shared holders, and no exclusive one. + Shared, + /// A single holder. + Exclusive, +} + +/// A file opened and locked, until it's dropped. +/// +/// Lock a file that is never replaced: renaming another file over the path +/// leaves the lock on the old file, so later openers would not conflict. +#[derive(Debug)] +pub struct LockedFile(File); + +impl LockedFile { + /// Opens `path` for reading and writing, creating it if needed, and + /// blocks until it's locked in `mode`. + /// + /// # Errors + /// + /// Fails if the file cannot be opened or locked. + pub fn open(platform: &impl FileLock, path: &Path, mode: LockMode) -> Result { + let file = Self::open_file(path)?; + platform + .lock(&file, mode) + .map_err(|source| Error::new(Op::Lock, path, source))?; + Ok(Self(file)) + } + + /// Opens `path` like [`LockedFile::open`], but returns `None` instead of + /// waiting when another holder conflicts. + /// + /// # Errors + /// + /// Fails if the file cannot be opened or locked. + pub fn try_open( + platform: &impl FileLock, + path: &Path, + mode: LockMode, + ) -> Result, Error> { + let file = Self::open_file(path)?; + let locked = platform + .try_lock(&file, mode) + .map_err(|source| Error::new(Op::Lock, path, source))?; + Ok(locked.then_some(Self(file))) + } + + fn open_file(path: &Path) -> Result { + OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(path) + .map_err(|source| Error::new(Op::Open, path, source)) + } +} + +impl Deref for LockedFile { + type Target = File; + + fn deref(&self) -> &File { + &self.0 + } +} diff --git a/crates/origin-platform/src/native/linux.rs b/crates/origin-platform/src/native/linux.rs new file mode 100644 index 00000000..f82f4b64 --- /dev/null +++ b/crates/origin-platform/src/native/linux.rs @@ -0,0 +1,110 @@ +//! Linux: `fdatasync` and `fsync`, `syncfs` for batches, `flock`, clones with +//! the `FICLONE` ioctl (Btrfs, XFS, bcachefs), and file systems told apart by +//! their `statfs` magic number. + +use std::fs::File; +use std::io::{self, ErrorKind}; +use std::path::Path; + +use crate::{CloneFile, Durability, Error, FileLock, FileSystem, FsKind, Op}; + +/// The Linux implementation of [`Platform`](crate::Platform). +#[derive(Clone, Copy, Debug, Default)] +pub struct Linux; + +impl Linux { + /// The file system has no clone ioctl at all. + const ENOTTY: i32 = 25; + + /// The magic number every FUSE file system reports. + const FUSE: u32 = 0x6573_5546; + + /// Network file systems by magic number, from `linux/magic.h` and the + /// file systems' own sources. + const NETWORK: [(u32, &str); 11] = [ + (0x6969, "NFS"), + (0x517B, "SMB"), + (0xFF53_4D42, "CIFS"), + (0xFE53_4D42, "SMB2"), + (0x0102_1997, "9p"), + (0x5346_414F, "AFS"), + (0x6B41_4653, "kAFS"), + (0x00C3_6400, "Ceph"), + (0x7375_7245, "Coda"), + (0x0BD0_0BD0, "Lustre"), + (0x4750_4653, "GPFS"), + ]; + + /// Classifies a file system by its magic number. Any file system not + /// known to be networked is local, except FUSE: sshfs and local disks + /// served through it share one magic number. + fn classify(magic: u32) -> FsKind { + if magic == Self::FUSE { + return FsKind::Unknown("FUSE"); + } + Self::NETWORK + .iter() + .find(|(network, _)| *network == magic) + .map_or(FsKind::Local, |(_, name)| FsKind::Network(name)) + } +} + +impl Durability for Linux { + /// One `syncfs` of the file system holding the files, which costs about + /// as much as two `fdatasync`s however many files there are. A single + /// file is synced on its own, which is cheaper. + /// + /// `syncfs` also waits for every other process's unwritten data on that + /// file system, so a busy disk slows it down. + fn sync_batch<'f>(&self, files: impl IntoIterator) -> Result<(), Error> { + let mut files = files.into_iter(); + let Some(path) = files.next() else { + return Ok(()); + }; + let file = File::open(path).map_err(|source| Error::new(Op::Open, path, source))?; + let synced = if files.next().is_none() { + self.sync_file(&file) + } else { + rustix::fs::syncfs(&file).map_err(io::Error::from) + }; + synced.map_err(|source| Error::new(Op::Sync, path, source)) + } +} + +impl FileLock for Linux {} + +impl CloneFile for Linux { + /// `FICLONE` reports `EOPNOTSUPP` on file systems that cannot clone, + /// `EXDEV` across file systems, `EINVAL` when the file system cannot + /// clone these particular files, and `ENOTTY` without the ioctl. + fn cannot_clone(&self, error: &io::Error) -> bool { + matches!( + error.kind(), + ErrorKind::Unsupported | ErrorKind::CrossesDevices | ErrorKind::InvalidInput + ) || error.raw_os_error() == Some(Self::ENOTTY) + } +} + +impl FileSystem for Linux { + /// Magic numbers are 32 bits wide, in a field as wide as a pointer: one + /// that doesn't fit is no file system origin knows. + fn file_system(&self, path: &Path) -> io::Result { + let stat = rustix::fs::statfs(path)?; + Ok(u32::try_from(stat.f_type).map_or(FsKind::Unknown("unrecognized"), Self::classify)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn classifies_file_systems_by_magic_number() { + assert_eq!(Linux::classify(0xEF53), FsKind::Local, "ext4"); + assert_eq!(Linux::classify(0x9123_683E), FsKind::Local, "Btrfs"); + assert_eq!(Linux::classify(0x6969), FsKind::Network("NFS")); + assert_eq!(Linux::classify(0xFE53_4D42), FsKind::Network("SMB2")); + assert_eq!(Linux::classify(0x0102_1997), FsKind::Network("9p")); + assert_eq!(Linux::classify(0x6573_5546), FsKind::Unknown("FUSE")); + } +} diff --git a/crates/origin-platform/src/native/macos.rs b/crates/origin-platform/src/native/macos.rs new file mode 100644 index 00000000..6e4b0907 --- /dev/null +++ b/crates/origin-platform/src/native/macos.rs @@ -0,0 +1,96 @@ +//! macOS: `F_FULLFSYNC`, which also flushes the drive's cache, `flock`, +//! clones with `clonefile` (APFS), and file systems told apart by their +//! `statfs` type name. + +use std::fs::File; +use std::io::{self, ErrorKind}; +use std::path::Path; + +use crate::{CloneFile, Durability, Error, FileLock, FileSystem, FsKind, Op}; + +/// The macOS implementation of [`Platform`](crate::Platform). +#[derive(Clone, Copy, Debug, Default)] +pub struct MacOs; + +impl MacOs { + /// The file system cannot clone. The standard library leaves this code + /// uncategorized, since it differs from `EOPNOTSUPP` on macOS. + const ENOTSUP: i32 = 45; + + /// Network file systems by type name. + const NETWORK: [(&str, &str); 4] = [ + ("nfs", "NFS"), + ("smbfs", "SMB"), + ("afpfs", "AFP"), + ("webdav", "WebDAV"), + ]; + + /// The type names of macFUSE, which serves sshfs as well as local disks. + const FUSE: [&str; 3] = ["macfuse", "osxfuse", "osxfusefs"]; + + /// Classifies a file system by its type name. Any file system not known + /// to be networked is local, except FUSE. + fn classify(name: &[u8]) -> FsKind { + if Self::FUSE.iter().any(|fuse| fuse.as_bytes() == name) { + return FsKind::Unknown("macFUSE"); + } + Self::NETWORK + .iter() + .find(|(network, _)| network.as_bytes() == name) + .map_or(FsKind::Local, |(_, display)| FsKind::Network(display)) + } +} + +impl Durability for MacOs { + /// A plain `fsync` of each file, which hands its data to the drive + /// without flushing the drive's cache, then a single `F_FULLFSYNC` that + /// flushes the cache for all of them, as SQLite does. + fn sync_batch<'f>(&self, files: impl IntoIterator) -> Result<(), Error> { + let mut last = None; + for path in files { + let file = File::open(path).map_err(|source| Error::new(Op::Open, path, source))?; + rustix::fs::fsync(&file).map_err(|errno| Error::new(Op::Sync, path, errno.into()))?; + last = Some((file, path)); + } + let Some((file, path)) = last else { + return Ok(()); + }; + rustix::fs::fcntl_fullfsync(&file).map_err(|errno| Error::new(Op::Sync, path, errno.into())) + } +} + +impl FileLock for MacOs {} + +impl CloneFile for MacOs { + /// `clonefile` reports `ENOTSUP` on file systems that cannot clone and + /// `EXDEV` across volumes. + fn cannot_clone(&self, error: &io::Error) -> bool { + matches!( + error.kind(), + ErrorKind::Unsupported | ErrorKind::CrossesDevices + ) || error.raw_os_error() == Some(Self::ENOTSUP) + } +} + +impl FileSystem for MacOs { + /// The type name is a NUL-terminated C string. + fn file_system(&self, path: &Path) -> io::Result { + let stat = rustix::fs::statfs(path)?; + let name = stat.f_fstypename.map(|c| c.to_ne_bytes()[0]); + let len = name.iter().position(|&b| b == 0).unwrap_or(name.len()); + Ok(Self::classify(&name[..len])) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn classifies_file_systems_by_type_name() { + assert_eq!(MacOs::classify(b"apfs"), FsKind::Local); + assert_eq!(MacOs::classify(b"smbfs"), FsKind::Network("SMB")); + assert_eq!(MacOs::classify(b"nfs"), FsKind::Network("NFS")); + assert_eq!(MacOs::classify(b"macfuse"), FsKind::Unknown("macFUSE")); + } +} diff --git a/crates/origin-platform/src/native/mod.rs b/crates/origin-platform/src/native/mod.rs new file mode 100644 index 00000000..b65c611e --- /dev/null +++ b/crates/origin-platform/src/native/mod.rs @@ -0,0 +1,16 @@ +//! The implementations of the platform traits, one module per supported +//! platform. Each calls its platform's own system calls, so only the one for +//! the build target is compiled. + +cfg_select! { + target_os = "linux" => { + pub mod linux; + /// The platform origin was built for. + pub type Native = linux::Linux; + } + target_os = "macos" => { + pub mod macos; + /// The platform origin was built for. + pub type Native = macos::MacOs; + } +} diff --git a/crates/origin-platform/tests/conformance.rs b/crates/origin-platform/tests/conformance.rs new file mode 100644 index 00000000..c9ada34c --- /dev/null +++ b/crates/origin-platform/tests/conformance.rs @@ -0,0 +1,237 @@ +//! The conformance suite every [`Platform`] must pass, run against the one +//! built for this target. + +use origin_platform::Native; + +/// Runs each test of the suite against a platform. +macro_rules! conformance { + ($platform:expr; $($test:ident),* $(,)?) => { + $( + #[test] + fn $test() { + suite::$test(&$platform); + } + )* + }; +} + +conformance!( + Native::default(); + batches_survive_reopen, + empty_batches_succeed, + syncing_a_missing_directory_fails, + syncing_a_missing_file_in_a_batch_fails, + exclusive_locks_exclude_everyone, + shared_locks_coexist, + blocking_locks_wait_for_release, + locks_are_released_when_the_holder_dies, + clones_are_independent_or_unsupported, + clone_failures_are_not_unsupported, + temp_dirs_are_local, + inspecting_a_missing_path_fails, +); + +mod suite { + use std::env; + use std::fs; + use std::io::{self, BufRead, BufReader}; + use std::path::Path; + use std::process::{Command, Stdio}; + use std::sync::mpsc; + use std::thread; + use std::time::Duration; + + use origin_platform::{ + CloneError, DurableWrite, Error, FsKind, LockMode, LockedFile, Op, Platform, WritableError, + }; + + /// Stages a batch from several threads, large enough to be renamed from + /// several too, then reads it back through fresh opens once the write is + /// gone. + pub fn batches_survive_reopen(platform: &impl Platform) { + let root = tempfile::tempdir().unwrap(); + let path = |file: usize| root.path().join(format!("objects/{:02x}/{file}", file % 4)); + let files: Vec = (0..512).collect(); + let write = DurableWrite::new(platform); + thread::scope(|scope| { + for chunk in files.chunks(128) { + let write = &write; + scope.spawn(move || { + for &file in chunk { + write + .stage(path(file), file.to_string().as_bytes()) + .unwrap(); + } + }); + } + }); + write.commit().unwrap(); + + for &file in &files { + assert_eq!(fs::read(path(file)).unwrap(), file.to_string().as_bytes()); + } + let published = fs::read_dir(root.path().join("objects")) + .unwrap() + .flat_map(|shard| fs::read_dir(shard.unwrap().path()).unwrap()) + .count(); + assert_eq!(published, files.len(), "no temporary file is left"); + } + + pub fn empty_batches_succeed(platform: &impl Platform) { + DurableWrite::new(platform).commit().unwrap(); + } + + pub fn syncing_a_missing_directory_fails(platform: &impl Platform) { + let root = tempfile::tempdir().unwrap(); + let error = platform.sync_dir(&root.path().join("missing")).unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::NotFound); + } + + pub fn syncing_a_missing_file_in_a_batch_fails(platform: &impl Platform) { + let root = tempfile::tempdir().unwrap(); + let missing = root.path().join("missing"); + let error = platform.sync_batch([missing.as_path()]).unwrap_err(); + assert_eq!(error.path, missing); + assert_eq!(error.source.kind(), io::ErrorKind::NotFound); + } + + pub fn exclusive_locks_exclude_everyone(platform: &impl Platform) { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("lock"); + let held = LockedFile::open(platform, &path, LockMode::Exclusive).unwrap(); + for mode in [LockMode::Exclusive, LockMode::Shared] { + let other = LockedFile::try_open(platform, &path, mode).unwrap(); + assert!(other.is_none(), "{mode:?} lock taken while held"); + } + drop(held); + assert!( + LockedFile::try_open(platform, &path, LockMode::Exclusive) + .unwrap() + .is_some() + ); + } + + pub fn shared_locks_coexist(platform: &impl Platform) { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("lock"); + let _first = LockedFile::open(platform, &path, LockMode::Shared).unwrap(); + let second = LockedFile::try_open(platform, &path, LockMode::Shared).unwrap(); + assert!(second.is_some()); + let exclusive = LockedFile::try_open(platform, &path, LockMode::Exclusive).unwrap(); + assert!(exclusive.is_none()); + } + + pub fn blocking_locks_wait_for_release(platform: &impl Platform) { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("lock"); + let held = LockedFile::open(platform, &path, LockMode::Exclusive).unwrap(); + let (locked, waiter) = mpsc::channel(); + thread::scope(|scope| { + scope.spawn(|| { + let _lock = LockedFile::open(platform, &path, LockMode::Exclusive).unwrap(); + locked.send(()).unwrap(); + }); + assert!( + waiter.recv_timeout(Duration::from_millis(100)).is_err(), + "locked while held" + ); + drop(held); + waiter + .recv_timeout(Duration::from_secs(10)) + .expect("still waiting after release"); + }); + } + + /// Set in the child process that holds the lock, to the lock's path. + const HOLDER: &str = "ORIGIN_TEST_LOCK_HOLDER"; + /// What the child prints once it holds the lock. + const HELD: &str = "origin: lock held"; + + /// Reruns this test binary as a child that holds a lock, then kills it + /// as a crash would. + pub fn locks_are_released_when_the_holder_dies(platform: &impl Platform) { + if let Some(path) = env::var_os(HOLDER) { + let _held = LockedFile::open(platform, Path::new(&path), LockMode::Exclusive).unwrap(); + println!("{HELD}"); + // Bounded, so the child cannot outlive a failed parent for long. + thread::sleep(Duration::from_secs(60)); + return; + } + + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("lock"); + let mut child = Command::new(env::current_exe().unwrap()) + .args(["locks_are_released_when_the_holder_dies", "--nocapture"]) + .env(HOLDER, &path) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + let output = BufReader::new(child.stdout.take().unwrap()); + assert!( + output.lines().any(|line| line.unwrap() == HELD), + "the child never held the lock" + ); + let other = LockedFile::try_open(platform, &path, LockMode::Exclusive).unwrap(); + assert!(other.is_none(), "locked while the child holds it"); + + child.kill().unwrap(); + child.wait().unwrap(); + let other = LockedFile::try_open(platform, &path, LockMode::Exclusive).unwrap(); + assert!(other.is_some(), "the lock outlived its holder"); + } + + /// Clones where the test's file system can, and reports it can't + /// otherwise. + pub fn clones_are_independent_or_unsupported(platform: &impl Platform) { + let root = tempfile::tempdir().unwrap(); + let (from, to) = (root.path().join("from"), root.path().join("to")); + fs::write(&from, b"original").unwrap(); + match platform.clone_file(&from, &to) { + Ok(()) => { + assert_eq!(fs::read(&to).unwrap(), b"original"); + fs::write(&to, b"changed").unwrap(); + assert_eq!(fs::read(&from).unwrap(), b"original"); + } + Err(CloneError::Unsupported { .. }) => { + assert!(!to.exists(), "a failed clone left a file behind"); + } + Err(error) => panic!("{error}: {error:?}"), + } + } + + /// Callers copy on `Unsupported`, which must not hide real failures. + pub fn clone_failures_are_not_unsupported(platform: &impl Platform) { + let root = tempfile::tempdir().unwrap(); + let (from, to) = (root.path().join("from"), root.path().join("to")); + let error = platform.clone_file(&from, &to).unwrap_err(); + assert!( + matches!(error, CloneError::Io { .. }), + "missing source: {error}" + ); + + fs::write(&from, b"new").unwrap(); + fs::write(&to, b"existing").unwrap(); + let error = platform.clone_file(&from, &to).unwrap_err(); + assert!( + matches!(error, CloneError::Io { .. }), + "existing target: {error}" + ); + assert_eq!(fs::read(&to).unwrap(), b"existing"); + } + + pub fn temp_dirs_are_local(platform: &impl Platform) { + let root = tempfile::tempdir().unwrap(); + assert_eq!(platform.file_system(root.path()).unwrap(), FsKind::Local); + platform.check_writable(root.path()).unwrap(); + } + + pub fn inspecting_a_missing_path_fails(platform: &impl Platform) { + let root = tempfile::tempdir().unwrap(); + let missing = root.path().join("missing"); + let error = platform.check_writable(&missing).unwrap_err(); + assert!( + matches!(error, WritableError::Io(Error { op: Op::Inspect, ref path, .. }) if *path == missing), + "{error:?}" + ); + } +} diff --git a/justfile b/justfile index cdee18fb..f36de0df 100644 --- a/justfile +++ b/justfile @@ -27,3 +27,7 @@ doc-test: deny: @cargo deny check + +# Micro-benchmarks of the hot paths (hashing, storage). +bench *ARGS: + @cargo bench --locked --workspace -- {{ARGS}}