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, 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(
1293 path: PathBuf,
1294 content: FileContent,
1295 cancel: Option<&CancellationToken>,
1296) -> Result<(), FileError> {
1297 let task_path = path.clone();
1298 let cancel = cancel.cloned();
1299 tokio::task::spawn_blocking(move || {
1300 let path = task_path.to_string_lossy();
1301 check_cancel_file(cancel.as_ref(), Some(&path))?;
1302 let write = || -> std::io::Result<()> {
1303 let mut file = std::fs::File::create(&task_path)?;
1304 file.write_all(content.as_bytes())?;
1305 file.flush()
1306 };
1307 write().map_err(|error| io_to_file_error(error, Some(&path)))
1308 })
1309 .await
1310 .map_err(|error| {
1311 FileError::new(FileErrorCode::Unknown, "file write task failed")
1312 .with_path(path.to_string_lossy())
1313 .with_source(Box::new(error))
1314 })?
1315}
1316
1317fn random_suffix() -> String {
1318 uuid::Uuid::new_v4().simple().to_string()
1320}
1321
1322async fn drain_shell_pipe(
1323 pipe: Option<impl tokio::io::AsyncRead + Unpin>,
1324 mut callback: Option<Box<dyn FnMut(&str) + Send + '_>>,
1325 retained: &mut String,
1326 streamed: Option<&tokio::sync::mpsc::Sender<String>>,
1327 shell_exited: &CancellationToken,
1328 cancel: Option<&CancellationToken>,
1329) {
1330 use tokio::io::AsyncReadExt;
1331 use tokio::time::{timeout, Duration, Instant};
1332
1333 let Some(mut pipe) = pipe else { return };
1334 let mut buffer = [0u8; 8192];
1335 let mut decoder = crate::output_decode::StreamDecoder::new();
1336 let mut drain_budget = Duration::from_millis(EXIT_STDIO_GRACE_MS);
1337 let cancelled = async {
1338 match cancel {
1339 Some(token) => token.cancelled().await,
1340 None => std::future::pending::<()>().await,
1341 }
1342 };
1343 tokio::pin!(cancelled);
1344 loop {
1345 let read = async {
1346 let read = pipe.read(&mut buffer);
1347 tokio::pin!(read);
1348 tokio::select! {
1349 biased;
1350 _ = shell_exited.cancelled() => {},
1351 result = &mut read => return result.unwrap_or(0),
1352 }
1353
1354 if drain_budget.is_zero() {
1357 return 0;
1358 }
1359 let started = Instant::now();
1360 let result = timeout(drain_budget, &mut read).await;
1361 drain_budget = drain_budget.saturating_sub(started.elapsed());
1362 result.ok().and_then(Result::ok).unwrap_or(0)
1363 };
1364 let count = tokio::select! {
1365 biased;
1366 _ = &mut cancelled => 0,
1367 count = read => count,
1368 };
1369 let chunk = if count == 0 {
1370 decoder.finish()
1371 } else {
1372 decoder.push(&buffer[..count])
1373 };
1374 if !chunk.is_empty() {
1375 if let Some(callback) = callback.as_mut() {
1376 callback(&chunk);
1377 }
1378 if let Some(sender) = streamed {
1379 let _ = sender.send(chunk).await;
1380 } else {
1381 retained.push_str(&chunk);
1382 }
1383 }
1384 if count == 0 {
1385 break;
1386 }
1387 }
1388}
1389
1390impl OsExecutionEnv {
1391 async fn exec_inner(
1392 &self,
1393 command: &str,
1394 options: ShellExecOptions<'_>,
1395 streamed: Option<tokio::sync::mpsc::Sender<String>>,
1396 ) -> Result<ShellOutput, ExecutionError> {
1397 check_cancel_exec(options.cancel)?;
1399 let timeout = match resolve_timeout(options.timeout) {
1401 Ok(t) => t,
1402 Err(e) => return Err(e),
1403 };
1404 let cwd = match &options.cwd {
1406 Some(c) => self.resolve_path(&c.to_string_lossy()),
1407 None => self.cwd.clone(),
1408 };
1409 let shell_cfg = match &options.shell {
1412 Some(override_shell) => ShellConfig {
1413 shell: override_shell.program.clone(),
1414 args: override_shell.args.clone(),
1415 transport: CommandTransport::Argv,
1416 },
1417 None => self.get_shell_config().await?,
1418 };
1419 self.exec_configured(command, options, streamed, shell_cfg, timeout, cwd)
1420 .await
1421 }
1422
1423 async fn exec_configured(
1424 &self,
1425 command: &str,
1426 options: ShellExecOptions<'_>,
1427 streamed: Option<tokio::sync::mpsc::Sender<String>>,
1428 shell_cfg: ShellConfig,
1429 timeout: Option<std::time::Duration>,
1430 cwd: PathBuf,
1431 ) -> Result<ShellOutput, ExecutionError> {
1432 if !cwd.exists() {
1434 return Err(ExecutionError::new(
1435 ExecutionErrorCode::SpawnError,
1436 format!(
1437 "Working directory does not exist: {}\nCannot execute bash commands.",
1438 cwd.display()
1439 ),
1440 ));
1441 }
1442
1443 check_cancel_exec(options.cancel)?;
1444 let mut cmd = tokio::process::Command::new(&shell_cfg.shell);
1446 cmd.current_dir(&cwd);
1447 cmd.env_clear();
1448 for (k, v) in NON_INTERACTIVE_SHELL_ENV {
1452 cmd.env(k, v);
1453 }
1454 if options.inherit_env {
1461 let mut inherit = |name: &str, value: &str| {
1462 if !is_host_private_env(name) {
1463 cmd.env(name, value);
1464 }
1465 };
1466 match &self.environment {
1467 Some(environment) => {
1468 for (name, value) in environment {
1469 inherit(name, value);
1470 }
1471 }
1472 None => {
1473 for (name, value) in std::env::vars() {
1474 inherit(&name, &value);
1475 }
1476 }
1477 }
1478 }
1479 if let Some(base) = &self.shell_env {
1480 for (k, v) in base {
1481 cmd.env(k, v);
1482 }
1483 }
1484 if let Some(extra) = &options.env {
1485 for (k, v) in extra {
1486 cmd.env(k, v);
1487 }
1488 }
1489 cmd.kill_on_drop(true);
1491 cmd.stdout(std::process::Stdio::piped());
1492 cmd.stderr(std::process::Stdio::piped());
1493 #[cfg(unix)]
1494 {
1495 cmd.process_group(0); }
1497 #[cfg(windows)]
1498 {
1499 use windows_sys::Win32::System::Threading::{CREATE_NO_WINDOW, CREATE_SUSPENDED};
1500 cmd.creation_flags(CREATE_NO_WINDOW | CREATE_SUSPENDED);
1502 }
1503
1504 cmd.args(&shell_cfg.args);
1505 match shell_cfg.transport {
1506 CommandTransport::Argv => {
1507 cmd.stdin(std::process::Stdio::null());
1510 cmd.arg(command);
1511 }
1512 CommandTransport::Stdin => {
1513 cmd.stdin(std::process::Stdio::piped());
1515 }
1516 }
1517
1518 let mut child = match cmd.spawn() {
1519 Ok(c) => c,
1520 Err(e) => {
1521 return Err(ExecutionError::new(
1522 ExecutionErrorCode::SpawnError,
1523 format!("failed to spawn shell: {e}"),
1524 ));
1525 }
1526 };
1527 let pid = child.id();
1528 let mut process_guard = ShellProcessGuard {
1529 pid,
1530 active: self.active_pids.clone(),
1531 };
1532 #[cfg(windows)]
1533 {
1534 let started = match (pid, child.raw_handle()) {
1535 (Some(pid), Some(process)) => shell_jobs::start(pid, process),
1536 _ => Err("the shell has no process handle".to_owned()),
1537 };
1538 if let Err(error) = started {
1539 if let Some(pid) = pid {
1540 shell_jobs::forget(pid);
1541 }
1542 let _ = child.start_kill();
1543 return Err(ExecutionError::new(
1544 ExecutionErrorCode::SpawnError,
1545 format!("failed to start shell: {error}"),
1546 ));
1547 }
1548 }
1549 if let Some(pid) = pid {
1550 self.active_pids
1551 .lock()
1552 .unwrap_or_else(|e| e.into_inner())
1553 .insert(pid);
1554 }
1555
1556 let stdin = child.stdin.take();
1557 let stop_input = CancellationToken::new();
1558 let deadline = timeout.map(|duration| tokio::time::Instant::now() + duration);
1559 let mut stdout_buf = String::new();
1560 let mut stderr_buf = String::new();
1561 let cancel = options.cancel;
1562 let shell_exited = CancellationToken::new();
1563 let stdout_task = drain_shell_pipe(
1564 child.stdout.take(),
1565 options.on_stdout,
1566 &mut stdout_buf,
1567 streamed.as_ref(),
1568 &shell_exited,
1569 cancel,
1570 );
1571 let stderr_task = drain_shell_pipe(
1572 child.stderr.take(),
1573 options.on_stderr,
1574 &mut stderr_buf,
1575 streamed.as_ref(),
1576 &shell_exited,
1577 cancel,
1578 );
1579
1580 let mut timed_out = false;
1583 let exit_status = {
1584 let status_fut = async {
1585 let expired = async {
1586 match deadline {
1587 Some(at) => tokio::time::sleep_until(at).await,
1588 None => std::future::pending::<()>().await,
1589 }
1590 };
1591 let cancelled = async {
1592 match cancel {
1593 Some(token) => token.cancelled().await,
1594 None => std::future::pending::<()>().await,
1595 }
1596 };
1597 tokio::select! {
1598 status = child.wait() => return status,
1599 () = expired => timed_out = true,
1600 () = cancelled => {}
1601 }
1602 stop_input.cancel();
1603 if let Some(pid) = child.id() {
1604 kill_process_tree(pid).await;
1605 }
1606 child.wait().await
1607 };
1608 tokio::pin!(status_fut, stdout_task, stderr_task);
1609 let (mut stdout_done, mut stderr_done) = (false, false);
1610 let status_res = {
1611 let stdin_task = async {
1612 let Some(mut stdin) = stdin else { return };
1613 use tokio::io::AsyncWriteExt;
1614
1615 tokio::select! {
1619 biased;
1620 () = stop_input.cancelled() => {}
1621 () = async {
1622 if stdin.write_all(command.as_bytes()).await.is_ok() {
1623 let _ = stdin.flush().await;
1624 }
1625 } => {}
1626 }
1627 };
1628 tokio::pin!(stdin_task);
1629 let mut stdin_done = false;
1630 loop {
1631 tokio::select! {
1632 status = &mut status_fut => break status,
1633 () = &mut stdin_task, if !stdin_done => stdin_done = true,
1634 () = &mut stdout_task, if !stdout_done => stdout_done = true,
1635 () = &mut stderr_task, if !stderr_done => stderr_done = true,
1636 }
1637 }
1638 };
1639 if status_res.is_ok() {
1642 process_guard.finish();
1643 }
1644 shell_exited.cancel();
1647 tokio::join!(
1648 async {
1649 if !stdout_done {
1650 (&mut stdout_task).await;
1651 }
1652 },
1653 async {
1654 if !stderr_done {
1655 (&mut stderr_task).await;
1656 }
1657 },
1658 );
1659 status_res
1660 };
1661
1662 if timed_out {
1666 let _ = tokio::time::sleep(std::time::Duration::from_millis(EXIT_STDIO_GRACE_MS)).await;
1667 }
1668
1669 let status = match exit_status {
1671 Ok(s) => s,
1672 Err(e) => {
1673 return Err(ExecutionError::new(
1674 ExecutionErrorCode::SpawnError,
1675 format!("child wait failed: {e}"),
1676 ));
1677 }
1678 };
1679 if timed_out {
1680 return Err(ExecutionError::timeout(
1681 options.timeout.map(|f| f as u64).unwrap_or(0),
1682 ));
1683 }
1684 if cancel.map(|t| t.is_cancelled()).unwrap_or(false) {
1685 return Err(ExecutionError::aborted());
1686 }
1687 let exit_code = status.code().unwrap_or(0);
1688 Ok(ShellOutput {
1689 stdout: stdout_buf,
1690 stderr: stderr_buf,
1691 exit_code,
1692 })
1693 }
1694}
1695
1696#[async_trait]
1697impl Shell for OsExecutionEnv {
1698 async fn exec<'a>(
1699 &'a self,
1700 command: &str,
1701 options: ShellExecOptions<'a>,
1702 ) -> Result<ShellOutput, ExecutionError> {
1703 self.exec_inner(command, options, None).await
1704 }
1705
1706 async fn exec_streamed<'a>(
1707 &'a self,
1708 command: &str,
1709 options: ShellExecOptions<'a>,
1710 output: tokio::sync::mpsc::Sender<String>,
1711 ) -> Result<i32, ExecutionError> {
1712 self.exec_inner(command, options, Some(output))
1713 .await
1714 .map(|result| result.exit_code)
1715 }
1716
1717 async fn cleanup(&self) {
1718 FileSystem::cleanup(self).await
1719 }
1720}
1721
1722#[async_trait]
1723impl ExecutionEnv for OsExecutionEnv {}
1724
1725#[async_trait]
1726impl MutatingEnv for OsExecutionEnv {
1727 fn as_env(&self) -> &dyn ExecutionEnv {
1728 self
1729 }
1730 fn mutation_registry(&self) -> &MutationQueueRegistry {
1731 &self.registry
1732 }
1733}
1734
1735#[cfg(test)]
1736mod stdin_transport_tests {
1737 use super::*;
1738 use std::time::Duration;
1739
1740 fn long_script(first: &str, last: &str) -> String {
1741 format!(
1742 "{first}\n{}{last}\n",
1743 "# benign stdin pipe fixture data\n".repeat(64 * 1024)
1744 )
1745 }
1746
1747 async fn exec_stdin(
1748 env: &OsExecutionEnv,
1749 script: &str,
1750 options: ShellExecOptions<'_>,
1751 ) -> Result<ShellOutput, ExecutionError> {
1752 let config = ShellConfig {
1753 shell: env.get_shell_config().await?.shell,
1754 args: vec!["-s".to_owned()],
1755 transport: CommandTransport::Stdin,
1756 };
1757 let timeout = resolve_timeout(options.timeout)?;
1758 env.exec_configured(script, options, None, config, timeout, env.cwd.clone())
1759 .await
1760 }
1761
1762 #[tokio::test]
1763 async fn stdin_transport_drains_output_while_sending_the_script() {
1764 let temp = tempfile::tempdir().unwrap();
1765 let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1766 let script = long_script(
1767 "head -c 262144 /dev/zero | tr '\\0' a; head -c 262144 /dev/zero | tr '\\0' b >&2",
1768 "printf 'end of script'",
1769 );
1770 let output = tokio::time::timeout(
1771 Duration::from_secs(4),
1772 exec_stdin(
1773 &env,
1774 &script,
1775 ShellExecOptions {
1776 timeout: Some(3.0),
1777 ..Default::default()
1778 },
1779 ),
1780 )
1781 .await
1782 .expect("shell blocked feeding stdin while its output pipes were full");
1783 let output = match output {
1784 Err(error) if error.code == ExecutionErrorCode::ShellUnavailable => return,
1785 output => output.unwrap(),
1786 };
1787 assert_eq!(output.exit_code, 0);
1788 assert_eq!(output.stdout.len(), 262144 + "end of script".len());
1789 assert!(output.stdout.ends_with("end of script"));
1790 assert_eq!(output.stderr.len(), 262144);
1791 assert!(output.stderr.bytes().all(|byte| byte == b'b'));
1792 }
1793
1794 #[tokio::test]
1795 async fn stdin_transport_timeout_covers_blocked_script_upload() {
1796 let temp = tempfile::tempdir().unwrap();
1797 let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1798 let script = long_script("sleep 30", "printf 'unexpected completion'");
1799 let error = tokio::time::timeout(
1800 Duration::from_secs(3),
1801 exec_stdin(
1802 &env,
1803 &script,
1804 ShellExecOptions {
1805 timeout: Some(0.15),
1806 ..Default::default()
1807 },
1808 ),
1809 )
1810 .await
1811 .expect("command timeout did not start while stdin was blocked")
1812 .unwrap_err();
1813 if error.code == ExecutionErrorCode::ShellUnavailable {
1814 return;
1815 }
1816 assert_eq!(error.code, ExecutionErrorCode::Timeout);
1817 }
1818
1819 #[tokio::test]
1820 async fn stdin_transport_cancellation_covers_blocked_script_upload() {
1821 let temp = tempfile::tempdir().unwrap();
1822 let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1823 let script = long_script("sleep 30", "printf 'unexpected completion'");
1824 let signal = CancellationToken::new();
1825 let (result, ()) = tokio::join!(
1826 tokio::time::timeout(
1827 Duration::from_secs(3),
1828 exec_stdin(
1829 &env,
1830 &script,
1831 ShellExecOptions {
1832 cancel: Some(&signal),
1833 ..Default::default()
1834 },
1835 ),
1836 ),
1837 async {
1838 tokio::time::sleep(Duration::from_millis(150)).await;
1839 signal.cancel();
1840 },
1841 );
1842 let error = result
1843 .expect("cancellation was not observed while stdin was blocked")
1844 .unwrap_err();
1845 if error.code == ExecutionErrorCode::ShellUnavailable {
1846 return;
1847 }
1848 assert_eq!(error.code, ExecutionErrorCode::Aborted);
1849 }
1850
1851 #[tokio::test]
1852 async fn stdin_transport_keeps_a_deliberate_early_exit_code() {
1853 let temp = tempfile::tempdir().unwrap();
1854 let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1855 let script = long_script(
1856 "printf 'early exit'; exit 7",
1857 "printf 'unexpected completion'",
1858 );
1859 let result = tokio::time::timeout(
1860 Duration::from_secs(3),
1861 exec_stdin(&env, &script, ShellExecOptions::default()),
1862 )
1863 .await
1864 .expect("shell blocked after closing its stdin");
1865 let output = match result {
1866 Err(error) if error.code == ExecutionErrorCode::ShellUnavailable => return,
1867 output => output.unwrap(),
1868 };
1869 assert_eq!(output.exit_code, 7);
1870 assert_eq!(output.stdout, "early exit");
1871 }
1872}
1873
1874#[cfg(test)]
1875mod durability_tests {
1876 use super::*;
1877
1878 #[test]
1879 fn queued_overwrite_cancelled_before_open_preserves_existing_bytes() {
1880 let runtime = tokio::runtime::Builder::new_current_thread()
1881 .enable_all()
1882 .max_blocking_threads(1)
1883 .build()
1884 .unwrap();
1885 runtime.block_on(async {
1886 let temp = tempfile::tempdir().unwrap();
1887 let path = temp.path().join("note.txt");
1888 std::fs::write(&path, b"original").unwrap();
1889 let (entered_tx, entered_rx) = tokio::sync::oneshot::channel();
1890 let (release_tx, release_rx) = std::sync::mpsc::channel();
1891 let blocker = tokio::task::spawn_blocking(move || {
1892 entered_tx.send(()).unwrap();
1893 release_rx.recv().unwrap();
1894 });
1895 entered_rx.await.unwrap();
1896
1897 let signal = CancellationToken::new();
1898 let write = write_cancellable(
1899 path.clone(),
1900 FileContent::Text("replacement".into()),
1901 Some(&signal),
1902 );
1903 tokio::pin!(write);
1904 let queued = futures::poll!(&mut write).is_pending();
1905 signal.cancel();
1906 release_tx.send(()).unwrap();
1907 blocker.await.unwrap();
1908
1909 assert!(queued, "overwrite should be queued on the blocking pool");
1910 let result = write.await;
1911 let contents = std::fs::read(&path).unwrap();
1912 assert_eq!(
1913 contents, b"original",
1914 "queued cancellation changed the file (write result: {result:?})"
1915 );
1916 assert_eq!(result.unwrap_err().code, FileErrorCode::Aborted);
1917 });
1918 }
1919
1920 #[tokio::test]
1921 async fn os_backend_syncs_staged_file_and_publication_directory() {
1922 let temp = tempfile::tempdir().unwrap();
1923 let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1924 env.write_file("staged", FileContent::Text("durable slice".into()), None)
1925 .await
1926 .unwrap();
1927 env.sync_file("staged", false, None).await.unwrap();
1928 env.sync_directory(".", None).await.unwrap();
1929 }
1930
1931 #[tokio::test]
1932 async fn os_writer_lease_persists_and_verifies_a_monotonic_fence() {
1933 let temp = tempfile::tempdir().unwrap();
1934 let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1935 let first = env
1936 .try_acquire_writer_lease("journal.jsonl")
1937 .await
1938 .unwrap()
1939 .unwrap();
1940 first.verify_fence().unwrap();
1941 drop(first);
1942 let second = env
1943 .try_acquire_writer_lease("journal.jsonl")
1944 .await
1945 .unwrap()
1946 .unwrap();
1947 second.verify_fence().unwrap();
1948 drop(second);
1949 assert_eq!(
1950 std::fs::read_to_string(temp.path().join("journal.jsonl.lock")).unwrap(),
1951 "2"
1952 );
1953 }
1954
1955 #[cfg(unix)]
1956 #[tokio::test]
1957 async fn os_writer_lease_releases_a_shared_open_file_description() {
1958 let temp = tempfile::tempdir().unwrap();
1959 let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1960 let lock = temp.path().join("journal.jsonl.lock");
1961 std::fs::write(&lock, "1").unwrap();
1962 let file = std::fs::OpenOptions::new()
1963 .read(true)
1964 .write(true)
1965 .open(&lock)
1966 .unwrap();
1967 fs2::FileExt::try_lock_exclusive(&file).unwrap();
1968 let inherited = file.try_clone().unwrap();
1969 let lease = OsWriterLease { file, fence: 1 };
1970 assert!(env.try_acquire_writer_lease("journal.jsonl").await.is_err());
1971 drop(lease);
1972 let next = env
1973 .try_acquire_writer_lease("journal.jsonl")
1974 .await
1975 .expect("retired writer retained a lock through the shared description")
1976 .unwrap();
1977 next.verify_fence().unwrap();
1978 assert_eq!(std::fs::read_to_string(lock).unwrap(), "2");
1979 drop(inherited);
1980 }
1981}
1982
1983fn resolve_timeout(timeout: Option<f64>) -> Result<Option<std::time::Duration>, ExecutionError> {
1985 match timeout {
1986 None => Ok(None),
1987 Some(secs) => {
1988 if !secs.is_finite() || secs <= 0.0 {
1989 return Err(ExecutionError::new(
1990 ExecutionErrorCode::Timeout,
1991 "Invalid timeout: must be a finite number of seconds",
1992 ));
1993 }
1994 let ms = secs * 1000.0;
1995 if ms > MAX_TIMEOUT_MS as f64 {
1996 return Err(ExecutionError::new(
1997 ExecutionErrorCode::Timeout,
1998 format!(
1999 "Invalid timeout: maximum is {} seconds",
2000 MAX_TIMEOUT_SECONDS
2001 ),
2002 ));
2003 }
2004 Ok(Some(std::time::Duration::from_secs_f64(secs)))
2005 }
2006 }
2007}