use std::future::Future;
use std::time::Duration;
use crate::cli::CliError;
use crate::cli::vagrant::Failure;
use crate::events::WarningCode;
pub(super) const PATIENCE: Duration = Duration::from_secs(60);
pub(super) const STATUS_PATIENCE: Duration = Duration::from_secs(10);
const POLL: Duration = Duration::from_secs(2);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Rerun {
Read,
Converges,
Repeats,
}
impl Rerun {
fn again(self, acted: bool) -> bool {
match self {
Rerun::Read | Rerun::Converges => true,
Rerun::Repeats => !acted,
}
}
}
pub(super) async fn retrying<T, F, Fut>(
warn: &(dyn Fn(WarningCode, &str) + Send + Sync),
what: &str,
rerun: Rerun,
patience: Duration,
mut attempt: F,
) -> Result<T, CliError<Failure>>
where
F: FnMut() -> Fut,
Fut: Future<Output = Result<T, CliError<Failure>>>,
{
let mut deadline = None;
loop {
let ended = attempt().await;
let again = match &ended {
Err(CliError::Failed {
failure: Failure::Locked { acted, .. },
..
}) => rerun.again(*acted),
_ => false,
};
if !again {
return ended;
}
let now = tokio::time::Instant::now();
let until = *deadline.get_or_insert(now + patience);
if now + POLL > until {
return ended;
}
tokio::time::sleep(POLL).await;
tracing::debug!(call = what, "another Vagrant process holds a machine's lock: made again");
if rerun != Rerun::Read {
warn(
WarningCode::Retrying,
&format!("`vagrant {what}`: another Vagrant process held a machine's lock; running it again"),
);
}
}
}
#[cfg(test)]
mod tests {
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
use super::*;
fn locked(acted: bool) -> CliError<Failure> {
CliError::Failed {
tool: "vagrant",
failure: Failure::Locked { acted, machines: Vec::new() },
}
}
#[tokio::test(start_paused = true)]
async fn a_refused_call_that_converges_is_made_again_until_it_goes_through() {
let tries = AtomicUsize::new(0);
let warned = Mutex::new(Vec::new());
let warn = |code: WarningCode, said: &str| warned.lock().unwrap().push((code, said.to_owned()));
let out = retrying(&warn, "halt", Rerun::Converges, PATIENCE, || async {
if tries.fetch_add(1, Ordering::SeqCst) < 2 { Err(locked(true)) } else { Ok(7) }
})
.await;
assert_eq!(out.unwrap(), 7);
assert_eq!(tries.load(Ordering::SeqCst), 3);
assert_eq!(warned.lock().unwrap().len(), 2, "each new try is said");
}
#[tokio::test(start_paused = true)]
async fn a_call_that_repeats_is_made_again_only_when_it_hadnt_acted() {
let quiet = |_: WarningCode, _: &str| {};
let tries = AtomicUsize::new(0);
let out: Result<(), _> = retrying(&quiet, "provision", Rerun::Repeats, PATIENCE, || async {
tries.fetch_add(1, Ordering::SeqCst);
Err(locked(true))
})
.await;
assert!(
matches!(
out,
Err(CliError::Failed {
failure: Failure::Locked { acted: true, .. },
..
})
),
"{out:?}"
);
assert_eq!(tries.load(Ordering::SeqCst), 1, "it had acted: never twice");
let fresh = AtomicUsize::new(0);
let through: Result<(), _> = retrying(&quiet, "provision", Rerun::Repeats, PATIENCE, || async {
if fresh.fetch_add(1, Ordering::SeqCst) == 0 {
Err(locked(false))
} else {
Ok(())
}
})
.await;
through.expect("a call that hadn't acted is made again");
assert_eq!(fresh.load(Ordering::SeqCst), 2);
}
#[tokio::test(start_paused = true)]
async fn the_patience_ends_the_tries_and_other_failures_end_them_at_once() {
let quiet = |_: WarningCode, _: &str| {};
let tries = AtomicUsize::new(0);
let out: Result<(), _> = retrying(&quiet, "status", Rerun::Read, STATUS_PATIENCE, || async {
tries.fetch_add(1, Ordering::SeqCst);
Err(locked(false))
})
.await;
assert!(matches!(
out,
Err(CliError::Failed {
failure: Failure::Locked { .. },
..
})
));
assert_eq!(tries.load(Ordering::SeqCst), 6, "10 s of patience, 2 s apart, after the first");
let other = AtomicUsize::new(0);
let failed: Result<(), _> = retrying(&quiet, "up", Rerun::Converges, PATIENCE, || async {
other.fetch_add(1, Ordering::SeqCst);
Err(CliError::Failed {
tool: "vagrant",
failure: Failure::Other("boom".into()),
})
})
.await;
assert!(
matches!(&failed, Err(CliError::Failed { failure: Failure::Other(why), .. }) if why == "boom"),
"{failed:?}"
);
assert_eq!(other.load(Ordering::SeqCst), 1, "never tried again");
}
}