use std::collections::VecDeque;
use std::future::Future;
use std::io;
use std::path::{Component, Path};
use std::pin::Pin;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};
use futures_io::AsyncWrite;
use ostrya_core::{Checksum, Commit, DirMeta, ObjectType};
use crate::error::{Error, Result};
use crate::file::{FileKind, FileObject};
use crate::mtree::{ChildKind, ChildRef, MutableTree};
use crate::transaction::Transaction;
use crate::write::{ContentWriter, FileMeta};
const MAX_SYMLINK_DEPTH: usize = 40;
#[derive(Clone)]
enum Comp {
Normal(String),
Parent,
}
enum WalkEnd {
Dir(Vec<String>),
Leaf { name: String, checksum: Checksum },
}
#[derive(Debug, Clone, Copy, Default)]
pub struct MergeOptions {
pub allow_overwrite: bool,
pub follow_symlinks: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StagingEntry {
File {
name: String,
checksum: Checksum,
},
Dir {
name: String,
},
}
pub struct StagingTree<'txn> {
txn: &'txn Transaction,
tree: Arc<Mutex<MutableTree>>,
writers: Arc<AtomicUsize>,
}
impl Transaction {
pub async fn staging_tree(&self, source: Option<&Commit>) -> Result<StagingTree<'_>> {
let tree = match source {
None => MutableTree::new(),
Some(commit) => {
MutableTree::hydrate(self.repo(), commit.root_dirtree, commit.root_dirmeta).await?
}
};
Ok(StagingTree::from_tree(self, tree))
}
pub fn staging_tree_from_mutable_tree(&self, source: MutableTree) -> StagingTree<'_> {
StagingTree::from_tree(self, source)
}
}
impl<'txn> StagingTree<'txn> {
fn from_tree(txn: &'txn Transaction, tree: MutableTree) -> StagingTree<'txn> {
StagingTree {
txn,
tree: Arc::new(Mutex::new(tree)),
writers: Arc::new(AtomicUsize::new(0)),
}
}
pub fn close(self) -> Result<MutableTree> {
let outstanding = self.writers.load(Ordering::Acquire);
if outstanding != 0 {
return Err(Error::Staging(format!(
"cannot close the staging tree: {outstanding} file writer(s) still outstanding"
)));
}
let mut guard = self.tree.lock().unwrap();
Ok(std::mem::take(&mut *guard))
}
pub async fn write_file(&self, path: &Path, meta: &FileMeta) -> Result<StagedFileWriter<'txn>> {
let (parent, name) = self.resolve_parent(path).await?;
self.check_writable_leaf(path, &parent, &name)?;
let writer = self.txn.content_writer(None, meta).await?;
self.writers.fetch_add(1, Ordering::AcqRel);
Ok(StagedFileWriter {
tree: self.tree.clone(),
writers: self.writers.clone(),
writer: Some(writer),
parent,
name,
})
}
pub async fn write_file_content(
&self,
path: &Path,
meta: &FileMeta,
content: &[u8],
) -> Result<()> {
let (parent, name) = self.resolve_parent(path).await?;
self.check_writable_leaf(path, &parent, &name)?;
let checksum = self.txn.write_regfile_inline(None, meta, content).await?;
self.with_dir_mut(&parent, |dir| dir.replace_file(&name, checksum))
}
pub async fn make_dir(&self, path: &Path, meta: &DirMeta) -> Result<()> {
let (parent, name) = self.resolve_parent(path).await?;
if !matches!(self.peek(&parent, &name)?, ChildKind::Absent) {
return Err(Error::Staging(format!(
"cannot create directory {}: an entry already exists there",
path.display()
)));
}
let dirmeta = self.stage_dirmeta(meta).await?;
self.with_dir_mut(&parent, |dir| {
if !matches!(dir.child_kind(&name), ChildKind::Absent) {
return Err(Error::Staging(format!(
"cannot create directory {}: an entry already exists there",
path.display()
)));
}
dir.insert_empty_dir(&name, Some(dirmeta));
Ok(())
})
}
pub async fn make_dir_all(&self, path: &Path, meta: &DirMeta) -> Result<()> {
let comps = components_of(path)?;
let mut dirmeta: Option<Checksum> = None;
let mut cur: Vec<String> = Vec::new();
for comp in comps {
let name = match comp {
Comp::Parent => {
cur.pop();
continue;
}
Comp::Normal(name) => name,
};
match self.peek(&cur, &name)? {
ChildKind::Dir | ChildKind::LazyDir { .. } => {
self.ensure_child_dir(&cur, &name).await?;
cur.push(name);
}
ChildKind::Absent => {
let dm = match dirmeta {
Some(dm) => dm,
None => {
let dm = self.stage_dirmeta(meta).await?;
dirmeta = Some(dm);
dm
}
};
self.with_dir_mut(&cur, |dir| {
match dir.child_kind(&name) {
ChildKind::Absent => dir.insert_empty_dir(&name, Some(dm)),
ChildKind::File(_) => {
return Err(Error::Staging(format!(
"cannot create directory {}: {name:?} is a file",
path.display()
)));
}
ChildKind::Dir | ChildKind::LazyDir { .. } => {}
}
Ok(())
})?;
self.ensure_child_dir(&cur, &name).await?;
cur.push(name);
}
ChildKind::File(checksum) => {
let obj = self.txn.load_file_staged_first(&checksum).await?;
match obj.kind {
FileKind::Symlink { target } => {
cur = self.resolve_symlink_dir(&cur, &target).await?;
}
FileKind::Regular { .. } => {
return Err(Error::Staging(format!(
"cannot create directory {}: {name:?} is a file",
path.display()
)));
}
}
}
}
}
Ok(())
}
pub async fn symlink(&self, path: &Path, target: &Path, meta: &FileMeta) -> Result<()> {
let (parent, name) = self.resolve_parent(path).await?;
if !matches!(self.peek(&parent, &name)?, ChildKind::Absent) {
return Err(Error::Staging(format!(
"cannot create symlink {}: an entry already exists there",
path.display()
)));
}
let target = target
.to_str()
.ok_or_else(|| Error::Staging("symlink target is not valid UTF-8".into()))?;
let checksum = self.txn.write_symlink(target, meta, None).await?;
self.with_dir_mut(&parent, |dir| {
if !matches!(dir.child_kind(&name), ChildKind::Absent) {
return Err(Error::Staging(format!(
"cannot create symlink {}: an entry already exists there",
path.display()
)));
}
dir.replace_file(&name, checksum)
})
}
pub async fn hardlink(&self, path: &Path, target: &Path) -> Result<()> {
let checksum = match self
.walk_from(Vec::new(), components_of(target)?, false)
.await?
{
WalkEnd::Leaf { checksum, .. } => checksum,
WalkEnd::Dir(_) => {
return Err(Error::Staging(format!(
"cannot hardlink from {}: the target is a directory",
target.display()
)));
}
};
let (parent, name) = self.resolve_parent(path).await?;
self.with_dir_mut(&parent, |dir| {
if !matches!(dir.child_kind(&name), ChildKind::Absent) {
return Err(Error::Staging(format!(
"cannot hardlink {}: an entry already exists there",
path.display()
)));
}
dir.replace_file(&name, checksum)
})
}
pub async fn read_file(&self, path: &Path, follow_symlinks: bool) -> Result<FileObject> {
match self
.walk_from(Vec::new(), components_of(path)?, follow_symlinks)
.await?
{
WalkEnd::Leaf { checksum, .. } => self.txn.load_file_staged_first(&checksum).await,
WalkEnd::Dir(_) => Err(Error::Staging(format!(
"{} is a directory, not a file",
path.display()
))),
}
}
pub async fn read_dir(&self, path: &Path, follow_symlinks: bool) -> Result<Vec<StagingEntry>> {
let dir_path = match self
.walk_from(Vec::new(), components_of(path)?, follow_symlinks)
.await?
{
WalkEnd::Dir(p) => p,
WalkEnd::Leaf { name, .. } => {
return Err(Error::Staging(format!("{name:?} is not a directory")));
}
};
self.with_dir(&dir_path, |dir| {
let mut entries = Vec::new();
for (name, checksum) in dir.file_entries() {
entries.push(StagingEntry::File {
name: name.to_owned(),
checksum,
});
}
for (name, _child) in dir.dir_entries() {
entries.push(StagingEntry::Dir {
name: name.to_owned(),
});
}
entries
})
}
pub async fn merge(&self, other: &MutableTree, opts: MergeOptions) -> Result<()> {
merge_into(self, Vec::new(), RightDir::Mutable(other), &opts).await
}
async fn stage_dirmeta(&self, meta: &DirMeta) -> Result<Checksum> {
let bytes = meta.serialize()?;
self.txn
.write_metadata(ObjectType::DirMeta, None, &bytes)
.await
}
fn check_writable_leaf(&self, path: &Path, parent: &[String], name: &str) -> Result<()> {
match self.peek(parent, name)? {
ChildKind::Dir | ChildKind::LazyDir { .. } => Err(Error::Staging(format!(
"cannot write file {}: a directory exists at that path",
path.display()
))),
_ => Ok(()),
}
}
async fn resolve_parent(&self, path: &Path) -> Result<(Vec<String>, String)> {
let comps = components_of(path)?;
let (last, init) = comps
.split_last()
.ok_or_else(|| Error::Staging(format!("{} has no final component", path.display())))?;
let name = match last {
Comp::Normal(name) => name.clone(),
Comp::Parent => {
return Err(Error::Staging(format!("{} ends in `..`", path.display())));
}
};
let parent = match self.walk_from(Vec::new(), init.to_vec(), true).await? {
WalkEnd::Dir(dir) => dir,
WalkEnd::Leaf { .. } => {
return Err(Error::Staging(format!(
"cannot resolve {}: a parent component is not a directory",
path.display()
)));
}
};
Ok((parent, name))
}
async fn resolve_symlink_dir(&self, base: &[String], target: &str) -> Result<Vec<String>> {
let (absolute, comps) = split_target(target)?;
let start = if absolute { Vec::new() } else { base.to_vec() };
match self.walk_from(start, comps, true).await? {
WalkEnd::Dir(dir) => Ok(dir),
WalkEnd::Leaf { name, .. } => Err(Error::Staging(format!(
"symlink target {target:?} resolves to the file {name:?}, not a directory"
))),
}
}
async fn walk_from(
&self,
start: Vec<String>,
comps: Vec<Comp>,
follow_final: bool,
) -> Result<WalkEnd> {
let mut cur = start;
let mut pending: VecDeque<Comp> = comps.into();
let mut symlink_depth = 0usize;
let mut last_symlink: Option<(String, String)> = None;
while let Some(comp) = pending.pop_front() {
let is_final = pending.is_empty();
let name = match comp {
Comp::Parent => {
cur.pop();
continue;
}
Comp::Normal(name) => name,
};
match self.peek(&cur, &name)? {
ChildKind::Absent => {
return Err(match &last_symlink {
Some((symlink, target)) => Error::Staging(format!(
"dangling symlink {symlink} -> {target}: no entry {name:?} under /{}",
cur.join("/")
)),
None => Error::Staging(format!(
"path not found: no entry {name:?} under /{}",
cur.join("/")
)),
});
}
ChildKind::Dir | ChildKind::LazyDir { .. } => {
self.ensure_child_dir(&cur, &name).await?;
cur.push(name);
}
ChildKind::File(checksum) => {
if is_final && !follow_final {
return Ok(WalkEnd::Leaf { name, checksum });
}
let obj = self.txn.load_file_staged_first(&checksum).await?;
match obj.kind {
FileKind::Symlink { target } => {
symlink_depth += 1;
if symlink_depth > MAX_SYMLINK_DEPTH {
return Err(Error::Staging(format!(
"symlink chain too deep (possible loop) resolving {name:?} \
under /{}",
cur.join("/")
)));
}
last_symlink = Some((join(&cur, &name), target.clone()));
let (absolute, target_comps) = split_target(&target)?;
if absolute {
cur.clear();
}
for comp in target_comps.into_iter().rev() {
pending.push_front(comp);
}
}
FileKind::Regular { .. } => {
if is_final {
return Ok(WalkEnd::Leaf { name, checksum });
}
return Err(Error::Staging(format!(
"not a directory: {name:?} under /{} is a regular file",
cur.join("/")
)));
}
}
}
}
}
Ok(WalkEnd::Dir(cur))
}
async fn ensure_child_dir(&self, path: &[String], name: &str) -> Result<()> {
loop {
let (kind, repo) = {
let tree = self.tree.lock().unwrap();
let dir = tree
.dir_at(path)
.ok_or_else(|| Error::Staging(dir_gone(path)))?;
(dir.child_kind(name), dir.repo())
};
match kind {
ChildKind::Dir => return Ok(()),
ChildKind::LazyDir { dirtree, dirmeta } => {
let repo = repo.ok_or_else(|| {
Error::Staging(format!("cannot hydrate {name:?}: no repository handle"))
})?;
let loaded = MutableTree::hydrate(&repo, dirtree, dirmeta).await?;
let mut tree = self.tree.lock().unwrap();
if let Some(dir) = tree.dir_at_mut(path)
&& matches!(dir.child_kind(name), ChildKind::LazyDir { .. })
{
dir.install_hydrated_child(name, loaded);
}
}
ChildKind::File(_) => {
return Err(Error::Staging(format!(
"not a directory: {name:?} under /{}",
path.join("/")
)));
}
ChildKind::Absent => {
return Err(Error::Staging(format!(
"path not found: no entry {name:?} under /{}",
path.join("/")
)));
}
}
}
}
fn peek(&self, path: &[String], name: &str) -> Result<ChildKind> {
let tree = self.tree.lock().unwrap();
let dir = tree
.dir_at(path)
.ok_or_else(|| Error::Staging(dir_gone(path)))?;
Ok(dir.child_kind(name))
}
fn with_dir<R>(&self, path: &[String], f: impl FnOnce(&MutableTree) -> R) -> Result<R> {
let tree = self.tree.lock().unwrap();
let dir = tree
.dir_at(path)
.ok_or_else(|| Error::Staging(dir_gone(path)))?;
Ok(f(dir))
}
fn with_dir_mut<R>(
&self,
path: &[String],
f: impl FnOnce(&mut MutableTree) -> Result<R>,
) -> Result<R> {
let mut tree = self.tree.lock().unwrap();
let dir = tree
.dir_at_mut(path)
.ok_or_else(|| Error::Staging(dir_gone(path)))?;
f(dir)
}
}
enum RightDir<'a> {
Mutable(&'a MutableTree),
Committed {
txn: &'a Transaction,
dirtree: Checksum,
dirmeta: Checksum,
},
}
impl<'a> RightDir<'a> {
fn dirmeta(&self) -> Option<Checksum> {
match self {
RightDir::Mutable(tree) => tree.metadata_checksum(),
RightDir::Committed { dirmeta, .. } => Some(*dirmeta),
}
}
async fn entries(
&self,
txn: &'a Transaction,
) -> Result<(Vec<(String, Checksum)>, Vec<(String, RightDir<'a>)>)> {
match self {
RightDir::Mutable(tree) => {
let tree: &'a MutableTree = tree;
let files = tree
.file_entries()
.map(|(name, checksum)| (name.to_owned(), checksum))
.collect();
let dirs = tree
.dir_entries()
.map(|(name, child)| {
let view = match child {
ChildRef::Loaded(sub) => RightDir::Mutable(sub),
ChildRef::Lazy { dirtree, dirmeta } => RightDir::Committed {
txn,
dirtree,
dirmeta,
},
};
(name.to_owned(), view)
})
.collect();
Ok((files, dirs))
}
RightDir::Committed { txn, dirtree, .. } => {
let txn: &'a Transaction = txn;
let dt = txn.load_dirtree_staged_first(dirtree).await?;
let files = dt.files.into_iter().collect();
let dirs = dt
.dirs
.into_iter()
.map(|(name, child_dirtree, child_dirmeta)| {
(
name,
RightDir::Committed {
txn,
dirtree: child_dirtree,
dirmeta: child_dirmeta,
},
)
})
.collect();
Ok((files, dirs))
}
}
}
}
type MergeFuture<'a> = Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;
fn merge_into<'a>(
st: &'a StagingTree<'_>,
left_path: Vec<String>,
right: RightDir<'a>,
opts: &'a MergeOptions,
) -> MergeFuture<'a> {
Box::pin(async move {
if let Some(right_dm) = right.dirmeta() {
let left_dm = {
let tree = st.tree.lock().unwrap();
match tree.dir_at(&left_path) {
Some(dir) => dir.metadata_checksum(),
None => return Err(Error::Staging(dir_gone(&left_path))),
}
};
match left_dm {
Some(left) if left == right_dm => {}
Some(_) if !opts.allow_overwrite => {
return Err(Error::MergeConflict(format!(
"directory metadata differs at /{}",
left_path.join("/")
)));
}
_ => {
st.with_dir_mut(&left_path, |dir| {
dir.set_metadata_checksum(right_dm);
Ok(())
})?;
}
}
}
let (rfiles, rdirs) = right.entries(st.txn).await?;
for (name, right_csum) in rfiles {
match st.peek(&left_path, &name)? {
ChildKind::Absent => {
st.with_dir_mut(&left_path, |dir| dir.replace_file(&name, right_csum))?;
}
ChildKind::File(left_csum) if left_csum == right_csum => {}
ChildKind::File(_) => {
if !opts.allow_overwrite {
return Err(Error::MergeConflict(format!(
"file differs at /{}",
join(&left_path, &name)
)));
}
st.with_dir_mut(&left_path, |dir| dir.replace_file(&name, right_csum))?;
}
ChildKind::Dir | ChildKind::LazyDir { .. } => {
if !opts.allow_overwrite {
return Err(Error::MergeConflict(format!(
"a file cannot overwrite the directory at /{}",
join(&left_path, &name)
)));
}
st.with_dir_mut(&left_path, |dir| {
dir.remove(&name, true)?;
dir.replace_file(&name, right_csum)
})?;
}
}
}
for (name, right_child) in rdirs {
match st.peek(&left_path, &name)? {
ChildKind::Absent => {
st.with_dir_mut(&left_path, |dir| {
dir.insert_empty_dir(&name, right_child.dirmeta());
Ok(())
})?;
let mut child_path = left_path.clone();
child_path.push(name);
merge_into(st, child_path, right_child, opts).await?;
}
ChildKind::Dir | ChildKind::LazyDir { .. } => {
st.ensure_child_dir(&left_path, &name).await?;
let mut child_path = left_path.clone();
child_path.push(name);
merge_into(st, child_path, right_child, opts).await?;
}
ChildKind::File(left_csum) => {
if opts.follow_symlinks {
let obj = st.txn.load_file_staged_first(&left_csum).await?;
if let FileKind::Symlink { target } = obj.kind {
let target_dir = st.resolve_symlink_dir(&left_path, &target).await?;
merge_into(st, target_dir, right_child, opts).await?;
continue;
}
}
if !opts.allow_overwrite {
return Err(Error::MergeConflict(format!(
"a directory cannot overwrite the file at /{}",
join(&left_path, &name)
)));
}
st.with_dir_mut(&left_path, |dir| {
dir.remove(&name, true)?;
dir.insert_empty_dir(&name, right_child.dirmeta());
Ok(())
})?;
let mut child_path = left_path.clone();
child_path.push(name);
merge_into(st, child_path, right_child, opts).await?;
}
}
}
Ok(())
})
}
pub struct StagedFileWriter<'txn> {
tree: Arc<Mutex<MutableTree>>,
writers: Arc<AtomicUsize>,
writer: Option<ContentWriter<'txn>>,
parent: Vec<String>,
name: String,
}
impl StagedFileWriter<'_> {
pub async fn finish(mut self) -> Result<()> {
let writer = self.writer.take().expect("writer present until finish");
let outcome = match writer.finish().await {
Ok(checksum) => {
let mut tree = self.tree.lock().unwrap();
match tree.dir_at_mut(&self.parent) {
Some(dir) => dir.replace_file(&self.name, checksum),
None => Err(Error::Staging(dir_gone(&self.parent))),
}
}
Err(e) => Err(e),
};
self.writers.fetch_sub(1, Ordering::AcqRel);
outcome
}
}
impl Drop for StagedFileWriter<'_> {
fn drop(&mut self) {
if self.writer.is_some() {
self.writers.fetch_sub(1, Ordering::AcqRel);
}
}
}
impl AsyncWrite for StagedFileWriter<'_> {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
match &mut self.get_mut().writer {
Some(writer) => Pin::new(writer).poll_write(cx, buf),
None => Poll::Ready(Ok(0)),
}
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
match &mut self.get_mut().writer {
Some(writer) => Pin::new(writer).poll_flush(cx),
None => Poll::Ready(Ok(())),
}
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
self.poll_flush(cx)
}
}
#[cfg(feature = "tokio")]
impl ostrya_rt::tokio_io::AsyncWrite for StagedFileWriter<'_> {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
AsyncWrite::poll_write(self, cx, buf)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
AsyncWrite::poll_flush(self, cx)
}
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
AsyncWrite::poll_close(self, cx)
}
}
fn components_of(path: &Path) -> Result<Vec<Comp>> {
path.components()
.filter_map(|c| match c {
Component::Normal(part) => Some(
part.to_str()
.map(|s| Comp::Normal(s.to_owned()))
.ok_or_else(|| {
Error::Staging(format!(
"path component is not valid UTF-8: {}",
path.display()
))
}),
),
Component::ParentDir => Some(Ok(Comp::Parent)),
Component::RootDir | Component::CurDir | Component::Prefix(_) => None,
})
.collect()
}
fn split_target(target: &str) -> Result<(bool, Vec<Comp>)> {
Ok((target.starts_with('/'), components_of(Path::new(target))?))
}
fn join(path: &[String], name: &str) -> String {
if path.is_empty() {
name.to_owned()
} else {
format!("{}/{}", path.join("/"), name)
}
}
fn dir_gone(path: &[String]) -> String {
format!("directory /{} is no longer present", path.join("/"))
}
const _: fn() = || {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<StagingTree<'static>>();
assert_send_sync::<StagedFileWriter<'static>>();
assert_send_sync::<StagingEntry>();
assert_send_sync::<MergeOptions>();
};
#[cfg(feature = "tokio")]
const _: fn() = || {
fn assert_tokio_write<T: ostrya_rt::tokio_io::AsyncWrite>() {}
assert_tokio_write::<StagedFileWriter<'static>>();
};