|
| 1 | +// Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +// or more contributor license agreements. See the NOTICE file |
| 3 | +// distributed with this work for additional information |
| 4 | +// regarding copyright ownership. The ASF licenses this file |
| 5 | +// to you under the Apache License, Version 2.0 (the |
| 6 | +// "License"); you may not use this file except in compliance |
| 7 | +// with the License. You may obtain a copy of the License at |
| 8 | +// |
| 9 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +// |
| 11 | +// Unless required by applicable law or agreed to in writing, |
| 12 | +// software distributed under the License is distributed on an |
| 13 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +// KIND, either express or implied. See the License for the |
| 15 | +// specific language governing permissions and limitations |
| 16 | +// under the License. |
| 17 | + |
| 18 | +use rand::prelude::*; |
| 19 | +use std::time::Duration; |
| 20 | + |
| 21 | +/// Exponential backoff with jitter |
| 22 | +/// |
| 23 | +/// See <https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/> |
| 24 | +#[allow(missing_copy_implementations)] |
| 25 | +#[derive(Debug, Clone)] |
| 26 | +pub struct BackoffConfig { |
| 27 | + /// The initial backoff duration |
| 28 | + pub init_backoff: Duration, |
| 29 | + /// The maximum backoff duration |
| 30 | + pub max_backoff: Duration, |
| 31 | + /// The base of the exponential to use |
| 32 | + pub base: f64, |
| 33 | +} |
| 34 | + |
| 35 | +impl Default for BackoffConfig { |
| 36 | + fn default() -> Self { |
| 37 | + Self { |
| 38 | + init_backoff: Duration::from_millis(100), |
| 39 | + max_backoff: Duration::from_secs(15), |
| 40 | + base: 2., |
| 41 | + } |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +/// [`Backoff`] can be created from a [`BackoffConfig`] |
| 46 | +/// |
| 47 | +/// Consecutive calls to [`Backoff::next`] will return the next backoff interval |
| 48 | +/// |
| 49 | +pub struct Backoff { |
| 50 | + init_backoff: f64, |
| 51 | + next_backoff_secs: f64, |
| 52 | + max_backoff_secs: f64, |
| 53 | + base: f64, |
| 54 | + rng: Option<Box<dyn RngCore + Sync + Send>>, |
| 55 | +} |
| 56 | + |
| 57 | +impl std::fmt::Debug for Backoff { |
| 58 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 59 | + f.debug_struct("Backoff") |
| 60 | + .field("init_backoff", &self.init_backoff) |
| 61 | + .field("next_backoff_secs", &self.next_backoff_secs) |
| 62 | + .field("max_backoff_secs", &self.max_backoff_secs) |
| 63 | + .field("base", &self.base) |
| 64 | + .finish() |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +impl Backoff { |
| 69 | + /// Create a new [`Backoff`] from the provided [`BackoffConfig`] |
| 70 | + pub fn new(config: &BackoffConfig) -> Self { |
| 71 | + Self::new_with_rng(config, None) |
| 72 | + } |
| 73 | + |
| 74 | + /// Creates a new `Backoff` with the optional `rng` |
| 75 | + /// |
| 76 | + /// Used [`rand::thread_rng()`] if no rng provided |
| 77 | + pub fn new_with_rng( |
| 78 | + config: &BackoffConfig, |
| 79 | + rng: Option<Box<dyn RngCore + Sync + Send>>, |
| 80 | + ) -> Self { |
| 81 | + let init_backoff = config.init_backoff.as_secs_f64(); |
| 82 | + Self { |
| 83 | + init_backoff, |
| 84 | + next_backoff_secs: init_backoff, |
| 85 | + max_backoff_secs: config.max_backoff.as_secs_f64(), |
| 86 | + base: config.base, |
| 87 | + rng, |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + /// Returns the next backoff duration to wait for |
| 92 | + pub fn next(&mut self) -> Duration { |
| 93 | + let range = self.init_backoff..(self.next_backoff_secs * self.base); |
| 94 | + |
| 95 | + let rand_backoff = match self.rng.as_mut() { |
| 96 | + Some(rng) => rng.gen_range(range), |
| 97 | + None => thread_rng().gen_range(range), |
| 98 | + }; |
| 99 | + |
| 100 | + let next_backoff = self.max_backoff_secs.min(rand_backoff); |
| 101 | + Duration::from_secs_f64(std::mem::replace( |
| 102 | + &mut self.next_backoff_secs, |
| 103 | + next_backoff, |
| 104 | + )) |
| 105 | + } |
| 106 | +} |
| 107 | + |
| 108 | +#[cfg(test)] |
| 109 | +mod tests { |
| 110 | + use super::*; |
| 111 | + use rand::rngs::mock::StepRng; |
| 112 | + |
| 113 | + #[test] |
| 114 | + fn test_backoff() { |
| 115 | + let init_backoff_secs = 1.; |
| 116 | + let max_backoff_secs = 500.; |
| 117 | + let base = 3.; |
| 118 | + |
| 119 | + let config = BackoffConfig { |
| 120 | + init_backoff: Duration::from_secs_f64(init_backoff_secs), |
| 121 | + max_backoff: Duration::from_secs_f64(max_backoff_secs), |
| 122 | + base, |
| 123 | + }; |
| 124 | + |
| 125 | + let assert_fuzzy_eq = |
| 126 | + |a: f64, b: f64| assert!((b - a).abs() < 0.0001, "{} != {}", a, b); |
| 127 | + |
| 128 | + // Create a static rng that takes the minimum of the range |
| 129 | + let rng = Box::new(StepRng::new(0, 0)); |
| 130 | + let mut backoff = Backoff::new_with_rng(&config, Some(rng)); |
| 131 | + |
| 132 | + for _ in 0..20 { |
| 133 | + assert_eq!(backoff.next().as_secs_f64(), init_backoff_secs); |
| 134 | + } |
| 135 | + |
| 136 | + // Create a static rng that takes the maximum of the range |
| 137 | + let rng = Box::new(StepRng::new(u64::MAX, 0)); |
| 138 | + let mut backoff = Backoff::new_with_rng(&config, Some(rng)); |
| 139 | + |
| 140 | + for i in 0..20 { |
| 141 | + let value = (base.powi(i) * init_backoff_secs).min(max_backoff_secs); |
| 142 | + assert_fuzzy_eq(backoff.next().as_secs_f64(), value); |
| 143 | + } |
| 144 | + |
| 145 | + // Create a static rng that takes the mid point of the range |
| 146 | + let rng = Box::new(StepRng::new(u64::MAX / 2, 0)); |
| 147 | + let mut backoff = Backoff::new_with_rng(&config, Some(rng)); |
| 148 | + |
| 149 | + let mut value = init_backoff_secs; |
| 150 | + for _ in 0..20 { |
| 151 | + assert_fuzzy_eq(backoff.next().as_secs_f64(), value); |
| 152 | + value = (init_backoff_secs + (value * base - init_backoff_secs) / 2.) |
| 153 | + .min(max_backoff_secs); |
| 154 | + } |
| 155 | + } |
| 156 | +} |
0 commit comments