limiteron 0.3.0-rc.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
// Copyright (c) 2026 Kirky.X
// SPDX-License-Identifier: MIT
//! 规则构建器模块
//!
//! 提供从配置构建规则和决策链的功能,将规则构建逻辑从 Governor 中分离出来。
//!
//! # 功能
//!
//! - 从 FlowControlConfig 构建规则列表
//! - 从 FlowControlConfig 构建决策链映射
//! - 时长字符串解析

use crate::config::{FlowControlConfig, LimiterConfig, LimiterTypeName, Matcher as ConfigMatcher};
use crate::decision_chain::{DecisionChain, DecisionNode};
use crate::error::LimiteronError;
#[cfg(feature = "quota-control")]
use crate::limiters::QuotaLimiter;
use crate::limiters::{
    ConcurrencyLimiter, FixedWindowLimiter, Limiter, ShardedSlidingWindowLimiter,
    TokenBucketLimiter,
};
use crate::matchers::{
    CompositeCondition, ConditionEvaluator, IpRange, LogicalOperator, MatchCondition,
    Rule as MatcherRule,
};
use dashmap::DashMap;
use log::warn;
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;

/// 规则构建器
///
/// 负责从配置构建规则列表和决策链。
///
/// # 示例
///
/// ```rust
/// use limiteron::RuleBuilder;
/// use limiteron::config::FlowControlConfig;
///
/// let config = FlowControlConfig::default();
/// let rules = RuleBuilder::build_rules(&config).unwrap();
/// let chains = RuleBuilder::build_rule_chains(&config).unwrap();
/// ```
pub struct RuleBuilder;

impl RuleBuilder {
    /// 解析时长字符串
    ///
    /// 支持以下格式:
    /// - `ms` 后缀:毫秒
    /// - `s` 后缀:秒
    /// - `m` 后缀:分钟
    /// - `h` 后缀:小时
    ///
    /// # 参数
    ///
    /// - `s`: 时长字符串
    ///
    /// # 返回
    ///
    /// - `Ok(Duration)`: 解析成功
    /// - `Err(LimiteronError)`: 解析失败
    ///
    /// # 示例
    ///
    /// ```rust
    /// use limiteron::RuleBuilder;
    /// use std::time::Duration;
    ///
    /// assert_eq!(RuleBuilder::parse_duration("100ms").unwrap(), Duration::from_millis(100));
    /// assert_eq!(RuleBuilder::parse_duration("10s").unwrap(), Duration::from_secs(10));
    /// assert_eq!(RuleBuilder::parse_duration("5m").unwrap(), Duration::from_secs(300));
    /// assert_eq!(RuleBuilder::parse_duration("2h").unwrap(), Duration::from_secs(7200));
    /// ```
    pub fn parse_duration(s: &str) -> Result<Duration, LimiteronError> {
        crate::config::parse_window_size(s).map_err(LimiteronError::ConfigError)
    }

    /// 从配置构建规则对应的决策链
    ///
    /// # 参数
    ///
    /// - `config`: 流量控制配置
    ///
    /// # 返回
    ///
    /// - `Ok(DashMap<String, DecisionChain>)`: 决策链映射(规则ID -> 决策链)
    /// - `Err(LimiteronError)`: 构建失败
    ///
    /// # 示例
    ///
    /// ```rust
    /// use limiteron::RuleBuilder;
    /// use limiteron::config::FlowControlConfig;
    ///
    /// let config = FlowControlConfig::default();
    /// let chains = RuleBuilder::build_rule_chains(&config).unwrap();
    /// ```
    pub fn build_rule_chains(
        config: &FlowControlConfig,
    ) -> Result<DashMap<String, DecisionChain>, LimiteronError> {
        let chains = DashMap::new();

        for rule in &config.rules {
            let mut nodes: Vec<DecisionNode> = Vec::new();

            for (index, limiter_config) in rule.limiters.iter().enumerate() {
                let (limiter, type_name): (Arc<dyn Limiter>, LimiterTypeName) = match limiter_config
                {
                    LimiterConfig::TokenBucket {
                        capacity,
                        refill_rate,
                    } => (
                        Arc::new(TokenBucketLimiter::new(*capacity, *refill_rate)),
                        LimiterTypeName::TokenBucket,
                    ),
                    LimiterConfig::SlidingWindow {
                        window_size,
                        max_requests,
                    } => {
                        let duration = Self::parse_duration(window_size)?;
                        (
                            Arc::new(ShardedSlidingWindowLimiter::new(duration, *max_requests)),
                            LimiterTypeName::SlidingWindow,
                        )
                    }
                    LimiterConfig::FixedWindow {
                        window_size,
                        max_requests,
                    } => {
                        let duration = Self::parse_duration(window_size)?;
                        (
                            Arc::new(FixedWindowLimiter::new(duration, *max_requests)),
                            LimiterTypeName::FixedWindow,
                        )
                    }
                    LimiterConfig::Quota {
                        quota_type: _quota_type,
                        limit: _limit,
                        window: _window,
                        alert_threshold: _,
                        overdraft: _overdraft,
                    } => {
                        // quota-control 特性开启时真实挂载配额限流器(不再静默跳过;
                        // diting MED-004 修复)。链式场景经 QuotaLimiter 的匿名桶生效。
                        #[cfg(feature = "quota-control")]
                        {
                            let window_secs = Self::parse_duration(_window)?.as_secs().max(1);
                            let limit_val: u64 = *_limit;
                            // 配置侧 overdraft 为 {enabled, max_overdraft};
                            // 按"透支量/配额上限"映射为百分比后接入 QuotaConfig
                            let overdraft_percent: u8 = _overdraft
                                .as_ref()
                                .filter(|o| o.enabled)
                                .map(|o| {
                                    let percent = o
                                        .max_overdraft
                                        .saturating_mul(100)
                                        .checked_div(limit_val.max(1))
                                        .unwrap_or(0);
                                    percent.min(100) as u8
                                })
                                .unwrap_or(0);
                            let config = crate::quota::QuotaConfig {
                                quota_type: *_quota_type,
                                limit: limit_val,
                                window_size: window_secs,
                                allow_overdraft: _overdraft.as_ref().is_some_and(|o| o.enabled),
                                overdraft_limit_percent: overdraft_percent,
                                ..crate::quota::QuotaConfig::default()
                            };
                            (Arc::new(QuotaLimiter::new(config)), LimiterTypeName::Quota)
                        }
                        #[cfg(not(feature = "quota-control"))]
                        {
                            warn!(
                                "QuotaLimiter requires 'quota-control' feature to be enabled, \
                                 skipping Quota configuration"
                            );
                            continue;
                        }
                    }
                    LimiterConfig::Concurrency { max_concurrent } => {
                        // diting HIGH-002 修复后:链式 allow() 以「租约」真实计入并发占用
                        //(LEASE_DURATION 内持有 permit,近似请求生命周期)。
                        // 精确的请求级并发控制仍推荐服务层直接使用 acquire()/guard。
                        (
                            Arc::new(ConcurrencyLimiter::new(*max_concurrent)),
                            LimiterTypeName::Concurrency,
                        )
                    }
                    LimiterConfig::Custom { name, config: _ } => {
                        // CustomLimiter integration requires custom-limiter feature and
                        // manual registration via CustomLimiterRegistry
                        #[cfg(feature = "custom-limiter")]
                        warn!(
                            "CustomLimiter '{}' requires registration via CustomLimiterRegistry, skipping",
                            name
                        );
                        #[cfg(not(feature = "custom-limiter"))]
                        warn!(
                            "CustomLimiter '{}' skipped - custom-limiter feature not enabled",
                            name
                        );
                        continue;
                    }
                };

                let node = DecisionNode::with_dependencies(
                    format!("{}_limiter_{}", rule.id, index),
                    format!("{} - {}", rule.name, type_name),
                    limiter,
                    100u16.saturating_sub(index as u16), // Priority: earlier limiters have higher priority
                );
                nodes.push(node);
            }

            chains.insert(rule.id.clone(), DecisionChain::with_dependencies(nodes));
        }

        Ok(chains)
    }

    /// 从配置构建规则列表
    ///
    /// # 参数
    ///
    /// - `config`: 流量控制配置
    ///
    /// # 返回
    ///
    /// - `Ok(Vec<MatcherRule>)`: 规则列表
    /// - `Err(LimiteronError)`: 构建失败
    ///
    /// # 示例
    ///
    /// ```rust
    /// use limiteron::RuleBuilder;
    /// use limiteron::config::FlowControlConfig;
    ///
    /// let config = FlowControlConfig::default();
    /// let rules = RuleBuilder::build_rules(&config).unwrap();
    /// ```
    pub fn build_rules(config: &FlowControlConfig) -> Result<Vec<MatcherRule>, LimiteronError> {
        let mut rules = Vec::new();

        for rule_config in &config.rules {
            let mut conditions: Vec<Box<dyn ConditionEvaluator>> = Vec::new();

            for matcher in &rule_config.matchers {
                if let Some(condition) = base_condition(matcher)? {
                    conditions.push(condition);
                    continue;
                }
                // Custom 匹配器:未提供注册表的构建路径编译为恒不匹配
                // 占位(E1 可见性修复:构建期 warn 一次,热路径降 debug)
                let ConfigMatcher::Custom { name, .. } = matcher else {
                    unreachable!("base_condition 仅对 Custom 返回 None");
                };
                log::warn!(
                    "自定义匹配器 '{}' 未集成 CustomMatcherRegistry,该规则将恒不匹配(其限制不会生效)",
                    name
                );
                let name = name.clone();
                conditions.push(Box::new(MatchCondition::Custom(Arc::new(
                    move |_context| {
                        log::debug!("自定义匹配器 '{}' 为占位实现,恒不匹配", name);
                        false
                    },
                ))));
            }

            if let Some(rule) = assemble_rule(rule_config, conditions) {
                rules.push(rule);
            }
        }

        Ok(rules)
    }

    /// 带自定义匹配器注册表的规则构建(E1 完整集成)
    ///
    /// 与 [`Self::build_rules`] 相同,但配置中的 `Custom` 匹配器会从
    /// `registry` 解析:已注册的匹配器被快照(`Arc`)进条件闭包并真实
    /// 参与运行时求值;未注册的仍编译为恒不匹配占位并告警。
    ///
    /// # 性能约束
    /// 条件求值是同步路径,闭包内经 `drive_lightweight` 驱动异步
    /// `matches`——自定义匹配器必须是轻量实现(头检查/阈值比较),
    /// 返回 `Pending` 的实现将按不匹配处理并记 error 日志。
    pub async fn build_rules_with_registry(
        config: &FlowControlConfig,
        registry: &crate::matchers::custom::CustomMatcherRegistry,
    ) -> Result<Vec<MatcherRule>, LimiteronError> {
        use crate::matchers::RequestContext;

        let mut rules = Vec::new();

        for rule_config in &config.rules {
            let mut conditions: Vec<Box<dyn ConditionEvaluator>> = Vec::new();

            for matcher in &rule_config.matchers {
                if let Some(condition) = base_condition(matcher)? {
                    conditions.push(condition);
                    continue;
                }
                let ConfigMatcher::Custom { name, .. } = matcher else {
                    unreachable!("base_condition 仅对 Custom 返回 None");
                };
                if let Some(matcher) = registry.get(name).await {
                    log::info!("自定义匹配器 '{}' 已从注册表解析并生效", name);
                    let name = name.clone();
                    conditions.push(Box::new(MatchCondition::Custom(Arc::new(
                        move |context: &RequestContext| {
                            let fut = matcher.matches(context);
                            match drive_lightweight(fut) {
                                Ok(v) => v,
                                Err(e) => {
                                    log::warn!(
                                        "自定义匹配器 '{}' 求值失败,按不匹配处理: {}",
                                        name,
                                        e
                                    );
                                    false
                                }
                            }
                        },
                    ))));
                } else {
                    log::warn!(
                        "自定义匹配器 '{}' 未在注册表中注册,该规则将恒不匹配(其限制不会生效)",
                        name
                    );
                    let name = name.clone();
                    conditions.push(Box::new(MatchCondition::Custom(Arc::new(
                        move |_context: &RequestContext| {
                            log::debug!("自定义匹配器 '{}' 为占位实现,恒不匹配", name);
                            false
                        },
                    ))));
                }
            }

            if let Some(rule) = assemble_rule(rule_config, conditions) {
                rules.push(rule);
            }
        }

        Ok(rules)
    }
}

/// 非 Custom 匹配器的条件编译(diting 简化:`build_rules` 与
/// `build_rules_with_registry` 共用;`Custom` 由调用方按注册表情况处理)
fn base_condition(
    matcher: &ConfigMatcher,
) -> Result<Option<Box<dyn ConditionEvaluator>>, LimiteronError> {
    Ok(match matcher {
        ConfigMatcher::User { user_ids } => Some(Box::new(MatchCondition::User(user_ids.clone()))),
        ConfigMatcher::Ip { ip_ranges } => {
            let ranges: Result<Vec<IpRange>, _> = ip_ranges.iter().map(|s| s.parse()).collect();
            Some(Box::new(MatchCondition::Ip(ranges?)))
        }
        ConfigMatcher::Geo { countries } => Some(Box::new(MatchCondition::Geo(countries.clone()))),
        ConfigMatcher::ApiVersion { versions } => {
            Some(Box::new(MatchCondition::ApiVersion(versions.clone())))
        }
        ConfigMatcher::Device { device_types } => {
            Some(Box::new(MatchCondition::Device(device_types.clone())))
        }
        ConfigMatcher::Custom { .. } => None,
    })
}

/// 组装单条规则:单条件直用,多条件 AND 组合,无条件跳过
fn assemble_rule(
    rule_config: &crate::config::Rule,
    mut conditions: Vec<Box<dyn ConditionEvaluator>>,
) -> Option<MatcherRule> {
    let final_condition: Box<dyn ConditionEvaluator> = if conditions.len() == 1 {
        conditions.pop().unwrap()
    } else if conditions.is_empty() {
        return None;
    } else {
        Box::new(CompositeCondition {
            conditions,
            operator: LogicalOperator::And,
        })
    };

    Some(MatcherRule {
        id: rule_config.id.clone(),
        name: rule_config.name.clone(),
        priority: rule_config.priority,
        condition: final_condition,
        enabled: true,
    })
}

// ============================================================================
// 单元测试
// ============================================================================

/// 轻量同步驱动器:单次 poll,Pending 显性失败
///
/// 供 `MatchCondition::Custom` 的同步求值路径驱动自定义匹配器的异步
/// `matches`。自定义匹配器契约:轻量、首次 poll 即 Ready(头检查/
/// 阈值比较等)。
///
/// 修复(diting High):不得对 `Pending` 自旋——noop waker 无人唤醒,
/// 任何含真实 await 点的实现(contended 锁、`yield_now`、IO/定时器)
/// 会把调用线程永久挂死在 100% CPU 循环。Pending 一律 `log::error!`
/// 并按不匹配处理(与求值失败同口径)。
pub(crate) fn drive_lightweight<E>(fut: impl Future<Output = Result<bool, E>>) -> Result<bool, E> {
    use std::pin::pin;
    use std::task::{Context, Poll};

    let waker = std::task::Waker::noop();
    let mut cx = Context::from_waker(waker);
    match pin!(fut).poll(&mut cx) {
        Poll::Ready(out) => out,
        Poll::Pending => {
            log::error!("自定义匹配器返回 Pending(违反「首次 poll 即 Ready」契约),按不匹配处理");
            Ok(false)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{ActionConfig, Matcher, QuotaType, Rule};

    #[test]
    fn test_parse_duration_milliseconds() {
        assert_eq!(
            RuleBuilder::parse_duration("100ms").unwrap(),
            Duration::from_millis(100)
        );
        assert_eq!(
            RuleBuilder::parse_duration("1ms").unwrap(),
            Duration::from_millis(1)
        );
    }

    #[test]
    fn test_parse_duration_seconds() {
        assert_eq!(
            RuleBuilder::parse_duration("10s").unwrap(),
            Duration::from_secs(10)
        );
        assert_eq!(
            RuleBuilder::parse_duration("1s").unwrap(),
            Duration::from_secs(1)
        );
    }

    /// E1 集成回归:build_rules_with_registry 下已注册的 Custom 匹配器
    /// 真实参与求值;未注册的为恒不匹配占位。
    #[tokio::test]
    async fn test_build_rules_with_registry_resolves_custom_matcher() {
        use crate::config::{Action, ActionConfig, FlowControlConfig, GlobalConfig, Matcher, Rule};
        use crate::matchers::RequestContext;
        use crate::matchers::custom::CustomMatcherRegistry;

        struct EnvGateMatcher;
        #[async_trait::async_trait]
        impl crate::matchers::custom::CustomMatcher for EnvGateMatcher {
            fn name(&self) -> &str {
                "env-gate"
            }
            async fn matches(&self, context: &RequestContext) -> Result<bool, LimiteronError> {
                Ok(context
                    .get_header("X-Env")
                    .map(|v| v == "beta")
                    .unwrap_or(false))
            }
            fn load_config(&mut self, _config: serde_json::Value) -> Result<(), LimiteronError> {
                Ok(())
            }
        }

        let registry = CustomMatcherRegistry::new();
        registry
            .register("env-gate".to_string(), Box::new(EnvGateMatcher))
            .await
            .unwrap();

        let config = FlowControlConfig {
            version: "0.1.0".to_string(),
            global: GlobalConfig::default(),
            rules: vec![
                Rule {
                    id: "rule-registered".to_string(),
                    name: "Registered custom".to_string(),
                    priority: 100,
                    matchers: vec![Matcher::Custom {
                        name: "env-gate".to_string(),
                        config: serde_json::json!({}),
                    }],
                    limiters: vec![],
                    action: ActionConfig {
                        on_exceed: Action::Reject,
                        ban: None,
                    },
                },
                Rule {
                    id: "rule-unregistered".to_string(),
                    name: "Unregistered custom".to_string(),
                    priority: 90,
                    matchers: vec![Matcher::Custom {
                        name: "no-such-matcher".to_string(),
                        config: serde_json::json!({}),
                    }],
                    limiters: vec![],
                    action: ActionConfig {
                        on_exceed: Action::Reject,
                        ban: None,
                    },
                },
            ],
        };

        let rules = RuleBuilder::build_rules_with_registry(&config, &registry)
            .await
            .unwrap();
        assert_eq!(rules.len(), 2);

        let by_id = |id: &str| {
            rules
                .iter()
                .find(|r| r.id == id)
                .unwrap_or_else(|| panic!("rule {id} missing"))
        };

        let beta_ctx = RequestContext::new().with_header("X-Env", "beta");
        let prod_ctx = RequestContext::new().with_header("X-Env", "prod");

        // 已注册:beta 命中、prod 不命中
        assert!(by_id("rule-registered").condition.evaluate(&beta_ctx));
        assert!(!by_id("rule-registered").condition.evaluate(&prod_ctx));

        // 未注册:恒不匹配(fail-open 占位)
        assert!(!by_id("rule-unregistered").condition.evaluate(&beta_ctx));

        // diting High 回归:Pending future 不得自旋挂死,显性按不匹配处理
        struct PendingMatcher;
        #[async_trait::async_trait]
        impl crate::matchers::custom::CustomMatcher for PendingMatcher {
            fn name(&self) -> &str {
                "pending-matcher"
            }
            async fn matches(&self, _context: &RequestContext) -> Result<bool, LimiteronError> {
                std::future::pending().await
            }
            fn load_config(&mut self, _config: serde_json::Value) -> Result<(), LimiteronError> {
                Ok(())
            }
        }
        registry
            .register("pending-matcher".to_string(), Box::new(PendingMatcher))
            .await
            .unwrap();
        let config2 = FlowControlConfig {
            version: "0.1.0".to_string(),
            global: GlobalConfig::default(),
            rules: vec![Rule {
                id: "rule-pending".to_string(),
                name: "Pending custom".to_string(),
                priority: 100,
                matchers: vec![Matcher::Custom {
                    name: "pending-matcher".to_string(),
                    config: serde_json::json!({}),
                }],
                limiters: vec![],
                action: ActionConfig {
                    on_exceed: Action::Reject,
                    ban: None,
                },
            }],
        };
        let rules3 = RuleBuilder::build_rules_with_registry(&config2, &registry)
            .await
            .unwrap();
        assert!(
            !rules3[0].condition.evaluate(&beta_ctx),
            "Pending 的自定义匹配器必须按不匹配处理(不得挂死)"
        );
    }

    #[test]
    fn test_parse_duration_minutes() {
        assert_eq!(
            RuleBuilder::parse_duration("5m").unwrap(),
            Duration::from_secs(300)
        );
        assert_eq!(
            RuleBuilder::parse_duration("1m").unwrap(),
            Duration::from_secs(60)
        );
    }

    #[test]
    fn test_parse_duration_hours() {
        assert_eq!(
            RuleBuilder::parse_duration("2h").unwrap(),
            Duration::from_secs(7200)
        );
        assert_eq!(
            RuleBuilder::parse_duration("1h").unwrap(),
            Duration::from_secs(3600)
        );
    }

    #[test]
    fn test_parse_duration_with_whitespace() {
        assert_eq!(
            RuleBuilder::parse_duration(" 10s ").unwrap(),
            Duration::from_secs(10)
        );
    }

    #[test]
    fn test_parse_duration_invalid_format() {
        assert!(RuleBuilder::parse_duration("10").is_err());
        assert!(RuleBuilder::parse_duration("10x").is_err());
        assert!(RuleBuilder::parse_duration("").is_err());
    }

    #[test]
    fn test_parse_duration_invalid_number() {
        assert!(RuleBuilder::parse_duration("abs").is_err());
        assert!(RuleBuilder::parse_duration("abcms").is_err());
    }

    #[test]
    fn test_build_rules_empty_config() {
        let config = FlowControlConfig::default();
        let rules = RuleBuilder::build_rules(&config).unwrap();
        assert!(rules.is_empty());
    }

    #[test]
    fn test_build_rule_chains_empty_config() {
        let config = FlowControlConfig::default();
        let chains = RuleBuilder::build_rule_chains(&config).unwrap();
        assert!(chains.is_empty());
    }

    #[test]
    fn test_parse_duration_valid() {
        use std::time::Duration;
        assert_eq!(
            RuleBuilder::parse_duration("100ms").unwrap(),
            Duration::from_millis(100)
        );
        assert_eq!(
            RuleBuilder::parse_duration("10s").unwrap(),
            Duration::from_secs(10)
        );
        assert_eq!(
            RuleBuilder::parse_duration("5m").unwrap(),
            Duration::from_secs(300)
        );
        assert_eq!(
            RuleBuilder::parse_duration("2h").unwrap(),
            Duration::from_secs(7200)
        );
        assert_eq!(
            RuleBuilder::parse_duration("1d").unwrap(),
            Duration::from_secs(86400)
        );
    }

    #[test]
    fn test_parse_duration_invalid() {
        assert!(RuleBuilder::parse_duration("").is_err());
        assert!(RuleBuilder::parse_duration("abc").is_err());
        assert!(RuleBuilder::parse_duration("10x").is_err());
    }

    #[test]
    fn test_build_rule_chains_with_single_rule() {
        let config = FlowControlConfig {
            rules: vec![Rule {
                id: "test-rule".to_string(),
                name: "Test Rule".to_string(),
                priority: 1,
                matchers: vec![Matcher::User {
                    user_ids: vec!["user1".to_string()],
                }],
                limiters: vec![LimiterConfig::TokenBucket {
                    capacity: 100,
                    refill_rate: 10,
                }],
                action: ActionConfig::default(),
            }],
            ..Default::default()
        };
        let chains = RuleBuilder::build_rule_chains(&config).unwrap();
        assert_eq!(chains.len(), 1);
        assert!(chains.contains_key("test-rule"));
    }

    #[test]
    fn test_build_rule_chains_with_multiple_rules() {
        let config = FlowControlConfig {
            rules: vec![
                Rule {
                    id: "rule1".to_string(),
                    name: "Rule 1".to_string(),
                    priority: 1,
                    matchers: vec![Matcher::User {
                        user_ids: vec!["user1".to_string()],
                    }],
                    limiters: vec![LimiterConfig::TokenBucket {
                        capacity: 100,
                        refill_rate: 10,
                    }],
                    action: ActionConfig::default(),
                },
                Rule {
                    id: "rule2".to_string(),
                    name: "Rule 2".to_string(),
                    priority: 2,
                    matchers: vec![Matcher::Ip {
                        ip_ranges: vec!["192.168.1.0/24".to_string()],
                    }],
                    limiters: vec![LimiterConfig::FixedWindow {
                        window_size: "1m".to_string(),
                        max_requests: 100,
                    }],
                    action: ActionConfig::default(),
                },
            ],
            ..Default::default()
        };
        let chains = RuleBuilder::build_rule_chains(&config).unwrap();
        assert_eq!(chains.len(), 2);
        assert!(chains.contains_key("rule1"));
        assert!(chains.contains_key("rule2"));
    }

    #[test]
    fn test_build_rule_chains_empty_rules() {
        let config = FlowControlConfig {
            rules: vec![],
            ..Default::default()
        };
        let chains = RuleBuilder::build_rule_chains(&config).unwrap();
        assert!(chains.is_empty());
    }

    // ==================== build_rules coverage expansion ====================

    #[test]
    fn test_build_rules_single_user_matcher() {
        let config = FlowControlConfig {
            rules: vec![Rule {
                id: "user-rule".into(),
                name: "User Rule".into(),
                priority: 10,
                matchers: vec![Matcher::User {
                    user_ids: vec!["user1".into(), "user2".into()],
                }],
                limiters: vec![LimiterConfig::TokenBucket {
                    capacity: 100,
                    refill_rate: 10,
                }],
                action: ActionConfig::default(),
            }],
            ..Default::default()
        };
        let rules = RuleBuilder::build_rules(&config).unwrap();
        assert_eq!(rules.len(), 1);
        assert_eq!(rules[0].id, "user-rule");
        assert_eq!(rules[0].name, "User Rule");
        assert_eq!(rules[0].priority, 10);
        assert!(rules[0].enabled);
    }

    #[test]
    fn test_build_rules_single_ip_matcher() {
        let config = FlowControlConfig {
            rules: vec![Rule {
                id: "ip-rule".into(),
                name: "IP Rule".into(),
                priority: 20,
                matchers: vec![Matcher::Ip {
                    ip_ranges: vec!["10.0.0.0/8".into()],
                }],
                limiters: vec![LimiterConfig::TokenBucket {
                    capacity: 100,
                    refill_rate: 10,
                }],
                action: ActionConfig::default(),
            }],
            ..Default::default()
        };
        let rules = RuleBuilder::build_rules(&config).unwrap();
        assert_eq!(rules.len(), 1);
        assert_eq!(rules[0].id, "ip-rule");
    }

    #[test]
    fn test_build_rules_invalid_ip_range() {
        let config = FlowControlConfig {
            rules: vec![Rule {
                id: "bad-ip".into(),
                name: "Bad IP".into(),
                priority: 1,
                matchers: vec![Matcher::Ip {
                    ip_ranges: vec!["not-an-ip".into()],
                }],
                limiters: vec![LimiterConfig::TokenBucket {
                    capacity: 100,
                    refill_rate: 10,
                }],
                action: ActionConfig::default(),
            }],
            ..Default::default()
        };
        assert!(RuleBuilder::build_rules(&config).is_err());
    }

    #[test]
    fn test_build_rules_single_geo_matcher() {
        let config = FlowControlConfig {
            rules: vec![Rule {
                id: "geo-rule".into(),
                name: "Geo Rule".into(),
                priority: 30,
                matchers: vec![Matcher::Geo {
                    countries: vec!["US".into(), "CN".into()],
                }],
                limiters: vec![LimiterConfig::TokenBucket {
                    capacity: 200,
                    refill_rate: 20,
                }],
                action: ActionConfig::default(),
            }],
            ..Default::default()
        };
        let rules = RuleBuilder::build_rules(&config).unwrap();
        assert_eq!(rules.len(), 1);
        assert_eq!(rules[0].id, "geo-rule");
    }

    #[test]
    fn test_build_rules_single_api_version_matcher() {
        let config = FlowControlConfig {
            rules: vec![Rule {
                id: "api-rule".into(),
                name: "API Rule".into(),
                priority: 40,
                matchers: vec![Matcher::ApiVersion {
                    versions: vec!["v1".into(), "v2".into()],
                }],
                limiters: vec![LimiterConfig::TokenBucket {
                    capacity: 300,
                    refill_rate: 30,
                }],
                action: ActionConfig::default(),
            }],
            ..Default::default()
        };
        let rules = RuleBuilder::build_rules(&config).unwrap();
        assert_eq!(rules.len(), 1);
        assert_eq!(rules[0].id, "api-rule");
    }

    #[test]
    fn test_build_rules_single_device_matcher() {
        let config = FlowControlConfig {
            rules: vec![Rule {
                id: "device-rule".into(),
                name: "Device Rule".into(),
                priority: 50,
                matchers: vec![Matcher::Device {
                    device_types: vec!["mobile".into(), "desktop".into()],
                }],
                limiters: vec![LimiterConfig::TokenBucket {
                    capacity: 400,
                    refill_rate: 40,
                }],
                action: ActionConfig::default(),
            }],
            ..Default::default()
        };
        let rules = RuleBuilder::build_rules(&config).unwrap();
        assert_eq!(rules.len(), 1);
        assert_eq!(rules[0].id, "device-rule");
    }

    #[test]
    fn test_build_rules_custom_matcher() {
        let config = FlowControlConfig {
            rules: vec![Rule {
                id: "custom-rule".into(),
                name: "Custom Rule".into(),
                priority: 60,
                matchers: vec![Matcher::Custom {
                    name: "my-custom".into(),
                    config: serde_json::json!({"key": "value"}),
                }],
                limiters: vec![LimiterConfig::TokenBucket {
                    capacity: 500,
                    refill_rate: 50,
                }],
                action: ActionConfig::default(),
            }],
            ..Default::default()
        };
        let rules = RuleBuilder::build_rules(&config).unwrap();
        assert_eq!(rules.len(), 1);
        assert_eq!(rules[0].id, "custom-rule");
    }

    #[test]
    fn test_build_rules_multiple_matchers_composite() {
        let config = FlowControlConfig {
            rules: vec![Rule {
                id: "composite-rule".into(),
                name: "Composite Rule".into(),
                priority: 70,
                matchers: vec![
                    Matcher::User {
                        user_ids: vec!["user1".into()],
                    },
                    Matcher::Geo {
                        countries: vec!["US".into()],
                    },
                ],
                limiters: vec![LimiterConfig::TokenBucket {
                    capacity: 600,
                    refill_rate: 60,
                }],
                action: ActionConfig::default(),
            }],
            ..Default::default()
        };
        let rules = RuleBuilder::build_rules(&config).unwrap();
        assert_eq!(rules.len(), 1);
        assert_eq!(rules[0].id, "composite-rule");
    }

    #[test]
    fn test_build_rules_no_matchers_skipped() {
        let config = FlowControlConfig {
            rules: vec![Rule {
                id: "skip-rule".into(),
                name: "Skip Rule".into(),
                priority: 1,
                matchers: vec![],
                limiters: vec![LimiterConfig::TokenBucket {
                    capacity: 100,
                    refill_rate: 10,
                }],
                action: ActionConfig::default(),
            }],
            ..Default::default()
        };
        let rules = RuleBuilder::build_rules(&config).unwrap();
        assert!(rules.is_empty());
    }

    #[test]
    fn test_build_rules_multiple_rules_various_matchers() {
        let config = FlowControlConfig {
            rules: vec![
                Rule {
                    id: "rule-a".into(),
                    name: "Rule A".into(),
                    priority: 1,
                    matchers: vec![Matcher::User {
                        user_ids: vec!["user1".into()],
                    }],
                    limiters: vec![LimiterConfig::TokenBucket {
                        capacity: 100,
                        refill_rate: 10,
                    }],
                    action: ActionConfig::default(),
                },
                Rule {
                    id: "rule-b".into(),
                    name: "Rule B".into(),
                    priority: 2,
                    matchers: vec![Matcher::Device {
                        device_types: vec!["mobile".into()],
                    }],
                    limiters: vec![LimiterConfig::FixedWindow {
                        window_size: "1m".into(),
                        max_requests: 100,
                    }],
                    action: ActionConfig::default(),
                },
            ],
            ..Default::default()
        };
        let rules = RuleBuilder::build_rules(&config).unwrap();
        assert_eq!(rules.len(), 2);
        assert_eq!(rules[0].id, "rule-a");
        assert_eq!(rules[1].id, "rule-b");
        assert_eq!(rules[0].priority, 1);
        assert_eq!(rules[1].priority, 2);
    }

    // ==================== build_rule_chains coverage expansion ====================

    #[test]
    fn test_build_rule_chains_sliding_window() {
        let config = FlowControlConfig {
            rules: vec![Rule {
                id: "sliding-rule".into(),
                name: "Sliding Window Rule".into(),
                priority: 1,
                matchers: vec![Matcher::User {
                    user_ids: vec!["user1".into()],
                }],
                limiters: vec![LimiterConfig::SlidingWindow {
                    window_size: "30s".into(),
                    max_requests: 100,
                }],
                action: ActionConfig::default(),
            }],
            ..Default::default()
        };
        let chains = RuleBuilder::build_rule_chains(&config).unwrap();
        assert_eq!(chains.len(), 1);
        assert!(chains.contains_key("sliding-rule"));
        let chain = chains.get("sliding-rule").unwrap();
        assert_eq!(chain.node_count(), 1);
    }

    #[test]
    fn test_build_rule_chains_concurrency() {
        let config = FlowControlConfig {
            rules: vec![Rule {
                id: "concurrency-rule".into(),
                name: "Concurrency Rule".into(),
                priority: 1,
                matchers: vec![Matcher::User {
                    user_ids: vec!["user1".into()],
                }],
                limiters: vec![LimiterConfig::Concurrency { max_concurrent: 50 }],
                action: ActionConfig::default(),
            }],
            ..Default::default()
        };
        let chains = RuleBuilder::build_rule_chains(&config).unwrap();
        assert_eq!(chains.len(), 1);
        assert!(chains.contains_key("concurrency-rule"));
        let chain = chains.get("concurrency-rule").unwrap();
        assert_eq!(chain.node_count(), 1);
    }

    #[test]
    fn test_build_rule_chains_quota_skipped() {
        let config = FlowControlConfig {
            rules: vec![Rule {
                id: "quota-rule".into(),
                name: "Quota Rule".into(),
                priority: 1,
                matchers: vec![Matcher::User {
                    user_ids: vec!["user1".into()],
                }],
                limiters: vec![LimiterConfig::Quota {
                    quota_type: QuotaType::Count,
                    limit: 1000,
                    window: "1d".into(),
                    alert_threshold: Some(80),
                    overdraft: None,
                }],
                action: ActionConfig::default(),
            }],
            ..Default::default()
        };
        let chains = RuleBuilder::build_rule_chains(&config).unwrap();
        assert_eq!(chains.len(), 1);
        assert!(chains.contains_key("quota-rule"));
        let chain = chains.get("quota-rule").unwrap();
        // quota-control 特性开启时配额规则被真实挂载(diting MED-004 修复)
        #[cfg(feature = "quota-control")]
        assert_eq!(chain.node_count(), 1);
        #[cfg(not(feature = "quota-control"))]
        assert_eq!(chain.node_count(), 0);
    }

    #[test]
    fn test_build_rule_chains_custom_skipped() {
        let config = FlowControlConfig {
            rules: vec![Rule {
                id: "custom-rule".into(),
                name: "Custom Limiter Rule".into(),
                priority: 1,
                matchers: vec![Matcher::User {
                    user_ids: vec!["user1".into()],
                }],
                limiters: vec![LimiterConfig::Custom {
                    name: "my-custom-limiter".into(),
                    config: serde_json::json!({"key": "value"}),
                }],
                action: ActionConfig::default(),
            }],
            ..Default::default()
        };
        let chains = RuleBuilder::build_rule_chains(&config).unwrap();
        assert_eq!(chains.len(), 1);
        assert!(chains.contains_key("custom-rule"));
        let chain = chains.get("custom-rule").unwrap();
        assert_eq!(chain.node_count(), 0);
    }

    #[test]
    fn test_build_rule_chains_multiple_limiters_per_rule() {
        let config = FlowControlConfig {
            rules: vec![Rule {
                id: "multi-limiter".into(),
                name: "Multi Limiter".into(),
                priority: 1,
                matchers: vec![Matcher::User {
                    user_ids: vec!["user1".into()],
                }],
                limiters: vec![
                    LimiterConfig::TokenBucket {
                        capacity: 100,
                        refill_rate: 10,
                    },
                    LimiterConfig::FixedWindow {
                        window_size: "1m".into(),
                        max_requests: 50,
                    },
                ],
                action: ActionConfig::default(),
            }],
            ..Default::default()
        };
        let chains = RuleBuilder::build_rule_chains(&config).unwrap();
        assert_eq!(chains.len(), 1);
        assert!(chains.contains_key("multi-limiter"));
        let chain = chains.get("multi-limiter").unwrap();
        assert_eq!(chain.node_count(), 2);
    }

    #[test]
    fn test_build_rule_chains_invalid_window_size() {
        let config = FlowControlConfig {
            rules: vec![Rule {
                id: "bad-window".into(),
                name: "Bad Window".into(),
                priority: 1,
                matchers: vec![Matcher::User {
                    user_ids: vec!["user1".into()],
                }],
                limiters: vec![LimiterConfig::SlidingWindow {
                    window_size: "invalid".into(),
                    max_requests: 100,
                }],
                action: ActionConfig::default(),
            }],
            ..Default::default()
        };
        assert!(RuleBuilder::build_rule_chains(&config).is_err());
    }

    #[test]
    fn test_build_rule_chains_all_limiter_types() {
        let config = FlowControlConfig {
            rules: vec![Rule {
                id: "all-types".into(),
                name: "All Types".into(),
                priority: 100,
                matchers: vec![Matcher::User {
                    user_ids: vec!["user1".into()],
                }],
                limiters: vec![
                    LimiterConfig::TokenBucket {
                        capacity: 100,
                        refill_rate: 10,
                    },
                    LimiterConfig::SlidingWindow {
                        window_size: "30s".into(),
                        max_requests: 200,
                    },
                    LimiterConfig::FixedWindow {
                        window_size: "1m".into(),
                        max_requests: 50,
                    },
                    LimiterConfig::Concurrency { max_concurrent: 25 },
                    LimiterConfig::Quota {
                        quota_type: QuotaType::Count,
                        limit: 1000,
                        window: "1d".into(),
                        alert_threshold: None,
                        overdraft: None,
                    },
                    LimiterConfig::Custom {
                        name: "test".into(),
                        config: serde_json::json!({"key": "val"}),
                    },
                ],
                action: ActionConfig::default(),
            }],
            ..Default::default()
        };
        let chains = RuleBuilder::build_rule_chains(&config).unwrap();
        assert_eq!(chains.len(), 1);
        let chain = chains.get("all-types").unwrap();
        // 6 个 limiter 配置:Custom 始终跳过;
        // quota-control 开启时 Quota 真实挂载 → 5 节点,否则 4 节点
        #[cfg(feature = "quota-control")]
        assert_eq!(chain.node_count(), 5);
        #[cfg(not(feature = "quota-control"))]
        assert_eq!(chain.node_count(), 4);
    }

    #[test]
    fn test_build_rule_chains_with_fixed_window() {
        let config = FlowControlConfig {
            rules: vec![Rule {
                id: "fixed-rule".into(),
                name: "Fixed Window Rule".into(),
                priority: 1,
                matchers: vec![Matcher::User {
                    user_ids: vec!["user1".into()],
                }],
                limiters: vec![LimiterConfig::FixedWindow {
                    window_size: "5m".into(),
                    max_requests: 200,
                }],
                action: ActionConfig::default(),
            }],
            ..Default::default()
        };
        let chains = RuleBuilder::build_rule_chains(&config).unwrap();
        assert_eq!(chains.len(), 1);
        assert!(chains.contains_key("fixed-rule"));
        let chain = chains.get("fixed-rule").unwrap();
        assert_eq!(chain.node_count(), 1);
    }

    #[test]
    fn test_build_rule_chains_token_bucket_boundary_values() {
        let config = FlowControlConfig {
            rules: vec![Rule {
                id: "boundary".into(),
                name: "Boundary".into(),
                priority: 1,
                matchers: vec![Matcher::User {
                    user_ids: vec!["user1".into()],
                }],
                limiters: vec![LimiterConfig::TokenBucket {
                    capacity: 1,
                    refill_rate: 1,
                }],
                action: ActionConfig::default(),
            }],
            ..Default::default()
        };
        let chains = RuleBuilder::build_rule_chains(&config).unwrap();
        assert_eq!(chains.len(), 1);
        assert!(chains.contains_key("boundary"));
        let chain = chains.get("boundary").unwrap();
        assert_eq!(chain.node_count(), 1);
    }
}