rcom/tests/sftp_create.rs
2026-12-05 23:30:06 +03:00

352 lines
12 KiB
Rust

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use async_trait::async_trait;
use rcom::domain::{Entry, EntryKind, HostAlias, Location};
use rcom::fs::{FileOperations, FsError, StagingOperations, TransferCapabilities};
use rcom::ssh::{SftpFileOperations, SftpReader, SftpTransferTransport, SftpWriter};
use tokio::sync::Notify;
#[derive(Default)]
struct FakeState {
entries: BTreeMap<PathBuf, EntryKind>,
canonical_targets: BTreeMap<PathBuf, PathBuf>,
metadata_calls: Vec<(PathBuf, bool)>,
create_file_calls: Vec<PathBuf>,
create_dir_calls: Vec<PathBuf>,
}
#[derive(Clone)]
struct FakeTransport {
host: HostAlias,
state: Arc<Mutex<FakeState>>,
close_error: Option<FsError>,
pause_create_file: bool,
create_file_started: Arc<Notify>,
resume_create_file: Arc<Notify>,
}
impl FakeTransport {
fn new(host: &str) -> Self {
Self {
host: HostAlias::new(host),
state: Arc::new(Mutex::new(FakeState::default())),
close_error: None,
pause_create_file: false,
create_file_started: Arc::new(Notify::new()),
resume_create_file: Arc::new(Notify::new()),
}
}
fn with_entry(self, path: &str, kind: EntryKind) -> Self {
self.state
.lock()
.unwrap()
.entries
.insert(PathBuf::from(path), kind);
self
}
fn with_canonical_target(self, path: &str, target: &str) -> Self {
self.state
.lock()
.unwrap()
.canonical_targets
.insert(PathBuf::from(path), PathBuf::from(target));
self
}
fn with_close_error(mut self, error: FsError) -> Self {
self.close_error = Some(error);
self
}
fn with_paused_create_file(mut self) -> Self {
self.pause_create_file = true;
self
}
fn operations(&self) -> SftpFileOperations {
SftpFileOperations::new(self.host.clone(), 1, Arc::new(self.clone()))
}
fn location(&self, path: &str) -> Location {
Location::ssh(self.host.clone(), path)
}
fn kind(&self, path: &str) -> Option<EntryKind> {
self.state
.lock()
.unwrap()
.entries
.get(Path::new(path))
.copied()
}
fn file_calls(&self) -> Vec<PathBuf> {
self.state.lock().unwrap().create_file_calls.clone()
}
fn dir_calls(&self) -> Vec<PathBuf> {
self.state.lock().unwrap().create_dir_calls.clone()
}
fn metadata_calls(&self) -> Vec<(PathBuf, bool)> {
self.state.lock().unwrap().metadata_calls.clone()
}
}
#[async_trait]
impl SftpTransferTransport for FakeTransport {
fn capabilities(&self) -> TransferCapabilities {
TransferCapabilities {
canonicalize: true,
regular_files: true,
permissions: false,
mtime: false,
atomic_rename: true,
sftp_version: Some(3),
}
}
async fn canonicalize(&self, path: &Path) -> Result<PathBuf, FsError> {
let state = self.state.lock().unwrap();
if !state.entries.contains_key(path) {
return Err(FsError::NotFound);
}
Ok(state
.canonical_targets
.get(path)
.cloned()
.unwrap_or_else(|| path.to_path_buf()))
}
async fn metadata(&self, path: &Path, follow_symlinks: bool) -> Result<Entry, FsError> {
let mut state = self.state.lock().unwrap();
state
.metadata_calls
.push((path.to_path_buf(), follow_symlinks));
let kind = state.entries.get(path).copied().ok_or(FsError::NotFound)?;
let name = path
.file_name()
.map(|name| name.to_os_string())
.unwrap_or_else(|| "/".into());
Ok(Entry::new(name, kind))
}
async fn open_read(&self, _path: &Path) -> Result<SftpReader, FsError> {
Err(FsError::Unsupported("read is not needed".into()))
}
async fn create_part(&self, _path: &Path) -> Result<SftpWriter, FsError> {
Err(FsError::Unsupported("parts are not needed".into()))
}
async fn create_file(&self, path: &Path) -> Result<(), FsError> {
{
let mut state = self.state.lock().unwrap();
state.create_file_calls.push(path.to_path_buf());
if state.entries.contains_key(path) {
return Err(FsError::Other("destination already exists".into()));
}
state.entries.insert(path.to_path_buf(), EntryKind::File);
}
if self.pause_create_file {
self.create_file_started.notify_one();
self.resume_create_file.notified().await;
}
if let Some(error) = &self.close_error {
return Err(error.clone());
}
Ok(())
}
async fn create_dir(&self, path: &Path) -> Result<(), FsError> {
let mut state = self.state.lock().unwrap();
state.create_dir_calls.push(path.to_path_buf());
if state.entries.contains_key(path) {
return Err(FsError::Other("destination already exists".into()));
}
state
.entries
.insert(path.to_path_buf(), EntryKind::Directory);
Ok(())
}
async fn rename(&self, _from: &Path, _to: &Path) -> Result<(), FsError> {
Err(FsError::Unsupported("rename is not needed".into()))
}
async fn remove_file(&self, _path: &Path) -> Result<(), FsError> {
Err(FsError::Unsupported("remove is not needed".into()))
}
async fn remove_dir(&self, _path: &Path) -> Result<(), FsError> {
Err(FsError::Unsupported("remove is not needed".into()))
}
}
#[tokio::test]
async fn creates_empty_file_and_directory_in_canonical_parent() {
let transport = FakeTransport::new("edge")
.with_entry("/", EntryKind::Directory)
.with_entry("/out", EntryKind::Directory);
let operations = transport.operations();
operations
.create_file(&transport.location("/out/new.txt"))
.await
.unwrap();
operations
.create_dir(&transport.location("/out/new-dir"))
.await
.unwrap();
assert_eq!(transport.kind("/out/new.txt"), Some(EntryKind::File));
assert_eq!(transport.kind("/out/new-dir"), Some(EntryKind::Directory));
assert_eq!(transport.file_calls(), [PathBuf::from("/out/new.txt")]);
assert_eq!(transport.dir_calls(), [PathBuf::from("/out/new-dir")]);
}
#[tokio::test]
async fn existing_file_and_directory_are_not_opened_or_replaced() {
let transport = FakeTransport::new("edge")
.with_entry("/", EntryKind::Directory)
.with_entry("/out", EntryKind::Directory)
.with_entry("/out/existing.txt", EntryKind::File)
.with_entry("/out/existing-dir", EntryKind::Directory);
let operations = transport.operations();
let file_result = operations
.create_file(&transport.location("/out/existing.txt"))
.await;
let dir_result = operations
.create_dir(&transport.location("/out/existing-dir"))
.await;
assert_eq!(
file_result,
Err(FsError::Other("destination already exists".into()))
);
assert_eq!(
dir_result,
Err(FsError::Other("destination already exists".into()))
);
assert!(transport.file_calls().is_empty());
assert!(transport.dir_calls().is_empty());
assert_eq!(transport.kind("/out/existing.txt"), Some(EntryKind::File));
assert_eq!(
transport.kind("/out/existing-dir"),
Some(EntryKind::Directory)
);
}
#[tokio::test]
async fn mixed_endpoint_is_disconnected_before_any_transport_mutation() {
let transport = FakeTransport::new("edge")
.with_entry("/", EntryKind::Directory)
.with_entry("/out", EntryKind::Directory);
let operations = transport.operations();
let file_result = operations
.create_file(&Location::local("/out/new.txt"))
.await;
let dir_result = operations
.create_dir(&Location::ssh(HostAlias::new("other"), "/out/new-dir"))
.await;
assert_eq!(file_result, Err(FsError::Disconnected));
assert_eq!(dir_result, Err(FsError::Disconnected));
assert!(transport.file_calls().is_empty());
assert!(transport.dir_calls().is_empty());
assert!(transport.metadata_calls().is_empty());
}
#[tokio::test]
async fn stale_epoch_rejects_new_directory_and_late_file_success() {
let transport = FakeTransport::new("edge")
.with_entry("/", EntryKind::Directory)
.with_entry("/out", EntryKind::Directory)
.with_paused_create_file();
let operations = Arc::new(transport.operations());
operations.invalidate();
let dir_result = operations
.create_dir(&transport.location("/out/stale-dir"))
.await;
assert_eq!(dir_result, Err(FsError::Disconnected));
assert!(transport.dir_calls().is_empty());
let current = SftpFileOperations::new(HostAlias::new("edge"), 1, Arc::new(transport.clone()));
let current = Arc::new(current);
let task_operations = current.clone();
let destination = transport.location("/out/late.txt");
let task = tokio::spawn(async move { task_operations.create_file(&destination).await });
transport.create_file_started.notified().await;
current.invalidate();
transport.resume_create_file.notify_one();
assert_eq!(task.await.unwrap(), Err(FsError::Disconnected));
assert_eq!(transport.kind("/out/late.txt"), Some(EntryKind::File));
assert_eq!(transport.file_calls(), [PathBuf::from("/out/late.txt")]);
}
#[tokio::test]
async fn symlink_parent_and_canonical_redirect_are_rejected() {
let transport = FakeTransport::new("edge")
.with_entry("/", EntryKind::Directory)
.with_entry("/out", EntryKind::Directory)
.with_entry("/out/link", EntryKind::Symlink)
.with_entry("/out/link/nested", EntryKind::Directory)
.with_canonical_target("/out/link", "/outside")
.with_canonical_target("/out/link/nested", "/outside/nested");
let operations = transport.operations();
let file_result = operations
.create_file(&transport.location("/out/link/new.txt"))
.await;
let dir_result = operations
.create_dir(&transport.location("/out/link/nested/new-dir"))
.await;
assert_eq!(
file_result,
Err(FsError::Other(
"destination parent is not a real directory".into()
))
);
assert_eq!(
dir_result,
Err(FsError::Other(
"destination parent differs from its canonical directory".into()
))
);
assert!(transport.file_calls().is_empty());
assert!(transport.dir_calls().is_empty());
assert_eq!(transport.kind("/outside/new.txt"), None);
assert_eq!(transport.kind("/outside/nested/new-dir"), None);
assert!(
transport
.metadata_calls()
.contains(&(PathBuf::from("/out/link"), false))
);
}
#[tokio::test]
async fn close_error_is_returned_without_retrying_create_new() {
let close_error = FsError::Other("close failed".into());
let transport = FakeTransport::new("edge")
.with_entry("/", EntryKind::Directory)
.with_entry("/out", EntryKind::Directory)
.with_close_error(close_error.clone());
let operations = transport.operations();
let result = operations
.create_file(&transport.location("/out/new.txt"))
.await;
assert_eq!(result, Err(close_error));
assert_eq!(transport.kind("/out/new.txt"), Some(EntryKind::File));
assert_eq!(transport.file_calls(), [PathBuf::from("/out/new.txt")]);
}