rinne_workers/transport/
subprocess.rs1use std::path::PathBuf;
9use std::process::Stdio;
10use std::time::{Duration, Instant};
11
12use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
13use tokio::process::Command;
14use tokio_util::sync::CancellationToken;
15
16use rinne_core::worker::{emit, EventSink, ExecStatus, WorkerEvent};
17use rinne_core::{Result, RinneError};
18
19pub struct SubprocessSpec {
21 pub program: String,
22 pub args: Vec<String>,
23 pub workspace: PathBuf,
25 pub stdin: Option<String>,
28 pub timeout: Option<Duration>,
30}
31
32pub struct SubprocessOutput {
34 pub stdout: String,
35 pub stderr: String,
36 pub exit_code: Option<i32>,
37 pub status: ExecStatus,
38 pub wall_ms: u64,
39}
40
41pub type LineMapper = fn(&str) -> Vec<WorkerEvent>;
45
46pub async fn run(
48 spec: SubprocessSpec,
49 events: &EventSink,
50 cancel: &CancellationToken,
51 mapper: LineMapper,
52) -> Result<SubprocessOutput> {
53 let started = Instant::now();
54
55 let mut cmd = Command::new(&spec.program);
56 cmd.args(&spec.args)
57 .current_dir(&spec.workspace)
58 .stdin(if spec.stdin.is_some() {
59 Stdio::piped()
60 } else {
61 Stdio::null()
62 })
63 .stdout(Stdio::piped())
64 .stderr(Stdio::piped())
65 .kill_on_drop(true);
66
67 let mut child = cmd
68 .spawn()
69 .map_err(|e| RinneError::Worker(format!("failed to spawn {}: {e}", spec.program)))?;
70
71 if let Some(input) = &spec.stdin {
72 if let Some(mut stdin) = child.stdin.take() {
73 stdin
74 .write_all(input.as_bytes())
75 .await
76 .map_err(|e| RinneError::Worker(format!("stdin write failed: {e}")))?;
77 }
79 }
80
81 let stdout = child
82 .stdout
83 .take()
84 .ok_or_else(|| RinneError::Worker("no stdout pipe".into()))?;
85 let stderr = child
86 .stderr
87 .take()
88 .ok_or_else(|| RinneError::Worker("no stderr pipe".into()))?;
89
90 let stderr_task = tokio::spawn(async move {
92 let mut buf = String::new();
93 let mut rdr = BufReader::new(stderr);
94 let _ = rdr.read_to_string(&mut buf).await;
95 buf
96 });
97
98 let mut lines = BufReader::new(stdout).lines();
99 let mut captured = String::new();
100
101 let deadline = spec
104 .timeout
105 .map(|d| Instant::now() + d)
106 .unwrap_or_else(|| Instant::now() + Duration::from_secs(60 * 60 * 24 * 365));
107 let sleep = tokio::time::sleep_until(tokio::time::Instant::from_std(deadline));
108 tokio::pin!(sleep);
109
110 let mut terminal: Option<ExecStatus> = None;
111
112 loop {
113 tokio::select! {
114 line = lines.next_line() => {
115 match line {
116 Ok(Some(l)) => {
117 captured.push_str(&l);
118 captured.push('\n');
119 for ev in mapper(&l) {
120 emit(events, ev);
121 }
122 }
123 Ok(None) => break, Err(e) => {
125 terminal = Some(ExecStatus::Failed(format!("stdout read error: {e}")));
126 break;
127 }
128 }
129 }
130 _ = cancel.cancelled() => {
131 let _ = child.start_kill();
132 terminal = Some(ExecStatus::Cancelled);
133 break;
134 }
135 _ = &mut sleep => {
136 let _ = child.start_kill();
137 terminal = Some(ExecStatus::TimedOut);
138 break;
139 }
140 }
141 }
142
143 let wait_status = child
144 .wait()
145 .await
146 .map_err(|e| RinneError::Worker(format!("wait failed: {e}")))?;
147 let stderr_str = stderr_task.await.unwrap_or_default();
148 let exit_code = wait_status.code();
149
150 let status = terminal.unwrap_or_else(|| {
151 if wait_status.success() {
152 ExecStatus::Success
153 } else {
154 let code = exit_code
155 .map(|c| c.to_string())
156 .unwrap_or_else(|| "signal".into());
157 ExecStatus::Failed(format!("exited {code}"))
158 }
159 });
160
161 emit(events, WorkerEvent::Done);
162
163 Ok(SubprocessOutput {
164 stdout: captured,
165 stderr: stderr_str,
166 exit_code,
167 status,
168 wall_ms: started.elapsed().as_millis() as u64,
169 })
170}
171
172pub fn raw_lines(line: &str) -> Vec<WorkerEvent> {
174 if line.trim().is_empty() {
175 Vec::new()
176 } else {
177 vec![WorkerEvent::Raw(line.to_string())]
178 }
179}