|
| 1 | +use std::time::Duration; |
| 2 | + |
| 3 | +use backoff::{ |
| 4 | + default::{INITIAL_INTERVAL_MILLIS, MAX_INTERVAL_MILLIS, MULTIPLIER, RANDOMIZATION_FACTOR}, |
| 5 | + ExponentialBackoff, ExponentialBackoffBuilder, |
| 6 | +}; |
| 7 | + |
| 8 | +#[derive(Debug)] |
| 9 | +pub struct PythLazerExponentialBackoffBuilder { |
| 10 | + initial_interval: Duration, |
| 11 | + randomization_factor: f64, |
| 12 | + multiplier: f64, |
| 13 | + max_interval: Duration, |
| 14 | +} |
| 15 | + |
| 16 | +impl Default for PythLazerExponentialBackoffBuilder { |
| 17 | + fn default() -> Self { |
| 18 | + Self { |
| 19 | + initial_interval: Duration::from_millis(INITIAL_INTERVAL_MILLIS), |
| 20 | + randomization_factor: RANDOMIZATION_FACTOR, |
| 21 | + multiplier: MULTIPLIER, |
| 22 | + max_interval: Duration::from_millis(MAX_INTERVAL_MILLIS), |
| 23 | + } |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +impl PythLazerExponentialBackoffBuilder { |
| 28 | + pub fn new() -> Self { |
| 29 | + Default::default() |
| 30 | + } |
| 31 | + |
| 32 | + /// The initial retry interval. |
| 33 | + pub fn with_initial_interval(&mut self, initial_interval: Duration) -> &mut Self { |
| 34 | + self.initial_interval = initial_interval; |
| 35 | + self |
| 36 | + } |
| 37 | + |
| 38 | + /// The randomization factor to use for creating a range around the retry interval. |
| 39 | + /// |
| 40 | + /// A randomization factor of 0.5 results in a random period ranging between 50% below and 50% |
| 41 | + /// above the retry interval. |
| 42 | + pub fn with_randomization_factor(&mut self, randomization_factor: f64) -> &mut Self { |
| 43 | + self.randomization_factor = randomization_factor; |
| 44 | + self |
| 45 | + } |
| 46 | + |
| 47 | + /// The value to multiply the current interval with for each retry attempt. |
| 48 | + pub fn with_multiplier(&mut self, multiplier: f64) -> &mut Self { |
| 49 | + self.multiplier = multiplier; |
| 50 | + self |
| 51 | + } |
| 52 | + |
| 53 | + /// The maximum value of the back off period. Once the retry interval reaches this |
| 54 | + /// value it stops increasing. |
| 55 | + pub fn with_max_interval(&mut self, max_interval: Duration) -> &mut Self { |
| 56 | + self.max_interval = max_interval; |
| 57 | + self |
| 58 | + } |
| 59 | + |
| 60 | + pub fn build(&self) -> ExponentialBackoff { |
| 61 | + ExponentialBackoffBuilder::default() |
| 62 | + .with_initial_interval(self.initial_interval) |
| 63 | + .with_randomization_factor(self.randomization_factor) |
| 64 | + .with_multiplier(self.multiplier) |
| 65 | + .with_max_interval(self.max_interval) |
| 66 | + .with_max_elapsed_time(None) |
| 67 | + .build() |
| 68 | + } |
| 69 | +} |
0 commit comments