use std::collections::{HashMap, HashSet};
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use async_trait::async_trait;
use tokio_util::sync::CancellationToken;
use crate::env::{
check_cancel_exec, check_cancel_file, ExecutionEnv, FileContent, FileInfo, FileKind,
FileSystem, Shell, ShellExecOptions, ShellOutput, WriterLease,
};
use crate::error::{
io_to_file_error, ExecutionError, ExecutionErrorCode, FileError, FileErrorCode,
};
use crate::file_mutation_queue::{MutatingEnv, MutationQueueRegistry};
const MAX_TIMEOUT_MS: u64 = 2_147_483_647;
const MAX_TIMEOUT_SECONDS: f64 = 2_147_483.647;
const EXIT_STDIO_GRACE_MS: u64 = 100;
const NON_INTERACTIVE_SHELL_ENV: &[(&str, &str)] = &[
("GIT_TERMINAL_PROMPT", "0"),
("GCM_INTERACTIVE", "Never"),
("SSH_ASKPASS_REQUIRE", "never"),
];
#[derive(Clone, Copy)]
enum CommandTransport {
Argv,
Stdin,
}
struct ShellConfig {
shell: PathBuf,
args: Vec<String>,
transport: CommandTransport,
}
mod append;
mod read;
struct OsWriterLease {
file: std::fs::File,
fence: u64,
}
#[cfg(unix)]
impl Drop for OsWriterLease {
fn drop(&mut self) {
let _ = fs2::FileExt::unlock(&self.file);
}
}
impl WriterLease for OsWriterLease {
fn verify_fence(&self) -> Result<(), FileError> {
let mut probe = self
.file
.try_clone()
.map_err(|error| io_to_file_error(error, Some("writer lease fence")))?;
probe
.seek(SeekFrom::Start(0))
.map_err(|error| io_to_file_error(error, Some("writer lease fence")))?;
let mut contents = String::new();
probe
.read_to_string(&mut contents)
.map_err(|error| io_to_file_error(error, Some("writer lease fence")))?;
let current = contents.trim().parse::<u64>().map_err(|error| {
FileError::new(
FileErrorCode::Unknown,
format!("invalid persisted writer lease fence: {error}"),
)
})?;
if current != self.fence {
return Err(FileError::new(
FileErrorCode::PermissionDenied,
"writer lease fence changed; reopen the session",
));
}
Ok(())
}
}
pub const HOST_PRIVATE_ENV: &[&str] = &[rpi_plugin_sdk::SESSION_ID_ENV];
pub fn is_host_private_env(name: &str) -> bool {
HOST_PRIVATE_ENV.contains(&name) || rpi_plugin_sdk::SUBAGENT_PARENT_ENV.contains(&name)
}
pub struct OsExecutionEnv {
cwd: PathBuf,
shell_path: Option<PathBuf>,
shell_env: Option<HashMap<String, String>>,
environment: Option<HashMap<String, String>>,
active_pids: Arc<Mutex<HashSet<u32>>>,
registry: Arc<MutationQueueRegistry>,
}
impl OsExecutionEnv {
pub fn new() -> Self {
Self {
cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from("/")),
shell_path: None,
shell_env: None,
environment: None,
active_pids: Arc::new(Mutex::new(HashSet::new())),
registry: Arc::new(MutationQueueRegistry::new()),
}
}
pub fn with_cwd(cwd: PathBuf) -> Self {
Self {
cwd,
shell_path: None,
shell_env: None,
environment: None,
active_pids: Arc::new(Mutex::new(HashSet::new())),
registry: Arc::new(MutationQueueRegistry::new()),
}
}
pub fn with_shell_path(mut self, shell_path: PathBuf) -> Self {
self.shell_path = Some(shell_path);
self
}
pub fn with_shell_env(mut self, env: HashMap<String, String>) -> Self {
self.shell_env = Some(env);
self
}
pub fn with_environment(mut self, environment: HashMap<String, String>) -> Self {
self.environment = Some(environment);
self
}
pub fn has_explicit_environment(&self) -> bool {
self.environment.is_some()
}
fn resolve_path(&self, path: &str) -> PathBuf {
let cwd = &self.cwd;
let home = || match &self.environment {
Some(environment) => environment
.get(if cfg!(windows) { "USERPROFILE" } else { "HOME" })
.cloned()
.unwrap_or_default(),
None => home_dir_string(),
};
let mut p = path.to_string();
if p == "~" {
let home = home();
if self.environment.is_none() || !home.is_empty() {
p = home;
}
} else if let Some(rest) = p.strip_prefix("~/") {
let home = home();
if self.environment.is_none() || !home.is_empty() {
p = format!("{home}/{rest}");
}
} else if cfg!(windows) {
if let Some(rest) = p.strip_prefix("~\\") {
let home = home();
if self.environment.is_none() || !home.is_empty() {
p = format!("{home}\\{rest}");
}
}
}
if p.starts_with("file://") {
if let Some(local) = file_url_to_path(&p) {
p = local;
}
}
let pb = PathBuf::from(&p);
if pb.is_absolute() {
normalize_absolute(&pb)
} else {
normalize_absolute(&cwd.join(pb))
}
}
async fn get_shell_config(&self) -> Result<ShellConfig, ExecutionError> {
if let Some(sp) = &self.shell_path {
if sp.is_file() {
return Ok(bash_shell_config(sp.clone()));
}
return Err(ExecutionError::new(
ExecutionErrorCode::ShellUnavailable,
format!("Custom shell path not found: {}", sp.display()),
));
}
#[cfg(windows)]
{
if let Some(cfg) = windows_probe_bash().await {
return Ok(cfg);
}
return Err(ExecutionError::new(
ExecutionErrorCode::ShellUnavailable,
"bash not found. Install Git for Windows / MSYS2 / Cygwin, or set shellPath.",
));
}
#[cfg(not(windows))]
{
if std::path::Path::new("/bin/bash").is_file() {
return Ok(ShellConfig {
shell: PathBuf::from("/bin/bash"),
args: vec!["-c".to_string()],
transport: CommandTransport::Argv,
});
}
if let Some(found) =
run_command("which", &["bash"], std::time::Duration::from_millis(5000)).await
{
let trimmed = found.trim();
if !trimmed.is_empty() && std::path::Path::new(trimmed).is_file() {
return Ok(ShellConfig {
shell: PathBuf::from(trimmed),
args: vec!["-c".to_string()],
transport: CommandTransport::Argv,
});
}
}
return Ok(ShellConfig {
shell: PathBuf::from("sh"),
args: vec!["-c".to_string()],
transport: CommandTransport::Argv,
});
}
}
}
impl Default for OsExecutionEnv {
fn default() -> Self {
Self::new()
}
}
fn home_dir_string() -> String {
dirs::home_dir()
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_default()
}
fn normalize_absolute(p: &Path) -> PathBuf {
let mut out = PathBuf::new();
for comp in p.components() {
match comp {
std::path::Component::ParentDir => {
out.pop();
}
std::path::Component::CurDir => {}
other => out.push(other),
}
}
out
}
fn file_url_to_path(url: &str) -> Option<String> {
let rest = url.strip_prefix("file://")?;
if let Some(drive_rest) = rest.strip_prefix('/') {
if drive_rest.len() >= 2 && drive_rest.as_bytes()[1] == b':' {
return Some(drive_rest.to_string());
}
return Some(format!("/{}", drive_rest));
}
Some(rest.to_string())
}
fn bash_shell_config(shell: PathBuf) -> ShellConfig {
if is_legacy_wsl_bash_path(&shell) {
ShellConfig {
shell,
args: vec!["-s".to_string()],
transport: CommandTransport::Stdin,
}
} else {
ShellConfig {
shell,
args: vec!["-c".to_string()],
transport: CommandTransport::Argv,
}
}
}
fn is_legacy_wsl_bash_path(p: &Path) -> bool {
let s = p.to_string_lossy().replace('/', "\\").to_lowercase();
let re = regex::Regex::new(r"^[a-z]:\\windows\\(?:system32|sysnative)\\bash\.exe$").unwrap();
re.is_match(&s)
}
#[cfg(windows)]
async fn windows_probe_bash() -> Option<ShellConfig> {
let pf = std::env::var("ProgramFiles").ok();
let pf86 = std::env::var("ProgramFiles(x86)").ok();
let mut candidates: Vec<PathBuf> = Vec::new();
if let Some(p) = pf {
candidates.push(PathBuf::from(p).join("Git").join("bin").join("bash.exe"));
}
if let Some(p) = pf86 {
candidates.push(PathBuf::from(p).join("Git").join("bin").join("bash.exe"));
}
for c in &candidates {
if tokio::fs::metadata(c).await.is_ok() {
return Some(bash_shell_config(c.clone()));
}
}
if let Some(found) = run_command(
"where",
&["bash.exe"],
std::time::Duration::from_millis(5000),
)
.await
{
let first = found.lines().next().unwrap_or("").trim().to_string();
if !first.is_empty() && tokio::fs::metadata(&first).await.is_ok() {
return Some(bash_shell_config(PathBuf::from(first)));
}
}
None
}
async fn run_command(cmd: &str, args: &[&str], timeout: std::time::Duration) -> Option<String> {
let mut command = tokio::process::Command::new(cmd);
command.args(args);
command.stdout(std::process::Stdio::piped());
command.stderr(std::process::Stdio::null());
command.stdin(std::process::Stdio::null());
#[cfg(windows)]
{
use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW;
command.creation_flags(CREATE_NO_WINDOW);
}
let child = command.spawn().ok()?;
let out = match tokio::time::timeout(timeout, child.wait_with_output()).await {
Ok(Ok(o)) => o,
_ => return None,
};
if !out.status.success() {
return None;
}
let s = crate::output_decode::decode_output(&out.stdout);
if s.trim().is_empty() {
None
} else {
Some(s)
}
}
#[cfg(windows)]
mod shell_jobs {
use std::collections::HashMap;
use std::sync::{LazyLock, Mutex};
use win32job::{ExtendedLimitInfo, Job};
static JOBS: LazyLock<Mutex<HashMap<u32, Job>>> = LazyLock::new(Default::default);
pub fn start(pid: u32, process: std::os::windows::io::RawHandle) -> Result<(), String> {
if let Ok(job) = Job::create() {
if job.assign_process(process as isize).is_ok() {
JOBS.lock().unwrap().insert(pid, job);
}
}
rpi_plugin_sdk::process::resume_child(pid)
}
pub fn terminate(pid: u32) -> bool {
let Some(job) = JOBS.lock().unwrap().remove(&pid) else {
return false;
};
let mut info = ExtendedLimitInfo::new();
info.limit_kill_on_job_close();
job.set_extended_limit_info(&info).is_ok()
}
pub fn forget(pid: u32) {
JOBS.lock().unwrap().remove(&pid);
}
}
struct ShellProcessGuard {
pid: Option<u32>,
active: Arc<Mutex<HashSet<u32>>>,
}
impl ShellProcessGuard {
fn finish(&mut self) {
if let Some(pid) = self.pid.take() {
#[cfg(windows)]
shell_jobs::forget(pid);
self.active
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&pid);
}
}
}
impl Drop for ShellProcessGuard {
fn drop(&mut self) {
if let Some(pid) = self.pid {
#[cfg(unix)]
{
use nix::sys::signal::{kill, Signal};
use nix::unistd::Pid;
let _ = kill(Pid::from_raw(-(pid as i32)), Signal::SIGKILL);
}
#[cfg(windows)]
shell_jobs::terminate(pid);
self.finish();
}
}
}
async fn kill_process_tree(pid: u32) {
#[cfg(windows)]
{
if shell_jobs::terminate(pid) {
return;
}
use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW;
let mut cmd = tokio::process::Command::new("taskkill");
cmd.args(&["/F", "/T", "/PID", &pid.to_string()]);
cmd.creation_flags(CREATE_NO_WINDOW);
cmd.stdin(std::process::Stdio::null());
cmd.stdout(std::process::Stdio::null());
cmd.stderr(std::process::Stdio::null());
let _ = cmd.status().await;
}
#[cfg(unix)]
{
use nix::sys::signal::{kill, Signal};
use nix::unistd::Pid;
let pg = Pid::from_raw(-(pid as i32));
if kill(pg, Signal::SIGKILL).is_err() {
let _ = kill(Pid::from_raw(pid as i32), Signal::SIGKILL);
}
}
#[cfg(not(any(windows, unix)))]
{
let _ = pid;
}
}
#[async_trait]
impl FileSystem for OsExecutionEnv {
fn native_file_path(&self, path: &str) -> Option<PathBuf> {
#[cfg(unix)]
return Some(self.resolve_path(path));
#[cfg(not(unix))]
{
let _ = path;
None
}
}
async fn try_acquire_writer_lease(
&self,
path: &str,
) -> Result<Option<Box<dyn WriterLease>>, FileError> {
let session_path = self.resolve_path(path);
let lock_path = PathBuf::from(format!("{}.lock", session_path.display()));
let display_path = session_path.to_string_lossy().into_owned();
tokio::task::spawn_blocking(move || {
use fs2::FileExt;
let mut file = std::fs::OpenOptions::new()
.create(true)
.read(true)
.write(true)
.open(&lock_path)
.map_err(|error| io_to_file_error(error, Some(&lock_path.to_string_lossy())))?;
file.try_lock_exclusive().map_err(|error| {
FileError::new(
FileErrorCode::PermissionDenied,
format!("writer lease is already held for {display_path}"),
)
.with_path(lock_path.to_string_lossy())
.with_source(Box::new(error))
})?;
file.seek(SeekFrom::Start(0))
.map_err(|error| io_to_file_error(error, Some(&lock_path.to_string_lossy())))?;
let mut contents = String::new();
file.read_to_string(&mut contents)
.map_err(|error| io_to_file_error(error, Some(&lock_path.to_string_lossy())))?;
let previous = if contents.trim().is_empty() {
0
} else {
contents.trim().parse::<u64>().map_err(|error| {
FileError::new(
FileErrorCode::Unknown,
format!("invalid persisted writer lease fence: {error}"),
)
.with_path(lock_path.to_string_lossy())
})?
};
let fence = previous.checked_add(1).ok_or_else(|| {
FileError::new(FileErrorCode::Unknown, "writer lease fence exhausted")
.with_path(lock_path.to_string_lossy())
})?;
file.seek(SeekFrom::Start(0))
.and_then(|_| file.set_len(0))
.and_then(|_| file.write_all(fence.to_string().as_bytes()))
.and_then(|_| file.sync_all())
.map_err(|error| io_to_file_error(error, Some(&lock_path.to_string_lossy())))?;
Ok(Some(
Box::new(OsWriterLease { file, fence }) as Box<dyn WriterLease>
))
})
.await
.map_err(|error| {
FileError::new(
FileErrorCode::Unknown,
format!("writer lease task failed: {error}"),
)
.with_path(session_path.to_string_lossy())
})?
}
async fn sync_file(
&self,
path: &str,
data_only: bool,
cancel: Option<&CancellationToken>,
) -> Result<(), FileError> {
check_cancel_file(cancel, Some(path))?;
let abs = self.resolve_path(path);
let error_path = abs.to_string_lossy().into_owned();
let io_path = error_path.clone();
tokio::task::spawn_blocking(move || {
let file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.open(&abs)
.map_err(|error| io_to_file_error(error, Some(&io_path)))?;
if data_only {
file.sync_data()
.map_err(|error| io_to_file_error(error, Some(&io_path)))
} else {
file.sync_all()
.map_err(|error| io_to_file_error(error, Some(&io_path)))
}
})
.await
.map_err(|error| {
FileError::new(
FileErrorCode::Unknown,
format!("file sync task failed: {error}"),
)
.with_path(error_path)
})??;
Ok(())
}
async fn sync_directory(
&self,
path: &str,
cancel: Option<&CancellationToken>,
) -> Result<(), FileError> {
check_cancel_file(cancel, Some(path))?;
let abs = self.resolve_path(path);
#[cfg(unix)]
{
let error_path = abs.to_string_lossy().into_owned();
let io_path = error_path.clone();
tokio::task::spawn_blocking(move || {
std::fs::File::open(&abs)
.map_err(|error| io_to_file_error(error, Some(&io_path)))?
.sync_all()
.map_err(|error| io_to_file_error(error, Some(&io_path)))
})
.await
.map_err(|error| {
FileError::new(
FileErrorCode::Unknown,
format!("directory sync task failed: {error}"),
)
.with_path(error_path)
})??;
}
#[cfg(not(unix))]
{
let _ = abs;
}
Ok(())
}
async fn sync_file_and_parent(
&self,
path: &str,
cancel: Option<&CancellationToken>,
) -> Result<(), FileError> {
check_cancel_file(cancel, Some(path))?;
#[cfg(unix)]
{
let abs = self.resolve_path(path);
let info = self.file_info(path, cancel).await?;
if info.kind != FileKind::File {
return Err(FileError::new(
FileErrorCode::NotSupported,
"journal synchronization requires a regular file",
)
.with_path(path));
}
self.sync_file(path, false, cancel).await?;
let parent = abs.parent().ok_or_else(|| {
FileError::new(
FileErrorCode::NotSupported,
"journal has no parent directory",
)
.with_path(path)
})?;
self.sync_directory(&parent.to_string_lossy(), cancel).await
}
#[cfg(not(unix))]
{
Err(FileError::new(
FileErrorCode::NotSupported,
"physical journal synchronization is unsupported on this platform",
)
.with_path(path))
}
}
async fn open_append_file(
&self,
path: &str,
) -> Result<Option<Box<dyn crate::env::AppendFile>>, FileError> {
let path = self.resolve_path(path);
Ok(Some(Box::new(append::OsAppendFile::open(path).await?)))
}
async fn open_read_file(
&self,
path: &str,
) -> Result<Option<Arc<dyn crate::env::ReadFile>>, FileError> {
let path = self.resolve_path(path);
Ok(Some(Arc::new(read::OsReadFile::open(path).await?)))
}
async fn truncate_file(
&self,
path: &str,
len: u64,
cancel: Option<&CancellationToken>,
) -> Result<(), FileError> {
check_cancel_file(cancel, Some(path))?;
let abs = self.resolve_path(path);
let error_path = abs.to_string_lossy().into_owned();
tokio::task::spawn_blocking(move || {
let file = std::fs::OpenOptions::new().write(true).open(&abs)?;
if len > file.metadata()?.len() {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"truncation cannot grow a file",
));
}
file.set_len(len)
})
.await
.map_err(|error| {
FileError::new(
FileErrorCode::Unknown,
format!("file truncation task failed: {error}"),
)
})?
.map_err(|error| io_to_file_error(error, Some(&error_path)))
}
fn cwd(&self) -> &Path {
&self.cwd
}
async fn absolute_path(
&self,
path: &str,
cancel: Option<&CancellationToken>,
) -> Result<PathBuf, FileError> {
check_cancel_file(cancel, Some(path))?;
Ok(self.resolve_path(path))
}
async fn join_path(
&self,
parts: &[&str],
cancel: Option<&CancellationToken>,
) -> Result<PathBuf, FileError> {
check_cancel_file(cancel, None)?;
let mut out = PathBuf::new();
for p in parts {
out.push(p);
}
Ok(out)
}
async fn read_text_file(
&self,
path: &str,
cancel: Option<&CancellationToken>,
) -> Result<String, FileError> {
check_cancel_file(cancel, Some(path))?;
let abs = self.resolve_path(path);
let bytes = read_cancellable(&abs, cancel).await?;
String::from_utf8(bytes).map_err(|e| {
FileError::new(FileErrorCode::Invalid, format!("invalid utf-8: {e}"))
.with_path(abs.to_string_lossy())
})
}
async fn read_text_lines(
&self,
path: &str,
max_lines: Option<usize>,
cancel: Option<&CancellationToken>,
) -> Result<Vec<String>, FileError> {
check_cancel_file(cancel, Some(path))?;
if max_lines.map(|m| m == 0).unwrap_or(false) {
return Ok(Vec::new());
}
let abs = self.resolve_path(path);
read::read_text_lines(&abs, max_lines, cancel).await
}
async fn read_binary_file(
&self,
path: &str,
cancel: Option<&CancellationToken>,
) -> Result<Vec<u8>, FileError> {
check_cancel_file(cancel, Some(path))?;
let abs = self.resolve_path(path);
read_cancellable(&abs, cancel).await
}
async fn write_file(
&self,
path: &str,
content: FileContent,
cancel: Option<&CancellationToken>,
) -> Result<(), FileError> {
check_cancel_file(cancel, Some(path))?;
let abs = self.resolve_path(path);
if let Some(parent) = abs.parent() {
if !parent.as_os_str().is_empty() {
if let Err(e) = tokio::fs::create_dir_all(parent).await {
return Err(io_to_file_error(e, Some(&abs.to_string_lossy())));
}
}
}
check_cancel_file(cancel, Some(&abs.to_string_lossy()))?;
write_cancellable(abs, content, cancel).await
}
async fn write_new_file(
&self,
path: &str,
content: FileContent,
cancel: Option<&CancellationToken>,
) -> Result<(), FileError> {
check_cancel_file(cancel, Some(path))?;
let abs = self.resolve_path(path);
let cancel = cancel.cloned();
tokio::task::spawn_blocking(move || {
let display = abs.to_string_lossy();
check_cancel_file(cancel.as_ref(), Some(&display))?;
let mut options = std::fs::OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let mut file = options
.open(&abs)
.map_err(|error| io_to_file_error(error, Some(&display)))?;
for chunk in content.as_bytes().chunks(64 * 1024) {
check_cancel_file(cancel.as_ref(), Some(&display))?;
file.write_all(chunk)
.map_err(|error| io_to_file_error(error, Some(&display)))?;
}
file.flush()
.map_err(|error| io_to_file_error(error, Some(&display)))
})
.await
.map_err(|_| {
FileError::new(
FileErrorCode::Unknown,
"exclusive file creation task stopped",
)
})?
}
async fn append_file(
&self,
path: &str,
content: FileContent,
cancel: Option<&CancellationToken>,
) -> Result<(), FileError> {
check_cancel_file(cancel, Some(path))?;
let abs = self.resolve_path(path);
if let Some(parent) = abs.parent() {
if !parent.as_os_str().is_empty() {
let _ = tokio::fs::create_dir_all(parent).await;
}
}
use tokio::io::AsyncWriteExt;
let res = match tokio::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&abs)
.await
{
Ok(mut f) => {
match f.write_all(content.as_bytes()).await {
Ok(()) => f.flush().await,
Err(error) => Err(error),
}
}
Err(e) => return Err(io_to_file_error(e, Some(&abs.to_string_lossy()))),
};
res.map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))
}
async fn rename_file(
&self,
source: &str,
dest: &str,
cancel: Option<&CancellationToken>,
) -> Result<(), FileError> {
check_cancel_file(cancel, Some(source))?;
let src = self.resolve_path(source);
let dst = self.resolve_path(dest);
tokio::fs::rename(&src, &dst)
.await
.map_err(|e| io_to_file_error(e, Some(&src.to_string_lossy())))
}
async fn file_info(
&self,
path: &str,
cancel: Option<&CancellationToken>,
) -> Result<FileInfo, FileError> {
check_cancel_file(cancel, Some(path))?;
let abs = self.resolve_path(path);
let meta = tokio::fs::symlink_metadata(&abs)
.await
.map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?;
let ft = meta.file_type();
let kind = if ft.is_file() {
FileKind::File
} else if ft.is_dir() {
FileKind::Directory
} else if ft.is_symlink() {
FileKind::Symlink
} else {
return Err(
FileError::new(FileErrorCode::Invalid, "Unsupported file type")
.with_path(abs.to_string_lossy()),
);
};
let mtime_ms = meta
.modified()
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_millis() as i64)
.unwrap_or(0);
Ok(FileInfo {
name: abs
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| abs.to_string_lossy().into_owned()),
path: abs.clone(),
kind,
size: meta.len(),
mtime_ms,
})
}
async fn list_dir(
&self,
path: &str,
cancel: Option<&CancellationToken>,
) -> Result<Vec<FileInfo>, FileError> {
check_cancel_file(cancel, Some(path))?;
let abs = self.resolve_path(path);
let mut entries = tokio::fs::read_dir(&abs)
.await
.map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?;
let mut out = Vec::new();
while let Some(entry) = entries
.next_entry()
.await
.map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?
{
if let Some(t) = cancel {
if t.is_cancelled() {
return Err(FileError::aborted().with_path(abs.to_string_lossy()));
}
}
let ep = entry.path();
let meta = match tokio::fs::symlink_metadata(&ep).await {
Ok(m) => m,
Err(e) => {
let code = crate::error::io_to_file_code(&e);
if code == FileErrorCode::NotSupported {
continue;
}
return Err(io_to_file_error(e, Some(&ep.to_string_lossy())));
}
};
let ft = meta.file_type();
let kind = if ft.is_file() {
FileKind::File
} else if ft.is_dir() {
FileKind::Directory
} else if ft.is_symlink() {
FileKind::Symlink
} else {
continue; };
let mtime_ms = meta
.modified()
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_millis() as i64)
.unwrap_or(0);
out.push(FileInfo {
name: entry.file_name().to_string_lossy().into_owned(),
path: ep,
kind,
size: meta.len(),
mtime_ms,
});
}
Ok(out)
}
async fn has_file_with_suffix(
&self,
path: &str,
suffix: &str,
cancel: Option<&CancellationToken>,
) -> Result<bool, FileError> {
check_cancel_file(cancel, Some(path))?;
let abs = self.resolve_path(path);
let error_path = abs.to_string_lossy().into_owned();
let suffix = String::from(suffix);
let cancel = cancel.cloned();
tokio::task::spawn_blocking(move || {
check_cancel_file(cancel.as_ref(), Some(&abs.to_string_lossy()))?;
let entries = std::fs::read_dir(&abs)
.map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?;
for entry in entries {
check_cancel_file(cancel.as_ref(), Some(&abs.to_string_lossy()))?;
let entry = entry.map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?;
if !entry.file_name().to_string_lossy().ends_with(&suffix) {
continue;
}
let kind = match entry.file_type() {
Ok(kind) => kind,
Err(error)
if crate::error::io_to_file_code(&error) == FileErrorCode::NotSupported =>
{
continue
}
Err(error) => {
return Err(io_to_file_error(
error,
Some(&entry.path().to_string_lossy()),
))
}
};
check_cancel_file(cancel.as_ref(), Some(&abs.to_string_lossy()))?;
if kind.is_file() || kind.is_symlink() {
return Ok(true);
}
}
check_cancel_file(cancel.as_ref(), Some(&abs.to_string_lossy()))?;
Ok(false)
})
.await
.map_err(|error| {
FileError::new(
FileErrorCode::Unknown,
format!("directory scan task failed: {error}"),
)
.with_path(error_path)
})?
}
async fn canonical_path(
&self,
path: &str,
cancel: Option<&CancellationToken>,
) -> Result<PathBuf, FileError> {
check_cancel_file(cancel, Some(path))?;
let abs = self.resolve_path(path);
tokio::fs::canonicalize(&abs)
.await
.map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))
}
async fn exists(
&self,
path: &str,
cancel: Option<&CancellationToken>,
) -> Result<bool, FileError> {
check_cancel_file(cancel, Some(path))?;
let abs = self.resolve_path(path);
match tokio::fs::symlink_metadata(&abs).await {
Ok(_) => Ok(true),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(e) => Err(io_to_file_error(e, Some(&abs.to_string_lossy()))),
}
}
async fn create_dir(
&self,
path: &str,
recursive: bool,
cancel: Option<&CancellationToken>,
) -> Result<(), FileError> {
check_cancel_file(cancel, Some(path))?;
let abs = self.resolve_path(path);
let res = if recursive {
tokio::fs::create_dir_all(&abs).await
} else {
tokio::fs::create_dir(&abs).await
};
res.map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))
}
async fn remove(
&self,
path: &str,
recursive: bool,
force: bool,
cancel: Option<&CancellationToken>,
) -> Result<(), FileError> {
check_cancel_file(cancel, Some(path))?;
let abs = self.resolve_path(path);
let res = if recursive {
tokio::fs::remove_dir_all(&abs).await
} else {
match tokio::fs::remove_file(&abs).await {
Ok(()) => Ok(()),
Err(_) => tokio::fs::remove_dir(&abs).await,
}
};
match res {
Ok(()) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound && force => Ok(()),
Err(e) => Err(io_to_file_error(e, Some(&abs.to_string_lossy()))),
}
}
async fn create_temp_dir(
&self,
prefix: Option<&str>,
cancel: Option<&CancellationToken>,
) -> Result<PathBuf, FileError> {
check_cancel_file(cancel, None)?;
let prefix = prefix.unwrap_or("tmp-");
let tmp =
tempfile::tempdir_in(std::env::temp_dir()).map_err(|e| io_to_file_error(e, None))?;
let path = tmp.path().to_path_buf();
std::mem::forget(tmp); let final_path = std::env::temp_dir().join(format!("{}{}", prefix, random_suffix()));
if let Err(e) = tokio::fs::rename(&path, &final_path).await {
let _ = e;
return Ok(path);
}
Ok(final_path)
}
async fn create_temp_file(
&self,
prefix: &str,
suffix: &str,
cancel: Option<&CancellationToken>,
) -> Result<PathBuf, FileError> {
check_cancel_file(cancel, None)?;
let dir = self.create_temp_dir(Some("tmp-"), cancel).await?;
let name = format!("{}{}{}", prefix, random_suffix(), suffix);
let path = dir.join(name);
tokio::fs::File::create(&path)
.await
.map_err(|e| io_to_file_error(e, Some(&path.to_string_lossy())))?;
Ok(path)
}
async fn cleanup(&self) {
let pids: Vec<u32> = self
.active_pids
.lock()
.unwrap_or_else(|e| e.into_inner())
.iter()
.copied()
.collect();
for pid in pids {
kill_process_tree(pid).await;
}
self.active_pids
.lock()
.unwrap_or_else(|e| e.into_inner())
.clear();
}
}
async fn read_cancellable(
path: &Path,
cancel: Option<&CancellationToken>,
) -> Result<Vec<u8>, FileError> {
let read = tokio::fs::read(path);
let res = match cancel {
Some(t) => tokio::select! {
r = read => r,
_ = t.cancelled() => return Err(FileError::aborted().with_path(path.to_string_lossy())),
},
None => read.await,
};
res.map_err(|e| io_to_file_error(e, Some(&path.to_string_lossy())))
}
async fn write_cancellable(
path: PathBuf,
content: FileContent,
cancel: Option<&CancellationToken>,
) -> Result<(), FileError> {
let task_path = path.clone();
let cancel = cancel.cloned();
tokio::task::spawn_blocking(move || {
let path = task_path.to_string_lossy();
check_cancel_file(cancel.as_ref(), Some(&path))?;
let write = || -> std::io::Result<()> {
let mut file = std::fs::File::create(&task_path)?;
file.write_all(content.as_bytes())?;
file.flush()
};
write().map_err(|error| io_to_file_error(error, Some(&path)))
})
.await
.map_err(|error| {
FileError::new(FileErrorCode::Unknown, "file write task failed")
.with_path(path.to_string_lossy())
.with_source(Box::new(error))
})?
}
fn random_suffix() -> String {
uuid::Uuid::new_v4().simple().to_string()
}
async fn drain_shell_pipe(
pipe: Option<impl tokio::io::AsyncRead + Unpin>,
mut callback: Option<Box<dyn FnMut(&str) + Send + '_>>,
retained: &mut String,
streamed: Option<&tokio::sync::mpsc::Sender<String>>,
shell_exited: &CancellationToken,
cancel: Option<&CancellationToken>,
) {
use tokio::io::AsyncReadExt;
use tokio::time::{timeout, Duration, Instant};
let Some(mut pipe) = pipe else { return };
let mut buffer = [0u8; 8192];
let mut decoder = crate::output_decode::StreamDecoder::new();
let mut drain_budget = Duration::from_millis(EXIT_STDIO_GRACE_MS);
let cancelled = async {
match cancel {
Some(token) => token.cancelled().await,
None => std::future::pending::<()>().await,
}
};
tokio::pin!(cancelled);
loop {
let read = async {
let read = pipe.read(&mut buffer);
tokio::pin!(read);
tokio::select! {
biased;
_ = shell_exited.cancelled() => {},
result = &mut read => return result.unwrap_or(0),
}
if drain_budget.is_zero() {
return 0;
}
let started = Instant::now();
let result = timeout(drain_budget, &mut read).await;
drain_budget = drain_budget.saturating_sub(started.elapsed());
result.ok().and_then(Result::ok).unwrap_or(0)
};
let count = tokio::select! {
biased;
_ = &mut cancelled => 0,
count = read => count,
};
let chunk = if count == 0 {
decoder.finish()
} else {
decoder.push(&buffer[..count])
};
if !chunk.is_empty() {
if let Some(callback) = callback.as_mut() {
callback(&chunk);
}
if let Some(sender) = streamed {
let _ = sender.send(chunk).await;
} else {
retained.push_str(&chunk);
}
}
if count == 0 {
break;
}
}
}
impl OsExecutionEnv {
async fn exec_inner(
&self,
command: &str,
options: ShellExecOptions<'_>,
streamed: Option<tokio::sync::mpsc::Sender<String>>,
) -> Result<ShellOutput, ExecutionError> {
check_cancel_exec(options.cancel)?;
let timeout = match resolve_timeout(options.timeout) {
Ok(t) => t,
Err(e) => return Err(e),
};
let cwd = match &options.cwd {
Some(c) => self.resolve_path(&c.to_string_lossy()),
None => self.cwd.clone(),
};
let shell_cfg = match &options.shell {
Some(override_shell) => ShellConfig {
shell: override_shell.program.clone(),
args: override_shell.args.clone(),
transport: CommandTransport::Argv,
},
None => self.get_shell_config().await?,
};
self.exec_configured(command, options, streamed, shell_cfg, timeout, cwd)
.await
}
async fn exec_configured(
&self,
command: &str,
options: ShellExecOptions<'_>,
streamed: Option<tokio::sync::mpsc::Sender<String>>,
shell_cfg: ShellConfig,
timeout: Option<std::time::Duration>,
cwd: PathBuf,
) -> Result<ShellOutput, ExecutionError> {
if !cwd.exists() {
return Err(ExecutionError::new(
ExecutionErrorCode::SpawnError,
format!(
"Working directory does not exist: {}\nCannot execute bash commands.",
cwd.display()
),
));
}
check_cancel_exec(options.cancel)?;
let mut cmd = tokio::process::Command::new(&shell_cfg.shell);
cmd.current_dir(&cwd);
cmd.env_clear();
for (k, v) in NON_INTERACTIVE_SHELL_ENV {
cmd.env(k, v);
}
if options.inherit_env {
let mut inherit = |name: &str, value: &str| {
if !is_host_private_env(name) {
cmd.env(name, value);
}
};
match &self.environment {
Some(environment) => {
for (name, value) in environment {
inherit(name, value);
}
}
None => {
for (name, value) in std::env::vars() {
inherit(&name, &value);
}
}
}
}
if let Some(base) = &self.shell_env {
for (k, v) in base {
cmd.env(k, v);
}
}
if let Some(extra) = &options.env {
for (k, v) in extra {
cmd.env(k, v);
}
}
cmd.kill_on_drop(true);
cmd.stdout(std::process::Stdio::piped());
cmd.stderr(std::process::Stdio::piped());
#[cfg(unix)]
{
cmd.process_group(0); }
#[cfg(windows)]
{
use windows_sys::Win32::System::Threading::{CREATE_NO_WINDOW, CREATE_SUSPENDED};
cmd.creation_flags(CREATE_NO_WINDOW | CREATE_SUSPENDED);
}
cmd.args(&shell_cfg.args);
match shell_cfg.transport {
CommandTransport::Argv => {
cmd.stdin(std::process::Stdio::null());
cmd.arg(command);
}
CommandTransport::Stdin => {
cmd.stdin(std::process::Stdio::piped());
}
}
let mut child = match cmd.spawn() {
Ok(c) => c,
Err(e) => {
return Err(ExecutionError::new(
ExecutionErrorCode::SpawnError,
format!("failed to spawn shell: {e}"),
));
}
};
let pid = child.id();
let mut process_guard = ShellProcessGuard {
pid,
active: self.active_pids.clone(),
};
#[cfg(windows)]
{
let started = match (pid, child.raw_handle()) {
(Some(pid), Some(process)) => shell_jobs::start(pid, process),
_ => Err("the shell has no process handle".to_owned()),
};
if let Err(error) = started {
if let Some(pid) = pid {
shell_jobs::forget(pid);
}
let _ = child.start_kill();
return Err(ExecutionError::new(
ExecutionErrorCode::SpawnError,
format!("failed to start shell: {error}"),
));
}
}
if let Some(pid) = pid {
self.active_pids
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(pid);
}
let stdin = child.stdin.take();
let stop_input = CancellationToken::new();
let deadline = timeout.map(|duration| tokio::time::Instant::now() + duration);
let mut stdout_buf = String::new();
let mut stderr_buf = String::new();
let cancel = options.cancel;
let shell_exited = CancellationToken::new();
let stdout_task = drain_shell_pipe(
child.stdout.take(),
options.on_stdout,
&mut stdout_buf,
streamed.as_ref(),
&shell_exited,
cancel,
);
let stderr_task = drain_shell_pipe(
child.stderr.take(),
options.on_stderr,
&mut stderr_buf,
streamed.as_ref(),
&shell_exited,
cancel,
);
let mut timed_out = false;
let exit_status = {
let status_fut = async {
let expired = async {
match deadline {
Some(at) => tokio::time::sleep_until(at).await,
None => std::future::pending::<()>().await,
}
};
let cancelled = async {
match cancel {
Some(token) => token.cancelled().await,
None => std::future::pending::<()>().await,
}
};
tokio::select! {
status = child.wait() => return status,
() = expired => timed_out = true,
() = cancelled => {}
}
stop_input.cancel();
if let Some(pid) = child.id() {
kill_process_tree(pid).await;
}
child.wait().await
};
tokio::pin!(status_fut, stdout_task, stderr_task);
let (mut stdout_done, mut stderr_done) = (false, false);
let status_res = {
let stdin_task = async {
let Some(mut stdin) = stdin else { return };
use tokio::io::AsyncWriteExt;
tokio::select! {
biased;
() = stop_input.cancelled() => {}
() = async {
if stdin.write_all(command.as_bytes()).await.is_ok() {
let _ = stdin.flush().await;
}
} => {}
}
};
tokio::pin!(stdin_task);
let mut stdin_done = false;
loop {
tokio::select! {
status = &mut status_fut => break status,
() = &mut stdin_task, if !stdin_done => stdin_done = true,
() = &mut stdout_task, if !stdout_done => stdout_done = true,
() = &mut stderr_task, if !stderr_done => stderr_done = true,
}
}
};
if status_res.is_ok() {
process_guard.finish();
}
shell_exited.cancel();
tokio::join!(
async {
if !stdout_done {
(&mut stdout_task).await;
}
},
async {
if !stderr_done {
(&mut stderr_task).await;
}
},
);
status_res
};
if timed_out {
let _ = tokio::time::sleep(std::time::Duration::from_millis(EXIT_STDIO_GRACE_MS)).await;
}
let status = match exit_status {
Ok(s) => s,
Err(e) => {
return Err(ExecutionError::new(
ExecutionErrorCode::SpawnError,
format!("child wait failed: {e}"),
));
}
};
if timed_out {
return Err(ExecutionError::timeout(
options.timeout.map(|f| f as u64).unwrap_or(0),
));
}
if cancel.map(|t| t.is_cancelled()).unwrap_or(false) {
return Err(ExecutionError::aborted());
}
let exit_code = status.code().unwrap_or(0);
Ok(ShellOutput {
stdout: stdout_buf,
stderr: stderr_buf,
exit_code,
})
}
}
#[async_trait]
impl Shell for OsExecutionEnv {
async fn exec<'a>(
&'a self,
command: &str,
options: ShellExecOptions<'a>,
) -> Result<ShellOutput, ExecutionError> {
self.exec_inner(command, options, None).await
}
async fn exec_streamed<'a>(
&'a self,
command: &str,
options: ShellExecOptions<'a>,
output: tokio::sync::mpsc::Sender<String>,
) -> Result<i32, ExecutionError> {
self.exec_inner(command, options, Some(output))
.await
.map(|result| result.exit_code)
}
async fn cleanup(&self) {
FileSystem::cleanup(self).await
}
}
#[async_trait]
impl ExecutionEnv for OsExecutionEnv {}
#[async_trait]
impl MutatingEnv for OsExecutionEnv {
fn as_env(&self) -> &dyn ExecutionEnv {
self
}
fn mutation_registry(&self) -> &MutationQueueRegistry {
&self.registry
}
}
#[cfg(test)]
mod stdin_transport_tests {
use super::*;
use std::time::Duration;
fn long_script(first: &str, last: &str) -> String {
format!(
"{first}\n{}{last}\n",
"# benign stdin pipe fixture data\n".repeat(64 * 1024)
)
}
async fn exec_stdin(
env: &OsExecutionEnv,
script: &str,
options: ShellExecOptions<'_>,
) -> Result<ShellOutput, ExecutionError> {
let config = ShellConfig {
shell: env.get_shell_config().await?.shell,
args: vec!["-s".to_owned()],
transport: CommandTransport::Stdin,
};
let timeout = resolve_timeout(options.timeout)?;
env.exec_configured(script, options, None, config, timeout, env.cwd.clone())
.await
}
#[tokio::test]
async fn stdin_transport_drains_output_while_sending_the_script() {
let temp = tempfile::tempdir().unwrap();
let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
let script = long_script(
"head -c 262144 /dev/zero | tr '\\0' a; head -c 262144 /dev/zero | tr '\\0' b >&2",
"printf 'end of script'",
);
let output = tokio::time::timeout(
Duration::from_secs(4),
exec_stdin(
&env,
&script,
ShellExecOptions {
timeout: Some(3.0),
..Default::default()
},
),
)
.await
.expect("shell blocked feeding stdin while its output pipes were full");
let output = match output {
Err(error) if error.code == ExecutionErrorCode::ShellUnavailable => return,
output => output.unwrap(),
};
assert_eq!(output.exit_code, 0);
assert_eq!(output.stdout.len(), 262144 + "end of script".len());
assert!(output.stdout.ends_with("end of script"));
assert_eq!(output.stderr.len(), 262144);
assert!(output.stderr.bytes().all(|byte| byte == b'b'));
}
#[tokio::test]
async fn stdin_transport_timeout_covers_blocked_script_upload() {
let temp = tempfile::tempdir().unwrap();
let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
let script = long_script("sleep 30", "printf 'unexpected completion'");
let error = tokio::time::timeout(
Duration::from_secs(3),
exec_stdin(
&env,
&script,
ShellExecOptions {
timeout: Some(0.15),
..Default::default()
},
),
)
.await
.expect("command timeout did not start while stdin was blocked")
.unwrap_err();
if error.code == ExecutionErrorCode::ShellUnavailable {
return;
}
assert_eq!(error.code, ExecutionErrorCode::Timeout);
}
#[tokio::test]
async fn stdin_transport_cancellation_covers_blocked_script_upload() {
let temp = tempfile::tempdir().unwrap();
let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
let script = long_script("sleep 30", "printf 'unexpected completion'");
let signal = CancellationToken::new();
let (result, ()) = tokio::join!(
tokio::time::timeout(
Duration::from_secs(3),
exec_stdin(
&env,
&script,
ShellExecOptions {
cancel: Some(&signal),
..Default::default()
},
),
),
async {
tokio::time::sleep(Duration::from_millis(150)).await;
signal.cancel();
},
);
let error = result
.expect("cancellation was not observed while stdin was blocked")
.unwrap_err();
if error.code == ExecutionErrorCode::ShellUnavailable {
return;
}
assert_eq!(error.code, ExecutionErrorCode::Aborted);
}
#[tokio::test]
async fn stdin_transport_keeps_a_deliberate_early_exit_code() {
let temp = tempfile::tempdir().unwrap();
let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
let script = long_script(
"printf 'early exit'; exit 7",
"printf 'unexpected completion'",
);
let result = tokio::time::timeout(
Duration::from_secs(3),
exec_stdin(&env, &script, ShellExecOptions::default()),
)
.await
.expect("shell blocked after closing its stdin");
let output = match result {
Err(error) if error.code == ExecutionErrorCode::ShellUnavailable => return,
output => output.unwrap(),
};
assert_eq!(output.exit_code, 7);
assert_eq!(output.stdout, "early exit");
}
}
#[cfg(test)]
mod durability_tests {
use super::*;
#[test]
fn queued_overwrite_cancelled_before_open_preserves_existing_bytes() {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.max_blocking_threads(1)
.build()
.unwrap();
runtime.block_on(async {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("note.txt");
std::fs::write(&path, b"original").unwrap();
let (entered_tx, entered_rx) = tokio::sync::oneshot::channel();
let (release_tx, release_rx) = std::sync::mpsc::channel();
let blocker = tokio::task::spawn_blocking(move || {
entered_tx.send(()).unwrap();
release_rx.recv().unwrap();
});
entered_rx.await.unwrap();
let signal = CancellationToken::new();
let write = write_cancellable(
path.clone(),
FileContent::Text("replacement".into()),
Some(&signal),
);
tokio::pin!(write);
let queued = futures::poll!(&mut write).is_pending();
signal.cancel();
release_tx.send(()).unwrap();
blocker.await.unwrap();
assert!(queued, "overwrite should be queued on the blocking pool");
let result = write.await;
let contents = std::fs::read(&path).unwrap();
assert_eq!(
contents, b"original",
"queued cancellation changed the file (write result: {result:?})"
);
assert_eq!(result.unwrap_err().code, FileErrorCode::Aborted);
});
}
#[tokio::test]
async fn os_backend_syncs_staged_file_and_publication_directory() {
let temp = tempfile::tempdir().unwrap();
let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
env.write_file("staged", FileContent::Text("durable slice".into()), None)
.await
.unwrap();
env.sync_file("staged", false, None).await.unwrap();
env.sync_directory(".", None).await.unwrap();
}
#[tokio::test]
async fn os_writer_lease_persists_and_verifies_a_monotonic_fence() {
let temp = tempfile::tempdir().unwrap();
let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
let first = env
.try_acquire_writer_lease("journal.jsonl")
.await
.unwrap()
.unwrap();
first.verify_fence().unwrap();
drop(first);
let second = env
.try_acquire_writer_lease("journal.jsonl")
.await
.unwrap()
.unwrap();
second.verify_fence().unwrap();
drop(second);
assert_eq!(
std::fs::read_to_string(temp.path().join("journal.jsonl.lock")).unwrap(),
"2"
);
}
#[cfg(unix)]
#[tokio::test]
async fn os_writer_lease_releases_a_shared_open_file_description() {
let temp = tempfile::tempdir().unwrap();
let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
let lock = temp.path().join("journal.jsonl.lock");
std::fs::write(&lock, "1").unwrap();
let file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.open(&lock)
.unwrap();
fs2::FileExt::try_lock_exclusive(&file).unwrap();
let inherited = file.try_clone().unwrap();
let lease = OsWriterLease { file, fence: 1 };
assert!(env.try_acquire_writer_lease("journal.jsonl").await.is_err());
drop(lease);
let next = env
.try_acquire_writer_lease("journal.jsonl")
.await
.expect("retired writer retained a lock through the shared description")
.unwrap();
next.verify_fence().unwrap();
assert_eq!(std::fs::read_to_string(lock).unwrap(), "2");
drop(inherited);
}
}
fn resolve_timeout(timeout: Option<f64>) -> Result<Option<std::time::Duration>, ExecutionError> {
match timeout {
None => Ok(None),
Some(secs) => {
if !secs.is_finite() || secs <= 0.0 {
return Err(ExecutionError::new(
ExecutionErrorCode::Timeout,
"Invalid timeout: must be a finite number of seconds",
));
}
let ms = secs * 1000.0;
if ms > MAX_TIMEOUT_MS as f64 {
return Err(ExecutionError::new(
ExecutionErrorCode::Timeout,
format!(
"Invalid timeout: maximum is {} seconds",
MAX_TIMEOUT_SECONDS
),
));
}
Ok(Some(std::time::Duration::from_secs_f64(secs)))
}
}
}