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