diff --git a/crates/origin-platform/benches/platform.rs b/crates/origin-platform/benches/platform.rs index 43cda408..a4d09cd4 100644 --- a/crates/origin-platform/benches/platform.rs +++ b/crates/origin-platform/benches/platform.rs @@ -1,5 +1,4 @@ -//! The cost of durability and locking on the native platform: what every -//! store write and target landing pays. +//! Benchmarks durable writes and file locks on the native platform. use std::path::PathBuf; use std::thread; @@ -12,11 +11,12 @@ fn main() { divan::main(); } -/// The size of a typical small record. +/// The contents of each benchmarked file: 512 bytes, 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. +/// Returns a generator of fresh paths for one durable write: `files` paths +/// 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; @@ -28,8 +28,8 @@ fn paths(dir: &tempfile::TempDir, files: usize, shards: usize) -> impl FnMut() - } } -/// Each file written durably on its own: a batch sync and a directory sync -/// per file. +/// Writes each file in a durable write of its own, which costs 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(); @@ -46,7 +46,8 @@ fn one_at_a_time(bencher: Bencher<'_, '_>, files: usize) { }); } -/// One group commit: a batch sync, and one for the directory. +/// Writes all the files in one durable write: one batch sync and one +/// directory sync. #[divan::bench(args = [1, 16, 128], sample_count = 10, sample_size = 1)] fn batched(bencher: Bencher<'_, '_>, files: usize) { let dir = tempfile::tempdir().unwrap(); @@ -63,8 +64,8 @@ fn batched(bencher: Bencher<'_, '_>, files: usize) { }); } -/// One group commit of files spread over 32 directories, like loose -/// objects. +/// Writes all the files in one durable write, 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(); @@ -81,7 +82,8 @@ fn batched_sharded(bencher: Bencher<'_, '_>, files: usize) { }); } -/// One group commit staged from 8 threads, which overlaps their writes. +/// Writes all the files in one durable write, staged from 8 threads at +/// once. #[divan::bench(args = [16, 128], sample_count = 10, sample_size = 1)] fn batched_parallel(bencher: Bencher<'_, '_>, files: usize) { let dir = tempfile::tempdir().unwrap(); @@ -105,7 +107,8 @@ fn batched_parallel(bencher: Bencher<'_, '_>, files: usize) { }); } -/// Taking and releasing an uncontended lock, as every landing does. +/// Takes and releases an uncontended exclusive lock, as every landing +/// does. #[divan::bench] fn lock(bencher: Bencher<'_, '_>) { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/origin-platform/src/clone.rs b/crates/origin-platform/src/clone.rs index 2b492aeb..0f1b227b 100644 --- a/crates/origin-platform/src/clone.rs +++ b/crates/origin-platform/src/clone.rs @@ -1,24 +1,25 @@ 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. +/// Makes 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`]. +/// Only some file systems can clone. Callers copy the file instead when a +/// clone fails with [`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. + /// Returns 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 with different error codes. 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. + /// Fails with [`CloneError::Unsupported`] if the file system cannot clone + /// these files, and with [`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 @@ -37,7 +38,7 @@ pub trait CloneFile { /// A clone that failed. #[derive(Debug, thiserror::Error)] pub enum CloneError { - /// The file system cannot clone these files. Copying them works instead. + /// The file system cannot clone these files. Copy them instead. #[error("the file system cannot clone {} to {}", from.display(), to.display())] Unsupported { /// The file to clone. diff --git a/crates/origin-platform/src/durability.rs b/crates/origin-platform/src/durability.rs index befef1ad..7213d831 100644 --- a/crates/origin-platform/src/durability.rs +++ b/crates/origin-platform/src/durability.rs @@ -12,11 +12,12 @@ use std::thread; use crate::{Error, Op}; -/// Flushes written data to stable storage, so it survives a crash or a power -/// loss. +/// 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. +/// platform's strongest sync. Each platform implements `sync_batch` its own +/// way. pub trait Durability { /// Flushes a file's contents, and the metadata needed to read them back. /// @@ -27,8 +28,8 @@ pub trait Durability { file.sync_data() } - /// Flushes a directory's entries, making the files created in, renamed - /// into or removed from it durable. + /// Flushes a directory's entries, so the files created in, renamed into or + /// removed from it survive a crash. /// /// # Errors /// @@ -48,25 +49,22 @@ pub trait Durability { 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 +/// Writes a group of files durably, at the cost of one batch sync plus 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. +/// destination's directory. [`DurableWrite::commit`] syncs them all with +/// [`Durability::sync_batch`], renames them into place and syncs their +/// directories. Readers see either the old file or the complete new one, +/// and once `commit` returns, a crash loses none of them. /// -/// Staging beside the destination keeps each rename within one directory, -/// so writes to different directories never contend on a shared one. +/// Dropping the write without committing removes its temporary files. A +/// crash leaves them behind, so code that lists a directory written this +/// way must skip the names [`DurableWrite::is_temporary`] recognizes, and +/// remove the stale ones. /// /// [`DurableWrite::sync_with`] adds a file written in place, such as an -/// append-only log, to the batch sync, so it becomes durable no later than -/// the batch is published, at no extra sync. +/// append-only log, to the batch sync. /// /// Files can be staged from several threads at once. #[derive(Debug)] @@ -78,29 +76,31 @@ pub struct DurableWrite<'a, P> { /// The files staged so far. #[derive(Debug, Default)] struct Staged { - /// Each temporary file and the path it's published to. + /// Each temporary file, and the path it is renamed to on commit. files: Vec<(PathBuf, PathBuf)>, - /// The directories whose entries must be durable: the published files' - /// parents, and those added with [`DurableWrite::sync_dir_with`]. + /// The directories to sync on commit: the staged files' parents, existing + /// directories this write relies on, and those added with + /// [`DurableWrite::sync_dir_with`]. dirs: BTreeSet, - /// Files written in place, synced with the batch but never renamed. + /// Files written in place: synced with the batch, never renamed. in_place: Vec, } -/// Distinguishes the temporary files of one process. +/// A counter that gives each temporary file of this process a unique +/// name. static NEXT_TEMP: AtomicU64 = AtomicU64::new(0); impl

DurableWrite<'_, P> { - /// How temporary file names start: `.tmp--`. + /// The prefix of temporary file names, which are `.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. + /// The fewest renames each thread of [`DurableWrite::commit`] handles. A + /// smaller batch is renamed on the current thread, since spawning threads + /// would cost 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. + /// Returns whether `name` is a temporary file's name: a file still being + /// written, or one left behind by a write that crashed. #[must_use] pub fn is_temporary(name: &OsStr) -> bool { name.as_encoded_bytes() @@ -117,16 +117,14 @@ impl<'a, P: Durability> DurableWrite<'a, P> { } } - /// 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. + /// Writes `contents` to a temporary file that replaces `path` on + /// [`DurableWrite::commit`]. Creates any missing parent directories. /// - /// 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. + /// The directories it creates are synced right away, so they stay durable + /// even if this write is never committed. An existing directory may not be + /// durable yet, since another write may have just created it, so the parent + /// of the deepest existing directory is synced too: right away if this + /// write creates directories in it, otherwise on commit. /// /// # Errors /// @@ -137,12 +135,12 @@ impl<'a, P: Durability> DurableWrite<'a, P> { } /// Stages `path` like [`DurableWrite::stage`], with the contents `write` - /// writes through a buffered [`StagedFile`], so a file never needs to - /// fit in memory. If `write` fails, nothing is staged. + /// writes through a buffered [`StagedFile`], so the file never has to fit + /// in memory. If `write` fails, nothing is staged. /// /// # Errors /// - /// Fails like [`DurableWrite::stage`], or with the error of `write`. + /// Fails like [`DurableWrite::stage`], or with the error `write` returns. pub fn stage_with>( &self, path: impl Into, @@ -168,30 +166,29 @@ impl<'a, P: Durability> DurableWrite<'a, P> { Ok(()) } - /// Makes the entries of `dir` durable with the batch, as for a file - /// staged in it: for a file another write published, which this one - /// relies on, and may not have synced yet. + /// Adds `dir` to the directories synced on commit. Use it for the + /// directory of a file another write published, which this one relies on + /// and which may not be synced yet. pub fn sync_dir_with(&self, dir: impl Into) { let mut staged = self.staged.lock().unwrap_or_else(PoisonError::into_inner); staged.dirs.insert(dir.into()); } - /// Makes `path`, a file already written in place, durable with the - /// batch: [`DurableWrite::commit`] syncs it with the staged files, before - /// publishing any of them. + /// Adds `path`, a file already written in place, to the batch sync: + /// [`DurableWrite::commit`] syncs it with the staged files, before renaming + /// any of them. pub fn sync_with(&self, path: impl Into) { let mut staged = self.staged.lock().unwrap_or_else(PoisonError::into_inner); staged.in_place.push(path.into()); } - /// Creates the missing parent directories of `path`, outermost first, - /// syncing the directory each is created in right after creating it. + /// Creates the missing parent directories of `path`, outermost first, and + /// syncs each one's parent 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. + /// The deepest existing directory may not be durable yet, so the directory + /// holding it is synced too: right away, before anything is created in it, + /// or, when nothing needs creating, returned for the commit to sync. + /// Returns `None` when nothing is left to sync. fn create_parents(&self, path: &Path) -> Result, Error> { let mut missing = Vec::new(); let mut dir = Self::parent(path); @@ -223,7 +220,7 @@ impl<'a, P: Durability> DurableWrite<'a, P> { Ok(None) } - /// The directory containing `path`, which is `.` for a bare file name. + /// Returns the directory containing `path`, or `.` for a bare file name. #[must_use] pub fn parent(path: &Path) -> &Path { match path.parent() { @@ -232,8 +229,8 @@ impl<'a, P: Durability> DurableWrite<'a, P> { } } - /// The directory holding the entry of the directory `dir`, unless it - /// can't be named: for `/`, or `.`. + /// Returns the directory holding the entry of the directory `dir`, or + /// `None` when it can't be named: for `/` and `.`. fn holder(dir: &Path) -> Option<&Path> { (dir != Path::new(".") && dir.parent().is_some()).then(|| Self::parent(dir)) } @@ -244,9 +241,9 @@ impl<'a, P: Durability> DurableWrite<'a, P> { /// /// # 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. + /// Fails if the batch sync fails, in which case no file is renamed, or if a + /// rename or a directory sync fails, in which case the files renamed before + /// it are visible but may not be durable. pub fn commit(mut self) -> Result<(), Error> { let staged = self .staged @@ -266,8 +263,8 @@ impl<'a, P: Durability> DurableWrite<'a, P> { Ok(()) } - /// Renames each temporary file to its path, spread over the cores. Each - /// rename locks its directory, and a batch usually spans many. + /// Renames each temporary file to its path, on several threads when there + /// are enough files to be worth it. fn rename_all(files: &[(PathBuf, PathBuf)]) -> Result<(), Error> { let rename = |files: &[(PathBuf, PathBuf)]| { files.iter().try_for_each(|(temp, path)| { @@ -320,7 +317,7 @@ pub struct StagedFile { } impl StagedFile { - /// Creates `temp` and fills it with `write`. + /// Creates `temp`, fills it with `write`, and flushes the buffer. fn write>( temp: &Path, write: impl FnOnce(&mut Self) -> Result<(), E>, @@ -354,8 +351,8 @@ impl StagedFile { mod tests { use super::*; - /// Records syncs instead of performing them, and fails batches when - /// asked to. + /// A `Durability` that records syncs instead of performing them, and fails + /// batch syncs when `fail_batches` is set. #[derive(Default)] struct Recorder { calls: Mutex>, @@ -365,8 +362,8 @@ mod tests { #[derive(Debug, PartialEq, Eq)] enum Call { Dir(PathBuf), - /// A batch sync, with how many of its files were still unpublished - /// temporary files. + /// A batch sync, with how many of its files existed when it ran: staged + /// files not yet renamed, or files written in place. Batch(usize), } @@ -397,7 +394,7 @@ mod tests { } } - /// The names in `dir`, sorted. + /// Returns the names in `dir`, sorted. fn names(dir: &Path) -> Vec { let mut names: Vec<_> = fs::read_dir(dir) .unwrap() diff --git a/crates/origin-platform/src/file_system.rs b/crates/origin-platform/src/file_system.rs index 972449d3..48e081ca 100644 --- a/crates/origin-platform/src/file_system.rs +++ b/crates/origin-platform/src/file_system.rs @@ -3,25 +3,23 @@ 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. +/// Tells local file systems from network ones. Origin refuses to write to +/// network file systems: they can lose locks and reorder or drop syncs, so +/// a crash or a concurrent writer can corrupt a repository on one. /// -/// 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. +/// Folders of sync services such as Dropbox and iCloud Drive are on a local +/// file system, so a repository there is accepted, even though the service +/// may replace files behind origin's back. pub trait FileSystem { - /// The kind of file system holding `path`, which must exist. + /// Returns 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. + /// Checks that the repository at `path` may be opened for writing. Refuses + /// network file systems, and accepts the ones the platform cannot identify. /// /// # Errors /// @@ -46,14 +44,15 @@ pub trait FileSystem { pub enum FsKind { /// A disk attached to this machine. Local, - /// A file system served by another machine, by name, such as `NFS`. + /// A file system served by another machine, with its 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. + /// A file system that may be local or networked, with its name. FUSE is + /// one: it serves sshfs as well as local disks. Unknown(&'static str), } -/// A repository that cannot be opened for writing. +/// Why a repository cannot be opened for writing. #[derive(Debug, thiserror::Error)] pub enum WritableError { /// The repository is on a network file system. @@ -63,7 +62,7 @@ pub enum WritableError { path.display() )] Network { - /// The repository. + /// The repository's path. path: PathBuf, /// The file system's name. name: &'static str, diff --git a/crates/origin-platform/src/lib.rs b/crates/origin-platform/src/lib.rs index aec0e893..af4583ac 100644 --- a/crates/origin-platform/src/lib.rs +++ b/crates/origin-platform/src/lib.rs @@ -2,13 +2,13 @@ //! locks, copy-on-write clones, positioned reads, 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. +//! Each operation is a trait. Each supported platform implements them in +//! its own module under [`native`], and [`Native`] is the one for the build +//! target. 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. +//! 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; @@ -26,8 +26,8 @@ pub use lock::{FileLock, LockMode, LockedFile}; pub use native::Native; pub use read::ReadAt; -/// Everything origin needs from the platform it runs on, shared by all the -/// threads of a process. +/// Everything origin needs from the platform it runs on. It is `Send` and +/// `Sync`, so all the threads of a process can share one. pub trait Platform: Durability + FileLock + CloneFile + FileSystem + ReadAt + Send + Sync {} impl Platform for T {} diff --git a/crates/origin-platform/src/lock.rs b/crates/origin-platform/src/lock.rs index 5123df90..4bb018cd 100644 --- a/crates/origin-platform/src/lock.rs +++ b/crates/origin-platform/src/lock.rs @@ -8,9 +8,9 @@ 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. +/// including when the process dies, so a crash never leaves a stale lock. +/// 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`. /// @@ -24,8 +24,8 @@ pub trait FileLock { } } - /// Locks `file` in `mode` unless another holder conflicts, returning - /// whether it did. + /// Locks `file` in `mode` unless another holder conflicts. Returns whether + /// it took the lock. /// /// # Errors /// @@ -46,16 +46,18 @@ pub trait FileLock { /// How a lock is shared. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum LockMode { - /// Any number of shared holders, and no exclusive one. + /// Shared with any number of other shared holders. Conflicts with an + /// exclusive one. Shared, - /// A single holder. + /// Held by one holder alone. Conflicts with any other lock. Exclusive, } -/// A file opened and locked, until it's dropped. +/// A file opened and locked until it is 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. +/// Only lock a file that is never replaced: if another file is renamed over +/// the path, the lock stays on the old file, and later openers don't +/// conflict with it. #[derive(Debug)] pub struct LockedFile(File); diff --git a/crates/origin-platform/src/native/linux.rs b/crates/origin-platform/src/native/linux.rs index 6b337cfc..f4ea4e95 100644 --- a/crates/origin-platform/src/native/linux.rs +++ b/crates/origin-platform/src/native/linux.rs @@ -1,6 +1,7 @@ -//! Linux: `fdatasync` and `fsync`, `syncfs` for large batches, `flock`, -//! clones with the `FICLONE` ioctl (Btrfs, XFS, bcachefs), `pread`, and file -//! systems told apart by their `statfs` magic number. +//! The Linux platform. It syncs with `fdatasync` and `fsync` (`syncfs` for +//! large batches), locks with `flock`, clones with the `FICLONE` ioctl +//! (Btrfs, XFS, bcachefs), reads with `pread`, and identifies file systems +//! by their `statfs` magic number. use std::fs::File; use std::io::{self, ErrorKind}; @@ -15,18 +16,18 @@ use crate::{CloneFile, Durability, Error, FileLock, FileSystem, FsKind, Op, Read pub struct Linux; impl Linux { - /// The most files a batch syncs each on its own, rather than with + /// The most files a batch syncs one by one. A larger batch uses a single /// `syncfs`. const SYNC_EACH: usize = 2; - /// The file system has no clone ioctl at all. + /// The `ENOTTY` error code: 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. + /// The magic numbers and names of network file systems, from + /// `linux/magic.h` and the file systems' own sources. const NETWORK: [(u32, &str); 11] = [ (0x6969, "NFS"), (0x517B, "SMB"), @@ -47,9 +48,9 @@ impl Linux { sync(&file).map_err(|source| Error::new(Op::Sync, path, source)) } - /// 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. + /// Classifies a file system by its magic number. FUSE is `Unknown`, since + /// sshfs and local disks served through it share one magic number. Known + /// network file systems are `Network`, and everything else is `Local`. fn classify(magic: u32) -> FsKind { if magic == Self::FUSE { return FsKind::Unknown("FUSE"); @@ -62,14 +63,14 @@ impl Linux { } 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. + /// Syncs a batch of up to two files by syncing each file, in parallel. + /// Syncs a larger batch with one `syncfs` of the file system holding the + /// first file, which costs about as much as two `fdatasync`s however many + /// files there are. /// - /// `syncfs` also waits for every other process's unwritten data on that - /// file system, so a busy disk slows it down. Batches of up to two - /// files, such as a record and the index log, sync each on its own - /// instead, all at once: a journaling file system commits them together, - /// for about the cost of one `fdatasync`. + /// `syncfs` also waits for other processes' unwritten data on that file + /// system, which is why small batches, such as a record and the index log, + /// sync each file instead. fn sync_batch<'f>(&self, files: impl IntoIterator) -> Result<(), Error> { let first: Vec<_> = files.into_iter().take(Self::SYNC_EACH + 1).collect(); let Some((&one, others)) = first.split_first() else { @@ -103,9 +104,10 @@ impl FileLock for Linux {} impl ReadAt 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. + /// Returns true for the errors `FICLONE` reports when it cannot clone: + /// `EOPNOTSUPP` (the file system cannot clone), `EXDEV` (across file + /// systems), `EINVAL` (it cannot clone these files) and `ENOTTY` (no clone + /// ioctl). fn cannot_clone(&self, error: &io::Error) -> bool { matches!( error.kind(), @@ -115,8 +117,8 @@ impl CloneFile for Linux { } 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. + /// Reads the magic number with `statfs`. A value that doesn't fit in 32 + /// bits is no known file system, so it is `Unknown`. 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)) diff --git a/crates/origin-platform/src/native/macos.rs b/crates/origin-platform/src/native/macos.rs index 9eafb778..b1d48768 100644 --- a/crates/origin-platform/src/native/macos.rs +++ b/crates/origin-platform/src/native/macos.rs @@ -1,6 +1,7 @@ -//! macOS: `F_FULLFSYNC`, which also flushes the drive's cache, `flock`, -//! clones with `clonefile` (APFS), `pread`, and file systems told apart by -//! their `statfs` type name. +//! The macOS platform. It syncs with `fsync` and `F_FULLFSYNC`, which also +//! flushes the drive's cache, locks with `flock`, clones with `clonefile` +//! (APFS), reads with `pread`, and identifies file systems by their +//! `statfs` type name. use std::fs::File; use std::io::{self, ErrorKind}; @@ -13,11 +14,12 @@ use crate::{CloneFile, Durability, Error, FileLock, FileSystem, FsKind, Op, Read pub struct MacOs; impl MacOs { - /// The file system cannot clone. The standard library leaves this code - /// uncategorized, since it differs from `EOPNOTSUPP` on macOS. + /// The `ENOTSUP` error code: the file system cannot clone. It differs from + /// `EOPNOTSUPP` on macOS, and the standard library leaves it + /// uncategorized. const ENOTSUP: i32 = 45; - /// Network file systems by type name. + /// The type names and display names of network file systems. const NETWORK: [(&str, &str); 4] = [ ("nfs", "NFS"), ("smbfs", "SMB"), @@ -28,8 +30,8 @@ impl MacOs { /// 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. + /// Classifies a file system by its type name. macFUSE is `Unknown`, known + /// network file systems are `Network`, and everything else is `Local`. fn classify(name: &[u8]) -> FsKind { if Self::FUSE.iter().any(|fuse| fuse.as_bytes() == name) { return FsKind::Unknown("macFUSE"); @@ -42,9 +44,9 @@ impl MacOs { } 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. + /// Syncs each file with a plain `fsync`, which hands its data to the drive + /// without flushing the drive's cache, then flushes the cache once for all + /// of them with `F_FULLFSYNC`, as SQLite does. fn sync_batch<'f>(&self, files: impl IntoIterator) -> Result<(), Error> { let mut last = None; for path in files { @@ -64,8 +66,8 @@ impl FileLock for MacOs {} impl ReadAt for MacOs {} impl CloneFile for MacOs { - /// `clonefile` reports `ENOTSUP` on file systems that cannot clone and - /// `EXDEV` across volumes. + /// Returns true for the errors `clonefile` reports when it cannot clone: + /// `ENOTSUP` (the file system cannot clone) and `EXDEV` (across volumes). fn cannot_clone(&self, error: &io::Error) -> bool { matches!( error.kind(), @@ -75,7 +77,8 @@ impl CloneFile for MacOs { } impl FileSystem for MacOs { - /// The type name is a NUL-terminated C string. + /// Reads the type name with `statfs`. The 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]); diff --git a/crates/origin-platform/src/native/mod.rs b/crates/origin-platform/src/native/mod.rs index b65c611e..551d0f9d 100644 --- a/crates/origin-platform/src/native/mod.rs +++ b/crates/origin-platform/src/native/mod.rs @@ -1,6 +1,5 @@ //! 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. +//! platform. Only the module for the build target is compiled. cfg_select! { target_os = "linux" => { diff --git a/crates/origin-platform/src/read.rs b/crates/origin-platform/src/read.rs index 00f65806..4166beb8 100644 --- a/crates/origin-platform/src/read.rs +++ b/crates/origin-platform/src/read.rs @@ -2,7 +2,7 @@ use std::fs::File; use std::io; use std::os::unix::fs::FileExt; -/// Reads at an offset without moving a file's cursor, so any number of +/// Reads at an offset without moving the file's cursor, so any number of /// threads can read one open file at once. /// /// The default method uses `pread`, which every supported platform has. diff --git a/crates/origin-platform/tests/conformance.rs b/crates/origin-platform/tests/conformance.rs index 7b1824e4..214b6f29 100644 --- a/crates/origin-platform/tests/conformance.rs +++ b/crates/origin-platform/tests/conformance.rs @@ -1,9 +1,10 @@ -//! The conformance suite every [`Platform`] must pass, run against the one -//! built for this target. +//! The conformance suite every [`Platform`] must pass, run against the +//! platform for this build target. use origin_platform::Native; -/// Runs each test of the suite against a platform. +/// Generates one `#[test]` per named test of the suite, each run against +/// the given platform. macro_rules! conformance { ($platform:expr; $($test:ident),* $(,)?) => { $( @@ -46,9 +47,9 @@ mod suite { 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. + /// Stages 512 files from several threads, enough for the commit to rename + /// them on several threads too, then checks that each file reads back and + /// that no temporary file is left. 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)); @@ -148,8 +149,8 @@ mod suite { /// 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. + /// Runs this test binary again as a child that holds a lock, kills the + /// child as a crash would, and checks that the lock is released. 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(); @@ -181,8 +182,9 @@ mod suite { assert!(other.is_some(), "the lock outlived its holder"); } - /// Clones where the test's file system can, and reports it can't - /// otherwise. + /// Clones a file and checks that the clone is independent of the + /// original. On a file system that cannot clone, checks that the clone + /// fails with `Unsupported` and leaves no file behind. 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")); @@ -200,7 +202,9 @@ mod suite { } } - /// Callers copy on `Unsupported`, which must not hide real failures. + /// Checks that a missing source or an existing target fails with `Io`, + /// not `Unsupported`: callers copy on `Unsupported`, which would hide the + /// failure. 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"));