qubit_retry/options/retry_delay.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2025 - 2026 Haixing Hu.
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 *
7 * Licensed under the Apache License, Version 2.0.
8 *
9 ******************************************************************************/
10//! RetryDelay strategies for retry attempts.
11//!
12//! A [`RetryDelay`] produces the base sleep duration after a failed attempt. The
13//! base duration is calculated before [`crate::RetryJitter`] is applied by a retry
14//! executor.
15//!
16//! # Text interchange
17//!
18//! [`std::fmt::Display`] and [`std::str::FromStr`] share a canonical string form:
19//!
20//! - `none`
21//! - `fixed(<duration>)` — duration fields are displayed as saturated whole milliseconds
22//! with an `ms` suffix; `FromStr` accepts any duration string parsed by
23//! [`qubit_serde::serde::duration_with_unit`]
24//! - `random(<min>..=<max>)` — same rules for the two duration fields
25//! - `exponential(initial=<...>, max=<...>, multiplier=<f64>)` — same for `initial` and `max`
26//!
27//! For [`std::str::FromStr`], substrings for duration fields follow
28//! [`qubit_serde::serde::duration_with_unit`] (bare integer as milliseconds, unit
29//! suffixes, etc.; see that module). [`std::fmt::Display`] normalizes to whole
30//! millisecond + `ms` for those fields.
31
32use std::str::FromStr;
33use std::time::Duration;
34
35use parse_display::{
36 Display,
37 FromStr,
38};
39use rand::RngExt;
40use serde::{
41 Deserialize,
42 Serialize,
43};
44
45use super::retry_delay_duration_format::RetryDelayDurationFormat;
46use crate::constants::DEFAULT_RETRY_DELAY;
47
48/// Base delay strategy before jitter is applied.
49///
50/// RetryDelay strategies are value types that can be reused across executors. Random
51/// and exponential strategies are validated separately by [`RetryDelay::validate`],
52/// which is called when building [`crate::RetryOptions`].
53#[derive(Debug, Clone, PartialEq, Display, FromStr, Serialize, Deserialize)]
54pub enum RetryDelay {
55 /// Retry immediately.
56 #[display("none")]
57 None,
58
59 /// Wait for a constant delay after every failed attempt.
60 #[display("fixed({0})")]
61 Fixed(
62 #[display(with = RetryDelayDurationFormat)]
63 #[serde(with = "qubit_serde::serde::duration_millis")]
64 Duration,
65 ),
66
67 /// Pick a delay uniformly from the inclusive range.
68 #[display("random({min}..={max})")]
69 Random {
70 /// Lower bound for the delay.
71 #[display(with = RetryDelayDurationFormat)]
72 #[serde(with = "qubit_serde::serde::duration_millis")]
73 min: Duration,
74 /// Upper bound for the delay.
75 #[display(with = RetryDelayDurationFormat)]
76 #[serde(with = "qubit_serde::serde::duration_millis")]
77 max: Duration,
78 },
79
80 /// Exponential backoff capped by `max`.
81 #[display("exponential(initial={initial}, max={max}, multiplier={multiplier})")]
82 Exponential {
83 /// RetryDelay used for the first retry.
84 #[display(with = RetryDelayDurationFormat)]
85 #[serde(with = "qubit_serde::serde::duration_millis")]
86 initial: Duration,
87 /// Maximum delay.
88 #[display(with = RetryDelayDurationFormat)]
89 #[serde(with = "qubit_serde::serde::duration_millis")]
90 max: Duration,
91 /// Multiplicative factor applied per failed attempt.
92 multiplier: f64,
93 },
94}
95
96impl RetryDelay {
97 /// Creates a no-delay strategy.
98 ///
99 /// # Parameters
100 /// This function has no parameters.
101 ///
102 /// # Returns
103 /// A [`RetryDelay::None`] strategy.
104 ///
105 /// # Errors
106 /// This function does not return errors.
107 #[inline]
108 pub fn none() -> Self {
109 Self::None
110 }
111
112 /// Creates a fixed-delay strategy.
113 ///
114 /// # Parameters
115 /// - `delay`: Duration slept after each failed attempt.
116 ///
117 /// # Returns
118 /// A [`RetryDelay::Fixed`] strategy.
119 ///
120 /// # Errors
121 /// This constructor does not validate `delay`; use [`RetryDelay::validate`] to
122 /// reject a zero duration.
123 #[inline]
124 pub fn fixed(delay: Duration) -> Self {
125 Self::Fixed(delay)
126 }
127
128 /// Creates a random-delay strategy.
129 ///
130 /// # Parameters
131 /// - `min`: Inclusive lower bound for generated delays.
132 /// - `max`: Inclusive upper bound for generated delays.
133 ///
134 /// # Returns
135 /// A [`RetryDelay::Random`] strategy.
136 ///
137 /// # Errors
138 /// This constructor does not validate the range; use [`RetryDelay::validate`] to
139 /// reject a zero minimum, a minimum greater than the maximum, or bounds
140 /// that cannot be sampled as `u64` nanoseconds.
141 #[inline]
142 pub fn random(min: Duration, max: Duration) -> Self {
143 Self::Random { min, max }
144 }
145
146 /// Creates an exponential-backoff strategy.
147 ///
148 /// # Parameters
149 /// - `initial`: RetryDelay used for the first retry.
150 /// - `max`: Upper bound applied to every calculated delay.
151 /// - `multiplier`: Factor applied for each subsequent failed attempt.
152 ///
153 /// # Returns
154 /// A [`RetryDelay::Exponential`] strategy.
155 ///
156 /// # Errors
157 /// This constructor does not validate the parameters; use
158 /// [`RetryDelay::validate`] to reject a zero initial delay, `max < initial`, or
159 /// a multiplier that is non-finite or less than or equal to `1.0`.
160 #[inline]
161 pub fn exponential(initial: Duration, max: Duration, multiplier: f64) -> Self {
162 Self::Exponential {
163 initial,
164 max,
165 multiplier,
166 }
167 }
168
169 /// Calculates the base delay for an attempt number starting at 1.
170 ///
171 /// Attempt `1` means the first failed attempt, so exponential backoff
172 /// returns `initial` for attempts `0` and `1`. Random delays use a fresh
173 /// random value for every call.
174 ///
175 /// # Parameters
176 /// - `attempt`: Failed attempt number. Values `0` and `1` are treated as
177 /// the first exponential-backoff step.
178 ///
179 /// # Returns
180 /// The base delay before jitter is applied.
181 ///
182 /// # Errors
183 /// This function does not return errors. Invalid strategies should be
184 /// rejected with [`RetryDelay::validate`] before they are used in an executor.
185 pub fn base_delay(&self, attempt: u32) -> Duration {
186 match self {
187 Self::None => Duration::ZERO,
188 Self::Fixed(delay) => *delay,
189 Self::Random { min, max } => {
190 if min >= max {
191 return *min;
192 }
193 let mut rng = rand::rng();
194 let min_nanos = Self::duration_to_nanos_u64(*min);
195 let max_nanos = Self::duration_to_nanos_u64(*max);
196 Duration::from_nanos(rng.random_range(min_nanos..=max_nanos))
197 }
198 Self::Exponential {
199 initial,
200 max,
201 multiplier,
202 } => Self::exponential_delay(*initial, *max, *multiplier, attempt),
203 }
204 }
205
206 /// Returns whether a duration can be represented as whole nanoseconds in `u64`.
207 ///
208 /// # Parameters
209 /// - `duration`: Duration to inspect.
210 ///
211 /// # Returns
212 /// `true` when the duration can be sampled by the random delay generator
213 /// without lossy saturation.
214 ///
215 /// # Errors
216 /// This function does not return errors.
217 fn duration_fits_nanos_u64(duration: Duration) -> bool {
218 duration.as_nanos() <= u64::MAX as u128
219 }
220
221 /// Converts a [`Duration`] to whole nanoseconds as `u64`.
222 ///
223 /// Values larger than [`u64::MAX`] nanoseconds are saturated to
224 /// [`u64::MAX`] so the result fits in `u64` for uniform random delay sampling
225 /// in [`RetryDelay::base_delay`].
226 ///
227 /// # Parameters
228 /// - `duration`: Duration to convert.
229 ///
230 /// # Returns
231 /// The duration in nanoseconds, capped at [`u64::MAX`].
232 ///
233 /// # Errors
234 /// This function does not return errors.
235 fn duration_to_nanos_u64(duration: Duration) -> u64 {
236 duration.as_nanos().min(u64::MAX as u128) as u64
237 }
238
239 /// Computes the exponential backoff delay for a given failed-attempt index.
240 ///
241 /// The effective exponent is `attempt.saturating_sub(1)`, so attempts `0`
242 /// and `1` both yield the initial delay (matching [`RetryDelay::base_delay`]).
243 /// Each further attempt multiplies the base nanosecond count by
244 /// `multiplier` that many times, then the result is capped at `max`.
245 ///
246 /// # Parameters
247 /// - `initial`: RetryDelay for the first retry step (attempts `0` and `1`).
248 /// - `max`: Upper bound on the returned delay.
249 /// - `multiplier`: Factor applied per additional attempt beyond the first.
250 /// - `attempt`: Failed attempt number (see [`RetryDelay::base_delay`]).
251 ///
252 /// # Returns
253 /// The computed delay, or `max` when the scaled value is not finite or is
254 /// not less than `max` in nanoseconds.
255 ///
256 /// # Errors
257 /// This function does not return errors. Callers must ensure parameters
258 /// satisfy [`RetryDelay::validate`] when constructing a public executor.
259 fn exponential_delay(initial: Duration, max: Duration, multiplier: f64, attempt: u32) -> Duration {
260 let power = attempt.saturating_sub(1);
261 let factor = multiplier.powi(power.min(i32::MAX as u32) as i32);
262 if !factor.is_finite() {
263 return max;
264 }
265 let secs = initial.as_secs_f64() * factor;
266 if !secs.is_finite() || secs >= max.as_secs_f64() {
267 return max;
268 }
269 Duration::try_from_secs_f64(secs).map_or(max, |delay| delay.min(max))
270 }
271
272 /// Validates strategy parameters.
273 ///
274 /// Returns a human-readable message describing the invalid field when the
275 /// strategy cannot be used safely by an executor.
276 ///
277 /// # Returns
278 /// `Ok(())` when all parameters are usable; otherwise an error message that
279 /// can be wrapped by [`crate::RetryConfigError`].
280 ///
281 /// # Parameters
282 /// This method has no parameters.
283 ///
284 /// # Errors
285 /// Returns an error when a fixed delay is zero, a random range is invalid,
286 /// random bounds cannot be sampled as `u64` nanoseconds, or exponential
287 /// backoff parameters are zero, inverted, non-finite, or too small.
288 pub fn validate(&self) -> Result<(), String> {
289 match self {
290 Self::None => Ok(()),
291 Self::Fixed(delay) => {
292 if delay.is_zero() {
293 Err("fixed delay cannot be zero".to_string())
294 } else {
295 Ok(())
296 }
297 }
298 Self::Random { min, max } => {
299 if min.is_zero() {
300 Err("random delay minimum cannot be zero".to_string())
301 } else if min > max {
302 Err("random delay minimum cannot be greater than maximum".to_string())
303 } else if !Self::duration_fits_nanos_u64(*min) || !Self::duration_fits_nanos_u64(*max) {
304 Err("random delay bounds must fit into u64 nanoseconds".to_string())
305 } else {
306 Ok(())
307 }
308 }
309 Self::Exponential {
310 initial,
311 max,
312 multiplier,
313 } => {
314 if initial.is_zero() {
315 Err("exponential delay initial value cannot be zero".to_string())
316 } else if max < initial {
317 Err("exponential delay maximum cannot be smaller than initial".to_string())
318 } else if !multiplier.is_finite() || *multiplier <= 1.0 {
319 Err("exponential delay multiplier must be finite and greater than 1.0".to_string())
320 } else {
321 Ok(())
322 }
323 }
324 }
325 }
326}
327
328impl Default for RetryDelay {
329 /// Creates the default exponential-backoff strategy.
330 ///
331 /// # Returns
332 /// The value obtained by parsing [`crate::constants::DEFAULT_RETRY_DELAY`]
333 /// using [`RetryDelay::from_str`].
334 ///
335 /// # Parameters
336 /// This function has no parameters.
337 ///
338 /// # Errors
339 /// This function does not return errors.
340 ///
341 /// # Panics
342 /// Panics if [`crate::constants::DEFAULT_RETRY_DELAY`] is not a valid
343 /// [`RetryDelay`] string. That indicates a crate bug, not a caller mistake.
344 #[inline]
345 fn default() -> Self {
346 Self::from_str(DEFAULT_RETRY_DELAY).expect("DEFAULT_RETRY_DELAY must be a valid RetryDelay string")
347 }
348}