wordval-utils 1.0.8

Wordval utilities: string manipulation, date handling, masking, ID generation, validation, crypto, web helpers, collection tools, retry utilities
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
//! 重试工具:同步重试、指数退避、预算制异步重试管理器
//!
//! - [`Retry`]:**同步**重试(内部 `thread::sleep`),仅限同步上下文;
//!   在 tokio 运行时内调用会阻塞 worker 线程,异步场景必须用 [`RetryManager`]。
//! - [`RetryManager`]:异步预算制重试——总耗时预算 + 单次尝试超时 +
//!   取消令牌 + 错误分类(可重试 vs 不可重试),复用 [`backoff`] 的
//!   指数退避延迟逻辑。
//!
//! # 边界条件(诚实文档)
//!
//! - 被取消([`RetryError::Cancelled`])或超时的尝试**结果未知**:
//!   对非幂等操作(如 POST 下单),上层需自行保证幂等或对账。
//! - [`RetryManager`] 无状态、`Send + Sync`:退避状态在每次 `run` 内部
//!   独立创建,可在多任务间共享同一实例。

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

use tokio_util::sync::CancellationToken;

use crate::backoff::ExponentialBackoff;
use crate::correctness::{check_predicate_true, CorrectnessError};

/// 重试工具
pub struct Retry;

impl Retry {
    /// 固定间隔重试
    ///
    /// # 参数
    ///
    /// * `max_attempts` - 最大尝试次数(包括首次)
    /// * `delay` - 每次重试间隔
    /// * `f` - 要执行的操作,返回 `Result<T, E>`
    ///
    /// # 返回
    ///
    /// 成功时返回 `Ok(T)`,所有尝试失败后返回最后一个错误。
    ///
    /// # 警告
    ///
    /// 内部使用 `thread::sleep` **阻塞等待**——仅限同步上下文(初始化代码、
    /// 非异步线程)。在 tokio 运行时内调用会阻塞 worker 线程,异步场景请用
    /// [`RetryManager`]。
    ///
    /// # 示例
    ///
    /// ```
    /// 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)`,所有尝试失败后返回最后一个错误。
    ///
    /// # 警告
    ///
    /// 同 [`Retry::run`]:`thread::sleep` 阻塞等待,仅限同步上下文。
    ///
    /// # 示例
    ///
    /// ```
    /// 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` - 要执行的操作
    ///
    /// # 警告
    ///
    /// 同 [`Retry::run`]:`thread::sleep` 阻塞等待,仅限同步上下文。
    ///
    /// # 示例
    ///
    /// ```
    /// 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!()
    }
}

/// 异步重试配置
///
/// 退避参数校验复用 [`ExponentialBackoff::new`](构造期返回错误而非 panic)。
#[derive(Debug, Clone)]
pub struct RetryConfig {
    /// 最大尝试次数(含首次,必须 >= 1)
    pub max_attempts: u32,
    /// 初始延迟(必须非零)
    pub initial_delay: Duration,
    /// 延迟封顶(必须 >= initial_delay)
    pub max_delay: Duration,
    /// 增长因子,范围 `[1.0, 100.0]`
    pub factor: f64,
    /// 抖动上限(毫秒),0 表示无抖动
    pub jitter_ms: u64,
    /// 首次尝试前是否零延迟(仅首跳生效一次)
    pub immediate_first: bool,
    /// 总耗时预算(含尝试与等待);超预算立即放弃并返回
    /// [`RetryError::BudgetExhausted`],`None` 表示不设总预算
    pub total_budget: Option<Duration>,
    /// 单次尝试超时;超时的尝试按可重试失败计(结果未知,见模块文档),
    /// `None` 表示不设单次超时
    pub per_attempt_timeout: Option<Duration>,
}

impl RetryConfig {
    /// 常用默认配置:最多 5 次、100ms 起步、指数增长封顶 10s、25ms 抖动
    pub fn defaults() -> Self {
        Self {
            max_attempts: 5,
            initial_delay: Duration::from_millis(100),
            max_delay: Duration::from_secs(10),
            factor: 2.0,
            jitter_ms: 25,
            immediate_first: false,
            total_budget: None,
            per_attempt_timeout: None,
        }
    }
}

/// 重试失败原因分类
///
/// `last_error: None` 表示最后一次失败是**尝试超时**(超时没有 `E` 可携带)。
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RetryError<E> {
    /// 取消令牌触发(可能在尝试前、尝试中或等待延迟中)。
    /// 被取消的尝试结果未知,非幂等操作需上层对账。
    Cancelled,
    /// 尝试次数耗尽
    AttemptsExhausted {
        /// 实际尝试次数
        attempts: u32,
        /// 最后一次的业务错误;`None` = 最后一次是超时
        last_error: Option<E>,
    },
    /// 总耗时预算耗尽
    BudgetExhausted {
        /// 已完成的尝试次数
        attempts: u32,
        /// 最后一次的业务错误;`None` = 最后一次是超时
        last_error: Option<E>,
    },
}

impl<E: std::fmt::Display> std::fmt::Display for RetryError<E> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Cancelled => write!(f, "retry cancelled"),
            Self::AttemptsExhausted { attempts, last_error } => match last_error {
                Some(e) => write!(f, "retry attempts exhausted ({attempts}): {e}"),
                None => write!(f, "retry attempts exhausted ({attempts}): last attempt timed out"),
            },
            Self::BudgetExhausted { attempts, last_error } => match last_error {
                Some(e) => write!(f, "retry budget exhausted ({attempts} attempts): {e}"),
                None => write!(f, "retry budget exhausted ({attempts} attempts): last attempt timed out"),
            },
        }
    }
}

impl<E: std::fmt::Display + std::fmt::Debug> std::error::Error for RetryError<E> {}

/// 预算制异步重试管理器:无状态、线程安全
///
/// 除常规重试次数外提供「总耗时预算」维度,把总预算、单次尝试超时、
/// 取消传播、错误分类统一在一个循环里处理。退避延迟复用
/// [`ExponentialBackoff`](含抖动与饱和期分布保持)。
///
/// # 示例
///
/// ```no_run
/// use wordval_utils::retry::{RetryConfig, RetryManager};
/// use std::time::Duration;
///
/// # async fn demo() {
/// let mgr = RetryManager::new(RetryConfig {
///     total_budget: Some(Duration::from_secs(5)),
///     per_attempt_timeout: Some(Duration::from_secs(1)),
///     ..RetryConfig::defaults()
/// }).unwrap();
///
/// let result: Result<u32, _> = mgr.run(|| async {
///     Ok::<u32, std::fmt::Error>(42)
/// }).await;
/// assert_eq!(result.unwrap(), 42);
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct RetryManager {
    config: RetryConfig,
}

impl RetryManager {
    /// 创建重试管理器;参数在构造期校验
    ///
    /// # Errors
    ///
    /// - `max_attempts` 为 0
    /// - 退避参数非法(见 [`ExponentialBackoff::new`])
    pub fn new(config: RetryConfig) -> Result<Self, CorrectnessError> {
        check_predicate_true(config.max_attempts >= 1, "max_attempts must be >= 1")?;
        check_predicate_true(
            config.per_attempt_timeout.map_or(true, |t| !t.is_zero()),
            "per_attempt_timeout must be non-zero",
        )?;
        check_predicate_true(
            config.total_budget.map_or(true, |t| !t.is_zero()),
            "total_budget must be non-zero",
        )?;
        // 退避参数复用 backoff 的构造期校验
        ExponentialBackoff::new(
            config.initial_delay,
            config.max_delay,
            config.factor,
            config.jitter_ms,
            config.immediate_first,
        )?;
        Ok(Self { config })
    }

    /// 运行操作并按配置重试;所有错误视为可重试
    pub async fn run<T, E, F, Fut>(&self, mut f: F) -> Result<T, RetryError<E>>
    where
        F: FnMut() -> Fut,
        Fut: std::future::Future<Output = Result<T, E>>,
    {
        self.run_impl(None, |_: &E| true, &mut f).await
    }

    /// 带取消令牌运行:令牌触发时立即返回 [`RetryError::Cancelled`]
    /// (尝试前、尝试中、等待延迟中三处检查点均生效)
    pub async fn run_with_cancel<T, E, F, Fut>(
        &self,
        cancel: &CancellationToken,
        mut f: F,
    ) -> Result<T, RetryError<E>>
    where
        F: FnMut() -> Fut,
        Fut: std::future::Future<Output = Result<T, E>>,
    {
        self.run_impl(Some(cancel), |_: &E| true, &mut f).await
    }

    /// 带错误分类器运行:`is_retryable` 返回 `false` 的错误立即透传,
    /// 不再重试(如参数校验错误 vs 网络瞬态错误)
    pub async fn run_if<T, E, F, Fut, C>(&self, is_retryable: C, mut f: F) -> Result<T, RetryError<E>>
    where
        F: FnMut() -> Fut,
        Fut: std::future::Future<Output = Result<T, E>>,
        C: Fn(&E) -> bool,
    {
        self.run_impl(None, is_retryable, &mut f).await
    }

    /// 全参数内部实现:取消 + 分类 + 重试循环
    async fn run_impl<T, E, F, Fut, C>(
        &self,
        cancel: Option<&CancellationToken>,
        is_retryable: C,
        f: &mut F,
    ) -> Result<T, RetryError<E>>
    where
        F: FnMut() -> Fut,
        Fut: std::future::Future<Output = Result<T, E>>,
        C: Fn(&E) -> bool,
    {
        // 每次运行独立创建退避状态(manager 无状态可共享)
        let mut backoff = ExponentialBackoff::new(
            self.config.initial_delay,
            self.config.max_delay,
            self.config.factor,
            self.config.jitter_ms,
            self.config.immediate_first,
        )
        .expect("RetryManager::new 已校验退避参数,此处不可失败");

        let started = tokio::time::Instant::now();
        let mut last_error: Option<E> = None;
        // 是否因取消/预算退出(决定最终错误归类时不再补一次尝试)
        let mut attempts: u32 = 0;

        while attempts < self.config.max_attempts {
            // 检查点 1:取消(尝试前)
            if let Some(c) = cancel {
                if c.is_cancelled() {
                    return Err(RetryError::Cancelled);
                }
            }
            // 检查点 2:总预算(尝试前,剩余不足一次尝试则放弃)
            if let Some(budget) = self.config.total_budget {
                if started.elapsed() >= budget {
                    return Err(RetryError::BudgetExhausted {
                        attempts,
                        last_error,
                    });
                }
            }

            attempts += 1;
            let fut = f();
            // 尝试执行:叠加取消与单次超时
            let result = match cancel {
                Some(c) => {
                    let run_fut = maybe_timeout(self.config.per_attempt_timeout, fut);
                    tokio::select! {
                        biased;
                        _ = c.cancelled() => return Err(RetryError::Cancelled),
                        r = run_fut => r,
                    }
                }
                None => maybe_timeout(self.config.per_attempt_timeout, fut).await,
            };

            match result {
                Some(Ok(value)) => return Ok(value),
                Some(Err(e)) => {
                    if !is_retryable(&e) {
                        return Err(RetryError::AttemptsExhausted {
                            attempts,
                            last_error: Some(e),
                        });
                    }
                    last_error = Some(e);
                }
                // 单次超时:结果未知,按可重试失败计(last_error 置 None 表示超时)
                None => last_error = None,
            }

            // 已是最后一次尝试:不再等待延迟,直接按耗尽归类
            if attempts >= self.config.max_attempts {
                break;
            }

            // 检查点 3:取消 + 预算(等待延迟中)
            let delay = backoff.next_duration();
            match cancel {
                Some(c) => {
                    tokio::select! {
                        biased;
                        _ = c.cancelled() => return Err(RetryError::Cancelled),
                        () = tokio::time::sleep(delay) => {}
                    }
                }
                None => tokio::time::sleep(delay).await,
            }
        }

        // 区分「预算在等待延迟中耗尽」与「次数耗尽」
        if let Some(budget) = self.config.total_budget {
            if started.elapsed() >= budget {
                return Err(RetryError::BudgetExhausted {
                    attempts,
                    last_error,
                });
            }
        }
        Err(RetryError::AttemptsExhausted {
            attempts,
            last_error,
        })
    }
}

/// 按需包裹单次尝试超时;`None` 时直接执行
async fn maybe_timeout<E, T>(
    timeout: Option<Duration>,
    fut: impl std::future::Future<Output = Result<T, E>>,
) -> Option<Result<T, E>> {
    match timeout {
        Some(t) => tokio::time::timeout(t, fut).await.ok(),
        None => Some(fut.await),
    }
}

#[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),
        );
    }

    // ── RetryManager ─────────────────────────────────────────────

    fn fast_cfg(max_attempts: u32) -> RetryConfig {
        RetryConfig {
            max_attempts,
            initial_delay: Duration::from_millis(1),
            max_delay: Duration::from_millis(5),
            factor: 2.0,
            jitter_ms: 0,
            immediate_first: false,
            total_budget: None,
            per_attempt_timeout: None,
        }
    }

    #[tokio::test]
    async fn manager_success_first_try() {
        let mgr = RetryManager::new(fast_cfg(3)).unwrap();
        let n = mgr.run(|| async { Ok::<i32, &str>(1) }).await.unwrap();
        assert_eq!(n, 1);
    }

    #[tokio::test]
    async fn manager_success_after_retries() {
        let mgr = RetryManager::new(fast_cfg(4)).unwrap();
        let calls = Arc::new(AtomicU32::new(0));
        let c = calls.clone();
        let n = mgr
            .run(move || {
                let c = c.clone();
                async move {
                    let k = c.fetch_add(1, Ordering::SeqCst);
                    if k < 2 {
                        Err("no")
                    } else {
                        Ok(k)
                    }
                }
            })
            .await
            .unwrap();
        assert_eq!(n, 2);
        assert_eq!(calls.load(Ordering::SeqCst), 3);
    }

    #[tokio::test]
    async fn manager_attempts_exhausted() {
        let mgr = RetryManager::new(fast_cfg(3)).unwrap();
        let err = mgr
            .run(|| async { Err::<i32, _>("boom") })
            .await
            .unwrap_err();
        match err {
            RetryError::AttemptsExhausted { attempts, last_error } => {
                assert_eq!(attempts, 3);
                assert_eq!(last_error, Some("boom"));
            }
            other => panic!("期望 AttemptsExhausted,实际 {other:?}"),
        }
    }

    #[tokio::test]
    async fn manager_config_validation() {
        assert!(RetryManager::new(RetryConfig {
            max_attempts: 0,
            ..fast_cfg(1)
        })
        .is_err());
        assert!(RetryManager::new(RetryConfig {
            initial_delay: Duration::ZERO,
            ..fast_cfg(1)
        })
        .is_err());
        assert!(RetryManager::new(RetryConfig {
            factor: 1000.0,
            ..fast_cfg(1)
        })
        .is_err());
    }

    /// 不可重试错误立即透传,不再消耗尝试次数
    #[tokio::test]
    async fn manager_non_retryable_passthrough() {
        let mgr = RetryManager::new(fast_cfg(5)).unwrap();
        let calls = Arc::new(AtomicU32::new(0));
        let c = calls.clone();
        let err = mgr
            .run_if(
                |e: &i32| *e != 7, // 7 视为不可重试
                move || {
                    let c = c.clone();
                    async move {
                        c.fetch_add(1, Ordering::SeqCst);
                        Err::<i32, _>(7)
                    }
                },
            )
            .await
            .unwrap_err();
        match err {
            RetryError::AttemptsExhausted { attempts, .. } => assert_eq!(attempts, 1),
            other => panic!("期望 AttemptsExhausted,实际 {other:?}"),
        }
        assert_eq!(calls.load(Ordering::SeqCst), 1);
    }

    /// 总预算耗尽:快于次数耗尽时按 BudgetExhausted 归类
    #[tokio::test(start_paused = true)]
    async fn manager_budget_exhausted() {
        let mgr = RetryManager::new(RetryConfig {
            max_attempts: 100,
            initial_delay: Duration::from_secs(1),
            max_delay: Duration::from_secs(1),
            total_budget: Some(Duration::from_secs(3)),
            ..fast_cfg(1)
        })
        .unwrap();
        let err = mgr
            .run(|| async { Err::<i32, _>("boom") })
            .await
            .unwrap_err();
        match err {
            RetryError::BudgetExhausted { attempts, .. } => {
                // 暂停时钟下尝试瞬间完成:t=0,1,2 各一次,t=3 循环顶预算检查失败
                assert_eq!(attempts, 3);
            }
            other => panic!("期望 BudgetExhausted,实际 {other:?}"),
        }
    }

    /// 单次尝试超时:按可重试失败计,last_error 为 None
    #[tokio::test(start_paused = true)]
    async fn manager_attempt_timeout_retries() {
        let mgr = RetryManager::new(RetryConfig {
            max_attempts: 2,
            per_attempt_timeout: Some(Duration::from_millis(10)),
            ..fast_cfg(1)
        })
        .unwrap();
        let err = mgr
            .run(|| async {
                tokio::time::sleep(Duration::from_secs(60)).await; // 永远超时
                Ok::<i32, &str>(1)
            })
            .await
            .unwrap_err();
        match err {
            RetryError::AttemptsExhausted {
                attempts,
                last_error,
            } => {
                assert_eq!(attempts, 2);
                assert!(last_error.is_none(), "超时无业务错误可携带");
            }
            other => panic!("期望 AttemptsExhausted,实际 {other:?}"),
        }
    }

    /// 取消令牌在尝试中触发 → Cancelled
    #[tokio::test]
    async fn manager_cancel_during_attempt() {
        let mgr = RetryManager::new(fast_cfg(5)).unwrap();
        let cancel = CancellationToken::new();
        let c2 = cancel.clone();
        let err = mgr
            .run_with_cancel(&cancel, move || {
                let c2 = c2.clone();
                async move {
                    c2.cancel(); // 尝试一开始就取消
                    tokio::time::sleep(Duration::from_millis(10)).await;
                    Err::<i32, _>("boom")
                }
            })
            .await
            .unwrap_err();
        assert!(matches!(err, RetryError::Cancelled));
    }

    /// 取消令牌在等待延迟中触发 → Cancelled,不发起下一次尝试
    #[tokio::test(start_paused = true)]
    async fn manager_cancel_during_backoff() {
        // 首次退避 10ms,取消定在 2ms——必落在首次退避等待中
        let mgr = RetryManager::new(RetryConfig {
            initial_delay: Duration::from_millis(10),
            max_delay: Duration::from_millis(10),
            ..fast_cfg(5)
        })
        .unwrap();
        let cancel = CancellationToken::new();
        let calls = Arc::new(AtomicU32::new(0));
        let c = calls.clone();
        let c2 = cancel.clone();
        tokio::spawn(async move {
            // 首次尝试失败、进入退避等待后取消
            tokio::time::sleep(Duration::from_millis(2)).await;
            c2.cancel();
        });
        let err = mgr
            .run_with_cancel(&cancel, move || {
                let c = c.clone();
                async move {
                    c.fetch_add(1, Ordering::SeqCst);
                    Err::<i32, _>("boom")
                }
            })
            .await
            .unwrap_err();
        assert!(matches!(err, RetryError::Cancelled));
        // 只应有 1 次尝试(取消发生在退避等待中)
        assert_eq!(calls.load(Ordering::SeqCst), 1);
    }
}