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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
use crate::RetryPolicy;
use std::time::Duration;
pub trait BackoffStrategy<E> {
type Output;
fn delay(&mut self, attempt: u32, error: &E) -> Self::Output;
}
#[derive(Debug)]
pub struct NoBackoff;
impl<E> BackoffStrategy<E> for NoBackoff {
type Output = Duration;
#[inline]
fn delay(&mut self, _attempt: u32, _error: &E) -> Duration {
Duration::new(0, 0)
}
}
#[derive(Debug)]
pub struct ExponentialBackoff {
pub(crate) delay: Duration,
}
impl<E> BackoffStrategy<E> for ExponentialBackoff {
type Output = Duration;
#[inline]
fn delay(&mut self, _attempt: u32, _error: &E) -> Duration {
let prev_delay = self.delay;
self.delay *= 2;
prev_delay
}
}
#[derive(Debug)]
pub struct FixedBackoff {
pub(crate) delay: Duration,
}
impl<E> BackoffStrategy<E> for FixedBackoff {
type Output = Duration;
#[inline]
fn delay(&mut self, _attempt: u32, _error: &E) -> Duration {
self.delay
}
}
#[derive(Debug)]
pub struct LinearBackoff {
pub(crate) delay: Duration,
}
impl<E> BackoffStrategy<E> for LinearBackoff {
type Output = Duration;
#[inline]
fn delay(&mut self, attempt: u32, _error: &E) -> Duration {
self.delay * attempt
}
}
#[derive(Debug)]
pub struct CustomBackoffStrategy<F> {
pub(crate) f: F,
}
impl<F, E, T> BackoffStrategy<E> for CustomBackoffStrategy<F>
where
F: FnMut(u32, &E) -> T,
RetryPolicy: From<T>,
{
type Output = RetryPolicy;
#[inline]
fn delay(&mut self, attempt: u32, error: &E) -> RetryPolicy {
RetryPolicy::from((self.f)(attempt, error))
}
}