//! Waiting out an object that has stopped answering for a while.//!//! A 5xx, a timeout or an unreachable server says nothing about the file being//! sent: the object comes back, usually within minutes. One [`Patience`] is//! shared by every thread of a run, so an outage slows the whole run down//! together rather than each thread finding it out alone, and the run gives up//! only after [`GIVE_UP`] with no answer from the object at all. Any answer,//! a refusal too, shows the object is there and starts that time again.use std::sync::Mutex;use std::time::{Duration, Instant};usecrate::object::ObjectError;/// The first wait after a failure; each further failure doubles it.pubconst FIRST_WAIT: Duration = Duration::from_secs(5);/// The longest one wait grows to.pubconst LONGEST_WAIT: Duration = Duration::from_secs(120);/// How long the object may say nothing before the run stops trying.pubconst GIVE_UP: Duration = Duration::from_secs(30 * 60);structState {/// When the object last answered anything. answered: Instant,/// Failures in a row, which set the length of the next wait. failures: u32,/// No call starts before this. not_before: Instant, gave_up: bool,}pubstructPatience { first: Duration, longest: Duration, give_up: Duration, state: Mutex<State>,}implDefaultforPatience {fn default() -> Patience {Patience::new(FIRST_WAIT, LONGEST_WAIT, GIVE_UP) }}implPatience {pubfn new(first: Duration, longest: Duration, give_up: Duration) -> Patience {let now = Instant::now();Patience { first, longest, give_up, state: Mutex::new(State { answered: now, failures: 0, not_before: now, gave_up: false }) } }fn state(&self) -> std::sync::MutexGuard<'_, State> {self.state.lock().unwrap_or_else(|p| p.into_inner()) }/// The wait after `failures` failures in a row: doubling, capped, with up/// to a quarter more so that senders do not come back in step.fn wait_after(&self, failures: u32) -> Duration {let doubled = self.first.saturating_mul(2u32.saturating_pow(failures.saturating_sub(1).min(16)));let wait = doubled.min(self.longest); wait + wait.mul_f64(rand::random::<f64>() / 4.0) }/// Sleep until a call may start; `false` once the run has given up, when/// the caller makes its one last try at once.fn hold(&self) -> bool {loop {let wait = {let state = self.state();if state.gave_up {returnfalse; } state.not_before.saturating_duration_since(Instant::now()) };if wait.is_zero() {returntrue; } std::thread::sleep(wait); } }fn answered(&self) {letmut state = self.state(); state.answered = Instant::now(); state.failures = 0; }/// A passing failure: `true` to try again. A failure of a call that/// started before the current wait was set does not lengthen it, so/// threads failing together count as one failure.fn failed(&self, why: &str) -> bool {letmut state = self.state();let now = Instant::now();if now.duration_since(state.answered) >= self.give_up { state.gave_up = true;returnfalse; }if now >= state.not_before { state.failures += 1;let wait = self.wait_after(state.failures); state.not_before = now + wait;if state.failures == 1 { eprintln!("the object is not answering ({why}); trying again for up to {} minutes", self.give_up.as_secs() / 60); } }true }/// `call` until it answers, for as long as its failures are passing ones/// (`passing`); any other failure is the object's answer and comes back/// as it is.pubfn attempt<T, E: std::fmt::Display>(&self, mut call: implFnMut() -> Result<T, E>, passing: implFn(&E) -> bool) -> Result<T, E> {loop {let waiting = self.hold();match call() {Ok(answer) => {self.answered();returnOk(answer); }Err(error) if passing(&error) => {if !waiting || !self.failed(&error.to_string()) {returnErr(error); } }Err(error) => {self.answered();returnErr(error); } } } }/// [`Patience::attempt`] of a call to the object.pubfn run<T>(&self, call: implFnMut() -> Result<T, ObjectError>) -> Result<T, ObjectError> {self.attempt(call, ObjectError::is_passing) }}#[cfg(test)]mod tests {usesuper::*;fn quick() -> Patience {Patience::new(Duration::from_millis(1), Duration::from_millis(4), Duration::from_secs(60)) }fn down() -> ObjectError {ObjectError::Refused { status: 500, code: "internal_error".into(), message: "the business did not answer".into() } } #[test]fn a_passing_failure_is_tried_again_until_the_object_answers() {letmut calls = 0;let answer = quick().run(|| { calls += 1;if calls < 5 { Err(down()) } else { Ok(calls) } }); assert_eq!(answer, Ok(5)); } #[test]fn a_refusal_is_the_objects_answer_and_is_not_tried_again() {letmut calls = 0;let answer: Result<(), _> = quick().run(|| { calls += 1;Err(ObjectError::Refused { status: 413, code: "object_full".into(), message: "full".into() }) }); assert!(answer.is_err()); assert_eq!(calls, 1); } #[test]fn it_gives_up_only_after_the_whole_time_without_an_answer() {let patience = Patience::new(Duration::from_millis(1), Duration::from_millis(2), Duration::from_millis(30));let started = Instant::now();let answer: Result<(), _> = patience.run(|| Err(down())); assert_eq!(answer, Err(down())); assert!(started.elapsed() >= Duration::from_millis(30));// Given up, the next file makes one try and does not wait the time again.letmut calls = 0;let again: Result<(), _> = patience.run(|| { calls += 1;Err(down()) }); assert!(again.is_err()); assert_eq!(calls, 1); } #[test]fn the_wait_doubles_and_stops_at_its_cap() {let patience = Patience::new(Duration::from_secs(5), Duration::from_secs(120), GIVE_UP);let within = |failures, least: u64| {let wait = patience.wait_after(failures); assert!(wait >= Duration::from_secs(least) && wait <= Duration::from_secs(least) + Duration::from_secs(least) / 4, "{wait:?}"); }; within(1, 5); within(2, 10); within(5, 80); within(6, 120); within(40, 120); }}