|
1 | 1 | use crate::errors::HandlerResult;
|
2 | 2 | use crate::serde::{Deserialize, Serialize};
|
3 | 3 | use std::future::Future;
|
| 4 | +use std::time::Duration; |
4 | 5 |
|
5 | 6 | /// Run closure trait
|
6 | 7 | pub trait RunClosure {
|
|
23 | 24 | self()
|
24 | 25 | }
|
25 | 26 | }
|
| 27 | + |
| 28 | +/// This struct represents the policy to execute retries for run closures. |
| 29 | +#[derive(Debug, Clone)] |
| 30 | +pub struct RunRetryPolicy { |
| 31 | + pub(crate) initial_interval: Duration, |
| 32 | + pub(crate) factor: f32, |
| 33 | + pub(crate) max_interval: Option<Duration>, |
| 34 | + pub(crate) max_attempts: Option<u32>, |
| 35 | + pub(crate) max_duration: Option<Duration>, |
| 36 | +} |
| 37 | + |
| 38 | +impl Default for RunRetryPolicy { |
| 39 | + fn default() -> Self { |
| 40 | + Self { |
| 41 | + initial_interval: Duration::from_millis(100), |
| 42 | + factor: 2.0, |
| 43 | + max_interval: Some(Duration::from_secs(2)), |
| 44 | + max_attempts: None, |
| 45 | + max_duration: Some(Duration::from_secs(50)), |
| 46 | + } |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +impl RunRetryPolicy { |
| 51 | + /// Create a new retry policy. |
| 52 | + pub fn new() -> Self { |
| 53 | + Self { |
| 54 | + initial_interval: Duration::from_millis(100), |
| 55 | + factor: 1.0, |
| 56 | + max_interval: None, |
| 57 | + max_attempts: None, |
| 58 | + max_duration: None, |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + /// Initial interval for the first retry attempt. |
| 63 | + pub fn with_initial_interval(mut self, initial_interval: Duration) -> Self { |
| 64 | + self.initial_interval = initial_interval; |
| 65 | + self |
| 66 | + } |
| 67 | + |
| 68 | + /// Maximum interval between retries. |
| 69 | + pub fn with_factor(mut self, factor: f32) -> Self { |
| 70 | + self.factor = factor; |
| 71 | + self |
| 72 | + } |
| 73 | + |
| 74 | + /// Maximum interval between retries. |
| 75 | + pub fn with_max_interval(mut self, max_interval: Duration) -> Self { |
| 76 | + self.max_interval = Some(max_interval); |
| 77 | + self |
| 78 | + } |
| 79 | + |
| 80 | + /// Gives up retrying when either this number of attempts is reached, |
| 81 | + /// or `max_duration` (if set) is reached first. |
| 82 | + /// Infinite retries if this field and `max_duration` are unset. |
| 83 | + pub fn with_max_attempts(mut self, max_attempts: u32) -> Self { |
| 84 | + self.max_attempts = Some(max_attempts); |
| 85 | + self |
| 86 | + } |
| 87 | + |
| 88 | + /// Gives up retrying when either the retry loop lasted for this given max duration, |
| 89 | + /// or `max_attempts` (if set) is reached first. |
| 90 | + /// Infinite retries if this field and `max_attempts` are unset. |
| 91 | + pub fn with_max_duration(mut self, max_duration: Duration) -> Self { |
| 92 | + self.max_duration = Some(max_duration); |
| 93 | + self |
| 94 | + } |
| 95 | +} |
0 commit comments