use super::*;
pub(super) fn backoff(attempt: u32) -> Duration {
Duration::from_millis(500 * 2u64.pow(attempt.saturating_sub(1).min(4)))
}
pub(super) fn attempts_note(error: &str, retries: u32) -> String {
match retries {
0 => error.to_string(),
n => {
let (first, rest) = error.split_once('\n').unwrap_or((error, ""));
let rest = if rest.is_empty() {
String::new()
} else {
format!("\n{rest}")
};
format!("{first} (after {} attempts){rest}", n + 1)
}
}
}
#[must_use = "the command only runs when `run` is called"]
pub struct StepCommand<'a, 'c> {
pub(super) step: &'a Step,
pub(super) command: Box<dyn BorrowMut<Command> + Send + Sync + 'c>,
pub(super) stdin: Option<Stdio>,
pub(super) timeout: Option<Duration>,
pub(super) retries: u32,
pub(super) tail: usize,
}
impl std::fmt::Debug for StepCommand<'_, '_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("StepCommand")
.field("step", self.step)
.field("command", (*self.command).borrow())
.field("timeout", &self.timeout)
.field("retries", &self.retries)
.field("tail", &self.tail)
.finish_non_exhaustive()
}
}
impl StepCommand<'_, '_> {
pub fn timeout(mut self, limit: Duration) -> Self {
self.timeout = Some(limit);
self
}
pub fn retries(mut self, n: u32) -> Self {
self.retries = n;
self
}
pub fn tail(mut self, lines: usize) -> Self {
self.tail = lines;
self
}
pub fn stdin(mut self, stdin: Stdio) -> Self {
self.stdin = Some(stdin);
self
}
pub fn run(mut self) -> Result<String, RunError> {
self.step.start_if_pending();
let stdin = self.stdin.take().unwrap_or_else(Stdio::null);
(*self.command).borrow_mut().stdin(stdin);
let mut attempt = 0;
loop {
match self.once() {
Ok(output) => {
self.step.settle_after(attempt);
return Ok(output);
}
Err(e) if attempt < self.retries && e.kind.retryable() => {
attempt += 1;
self.step
.detail(format!("attempt {} of {} · {e}", attempt + 1, self.retries + 1));
thread::sleep(backoff(attempt));
}
Err(e) => {
let mut note = e.to_string();
let lines: Vec<&str> = e.output.lines().filter(|l| !l.trim().is_empty()).collect();
for line in &lines[lines.len().saturating_sub(self.tail)..] {
note += "\n";
note += line;
}
self.step.fail(attempts_note(¬e, attempt));
return Err(e);
}
}
}
}
fn once(&mut self) -> Result<String, RunError> {
let command = (*self.command).borrow_mut();
let program = command.get_program().to_string_lossy().into_owned();
let mut child = command
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|e| RunError {
program: program.clone(),
output: String::new(),
kind: RunErrorKind::Spawn(e),
})?;
let lines = Arc::new(Mutex::new(Vec::<String>::new()));
let readers: Vec<JoinHandle<()>> = [
child.stdout.take().map(|p| Box::new(p) as Box<dyn Read + Send>),
child.stderr.take().map(|p| Box::new(p) as Box<dyn Read + Send>),
]
.into_iter()
.flatten()
.map(|pipe| {
let (lines, step) = (lines.clone(), self.step.clone());
thread::spawn(move || read_lines(pipe, &lines, &step))
})
.collect();
let started = Instant::now();
let outcome = loop {
match child.try_wait() {
Ok(Some(status)) => break Ok(status),
Ok(None) if self.timeout.is_some_and(|t| started.elapsed() >= t) => {
let _ = child.kill();
let _ = child.wait();
break Err(RunErrorKind::TimedOut(self.timeout.unwrap_or_default()));
}
Ok(None) => thread::sleep(Duration::from_millis(30)),
Err(e) => break Err(RunErrorKind::Spawn(e)),
}
};
let grace = Instant::now() + Duration::from_millis(250);
while readers.iter().any(|r| !r.is_finished()) && Instant::now() < grace {
thread::sleep(Duration::from_millis(10));
}
for reader in readers.into_iter().filter(JoinHandle::is_finished) {
let _ = reader.join();
}
let output = lock(&lines).join("\n");
let kind = match outcome {
Ok(status) if status.success() => return Ok(output),
Ok(status) => RunErrorKind::Exit(status),
Err(kind) => kind,
};
Err(RunError { program, output, kind })
}
}
pub(super) fn read_lines(mut pipe: Box<dyn Read + Send>, lines: &Mutex<Vec<String>>, step: &Step) {
let mut pending = Vec::new();
let mut buf = [0u8; 4096];
let finish = |bytes: &mut Vec<u8>| {
let line = crate::text::strip_ansi(&String::from_utf8_lossy(bytes));
bytes.clear();
let line = line.trim_end().to_string();
if line.trim().is_empty() {
return;
}
step.detail(crate::text::truncate(line.trim(), 60));
lock(lines).push(line);
};
loop {
let n = match pipe.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => n,
};
for &b in &buf[..n] {
if b == b'\n' || b == b'\r' {
finish(&mut pending);
} else {
pending.push(b);
}
}
}
finish(&mut pending);
}
#[derive(Debug)]
pub struct RunError {
program: String,
output: String,
kind: RunErrorKind,
}
#[derive(Debug)]
#[non_exhaustive]
pub enum RunErrorKind {
Spawn(std::io::Error),
Exit(ExitStatus),
TimedOut(Duration),
}
impl RunErrorKind {
fn retryable(&self) -> bool {
!matches!(self, RunErrorKind::Spawn(_))
}
}
impl RunError {
pub fn program(&self) -> &str {
&self.program
}
pub fn kind(&self) -> &RunErrorKind {
&self.kind
}
pub fn code(&self) -> Option<i32> {
self.status().and_then(|s| s.code())
}
pub fn output(&self) -> &str {
&self.output
}
pub fn status(&self) -> Option<ExitStatus> {
match self.kind {
RunErrorKind::Exit(status) => Some(status),
_ => None,
}
}
pub fn timed_out(&self) -> bool {
matches!(self.kind, RunErrorKind::TimedOut(_))
}
}
impl std::fmt::Display for RunError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let program = &self.program;
match &self.kind {
RunErrorKind::Spawn(e) => write!(f, "couldn't run {program}: {e}"),
RunErrorKind::Exit(status) => match status.code() {
Some(code) => write!(f, "{program} exited with status {code}"),
None => write!(f, "{program} was stopped by a signal"),
},
RunErrorKind::TimedOut(limit) => write!(f, "{program} timed out after {}", format::duration(*limit)),
}
}
}
impl std::error::Error for RunError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
RunErrorKind::Spawn(e) => Some(e),
_ => None,
}
}
}
const _: fn() = || {
fn send_sync<T: Send + Sync>() {}
send_sync::<StepCommand<'static, 'static>>();
};