use std::ops::ControlFlow;
use std::sync::Arc;
use std::time::Duration;
use crate::errors::Error;
pub trait RetryPolicy: Send + Sync + 'static {
fn should_retry(&self, ctx: &RetryContext<'_>) -> ControlFlow<(), Duration>;
fn retries_file_parts(&self) -> bool {
true
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy)]
pub struct RetryContext<'a> {
pub request: &'static str,
pub error: &'a Error,
pub fail_count: u32,
pub flood_count: u32,
pub slept_so_far: Duration,
pub flood_wait: Option<Duration>,
pub file_part: bool,
}
const PART_TRIES_PER_TRY: usize = 4;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AutoSleep {
pub threshold: Duration,
pub tries: usize,
}
impl Default for AutoSleep {
fn default() -> Self {
AutoSleep { threshold: Duration::from_secs(60), tries: 5 }
}
}
impl AutoSleep {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn threshold(mut self, threshold: Duration) -> Self {
self.threshold = threshold;
self
}
#[must_use]
pub fn tries(mut self, tries: usize) -> Self {
self.tries = tries;
self
}
}
impl RetryPolicy for AutoSleep {
fn should_retry(&self, ctx: &RetryContext<'_>) -> ControlFlow<(), Duration> {
let tries = if ctx.file_part { self.tries.saturating_mul(PART_TRIES_PER_TRY) } else { self.tries };
match ctx.flood_wait {
Some(wait) if wait <= self.threshold && ctx.flood_count as usize <= tries => ControlFlow::Continue(wait),
_ => ControlFlow::Break(()),
}
}
}
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct Tally {
pub(crate) failures: u32,
pub(crate) floods: u32,
pub(crate) slept: Duration,
}
impl Tally {
pub(crate) fn failed(&mut self, error: &Error) {
self.failures += 1;
if error.flood_wait().is_some() {
self.floods += 1;
}
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct NoRetries;
impl RetryPolicy for NoRetries {
fn should_retry(&self, _: &RetryContext<'_>) -> ControlFlow<(), Duration> {
ControlFlow::Break(())
}
fn retries_file_parts(&self) -> bool {
false
}
}
#[derive(Clone)]
pub struct Retry(pub Arc<dyn RetryPolicy>);
impl Retry {
pub fn new(policy: impl RetryPolicy) -> Retry {
Retry(Arc::new(policy))
}
}
impl Default for Retry {
fn default() -> Self {
Retry::new(AutoSleep::default())
}
}
impl std::fmt::Debug for Retry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Retry")
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::errors::RpcError;
fn ask(policy: &impl RetryPolicy, flood_wait: Option<u64>, fail_count: u32) -> ControlFlow<(), Duration> {
ask_about(policy, flood_wait, fail_count, false)
}
fn ask_about(
policy: &impl RetryPolicy,
flood_wait: Option<u64>,
fail_count: u32,
file_part: bool,
) -> ControlFlow<(), Duration> {
let error = Error::Rpc(RpcError::parse(420, "FLOOD_WAIT_1"));
let flood_wait = flood_wait.map(Duration::from_secs);
let slept_so_far = Duration::ZERO;
let ctx = RetryContext {
request: "x.y",
error: &error,
fail_count,
flood_count: fail_count,
slept_so_far,
flood_wait,
file_part,
};
policy.should_retry(&ctx)
}
#[test]
fn auto_sleep_follows_its_threshold_and_tries() {
let policy = AutoSleep { threshold: Duration::from_secs(10), tries: 2 };
let sleep = |secs| ControlFlow::Continue(Duration::from_secs(secs));
assert_eq!(ask(&policy, Some(10), 1), sleep(10));
assert_eq!(ask(&policy, Some(3), 2), sleep(3));
assert_eq!(ask(&policy, Some(3), 3), ControlFlow::Break(()), "a third retry is over the tries");
assert_eq!(ask(&policy, Some(11), 1), ControlFlow::Break(()), "a wait over the threshold");
assert_eq!(ask(&policy, None, 1), ControlFlow::Break(()), "not a flood wait");
assert_eq!(ask(&AutoSleep { tries: 0, ..policy }, Some(1), 1), ControlFlow::Break(()));
assert_eq!(ask(&AutoSleep { threshold: Duration::ZERO, ..policy }, Some(1), 1), ControlFlow::Break(()));
assert_eq!(AutoSleep::default(), AutoSleep { threshold: Duration::from_secs(60), tries: 5 });
}
#[test]
fn no_retries_never_retries() {
assert_eq!(ask(&NoRetries, Some(1), 1), ControlFlow::Break(()));
}
#[test]
fn auto_sleep_new_keeps_the_defaults_a_setter_leaves_alone() {
let patient = AutoSleep::new().threshold(Duration::from_secs(300));
assert_eq!(patient.tries, 5);
assert_eq!(ask(&patient, Some(200), 1), ControlFlow::Continue(Duration::from_secs(200)));
assert_eq!(ask(&AutoSleep::new().tries(0), Some(1), 1), ControlFlow::Break(()));
}
#[test]
fn auto_sleep_gives_a_file_part_four_times_the_tries() {
let policy = AutoSleep::new();
assert_eq!(ask_about(&policy, Some(3), 6, false), ControlFlow::Break(()), "a 6th wait for a request");
assert_eq!(ask_about(&policy, Some(3), 20, true), ControlFlow::Continue(Duration::from_secs(3)));
assert_eq!(ask_about(&policy, Some(3), 21, true), ControlFlow::Break(()), "a 21st wait is over the tries");
assert_eq!(ask_about(&policy, Some(61), 1, true), ControlFlow::Break(()), "a wait over the threshold");
assert_eq!(ask_about(&AutoSleep::new().tries(0), Some(1), 1, true), ControlFlow::Break(()));
}
}