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;
8use oxdock_diagnostics::DiagnosticResult;
9use oxdock_fs::GuardedPath;
10use oxdock_parser::{
11 Arg, AssertTarget, Command, KEYWORD_BREAK, KEYWORD_CONTINUE, KEYWORD_RETURN, Step, StepKind,
12 Value, guard_option_allows,
13};
14use oxdock_process::{BackgroundHandle, CommandStdin, ProcessManager, SharedInput, SharedOutput};
15
16fn exit_status_from_code(code: i32) -> ExitStatus {
18 #[cfg(unix)]
19 {
20 use std::os::unix::process::ExitStatusExt;
21 ExitStatus::from_raw(code << 8)
22 }
23 #[cfg(windows)]
24 {
25 use std::os::windows::process::ExitStatusExt;
26 ExitStatus::from_raw(code as u32)
27 }
28}
29
30use super::diagnostics as step_diag;
31use super::handlers;
32use super::io::{ExactCapture, SlidingWindow, StreamHandle};
33use super::native::PureTable;
34use super::state::{ExecState, TaskEntry, TaskPhase};
35use oxdock_pipe::PipeInner;
36
37pub(super) struct ThreadJoinHandle {
40 join: Option<std::thread::JoinHandle<Result<()>>>,
41 cancel_token: Arc<AtomicBool>,
42 cancel_hub: Arc<oxdock_process::CancelHub>,
43 active_process: Arc<Mutex<Option<Box<dyn BackgroundHandle>>>>,
44 worker: Arc<Mutex<Option<std::thread::ThreadId>>>,
52 thread_error: Option<anyhow::Error>,
54 thread_exit_code: Option<i64>,
58}
59
60impl ThreadJoinHandle {
61 pub(super) fn new(
62 join: std::thread::JoinHandle<Result<()>>,
63 cancel_token: Arc<AtomicBool>,
64 cancel_hub: Arc<oxdock_process::CancelHub>,
65 active_process: Arc<Mutex<Option<Box<dyn BackgroundHandle>>>>,
66 worker: Arc<Mutex<Option<std::thread::ThreadId>>>,
67 ) -> Self {
68 Self {
69 join: Some(join),
70 cancel_token,
71 cancel_hub,
72 active_process,
73 worker,
74 thread_error: None,
75 thread_exit_code: None,
76 }
77 }
78
79 fn reemit_error(&self) -> anyhow::Error {
85 let msg = self
86 .thread_error
87 .as_ref()
88 .map(|err| format!("{err:#}"))
89 .unwrap_or_else(|| "background thread failed without an error".to_string());
90 match self.thread_exit_code {
91 Some(code) => anyhow::Error::new(super::exit::ExitRequest(code)).context(msg),
92 None => anyhow::anyhow!("{msg}"),
93 }
94 }
95
96 fn is_self(&self) -> bool {
98 let guard = self.worker.lock().unwrap_or_else(|e| e.into_inner());
99 guard.is_some_and(|id| id == std::thread::current().id())
100 }
101
102 fn reap(&mut self) {
104 if self.join.is_none() {
105 return;
106 }
107 if self.is_self() {
108 let _ = self.join.take();
112 return;
113 }
114 let handle = self.join.take().unwrap();
115 match handle.join() {
116 Ok(Ok(())) => {}
117 Ok(Err(e)) => {
118 self.thread_exit_code = super::exit::exit_code_of(&e);
119 self.thread_error = Some(e);
120 }
121 Err(panic) => {
122 let msg = if let Some(s) = panic.downcast_ref::<&str>() {
123 s.to_string()
124 } else if let Some(s) = panic.downcast_ref::<String>() {
125 s.clone()
126 } else {
127 "thread panicked".to_string()
128 };
129 self.thread_error = Some(anyhow::anyhow!("{msg}"));
130 }
131 }
132 }
133}
134
135impl BackgroundHandle for ThreadJoinHandle {
136 fn try_wait(&mut self) -> Result<Option<ExitStatus>> {
137 if let Some(join) = &self.join {
138 if join.is_finished() {
139 self.reap();
140 } else {
141 return Ok(None);
142 }
143 }
144 if self.thread_error.is_some() {
150 Err(self.reemit_error())
151 } else {
152 Ok(Some(exit_status_from_code(0)))
153 }
154 }
155
156 fn kill(&mut self) -> Result<()> {
157 self.cancel_token.store(true, Ordering::SeqCst);
159 self.cancel_hub.mark_cancelled();
162 if let Ok(mut guard) = self.active_process.lock()
164 && let Some(ref mut proc) = *guard
165 {
166 let _ = proc.kill();
167 }
168 self.reap();
170 Ok(())
171 }
172
173 fn wait(&mut self) -> Result<ExitStatus> {
174 self.reap();
175 if self.thread_error.is_some() {
177 Err(self.reemit_error())
178 } else {
179 Ok(exit_status_from_code(0))
180 }
181 }
182}
183
184impl Drop for ThreadJoinHandle {
185 fn drop(&mut self) {
186 let _ = self.kill();
187 }
188}
189
190static ASSERT_GENERATION: AtomicUsize = AtomicUsize::new(0);
194
195#[derive(Debug)]
202pub(super) enum Flow {
203 Done,
204 Break { idx: usize },
205 Continue { idx: usize },
206 Return { idx: usize, value: Value },
207}
208
209pub(super) fn allocate_assert_generation() -> usize {
210 ASSERT_GENERATION.fetch_add(1, Ordering::Relaxed)
211}
212
213#[derive(Clone, Copy, PartialEq, Eq)]
215pub(super) enum AssertStream {
216 Stdout,
217 Stderr,
218}
219
220fn extract_stream_needle(kind: &StepKind) -> Option<(AssertStream, &Arg)> {
224 let step = match kind {
225 StepKind::WithIo { cmd, .. } => cmd.as_ref(),
226 other => other,
227 };
228 match step {
229 StepKind::AssertContains { haystack, needle } => match haystack {
230 AssertTarget::Stdout => Some((AssertStream::Stdout, needle)),
231 AssertTarget::Stderr => Some((AssertStream::Stderr, needle)),
232 _ => None,
233 },
234 _ => None,
235 }
236}
237
238fn needs_exact_stdout(kind: &StepKind) -> bool {
241 let step = match kind {
242 StepKind::WithIo { cmd, .. } => cmd.as_ref(),
243 other => other,
244 };
245 matches!(
246 step,
247 StepKind::AssertEq {
248 actual: AssertTarget::Stdout,
249 ..
250 } | StepKind::AssertNe {
251 actual: AssertTarget::Stdout,
252 ..
253 }
254 )
255}
256
257pub(super) enum ResolvedAssertTarget {
260 Value(Value),
261 Stdout,
262 Stderr,
263 Pipe(Vec<u8>),
264}
265
266pub(super) fn resolve_assert_target<P: ProcessManager>(
272 target: &AssertTarget,
273 cx: &mut StepCtx<'_, P>,
274) -> DiagnosticResult<ResolvedAssertTarget> {
275 match target {
276 AssertTarget::Value(arg) => {
277 let value = super::args::evaluate_assert_operand(arg, cx)?;
278 if let Some(handle) = value.as_pipe_handle() {
279 let bytes = cx.state.io.peek_pipe_content(&handle).map_err(|e| {
280 step_diag::eval_pipe_assertion_read_failed(&anyhow::Error::from(e))
281 })?;
282 return Ok(ResolvedAssertTarget::Pipe(bytes));
283 }
284 Ok(ResolvedAssertTarget::Value(value))
285 }
286 AssertTarget::Stdout => Ok(ResolvedAssertTarget::Stdout),
287 AssertTarget::Stderr => Ok(ResolvedAssertTarget::Stderr),
288 }
289}
290
291pub(super) fn pre_register_assertions<P: ProcessManager>(
298 state: &mut ExecState<P>,
299 steps: &[Step],
300 generation: usize,
301) -> DiagnosticResult<()> {
302 let mut windows = match state.assert_windows.lock() {
303 Ok(guard) => guard,
304 Err(_) => {
305 return Err(super::diagnostics::std_assert_lock_poisoned(
306 "assert_windows",
307 ));
308 }
309 };
310 let mut stderr_windows = match state.assert_windows_stderr.lock() {
311 Ok(guard) => guard,
312 Err(_) => {
313 return Err(super::diagnostics::std_assert_lock_poisoned(
314 "assert_windows_stderr",
315 ));
316 }
317 };
318 let mut exact = match state.exact_stdout.lock() {
319 Ok(guard) => guard,
320 Err(_) => return Err(super::diagnostics::std_assert_lock_poisoned("exact_stdout")),
321 };
322 for (idx, step) in steps.iter().enumerate() {
323 if let Some((stream, arg)) = extract_stream_needle(&step.kind) {
324 let resolved = super::args::resolve_arg_state(arg, state)?;
325 let map = match stream {
326 AssertStream::Stdout => &mut windows,
327 AssertStream::Stderr => &mut stderr_windows,
328 };
329 map.insert((generation, idx), SlidingWindow::new(resolved.into_bytes()));
330 }
331 if needs_exact_stdout(&step.kind) {
332 exact.entry(generation).or_insert_with(ExactCapture::new);
333 }
334 }
335 Ok(())
336}
337
338#[allow(clippy::collapsible_if)]
344pub(super) fn sync_iteration_assert_needles<P: ProcessManager>(
345 state: &ExecState<P>,
346 steps: &[Step],
347 generation: usize,
348) -> DiagnosticResult<()> {
349 let mut windows = match state.assert_windows.lock() {
350 Ok(guard) => guard,
351 Err(_) => {
352 return Err(super::diagnostics::std_assert_lock_poisoned(
353 "assert_windows",
354 ));
355 }
356 };
357 let mut stderr_windows = match state.assert_windows_stderr.lock() {
358 Ok(guard) => guard,
359 Err(_) => {
360 return Err(super::diagnostics::std_assert_lock_poisoned(
361 "assert_windows_stderr",
362 ));
363 }
364 };
365 for (idx, step) in steps.iter().enumerate() {
366 if let Some((stream, arg)) = extract_stream_needle(&step.kind) {
367 let map = match stream {
368 AssertStream::Stdout => &mut windows,
369 AssertStream::Stderr => &mut stderr_windows,
370 };
371 if let Some(w) = map.get_mut(&(generation, idx)) {
372 let resolved = super::args::resolve_arg_state(arg, state)?;
373 w.update_needle(resolved.into_bytes());
374 }
375 }
376 }
377 Ok(())
378}
379
380#[derive(Debug, Clone, Copy, PartialEq, Eq)]
388pub struct TtyRequest {
389 pub rows: Option<u16>,
391 pub cols: Option<u16>,
393}
394
395pub struct StepCtx<'a, P: ProcessManager> {
408 pub(super) state: &'a mut ExecState<P>,
409 pub(super) process: &'a mut P,
410 pub(super) stdin: CommandStdin,
411 pub(super) expose_stdin: bool,
412 pub(super) out: Option<StreamHandle>,
413 pub(super) err: Option<StreamHandle>,
414 pub(super) out_pipe: Option<Arc<PipeInner>>,
420 pub(super) stdin_pipe: Option<Arc<PipeInner>>,
425 pub(super) tty: Option<TtyRequest>,
430}
431
432impl<'a, P: ProcessManager> StepCtx<'a, P> {
433 pub(super) fn for_mcp(
437 state: &'a mut ExecState<P>,
438 process: &'a mut P,
439 stdin: CommandStdin,
440 out: Option<StreamHandle>,
441 err: Option<StreamHandle>,
442 ) -> Self {
443 Self {
444 state,
445 process,
446 stdin,
447 expose_stdin: false,
448 out,
449 err,
450 out_pipe: None,
451 stdin_pipe: None,
452 tty: None,
453 }
454 }
455
456 pub(super) fn err_shared(&self) -> Option<SharedOutput> {
460 match self.err.clone() {
461 Some(StreamHandle::Stream(writer)) => Some(writer),
462 _ => None,
463 }
464 }
465
466 pub fn get_var(&self, key: &str) -> Option<Value> {
468 self.state.get_var(key)
469 }
470
471 pub fn get_env(&self, key: &str) -> Option<String> {
475 self.state.get_env(key).map(str::to_string)
476 }
477
478 pub fn env_snapshot(&self) -> HashMap<String, String> {
485 self.state.envs.as_ref().clone()
486 }
487
488 pub fn ensure_scratch_materialized(&self) -> DiagnosticResult<()> {
493 self.state
494 .cargo_scratch
495 .ensure_materialized()
496 .map_err(|err| super::diagnostics::eval_scratch_materialize_failed(&err))
497 }
498
499 pub fn cwd(&self) -> &GuardedPath {
501 &self.state.cwd
502 }
503
504 pub fn workspace_root(&self) -> &GuardedPath {
509 self.state.fs.root()
510 }
511
512 pub fn pure_functions(&self) -> std::sync::Arc<PureTable> {
520 self.state.pure_function_table()
521 }
522
523 pub fn new_pipe(&self) -> Value {
528 Value::pipe_fresh_in_task(self.state.task_id)
529 }
530
531 pub fn pipe_reader(&self, value: &Value) -> DiagnosticResult<SharedInput> {
540 use oxdock_pipe::{Materialized, materialize};
541 let Some(handle) = value.as_pipe_handle() else {
542 return Err(super::diagnostics::std_pipe_needs_pipe(
543 "pipe_reader",
544 value.type_name(),
545 ));
546 };
547 match materialize(&handle, false)? {
548 Materialized::Script(backend) => Ok(backend.reader_handle()),
549 #[cfg(not(miri))]
550 Materialized::Os(entry) => {
551 let owned = entry
552 .reader
553 .take()
554 .map_err(|_| super::diagnostics::std_pipe_handle_spent())?;
555 Ok(Arc::new(Mutex::new(owned)))
556 }
557 }
558 }
559
560 pub fn pipe_writer(&self, value: &Value) -> DiagnosticResult<SharedOutput> {
564 use oxdock_pipe::{Materialized, materialize};
565 let Some(handle) = value.as_pipe_handle() else {
566 return Err(super::diagnostics::std_pipe_needs_pipe(
567 "pipe_writer",
568 value.type_name(),
569 ));
570 };
571 match materialize(&handle, false)? {
572 Materialized::Script(backend) => Ok(backend.writer_handle()),
573 #[cfg(not(miri))]
574 Materialized::Os(entry) => {
575 let owned = entry
576 .writer
577 .take()
578 .map_err(|_| super::diagnostics::std_pipe_handle_spent())?;
579 Ok(Arc::new(Mutex::new(owned)))
580 }
581 }
582 }
583
584 pub fn close_pipe(&self, value: &Value) -> DiagnosticResult<()> {
590 let Some(handle) = value.as_pipe_handle() else {
591 return Err(super::diagnostics::std_pipe_needs_pipe(
592 "close_pipe",
593 value.type_name(),
594 ));
595 };
596 let Some(backend) = oxdock_pipe::script_backend(&handle) else {
597 return Err(super::diagnostics::std_pipe_close_needs_script());
598 };
599 backend.force_close();
600 Ok(())
601 }
602
603 pub fn is_cancelled(&self) -> bool {
607 self.state
608 .cancel_token
609 .load(std::sync::atomic::Ordering::SeqCst)
610 }
611
612 pub fn cancel_token(&self) -> Arc<AtomicBool> {
617 Arc::clone(&self.state.cancel_token)
618 }
619
620 pub fn cancel_hub(&self) -> Arc<oxdock_process::CancelHub> {
624 Arc::clone(&self.state.cancel_hub)
625 }
626
627 pub fn is_async_task(&self) -> bool {
630 self.state.inside_async
631 }
632
633 pub fn module_state<T: Send + Sync + 'static>(
639 &self,
640 module: &str,
641 ) -> Option<std::sync::Arc<T>> {
642 self.state
643 .module_states
644 .get(&(module.to_string(), std::any::TypeId::of::<T>()))?
645 .clone()
646 .downcast::<T>()
647 .ok()
648 }
649
650 pub fn pipe_backend(&self, value: &Value) -> Option<Arc<PipeInner>> {
657 let handle = value.as_pipe_handle()?;
658 oxdock_pipe::script_backend(&handle)
659 }
660}
661
662#[allow(clippy::too_many_arguments)]
663pub(super) fn execute_steps<P: ProcessManager>(
664 state: &mut ExecState<P>,
665 process: &mut P,
666 steps: &[Step],
667 stdin: CommandStdin,
668 expose_stdin: bool,
669 out: Option<StreamHandle>,
670 err: Option<StreamHandle>,
671 out_pipe: Option<Arc<PipeInner>>,
672 stdin_pipe: Option<Arc<PipeInner>>,
673 wait_at_end: bool,
674) -> Result<Flow> {
675 let generation = allocate_assert_generation();
676 let flow = match execute_steps_inner(InnerArgs {
677 state,
678 process,
679 generation,
680 steps,
681 stdin,
682 expose_stdin,
683 out,
684 err,
685 out_pipe,
686 stdin_pipe,
687 wait_at_end,
688 }) {
689 Ok(flow) => flow,
690 Err(e) => {
691 teardown_tasks_on_error(state);
697 cleanup_assertion_generation(state, generation)?;
698 return Err(e);
699 }
700 };
701 cleanup_assertion_generation(state, generation)?;
703 Ok(flow)
704}
705
706fn cleanup_assertion_generation<P: ProcessManager>(
709 state: &mut ExecState<P>,
710 generation: usize,
711) -> DiagnosticResult<()> {
712 let mut windows = match state.assert_windows.lock() {
713 Ok(guard) => guard,
714 Err(_) => {
715 return Err(super::diagnostics::std_assert_lock_poisoned(
716 "assert_windows",
717 ));
718 }
719 };
720 windows.retain(|(g, _), _| *g != generation);
721 let mut stderr_windows = match state.assert_windows_stderr.lock() {
722 Ok(guard) => guard,
723 Err(_) => {
724 return Err(super::diagnostics::std_assert_lock_poisoned(
725 "assert_windows_stderr",
726 ));
727 }
728 };
729 stderr_windows.retain(|(g, _), _| *g != generation);
730 let mut exact = match state.exact_stdout.lock() {
731 Ok(guard) => guard,
732 Err(_) => return Err(super::diagnostics::std_assert_lock_poisoned("exact_stdout")),
733 };
734 exact.retain(|g, _| *g != generation);
735 Ok(())
736}
737
738fn teardown_tasks_on_error<P: ProcessManager>(state: &mut ExecState<P>) {
743 for survivor in state.bg_children.iter_mut() {
744 let _ = survivor.handle.kill();
745 }
746 state.bg_children.clear();
747 if state.inside_async {
748 return;
749 }
750 let entries: Vec<Arc<TaskEntry>> = {
751 let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
752 named.values().cloned().collect()
753 };
754 let mut to_kill: Vec<(Arc<TaskEntry>, Box<dyn BackgroundHandle>)> = Vec::new();
755 for entry in &entries {
756 let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
757 match guard.phase {
758 TaskPhase::Running | TaskPhase::Awaiting => {
759 guard.phase = TaskPhase::Cancelled;
760 if let Some(handle) = guard.handle.take() {
761 to_kill.push((Arc::clone(entry), handle));
762 }
763 }
764 TaskPhase::Cancelled | TaskPhase::Completed => {}
765 }
766 }
767 for (entry, mut handle) in to_kill {
768 let _ = handle.kill();
769 entry.finish_teardown();
770 }
771}
772
773#[allow(clippy::too_many_arguments)]
776pub(super) fn execute_single_step_with_generation<P: ProcessManager>(
777 state: &mut ExecState<P>,
778 process: &mut P,
779 cmd: &StepKind,
780 generation: usize,
781 idx: usize,
782 stdin: CommandStdin,
783 expose_stdin: bool,
784 out: Option<StreamHandle>,
785 err: Option<StreamHandle>,
786 out_pipe: Option<Arc<PipeInner>>,
787 stdin_pipe: Option<Arc<PipeInner>>,
788 tty: Option<TtyRequest>,
789) -> Result<Flow> {
790 let mut cx = StepCtx {
791 state,
792 process,
793 stdin,
794 expose_stdin,
795 out,
796 err,
797 out_pipe,
798 stdin_pipe,
799 tty,
800 };
801 match cmd {
806 StepKind::FuncDef { .. }
807 | StepKind::Call { .. }
808 | StepKind::Return { .. }
809 | StepKind::ImportFile { .. }
810 | StepKind::ImportFuncs { .. }
811 | StepKind::While { .. }
812 | StepKind::Break
813 | StepKind::Continue
814 | StepKind::For { .. }
815 | StepKind::If { .. }
816 | StepKind::Switch { .. }
817 | StepKind::Timeout { .. }
818 | StepKind::Fail { .. }
819 | StepKind::Isolated { .. }
820 | StepKind::WithIo { .. }
821 | StepKind::Bind {
822 rhs: oxdock_parser::BindRhs::Capture(_),
823 ..
824 } => {
825 return dispatch_flow_step(cmd, &mut cx, generation, idx);
826 }
827 _ => {}
828 }
829 match cmd {
830 StepKind::Run(arg) => {
831 let cmd = super::args::resolve_arg(arg, &mut cx)?;
832 let cmd = super::args::expand_dsl_vars(&cmd, cx.state)?;
833 handlers::run(&mut cx, &cmd)
834 }
835 StepKind::RunExec { argv } => {
836 let resolved = handlers::resolve_run_exec_argv(argv, &mut cx)?;
837 handlers::run_argv(&mut cx, &resolved)
838 }
839 StepKind::Echo(arg) => {
840 let msg = super::args::resolve_arg(arg, &mut cx)?;
841 handlers::echo(&mut cx, &msg)
842 }
843 StepKind::AsyncBlock { .. } => handlers::dispatch_async_block(cmd, &mut cx),
844 StepKind::Workdir(arg) => {
845 let path = super::args::resolve_arg(arg, &mut cx)?;
846 handlers::workdir(&mut cx, &path)
847 }
848 StepKind::Workspace(target) => handlers::workspace(&mut cx, target),
849 StepKind::RemoteBlock {
850 target,
851 vars,
852 env,
853 body,
854 } => super::remote::run_remote_block(&mut cx, target, vars, env, body),
855 StepKind::Env { key, value } => {
856 let resolved = super::args::resolve_arg(value, &mut cx)?;
857 handlers::env(&mut cx, key, &resolved)
858 }
859 StepKind::InheritEnv { keys } => {
860 handlers::inherit_env(&mut cx, keys)?;
861 sync_iteration_assert_needles(
862 cx.state,
863 &[Step {
864 guard: None,
865 kind: cmd.clone(),
866 scope_enter: 0,
867 scope_exit: 0,
868 line: 0,
869 col: 0,
870 }],
871 generation,
872 )?;
873 Ok(())
874 }
875 StepKind::IsolatedInheritEnv { keys } => {
876 handlers::isolated_inherit_env(&mut cx, keys)?;
877 Ok(())
878 }
879 StepKind::Copy {
880 from_workspace,
881 from_host,
882 to_host,
883 from,
884 to,
885 } => {
886 if *from_host || *to_host {
887 super::remote::copy_transfer(&mut cx, *from_host, *to_host, from, to)
888 } else {
889 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
890 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
891 handlers::copy(
892 &mut cx,
893 from_workspace.clone(),
894 &from_resolved,
895 &to_resolved,
896 )
897 }
898 }
899 StepKind::CopyGit {
900 rev,
901 from,
902 to,
903 include_dirty,
904 } => {
905 let rev_resolved = super::args::resolve_arg(rev, &mut cx)?;
906 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
907 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
908 handlers::copy_git(
909 &mut cx,
910 &rev_resolved,
911 &from_resolved,
912 &to_resolved,
913 *include_dirty,
914 )
915 }
916 StepKind::Archive { src, dst, raw } => {
917 let src_resolved = super::args::resolve_arg(src, &mut cx)?;
918 let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
919 handlers::archive(&mut cx, &src_resolved, &dst_resolved, *raw)
920 }
921 StepKind::Unarchive {
922 src,
923 dst,
924 max_bytes,
925 } => {
926 let src_resolved = super::args::resolve_arg(src, &mut cx)?;
927 let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
928 let cap_resolved = super::args::resolve_arg_opt(max_bytes, &mut cx)?;
929 handlers::unarchive(
930 &mut cx,
931 &src_resolved,
932 &dst_resolved,
933 cap_resolved.as_deref(),
934 )
935 }
936 StepKind::Symlink {
937 from_workspace,
938 from,
939 to,
940 } => {
941 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
942 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
943 handlers::symlink(
944 &mut cx,
945 from_workspace.clone(),
946 &from_resolved,
947 &to_resolved,
948 )
949 }
950 StepKind::Mkdir(arg) => {
951 let path = super::args::resolve_arg(arg, &mut cx)?;
952 handlers::mkdir(&mut cx, &path)
953 }
954 StepKind::Install { from, to } => {
955 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
956 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
957 handlers::install(&mut cx, &from_resolved, &to_resolved)
958 }
959 StepKind::SetExecutable { path } => {
960 let resolved = super::args::resolve_arg(path, &mut cx)?;
961 handlers::set_executable(&mut cx, &resolved)
962 }
963 StepKind::Ls(arg) => {
964 let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
965 handlers::ls(&mut cx, &resolved)
966 }
967 StepKind::Read(arg) => {
968 let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
969 handlers::read(&mut cx, &resolved)
970 }
971 StepKind::ReadLine { var } => handlers::read_line(&mut cx, var),
972 StepKind::Prompt {
973 var,
974 message,
975 default,
976 } => {
977 let message_resolved = super::args::resolve_arg(message, &mut cx)?;
978 let default_resolved = match default {
979 Some(d) => Some(super::args::resolve_arg(d, &mut cx)?),
980 None => None,
981 };
982 handlers::prompt(&mut cx, var, &message_resolved, default_resolved.as_deref())
983 }
984 StepKind::ListAppend { list, item } => {
985 let value = super::args::evaluate_assert_operand(item, &mut cx)?;
986 handlers::push_into(&mut cx, list, value)
987 }
988 StepKind::Write { path, contents } => {
989 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
990 let contents_resolved = super::args::resolve_arg_opt(contents, &mut cx)?;
991 handlers::write(&mut cx, &path_resolved, contents_resolved.as_deref())
992 }
993 StepKind::Append { path, contents } => {
994 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
995 let contents_resolved = super::args::resolve_arg_opt(contents, &mut cx)?;
996 handlers::append(&mut cx, &path_resolved, contents_resolved.as_deref())
997 }
998 StepKind::AppendLine { path, contents } => {
999 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1000 let contents_resolved = super::args::resolve_arg(contents, &mut cx)?;
1001 handlers::append_line(&mut cx, &path_resolved, &contents_resolved)
1002 }
1003 StepKind::Remove { path, recursive } => {
1004 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1005 handlers::remove(&mut cx, &path_resolved, *recursive)
1006 }
1007 StepKind::Expand { path, overrides } => {
1008 let path_resolved = super::args::resolve_arg_opt(path, &mut cx)?;
1009 let overrides_resolved = super::args::resolve_overrides(overrides, &mut cx)?;
1010 handlers::replace(&mut cx, &path_resolved, &overrides_resolved)
1011 }
1012 StepKind::AssertEq {
1013 hash,
1014 actual,
1015 expected,
1016 }
1017 | StepKind::AssertNe {
1018 hash,
1019 actual,
1020 expected,
1021 } => {
1022 let (verb, expect_equal) = match cmd {
1023 StepKind::AssertEq { .. } => (Command::AssertEq.as_str(), true),
1024 _ => (Command::AssertNe.as_str(), false),
1025 };
1026 let target = resolve_assert_target(actual, &mut cx)?;
1027 let expected_resolved = match expected {
1028 Some(e) => Some(super::args::evaluate_assert_operand(e, &mut cx)?),
1029 None => None,
1030 };
1031 handlers::assert_equality(
1032 &mut cx,
1033 generation,
1034 verb,
1035 expect_equal,
1036 hash,
1037 &target,
1038 expected_resolved.as_ref(),
1039 )
1040 }
1041 StepKind::AssertContains { haystack, needle } => {
1042 let target = resolve_assert_target(haystack, &mut cx)?;
1043 handlers::assert_contains(&mut cx, generation, idx, &target, needle)
1044 }
1045 StepKind::WithIoBlock { .. } => Err(step_diag::eval_with_io_unexpanded().into()),
1046 StepKind::Exit(code) => {
1047 let code = super::args::resolve_arg_as_int(code, &mut cx)?;
1048 handlers::exit(&mut cx, code)
1049 }
1050 StepKind::Bind {
1051 var,
1052 decl_type,
1053 is_const,
1054 rhs: oxdock_parser::BindRhs::Expr(expr),
1055 } => handlers::assign(&mut cx, var, decl_type.clone(), expr, *is_const),
1056 StepKind::Bind {
1057 var,
1058 decl_type,
1059 is_const,
1060 rhs: oxdock_parser::BindRhs::Async(body),
1061 } => handlers::dispatch_assign_async(var, decl_type.clone(), body, &mut cx, *is_const),
1062 StepKind::Bind {
1063 var,
1064 decl_type,
1065 is_const,
1066 rhs: oxdock_parser::BindRhs::Await { task_var, .. },
1067 } => handlers::dispatch_await_capture(var, decl_type.clone(), task_var, &mut cx, *is_const),
1068 StepKind::Set { var, expr } => handlers::set_var_value(&mut cx, var, expr),
1069 StepKind::Await { var, .. } => handlers::dispatch_await(var, &mut cx),
1070 StepKind::Cancel { var, .. } => handlers::dispatch_cancel(var, &mut cx),
1071 StepKind::Sleep { duration } => {
1072 let duration = super::args::resolve_arg_as_duration(duration, &mut cx)?;
1073 handlers::sleep(&mut cx, &duration)
1074 }
1075 StepKind::TypeAlias { .. } => {
1076 Ok(())
1079 }
1080 StepKind::FuncDef { .. }
1081 | StepKind::Call { .. }
1082 | StepKind::Return { .. }
1083 | StepKind::ImportFile { .. }
1084 | StepKind::ImportFuncs { .. }
1085 | StepKind::While { .. }
1086 | StepKind::Break
1087 | StepKind::Continue
1088 | StepKind::For { .. }
1089 | StepKind::If { .. }
1090 | StepKind::Switch { .. }
1091 | StepKind::Timeout { .. }
1092 | StepKind::Fail { .. }
1093 | StepKind::Isolated { .. }
1094 | StepKind::WithIo { .. }
1095 | StepKind::Bind {
1096 rhs: oxdock_parser::BindRhs::Capture(_),
1097 ..
1098 } => {
1099 unreachable!("compound steps dispatch before this match")
1100 }
1101 }?;
1102 Ok(Flow::Done)
1103}
1104
1105#[allow(clippy::too_many_arguments)]
1106fn step_error(step: &Step, idx: usize, err: anyhow::Error) -> anyhow::Error {
1112 let mut loc = format!("step {}", idx + 1);
1113 if step.line > 0 {
1114 loc.push_str(&format!(", line {}", step.line));
1115 if step.col > 0 {
1116 loc.push_str(&format!(", col {}", step.col));
1117 }
1118 }
1119 err.context(loc)
1120}
1121
1122struct InnerArgs<'a, P: ProcessManager> {
1126 state: &'a mut ExecState<P>,
1127 process: &'a mut P,
1128 generation: usize,
1129 steps: &'a [Step],
1130 stdin: CommandStdin,
1131 expose_stdin: bool,
1132 out: Option<StreamHandle>,
1133 err: Option<StreamHandle>,
1134 out_pipe: Option<Arc<PipeInner>>,
1135 stdin_pipe: Option<Arc<PipeInner>>,
1136 wait_at_end: bool,
1137}
1138
1139fn execute_steps_inner<P: ProcessManager>(args: InnerArgs<'_, P>) -> Result<Flow> {
1140 let InnerArgs {
1141 state,
1142 process,
1143 generation,
1144 steps,
1145 stdin,
1146 expose_stdin,
1147 out,
1148 err,
1149 out_pipe,
1150 stdin_pipe,
1151 wait_at_end,
1152 } = args;
1153 pre_register_assertions(state, steps, generation)?;
1155
1156 for (idx, step) in steps.iter().enumerate() {
1157 if state.cancel_token.load(Ordering::SeqCst) {
1159 return Err(step_diag::eval_async_cancelled().into());
1160 }
1161 if step.scope_enter > 0 {
1162 for _ in 0..step.scope_enter {
1163 state.push_scope();
1164 }
1165 }
1166
1167 let should_run = guard_option_allows(step.guard.as_ref(), &state.envs);
1168 let flow_result: Result<Flow> = (|| {
1172 if !should_run {
1173 Ok(Flow::Done)
1174 } else {
1175 let flow_result: Result<Flow> = match &step.kind {
1180 StepKind::FuncDef { .. }
1181 | StepKind::Call { .. }
1182 | StepKind::Return { .. }
1183 | StepKind::ImportFile { .. }
1184 | StepKind::ImportFuncs { .. }
1185 | StepKind::While { .. }
1186 | StepKind::Break
1187 | StepKind::Continue
1188 | StepKind::For { .. }
1189 | StepKind::If { .. }
1190 | StepKind::Switch { .. }
1191 | StepKind::Timeout { .. }
1192 | StepKind::Fail { .. }
1193 | StepKind::Isolated { .. }
1194 | StepKind::WithIo { .. }
1195 | StepKind::Bind {
1196 rhs: oxdock_parser::BindRhs::Capture(_),
1197 ..
1198 } => {
1199 let mut cx = StepCtx {
1200 state,
1201 process,
1202 stdin: stdin.clone(),
1203 expose_stdin,
1204 out: out.clone(),
1205 err: err.clone(),
1206 out_pipe: out_pipe.clone(),
1207 stdin_pipe: stdin_pipe.clone(),
1208 tty: None,
1209 };
1210 dispatch_flow_step(&step.kind, &mut cx, generation, idx)
1211 }
1212 _ => {
1213 let flow = execute_single_step_with_generation(
1214 state,
1215 process,
1216 &step.kind,
1217 generation,
1218 idx,
1219 stdin.clone(),
1220 expose_stdin,
1221 out.clone(),
1222 err.clone(),
1223 out_pipe.clone(),
1224 stdin_pipe.clone(),
1225 None,
1226 )?;
1227 if matches!(
1228 &step.kind,
1229 StepKind::Env { .. }
1230 | StepKind::InheritEnv { .. }
1231 | StepKind::IsolatedInheritEnv { .. }
1232 ) {
1233 sync_iteration_assert_needles(state, steps, generation)?;
1234 }
1235 Ok(flow)
1236 }
1237 };
1238 flow_result
1239 }
1240 })()
1241 .map_err(|err| step_error(step, idx, err));
1242
1243 let restore_result = restore_scopes(state, step.scope_exit);
1244 let expiry_drained = if let Some(expiry) = state.keeper_expiry.as_mut() {
1249 expiry.expire_step(steps, idx)
1250 } else {
1251 false
1252 };
1253 if expiry_drained {
1254 state.keeper_expiry = None;
1255 }
1256 let flow = flow_result?;
1257 restore_result?;
1258 match flow {
1259 Flow::Done => {}
1260 Flow::Break { .. } | Flow::Continue { .. } | Flow::Return { .. } => {
1261 return Ok(flow);
1262 }
1263 }
1264 }
1265
1266 let reap_named = !state.inside_async;
1274 let floor = state.reap_floor;
1279 let in_scope = |id: u64| floor.map(|f| id >= f).unwrap_or(true);
1280 let has_bg = state.bg_children.iter().any(|c| in_scope(c.task_id));
1281 let named_pending = |state: &ExecState<P>| {
1282 reap_named
1283 && state
1284 .named_tasks
1285 .lock()
1286 .unwrap_or_else(|e| e.into_inner())
1287 .iter()
1288 .any(|(id, entry)| {
1289 in_scope(*id) && !entry.state.lock().unwrap_or_else(|e| e.into_inner()).reaped
1290 })
1291 };
1292 let has_named = named_pending(state);
1293 if wait_at_end && (has_bg || has_named) {
1294 loop {
1295 let mut failed_status: Option<anyhow::Error> = None;
1296
1297 if failed_status.is_none() && state.cancel_token.load(Ordering::SeqCst) {
1302 failed_status = Some(step_diag::eval_async_cancelled().into());
1303 }
1304
1305 let mut i = 0;
1309 while i < state.bg_children.len() {
1310 if !in_scope(state.bg_children[i].task_id) {
1311 i += 1;
1312 continue;
1313 }
1314 match state.bg_children[i].handle.try_wait() {
1315 Ok(Some(status)) => {
1316 if !status.success() && failed_status.is_none() {
1317 failed_status =
1318 Some(step_diag::eval_async_exit_status(None, &status).into());
1319 break;
1320 }
1321 state.bg_children.swap_remove(i);
1322 }
1323 Ok(None) => {
1324 i += 1;
1325 }
1326 Err(e) => {
1327 if failed_status.is_none() {
1328 failed_status = Some(e);
1329 }
1330 break;
1331 }
1332 }
1333 }
1334
1335 if failed_status.is_none() && reap_named {
1339 let entries: Vec<(u64, Arc<TaskEntry>)> = {
1340 let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1341 named
1342 .iter()
1343 .map(|(id, entry)| (*id, Arc::clone(entry)))
1344 .collect()
1345 };
1346 for (id, entry) in &entries {
1347 if !in_scope(*id) {
1348 continue;
1349 }
1350 enum Poll {
1351 Pending,
1352 CompletedOk,
1353 CompletedErr(anyhow::Error),
1354 }
1355 let poll = {
1356 let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1357 match guard.phase {
1358 TaskPhase::Running | TaskPhase::Awaiting => {
1359 match guard.handle.as_mut() {
1360 Some(handle) => match handle.try_wait() {
1361 Ok(Some(status)) => {
1362 let _ = guard.handle.take();
1363 guard.phase = TaskPhase::Completed;
1364 if status.success() {
1365 Poll::CompletedOk
1366 } else {
1367 Poll::CompletedErr(
1368 step_diag::eval_async_exit_status(
1369 Some(*id),
1370 &status,
1371 )
1372 .into(),
1373 )
1374 }
1375 }
1376 Ok(None) => Poll::Pending,
1377 Err(e) => {
1378 let _ = guard.handle.take();
1379 guard.phase = TaskPhase::Completed;
1380 Poll::CompletedErr(e)
1381 }
1382 },
1383 None => Poll::Pending,
1386 }
1387 }
1388 TaskPhase::Cancelled | TaskPhase::Completed => Poll::Pending,
1389 }
1390 };
1391 match poll {
1392 Poll::Pending => {}
1393 Poll::CompletedOk => {
1394 entry.finish_teardown();
1395 }
1396 Poll::CompletedErr(e) => {
1397 entry.finish_teardown();
1398 if failed_status.is_none() {
1399 failed_status = Some(e);
1400 }
1401 break;
1402 }
1403 }
1404 }
1405 }
1406
1407 if let Some(err) = failed_status {
1412 for survivor in state.bg_children.iter_mut() {
1413 if in_scope(survivor.task_id) {
1414 let _ = survivor.handle.kill();
1415 }
1416 }
1417 if reap_named {
1418 let entries: Vec<(u64, Arc<TaskEntry>)> = {
1419 let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1420 named
1421 .iter()
1422 .map(|(id, entry)| (*id, Arc::clone(entry)))
1423 .collect()
1424 };
1425 let mut to_kill: Vec<(Arc<TaskEntry>, Box<dyn BackgroundHandle>)> = Vec::new();
1426 for (id, entry) in &entries {
1427 if !in_scope(*id) {
1428 continue;
1429 }
1430 let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1431 match guard.phase {
1432 TaskPhase::Running | TaskPhase::Awaiting => {
1433 guard.phase = TaskPhase::Cancelled;
1434 if let Some(handle) = guard.handle.take() {
1435 to_kill.push((Arc::clone(entry), handle));
1436 }
1437 }
1438 TaskPhase::Cancelled | TaskPhase::Completed => {}
1439 }
1440 }
1441 for (entry, mut handle) in to_kill {
1442 let _ = handle.kill();
1443 entry.finish_teardown();
1444 }
1445 }
1446 state.bg_children.retain(|c| !in_scope(c.task_id));
1450 return Err(err);
1451 }
1452
1453 let bg_empty = !state.bg_children.iter().any(|c| in_scope(c.task_id));
1454 if bg_empty && !named_pending(state) {
1455 return Ok(Flow::Done);
1456 }
1457 if reap_named {
1461 let unreaped: Vec<Arc<TaskEntry>> = {
1462 let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1463 named
1464 .iter()
1465 .filter(|(id, entry)| {
1466 if !in_scope(**id) {
1467 return false;
1468 }
1469 let guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1470 matches!(guard.phase, TaskPhase::Cancelled) && !guard.reaped
1471 })
1472 .map(|(_, entry)| Arc::clone(entry))
1473 .collect()
1474 };
1475 for entry in &unreaped {
1476 entry.wait_reaped();
1477 }
1478 }
1479 std::thread::sleep(std::time::Duration::from_millis(10));
1480 }
1481 }
1482
1483 Ok(Flow::Done)
1484}
1485
1486fn restore_scopes<P: ProcessManager>(
1487 state: &mut ExecState<P>,
1488 count: usize,
1489) -> DiagnosticResult<()> {
1490 for _ in 0..count {
1491 state.pop_scope()?;
1492 }
1493 Ok(())
1494}
1495
1496#[allow(clippy::too_many_arguments)]
1503pub(super) fn execute_scoped_remote_body<P: ProcessManager>(
1504 state: &mut ExecState<P>,
1505 process: &mut P,
1506 steps: &[Step],
1507 stdin: CommandStdin,
1508 expose_stdin: bool,
1509 out: Option<StreamHandle>,
1510 err: Option<StreamHandle>,
1511 out_pipe: Option<Arc<PipeInner>>,
1512 stdin_pipe: Option<Arc<PipeInner>>,
1513) -> Result<()> {
1514 let flow = execute_scoped_steps(
1515 state,
1516 process,
1517 steps,
1518 stdin,
1519 expose_stdin,
1520 out,
1521 err,
1522 out_pipe,
1523 stdin_pipe,
1524 true,
1525 )?;
1526 match flow {
1527 Flow::Done => Ok(()),
1528 Flow::Break { idx } => {
1529 Err(step_diag::eval_flow_crosses_remote(idx + 1, KEYWORD_BREAK).into())
1530 }
1531 Flow::Continue { idx } => {
1532 Err(step_diag::eval_flow_crosses_remote(idx + 1, KEYWORD_CONTINUE).into())
1533 }
1534 Flow::Return { idx, .. } => {
1535 Err(step_diag::eval_flow_crosses_remote(idx + 1, KEYWORD_RETURN).into())
1536 }
1537 }
1538}
1539
1540#[allow(clippy::too_many_arguments)]
1545pub(super) fn execute_scoped_steps<P: ProcessManager>(
1546 state: &mut ExecState<P>,
1547 process: &mut P,
1548 steps: &[Step],
1549 stdin: CommandStdin,
1550 expose_stdin: bool,
1551 out: Option<StreamHandle>,
1552 err: Option<StreamHandle>,
1553 out_pipe: Option<Arc<PipeInner>>,
1554 stdin_pipe: Option<Arc<PipeInner>>,
1555 wait_at_end: bool,
1556) -> Result<Flow> {
1557 state.push_scope();
1558 let res = execute_steps(
1559 state,
1560 process,
1561 steps,
1562 stdin,
1563 expose_stdin,
1564 out,
1565 err,
1566 out_pipe,
1567 stdin_pipe,
1568 wait_at_end,
1569 );
1570 let pop_res = state.pop_scope().map_err(anyhow::Error::from);
1573 match (res, pop_res) {
1574 (Ok(flow), Ok(())) => Ok(flow),
1575 (Err(e), _) => Err(e),
1576 (Ok(_), Err(e)) => Err(e),
1577 }
1578}
1579
1580fn dispatch_flow_step<P: ProcessManager>(
1584 cmd: &StepKind,
1585 cx: &mut StepCtx<'_, P>,
1586 generation: usize,
1587 idx: usize,
1588) -> Result<Flow> {
1589 match cmd {
1590 StepKind::FuncDef {
1591 name,
1592 params,
1593 return_type,
1594 is_async,
1595 body,
1596 ..
1597 } => {
1598 handlers::define_func(cx, name, params, return_type, *is_async, body)?;
1599 Ok(Flow::Done)
1600 }
1601 StepKind::Call { name, args } => {
1602 let _ = handlers::call_func_value(cx, name, args)?;
1603 Ok(Flow::Done)
1604 }
1605 StepKind::Return { expr, .. } => handlers::handle_return(cx, idx, expr),
1606 StepKind::ImportFile { path, alias } => {
1607 let _ = super::import::import_file(cx, path, alias)?;
1608 Ok(Flow::Done)
1609 }
1610 StepKind::ImportFuncs {
1611 path,
1612 alias,
1613 func_names,
1614 type_names,
1615 } => {
1616 super::import::import_funcs(cx, path, alias.as_deref(), func_names, type_names)?;
1617 Ok(Flow::Done)
1618 }
1619 StepKind::While { cond, body } => handlers::while_loop(cx, cond, body),
1620 StepKind::Break => Ok(Flow::Break { idx }),
1621 StepKind::Continue => Ok(Flow::Continue { idx }),
1622 StepKind::For {
1623 key_var,
1624 key_type,
1625 var,
1626 var_type,
1627 in_expr,
1628 body,
1629 } => handlers::for_loop(
1630 cx,
1631 key_var.as_deref(),
1632 key_type.clone(),
1633 var,
1634 var_type.clone(),
1635 in_expr,
1636 body,
1637 ),
1638 StepKind::If {
1639 cond,
1640 then_body,
1641 else_ifs,
1642 else_body,
1643 } => handlers::if_then(cx, cond, then_body, else_ifs, else_body),
1644 StepKind::Switch {
1645 discriminant,
1646 cases,
1647 default_body,
1648 } => handlers::switch_run(cx, discriminant, cases, default_body),
1649 StepKind::Timeout { duration, body } => {
1650 let duration = super::args::resolve_arg_as_duration(duration, cx)?;
1651 handlers::timeout(cx, &duration, body)
1652 }
1653 StepKind::Fail {
1654 code,
1655 message,
1656 body,
1657 } => handlers::fail(cx, code, message, body),
1658 StepKind::Isolated { body } => handlers::isolated(cx, body),
1659 StepKind::WithIo { bindings, cmd } => handlers::with_io(cx, generation, idx, bindings, cmd),
1660 StepKind::Bind {
1661 var,
1662 decl_type,
1663 is_const,
1664 rhs: oxdock_parser::BindRhs::Capture(cmd),
1665 } => handlers::assign_capture(cx, generation, idx, var, decl_type.clone(), cmd, *is_const),
1666 _ => {
1667 unreachable!("dispatch_flow_step handles only compound steps")
1668 }
1669 }
1670}