| 1 | use std::collections::VecDeque; |
| 2 | use std::path::PathBuf; |
| 3 | use std::process::Stdio; |
| 4 | use std::sync::{Arc, Mutex}; |
| 5 | |
| 6 | use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; |
| 7 | use tokio::process::Command; |
| 8 | use tokio::sync::{mpsc, oneshot}; |
| 9 | |
| 10 | use crate::invocation::{Invocation, RunPlan}; |
| 11 | use crate::parse::{OutputParser, RunEvent}; |
| 12 | use crate::profile::OutputFormat; |
| 13 | |
| 14 | const STDERR_TAIL_LINES: usize = 20; |
| 15 | const PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); |
| 16 | const STOP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15); |
| 17 | |
| 18 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 19 | pub enum RunUpdate { |
| 20 | Event(RunEvent), |
| 21 | Stderr(String), |
| 22 | Started(u32), |
| 23 | } |
| 24 | |
| 25 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 26 | pub enum RunStatus { |
| 27 | Completed { |
| 28 | final_text: String, |
| 29 | }, |
| 30 | Failed { |
| 31 | message: String, |
| 32 | stderr_tail: Vec<String>, |
| 33 | }, |
| 34 | Stopped, |
| 35 | } |
| 36 | |
| 37 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 38 | pub struct RunOutcome { |
| 39 | pub status: RunStatus, |
| 40 | pub exit_code: Option<i32>, |
| 41 | } |
| 42 | |
| 43 | fn command_for(invocation: &Invocation) -> Command { |
| 44 | let program = crate::catalog::resolve_program(&invocation.program) |
| 45 | .unwrap_or_else(|| PathBuf::from(&invocation.program)); |
| 46 | let mut command = Command::new(program); |
| 47 | command.args(&invocation.args); |
| 48 | if let Some(cwd) = &invocation.cwd { |
| 49 | command.current_dir(cwd); |
| 50 | } |
| 51 | prepend_user_bin(&mut command); |
| 52 | command.kill_on_drop(true); |
| 53 | #[cfg(windows)] |
| 54 | command.creation_flags(0x0800_0000); |
| 55 | command |
| 56 | } |
| 57 | |
| 58 | fn prepend_user_bin(command: &mut Command) { |
| 59 | let Some(home) = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")) else { |
| 60 | return; |
| 61 | }; |
| 62 | let bin = PathBuf::from(home).join(".local").join("bin"); |
| 63 | if !bin.is_dir() { |
| 64 | return; |
| 65 | } |
| 66 | let mut paths = vec![bin]; |
| 67 | if let Some(path) = std::env::var_os("PATH") { |
| 68 | paths.extend(std::env::split_paths(&path)); |
| 69 | } |
| 70 | if let Ok(joined) = std::env::join_paths(paths) { |
| 71 | command.env("PATH", joined); |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | #[cfg(windows)] |
| 76 | fn taskkill_tree(process_id: u32) -> Invocation { |
| 77 | Invocation { |
| 78 | program: "taskkill".to_string(), |
| 79 | args: ["/PID", &process_id.to_string(), "/T", "/F"] |
| 80 | .map(String::from) |
| 81 | .to_vec(), |
| 82 | cwd: None, |
| 83 | stdin: None, |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | fn failed(message: String, stderr_tail: Vec<String>, exit_code: Option<i32>) -> RunOutcome { |
| 88 | RunOutcome { |
| 89 | status: RunStatus::Failed { |
| 90 | message, |
| 91 | stderr_tail, |
| 92 | }, |
| 93 | exit_code, |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | pub async fn run_stop_invocation(invocation: &Invocation) { |
| 98 | run_stop_invocation_within(invocation, STOP_TIMEOUT).await; |
| 99 | } |
| 100 | |
| 101 | pub async fn run_stop_invocation_within(invocation: &Invocation, limit: std::time::Duration) { |
| 102 | let mut command = command_for(invocation); |
| 103 | command |
| 104 | .stdin(Stdio::null()) |
| 105 | .stdout(Stdio::null()) |
| 106 | .stderr(Stdio::null()); |
| 107 | if let Ok(mut child) = command.spawn() |
| 108 | && tokio::time::timeout(limit, child.wait()).await.is_err() |
| 109 | { |
| 110 | let _ = child.kill().await; |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | fn snapshot(tail: &Mutex<VecDeque<String>>) -> Vec<String> { |
| 115 | tail.lock() |
| 116 | .map(|lines| lines.iter().cloned().collect()) |
| 117 | .unwrap_or_default() |
| 118 | } |
| 119 | |
| 120 | pub async fn run( |
| 121 | plan: RunPlan, |
| 122 | format: OutputFormat, |
| 123 | events: mpsc::UnboundedSender<RunUpdate>, |
| 124 | stop: oneshot::Receiver<()>, |
| 125 | ) -> RunOutcome { |
| 126 | let cleanup = plan.cleanup.clone(); |
| 127 | let outcome = run_plan(plan, format, events, stop).await; |
| 128 | for path in cleanup { |
| 129 | let _ = std::fs::remove_file(path); |
| 130 | } |
| 131 | outcome |
| 132 | } |
| 133 | |
| 134 | async fn run_plan( |
| 135 | plan: RunPlan, |
| 136 | format: OutputFormat, |
| 137 | events: mpsc::UnboundedSender<RunUpdate>, |
| 138 | mut stop: oneshot::Receiver<()>, |
| 139 | ) -> RunOutcome { |
| 140 | let mut command = command_for(&plan.run); |
| 141 | command |
| 142 | .stdin(Stdio::piped()) |
| 143 | .stdout(Stdio::piped()) |
| 144 | .stderr(Stdio::piped()); |
| 145 | let mut child = match command.spawn() { |
| 146 | Ok(child) => child, |
| 147 | Err(error) => { |
| 148 | return failed( |
| 149 | format!("cannot start {}: {error}", plan.run.program), |
| 150 | Vec::new(), |
| 151 | None, |
| 152 | ); |
| 153 | } |
| 154 | }; |
| 155 | if let Some(process_id) = child.id() { |
| 156 | let _ = events.send(RunUpdate::Started(process_id)); |
| 157 | } |
| 158 | let (Some(stdin), Some(stdout), Some(stderr)) = |
| 159 | (child.stdin.take(), child.stdout.take(), child.stderr.take()) |
| 160 | else { |
| 161 | return failed( |
| 162 | "cannot attach to the process pipes".to_string(), |
| 163 | Vec::new(), |
| 164 | None, |
| 165 | ); |
| 166 | }; |
| 167 | |
| 168 | let prompt = plan.run.stdin.clone(); |
| 169 | let stdin_task = tokio::spawn(async move { |
| 170 | let mut stdin = stdin; |
| 171 | if let Some(prompt) = prompt { |
| 172 | let _ = stdin.write_all(prompt.as_bytes()).await; |
| 173 | } |
| 174 | let _ = stdin.shutdown().await; |
| 175 | }); |
| 176 | |
| 177 | let stderr_tail = Arc::new(Mutex::new(VecDeque::new())); |
| 178 | let stderr_task = { |
| 179 | let stderr_tail = Arc::clone(&stderr_tail); |
| 180 | let events = events.clone(); |
| 181 | tokio::spawn(async move { |
| 182 | let mut lines = BufReader::new(stderr).lines(); |
| 183 | while let Ok(Some(line)) = lines.next_line().await { |
| 184 | if let Ok(mut tail) = stderr_tail.lock() { |
| 185 | if tail.len() == STDERR_TAIL_LINES { |
| 186 | tail.pop_front(); |
| 187 | } |
| 188 | tail.push_back(line.clone()); |
| 189 | } |
| 190 | let _ = events.send(RunUpdate::Stderr(line)); |
| 191 | } |
| 192 | }) |
| 193 | }; |
| 194 | |
| 195 | let mut parser = OutputParser::new(format); |
| 196 | let mut final_text: Option<String> = None; |
| 197 | let mut failure_message: Option<String> = None; |
| 198 | let mut stdout_lines = BufReader::new(stdout).lines(); |
| 199 | let mut stop_armed = true; |
| 200 | |
| 201 | let mut handle_events = |parsed: Vec<RunEvent>| { |
| 202 | for event in parsed { |
| 203 | match &event { |
| 204 | RunEvent::Final(text) => final_text = Some(text.clone()), |
| 205 | RunEvent::Failed(message) => failure_message = Some(message.clone()), |
| 206 | _ => {} |
| 207 | } |
| 208 | let _ = events.send(RunUpdate::Event(event)); |
| 209 | } |
| 210 | }; |
| 211 | |
| 212 | loop { |
| 213 | tokio::select! { |
| 214 | stop_result = &mut stop, if stop_armed => { |
| 215 | if stop_result.is_ok() { |
| 216 | #[cfg(windows)] |
| 217 | if let Some(process_id) = child.id() { |
| 218 | run_stop_invocation(&taskkill_tree(process_id)).await; |
| 219 | } |
| 220 | let _ = child.kill().await; |
| 221 | if let Some(stop_invocation) = &plan.stop { |
| 222 | run_stop_invocation(stop_invocation).await; |
| 223 | } |
| 224 | stdin_task.abort(); |
| 225 | stderr_task.abort(); |
| 226 | return RunOutcome { status: RunStatus::Stopped, exit_code: None }; |
| 227 | } |
| 228 | stop_armed = false; |
| 229 | } |
| 230 | line = stdout_lines.next_line() => match line { |
| 231 | Ok(Some(line)) => handle_events(parser.feed(&line)), |
| 232 | _ => break, |
| 233 | } |
| 234 | } |
| 235 | } |
| 236 | handle_events(parser.finish()); |
| 237 | |
| 238 | let exit_code = child.wait().await.ok().and_then(|status| status.code()); |
| 239 | let _ = stdin_task.await; |
| 240 | let _ = stderr_task.await; |
| 241 | let tail = snapshot(&stderr_tail); |
| 242 | |
| 243 | match (exit_code, final_text) { |
| 244 | (Some(0), Some(final_text)) => RunOutcome { |
| 245 | status: RunStatus::Completed { final_text }, |
| 246 | exit_code, |
| 247 | }, |
| 248 | _ => { |
| 249 | let message = failure_message |
| 250 | .or_else(|| tail.last().cloned()) |
| 251 | .unwrap_or_else(|| match exit_code { |
| 252 | Some(code) => format!("exited with code {code}"), |
| 253 | None => "exited without a result".to_string(), |
| 254 | }); |
| 255 | failed(message, tail, exit_code) |
| 256 | } |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | fn first_line(bytes: &[u8]) -> Option<String> { |
| 261 | String::from_utf8_lossy(bytes) |
| 262 | .lines() |
| 263 | .map(str::trim) |
| 264 | .find(|line| !line.is_empty()) |
| 265 | .map(str::to_string) |
| 266 | } |
| 267 | |
| 268 | pub async fn probe(invocation: &Invocation) -> Result<String, String> { |
| 269 | let mut command = command_for(invocation); |
| 270 | command |
| 271 | .stdin(Stdio::null()) |
| 272 | .stdout(Stdio::piped()) |
| 273 | .stderr(Stdio::piped()); |
| 274 | let child = command |
| 275 | .spawn() |
| 276 | .map_err(|error| format!("cannot start {}: {error}", invocation.program))?; |
| 277 | let output = tokio::time::timeout(PROBE_TIMEOUT, child.wait_with_output()) |
| 278 | .await |
| 279 | .map_err(|_| "no answer within 10 seconds".to_string())? |
| 280 | .map_err(|error| error.to_string())?; |
| 281 | if output.status.success() { |
| 282 | return Ok(first_line(&output.stdout) |
| 283 | .or_else(|| first_line(&output.stderr)) |
| 284 | .unwrap_or_default()); |
| 285 | } |
| 286 | Err(first_line(&output.stderr) |
| 287 | .or_else(|| first_line(&output.stdout)) |
| 288 | .unwrap_or_else(|| match output.status.code() { |
| 289 | Some(code) => format!("exited with code {code}"), |
| 290 | None => "exited without a result".to_string(), |
| 291 | })) |
| 292 | } |