Skip to main content

hyprforge_process/
lib.rs

1//! Running a subprocess that might not come back.
2//!
3//! `Command::output()` waits forever. Every external program this
4//! project talks to — `hyprctl`, `gsettings`, `fc-list` — is one that
5//! can stop answering: a wedged compositor, a hung dconf, an NFS home
6//! directory. Waiting forever on any of them means an app that has to
7//! be killed, and for a login screen it would mean nobody can log in.
8//!
9//! That is the same shape of mistake as waiting forever for a
10//! compositor to grant a session lock, which cost five visible seconds
11//! before anyone noticed. Unbounded waits on another process are worth
12//! treating as a category.
13//!
14//! Deliberately not in `hyprforge-paths`, which has no dependencies and
15//! is about where files live: this is about talking to another process,
16//! not about the filesystem. It used to live in `hyprforge-core`, on the
17//! theory that every caller already depended on that crate — but
18//! `hyprforge-network`, `hyprforge-bluetooth` and `hyprforge-power` are
19//! clients of other daemons (NetworkManager, BlueZ, systemd-logind) with
20//! no Hyprland config to read or write, and pulling in 4,000+ lines of
21//! `hlconfig`/`hyprlang`/`lua` machinery for a bounded-subprocess helper
22//! made the layering a lie. This crate has no workspace dependencies at
23//! all, same as `hyprforge-paths`, so a non-Hyprland app can use it
24//! without dragging in Hyprland at all. `hyprforge-core` re-exports this
25//! module as `hyprforge_core::command` so existing call sites keep
26//! working; new code should depend on `hyprforge-process` directly.
27
28use std::io;
29use std::process::{Command, Output, Stdio};
30use std::time::{Duration, Instant};
31
32/// Long enough that a busy machine is not cut off, short enough that a
33/// person does not conclude the app is broken.
34pub const TIMEOUT: Duration = Duration::from_secs(5);
35
36/// How often the child is checked for having exited.
37const POLL: Duration = Duration::from_millis(5);
38
39/// Like [`Command::output`], but gives up.
40///
41/// A timeout is reported as [`io::ErrorKind::TimedOut`], so callers that
42/// already handle a failed spawn need no new branch: not answering and
43/// not starting are the same problem from their side.
44///
45/// The child is killed on timeout rather than left running, because the
46/// usual reason to time out is that it is stuck, and a pile of stuck
47/// `hyprctl`s helps nobody.
48pub fn output(command: &mut Command, timeout: Duration) -> io::Result<Output> {
49    let mut child = command.stdout(Stdio::piped()).stderr(Stdio::piped()).spawn()?;
50
51    // Drained on their own threads rather than after the child exits.
52    // A pipe holds about 64KB before it blocks, and `fc-list` on a
53    // machine with a lot of fonts prints more than that — so reading
54    // only after exit would deadlock: the child waiting for the pipe to
55    // drain, this waiting for the child.
56    let mut stdout = child.stdout.take().map(reader);
57    let mut stderr = child.stderr.take().map(reader);
58
59    let started = Instant::now();
60    let status = loop {
61        match child.try_wait()? {
62            Some(status) => break status,
63            None if started.elapsed() >= timeout => {
64                let _ = child.kill();
65                let _ = child.wait();
66                return Err(io::Error::new(
67                    io::ErrorKind::TimedOut,
68                    format!("{:?} did not answer within {:?}", command.get_program(), timeout),
69                ));
70            }
71            None => std::thread::sleep(POLL),
72        }
73    };
74
75    Ok(Output {
76        status,
77        stdout: stdout.take().map(collect).unwrap_or_default(),
78        stderr: stderr.take().map(collect).unwrap_or_default(),
79    })
80}
81
82fn reader<R: io::Read + Send + 'static>(mut source: R) -> std::thread::JoinHandle<Vec<u8>> {
83    std::thread::spawn(move || {
84        let mut buffer = Vec::new();
85        let _ = source.read_to_end(&mut buffer);
86        buffer
87    })
88}
89
90/// A reader thread that panicked would only mean no output, and a
91/// panicking settings app is worse than a missing string.
92fn collect(handle: std::thread::JoinHandle<Vec<u8>>) -> Vec<u8> {
93    handle.join().unwrap_or_default()
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99
100    #[test]
101    fn an_ordinary_command_still_returns_its_output() {
102        let out = output(Command::new("echo").arg("hello"), TIMEOUT).unwrap();
103        assert!(out.status.success());
104        assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "hello");
105    }
106
107    #[test]
108    fn a_failing_command_is_reported_by_its_status_not_an_error() {
109        let out = output(&mut Command::new("false"), TIMEOUT).unwrap();
110        assert!(!out.status.success(), "a non-zero exit is data, not an error");
111    }
112
113    /// The whole point. Before this existed, a command that never
114    /// returned took the calling app with it.
115    #[test]
116    fn a_command_that_never_returns_gives_up() {
117        let started = Instant::now();
118        let result = output(Command::new("sleep").arg("60"), Duration::from_millis(200));
119        let error = result.expect_err("sleep 60 must not be waited on");
120        assert_eq!(error.kind(), io::ErrorKind::TimedOut);
121        assert!(started.elapsed() < Duration::from_secs(5), "waited {:?}", started.elapsed());
122    }
123
124    /// More output than a pipe holds, so reading it only after the child
125    /// exited would deadlock — the child blocked on a full pipe, this
126    /// blocked on the child.
127    #[test]
128    fn output_larger_than_a_pipe_buffer_does_not_deadlock() {
129        let out = output(
130            Command::new("sh").arg("-c").arg("yes hyprforge | head -c 400000"),
131            Duration::from_secs(10),
132        )
133        .expect("a chatty command is not a hung one");
134        assert_eq!(out.stdout.len(), 400_000);
135    }
136
137    #[test]
138    fn a_program_that_does_not_exist_is_an_error_like_before() {
139        let error = output(&mut Command::new("hyprforge-no-such-program"), TIMEOUT).unwrap_err();
140        assert_eq!(error.kind(), io::ErrorKind::NotFound);
141    }
142}