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 {
778 StepKind::FuncDef { .. }
779 | StepKind::Call { .. }
780 | StepKind::Return { .. }
781 | StepKind::ImportFile { .. }
782 | StepKind::ImportFuncs { .. }
783 | StepKind::While { .. }
784 | StepKind::Break
785 | StepKind::Continue
786 | StepKind::For { .. }
787 | StepKind::If { .. }
788 | StepKind::Timeout { .. }
789 | StepKind::Isolated { .. }
790 | StepKind::WithIo { .. }
791 | StepKind::AssignCapture { .. } => {
792 return dispatch_flow_step(cmd, &mut cx, generation, idx);
793 }
794 _ => {}
795 }
796 match cmd {
797 StepKind::Run(arg) => {
798 let cmd = super::args::resolve_arg(arg, &mut cx)?;
799 let cmd = super::args::expand_dsl_vars(&cmd, cx.state)?;
800 handlers::run(&mut cx, &cmd)
801 }
802 StepKind::RunExec { argv } => {
803 let resolved = handlers::resolve_run_exec_argv(argv, &mut cx)?;
804 handlers::run_argv(&mut cx, &resolved)
805 }
806 StepKind::Echo(arg) => {
807 let msg = super::args::resolve_arg(arg, &mut cx)?;
808 handlers::echo(&mut cx, &msg)
809 }
810 StepKind::AsyncBlock { .. } => handlers::dispatch_async_block(cmd, &mut cx),
811 StepKind::Workdir(arg) => {
812 let path = super::args::resolve_arg(arg, &mut cx)?;
813 handlers::workdir(&mut cx, &path)
814 }
815 StepKind::Workspace(target) => handlers::workspace(&mut cx, target),
816 StepKind::RemoteBlock {
817 target,
818 vars,
819 env,
820 body,
821 } => super::remote::run_remote_block(&mut cx, target, vars, env, body),
822 StepKind::Env { key, value } => {
823 let resolved = super::args::resolve_arg(value, &mut cx)?;
824 handlers::env(&mut cx, key, &resolved)
825 }
826 StepKind::InheritEnv { keys } => {
827 handlers::inherit_env(&mut cx, keys)?;
828 sync_iteration_assert_needles(
829 cx.state,
830 &[Step {
831 guard: None,
832 kind: cmd.clone(),
833 scope_enter: 0,
834 scope_exit: 0,
835 line: 0,
836 col: 0,
837 }],
838 generation,
839 )?;
840 Ok(())
841 }
842 StepKind::IsolatedInheritEnv { keys } => {
843 handlers::isolated_inherit_env(&mut cx, keys)?;
844 Ok(())
845 }
846 StepKind::Copy {
847 from_workspace,
848 from_host,
849 to_host,
850 from,
851 to,
852 } => {
853 if *from_host || *to_host {
854 super::remote::copy_transfer(&mut cx, *from_host, *to_host, from, to)
855 } else {
856 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
857 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
858 handlers::copy(
859 &mut cx,
860 from_workspace.clone(),
861 &from_resolved,
862 &to_resolved,
863 )
864 }
865 }
866 StepKind::CopyGit {
867 rev,
868 from,
869 to,
870 include_dirty,
871 } => {
872 let rev_resolved = super::args::resolve_arg(rev, &mut cx)?;
873 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
874 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
875 handlers::copy_git(
876 &mut cx,
877 &rev_resolved,
878 &from_resolved,
879 &to_resolved,
880 *include_dirty,
881 )
882 }
883 StepKind::Archive { src, dst, raw } => {
884 let src_resolved = super::args::resolve_arg(src, &mut cx)?;
885 let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
886 handlers::archive(&mut cx, &src_resolved, &dst_resolved, *raw)
887 }
888 StepKind::Unarchive {
889 src,
890 dst,
891 max_bytes,
892 } => {
893 let src_resolved = super::args::resolve_arg(src, &mut cx)?;
894 let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
895 let cap_resolved = super::args::resolve_arg_opt(max_bytes, &mut cx)?;
896 handlers::unarchive(
897 &mut cx,
898 &src_resolved,
899 &dst_resolved,
900 cap_resolved.as_deref(),
901 )
902 }
903 StepKind::Symlink {
904 from_workspace,
905 from,
906 to,
907 } => {
908 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
909 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
910 handlers::symlink(
911 &mut cx,
912 from_workspace.clone(),
913 &from_resolved,
914 &to_resolved,
915 )
916 }
917 StepKind::Mkdir(arg) => {
918 let path = super::args::resolve_arg(arg, &mut cx)?;
919 handlers::mkdir(&mut cx, &path)
920 }
921 StepKind::Install { from, to } => {
922 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
923 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
924 handlers::install(&mut cx, &from_resolved, &to_resolved)
925 }
926 StepKind::SetExecutable { path } => {
927 let resolved = super::args::resolve_arg(path, &mut cx)?;
928 handlers::set_executable(&mut cx, &resolved)
929 }
930 StepKind::Ls(arg) => {
931 let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
932 handlers::ls(&mut cx, &resolved)
933 }
934 StepKind::Read(arg) => {
935 let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
936 handlers::read(&mut cx, &resolved)
937 }
938 StepKind::ReadLine { var } => handlers::read_line(&mut cx, var),
939 StepKind::Prompt {
940 var,
941 message,
942 default,
943 } => {
944 let message_resolved = super::args::resolve_arg(message, &mut cx)?;
945 let default_resolved = match default {
946 Some(d) => Some(super::args::resolve_arg(d, &mut cx)?),
947 None => None,
948 };
949 handlers::prompt(&mut cx, var, &message_resolved, default_resolved.as_deref())
950 }
951 StepKind::ListAppend { list, item } => {
952 let value = super::args::evaluate_assert_operand(item, &mut cx)?;
953 handlers::push_into(&mut cx, list, value)
954 }
955 StepKind::Write { path, contents } => {
956 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
957 let contents_resolved = super::args::resolve_arg_opt(contents, &mut cx)?;
958 handlers::write(&mut cx, &path_resolved, contents_resolved.as_deref())
959 }
960 StepKind::Append { path, contents } => {
961 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
962 let contents_resolved = super::args::resolve_arg_opt(contents, &mut cx)?;
963 handlers::append(&mut cx, &path_resolved, contents_resolved.as_deref())
964 }
965 StepKind::AppendLine { path, contents } => {
966 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
967 let contents_resolved = super::args::resolve_arg(contents, &mut cx)?;
968 handlers::append_line(&mut cx, &path_resolved, &contents_resolved)
969 }
970 StepKind::Remove { path, recursive } => {
971 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
972 handlers::remove(&mut cx, &path_resolved, *recursive)
973 }
974 StepKind::Expand { path, overrides } => {
975 let path_resolved = super::args::resolve_arg_opt(path, &mut cx)?;
976 let overrides_resolved = super::args::resolve_overrides(overrides, &mut cx)?;
977 handlers::replace(&mut cx, &path_resolved, &overrides_resolved)
978 }
979 StepKind::AssertEq {
980 hash,
981 actual,
982 expected,
983 }
984 | StepKind::AssertNe {
985 hash,
986 actual,
987 expected,
988 } => {
989 let (verb, expect_equal) = match cmd {
990 StepKind::AssertEq { .. } => (Command::AssertEq.as_str(), true),
991 _ => (Command::AssertNe.as_str(), false),
992 };
993 let target = resolve_assert_target(actual, &mut cx)?;
994 let expected_resolved = match expected {
995 Some(e) => Some(super::args::evaluate_assert_operand(e, &mut cx)?),
996 None => None,
997 };
998 handlers::assert_equality(
999 &mut cx,
1000 generation,
1001 verb,
1002 expect_equal,
1003 hash,
1004 &target,
1005 expected_resolved.as_ref(),
1006 )
1007 }
1008 StepKind::AssertContains { haystack, needle } => {
1009 let target = resolve_assert_target(haystack, &mut cx)?;
1010 handlers::assert_contains(&mut cx, generation, idx, &target, needle)
1011 }
1012 StepKind::WithIoBlock { .. } => {
1013 bail!("WITH_IO block should have been expanded during parsing")
1014 }
1015 StepKind::Exit(code) => {
1016 let code = super::args::resolve_arg_as_int(code, &mut cx)?;
1017 handlers::exit(&mut cx, code)
1018 }
1019 StepKind::Assign {
1020 var,
1021 decl_type,
1022 expr,
1023 } => handlers::assign(&mut cx, var, decl_type.clone(), expr),
1024 StepKind::Set { var, expr } => handlers::set_var_value(&mut cx, var, expr),
1025 StepKind::AssignAsync {
1026 var,
1027 decl_type,
1028 body,
1029 } => handlers::dispatch_assign_async(var, decl_type.clone(), body, &mut cx),
1030 StepKind::Await { var } => handlers::dispatch_await(var, &mut cx),
1031 StepKind::AwaitCapture {
1032 out_var,
1033 out_type,
1034 task_var,
1035 } => handlers::dispatch_await_capture(out_var, out_type.clone(), task_var, &mut cx),
1036 StepKind::Cancel { var } => handlers::dispatch_cancel(var, &mut cx),
1037 StepKind::Sleep { duration } => {
1038 let duration = super::args::resolve_arg_as_duration(duration, &mut cx)?;
1039 handlers::sleep(&mut cx, &duration)
1040 }
1041 StepKind::TypeAlias { .. } => {
1042 Ok(())
1045 }
1046 StepKind::FuncDef { .. }
1047 | StepKind::Call { .. }
1048 | StepKind::Return { .. }
1049 | StepKind::ImportFile { .. }
1050 | StepKind::ImportFuncs { .. }
1051 | StepKind::While { .. }
1052 | StepKind::Break
1053 | StepKind::Continue
1054 | StepKind::For { .. }
1055 | StepKind::If { .. }
1056 | StepKind::Timeout { .. }
1057 | StepKind::Isolated { .. }
1058 | StepKind::WithIo { .. }
1059 | StepKind::AssignCapture { .. } => {
1060 unreachable!("compound steps dispatch before this match")
1061 }
1062 }?;
1063 Ok(Flow::Done)
1064}
1065
1066#[allow(clippy::too_many_arguments)]
1067fn step_error(step: &Step, idx: usize, err: anyhow::Error) -> anyhow::Error {
1073 let mut loc = format!("step {}", idx + 1);
1074 if step.line > 0 {
1075 loc.push_str(&format!(", line {}", step.line));
1076 if step.col > 0 {
1077 loc.push_str(&format!(", col {}", step.col));
1078 }
1079 }
1080 err.context(loc)
1081}
1082
1083struct InnerArgs<'a, P: ProcessManager> {
1087 state: &'a mut ExecState<P>,
1088 process: &'a mut P,
1089 generation: usize,
1090 steps: &'a [Step],
1091 stdin: CommandStdin,
1092 expose_stdin: bool,
1093 out: Option<StreamHandle>,
1094 err: Option<StreamHandle>,
1095 out_pipe: Option<Arc<PipeInner>>,
1096 stdin_pipe: Option<Arc<PipeInner>>,
1097 wait_at_end: bool,
1098}
1099
1100fn execute_steps_inner<P: ProcessManager>(args: InnerArgs<'_, P>) -> Result<Flow> {
1101 let InnerArgs {
1102 state,
1103 process,
1104 generation,
1105 steps,
1106 stdin,
1107 expose_stdin,
1108 out,
1109 err,
1110 out_pipe,
1111 stdin_pipe,
1112 wait_at_end,
1113 } = args;
1114 pre_register_assertions(state, steps, generation)?;
1116
1117 for (idx, step) in steps.iter().enumerate() {
1118 if state.cancel_token.load(Ordering::SeqCst) {
1120 bail!("ASYNC task cancelled");
1121 }
1122 if step.scope_enter > 0 {
1123 for _ in 0..step.scope_enter {
1124 state.push_scope();
1125 }
1126 }
1127
1128 let should_run = guard_option_allows(step.guard.as_ref(), &state.envs);
1129 let flow_result: Result<Flow> = (|| {
1133 if !should_run {
1134 Ok(Flow::Done)
1135 } else {
1136 let mut cx = StepCtx {
1137 state,
1138 process,
1139 stdin: stdin.clone(),
1140 expose_stdin,
1141 out: out.clone(),
1142 err: err.clone(),
1143 out_pipe: out_pipe.clone(),
1144 stdin_pipe: stdin_pipe.clone(),
1145 tty: None,
1146 };
1147 let flow_result: Result<Flow> = match &step.kind {
1150 StepKind::FuncDef { .. }
1151 | StepKind::Call { .. }
1152 | StepKind::Return { .. }
1153 | StepKind::ImportFile { .. }
1154 | StepKind::ImportFuncs { .. }
1155 | StepKind::While { .. }
1156 | StepKind::Break
1157 | StepKind::Continue
1158 | StepKind::For { .. }
1159 | StepKind::If { .. }
1160 | StepKind::Timeout { .. }
1161 | StepKind::Isolated { .. }
1162 | StepKind::WithIo { .. }
1163 | StepKind::AssignCapture { .. } => {
1164 dispatch_flow_step(&step.kind, &mut cx, generation, idx)
1165 }
1166 _ => {
1167 match &step.kind {
1168 StepKind::InheritEnv { keys } => {
1169 handlers::inherit_env(&mut cx, keys)?;
1170 sync_iteration_assert_needles(cx.state, steps, generation)?;
1171 Ok(())
1172 }
1173 StepKind::IsolatedInheritEnv { keys } => {
1174 handlers::isolated_inherit_env(&mut cx, keys)?;
1175 Ok(())
1176 }
1177 StepKind::Workdir(arg) => {
1178 let path = super::args::resolve_arg(arg, &mut cx)?;
1179 handlers::workdir(&mut cx, &path)
1180 }
1181 StepKind::Workspace(target) => handlers::workspace(&mut cx, target),
1182 StepKind::RemoteBlock {
1183 target,
1184 vars,
1185 env,
1186 body,
1187 } => super::remote::run_remote_block(&mut cx, target, vars, env, body),
1188 StepKind::Env { key, value } => {
1189 let resolved = super::args::resolve_arg(value, &mut cx)?;
1190 handlers::env(&mut cx, key, &resolved)?;
1191 sync_iteration_assert_needles(cx.state, steps, generation)?;
1192 Ok(())
1193 }
1194 StepKind::Run(arg) => {
1195 let cmd = super::args::resolve_arg(arg, &mut cx)?;
1196 let cmd = super::args::expand_dsl_vars(&cmd, cx.state)?;
1197 handlers::run(&mut cx, &cmd)
1198 }
1199 StepKind::RunExec { argv } => {
1200 let resolved = handlers::resolve_run_exec_argv(argv, &mut cx)?;
1201 handlers::run_argv(&mut cx, &resolved)
1202 }
1203 StepKind::Echo(arg) => {
1204 let msg = super::args::resolve_arg(arg, &mut cx)?;
1205 handlers::echo(&mut cx, &msg)
1206 }
1207 StepKind::AsyncBlock { .. } => {
1208 handlers::dispatch_async_block(&step.kind, &mut cx)
1209 }
1210 StepKind::Copy {
1211 from_workspace,
1212 from_host,
1213 to_host,
1214 from,
1215 to,
1216 } => {
1217 if *from_host || *to_host {
1218 super::remote::copy_transfer(
1219 &mut cx, *from_host, *to_host, from, to,
1220 )
1221 } else {
1222 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1223 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1224 handlers::copy(
1225 &mut cx,
1226 from_workspace.clone(),
1227 &from_resolved,
1228 &to_resolved,
1229 )
1230 }
1231 }
1232 StepKind::CopyGit {
1233 rev,
1234 from,
1235 to,
1236 include_dirty,
1237 } => {
1238 let rev_resolved = super::args::resolve_arg(rev, &mut cx)?;
1239 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1240 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1241 handlers::copy_git(
1242 &mut cx,
1243 &rev_resolved,
1244 &from_resolved,
1245 &to_resolved,
1246 *include_dirty,
1247 )
1248 }
1249 StepKind::Archive { src, dst, raw } => {
1250 let src_resolved = super::args::resolve_arg(src, &mut cx)?;
1251 let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
1252 handlers::archive(&mut cx, &src_resolved, &dst_resolved, *raw)
1253 }
1254 StepKind::Unarchive {
1255 src,
1256 dst,
1257 max_bytes,
1258 } => {
1259 let src_resolved = super::args::resolve_arg(src, &mut cx)?;
1260 let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
1261 let cap_resolved =
1262 super::args::resolve_arg_opt(max_bytes, &mut cx)?;
1263 handlers::unarchive(
1264 &mut cx,
1265 &src_resolved,
1266 &dst_resolved,
1267 cap_resolved.as_deref(),
1268 )
1269 }
1270 StepKind::Symlink {
1271 from_workspace,
1272 from,
1273 to,
1274 } => {
1275 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1276 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1277 handlers::symlink(
1278 &mut cx,
1279 from_workspace.clone(),
1280 &from_resolved,
1281 &to_resolved,
1282 )
1283 }
1284 StepKind::Mkdir(arg) => {
1285 let path = super::args::resolve_arg(arg, &mut cx)?;
1286 handlers::mkdir(&mut cx, &path)
1287 }
1288 StepKind::Install { from, to } => {
1289 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1290 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1291 handlers::install(&mut cx, &from_resolved, &to_resolved)
1292 }
1293 StepKind::SetExecutable { path } => {
1294 let resolved = super::args::resolve_arg(path, &mut cx)?;
1295 handlers::set_executable(&mut cx, &resolved)
1296 }
1297 StepKind::Ls(arg) => {
1298 let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
1299 handlers::ls(&mut cx, &resolved)
1300 }
1301 StepKind::Read(arg) => {
1302 let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
1303 handlers::read(&mut cx, &resolved)
1304 }
1305 StepKind::ReadLine { var } => handlers::read_line(&mut cx, var),
1306 StepKind::Prompt {
1307 var,
1308 message,
1309 default,
1310 } => {
1311 let message_resolved = super::args::resolve_arg(message, &mut cx)?;
1312 let default_resolved = match default {
1313 Some(d) => Some(super::args::resolve_arg(d, &mut cx)?),
1314 None => None,
1315 };
1316 handlers::prompt(
1317 &mut cx,
1318 var,
1319 &message_resolved,
1320 default_resolved.as_deref(),
1321 )
1322 }
1323 StepKind::ListAppend { list, item } => {
1324 let value = super::args::evaluate_assert_operand(item, &mut cx)?;
1325 handlers::push_into(&mut cx, list, value)
1326 }
1327 StepKind::Write { path, contents } => {
1328 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1329 let contents_resolved =
1330 super::args::resolve_arg_opt(contents, &mut cx)?;
1331 handlers::write(
1332 &mut cx,
1333 &path_resolved,
1334 contents_resolved.as_deref(),
1335 )
1336 }
1337 StepKind::Append { path, contents } => {
1338 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1339 let contents_resolved =
1340 super::args::resolve_arg_opt(contents, &mut cx)?;
1341 handlers::append(
1342 &mut cx,
1343 &path_resolved,
1344 contents_resolved.as_deref(),
1345 )
1346 }
1347 StepKind::AppendLine { path, contents } => {
1348 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1349 let contents_resolved =
1350 super::args::resolve_arg(contents, &mut cx)?;
1351 handlers::append_line(&mut cx, &path_resolved, &contents_resolved)
1352 }
1353 StepKind::Remove { path, recursive } => {
1354 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1355 handlers::remove(&mut cx, &path_resolved, *recursive)
1356 }
1357 StepKind::Expand { path, overrides } => {
1358 let path_resolved = super::args::resolve_arg_opt(path, &mut cx)?;
1359 let overrides_resolved =
1360 super::args::resolve_overrides(overrides, &mut cx)?;
1361 handlers::replace(&mut cx, &path_resolved, &overrides_resolved)
1362 }
1363 StepKind::AssertEq {
1364 hash,
1365 actual,
1366 expected,
1367 }
1368 | StepKind::AssertNe {
1369 hash,
1370 actual,
1371 expected,
1372 } => {
1373 let (verb, expect_equal) = match &step.kind {
1374 StepKind::AssertEq { .. } => (Command::AssertEq.as_str(), true),
1375 _ => (Command::AssertNe.as_str(), false),
1376 };
1377 let target = resolve_assert_target(actual, &mut cx)?;
1378 let expected_resolved = match expected {
1379 Some(e) => {
1380 Some(super::args::evaluate_assert_operand(e, &mut cx)?)
1381 }
1382 None => None,
1383 };
1384 handlers::assert_equality(
1385 &mut cx,
1386 generation,
1387 verb,
1388 expect_equal,
1389 hash,
1390 &target,
1391 expected_resolved.as_ref(),
1392 )
1393 }
1394 StepKind::AssertContains { haystack, needle } => {
1395 let target = resolve_assert_target(haystack, &mut cx)?;
1396 handlers::assert_contains(&mut cx, generation, idx, &target, needle)
1397 }
1398 StepKind::WithIoBlock { .. } => {
1399 bail!("WITH_IO block should have been expanded during parsing")
1400 }
1401 StepKind::Exit(code) => {
1402 let code = super::args::resolve_arg_as_int(code, &mut cx)?;
1403 handlers::exit(&mut cx, code)
1404 }
1405 StepKind::Assign {
1406 var,
1407 decl_type,
1408 expr,
1409 } => handlers::assign(&mut cx, var, decl_type.clone(), expr),
1410 StepKind::Set { var, expr } => {
1411 handlers::set_var_value(&mut cx, var, expr)
1412 }
1413 StepKind::AssignAsync {
1414 var,
1415 decl_type,
1416 body,
1417 } => handlers::dispatch_assign_async(
1418 var,
1419 decl_type.clone(),
1420 body,
1421 &mut cx,
1422 ),
1423 StepKind::Await { var } => handlers::dispatch_await(var, &mut cx),
1424 StepKind::AwaitCapture {
1425 out_var,
1426 out_type,
1427 task_var,
1428 } => handlers::dispatch_await_capture(
1429 out_var,
1430 out_type.clone(),
1431 task_var,
1432 &mut cx,
1433 ),
1434 StepKind::Cancel { var } => handlers::dispatch_cancel(var, &mut cx),
1435 StepKind::Sleep { duration } => {
1436 let duration =
1437 super::args::resolve_arg_as_duration(duration, &mut cx)?;
1438 handlers::sleep(&mut cx, &duration)
1439 }
1440 StepKind::TypeAlias { .. } => {
1441 Ok(())
1444 }
1445 StepKind::FuncDef { .. }
1446 | StepKind::Call { .. }
1447 | StepKind::Return { .. }
1448 | StepKind::ImportFile { .. }
1449 | StepKind::ImportFuncs { .. }
1450 | StepKind::While { .. }
1451 | StepKind::Break
1452 | StepKind::Continue
1453 | StepKind::For { .. }
1454 | StepKind::If { .. }
1455 | StepKind::Timeout { .. }
1456 | StepKind::Isolated { .. }
1457 | StepKind::WithIo { .. }
1458 | StepKind::AssignCapture { .. } => {
1459 unreachable!("compound steps dispatch in the outer match")
1460 }
1461 }?;
1462 Ok(Flow::Done)
1463 }
1464 };
1465 flow_result
1466 }
1467 })()
1468 .map_err(|err| step_error(step, idx, err));
1469
1470 let restore_result = restore_scopes(state, step.scope_exit);
1471 let expiry_drained = if let Some(expiry) = state.keeper_expiry.as_mut() {
1476 expiry.expire_step(steps, idx)
1477 } else {
1478 false
1479 };
1480 if expiry_drained {
1481 state.keeper_expiry = None;
1482 }
1483 let flow = flow_result?;
1484 restore_result?;
1485 match flow {
1486 Flow::Done => {}
1487 Flow::Break { .. } | Flow::Continue { .. } | Flow::Return { .. } => {
1488 return Ok(flow);
1489 }
1490 }
1491 }
1492
1493 let reap_named = !state.inside_async;
1501 let floor = state.reap_floor;
1506 let in_scope = |id: u64| floor.map(|f| id >= f).unwrap_or(true);
1507 let has_bg = state.bg_children.iter().any(|c| in_scope(c.task_id));
1508 let named_pending = |state: &ExecState<P>| {
1509 reap_named
1510 && state
1511 .named_tasks
1512 .lock()
1513 .unwrap_or_else(|e| e.into_inner())
1514 .iter()
1515 .any(|(id, entry)| {
1516 in_scope(*id) && !entry.state.lock().unwrap_or_else(|e| e.into_inner()).reaped
1517 })
1518 };
1519 let has_named = named_pending(state);
1520 if wait_at_end && (has_bg || has_named) {
1521 loop {
1522 let mut failed_status: Option<anyhow::Error> = None;
1523
1524 if failed_status.is_none() && state.cancel_token.load(Ordering::SeqCst) {
1529 failed_status = Some(anyhow::anyhow!("ASYNC task cancelled"));
1530 }
1531
1532 let mut i = 0;
1536 while i < state.bg_children.len() {
1537 if !in_scope(state.bg_children[i].task_id) {
1538 i += 1;
1539 continue;
1540 }
1541 match state.bg_children[i].handle.try_wait() {
1542 Ok(Some(status)) => {
1543 if !status.success() && failed_status.is_none() {
1544 failed_status =
1545 Some(anyhow::anyhow!("ASYNC process exited with status {status}"));
1546 break;
1547 }
1548 state.bg_children.swap_remove(i);
1549 }
1550 Ok(None) => {
1551 i += 1;
1552 }
1553 Err(e) => {
1554 if failed_status.is_none() {
1555 failed_status = Some(e);
1556 }
1557 break;
1558 }
1559 }
1560 }
1561
1562 if failed_status.is_none() && reap_named {
1566 let entries: Vec<(u64, Arc<TaskEntry>)> = {
1567 let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1568 named
1569 .iter()
1570 .map(|(id, entry)| (*id, Arc::clone(entry)))
1571 .collect()
1572 };
1573 for (id, entry) in &entries {
1574 if !in_scope(*id) {
1575 continue;
1576 }
1577 enum Poll {
1578 Pending,
1579 CompletedOk,
1580 CompletedErr(anyhow::Error),
1581 }
1582 let poll = {
1583 let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1584 match guard.phase {
1585 TaskPhase::Running | TaskPhase::Awaiting => {
1586 match guard.handle.as_mut() {
1587 Some(handle) => match handle.try_wait() {
1588 Ok(Some(status)) => {
1589 let _ = guard.handle.take();
1590 guard.phase = TaskPhase::Completed;
1591 if status.success() {
1592 Poll::CompletedOk
1593 } else {
1594 Poll::CompletedErr(anyhow::anyhow!(
1595 "named ASYNC task {id} exited with status {status}"
1596 ))
1597 }
1598 }
1599 Ok(None) => Poll::Pending,
1600 Err(e) => {
1601 let _ = guard.handle.take();
1602 guard.phase = TaskPhase::Completed;
1603 Poll::CompletedErr(e)
1604 }
1605 },
1606 None => Poll::Pending,
1609 }
1610 }
1611 TaskPhase::Cancelled | TaskPhase::Completed => Poll::Pending,
1612 }
1613 };
1614 match poll {
1615 Poll::Pending => {}
1616 Poll::CompletedOk => {
1617 entry.finish_teardown();
1618 }
1619 Poll::CompletedErr(e) => {
1620 entry.finish_teardown();
1621 if failed_status.is_none() {
1622 failed_status = Some(e);
1623 }
1624 break;
1625 }
1626 }
1627 }
1628 }
1629
1630 if let Some(err) = failed_status {
1635 for survivor in state.bg_children.iter_mut() {
1636 if in_scope(survivor.task_id) {
1637 let _ = survivor.handle.kill();
1638 }
1639 }
1640 if reap_named {
1641 let entries: Vec<(u64, Arc<TaskEntry>)> = {
1642 let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1643 named
1644 .iter()
1645 .map(|(id, entry)| (*id, Arc::clone(entry)))
1646 .collect()
1647 };
1648 let mut to_kill: Vec<(Arc<TaskEntry>, Box<dyn BackgroundHandle>)> = Vec::new();
1649 for (id, entry) in &entries {
1650 if !in_scope(*id) {
1651 continue;
1652 }
1653 let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1654 match guard.phase {
1655 TaskPhase::Running | TaskPhase::Awaiting => {
1656 guard.phase = TaskPhase::Cancelled;
1657 if let Some(handle) = guard.handle.take() {
1658 to_kill.push((Arc::clone(entry), handle));
1659 }
1660 }
1661 TaskPhase::Cancelled | TaskPhase::Completed => {}
1662 }
1663 }
1664 for (entry, mut handle) in to_kill {
1665 let _ = handle.kill();
1666 entry.finish_teardown();
1667 }
1668 }
1669 state.bg_children.retain(|c| !in_scope(c.task_id));
1673 return Err(err);
1674 }
1675
1676 let bg_empty = !state.bg_children.iter().any(|c| in_scope(c.task_id));
1677 if bg_empty && !named_pending(state) {
1678 return Ok(Flow::Done);
1679 }
1680 if reap_named {
1684 let unreaped: Vec<Arc<TaskEntry>> = {
1685 let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1686 named
1687 .iter()
1688 .filter(|(id, entry)| {
1689 if !in_scope(**id) {
1690 return false;
1691 }
1692 let guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1693 matches!(guard.phase, TaskPhase::Cancelled) && !guard.reaped
1694 })
1695 .map(|(_, entry)| Arc::clone(entry))
1696 .collect()
1697 };
1698 for entry in &unreaped {
1699 entry.wait_reaped();
1700 }
1701 }
1702 std::thread::sleep(std::time::Duration::from_millis(10));
1703 }
1704 }
1705
1706 Ok(Flow::Done)
1707}
1708
1709fn restore_scopes<P: ProcessManager>(state: &mut ExecState<P>, count: usize) -> Result<()> {
1710 for _ in 0..count {
1711 state.pop_scope()?;
1712 }
1713 Ok(())
1714}
1715
1716#[allow(clippy::too_many_arguments)]
1723pub(super) fn execute_scoped_remote_body<P: ProcessManager>(
1724 state: &mut ExecState<P>,
1725 process: &mut P,
1726 steps: &[Step],
1727 stdin: CommandStdin,
1728 expose_stdin: bool,
1729 out: Option<StreamHandle>,
1730 err: Option<StreamHandle>,
1731 out_pipe: Option<Arc<PipeInner>>,
1732 stdin_pipe: Option<Arc<PipeInner>>,
1733) -> Result<()> {
1734 let flow = execute_scoped_steps(
1735 state,
1736 process,
1737 steps,
1738 stdin,
1739 expose_stdin,
1740 out,
1741 err,
1742 out_pipe,
1743 stdin_pipe,
1744 true,
1745 )?;
1746 match flow {
1747 Flow::Done => Ok(()),
1748 Flow::Break { idx } => {
1749 bail!("step {}: BREAK cannot cross a REMOTE boundary", idx + 1);
1750 }
1751 Flow::Continue { idx } => {
1752 bail!("step {}: CONTINUE cannot cross a REMOTE boundary", idx + 1);
1753 }
1754 Flow::Return { idx, .. } => {
1755 bail!("step {}: RETURN cannot cross a REMOTE boundary", idx + 1);
1756 }
1757 }
1758}
1759
1760#[allow(clippy::too_many_arguments)]
1765pub(super) fn execute_scoped_steps<P: ProcessManager>(
1766 state: &mut ExecState<P>,
1767 process: &mut P,
1768 steps: &[Step],
1769 stdin: CommandStdin,
1770 expose_stdin: bool,
1771 out: Option<StreamHandle>,
1772 err: Option<StreamHandle>,
1773 out_pipe: Option<Arc<PipeInner>>,
1774 stdin_pipe: Option<Arc<PipeInner>>,
1775 wait_at_end: bool,
1776) -> Result<Flow> {
1777 state.push_scope();
1778 let res = execute_steps(
1779 state,
1780 process,
1781 steps,
1782 stdin,
1783 expose_stdin,
1784 out,
1785 err,
1786 out_pipe,
1787 stdin_pipe,
1788 wait_at_end,
1789 );
1790 let pop_res = state.pop_scope();
1793 match (res, pop_res) {
1794 (Ok(flow), Ok(())) => Ok(flow),
1795 (Err(e), _) => Err(e),
1796 (Ok(_), Err(e)) => Err(e),
1797 }
1798}
1799
1800fn dispatch_flow_step<P: ProcessManager>(
1804 cmd: &StepKind,
1805 cx: &mut StepCtx<'_, P>,
1806 generation: usize,
1807 idx: usize,
1808) -> Result<Flow> {
1809 match cmd {
1810 StepKind::FuncDef {
1811 name, params, body, ..
1812 } => {
1813 handlers::define_func(cx, name, params, body)?;
1814 Ok(Flow::Done)
1815 }
1816 StepKind::Call { name, args } => {
1817 let _ = handlers::call_func_value(cx, name, args)?;
1818 Ok(Flow::Done)
1819 }
1820 StepKind::Return { expr } => handlers::handle_return(cx, idx, expr),
1821 StepKind::ImportFile { path, alias } => {
1822 let _ = super::import::import_file(cx, path, alias)?;
1823 Ok(Flow::Done)
1824 }
1825 StepKind::ImportFuncs {
1826 path,
1827 alias,
1828 func_names,
1829 type_names,
1830 } => {
1831 super::import::import_funcs(cx, path, alias.as_deref(), func_names, type_names)?;
1832 Ok(Flow::Done)
1833 }
1834 StepKind::While { cond, body } => handlers::while_loop(cx, cond, body),
1835 StepKind::Break => Ok(Flow::Break { idx }),
1836 StepKind::Continue => Ok(Flow::Continue { idx }),
1837 StepKind::For {
1838 key_var,
1839 key_type,
1840 var,
1841 var_type,
1842 in_expr,
1843 body,
1844 } => handlers::for_loop(
1845 cx,
1846 key_var.as_deref(),
1847 key_type.clone(),
1848 var,
1849 var_type.clone(),
1850 in_expr,
1851 body,
1852 ),
1853 StepKind::If {
1854 cond,
1855 then_body,
1856 else_ifs,
1857 else_body,
1858 } => handlers::if_then(cx, cond, then_body, else_ifs, else_body),
1859 StepKind::Timeout { duration, body } => {
1860 let duration = super::args::resolve_arg_as_duration(duration, cx)?;
1861 handlers::timeout(cx, &duration, body)
1862 }
1863 StepKind::Isolated { body } => handlers::isolated(cx, body),
1864 StepKind::WithIo { bindings, cmd } => handlers::with_io(cx, generation, idx, bindings, cmd),
1865 StepKind::AssignCapture {
1866 var,
1867 decl_type,
1868 cmd,
1869 } => handlers::assign_capture(cx, generation, idx, var, decl_type.clone(), cmd),
1870 _ => {
1871 unreachable!("dispatch_flow_step handles only compound steps")
1872 }
1873 }
1874}