use std::collections::HashMap;
use std::fs::Metadata;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use async_trait::async_trait;
use tokio_util::sync::CancellationToken;
use crate::error::{ExecutionError, FileError, FileErrorCode};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileKind {
File,
Directory,
Symlink,
}
#[derive(Debug, Clone)]
pub struct FileInfo {
pub name: String,
pub path: PathBuf,
pub kind: FileKind,
pub size: u64,
pub mtime_ms: i64,
}
#[derive(Debug, Clone)]
pub enum FileContent {
Text(String),
Bytes(Vec<u8>),
}
impl FileContent {
pub fn as_bytes(&self) -> &[u8] {
match self {
FileContent::Text(s) => s.as_bytes(),
FileContent::Bytes(b) => b,
}
}
}
impl From<String> for FileContent {
fn from(s: String) -> Self {
FileContent::Text(s)
}
}
impl From<&str> for FileContent {
fn from(s: &str) -> Self {
FileContent::Text(s.to_string())
}
}
impl From<Vec<u8>> for FileContent {
fn from(b: Vec<u8>) -> Self {
FileContent::Bytes(b)
}
}
#[derive(Debug, Clone)]
pub struct ShellOutput {
pub stdout: String,
pub stderr: String,
pub exit_code: i32,
}
#[derive(Clone, Debug)]
pub struct ShellOverride {
pub program: PathBuf,
pub args: Vec<String>,
}
pub struct ShellExecOptions<'a> {
pub shell: Option<ShellOverride>,
pub cwd: Option<PathBuf>,
pub env: Option<HashMap<String, String>>,
pub inherit_env: bool,
pub timeout: Option<f64>,
pub cancel: Option<&'a CancellationToken>,
pub on_stdout: Option<Box<dyn FnMut(&str) + Send + 'a>>,
pub on_stderr: Option<Box<dyn FnMut(&str) + Send + 'a>>,
}
impl<'a> Default for ShellExecOptions<'a> {
fn default() -> Self {
Self {
shell: None,
cwd: None,
env: None,
inherit_env: true,
timeout: None,
cancel: None,
on_stdout: None,
on_stderr: None,
}
}
}
impl<'a> ShellExecOptions<'a> {
pub fn new() -> Self {
Self::default()
}
}
pub trait WriterLease: Send + Sync {
fn verify_fence(&self) -> Result<(), FileError> {
Ok(())
}
}
#[derive(Clone)]
pub struct AppendReceipt {
pub reader: Arc<dyn ReadFile>,
pub offset: u64,
pub length: usize,
}
pub struct NativeAppendMetadata {
pub before: Metadata,
pub after: Metadata,
}
#[async_trait]
pub trait AppendFile: Send + Sync {
async fn append(&mut self, bytes: &[u8]) -> Result<(), FileError>;
async fn append_with_receipt(
&mut self,
bytes: &[u8],
) -> Result<Option<AppendReceipt>, FileError> {
self.append(bytes).await?;
Ok(None)
}
async fn append_with_native_metadata(
&mut self,
bytes: &[u8],
) -> Result<(Option<AppendReceipt>, Option<NativeAppendMetadata>), FileError> {
Ok((self.append_with_receipt(bytes).await?, None))
}
}
#[async_trait]
pub trait ReadFile: Send + Sync {
async fn read_all(&self) -> Result<Vec<u8>, FileError>;
async fn read_range(&self, offset: u64, length: usize) -> Result<Vec<u8>, FileError>;
fn native_metadata(&self) -> Option<Metadata> {
None
}
async fn byte_len(&self) -> Result<Option<u64>, FileError> {
Ok(None)
}
}
#[async_trait]
pub trait FileSystem: Send + Sync {
fn cwd(&self) -> &Path;
fn native_file_path(&self, _path: &str) -> Option<PathBuf> {
None
}
async fn absolute_path(
&self,
path: &str,
cancel: Option<&CancellationToken>,
) -> Result<PathBuf, FileError>;
async fn join_path(
&self,
parts: &[&str],
cancel: Option<&CancellationToken>,
) -> Result<PathBuf, FileError>;
async fn read_text_file(
&self,
path: &str,
cancel: Option<&CancellationToken>,
) -> Result<String, FileError>;
async fn read_text_lines(
&self,
path: &str,
max_lines: Option<usize>,
cancel: Option<&CancellationToken>,
) -> Result<Vec<String>, FileError>;
async fn read_binary_file(
&self,
path: &str,
cancel: Option<&CancellationToken>,
) -> Result<Vec<u8>, FileError>;
async fn write_file(
&self,
path: &str,
content: FileContent,
cancel: Option<&CancellationToken>,
) -> Result<(), FileError>;
async fn write_new_file(
&self,
path: &str,
_content: FileContent,
_cancel: Option<&CancellationToken>,
) -> Result<(), FileError> {
Err(FileError::new(
FileErrorCode::NotSupported,
"exclusive file creation is unsupported",
)
.with_path(path))
}
async fn append_file(
&self,
path: &str,
content: FileContent,
cancel: Option<&CancellationToken>,
) -> Result<(), FileError>;
async fn open_append_file(
&self,
_path: &str,
) -> Result<Option<Box<dyn AppendFile>>, FileError> {
Ok(None)
}
async fn try_acquire_writer_lease(
&self,
_path: &str,
) -> Result<Option<Box<dyn WriterLease>>, FileError> {
Ok(None)
}
async fn sync_file(
&self,
_path: &str,
_data_only: bool,
_cancel: Option<&CancellationToken>,
) -> Result<(), FileError> {
Ok(())
}
async fn sync_directory(
&self,
_path: &str,
_cancel: Option<&CancellationToken>,
) -> Result<(), FileError> {
Ok(())
}
async fn sync_file_and_parent(
&self,
path: &str,
_cancel: Option<&CancellationToken>,
) -> Result<(), FileError> {
Err(FileError::new(
FileErrorCode::NotSupported,
"physical journal synchronization is unsupported",
)
.with_path(path))
}
async fn open_read_file(
&self,
_path: &str,
) -> Result<Option<std::sync::Arc<dyn ReadFile>>, FileError> {
Ok(None)
}
async fn truncate_file(
&self,
path: &str,
len: u64,
cancel: Option<&CancellationToken>,
) -> Result<(), FileError> {
let _ = (len, cancel);
Err(FileError::new(
FileErrorCode::NotSupported,
"file truncation is unavailable",
)
.with_path(path))
}
async fn rename_file(
&self,
source: &str,
dest: &str,
cancel: Option<&CancellationToken>,
) -> Result<(), FileError>;
async fn file_info(
&self,
path: &str,
cancel: Option<&CancellationToken>,
) -> Result<FileInfo, FileError>;
async fn list_dir(
&self,
path: &str,
cancel: Option<&CancellationToken>,
) -> Result<Vec<FileInfo>, FileError>;
async fn has_file_with_suffix(
&self,
path: &str,
suffix: &str,
cancel: Option<&CancellationToken>,
) -> Result<bool, FileError> {
check_cancel_file(cancel, Some(path))?;
let entries = self.list_dir(path, cancel).await?;
check_cancel_file(cancel, Some(path))?;
Ok(entries
.iter()
.any(|entry| entry.kind != FileKind::Directory && entry.name.ends_with(suffix)))
}
async fn canonical_path(
&self,
path: &str,
cancel: Option<&CancellationToken>,
) -> Result<PathBuf, FileError>;
async fn exists(
&self,
path: &str,
cancel: Option<&CancellationToken>,
) -> Result<bool, FileError>;
async fn create_dir(
&self,
path: &str,
recursive: bool,
cancel: Option<&CancellationToken>,
) -> Result<(), FileError>;
async fn remove(
&self,
path: &str,
recursive: bool,
force: bool,
cancel: Option<&CancellationToken>,
) -> Result<(), FileError>;
async fn create_temp_dir(
&self,
prefix: Option<&str>,
cancel: Option<&CancellationToken>,
) -> Result<PathBuf, FileError>;
async fn create_temp_file(
&self,
prefix: &str,
suffix: &str,
cancel: Option<&CancellationToken>,
) -> Result<PathBuf, FileError>;
async fn cleanup(&self);
}
#[async_trait]
pub trait Shell: Send + Sync {
async fn exec<'a>(
&'a self,
command: &str,
options: ShellExecOptions<'a>,
) -> Result<ShellOutput, ExecutionError>;
async fn cleanup(&self);
}
#[async_trait]
pub trait ExecutionEnv: FileSystem + Shell {}
pub fn check_cancel_file(
cancel: Option<&CancellationToken>,
path: Option<&str>,
) -> Result<(), FileError> {
if let Some(t) = cancel {
if t.is_cancelled() {
let mut err = FileError::aborted();
if let Some(p) = path {
err = err.with_path(p);
}
return Err(err);
}
}
Ok(())
}
pub fn check_cancel_exec(cancel: Option<&CancellationToken>) -> Result<(), ExecutionError> {
if let Some(t) = cancel {
if t.is_cancelled() {
return Err(ExecutionError::aborted());
}
}
Ok(())
}
#[cfg(test)]
mod capability_tests {
use super::*;
#[derive(Default)]
struct LegacyAppender(Vec<u8>);
#[async_trait]
impl AppendFile for LegacyAppender {
async fn append(&mut self, bytes: &[u8]) -> Result<(), FileError> {
self.0.extend_from_slice(bytes);
Ok(())
}
}
struct LegacyReader;
#[async_trait]
impl ReadFile for LegacyReader {
async fn read_all(&self) -> Result<Vec<u8>, FileError> {
Ok(b"legacy".to_vec())
}
async fn read_range(&self, _offset: u64, _length: usize) -> Result<Vec<u8>, FileError> {
Err(FileError::new(FileErrorCode::NotSupported, "legacy reader"))
}
}
#[tokio::test]
async fn legacy_capabilities_keep_their_default_behavior() {
let mut writer = LegacyAppender::default();
let appender: &mut dyn AppendFile = &mut writer;
assert!(appender
.append_with_receipt(b"frame\n")
.await
.unwrap()
.is_none());
assert_eq!(writer.0, b"frame\n");
let reader: Arc<dyn ReadFile> = Arc::new(LegacyReader);
assert_eq!(reader.byte_len().await.unwrap(), None);
assert_eq!(reader.read_all().await.unwrap(), b"legacy");
}
#[tokio::test]
async fn default_receipt_method_preserves_append_errors() {
struct FailingAppender;
#[async_trait]
impl AppendFile for FailingAppender {
async fn append(&mut self, _bytes: &[u8]) -> Result<(), FileError> {
Err(FileError::new(FileErrorCode::Unknown, "append failed"))
}
}
assert!(FailingAppender.append_with_receipt(b"frame").await.is_err());
}
}