limiteron 0.2.4

Unified flow control framework for Rust
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
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
// Copyright (c) 2026 Kirky.X
// SPDX-License-Identifier: MIT
//! 熔断器类型定义

use crate::clock::{Clock, SystemClock};
use crate::constants::{
    DEFAULT_CIRCUIT_BREAKER_FAILURE_THRESHOLD, DEFAULT_CIRCUIT_BREAKER_HALF_OPEN_MAX_CALLS,
    DEFAULT_CIRCUIT_BREAKER_SLOW_CALL_DURATION_MILLIS,
    DEFAULT_CIRCUIT_BREAKER_SLOW_CALL_RATE_THRESHOLD, DEFAULT_CIRCUIT_BREAKER_SUCCESS_THRESHOLD,
    DEFAULT_CIRCUIT_BREAKER_TIMEOUT_SECS,
};
use crate::error::{CircuitBreakerStats, CircuitState, LimiteronError};
use log::{info, trace, warn};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
use tokio::sync::RwLock;

/// 错误分类器 trait
///
/// 用于判断错误是否应该计入失败计数。
/// 允许用户自定义哪些错误应该被视为失败。
///
/// # 示例
///
/// ```rust
/// use limiteron::circuit::ErrorClassifier;
/// use limiteron::error::LimiteronError;
///
/// #[derive(Debug)]
/// struct CustomErrorClassifier;
/// impl ErrorClassifier for CustomErrorClassifier {
///     fn is_counted_as_failure(&self, error: &LimiteronError) -> bool {
///         // 自定义逻辑:只有特定的错误才算失败
///         !matches!(error, LimiteronError::ValidationError(_))
///     }
/// }
/// ```
pub trait ErrorClassifier: Send + Sync + std::fmt::Debug {
    /// 判断错误是否应该计入失败计数
    ///
    /// # 参数
    /// - `error`: 要判断的错误
    ///
    /// # 返回
    /// - `true`: 错误应计入失败计数
    /// - `false`: 错误不应计入失败计数
    fn is_counted_as_failure(&self, error: &LimiteronError) -> bool;
}

/// 默认错误分类器
///
/// 默认行为:
/// - 5xx 错误(StorageError::ConnectionError, StorageError::TimeoutError)算失败
/// - 超时错误算失败
/// - 4xx 错误(ValidationError, NotFound)不算失败
#[derive(Debug)]
pub struct DefaultErrorClassifier;

impl ErrorClassifier for DefaultErrorClassifier {
    fn is_counted_as_failure(&self, error: &LimiteronError) -> bool {
        match error {
            // 存储相关的临时错误算失败
            LimiteronError::StorageError(storage_err) => storage_err.is_transient(),
            // 限流、熔断器错误不算失败(这些是预期的保护机制)
            LimiteronError::LimitError(_) | LimiteronError::CircuitBreakerError(_) => false,
            // 验证错误不算失败(客户端问题)
            LimiteronError::ValidationError(_) => false,
            // 其他错误算失败
            _ => true,
        }
    }
}

/// 熔断器配置
#[derive(Debug, Clone)]
pub struct CircuitBreakerConfig {
    /// 失败阈值(达到此值时熔断)
    pub failure_threshold: u64,
    /// 成功阈值(半开状态下达到此值时恢复)
    pub success_threshold: u64,
    /// 超时时间(打开状态后等待此时间再尝试恢复)
    pub timeout: Duration,
    /// 半开状态的最大调用次数
    pub half_open_max_calls: u64,
    /// 慢调用时长阈值(超过此时长视为慢调用)
    pub slow_call_duration_threshold: Duration,
    /// 慢调用率阈值(慢调用占比超过此值时熔断)
    pub slow_call_rate_threshold: f64,
    /// 错误分类器
    pub error_classifier: Arc<dyn ErrorClassifier>,
}

impl Default for CircuitBreakerConfig {
    fn default() -> Self {
        Self {
            failure_threshold: DEFAULT_CIRCUIT_BREAKER_FAILURE_THRESHOLD,
            success_threshold: DEFAULT_CIRCUIT_BREAKER_SUCCESS_THRESHOLD,
            timeout: Duration::from_secs(DEFAULT_CIRCUIT_BREAKER_TIMEOUT_SECS),
            half_open_max_calls: DEFAULT_CIRCUIT_BREAKER_HALF_OPEN_MAX_CALLS,
            slow_call_duration_threshold: Duration::from_millis(
                DEFAULT_CIRCUIT_BREAKER_SLOW_CALL_DURATION_MILLIS,
            ),
            slow_call_rate_threshold: DEFAULT_CIRCUIT_BREAKER_SLOW_CALL_RATE_THRESHOLD,
            error_classifier: Arc::new(DefaultErrorClassifier),
        }
    }
}

impl CircuitBreakerConfig {
    /// 创建新的熔断器配置
    pub fn new(failure_threshold: u64, success_threshold: u64, timeout: Duration) -> Self {
        Self {
            failure_threshold,
            success_threshold,
            timeout,
            half_open_max_calls: DEFAULT_CIRCUIT_BREAKER_HALF_OPEN_MAX_CALLS,
            slow_call_duration_threshold: Duration::from_millis(
                DEFAULT_CIRCUIT_BREAKER_SLOW_CALL_DURATION_MILLIS,
            ),
            slow_call_rate_threshold: DEFAULT_CIRCUIT_BREAKER_SLOW_CALL_RATE_THRESHOLD,
            error_classifier: Arc::new(DefaultErrorClassifier),
        }
    }

    /// 设置半开状态的最大调用次数
    pub fn half_open_max_calls(mut self, max_calls: u64) -> Self {
        self.half_open_max_calls = max_calls;
        self
    }

    /// 设置慢调用时长阈值
    pub fn slow_call_duration_threshold(mut self, threshold: Duration) -> Self {
        self.slow_call_duration_threshold = threshold;
        self
    }

    /// 设置慢调用率阈值
    pub fn slow_call_rate_threshold(mut self, threshold: f64) -> Self {
        self.slow_call_rate_threshold = threshold;
        self
    }

    /// 设置错误分类器
    pub fn error_classifier(mut self, classifier: Arc<dyn ErrorClassifier>) -> Self {
        self.error_classifier = classifier;
        self
    }
}

/// 熔断器
pub struct CircuitBreaker {
    /// 当前状态
    state: Arc<RwLock<CircuitState>>,
    /// 失败计数
    failure_count: Arc<AtomicU64>,
    /// 成功计数
    success_count: Arc<AtomicU64>,
    /// 总调用次数
    total_calls: Arc<AtomicU64>,
    /// 慢调用计数
    slow_call_count: Arc<AtomicU64>,
    /// 最后失败时间
    last_failure_time: Arc<RwLock<Option<Instant>>>,
    /// 最后状态变更时间
    last_state_change: Arc<RwLock<Option<Instant>>>,
    /// 半开状态下的调用计数
    half_open_calls: Arc<AtomicU64>,
    /// 配置
    config: CircuitBreakerConfig,
    /// 时钟实例
    clock: Arc<dyn Clock>,
    /// 事件发射器(可选,feature-gated)
    #[cfg(feature = "event-system")]
    event_emitter: Option<Arc<crate::events::EventEmitter>>,
}

/// 熔断器构建器
#[derive(Debug, Clone)]
pub struct CircuitBreakerBuilder {
    config: CircuitBreakerConfig,
}

impl CircuitBreakerBuilder {
    /// 创建新的构建器
    pub fn new() -> Self {
        Self {
            config: CircuitBreakerConfig::default(),
        }
    }

    /// 设置失败阈值
    pub fn failure_threshold(mut self, failure_threshold: u64) -> Self {
        self.config.failure_threshold = failure_threshold;
        self
    }

    /// 设置成功阈值
    pub fn success_threshold(mut self, success_threshold: u64) -> Self {
        self.config.success_threshold = success_threshold;
        self
    }

    /// 设置超时时间
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.config.timeout = timeout;
        self
    }

    /// 设置半开状态的最大调用次数
    pub fn half_open_max_calls(mut self, max_calls: u64) -> Self {
        self.config.half_open_max_calls = max_calls;
        self
    }

    /// 设置慢调用时长阈值
    pub fn slow_call_duration_threshold(mut self, threshold: Duration) -> Self {
        self.config.slow_call_duration_threshold = threshold;
        self
    }

    /// 设置慢调用率阈值
    pub fn slow_call_rate_threshold(mut self, threshold: f64) -> Self {
        self.config.slow_call_rate_threshold = threshold;
        self
    }

    /// 设置错误分类器
    pub fn error_classifier(mut self, classifier: Arc<dyn ErrorClassifier>) -> Self {
        self.config.error_classifier = classifier;
        self
    }

    /// 构建熔断器
    pub fn build(&self) -> CircuitBreaker {
        CircuitBreaker::with_dependencies(self.config.clone())
    }
}

impl Default for CircuitBreakerBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl CircuitBreaker {
    /// 使用依赖注入模式创建熔断器
    ///
    /// # 参数
    /// - `config`: 熔断器配置
    ///
    /// # 返回
    /// 配置好的熔断器实例
    ///
    /// # 示例
    /// ```rust
    /// use limiteron::circuit::{CircuitBreaker, CircuitBreakerConfig};
    /// use std::time::Duration;
    ///
    /// let config = CircuitBreakerConfig::new(5, 2, Duration::from_secs(60));
    /// let breaker = CircuitBreaker::with_dependencies(config);
    /// ```
    pub fn with_dependencies(config: CircuitBreakerConfig) -> Self {
        Self::with_clock(config, Arc::new(SystemClock))
    }

    /// 使用依赖注入模式和自定义时钟创建熔断器
    ///
    /// # 参数
    /// - `config`: 熔断器配置
    /// - `clock`: 时钟实现,用于时间注入(测试用)
    pub fn with_clock(config: CircuitBreakerConfig, clock: Arc<dyn Clock>) -> Self {
        info!(
            "创建熔断器: failure_threshold={}, success_threshold={}, timeout={:?}",
            config.failure_threshold, config.success_threshold, config.timeout
        );

        Self {
            state: Arc::new(RwLock::new(CircuitState::Closed)),
            failure_count: Arc::new(AtomicU64::new(0)),
            success_count: Arc::new(AtomicU64::new(0)),
            total_calls: Arc::new(AtomicU64::new(0)),
            slow_call_count: Arc::new(AtomicU64::new(0)),
            last_failure_time: Arc::new(RwLock::new(None)),
            last_state_change: Arc::new(RwLock::new(Some(clock.now()))),
            half_open_calls: Arc::new(AtomicU64::new(0)),
            config,
            clock,
            #[cfg(feature = "event-system")]
            event_emitter: None,
        }
    }

    /// 创建熔断器构建器
    ///
    /// # 返回
    /// 新的构建器实例
    ///
    /// # 示例
    /// ```rust
    /// use limiteron::circuit::CircuitBreaker;
    ///
    /// let builder = CircuitBreaker::builder();
    /// ```
    pub fn builder() -> CircuitBreakerBuilder {
        CircuitBreakerBuilder::new()
    }

    /// 创建新的熔断器(保持向后兼容)
    ///
    /// # 参数
    /// - `config`: 熔断器配置
    ///
    /// # 示例
    /// ```rust
    /// use limiteron::circuit::{CircuitBreaker, CircuitBreakerConfig};
    /// use std::time::Duration;
    ///
    /// let config = CircuitBreakerConfig::new(5, 2, Duration::from_secs(60));
    /// let breaker = CircuitBreaker::new(config);
    /// ```
    pub fn new(config: CircuitBreakerConfig) -> Self {
        Self::with_dependencies(config)
    }
}

impl Default for CircuitBreaker {
    fn default() -> Self {
        Self::with_dependencies(CircuitBreakerConfig::default())
    }
}

impl CircuitBreaker {
    /// 执行操作,自动处理熔断逻辑
    ///
    /// # 参数
    /// - `operation`: 要执行的操作
    ///
    /// # 返回
    /// - `Ok(T)`: 操作成功
    /// - `Err(LimiteronError)`: 操作失败或熔断器打开
    ///
    /// # 示例
    /// ```rust
    /// use limiteron::circuit::{CircuitBreaker, CircuitBreakerConfig};
    /// use std::time::Duration;
    ///
    /// # #[tokio::main]
    /// # async fn main() {
    /// let config = CircuitBreakerConfig::new(5, 2, Duration::from_secs(60));
    /// let breaker = CircuitBreaker::new(config);
    ///
    /// let result = breaker.execute(|| async {
    ///     // 执行操作
    ///     Ok::<(), limiteron::error::LimiteronError>(())
    /// }).await;
    /// # }
    /// ```
    pub async fn execute<F, Fut, T>(&self, operation: F) -> Result<T, LimiteronError>
    where
        F: FnOnce() -> Fut,
        Fut: std::future::Future<Output = Result<T, LimiteronError>>,
    {
        // 增加总调用次数
        self.total_calls.fetch_add(1, Ordering::Relaxed);

        // 检查熔断器状态
        let state = self.state.read().await;

        match *state {
            CircuitState::Open => {
                // 检查是否可以尝试恢复
                let last_failure = self.last_failure_time.read().await;
                if let Some(last_failure) = *last_failure {
                    if self.clock.now().duration_since(last_failure) >= self.config.timeout {
                        // 超时,切换到半开状态
                        drop(state);
                        self.transition_to_half_open().await;
                    } else {
                        // 仍在熔断状态,拒绝请求
                        drop(state);
                        warn!("熔断器打开,拒绝请求");
                        return Err(LimiteronError::LimitError(
                            "熔断器打开,请求被拒绝".to_string(),
                        ));
                    }
                }
            }
            CircuitState::HalfOpen => {
                // 检查半开状态下的调用次数
                let calls = self.half_open_calls.load(Ordering::Relaxed);
                if calls >= self.config.half_open_max_calls {
                    drop(state);
                    warn!("半开状态调用次数已达上限,拒绝请求");
                    return Err(LimiteronError::LimitError(
                        "半开状态调用次数已达上限".to_string(),
                    ));
                }
                self.half_open_calls.fetch_add(1, Ordering::Relaxed);
                drop(state);
            }
            CircuitState::Closed => {
                // 正常状态,继续执行
                drop(state);
            }
        }

        // 执行操作
        let start_time = self.clock.now();
        let result = operation().await;
        let elapsed = start_time.elapsed();

        // 记录调用时长并检查是否为慢调用
        self.record_call_duration(elapsed).await;

        // 根据操作结果更新状态
        match result {
            Ok(value) => {
                self.on_success().await;
                Ok(value)
            }
            Err(e) => {
                self.on_failure(&e).await;
                Err(e)
            }
        }
    }

    /// 操作成功时的处理
    async fn on_success(&self) {
        let state = self.state.read().await;

        match *state {
            CircuitState::Closed => {
                // 关闭状态下,重置失败计数
                self.failure_count.store(0, Ordering::Relaxed);
                self.success_count.fetch_add(1, Ordering::Relaxed);
                trace!("操作成功(关闭状态)");
            }
            CircuitState::HalfOpen => {
                // 半开状态下,增加成功计数
                let success_count = self.success_count.fetch_add(1, Ordering::Relaxed) + 1;

                if success_count >= self.config.success_threshold {
                    // 达到成功阈值,切换到关闭状态
                    drop(state);
                    self.transition_to_closed().await;
                } else {
                    trace!(
                        "操作成功(半开状态): {}/{}",
                        success_count, self.config.success_threshold
                    );
                }
            }
            CircuitState::Open => {
                // 打开状态不应该执行到这里
                warn!("熔断器打开状态下收到成功响应");
            }
        }
    }

    /// 操作失败时的处理
    async fn on_failure(&self, error: &LimiteronError) {
        // 使用错误分类器判断是否应该计入失败计数
        if !self.config.error_classifier.is_counted_as_failure(error) {
            trace!("错误不计入失败计数: {:?}", error);
            return;
        }

        let state = self.state.read().await;

        match *state {
            CircuitState::Closed => {
                // 关闭状态下,增加失败计数
                let failure_count = self.failure_count.fetch_add(1, Ordering::Relaxed) + 1;

                // 记录失败时间
                *self.last_failure_time.write().await = Some(self.clock.now());

                if failure_count >= self.config.failure_threshold {
                    // 达到失败阈值,切换到打开状态
                    drop(state);
                    self.transition_to_open().await;
                } else {
                    trace!(
                        "操作失败(关闭状态): {}/{}",
                        failure_count, self.config.failure_threshold
                    );
                }
            }
            CircuitState::HalfOpen => {
                // 半开状态下失败,立即切换到打开状态
                drop(state);
                self.transition_to_open().await;
            }
            CircuitState::Open => {
                // 打开状态不应该执行到这里
                warn!("熔断器打开状态下收到失败响应");
            }
        }
    }

    /// 记录调用时长并检查是否为慢调用
    ///
    /// 如果调用时长超过慢调用阈值,则增加慢调用计数。
    /// 如果慢调用率超过阈值,则触发熔断。
    async fn record_call_duration(&self, elapsed: Duration) {
        if elapsed >= self.config.slow_call_duration_threshold {
            let slow_calls = self.slow_call_count.fetch_add(1, Ordering::Relaxed) + 1;
            let total_calls = self.total_calls.load(Ordering::Relaxed);

            trace!(
                "慢调用检测: elapsed={:?}, threshold={:?}, slow_calls={}/{}",
                elapsed, self.config.slow_call_duration_threshold, slow_calls, total_calls
            );

            // 检查慢调用率是否超过阈值
            self.check_slow_call_rate(slow_calls, total_calls).await;
        }
    }

    /// 检查慢调用率是否超过阈值
    async fn check_slow_call_rate(&self, slow_calls: u64, total_calls: u64) {
        if total_calls == 0 {
            return;
        }

        let slow_call_rate = slow_calls as f64 / total_calls as f64;

        if slow_call_rate >= self.config.slow_call_rate_threshold {
            let state = self.state.read().await;
            if *state == CircuitState::Closed {
                drop(state);
                warn!(
                    "慢调用率超过阈值: {:.2}% >= {:.2}%,触发熔断",
                    slow_call_rate * 100.0,
                    self.config.slow_call_rate_threshold * 100.0
                );
                self.transition_to_open().await;
            }
        }
    }

    /// 统一的状态转换方法
    ///
    /// 统一处理状态转换逻辑,避免重复的状态检查和日志记录代码。
    async fn transition_to(&self, new_state: CircuitState) {
        let old_state = *self.state.read().await;
        if old_state == new_state {
            return; // 状态未改变,无需处理
        }

        // 更新状态和时间戳
        *self.state.write().await = new_state;
        *self.last_state_change.write().await = Some(self.clock.now());

        // 根据新状态重置相关计数器
        match new_state {
            CircuitState::Open => {
                self.success_count.store(0, Ordering::Relaxed);
                self.half_open_calls.store(0, Ordering::Relaxed);
                warn!(
                    "熔断器状态变更: {:?} -> Open (failure_count={})",
                    old_state,
                    self.failure_count.load(Ordering::Relaxed)
                );
            }
            CircuitState::HalfOpen => {
                self.success_count.store(0, Ordering::Relaxed);
                // 重置半开状态调用计数
                // 注意:将计数设置为1,因为当前请求(探针请求)将被允许通过
                self.half_open_calls.store(1, Ordering::Relaxed);
                info!("熔断器状态变更: {:?} -> HalfOpen", old_state);
            }
            CircuitState::Closed => {
                self.failure_count.store(0, Ordering::Relaxed);
                self.success_count.store(0, Ordering::Relaxed);
                self.half_open_calls.store(0, Ordering::Relaxed);
                self.slow_call_count.store(0, Ordering::Relaxed);
                info!("熔断器状态变更: {:?} -> Closed", old_state);
            }
        }

        // 发射熔断器状态变更事件
        #[cfg(feature = "event-system")]
        {
            if let Some(ref emitter) = self.event_emitter {
                let old_state_str = format!("{:?}", old_state);
                let new_state_str = format!("{:?}", new_state);
                let event =
                    crate::events::Event::new(crate::events::EventType::CircuitStateChanged {
                        from: old_state_str,
                        to: new_state_str,
                    });
                if let Err(e) = emitter.emit(event).await {
                    log::error!("Failed to emit circuit state change event: {}", e);
                }
            }
        }
    }

    /// 切换到打开状态
    async fn transition_to_open(&self) {
        self.transition_to(CircuitState::Open).await;
    }

    /// 切换到半开状态
    async fn transition_to_half_open(&self) {
        self.transition_to(CircuitState::HalfOpen).await;
    }

    /// 切换到关闭状态
    async fn transition_to_closed(&self) {
        self.transition_to(CircuitState::Closed).await;
    }

    /// 检查熔断器是否为指定状态(内部辅助方法)
    ///
    /// 统一的状态检查逻辑,避免重复的状态读取代码。
    async fn is_state(&self, target_state: CircuitState) -> bool {
        let state = self.state.read().await;
        *state == target_state
    }

    /// 检查熔断器是否打开
    pub async fn is_open(&self) -> bool {
        self.is_state(CircuitState::Open).await
    }

    /// 检查熔断器是否半开
    pub async fn is_half_open(&self) -> bool {
        self.is_state(CircuitState::HalfOpen).await
    }

    /// 检查熔断器是否关闭
    pub async fn is_closed(&self) -> bool {
        self.is_state(CircuitState::Closed).await
    }

    /// 获取当前状态
    pub async fn get_state(&self) -> CircuitState {
        *self.state.read().await
    }

    /// 重置熔断器到关闭状态
    pub async fn reset(&self) {
        info!("重置熔断器");
        *self.state.write().await = CircuitState::Closed;
        self.failure_count.store(0, Ordering::Relaxed);
        self.success_count.store(0, Ordering::Relaxed);
        self.total_calls.store(0, Ordering::Relaxed);
        self.slow_call_count.store(0, Ordering::Relaxed);
        *self.last_failure_time.write().await = None;
        *self.last_state_change.write().await = Some(self.clock.now());
        self.half_open_calls.store(0, Ordering::Relaxed);
    }

    /// 获取统计信息
    pub async fn get_stats(&self) -> CircuitBreakerStats {
        let state = *self.state.read().await;
        let last_failure = self.last_failure_time.read().await;
        let last_state_change = self.last_state_change.read().await;

        CircuitBreakerStats {
            state,
            failure_count: self.failure_count.load(Ordering::Relaxed),
            success_count: self.success_count.load(Ordering::Relaxed),
            total_calls: self.total_calls.load(Ordering::Relaxed),
            last_failure_time: last_failure.and_then(|t| {
                let elapsed = self.clock.now().duration_since(t);
                let duration = chrono::Duration::from_std(elapsed).ok()?;
                Some(chrono::Utc::now() - duration)
            }),
            last_state_change: last_state_change.and_then(|t| {
                let elapsed = self.clock.now().duration_since(t);
                let duration = chrono::Duration::from_std(elapsed).ok()?;
                Some(chrono::Utc::now() - duration)
            }),
        }
    }

    /// 获取配置
    pub fn config(&self) -> &CircuitBreakerConfig {
        &self.config
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_circuit_breaker_config_default() {
        let config = CircuitBreakerConfig::default();
        assert_eq!(config.failure_threshold, 5);
        assert_eq!(config.success_threshold, 3);
        assert_eq!(config.timeout, Duration::from_secs(30));
        assert_eq!(config.half_open_max_calls, 3);
    }

    #[test]
    fn test_circuit_breaker_config_new() {
        let config = CircuitBreakerConfig::new(10, 3, Duration::from_secs(120));
        assert_eq!(config.failure_threshold, 10);
        assert_eq!(config.success_threshold, 3);
        assert_eq!(config.timeout, Duration::from_secs(120));
    }

    #[test]
    fn test_circuit_breaker_config_builder() {
        let config =
            CircuitBreakerConfig::new(5, 2, Duration::from_secs(60)).half_open_max_calls(5);
        assert_eq!(config.half_open_max_calls, 5);
    }

    #[tokio::test]
    async fn test_circuit_breaker_initial_state() {
        let breaker = CircuitBreaker::default();
        assert!(breaker.is_closed().await);
        assert!(!breaker.is_open().await);
        assert!(!breaker.is_half_open().await);

        let stats = breaker.get_stats().await;
        assert_eq!(stats.state, CircuitState::Closed);
        assert_eq!(stats.failure_count, 0);
        assert_eq!(stats.success_count, 0);
        assert_eq!(stats.total_calls, 0);
    }

    #[tokio::test]
    async fn test_circuit_breaker_success() {
        let breaker = CircuitBreaker::default();

        let result = breaker
            .execute(|| async { Ok::<(), LimiteronError>(()) })
            .await;
        assert!(result.is_ok());

        let stats = breaker.get_stats().await;
        assert_eq!(stats.success_count, 1);
        assert_eq!(stats.failure_count, 0);
        assert_eq!(stats.total_calls, 1);
        assert!(breaker.is_closed().await);
    }

    #[tokio::test]
    async fn test_circuit_breaker_failure() {
        let config = CircuitBreakerConfig::new(3, 2, Duration::from_secs(60));
        let breaker = CircuitBreaker::new(config);

        // 第一次失败
        let result = breaker
            .execute(|| async {
                Err::<(), LimiteronError>(LimiteronError::BanError("test error".to_string()))
            })
            .await;
        assert!(result.is_err());

        let stats = breaker.get_stats().await;
        assert_eq!(stats.failure_count, 1);
        assert!(breaker.is_closed().await);

        // 第二次失败
        let result = breaker
            .execute(|| async {
                Err::<(), LimiteronError>(LimiteronError::BanError("test error".to_string()))
            })
            .await;
        assert!(result.is_err());

        let stats = breaker.get_stats().await;
        assert_eq!(stats.failure_count, 2);
        assert!(breaker.is_closed().await);

        // 第三次失败,应该触发熔断
        let result = breaker
            .execute(|| async {
                Err::<(), LimiteronError>(LimiteronError::BanError("test error".to_string()))
            })
            .await;
        assert!(result.is_err());

        let stats = breaker.get_stats().await;
        assert_eq!(stats.failure_count, 3);
        assert!(breaker.is_open().await);
    }

    #[tokio::test]
    async fn test_circuit_breaker_open_rejects_requests() {
        let config = CircuitBreakerConfig::new(2, 2, Duration::from_secs(60));
        let breaker = CircuitBreaker::new(config);

        // 触发熔断
        for _ in 0..2 {
            let _ = breaker
                .execute(|| async {
                    Err::<(), LimiteronError>(LimiteronError::BanError("test error".to_string()))
                })
                .await;
        }

        assert!(breaker.is_open().await);

        // 熔断器打开,请求应该被拒绝
        let result = breaker
            .execute(|| async { Ok::<(), LimiteronError>(()) })
            .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("熔断器打开"));
    }

    #[tokio::test]
    async fn test_circuit_breaker_half_open_recovery() {
        let config = CircuitBreakerConfig::new(2, 2, Duration::from_millis(100));
        let breaker = CircuitBreaker::new(config);

        // 触发熔断
        for _ in 0..2 {
            let _ = breaker
                .execute(|| async {
                    Err::<(), LimiteronError>(LimiteronError::BanError("test error".to_string()))
                })
                .await;
        }

        assert!(breaker.is_open().await);

        // 等待超时
        tokio::time::sleep(Duration::from_millis(150)).await;

        // 第一次成功,进入半开状态
        let result = breaker
            .execute(|| async { Ok::<(), LimiteronError>(()) })
            .await;
        assert!(result.is_ok());
        assert!(breaker.is_half_open().await);

        // 第二次成功,应该恢复到关闭状态
        let result = breaker
            .execute(|| async { Ok::<(), LimiteronError>(()) })
            .await;
        assert!(result.is_ok());
        assert!(breaker.is_closed().await);
    }

    #[tokio::test]
    async fn test_circuit_breaker_half_open_failure() {
        let config = CircuitBreakerConfig::new(2, 2, Duration::from_millis(100));
        let breaker = CircuitBreaker::new(config);

        // 触发熔断
        for _ in 0..2 {
            let _ = breaker
                .execute(|| async {
                    Err::<(), LimiteronError>(LimiteronError::BanError("test error".to_string()))
                })
                .await;
        }

        assert!(breaker.is_open().await);

        // 等待超时
        tokio::time::sleep(Duration::from_millis(150)).await;

        // 第一次成功,进入半开状态
        let result = breaker
            .execute(|| async { Ok::<(), LimiteronError>(()) })
            .await;
        assert!(result.is_ok());
        assert!(breaker.is_half_open().await);

        // 再次失败,应该回到打开状态
        let result = breaker
            .execute(|| async {
                Err::<(), LimiteronError>(LimiteronError::BanError("test error".to_string()))
            })
            .await;
        assert!(result.is_err());
        assert!(breaker.is_open().await);
    }

    #[tokio::test]
    async fn test_circuit_breaker_reset() {
        let config = CircuitBreakerConfig::new(2, 2, Duration::from_secs(60));
        let breaker = CircuitBreaker::new(config);

        // 触发熔断
        for _ in 0..2 {
            let _ = breaker
                .execute(|| async {
                    Err::<(), LimiteronError>(LimiteronError::BanError("test error".to_string()))
                })
                .await;
        }

        assert!(breaker.is_open().await);

        // 重置
        breaker.reset().await;

        // 验证重置
        assert!(breaker.is_closed().await);
        let stats = breaker.get_stats().await;
        assert_eq!(stats.failure_count, 0);
        assert_eq!(stats.success_count, 0);
        assert_eq!(stats.total_calls, 0);
    }

    #[tokio::test]
    async fn test_circuit_breaker_get_state() {
        let breaker = CircuitBreaker::default();
        assert_eq!(breaker.get_state().await, CircuitState::Closed);
    }

    #[tokio::test]
    async fn test_circuit_breaker_get_stats() {
        let breaker = CircuitBreaker::default();

        let _ = breaker
            .execute(|| async { Ok::<(), LimiteronError>(()) })
            .await;

        let stats = breaker.get_stats().await;
        assert_eq!(stats.state, CircuitState::Closed);
        assert_eq!(stats.success_count, 1);
        assert_eq!(stats.total_calls, 1);
        assert!(stats.last_state_change.is_some());
    }

    #[tokio::test]
    async fn test_circuit_breaker_half_open_max_calls() {
        let config =
            CircuitBreakerConfig::new(2, 3, Duration::from_millis(100)).half_open_max_calls(2);
        let breaker = CircuitBreaker::new(config);

        // 触发熔断
        for _ in 0..2 {
            let _ = breaker
                .execute(|| async {
                    Err::<(), LimiteronError>(LimiteronError::BanError("test error".to_string()))
                })
                .await;
        }

        assert!(breaker.is_open().await);

        // 等待超时
        tokio::time::sleep(Duration::from_millis(150)).await;

        // 第一次调用,进入半开状态
        let result = breaker
            .execute(|| async { Ok::<(), LimiteronError>(()) })
            .await;
        assert!(result.is_ok());

        // 第二次调用,达到上限
        let result = breaker
            .execute(|| async { Ok::<(), LimiteronError>(()) })
            .await;
        assert!(result.is_ok());

        // 第三次调用,应该被拒绝
        let result = breaker
            .execute(|| async { Ok::<(), LimiteronError>(()) })
            .await;
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("半开状态调用次数已达上限")
        );
    }

    #[tokio::test]
    async fn test_circuit_breaker_config() {
        let config = CircuitBreakerConfig::new(10, 5, Duration::from_secs(30));
        let breaker = CircuitBreaker::new(config);

        let breaker_config = breaker.config();
        assert_eq!(breaker_config.failure_threshold, 10);
        assert_eq!(breaker_config.success_threshold, 5);
        assert_eq!(breaker_config.timeout, Duration::from_secs(30));
    }

    // ==================== 增强的状态转换测试 ====================

    /// 测试 Closed → Open 转换
    #[tokio::test]
    async fn test_state_transition_closed_to_open() {
        let config = CircuitBreakerConfig::new(3, 2, Duration::from_secs(60));
        let breaker = CircuitBreaker::new(config);

        // 初始状态应为 Closed
        assert!(breaker.is_closed().await, "初始状态应为 Closed");
        assert_eq!(breaker.get_state().await, CircuitState::Closed);

        // 第一次失败
        let result = breaker
            .execute(|| async {
                Err::<(), LimiteronError>(LimiteronError::BanError("error 1".to_string()))
            })
            .await;
        assert!(result.is_err());
        assert!(breaker.is_closed().await, "第一次失败后仍应为 Closed");

        // 第二次失败
        let result = breaker
            .execute(|| async {
                Err::<(), LimiteronError>(LimiteronError::BanError("error 2".to_string()))
            })
            .await;
        assert!(result.is_err());
        assert!(breaker.is_closed().await, "第二次失败后仍应为 Closed");

        // 第三次失败,应触发熔断
        let result = breaker
            .execute(|| async {
                Err::<(), LimiteronError>(LimiteronError::BanError("error 3".to_string()))
            })
            .await;
        assert!(result.is_err());
        assert!(breaker.is_open().await, "第三次失败后应转换为 Open");
        assert_eq!(breaker.get_state().await, CircuitState::Open);
    }

    /// 测试 Open → HalfOpen 转换
    #[tokio::test]
    async fn test_state_transition_open_to_half_open() {
        let config = CircuitBreakerConfig::new(2, 2, Duration::from_millis(100));
        let breaker = CircuitBreaker::new(config);

        // 触发熔断
        for i in 0..2 {
            let _ = breaker
                .execute(|| async {
                    Err::<(), LimiteronError>(LimiteronError::BanError(format!("error {}", i)))
                })
                .await;
        }
        assert!(breaker.is_open().await, "应处于 Open 状态");

        // 未超时时请求应被拒绝
        let result = breaker
            .execute(|| async { Ok::<(), LimiteronError>(()) })
            .await;
        assert!(result.is_err());
        assert!(breaker.is_open().await, "未超时应保持 Open 状态");

        // 等待超时
        tokio::time::sleep(Duration::from_millis(150)).await;

        // 超时后第一次请求应进入 HalfOpen 状态
        let result = breaker
            .execute(|| async { Ok::<(), LimiteronError>(()) })
            .await;
        assert!(result.is_ok());
        assert!(breaker.is_half_open().await, "超时后应转换为 HalfOpen 状态");
    }

    /// 测试 HalfOpen → Closed 转换
    #[tokio::test]
    async fn test_state_transition_half_open_to_closed() {
        let config = CircuitBreakerConfig::new(2, 2, Duration::from_millis(100));
        let breaker = CircuitBreaker::new(config);

        // 触发熔断
        for _ in 0..2 {
            let _ = breaker
                .execute(|| async {
                    Err::<(), LimiteronError>(LimiteronError::BanError("error".to_string()))
                })
                .await;
        }
        assert!(breaker.is_open().await);

        // 等待超时进入半开状态
        tokio::time::sleep(Duration::from_millis(150)).await;

        // 第一次成功,进入半开状态
        let result = breaker
            .execute(|| async { Ok::<(), LimiteronError>(()) })
            .await;
        assert!(result.is_ok());
        assert!(breaker.is_half_open().await);

        // 第二次成功,应恢复到 Closed 状态
        let result = breaker
            .execute(|| async { Ok::<(), LimiteronError>(()) })
            .await;
        assert!(result.is_ok());
        assert!(
            breaker.is_closed().await,
            "成功次数达到阈值后应恢复到 Closed 状态"
        );
    }

    /// 测试完整的状态转换循环: Closed → Open → HalfOpen → Closed
    #[tokio::test]
    async fn test_state_transition_full_cycle() {
        let config = CircuitBreakerConfig::new(2, 2, Duration::from_millis(100));
        let breaker = CircuitBreaker::new(config);

        // 阶段1: Closed → Open
        for _ in 0..2 {
            let _ = breaker
                .execute(|| async {
                    Err::<(), LimiteronError>(LimiteronError::BanError("error".to_string()))
                })
                .await;
        }
        assert!(breaker.is_open().await, "阶段1: 应处于 Open 状态");

        // 阶段2: Open → HalfOpen
        tokio::time::sleep(Duration::from_millis(150)).await;
        let result = breaker
            .execute(|| async { Ok::<(), LimiteronError>(()) })
            .await;
        assert!(result.is_ok());
        assert!(breaker.is_half_open().await, "阶段2: 应处于 HalfOpen 状态");

        // 阶段3: HalfOpen → Closed
        let result = breaker
            .execute(|| async { Ok::<(), LimiteronError>(()) })
            .await;
        assert!(result.is_ok());
        assert!(breaker.is_closed().await, "阶段3: 应恢复到 Closed 状态");
    }

    /// 测试 Builder 模式
    #[tokio::test]
    async fn test_builder_pattern() {
        let breaker = CircuitBreaker::builder()
            .failure_threshold(10)
            .success_threshold(5)
            .timeout(Duration::from_secs(30))
            .half_open_max_calls(4)
            .build();

        let config = breaker.config();
        assert_eq!(config.failure_threshold, 10);
        assert_eq!(config.success_threshold, 5);
        assert_eq!(config.timeout, Duration::from_secs(30));
        assert_eq!(config.half_open_max_calls, 4);

        // 验证初始状态
        assert!(breaker.is_closed().await);
    }

    // ==================== 慢调用检测测试 ====================

    /// 测试慢调用时长阈值配置
    #[tokio::test]
    async fn test_slow_call_duration_threshold_config() {
        let config = CircuitBreakerConfig::default()
            .slow_call_duration_threshold(Duration::from_millis(100));
        assert_eq!(
            config.slow_call_duration_threshold,
            Duration::from_millis(100)
        );
    }

    /// 测试慢调用率阈值配置
    #[tokio::test]
    async fn test_slow_call_rate_threshold_config() {
        let config = CircuitBreakerConfig::default().slow_call_rate_threshold(0.8);
        assert_eq!(config.slow_call_rate_threshold, 0.8);
    }

    /// 测试默认错误分类器 - StorageError 超时算失败
    #[test]
    fn test_default_error_classifier_storage_timeout() {
        let classifier = DefaultErrorClassifier;
        let error = LimiteronError::StorageError(crate::error::StorageError::TimeoutError(
            "timeout".into(),
        ));
        assert!(classifier.is_counted_as_failure(&error));
    }

    /// 测试默认错误分类器 - StorageError 连接错误算失败
    #[test]
    fn test_default_error_classifier_connection_error() {
        let classifier = DefaultErrorClassifier;
        let error = LimiteronError::StorageError(crate::error::StorageError::ConnectionError(
            "connection".into(),
        ));
        assert!(classifier.is_counted_as_failure(&error));
    }

    /// 测试默认错误分类器 - LimitError 不算失败
    #[test]
    fn test_default_error_classifier_limit_error() {
        let classifier = DefaultErrorClassifier;
        let error = LimiteronError::LimitError("rate limited".into());
        assert!(!classifier.is_counted_as_failure(&error));
    }

    /// 测试默认错误分类器 - ValidationError 不算失败
    #[test]
    fn test_default_error_classifier_validation_error() {
        let classifier = DefaultErrorClassifier;
        let error = LimiteronError::ValidationError("invalid input".into());
        assert!(!classifier.is_counted_as_failure(&error));
    }

    /// 测试默认错误分类器 - CircuitBreakerError 不算失败
    #[test]
    fn test_default_error_classifier_circuit_breaker_error() {
        let classifier = DefaultErrorClassifier;
        let error = LimiteronError::CircuitBreakerError("circuit open".into());
        assert!(!classifier.is_counted_as_failure(&error));
    }

    /// 测试默认错误分类器 - 其他错误算失败
    #[test]
    fn test_default_error_classifier_other_errors() {
        let classifier = DefaultErrorClassifier;
        let error = LimiteronError::Other("unknown error".into());
        assert!(classifier.is_counted_as_failure(&error));
    }

    /// 测试自定义错误分类器
    #[tokio::test]
    async fn test_custom_error_classifier() {
        #[derive(Debug)]
        struct CustomClassifier;
        impl ErrorClassifier for CustomClassifier {
            fn is_counted_as_failure(&self, error: &LimiteronError) -> bool {
                // 只有 StorageError 算失败
                matches!(error, LimiteronError::StorageError(_))
            }
        }

        let config = CircuitBreakerConfig {
            error_classifier: Arc::new(CustomClassifier),
            failure_threshold: 2,
            ..Default::default()
        };

        let breaker = CircuitBreaker::new(config);

        // ValidationError 不应触发失败计数
        let _ = breaker
            .execute(|| async {
                Err::<(), LimiteronError>(LimiteronError::ValidationError("test".into()))
            })
            .await;

        let stats = breaker.get_stats().await;
        assert_eq!(stats.failure_count, 0);

        // StorageError 应该触发失败计数
        let _ = breaker
            .execute(|| async {
                Err::<(), LimiteronError>(LimiteronError::StorageError(
                    crate::error::StorageError::TimeoutError("timeout".into()),
                ))
            })
            .await;

        let stats = breaker.get_stats().await;
        assert_eq!(stats.failure_count, 1);
    }

    /// 测试 Builder 模式设置慢调用配置
    #[tokio::test]
    async fn test_builder_with_slow_call_config() {
        let breaker = CircuitBreaker::builder()
            .slow_call_duration_threshold(Duration::from_millis(200))
            .slow_call_rate_threshold(0.6)
            .build();

        let config = breaker.config();
        assert_eq!(
            config.slow_call_duration_threshold,
            Duration::from_millis(200)
        );
        assert_eq!(config.slow_call_rate_threshold, 0.6);
    }

    #[test]
    fn test_circuit_breaker_builder_default() {
        let builder = CircuitBreakerBuilder::default();
        assert_eq!(builder.config.failure_threshold, 5);
        assert_eq!(builder.config.success_threshold, 3);
    }

    #[test]
    fn test_config_error_classifier_builder() {
        let classifier: Arc<dyn ErrorClassifier> = Arc::new(DefaultErrorClassifier);
        let config = CircuitBreakerConfig::default().error_classifier(classifier);
        // Just verify it doesn't panic and config is accessible
        assert_eq!(config.failure_threshold, 5);
    }

    #[test]
    fn test_config_all_builder_methods() {
        let classifier: Arc<dyn ErrorClassifier> = Arc::new(DefaultErrorClassifier);
        let config = CircuitBreakerConfig::new(10, 5, Duration::from_secs(30))
            .half_open_max_calls(4)
            .slow_call_duration_threshold(Duration::from_millis(100))
            .slow_call_rate_threshold(0.7)
            .error_classifier(classifier);
        assert_eq!(config.failure_threshold, 10);
        assert_eq!(config.success_threshold, 5);
        assert_eq!(config.half_open_max_calls, 4);
        assert_eq!(
            config.slow_call_duration_threshold,
            Duration::from_millis(100)
        );
        assert!((config.slow_call_rate_threshold - 0.7).abs() < f64::EPSILON);
    }

    #[tokio::test]
    async fn test_slow_call_rate_triggers_open() {
        // Every call is "slow" (threshold=0) and rate threshold is 0.5
        // After 1 call: slow=1/total=1 = 1.0 >= 0.5 -> should open
        let config = CircuitBreakerConfig {
            slow_call_duration_threshold: Duration::ZERO,
            slow_call_rate_threshold: 0.5,
            failure_threshold: 100,
            ..Default::default()
        };
        let breaker = CircuitBreaker::new(config);

        let _ = breaker
            .execute(|| async { Ok::<(), LimiteronError>(()) })
            .await;

        assert!(
            breaker.is_open().await,
            "Slow call rate should trigger Open state"
        );
    }

    #[tokio::test]
    async fn test_slow_call_rate_below_threshold_stays_closed() {
        // threshold is very high so no calls are "slow"
        let config = CircuitBreakerConfig {
            slow_call_duration_threshold: Duration::from_secs(60),
            slow_call_rate_threshold: 0.5,
            ..Default::default()
        };
        let breaker = CircuitBreaker::new(config);

        for _ in 0..5 {
            let _ = breaker
                .execute(|| async { Ok::<(), LimiteronError>(()) })
                .await;
        }

        assert!(breaker.is_closed().await);
    }

    #[tokio::test]
    async fn test_on_success_in_open_state_logs_warning() {
        // Force breaker into Open state, then call on_success path
        let config = CircuitBreakerConfig::new(1, 1, Duration::from_secs(60));
        let breaker = CircuitBreaker::new(config);

        // Trigger open
        let _ = breaker
            .execute(|| async { Err::<(), LimiteronError>(LimiteronError::BanError("e".into())) })
            .await;
        assert!(breaker.is_open().await);

        // Next call should be rejected (still open, not timed out)
        let result = breaker
            .execute(|| async { Ok::<(), LimiteronError>(()) })
            .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_circuit_breaker_with_clock() {
        use crate::clock::MockClock;
        let mock_clock = Arc::new(MockClock::new());
        let clock: Arc<dyn Clock> = mock_clock.clone();
        let config = CircuitBreakerConfig::new(2, 2, Duration::from_secs(60));
        let breaker = CircuitBreaker::with_clock(config, clock);

        assert!(breaker.is_closed().await);
        let stats = breaker.get_stats().await;
        assert_eq!(stats.state, CircuitState::Closed);
    }

    #[tokio::test]
    async fn test_circuit_breaker_builder_error_classifier() {
        let classifier: Arc<dyn ErrorClassifier> = Arc::new(DefaultErrorClassifier);
        let breaker = CircuitBreaker::builder()
            .failure_threshold(3)
            .error_classifier(classifier)
            .build();
        assert_eq!(breaker.config().failure_threshold, 3);
    }

    #[tokio::test]
    async fn test_get_stats_after_failure() {
        let config = CircuitBreakerConfig::new(5, 2, Duration::from_secs(60));
        let breaker = CircuitBreaker::new(config);

        let _ = breaker
            .execute(|| async { Err::<(), LimiteronError>(LimiteronError::BanError("e".into())) })
            .await;

        let stats = breaker.get_stats().await;
        assert_eq!(stats.failure_count, 1);
        assert_eq!(stats.total_calls, 1);
        assert!(stats.last_failure_time.is_some());
    }

    #[test]
    fn test_default_error_classifier_storage_not_transient() {
        let classifier = DefaultErrorClassifier;
        // NotFound is NOT transient, so it should NOT be counted as failure
        let error = LimiteronError::StorageError(crate::error::StorageError::NotFound("nf".into()));
        assert!(!classifier.is_counted_as_failure(&error));
    }

    /// 测试在 Open 状态下调用 on_failure
    /// 覆盖 on_failure 内 CircuitState::Open 分支(line 500, 502)
    #[tokio::test]
    async fn test_on_failure_when_open() {
        let config = CircuitBreakerConfig::new(2, 2, Duration::from_secs(60));
        let breaker = CircuitBreaker::new(config);

        // 触发熔断,进入 Open 状态
        for _ in 0..2 {
            let _ = breaker
                .execute(|| async {
                    Err::<(), LimiteronError>(LimiteronError::BanError("e".to_string()))
                })
                .await;
        }
        assert!(breaker.is_open().await);

        // 直接调用 on_failure,覆盖 Open 分支
        // 此时状态为 Open,on_failure 内的 Open 分支会打印 warn 但不做状态转换
        let error = LimiteronError::BanError("open-state failure".to_string());
        breaker.on_failure(&error).await;

        // 状态应仍为 Open
        assert!(breaker.is_open().await);
    }
}