Skip to main content

artifactize_foundation/platform/
process.rs

1//! Native process lifetimes and admission, shared by process-owning callers.
2use std::{
3    ffi::{OsStr, OsString},
4    io,
5    path::{Path, PathBuf},
6    process::Stdio,
7    time::Duration,
8};
9use tokio::{process::Command, time::sleep};
10
11#[cfg(unix)]
12mod unix;
13#[cfg(windows)]
14mod windows;
15#[cfg(unix)]
16use unix as native;
17#[cfg(unix)]
18pub use unix::*;
19#[cfg(windows)]
20use windows as native;
21#[cfg(windows)]
22pub use windows::*;
23
24/// Spawn a verified executable with the process group's supervised lifetime.
25pub async fn spawn_verified(launch: super::executable::Launch<'_>) -> io::Result<Child> {
26    launch.spawn().await
27}
28
29/// A launch with a fixed program. Configure it without exposing a mutable command
30/// that could change which program runs. A handle-bound launch also carries native admission
31/// guards; an ordinary pathname launch does not.
32pub struct ResolvedCommand {
33    command: Command,
34    binding: self::native::Binding,
35}
36
37impl ResolvedCommand {
38    pub fn as_std(&self) -> &std::process::Command {
39        self.command.as_std()
40    }
41
42    pub fn current_dir(&mut self, dir: impl AsRef<Path>) -> &mut Self {
43        self.command.current_dir(dir);
44        self
45    }
46
47    pub fn env_clear(&mut self) -> &mut Self {
48        self.command.env_clear();
49        self
50    }
51
52    pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Self {
53        self.command.env(key, value);
54        self
55    }
56
57    pub fn envs<K, V>(&mut self, vars: impl IntoIterator<Item = (K, V)>) -> &mut Self
58    where
59        K: AsRef<OsStr>,
60        V: AsRef<OsStr>,
61    {
62        self.command.envs(vars);
63        self
64    }
65
66    pub fn stdin(&mut self, config: impl Into<Stdio>) -> &mut Self {
67        self.command.stdin(config);
68        self
69    }
70
71    pub fn stdout(&mut self, config: impl Into<Stdio>) -> &mut Self {
72        self.command.stdout(config);
73        self
74    }
75
76    pub fn stderr(&mut self, config: impl Into<Stdio>) -> &mut Self {
77        self.command.stderr(config);
78        self
79    }
80
81    pub fn kill_on_drop(&mut self, enabled: bool) -> &mut Self {
82        self.command.kill_on_drop(enabled);
83        self
84    }
85
86    pub fn hide_console_window(&mut self) -> &mut Self {
87        hide_console_window(self.command.as_std_mut());
88        self
89    }
90}
91
92/// An ordinary program selected by the caller, without an executable identity guarantee.
93pub struct Program {
94    path: PathBuf,
95    canonical: PathBuf,
96}
97
98impl Program {
99    fn resolve(path: PathBuf) -> io::Result<Self> {
100        if !path.is_absolute() {
101            return Err(io::Error::new(
102                io::ErrorKind::InvalidInput,
103                "launch requires a resolved absolute program",
104            ));
105        }
106        let canonical = std::fs::canonicalize(&path)?;
107        Ok(Self { path, canonical })
108    }
109
110    /// The selected spelling, before resolving aliases.
111    pub fn path(&self) -> &Path {
112        &self.path
113    }
114
115    /// The resolved absolute name of the program.
116    pub fn canonical_path(&self) -> &Path {
117        &self.canonical
118    }
119}
120
121/// Select an ordinary program using the caller's lookup environment. Its command uses
122/// the selected path rather than the child's search path, but does not verify its bytes.
123pub fn resolve_with(
124    program: &Path,
125    cwd: &Path,
126    variable: impl Fn(&str) -> Option<OsString>,
127) -> io::Result<Program> {
128    Program::resolve(super::program::resolve_with(program, cwd, variable)?)
129}
130
131/// Build an ordinary command from an absolute path supplied by the caller.
132/// For a custom lookup environment, use [`resolve_with`]. To check a digest or get consent
133/// before spawning, use an [`Executable`](super::executable::Executable) and pass that snapshot
134/// to [`super::executable::Launch`]. An ordinary command does not verify its executable.
135pub fn resolved_command(
136    program: &Path,
137    args: impl IntoIterator<Item = impl AsRef<OsStr>>,
138) -> io::Result<ResolvedCommand> {
139    Program::resolve(program.to_owned())?.command(args)
140}
141
142mod outcome;
143pub use outcome::{ProcessEnd, ProcessOutcome};
144
145// Give a signalled child a chance to exit before forcing cleanup.
146const CLEANUP_GRACE: Duration = Duration::from_secs(1);
147
148/// A process id, guaranteed nonzero: every OS reserves 0 for the kernel or an idle
149/// process, never one artifactize spawns or supervises. `#[serde(transparent)]` keeps
150/// the saved and wire representation the same plain integer.
151#[derive(
152    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
153)]
154#[serde(transparent)]
155pub struct ProcessId(std::num::NonZeroU32);
156
157impl ProcessId {
158    /// `pid` is a real, just-observed OS process id, so it is never 0.
159    pub fn new(pid: u32) -> Self {
160        Self(std::num::NonZeroU32::new(pid).expect("a real process id is never 0"))
161    }
162
163    pub fn get(self) -> u32 {
164        self.0.get()
165    }
166}
167
168impl From<std::num::NonZeroU32> for ProcessId {
169    fn from(pid: std::num::NonZeroU32) -> Self {
170        Self(pid)
171    }
172}
173
174impl std::fmt::Display for ProcessId {
175    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176        self.0.fmt(f)
177    }
178}
179
180/// Process id and start time, captured while the group leader is still inert.
181#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
182pub struct ChildIdentity {
183    pub pid: ProcessId,
184    /// Linux: clock ticks since boot (procfs field 22). macOS: microseconds since the
185    /// epoch (kernel birth timestamp). Windows: 100 ns intervals since 1601.
186    pub start_time: u64,
187}
188
189pub fn child_identity(pid: u32) -> io::Result<ChildIdentity> {
190    let start_time = process_start_time(pid)?;
191    Ok(ChildIdentity {
192        pid: ProcessId::new(pid),
193        start_time,
194    })
195}
196
197/// Whether `owner` is both present and still the process it was: absent (no local
198/// owner, such as a result mirrored from a remote review store) is never alive.
199pub fn is_alive(owner: Option<ChildIdentity>) -> io::Result<bool> {
200    let Some(owner) = owner else {
201        return Ok(false);
202    };
203    match running_process_start_time(owner.pid.get()) {
204        Ok(start_time) => Ok(start_time == owner.start_time),
205        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
206        Err(error) => Err(error),
207    }
208}
209
210pub async fn terminate(child: &mut Child) -> io::Result<()> {
211    let _ = child.interrupt();
212    tokio::select! {
213        _ = sleep(CLEANUP_GRACE) => {},
214        _ = child.wait() => {},
215    }
216    child.cleanup().await?;
217    Ok(())
218}
219
220#[cfg(test)]
221mod tests;