Skip to main content

oxdock_process/
contract.rs

1use std::collections::HashMap;
2
3use oxdock_fs::{CargoScratch, GuardedPath, PolicyPath};
4#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
5use std::process::ExitStatus;
6
7use std::sync::Arc;
8
9use crate::diagnostics as proc_diag;
10use oxdock_diagnostics::DiagnosticResult;
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`].
88/// Poll and wait report keyed diagnostics (`DiagnosticResult`), so the
89/// `step N` call path rides natively via `with_contexts` instead of
90/// anyhow context layers.
91pub trait BackgroundHandle: Send {
92    fn try_wait(&mut self) -> DiagnosticResult<Option<ExitStatus>>;
93    fn kill(&mut self) -> DiagnosticResult<()>;
94    fn wait(&mut self) -> DiagnosticResult<ExitStatus>;
95}
96
97#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
98pub enum CommandMode {
99    #[default]
100    Foreground,
101    Background,
102}
103
104#[derive(Clone, Default)]
105pub enum CommandStdout {
106    #[default]
107    Inherit,
108    Stream(SharedOutput),
109    Capture,
110    /// Direct OS kernel pipe writer for concurrent pipelines. Single use:
111    /// the handle is taken on spawn and the parent retains no copy, so the
112    /// reader observes EOF once the producer exits. Only valid with
113    /// concurrently spawned consumers (`ASYNC`); never for sequential steps.
114    #[cfg(not(miri))]
115    OsPipe(OsPipeWriter),
116}
117
118#[derive(Clone, Default)]
119pub enum CommandStdin {
120    /// Isolated null stdin. Preserves the previous `None` behavior.
121    #[default]
122    Null,
123    Inherit,
124    Stream(SharedInput),
125    /// Direct OS kernel pipe reader for concurrent pipelines. See
126    /// [`CommandStdout::OsPipe`] for the single use contract.
127    #[cfg(not(miri))]
128    OsPipe(OsPipeReader),
129}
130
131impl From<Option<SharedInput>> for CommandStdin {
132    fn from(stdin: Option<SharedInput>) -> Self {
133        match stdin {
134            Some(reader) => CommandStdin::Stream(reader),
135            None => CommandStdin::Null,
136        }
137    }
138}
139
140impl CommandStdin {
141    /// Whether stdin is bound to a virtual pipe (`WITH_IO [stdin=...]`).
142    /// A redirected stdin can never answer an interactive prompt, so
143    /// terminal-facing steps treat this as non-interactive even when
144    /// the host process itself owns a TTY.
145    pub fn is_redirected(&self) -> bool {
146        match self {
147            CommandStdin::Stream(_) => true,
148            #[cfg(not(miri))]
149            CommandStdin::OsPipe(_) => true,
150            CommandStdin::Null | CommandStdin::Inherit => false,
151        }
152    }
153}
154
155#[derive(Clone, Default)]
156pub enum CommandStderr {
157    #[default]
158    Inherit,
159    Stream(SharedOutput),
160    /// Direct OS kernel pipe writer, mirroring [`CommandStdout::OsPipe`].
161    /// Merging stdout and stderr into one live name takes the same slot
162    /// twice, so the second take bails; merge in shell via `2>&1` instead.
163    #[cfg(not(miri))]
164    OsPipe(OsPipeWriter),
165}
166
167#[derive(Clone, Default)]
168pub struct CommandOptions {
169    pub mode: CommandMode,
170    pub stdin: CommandStdin,
171    pub stdout: CommandStdout,
172    pub stderr: CommandStderr,
173}
174
175impl CommandOptions {
176    pub fn foreground() -> Self {
177        Self::default()
178    }
179
180    pub fn background() -> Self {
181        Self {
182            mode: CommandMode::Background,
183            ..Self::default()
184        }
185    }
186}
187
188pub enum CommandResult<H> {
189    Completed,
190    Captured(Vec<u8>),
191    Background(H),
192}
193
194/// Host environment variable that forces spawned children to inherit the
195/// parent's stdout/stderr instead of using the executor's stream routing.
196/// Recognized values are `"1"` and case-insensitive `"true"`. Set on the
197/// script environment (an `ENV` step or host inherit), not the process
198/// environment: the executor reads it from [`CommandContext::envs`].
199pub const INHERIT_STDOUT_ENV_VAR: &str = "OXDOCK_INHERIT_STDOUT";
200
201/// Host process-environment variable enabling `eprintln!` diagnostics for
202/// every spawned command (program plus argv/script). Read from the process
203/// environment at spawn time; any value (including empty) enables it.
204pub const PROCESS_DEBUG_ENV_VAR: &str = "OXBOOK_DEBUG";
205
206/// Abstraction for running shell commands both in the foreground and
207/// background. `oxdock-core` relies on this trait to decouple the executor
208/// from `std::process::Command`, which in turn enables Miri-friendly test
209/// doubles.
210pub trait ProcessManager: Clone + Send + 'static {
211    type Handle: BackgroundHandle + Clone + Send + 'static;
212
213    fn run_command(
214        &mut self,
215        ctx: &CommandContext,
216        script: &str,
217        options: CommandOptions,
218    ) -> DiagnosticResult<CommandResult<Self::Handle>>;
219
220    /// Spawn a command without waiting for completion. Returns a background
221    /// handle that can be polled or waited on later. The default implementation
222    /// delegates to `run_command` with `CommandMode::Background`.
223    fn spawn_command(
224        &mut self,
225        ctx: &CommandContext,
226        script: &str,
227        options: CommandOptions,
228    ) -> DiagnosticResult<CommandResult<Self::Handle>> {
229        self.run_command(ctx, script, options)
230    }
231
232    /// Run an executable directly with an argument vector (no shell).
233    /// Backs the `RUN ["exe", "arg", ...]` exec form. The default
234    /// implementation bails so existing out-of-tree managers keep
235    /// compiling; in-tree managers override this.
236    fn run_argv(
237        &mut self,
238        _ctx: &CommandContext,
239        argv: &[String],
240        _options: CommandOptions,
241    ) -> DiagnosticResult<CommandResult<Self::Handle>> {
242        Err(proc_diag::run_argv_unimplemented(argv))
243    }
244
245    /// Whether host stdin is an interactive terminal. The default
246    /// implementation reports the real stdin; test doubles override
247    /// this so prompt paths stay hermetic under any harness stdin.
248    fn stdin_is_terminal(&self) -> bool {
249        use std::io::IsTerminal;
250        std::io::stdin().is_terminal()
251    }
252
253    /// Spawn an argv command without waiting for completion. The default
254    /// implementation delegates to `run_argv`, mirroring `spawn_command`.
255    fn spawn_argv(
256        &mut self,
257        ctx: &CommandContext,
258        argv: &[String],
259        options: CommandOptions,
260    ) -> DiagnosticResult<CommandResult<Self::Handle>> {
261        self.run_argv(ctx, argv, options)
262    }
263}