wordval-utils 1.0.3

Wordval utilities: string manipulation, date handling, masking, ID generation, validation, crypto, web helpers, collection tools, retry utilities
Documentation
//! 重试工具:固定间隔、指数退避
//!
//! 用于外部服务调用(邮件/短信/第三方 API)的自动重试。

use std::thread;
use std::time::Duration;

/// 重试工具
pub struct Retry;

impl Retry {
    /// 固定间隔重试
    ///
    /// # 参数
    ///
    /// * `max_attempts` - 最大尝试次数(包括首次)
    /// * `delay` - 每次重试间隔
    /// * `f` - 要执行的操作,返回 `Result<T, E>`
    ///
    /// # 返回
    ///
    /// 成功时返回 `Ok(T)`,所有尝试失败后返回最后一个错误。
    ///
    /// # 示例
    ///
    /// ```
    /// use wordval_utils::retry::Retry;
    /// use std::time::Duration;
    ///
    /// let result = Retry::run(3, Duration::from_millis(10), || {
    ///     Ok::<i32, &str>(42)
    /// });
    /// assert_eq!(result.unwrap(), 42);
    /// ```
    pub fn run<T, E, F>(max_attempts: u32, delay: Duration, mut f: F) -> Result<T, E>
    where
        F: FnMut() -> Result<T, E>,
    {
        assert!(max_attempts > 0, "max_attempts must be greater than 0");

        for attempt in 0..max_attempts {
            match f() {
                Ok(value) => return Ok(value),
                Err(e) => {
                    if attempt + 1 == max_attempts {
                        return Err(e);
                    }
                    thread::sleep(delay);
                }
            }
        }
        unreachable!()
    }

    /// 指数退避重试
    ///
    /// # 参数
    ///
    /// * `max_attempts` - 最大尝试次数(包括首次)
    /// * `initial_delay` - 初始延迟时间
    /// * `f` - 要执行的操作,返回 `Result<T, E>`
    ///
    /// 延迟时间按 2 的幂次增长:`initial_delay`, `2 * initial_delay`, `4 * initial_delay`, ...
    ///
    /// # 返回
    ///
    /// 成功时返回 `Ok(T)`,所有尝试失败后返回最后一个错误。
    ///
    /// # 示例
    ///
    /// ```
    /// use wordval_utils::retry::Retry;
    /// use std::time::Duration;
    ///
    /// let result = Retry::with_backoff(3, Duration::from_millis(10), || {
    ///     Ok::<i32, &str>(42)
    /// });
    /// assert_eq!(result.unwrap(), 42);
    /// ```
    pub fn with_backoff<T, E, F>(max_attempts: u32, initial_delay: Duration, mut f: F) -> Result<T, E>
    where
        F: FnMut() -> Result<T, E>,
    {
        assert!(max_attempts > 0, "max_attempts must be greater than 0");

        let mut delay = initial_delay;
        for attempt in 0..max_attempts {
            match f() {
                Ok(value) => return Ok(value),
                Err(e) => {
                    if attempt + 1 == max_attempts {
                        return Err(e);
                    }
                    thread::sleep(delay);
                    // 溢出时饱和到 Duration::MAX,避免 panic
                    delay = delay.checked_mul(2).unwrap_or(Duration::MAX);
                }
            }
        }
        unreachable!()
    }

    /// 带最大延迟限制的指数退避重试
    ///
    /// # 参数
    ///
    /// * `max_attempts` - 最大尝试次数(包括首次)
    /// * `initial_delay` - 初始延迟时间
    /// * `max_delay` - 最大延迟时间(延迟不会超过此值)
    /// * `f` - 要执行的操作
    ///
    /// # 示例
    ///
    /// ```
    /// use wordval_utils::retry::Retry;
    /// use std::time::Duration;
    ///
    /// let result = Retry::with_backoff_capped(
    ///     5,
    ///     Duration::from_millis(100),
    ///     Duration::from_secs(1),
    ///     || Ok::<i32, &str>(42)
    /// );
    /// assert_eq!(result.unwrap(), 42);
    /// ```
    pub fn with_backoff_capped<T, E, F>(
        max_attempts: u32,
        initial_delay: Duration,
        max_delay: Duration,
        mut f: F,
    ) -> Result<T, E>
    where
        F: FnMut() -> Result<T, E>,
    {
        assert!(max_attempts > 0, "max_attempts must be greater than 0");

        let mut delay = initial_delay.min(max_delay);
        for attempt in 0..max_attempts {
            match f() {
                Ok(value) => return Ok(value),
                Err(e) => {
                    if attempt + 1 == max_attempts {
                        return Err(e);
                    }
                    thread::sleep(delay);
                    // 溢出时饱和到 max_delay,避免 panic
                    delay = delay
                        .checked_mul(2)
                        .map(|d| d.min(max_delay))
                        .unwrap_or(max_delay);
                }
            }
        }
        unreachable!()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicU32, Ordering};
    use std::sync::Arc;

    #[test]
    fn test_run_success_first_try() {
        let counter = Arc::new(AtomicU32::new(0));
        let counter_clone = counter.clone();

        let result: Result<i32, &str> = Retry::run(3, Duration::from_millis(1), move || {
            counter_clone.fetch_add(1, Ordering::SeqCst);
            Ok(42)
        });

        assert_eq!(result.unwrap(), 42);
        assert_eq!(counter.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn test_run_success_after_retries() {
        let counter = Arc::new(AtomicU32::new(0));
        let counter_clone = counter.clone();

        let result: Result<i32, &str> = Retry::run(3, Duration::from_millis(1), move || {
            let count = counter_clone.fetch_add(1, Ordering::SeqCst);
            if count < 2 {
                Err("not yet")
            } else {
                Ok(42)
            }
        });

        assert_eq!(result.unwrap(), 42);
        assert_eq!(counter.load(Ordering::SeqCst), 3);
    }

    #[test]
    fn test_run_all_fail() {
        let counter = Arc::new(AtomicU32::new(0));
        let counter_clone = counter.clone();

        let result: Result<i32, &str> = Retry::run(3, Duration::from_millis(1), move || {
            counter_clone.fetch_add(1, Ordering::SeqCst);
            Err("always fails")
        });

        assert_eq!(result.unwrap_err(), "always fails");
        assert_eq!(counter.load(Ordering::SeqCst), 3);
    }

    #[test]
    fn test_run_single_attempt() {
        let counter = Arc::new(AtomicU32::new(0));
        let counter_clone = counter.clone();

        let result: Result<i32, &str> = Retry::run(1, Duration::from_millis(1), move || {
            counter_clone.fetch_add(1, Ordering::SeqCst);
            Err("fail")
        });

        assert_eq!(result.unwrap_err(), "fail");
        assert_eq!(counter.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn test_with_backoff_success() {
        let counter = Arc::new(AtomicU32::new(0));
        let counter_clone = counter.clone();

        let result: Result<i32, &str> =
            Retry::with_backoff(3, Duration::from_millis(1), move || {
                let count = counter_clone.fetch_add(1, Ordering::SeqCst);
                if count < 1 {
                    Err("not yet")
                } else {
                    Ok(42)
                }
            });

        assert_eq!(result.unwrap(), 42);
        assert_eq!(counter.load(Ordering::SeqCst), 2);
    }

    #[test]
    fn test_with_backoff_all_fail() {
        let counter = Arc::new(AtomicU32::new(0));
        let counter_clone = counter.clone();

        let result: Result<i32, &str> =
            Retry::with_backoff(3, Duration::from_millis(1), move || {
                counter_clone.fetch_add(1, Ordering::SeqCst);
                Err("always fails")
            });

        assert_eq!(result.unwrap_err(), "always fails");
        assert_eq!(counter.load(Ordering::SeqCst), 3);
    }

    #[test]
    fn test_with_backoff_capped_success() {
        let counter = Arc::new(AtomicU32::new(0));
        let counter_clone = counter.clone();

        let result: Result<i32, &str> = Retry::with_backoff_capped(
            5,
            Duration::from_millis(1),
            Duration::from_millis(10),
            move || {
                let count = counter_clone.fetch_add(1, Ordering::SeqCst);
                if count < 3 {
                    Err("not yet")
                } else {
                    Ok(42)
                }
            },
        );

        assert_eq!(result.unwrap(), 42);
        assert_eq!(counter.load(Ordering::SeqCst), 4);
    }

    #[test]
    #[should_panic(expected = "max_attempts must be greater than 0")]
    fn test_run_zero_attempts() {
        let _ = Retry::run(0, Duration::from_millis(1), || Ok::<i32, &str>(42));
    }

    #[test]
    #[should_panic(expected = "max_attempts must be greater than 0")]
    fn test_with_backoff_zero_attempts() {
        let _ = Retry::with_backoff(0, Duration::from_millis(1), || Ok::<i32, &str>(42));
    }

    #[test]
    #[should_panic(expected = "max_attempts must be greater than 0")]
    fn test_with_backoff_capped_zero_attempts() {
        let _ = Retry::with_backoff_capped(
            0,
            Duration::from_millis(1),
            Duration::from_millis(10),
            || Ok::<i32, &str>(42),
        );
    }
}