Skip to main content

rust_anything/
process.rs

1//! Every outside program runs with stdin closed, in its own process group, under a time limit.
2
3use std::io::Read;
4use std::process::{Child, Command, ExitStatus, Stdio};
5use std::time::{Duration, Instant};
6
7use anyhow::{Context, Result, bail};
8
9const KEEP: usize = 1 << 20;
10
11pub struct Output {
12    pub status: ExitStatus,
13    pub stdout: Vec<u8>,
14    pub stderr: Vec<u8>,
15}
16
17impl Output {
18    pub fn success(&self) -> bool {
19        self.status.success()
20    }
21
22    pub fn stdout_text(&self) -> String {
23        String::from_utf8_lossy(&self.stdout).into_owned()
24    }
25
26    pub fn stderr_text(&self) -> String {
27        String::from_utf8_lossy(&self.stderr).into_owned()
28    }
29}
30
31/// `RUST_ANYTHING_COMMAND_TIMEOUT` seconds when set, else `default`.
32pub fn limit(default: Duration) -> Duration {
33    std::env::var("RUST_ANYTHING_COMMAND_TIMEOUT")
34        .ok()
35        .and_then(|v| v.parse::<f64>().ok())
36        .filter(|s| s.is_finite() && *s > 0.0)
37        .map_or(default, Duration::from_secs_f64)
38}
39
40pub const TESTS: Duration = Duration::from_secs(30 * 60);
41pub const BUILD: Duration = Duration::from_secs(30 * 60);
42pub const QUICK: Duration = Duration::from_secs(60);
43
44/// Runs `cmd` and captures its output (the last MiB of each stream).
45pub fn output(cmd: &mut Command, default: Duration) -> Result<Output> {
46    cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
47    let mut child = spawn(cmd)?;
48    let out = drain(child.stdout.take());
49    let err = drain(child.stderr.take());
50    let status = wait(&mut child, cmd, limit(default))?;
51    Ok(Output {
52        status,
53        stdout: out.join().unwrap_or_default(),
54        stderr: err.join().unwrap_or_default(),
55    })
56}
57
58/// Runs `cmd` with the output streams it was given.
59pub fn status(cmd: &mut Command, default: Duration) -> Result<ExitStatus> {
60    let mut child = spawn(cmd)?;
61    wait(&mut child, cmd, limit(default))
62}
63
64/// Runs `cmd` with `input` on its stdin and the output streams it was given (an agent reading
65/// its prompt).
66pub fn status_with_input(cmd: &mut Command, input: &[u8], default: Duration) -> Result<ExitStatus> {
67    let mut child = spawn_with(cmd, Stdio::piped())?;
68    let mut stdin = child.stdin.take().context("no stdin")?;
69    let input = input.to_vec();
70    let writer = std::thread::spawn(move || {
71        use std::io::Write as _;
72        let _ = stdin.write_all(&input);
73    });
74    let status = wait(&mut child, cmd, limit(default));
75    let _ = writer.join();
76    status
77}
78
79fn spawn(cmd: &mut Command) -> Result<Child> {
80    spawn_with(cmd, Stdio::null())
81}
82
83fn spawn_with(cmd: &mut Command, stdin: Stdio) -> Result<Child> {
84    cmd.stdin(stdin);
85    #[cfg(unix)]
86    {
87        use std::os::unix::process::CommandExt as _;
88        cmd.process_group(0);
89    }
90    cmd.spawn()
91        .with_context(|| format!("running `{}`", shown(cmd)))
92}
93
94fn drain(stream: Option<impl Read + Send + 'static>) -> std::thread::JoinHandle<Vec<u8>> {
95    std::thread::spawn(move || {
96        let mut kept = Vec::new();
97        let Some(mut stream) = stream else {
98            return kept;
99        };
100        let mut buf = [0u8; 8192];
101        while let Ok(n) = stream.read(&mut buf) {
102            if n == 0 {
103                break;
104            }
105            kept.extend_from_slice(&buf[..n]);
106            if kept.len() > 2 * KEEP {
107                kept.drain(..kept.len() - KEEP);
108            }
109        }
110        if kept.len() > KEEP {
111            kept.drain(..kept.len() - KEEP);
112        }
113        kept
114    })
115}
116
117fn wait(child: &mut Child, cmd: &Command, limit: Duration) -> Result<ExitStatus> {
118    let start = Instant::now();
119    let mut pause = Duration::from_millis(5);
120    loop {
121        if let Some(status) = child.try_wait()? {
122            return Ok(status);
123        }
124        if start.elapsed() > limit {
125            kill(child);
126            bail!(
127                "`{}` was still running after {}s and was stopped (set RUST_ANYTHING_COMMAND_TIMEOUT to allow longer; a test runner in watch mode never ends, so run it once, e.g. `vitest run`)",
128                shown(cmd),
129                limit.as_secs()
130            );
131        }
132        std::thread::sleep(pause);
133        pause = (pause * 2).min(Duration::from_millis(100));
134    }
135}
136
137fn kill(child: &mut Child) {
138    #[cfg(unix)]
139    {
140        let _ = Command::new("/bin/kill")
141            .args(["-KILL", "--", &format!("-{}", child.id())])
142            .stdin(Stdio::null())
143            .stdout(Stdio::null())
144            .stderr(Stdio::null())
145            .status();
146    }
147    let _ = child.kill();
148    let _ = child.wait();
149}
150
151fn shown(cmd: &Command) -> String {
152    std::iter::once(cmd.get_program())
153        .chain(cmd.get_args())
154        .map(|a| a.to_string_lossy().into_owned())
155        .collect::<Vec<_>>()
156        .join(" ")
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162
163    #[cfg(unix)]
164    #[test]
165    fn a_program_past_its_limit_is_stopped() {
166        let start = Instant::now();
167        let err = output(
168            Command::new("sh").args(["-c", "sleep 30"]),
169            Duration::from_millis(300),
170        )
171        .err()
172        .map(|e| e.to_string())
173        .unwrap_or_default();
174        assert!(err.contains("still running"), "{err}");
175        assert!(start.elapsed() < Duration::from_secs(5));
176    }
177
178    #[cfg(unix)]
179    #[test]
180    fn stdin_is_closed() {
181        let out = output(&mut Command::new("cat"), Duration::from_secs(5)).unwrap();
182        assert!(out.success());
183        assert!(out.stdout.is_empty());
184    }
185
186    #[cfg(unix)]
187    #[test]
188    fn output_is_kept_and_capped() {
189        let out = output(
190            Command::new("sh").args(["-c", "yes | head -c 3000000; echo err >&2"]),
191            Duration::from_secs(10),
192        )
193        .unwrap();
194        assert_eq!(out.stdout.len(), KEEP);
195        assert_eq!(out.stderr_text(), "err\n");
196    }
197}