//! 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}; use crate::object::ObjectError; /// The first wait after a failure; each further failure doubles it. pub const FIRST_WAIT: Duration = Duration::from_secs(5); /// The longest one wait grows to. pub const LONGEST_WAIT: Duration = Duration::from_secs(120); /// How long the object may say nothing before the run stops trying. pub const GIVE_UP: Duration = Duration::from_secs(30 * 60); struct State { /// 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, } pub struct Patience { first: Duration, longest: Duration, give_up: Duration, state: Mutex, } impl Default for Patience { fn default() -> Patience { Patience::new(FIRST_WAIT, LONGEST_WAIT, GIVE_UP) } } impl Patience { pub fn 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::() / 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 { return false; } state.not_before.saturating_duration_since(Instant::now()) }; if wait.is_zero() { return true; } std::thread::sleep(wait); } } fn answered(&self) { let mut 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 { let mut state = self.state(); let now = Instant::now(); if now.duration_since(state.answered) >= self.give_up { state.gave_up = true; return false; } 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. pub fn attempt(&self, mut call: impl FnMut() -> Result, passing: impl Fn(&E) -> bool) -> Result { loop { let waiting = self.hold(); match call() { Ok(answer) => { self.answered(); return Ok(answer); } Err(error) if passing(&error) => { if !waiting || !self.failed(&error.to_string()) { return Err(error); } } Err(error) => { self.answered(); return Err(error); } } } } /// [`Patience::attempt`] of a call to the object. pub fn run(&self, call: impl FnMut() -> Result) -> Result { self.attempt(call, ObjectError::is_passing) } } #[cfg(test)] mod tests { use super::*; 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() { let mut 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() { let mut 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. let mut 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); } }