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