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, 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::state::{ExecState, TaskEntry, TaskPhase};
29use oxdock_pipe::PipeInner;
30
31pub(super) struct ThreadJoinHandle {
34 join: Option<std::thread::JoinHandle<Result<()>>>,
35 cancel_token: Arc<AtomicBool>,
36 active_process: Arc<Mutex<Option<Box<dyn BackgroundHandle>>>>,
37 worker: Arc<Mutex<Option<std::thread::ThreadId>>>,
45 thread_error: Option<anyhow::Error>,
47}
48
49impl ThreadJoinHandle {
50 pub(super) fn new(
51 join: std::thread::JoinHandle<Result<()>>,
52 cancel_token: Arc<AtomicBool>,
53 active_process: Arc<Mutex<Option<Box<dyn BackgroundHandle>>>>,
54 worker: Arc<Mutex<Option<std::thread::ThreadId>>>,
55 ) -> Self {
56 Self {
57 join: Some(join),
58 cancel_token,
59 active_process,
60 worker,
61 thread_error: None,
62 }
63 }
64
65 fn is_self(&self) -> bool {
67 let guard = self.worker.lock().unwrap_or_else(|e| e.into_inner());
68 guard.is_some_and(|id| id == std::thread::current().id())
69 }
70
71 fn reap(&mut self) {
73 if self.join.is_none() {
74 return;
75 }
76 if self.is_self() {
77 let _ = self.join.take();
81 return;
82 }
83 let handle = self.join.take().unwrap();
84 match handle.join() {
85 Ok(Ok(())) => {}
86 Ok(Err(e)) => {
87 self.thread_error = Some(e);
88 }
89 Err(panic) => {
90 let msg = if let Some(s) = panic.downcast_ref::<&str>() {
91 s.to_string()
92 } else if let Some(s) = panic.downcast_ref::<String>() {
93 s.clone()
94 } else {
95 "thread panicked".to_string()
96 };
97 self.thread_error = Some(anyhow::anyhow!("{msg}"));
98 }
99 }
100 }
101}
102
103impl BackgroundHandle for ThreadJoinHandle {
104 fn try_wait(&mut self) -> Result<Option<ExitStatus>> {
105 if let Some(join) = &self.join {
106 if join.is_finished() {
107 self.reap();
108 } else {
109 return Ok(None);
110 }
111 }
112 if let Some(ref err) = self.thread_error {
118 Err(anyhow::anyhow!("{err:#}"))
119 } else {
120 Ok(Some(exit_status_from_code(0)))
121 }
122 }
123
124 fn kill(&mut self) -> Result<()> {
125 self.cancel_token.store(true, Ordering::SeqCst);
127 if let Ok(mut guard) = self.active_process.lock()
129 && let Some(ref mut proc) = *guard
130 {
131 let _ = proc.kill();
132 }
133 self.reap();
135 Ok(())
136 }
137
138 fn wait(&mut self) -> Result<ExitStatus> {
139 self.reap();
140 if let Some(ref err) = self.thread_error {
142 Err(anyhow::anyhow!("{err:#}"))
143 } else {
144 Ok(exit_status_from_code(0))
145 }
146 }
147}
148
149impl Drop for ThreadJoinHandle {
150 fn drop(&mut self) {
151 let _ = self.kill();
152 }
153}
154
155static ASSERT_GENERATION: AtomicUsize = AtomicUsize::new(0);
159
160#[derive(Debug)]
167pub(super) enum Flow {
168 Done,
169 Break { idx: usize },
170 Continue { idx: usize },
171 Return { idx: usize, value: Value },
172}
173
174pub(super) fn allocate_assert_generation() -> usize {
175 ASSERT_GENERATION.fetch_add(1, Ordering::Relaxed)
176}
177
178#[derive(Clone, Copy, PartialEq, Eq)]
180pub(super) enum AssertStream {
181 Stdout,
182 Stderr,
183}
184
185fn extract_stream_needle(kind: &StepKind) -> Option<(AssertStream, &Arg)> {
189 let step = match kind {
190 StepKind::WithIo { cmd, .. } => cmd.as_ref(),
191 other => other,
192 };
193 match step {
194 StepKind::AssertContains { haystack, needle } => match haystack {
195 AssertTarget::Stdout => Some((AssertStream::Stdout, needle)),
196 AssertTarget::Stderr => Some((AssertStream::Stderr, needle)),
197 _ => None,
198 },
199 _ => None,
200 }
201}
202
203fn needs_exact_stdout(kind: &StepKind) -> bool {
206 let step = match kind {
207 StepKind::WithIo { cmd, .. } => cmd.as_ref(),
208 other => other,
209 };
210 matches!(
211 step,
212 StepKind::AssertEq {
213 actual: AssertTarget::Stdout,
214 ..
215 }
216 )
217}
218
219pub(super) enum ResolvedAssertTarget {
222 Value(Value),
223 Stdout,
224 Stderr,
225 Pipe(Vec<u8>),
226}
227
228pub(super) fn resolve_assert_target<P: ProcessManager>(
234 target: &AssertTarget,
235 cx: &mut StepCtx<'_, P>,
236) -> Result<ResolvedAssertTarget> {
237 match target {
238 AssertTarget::Value(arg) => {
239 let value = super::args::evaluate_assert_operand(arg, cx)?;
240 if let Some(handle) = value.as_pipe_handle() {
241 let bytes =
242 cx.state.io.peek_pipe_content(&handle).map_err(|e| {
243 anyhow::anyhow!("step pipe assertion cannot read pipe: {e}")
244 })?;
245 return Ok(ResolvedAssertTarget::Pipe(bytes));
246 }
247 Ok(ResolvedAssertTarget::Value(value))
248 }
249 AssertTarget::Stdout => Ok(ResolvedAssertTarget::Stdout),
250 AssertTarget::Stderr => Ok(ResolvedAssertTarget::Stderr),
251 }
252}
253
254pub(super) fn pre_register_assertions<P: ProcessManager>(
261 state: &mut ExecState<P>,
262 steps: &[Step],
263 generation: usize,
264) -> Result<()> {
265 let mut windows = match state.assert_windows.lock() {
266 Ok(guard) => guard,
267 Err(_) => bail!("assert_windows poisoned"),
268 };
269 let mut stderr_windows = match state.assert_windows_stderr.lock() {
270 Ok(guard) => guard,
271 Err(_) => bail!("assert_windows_stderr poisoned"),
272 };
273 let mut exact = match state.exact_stdout.lock() {
274 Ok(guard) => guard,
275 Err(_) => bail!("exact_stdout poisoned"),
276 };
277 for (idx, step) in steps.iter().enumerate() {
278 if let Some((stream, arg)) = extract_stream_needle(&step.kind) {
279 let resolved = super::args::resolve_arg_state(arg, state)?;
280 let map = match stream {
281 AssertStream::Stdout => &mut windows,
282 AssertStream::Stderr => &mut stderr_windows,
283 };
284 map.insert((generation, idx), SlidingWindow::new(resolved.into_bytes()));
285 }
286 if needs_exact_stdout(&step.kind) {
287 exact.entry(generation).or_insert_with(ExactCapture::new);
288 }
289 }
290 Ok(())
291}
292
293#[allow(clippy::collapsible_if)]
299pub(super) fn sync_iteration_assert_needles<P: ProcessManager>(
300 state: &ExecState<P>,
301 steps: &[Step],
302 generation: usize,
303) -> Result<()> {
304 let mut windows = match state.assert_windows.lock() {
305 Ok(guard) => guard,
306 Err(_) => bail!("assert_windows poisoned"),
307 };
308 let mut stderr_windows = match state.assert_windows_stderr.lock() {
309 Ok(guard) => guard,
310 Err(_) => bail!("assert_windows_stderr poisoned"),
311 };
312 for (idx, step) in steps.iter().enumerate() {
313 if let Some((stream, arg)) = extract_stream_needle(&step.kind) {
314 let map = match stream {
315 AssertStream::Stdout => &mut windows,
316 AssertStream::Stderr => &mut stderr_windows,
317 };
318 if let Some(w) = map.get_mut(&(generation, idx)) {
319 let resolved = super::args::resolve_arg_state(arg, state)?;
320 w.update_needle(resolved.into_bytes());
321 }
322 }
323 }
324 Ok(())
325}
326
327pub struct StepCtx<'a, P: ProcessManager> {
340 pub(super) state: &'a mut ExecState<P>,
341 pub(super) process: &'a mut P,
342 pub(super) stdin: CommandStdin,
343 pub(super) expose_stdin: bool,
344 pub(super) out: Option<StreamHandle>,
345 pub(super) err: Option<StreamHandle>,
346 pub(super) out_pipe: Option<Arc<PipeInner>>,
352 pub(super) stdin_pipe: Option<Arc<PipeInner>>,
357}
358
359impl<'a, P: ProcessManager> StepCtx<'a, P> {
360 pub(super) fn err_shared(&self) -> Option<SharedOutput> {
364 match self.err.clone() {
365 Some(StreamHandle::Stream(writer)) => Some(writer),
366 _ => None,
367 }
368 }
369
370 pub fn get_var(&self, key: &str) -> Option<Value> {
372 self.state.get_var(key)
373 }
374
375 pub fn get_env(&self, key: &str) -> Option<String> {
377 self.state.envs.get(key).cloned()
378 }
379
380 pub fn env_snapshot(&self) -> HashMap<String, String> {
387 self.state.envs.as_ref().clone()
388 }
389
390 pub fn cwd(&self) -> &GuardedPath {
392 &self.state.cwd
393 }
394
395 pub fn new_pipe(&self) -> Value {
400 Value::pipe_fresh_in_task(self.state.task_id)
401 }
402
403 pub fn pipe_reader(&self, value: &Value) -> Result<SharedInput> {
412 use oxdock_pipe::{Materialized, materialize};
413 let Some(handle) = value.as_pipe_handle() else {
414 anyhow::bail!(
415 "host pipe_reader needs a PIPE value, got {}",
416 value.type_name()
417 );
418 };
419 match materialize(&handle, false)? {
420 Materialized::Script(backend) => Ok(backend.reader_handle()),
421 #[cfg(not(miri))]
422 Materialized::Os(entry) => {
423 let owned = entry.reader.take().map_err(|_| {
424 anyhow::anyhow!(
425 "OS pipe handle has already been consumed by another binding; declare a fresh LET $x: PIPE for a new session"
426 )
427 })?;
428 Ok(Arc::new(Mutex::new(owned)))
429 }
430 }
431 }
432
433 pub fn pipe_writer(&self, value: &Value) -> Result<SharedOutput> {
437 use oxdock_pipe::{Materialized, materialize};
438 let Some(handle) = value.as_pipe_handle() else {
439 anyhow::bail!(
440 "host pipe_writer needs a PIPE value, got {}",
441 value.type_name()
442 );
443 };
444 match materialize(&handle, false)? {
445 Materialized::Script(backend) => Ok(backend.writer_handle()),
446 #[cfg(not(miri))]
447 Materialized::Os(entry) => {
448 let owned = entry.writer.take().map_err(|_| {
449 anyhow::anyhow!(
450 "OS pipe handle has already been consumed by another binding; declare a fresh LET $x: PIPE for a new session"
451 )
452 })?;
453 Ok(Arc::new(Mutex::new(owned)))
454 }
455 }
456 }
457
458 pub fn close_pipe(&self, value: &Value) -> Result<()> {
464 let Some(handle) = value.as_pipe_handle() else {
465 anyhow::bail!(
466 "host close_pipe needs a PIPE value, got {}",
467 value.type_name()
468 );
469 };
470 let Some(backend) = oxdock_pipe::script_backend(&handle) else {
471 anyhow::bail!(
472 "host close_pipe needs a script-materialized pipe (unbound and OS handles cannot be force-closed)"
473 );
474 };
475 backend.force_close();
476 Ok(())
477 }
478
479 pub fn is_cancelled(&self) -> bool {
483 self.state
484 .cancel_token
485 .load(std::sync::atomic::Ordering::SeqCst)
486 }
487
488 pub fn is_async_task(&self) -> bool {
491 self.state.inside_async
492 }
493
494 pub fn pipe_backend(&self, value: &Value) -> Option<Arc<PipeInner>> {
501 let handle = value.as_pipe_handle()?;
502 oxdock_pipe::script_backend(&handle)
503 }
504}
505
506#[allow(clippy::too_many_arguments)]
507pub(super) fn execute_steps<P: ProcessManager>(
508 state: &mut ExecState<P>,
509 process: &mut P,
510 steps: &[Step],
511 stdin: CommandStdin,
512 expose_stdin: bool,
513 out: Option<StreamHandle>,
514 err: Option<StreamHandle>,
515 out_pipe: Option<Arc<PipeInner>>,
516 stdin_pipe: Option<Arc<PipeInner>>,
517 wait_at_end: bool,
518) -> Result<Flow> {
519 let generation = allocate_assert_generation();
520 let flow = match execute_steps_inner(
521 state,
522 process,
523 generation,
524 steps,
525 stdin,
526 expose_stdin,
527 out,
528 err,
529 out_pipe,
530 stdin_pipe,
531 wait_at_end,
532 ) {
533 Ok(flow) => flow,
534 Err(e) => {
535 teardown_tasks_on_error(state);
541 cleanup_assertion_generation(state, generation)?;
542 return Err(e);
543 }
544 };
545 cleanup_assertion_generation(state, generation)?;
547 Ok(flow)
548}
549
550fn cleanup_assertion_generation<P: ProcessManager>(
553 state: &mut ExecState<P>,
554 generation: usize,
555) -> Result<()> {
556 let mut windows = match state.assert_windows.lock() {
557 Ok(guard) => guard,
558 Err(_) => bail!("assert_windows poisoned"),
559 };
560 windows.retain(|(g, _), _| *g != generation);
561 let mut stderr_windows = match state.assert_windows_stderr.lock() {
562 Ok(guard) => guard,
563 Err(_) => bail!("assert_windows_stderr poisoned"),
564 };
565 stderr_windows.retain(|(g, _), _| *g != generation);
566 let mut exact = match state.exact_stdout.lock() {
567 Ok(guard) => guard,
568 Err(_) => bail!("exact_stdout poisoned"),
569 };
570 exact.retain(|g, _| *g != generation);
571 Ok(())
572}
573
574fn teardown_tasks_on_error<P: ProcessManager>(state: &mut ExecState<P>) {
579 for survivor in state.bg_children.iter_mut() {
580 let _ = survivor.kill();
581 }
582 state.bg_children.clear();
583 if state.inside_async {
584 return;
585 }
586 let entries: Vec<Arc<TaskEntry>> = {
587 let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
588 named.values().cloned().collect()
589 };
590 let mut to_kill: Vec<(Arc<TaskEntry>, Box<dyn BackgroundHandle>)> = Vec::new();
591 for entry in &entries {
592 let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
593 match guard.phase {
594 TaskPhase::Running | TaskPhase::Awaiting => {
595 guard.phase = TaskPhase::Cancelled;
596 if let Some(handle) = guard.handle.take() {
597 to_kill.push((Arc::clone(entry), handle));
598 }
599 }
600 TaskPhase::Cancelled | TaskPhase::Completed => {}
601 }
602 }
603 for (entry, mut handle) in to_kill {
604 let _ = handle.kill();
605 entry.finish_teardown();
606 }
607}
608
609#[allow(clippy::too_many_arguments)]
612pub(super) fn execute_single_step_with_generation<P: ProcessManager>(
613 state: &mut ExecState<P>,
614 process: &mut P,
615 cmd: &StepKind,
616 generation: usize,
617 idx: usize,
618 stdin: CommandStdin,
619 expose_stdin: bool,
620 out: Option<StreamHandle>,
621 err: Option<StreamHandle>,
622 out_pipe: Option<Arc<PipeInner>>,
623 stdin_pipe: Option<Arc<PipeInner>>,
624) -> Result<Flow> {
625 let mut cx = StepCtx {
626 state,
627 process,
628 stdin,
629 expose_stdin,
630 out,
631 err,
632 out_pipe,
633 stdin_pipe,
634 };
635 match cmd {
639 StepKind::FuncDef { .. }
640 | StepKind::Call { .. }
641 | StepKind::Return { .. }
642 | StepKind::While { .. }
643 | StepKind::Break
644 | StepKind::Continue
645 | StepKind::For { .. }
646 | StepKind::If { .. }
647 | StepKind::Timeout { .. }
648 | StepKind::WithIo { .. }
649 | StepKind::AssignCapture { .. } => {
650 return dispatch_flow_step(cmd, &mut cx, generation, idx);
651 }
652 _ => {}
653 }
654 match cmd {
655 StepKind::Run(arg) => {
656 let cmd = super::args::resolve_arg(arg, &mut cx)?;
657 let cmd = super::args::expand_dsl_vars(&cmd, cx.state);
658 handlers::run(&mut cx, idx, &cmd)
659 }
660 StepKind::RunExec { argv } => {
661 let resolved = handlers::resolve_run_exec_argv(argv, &mut cx)?;
662 handlers::run_argv(&mut cx, idx, &resolved)
663 }
664 StepKind::Echo(arg) => {
665 let msg = super::args::resolve_arg(arg, &mut cx)?;
666 handlers::echo(&mut cx, &msg)
667 }
668 StepKind::AsyncBlock { .. } => handlers::dispatch_async_block(cmd, &mut cx),
669 StepKind::Workdir(arg) => {
670 let path = super::args::resolve_arg(arg, &mut cx)?;
671 handlers::workdir(&mut cx, idx, &path)
672 }
673 StepKind::Workspace(target) => handlers::workspace(&mut cx, target),
674 StepKind::RemoteBlock {
675 target,
676 vars,
677 env,
678 body,
679 } => super::remote::run_remote_block(&mut cx, target, vars, env, body, idx),
680 StepKind::Env { key, value } => {
681 let resolved = super::args::resolve_arg(value, &mut cx)?;
682 handlers::env(&mut cx, key, &resolved)
683 }
684 StepKind::InheritEnv { keys } => {
685 handlers::inherit_env(&mut cx, keys)?;
686 sync_iteration_assert_needles(
687 cx.state,
688 &[Step {
689 guard: None,
690 kind: cmd.clone(),
691 scope_enter: 0,
692 scope_exit: 0,
693 }],
694 generation,
695 )?;
696 Ok(())
697 }
698 StepKind::Copy {
699 from_workspace,
700 from_host,
701 to_host,
702 from,
703 to,
704 } => {
705 if *from_host || *to_host {
706 super::remote::copy_transfer(&mut cx, *from_host, *to_host, from, to)
707 } else {
708 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
709 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
710 handlers::copy(
711 &mut cx,
712 idx,
713 from_workspace.clone(),
714 &from_resolved,
715 &to_resolved,
716 )
717 }
718 }
719 StepKind::CopyGit {
720 rev,
721 from,
722 to,
723 include_dirty,
724 } => {
725 let rev_resolved = super::args::resolve_arg(rev, &mut cx)?;
726 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
727 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
728 handlers::copy_git(
729 &mut cx,
730 idx,
731 &rev_resolved,
732 &from_resolved,
733 &to_resolved,
734 *include_dirty,
735 )
736 }
737 StepKind::HashSha256 { path } => {
738 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
739 handlers::hash_sha256(&mut cx, idx, &path_resolved)
740 }
741 StepKind::Symlink {
742 from_workspace,
743 from,
744 to,
745 } => {
746 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
747 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
748 handlers::symlink(
749 &mut cx,
750 idx,
751 from_workspace.clone(),
752 &from_resolved,
753 &to_resolved,
754 )
755 }
756 StepKind::Mkdir(arg) => {
757 let path = super::args::resolve_arg(arg, &mut cx)?;
758 handlers::mkdir(&mut cx, idx, &path)
759 }
760 StepKind::Ls(arg) => {
761 let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
762 handlers::ls(&mut cx, idx, &resolved)
763 }
764 StepKind::Cwd => handlers::cwd(&mut cx, idx),
765 StepKind::Read(arg) => {
766 let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
767 handlers::read(&mut cx, idx, &resolved)
768 }
769 StepKind::ReadLine { var } => handlers::read_line(&mut cx, idx, var),
770 StepKind::ListAppend { list, item } => {
771 let value = super::args::evaluate_assert_operand(item, &mut cx)?;
772 handlers::push_into(&mut cx, idx, list, value)
773 }
774 StepKind::Write { path, contents } => {
775 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
776 let contents_resolved = super::args::resolve_arg_opt(contents, &mut cx)?;
777 handlers::write(&mut cx, idx, &path_resolved, contents_resolved.as_deref())
778 }
779 StepKind::Append { path, contents } => {
780 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
781 let contents_resolved = super::args::resolve_arg_opt(contents, &mut cx)?;
782 handlers::append(&mut cx, idx, &path_resolved, contents_resolved.as_deref())
783 }
784 StepKind::Expand { path, overrides } => {
785 let path_resolved = super::args::resolve_arg_opt(path, &mut cx)?;
786 let overrides_resolved = super::args::resolve_overrides(overrides, &mut cx)?;
787 handlers::replace(&mut cx, idx, &path_resolved, &overrides_resolved)
788 }
789 StepKind::AssertEq {
790 hash,
791 actual,
792 expected,
793 } => {
794 let target = resolve_assert_target(actual, &mut cx)?;
795 let expected_resolved = match expected {
796 Some(e) => Some(super::args::evaluate_assert_operand(e, &mut cx)?),
797 None => None,
798 };
799 handlers::assert_eq(
800 &mut cx,
801 idx,
802 generation,
803 idx,
804 hash,
805 &target,
806 expected_resolved.as_ref(),
807 )
808 }
809 StepKind::AssertContains { haystack, needle } => {
810 let target = resolve_assert_target(haystack, &mut cx)?;
811 handlers::assert_contains(&mut cx, idx, generation, idx, &target, needle)
812 }
813 StepKind::WithIoBlock { .. } => {
814 bail!("WITH_IO block should have been expanded during parsing")
815 }
816 StepKind::Exit(code) => {
817 let code = super::args::resolve_arg_as_int(code, &mut cx)?;
818 handlers::exit(&mut cx, code)
819 }
820 StepKind::Assign {
821 var,
822 decl_type,
823 expr,
824 } => handlers::assign(&mut cx, var, decl_type.clone(), expr),
825 StepKind::Set { var, expr } => handlers::set_var_value(&mut cx, var, expr),
826 StepKind::AssignAsync {
827 var,
828 decl_type,
829 body,
830 } => handlers::dispatch_assign_async(var, decl_type.clone(), body, &mut cx),
831 StepKind::Await { var } => handlers::dispatch_await(var, &mut cx),
832 StepKind::AwaitCapture {
833 out_var,
834 out_type,
835 task_var,
836 } => handlers::dispatch_await_capture(out_var, out_type.clone(), task_var, &mut cx),
837 StepKind::Cancel { var } => handlers::dispatch_cancel(var, &mut cx),
838 StepKind::Sleep { duration } => {
839 let duration = super::args::resolve_arg_as_duration(duration, &mut cx)?;
840 handlers::sleep(&mut cx, idx, &duration)
841 }
842 StepKind::FuncDef { .. }
843 | StepKind::Call { .. }
844 | StepKind::Return { .. }
845 | StepKind::While { .. }
846 | StepKind::Break
847 | StepKind::Continue
848 | StepKind::For { .. }
849 | StepKind::If { .. }
850 | StepKind::Timeout { .. }
851 | StepKind::WithIo { .. }
852 | StepKind::AssignCapture { .. } => {
853 unreachable!("compound steps dispatch before this match")
854 }
855 }?;
856 Ok(Flow::Done)
857}
858
859#[allow(clippy::too_many_arguments)]
860fn execute_steps_inner<P: ProcessManager>(
861 state: &mut ExecState<P>,
862 process: &mut P,
863 generation: usize,
864 steps: &[Step],
865 stdin: CommandStdin,
866 expose_stdin: bool,
867 out: Option<StreamHandle>,
868 err: Option<StreamHandle>,
869 out_pipe: Option<Arc<PipeInner>>,
870 stdin_pipe: Option<Arc<PipeInner>>,
871 wait_at_end: bool,
872) -> Result<Flow> {
873 pre_register_assertions(state, steps, generation)?;
875
876 for (idx, step) in steps.iter().enumerate() {
877 if state.cancel_token.load(Ordering::SeqCst) {
879 bail!("ASYNC task cancelled");
880 }
881 if step.scope_enter > 0 {
882 for _ in 0..step.scope_enter {
883 state.push_scope();
884 }
885 }
886
887 let should_run = guard_option_allows(step.guard.as_ref(), &state.envs);
888 let flow_result: Result<Flow> = if !should_run {
889 Ok(Flow::Done)
890 } else {
891 let mut cx = StepCtx {
892 state,
893 process,
894 stdin: stdin.clone(),
895 expose_stdin,
896 out: out.clone(),
897 err: err.clone(),
898 out_pipe: out_pipe.clone(),
899 stdin_pipe: stdin_pipe.clone(),
900 };
901 let flow_result: Result<Flow> = match &step.kind {
904 StepKind::FuncDef { .. }
905 | StepKind::Call { .. }
906 | StepKind::Return { .. }
907 | StepKind::While { .. }
908 | StepKind::Break
909 | StepKind::Continue
910 | StepKind::For { .. }
911 | StepKind::If { .. }
912 | StepKind::Timeout { .. }
913 | StepKind::WithIo { .. }
914 | StepKind::AssignCapture { .. } => {
915 dispatch_flow_step(&step.kind, &mut cx, generation, idx)
916 }
917 _ => {
918 match &step.kind {
919 StepKind::InheritEnv { keys } => {
920 handlers::inherit_env(&mut cx, keys)?;
921 sync_iteration_assert_needles(cx.state, steps, generation)?;
922 Ok(())
923 }
924 StepKind::Workdir(arg) => {
925 let path = super::args::resolve_arg(arg, &mut cx)?;
926 handlers::workdir(&mut cx, idx, &path)
927 }
928 StepKind::Workspace(target) => handlers::workspace(&mut cx, target),
929 StepKind::RemoteBlock {
930 target,
931 vars,
932 env,
933 body,
934 } => super::remote::run_remote_block(&mut cx, target, vars, env, body, idx),
935 StepKind::Env { key, value } => {
936 let resolved = super::args::resolve_arg(value, &mut cx)?;
937 handlers::env(&mut cx, key, &resolved)?;
938 sync_iteration_assert_needles(cx.state, steps, generation)?;
939 Ok(())
940 }
941 StepKind::Run(arg) => {
942 let cmd = super::args::resolve_arg(arg, &mut cx)?;
943 let cmd = super::args::expand_dsl_vars(&cmd, cx.state);
944 handlers::run(&mut cx, idx, &cmd)
945 }
946 StepKind::RunExec { argv } => {
947 let resolved = handlers::resolve_run_exec_argv(argv, &mut cx)?;
948 handlers::run_argv(&mut cx, idx, &resolved)
949 }
950 StepKind::Echo(arg) => {
951 let msg = super::args::resolve_arg(arg, &mut cx)?;
952 handlers::echo(&mut cx, &msg)
953 }
954 StepKind::AsyncBlock { .. } => {
955 handlers::dispatch_async_block(&step.kind, &mut cx)
956 }
957 StepKind::Copy {
958 from_workspace,
959 from_host,
960 to_host,
961 from,
962 to,
963 } => {
964 if *from_host || *to_host {
965 super::remote::copy_transfer(
966 &mut cx, *from_host, *to_host, from, to,
967 )
968 } else {
969 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
970 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
971 handlers::copy(
972 &mut cx,
973 idx,
974 from_workspace.clone(),
975 &from_resolved,
976 &to_resolved,
977 )
978 }
979 }
980 StepKind::CopyGit {
981 rev,
982 from,
983 to,
984 include_dirty,
985 } => {
986 let rev_resolved = super::args::resolve_arg(rev, &mut cx)?;
987 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
988 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
989 handlers::copy_git(
990 &mut cx,
991 idx,
992 &rev_resolved,
993 &from_resolved,
994 &to_resolved,
995 *include_dirty,
996 )
997 }
998 StepKind::HashSha256 { path } => {
999 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1000 handlers::hash_sha256(&mut cx, idx, &path_resolved)
1001 }
1002 StepKind::Symlink {
1003 from_workspace,
1004 from,
1005 to,
1006 } => {
1007 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1008 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1009 handlers::symlink(
1010 &mut cx,
1011 idx,
1012 from_workspace.clone(),
1013 &from_resolved,
1014 &to_resolved,
1015 )
1016 }
1017 StepKind::Mkdir(arg) => {
1018 let path = super::args::resolve_arg(arg, &mut cx)?;
1019 handlers::mkdir(&mut cx, idx, &path)
1020 }
1021 StepKind::Ls(arg) => {
1022 let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
1023 handlers::ls(&mut cx, idx, &resolved)
1024 }
1025 StepKind::Cwd => handlers::cwd(&mut cx, idx),
1026 StepKind::Read(arg) => {
1027 let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
1028 handlers::read(&mut cx, idx, &resolved)
1029 }
1030 StepKind::ReadLine { var } => handlers::read_line(&mut cx, idx, var),
1031 StepKind::ListAppend { list, item } => {
1032 let value = super::args::evaluate_assert_operand(item, &mut cx)?;
1033 handlers::push_into(&mut cx, idx, list, value)
1034 }
1035 StepKind::Write { path, contents } => {
1036 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1037 let contents_resolved =
1038 super::args::resolve_arg_opt(contents, &mut cx)?;
1039 handlers::write(
1040 &mut cx,
1041 idx,
1042 &path_resolved,
1043 contents_resolved.as_deref(),
1044 )
1045 }
1046 StepKind::Append { path, contents } => {
1047 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1048 let contents_resolved =
1049 super::args::resolve_arg_opt(contents, &mut cx)?;
1050 handlers::append(
1051 &mut cx,
1052 idx,
1053 &path_resolved,
1054 contents_resolved.as_deref(),
1055 )
1056 }
1057 StepKind::Expand { path, overrides } => {
1058 let path_resolved = super::args::resolve_arg_opt(path, &mut cx)?;
1059 let overrides_resolved =
1060 super::args::resolve_overrides(overrides, &mut cx)?;
1061 handlers::replace(&mut cx, idx, &path_resolved, &overrides_resolved)
1062 }
1063 StepKind::AssertEq {
1064 hash,
1065 actual,
1066 expected,
1067 } => {
1068 let target = resolve_assert_target(actual, &mut cx)?;
1069 let expected_resolved = match expected {
1070 Some(e) => Some(super::args::evaluate_assert_operand(e, &mut cx)?),
1071 None => None,
1072 };
1073 handlers::assert_eq(
1074 &mut cx,
1075 idx,
1076 generation,
1077 idx,
1078 hash,
1079 &target,
1080 expected_resolved.as_ref(),
1081 )
1082 }
1083 StepKind::AssertContains { haystack, needle } => {
1084 let target = resolve_assert_target(haystack, &mut cx)?;
1085 handlers::assert_contains(
1086 &mut cx, idx, generation, idx, &target, needle,
1087 )
1088 }
1089 StepKind::WithIoBlock { .. } => {
1090 bail!("WITH_IO block should have been expanded during parsing")
1091 }
1092 StepKind::Exit(code) => {
1093 let code = super::args::resolve_arg_as_int(code, &mut cx)?;
1094 handlers::exit(&mut cx, code)
1095 }
1096 StepKind::Assign {
1097 var,
1098 decl_type,
1099 expr,
1100 } => handlers::assign(&mut cx, var, decl_type.clone(), expr),
1101 StepKind::Set { var, expr } => handlers::set_var_value(&mut cx, var, expr),
1102 StepKind::AssignAsync {
1103 var,
1104 decl_type,
1105 body,
1106 } => handlers::dispatch_assign_async(var, decl_type.clone(), body, &mut cx),
1107 StepKind::Await { var } => handlers::dispatch_await(var, &mut cx),
1108 StepKind::AwaitCapture {
1109 out_var,
1110 out_type,
1111 task_var,
1112 } => handlers::dispatch_await_capture(
1113 out_var,
1114 out_type.clone(),
1115 task_var,
1116 &mut cx,
1117 ),
1118 StepKind::Cancel { var } => handlers::dispatch_cancel(var, &mut cx),
1119 StepKind::Sleep { duration } => {
1120 let duration = super::args::resolve_arg_as_duration(duration, &mut cx)?;
1121 handlers::sleep(&mut cx, idx, &duration)
1122 }
1123 StepKind::FuncDef { .. }
1124 | StepKind::Call { .. }
1125 | StepKind::Return { .. }
1126 | StepKind::While { .. }
1127 | StepKind::Break
1128 | StepKind::Continue
1129 | StepKind::For { .. }
1130 | StepKind::If { .. }
1131 | StepKind::Timeout { .. }
1132 | StepKind::WithIo { .. }
1133 | StepKind::AssignCapture { .. } => {
1134 unreachable!("compound steps dispatch in the outer match")
1135 }
1136 }?;
1137 Ok(Flow::Done)
1138 }
1139 };
1140 flow_result
1141 };
1142
1143 let restore_result = restore_scopes(state, step.scope_exit);
1144 let expiry_drained = if let Some(expiry) = state.keeper_expiry.as_mut() {
1149 expiry.expire_step(steps, idx)
1150 } else {
1151 false
1152 };
1153 if expiry_drained {
1154 state.keeper_expiry = None;
1155 }
1156 let flow = flow_result?;
1157 restore_result?;
1158 match flow {
1159 Flow::Done => {}
1160 Flow::Break { .. } | Flow::Continue { .. } | Flow::Return { .. } => {
1161 return Ok(flow);
1162 }
1163 }
1164 }
1165
1166 let reap_named = !state.inside_async;
1174 let has_bg = !state.bg_children.is_empty();
1175 let named_pending = |state: &ExecState<P>| {
1176 reap_named
1177 && state
1178 .named_tasks
1179 .lock()
1180 .unwrap_or_else(|e| e.into_inner())
1181 .values()
1182 .any(|entry| !entry.state.lock().unwrap_or_else(|e| e.into_inner()).reaped)
1183 };
1184 let has_named = named_pending(state);
1185 if wait_at_end && (has_bg || has_named) {
1186 loop {
1187 let mut failed_status: Option<anyhow::Error> = None;
1188
1189 if failed_status.is_none() && state.cancel_token.load(Ordering::SeqCst) {
1194 failed_status = Some(anyhow::anyhow!("ASYNC task cancelled"));
1195 }
1196
1197 let mut i = 0;
1199 while i < state.bg_children.len() {
1200 match state.bg_children[i].try_wait() {
1201 Ok(Some(status)) => {
1202 if !status.success() && failed_status.is_none() {
1203 failed_status =
1204 Some(anyhow::anyhow!("ASYNC process exited with status {status}"));
1205 break;
1206 }
1207 state.bg_children.swap_remove(i);
1208 }
1209 Ok(None) => {
1210 i += 1;
1211 }
1212 Err(e) => {
1213 if failed_status.is_none() {
1214 failed_status = Some(e);
1215 }
1216 break;
1217 }
1218 }
1219 }
1220
1221 if failed_status.is_none() && reap_named {
1225 let entries: Vec<(u64, Arc<TaskEntry>)> = {
1226 let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1227 named
1228 .iter()
1229 .map(|(id, entry)| (*id, Arc::clone(entry)))
1230 .collect()
1231 };
1232 for (id, entry) in &entries {
1233 enum Poll {
1234 Pending,
1235 CompletedOk,
1236 CompletedErr(anyhow::Error),
1237 }
1238 let poll = {
1239 let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1240 match guard.phase {
1241 TaskPhase::Running | TaskPhase::Awaiting => {
1242 match guard.handle.as_mut() {
1243 Some(handle) => match handle.try_wait() {
1244 Ok(Some(status)) => {
1245 let _ = guard.handle.take();
1246 guard.phase = TaskPhase::Completed;
1247 if status.success() {
1248 Poll::CompletedOk
1249 } else {
1250 Poll::CompletedErr(anyhow::anyhow!(
1251 "named ASYNC task {id} exited with status {status}"
1252 ))
1253 }
1254 }
1255 Ok(None) => Poll::Pending,
1256 Err(e) => {
1257 let _ = guard.handle.take();
1258 guard.phase = TaskPhase::Completed;
1259 Poll::CompletedErr(e)
1260 }
1261 },
1262 None => Poll::Pending,
1265 }
1266 }
1267 TaskPhase::Cancelled | TaskPhase::Completed => Poll::Pending,
1268 }
1269 };
1270 match poll {
1271 Poll::Pending => {}
1272 Poll::CompletedOk => {
1273 entry.finish_teardown();
1274 }
1275 Poll::CompletedErr(e) => {
1276 entry.finish_teardown();
1277 if failed_status.is_none() {
1278 failed_status = Some(e);
1279 }
1280 break;
1281 }
1282 }
1283 }
1284 }
1285
1286 if let Some(err) = failed_status {
1291 for survivor in state.bg_children.iter_mut() {
1292 let _ = survivor.kill();
1293 }
1294 if reap_named {
1295 let entries: Vec<Arc<TaskEntry>> = {
1296 let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1297 named.values().cloned().collect()
1298 };
1299 let mut to_kill: Vec<(Arc<TaskEntry>, Box<dyn BackgroundHandle>)> = Vec::new();
1300 for entry in &entries {
1301 let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1302 match guard.phase {
1303 TaskPhase::Running | TaskPhase::Awaiting => {
1304 guard.phase = TaskPhase::Cancelled;
1305 if let Some(handle) = guard.handle.take() {
1306 to_kill.push((Arc::clone(entry), handle));
1307 }
1308 }
1309 TaskPhase::Cancelled | TaskPhase::Completed => {}
1310 }
1311 }
1312 for (entry, mut handle) in to_kill {
1313 let _ = handle.kill();
1314 entry.finish_teardown();
1315 }
1316 }
1317 state.bg_children.clear();
1318 return Err(err);
1319 }
1320
1321 let bg_empty = state.bg_children.is_empty();
1322 if bg_empty && !named_pending(state) {
1323 return Ok(Flow::Done);
1324 }
1325 if reap_named {
1329 let unreaped: Vec<Arc<TaskEntry>> = {
1330 let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1331 named
1332 .values()
1333 .filter(|entry| {
1334 let guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1335 matches!(guard.phase, TaskPhase::Cancelled) && !guard.reaped
1336 })
1337 .cloned()
1338 .collect()
1339 };
1340 for entry in &unreaped {
1341 entry.wait_reaped();
1342 }
1343 }
1344 std::thread::sleep(std::time::Duration::from_millis(10));
1345 }
1346 }
1347
1348 Ok(Flow::Done)
1349}
1350
1351fn restore_scopes<P: ProcessManager>(state: &mut ExecState<P>, count: usize) -> Result<()> {
1352 for _ in 0..count {
1353 state.pop_scope()?;
1354 }
1355 Ok(())
1356}
1357
1358#[allow(clippy::too_many_arguments)]
1365pub(super) fn execute_scoped_remote_body<P: ProcessManager>(
1366 state: &mut ExecState<P>,
1367 process: &mut P,
1368 steps: &[Step],
1369 stdin: CommandStdin,
1370 expose_stdin: bool,
1371 out: Option<StreamHandle>,
1372 err: Option<StreamHandle>,
1373 out_pipe: Option<Arc<PipeInner>>,
1374 stdin_pipe: Option<Arc<PipeInner>>,
1375) -> Result<()> {
1376 let flow = execute_scoped_steps(
1377 state,
1378 process,
1379 steps,
1380 stdin,
1381 expose_stdin,
1382 out,
1383 err,
1384 out_pipe,
1385 stdin_pipe,
1386 true,
1387 )?;
1388 match flow {
1389 Flow::Done => Ok(()),
1390 Flow::Break { idx } => {
1391 bail!("step {}: BREAK cannot cross a REMOTE boundary", idx + 1);
1392 }
1393 Flow::Continue { idx } => {
1394 bail!("step {}: CONTINUE cannot cross a REMOTE boundary", idx + 1);
1395 }
1396 Flow::Return { idx, .. } => {
1397 bail!("step {}: RETURN cannot cross a REMOTE boundary", idx + 1);
1398 }
1399 }
1400}
1401
1402#[allow(clippy::too_many_arguments)]
1407pub(super) fn execute_scoped_steps<P: ProcessManager>(
1408 state: &mut ExecState<P>,
1409 process: &mut P,
1410 steps: &[Step],
1411 stdin: CommandStdin,
1412 expose_stdin: bool,
1413 out: Option<StreamHandle>,
1414 err: Option<StreamHandle>,
1415 out_pipe: Option<Arc<PipeInner>>,
1416 stdin_pipe: Option<Arc<PipeInner>>,
1417 wait_at_end: bool,
1418) -> Result<Flow> {
1419 state.push_scope();
1420 let res = execute_steps(
1421 state,
1422 process,
1423 steps,
1424 stdin,
1425 expose_stdin,
1426 out,
1427 err,
1428 out_pipe,
1429 stdin_pipe,
1430 wait_at_end,
1431 );
1432 let pop_res = state.pop_scope();
1435 match (res, pop_res) {
1436 (Ok(flow), Ok(())) => Ok(flow),
1437 (Err(e), _) => Err(e),
1438 (Ok(_), Err(e)) => Err(e),
1439 }
1440}
1441
1442fn dispatch_flow_step<P: ProcessManager>(
1446 cmd: &StepKind,
1447 cx: &mut StepCtx<'_, P>,
1448 generation: usize,
1449 idx: usize,
1450) -> Result<Flow> {
1451 match cmd {
1452 StepKind::FuncDef { name, params, body } => {
1453 handlers::define_func(cx, name, params, body)?;
1454 Ok(Flow::Done)
1455 }
1456 StepKind::Call { name, args } => {
1457 let _ = handlers::call_func_value(cx, idx, name, args)?;
1458 Ok(Flow::Done)
1459 }
1460 StepKind::Return { expr } => handlers::handle_return(cx, idx, expr),
1461 StepKind::While { cond, body } => handlers::while_loop(cx, idx, cond, body),
1462 StepKind::Break => Ok(Flow::Break { idx }),
1463 StepKind::Continue => Ok(Flow::Continue { idx }),
1464 StepKind::For {
1465 key_var,
1466 key_type,
1467 var,
1468 var_type,
1469 in_expr,
1470 body,
1471 } => handlers::for_loop(
1472 cx,
1473 key_var.as_deref(),
1474 key_type.clone(),
1475 var,
1476 var_type.clone(),
1477 in_expr,
1478 body,
1479 ),
1480 StepKind::If {
1481 cond,
1482 then_body,
1483 else_ifs,
1484 else_body,
1485 } => handlers::if_then(cx, cond, then_body, else_ifs, else_body),
1486 StepKind::Timeout { duration, body } => {
1487 let duration = super::args::resolve_arg_as_duration(duration, cx)?;
1488 handlers::timeout(cx, idx, &duration, body)
1489 }
1490 StepKind::WithIo { bindings, cmd } => handlers::with_io(cx, generation, idx, bindings, cmd),
1491 StepKind::AssignCapture {
1492 var,
1493 decl_type,
1494 cmd,
1495 } => handlers::assign_capture(cx, generation, idx, var, decl_type.clone(), cmd),
1496 _ => {
1497 unreachable!("dispatch_flow_step handles only compound steps")
1498 }
1499 }
1500}