Skip to main content

merry_process/process_runner/
tokio_runner.rs

1use super::{
2    background::BackgroundSupervisor,
3    env_isolation::ProcessEnvIsolation,
4    environment::{process_current_dir, validate_environment_name, validate_os_string},
5    execution::run_spawned_process,
6};
7use merry_runtime::{
8    BackgroundProcessControl, ProcessActionIntent, ProcessRunner, ProcessRunnerContext,
9    ProcessRunnerError, ProcessRunnerFuture,
10};
11use std::{
12    collections::BTreeSet,
13    ffi::OsString,
14    path::{Path, PathBuf},
15    sync::Arc,
16};
17
18/// Host-process runner backed by [`tokio::process::Command`].
19///
20/// The runner executes the exact validated argv supplied by
21/// [`ProcessActionIntent`], inherits the current process environment minus
22/// variables excluded by [`ProcessEnvIsolation`] (`MERRY_*` by default), closes
23/// stdin, captures bounded stdout/stderr through the shared process IO path,
24/// and cooperatively cancels by killing the child process. Permission profiles
25/// and sandbox constraints are selected by the owning backend, not by this
26/// executor.
27#[derive(Debug, Default, Clone)]
28pub struct TokioProcessRunner {
29    cwd_root: Option<PathBuf>,
30    environment_overrides: Vec<(OsString, OsString)>,
31    env_isolation: ProcessEnvIsolation,
32    background: BackgroundSupervisor,
33}
34
35impl TokioProcessRunner {
36    /// Creates a Tokio-backed process runner.
37    #[must_use]
38    pub fn new() -> Self {
39        Self {
40            cwd_root: None,
41            environment_overrides: Vec::new(),
42            env_isolation: ProcessEnvIsolation::default(),
43            background: BackgroundSupervisor::new(),
44        }
45    }
46
47    /// Creates a Tokio-backed process runner whose process cwd values are
48    /// resolved under a stable workspace root.
49    #[must_use]
50    pub fn new_at_workspace_root(root: impl Into<PathBuf>) -> Self {
51        Self {
52            cwd_root: Some(root.into()),
53            environment_overrides: Vec::new(),
54            env_isolation: ProcessEnvIsolation::default(),
55            background: BackgroundSupervisor::new(),
56        }
57    }
58
59    pub(crate) fn with_background(mut self, background: BackgroundSupervisor) -> Self {
60        self.background = background;
61        self
62    }
63
64    /// Sets the environment isolation policy applied before spawning child
65    /// processes.
66    pub fn with_env_isolation(
67        mut self,
68        env_isolation: ProcessEnvIsolation,
69    ) -> Result<Self, ProcessRunnerError> {
70        env_isolation.validate_overrides(&self.environment_overrides)?;
71        self.env_isolation = env_isolation;
72        Ok(self)
73    }
74
75    /// Validates and applies environment assignments while preserving all
76    /// other non-isolated variables inherited from the Merry process.
77    pub fn with_environment_overrides(
78        mut self,
79        overrides: impl IntoIterator<Item = (OsString, OsString)>,
80    ) -> Result<Self, ProcessRunnerError> {
81        let mut names = BTreeSet::new();
82        let mut validated = Vec::new();
83        for (name, value) in overrides {
84            validate_environment_name(&name)?;
85            validate_os_string(&value, "host process environment value")?;
86            if !names.insert(name.clone()) {
87                return Err(ProcessRunnerError::infrastructure(
88                    "host process environment contains a duplicate variable",
89                ));
90            }
91            validated.push((name, value));
92        }
93        self.env_isolation.validate_overrides(&validated)?;
94        self.environment_overrides = validated;
95        Ok(self)
96    }
97}
98
99impl ProcessRunner for TokioProcessRunner {
100    fn run<'a>(
101        &'a self,
102        intent: ProcessActionIntent,
103        context: ProcessRunnerContext,
104    ) -> ProcessRunnerFuture<'a> {
105        let cwd_root = self.cwd_root.clone();
106        let environment_overrides = self.environment_overrides.clone();
107        let env_isolation = self.env_isolation.clone();
108        let background = self.background.clone();
109        Box::pin(async move {
110            run_tokio_process(
111                intent,
112                context,
113                cwd_root.as_deref(),
114                &environment_overrides,
115                &env_isolation,
116                background,
117            )
118            .await
119        })
120    }
121
122    fn background_control(&self) -> Option<Arc<dyn BackgroundProcessControl>> {
123        Some(Arc::new(self.background.clone()))
124    }
125}
126
127async fn run_tokio_process(
128    intent: ProcessActionIntent,
129    context: ProcessRunnerContext,
130    cwd_root: Option<&Path>,
131    environment_overrides: &[(OsString, OsString)],
132    env_isolation: &ProcessEnvIsolation,
133    background: BackgroundSupervisor,
134) -> Result<merry_runtime::ProcessRunnerOutput, ProcessRunnerError> {
135    let Some((program, args)) = intent.argv().split_first() else {
136        return Err(ProcessRunnerError::infrastructure(
137            "validated process argv was unexpectedly empty",
138        ));
139    };
140    let program = program.clone();
141    let program_for_error = program.clone();
142    let args = args.to_vec();
143
144    if context.cancellation_token().is_cancelled() {
145        return Err(ProcessRunnerError::Cancelled);
146    }
147
148    let mut command = tokio::process::Command::new(&program);
149    #[cfg(windows)]
150    let args = prepare_windows_spawn_command(&mut command, &program, args);
151    env_isolation.apply_to_tokio_command(&mut command);
152    command
153        .args(&args)
154        .current_dir(process_current_dir(cwd_root, &intent))
155        .envs(
156            environment_overrides
157                .iter()
158                .map(|(name, value)| (name, value)),
159        )
160        .stdin(std::process::Stdio::null())
161        .stdout(std::process::Stdio::piped())
162        .stderr(std::process::Stdio::piped())
163        .kill_on_drop(true);
164
165    run_spawned_process(command, intent, context, program_for_error, background).await
166}
167
168/// Applies Windows-specific UTF-8 and shell-invocation defaults before caller
169/// environment overrides so `intent.argv()` stays untainted for classification,
170/// permissions, and trajectory logging.
171#[cfg(windows)]
172fn prepare_windows_spawn_command(
173    command: &mut tokio::process::Command,
174    program: &str,
175    mut args: Vec<String>,
176) -> Vec<String> {
177    // Prevent Python/CLI tools from falling back to legacy Windows ANSI codepages.
178    command
179        .env("PYTHONUTF8", "1")
180        .env("PYTHONIOENCODING", "utf-8:surrogateescape");
181
182    let lower = program
183        .rsplit(['/', '\\'])
184        .next()
185        .unwrap_or(program)
186        .to_ascii_lowercase();
187
188    // Disable MSYS2 path conversion when invoking Git Bash so `/flag` arguments
189    // for native Windows toolchains (MSBuild, cl.exe) pass through unchanged.
190    if lower == "bash" || lower == "bash.exe" {
191        command
192            .env("MSYS_NO_PATHCONV", "1")
193            .env("MSYS2_ARG_CONV_EXCL", "*");
194        return args;
195    }
196
197    // Force UTF-8 console output for PowerShell piped stdout/stderr without
198    // modifying `$LASTEXITCODE`.
199    if matches!(
200        lower.as_str(),
201        "powershell" | "powershell.exe" | "pwsh" | "pwsh.exe"
202    ) && let Some(command_index) = args
203        .iter()
204        .position(|arg| arg.eq_ignore_ascii_case("-Command"))
205        && let Some(script) = args.get_mut(command_index + 1)
206    {
207        const UTF8_PREAMBLE: &str = "$OutputEncoding = [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false; ";
208        if !script.starts_with(UTF8_PREAMBLE) {
209            script.insert_str(0, UTF8_PREAMBLE);
210        }
211    }
212
213    args
214}