Skip to main content

oxdock_process/
contract.rs

1use std::collections::HashMap;
2
3use anyhow::Result;
4use oxdock_fs::{CargoScratch, GuardedPath, PolicyPath};
5#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
6use std::process::ExitStatus;
7
8use std::sync::Arc;
9
10use crate::diagnostics as proc_diag;
11
12// Shared-IO handles and take-once OS pipe halves live in `oxdock-pipe`
13// (leaf crate, no cycle); re-exported here so every existing
14// `oxdock_process::` path keeps resolving. The OS items keep their
15// `not(miri)` gates: kernel pipes are compiled out under Miri isolation.
16#[cfg(not(miri))]
17pub use oxdock_pipe::{OsPipeReader, OsPipeWriter, create_os_pipe};
18pub use oxdock_pipe::{SharedInput, SharedOutput};
19
20/// Context passed to process managers describing the current execution
21/// environment. Clones are cheap and explicit so background handles can own
22/// their working roots without juggling lifetimes.
23#[derive(Clone, Debug)]
24pub struct CommandContext {
25    cwd: PolicyPath,
26    envs: Arc<HashMap<String, String>>,
27    cargo_target_dir: CargoScratch,
28    workspace_root: GuardedPath,
29    build_context: GuardedPath,
30}
31
32impl CommandContext {
33    pub fn new(
34        cwd: &PolicyPath,
35        envs: Arc<HashMap<String, String>>,
36        cargo_target_dir: &CargoScratch,
37        workspace_root: &GuardedPath,
38        build_context: &GuardedPath,
39    ) -> Self {
40        Self {
41            cwd: cwd.clone(),
42            envs,
43            cargo_target_dir: cargo_target_dir.clone(),
44            workspace_root: workspace_root.clone(),
45            build_context: build_context.clone(),
46        }
47    }
48
49    /// Convenience constructor cloning a plain map into a fresh `Arc`.
50    pub fn from_map(
51        cwd: &PolicyPath,
52        envs: &HashMap<String, String>,
53        cargo_target_dir: &CargoScratch,
54        workspace_root: &GuardedPath,
55        build_context: &GuardedPath,
56    ) -> Self {
57        Self::new(
58            cwd,
59            Arc::new(envs.clone()),
60            cargo_target_dir,
61            workspace_root,
62            build_context,
63        )
64    }
65
66    pub fn cwd(&self) -> &PolicyPath {
67        &self.cwd
68    }
69
70    pub fn envs(&self) -> &Arc<HashMap<String, String>> {
71        &self.envs
72    }
73
74    pub fn cargo_target_dir(&self) -> &CargoScratch {
75        &self.cargo_target_dir
76    }
77
78    pub fn workspace_root(&self) -> &GuardedPath {
79        &self.workspace_root
80    }
81
82    pub fn build_context(&self) -> &GuardedPath {
83        &self.build_context
84    }
85}
86
87/// Handle for background processes spawned by a [`ProcessManager`].
88pub trait BackgroundHandle: Send {
89    fn try_wait(&mut self) -> Result<Option<ExitStatus>>;
90    fn kill(&mut self) -> Result<()>;
91    fn wait(&mut self) -> Result<ExitStatus>;
92}
93
94#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
95pub enum CommandMode {
96    #[default]
97    Foreground,
98    Background,
99}
100
101#[derive(Clone, Default)]
102pub enum CommandStdout {
103    #[default]
104    Inherit,
105    Stream(SharedOutput),
106    Capture,
107    /// Direct OS kernel pipe writer for concurrent pipelines. Single use:
108    /// the handle is taken on spawn and the parent retains no copy, so the
109    /// reader observes EOF once the producer exits. Only valid with
110    /// concurrently spawned consumers (`ASYNC`); never for sequential steps.
111    #[cfg(not(miri))]
112    OsPipe(OsPipeWriter),
113}
114
115#[derive(Clone, Default)]
116pub enum CommandStdin {
117    /// Isolated null stdin. Preserves the previous `None` behavior.
118    #[default]
119    Null,
120    Inherit,
121    Stream(SharedInput),
122    /// Direct OS kernel pipe reader for concurrent pipelines. See
123    /// [`CommandStdout::OsPipe`] for the single use contract.
124    #[cfg(not(miri))]
125    OsPipe(OsPipeReader),
126}
127
128impl From<Option<SharedInput>> for CommandStdin {
129    fn from(stdin: Option<SharedInput>) -> Self {
130        match stdin {
131            Some(reader) => CommandStdin::Stream(reader),
132            None => CommandStdin::Null,
133        }
134    }
135}
136
137impl CommandStdin {
138    /// Whether stdin is bound to a virtual pipe (`WITH_IO [stdin=...]`).
139    /// A redirected stdin can never answer an interactive prompt, so
140    /// terminal-facing steps treat this as non-interactive even when
141    /// the host process itself owns a TTY.
142    pub fn is_redirected(&self) -> bool {
143        match self {
144            CommandStdin::Stream(_) => true,
145            #[cfg(not(miri))]
146            CommandStdin::OsPipe(_) => true,
147            CommandStdin::Null | CommandStdin::Inherit => false,
148        }
149    }
150}
151
152#[derive(Clone, Default)]
153pub enum CommandStderr {
154    #[default]
155    Inherit,
156    Stream(SharedOutput),
157    /// Direct OS kernel pipe writer, mirroring [`CommandStdout::OsPipe`].
158    /// Merging stdout and stderr into one live name takes the same slot
159    /// twice, so the second take bails; merge in shell via `2>&1` instead.
160    #[cfg(not(miri))]
161    OsPipe(OsPipeWriter),
162}
163
164#[derive(Clone, Default)]
165pub struct CommandOptions {
166    pub mode: CommandMode,
167    pub stdin: CommandStdin,
168    pub stdout: CommandStdout,
169    pub stderr: CommandStderr,
170}
171
172impl CommandOptions {
173    pub fn foreground() -> Self {
174        Self::default()
175    }
176
177    pub fn background() -> Self {
178        Self {
179            mode: CommandMode::Background,
180            ..Self::default()
181        }
182    }
183}
184
185pub enum CommandResult<H> {
186    Completed,
187    Captured(Vec<u8>),
188    Background(H),
189}
190
191/// Host environment variable that forces spawned children to inherit the
192/// parent's stdout/stderr instead of using the executor's stream routing.
193/// Recognized values are `"1"` and case-insensitive `"true"`. Set on the
194/// script environment (an `ENV` step or host inherit), not the process
195/// environment: the executor reads it from [`CommandContext::envs`].
196pub const INHERIT_STDOUT_ENV_VAR: &str = "OXDOCK_INHERIT_STDOUT";
197
198/// Host process-environment variable enabling `eprintln!` diagnostics for
199/// every spawned command (program plus argv/script). Read from the process
200/// environment at spawn time; any value (including empty) enables it.
201pub const PROCESS_DEBUG_ENV_VAR: &str = "OXBOOK_DEBUG";
202
203/// Abstraction for running shell commands both in the foreground and
204/// background. `oxdock-core` relies on this trait to decouple the executor
205/// from `std::process::Command`, which in turn enables Miri-friendly test
206/// doubles.
207pub trait ProcessManager: Clone + Send + 'static {
208    type Handle: BackgroundHandle + Clone + Send + 'static;
209
210    fn run_command(
211        &mut self,
212        ctx: &CommandContext,
213        script: &str,
214        options: CommandOptions,
215    ) -> Result<CommandResult<Self::Handle>>;
216
217    /// Spawn a command without waiting for completion. Returns a background
218    /// handle that can be polled or waited on later. The default implementation
219    /// delegates to `run_command` with `CommandMode::Background`.
220    fn spawn_command(
221        &mut self,
222        ctx: &CommandContext,
223        script: &str,
224        options: CommandOptions,
225    ) -> Result<CommandResult<Self::Handle>> {
226        self.run_command(ctx, script, options)
227    }
228
229    /// Run an executable directly with an argument vector (no shell).
230    /// Backs the `RUN ["exe", "arg", ...]` exec form. The default
231    /// implementation bails so existing out-of-tree managers keep
232    /// compiling; in-tree managers override this.
233    fn run_argv(
234        &mut self,
235        _ctx: &CommandContext,
236        argv: &[String],
237        _options: CommandOptions,
238    ) -> Result<CommandResult<Self::Handle>> {
239        Err(anyhow::Error::new(proc_diag::run_argv_unimplemented(argv)))
240    }
241
242    /// Whether host stdin is an interactive terminal. The default
243    /// implementation reports the real stdin; test doubles override
244    /// this so prompt paths stay hermetic under any harness stdin.
245    fn stdin_is_terminal(&self) -> bool {
246        use std::io::IsTerminal;
247        std::io::stdin().is_terminal()
248    }
249
250    /// Spawn an argv command without waiting for completion. The default
251    /// implementation delegates to `run_argv`, mirroring `spawn_command`.
252    fn spawn_argv(
253        &mut self,
254        ctx: &CommandContext,
255        argv: &[String],
256        options: CommandOptions,
257    ) -> Result<CommandResult<Self::Handle>> {
258        self.run_argv(ctx, argv, options)
259    }
260}