1use std::collections::{HashMap, HashSet};
28use std::io::{Read, Seek, SeekFrom, Write};
29use std::path::{Path, PathBuf};
30use std::sync::{Arc, Mutex};
31
32use async_trait::async_trait;
33use tokio_util::sync::CancellationToken;
34
35use crate::env::{
36 check_cancel_exec, check_cancel_file, ExecutionEnv, FileContent, FileInfo, FileKind,
37 FileSystem, Shell, ShellExecOptions, ShellOutput, WriterLease,
38};
39use crate::error::{
40 io_to_file_error, ExecutionError, ExecutionErrorCode, FileError, FileErrorCode,
41};
42use crate::file_mutation_queue::{MutatingEnv, MutationQueueRegistry};
43
44const MAX_TIMEOUT_MS: u64 = 2_147_483_647;
46const MAX_TIMEOUT_SECONDS: f64 = 2_147_483.647;
48const EXIT_STDIO_GRACE_MS: u64 = 100;
51
52const NON_INTERACTIVE_SHELL_ENV: &[(&str, &str)] = &[
67 ("GIT_TERMINAL_PROMPT", "0"),
68 ("GCM_INTERACTIVE", "Never"),
69 ("SSH_ASKPASS_REQUIRE", "never"),
70];
71
72#[derive(Clone, Copy)]
74enum CommandTransport {
75 Argv,
77 Stdin,
79}
80
81struct ShellConfig {
83 shell: PathBuf,
84 args: Vec<String>,
85 transport: CommandTransport,
86}
87
88mod append;
89mod read;
90
91struct OsWriterLease {
93 file: std::fs::File,
94 fence: u64,
95}
96
97#[cfg(unix)]
98impl Drop for OsWriterLease {
99 fn drop(&mut self) {
100 let _ = fs2::FileExt::unlock(&self.file);
103 }
104}
105
106impl WriterLease for OsWriterLease {
107 fn verify_fence(&self) -> Result<(), FileError> {
108 let mut probe = self
109 .file
110 .try_clone()
111 .map_err(|error| io_to_file_error(error, Some("writer lease fence")))?;
112 probe
113 .seek(SeekFrom::Start(0))
114 .map_err(|error| io_to_file_error(error, Some("writer lease fence")))?;
115 let mut contents = String::new();
116 probe
117 .read_to_string(&mut contents)
118 .map_err(|error| io_to_file_error(error, Some("writer lease fence")))?;
119 let current = contents.trim().parse::<u64>().map_err(|error| {
120 FileError::new(
121 FileErrorCode::Unknown,
122 format!("invalid persisted writer lease fence: {error}"),
123 )
124 })?;
125 if current != self.fence {
126 return Err(FileError::new(
127 FileErrorCode::PermissionDenied,
128 "writer lease fence changed; reopen the session",
129 ));
130 }
131 Ok(())
132 }
133}
134
135pub const HOST_PRIVATE_ENV: &[&str] = &[rpi_plugin_sdk::SESSION_ID_ENV];
151
152pub fn is_host_private_env(name: &str) -> bool {
171 HOST_PRIVATE_ENV.contains(&name) || rpi_plugin_sdk::SUBAGENT_PARENT_ENV.contains(&name)
172}
173
174pub struct OsExecutionEnv {
176 cwd: PathBuf,
177 shell_path: Option<PathBuf>,
178 shell_env: Option<HashMap<String, String>>,
179 environment: Option<HashMap<String, String>>,
182 active_pids: Arc<Mutex<HashSet<u32>>>,
183 registry: Arc<MutationQueueRegistry>,
184}
185
186impl OsExecutionEnv {
187 pub fn new() -> Self {
188 Self {
189 cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from("/")),
190 shell_path: None,
191 shell_env: None,
192 environment: None,
193 active_pids: Arc::new(Mutex::new(HashSet::new())),
194 registry: Arc::new(MutationQueueRegistry::new()),
195 }
196 }
197
198 pub fn with_cwd(cwd: PathBuf) -> Self {
199 Self {
200 cwd,
201 shell_path: None,
202 shell_env: None,
203 environment: None,
204 active_pids: Arc::new(Mutex::new(HashSet::new())),
205 registry: Arc::new(MutationQueueRegistry::new()),
206 }
207 }
208
209 pub fn with_shell_path(mut self, shell_path: PathBuf) -> Self {
210 self.shell_path = Some(shell_path);
211 self
212 }
213
214 pub fn with_shell_env(mut self, env: HashMap<String, String>) -> Self {
215 self.shell_env = Some(env);
216 self
217 }
218
219 pub fn with_environment(mut self, environment: HashMap<String, String>) -> Self {
225 self.environment = Some(environment);
226 self
227 }
228
229 pub fn has_explicit_environment(&self) -> bool {
231 self.environment.is_some()
232 }
233
234 fn resolve_path(&self, path: &str) -> PathBuf {
236 let cwd = &self.cwd;
237 let home = || match &self.environment {
238 Some(environment) => environment
239 .get(if cfg!(windows) { "USERPROFILE" } else { "HOME" })
240 .cloned()
241 .unwrap_or_default(),
242 None => home_dir_string(),
243 };
244 let mut p = path.to_string();
245 if p == "~" {
249 let home = home();
250 if self.environment.is_none() || !home.is_empty() {
251 p = home;
252 }
253 } else if let Some(rest) = p.strip_prefix("~/") {
254 let home = home();
255 if self.environment.is_none() || !home.is_empty() {
256 p = format!("{home}/{rest}");
257 }
258 } else if cfg!(windows) {
259 if let Some(rest) = p.strip_prefix("~\\") {
260 let home = home();
261 if self.environment.is_none() || !home.is_empty() {
262 p = format!("{home}\\{rest}");
263 }
264 }
265 }
266 if p.starts_with("file://") {
268 if let Some(local) = file_url_to_path(&p) {
269 p = local;
270 }
271 }
272 let pb = PathBuf::from(&p);
273 if pb.is_absolute() {
274 normalize_absolute(&pb)
275 } else {
276 normalize_absolute(&cwd.join(pb))
277 }
278 }
279
280 async fn get_shell_config(&self) -> Result<ShellConfig, ExecutionError> {
283 if let Some(sp) = &self.shell_path {
288 if sp.is_file() {
289 return Ok(bash_shell_config(sp.clone()));
290 }
291 return Err(ExecutionError::new(
292 ExecutionErrorCode::ShellUnavailable,
293 format!("Custom shell path not found: {}", sp.display()),
294 ));
295 }
296 #[cfg(windows)]
298 {
299 if let Some(cfg) = windows_probe_bash().await {
300 return Ok(cfg);
301 }
302 return Err(ExecutionError::new(
303 ExecutionErrorCode::ShellUnavailable,
304 "bash not found. Install Git for Windows / MSYS2 / Cygwin, or set shellPath.",
305 ));
306 }
307 #[cfg(not(windows))]
309 {
310 if std::path::Path::new("/bin/bash").is_file() {
311 return Ok(ShellConfig {
312 shell: PathBuf::from("/bin/bash"),
313 args: vec!["-c".to_string()],
314 transport: CommandTransport::Argv,
315 });
316 }
317 if let Some(found) =
319 run_command("which", &["bash"], std::time::Duration::from_millis(5000)).await
320 {
321 let trimmed = found.trim();
322 if !trimmed.is_empty() && std::path::Path::new(trimmed).is_file() {
323 return Ok(ShellConfig {
324 shell: PathBuf::from(trimmed),
325 args: vec!["-c".to_string()],
326 transport: CommandTransport::Argv,
327 });
328 }
329 }
330 return Ok(ShellConfig {
332 shell: PathBuf::from("sh"),
333 args: vec!["-c".to_string()],
334 transport: CommandTransport::Argv,
335 });
336 }
337 }
338}
339
340impl Default for OsExecutionEnv {
341 fn default() -> Self {
342 Self::new()
343 }
344}
345
346fn home_dir_string() -> String {
347 dirs::home_dir()
348 .map(|p| p.to_string_lossy().into_owned())
349 .unwrap_or_default()
350}
351
352fn normalize_absolute(p: &Path) -> PathBuf {
353 let mut out = PathBuf::new();
356 for comp in p.components() {
357 match comp {
358 std::path::Component::ParentDir => {
359 out.pop();
360 }
361 std::path::Component::CurDir => {}
362 other => out.push(other),
363 }
364 }
365 out
366}
367
368fn file_url_to_path(url: &str) -> Option<String> {
369 let rest = url.strip_prefix("file://")?;
372 if let Some(drive_rest) = rest.strip_prefix('/') {
373 if drive_rest.len() >= 2 && drive_rest.as_bytes()[1] == b':' {
375 return Some(drive_rest.to_string());
376 }
377 return Some(format!("/{}", drive_rest));
378 }
379 Some(rest.to_string())
380}
381
382fn bash_shell_config(shell: PathBuf) -> ShellConfig {
383 if is_legacy_wsl_bash_path(&shell) {
384 ShellConfig {
385 shell,
386 args: vec!["-s".to_string()],
387 transport: CommandTransport::Stdin,
388 }
389 } else {
390 ShellConfig {
391 shell,
392 args: vec!["-c".to_string()],
393 transport: CommandTransport::Argv,
394 }
395 }
396}
397
398fn is_legacy_wsl_bash_path(p: &Path) -> bool {
399 let s = p.to_string_lossy().replace('/', "\\").to_lowercase();
400 let re = regex::Regex::new(r"^[a-z]:\\windows\\(?:system32|sysnative)\\bash\.exe$").unwrap();
401 re.is_match(&s)
402}
403
404#[cfg(windows)]
405async fn windows_probe_bash() -> Option<ShellConfig> {
406 let pf = std::env::var("ProgramFiles").ok();
407 let pf86 = std::env::var("ProgramFiles(x86)").ok();
408 let mut candidates: Vec<PathBuf> = Vec::new();
409 if let Some(p) = pf {
410 candidates.push(PathBuf::from(p).join("Git").join("bin").join("bash.exe"));
411 }
412 if let Some(p) = pf86 {
413 candidates.push(PathBuf::from(p).join("Git").join("bin").join("bash.exe"));
414 }
415 for c in &candidates {
416 if tokio::fs::metadata(c).await.is_ok() {
417 return Some(bash_shell_config(c.clone()));
418 }
419 }
420 if let Some(found) = run_command(
422 "where",
423 &["bash.exe"],
424 std::time::Duration::from_millis(5000),
425 )
426 .await
427 {
428 let first = found.lines().next().unwrap_or("").trim().to_string();
429 if !first.is_empty() && tokio::fs::metadata(&first).await.is_ok() {
430 return Some(bash_shell_config(PathBuf::from(first)));
431 }
432 }
433 None
434}
435
436async fn run_command(cmd: &str, args: &[&str], timeout: std::time::Duration) -> Option<String> {
440 let mut command = tokio::process::Command::new(cmd);
441 command.args(args);
442 command.stdout(std::process::Stdio::piped());
443 command.stderr(std::process::Stdio::null());
444 command.stdin(std::process::Stdio::null());
445 #[cfg(windows)]
446 {
447 use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW;
449 command.creation_flags(CREATE_NO_WINDOW);
450 }
451 let child = command.spawn().ok()?;
452 let out = match tokio::time::timeout(timeout, child.wait_with_output()).await {
453 Ok(Ok(o)) => o,
454 _ => return None,
455 };
456 if !out.status.success() {
457 return None;
458 }
459 let s = crate::output_decode::decode_output(&out.stdout);
461 if s.trim().is_empty() {
462 None
463 } else {
464 Some(s)
465 }
466}
467
468#[cfg(windows)]
475mod shell_jobs {
476 use std::collections::HashMap;
477 use std::sync::{LazyLock, Mutex};
478
479 use win32job::{ExtendedLimitInfo, Job};
480
481 static JOBS: LazyLock<Mutex<HashMap<u32, Job>>> = LazyLock::new(Default::default);
482
483 pub fn start(pid: u32, process: std::os::windows::io::RawHandle) -> Result<(), String> {
487 if let Ok(job) = Job::create() {
488 if job.assign_process(process as isize).is_ok() {
489 JOBS.lock().unwrap().insert(pid, job);
490 }
491 }
492 rpi_plugin_sdk::process::resume_child(pid)
493 }
494
495 pub fn terminate(pid: u32) -> bool {
498 let Some(job) = JOBS.lock().unwrap().remove(&pid) else {
499 return false;
500 };
501 let mut info = ExtendedLimitInfo::new();
502 info.limit_kill_on_job_close();
503 job.set_extended_limit_info(&info).is_ok()
504 }
505
506 pub fn forget(pid: u32) {
507 JOBS.lock().unwrap().remove(&pid);
508 }
509}
510
511struct ShellProcessGuard {
515 pid: Option<u32>,
516 active: Arc<Mutex<HashSet<u32>>>,
517}
518impl ShellProcessGuard {
519 fn finish(&mut self) {
520 if let Some(pid) = self.pid.take() {
521 #[cfg(windows)]
522 shell_jobs::forget(pid);
523 self.active
524 .lock()
525 .unwrap_or_else(|e| e.into_inner())
526 .remove(&pid);
527 }
528 }
529}
530impl Drop for ShellProcessGuard {
531 fn drop(&mut self) {
532 if let Some(pid) = self.pid {
533 #[cfg(unix)]
534 {
535 use nix::sys::signal::{kill, Signal};
536 use nix::unistd::Pid;
537 let _ = kill(Pid::from_raw(-(pid as i32)), Signal::SIGKILL);
540 }
541 #[cfg(windows)]
542 shell_jobs::terminate(pid);
543 self.finish();
544 }
545 }
546}
547
548async fn kill_process_tree(pid: u32) {
552 #[cfg(windows)]
553 {
554 if shell_jobs::terminate(pid) {
555 return;
556 }
557 use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW;
558 let mut cmd = tokio::process::Command::new("taskkill");
559 cmd.args(&["/F", "/T", "/PID", &pid.to_string()]);
560 cmd.creation_flags(CREATE_NO_WINDOW);
561 cmd.stdin(std::process::Stdio::null());
562 cmd.stdout(std::process::Stdio::null());
563 cmd.stderr(std::process::Stdio::null());
564 let _ = cmd.status().await;
569 }
570 #[cfg(unix)]
571 {
572 use nix::sys::signal::{kill, Signal};
573 use nix::unistd::Pid;
574 let pg = Pid::from_raw(-(pid as i32));
576 if kill(pg, Signal::SIGKILL).is_err() {
577 let _ = kill(Pid::from_raw(pid as i32), Signal::SIGKILL);
578 }
579 }
580 #[cfg(not(any(windows, unix)))]
581 {
582 let _ = pid;
583 }
584}
585
586#[async_trait]
587impl FileSystem for OsExecutionEnv {
588 fn native_file_path(&self, path: &str) -> Option<PathBuf> {
589 #[cfg(unix)]
590 return Some(self.resolve_path(path));
591 #[cfg(not(unix))]
592 {
593 let _ = path;
594 None
595 }
596 }
597
598 async fn try_acquire_writer_lease(
599 &self,
600 path: &str,
601 ) -> Result<Option<Box<dyn WriterLease>>, FileError> {
602 let session_path = self.resolve_path(path);
603 let lock_path = PathBuf::from(format!("{}.lock", session_path.display()));
604 let display_path = session_path.to_string_lossy().into_owned();
605 tokio::task::spawn_blocking(move || {
606 use fs2::FileExt;
607 let mut file = std::fs::OpenOptions::new()
608 .create(true)
609 .read(true)
610 .write(true)
611 .open(&lock_path)
612 .map_err(|error| io_to_file_error(error, Some(&lock_path.to_string_lossy())))?;
613 file.try_lock_exclusive().map_err(|error| {
614 FileError::new(
615 FileErrorCode::PermissionDenied,
616 format!("writer lease is already held for {display_path}"),
617 )
618 .with_path(lock_path.to_string_lossy())
619 .with_source(Box::new(error))
620 })?;
621 file.seek(SeekFrom::Start(0))
622 .map_err(|error| io_to_file_error(error, Some(&lock_path.to_string_lossy())))?;
623 let mut contents = String::new();
624 file.read_to_string(&mut contents)
625 .map_err(|error| io_to_file_error(error, Some(&lock_path.to_string_lossy())))?;
626 let previous = if contents.trim().is_empty() {
627 0
628 } else {
629 contents.trim().parse::<u64>().map_err(|error| {
630 FileError::new(
631 FileErrorCode::Unknown,
632 format!("invalid persisted writer lease fence: {error}"),
633 )
634 .with_path(lock_path.to_string_lossy())
635 })?
636 };
637 let fence = previous.checked_add(1).ok_or_else(|| {
638 FileError::new(FileErrorCode::Unknown, "writer lease fence exhausted")
639 .with_path(lock_path.to_string_lossy())
640 })?;
641 file.seek(SeekFrom::Start(0))
642 .and_then(|_| file.set_len(0))
643 .and_then(|_| file.write_all(fence.to_string().as_bytes()))
644 .and_then(|_| file.sync_all())
645 .map_err(|error| io_to_file_error(error, Some(&lock_path.to_string_lossy())))?;
646 Ok(Some(
647 Box::new(OsWriterLease { file, fence }) as Box<dyn WriterLease>
648 ))
649 })
650 .await
651 .map_err(|error| {
652 FileError::new(
653 FileErrorCode::Unknown,
654 format!("writer lease task failed: {error}"),
655 )
656 .with_path(session_path.to_string_lossy())
657 })?
658 }
659
660 async fn sync_file(
661 &self,
662 path: &str,
663 data_only: bool,
664 cancel: Option<&CancellationToken>,
665 ) -> Result<(), FileError> {
666 check_cancel_file(cancel, Some(path))?;
667 let abs = self.resolve_path(path);
668 let error_path = abs.to_string_lossy().into_owned();
669 let io_path = error_path.clone();
670 tokio::task::spawn_blocking(move || {
671 let file = std::fs::OpenOptions::new()
672 .read(true)
673 .write(true)
674 .open(&abs)
675 .map_err(|error| io_to_file_error(error, Some(&io_path)))?;
676 if data_only {
677 file.sync_data()
678 .map_err(|error| io_to_file_error(error, Some(&io_path)))
679 } else {
680 file.sync_all()
681 .map_err(|error| io_to_file_error(error, Some(&io_path)))
682 }
683 })
684 .await
685 .map_err(|error| {
686 FileError::new(
687 FileErrorCode::Unknown,
688 format!("file sync task failed: {error}"),
689 )
690 .with_path(error_path)
691 })??;
692 Ok(())
693 }
694
695 async fn sync_directory(
696 &self,
697 path: &str,
698 cancel: Option<&CancellationToken>,
699 ) -> Result<(), FileError> {
700 check_cancel_file(cancel, Some(path))?;
701 let abs = self.resolve_path(path);
702 #[cfg(unix)]
703 {
704 let error_path = abs.to_string_lossy().into_owned();
705 let io_path = error_path.clone();
706 tokio::task::spawn_blocking(move || {
707 std::fs::File::open(&abs)
708 .map_err(|error| io_to_file_error(error, Some(&io_path)))?
709 .sync_all()
710 .map_err(|error| io_to_file_error(error, Some(&io_path)))
711 })
712 .await
713 .map_err(|error| {
714 FileError::new(
715 FileErrorCode::Unknown,
716 format!("directory sync task failed: {error}"),
717 )
718 .with_path(error_path)
719 })??;
720 }
721 #[cfg(not(unix))]
722 {
723 let _ = abs;
727 }
728 Ok(())
729 }
730
731 async fn sync_file_and_parent(
732 &self,
733 path: &str,
734 cancel: Option<&CancellationToken>,
735 ) -> Result<(), FileError> {
736 check_cancel_file(cancel, Some(path))?;
737 #[cfg(unix)]
738 {
739 let abs = self.resolve_path(path);
740 let info = self.file_info(path, cancel).await?;
741 if info.kind != FileKind::File {
742 return Err(FileError::new(
743 FileErrorCode::NotSupported,
744 "journal synchronization requires a regular file",
745 )
746 .with_path(path));
747 }
748 self.sync_file(path, false, cancel).await?;
751 let parent = abs.parent().ok_or_else(|| {
752 FileError::new(
753 FileErrorCode::NotSupported,
754 "journal has no parent directory",
755 )
756 .with_path(path)
757 })?;
758 self.sync_directory(&parent.to_string_lossy(), cancel).await
759 }
760 #[cfg(not(unix))]
761 {
762 Err(FileError::new(
765 FileErrorCode::NotSupported,
766 "physical journal synchronization is unsupported on this platform",
767 )
768 .with_path(path))
769 }
770 }
771
772 async fn open_append_file(
773 &self,
774 path: &str,
775 ) -> Result<Option<Box<dyn crate::env::AppendFile>>, FileError> {
776 let path = self.resolve_path(path);
777 Ok(Some(Box::new(append::OsAppendFile::open(path).await?)))
778 }
779
780 async fn open_read_file(
781 &self,
782 path: &str,
783 ) -> Result<Option<Arc<dyn crate::env::ReadFile>>, FileError> {
784 let path = self.resolve_path(path);
785 Ok(Some(Arc::new(read::OsReadFile::open(path).await?)))
786 }
787
788 async fn truncate_file(
789 &self,
790 path: &str,
791 len: u64,
792 cancel: Option<&CancellationToken>,
793 ) -> Result<(), FileError> {
794 check_cancel_file(cancel, Some(path))?;
795 let abs = self.resolve_path(path);
796 let error_path = abs.to_string_lossy().into_owned();
797 tokio::task::spawn_blocking(move || {
798 let file = std::fs::OpenOptions::new().write(true).open(&abs)?;
799 if len > file.metadata()?.len() {
800 return Err(std::io::Error::new(
801 std::io::ErrorKind::InvalidInput,
802 "truncation cannot grow a file",
803 ));
804 }
805 file.set_len(len)
806 })
807 .await
808 .map_err(|error| {
809 FileError::new(
810 FileErrorCode::Unknown,
811 format!("file truncation task failed: {error}"),
812 )
813 })?
814 .map_err(|error| io_to_file_error(error, Some(&error_path)))
815 }
816
817 fn cwd(&self) -> &Path {
818 &self.cwd
819 }
820
821 async fn absolute_path(
822 &self,
823 path: &str,
824 cancel: Option<&CancellationToken>,
825 ) -> Result<PathBuf, FileError> {
826 check_cancel_file(cancel, Some(path))?;
827 Ok(self.resolve_path(path))
828 }
829
830 async fn join_path(
831 &self,
832 parts: &[&str],
833 cancel: Option<&CancellationToken>,
834 ) -> Result<PathBuf, FileError> {
835 check_cancel_file(cancel, None)?;
836 let mut out = PathBuf::new();
837 for p in parts {
838 out.push(p);
839 }
840 Ok(out)
841 }
842
843 async fn read_text_file(
844 &self,
845 path: &str,
846 cancel: Option<&CancellationToken>,
847 ) -> Result<String, FileError> {
848 check_cancel_file(cancel, Some(path))?;
849 let abs = self.resolve_path(path);
850 let bytes = read_cancellable(&abs, cancel).await?;
851 String::from_utf8(bytes).map_err(|e| {
852 FileError::new(FileErrorCode::Invalid, format!("invalid utf-8: {e}"))
853 .with_path(abs.to_string_lossy())
854 })
855 }
856
857 async fn read_text_lines(
858 &self,
859 path: &str,
860 max_lines: Option<usize>,
861 cancel: Option<&CancellationToken>,
862 ) -> Result<Vec<String>, FileError> {
863 check_cancel_file(cancel, Some(path))?;
864 if max_lines.map(|m| m == 0).unwrap_or(false) {
865 return Ok(Vec::new());
866 }
867 let abs = self.resolve_path(path);
868 read::read_text_lines(&abs, max_lines, cancel).await
869 }
870
871 async fn read_binary_file(
872 &self,
873 path: &str,
874 cancel: Option<&CancellationToken>,
875 ) -> Result<Vec<u8>, FileError> {
876 check_cancel_file(cancel, Some(path))?;
877 let abs = self.resolve_path(path);
878 read_cancellable(&abs, cancel).await
879 }
880
881 async fn write_file(
882 &self,
883 path: &str,
884 content: FileContent,
885 cancel: Option<&CancellationToken>,
886 ) -> Result<(), FileError> {
887 check_cancel_file(cancel, Some(path))?;
888 let abs = self.resolve_path(path);
889 if let Some(parent) = abs.parent() {
891 if !parent.as_os_str().is_empty() {
892 if let Err(e) = tokio::fs::create_dir_all(parent).await {
893 return Err(io_to_file_error(e, Some(&abs.to_string_lossy())));
894 }
895 }
896 }
897 check_cancel_file(cancel, Some(&abs.to_string_lossy()))?;
898 write_cancellable(&abs, content.as_bytes(), cancel).await
899 }
900
901 async fn write_new_file(
902 &self,
903 path: &str,
904 content: FileContent,
905 cancel: Option<&CancellationToken>,
906 ) -> Result<(), FileError> {
907 check_cancel_file(cancel, Some(path))?;
908 let abs = self.resolve_path(path);
909 let cancel = cancel.cloned();
910 tokio::task::spawn_blocking(move || {
914 let display = abs.to_string_lossy();
915 check_cancel_file(cancel.as_ref(), Some(&display))?;
916 let mut options = std::fs::OpenOptions::new();
917 options.write(true).create_new(true);
918 #[cfg(unix)]
919 {
920 use std::os::unix::fs::OpenOptionsExt;
921 options.mode(0o600);
922 }
923 let mut file = options
924 .open(&abs)
925 .map_err(|error| io_to_file_error(error, Some(&display)))?;
926 for chunk in content.as_bytes().chunks(64 * 1024) {
927 check_cancel_file(cancel.as_ref(), Some(&display))?;
928 file.write_all(chunk)
929 .map_err(|error| io_to_file_error(error, Some(&display)))?;
930 }
931 file.flush()
932 .map_err(|error| io_to_file_error(error, Some(&display)))
933 })
934 .await
935 .map_err(|_| {
936 FileError::new(
937 FileErrorCode::Unknown,
938 "exclusive file creation task stopped",
939 )
940 })?
941 }
942
943 async fn append_file(
944 &self,
945 path: &str,
946 content: FileContent,
947 cancel: Option<&CancellationToken>,
948 ) -> Result<(), FileError> {
949 check_cancel_file(cancel, Some(path))?;
950 let abs = self.resolve_path(path);
951 if let Some(parent) = abs.parent() {
952 if !parent.as_os_str().is_empty() {
953 let _ = tokio::fs::create_dir_all(parent).await;
954 }
955 }
956 use tokio::io::AsyncWriteExt;
957 let res = match tokio::fs::OpenOptions::new()
958 .create(true)
959 .append(true)
960 .open(&abs)
961 .await
962 {
963 Ok(mut f) => {
964 match f.write_all(content.as_bytes()).await {
968 Ok(()) => f.flush().await,
969 Err(error) => Err(error),
970 }
971 }
972 Err(e) => return Err(io_to_file_error(e, Some(&abs.to_string_lossy()))),
973 };
974 res.map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))
975 }
976
977 async fn rename_file(
978 &self,
979 source: &str,
980 dest: &str,
981 cancel: Option<&CancellationToken>,
982 ) -> Result<(), FileError> {
983 check_cancel_file(cancel, Some(source))?;
984 let src = self.resolve_path(source);
985 let dst = self.resolve_path(dest);
986 tokio::fs::rename(&src, &dst)
987 .await
988 .map_err(|e| io_to_file_error(e, Some(&src.to_string_lossy())))
989 }
990
991 async fn file_info(
992 &self,
993 path: &str,
994 cancel: Option<&CancellationToken>,
995 ) -> Result<FileInfo, FileError> {
996 check_cancel_file(cancel, Some(path))?;
997 let abs = self.resolve_path(path);
998 let meta = tokio::fs::symlink_metadata(&abs)
999 .await
1000 .map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?;
1001 let ft = meta.file_type();
1002 let kind = if ft.is_file() {
1003 FileKind::File
1004 } else if ft.is_dir() {
1005 FileKind::Directory
1006 } else if ft.is_symlink() {
1007 FileKind::Symlink
1008 } else {
1009 return Err(
1010 FileError::new(FileErrorCode::Invalid, "Unsupported file type")
1011 .with_path(abs.to_string_lossy()),
1012 );
1013 };
1014 let mtime_ms = meta
1015 .modified()
1016 .ok()
1017 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1018 .map(|d| d.as_millis() as i64)
1019 .unwrap_or(0);
1020 Ok(FileInfo {
1021 name: abs
1022 .file_name()
1023 .map(|n| n.to_string_lossy().into_owned())
1024 .unwrap_or_else(|| abs.to_string_lossy().into_owned()),
1025 path: abs.clone(),
1026 kind,
1027 size: meta.len(),
1028 mtime_ms,
1029 })
1030 }
1031
1032 async fn list_dir(
1033 &self,
1034 path: &str,
1035 cancel: Option<&CancellationToken>,
1036 ) -> Result<Vec<FileInfo>, FileError> {
1037 check_cancel_file(cancel, Some(path))?;
1038 let abs = self.resolve_path(path);
1039 let mut entries = tokio::fs::read_dir(&abs)
1040 .await
1041 .map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?;
1042 let mut out = Vec::new();
1043 while let Some(entry) = entries
1044 .next_entry()
1045 .await
1046 .map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?
1047 {
1048 if let Some(t) = cancel {
1049 if t.is_cancelled() {
1050 return Err(FileError::aborted().with_path(abs.to_string_lossy()));
1051 }
1052 }
1053 let ep = entry.path();
1054 let meta = match tokio::fs::symlink_metadata(&ep).await {
1055 Ok(m) => m,
1056 Err(e) => {
1057 let code = crate::error::io_to_file_code(&e);
1059 if code == FileErrorCode::NotSupported {
1060 continue;
1061 }
1062 return Err(io_to_file_error(e, Some(&ep.to_string_lossy())));
1063 }
1064 };
1065 let ft = meta.file_type();
1066 let kind = if ft.is_file() {
1067 FileKind::File
1068 } else if ft.is_dir() {
1069 FileKind::Directory
1070 } else if ft.is_symlink() {
1071 FileKind::Symlink
1072 } else {
1073 continue; };
1075 let mtime_ms = meta
1076 .modified()
1077 .ok()
1078 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1079 .map(|d| d.as_millis() as i64)
1080 .unwrap_or(0);
1081 out.push(FileInfo {
1082 name: entry.file_name().to_string_lossy().into_owned(),
1083 path: ep,
1084 kind,
1085 size: meta.len(),
1086 mtime_ms,
1087 });
1088 }
1089 Ok(out)
1090 }
1091
1092 async fn has_file_with_suffix(
1093 &self,
1094 path: &str,
1095 suffix: &str,
1096 cancel: Option<&CancellationToken>,
1097 ) -> Result<bool, FileError> {
1098 check_cancel_file(cancel, Some(path))?;
1099 let abs = self.resolve_path(path);
1100 let error_path = abs.to_string_lossy().into_owned();
1101 let suffix = String::from(suffix);
1102 let cancel = cancel.cloned();
1103 tokio::task::spawn_blocking(move || {
1106 check_cancel_file(cancel.as_ref(), Some(&abs.to_string_lossy()))?;
1107 let entries = std::fs::read_dir(&abs)
1108 .map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?;
1109 for entry in entries {
1110 check_cancel_file(cancel.as_ref(), Some(&abs.to_string_lossy()))?;
1111 let entry = entry.map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?;
1112 if !entry.file_name().to_string_lossy().ends_with(&suffix) {
1113 continue;
1114 }
1115 let kind = match entry.file_type() {
1116 Ok(kind) => kind,
1117 Err(error)
1118 if crate::error::io_to_file_code(&error) == FileErrorCode::NotSupported =>
1119 {
1120 continue
1121 }
1122 Err(error) => {
1123 return Err(io_to_file_error(
1124 error,
1125 Some(&entry.path().to_string_lossy()),
1126 ))
1127 }
1128 };
1129 check_cancel_file(cancel.as_ref(), Some(&abs.to_string_lossy()))?;
1130 if kind.is_file() || kind.is_symlink() {
1131 return Ok(true);
1132 }
1133 }
1134 check_cancel_file(cancel.as_ref(), Some(&abs.to_string_lossy()))?;
1135 Ok(false)
1136 })
1137 .await
1138 .map_err(|error| {
1139 FileError::new(
1140 FileErrorCode::Unknown,
1141 format!("directory scan task failed: {error}"),
1142 )
1143 .with_path(error_path)
1144 })?
1145 }
1146
1147 async fn canonical_path(
1148 &self,
1149 path: &str,
1150 cancel: Option<&CancellationToken>,
1151 ) -> Result<PathBuf, FileError> {
1152 check_cancel_file(cancel, Some(path))?;
1153 let abs = self.resolve_path(path);
1154 tokio::fs::canonicalize(&abs)
1155 .await
1156 .map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))
1157 }
1158
1159 async fn exists(
1160 &self,
1161 path: &str,
1162 cancel: Option<&CancellationToken>,
1163 ) -> Result<bool, FileError> {
1164 check_cancel_file(cancel, Some(path))?;
1165 let abs = self.resolve_path(path);
1166 match tokio::fs::symlink_metadata(&abs).await {
1167 Ok(_) => Ok(true),
1168 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
1169 Err(e) => Err(io_to_file_error(e, Some(&abs.to_string_lossy()))),
1170 }
1171 }
1172
1173 async fn create_dir(
1174 &self,
1175 path: &str,
1176 recursive: bool,
1177 cancel: Option<&CancellationToken>,
1178 ) -> Result<(), FileError> {
1179 check_cancel_file(cancel, Some(path))?;
1180 let abs = self.resolve_path(path);
1181 let res = if recursive {
1182 tokio::fs::create_dir_all(&abs).await
1183 } else {
1184 tokio::fs::create_dir(&abs).await
1185 };
1186 res.map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))
1187 }
1188
1189 async fn remove(
1190 &self,
1191 path: &str,
1192 recursive: bool,
1193 force: bool,
1194 cancel: Option<&CancellationToken>,
1195 ) -> Result<(), FileError> {
1196 check_cancel_file(cancel, Some(path))?;
1197 let abs = self.resolve_path(path);
1198 let res = if recursive {
1199 tokio::fs::remove_dir_all(&abs).await
1200 } else {
1201 match tokio::fs::remove_file(&abs).await {
1203 Ok(()) => Ok(()),
1204 Err(_) => tokio::fs::remove_dir(&abs).await,
1205 }
1206 };
1207 match res {
1208 Ok(()) => Ok(()),
1209 Err(e) if e.kind() == std::io::ErrorKind::NotFound && force => Ok(()),
1210 Err(e) => Err(io_to_file_error(e, Some(&abs.to_string_lossy()))),
1211 }
1212 }
1213
1214 async fn create_temp_dir(
1215 &self,
1216 prefix: Option<&str>,
1217 cancel: Option<&CancellationToken>,
1218 ) -> Result<PathBuf, FileError> {
1219 check_cancel_file(cancel, None)?;
1220 let prefix = prefix.unwrap_or("tmp-");
1221 let tmp =
1223 tempfile::tempdir_in(std::env::temp_dir()).map_err(|e| io_to_file_error(e, None))?;
1224 let path = tmp.path().to_path_buf();
1226 std::mem::forget(tmp); let final_path = std::env::temp_dir().join(format!("{}{}", prefix, random_suffix()));
1229 if let Err(e) = tokio::fs::rename(&path, &final_path).await {
1231 let _ = e;
1233 return Ok(path);
1234 }
1235 Ok(final_path)
1236 }
1237
1238 async fn create_temp_file(
1239 &self,
1240 prefix: &str,
1241 suffix: &str,
1242 cancel: Option<&CancellationToken>,
1243 ) -> Result<PathBuf, FileError> {
1244 check_cancel_file(cancel, None)?;
1245 let dir = self.create_temp_dir(Some("tmp-"), cancel).await?;
1248 let name = format!("{}{}{}", prefix, random_suffix(), suffix);
1249 let path = dir.join(name);
1250 tokio::fs::File::create(&path)
1251 .await
1252 .map_err(|e| io_to_file_error(e, Some(&path.to_string_lossy())))?;
1253 Ok(path)
1254 }
1255
1256 async fn cleanup(&self) {
1257 let pids: Vec<u32> = self
1258 .active_pids
1259 .lock()
1260 .unwrap_or_else(|e| e.into_inner())
1261 .iter()
1262 .copied()
1263 .collect();
1264 for pid in pids {
1265 kill_process_tree(pid).await;
1266 }
1267 self.active_pids
1268 .lock()
1269 .unwrap_or_else(|e| e.into_inner())
1270 .clear();
1271 }
1272}
1273
1274async fn read_cancellable(
1276 path: &Path,
1277 cancel: Option<&CancellationToken>,
1278) -> Result<Vec<u8>, FileError> {
1279 let read = tokio::fs::read(path);
1280 let res = match cancel {
1281 Some(t) => tokio::select! {
1282 r = read => r,
1283 _ = t.cancelled() => return Err(FileError::aborted().with_path(path.to_string_lossy())),
1284 },
1285 None => read.await,
1286 };
1287 res.map_err(|e| io_to_file_error(e, Some(&path.to_string_lossy())))
1288}
1289
1290async fn write_cancellable(
1292 path: &Path,
1293 bytes: &[u8],
1294 cancel: Option<&CancellationToken>,
1295) -> Result<(), FileError> {
1296 use tokio::io::AsyncWriteExt;
1297 let f = tokio::fs::File::create(path)
1298 .await
1299 .map_err(|e| io_to_file_error(e, Some(&path.to_string_lossy())))?;
1300 let write = async {
1301 let mut f = f;
1302 f.write_all(bytes).await?;
1303 f.flush().await?;
1304 Ok::<(), std::io::Error>(())
1305 };
1306 let res = match cancel {
1307 Some(t) => tokio::select! {
1308 r = write => r,
1309 _ = t.cancelled() => return Err(FileError::aborted().with_path(path.to_string_lossy())),
1310 },
1311 None => write.await,
1312 };
1313 res.map_err(|e| io_to_file_error(e, Some(&path.to_string_lossy())))
1314}
1315
1316fn random_suffix() -> String {
1317 uuid::Uuid::new_v4().simple().to_string()
1319}
1320
1321#[async_trait]
1322impl Shell for OsExecutionEnv {
1323 async fn exec<'a>(
1324 &'a self,
1325 command: &str,
1326 options: ShellExecOptions<'a>,
1327 ) -> Result<ShellOutput, ExecutionError> {
1328 check_cancel_exec(options.cancel)?;
1330 let timeout = match resolve_timeout(options.timeout) {
1332 Ok(t) => t,
1333 Err(e) => return Err(e),
1334 };
1335 let cwd = match &options.cwd {
1337 Some(c) => self.resolve_path(&c.to_string_lossy()),
1338 None => self.cwd.clone(),
1339 };
1340 let shell_cfg = match &options.shell {
1343 Some(override_shell) => ShellConfig {
1344 shell: override_shell.program.clone(),
1345 args: override_shell.args.clone(),
1346 transport: CommandTransport::Argv,
1347 },
1348 None => self.get_shell_config().await?,
1349 };
1350 if !cwd.exists() {
1352 return Err(ExecutionError::new(
1353 ExecutionErrorCode::SpawnError,
1354 format!(
1355 "Working directory does not exist: {}\nCannot execute bash commands.",
1356 cwd.display()
1357 ),
1358 ));
1359 }
1360
1361 let mut cmd = tokio::process::Command::new(&shell_cfg.shell);
1363 cmd.current_dir(&cwd);
1364 cmd.env_clear();
1365 for (k, v) in NON_INTERACTIVE_SHELL_ENV {
1369 cmd.env(k, v);
1370 }
1371 if options.inherit_env {
1378 let mut inherit = |name: &str, value: &str| {
1379 if !is_host_private_env(name) {
1380 cmd.env(name, value);
1381 }
1382 };
1383 match &self.environment {
1384 Some(environment) => {
1385 for (name, value) in environment {
1386 inherit(name, value);
1387 }
1388 }
1389 None => {
1390 for (name, value) in std::env::vars() {
1391 inherit(&name, &value);
1392 }
1393 }
1394 }
1395 }
1396 if let Some(base) = &self.shell_env {
1397 for (k, v) in base {
1398 cmd.env(k, v);
1399 }
1400 }
1401 if let Some(extra) = &options.env {
1402 for (k, v) in extra {
1403 cmd.env(k, v);
1404 }
1405 }
1406 cmd.kill_on_drop(true);
1408 cmd.stdin(std::process::Stdio::piped());
1409 cmd.stdout(std::process::Stdio::piped());
1410 cmd.stderr(std::process::Stdio::piped());
1411 #[cfg(unix)]
1412 {
1413 cmd.process_group(0); }
1415 #[cfg(windows)]
1416 {
1417 use windows_sys::Win32::System::Threading::{CREATE_NO_WINDOW, CREATE_SUSPENDED};
1418 cmd.creation_flags(CREATE_NO_WINDOW | CREATE_SUSPENDED);
1420 }
1421
1422 let transport = shell_cfg.transport;
1424 cmd.args(&shell_cfg.args);
1425 if matches!(transport, CommandTransport::Argv) {
1426 cmd.arg(command);
1427 }
1428
1429 let mut child = match cmd.spawn() {
1430 Ok(c) => c,
1431 Err(e) => {
1432 return Err(ExecutionError::new(
1433 ExecutionErrorCode::SpawnError,
1434 format!("failed to spawn shell: {e}"),
1435 ));
1436 }
1437 };
1438 let pid = child.id();
1439 let mut process_guard = ShellProcessGuard {
1440 pid,
1441 active: self.active_pids.clone(),
1442 };
1443 #[cfg(windows)]
1444 {
1445 let started = match (pid, child.raw_handle()) {
1446 (Some(pid), Some(process)) => shell_jobs::start(pid, process),
1447 _ => Err("the shell has no process handle".to_owned()),
1448 };
1449 if let Err(error) = started {
1450 if let Some(pid) = pid {
1451 shell_jobs::forget(pid);
1452 }
1453 let _ = child.start_kill();
1454 return Err(ExecutionError::new(
1455 ExecutionErrorCode::SpawnError,
1456 format!("failed to start shell: {error}"),
1457 ));
1458 }
1459 }
1460 if let Some(pid) = pid {
1461 self.active_pids
1462 .lock()
1463 .unwrap_or_else(|e| e.into_inner())
1464 .insert(pid);
1465 }
1466
1467 let mut stdin = child.stdin.take();
1474 if matches!(transport, CommandTransport::Stdin) {
1475 if let Some(stdin) = stdin.as_mut() {
1476 use tokio::io::AsyncWriteExt;
1477 let _ = stdin.write_all(command.as_bytes()).await;
1478 let _ = stdin.flush().await;
1479 }
1480 }
1481 drop(stdin);
1482
1483 let mut stdout_buf = String::new();
1485 let mut stderr_buf = String::new();
1486 let cancel = options.cancel;
1487 let stop_readers = CancellationToken::new();
1488 let mut on_stdout = options.on_stdout;
1489 let mut on_stderr = options.on_stderr;
1490
1491 let mut stdout = child.stdout.take();
1492 let mut stderr = child.stderr.take();
1493
1494 let stdout_task = async {
1495 if let Some(s) = stdout.as_mut() {
1496 let mut buf = vec![0u8; 8192];
1497 let mut decoder = crate::output_decode::StreamDecoder::new();
1498 use tokio::io::AsyncReadExt;
1499 loop {
1500 let read_result = tokio::select! {
1501 biased;
1502 _ = stop_readers.cancelled() => break,
1503 _ = async {
1504 match cancel {
1505 Some(token) => token.cancelled().await,
1506 None => std::future::pending::<()>().await,
1507 }
1508 } => break,
1509 result = s.read(&mut buf) => result,
1510 };
1511 let n = match read_result {
1512 Ok(0) => break,
1513 Ok(n) => n,
1514 Err(_) => break,
1515 };
1516 let chunk = decoder.push(&buf[..n]);
1517 if chunk.is_empty() {
1518 continue;
1519 }
1520 if let Some(cb) = on_stdout.as_mut() {
1521 cb(&chunk);
1524 }
1525 stdout_buf.push_str(&chunk);
1526 }
1527 let tail = decoder.finish();
1528 if !tail.is_empty() {
1529 if let Some(cb) = on_stdout.as_mut() {
1530 cb(&tail);
1531 }
1532 stdout_buf.push_str(&tail);
1533 }
1534 }
1535 };
1536 let stderr_task = async {
1537 if let Some(s) = stderr.as_mut() {
1538 let mut buf = vec![0u8; 8192];
1539 let mut decoder = crate::output_decode::StreamDecoder::new();
1540 use tokio::io::AsyncReadExt;
1541 loop {
1542 let read_result = tokio::select! {
1543 biased;
1544 _ = stop_readers.cancelled() => break,
1545 _ = async {
1546 match cancel {
1547 Some(token) => token.cancelled().await,
1548 None => std::future::pending::<()>().await,
1549 }
1550 } => break,
1551 result = s.read(&mut buf) => result,
1552 };
1553 let n = match read_result {
1554 Ok(0) => break,
1555 Ok(n) => n,
1556 Err(_) => break,
1557 };
1558 let chunk = decoder.push(&buf[..n]);
1559 if chunk.is_empty() {
1560 continue;
1561 }
1562 if let Some(cb) = on_stderr.as_mut() {
1563 cb(&chunk);
1564 }
1565 stderr_buf.push_str(&chunk);
1566 }
1567 let tail = decoder.finish();
1568 if !tail.is_empty() {
1569 if let Some(cb) = on_stderr.as_mut() {
1570 cb(&tail);
1571 }
1572 stderr_buf.push_str(&tail);
1573 }
1574 }
1575 };
1576
1577 let mut timed_out = false;
1579 let exit_status = {
1580 let status_fut = async {
1585 match (timeout, cancel) {
1586 (Some(to), Some(token)) => {
1587 tokio::select! {
1588 status = child.wait() => status,
1589 _ = tokio::time::sleep(to) => {
1590 timed_out = true;
1591 if let Some(pid) = child.id() {
1592 kill_process_tree(pid).await;
1593 }
1594 child.wait().await
1595 }
1596 _ = token.cancelled() => {
1597 if let Some(pid) = child.id() {
1598 kill_process_tree(pid).await;
1599 }
1600 child.wait().await
1601 }
1602 }
1603 }
1604 (Some(to), None) => match tokio::time::timeout(to, child.wait()).await {
1605 Ok(status) => status,
1606 Err(_) => {
1607 timed_out = true;
1608 if let Some(pid) = child.id() {
1609 kill_process_tree(pid).await;
1610 }
1611 child.wait().await
1612 }
1613 },
1614 (None, Some(token)) => {
1615 tokio::select! {
1616 status = child.wait() => status,
1617 _ = token.cancelled() => {
1618 if let Some(pid) = child.id() {
1619 kill_process_tree(pid).await;
1620 }
1621 child.wait().await
1622 }
1623 }
1624 }
1625 (None, None) => child.wait().await,
1626 }
1627 };
1628 tokio::pin!(status_fut, stdout_task, stderr_task);
1643 let (mut stdout_done, mut stderr_done) = (false, false);
1644 let status_res = loop {
1645 tokio::select! {
1646 status = &mut status_fut => break status,
1647 () = &mut stdout_task, if !stdout_done => stdout_done = true,
1648 () = &mut stderr_task, if !stderr_done => stderr_done = true,
1649 }
1650 };
1651 if status_res.is_ok() {
1654 process_guard.finish();
1655 }
1656 let drain = async {
1661 tokio::join!(
1662 async {
1663 if !stdout_done {
1664 (&mut stdout_task).await;
1665 }
1666 },
1667 async {
1668 if !stderr_done {
1669 (&mut stderr_task).await;
1670 }
1671 },
1672 );
1673 };
1674 tokio::pin!(drain);
1675 if tokio::time::timeout(
1676 std::time::Duration::from_millis(EXIT_STDIO_GRACE_MS),
1677 &mut drain,
1678 )
1679 .await
1680 .is_err()
1681 {
1682 stop_readers.cancel();
1685 drain.await;
1686 }
1687 status_res
1688 };
1689
1690 if timed_out {
1694 let _ = tokio::time::sleep(std::time::Duration::from_millis(EXIT_STDIO_GRACE_MS)).await;
1695 }
1696
1697 let status = match exit_status {
1699 Ok(s) => s,
1700 Err(e) => {
1701 return Err(ExecutionError::new(
1702 ExecutionErrorCode::SpawnError,
1703 format!("child wait failed: {e}"),
1704 ));
1705 }
1706 };
1707 if timed_out {
1708 return Err(ExecutionError::timeout(
1709 options.timeout.map(|f| f as u64).unwrap_or(0),
1710 ));
1711 }
1712 if cancel.map(|t| t.is_cancelled()).unwrap_or(false) {
1713 return Err(ExecutionError::aborted());
1714 }
1715 let exit_code = status.code().unwrap_or(0);
1716 Ok(ShellOutput {
1717 stdout: stdout_buf,
1718 stderr: stderr_buf,
1719 exit_code,
1720 })
1721 }
1722
1723 async fn cleanup(&self) {
1724 FileSystem::cleanup(self).await
1725 }
1726}
1727
1728#[async_trait]
1729impl ExecutionEnv for OsExecutionEnv {}
1730
1731#[async_trait]
1732impl MutatingEnv for OsExecutionEnv {
1733 fn as_env(&self) -> &dyn ExecutionEnv {
1734 self
1735 }
1736 fn mutation_registry(&self) -> &MutationQueueRegistry {
1737 &self.registry
1738 }
1739}
1740
1741#[cfg(test)]
1743mod durability_tests {
1744 use super::*;
1745
1746 #[tokio::test]
1747 async fn os_backend_syncs_staged_file_and_publication_directory() {
1748 let temp = tempfile::tempdir().unwrap();
1749 let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1750 env.write_file("staged", FileContent::Text("durable slice".into()), None)
1751 .await
1752 .unwrap();
1753 env.sync_file("staged", false, None).await.unwrap();
1754 env.sync_directory(".", None).await.unwrap();
1755 }
1756
1757 #[tokio::test]
1758 async fn os_writer_lease_persists_and_verifies_a_monotonic_fence() {
1759 let temp = tempfile::tempdir().unwrap();
1760 let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1761 let first = env
1762 .try_acquire_writer_lease("journal.jsonl")
1763 .await
1764 .unwrap()
1765 .unwrap();
1766 first.verify_fence().unwrap();
1767 drop(first);
1768 let second = env
1769 .try_acquire_writer_lease("journal.jsonl")
1770 .await
1771 .unwrap()
1772 .unwrap();
1773 second.verify_fence().unwrap();
1774 drop(second);
1775 assert_eq!(
1776 std::fs::read_to_string(temp.path().join("journal.jsonl.lock")).unwrap(),
1777 "2"
1778 );
1779 }
1780
1781 #[cfg(unix)]
1782 #[tokio::test]
1783 async fn os_writer_lease_releases_a_shared_open_file_description() {
1784 let temp = tempfile::tempdir().unwrap();
1785 let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1786 let lock = temp.path().join("journal.jsonl.lock");
1787 std::fs::write(&lock, "1").unwrap();
1788 let file = std::fs::OpenOptions::new()
1789 .read(true)
1790 .write(true)
1791 .open(&lock)
1792 .unwrap();
1793 fs2::FileExt::try_lock_exclusive(&file).unwrap();
1794 let inherited = file.try_clone().unwrap();
1795 let lease = OsWriterLease { file, fence: 1 };
1796 assert!(env.try_acquire_writer_lease("journal.jsonl").await.is_err());
1797 drop(lease);
1798 let next = env
1799 .try_acquire_writer_lease("journal.jsonl")
1800 .await
1801 .expect("retired writer retained a lock through the shared description")
1802 .unwrap();
1803 next.verify_fence().unwrap();
1804 assert_eq!(std::fs::read_to_string(lock).unwrap(), "2");
1805 drop(inherited);
1806 }
1807}
1808
1809fn resolve_timeout(timeout: Option<f64>) -> Result<Option<std::time::Duration>, ExecutionError> {
1810 match timeout {
1811 None => Ok(None),
1812 Some(secs) => {
1813 if !secs.is_finite() || secs <= 0.0 {
1814 return Err(ExecutionError::new(
1815 ExecutionErrorCode::Timeout,
1816 "Invalid timeout: must be a finite number of seconds",
1817 ));
1818 }
1819 let ms = secs * 1000.0;
1820 if ms > MAX_TIMEOUT_MS as f64 {
1821 return Err(ExecutionError::new(
1822 ExecutionErrorCode::Timeout,
1823 format!(
1824 "Invalid timeout: maximum is {} seconds",
1825 MAX_TIMEOUT_SECONDS
1826 ),
1827 ));
1828 }
1829 Ok(Some(std::time::Duration::from_secs_f64(secs)))
1830 }
1831 }
1832}