1use std::collections::HashMap;
2use std::process::ExitStatus;
3use std::sync::Arc;
4use std::sync::Mutex;
5use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
6
7use anyhow::{Result, bail};
8use oxdock_fs::GuardedPath;
9use oxdock_parser::{Arg, AssertTarget, Command, Step, StepKind, Value, guard_option_allows};
10use oxdock_process::{BackgroundHandle, CommandStdin, ProcessManager, SharedInput, SharedOutput};
11
12fn exit_status_from_code(code: i32) -> ExitStatus {
14 #[cfg(unix)]
15 {
16 use std::os::unix::process::ExitStatusExt;
17 ExitStatus::from_raw(code << 8)
18 }
19 #[cfg(windows)]
20 {
21 use std::os::windows::process::ExitStatusExt;
22 ExitStatus::from_raw(code as u32)
23 }
24}
25
26use super::handlers;
27use super::io::{ExactCapture, SlidingWindow, StreamHandle};
28use super::native::PureTable;
29use super::state::{ExecState, TaskEntry, TaskPhase};
30use oxdock_pipe::PipeInner;
31
32pub(super) struct ThreadJoinHandle {
35 join: Option<std::thread::JoinHandle<Result<()>>>,
36 cancel_token: Arc<AtomicBool>,
37 cancel_hub: Arc<oxdock_process::CancelHub>,
38 active_process: Arc<Mutex<Option<Box<dyn BackgroundHandle>>>>,
39 worker: Arc<Mutex<Option<std::thread::ThreadId>>>,
47 thread_error: Option<anyhow::Error>,
49 thread_exit_code: Option<i64>,
53}
54
55impl ThreadJoinHandle {
56 pub(super) fn new(
57 join: std::thread::JoinHandle<Result<()>>,
58 cancel_token: Arc<AtomicBool>,
59 cancel_hub: Arc<oxdock_process::CancelHub>,
60 active_process: Arc<Mutex<Option<Box<dyn BackgroundHandle>>>>,
61 worker: Arc<Mutex<Option<std::thread::ThreadId>>>,
62 ) -> Self {
63 Self {
64 join: Some(join),
65 cancel_token,
66 cancel_hub,
67 active_process,
68 worker,
69 thread_error: None,
70 thread_exit_code: None,
71 }
72 }
73
74 fn reemit_error(&self) -> anyhow::Error {
80 let msg = self
81 .thread_error
82 .as_ref()
83 .map(|err| format!("{err:#}"))
84 .unwrap_or_else(|| "background thread failed without an error".to_string());
85 match self.thread_exit_code {
86 Some(code) => anyhow::Error::new(super::exit::ExitRequest(code)).context(msg),
87 None => anyhow::anyhow!("{msg}"),
88 }
89 }
90
91 fn is_self(&self) -> bool {
93 let guard = self.worker.lock().unwrap_or_else(|e| e.into_inner());
94 guard.is_some_and(|id| id == std::thread::current().id())
95 }
96
97 fn reap(&mut self) {
99 if self.join.is_none() {
100 return;
101 }
102 if self.is_self() {
103 let _ = self.join.take();
107 return;
108 }
109 let handle = self.join.take().unwrap();
110 match handle.join() {
111 Ok(Ok(())) => {}
112 Ok(Err(e)) => {
113 self.thread_exit_code = super::exit::exit_code_of(&e);
114 self.thread_error = Some(e);
115 }
116 Err(panic) => {
117 let msg = if let Some(s) = panic.downcast_ref::<&str>() {
118 s.to_string()
119 } else if let Some(s) = panic.downcast_ref::<String>() {
120 s.clone()
121 } else {
122 "thread panicked".to_string()
123 };
124 self.thread_error = Some(anyhow::anyhow!("{msg}"));
125 }
126 }
127 }
128}
129
130impl BackgroundHandle for ThreadJoinHandle {
131 fn try_wait(&mut self) -> Result<Option<ExitStatus>> {
132 if let Some(join) = &self.join {
133 if join.is_finished() {
134 self.reap();
135 } else {
136 return Ok(None);
137 }
138 }
139 if self.thread_error.is_some() {
145 Err(self.reemit_error())
146 } else {
147 Ok(Some(exit_status_from_code(0)))
148 }
149 }
150
151 fn kill(&mut self) -> Result<()> {
152 self.cancel_token.store(true, Ordering::SeqCst);
154 self.cancel_hub.mark_cancelled();
157 if let Ok(mut guard) = self.active_process.lock()
159 && let Some(ref mut proc) = *guard
160 {
161 let _ = proc.kill();
162 }
163 self.reap();
165 Ok(())
166 }
167
168 fn wait(&mut self) -> Result<ExitStatus> {
169 self.reap();
170 if self.thread_error.is_some() {
172 Err(self.reemit_error())
173 } else {
174 Ok(exit_status_from_code(0))
175 }
176 }
177}
178
179impl Drop for ThreadJoinHandle {
180 fn drop(&mut self) {
181 let _ = self.kill();
182 }
183}
184
185static ASSERT_GENERATION: AtomicUsize = AtomicUsize::new(0);
189
190#[derive(Debug)]
197pub(super) enum Flow {
198 Done,
199 Break { idx: usize },
200 Continue { idx: usize },
201 Return { idx: usize, value: Value },
202}
203
204pub(super) fn allocate_assert_generation() -> usize {
205 ASSERT_GENERATION.fetch_add(1, Ordering::Relaxed)
206}
207
208#[derive(Clone, Copy, PartialEq, Eq)]
210pub(super) enum AssertStream {
211 Stdout,
212 Stderr,
213}
214
215fn extract_stream_needle(kind: &StepKind) -> Option<(AssertStream, &Arg)> {
219 let step = match kind {
220 StepKind::WithIo { cmd, .. } => cmd.as_ref(),
221 other => other,
222 };
223 match step {
224 StepKind::AssertContains { haystack, needle } => match haystack {
225 AssertTarget::Stdout => Some((AssertStream::Stdout, needle)),
226 AssertTarget::Stderr => Some((AssertStream::Stderr, needle)),
227 _ => None,
228 },
229 _ => None,
230 }
231}
232
233fn needs_exact_stdout(kind: &StepKind) -> bool {
236 let step = match kind {
237 StepKind::WithIo { cmd, .. } => cmd.as_ref(),
238 other => other,
239 };
240 matches!(
241 step,
242 StepKind::AssertEq {
243 actual: AssertTarget::Stdout,
244 ..
245 } | StepKind::AssertNe {
246 actual: AssertTarget::Stdout,
247 ..
248 }
249 )
250}
251
252pub(super) enum ResolvedAssertTarget {
255 Value(Value),
256 Stdout,
257 Stderr,
258 Pipe(Vec<u8>),
259}
260
261pub(super) fn resolve_assert_target<P: ProcessManager>(
267 target: &AssertTarget,
268 cx: &mut StepCtx<'_, P>,
269) -> Result<ResolvedAssertTarget> {
270 match target {
271 AssertTarget::Value(arg) => {
272 let value = super::args::evaluate_assert_operand(arg, cx)?;
273 if let Some(handle) = value.as_pipe_handle() {
274 let bytes =
275 cx.state.io.peek_pipe_content(&handle).map_err(|e| {
276 anyhow::anyhow!("step pipe assertion cannot read pipe: {e}")
277 })?;
278 return Ok(ResolvedAssertTarget::Pipe(bytes));
279 }
280 Ok(ResolvedAssertTarget::Value(value))
281 }
282 AssertTarget::Stdout => Ok(ResolvedAssertTarget::Stdout),
283 AssertTarget::Stderr => Ok(ResolvedAssertTarget::Stderr),
284 }
285}
286
287pub(super) fn pre_register_assertions<P: ProcessManager>(
294 state: &mut ExecState<P>,
295 steps: &[Step],
296 generation: usize,
297) -> Result<()> {
298 let mut windows = match state.assert_windows.lock() {
299 Ok(guard) => guard,
300 Err(_) => bail!("assert_windows poisoned"),
301 };
302 let mut stderr_windows = match state.assert_windows_stderr.lock() {
303 Ok(guard) => guard,
304 Err(_) => bail!("assert_windows_stderr poisoned"),
305 };
306 let mut exact = match state.exact_stdout.lock() {
307 Ok(guard) => guard,
308 Err(_) => bail!("exact_stdout poisoned"),
309 };
310 for (idx, step) in steps.iter().enumerate() {
311 if let Some((stream, arg)) = extract_stream_needle(&step.kind) {
312 let resolved = super::args::resolve_arg_state(arg, state)?;
313 let map = match stream {
314 AssertStream::Stdout => &mut windows,
315 AssertStream::Stderr => &mut stderr_windows,
316 };
317 map.insert((generation, idx), SlidingWindow::new(resolved.into_bytes()));
318 }
319 if needs_exact_stdout(&step.kind) {
320 exact.entry(generation).or_insert_with(ExactCapture::new);
321 }
322 }
323 Ok(())
324}
325
326#[allow(clippy::collapsible_if)]
332pub(super) fn sync_iteration_assert_needles<P: ProcessManager>(
333 state: &ExecState<P>,
334 steps: &[Step],
335 generation: usize,
336) -> Result<()> {
337 let mut windows = match state.assert_windows.lock() {
338 Ok(guard) => guard,
339 Err(_) => bail!("assert_windows poisoned"),
340 };
341 let mut stderr_windows = match state.assert_windows_stderr.lock() {
342 Ok(guard) => guard,
343 Err(_) => bail!("assert_windows_stderr poisoned"),
344 };
345 for (idx, step) in steps.iter().enumerate() {
346 if let Some((stream, arg)) = extract_stream_needle(&step.kind) {
347 let map = match stream {
348 AssertStream::Stdout => &mut windows,
349 AssertStream::Stderr => &mut stderr_windows,
350 };
351 if let Some(w) = map.get_mut(&(generation, idx)) {
352 let resolved = super::args::resolve_arg_state(arg, state)?;
353 w.update_needle(resolved.into_bytes());
354 }
355 }
356 }
357 Ok(())
358}
359
360#[derive(Debug, Clone, Copy, PartialEq, Eq)]
368pub struct TtyRequest {
369 pub rows: Option<u16>,
371 pub cols: Option<u16>,
373}
374
375pub struct StepCtx<'a, P: ProcessManager> {
388 pub(super) state: &'a mut ExecState<P>,
389 pub(super) process: &'a mut P,
390 pub(super) stdin: CommandStdin,
391 pub(super) expose_stdin: bool,
392 pub(super) out: Option<StreamHandle>,
393 pub(super) err: Option<StreamHandle>,
394 pub(super) out_pipe: Option<Arc<PipeInner>>,
400 pub(super) stdin_pipe: Option<Arc<PipeInner>>,
405 pub(super) tty: Option<TtyRequest>,
410}
411
412impl<'a, P: ProcessManager> StepCtx<'a, P> {
413 pub(super) fn for_mcp(
417 state: &'a mut ExecState<P>,
418 process: &'a mut P,
419 stdin: CommandStdin,
420 out: Option<StreamHandle>,
421 err: Option<StreamHandle>,
422 ) -> Self {
423 Self {
424 state,
425 process,
426 stdin,
427 expose_stdin: false,
428 out,
429 err,
430 out_pipe: None,
431 stdin_pipe: None,
432 tty: None,
433 }
434 }
435
436 pub(super) fn err_shared(&self) -> Option<SharedOutput> {
440 match self.err.clone() {
441 Some(StreamHandle::Stream(writer)) => Some(writer),
442 _ => None,
443 }
444 }
445
446 pub fn get_var(&self, key: &str) -> Option<Value> {
448 self.state.get_var(key)
449 }
450
451 pub fn get_env(&self, key: &str) -> Option<String> {
455 self.state.get_env(key).map(str::to_string)
456 }
457
458 pub fn env_snapshot(&self) -> HashMap<String, String> {
465 self.state.envs.as_ref().clone()
466 }
467
468 pub fn ensure_scratch_materialized(&self) -> Result<()> {
473 self.state.cargo_scratch.ensure_materialized()
474 }
475
476 pub fn cwd(&self) -> &GuardedPath {
478 &self.state.cwd
479 }
480
481 pub fn workspace_root(&self) -> &GuardedPath {
486 self.state.fs.root()
487 }
488
489 pub fn pure_functions(&self) -> std::sync::Arc<PureTable> {
497 self.state.pure_function_table()
498 }
499
500 pub fn new_pipe(&self) -> Value {
505 Value::pipe_fresh_in_task(self.state.task_id)
506 }
507
508 pub fn pipe_reader(&self, value: &Value) -> Result<SharedInput> {
517 use oxdock_pipe::{Materialized, materialize};
518 let Some(handle) = value.as_pipe_handle() else {
519 anyhow::bail!(
520 "host pipe_reader needs a PIPE value, got {}",
521 value.type_name()
522 );
523 };
524 match materialize(&handle, false)? {
525 Materialized::Script(backend) => Ok(backend.reader_handle()),
526 #[cfg(not(miri))]
527 Materialized::Os(entry) => {
528 let owned = entry.reader.take().map_err(|_| {
529 anyhow::anyhow!(
530 "OS pipe handle has already been consumed by another binding; declare a fresh LET $x: PIPE for a new session"
531 )
532 })?;
533 Ok(Arc::new(Mutex::new(owned)))
534 }
535 }
536 }
537
538 pub fn pipe_writer(&self, value: &Value) -> Result<SharedOutput> {
542 use oxdock_pipe::{Materialized, materialize};
543 let Some(handle) = value.as_pipe_handle() else {
544 anyhow::bail!(
545 "host pipe_writer needs a PIPE value, got {}",
546 value.type_name()
547 );
548 };
549 match materialize(&handle, false)? {
550 Materialized::Script(backend) => Ok(backend.writer_handle()),
551 #[cfg(not(miri))]
552 Materialized::Os(entry) => {
553 let owned = entry.writer.take().map_err(|_| {
554 anyhow::anyhow!(
555 "OS pipe handle has already been consumed by another binding; declare a fresh LET $x: PIPE for a new session"
556 )
557 })?;
558 Ok(Arc::new(Mutex::new(owned)))
559 }
560 }
561 }
562
563 pub fn close_pipe(&self, value: &Value) -> Result<()> {
569 let Some(handle) = value.as_pipe_handle() else {
570 anyhow::bail!(
571 "host close_pipe needs a PIPE value, got {}",
572 value.type_name()
573 );
574 };
575 let Some(backend) = oxdock_pipe::script_backend(&handle) else {
576 anyhow::bail!(
577 "host close_pipe needs a script-materialized pipe (unbound and OS handles cannot be force-closed)"
578 );
579 };
580 backend.force_close();
581 Ok(())
582 }
583
584 pub fn is_cancelled(&self) -> bool {
588 self.state
589 .cancel_token
590 .load(std::sync::atomic::Ordering::SeqCst)
591 }
592
593 pub fn cancel_token(&self) -> Arc<AtomicBool> {
598 Arc::clone(&self.state.cancel_token)
599 }
600
601 pub fn cancel_hub(&self) -> Arc<oxdock_process::CancelHub> {
605 Arc::clone(&self.state.cancel_hub)
606 }
607
608 pub fn is_async_task(&self) -> bool {
611 self.state.inside_async
612 }
613
614 pub fn module_state<T: Send + Sync + 'static>(
620 &self,
621 module: &str,
622 ) -> Option<std::sync::Arc<T>> {
623 self.state
624 .module_states
625 .get(&(module.to_string(), std::any::TypeId::of::<T>()))?
626 .clone()
627 .downcast::<T>()
628 .ok()
629 }
630
631 pub fn pipe_backend(&self, value: &Value) -> Option<Arc<PipeInner>> {
638 let handle = value.as_pipe_handle()?;
639 oxdock_pipe::script_backend(&handle)
640 }
641}
642
643#[allow(clippy::too_many_arguments)]
644pub(super) fn execute_steps<P: ProcessManager>(
645 state: &mut ExecState<P>,
646 process: &mut P,
647 steps: &[Step],
648 stdin: CommandStdin,
649 expose_stdin: bool,
650 out: Option<StreamHandle>,
651 err: Option<StreamHandle>,
652 out_pipe: Option<Arc<PipeInner>>,
653 stdin_pipe: Option<Arc<PipeInner>>,
654 wait_at_end: bool,
655) -> Result<Flow> {
656 let generation = allocate_assert_generation();
657 let flow = match execute_steps_inner(InnerArgs {
658 state,
659 process,
660 generation,
661 steps,
662 stdin,
663 expose_stdin,
664 out,
665 err,
666 out_pipe,
667 stdin_pipe,
668 wait_at_end,
669 }) {
670 Ok(flow) => flow,
671 Err(e) => {
672 teardown_tasks_on_error(state);
678 cleanup_assertion_generation(state, generation)?;
679 return Err(e);
680 }
681 };
682 cleanup_assertion_generation(state, generation)?;
684 Ok(flow)
685}
686
687fn cleanup_assertion_generation<P: ProcessManager>(
690 state: &mut ExecState<P>,
691 generation: usize,
692) -> Result<()> {
693 let mut windows = match state.assert_windows.lock() {
694 Ok(guard) => guard,
695 Err(_) => bail!("assert_windows poisoned"),
696 };
697 windows.retain(|(g, _), _| *g != generation);
698 let mut stderr_windows = match state.assert_windows_stderr.lock() {
699 Ok(guard) => guard,
700 Err(_) => bail!("assert_windows_stderr poisoned"),
701 };
702 stderr_windows.retain(|(g, _), _| *g != generation);
703 let mut exact = match state.exact_stdout.lock() {
704 Ok(guard) => guard,
705 Err(_) => bail!("exact_stdout poisoned"),
706 };
707 exact.retain(|g, _| *g != generation);
708 Ok(())
709}
710
711fn teardown_tasks_on_error<P: ProcessManager>(state: &mut ExecState<P>) {
716 for survivor in state.bg_children.iter_mut() {
717 let _ = survivor.handle.kill();
718 }
719 state.bg_children.clear();
720 if state.inside_async {
721 return;
722 }
723 let entries: Vec<Arc<TaskEntry>> = {
724 let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
725 named.values().cloned().collect()
726 };
727 let mut to_kill: Vec<(Arc<TaskEntry>, Box<dyn BackgroundHandle>)> = Vec::new();
728 for entry in &entries {
729 let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
730 match guard.phase {
731 TaskPhase::Running | TaskPhase::Awaiting => {
732 guard.phase = TaskPhase::Cancelled;
733 if let Some(handle) = guard.handle.take() {
734 to_kill.push((Arc::clone(entry), handle));
735 }
736 }
737 TaskPhase::Cancelled | TaskPhase::Completed => {}
738 }
739 }
740 for (entry, mut handle) in to_kill {
741 let _ = handle.kill();
742 entry.finish_teardown();
743 }
744}
745
746#[allow(clippy::too_many_arguments)]
749pub(super) fn execute_single_step_with_generation<P: ProcessManager>(
750 state: &mut ExecState<P>,
751 process: &mut P,
752 cmd: &StepKind,
753 generation: usize,
754 idx: usize,
755 stdin: CommandStdin,
756 expose_stdin: bool,
757 out: Option<StreamHandle>,
758 err: Option<StreamHandle>,
759 out_pipe: Option<Arc<PipeInner>>,
760 stdin_pipe: Option<Arc<PipeInner>>,
761 tty: Option<TtyRequest>,
762) -> Result<Flow> {
763 let mut cx = StepCtx {
764 state,
765 process,
766 stdin,
767 expose_stdin,
768 out,
769 err,
770 out_pipe,
771 stdin_pipe,
772 tty,
773 };
774 match cmd {
779 StepKind::FuncDef { .. }
780 | StepKind::Call { .. }
781 | StepKind::Return { .. }
782 | StepKind::ImportFile { .. }
783 | StepKind::ImportFuncs { .. }
784 | StepKind::While { .. }
785 | StepKind::Break
786 | StepKind::Continue
787 | StepKind::For { .. }
788 | StepKind::If { .. }
789 | StepKind::Switch { .. }
790 | StepKind::Timeout { .. }
791 | StepKind::Fail { .. }
792 | StepKind::Isolated { .. }
793 | StepKind::WithIo { .. }
794 | StepKind::Bind {
795 rhs: oxdock_parser::BindRhs::Capture(_),
796 ..
797 } => {
798 return dispatch_flow_step(cmd, &mut cx, generation, idx);
799 }
800 _ => {}
801 }
802 match cmd {
803 StepKind::Run(arg) => {
804 let cmd = super::args::resolve_arg(arg, &mut cx)?;
805 let cmd = super::args::expand_dsl_vars(&cmd, cx.state)?;
806 handlers::run(&mut cx, &cmd)
807 }
808 StepKind::RunExec { argv } => {
809 let resolved = handlers::resolve_run_exec_argv(argv, &mut cx)?;
810 handlers::run_argv(&mut cx, &resolved)
811 }
812 StepKind::Echo(arg) => {
813 let msg = super::args::resolve_arg(arg, &mut cx)?;
814 handlers::echo(&mut cx, &msg)
815 }
816 StepKind::AsyncBlock { .. } => handlers::dispatch_async_block(cmd, &mut cx),
817 StepKind::Workdir(arg) => {
818 let path = super::args::resolve_arg(arg, &mut cx)?;
819 handlers::workdir(&mut cx, &path)
820 }
821 StepKind::Workspace(target) => handlers::workspace(&mut cx, target),
822 StepKind::RemoteBlock {
823 target,
824 vars,
825 env,
826 body,
827 } => super::remote::run_remote_block(&mut cx, target, vars, env, body),
828 StepKind::Env { key, value } => {
829 let resolved = super::args::resolve_arg(value, &mut cx)?;
830 handlers::env(&mut cx, key, &resolved)
831 }
832 StepKind::InheritEnv { keys } => {
833 handlers::inherit_env(&mut cx, keys)?;
834 sync_iteration_assert_needles(
835 cx.state,
836 &[Step {
837 guard: None,
838 kind: cmd.clone(),
839 scope_enter: 0,
840 scope_exit: 0,
841 line: 0,
842 col: 0,
843 }],
844 generation,
845 )?;
846 Ok(())
847 }
848 StepKind::IsolatedInheritEnv { keys } => {
849 handlers::isolated_inherit_env(&mut cx, keys)?;
850 Ok(())
851 }
852 StepKind::Copy {
853 from_workspace,
854 from_host,
855 to_host,
856 from,
857 to,
858 } => {
859 if *from_host || *to_host {
860 super::remote::copy_transfer(&mut cx, *from_host, *to_host, from, to)
861 } else {
862 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
863 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
864 handlers::copy(
865 &mut cx,
866 from_workspace.clone(),
867 &from_resolved,
868 &to_resolved,
869 )
870 }
871 }
872 StepKind::CopyGit {
873 rev,
874 from,
875 to,
876 include_dirty,
877 } => {
878 let rev_resolved = super::args::resolve_arg(rev, &mut cx)?;
879 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
880 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
881 handlers::copy_git(
882 &mut cx,
883 &rev_resolved,
884 &from_resolved,
885 &to_resolved,
886 *include_dirty,
887 )
888 }
889 StepKind::Archive { src, dst, raw } => {
890 let src_resolved = super::args::resolve_arg(src, &mut cx)?;
891 let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
892 handlers::archive(&mut cx, &src_resolved, &dst_resolved, *raw)
893 }
894 StepKind::Unarchive {
895 src,
896 dst,
897 max_bytes,
898 } => {
899 let src_resolved = super::args::resolve_arg(src, &mut cx)?;
900 let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
901 let cap_resolved = super::args::resolve_arg_opt(max_bytes, &mut cx)?;
902 handlers::unarchive(
903 &mut cx,
904 &src_resolved,
905 &dst_resolved,
906 cap_resolved.as_deref(),
907 )
908 }
909 StepKind::Symlink {
910 from_workspace,
911 from,
912 to,
913 } => {
914 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
915 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
916 handlers::symlink(
917 &mut cx,
918 from_workspace.clone(),
919 &from_resolved,
920 &to_resolved,
921 )
922 }
923 StepKind::Mkdir(arg) => {
924 let path = super::args::resolve_arg(arg, &mut cx)?;
925 handlers::mkdir(&mut cx, &path)
926 }
927 StepKind::Install { from, to } => {
928 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
929 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
930 handlers::install(&mut cx, &from_resolved, &to_resolved)
931 }
932 StepKind::SetExecutable { path } => {
933 let resolved = super::args::resolve_arg(path, &mut cx)?;
934 handlers::set_executable(&mut cx, &resolved)
935 }
936 StepKind::Ls(arg) => {
937 let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
938 handlers::ls(&mut cx, &resolved)
939 }
940 StepKind::Read(arg) => {
941 let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
942 handlers::read(&mut cx, &resolved)
943 }
944 StepKind::ReadLine { var } => handlers::read_line(&mut cx, var),
945 StepKind::Prompt {
946 var,
947 message,
948 default,
949 } => {
950 let message_resolved = super::args::resolve_arg(message, &mut cx)?;
951 let default_resolved = match default {
952 Some(d) => Some(super::args::resolve_arg(d, &mut cx)?),
953 None => None,
954 };
955 handlers::prompt(&mut cx, var, &message_resolved, default_resolved.as_deref())
956 }
957 StepKind::ListAppend { list, item } => {
958 let value = super::args::evaluate_assert_operand(item, &mut cx)?;
959 handlers::push_into(&mut cx, list, value)
960 }
961 StepKind::Write { path, contents } => {
962 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
963 let contents_resolved = super::args::resolve_arg_opt(contents, &mut cx)?;
964 handlers::write(&mut cx, &path_resolved, contents_resolved.as_deref())
965 }
966 StepKind::Append { path, contents } => {
967 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
968 let contents_resolved = super::args::resolve_arg_opt(contents, &mut cx)?;
969 handlers::append(&mut cx, &path_resolved, contents_resolved.as_deref())
970 }
971 StepKind::AppendLine { path, contents } => {
972 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
973 let contents_resolved = super::args::resolve_arg(contents, &mut cx)?;
974 handlers::append_line(&mut cx, &path_resolved, &contents_resolved)
975 }
976 StepKind::Remove { path, recursive } => {
977 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
978 handlers::remove(&mut cx, &path_resolved, *recursive)
979 }
980 StepKind::Expand { path, overrides } => {
981 let path_resolved = super::args::resolve_arg_opt(path, &mut cx)?;
982 let overrides_resolved = super::args::resolve_overrides(overrides, &mut cx)?;
983 handlers::replace(&mut cx, &path_resolved, &overrides_resolved)
984 }
985 StepKind::AssertEq {
986 hash,
987 actual,
988 expected,
989 }
990 | StepKind::AssertNe {
991 hash,
992 actual,
993 expected,
994 } => {
995 let (verb, expect_equal) = match cmd {
996 StepKind::AssertEq { .. } => (Command::AssertEq.as_str(), true),
997 _ => (Command::AssertNe.as_str(), false),
998 };
999 let target = resolve_assert_target(actual, &mut cx)?;
1000 let expected_resolved = match expected {
1001 Some(e) => Some(super::args::evaluate_assert_operand(e, &mut cx)?),
1002 None => None,
1003 };
1004 handlers::assert_equality(
1005 &mut cx,
1006 generation,
1007 verb,
1008 expect_equal,
1009 hash,
1010 &target,
1011 expected_resolved.as_ref(),
1012 )
1013 }
1014 StepKind::AssertContains { haystack, needle } => {
1015 let target = resolve_assert_target(haystack, &mut cx)?;
1016 handlers::assert_contains(&mut cx, generation, idx, &target, needle)
1017 }
1018 StepKind::WithIoBlock { .. } => {
1019 bail!("WITH_IO block should have been expanded during parsing")
1020 }
1021 StepKind::Exit(code) => {
1022 let code = super::args::resolve_arg_as_int(code, &mut cx)?;
1023 handlers::exit(&mut cx, code)
1024 }
1025 StepKind::Bind {
1026 var,
1027 decl_type,
1028 is_const,
1029 rhs: oxdock_parser::BindRhs::Expr(expr),
1030 } => handlers::assign(&mut cx, var, decl_type.clone(), expr, *is_const),
1031 StepKind::Bind {
1032 var,
1033 decl_type,
1034 is_const,
1035 rhs: oxdock_parser::BindRhs::Async(body),
1036 } => handlers::dispatch_assign_async(var, decl_type.clone(), body, &mut cx, *is_const),
1037 StepKind::Bind {
1038 var,
1039 decl_type,
1040 is_const,
1041 rhs: oxdock_parser::BindRhs::Await { task_var, .. },
1042 } => handlers::dispatch_await_capture(var, decl_type.clone(), task_var, &mut cx, *is_const),
1043 StepKind::Set { var, expr } => handlers::set_var_value(&mut cx, var, expr),
1044 StepKind::Await { var, .. } => handlers::dispatch_await(var, &mut cx),
1045 StepKind::Cancel { var, .. } => handlers::dispatch_cancel(var, &mut cx),
1046 StepKind::Sleep { duration } => {
1047 let duration = super::args::resolve_arg_as_duration(duration, &mut cx)?;
1048 handlers::sleep(&mut cx, &duration)
1049 }
1050 StepKind::TypeAlias { .. } => {
1051 Ok(())
1054 }
1055 StepKind::FuncDef { .. }
1056 | StepKind::Call { .. }
1057 | StepKind::Return { .. }
1058 | StepKind::ImportFile { .. }
1059 | StepKind::ImportFuncs { .. }
1060 | StepKind::While { .. }
1061 | StepKind::Break
1062 | StepKind::Continue
1063 | StepKind::For { .. }
1064 | StepKind::If { .. }
1065 | StepKind::Switch { .. }
1066 | StepKind::Timeout { .. }
1067 | StepKind::Fail { .. }
1068 | StepKind::Isolated { .. }
1069 | StepKind::WithIo { .. }
1070 | StepKind::Bind {
1071 rhs: oxdock_parser::BindRhs::Capture(_),
1072 ..
1073 } => {
1074 unreachable!("compound steps dispatch before this match")
1075 }
1076 }?;
1077 Ok(Flow::Done)
1078}
1079
1080#[allow(clippy::too_many_arguments)]
1081fn step_error(step: &Step, idx: usize, err: anyhow::Error) -> anyhow::Error {
1087 let mut loc = format!("step {}", idx + 1);
1088 if step.line > 0 {
1089 loc.push_str(&format!(", line {}", step.line));
1090 if step.col > 0 {
1091 loc.push_str(&format!(", col {}", step.col));
1092 }
1093 }
1094 err.context(loc)
1095}
1096
1097struct InnerArgs<'a, P: ProcessManager> {
1101 state: &'a mut ExecState<P>,
1102 process: &'a mut P,
1103 generation: usize,
1104 steps: &'a [Step],
1105 stdin: CommandStdin,
1106 expose_stdin: bool,
1107 out: Option<StreamHandle>,
1108 err: Option<StreamHandle>,
1109 out_pipe: Option<Arc<PipeInner>>,
1110 stdin_pipe: Option<Arc<PipeInner>>,
1111 wait_at_end: bool,
1112}
1113
1114fn execute_steps_inner<P: ProcessManager>(args: InnerArgs<'_, P>) -> Result<Flow> {
1115 let InnerArgs {
1116 state,
1117 process,
1118 generation,
1119 steps,
1120 stdin,
1121 expose_stdin,
1122 out,
1123 err,
1124 out_pipe,
1125 stdin_pipe,
1126 wait_at_end,
1127 } = args;
1128 pre_register_assertions(state, steps, generation)?;
1130
1131 for (idx, step) in steps.iter().enumerate() {
1132 if state.cancel_token.load(Ordering::SeqCst) {
1134 bail!("ASYNC task cancelled");
1135 }
1136 if step.scope_enter > 0 {
1137 for _ in 0..step.scope_enter {
1138 state.push_scope();
1139 }
1140 }
1141
1142 let should_run = guard_option_allows(step.guard.as_ref(), &state.envs);
1143 let flow_result: Result<Flow> = (|| {
1147 if !should_run {
1148 Ok(Flow::Done)
1149 } else {
1150 let flow_result: Result<Flow> = match &step.kind {
1155 StepKind::FuncDef { .. }
1156 | StepKind::Call { .. }
1157 | StepKind::Return { .. }
1158 | StepKind::ImportFile { .. }
1159 | StepKind::ImportFuncs { .. }
1160 | StepKind::While { .. }
1161 | StepKind::Break
1162 | StepKind::Continue
1163 | StepKind::For { .. }
1164 | StepKind::If { .. }
1165 | StepKind::Switch { .. }
1166 | StepKind::Timeout { .. }
1167 | StepKind::Fail { .. }
1168 | StepKind::Isolated { .. }
1169 | StepKind::WithIo { .. }
1170 | StepKind::Bind {
1171 rhs: oxdock_parser::BindRhs::Capture(_),
1172 ..
1173 } => {
1174 let mut cx = StepCtx {
1175 state,
1176 process,
1177 stdin: stdin.clone(),
1178 expose_stdin,
1179 out: out.clone(),
1180 err: err.clone(),
1181 out_pipe: out_pipe.clone(),
1182 stdin_pipe: stdin_pipe.clone(),
1183 tty: None,
1184 };
1185 dispatch_flow_step(&step.kind, &mut cx, generation, idx)
1186 }
1187 _ => {
1188 let flow = execute_single_step_with_generation(
1189 state,
1190 process,
1191 &step.kind,
1192 generation,
1193 idx,
1194 stdin.clone(),
1195 expose_stdin,
1196 out.clone(),
1197 err.clone(),
1198 out_pipe.clone(),
1199 stdin_pipe.clone(),
1200 None,
1201 )?;
1202 if matches!(
1203 &step.kind,
1204 StepKind::Env { .. }
1205 | StepKind::InheritEnv { .. }
1206 | StepKind::IsolatedInheritEnv { .. }
1207 ) {
1208 sync_iteration_assert_needles(state, steps, generation)?;
1209 }
1210 Ok(flow)
1211 }
1212 };
1213 flow_result
1214 }
1215 })()
1216 .map_err(|err| step_error(step, idx, err));
1217
1218 let restore_result = restore_scopes(state, step.scope_exit);
1219 let expiry_drained = if let Some(expiry) = state.keeper_expiry.as_mut() {
1224 expiry.expire_step(steps, idx)
1225 } else {
1226 false
1227 };
1228 if expiry_drained {
1229 state.keeper_expiry = None;
1230 }
1231 let flow = flow_result?;
1232 restore_result?;
1233 match flow {
1234 Flow::Done => {}
1235 Flow::Break { .. } | Flow::Continue { .. } | Flow::Return { .. } => {
1236 return Ok(flow);
1237 }
1238 }
1239 }
1240
1241 let reap_named = !state.inside_async;
1249 let floor = state.reap_floor;
1254 let in_scope = |id: u64| floor.map(|f| id >= f).unwrap_or(true);
1255 let has_bg = state.bg_children.iter().any(|c| in_scope(c.task_id));
1256 let named_pending = |state: &ExecState<P>| {
1257 reap_named
1258 && state
1259 .named_tasks
1260 .lock()
1261 .unwrap_or_else(|e| e.into_inner())
1262 .iter()
1263 .any(|(id, entry)| {
1264 in_scope(*id) && !entry.state.lock().unwrap_or_else(|e| e.into_inner()).reaped
1265 })
1266 };
1267 let has_named = named_pending(state);
1268 if wait_at_end && (has_bg || has_named) {
1269 loop {
1270 let mut failed_status: Option<anyhow::Error> = None;
1271
1272 if failed_status.is_none() && state.cancel_token.load(Ordering::SeqCst) {
1277 failed_status = Some(anyhow::anyhow!("ASYNC task cancelled"));
1278 }
1279
1280 let mut i = 0;
1284 while i < state.bg_children.len() {
1285 if !in_scope(state.bg_children[i].task_id) {
1286 i += 1;
1287 continue;
1288 }
1289 match state.bg_children[i].handle.try_wait() {
1290 Ok(Some(status)) => {
1291 if !status.success() && failed_status.is_none() {
1292 failed_status =
1293 Some(anyhow::anyhow!("ASYNC process exited with status {status}"));
1294 break;
1295 }
1296 state.bg_children.swap_remove(i);
1297 }
1298 Ok(None) => {
1299 i += 1;
1300 }
1301 Err(e) => {
1302 if failed_status.is_none() {
1303 failed_status = Some(e);
1304 }
1305 break;
1306 }
1307 }
1308 }
1309
1310 if failed_status.is_none() && reap_named {
1314 let entries: Vec<(u64, Arc<TaskEntry>)> = {
1315 let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1316 named
1317 .iter()
1318 .map(|(id, entry)| (*id, Arc::clone(entry)))
1319 .collect()
1320 };
1321 for (id, entry) in &entries {
1322 if !in_scope(*id) {
1323 continue;
1324 }
1325 enum Poll {
1326 Pending,
1327 CompletedOk,
1328 CompletedErr(anyhow::Error),
1329 }
1330 let poll = {
1331 let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1332 match guard.phase {
1333 TaskPhase::Running | TaskPhase::Awaiting => {
1334 match guard.handle.as_mut() {
1335 Some(handle) => match handle.try_wait() {
1336 Ok(Some(status)) => {
1337 let _ = guard.handle.take();
1338 guard.phase = TaskPhase::Completed;
1339 if status.success() {
1340 Poll::CompletedOk
1341 } else {
1342 Poll::CompletedErr(anyhow::anyhow!(
1343 "named ASYNC task {id} exited with status {status}"
1344 ))
1345 }
1346 }
1347 Ok(None) => Poll::Pending,
1348 Err(e) => {
1349 let _ = guard.handle.take();
1350 guard.phase = TaskPhase::Completed;
1351 Poll::CompletedErr(e)
1352 }
1353 },
1354 None => Poll::Pending,
1357 }
1358 }
1359 TaskPhase::Cancelled | TaskPhase::Completed => Poll::Pending,
1360 }
1361 };
1362 match poll {
1363 Poll::Pending => {}
1364 Poll::CompletedOk => {
1365 entry.finish_teardown();
1366 }
1367 Poll::CompletedErr(e) => {
1368 entry.finish_teardown();
1369 if failed_status.is_none() {
1370 failed_status = Some(e);
1371 }
1372 break;
1373 }
1374 }
1375 }
1376 }
1377
1378 if let Some(err) = failed_status {
1383 for survivor in state.bg_children.iter_mut() {
1384 if in_scope(survivor.task_id) {
1385 let _ = survivor.handle.kill();
1386 }
1387 }
1388 if reap_named {
1389 let entries: Vec<(u64, Arc<TaskEntry>)> = {
1390 let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1391 named
1392 .iter()
1393 .map(|(id, entry)| (*id, Arc::clone(entry)))
1394 .collect()
1395 };
1396 let mut to_kill: Vec<(Arc<TaskEntry>, Box<dyn BackgroundHandle>)> = Vec::new();
1397 for (id, entry) in &entries {
1398 if !in_scope(*id) {
1399 continue;
1400 }
1401 let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1402 match guard.phase {
1403 TaskPhase::Running | TaskPhase::Awaiting => {
1404 guard.phase = TaskPhase::Cancelled;
1405 if let Some(handle) = guard.handle.take() {
1406 to_kill.push((Arc::clone(entry), handle));
1407 }
1408 }
1409 TaskPhase::Cancelled | TaskPhase::Completed => {}
1410 }
1411 }
1412 for (entry, mut handle) in to_kill {
1413 let _ = handle.kill();
1414 entry.finish_teardown();
1415 }
1416 }
1417 state.bg_children.retain(|c| !in_scope(c.task_id));
1421 return Err(err);
1422 }
1423
1424 let bg_empty = !state.bg_children.iter().any(|c| in_scope(c.task_id));
1425 if bg_empty && !named_pending(state) {
1426 return Ok(Flow::Done);
1427 }
1428 if reap_named {
1432 let unreaped: Vec<Arc<TaskEntry>> = {
1433 let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1434 named
1435 .iter()
1436 .filter(|(id, entry)| {
1437 if !in_scope(**id) {
1438 return false;
1439 }
1440 let guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1441 matches!(guard.phase, TaskPhase::Cancelled) && !guard.reaped
1442 })
1443 .map(|(_, entry)| Arc::clone(entry))
1444 .collect()
1445 };
1446 for entry in &unreaped {
1447 entry.wait_reaped();
1448 }
1449 }
1450 std::thread::sleep(std::time::Duration::from_millis(10));
1451 }
1452 }
1453
1454 Ok(Flow::Done)
1455}
1456
1457fn restore_scopes<P: ProcessManager>(state: &mut ExecState<P>, count: usize) -> Result<()> {
1458 for _ in 0..count {
1459 state.pop_scope()?;
1460 }
1461 Ok(())
1462}
1463
1464#[allow(clippy::too_many_arguments)]
1471pub(super) fn execute_scoped_remote_body<P: ProcessManager>(
1472 state: &mut ExecState<P>,
1473 process: &mut P,
1474 steps: &[Step],
1475 stdin: CommandStdin,
1476 expose_stdin: bool,
1477 out: Option<StreamHandle>,
1478 err: Option<StreamHandle>,
1479 out_pipe: Option<Arc<PipeInner>>,
1480 stdin_pipe: Option<Arc<PipeInner>>,
1481) -> Result<()> {
1482 let flow = execute_scoped_steps(
1483 state,
1484 process,
1485 steps,
1486 stdin,
1487 expose_stdin,
1488 out,
1489 err,
1490 out_pipe,
1491 stdin_pipe,
1492 true,
1493 )?;
1494 match flow {
1495 Flow::Done => Ok(()),
1496 Flow::Break { idx } => {
1497 bail!("step {}: BREAK cannot cross a REMOTE boundary", idx + 1);
1498 }
1499 Flow::Continue { idx } => {
1500 bail!("step {}: CONTINUE cannot cross a REMOTE boundary", idx + 1);
1501 }
1502 Flow::Return { idx, .. } => {
1503 bail!("step {}: RETURN cannot cross a REMOTE boundary", idx + 1);
1504 }
1505 }
1506}
1507
1508#[allow(clippy::too_many_arguments)]
1513pub(super) fn execute_scoped_steps<P: ProcessManager>(
1514 state: &mut ExecState<P>,
1515 process: &mut P,
1516 steps: &[Step],
1517 stdin: CommandStdin,
1518 expose_stdin: bool,
1519 out: Option<StreamHandle>,
1520 err: Option<StreamHandle>,
1521 out_pipe: Option<Arc<PipeInner>>,
1522 stdin_pipe: Option<Arc<PipeInner>>,
1523 wait_at_end: bool,
1524) -> Result<Flow> {
1525 state.push_scope();
1526 let res = execute_steps(
1527 state,
1528 process,
1529 steps,
1530 stdin,
1531 expose_stdin,
1532 out,
1533 err,
1534 out_pipe,
1535 stdin_pipe,
1536 wait_at_end,
1537 );
1538 let pop_res = state.pop_scope();
1541 match (res, pop_res) {
1542 (Ok(flow), Ok(())) => Ok(flow),
1543 (Err(e), _) => Err(e),
1544 (Ok(_), Err(e)) => Err(e),
1545 }
1546}
1547
1548fn dispatch_flow_step<P: ProcessManager>(
1552 cmd: &StepKind,
1553 cx: &mut StepCtx<'_, P>,
1554 generation: usize,
1555 idx: usize,
1556) -> Result<Flow> {
1557 match cmd {
1558 StepKind::FuncDef {
1559 name,
1560 params,
1561 return_type,
1562 is_async,
1563 body,
1564 ..
1565 } => {
1566 handlers::define_func(cx, name, params, return_type, *is_async, body)?;
1567 Ok(Flow::Done)
1568 }
1569 StepKind::Call { name, args } => {
1570 let _ = handlers::call_func_value(cx, name, args)?;
1571 Ok(Flow::Done)
1572 }
1573 StepKind::Return { expr, .. } => handlers::handle_return(cx, idx, expr),
1574 StepKind::ImportFile { path, alias } => {
1575 let _ = super::import::import_file(cx, path, alias)?;
1576 Ok(Flow::Done)
1577 }
1578 StepKind::ImportFuncs {
1579 path,
1580 alias,
1581 func_names,
1582 type_names,
1583 } => {
1584 super::import::import_funcs(cx, path, alias.as_deref(), func_names, type_names)?;
1585 Ok(Flow::Done)
1586 }
1587 StepKind::While { cond, body } => handlers::while_loop(cx, cond, body),
1588 StepKind::Break => Ok(Flow::Break { idx }),
1589 StepKind::Continue => Ok(Flow::Continue { idx }),
1590 StepKind::For {
1591 key_var,
1592 key_type,
1593 var,
1594 var_type,
1595 in_expr,
1596 body,
1597 } => handlers::for_loop(
1598 cx,
1599 key_var.as_deref(),
1600 key_type.clone(),
1601 var,
1602 var_type.clone(),
1603 in_expr,
1604 body,
1605 ),
1606 StepKind::If {
1607 cond,
1608 then_body,
1609 else_ifs,
1610 else_body,
1611 } => handlers::if_then(cx, cond, then_body, else_ifs, else_body),
1612 StepKind::Switch {
1613 discriminant,
1614 cases,
1615 default_body,
1616 } => handlers::switch_run(cx, discriminant, cases, default_body),
1617 StepKind::Timeout { duration, body } => {
1618 let duration = super::args::resolve_arg_as_duration(duration, cx)?;
1619 handlers::timeout(cx, &duration, body)
1620 }
1621 StepKind::Fail {
1622 code,
1623 message,
1624 body,
1625 } => handlers::fail(cx, code, message, body),
1626 StepKind::Isolated { body } => handlers::isolated(cx, body),
1627 StepKind::WithIo { bindings, cmd } => handlers::with_io(cx, generation, idx, bindings, cmd),
1628 StepKind::Bind {
1629 var,
1630 decl_type,
1631 is_const,
1632 rhs: oxdock_parser::BindRhs::Capture(cmd),
1633 } => handlers::assign_capture(cx, generation, idx, var, decl_type.clone(), cmd, *is_const),
1634 _ => {
1635 unreachable!("dispatch_flow_step handles only compound steps")
1636 }
1637 }
1638}