Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 15 additions & 12 deletions crates/origin-platform/benches/platform.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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<PathBuf> {
let objects = dir.path().join("objects");
let mut write = 0;
Expand All @@ -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();
Expand All @@ -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();
Expand All @@ -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();
Expand All @@ -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();
Expand All @@ -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();
Expand Down
23 changes: 12 additions & 11 deletions crates/origin-platform/src/clone.rs
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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.
Expand Down
133 changes: 65 additions & 68 deletions crates/origin-platform/src/durability.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
///
Expand All @@ -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
///
Expand All @@ -48,25 +49,22 @@ pub trait Durability {
fn sync_batch<'f>(&self, files: impl IntoIterator<Item = &'f Path>) -> 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)]
Expand All @@ -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<PathBuf>,
/// Files written in place, synced with the batch but never renamed.
/// Files written in place: synced with the batch, never renamed.
in_place: Vec<PathBuf>,
}

/// 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<P> DurableWrite<'_, P> {
/// How temporary file names start: `.tmp-<pid>-<n>`.
/// The prefix of temporary file names, which are `.tmp-<pid>-<n>`.
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()
Expand All @@ -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
///
Expand All @@ -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<E: From<Error>>(
&self,
path: impl Into<PathBuf>,
Expand All @@ -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<PathBuf>) {
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<PathBuf>) {
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<Option<PathBuf>, Error> {
let mut missing = Vec::new();
let mut dir = Self::parent(path);
Expand Down Expand Up @@ -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() {
Expand All @@ -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))
}
Expand All @@ -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
Expand All @@ -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)| {
Expand Down Expand Up @@ -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<E: From<Error>>(
temp: &Path,
write: impl FnOnce(&mut Self) -> Result<(), E>,
Expand Down Expand Up @@ -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<Vec<Call>>,
Expand All @@ -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),
}

Expand Down Expand Up @@ -397,7 +394,7 @@ mod tests {
}
}

/// The names in `dir`, sorted.
/// Returns the names in `dir`, sorted.
fn names(dir: &Path) -> Vec<String> {
let mut names: Vec<_> = fs::read_dir(dir)
.unwrap()
Expand Down
Loading
Loading