job-limits 0.1.0

Memory limits for child processes, and a guard that cleans up the whole process tree (same API on unix and Windows)
Documentation
//! Behavior of `spawn` and `spawn_tokio`.

use std::process::Command;

use job_limits::Limits;

/// A command that exits with code 3.
fn exit3() -> Command {
    #[cfg(unix)]
    {
        let mut c = Command::new("sh");
        c.args(["-c", "exit 3"]);
        c
    }
    #[cfg(windows)]
    {
        let mut c = Command::new("cmd");
        c.args(["/c", "exit 3"]);
        c
    }
}

#[test]
fn spawns_and_returns_the_exit_code() {
    let (mut child, _guard) = Limits::new()
        .process_memory(1 << 30)
        .spawn(&mut exit3())
        .unwrap();
    assert_eq!(child.wait().unwrap().code(), Some(3));
}

#[test]
fn rejects_a_memory_limit_of_zero() {
    let err = Limits::new()
        .process_memory(0)
        .spawn(&mut exit3())
        .unwrap_err();
    assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput);
}

#[cfg(feature = "tokio")]
#[tokio::test]
async fn spawns_and_returns_the_exit_code_with_tokio() {
    let mut command = tokio::process::Command::from(exit3());
    let (mut child, _guard) = Limits::new()
        .process_memory(1 << 30)
        .spawn_tokio(&mut command)
        .unwrap();
    assert_eq!(child.wait().await.unwrap().code(), Some(3));
}

#[cfg(target_os = "linux")]
mod linux {
    use super::*;
    use std::io::{BufRead, BufReader, Read};
    use std::process::Stdio;
    use std::time::{Duration, Instant};

    #[test]
    fn the_memory_limit_shows_up_in_the_childs_ulimit() {
        let mut command = Command::new("sh");
        command.args(["-c", "ulimit -v"]).stdout(Stdio::piped());
        let (mut child, _guard) = Limits::new()
            .process_memory(1 << 30)
            .spawn(&mut command)
            .unwrap();
        let mut out = String::new();
        child
            .stdout
            .take()
            .unwrap()
            .read_to_string(&mut out)
            .unwrap();
        child.wait().unwrap();
        assert_eq!(out.trim(), (1u64 << 20).to_string());
    }

    /// Whether the process has ended (or become a zombie).
    fn gone(pid: u32) -> bool {
        match std::fs::read_to_string(format!("/proc/{pid}/stat")) {
            Err(_) => true,
            Ok(stat) => stat
                .rsplit_once(") ")
                .is_some_and(|(_, rest)| rest.starts_with('Z')),
        }
    }

    #[test]
    fn dropping_the_guard_ends_grandchildren_too() {
        let mut command = Command::new("sh");
        command
            .args(["-c", "sleep 30 & echo $!; wait"])
            .stdout(Stdio::piped());
        let (mut child, guard) = Limits::new().spawn(&mut command).unwrap();
        let mut line = String::new();
        BufReader::new(child.stdout.take().unwrap())
            .read_line(&mut line)
            .unwrap();
        let grandchild: u32 = line.trim().parse().unwrap();
        assert!(!gone(grandchild));

        drop(guard);
        child.wait().unwrap();
        let started = Instant::now();
        while !gone(grandchild) {
            assert!(
                started.elapsed() < Duration::from_secs(5),
                "the grandchild is still alive"
            );
            std::thread::sleep(Duration::from_millis(20));
        }
    }
}