Skip to main content

docsrs_cli/retry/
config.rs

1//! Retry policy struct resolved from [`Config`] (single source of truth).
2
3use std::time::Duration;
4
5use crate::config::Config;
6
7use super::backoff::backoff_full_jitter;
8use super::{
9    DEFAULT_MAX_RETRIES, DEFAULT_RETRY_BASE_MS, DEFAULT_RETRY_MAX_DELAY_MS,
10    DEFAULT_RETRY_MAX_ELAPSED_MS, HARD_MAX_DELAY_MS, HARD_MAX_ELAPSED_MS, HARD_MAX_RETRIES,
11    MILLIS_PER_SECOND, MIN_DERIVED_ELAPSED_MS, MIN_RETRY_BASE_MS,
12};
13
14/// Named retry policy for the product HTTP client (one dependency class).
15///
16/// Built from [`Config`] so CLI / TOML / env share one struct. Clone is cheap
17/// (`Copy`).
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub struct RetryConfig {
20    /// Retries after the first attempt (`0` = single try).
21    pub max_retries: u32,
22    /// Exponential base delay in milliseconds.
23    pub base_ms: u64,
24    /// Maximum single sleep in milliseconds.
25    pub max_delay_ms: u64,
26    /// Total wall budget for the retry loop (attempts + sleeps), milliseconds.
27    pub max_elapsed_ms: u64,
28    /// Kill switch: when false, never retries.
29    pub enabled: bool,
30}
31
32impl RetryConfig {
33    /// Resolve policy from runtime config (clamped).
34    ///
35    /// Coherence: `base_ms ≥ MIN_RETRY_BASE_MS`, `max_delay ≥ base`,
36    /// `max_elapsed ≥ max_delay` (or wall timeout when config field is `0`).
37    pub fn from_config(cfg: &Config) -> Self {
38        let max_retries = cfg.max_retries.min(HARD_MAX_RETRIES);
39        let base_ms = if cfg.retry_base_ms == 0 {
40            DEFAULT_RETRY_BASE_MS
41        } else {
42            cfg.retry_base_ms.max(MIN_RETRY_BASE_MS)
43        };
44        let max_delay_ms = cfg.retry_max_delay_ms.min(HARD_MAX_DELAY_MS).max(base_ms);
45        // `0` means derive from wall-clock timeout (one-shot: retries must not
46        // outlive the operation deadline).
47        let derived = cfg
48            .timeout_secs
49            .saturating_mul(MILLIS_PER_SECOND)
50            .max(MIN_DERIVED_ELAPSED_MS);
51        let max_elapsed_ms = if cfg.retry_max_elapsed_ms == 0 {
52            derived.min(HARD_MAX_ELAPSED_MS)
53        } else {
54            cfg.retry_max_elapsed_ms
55                .min(HARD_MAX_ELAPSED_MS)
56                .max(max_delay_ms)
57        };
58        let enabled = !cfg.disable_retry && max_retries > 0;
59        Self {
60            max_retries,
61            base_ms,
62            max_delay_ms,
63            max_elapsed_ms,
64            enabled,
65        }
66    }
67
68    /// Total attempts including the first try.
69    pub fn max_attempts(self) -> u32 {
70        if !self.enabled {
71            1
72        } else {
73            self.max_retries.saturating_add(1)
74        }
75    }
76
77    /// Whether another attempt is allowed after `attempt` (1-based completed count).
78    pub fn may_retry(self, attempt: u32) -> bool {
79        self.enabled && attempt < self.max_attempts()
80    }
81
82    /// Whether another attempt is allowed given attempt count **and** elapsed budget.
83    ///
84    /// Rules: combine `max_attempts` and `max_elapsed_time`. A planned wait that
85    /// would exceed the remaining budget aborts retry (no sleep past budget).
86    pub fn may_retry_within_budget(
87        self,
88        attempt: u32,
89        elapsed: Duration,
90        planned_wait: Duration,
91    ) -> bool {
92        if !self.may_retry(attempt) {
93            return false;
94        }
95        let budget = Duration::from_millis(self.max_elapsed_ms);
96        if elapsed >= budget {
97            return false;
98        }
99        let remaining = budget.saturating_sub(elapsed);
100        planned_wait <= remaining
101    }
102
103    /// Remaining time in the elapsed budget (zero when exhausted).
104    pub fn remaining_budget(self, elapsed: Duration) -> Duration {
105        Duration::from_millis(self.max_elapsed_ms).saturating_sub(elapsed)
106    }
107
108    /// Full-jitter delay for this attempt number (1-based).
109    pub fn delay_for_attempt(self, attempt: u32) -> Duration {
110        backoff_full_jitter(self.base_ms, attempt, self.max_delay_ms)
111    }
112}
113
114impl Default for RetryConfig {
115    fn default() -> Self {
116        Self {
117            max_retries: DEFAULT_MAX_RETRIES,
118            base_ms: DEFAULT_RETRY_BASE_MS,
119            max_delay_ms: DEFAULT_RETRY_MAX_DELAY_MS,
120            max_elapsed_ms: DEFAULT_RETRY_MAX_ELAPSED_MS,
121            enabled: true,
122        }
123    }
124}