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
4 changes: 4 additions & 0 deletions apps/origin-src/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -53,5 +53,9 @@ harness = false
name = "packs"
harness = false

[[bench]]
name = "workspace"
harness = false

[lints]
workspace = true
54 changes: 54 additions & 0 deletions apps/origin-src/benches/workspace.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
//! Checking a 20k-file tree out into an empty directory, durably, by
//! writing every file from the store.

use std::sync::LazyLock;

use divan::Bencher;
use divan::counter::ItemsCount;
use origin_platform::Native;
use origin_shared::{Record, Tree, TreeId};
use origin_src::fixture::FixtureTree;
use origin_src::store::Store;
use origin_src::tree::FileChange;
use origin_src::worktree::{StatCache, Worktree};

fn main() {
divan::main();
}

const TREE: FixtureTree = FixtureTree::LARGE;

/// The main working copy: the fixture, snapshotted.
struct Main {
dir: tempfile::TempDir,
/// Every file of the snapshot, as checking it out adds them.
changes: Vec<FileChange>,
}

static MAIN: LazyLock<Main> = LazyLock::new(|| {
let dir = tempfile::tempdir().unwrap();
TREE.write(dir.path()).unwrap();
let store = Store::new(dir.path().join(".origin"), Native::default());
store.init().unwrap();
let empty = Tree::default().encode();
store.write_all(std::slice::from_ref(&empty)).unwrap();
let (root, _) = Worktree::new(dir.path(), &store)
.snapshot(&StatCache::default())
.unwrap();
let changes = store.diff(TreeId::from(empty.id()), root).unwrap();
Main { dir, changes }
});

/// Every file read from the store, decompressed, verified and written.
#[divan::bench(sample_count = 10, sample_size = 1)]
fn from_store(bencher: Bencher<'_, '_>) {
let store = Store::new(MAIN.dir.path().join(".origin"), Native::default());
bencher
.counter(ItemsCount::new(MAIN.changes.len()))
.with_inputs(|| tempfile::tempdir().unwrap())
.bench_local_refs(|workspace| {
Worktree::new(workspace.path(), &store)
.checkout(&MAIN.changes)
.unwrap();
});
}
2 changes: 1 addition & 1 deletion apps/origin-src/src/workspace/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,7 @@ impl Workspace {
Ok(())
}

/// Makes the files match `to`, given that they match `from`.
/// Makes the files match `to`, given that they match `from`, durably.
fn checkout(&self, from: TreeId, to: TreeId) -> Result<(), WorkspaceError> {
let changes = self.store.diff(from, to)?;
Ok(Worktree::new(&self.root, &self.store).checkout(&changes)?)
Expand Down
149 changes: 127 additions & 22 deletions apps/origin-src/src/worktree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,18 @@
//! copy. To keep that fast, a stat cache remembers each file's metadata and
//! blob id, so only files whose metadata changed are read and hashed, and
//! every phase runs in parallel.
//!
//! Checkouts write files from the store, in parallel, and the files they
//! write are durable once they return.

use std::collections::HashMap;
use std::collections::{BTreeSet, HashMap};
use std::ffi::OsStr;
use std::fs::{self, File};
use std::io;
use std::ops::Range;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::{MetadataExt, PermissionsExt, symlink};
use std::panic;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
Expand Down Expand Up @@ -54,6 +58,12 @@ impl Stat {
}
}

/// A file a checkout writes.
struct Write {
path: PathBuf,
entry: TreeEntry,
}

/// The stat cache: what each file looked like when it was last hashed, and
/// the snapshot those files made.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
Expand Down Expand Up @@ -233,6 +243,10 @@ impl<'a, P: Platform> Worktree<'a, P> {
/// Below this many items, threads cost more than they save.
const PARALLEL_THRESHOLD: usize = 64;

/// From this many files on, a checkout syncs the first half of them
/// while it writes the second.
const EARLY_SYNC: usize = 1024;

/// The working copy rooted at `root`.
#[must_use]
pub fn new(root: &'a Path, store: &'a Store<P>) -> Self {
Expand Down Expand Up @@ -460,13 +474,18 @@ impl<'a, P: Platform> Worktree<'a, P> {

/// Makes the files match a snapshot, given how they differ from it:
/// removes the files `changes` remove, then writes the ones they add or
/// modify. Directories left empty are removed.
/// modify, in parallel. Directories left empty are removed. Once it
/// returns, the files and directories it changed are durable, at the
/// cost of one batch sync.
///
/// # Errors
///
/// Fails if a file's content cannot be read from the store, or a file
/// cannot be removed or written.
/// cannot be removed, written or synced.
pub fn checkout(&self, changes: &[FileChange]) -> Result<(), SnapshotError> {
if changes.is_empty() {
return Ok(());
}
// Removing first frees the paths of files that become directories,
// and of directories that become files.
for change in changes.iter().filter(|change| change.new.is_none()) {
Expand All @@ -479,11 +498,99 @@ impl<'a, P: Platform> Worktree<'a, P> {
}
}
}
let writes: Vec<_> = changes
.iter()
.filter_map(|change| {
Some(Write {
path: self.absolute(&change.path),
entry: change.new?,
})
})
.collect();
// Creating the directories first lets the files be written in any
// order.
let mut dirs: Vec<_> = writes
.iter()
.filter_map(|write| write.path.parent())
.collect();
dirs.sort_unstable();
dirs.dedup();
for dir in dirs {
fs::create_dir_all(dir).map_err(|source| SnapshotError::Io {
path: dir.to_owned(),
source,
})?;
}
// Many files take long to sync: the first half is written back
// while the second is written, so the final sync, the barrier, has
// less left to wait for.
let half = if writes.len() >= Self::EARLY_SYNC {
writes.len() / 2
} else {
0
};
let (first, second) = writes.split_at(half);
self.write_files(first)?;
thread::scope(|scope| {
let early = (!first.is_empty()).then(|| {
scope.spawn(|| {
let files = first
.iter()
.filter(|write| write.entry.kind != EntryKind::Symlink);
self.store
.platform
.sync_batch(files.map(|write| write.path.as_path()))
})
});
let written = self.write_files(second);
let synced = early.map(|early| {
early
.join()
.unwrap_or_else(|panic| panic::resume_unwind(panic))
});
written?;
synced.transpose().map_err(StoreError::from)?;
Ok::<_, SnapshotError>(())
})?;
self.sync(changes, &writes)
}

/// Writes `writes`, a contiguous run of files per core, rather than
/// files handed out one at a time: creating files locks their
/// directory, and a run mostly keeps to directories of its own, which
/// is 40% faster.
fn write_files(&self, writes: &[Write]) -> Result<(), SnapshotError> {
Store::<P>::on_every_core(writes, |chunk| {
chunk.iter().try_for_each(|write| self.write_file(write))
})
.into_iter()
.collect()
}

/// Makes what a checkout of `changes` wrote, `writes`, durable: the
/// files, but symlinks, whose content their directory holds, and every
/// directory up to the root whose entries may have changed.
fn sync(&self, changes: &[FileChange], writes: &[Write]) -> Result<(), SnapshotError> {
let write = self.store.durable_write();
for file in writes {
if file.entry.kind != EntryKind::Symlink {
write.sync_with(&file.path);
}
}
let mut dirs = BTreeSet::new();
for change in changes {
if let Some(entry) = change.new {
self.write_file(&change.path, entry)?;
let path = self.absolute(&change.path);
for dir in path.ancestors().skip(1) {
if !dirs.insert(dir.to_owned()) || dir == self.root {
break;
}
}
}
// Those a removal emptied are gone, with their entries.
for dir in dirs.into_iter().filter(|dir| dir.is_dir()) {
write.sync_with(dir);
}
write.commit().map_err(StoreError::from)?;
Ok(())
}

Expand All @@ -502,30 +609,28 @@ impl<'a, P: Platform> Worktree<'a, P> {
}
}

/// Writes the file `entry` describes at `path`, replacing any file
/// there.
fn write_file(&self, path: &RepoPath, entry: TreeEntry) -> Result<(), SnapshotError> {
/// Writes the file `write` describes, whose directory exists, replacing
/// any file there.
fn write_file(&self, write: &Write) -> Result<(), SnapshotError> {
let Write { path, entry } = write;
let (path, entry) = (path.as_path(), *entry);
let io_error = |source| SnapshotError::Io {
path: path.to_owned(),
source,
};
// Never write through a symlink, or keep the old file's mode.
Self::remove(path)?;
let blob = self.store.read(entry.id)?;
let content = blob.blob_content().map_err(|source| StoreError::Decode {
id: entry.id,
source,
})?;
let path = self.absolute(path);
let io_error = |source| SnapshotError::Io {
path: path.clone(),
source,
};
// Never write through a symlink, or keep the old file's mode.
Self::remove(&path)?;
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).map_err(io_error)?;
}
match entry.kind {
EntryKind::Symlink => symlink(OsStr::from_bytes(content), &path).map_err(io_error),
EntryKind::Executable => fs::write(&path, content)
.and_then(|()| fs::set_permissions(&path, fs::Permissions::from_mode(0o755)))
EntryKind::Symlink => symlink(OsStr::from_bytes(content), path).map_err(io_error),
EntryKind::Executable => fs::write(path, content)
.and_then(|()| fs::set_permissions(path, fs::Permissions::from_mode(0o755)))
.map_err(io_error),
EntryKind::File | EntryKind::Tree => fs::write(&path, content).map_err(io_error),
EntryKind::File | EntryKind::Tree => fs::write(path, content).map_err(io_error),
}
}

Expand Down
Loading