Skip to main content

industrial_protocols_kernel/
retry.rs

1// Copyright (c) 2026 erik <erik@erik.xyz> — https://erik.xyz
2//! # 重试配置
3//!
4//! 支持四种重试策略:
5//!
6//! - **Fixed** — 固定延迟(如每次重试间隔 100ms)
7//! - **Exponential** — 指数退避(每次延迟翻倍,有上限)
8//! - **Linear** — 线性增长(每次延迟增加固定步长)
9//! - **None** — 不重试
10//!
11//! ## 使用示例
12//!
13//! ```rust,no_run
14//! use industrial_protocols_kernel::retry::*;
15//!
16//! let config = RetryConfig {
17//!     max_attempts: 3,
18//!     strategy: RetryStrategy::Exponential { base_ms: 100, max_ms: 5000 },
19//! };
20//! let result = config.run(|| {
21//!     // 尝试操作,返回 Result
22//!     Ok::<i32, &str>(42)
23//! });
24//! ```
25
26use std::time::Duration;
27
28#[derive(Debug, Clone)]
29pub struct RetryConfig {
30    pub max_attempts: u32,
31    pub strategy: RetryStrategy,
32}
33
34#[derive(Debug, Clone)]
35pub enum RetryStrategy {
36    Fixed { delay_ms: u64 },
37    Exponential { base_ms: u64, max_ms: u64 },
38    Linear { base_ms: u64, step_ms: u64 },
39    None,
40}
41
42impl RetryConfig {
43    pub fn start(&self) -> RetryState {
44        RetryState {
45            config: self.clone(),
46            attempt: 0,
47            current_delay: self.initial_delay(),
48        }
49    }
50
51    fn initial_delay(&self) -> Duration {
52        match &self.strategy {
53            RetryStrategy::Fixed { delay_ms } => Duration::from_millis(*delay_ms),
54            RetryStrategy::Exponential { base_ms, .. } => Duration::from_millis(*base_ms),
55            RetryStrategy::Linear { base_ms, .. } => Duration::from_millis(*base_ms),
56            RetryStrategy::None => Duration::ZERO,
57        }
58    }
59
60    pub fn run<F, T, E>(&self, mut f: F) -> std::result::Result<T, E>
61    where
62        F: FnMut() -> std::result::Result<T, E>,
63    {
64        let mut state = self.start();
65        loop {
66            match f() {
67                Ok(val) => return Ok(val),
68                Err(e) => match state.next_delay() {
69                    Some(delay) => std::thread::sleep(delay),
70                    None => return Err(e),
71                },
72            }
73        }
74    }
75}
76
77pub struct RetryState {
78    config: RetryConfig,
79    attempt: u32,
80    current_delay: Duration,
81}
82
83impl RetryState {
84    pub fn next_delay(&mut self) -> Option<Duration> {
85        if self.attempt >= self.config.max_attempts.saturating_sub(1) {
86            return None;
87        }
88        let delay = self.current_delay;
89        self.advance();
90        Some(delay)
91    }
92
93    fn advance(&mut self) {
94        self.attempt += 1;
95        self.current_delay = match &self.config.strategy {
96            RetryStrategy::Fixed { delay_ms } => Duration::from_millis(*delay_ms),
97            RetryStrategy::Exponential { base_ms: _, max_ms } => {
98                let next = (self.current_delay.as_millis() as u64).saturating_mul(2);
99                Duration::from_millis(next.min(*max_ms))
100            }
101            RetryStrategy::Linear {
102                base_ms: _,
103                step_ms,
104            } => self.current_delay + Duration::from_millis(*step_ms),
105            RetryStrategy::None => Duration::ZERO,
106        };
107    }
108}
109
110impl Iterator for RetryState {
111    type Item = Duration;
112    fn next(&mut self) -> Option<Duration> {
113        self.next_delay()
114    }
115}