Skip to main content

open_net/libs/retry/src/
schedule.rs

1use super::{Backoff, Jitter, RetryConfigError};
2use std::time::Duration;
3
4/// Whether an operation inherits, disables, or replaces its client's retry policy.
5#[derive(Clone, Debug, PartialEq)]
6pub enum RetrySetting<P> {
7    /// Resolve to the configured client default.
8    Inherit,
9    /// Execute at most once, independently of the client default.
10    Disabled,
11    /// Replace the entire client policy for this operation.
12    Policy(P),
13}
14
15impl<P> Default for RetrySetting<P> {
16    fn default() -> Self {
17        Self::Inherit
18    }
19}
20
21impl<P: Clone> RetrySetting<P> {
22    /// Resolve the selection with protocol-specific default and disabled values.
23    pub fn resolve(&self, default: &P, disabled: P) -> P {
24        match self {
25            Self::Inherit => default.clone(),
26            Self::Disabled => disabled,
27            Self::Policy(policy) => policy.clone(),
28        }
29    }
30}
31
32/// The result of a synchronous, read-only protocol or business classifier.
33#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
34pub enum RetryDecision {
35    /// Apply the protocol's configured built-in classification.
36    #[default]
37    Default,
38    /// Request another attempt, subject to safety, cancellation and all budgets.
39    Retry,
40    /// Stop even if a built-in rule would otherwise retry.
41    Stop,
42}
43
44/// Immutable, validated attempt and delay configuration shared by all transports.
45///
46/// Sharing or cloning a schedule never shares counters or a random stream.
47/// Each executing operation creates its own private runtime state.
48#[derive(Clone, Debug, PartialEq)]
49pub struct RetrySchedule {
50    max_attempts: u32,
51    backoff: Backoff,
52    jitter: Jitter,
53}
54
55impl RetrySchedule {
56    /// Start a builder with one immediate attempt and no jitter.
57    pub fn builder() -> RetryScheduleBuilder {
58        RetryScheduleBuilder::default()
59    }
60
61    /// Configure exactly one attempt, with no retry delay.
62    pub fn no_retry() -> Self {
63        Self {
64            max_attempts: 1,
65            backoff: Backoff::None,
66            jitter: Jitter::None,
67        }
68    }
69
70    /// Return the total attempt limit, including the initial attempt.
71    pub fn max_attempts(&self) -> u32 {
72        self.max_attempts
73    }
74
75    /// Return the built-in backoff rule.
76    pub fn backoff(&self) -> &Backoff {
77        &self.backoff
78    }
79
80    /// Return the jitter configuration.
81    pub fn jitter(&self) -> Jitter {
82        self.jitter
83    }
84
85    /// Return a deterministic delay before a one-based retry, without jitter.
86    ///
87    /// For a schedule of five attempts the valid ordinals are one through four.
88    pub fn delay_for(&self, retry_ordinal: u32) -> Result<Duration, RetryConfigError> {
89        if retry_ordinal == 0 || retry_ordinal >= self.max_attempts {
90            return Err(RetryConfigError::new(
91                "retry_ordinal",
92                "must be between one and max_attempts - 1",
93            ));
94        }
95        self.backoff.delay_for_validated(retry_ordinal)
96    }
97
98    pub(crate) fn sampled_delay(
99        &self,
100        retry_ordinal: u32,
101        unit: f64,
102    ) -> Result<Duration, RetryConfigError> {
103        self.jitter
104            .apply(self.delay_for(retry_ordinal)?, unit, &self.backoff)
105    }
106}
107
108impl Default for RetrySchedule {
109    fn default() -> Self {
110        Self::no_retry()
111    }
112}
113
114/// Builder for one validated retry schedule.
115#[derive(Clone, Debug)]
116pub struct RetryScheduleBuilder {
117    max_attempts: u32,
118    backoff: Backoff,
119    jitter: Jitter,
120}
121
122impl Default for RetryScheduleBuilder {
123    fn default() -> Self {
124        Self {
125            max_attempts: 1,
126            backoff: Backoff::None,
127            jitter: Jitter::None,
128        }
129    }
130}
131
132impl RetryScheduleBuilder {
133    /// Set the total number of attempts, including the first. Zero is invalid.
134    pub fn max_attempts(mut self, count: u32) -> Self {
135        self.max_attempts = count;
136        self
137    }
138
139    /// Replace the delay rule. A sequence requires exactly `max_attempts - 1` entries.
140    pub fn backoff(mut self, backoff: Backoff) -> Self {
141        self.backoff = backoff;
142        self
143    }
144
145    /// Replace the optional delay randomization.
146    pub fn jitter(mut self, jitter: Jitter) -> Self {
147        self.jitter = jitter;
148        self
149    }
150
151    /// Validate all settings without allocating per-attempt runtime state.
152    pub fn build(self) -> Result<RetrySchedule, RetryConfigError> {
153        if self.max_attempts == 0 {
154            return Err(RetryConfigError::new(
155                "max_attempts",
156                "must be at least one",
157            ));
158        }
159        self.backoff.validate(self.max_attempts)?;
160        self.jitter.validate(&self.backoff)?;
161        Ok(RetrySchedule {
162            max_attempts: self.max_attempts,
163            backoff: self.backoff,
164            jitter: self.jitter,
165        })
166    }
167}