1use super::*;
4
5pub(super) fn backoff(attempt: u32) -> Duration {
7 Duration::from_millis(500 * 2u64.pow(attempt.saturating_sub(1).min(4)))
8}
9
10pub(super) fn attempts_note(error: &str, retries: u32) -> String {
11 match retries {
12 0 => error.to_string(),
13 n => {
14 let (first, rest) = error.split_once('\n').unwrap_or((error, ""));
15 let rest = if rest.is_empty() {
16 String::new()
17 } else {
18 format!("\n{rest}")
19 };
20 format!("{first} (after {} attempts){rest}", n + 1)
21 }
22 }
23}
24
25#[must_use = "the command only runs when `run` is called"]
41pub struct StepCommand<'a, 'c> {
42 pub(super) step: &'a Step,
43 pub(super) command: Box<dyn BorrowMut<Command> + Send + Sync + 'c>,
44 pub(super) stdin: Option<Stdio>,
45 pub(super) timeout: Option<Duration>,
46 pub(super) retries: u32,
47 pub(super) tail: usize,
48}
49
50impl std::fmt::Debug for StepCommand<'_, '_> {
51 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52 f.debug_struct("StepCommand")
53 .field("step", self.step)
54 .field("command", (*self.command).borrow())
55 .field("timeout", &self.timeout)
56 .field("retries", &self.retries)
57 .field("tail", &self.tail)
58 .finish_non_exhaustive()
59 }
60}
61
62impl StepCommand<'_, '_> {
63 pub fn timeout(mut self, limit: Duration) -> Self {
65 self.timeout = Some(limit);
66 self
67 }
68
69 pub fn retries(mut self, n: u32) -> Self {
72 self.retries = n;
73 self
74 }
75
76 pub fn tail(mut self, lines: usize) -> Self {
78 self.tail = lines;
79 self
80 }
81
82 pub fn stdin(mut self, stdin: Stdio) -> Self {
95 self.stdin = Some(stdin);
96 self
97 }
98
99 pub fn run(mut self) -> Result<String, RunError> {
107 self.step.start_if_pending();
108 let stdin = self.stdin.take().unwrap_or_else(Stdio::null);
109 (*self.command).borrow_mut().stdin(stdin);
110 let mut attempt = 0;
111 loop {
112 match self.once() {
113 Ok(output) => {
114 self.step.settle_after(attempt);
115 return Ok(output);
116 }
117 Err(e) if attempt < self.retries && e.kind.retryable() => {
118 attempt += 1;
119 self.step
120 .detail(format!("attempt {} of {} ยท {e}", attempt + 1, self.retries + 1));
121 thread::sleep(backoff(attempt));
122 }
123 Err(e) => {
124 let mut note = e.to_string();
125 let lines: Vec<&str> = e.output.lines().filter(|l| !l.trim().is_empty()).collect();
126 for line in &lines[lines.len().saturating_sub(self.tail)..] {
127 note += "\n";
128 note += line;
129 }
130 self.step.fail(attempts_note(¬e, attempt));
131 return Err(e);
132 }
133 }
134 }
135 }
136
137 fn once(&mut self) -> Result<String, RunError> {
138 let command = (*self.command).borrow_mut();
139 let program = command.get_program().to_string_lossy().into_owned();
140 let mut child = command
141 .stdout(Stdio::piped())
142 .stderr(Stdio::piped())
143 .spawn()
144 .map_err(|e| RunError {
145 program: program.clone(),
146 output: String::new(),
147 kind: RunErrorKind::Spawn(e),
148 })?;
149 let lines = Arc::new(Mutex::new(Vec::<String>::new()));
150 let readers: Vec<JoinHandle<()>> = [
151 child.stdout.take().map(|p| Box::new(p) as Box<dyn Read + Send>),
152 child.stderr.take().map(|p| Box::new(p) as Box<dyn Read + Send>),
153 ]
154 .into_iter()
155 .flatten()
156 .map(|pipe| {
157 let (lines, step) = (lines.clone(), self.step.clone());
158 thread::spawn(move || read_lines(pipe, &lines, &step))
159 })
160 .collect();
161
162 let started = Instant::now();
163 let outcome = loop {
164 match child.try_wait() {
165 Ok(Some(status)) => break Ok(status),
166 Ok(None) if self.timeout.is_some_and(|t| started.elapsed() >= t) => {
167 let _ = child.kill();
168 let _ = child.wait();
169 break Err(RunErrorKind::TimedOut(self.timeout.unwrap_or_default()));
170 }
171 Ok(None) => thread::sleep(Duration::from_millis(30)),
172 Err(e) => break Err(RunErrorKind::Spawn(e)),
173 }
174 };
175 let grace = Instant::now() + Duration::from_millis(250);
179 while readers.iter().any(|r| !r.is_finished()) && Instant::now() < grace {
180 thread::sleep(Duration::from_millis(10));
181 }
182 for reader in readers.into_iter().filter(JoinHandle::is_finished) {
183 let _ = reader.join();
184 }
185 let output = lock(&lines).join("\n");
186 let kind = match outcome {
187 Ok(status) if status.success() => return Ok(output),
188 Ok(status) => RunErrorKind::Exit(status),
189 Err(kind) => kind,
190 };
191 Err(RunError { program, output, kind })
192 }
193}
194
195pub(super) fn read_lines(mut pipe: Box<dyn Read + Send>, lines: &Mutex<Vec<String>>, step: &Step) {
198 let mut pending = Vec::new();
199 let mut buf = [0u8; 4096];
200 let finish = |bytes: &mut Vec<u8>| {
201 let line = crate::text::strip_ansi(&String::from_utf8_lossy(bytes));
202 bytes.clear();
203 let line = line.trim_end().to_string();
204 if line.trim().is_empty() {
205 return;
206 }
207 step.detail(crate::text::truncate(line.trim(), 60));
208 lock(lines).push(line);
209 };
210 loop {
211 let n = match pipe.read(&mut buf) {
212 Ok(0) | Err(_) => break,
213 Ok(n) => n,
214 };
215 for &b in &buf[..n] {
216 if b == b'\n' || b == b'\r' {
217 finish(&mut pending);
218 } else {
219 pending.push(b);
220 }
221 }
222 }
223 finish(&mut pending);
224}
225
226#[derive(Debug)]
228pub struct RunError {
229 program: String,
230 output: String,
231 kind: RunErrorKind,
232}
233
234#[derive(Debug)]
236#[non_exhaustive]
237pub enum RunErrorKind {
238 Spawn(std::io::Error),
240 Exit(ExitStatus),
242 TimedOut(Duration),
244}
245
246impl RunErrorKind {
247 fn retryable(&self) -> bool {
249 !matches!(self, RunErrorKind::Spawn(_))
250 }
251}
252
253impl RunError {
254 pub fn program(&self) -> &str {
256 &self.program
257 }
258
259 pub fn kind(&self) -> &RunErrorKind {
261 &self.kind
262 }
263
264 pub fn code(&self) -> Option<i32> {
267 self.status().and_then(|s| s.code())
268 }
269
270 pub fn output(&self) -> &str {
272 &self.output
273 }
274
275 pub fn status(&self) -> Option<ExitStatus> {
277 match self.kind {
278 RunErrorKind::Exit(status) => Some(status),
279 _ => None,
280 }
281 }
282
283 pub fn timed_out(&self) -> bool {
285 matches!(self.kind, RunErrorKind::TimedOut(_))
286 }
287}
288
289impl std::fmt::Display for RunError {
290 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
291 let program = &self.program;
292 match &self.kind {
293 RunErrorKind::Spawn(e) => write!(f, "couldn't run {program}: {e}"),
294 RunErrorKind::Exit(status) => match status.code() {
295 Some(code) => write!(f, "{program} exited with status {code}"),
296 None => write!(f, "{program} was stopped by a signal"),
297 },
298 RunErrorKind::TimedOut(limit) => write!(f, "{program} timed out after {}", format::duration(*limit)),
299 }
300 }
301}
302
303impl std::error::Error for RunError {
304 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
305 match &self.kind {
306 RunErrorKind::Spawn(e) => Some(e),
307 _ => None,
308 }
309 }
310}
311
312const _: fn() = || {
314 fn send_sync<T: Send + Sync>() {}
315 send_sync::<StepCommand<'static, 'static>>();
316};