qubit-retry 0.10.5

Retry module, providing a feature-complete, type-safe retry management system with support for multiple delay strategies and event listeners
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
/*******************************************************************************
 *
 *    Copyright (c) 2025 - 2026 Haixing Hu.
 *
 *    SPDX-License-Identifier: Apache-2.0
 *
 *    Licensed under the Apache License, Version 2.0.
 *
 ******************************************************************************/
//! Raw retry configuration values from `qubit-config` and merge into
//! [`RetryOptions`](crate::options::RetryOptions).
//!

use std::str::FromStr;
use std::time::Duration;

use qubit_config::{
    ConfigReader,
    ConfigResult,
};

use super::attempt_timeout_option::AttemptTimeoutOption;
use super::attempt_timeout_policy::AttemptTimeoutPolicy;
use super::retry_delay::RetryDelay;
use super::retry_jitter::RetryJitter;
use super::retry_options::RetryOptions;

use crate::RetryConfigError;
use crate::constants::{
    DEFAULT_RETRY_EXPONENTIAL_INITIAL_DELAY_MILLIS,
    DEFAULT_RETRY_EXPONENTIAL_MAX_DELAY_MILLIS,
    DEFAULT_RETRY_EXPONENTIAL_MULTIPLIER,
    DEFAULT_RETRY_JITTER_FACTOR,
    DEFAULT_RETRY_RANDOM_MAX_DELAY_MILLIS,
    DEFAULT_RETRY_RANDOM_MIN_DELAY_MILLIS,
    KEY_ATTEMPT_TIMEOUT_MILLIS,
    KEY_ATTEMPT_TIMEOUT_POLICY,
    KEY_DELAY,
    KEY_DELAY_STRATEGY,
    KEY_EXPONENTIAL_INITIAL_DELAY_MILLIS,
    KEY_EXPONENTIAL_MAX_DELAY_MILLIS,
    KEY_EXPONENTIAL_MULTIPLIER,
    KEY_FIXED_DELAY_MILLIS,
    KEY_JITTER_FACTOR,
    KEY_MAX_ATTEMPTS,
    KEY_MAX_OPERATION_ELAPSED_MILLIS,
    KEY_MAX_OPERATION_ELAPSED_UNLIMITED,
    KEY_MAX_TOTAL_ELAPSED_MILLIS,
    KEY_MAX_TOTAL_ELAPSED_UNLIMITED,
    KEY_RANDOM_MAX_DELAY_MILLIS,
    KEY_RANDOM_MIN_DELAY_MILLIS,
    KEY_WORKER_CANCEL_GRACE_MILLIS,
};

/// Raw retry configuration values read from `qubit-config`.
///
/// This struct deliberately keeps all `ConfigReader` calls in one place. The
/// conversion from `qubit-config` errors to retry-specific errors happens at
/// the caller boundary, while the remaining methods only translate already
/// typed values into retry domain objects.
///
/// Fields are public so callers and integration tests can build snapshots
/// programmatically and merge them with [`RetryConfigValues::to_options`].
///
#[derive(Debug, Clone, PartialEq)]
pub struct RetryConfigValues {
    /// Optional maximum attempts value.
    pub max_attempts: Option<u32>,
    /// Optional cumulative user operation elapsed-time budget in milliseconds.
    pub max_operation_elapsed_millis: Option<u64>,
    /// Optional explicit switch for unlimited user operation elapsed-time budget.
    pub max_operation_elapsed_unlimited: Option<bool>,
    /// Optional total retry-flow elapsed-time budget in milliseconds.
    pub max_total_elapsed_millis: Option<u64>,
    /// Optional explicit switch for unlimited total retry-flow elapsed-time budget.
    pub max_total_elapsed_unlimited: Option<bool>,
    /// Optional attempt timeout in milliseconds.
    pub attempt_timeout_millis: Option<u64>,
    /// Optional action selected when one attempt times out.
    pub attempt_timeout_policy: Option<String>,
    /// Optional worker cancellation grace period in milliseconds.
    pub worker_cancel_grace_millis: Option<u64>,
    /// Optional primary delay strategy name.
    pub delay: Option<String>,
    /// Optional backward-compatible delay strategy alias.
    pub delay_strategy: Option<String>,
    /// Optional fixed delay in milliseconds.
    pub fixed_delay_millis: Option<u64>,
    /// Optional random delay lower bound in milliseconds.
    pub random_min_delay_millis: Option<u64>,
    /// Optional random delay upper bound in milliseconds.
    pub random_max_delay_millis: Option<u64>,
    /// Optional exponential initial delay in milliseconds.
    pub exponential_initial_delay_millis: Option<u64>,
    /// Optional exponential maximum delay in milliseconds.
    pub exponential_max_delay_millis: Option<u64>,
    /// Optional exponential multiplier.
    pub exponential_multiplier: Option<f64>,
    /// Optional jitter factor.
    pub jitter_factor: Option<f64>,
}

impl RetryConfigValues {
    /// Creates a snapshot by reading all retry-related configuration values.
    ///
    /// # Parameters
    /// - `config`: Configuration reader whose keys are relative to the retry
    ///   configuration prefix.
    ///
    /// # Returns
    /// A [`RetryConfigValues`] snapshot containing every retry option key
    /// understood by this crate.
    ///
    /// # Errors
    /// Returns `qubit-config`'s `ConfigError` through [`ConfigResult`] when any
    /// present key cannot be read as the expected type or string substitution
    /// fails.
    pub(crate) fn new<R>(config: &R) -> ConfigResult<Self>
    where
        R: ConfigReader + ?Sized,
    {
        Ok(Self {
            max_attempts: config.get_optional(KEY_MAX_ATTEMPTS)?,
            max_operation_elapsed_millis: config.get_optional(KEY_MAX_OPERATION_ELAPSED_MILLIS)?,
            max_operation_elapsed_unlimited: config
                .get_optional(KEY_MAX_OPERATION_ELAPSED_UNLIMITED)?,
            max_total_elapsed_millis: config.get_optional(KEY_MAX_TOTAL_ELAPSED_MILLIS)?,
            max_total_elapsed_unlimited: config.get_optional(KEY_MAX_TOTAL_ELAPSED_UNLIMITED)?,
            attempt_timeout_millis: config.get_optional(KEY_ATTEMPT_TIMEOUT_MILLIS)?,
            attempt_timeout_policy: config.get_optional_string(KEY_ATTEMPT_TIMEOUT_POLICY)?,
            worker_cancel_grace_millis: config.get_optional(KEY_WORKER_CANCEL_GRACE_MILLIS)?,
            delay: config.get_optional_string(KEY_DELAY)?,
            delay_strategy: config.get_optional_string(KEY_DELAY_STRATEGY)?,
            fixed_delay_millis: config.get_optional(KEY_FIXED_DELAY_MILLIS)?,
            random_min_delay_millis: config.get_optional(KEY_RANDOM_MIN_DELAY_MILLIS)?,
            random_max_delay_millis: config.get_optional(KEY_RANDOM_MAX_DELAY_MILLIS)?,
            exponential_initial_delay_millis: config
                .get_optional(KEY_EXPONENTIAL_INITIAL_DELAY_MILLIS)?,
            exponential_max_delay_millis: config.get_optional(KEY_EXPONENTIAL_MAX_DELAY_MILLIS)?,
            exponential_multiplier: config.get_optional(KEY_EXPONENTIAL_MULTIPLIER)?,
            jitter_factor: config.get_optional(KEY_JITTER_FACTOR)?,
        })
    }

    /// Converts the raw configuration snapshot into validated retry options.
    ///
    /// # Parameters
    /// - `default`: Default options used when a config key is absent.
    ///
    /// # Returns
    /// A validated [`RetryOptions`] value.
    ///
    /// # Errors
    /// Returns [`RetryConfigError`] when the delay strategy name is unsupported
    /// or the resulting options fail validation.
    pub fn to_options(&self, default: &RetryOptions) -> Result<RetryOptions, RetryConfigError> {
        let max_attempts = self.max_attempts.unwrap_or(default.max_attempts());
        let max_operation_elapsed = self.get_max_operation_elapsed(default);
        let max_total_elapsed = self.get_max_total_elapsed(default);
        let attempt_timeout = self.get_attempt_timeout(default)?;
        let worker_cancel_grace = self.get_worker_cancel_grace(default);
        let delay = self.get_delay(default)?;
        let jitter = self.get_jitter(default);
        let mut options = RetryOptions::new_with_attempt_timeout(
            max_attempts,
            max_operation_elapsed,
            max_total_elapsed,
            delay,
            jitter,
            attempt_timeout,
        )?;
        options.worker_cancel_grace = worker_cancel_grace;
        options.validate()?;
        Ok(options)
    }

    /// Resolves the cumulative user operation elapsed-time budget.
    ///
    /// # Parameters
    /// - `default`: Fallback when `max_operation_elapsed_millis` is absent from config.
    ///
    /// # Returns
    /// - `None` when `max_operation_elapsed_unlimited` is configured as `true`.
    /// - `Some(Duration)` when `max_operation_elapsed_millis` is present (including zero).
    /// - `default.max_operation_elapsed` when the key is absent.
    ///
    /// # Errors
    /// This method does not return errors.
    fn get_max_operation_elapsed(&self, default: &RetryOptions) -> Option<Duration> {
        if self.max_operation_elapsed_unlimited.unwrap_or(false) {
            return None;
        }
        match self.max_operation_elapsed_millis {
            Some(millis) => Some(Duration::from_millis(millis)),
            None => default.max_operation_elapsed(),
        }
    }

    /// Resolves the total retry-flow elapsed-time budget.
    ///
    /// # Parameters
    /// - `default`: Fallback when `max_total_elapsed_millis` is absent from config.
    ///
    /// # Returns
    /// - `None` when `max_total_elapsed_unlimited` is configured as `true`.
    /// - `Some(Duration)` when `max_total_elapsed_millis` is present (including zero).
    /// - `default.max_total_elapsed` when the key is absent.
    ///
    /// # Errors
    /// This method does not return errors.
    fn get_max_total_elapsed(&self, default: &RetryOptions) -> Option<Duration> {
        if self.max_total_elapsed_unlimited.unwrap_or(false) {
            return None;
        }
        match self.max_total_elapsed_millis {
            Some(millis) => Some(Duration::from_millis(millis)),
            None => default.max_total_elapsed(),
        }
    }

    /// Resolves per-attempt timeout settings.
    ///
    /// # Parameters
    /// - `default`: Default options used when timeout keys are absent.
    ///
    /// # Returns
    /// `Ok(Some(AttemptTimeoutOption))` when a timeout is configured, or
    /// `Ok(None)` when per-attempt timeout is disabled.
    ///
    /// # Errors
    /// Returns [`RetryConfigError`] when policy text is unsupported or when a
    /// policy is configured without a timeout and no default timeout exists.
    fn get_attempt_timeout(
        &self,
        default: &RetryOptions,
    ) -> Result<Option<AttemptTimeoutOption>, RetryConfigError> {
        let default_attempt_timeout = default.attempt_timeout();
        let policy = self
            .attempt_timeout_policy
            .as_deref()
            .map(parse_attempt_timeout_policy)
            .transpose()?;

        match self.attempt_timeout_millis {
            Some(timeout_millis) => {
                let policy = policy
                    .or_else(|| {
                        default_attempt_timeout.map(|attempt_timeout| attempt_timeout.policy())
                    })
                    .unwrap_or_default();
                Ok(Some(AttemptTimeoutOption::new(
                    Duration::from_millis(timeout_millis),
                    policy,
                )))
            }
            None => {
                if let Some(policy) = policy {
                    let Some(default_attempt_timeout) = default_attempt_timeout else {
                        return Err(RetryConfigError::invalid_value(
                            KEY_ATTEMPT_TIMEOUT_POLICY,
                            "attempt_timeout_policy requires attempt_timeout_millis when the default has no attempt timeout",
                        ));
                    };
                    Ok(Some(default_attempt_timeout.with_policy(policy)))
                } else {
                    Ok(default_attempt_timeout)
                }
            }
        }
    }

    /// Resolves the worker cancellation grace period.
    ///
    /// # Parameters
    /// - `default`: Default options used when the config key is absent.
    ///
    /// # Returns
    /// Configured grace duration, or the default option's grace duration.
    ///
    /// # Errors
    /// This method does not return errors because the raw config value was read
    /// as an unsigned integer before this method is called.
    fn get_worker_cancel_grace(&self, default: &RetryOptions) -> Duration {
        self.worker_cancel_grace_millis
            .map(Duration::from_millis)
            .unwrap_or_else(|| default.worker_cancel_grace())
    }

    /// Resolves the base delay strategy.
    ///
    /// # Parameters
    /// - `default`: Default options used when neither explicit nor implicit
    ///   delay configuration is present.
    ///
    /// # Returns
    /// The explicit, implicit, or default [`RetryDelay`] strategy.
    ///
    /// # Errors
    /// Returns [`RetryConfigError`] when the explicit delay strategy name is
    /// unsupported.
    fn get_delay(&self, default: &RetryOptions) -> Result<RetryDelay, RetryConfigError> {
        let strategy = self
            .delay
            .as_deref()
            .map(|value| (KEY_DELAY, value))
            .or_else(|| {
                self.delay_strategy
                    .as_deref()
                    .map(|value| (KEY_DELAY_STRATEGY, value))
            })
            .map(|(key, value)| (key, value.trim().to_ascii_lowercase()));
        match strategy {
            None => Ok(self
                .get_implicit_delay()
                .unwrap_or_else(|| default.delay().clone())),
            Some((_, strategy)) if strategy == "none" => Ok(RetryDelay::None),
            Some((_, strategy)) if strategy == "fixed" => {
                let Some(fixed_delay_millis) = self.fixed_delay_millis else {
                    return Err(RetryConfigError::invalid_value(
                        KEY_FIXED_DELAY_MILLIS,
                        "fixed delay strategy requires fixed_delay_millis",
                    ));
                };
                Ok(RetryDelay::fixed(Duration::from_millis(fixed_delay_millis)))
            }
            Some((_, strategy)) if strategy == "random" => Ok(RetryDelay::random(
                Duration::from_millis(self.random_min_delay_millis.ok_or_else(|| {
                    RetryConfigError::invalid_value(
                        KEY_RANDOM_MIN_DELAY_MILLIS,
                        "random delay strategy requires random_min_delay_millis",
                    )
                })?),
                Duration::from_millis(self.random_max_delay_millis.ok_or_else(|| {
                    RetryConfigError::invalid_value(
                        KEY_RANDOM_MAX_DELAY_MILLIS,
                        "random delay strategy requires random_max_delay_millis",
                    )
                })?),
            )),
            Some((_, strategy))
                if strategy == "exponential" || strategy == "exponential_backoff" =>
            {
                let initial_delay = self.exponential_initial_delay_millis.ok_or_else(|| {
                    RetryConfigError::invalid_value(
                        KEY_EXPONENTIAL_INITIAL_DELAY_MILLIS,
                        "exponential delay strategy requires exponential_initial_delay_millis",
                    )
                })?;
                let max_delay = self.exponential_max_delay_millis.ok_or_else(|| {
                    RetryConfigError::invalid_value(
                        KEY_EXPONENTIAL_MAX_DELAY_MILLIS,
                        "exponential delay strategy requires exponential_max_delay_millis",
                    )
                })?;
                let multiplier = self.exponential_multiplier.ok_or_else(|| {
                    RetryConfigError::invalid_value(
                        KEY_EXPONENTIAL_MULTIPLIER,
                        "exponential delay strategy requires exponential_multiplier",
                    )
                })?;
                Ok(RetryDelay::exponential(
                    Duration::from_millis(initial_delay),
                    Duration::from_millis(max_delay),
                    multiplier,
                ))
            }
            Some((key, other)) => Err(RetryConfigError::invalid_value(
                key,
                format!("unsupported delay strategy '{other}'"),
            )),
        }
    }

    /// Resolves a delay strategy from parameter keys when no strategy name is configured.
    ///
    /// # Parameters
    /// This method has no parameters.
    ///
    /// # Returns
    /// `Some(RetryDelay)` when any delay parameter key is present; otherwise `None`.
    ///
    /// # Errors
    /// This method does not return errors because all config reads have already
    /// succeeded.
    fn get_implicit_delay(&self) -> Option<RetryDelay> {
        if let Some(millis) = self.fixed_delay_millis {
            return Some(RetryDelay::fixed(Duration::from_millis(millis)));
        }
        if self.random_min_delay_millis.is_some() || self.random_max_delay_millis.is_some() {
            return Some(RetryDelay::random(
                Duration::from_millis(
                    self.random_min_delay_millis
                        .unwrap_or(DEFAULT_RETRY_RANDOM_MIN_DELAY_MILLIS),
                ),
                Duration::from_millis(
                    self.random_max_delay_millis
                        .unwrap_or(DEFAULT_RETRY_RANDOM_MAX_DELAY_MILLIS),
                ),
            ));
        }
        if self.exponential_initial_delay_millis.is_some()
            || self.exponential_max_delay_millis.is_some()
            || self.exponential_multiplier.is_some()
        {
            return Some(RetryDelay::exponential(
                Duration::from_millis(
                    self.exponential_initial_delay_millis
                        .unwrap_or(DEFAULT_RETRY_EXPONENTIAL_INITIAL_DELAY_MILLIS),
                ),
                Duration::from_millis(
                    self.exponential_max_delay_millis
                        .unwrap_or(DEFAULT_RETRY_EXPONENTIAL_MAX_DELAY_MILLIS),
                ),
                self.exponential_multiplier
                    .unwrap_or(DEFAULT_RETRY_EXPONENTIAL_MULTIPLIER),
            ));
        }
        None
    }

    /// Resolves the jitter strategy.
    ///
    /// # Parameters
    /// - `default`: Default options used when no jitter key is present or the
    ///   jitter factor key is absent.
    ///
    /// # Returns
    /// The configured or default [`RetryJitter`] strategy.
    ///
    /// # Errors
    /// This method does not return errors. RetryJitter value validation is handled
    /// by [`RetryOptions::new`].
    fn get_jitter(&self, default: &RetryOptions) -> RetryJitter {
        match self.jitter_factor {
            Some(factor) if factor == DEFAULT_RETRY_JITTER_FACTOR => RetryJitter::None,
            None => default.jitter(),
            Some(factor) => RetryJitter::Factor(factor),
        }
    }
}

/// Parses a configured attempt-timeout policy.
///
/// # Parameters
/// - `value`: Raw policy text read from configuration.
///
/// # Returns
/// A parsed [`AttemptTimeoutPolicy`].
///
/// # Errors
/// Returns [`RetryConfigError`] when the policy text is unsupported.
fn parse_attempt_timeout_policy(value: &str) -> Result<AttemptTimeoutPolicy, RetryConfigError> {
    AttemptTimeoutPolicy::from_str(value)
        .map_err(|message| RetryConfigError::invalid_value(KEY_ATTEMPT_TIMEOUT_POLICY, message))
}