1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
use crate::Error;
use backoff::{backoff::Backoff, ExponentialBackoff};
use futures::Future;
use std::{fmt::Debug, time::Duration};
fn get_exponential_backoff() -> ExponentialBackoff {
ExponentialBackoff {
max_elapsed_time: Some(Duration::from_secs(60 * 10)), max_interval: Duration::from_secs(60 * 2), initial_interval: Duration::from_secs(1), current_interval: Duration::from_secs(1), multiplier: 2.0, randomization_factor: 0.25, ..Default::default()
}
}
pub enum RetryPolicy<E> {
Skip(E),
Throw(E),
}
pub async fn notify_retry<E, L, FL, R, FR, T>(call: L, verify: R) -> Result<T, Error>
where
E: Debug,
L: Fn() -> FL,
FL: Future<Output = Result<T, E>>,
R: Fn(Result<T, E>) -> FR,
FR: Future<Output = Result<T, RetryPolicy<Error>>>,
{
let mut backoff = get_exponential_backoff();
loop {
let err = match verify(call().await).await {
Ok(ok) => return Ok(ok),
Err(RetryPolicy::Skip(err)) => err,
Err(RetryPolicy::Throw(err)) => return Err(err),
};
match backoff.next_backoff() {
Some(wait) => {
log::warn!("{} - next retry in {:.3} s", err, wait.as_secs_f64());
tokio::time::sleep(wait).await;
}
None => break Err(Error::Timeout),
}
}
}