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
19const MAX_CAPTURE_BYTES: usize = 8 * 1024 * 1024;
23
24pub struct SubprocessSpec {
26 pub program: String,
27 pub args: Vec<String>,
28 pub workspace: PathBuf,
30 pub stdin: Option<String>,
33 pub timeout: Option<Duration>,
35 pub env: Vec<(String, String)>,
39}
40
41pub struct SubprocessOutput {
43 pub stdout: String,
44 pub stderr: String,
45 pub exit_code: Option<i32>,
46 pub status: ExecStatus,
47 pub wall_ms: u64,
48}
49
50pub type LineMapper = fn(&str) -> Vec<WorkerEvent>;
54
55pub async fn run(
57 spec: SubprocessSpec,
58 events: &EventSink,
59 cancel: &CancellationToken,
60 mapper: LineMapper,
61) -> Result<SubprocessOutput> {
62 let started = Instant::now();
63
64 let mut cmd = Command::new(&spec.program);
65 cmd.args(&spec.args)
66 .envs(spec.env.iter().map(|(k, v)| (k.clone(), v.clone())))
67 .current_dir(&spec.workspace)
68 .stdin(if spec.stdin.is_some() {
69 Stdio::piped()
70 } else {
71 Stdio::null()
72 })
73 .stdout(Stdio::piped())
74 .stderr(Stdio::piped())
75 .kill_on_drop(true);
76
77 let mut child = cmd
78 .spawn()
79 .map_err(|e| RinneError::Worker(format!("failed to spawn {}: {e}", spec.program)))?;
80
81 if let Some(input) = &spec.stdin {
82 if let Some(mut stdin) = child.stdin.take() {
83 stdin
84 .write_all(input.as_bytes())
85 .await
86 .map_err(|e| RinneError::Worker(format!("stdin write failed: {e}")))?;
87 }
89 }
90
91 let stdout = child
92 .stdout
93 .take()
94 .ok_or_else(|| RinneError::Worker("no stdout pipe".into()))?;
95 let stderr = child
96 .stderr
97 .take()
98 .ok_or_else(|| RinneError::Worker("no stderr pipe".into()))?;
99
100 let stderr_task = tokio::spawn(async move {
103 let mut buf = Vec::new();
104 let mut rdr = BufReader::new(stderr).take(MAX_CAPTURE_BYTES as u64);
105 let _ = rdr.read_to_end(&mut buf).await;
106 String::from_utf8_lossy(&buf).into_owned()
107 });
108
109 let mut lines = BufReader::new(stdout).lines();
110 let mut captured = String::new();
111 let mut truncated = false;
112
113 let deadline = spec
116 .timeout
117 .map(|d| Instant::now() + d)
118 .unwrap_or_else(|| Instant::now() + Duration::from_secs(60 * 60 * 24 * 365));
119 let sleep = tokio::time::sleep_until(tokio::time::Instant::from_std(deadline));
120 tokio::pin!(sleep);
121
122 let mut terminal: Option<ExecStatus> = None;
123
124 loop {
125 tokio::select! {
126 line = lines.next_line() => {
127 match line {
128 Ok(Some(l)) => {
129 if captured.len() < MAX_CAPTURE_BYTES {
131 captured.push_str(&l);
132 captured.push('\n');
133 } else if !truncated {
134 truncated = true;
135 captured.push_str("\n…[output truncated]\n");
136 }
137 for ev in mapper(&l) {
138 emit(events, ev);
139 }
140 }
141 Ok(None) => break, Err(e) => {
143 terminal = Some(ExecStatus::Failed(format!("stdout read error: {e}")));
144 break;
145 }
146 }
147 }
148 _ = cancel.cancelled() => {
149 let _ = child.start_kill();
150 terminal = Some(ExecStatus::Cancelled);
151 break;
152 }
153 _ = &mut sleep => {
154 let _ = child.start_kill();
155 terminal = Some(ExecStatus::TimedOut);
156 break;
157 }
158 }
159 }
160
161 let wait_status = match tokio::time::timeout(Duration::from_secs(5), child.wait()).await {
165 Ok(r) => r.map_err(|e| RinneError::Worker(format!("wait failed: {e}")))?,
166 Err(_) => {
167 let _ = child.start_kill();
168 child
169 .wait()
170 .await
171 .map_err(|e| RinneError::Worker(format!("wait failed: {e}")))?
172 }
173 };
174 let stderr_str = tokio::time::timeout(Duration::from_secs(2), stderr_task)
177 .await
178 .ok()
179 .and_then(|r| r.ok())
180 .unwrap_or_default();
181 let exit_code = wait_status.code();
182
183 let status = terminal.unwrap_or_else(|| {
184 if wait_status.success() {
185 ExecStatus::Success
186 } else {
187 let code = exit_code
188 .map(|c| c.to_string())
189 .unwrap_or_else(|| "signal".into());
190 ExecStatus::Failed(format!("exited {code}"))
191 }
192 });
193
194 emit(events, WorkerEvent::Done);
195
196 Ok(SubprocessOutput {
197 stdout: captured,
198 stderr: stderr_str,
199 exit_code,
200 status,
201 wall_ms: started.elapsed().as_millis() as u64,
202 })
203}
204
205pub fn raw_lines(line: &str) -> Vec<WorkerEvent> {
207 if line.trim().is_empty() {
208 Vec::new()
209 } else {
210 vec![WorkerEvent::Raw(line.to_string())]
211 }
212}