1103 lines
38 KiB
Rust
1103 lines
38 KiB
Rust
use std::collections::{BTreeMap, HashMap, VecDeque};
|
|
use std::io;
|
|
use std::path::{Path, PathBuf};
|
|
use std::pin::Pin;
|
|
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
|
use std::sync::{Arc, Mutex};
|
|
use std::task::{Context, Poll};
|
|
use std::time::{Duration, SystemTime};
|
|
|
|
use async_trait::async_trait;
|
|
use rcom::domain::{Entry, EntryKind, HostAlias, Location, SourceId};
|
|
use rcom::fs::{
|
|
BackendHandle, FileOperations, FsError, LocalFileOperations, LocalFs, PartFile, PartWriter,
|
|
StagingOperations, TransferCapabilities, execute_copy_move,
|
|
};
|
|
use rcom::operations::{
|
|
CollisionPolicy, CommitOutcome, ItemId, OperationKind, OperationPlan, PlanGeneration, PlanId,
|
|
SourceCleanupOutcome, SourceItem,
|
|
};
|
|
use rcom::ssh::{SftpFileOperations, SftpReader, SftpTransferTransport, SftpWriter};
|
|
use rcom::test_support::{MemoryFs, MemoryTransferFs, TransferOperation};
|
|
use tempfile::TempDir;
|
|
use tokio::io::{AsyncReadExt, AsyncWrite};
|
|
use tokio_util::sync::CancellationToken;
|
|
|
|
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
|
|
enum StreamOperation {
|
|
Write,
|
|
Flush,
|
|
Close,
|
|
}
|
|
|
|
#[derive(Clone, Debug)]
|
|
enum StreamFault {
|
|
Error(FsError),
|
|
AfterApply(FsError),
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
struct FakeTransport {
|
|
host: HostAlias,
|
|
memory: MemoryTransferFs,
|
|
capabilities: TransferCapabilities,
|
|
stream_faults: Arc<Mutex<HashMap<StreamOperation, VecDeque<StreamFault>>>>,
|
|
create_dir_calls: Arc<Mutex<Vec<PathBuf>>>,
|
|
rename_calls: Arc<AtomicUsize>,
|
|
permission_calls: Arc<AtomicUsize>,
|
|
mtime_calls: Arc<AtomicUsize>,
|
|
part_files: Arc<Mutex<HashMap<PathBuf, PartFile>>>,
|
|
wrong_part_size: Arc<AtomicBool>,
|
|
disconnected: Arc<AtomicBool>,
|
|
disconnect_on_commit: Arc<AtomicBool>,
|
|
after_write_destination: Arc<Mutex<Option<Location>>>,
|
|
}
|
|
|
|
impl FakeTransport {
|
|
fn new(host: &str, epoch: u64) -> Self {
|
|
let host = HostAlias::new(host);
|
|
Self {
|
|
memory: MemoryTransferFs::new(SourceId::Ssh(host.clone()), epoch),
|
|
host,
|
|
capabilities: TransferCapabilities {
|
|
canonicalize: true,
|
|
regular_files: true,
|
|
permissions: true,
|
|
mtime: true,
|
|
atomic_rename: true,
|
|
sftp_version: Some(3),
|
|
},
|
|
stream_faults: Arc::new(Mutex::new(HashMap::new())),
|
|
create_dir_calls: Arc::new(Mutex::new(Vec::new())),
|
|
rename_calls: Arc::new(AtomicUsize::new(0)),
|
|
permission_calls: Arc::new(AtomicUsize::new(0)),
|
|
mtime_calls: Arc::new(AtomicUsize::new(0)),
|
|
part_files: Arc::new(Mutex::new(HashMap::new())),
|
|
wrong_part_size: Arc::new(AtomicBool::new(false)),
|
|
disconnected: Arc::new(AtomicBool::new(false)),
|
|
disconnect_on_commit: Arc::new(AtomicBool::new(false)),
|
|
after_write_destination: Arc::new(Mutex::new(None)),
|
|
}
|
|
}
|
|
|
|
fn with_file(self, path: &str, contents: &[u8]) -> Self {
|
|
self.memory.insert_file(self.location(path), contents);
|
|
self
|
|
}
|
|
|
|
fn with_dir(self, path: &str) -> Self {
|
|
self.memory.insert_dir(self.location(path));
|
|
self
|
|
}
|
|
|
|
fn location(&self, path: impl Into<PathBuf>) -> Location {
|
|
Location::ssh(self.host.clone(), path)
|
|
}
|
|
|
|
fn fail_stream(&self, operation: StreamOperation, error: FsError) {
|
|
self.stream_faults
|
|
.lock()
|
|
.unwrap()
|
|
.entry(operation)
|
|
.or_default()
|
|
.push_back(StreamFault::Error(error));
|
|
}
|
|
|
|
fn fail_stream_after_apply(&self, operation: StreamOperation, error: FsError) {
|
|
self.stream_faults
|
|
.lock()
|
|
.unwrap()
|
|
.entry(operation)
|
|
.or_default()
|
|
.push_back(StreamFault::AfterApply(error));
|
|
}
|
|
|
|
fn take_stream_fault(&self, operation: StreamOperation) -> Option<StreamFault> {
|
|
self.stream_faults
|
|
.lock()
|
|
.unwrap()
|
|
.get_mut(&operation)
|
|
.and_then(VecDeque::pop_front)
|
|
}
|
|
|
|
fn check_connection(&self) -> Result<(), FsError> {
|
|
if self.disconnected.load(Ordering::Acquire) {
|
|
Err(FsError::Disconnected)
|
|
} else {
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
fn memory_location(&self, path: &Path) -> Location {
|
|
self.part_files
|
|
.lock()
|
|
.unwrap()
|
|
.get(path)
|
|
.map_or_else(|| self.location(path), |part| part.location().clone())
|
|
}
|
|
|
|
fn part_contents(&self, location: &Location) -> Result<Vec<u8>, FsError> {
|
|
let location = self.memory_location(location.path());
|
|
self.memory.part_contents(&location)
|
|
}
|
|
|
|
fn part_owner(&self, location: &Location) -> Option<u64> {
|
|
let location = self.memory_location(location.path());
|
|
self.memory.part_owner(&location)
|
|
}
|
|
|
|
fn operations(&self) -> Arc<SftpFileOperations> {
|
|
Arc::new(SftpFileOperations::new(
|
|
self.host.clone(),
|
|
self.memory.epoch(),
|
|
Arc::new(self.clone()),
|
|
))
|
|
}
|
|
|
|
fn remote_handle(&self, operations: &Arc<SftpFileOperations>, read: MemoryFs) -> BackendHandle {
|
|
BackendHandle::new(
|
|
SourceId::Ssh(self.host.clone()),
|
|
Arc::new(read),
|
|
operations.clone(),
|
|
)
|
|
.unwrap()
|
|
}
|
|
}
|
|
|
|
#[async_trait]
|
|
impl SftpTransferTransport for FakeTransport {
|
|
fn capabilities(&self) -> TransferCapabilities {
|
|
self.capabilities
|
|
}
|
|
|
|
async fn canonicalize(&self, path: &Path) -> Result<PathBuf, FsError> {
|
|
self.check_connection()?;
|
|
let mapped = self.memory_location(path);
|
|
if self.memory.part_contents(&mapped).is_ok() {
|
|
return Ok(mapped.path);
|
|
}
|
|
Ok(self.memory.canonicalize(&mapped).await?.path)
|
|
}
|
|
|
|
async fn metadata(&self, path: &Path, follow_symlinks: bool) -> Result<Entry, FsError> {
|
|
self.check_connection()?;
|
|
let mapped = self.memory_location(path);
|
|
let mut entry = match self.memory.part_contents(&mapped) {
|
|
Ok(contents) => Entry::new(
|
|
mapped.file_name_owned().unwrap_or_default(),
|
|
EntryKind::File,
|
|
)
|
|
.with_metadata(Some(contents.len() as u64), None, None),
|
|
Err(FsError::NotFound) => self.memory.metadata(&mapped, follow_symlinks).await?,
|
|
Err(error) => return Err(error),
|
|
};
|
|
if self.wrong_part_size.load(Ordering::Acquire)
|
|
&& path
|
|
.file_name()
|
|
.is_some_and(|name| name.to_string_lossy().starts_with(".rcom-part-"))
|
|
{
|
|
entry.size = entry.size.map(|size| size + 1);
|
|
}
|
|
Ok(entry)
|
|
}
|
|
|
|
async fn open_read(&self, path: &Path) -> Result<SftpReader, FsError> {
|
|
self.check_connection()?;
|
|
let stream = self.memory.open_read(&self.memory_location(path)).await?;
|
|
Ok(Box::pin(stream))
|
|
}
|
|
|
|
async fn create_part(&self, path: &Path) -> Result<SftpWriter, FsError> {
|
|
self.check_connection()?;
|
|
let writer = self.memory.open_part(&self.location(path)).await?;
|
|
self.part_files
|
|
.lock()
|
|
.unwrap()
|
|
.insert(path.to_path_buf(), writer.part().clone());
|
|
Ok(Box::pin(FakeWriter {
|
|
inner: Some(writer),
|
|
transport: self.clone(),
|
|
after_write_destination: self.after_write_destination.lock().unwrap().take(),
|
|
}))
|
|
}
|
|
|
|
async fn create_dir(&self, path: &Path) -> Result<(), FsError> {
|
|
self.check_connection()?;
|
|
self.create_dir_calls
|
|
.lock()
|
|
.unwrap()
|
|
.push(path.to_path_buf());
|
|
let location = self.location(path);
|
|
match self.memory.metadata(&location, false).await {
|
|
Ok(_) => return Err(FsError::Other("destination already exists".into())),
|
|
Err(FsError::NotFound) => {}
|
|
Err(error) => return Err(error),
|
|
}
|
|
self.memory.insert_dir(location);
|
|
Ok(())
|
|
}
|
|
|
|
async fn rename(&self, from: &Path, to: &Path) -> Result<(), FsError> {
|
|
self.check_connection()?;
|
|
self.rename_calls.fetch_add(1, Ordering::AcqRel);
|
|
let part = self.part_files.lock().unwrap().get(from).cloned();
|
|
let is_part = part.is_some();
|
|
let result = if let Some(part) = part {
|
|
let commit = self.memory.commit_part(part).await;
|
|
let commit_applied = self.memory.file_contents(&self.location(from)).is_ok();
|
|
match commit {
|
|
Ok(()) => {
|
|
self.memory
|
|
.rename(&self.location(from), &self.location(to))
|
|
.await
|
|
}
|
|
Err(error) if commit_applied => {
|
|
self.memory
|
|
.rename(&self.location(from), &self.location(to))
|
|
.await?;
|
|
Err(error)
|
|
}
|
|
Err(error) => Err(error),
|
|
}
|
|
} else {
|
|
self.memory
|
|
.rename(&self.location(from), &self.location(to))
|
|
.await
|
|
};
|
|
if result.is_ok() {
|
|
self.part_files.lock().unwrap().remove(from);
|
|
}
|
|
if self.disconnect_on_commit.load(Ordering::Acquire)
|
|
&& is_part
|
|
&& matches!(result, Err(FsError::Disconnected))
|
|
{
|
|
self.disconnected.store(true, Ordering::Release);
|
|
}
|
|
result
|
|
}
|
|
|
|
async fn remove_file(&self, path: &Path) -> Result<(), FsError> {
|
|
self.check_connection()?;
|
|
let part = self.part_files.lock().unwrap().get(path).cloned();
|
|
let result = if let Some(part) = part {
|
|
self.memory.discard_part(part).await
|
|
} else {
|
|
self.memory.remove_file(&self.location(path)).await
|
|
};
|
|
if result.is_ok() {
|
|
self.part_files.lock().unwrap().remove(path);
|
|
}
|
|
result
|
|
}
|
|
|
|
async fn remove_dir(&self, path: &Path) -> Result<(), FsError> {
|
|
self.check_connection()?;
|
|
self.memory.remove_dir(&self.location(path)).await
|
|
}
|
|
|
|
async fn set_permissions(&self, path: &Path, _mode: u32) -> Result<(), FsError> {
|
|
self.permission_calls.fetch_add(1, Ordering::AcqRel);
|
|
self.check_connection()?;
|
|
let mapped = self.memory_location(path);
|
|
if self.memory.part_contents(&mapped).is_ok() {
|
|
return Ok(());
|
|
}
|
|
self.memory.metadata(&mapped, false).await?;
|
|
Ok(())
|
|
}
|
|
|
|
async fn set_mtime(&self, path: &Path, _modified: SystemTime) -> Result<(), FsError> {
|
|
self.mtime_calls.fetch_add(1, Ordering::AcqRel);
|
|
self.check_connection()?;
|
|
let mapped = self.memory_location(path);
|
|
if self.memory.part_contents(&mapped).is_ok() {
|
|
return Ok(());
|
|
}
|
|
self.memory.metadata(&mapped, false).await?;
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
struct FakeWriter {
|
|
inner: Option<PartWriter>,
|
|
transport: FakeTransport,
|
|
after_write_destination: Option<Location>,
|
|
}
|
|
|
|
impl FakeWriter {
|
|
fn before(&self, operation: StreamOperation) -> Option<StreamFault> {
|
|
self.transport.take_stream_fault(operation)
|
|
}
|
|
}
|
|
|
|
impl AsyncWrite for FakeWriter {
|
|
fn poll_write(
|
|
mut self: Pin<&mut Self>,
|
|
context: &mut Context<'_>,
|
|
buffer: &[u8],
|
|
) -> Poll<io::Result<usize>> {
|
|
let fault = self.before(StreamOperation::Write);
|
|
if let Some(StreamFault::Error(error)) = fault.clone() {
|
|
return Poll::Ready(Err(io_error(error)));
|
|
}
|
|
let result = Pin::new(self.inner.as_mut().unwrap()).poll_write(context, buffer);
|
|
if let Poll::Ready(Ok(_)) = &result
|
|
&& let Some(destination) = self.after_write_destination.take()
|
|
{
|
|
self.transport.memory.insert_file(destination, b"existing");
|
|
}
|
|
if result.is_ready()
|
|
&& let Some(StreamFault::AfterApply(error)) = fault
|
|
{
|
|
return Poll::Ready(Err(io_error(error)));
|
|
}
|
|
result
|
|
}
|
|
|
|
fn poll_flush(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<io::Result<()>> {
|
|
let fault = self.before(StreamOperation::Flush);
|
|
if let Some(StreamFault::Error(error)) = fault.clone() {
|
|
return Poll::Ready(Err(io_error(error)));
|
|
}
|
|
let result = Pin::new(self.inner.as_mut().unwrap()).poll_flush(context);
|
|
if result.is_ready()
|
|
&& let Some(StreamFault::AfterApply(error)) = fault
|
|
{
|
|
return Poll::Ready(Err(io_error(error)));
|
|
}
|
|
result
|
|
}
|
|
|
|
fn poll_shutdown(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<io::Result<()>> {
|
|
let fault = self.before(StreamOperation::Close);
|
|
if let Some(StreamFault::Error(error)) = fault.clone() {
|
|
return Poll::Ready(Err(io_error(error)));
|
|
}
|
|
let result = Pin::new(self.inner.as_mut().unwrap()).poll_shutdown(context);
|
|
if result.is_ready()
|
|
&& let Some(StreamFault::AfterApply(error)) = fault
|
|
{
|
|
return Poll::Ready(Err(io_error(error)));
|
|
}
|
|
result
|
|
}
|
|
}
|
|
|
|
fn io_error(error: FsError) -> io::Error {
|
|
let kind = match error {
|
|
FsError::Timeout => io::ErrorKind::TimedOut,
|
|
FsError::Disconnected => io::ErrorKind::ConnectionReset,
|
|
FsError::PermissionDenied => io::ErrorKind::PermissionDenied,
|
|
FsError::NotFound => io::ErrorKind::NotFound,
|
|
_ => io::ErrorKind::Other,
|
|
};
|
|
io::Error::new(kind, error)
|
|
}
|
|
|
|
fn local_handle() -> BackendHandle {
|
|
BackendHandle::new(
|
|
SourceId::Local,
|
|
Arc::new(LocalFs::new()),
|
|
Arc::new(LocalFileOperations::new()),
|
|
)
|
|
.unwrap()
|
|
}
|
|
|
|
fn one_file_plan(source: Location, destination: Location, kind: OperationKind) -> OperationPlan {
|
|
let mut epochs = BTreeMap::new();
|
|
for (endpoint, epoch) in [(source.source.clone(), 1), (destination.source.clone(), 1)] {
|
|
if matches!(endpoint, SourceId::Ssh(_)) {
|
|
epochs.insert(endpoint, epoch);
|
|
}
|
|
}
|
|
OperationPlan::new(
|
|
PlanId::new(1),
|
|
PlanGeneration::new(1),
|
|
kind,
|
|
vec![SourceItem::new(ItemId::new(1), source)],
|
|
destination,
|
|
CollisionPolicy::Ask,
|
|
Some(1),
|
|
None,
|
|
epochs,
|
|
)
|
|
.unwrap()
|
|
}
|
|
|
|
async fn closed_part(
|
|
operations: &SftpFileOperations,
|
|
destination: &Location,
|
|
contents: &[u8],
|
|
) -> PartFile {
|
|
let mut writer = operations.open_part(destination).await.unwrap();
|
|
operations.write_part(&mut writer, contents).await.unwrap();
|
|
operations.flush_and_close(writer).await.unwrap()
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn local_to_sftp_streams_through_generic_executor_and_preserves_source() {
|
|
let local = TempDir::new().unwrap();
|
|
let source = Location::local(local.path().join("source.bin"));
|
|
tokio::fs::write(source.path(), vec![b'x'; 150_000])
|
|
.await
|
|
.unwrap();
|
|
let source_handle = local_handle();
|
|
let remote = FakeTransport::new("edge", 1).with_dir("/out");
|
|
let destination = remote.location("/out/source.bin");
|
|
let destination_operations = remote.operations();
|
|
let destination_handle = remote.remote_handle(
|
|
&destination_operations,
|
|
MemoryFs::new().with_dir(remote.location("/out")),
|
|
);
|
|
|
|
let results = execute_copy_move(
|
|
&one_file_plan(source.clone(), remote.location("/out"), OperationKind::Copy),
|
|
&source_handle,
|
|
&destination_handle,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(results[0].outcome().commit(), CommitOutcome::Committed);
|
|
assert_eq!(
|
|
remote.memory.file_contents(&destination).unwrap().len(),
|
|
150_000
|
|
);
|
|
assert_eq!(tokio::fs::read(source.path()).await.unwrap().len(), 150_000);
|
|
assert!(remote.memory.part_locations().is_empty());
|
|
assert_eq!(remote.mtime_calls.load(Ordering::Acquire), 1);
|
|
#[cfg(unix)]
|
|
assert_eq!(remote.permission_calls.load(Ordering::Acquire), 1);
|
|
assert!(
|
|
destination_operations.warnings().is_empty(),
|
|
"unexpected warnings: {:?}",
|
|
destination_operations.warnings()
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn generic_executor_reports_unsupported_metadata_capabilities() {
|
|
let local = TempDir::new().unwrap();
|
|
let source = Location::local(local.path().join("source.bin"));
|
|
tokio::fs::write(source.path(), b"contents").await.unwrap();
|
|
let mut remote = FakeTransport::new("edge", 1).with_dir("/out");
|
|
remote.capabilities.permissions = false;
|
|
remote.capabilities.mtime = false;
|
|
let operations = remote.operations();
|
|
let destination_handle = remote.remote_handle(
|
|
&operations,
|
|
MemoryFs::new().with_dir(remote.location("/out")),
|
|
);
|
|
|
|
let results = execute_copy_move(
|
|
&one_file_plan(source, remote.location("/out"), OperationKind::Copy),
|
|
&local_handle(),
|
|
&destination_handle,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(results[0].outcome().commit(), CommitOutcome::Committed);
|
|
assert_eq!(remote.permission_calls.load(Ordering::Acquire), 0);
|
|
assert_eq!(remote.mtime_calls.load(Ordering::Acquire), 0);
|
|
let warnings = operations.take_capability_warnings();
|
|
assert_eq!(warnings.len(), 2);
|
|
assert!(
|
|
warnings
|
|
.iter()
|
|
.any(|warning| warning.contains("Permission"))
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn sftp_to_local_streams_without_a_full_remote_download() {
|
|
let remote = FakeTransport::new("edge", 1).with_file("/source/data.bin", b"remote contents");
|
|
remote.memory.set_read_chunk_size(3);
|
|
let source = remote.location("/source/data.bin");
|
|
let source_operations = remote.operations();
|
|
let source_handle = remote.remote_handle(
|
|
&source_operations,
|
|
MemoryFs::new().with_file(source.clone(), b"remote contents"),
|
|
);
|
|
let local = TempDir::new().unwrap();
|
|
let destination_handle = local_handle();
|
|
let final_destination = Location::local(local.path().join("data.bin"));
|
|
|
|
let results = execute_copy_move(
|
|
&one_file_plan(
|
|
source.clone(),
|
|
Location::local(local.path()),
|
|
OperationKind::Copy,
|
|
),
|
|
&source_handle,
|
|
&destination_handle,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(results[0].outcome().commit(), CommitOutcome::Committed);
|
|
assert_eq!(
|
|
tokio::fs::read(final_destination.path()).await.unwrap(),
|
|
b"remote contents"
|
|
);
|
|
assert_eq!(
|
|
remote.memory.file_contents(&source).unwrap(),
|
|
b"remote contents"
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn sftp_a_to_sftp_b_uses_client_streams_and_independent_epochs() {
|
|
let source_remote = FakeTransport::new("source", 4).with_file("/in/data", b"via client");
|
|
source_remote.memory.set_read_chunk_size(2);
|
|
let destination_remote = FakeTransport::new("destination", 9).with_dir("/out");
|
|
destination_remote.memory.set_write_chunk_size(1);
|
|
let source = source_remote.location("/in/data");
|
|
let destination = destination_remote.location("/out/data");
|
|
let source_operations = source_remote.operations();
|
|
let destination_operations = destination_remote.operations();
|
|
let source_handle = source_remote.remote_handle(
|
|
&source_operations,
|
|
MemoryFs::new().with_file(source.clone(), b"via client"),
|
|
);
|
|
let destination_handle = destination_remote.remote_handle(
|
|
&destination_operations,
|
|
MemoryFs::new().with_dir(destination_remote.location("/out")),
|
|
);
|
|
let mut plan = one_file_plan(
|
|
source.clone(),
|
|
destination_remote.location("/out"),
|
|
OperationKind::Copy,
|
|
);
|
|
let mut epochs = BTreeMap::from([(source.source.clone(), 4), (destination.source.clone(), 9)]);
|
|
plan = OperationPlan::new(
|
|
plan.id(),
|
|
plan.generation(),
|
|
plan.kind(),
|
|
plan.sources().to_vec(),
|
|
plan.destination().clone(),
|
|
plan.policy(),
|
|
plan.expected_items(),
|
|
plan.expected_bytes(),
|
|
std::mem::take(&mut epochs),
|
|
)
|
|
.unwrap();
|
|
|
|
let results = execute_copy_move(
|
|
&plan,
|
|
&source_handle,
|
|
&destination_handle,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(results[0].outcome().commit(), CommitOutcome::Committed);
|
|
assert_eq!(
|
|
destination_remote
|
|
.memory
|
|
.file_contents(&destination)
|
|
.unwrap(),
|
|
b"via client"
|
|
);
|
|
assert_eq!(
|
|
source_remote.memory.file_contents(&source).unwrap(),
|
|
b"via client"
|
|
);
|
|
assert_eq!(source_operations.epoch(), 4);
|
|
assert_eq!(destination_operations.epoch(), 9);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn partial_files_and_staging_roots_are_siblings_of_destination() {
|
|
let remote = FakeTransport::new("edge", 1).with_dir("/out");
|
|
let operations = remote.operations();
|
|
let destination = remote.location("/out/final");
|
|
let writer = operations.open_part(&destination).await.unwrap();
|
|
let part = writer.part().location().clone();
|
|
assert_eq!(part.parent(), destination.parent());
|
|
assert_ne!(part.parent(), Some(destination.clone()));
|
|
drop(writer);
|
|
|
|
let staging = operations.create_staging_dir(&destination).await.unwrap();
|
|
assert_eq!(staging.location().parent(), destination.parent());
|
|
assert_ne!(staging.location().parent(), Some(destination.clone()));
|
|
assert!(
|
|
remote
|
|
.create_dir_calls
|
|
.lock()
|
|
.unwrap()
|
|
.contains(&staging.location().path)
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn directory_copy_commits_one_sibling_staging_tree() {
|
|
let local = TempDir::new().unwrap();
|
|
let source = Location::local(local.path().join("tree"));
|
|
tokio::fs::create_dir_all(source.path().join("nested"))
|
|
.await
|
|
.unwrap();
|
|
tokio::fs::write(source.path().join("nested/file"), b"nested")
|
|
.await
|
|
.unwrap();
|
|
let source_handle = local_handle();
|
|
let remote = FakeTransport::new("edge", 1).with_dir("/out");
|
|
let operations = remote.operations();
|
|
let destination_handle = remote.remote_handle(
|
|
&operations,
|
|
MemoryFs::new().with_dir(remote.location("/out")),
|
|
);
|
|
|
|
let results = execute_copy_move(
|
|
&one_file_plan(source, remote.location("/out"), OperationKind::Copy),
|
|
&source_handle,
|
|
&destination_handle,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(results[0].outcome().commit(), CommitOutcome::Committed);
|
|
assert_eq!(
|
|
remote
|
|
.memory
|
|
.file_contents(&remote.location("/out/tree/nested/file"))
|
|
.unwrap(),
|
|
b"nested"
|
|
);
|
|
let created = remote.create_dir_calls.lock().unwrap().clone();
|
|
assert_eq!(created[0].parent(), Some(Path::new("/out")));
|
|
assert_eq!(remote.rename_calls.load(Ordering::Acquire), 2);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn write_timeout_is_unknown_leaves_part_and_never_deletes_move_source() {
|
|
let local = TempDir::new().unwrap();
|
|
let source = Location::local(local.path().join("source"));
|
|
tokio::fs::write(source.path(), b"source").await.unwrap();
|
|
let source_handle = local_handle();
|
|
let remote = FakeTransport::new("edge", 1).with_dir("/out");
|
|
remote.fail_stream(StreamOperation::Write, FsError::Timeout);
|
|
let operations = remote.operations();
|
|
let destination_handle = remote.remote_handle(
|
|
&operations,
|
|
MemoryFs::new().with_dir(remote.location("/out")),
|
|
);
|
|
|
|
let results = execute_copy_move(
|
|
&one_file_plan(source.clone(), remote.location("/out"), OperationKind::Move),
|
|
&source_handle,
|
|
&destination_handle,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(results[0].outcome().commit(), CommitOutcome::Unknown);
|
|
assert!(results[0].partial().is_some());
|
|
assert_eq!(remote.memory.part_locations().len(), 1);
|
|
assert_eq!(tokio::fs::read(source.path()).await.unwrap(), b"source");
|
|
assert_eq!(
|
|
remote.memory.file_contents(&remote.location("/out/source")),
|
|
Err(FsError::NotFound)
|
|
);
|
|
assert_eq!(remote.rename_calls.load(Ordering::Acquire), 0);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn read_and_open_part_failures_preserve_source_without_destination_mutation() {
|
|
let source_remote = FakeTransport::new("edge", 1).with_file("/source", b"source");
|
|
source_remote
|
|
.memory
|
|
.fail_next(TransferOperation::Read, FsError::Timeout);
|
|
let source = source_remote.location("/source");
|
|
let source_operations = source_remote.operations();
|
|
let source_handle = source_remote.remote_handle(
|
|
&source_operations,
|
|
MemoryFs::new().with_file(source.clone(), b"source"),
|
|
);
|
|
let local = TempDir::new().unwrap();
|
|
let destination_handle = local_handle();
|
|
let results = execute_copy_move(
|
|
&one_file_plan(
|
|
source.clone(),
|
|
Location::local(local.path()),
|
|
OperationKind::Move,
|
|
),
|
|
&source_handle,
|
|
&destination_handle,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
assert_eq!(results[0].outcome().commit(), CommitOutcome::NotAttempted);
|
|
assert_eq!(
|
|
source_remote.memory.file_contents(&source).unwrap(),
|
|
b"source"
|
|
);
|
|
assert!(!local.path().join("source").exists());
|
|
|
|
let local_source = Location::local(local.path().join("input"));
|
|
tokio::fs::write(local_source.path(), b"input")
|
|
.await
|
|
.unwrap();
|
|
let source_handle = local_handle();
|
|
let destination_remote = FakeTransport::new("edge", 1).with_dir("/out");
|
|
destination_remote
|
|
.memory
|
|
.fail_next(TransferOperation::OpenPart, FsError::PermissionDenied);
|
|
let destination_operations = destination_remote.operations();
|
|
let destination_handle = destination_remote.remote_handle(
|
|
&destination_operations,
|
|
MemoryFs::new().with_dir(destination_remote.location("/out")),
|
|
);
|
|
let results = execute_copy_move(
|
|
&one_file_plan(
|
|
local_source.clone(),
|
|
destination_remote.location("/out"),
|
|
OperationKind::Move,
|
|
),
|
|
&source_handle,
|
|
&destination_handle,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
assert_eq!(results[0].outcome().commit(), CommitOutcome::NotCommitted);
|
|
assert!(destination_remote.memory.part_locations().is_empty());
|
|
assert_eq!(
|
|
tokio::fs::read(local_source.path()).await.unwrap(),
|
|
b"input"
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn source_delete_failure_after_commit_is_partial_and_preserves_both_copies() {
|
|
let remote = FakeTransport::new("edge", 1).with_file("/source", b"source");
|
|
remote
|
|
.memory
|
|
.fail_next(TransferOperation::RemoveFile, FsError::PermissionDenied);
|
|
let source = remote.location("/source");
|
|
let operations = remote.operations();
|
|
let source_handle = remote.remote_handle(
|
|
&operations,
|
|
MemoryFs::new().with_file(source.clone(), b"source"),
|
|
);
|
|
let local = TempDir::new().unwrap();
|
|
let destination_handle = local_handle();
|
|
|
|
let results = execute_copy_move(
|
|
&one_file_plan(
|
|
source.clone(),
|
|
Location::local(local.path()),
|
|
OperationKind::Move,
|
|
),
|
|
&source_handle,
|
|
&destination_handle,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(results[0].outcome().commit(), CommitOutcome::Committed);
|
|
assert_eq!(
|
|
results[0].outcome().source_cleanup(),
|
|
SourceCleanupOutcome::Failed
|
|
);
|
|
assert_eq!(remote.memory.file_contents(&source).unwrap(), b"source");
|
|
assert_eq!(
|
|
tokio::fs::read(local.path().join("source")).await.unwrap(),
|
|
b"source"
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn flush_close_and_close_after_apply_are_unknown_without_retry() {
|
|
for (operation, error) in [
|
|
(StreamOperation::Flush, FsError::Disconnected),
|
|
(StreamOperation::Close, FsError::Timeout),
|
|
] {
|
|
let remote = FakeTransport::new("edge", 1).with_dir("/out");
|
|
remote.fail_stream_after_apply(operation, error.clone());
|
|
let operations = remote.operations();
|
|
let destination = remote.location("/out/file");
|
|
let mut writer = operations.open_part(&destination).await.unwrap();
|
|
operations.write_part(&mut writer, b"data").await.unwrap();
|
|
let part = writer.part().clone();
|
|
|
|
assert_eq!(operations.flush_and_close(writer).await.unwrap_err(), error);
|
|
assert_eq!(remote.part_contents(part.location()).unwrap(), b"data");
|
|
assert_eq!(remote.rename_calls.load(Ordering::Acquire), 0);
|
|
assert_eq!(operations.warnings(), Vec::new());
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn size_mismatch_and_collision_recheck_do_not_commit_or_replace_destination() {
|
|
let remote = FakeTransport::new("edge", 1).with_dir("/out");
|
|
remote.wrong_part_size.store(true, Ordering::Release);
|
|
let operations = remote.operations();
|
|
let destination = remote.location("/out/file");
|
|
let part = closed_part(&operations, &destination, b"data").await;
|
|
assert!(
|
|
operations
|
|
.commit_part(part)
|
|
.await
|
|
.unwrap_err()
|
|
.to_string()
|
|
.contains("size")
|
|
);
|
|
assert_eq!(remote.rename_calls.load(Ordering::Acquire), 0);
|
|
|
|
let local = TempDir::new().unwrap();
|
|
let source = Location::local(local.path().join("source"));
|
|
tokio::fs::write(source.path(), b"new").await.unwrap();
|
|
let source_handle = local_handle();
|
|
let collision_remote = FakeTransport::new("edge", 1).with_dir("/out");
|
|
let collision_operations = collision_remote.operations();
|
|
let collision_destination = collision_remote.location("/out/source");
|
|
// The destination appears after the first bytes have been written, after the executor's
|
|
// initial collision check but before its mandatory pre-commit recheck.
|
|
*collision_remote.after_write_destination.lock().unwrap() = Some(collision_destination.clone());
|
|
let destination_handle = collision_remote.remote_handle(
|
|
&collision_operations,
|
|
MemoryFs::new().with_dir(collision_remote.location("/out")),
|
|
);
|
|
let results = execute_copy_move(
|
|
&one_file_plan(
|
|
source.clone(),
|
|
collision_remote.location("/out"),
|
|
OperationKind::Copy,
|
|
),
|
|
&source_handle,
|
|
&destination_handle,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
assert_eq!(results[0].outcome().commit(), CommitOutcome::NotCommitted);
|
|
assert_eq!(
|
|
collision_remote
|
|
.memory
|
|
.file_contents(&collision_destination)
|
|
.unwrap(),
|
|
b"existing"
|
|
);
|
|
assert_eq!(tokio::fs::read(source.path()).await.unwrap(), b"new");
|
|
assert_eq!(collision_remote.rename_calls.load(Ordering::Acquire), 0);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn after_apply_commit_disconnect_reconciles_or_remains_unknown_without_source_delete() {
|
|
let remote = FakeTransport::new("edge", 1)
|
|
.with_file("/source", b"source")
|
|
.with_dir("/out");
|
|
let operations = remote.operations();
|
|
let destination = remote.location("/out/file");
|
|
let part = closed_part(&operations, &destination, b"committed").await;
|
|
remote
|
|
.memory
|
|
.disconnect_after_apply(TransferOperation::Commit);
|
|
|
|
assert_eq!(
|
|
operations.commit_part(part).await.unwrap_err(),
|
|
FsError::Disconnected
|
|
);
|
|
assert_eq!(
|
|
remote.memory.file_contents(&destination).unwrap(),
|
|
b"committed"
|
|
);
|
|
assert_eq!(
|
|
remote
|
|
.memory
|
|
.file_contents(&remote.location("/source"))
|
|
.unwrap(),
|
|
b"source"
|
|
);
|
|
assert_eq!(remote.rename_calls.load(Ordering::Acquire), 1);
|
|
|
|
let local = TempDir::new().unwrap();
|
|
let source = Location::local(local.path().join("source"));
|
|
tokio::fs::write(source.path(), b"source").await.unwrap();
|
|
let source_handle = local_handle();
|
|
let unknown_remote = FakeTransport::new("edge", 1).with_dir("/out");
|
|
unknown_remote
|
|
.memory
|
|
.disconnect_after_apply(TransferOperation::Commit);
|
|
unknown_remote
|
|
.disconnect_on_commit
|
|
.store(true, Ordering::Release);
|
|
let unknown_operations = unknown_remote.operations();
|
|
let destination_handle = unknown_remote.remote_handle(
|
|
&unknown_operations,
|
|
MemoryFs::new().with_dir(unknown_remote.location("/out")),
|
|
);
|
|
|
|
let results = execute_copy_move(
|
|
&one_file_plan(
|
|
source.clone(),
|
|
unknown_remote.location("/out"),
|
|
OperationKind::Move,
|
|
),
|
|
&source_handle,
|
|
&destination_handle,
|
|
&CancellationToken::new(),
|
|
)
|
|
.await;
|
|
|
|
// The rename was applied but the dead transport prevents reconciliation. This is Unknown, not
|
|
// success and not NotCommitted; no automatic retry or source deletion is permitted.
|
|
assert_eq!(results[0].outcome().commit(), CommitOutcome::Unknown);
|
|
assert!(results[0].partial().is_some());
|
|
assert_eq!(unknown_remote.rename_calls.load(Ordering::Acquire), 1);
|
|
assert_eq!(tokio::fs::read(source.path()).await.unwrap(), b"source");
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn reconnect_rejects_stale_writes_results_and_old_part_ownership() {
|
|
let old_transport = FakeTransport::new("edge", 7).with_dir("/out");
|
|
let old = old_transport.operations();
|
|
let destination = old_transport.location("/out/file");
|
|
let part = closed_part(&old, &destination, b"old").await;
|
|
let part_location = part.location().clone();
|
|
|
|
// Pause the old commit after it entered transport, then reconnect before its result returns.
|
|
let gate = old_transport.memory.gate_next(TransferOperation::Commit);
|
|
let old_task = {
|
|
let old = old.clone();
|
|
let part = part.clone();
|
|
tokio::spawn(async move { old.commit_part(part).await })
|
|
};
|
|
tokio::time::timeout(Duration::from_secs(1), gate.wait_entered())
|
|
.await
|
|
.expect("old commit did not enter transport");
|
|
let mut new_transport = FakeTransport::new("edge", 8).with_dir("/out");
|
|
new_transport.memory = old_transport.memory.reconnect(8);
|
|
let current = old.reconnect(8, Arc::new(new_transport.clone())).unwrap();
|
|
gate.release();
|
|
assert_eq!(
|
|
tokio::time::timeout(Duration::from_secs(1), old_task)
|
|
.await
|
|
.expect("stale commit did not finish")
|
|
.unwrap()
|
|
.unwrap_err(),
|
|
FsError::Disconnected
|
|
);
|
|
assert_eq!(old_transport.rename_calls.load(Ordering::Acquire), 1);
|
|
assert_eq!(
|
|
current.commit_part(part).await.unwrap_err(),
|
|
FsError::PermissionDenied
|
|
);
|
|
assert_eq!(old_transport.part_owner(&part_location), Some(7));
|
|
assert_eq!(old_transport.part_contents(&part_location).unwrap(), b"old");
|
|
|
|
let stale_part = old.open_part(&destination).await;
|
|
assert!(stale_part.is_err());
|
|
let mut current_writer = current.open_part(&destination).await.unwrap();
|
|
current
|
|
.write_part(&mut current_writer, b"new")
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(
|
|
old.write_part(&mut current_writer, b"stale")
|
|
.await
|
|
.unwrap_err(),
|
|
FsError::Disconnected
|
|
);
|
|
assert_eq!(
|
|
old_transport.memory.file_contents(&destination),
|
|
Err(FsError::NotFound)
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn manager_style_invalidation_disconnects_shared_readers_and_writers() {
|
|
let remote = FakeTransport::new("edge", 11)
|
|
.with_file("/source", b"source")
|
|
.with_dir("/out");
|
|
let operations = remote.operations();
|
|
let source = remote.location("/source");
|
|
let mut reader = operations.open_read(&source).await.unwrap();
|
|
let destination = remote.location("/out/file");
|
|
let mut writer = operations.open_part(&destination).await.unwrap();
|
|
|
|
// This is the exact FileOperations hook used by ConnectionManager::invalidate_if_epoch.
|
|
operations.invalidate_session(11);
|
|
|
|
assert_eq!(
|
|
reader.read(&mut [0; 1]).await.unwrap_err().kind(),
|
|
io::ErrorKind::NotConnected
|
|
);
|
|
assert_eq!(
|
|
operations
|
|
.write_part(&mut writer, b"stale")
|
|
.await
|
|
.unwrap_err(),
|
|
FsError::Disconnected
|
|
);
|
|
assert_eq!(remote.memory.part_locations().len(), 1);
|
|
assert_eq!(remote.memory.file_contents(&source).unwrap(), b"source");
|
|
|
|
// A late invalidation for the old epoch cannot disconnect a replacement session.
|
|
let replacement_transport = FakeTransport::new("edge", 12).with_dir("/out");
|
|
let current = operations
|
|
.reconnect(12, Arc::new(replacement_transport))
|
|
.unwrap();
|
|
current.invalidate_session(11);
|
|
assert!(current.is_current());
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn metadata_capabilities_emit_warnings_but_do_not_block_commit() {
|
|
let mut remote = FakeTransport::new("edge", 1).with_dir("/out");
|
|
remote.capabilities.permissions = false;
|
|
remote.capabilities.mtime = false;
|
|
let operations = remote.operations();
|
|
let destination = remote.location("/out/file");
|
|
let part = closed_part(&operations, &destination, b"data").await;
|
|
let source = Entry::new("file", EntryKind::File).with_metadata(
|
|
Some(4),
|
|
Some(SystemTime::UNIX_EPOCH + Duration::from_secs(10)),
|
|
Some(0o640),
|
|
);
|
|
|
|
let warnings = operations.preserve_metadata(&part, &source).await.unwrap();
|
|
assert_eq!(warnings.len(), 2);
|
|
operations.commit_part(part).await.unwrap();
|
|
assert_eq!(remote.memory.file_contents(&destination).unwrap(), b"data");
|
|
assert_eq!(operations.warnings(), warnings);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn remove_file_remove_dir_and_discard_are_typed_and_owned() {
|
|
let remote = FakeTransport::new("edge", 1)
|
|
.with_file("/delete", b"delete")
|
|
.with_dir("/empty")
|
|
.with_dir("/out");
|
|
let operations = remote.operations();
|
|
let local = Location::local("/delete");
|
|
assert_eq!(
|
|
operations.remove_file(&local).await.unwrap_err(),
|
|
FsError::Disconnected
|
|
);
|
|
|
|
let destination = remote.location("/out/file");
|
|
let part = closed_part(&operations, &destination, b"data").await;
|
|
let part_location = part.location().clone();
|
|
operations.discard_part(part).await.unwrap();
|
|
assert_eq!(remote.part_contents(&part_location), Err(FsError::NotFound));
|
|
|
|
operations
|
|
.remove_file(&remote.location("/delete"))
|
|
.await
|
|
.unwrap();
|
|
operations
|
|
.remove_dir(&remote.location("/empty"))
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(
|
|
remote.memory.file_contents(&remote.location("/delete")),
|
|
Err(FsError::NotFound)
|
|
);
|
|
assert_eq!(
|
|
remote
|
|
.memory
|
|
.metadata(&remote.location("/empty"), false)
|
|
.await,
|
|
Err(FsError::NotFound)
|
|
);
|
|
}
|