vpf-runner 0.4.1

The reference runner of the Verifiable Plan Format (VPF): runs a plan step by step and proves each step.
Documentation
//! A command line, run in the folder until it ends or the run's time is over.

use std::fs;
use std::io::{Read, Write};
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};

use serde::{Deserialize, Serialize};

/// How a command ended.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Ended {
    /// Whether it ended with the code 0.
    pub passed: bool,
    /// What it wrote to its output.
    pub out: String,
    /// What it wrote to its error output.
    pub err: String,
    /// The code it ended with, when it ended by itself.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub code: Option<i32>,
}

impl Ended {
    /// What it wrote, output first.
    pub fn said(&self) -> String {
        let (out, err) = (self.out.trim(), self.err.trim());
        match (out.is_empty(), err.is_empty()) {
            (_, true) => out.to_owned(),
            (true, false) => err.to_owned(),
            (false, false) => format!("{out}\n{err}"),
        }
    }

    /// The points against a command that did not pass: what it wrote or, when it wrote nothing, the command
    /// and how it ended.
    pub fn points(&self, line: &str) -> String {
        let said = self.said();
        if !said.is_empty() {
            return said;
        }
        match self.code {
            Some(code) => {
                format!("The command `{line}` ended with the code {code} and wrote nothing.")
            }
            None => format!("The command `{line}` was stopped and wrote nothing."),
        }
    }
}

/// Runs a command line in a folder as [`run`] does, keeping in `keep` its process, its output and how it ended, so
/// that what it did is known even when the runner stops while it works. Where that cannot be done, as [`run`].
///
/// # Errors
///
/// When the deadline passes before the command ends.
pub fn run_kept(
    line: &str,
    folder: &Path,
    variables: &[(&str, String)],
    input: &str,
    keep: &Path,
    deadline: Option<Instant>,
) -> Result<Ended, TimeOver> {
    if !cfg!(unix) || fs::create_dir_all(keep).is_err() {
        return run(line, folder, variables, input, deadline);
    }
    let path = |name: &str| {
        let path = keep.join(name).display().to_string();
        format!("'{}'", path.replace('\'', "'\\''"))
    };
    let wrapped = format!(
        "echo $$ > {pid}; ( {line}\n ) > {out} 2> {err}; echo $? > {part} && mv {part} {code}",
        pid = path("pid"),
        out = path("out"),
        err = path("err"),
        part = path("code.part"),
        code = path("code"),
    );
    let ended = run(&wrapped, folder, variables, input, deadline)?;
    Ok(kept(keep).unwrap_or(ended))
}

/// How a command run by [`run_kept`] in `keep` ended, waiting for it while it still runs, as a runner that stopped
/// meanwhile finds it again. Nothing when no command was kept there, or it stopped without ending.
///
/// # Errors
///
/// When the deadline passes before the command ends.
pub fn rejoin(keep: &Path, deadline: Option<Instant>) -> Option<Result<Ended, TimeOver>> {
    loop {
        if let Some(ended) = kept(keep) {
            return Some(Ok(ended));
        }
        let pid = kept_pid(keep)?;
        if !alive(pid) {
            return kept(keep).map(Ok);
        }
        if deadline.is_some_and(|deadline| Instant::now() >= deadline) {
            return Some(Err(TimeOver));
        }
        thread::sleep(Duration::from_millis(50));
    }
}

/// The process of a command run by [`run_kept`] in `dir` that still runs.
pub fn still_running(dir: &Path) -> Option<u32> {
    if kept(dir).is_some() {
        return None;
    }
    kept_pid(dir).filter(|pid| alive(*pid))
}

fn kept_pid(dir: &Path) -> Option<u32> {
    fs::read_to_string(dir.join("pid"))
        .ok()?
        .trim()
        .parse()
        .ok()
}

/// How a command run by [`run_kept`] ended, as it kept it in `dir`, once it has ended.
pub fn kept(dir: &Path) -> Option<Ended> {
    let code: i32 = fs::read_to_string(dir.join("code"))
        .ok()?
        .trim()
        .parse()
        .ok()?;
    let read = |name: &str| fs::read_to_string(dir.join(name)).unwrap_or_default();
    Some(Ended {
        passed: code == 0,
        out: read("out"),
        err: read("err"),
        code: Some(code),
    })
}

/// Whether a process with this id runs. A process that ended and was not reaped, as happens to one whose runner
/// is gone where nothing reaps orphans, does not.
pub fn alive(pid: u32) -> bool {
    if let Ok(stat) = fs::read_to_string(format!("/proc/{pid}/stat")) {
        let state = stat
            .rsplit_once(") ")
            .and_then(|(_, rest)| rest.chars().next());
        return !matches!(state, Some('Z' | 'X') | None);
    }
    cfg!(unix)
        && Command::new("kill")
            .args(["-0", &pid.to_string()])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .is_ok_and(|status| status.success())
}

/// The run's time was over before the command ended.
pub struct TimeOver;

fn shell(line: &str) -> Command {
    if cfg!(windows) {
        let mut command = Command::new("cmd");
        command.args(["/C", line]);
        command
    } else {
        let mut command = Command::new("sh");
        command.args(["-c", line]);
        command
    }
}

fn reader(mut stream: impl Read + Send + 'static) -> JoinHandle<String> {
    thread::spawn(move || {
        let mut bytes = Vec::new();
        let _ = stream.read_to_end(&mut bytes);
        String::from_utf8_lossy(&bytes).into_owned()
    })
}

fn stop(child: &mut Child) {
    #[cfg(unix)]
    {
        // The command runs in a group of its own, so whatever it started stops with it.
        let _ = Command::new("kill")
            .args(["-KILL", "--", &format!("-{}", child.id())])
            .stderr(Stdio::null())
            .status();
    }
    let _ = child.kill();
    let _ = child.wait();
}

/// Runs a command line in the folder, with these variables and this input.
///
/// # Errors
///
/// [`TimeOver`] when the deadline, if any, passes first. A command that cannot start ends as refused.
pub fn run(
    line: &str,
    folder: &Path,
    variables: &[(&str, String)],
    input: &str,
    deadline: Option<Instant>,
) -> Result<Ended, TimeOver> {
    let mut command = shell(line);
    command
        .current_dir(folder)
        .envs(variables.iter().map(|(key, value)| (*key, value)))
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    #[cfg(unix)]
    std::os::unix::process::CommandExt::process_group(&mut command, 0);
    let mut child = match command.spawn() {
        Ok(child) => child,
        Err(error) => {
            return Ok(Ended {
                passed: false,
                out: String::new(),
                err: format!("the command could not start: {error}"),
                code: None,
            });
        }
    };
    if let Some(mut stdin) = child.stdin.take() {
        let input = input.to_owned();
        thread::spawn(move || {
            let _ = stdin.write_all(input.as_bytes());
        });
    }
    let out = child.stdout.take().map(reader);
    let err = child.stderr.take().map(reader);
    loop {
        match child.try_wait() {
            Ok(Some(status)) => {
                let text = |handle: Option<JoinHandle<String>>| {
                    handle
                        .and_then(|handle| handle.join().ok())
                        .unwrap_or_default()
                };
                return Ok(Ended {
                    passed: status.success(),
                    out: text(out),
                    err: text(err),
                    code: status.code(),
                });
            }
            Ok(None) if deadline.is_some_and(|deadline| Instant::now() >= deadline) => {
                stop(&mut child);
                return Err(TimeOver);
            }
            Ok(None) => thread::sleep(Duration::from_millis(10)),
            Err(error) => {
                stop(&mut child);
                return Ok(Ended {
                    passed: false,
                    out: String::new(),
                    err: format!("the command could not be followed: {error}"),
                    code: None,
                });
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::alive;

    #[test]
    #[cfg(target_os = "linux")]
    fn a_process_that_ended_and_was_not_reaped_does_not_run() {
        let mut child = std::process::Command::new("true")
            .spawn()
            .expect("a process");
        let pid = child.id();
        // Not waited for, it stays a zombie until reaped.
        std::thread::sleep(std::time::Duration::from_millis(200));
        assert!(!alive(pid));
        child.wait().expect("reaped");
        let mut running = std::process::Command::new("sleep")
            .arg("5")
            .spawn()
            .expect("a process");
        assert!(alive(running.id()));
        running.kill().expect("killed");
        running.wait().expect("reaped");
    }
}