diff --git a/crates/vt/src/session/execute/mod.rs b/crates/vt/src/session/execute/mod.rs index f357fac85..a22623019 100644 --- a/crates/vt/src/session/execute/mod.rs +++ b/crates/vt/src/session/execute/mod.rs @@ -32,7 +32,7 @@ use vt_server::{Recorder, Reports, ServerHandle, StopAccepting, serve}; use self::{ glob::compute_globbed_inputs, pipe::{PipeSinks, StdOutput, pipe_stdio}, - spawn::{ChildHandle, ChildOutcome, SpawnStdio, spawn}, + spawn::{ChildOutcome, ChildWait, PipedChild, PipedMode, spawn_inherited, spawn_piped}, }; use super::{ cache::{ @@ -136,27 +136,18 @@ struct Tracking<'a> { stop_accepting: StopAccepting, } -/// The IPC server's handles for the run phase. The two halves are -/// inseparable — whenever the driver is polled, `stop_accepting` must be -/// signalled after the child exits or the driver never resolves — so they -/// travel as one value and a driver-without-signal state is unrepresentable. -struct IpcHandles<'m> { - /// Signalled after the child exits so the server stops accepting and - /// drains. - stop_accepting: &'m StopAccepting, - /// The server's driver, polled alongside the child. - driver: &'m mut IpcDriver, -} - -/// Mode-scoped borrows for the run phase, extracted in one pass so the pipe -/// sinks and the IPC handles can be borrowed simultaneously (disjoint fields -/// of the same mode). -struct RunHandles<'m> { - /// Pipe writers + capture slot. `None` only in the inherited-uncached - /// case, where there are no pipes to drain. - sinks: Option>, - /// The IPC server's handles. `None` iff execution is uncached. - ipc: Option>, +impl Tracking<'_> { + /// The extra envs to inject into the child: IPC connection info + the + /// napi addon path runner-aware tools `require()`. + fn injected_envs(&self) -> Vec<(&OsStr, &OsStr)> { + let mut envs: Vec<(&OsStr, &OsStr)> = + self.ipc_envs.iter().map(|(k, v)| (*k, v.as_os_str())).collect(); + envs.push(( + OsStr::new(NODE_CLIENT_PATH_ENV_NAME), + crate::napi_client::napi_client_path().as_path().as_os_str(), + )); + envs + } } impl<'a> ExecutionMode<'a> { @@ -213,60 +204,130 @@ impl<'a> ExecutionMode<'a> { }) } - /// The extra envs to inject into the child: IPC connection info + the - /// napi addon path runner-aware tools `require()`. Empty when execution - /// is uncached. - fn injected_envs(&self) -> Vec<(&OsStr, &OsStr)> { - match self { - Self::Cached { state: CacheState { tracking: t, .. }, .. } => { - let mut envs: Vec<(&OsStr, &OsStr)> = - t.ipc_envs.iter().map(|(k, v)| (*k, v.as_os_str())).collect(); - envs.push(( - OsStr::new(NODE_CLIENT_PATH_ENV_NAME), - crate::napi_client::napi_client_path().as_path().as_os_str(), - )); - envs - } - Self::Uncached { .. } => Vec::new(), - } - } - - /// The arguments `spawn()` derives from the mode: stdio handling and - /// whether fspy tracking is on. - const fn spawn_config(&self) -> (SpawnStdio, bool) { - match self { - Self::Cached { state, .. } => (SpawnStdio::Piped, state.tracking.fspy.is_some()), - Self::Uncached { pipe_writers: Some(_) } => (SpawnStdio::Piped, false), - Self::Uncached { pipe_writers: None } => (SpawnStdio::Inherited, false), - } - } - - /// Extract all mode-scoped borrows for the run phase in one pass: the - /// pipe sinks plus the IPC server's handles (disjoint field borrows - /// inside the same match arm). - fn run_handles(&mut self) -> RunHandles<'_> { + /// Phases 5 & 6: spawn the child process, drain its pipes (if piped), and + /// wait for exit — concurrently with the IPC driver when cached. + /// + /// Consumes `self` and returns a mode-typed [`RunOutcome`] so downstream + /// phases cannot pair an uncached run with IPC reports (or a cached run + /// without them). + async fn spawn_and_run( + self, + spawn_command: &vt_plan::SpawnCommand, + start: Instant, + fast_fail_token: &CancellationToken, + ) -> Result, ExecutionError> { match self { - Self::Cached { pipe_writers, state } => { - let sinks = Some(PipeSinks { + Self::Cached { mut pipe_writers, mut state } => { + let piped_mode = if state.tracking.fspy.is_some() { + PipedMode::Tracked + } else { + PipedMode::Plain + }; + let child = spawn_piped( + spawn_command, + piped_mode, + fast_fail_token.clone(), + state.tracking.injected_envs(), + ) + .await + .map_err(ExecutionError::Spawn)?; + tracing::debug!( + fspy = (piped_mode == PipedMode::Tracked), + elapsed = ?start.elapsed(), + "spawned the task process" + ); + + // The IPC driver must be polled during pipe drain — otherwise a + // tool doing a blocking `getEnv` can deadlock: child stalls on + // IPC, stdout stays open, pipe_stdio waits for EOF, driver + // never runs. `stop_accepting` fires right after child exit so + // the driver drains any in-flight clients. + // + // Box::pin keeps the child-and-pipe stack off the enclosing + // future: pipe_stdio alone makes the combined future large + // enough to trip clippy::large_futures in every caller. + let sinks = PipeSinks { stdout_writer: &mut pipe_writers.stdout_writer, stderr_writer: &mut pipe_writers.stderr_writer, capture: Some(&mut state.std_outputs), - }); - let ipc = Some(IpcHandles { - stop_accepting: &state.tracking.stop_accepting, - driver: &mut state.tracking.ipc_server_fut, - }); - RunHandles { sinks, ipc } + }; + let stop_accepting = &state.tracking.stop_accepting; + let child_work = async { + let result = + Box::pin(run_piped_child(child, sinks, fast_fail_token.clone())).await; + stop_accepting.signal(); + result + }; + let (wait_result, join_result) = + tokio::join!(child_work, &mut state.tracking.ipc_server_fut); + if let Err(e) = &join_result { + tracing::warn!(?e, "IPC server failed; cache will not be updated"); + } + Ok(RunOutcome::Cached { + state: Box::new(state), + outcome: wait_result?, + ipc_result: join_result.map(Recorder::into_reports), + }) } - Self::Uncached { pipe_writers: Some(pipe_writers) } => RunHandles { - sinks: Some(PipeSinks { + Self::Uncached { pipe_writers: Some(mut pipe_writers) } => { + let child = spawn_piped( + spawn_command, + PipedMode::Plain, + fast_fail_token.clone(), + std::iter::empty::<(&OsStr, &OsStr)>(), + ) + .await + .map_err(ExecutionError::Spawn)?; + tracing::debug!( + fspy = false, + elapsed = ?start.elapsed(), + "spawned the task process" + ); + + let sinks = PipeSinks { stdout_writer: &mut pipe_writers.stdout_writer, stderr_writer: &mut pipe_writers.stderr_writer, capture: None, - }), - ipc: None, - }, - Self::Uncached { pipe_writers: None } => RunHandles { sinks: None, ipc: None }, + }; + let child_work = Box::pin(run_piped_child(child, sinks, fast_fail_token.clone())); + Ok(RunOutcome::Uncached { outcome: child_work.await? }) + } + Self::Uncached { pipe_writers: None } => { + let child = spawn_inherited(spawn_command, fast_fail_token.clone()) + .map_err(ExecutionError::Spawn)?; + tracing::debug!( + fspy = false, + elapsed = ?start.elapsed(), + "spawned the task process" + ); + + // Measure post-spawn runtime for the exit debug log, matching + // `run_piped_child` rather than including spawn overhead. + Ok(RunOutcome::Uncached { outcome: wait_child(child.wait, Instant::now()).await? }) + } + } + } +} + +/// Mode-typed result of [`ExecutionMode::spawn_and_run`]. +/// +/// Couples `CacheState` and the IPC server's reports inside [`Self::Cached`] so +/// cached-without-IPC and uncached-with-IPC states are unrepresentable. +enum RunOutcome<'a> { + Cached { + state: Box>, + outcome: ChildOutcome, + ipc_result: Result, + }, + Uncached { + outcome: ChildOutcome, + }, +} + +impl RunOutcome<'_> { + const fn exit_status(&self) -> std::process::ExitStatus { + match self { + Self::Cached { outcome, .. } | Self::Uncached { outcome } => outcome.exit_status, } } } @@ -337,9 +398,9 @@ impl SpawnReport { /// the time it ends, nothing else happens. /// 2. `leaf_reporter.start(&cache_status)` → `StdioConfig` /// 3. If cache hit: replay cached outputs via `StdioConfig` writers -/// 4. Otherwise: `spawn()` with the chosen stdio mode, drain pipes and wait -/// via [`run_child`], then decide the cache update -/// ([`cache_update::update_cache`]) +/// 4. Otherwise: spawn the child with the chosen stdio/tracking mode, drain +/// pipes (if piped) and wait via [`ExecutionMode::spawn_and_run`], then +/// decide the cache update ([`cache_update::update_cache`]) /// /// A dry run (`RunKind::Dry`) only looks: the lookup in step 1 writes /// nothing, and steps 3 and 4 are skipped. @@ -484,110 +545,73 @@ async fn run( }; // 4. Fold the cache/fspy/stdio decisions into the typed mode. - let mut mode = match ExecutionMode::build(cache_metadata, stdio_config, globbed_inputs) { + let mode = match ExecutionMode::build(cache_metadata, stdio_config, globbed_inputs) { Ok(mode) => mode, Err(err) => return Err(spawn_err(spawn_cache_status, err)), }; - // Measure end-to-end duration here — spawn() doesn't track time. + // Measure end-to-end duration here — spawn doesn't track time. let start = Instant::now(); - // 5. Spawn. Returns pipes (Piped) or `None` (Inherited) plus a - // cancellation-aware wait future. - let (spawn_stdio, fspy_enabled) = mode.spawn_config(); - let child = match spawn( - &spawn_execution.spawn_command, - fspy_enabled, - spawn_stdio, - fast_fail_token.clone(), - mode.injected_envs(), - ) - .await - { - Ok(child) => child, - Err(err) => return Err(spawn_err(spawn_cache_status, ExecutionError::Spawn(err))), - }; - tracing::debug!(fspy = fspy_enabled, elapsed = ?start.elapsed(), "spawned the task process"); - - // 6. Drain the pipes and wait for exit, concurrently with the IPC driver. - // The driver must be polled during pipe drain — otherwise a tool doing - // a blocking `getEnv` can deadlock: child stalls on IPC, stdout stays - // open, pipe_stdio waits for EOF, driver never runs. `stop_accepting` - // fires after child.wait so the driver drains any in-flight clients. - // Box::pin keeps the child-and-pipe stack off the enclosing future: - // pipe_stdio alone makes the combined future large enough to trip - // clippy::large_futures in every caller otherwise. - let RunHandles { sinks, ipc } = mode.run_handles(); - let (wait_result, ipc_server_result) = if let Some(IpcHandles { stop_accepting, driver }) = ipc - { - let child_work = - Box::pin(run_child(child, sinks, Some(stop_accepting), fast_fail_token.clone())); - let (wait_result, join_result) = tokio::join!(child_work, driver); - if let Err(e) = &join_result { - tracing::warn!(?e, "IPC server failed; cache will not be updated"); - } - (wait_result, Some(join_result.map(Recorder::into_reports))) - } else { - let child_work = Box::pin(run_child(child, sinks, None, fast_fail_token.clone())); - (child_work.await, None) - }; - let outcome = match wait_result { - Ok(outcome) => outcome, - Err(err) => return Err(spawn_err(spawn_cache_status, err)), - }; + // 5 & 6. Spawn the child, drain pipes (if piped), and wait for exit + // (concurrently with the IPC driver when cached). + let run_outcome = + match mode.spawn_and_run(&spawn_execution.spawn_command, start, &fast_fail_token).await { + Ok(result) => result, + Err(err) => return Err(spawn_err(spawn_cache_status, err)), + }; let duration = start.elapsed(); // Non-zero exit: cache is never updated. - if !outcome.exit_status.success() { + let exit_status = run_outcome.exit_status(); + if !exit_status.success() { return Ok(SpawnReport::Spawned { cache_status: spawn_cache_status, - outcome: SpawnLeafOutcome::Failed { - exit_code: non_zero_exit_code(outcome.exit_status), - }, + outcome: SpawnLeafOutcome::Failed { exit_code: non_zero_exit_code(exit_status) }, }); } - // Extract reports, or short-circuit when the IPC server failed. An Err - // here means reports may be incomplete: caching this run would risk - // stale inputs/outputs, so skip all cache-related computation entirely. - let reports: Option = match ipc_server_result { - Some(Ok(reports)) => { - tracing::debug!(?reports, "runner-aware tools reported"); - Some(reports) - } - None => None, - Some(Err(err)) => { - return Ok(SpawnReport::Spawned { - cache_status: spawn_cache_status, - outcome: SpawnLeafOutcome::Success { - cache_update: CacheUpdateOutcome::NotUpdated( - CacheNotUpdatedReason::IpcServerError(err), - ), - }, - }); - } - }; - // 7. Decide the cache update (only when we were in `Cached` mode). Cache // update errors do not affect `SpawnOutcome` or fast-fail (the process // exited 0, so we report `SpawnedSuccess`), though the summary reporter // still turns post-run cache errors into a non-zero run exit code. - let cache_update = match mode { - ExecutionMode::Cached { state, .. } => { + let cache_update = match run_outcome { + RunOutcome::Cached { state, outcome, ipc_result } => { + #[cfg(not(fspy))] + let _ = outcome; + // Extract reports, or short-circuit when the IPC server failed. An + // Err here means reports may be incomplete: caching this run would + // risk stale inputs/outputs, so skip all cache-related computation. + let reports = match ipc_result { + Ok(reports) => { + tracing::debug!(?reports, "runner-aware tools reported"); + reports + } + Err(err) => { + return Ok(SpawnReport::Spawned { + cache_status: spawn_cache_status, + outcome: SpawnLeafOutcome::Success { + cache_update: CacheUpdateOutcome::NotUpdated( + CacheNotUpdatedReason::IpcServerError(err), + ), + }, + }); + } + }; cache_update::update_cache( cache, workspace_root, cache_dir, - state, + *state, #[cfg(fspy)] outcome.path_accesses.as_ref(), - reports.as_ref(), + Some(&reports), duration, &cancel_token, ) .await } - ExecutionMode::Uncached { .. } => { + RunOutcome::Uncached { .. } => { // Caching was disabled for this task. CacheUpdateOutcome::NotUpdated(CacheNotUpdatedReason::CacheDisabled) } @@ -727,53 +751,46 @@ async fn replay_cache_hit( } } -/// Phase 6: drain the child's pipes (if piped) and wait for exit. A pipe -/// failure cancels the child so the wait future kills it instead of orphaning -/// it. After the child exits (on every path), `stop_accepting` is signalled so -/// the IPC server stops accepting and starts draining. -async fn run_child( - mut child: ChildHandle, - sinks: Option>, - stop_accepting: Option<&StopAccepting>, +/// Wait for an already-spawned child to exit and log its exit status. +async fn wait_child(wait: ChildWait, start: Instant) -> Result { + let wait_result = wait.await.map_err(|err| ExecutionError::WaitForTaskProcessExit(err.into())); + if let Ok(outcome) = &wait_result { + tracing::debug!( + success = outcome.exit_status.success(), + exit_code = outcome.exit_status.code(), + elapsed = ?start.elapsed(), + "the task process exited" + ); + } + wait_result +} + +/// Phase 6 (piped): drain the child's stdout/stderr pipes and wait for exit. +/// A pipe failure cancels the child so the wait future kills it instead of +/// orphaning it. +async fn run_piped_child( + child: PipedChild, + sinks: PipeSinks<'_>, fast_fail_token: CancellationToken, ) -> Result { let start = Instant::now(); - let pipe_result: Result<(), ExecutionError> = if let Some(sinks) = sinks { - let stdout = child.stdout.take().expect("SpawnStdio::Piped yields a stdout pipe"); - let stderr = child.stderr.take().expect("SpawnStdio::Piped yields a stderr pipe"); - #[expect( - clippy::large_futures, - reason = "pipe_stdio streams child I/O and creates a large future" - )] - let r = pipe_stdio(stdout, stderr, sinks, fast_fail_token.clone()).await; - r.map_err(|err| ExecutionError::ForwardTaskProcessOutput(err.into())) - } else { - Ok(()) - }; + #[expect( + clippy::large_futures, + reason = "pipe_stdio streams child I/O and creates a large future" + )] + let pipe_result = + pipe_stdio(child.pipes.stdout, child.pipes.stderr, sinks, fast_fail_token.clone()) + .await + .map_err(|err| ExecutionError::ForwardTaskProcessOutput(err.into())); - let wait_result = match pipe_result { - Ok(()) => { - child.wait.await.map_err(|err| ExecutionError::WaitForTaskProcessExit(err.into())) - } + match pipe_result { + Ok(()) => wait_child(child.wait, start).await, Err(err) => { // Pipe failed — cancel so `child.wait` kills the child instead of - // orphaning it. Still signal the server below so it can drain. + // orphaning it. fast_fail_token.cancel(); let _ = child.wait.await; Err(err) } - }; - - if let Some(stop_accepting) = stop_accepting { - stop_accepting.signal(); } - if let Ok(outcome) = &wait_result { - tracing::debug!( - success = outcome.exit_status.success(), - exit_code = outcome.exit_status.code(), - elapsed = ?start.elapsed(), - "the task process exited" - ); - } - wait_result } diff --git a/crates/vt/src/session/execute/spawn.rs b/crates/vt/src/session/execute/spawn.rs index 7e2abb59e..c925f7320 100644 --- a/crates/vt/src/session/execute/spawn.rs +++ b/crates/vt/src/session/execute/spawn.rs @@ -1,9 +1,13 @@ //! Unified spawn abstraction over fspy and plain tokio processes. //! -//! [`spawn`] does one thing: hand back the child's stdio pipes plus a -//! cancellation-aware `wait` future. Draining the pipes is [`super::pipe`]'s -//! job; normalizing fspy path accesses is [`super::tracked_accesses`]'s (only -//! compiled when `cfg(fspy)` is on). +//! Two entry points enforce valid stdio/tracking combinations at compile time: +//! - [`spawn_piped`] pipes stdout/stderr (optionally under fspy tracing) and +//! returns [`PipedChild`] with coupled [`ChildPipes`]. +//! - [`spawn_inherited`] inherits stdio directly (never fspy-tracked) and +//! returns [`InheritedChild`] with no pipes. +//! +//! Draining pipes is [`super::pipe`]'s job; normalizing fspy path accesses is +//! [`super::tracked_accesses`]'s (only compiled when `cfg(fspy)` is on). use std::{ffi::OsStr, io, process::Stdio}; @@ -14,87 +18,126 @@ use tokio::process::{ChildStderr, ChildStdout}; use tokio_util::sync::CancellationToken; use vt_plan::SpawnCommand; -/// How the child's stdin/stdout/stderr are configured. +/// Whether a piped child runs under fspy filesystem tracing. +/// +/// Inherited stdio cannot be combined with fspy tracing, so tracking is only +/// accepted by [`spawn_piped`]. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum SpawnStdio { - /// All three fds inherited from the parent. On Unix, [`spawn`] also clears - /// `FD_CLOEXEC` on fds 0-2 (libuv workaround — - /// ). - Inherited, - /// stdin is `/dev/null`; stdout and stderr are piped. Drain the pipes with - /// [`super::pipe::pipe_stdio`]. - Piped, +pub enum PipedMode { + /// Plain tokio process without filesystem tracing. + Plain, + /// Tracked with fspy when `cfg(fspy)` is enabled; falls back to a plain + /// tokio process on targets without `cfg(fspy)`. + Tracked, } -/// Handle to a spawned child. +/// Coupled stdout/stderr pipes from a piped child process. /// -/// `stdout` and `stderr` are `Some` iff [`SpawnStdio::Piped`] was requested. -/// `wait` resolves when the child exits and handles cancellation internally: -/// when the token fires, the child (and on Windows its descendants via the Job -/// Object) is killed before the future resolves. -pub struct ChildHandle { - pub stdout: Option, - pub stderr: Option, - pub wait: LocalBoxFuture<'static, io::Result>, +/// Both pipes are always created together, so half-piped states are +/// unrepresentable. +pub struct ChildPipes { + pub stdout: ChildStdout, + pub stderr: ChildStderr, +} + +/// Cancellation-aware future resolving when the child exits. +/// +/// When the cancellation token fires, the child (and on Windows its +/// descendants via the Job Object) is killed before the future resolves. +pub type ChildWait = LocalBoxFuture<'static, io::Result>; + +/// Handle to a child spawned with piped stdout/stderr. +pub struct PipedChild { + pub pipes: ChildPipes, + pub wait: ChildWait, +} + +/// Handle to a child spawned with inherited stdio. +pub struct InheritedChild { + pub wait: ChildWait, } /// Result of waiting for a child to exit. pub struct ChildOutcome { pub exit_status: std::process::ExitStatus, - /// Raw fspy accesses. `Some` iff `fspy` was `true` at spawn time, and + /// Raw fspy accesses. `Some` iff spawned with [`PipedMode::Tracked`], and /// `Err` when a tracked process could not record everything it did. #[cfg(fspy)] pub path_accesses: Option>, } -/// Spawn a command with the requested fspy and stdio configuration. +/// Spawn a command with piped stdout/stderr (`stdin` set to `/dev/null`) and +/// optional fspy filesystem tracking. /// /// `extra_envs` are applied **after** `cmd.spawn_envs`, so runtime-injected /// entries (e.g. the runner's IPC name + napi addon path) override any /// same-named key from the plan. /// -/// Cancellation is unified: whether fspy is enabled or not, the returned `wait` -/// future observes `cancellation_token` and kills the child before resolving. +/// Cancellation is unified: whether fspy is enabled or not, the returned +/// [`PipedChild::wait`] future observes `cancellation_token` and kills the +/// child before resolving. /// -/// On builds without `cfg(fspy)`, the `fspy` argument is ignored and the tokio -/// path is always taken. +/// On builds without `cfg(fspy)`, [`PipedMode::Tracked`] falls back to the +/// plain tokio path. #[tracing::instrument(level = "debug", skip_all)] -pub async fn spawn( +pub async fn spawn_piped( cmd: &SpawnCommand, - fspy: bool, - stdio: SpawnStdio, + mode: PipedMode, cancellation_token: CancellationToken, extra_envs: E, -) -> anyhow::Result +) -> anyhow::Result where E: IntoIterator, K: AsRef, V: AsRef, { #[cfg(fspy)] - if fspy { - return spawn_fspy(cmd, stdio, cancellation_token, extra_envs).await; + if mode == PipedMode::Tracked { + return spawn_fspy(cmd, cancellation_token, extra_envs).await; } #[cfg(not(fspy))] - let _ = fspy; + let _ = mode; - let mut tokio_cmd = tokio::process::Command::new(cmd.program_path.as_path()); - tokio_cmd.args(cmd.args.iter().map(vt_str::Str::as_str)); - tokio_cmd.env_clear(); - tokio_cmd.envs(cmd.spawn_envs.iter()); - tokio_cmd.envs(extra_envs); - tokio_cmd.current_dir(&*cmd.cwd); - apply_stdio(&mut tokio_cmd, stdio); - spawn_tokio(tokio_cmd, cancellation_token) + let mut tokio_cmd = build_tokio_command(cmd, extra_envs); + tokio_cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()); + let mut child = tokio_cmd.spawn()?; + let pipes = take_pipes(&mut child.stdout, &mut child.stderr); + let wait = spawn_tokio_wait(child, cancellation_token)?; + Ok(PipedChild { pipes, wait }) +} + +/// Spawn a command with stdin/stdout/stderr inherited from the parent. +/// +/// Inherited spawns never run under fspy tracking. On Unix, this also clears +/// `FD_CLOEXEC` on fds 0-2 (libuv workaround — +/// ). +#[tracing::instrument(level = "debug", skip_all)] +pub fn spawn_inherited( + cmd: &SpawnCommand, + cancellation_token: CancellationToken, +) -> anyhow::Result { + let mut tokio_cmd = build_tokio_command(cmd, std::iter::empty::<(&OsStr, &OsStr)>()); + tokio_cmd.stdin(Stdio::inherit()).stdout(Stdio::inherit()).stderr(Stdio::inherit()); + // libuv (used by Node.js) marks stdin/stdout/stderr as close-on-exec; + // without this fix the child reopens fds 0-2 as /dev/null after exec. + // See: https://github.com/libuv/libuv/issues/2062 + // SAFETY: the pre_exec closure only performs fcntl operations on + // stdio fds, which is safe in a post-fork context. + #[cfg(unix)] + unsafe { + tokio_cmd.pre_exec(clear_stdio_cloexec); + } + let child = tokio_cmd.spawn()?; + let wait = spawn_tokio_wait(child, cancellation_token)?; + Ok(InheritedChild { wait }) } #[cfg(fspy)] async fn spawn_fspy( cmd: &SpawnCommand, - stdio: SpawnStdio, cancellation_token: CancellationToken, extra_envs: E, -) -> anyhow::Result +) -> anyhow::Result where E: IntoIterator, K: AsRef, @@ -105,24 +148,7 @@ where fspy_cmd.envs(cmd.spawn_envs.iter()); fspy_cmd.envs(extra_envs); fspy_cmd.current_dir(&*cmd.cwd); - - match stdio { - SpawnStdio::Inherited => { - fspy_cmd.stdin(Stdio::inherit()).stdout(Stdio::inherit()).stderr(Stdio::inherit()); - // libuv (used by Node.js) marks stdin/stdout/stderr as close-on-exec; - // without this fix the child reopens fds 0-2 as /dev/null after exec. - // See: https://github.com/libuv/libuv/issues/2062 - // SAFETY: the pre_exec closure only performs fcntl operations on - // stdio fds, which is safe in a post-fork context. - #[cfg(unix)] - unsafe { - fspy_cmd.pre_exec(clear_stdio_cloexec); - } - } - SpawnStdio::Piped => { - fspy_cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()); - } - } + fspy_cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()); let mut tracked = fspy_cmd.spawn(cancellation_token).await?; @@ -134,8 +160,7 @@ where super::win_job::assign_to_kill_on_close_job(tracked.process_handle.as_raw_handle())? }; - let stdout = tracked.stdout.take(); - let stderr = tracked.stderr.take(); + let pipes = take_pipes(&mut tracked.stdout, &mut tracked.stderr); let wait_handle = tracked.wait_handle; let wait = async move { @@ -152,15 +177,42 @@ where } .boxed_local(); - Ok(ChildHandle { stdout, stderr, wait }) + Ok(PipedChild { pipes, wait }) } -fn spawn_tokio( - mut cmd: tokio::process::Command, - cancellation_token: CancellationToken, -) -> anyhow::Result { - let mut child = cmd.spawn()?; +const fn take_pipes( + stdout: &mut Option, + stderr: &mut Option, +) -> ChildPipes { + ChildPipes { + stdout: stdout.take().expect("stdout was configured as Stdio::piped()"), + stderr: stderr.take().expect("stderr was configured as Stdio::piped()"), + } +} +fn build_tokio_command(cmd: &SpawnCommand, extra_envs: E) -> tokio::process::Command +where + E: IntoIterator, + K: AsRef, + V: AsRef, +{ + let mut tokio_cmd = tokio::process::Command::new(cmd.program_path.as_path()); + tokio_cmd.args(cmd.args.iter().map(vt_str::Str::as_str)); + tokio_cmd.env_clear(); + tokio_cmd.envs(cmd.spawn_envs.iter()); + tokio_cmd.envs(extra_envs); + tokio_cmd.current_dir(&*cmd.cwd); + tokio_cmd +} + +#[cfg_attr( + not(windows), + expect(clippy::unnecessary_wraps, reason = "Windows job object assignment is fallible") +)] +fn spawn_tokio_wait( + mut child: tokio::process::Child, + cancellation_token: CancellationToken, +) -> anyhow::Result { #[cfg(windows)] let job = { use std::os::windows::io::{AsRawHandle, BorrowedHandle}; @@ -171,9 +223,6 @@ fn spawn_tokio( super::win_job::assign_to_kill_on_close_job(owned.as_raw_handle())? }; - let stdout = child.stdout.take(); - let stderr = child.stderr.take(); - let wait = async move { let exit_status = tokio::select! { status = child.wait() => status?, @@ -196,27 +245,7 @@ fn spawn_tokio( } .boxed_local(); - Ok(ChildHandle { stdout, stderr, wait }) -} - -fn apply_stdio(cmd: &mut tokio::process::Command, stdio: SpawnStdio) { - match stdio { - SpawnStdio::Inherited => { - cmd.stdin(Stdio::inherit()).stdout(Stdio::inherit()).stderr(Stdio::inherit()); - // libuv (used by Node.js) marks stdin/stdout/stderr as close-on-exec; - // without this fix the child reopens fds 0-2 as /dev/null after exec. - // See: https://github.com/libuv/libuv/issues/2062 - // SAFETY: the pre_exec closure only performs fcntl operations on - // stdio fds, which is safe in a post-fork context. - #[cfg(unix)] - unsafe { - cmd.pre_exec(clear_stdio_cloexec); - } - } - SpawnStdio::Piped => { - cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()); - } - } + Ok(wait) } #[cfg(unix)]