artifactize-foundation 0.27.2

Native file, path and executable primitives for Artifactize.
Documentation
//! Native process lifetimes and admission, shared by process-owning callers.
use std::{
    ffi::{OsStr, OsString},
    io,
    path::{Path, PathBuf},
    process::Stdio,
    time::Duration,
};
use tokio::{process::Command, time::sleep};

#[cfg(unix)]
mod unix;
#[cfg(windows)]
mod windows;
#[cfg(unix)]
use unix as native;
#[cfg(unix)]
pub use unix::*;
#[cfg(windows)]
use windows as native;
#[cfg(windows)]
pub use windows::*;

/// Spawn a verified executable with the process group's supervised lifetime.
pub async fn spawn_verified(launch: super::executable::Launch<'_>) -> io::Result<Child> {
    launch.spawn().await
}

/// A launch with a fixed program. Configure it without exposing a mutable command
/// that could change which program runs. A handle-bound launch also carries native admission
/// guards; an ordinary pathname launch does not.
pub struct ResolvedCommand {
    command: Command,
    binding: self::native::Binding,
}

impl ResolvedCommand {
    pub fn as_std(&self) -> &std::process::Command {
        self.command.as_std()
    }

    pub fn current_dir(&mut self, dir: impl AsRef<Path>) -> &mut Self {
        self.command.current_dir(dir);
        self
    }

    pub fn env_clear(&mut self) -> &mut Self {
        self.command.env_clear();
        self
    }

    pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Self {
        self.command.env(key, value);
        self
    }

    pub fn envs<K, V>(&mut self, vars: impl IntoIterator<Item = (K, V)>) -> &mut Self
    where
        K: AsRef<OsStr>,
        V: AsRef<OsStr>,
    {
        self.command.envs(vars);
        self
    }

    pub fn stdin(&mut self, config: impl Into<Stdio>) -> &mut Self {
        self.command.stdin(config);
        self
    }

    pub fn stdout(&mut self, config: impl Into<Stdio>) -> &mut Self {
        self.command.stdout(config);
        self
    }

    pub fn stderr(&mut self, config: impl Into<Stdio>) -> &mut Self {
        self.command.stderr(config);
        self
    }

    pub fn kill_on_drop(&mut self, enabled: bool) -> &mut Self {
        self.command.kill_on_drop(enabled);
        self
    }

    pub fn hide_console_window(&mut self) -> &mut Self {
        hide_console_window(self.command.as_std_mut());
        self
    }
}

/// An ordinary program selected by the caller, without an executable identity guarantee.
pub struct Program {
    path: PathBuf,
    canonical: PathBuf,
}

impl Program {
    fn resolve(path: PathBuf) -> io::Result<Self> {
        if !path.is_absolute() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "launch requires a resolved absolute program",
            ));
        }
        let canonical = std::fs::canonicalize(&path)?;
        Ok(Self { path, canonical })
    }

    /// The selected spelling, before resolving aliases.
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// The resolved absolute name of the program.
    pub fn canonical_path(&self) -> &Path {
        &self.canonical
    }
}

/// Select an ordinary program using the caller's lookup environment. Its command uses
/// the selected path rather than the child's search path, but does not verify its bytes.
pub fn resolve_with(
    program: &Path,
    cwd: &Path,
    variable: impl Fn(&str) -> Option<OsString>,
) -> io::Result<Program> {
    Program::resolve(super::program::resolve_with(program, cwd, variable)?)
}

/// Build an ordinary command from an absolute path supplied by the caller.
/// For a custom lookup environment, use [`resolve_with`]. To check a digest or get consent
/// before spawning, use an [`Executable`](super::executable::Executable) and pass that snapshot
/// to [`super::executable::Launch`]. An ordinary command does not verify its executable.
pub fn resolved_command(
    program: &Path,
    args: impl IntoIterator<Item = impl AsRef<OsStr>>,
) -> io::Result<ResolvedCommand> {
    Program::resolve(program.to_owned())?.command(args)
}

mod outcome;
pub use outcome::{ProcessEnd, ProcessOutcome};

// Give a signalled child a chance to exit before forcing cleanup.
const CLEANUP_GRACE: Duration = Duration::from_secs(1);

/// A process id, guaranteed nonzero: every OS reserves 0 for the kernel or an idle
/// process, never one artifactize spawns or supervises. `#[serde(transparent)]` keeps
/// the saved and wire representation the same plain integer.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
)]
#[serde(transparent)]
pub struct ProcessId(std::num::NonZeroU32);

impl ProcessId {
    /// `pid` is a real, just-observed OS process id, so it is never 0.
    pub fn new(pid: u32) -> Self {
        Self(std::num::NonZeroU32::new(pid).expect("a real process id is never 0"))
    }

    pub fn get(self) -> u32 {
        self.0.get()
    }
}

impl From<std::num::NonZeroU32> for ProcessId {
    fn from(pid: std::num::NonZeroU32) -> Self {
        Self(pid)
    }
}

impl std::fmt::Display for ProcessId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

/// Process id and start time, captured while the group leader is still inert.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ChildIdentity {
    pub pid: ProcessId,
    /// Linux: clock ticks since boot (procfs field 22). macOS: microseconds since the
    /// epoch (kernel birth timestamp). Windows: 100 ns intervals since 1601.
    pub start_time: u64,
}

pub fn child_identity(pid: u32) -> io::Result<ChildIdentity> {
    let start_time = process_start_time(pid)?;
    Ok(ChildIdentity {
        pid: ProcessId::new(pid),
        start_time,
    })
}

/// Whether `owner` is both present and still the process it was: absent (no local
/// owner, such as a result mirrored from a remote review store) is never alive.
pub fn is_alive(owner: Option<ChildIdentity>) -> io::Result<bool> {
    let Some(owner) = owner else {
        return Ok(false);
    };
    match running_process_start_time(owner.pid.get()) {
        Ok(start_time) => Ok(start_time == owner.start_time),
        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
        Err(error) => Err(error),
    }
}

pub async fn terminate(child: &mut Child) -> io::Result<()> {
    let _ = child.interrupt();
    tokio::select! {
        _ = sleep(CLEANUP_GRACE) => {},
        _ = child.wait() => {},
    }
    child.cleanup().await?;
    Ok(())
}

#[cfg(test)]
mod tests;