retry_if/
configuration.rs

1use std::time::Duration;
2
3/// Configuration for an exponential backoff, allowing control over the entire strategy.
4///
5/// This will retry a failing operation up to `max_tries`, waiting for a duration of `t_wait` on the
6/// first failure and `t_wait * backoff**attempt` for all remaining attempts. The maximum single wait
7/// can be capped by `backoff_max`, and the total waiting time before failing can be set with `t_wait_max`.
8///
9/// The behavior of `t_wait_max` is such that the function guarantees it will not begin sleeping if
10/// sleeping would cause the function to exceed a total execution time of `t_wait_max`. It is
11/// however possible for the execution to exceed `t_wait_max` if the decorated code
12/// (e.g. calling an API) causes it to exceed this time.
13///
14///
15/// # Example: Classic Exponential Backoff
16/// This backoff configuration will retry up to 5 times, waiting 1 second at first, then 2 seconds,
17/// 4 seconds, etc.
18/// ```
19/// # use crate::retry_if::ExponentialBackoffConfig;
20/// # use tokio::time::Duration;
21///
22/// const BACKOFF_CONFIG: ExponentialBackoffConfig = ExponentialBackoffConfig {
23///     max_retries: 5,
24///     t_wait: Duration::from_secs(1),
25///     backoff: 2.0,
26///     t_wait_max: None,
27///     backoff_max: None,
28/// };
29/// ```
30///
31/// # Example: Constant Linear Retries
32/// This configuration will retry up to five times, with no exponential behavior, since the backoff
33/// exponent is `1.0`. It will wait 1 second for all retry attempts.
34/// ```
35/// # use crate::retry_if::ExponentialBackoffConfig;
36/// # use tokio::time::Duration;
37///
38/// const BACKOFF_CONFIG: ExponentialBackoffConfig = ExponentialBackoffConfig {
39///     max_retries: 5,
40///     t_wait: Duration::from_secs(1),
41///     backoff: 1.0,
42///     t_wait_max: None,
43///     backoff_max: None,
44/// };
45/// ```
46///
47/// # Example: Backoff With a Maximum Wait Time
48/// This backoff configuration will retry up to 25 times, doubling the wait with each retry.
49///
50/// Setting `t_wait_max` to 10 minutes means that regardless of the number of retries or backoff
51/// exponent, it will return in 10 minutes or less.
52///
53/// ```
54/// # use crate::retry_if::ExponentialBackoffConfig;
55/// # use tokio::time::Duration;
56///
57/// const BACKOFF_CONFIG: ExponentialBackoffConfig = ExponentialBackoffConfig {
58///     max_retries: 25,
59///     t_wait: Duration::from_secs(1),
60///     backoff: 2.0,
61///     t_wait_max: Some(Duration::from_secs(600)),
62///     backoff_max: None,
63/// };
64/// ```
65///
66/// # Example: Limited Backoff
67/// This backoff configuration will retry up to 15 times, waiting 1 second at first, then 2 seconds,
68/// 4 seconds, etc.
69///
70/// Setting `backoff_max` to 30 seconds ensures it will exponentially back off until reaching a 30s
71/// wait time, then will continue to retry every 30s until it succeeds, exhausts retries, or hits
72/// `t_wait_max` (not configured in this case).
73/// ```
74/// # use crate::retry_if::ExponentialBackoffConfig;
75/// # use tokio::time::Duration;
76///
77/// const BACKOFF_CONFIG: ExponentialBackoffConfig = ExponentialBackoffConfig {
78///     max_retries: 15,
79///     t_wait: Duration::from_secs(1),
80///     backoff: 2.0,
81///     t_wait_max: None,
82///     backoff_max: Some(Duration::from_secs(30)),
83/// };
84/// ```
85
86#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
87#[derive(Debug, Clone, Copy, PartialEq)]
88pub struct ExponentialBackoffConfig {
89    /// maximum number of retry attempts to make
90    pub max_retries: i32,
91    /// initial duration to wait
92    pub t_wait: Duration,
93    /// backoff exponent, e.g. `2.0` for a classic exponential backoff
94    pub backoff: f64,
95    /// maximum time to attempt retries before returning the last result
96    pub t_wait_max: Option<Duration>,
97    /// maximum time to wait for any single retry, i.e. backoff exponentially up to this duration,
98    /// then wait in constant time of `backoff_max`
99    pub backoff_max: Option<Duration>,
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105
106    #[cfg(feature = "serde")]
107    #[test]
108    fn test_simple_deserialization() {
109        let raw = r#"{"max_retries": 3, "t_wait": {"secs": 5,"nanos": 0}, "backoff": 2}"#;
110        let expected_config = ExponentialBackoffConfig {
111            max_retries: 3,
112            t_wait: Duration::from_secs(5),
113            backoff: 2.0,
114            t_wait_max: None,
115            backoff_max: None,
116        };
117
118        let config: ExponentialBackoffConfig = serde_json::from_str(raw).unwrap();
119
120        assert_eq!(expected_config, config);
121    }
122
123    #[cfg(feature = "serde")]
124    #[test]
125    fn test_deserialization_with_optionals() {
126        let raw = r#"{
127            "max_retries": 3,
128            "t_wait": {"secs": 5,"nanos": 0},
129            "backoff": 2,
130            "t_wait_max": {"secs": 120,"nanos": 0},
131            "backoff_max": {"secs": 15,"nanos": 0}
132        }"#;
133        let expected_config = ExponentialBackoffConfig {
134            max_retries: 3,
135            t_wait: Duration::from_secs(5),
136            backoff: 2.0,
137            t_wait_max: Some(Duration::from_secs(120)),
138            backoff_max: Some(Duration::from_secs(15)),
139        };
140
141        let config: ExponentialBackoffConfig = serde_json::from_str(raw).unwrap();
142
143        assert_eq!(expected_config, config);
144    }
145}