glacier-web 0.5.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Running other programs, as Laravel's `Process`: a command, its
//! arguments, a timeout, and what it printed.
//!
//! ```glacier
//! alias glacier.process.Process
//!
//! out = Process.new("pdftotext").args(["report.pdf", "-"]).timeout(10.seconds()).run()!
//! if out.success() do
//!   text = out.stdout
//! end
//! ```
//!
//! In tests no program runs: `stub_process("pdftotext", 0, "text")`
//! says what one prints, and a command no stub matches fails.

use std::sync::{Arc, Mutex};

use chrono::TimeDelta;

use crate::error::{Error, Result};
use crate::jobs::Delay;

/// A program to run; see the [module docs](self).
#[derive(Debug, Clone)]
#[must_use = "a process does nothing until `run`"]
pub struct Process {
    program: String,
    args: Vec<String>,
    dir: Option<String>,
    input: Option<String>,
    timeout: TimeDelta,
}

/// What a program did: its exit status and what it printed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Output {
    /// The exit code; `-1` when a signal stopped it.
    pub status: i32,
    pub stdout: String,
    pub stderr: String,
}

impl Output {
    /// Whether it exited with 0.
    pub fn success(&self) -> bool {
        self.status == 0
    }
}

impl Process {
    /// `program`, found on the `PATH`, given a minute to finish.
    pub fn new(program: impl Into<String>) -> Self {
        Self {
            program: program.into(),
            args: Vec::new(),
            dir: None,
            input: None,
            timeout: TimeDelta::minutes(1),
        }
    }

    /// Its arguments, each passed as it is (no shell, so nothing in them
    /// is interpreted).
    pub fn args<T: Into<String>>(mut self, args: impl IntoIterator<Item = T>) -> Self {
        self.args.extend(args.into_iter().map(Into::into));
        self
    }

    /// Runs it in `dir`.
    pub fn dir(mut self, dir: impl Into<String>) -> Self {
        self.dir = Some(dir.into());
        self
    }

    /// Writes `input` to its standard input.
    pub fn input(mut self, input: impl Into<String>) -> Self {
        self.input = Some(input.into());
        self
    }

    /// Stops it, as an error, if it runs longer than `timeout`.
    pub fn timeout(mut self, timeout: impl Delay) -> Self {
        self.timeout = timeout.delay();
        self
    }

    /// Runs it to the end and gives its [`Output`], whatever its status.
    ///
    /// # Errors
    ///
    /// When it can't be started, or runs past its timeout (`504`); in a
    /// test, when no stub matches it.
    pub async fn run(self) -> Result<Output> {
        if let Ok(fake) = FAKE.try_with(Arc::clone) {
            return fake.answer(&self);
        }
        use tokio::io::AsyncWriteExt;
        let mut command = tokio::process::Command::new(&self.program);
        command
            .args(&self.args)
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .kill_on_drop(true);
        if let Some(dir) = &self.dir {
            command.current_dir(dir);
        }
        let mut child = command
            .spawn()
            .map_err(|e| Error::internal(format!("running `{}`: {e}", self.program)))?;
        if let Some(mut stdin) = child.stdin.take() {
            let input = self.input.clone().unwrap_or_default();
            stdin
                .write_all(input.as_bytes())
                .await
                .map_err(|e| Error::internal(format!("writing to `{}`: {e}", self.program)))?;
        }
        let limit = self.timeout.to_std().unwrap_or_default();
        let output = tokio::time::timeout(limit, child.wait_with_output())
            .await
            .map_err(|_| {
                Error::new(
                    http::StatusCode::GATEWAY_TIMEOUT,
                    format!(
                        "`{}` ran past its timeout of {}s",
                        self.program,
                        limit.as_secs()
                    ),
                )
            })?
            .map_err(|e| Error::internal(format!("running `{}`: {e}", self.program)))?;
        Ok(Output {
            status: output.status.code().unwrap_or(-1),
            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
        })
    }
}

/// A test's stubbed programs, and what it ran.
#[derive(Default)]
struct Fake {
    stubs: Mutex<Vec<(String, Output)>>,
    ran: Mutex<Vec<Vec<String>>>,
}

impl Fake {
    fn answer(&self, process: &Process) -> Result<Output> {
        let mut line = vec![process.program.clone()];
        line.extend(process.args.iter().cloned());
        self.ran
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .push(line);
        // The latest stub for the program wins.
        self.stubs
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .iter()
            .rev()
            .find(|(program, _)| *program == process.program)
            .map(|(_, output)| output.clone())
            .ok_or_else(|| {
                Error::internal(format!(
                    "`{}`: tests run no real programs; stub it with `stub_process(\"{}\", 0, \"…\")`",
                    process.program, process.program
                ))
            })
    }
}

tokio::task_local! {
    static FAKE: Arc<Fake>;
}

/// Runs `fut` with no real programs: `#[glacier::test]` does this.
#[doc(hidden)]
pub async fn with_fake<F: std::future::Future>(fut: F) -> F::Output {
    FAKE.scope(Arc::default(), fut).await
}

/// In a test, `program` exits with `status` having printed `stdout`.
///
/// # Panics
///
/// Outside a `#[glacier::test]`.
pub fn stub(program: &str, status: i32, stdout: &str) {
    let fake = FAKE
        .try_with(Arc::clone)
        .expect("stub_process works inside a #[glacier::test]");
    fake.stubs.lock().unwrap_or_else(|e| e.into_inner()).push((
        program.to_owned(),
        Output {
            status,
            stdout: stdout.to_owned(),
            stderr: String::new(),
        },
    ));
}

/// The programs a test ran, each with its arguments, oldest first.
pub fn ran() -> Vec<Vec<String>> {
    FAKE.try_with(|fake| fake.ran.lock().unwrap_or_else(|e| e.into_inner()).clone())
        .unwrap_or_default()
}

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

    #[tokio::test]
    async fn runs_a_program_and_reads_what_it_printed() {
        let out = Process::new("sh")
            .args(["-c", "read line; echo \"got $line\"; echo oops >&2; exit 3"])
            .input("hello\n")
            .run()
            .await
            .unwrap();
        assert_eq!(out.status, 3);
        assert_eq!(out.stdout, "got hello\n");
        assert_eq!(out.stderr, "oops\n");
        assert!(!out.success());
    }

    #[tokio::test]
    async fn stops_one_that_runs_too_long() {
        let error = Process::new("sleep")
            .args(["5"])
            .timeout(TimeDelta::milliseconds(100))
            .run()
            .await
            .unwrap_err();
        assert_eq!(error.status(), http::StatusCode::GATEWAY_TIMEOUT);
    }

    #[tokio::test]
    async fn tests_answer_from_stubs() {
        with_fake(async {
            stub("pdftotext", 0, "Quarterly report");
            let out = Process::new("pdftotext")
                .args(["r.pdf", "-"])
                .run()
                .await
                .unwrap();
            assert_eq!(out.stdout, "Quarterly report");
            assert_eq!(ran(), [vec!["pdftotext", "r.pdf", "-"]]);
            let missing = Process::new("convert").run().await.unwrap_err();
            assert!(
                missing.to_string().contains("tests run no real programs"),
                "{missing}"
            );
        })
        .await;
    }
}