qiniu_http_client/client/backoff/
exponential.rs

1use super::{Backoff, BackoffOptions, GotBackoffDuration, RetryDecision};
2use qiniu_http::RequestParts as HttpRequestParts;
3use std::time::Duration;
4
5/// 指数级增长的退避时长提供者
6///
7/// 默认底数为 2,基础时长为 100 毫秒
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct ExponentialBackoff {
10    base_number: u32,
11    base_delay: Duration,
12}
13
14impl ExponentialBackoff {
15    /// 创建指数级增长的退避时长提供者
16    ///
17    /// 需要提供底数和基础时长,返回的退避时长为 `base_delay * (base_number ^ retry_count)`
18    #[inline]
19    pub const fn new(base_number: u32, base_delay: Duration) -> Self {
20        Self {
21            base_number,
22            base_delay,
23        }
24    }
25
26    /// 获取底数
27    #[inline]
28    pub const fn base_number(&self) -> u32 {
29        self.base_number
30    }
31
32    /// 获取基础时长
33    #[inline]
34    pub const fn base_delay(&self) -> Duration {
35        self.base_delay
36    }
37}
38
39impl Backoff for ExponentialBackoff {
40    fn time(&self, _request: &mut HttpRequestParts, opts: BackoffOptions) -> GotBackoffDuration {
41        let retried_count = if opts.retry_decision() == RetryDecision::Throttled {
42            opts.retried().retried_total()
43        } else {
44            opts.retried().retried_on_current_endpoint()
45        };
46        GotBackoffDuration::from(self.base_delay * self.base_number.pow(retried_count as u32))
47    }
48}
49
50impl Default for ExponentialBackoff {
51    #[inline]
52    fn default() -> Self {
53        ExponentialBackoff::new(2, Duration::from_millis(100))
54    }
55}