Skip to main content

sprite/utils/
timeout.rs

1//! Cross-platform timeout utilities for Sprite operations
2//!
3//! This module provides cross-platform timeout functionality that works
4//! on macOS, Linux, and Windows without external dependencies.
5
6use anyhow::{Context, Result};
7use std::io;
8use std::process::{Child, Command, Stdio};
9use std::thread;
10use std::time::{Duration, Instant};
11
12/// Cross-platform timeout for executing commands
13#[allow(dead_code)]
14pub fn run_with_timeout(mut cmd: Command, timeout_secs: u64) -> Result<String> {
15    let timeout_duration = Duration::from_secs(timeout_secs);
16
17    // Redirect stdout and stderr to capture output
18    cmd.stdout(Stdio::piped());
19    cmd.stderr(Stdio::piped());
20
21    let child = cmd.spawn().context("Failed to spawn command")?;
22
23    // Wait for completion with timeout
24    let result = wait_with_timeout(child, timeout_duration);
25
26    match result {
27        TimeoutResult::Completed(output) => {
28            let stdout = String::from_utf8_lossy(&output.stdout).to_string();
29            let stderr = String::from_utf8_lossy(&output.stderr).to_string();
30
31            if output.status.success() {
32                Ok(stdout)
33            } else {
34                Err(anyhow::anyhow!(
35                    "Command failed with exit code {:?}. Stderr: {}",
36                    output.status.code(),
37                    stderr
38                ))
39            }
40        }
41        TimeoutResult::Timeout => Err(anyhow::anyhow!(
42            "Command timed out after {} seconds",
43            timeout_secs
44        )),
45        TimeoutResult::Error(e) => Err(anyhow::anyhow!("Error waiting for command: {}", e)),
46    }
47}
48
49/// Result of a timed wait operation
50#[allow(dead_code)]
51enum TimeoutResult {
52    Completed(std::process::Output),
53    Timeout,
54    Error(io::Error),
55}
56
57/// Wait for a child process with timeout
58#[allow(dead_code)]
59fn wait_with_timeout(mut child: Child, timeout: Duration) -> TimeoutResult {
60    let start_time = Instant::now();
61
62    loop {
63        match child.try_wait() {
64            Ok(Some(_)) => {
65                // Process has exited, get the output
66                match child.wait_with_output() {
67                    Ok(output) => return TimeoutResult::Completed(output),
68                    Err(e) => return TimeoutResult::Error(e),
69                }
70            }
71            Ok(None) => {
72                // Process is still running
73                if start_time.elapsed() >= timeout {
74                    return TimeoutResult::Timeout;
75                }
76                // Sleep for a short time before checking again
77                thread::sleep(Duration::from_millis(100));
78            }
79            Err(e) => return TimeoutResult::Error(e),
80        }
81    }
82}
83
84/// Force kill a child process and its children
85#[cfg(unix)]
86#[allow(dead_code)]
87fn kill_child_process(child: &mut Child) -> Result<()> {
88    // Check if process is still running first
89    if child.try_wait().ok().is_some_and(|status| status.is_none()) {
90        let pid = child.id();
91        // Send SIGTERM first
92        unsafe {
93            libc::kill(pid as libc::pid_t, libc::SIGTERM);
94        }
95
96        // Give it a moment to exit gracefully
97        thread::sleep(Duration::from_millis(1000));
98
99        // If still running, send SIGKILL
100        match child.try_wait() {
101            Ok(Some(_)) => {
102                // Process has exited
103                Ok(())
104            }
105            Ok(None) => {
106                // Still running, force kill
107                unsafe {
108                    libc::kill(pid as libc::pid_t, libc::SIGKILL);
109                }
110                child.wait()?;
111                Ok(())
112            }
113            Err(e) => Err(anyhow::anyhow!("Failed to kill process: {}", e)),
114        }
115    } else {
116        Ok(())
117    }
118}
119
120/// Force kill a child process on Windows
121#[cfg(windows)]
122#[allow(dead_code)]
123fn kill_child_process(child: &mut Child) -> Result<()> {
124    // On Windows, we can use a simpler approach
125    // Check if process is still running first
126    if child.try_wait().ok().is_some_and(|status| status.is_none()) {
127        let pid = child.id();
128        // Use taskkill to terminate the process
129        let mut kill_cmd = Command::new("taskkill");
130        kill_cmd.args(["/F", "/PID", &pid.to_string()]);
131        let _ = kill_cmd.output();
132
133        // Wait for the process to exit
134        let _ = child.wait();
135    } else {
136        // Process already exited
137    }
138    Ok(())
139}
140
141/// Execute a command string with timeout (for shell commands)
142#[allow(dead_code)]
143pub fn execute_with_timeout(shell_cmd: &str, timeout_secs: u64) -> Result<String> {
144    let (shell, shell_arg) = if cfg!(target_os = "windows") {
145        ("cmd", "/C")
146    } else {
147        ("sh", "-c")
148    };
149
150    let mut cmd = Command::new(shell);
151    cmd.arg(shell_arg);
152    cmd.arg(shell_cmd);
153
154    run_with_timeout(cmd, timeout_secs)
155}
156
157/// Simple timeout function for blocking operations
158#[allow(dead_code)]
159pub fn with_timeout<F, T>(timeout_secs: u64, operation: F) -> Result<T>
160where
161    F: FnOnce() -> Result<T> + std::marker::Send + 'static,
162    T: Send + 'static,
163{
164    let timeout_duration = Duration::from_secs(timeout_secs);
165
166    // Use a channel to implement timeout
167    let (sender, receiver) = std::sync::mpsc::channel();
168
169    // Spawn the operation in a separate thread
170    thread::spawn(move || match operation() {
171        Ok(result) => {
172            let _ = sender.send(Ok(result));
173        }
174        Err(e) => {
175            let _ = sender.send(Err(e));
176        }
177    });
178
179    // Wait for completion with timeout
180    match receiver.recv_timeout(timeout_duration) {
181        Ok(result) => result,
182        Err(std::sync::mpsc::RecvTimeoutError::Timeout) => Err(anyhow::anyhow!(
183            "Operation timed out after {} seconds",
184            timeout_secs
185        )),
186        Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
187            Err(anyhow::anyhow!("Operation thread panicked"))
188        }
189    }
190}