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
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
1446
1447
1448
1449
1450
1451
1452
1453
1454
// Copyright (c) 2026 Kirky.X
// SPDX-License-Identifier: MIT
//! HTTP处理器

use axum::{
    Extension, Json,
    extract::{Path, Query, State},
    http::StatusCode,
    response::IntoResponse,
};
use serde::{Deserialize, Serialize};

use super::routes::OperatorIdentity;
use super::server::AppState;
#[cfg(feature = "ban-manager")]
use crate::ban::{BanFilter, BanTarget};

// ==================== 响应类型 ====================

/// 通用响应
#[derive(Serialize)]
pub struct ApiResponse<T: Serialize> {
    pub success: bool,
    pub message: String,
    pub data: Option<T>,
}

impl<T: Serialize> ApiResponse<T> {
    pub fn ok(data: T) -> Self {
        Self {
            success: true,
            message: "OK".to_string(),
            data: Some(data),
        }
    }

    pub fn error(message: impl Into<String>) -> Self {
        Self {
            success: false,
            message: message.into(),
            data: None,
        }
    }
}

//
// 三个端点在 routes 层 bypass 速率限制与 API key 认证:
// K8s kubelet 探针与 Prometheus 抓取器不携带管理凭证。

/// GET /healthz — 存活探针
///
/// 进程存活且事件循环可响应即返回 200(不做组件级检查——那是 /readyz 的职责)。
pub async fn healthz() -> Json<serde_json::Value> {
    Json(serde_json::json!({ "status": "ok" }))
}

/// GET /readyz — 就绪探针
///
/// 聚合 [`Governor::health_status()`](crate::governor::Governor::health_status) 的组件级状态:
/// - 全部健康 → 200 + `{"status":"ready", ...}`
/// - 任一不健康 → 503 + 不健康组件明细
pub async fn readyz(State(state): State<AppState>) -> axum::response::Response {
    let status = state.governor.health_status().await;
    let body = serde_json::json!({
        "status": if status.healthy() { "ready" } else { "not_ready" },
        "storage_healthy": status.storage_healthy,
        "ban_storage_healthy": status.ban_storage_healthy,
        "cache_healthy": status.cache_healthy,
        "background_tasks_alive": status.background_tasks_alive,
    });
    if status.healthy() {
        (StatusCode::OK, Json(body)).into_response()
    } else {
        (StatusCode::SERVICE_UNAVAILABLE, Json(body)).into_response()
    }
}

/// GET /metrics — Prometheus 文本格式指标
///
/// 数据源优先级:`AppState.metrics`(显式注入)→ 全局指标(`try_global()`)
/// → 空 exposition(合法 Prometheus 注释行,保持 200 契约)。
#[cfg(feature = "monitoring")]
pub async fn metrics(State(state): State<AppState>) -> axum::response::Response {
    use axum::http::header;
    let content_type = "text/plain; version=0.0.4";
    let text = match state.metrics.clone().or_else(crate::telemetry::try_global) {
        Some(m) => m.gather(),
        None => "# limiteron metrics not configured\n".to_string(),
    };
    ([(header::CONTENT_TYPE, content_type)], text).into_response()
}

/// GET /metrics(无 monitoring feature)——空 exposition
#[cfg(not(feature = "monitoring"))]
pub async fn metrics() -> axum::response::Response {
    use axum::http::header;
    (
        [(header::CONTENT_TYPE, "text/plain; version=0.0.4")],
        "# limiteron metrics feature disabled\n".to_string(),
    )
        .into_response()
}

// ==================== 系统状态 ====================

/// 系统整体状态
#[derive(Serialize)]
pub struct SystemStatus {
    pub total_requests: u64,
    pub blocked_requests: u64,
    pub success_rate: f64,
    #[cfg(feature = "ban-manager")]
    pub active_bans: usize,
    #[cfg(feature = "circuit-breaker")]
    pub circuit_breaker: String,
}

/// GET /api/v1/status
pub async fn get_status(State(state): State<AppState>) -> Json<ApiResponse<SystemStatus>> {
    let stats = state.governor.stats().await;

    // 饱和运算:计数器持续累加可能接近 u64::MAX,且回退场景下
    // blocked 可能超过 total,裸加减会 panic(debug)或回绕(release)
    let blocked = stats
        .rejected_requests
        .saturating_add(stats.banned_requests);
    let total = stats.total_requests;
    let success_rate = if total > 0 {
        (total.saturating_sub(blocked)) as f64 / total as f64
    } else {
        1.0
    };

    #[cfg(feature = "ban-manager")]
    let active_bans: usize = if let Some(ref bm) = state.ban_manager {
        bm.list_bans(BanFilter {
            active_only: true,
            ..Default::default()
        })
        .await
        .map(|v| v.len())
        .unwrap_or(0)
    } else {
        0
    };

    #[cfg(feature = "circuit-breaker")]
    let cb_state = if let Some(ref cb) = state.circuit_breaker {
        cb.get_state().await.to_string()
    } else {
        "disabled".to_string()
    };

    Json(ApiResponse::ok(SystemStatus {
        total_requests: total,
        blocked_requests: blocked,
        success_rate,
        #[cfg(feature = "ban-manager")]
        active_bans,
        #[cfg(feature = "circuit-breaker")]
        circuit_breaker: cb_state,
    }))
}

// ==================== Governor 自省 ====================

/// GET /api/v1/introspect —— 运行时自省快照(JSON)
///
/// 聚合 Governor 的规则/决策链/统计/L1 缓存/健康状态,并叠加
/// 封禁清单(ban-manager)与熔断状态(circuit-breaker)。
/// 只读端点:viewer 角色即可访问。
pub async fn introspect(State(state): State<AppState>) -> Json<serde_json::Value> {
    let snapshot = state.governor.introspect().await;
    let mut body = serde_json::to_value(&snapshot).unwrap_or_else(|_| serde_json::json!({}));

    #[cfg(feature = "ban-manager")]
    if let Some(ref bm) = state.ban_manager {
        if let Ok(bans) = bm
            .list_bans(BanFilter {
                active_only: true,
                ..Default::default()
            })
            .await
        {
            let items: Vec<serde_json::Value> = bans
                .iter()
                .map(|b| {
                    serde_json::json!({
                        "target": b.target,
                        "ban_times": b.ban_times,
                        "is_manual": b.is_manual,
                        "reason": b.reason,
                        "expires_at": b.expires_at.to_rfc3339(),
                    })
                })
                .collect();
            body["active_bans"] = serde_json::Value::Array(items);
        }
    }

    #[cfg(feature = "circuit-breaker")]
    if let Some(ref cb) = state.circuit_breaker {
        body["circuit_breaker_state"] = serde_json::json!(cb.get_state().await.to_string());
    }

    Json(body)
}

// ==================== 规则热更新 / 批量 API ====================

/// 批量检查/预取的条目数上限(防单请求打爆控制面)
const BATCH_MAX_ITEMS: usize = 1000;

/// POST /api/v1/config —— 规则热更新(原子换配置)
///
/// 请求体为完整 `FlowControlConfig` JSON。校验失败或预构建失败返回
/// 400 且**旧配置原样保留**(rollback 语义);成功则原子换入新配置
/// 并同步重建规则匹配器与决策链(真实生效,见 `Governor::apply_config`)。
/// 写操作:仅 admin 角色可调用。
pub async fn apply_config(
    State(state): State<AppState>,
    Json(config): Json<crate::config::FlowControlConfig>,
) -> (StatusCode, Json<ApiResponse<serde_json::Value>>) {
    match state.governor.apply_config(config).await {
        Ok(report) => {
            let data = serde_json::to_value(&report).unwrap_or_else(|_| serde_json::json!({}));
            (
                StatusCode::OK,
                Json(ApiResponse {
                    success: true,
                    message: "config applied".to_string(),
                    data: Some(data),
                }),
            )
        }
        Err(e) => (
            StatusCode::BAD_REQUEST,
            Json(ApiResponse::error(format!("config rejected: {e}"))),
        ),
    }
}

/// 批量检查请求条目
#[derive(Deserialize)]
pub struct BatchCheckItem {
    #[serde(default)]
    pub user_id: Option<String>,
    #[serde(default)]
    pub ip: Option<String>,
    #[serde(default)]
    pub path: Option<String>,
    #[serde(default)]
    pub method: Option<String>,
}

/// 批量检查请求体:N 个 key 一次决策
#[derive(Deserialize)]
pub struct BatchCheckBody {
    pub requests: Vec<BatchCheckItem>,
}

/// POST /api/v1/check/batch —— 批量检查端点
///
/// 请求体 `{"requests": [{user_id, ip, path, method}, ...]}`,对 N 个
/// key 各执行一次完整 Governor 决策,返回逐项结果。单条失败不中断
/// 整批(逐项报告 error)。上限 `BATCH_MAX_ITEMS` 条,超出返回 400。
pub async fn check_batch(
    State(state): State<AppState>,
    Json(body): Json<BatchCheckBody>,
) -> (StatusCode, Json<ApiResponse<serde_json::Value>>) {
    if body.requests.is_empty() {
        return (
            StatusCode::BAD_REQUEST,
            Json(ApiResponse::error(
                "batch check requires at least one request",
            )),
        );
    }
    if body.requests.len() > BATCH_MAX_ITEMS {
        return (
            StatusCode::BAD_REQUEST,
            Json(ApiResponse::error(format!(
                "batch check limited to {BATCH_MAX_ITEMS} requests per call"
            ))),
        );
    }

    let mut results = Vec::with_capacity(body.requests.len());
    for (index, item) in body.requests.into_iter().enumerate() {
        let mut ctx = crate::matchers::RequestContext::new();
        // 默认 CompositeExtractor 从 X-User-Id 头 / 客户端 IP / X-API-Key
        // 提取标识符;批量端点将 body 字段映射到对应提取源。
        if let Some(user_id) = item.user_id {
            ctx.headers.insert("x-user-id".to_string(), user_id);
        }
        ctx.ip = item.ip.clone();
        ctx.client_ip = item.ip;
        ctx.path = item.path.unwrap_or_default();
        ctx.method = item.method.unwrap_or_else(|| "GET".to_string());

        match state.governor.check(&ctx).await {
            Ok(decision) => {
                let (kind, allowed) = match &decision {
                    crate::error::Decision::Allowed(_) => ("Allowed", true),
                    crate::error::Decision::Rejected(_) => ("Rejected", false),
                    crate::error::Decision::Banned(_) => ("Banned", false),
                };
                results.push(serde_json::json!({
                    "index": index,
                    "allowed": allowed,
                    "decision": kind,
                }));
            }
            Err(e) => {
                results.push(serde_json::json!({
                    "index": index,
                    "allowed": false,
                    "decision": "Error",
                    "error": e.to_string(),
                }));
            }
        }
    }

    let allowed_count = results.iter().filter(|r| r["allowed"] == true).count();
    (
        StatusCode::OK,
        Json(ApiResponse {
            success: true,
            message: format!("{allowed_count}/{} allowed", results.len()),
            data: Some(serde_json::json!({ "results": results })),
        }),
    )
}

/// 令牌预取条目
#[derive(Deserialize)]
pub struct TokenPrefetchItem {
    /// 预取 key(客户端标识)
    pub key: String,
    /// 预取令牌数(一次原子预留)
    pub tokens: u64,
}

/// 批量令牌预取请求体
#[derive(Deserialize)]
pub struct TokenPrefetchBody {
    pub items: Vec<TokenPrefetchItem>,
}

/// 进程级批量令牌预取器(控制面专用,不参与决策热路径)。
///
/// Admin API 无状态 handler 的共享实例;容量即语义(last-config-wins)。
static TOKEN_PREFETCHER: std::sync::OnceLock<crate::limiters::BatchTokenPrefetcher> =
    std::sync::OnceLock::new();

fn token_prefetcher() -> &'static crate::limiters::BatchTokenPrefetcher {
    TOKEN_PREFETCHER.get_or_init(crate::limiters::BatchTokenPrefetcher::new)
}

/// POST /api/v1/tokens/prefetch —— 批量令牌预取
///
/// 请求体 `{"items": [{"key": "...", "tokens": N}, ...]}`,为 N 个 key
/// 各一次性原子预留 tokens 个令牌(见 `BatchTokenPrefetcher`)。返回
/// 逐项 `granted` 与汇总计数。上限 `BATCH_MAX_ITEMS` 条。
pub async fn prefetch_tokens(
    Json(body): Json<TokenPrefetchBody>,
) -> (StatusCode, Json<ApiResponse<serde_json::Value>>) {
    if body.items.is_empty() {
        return (
            StatusCode::BAD_REQUEST,
            Json(ApiResponse::error(
                "token prefetch requires at least one item",
            )),
        );
    }
    if body.items.len() > BATCH_MAX_ITEMS {
        return (
            StatusCode::BAD_REQUEST,
            Json(ApiResponse::error(format!(
                "token prefetch limited to {BATCH_MAX_ITEMS} items per call"
            ))),
        );
    }

    let pairs: Vec<(String, u64)> = body.items.into_iter().map(|i| (i.key, i.tokens)).collect();
    let results = token_prefetcher().prefetch_batch(&pairs).await;
    let granted_count = results.iter().filter(|r| r.granted).count();

    (
        StatusCode::OK,
        Json(ApiResponse {
            success: true,
            message: format!("{granted_count}/{} granted", results.len()),
            data: Some(serde_json::to_value(&results).unwrap_or_else(|_| serde_json::json!([]))),
        }),
    )
}

// ==================== 封禁管理 ====================

/// 解除封禁请求
#[derive(Deserialize)]
pub struct UnbanRequest {
    pub reason: Option<String>,
    /// 操作者标识(已弃用,vuln-0001 修复后由 API key mapping 决定)
    ///
    /// 此字段保留仅为向后兼容(旧客户端仍可发送),但服务端会忽略其值。
    /// 实际 operator 身份由 `OperatorIdentity`(来自鉴权 middleware)决定。
    #[serde(default)]
    pub operator: Option<String>,
}

/// DELETE /api/v1/ban/{target} 的 query 参数
///
/// - `?type=ip|user|mac|geo|cidr`:显式指定目标类型,用于解封通过 API 创建的 MAC/Geo/CIDR 封禁
/// - 未提供时按原有行为自动推断(IP 优先,回退 UserId)
#[derive(Deserialize, Default)]
pub struct BanTargetQuery {
    /// 目标类型:ip | user | mac | geo
    #[serde(rename = "type")]
    pub target_type: Option<String>,
}

/// DELETE /api/v1/ban/{target}
///
/// 路径 `target` 默认按 IP 解析,回退为 UserId;通过 `?type=` 可显式指定
/// ip/user/mac/geo/cidr 之一,以解封非 IP/UserId 目标。
/// 状态码:200=成功, 400=不支持的 type, 404=未找到, 503=未配置, 500=内部错误
///
/// vuln-0001 修复:operator 身份由 `OperatorIdentity`(鉴权 middleware 注入)决定,
/// 不再使用 JSON body 中的 `operator` 字段。
#[cfg(feature = "ban-manager")]
pub async fn delete_ban(
    State(state): State<AppState>,
    Extension(operator): Extension<OperatorIdentity>,
    Path(target): Path<String>,
    Query(query): Query<BanTargetQuery>,
    Json(req): Json<UnbanRequest>,
) -> (StatusCode, Json<ApiResponse<()>>) {
    let Some(ref ban_manager) = state.ban_manager else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiResponse::error("Ban manager not configured")),
        );
    };
    let ban_target = match query.target_type.as_deref() {
        Some("ip") => BanTarget::Ip(target),
        Some("user") => BanTarget::UserId(target),
        Some("mac") => BanTarget::Mac(target),
        Some("geo") => BanTarget::Geo {
            country_code: target,
        },
        Some("cidr") => BanTarget::Cidr(target),
        Some(other) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(ApiResponse::error(format!(
                    "unsupported target type: {}",
                    other
                ))),
            );
        }
        None => {
            // 自动推断:IP 优先,回退 UserId
            if target.parse::<std::net::IpAddr>().is_ok() {
                BanTarget::Ip(target)
            } else {
                BanTarget::UserId(target)
            }
        }
    };
    // vuln-0001 修复:operator 来自 OperatorIdentity(API key mapping),而非 body
    match ban_manager.delete_ban(&ban_target, operator.0).await {
        Ok(true) => (
            StatusCode::OK,
            Json(ApiResponse {
                success: true,
                message: req.reason.unwrap_or_else(|| "Ban removed".to_string()),
                data: Some(()),
            }),
        ),
        Ok(false) => (
            StatusCode::NOT_FOUND,
            Json(ApiResponse::error("Ban not found")),
        ),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ApiResponse::error(format!("Failed to remove ban: {}", e))),
        ),
    }
}

/// DELETE /api/v1/ban/{target} (无ban-manager特性)
#[cfg(not(feature = "ban-manager"))]
pub async fn delete_ban(
    Path(_target): Path<String>,
    Query(_query): Query<BanTargetQuery>,
) -> (StatusCode, Json<ApiResponse<()>>) {
    (
        StatusCode::SERVICE_UNAVAILABLE,
        Json(ApiResponse::error("Ban manager not configured")),
    )
}

/// 创建封禁请求
#[derive(Deserialize)]
#[cfg(feature = "ban-manager")]
pub struct CreateBanRequest {
    /// 封禁目标(与 BanTarget serde 格式一致:{"type":"ip","value":"1.2.3.4"})
    pub target: crate::storage::BanTarget,
    /// 封禁原因
    pub reason: String,
    /// 操作者标识(已弃用,vuln-0001 修复后由 API key mapping 决定)
    ///
    /// 此字段保留仅为向后兼容(旧客户端仍可发送),但服务端会忽略其值。
    /// 实际 operator 身份由 `OperatorIdentity`(来自鉴权 middleware)决定。
    #[serde(default)]
    pub operator: Option<String>,
    /// 封禁时长(秒),None = 使用退避算法自动计算
    #[serde(default)]
    pub duration_secs: Option<u64>,
}

/// 创建封禁响应
#[derive(Serialize)]
#[cfg(feature = "ban-manager")]
pub struct BanResponse {
    pub id: String,
    pub ban_times: u32,
    pub expires_at: i64,
    pub is_manual: bool,
}

/// POST /api/v1/ban
///
/// 创建封禁。支持 ip/user/mac/geo 四种 target 类型。
/// 错误映射:ValidationError→400, AuthorizationError→403, 其他→500。
///
/// vuln-0001 修复:operator 身份由 `OperatorIdentity`(鉴权 middleware 注入)决定,
/// 不再使用 JSON body 中的 `operator` 字段。
#[cfg(feature = "ban-manager")]
pub async fn create_ban(
    State(state): State<AppState>,
    Extension(operator): Extension<OperatorIdentity>,
    Json(req): Json<CreateBanRequest>,
) -> (StatusCode, Json<ApiResponse<BanResponse>>) {
    use crate::ban::BanSource;
    use std::time::Duration;

    let Some(ref ban_manager) = state.ban_manager else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiResponse::error("Ban manager not configured")),
        );
    };

    // vuln-0001 修复:operator 来自 OperatorIdentity(API key mapping),而非 body
    let source = BanSource::Manual {
        operator: operator.0,
    };
    let duration = req.duration_secs.map(Duration::from_secs);

    match ban_manager
        .create_ban(
            req.target,
            req.reason,
            source,
            serde_json::json!({"source": "http-api"}),
            duration,
        )
        .await
    {
        Ok(detail) => (
            StatusCode::CREATED,
            Json(ApiResponse::ok(BanResponse {
                id: detail.id,
                ban_times: detail.ban_times,
                expires_at: detail.expires_at.timestamp(),
                is_manual: detail.is_manual,
            })),
        ),
        Err(e) => {
            let status = match &e {
                crate::error::LimiteronError::ValidationError(_) => StatusCode::BAD_REQUEST,
                crate::error::LimiteronError::AuthorizationError(_) => StatusCode::FORBIDDEN,
                _ => StatusCode::INTERNAL_SERVER_ERROR,
            };
            (status, Json(ApiResponse::error(format!("{}", e))))
        }
    }
}

/// POST /api/v1/ban (无ban-manager特性)
#[cfg(not(feature = "ban-manager"))]
pub async fn create_ban() -> (StatusCode, Json<ApiResponse<()>>) {
    (
        StatusCode::SERVICE_UNAVAILABLE,
        Json(ApiResponse::error("Ban manager not configured")),
    )
}

// ==================== 配额管理 ====================

/// 更新配额请求
#[derive(Deserialize)]
pub struct UpdateQuotaRequest {
    pub resource: String,
    pub new_limit: u64,
    #[serde(default)]
    pub duration_secs: Option<u64>,
}

/// 更新配额响应
#[derive(Serialize)]
pub struct UpdateQuotaResponse {
    pub success: bool,
    pub expires_at: Option<u64>,
}

/// PUT /api/v1/quota/{tenant_id}
///
/// 状态码:200=成功, 400=不支持的操作, 503=未配置, 500=内部错误
#[cfg(feature = "quota-control")]
pub async fn update_quota(
    State(state): State<AppState>,
    Path(tenant_id): Path<String>,
    Json(req): Json<UpdateQuotaRequest>,
) -> (StatusCode, Json<ApiResponse<UpdateQuotaResponse>>) {
    let Some(ref quota_controller) = state.quota_controller else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiResponse::error("Quota controller not configured")),
        );
    };
    // QuotaController 当前不支持 per-tenant 配额上限更新(配额上限为全局 QuotaConfig)
    // 提供重置配额使用量作为最接近的操作
    if req.new_limit == 0 {
        // new_limit=0 视为重置信号
        match quota_controller
            .reset_quota(&tenant_id, &req.resource)
            .await
        {
            Ok(_) => (
                StatusCode::OK,
                Json(ApiResponse::ok(UpdateQuotaResponse {
                    success: true,
                    expires_at: req.duration_secs.map(|d| {
                        use std::time::{SystemTime, UNIX_EPOCH};
                        SystemTime::now()
                            .duration_since(UNIX_EPOCH)
                            .map(|t| t.as_secs() + d)
                            .unwrap_or(0)
                    }),
                })),
            ),
            Err(e) => (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiResponse::error(format!("Failed to reset quota: {}", e))),
            ),
        }
    } else {
        (
            StatusCode::BAD_REQUEST,
            Json(ApiResponse::error(
                "Per-tenant quota limit update is not supported; use global QuotaConfig update_config instead",
            )),
        )
    }
}

/// PUT /api/v1/quota/{tenant_id} (无quota-control特性)
#[cfg(not(feature = "quota-control"))]
pub async fn update_quota(
    Path(_tenant_id): Path<String>,
) -> (StatusCode, Json<ApiResponse<UpdateQuotaResponse>>) {
    (
        StatusCode::SERVICE_UNAVAILABLE,
        Json(ApiResponse::error("Quota controller not configured")),
    )
}

// ==================== 熔断器状态 ====================

/// 熔断器状态响应
#[derive(Serialize)]
pub struct CircuitBreakerStatus {
    pub state: String,
    pub failure_rate: f64,
    pub slow_call_rate: f64,
}

/// GET /api/v1/status/circuit-breaker
///
/// 状态码:200=成功, 503=未配置
#[cfg(feature = "circuit-breaker")]
pub async fn get_circuit_breaker_status(
    State(state): State<AppState>,
) -> (StatusCode, Json<ApiResponse<CircuitBreakerStatus>>) {
    if let Some(ref cb) = state.circuit_breaker {
        let stats = cb.get_stats().await;
        let total = stats.total_calls as f64;
        // CircuitBreakerStats 不跟踪 slow_call_rate,置为 0.0
        let failure_rate = if total > 0.0 {
            stats.failure_count as f64 / total
        } else {
            0.0
        };
        (
            StatusCode::OK,
            Json(ApiResponse::ok(CircuitBreakerStatus {
                state: stats.state.to_string(),
                failure_rate,
                slow_call_rate: 0.0,
            })),
        )
    } else {
        (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiResponse::error("Circuit breaker not configured")),
        )
    }
}

/// GET /api/v1/status/circuit-breaker (无circuit-breaker特性)
#[cfg(not(feature = "circuit-breaker"))]
pub async fn get_circuit_breaker_status() -> (StatusCode, Json<ApiResponse<()>>) {
    (
        StatusCode::SERVICE_UNAVAILABLE,
        Json(ApiResponse::error("Circuit breaker not configured")),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::admin::AppState;
    use crate::admin::{make_governor, make_state};
    use std::sync::Arc;

    #[test]
    fn test_api_response_ok_contains_data() {
        let resp: ApiResponse<i32> = ApiResponse::ok(42);
        assert!(resp.success);
        assert_eq!(resp.message, "OK");
        assert_eq!(resp.data, Some(42));
    }

    #[test]
    fn test_api_response_error_has_no_data() {
        let resp: ApiResponse<i32> = ApiResponse::error("something failed");
        assert!(!resp.success);
        assert_eq!(resp.message, "something failed");
        assert_eq!(resp.data, None);
    }

    #[test]
    fn test_api_response_error_accepts_string_and_str() {
        let owned = String::from("owned error");
        let resp1: ApiResponse<i32> = ApiResponse::error(owned);
        assert_eq!(resp1.message, "owned error");

        let resp2: ApiResponse<i32> = ApiResponse::error("borrowed error");
        assert_eq!(resp2.message, "borrowed error");
    }

    // ========================================================================
    // Handler 集成测试
    // ========================================================================

    #[tokio::test]
    async fn test_get_status_empty_governor() {
        let state = make_state().await;
        let resp = get_status(State(state)).await;
        assert!(resp.0.success);
        let data = resp.0.data.unwrap();
        assert_eq!(data.total_requests, 0);
        assert_eq!(data.blocked_requests, 0);
        assert_eq!(data.success_rate, 1.0);
    }

    #[cfg(feature = "ban-manager")]
    #[tokio::test]
    async fn test_delete_ban_no_manager() {
        let state = make_state().await;
        let req = UnbanRequest {
            reason: None,
            operator: None,
        };
        let resp = delete_ban(
            State(state),
            Extension(OperatorIdentity("tester".to_string())),
            Path("192.168.1.1".to_string()),
            Query(Default::default()),
            Json(req),
        )
        .await;
        assert!(!resp.1.0.success);
        assert_eq!(resp.1.0.message, "Ban manager not configured");
    }

    #[cfg(feature = "ban-manager")]
    #[tokio::test]
    async fn test_delete_ban_with_manager_ip_target() {
        use crate::BanManager;
        let ban_manager = Arc::new(BanManager::new().await.unwrap());
        let governor = Arc::new(make_governor().await);
        let state = AppState {
            governor,
            ban_manager: Some(ban_manager),
            #[cfg(feature = "quota-control")]
            quota_controller: None,
            #[cfg(feature = "circuit-breaker")]
            circuit_breaker: None,
            #[cfg(feature = "monitoring")]
            metrics: None,
        };
        // 未封禁的 IP → Ban not found
        let req = UnbanRequest {
            reason: Some("test".to_string()),
            operator: Some("tester".to_string()),
        };
        let resp = delete_ban(
            State(state),
            Extension(OperatorIdentity("tester".to_string())),
            Path("192.168.1.1".to_string()),
            Query(Default::default()),
            Json(req),
        )
        .await;
        assert!(!resp.1.0.success);
        assert_eq!(resp.1.0.message, "Ban not found");
    }

    #[cfg(feature = "ban-manager")]
    #[tokio::test]
    async fn test_delete_ban_with_manager_userid_target() {
        use crate::BanManager;
        let ban_manager = Arc::new(BanManager::new().await.unwrap());
        let governor = Arc::new(make_governor().await);
        let state = AppState {
            governor,
            ban_manager: Some(ban_manager),
            #[cfg(feature = "quota-control")]
            quota_controller: None,
            #[cfg(feature = "circuit-breaker")]
            circuit_breaker: None,
            #[cfg(feature = "monitoring")]
            metrics: None,
        };
        // 非 IP 字符串 → UserId 目标
        let req = UnbanRequest {
            reason: None,
            operator: None,
        };
        let resp = delete_ban(
            State(state),
            Extension(OperatorIdentity("tester".to_string())),
            Path("user-123".to_string()),
            Query(Default::default()),
            Json(req),
        )
        .await;
        assert!(!resp.1.0.success);
        assert_eq!(resp.1.0.message, "Ban not found");
    }

    #[cfg(feature = "quota-control")]
    #[tokio::test]
    async fn test_update_quota_no_controller() {
        let state = make_state().await;
        let req = UpdateQuotaRequest {
            resource: "api".to_string(),
            new_limit: 0,
            duration_secs: None,
        };
        let resp = update_quota(State(state), Path("tenant-1".to_string()), Json(req)).await;
        assert!(!resp.1.0.success);
        assert_eq!(resp.1.0.message, "Quota controller not configured");
    }

    #[cfg(feature = "quota-control")]
    #[tokio::test]
    async fn test_update_quota_unsupported_limit() {
        use crate::QuotaController;
        use crate::cache::CacheQuotaStorage;
        use crate::quota::QuotaConfig;
        use crate::storage::QuotaStorage;
        use oxcache::backend::memory::DashMapMemoryBackend;
        let storage: Arc<dyn QuotaStorage> = Arc::new(CacheQuotaStorage::new(Arc::new(
            DashMapMemoryBackend::new(),
        )));
        let quota_controller = Arc::new(QuotaController::with_dependencies(
            storage,
            QuotaConfig::default(),
        ));
        let governor = Arc::new(make_governor().await);
        let state = AppState {
            governor,
            #[cfg(feature = "ban-manager")]
            ban_manager: None,
            quota_controller: Some(quota_controller),
            #[cfg(feature = "circuit-breaker")]
            circuit_breaker: None,
            #[cfg(feature = "monitoring")]
            metrics: None,
        };
        // new_limit > 0 → 不支持
        let req = UpdateQuotaRequest {
            resource: "api".to_string(),
            new_limit: 100,
            duration_secs: None,
        };
        let resp = update_quota(State(state), Path("tenant-1".to_string()), Json(req)).await;
        assert!(!resp.1.0.success);
        assert!(resp.1.0.message.contains("not supported"));
    }

    #[cfg(feature = "circuit-breaker")]
    #[tokio::test]
    async fn test_get_circuit_breaker_status_no_cb() {
        let state = make_state().await;
        let resp = get_circuit_breaker_status(State(state)).await;
        assert!(!resp.1.0.success);
        assert_eq!(resp.1.0.message, "Circuit breaker not configured");
    }

    #[cfg(feature = "circuit-breaker")]
    #[tokio::test]
    async fn test_get_circuit_breaker_status_with_cb() {
        use crate::circuit::{CircuitBreaker, CircuitBreakerConfig};
        let cb = Arc::new(CircuitBreaker::with_dependencies(
            CircuitBreakerConfig::default(),
        ));
        let governor = Arc::new(make_governor().await);
        let state = AppState {
            governor,
            #[cfg(feature = "ban-manager")]
            ban_manager: None,
            #[cfg(feature = "quota-control")]
            quota_controller: None,
            circuit_breaker: Some(cb),
            #[cfg(feature = "monitoring")]
            metrics: None,
        };
        let resp = get_circuit_breaker_status(State(state)).await;
        assert!(resp.1.0.success);
        let data = resp.1.0.data.unwrap();
        assert_eq!(data.failure_rate, 0.0);
        assert_eq!(data.slow_call_rate, 0.0);
    }

    #[cfg(feature = "ban-manager")]
    #[tokio::test]
    async fn test_get_status_with_ban_manager_and_cb() {
        use crate::BanManager;
        use crate::circuit::{CircuitBreaker, CircuitBreakerConfig};
        let ban_manager = Arc::new(BanManager::new().await.unwrap());
        let cb = Arc::new(CircuitBreaker::with_dependencies(
            CircuitBreakerConfig::default(),
        ));
        let governor = Arc::new(make_governor().await);
        let state = AppState {
            governor,
            ban_manager: Some(ban_manager),
            #[cfg(feature = "quota-control")]
            quota_controller: None,
            circuit_breaker: Some(cb),
            #[cfg(feature = "monitoring")]
            metrics: None,
        };
        let resp = get_status(State(state)).await;
        assert!(resp.0.success);
        let data = resp.0.data.unwrap();
        assert_eq!(data.active_bans, 0);
        assert!(!data.circuit_breaker.is_empty());
    }

    #[cfg(feature = "ban-manager")]
    #[tokio::test]
    async fn test_delete_ban_success() {
        use crate::BanManager;
        use crate::ban::BanTarget;
        use crate::storage::BanRecord;
        let ban_manager = Arc::new(BanManager::new().await.unwrap());
        // 先添加一条封禁
        let target = BanTarget::Ip("10.0.0.1".to_string());
        let now = chrono::Utc::now();
        ban_manager
            .add_ban(BanRecord {
                target: target.clone(),
                ban_times: 1,
                duration: std::time::Duration::from_secs(3600),
                banned_at: now,
                expires_at: now + chrono::Duration::seconds(3600),
                is_manual: true,
                reason: "test ban".to_string(),
            })
            .await
            .unwrap();
        let governor = Arc::new(make_governor().await);
        let state = AppState {
            governor,
            ban_manager: Some(ban_manager),
            #[cfg(feature = "quota-control")]
            quota_controller: None,
            #[cfg(feature = "circuit-breaker")]
            circuit_breaker: None,
            #[cfg(feature = "monitoring")]
            metrics: None,
        };
        let req = UnbanRequest {
            reason: Some("manual unban".to_string()),
            operator: Some("admin".to_string()),
        };
        let resp = delete_ban(
            State(state),
            Extension(OperatorIdentity("admin".to_string())),
            Path("10.0.0.1".to_string()),
            Query(Default::default()),
            Json(req),
        )
        .await;
        assert!(resp.1.0.success);
        assert_eq!(resp.1.0.message, "manual unban");
    }

    #[cfg(feature = "ban-manager")]
    #[tokio::test]
    async fn test_delete_ban_mac_with_explicit_type() {
        use crate::BanManager;
        use crate::ban::BanTarget;
        use crate::storage::BanRecord;
        let ban_manager = Arc::new(BanManager::new().await.unwrap());
        // 通过 API 创建的 MAC 封禁,仅能通过 ?type=mac 解封
        let target = BanTarget::Mac("00:1a:2b:3c:4d:5e".to_string());
        let now = chrono::Utc::now();
        ban_manager
            .add_ban(BanRecord {
                target: target.clone(),
                ban_times: 1,
                duration: std::time::Duration::from_secs(3600),
                banned_at: now,
                expires_at: now + chrono::Duration::seconds(3600),
                is_manual: true,
                reason: "mac ban".to_string(),
            })
            .await
            .unwrap();
        let governor = Arc::new(make_governor().await);
        let state = AppState {
            governor,
            ban_manager: Some(ban_manager),
            #[cfg(feature = "quota-control")]
            quota_controller: None,
            #[cfg(feature = "circuit-breaker")]
            circuit_breaker: None,
            #[cfg(feature = "monitoring")]
            metrics: None,
        };
        // ?type=mac 显式指定 → 成功解封
        let req = UnbanRequest {
            reason: Some("mac unban".to_string()),
            operator: Some("admin".to_string()),
        };
        let query = Query(BanTargetQuery {
            target_type: Some("mac".to_string()),
        });
        let resp = delete_ban(
            State(state),
            Extension(OperatorIdentity("admin".to_string())),
            Path("00:1a:2b:3c:4d:5e".to_string()),
            query,
            Json(req),
        )
        .await;
        assert!(resp.1.0.success);
        assert_eq!(resp.1.0.message, "mac unban");
    }

    #[cfg(feature = "ban-manager")]
    #[tokio::test]
    async fn test_delete_ban_geo_with_explicit_type() {
        use crate::BanManager;
        use crate::ban::BanTarget;
        use crate::storage::BanRecord;
        let ban_manager = Arc::new(BanManager::new().await.unwrap());
        // 通过 API 创建的 Geo 封禁,仅能通过 ?type=geo 解封
        let target = BanTarget::Geo {
            country_code: "CN".to_string(),
        };
        let now = chrono::Utc::now();
        ban_manager
            .add_ban(BanRecord {
                target: target.clone(),
                ban_times: 1,
                duration: std::time::Duration::from_secs(3600),
                banned_at: now,
                expires_at: now + chrono::Duration::seconds(3600),
                is_manual: true,
                reason: "geo ban".to_string(),
            })
            .await
            .unwrap();
        let governor = Arc::new(make_governor().await);
        let state = AppState {
            governor,
            ban_manager: Some(ban_manager),
            #[cfg(feature = "quota-control")]
            quota_controller: None,
            #[cfg(feature = "circuit-breaker")]
            circuit_breaker: None,
            #[cfg(feature = "monitoring")]
            metrics: None,
        };
        // ?type=geo 显式指定 → 成功解封
        let req = UnbanRequest {
            reason: Some("geo unban".to_string()),
            operator: Some("admin".to_string()),
        };
        let query = Query(BanTargetQuery {
            target_type: Some("geo".to_string()),
        });
        let resp = delete_ban(
            State(state),
            Extension(OperatorIdentity("admin".to_string())),
            Path("CN".to_string()),
            query,
            Json(req),
        )
        .await;
        assert!(resp.1.0.success);
        assert_eq!(resp.1.0.message, "geo unban");
    }

    #[cfg(feature = "ban-manager")]
    #[tokio::test]
    async fn test_delete_ban_unsupported_target_type_returns_400() {
        use crate::BanManager;
        let ban_manager = Arc::new(BanManager::new().await.unwrap());
        let governor = Arc::new(make_governor().await);
        let state = AppState {
            governor,
            ban_manager: Some(ban_manager),
            #[cfg(feature = "quota-control")]
            quota_controller: None,
            #[cfg(feature = "circuit-breaker")]
            circuit_breaker: None,
            #[cfg(feature = "monitoring")]
            metrics: None,
        };
        // ?type=foo 不支持 → 400 BAD_REQUEST
        let req = UnbanRequest {
            reason: None,
            operator: None,
        };
        let query = Query(BanTargetQuery {
            target_type: Some("foo".to_string()),
        });
        let (status, resp) = delete_ban(
            State(state),
            Extension(OperatorIdentity("tester".to_string())),
            Path("1.2.3.4".to_string()),
            query,
            Json(req),
        )
        .await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert!(!resp.0.success);
        assert!(resp.0.message.contains("unsupported target type: foo"));
    }

    #[cfg(feature = "ban-manager")]
    #[tokio::test]
    async fn test_delete_ban_mac_without_type_falls_back_to_userid() {
        use crate::BanManager;
        use crate::ban::BanTarget;
        use crate::storage::BanRecord;
        let ban_manager = Arc::new(BanManager::new().await.unwrap());
        // 创建 MAC 封禁
        let target = BanTarget::Mac("aa:bb:cc:dd:ee:ff".to_string());
        let now = chrono::Utc::now();
        ban_manager
            .add_ban(BanRecord {
                target: target.clone(),
                ban_times: 1,
                duration: std::time::Duration::from_secs(3600),
                banned_at: now,
                expires_at: now + chrono::Duration::seconds(3600),
                is_manual: true,
                reason: "mac ban".to_string(),
            })
            .await
            .unwrap();
        let governor = Arc::new(make_governor().await);
        let state = AppState {
            governor,
            ban_manager: Some(ban_manager),
            #[cfg(feature = "quota-control")]
            quota_controller: None,
            #[cfg(feature = "circuit-breaker")]
            circuit_breaker: None,
            #[cfg(feature = "monitoring")]
            metrics: None,
        };
        // 不指定 type → 自动推断为 UserId(MAC 字符串不是合法 IP)→ 404 NOT_FOUND
        // 这验证了 ?type=mac 是解封 MAC 的必要条件(修复前的 bug 复现)
        let req = UnbanRequest {
            reason: None,
            operator: None,
        };
        let (status, resp) = delete_ban(
            State(state),
            Extension(OperatorIdentity("tester".to_string())),
            Path("aa:bb:cc:dd:ee:ff".to_string()),
            Query(Default::default()),
            Json(req),
        )
        .await;
        assert_eq!(status, StatusCode::NOT_FOUND);
        assert_eq!(resp.0.message, "Ban not found");
    }

    #[cfg(feature = "quota-control")]
    #[tokio::test]
    async fn test_update_quota_reset_success() {
        use crate::QuotaController;
        use crate::cache::CacheQuotaStorage;
        use crate::quota::QuotaConfig;
        use crate::storage::QuotaStorage;
        use oxcache::backend::memory::DashMapMemoryBackend;
        let storage: Arc<dyn QuotaStorage> = Arc::new(CacheQuotaStorage::new(Arc::new(
            DashMapMemoryBackend::new(),
        )));
        let quota_controller = Arc::new(QuotaController::with_dependencies(
            storage,
            QuotaConfig::default(),
        ));
        let governor = Arc::new(make_governor().await);
        let state = AppState {
            governor,
            #[cfg(feature = "ban-manager")]
            ban_manager: None,
            quota_controller: Some(quota_controller),
            #[cfg(feature = "circuit-breaker")]
            circuit_breaker: None,
            #[cfg(feature = "monitoring")]
            metrics: None,
        };
        let req = UpdateQuotaRequest {
            resource: "api".to_string(),
            new_limit: 0,
            duration_secs: Some(3600),
        };
        let resp = update_quota(State(state), Path("tenant-1".to_string()), Json(req)).await;
        assert!(resp.1.0.success);
        let data = resp.1.0.data.unwrap();
        assert!(data.expires_at.is_some());
    }

    #[cfg(feature = "circuit-breaker")]
    #[tokio::test]
    async fn test_get_circuit_breaker_status_with_failures() {
        use crate::circuit::{CircuitBreaker, CircuitBreakerConfig};
        use crate::error::{LimiteronError, StorageError};
        let cb = Arc::new(CircuitBreaker::with_dependencies(
            CircuitBreakerConfig::default(),
        ));
        // 通过 execute 触发一次失败以覆盖 failure_rate > 0 分支
        // 使用 ConnectionError(transient)才会被 DefaultErrorClassifier 计为失败
        let _ = cb
            .execute(|| async {
                Err::<(), LimiteronError>(LimiteronError::StorageError(
                    StorageError::ConnectionError("test".to_string()),
                ))
            })
            .await;
        let governor = Arc::new(make_governor().await);
        let state = AppState {
            governor,
            #[cfg(feature = "ban-manager")]
            ban_manager: None,
            #[cfg(feature = "quota-control")]
            quota_controller: None,
            circuit_breaker: Some(cb),
            #[cfg(feature = "monitoring")]
            metrics: None,
        };
        let resp = get_circuit_breaker_status(State(state)).await;
        assert!(resp.1.0.success);
        let data = resp.1.0.data.unwrap();
        assert!(data.failure_rate > 0.0);
    }

    // ========================================================================
    // 规则热更新 / 批量检查 / 批量令牌预取
    // ========================================================================

    /// 构造一条合法规则的最小配置(与 test_support::make_valid_config 同构)
    fn t613_valid_config() -> crate::config::FlowControlConfig {
        use crate::config::{Action, ActionConfig, LimiterConfig, Matcher, Rule};
        crate::config::FlowControlConfig {
            version: "1.0.1".to_string(),
            global: crate::config::GlobalConfig::default(),
            rules: vec![Rule {
                id: "hot_rule".to_string(),
                name: "Hot Rule".to_string(),
                priority: 50,
                matchers: vec![Matcher::User {
                    user_ids: vec!["*".to_string()],
                }],
                limiters: vec![LimiterConfig::TokenBucket {
                    capacity: 1000,
                    refill_rate: 100,
                }],
                action: ActionConfig {
                    on_exceed: Action::Reject,
                    ban: None,
                },
            }],
        }
    }

    #[tokio::test]
    async fn test_t613_apply_config_swaps_rules() {
        let state = make_state().await;
        // 换入新配置(新规则 ID)
        let resp = apply_config(State(state.clone()), Json(t613_valid_config())).await;
        assert_eq!(resp.0, StatusCode::OK, "{:?}", resp.1.0.message);
        assert!(resp.1.0.success);
        let data = resp.1.0.data.unwrap();
        assert_eq!(data["applied"], serde_json::json!(true));
        assert_eq!(data["new_version"], serde_json::json!("1.0.1"));
        assert_eq!(data["rule_count"], serde_json::json!(1));

        // 自省应反映新规则 ID(换装真实生效,非仅换 config 句柄)
        let snap = state.governor.introspect().await;
        assert!(
            snap.rules.iter().any(|r| r.id == "hot_rule"),
            "hot-swapped rule must be visible in introspection"
        );
        // 配置历史应记录本次 API 换装
        let history = state.governor.get_config_history().await;
        assert!(
            history.iter().any(|rec| rec.new_version == "1.0.1"),
            "apply_config must record config history"
        );
    }

    #[tokio::test]
    async fn test_t613_apply_config_rejects_invalid_and_rolls_back() {
        let state = make_state().await;
        // 非法配置:rules 为空 → validate 报错 → 400 且旧配置保留
        let mut bad = t613_valid_config();
        bad.rules.clear();
        let resp = apply_config(State(state.clone()), Json(bad)).await;
        assert_eq!(resp.0, StatusCode::BAD_REQUEST);
        assert!(!resp.1.0.success);

        // 自省仍是旧配置的规则(test_rule),未被空配置替换
        let snap = state.governor.introspect().await;
        assert!(
            snap.rules.iter().any(|r| r.id == "test_rule"),
            "invalid apply must keep old config (rollback semantics)"
        );
    }

    #[tokio::test]
    async fn test_t613_check_batch_decides_all_keys() {
        let state = make_state().await;
        let body = BatchCheckBody {
            requests: vec![
                BatchCheckItem {
                    user_id: Some("batch-user-1".to_string()),
                    ip: None,
                    path: Some("/api".to_string()),
                    method: Some("GET".to_string()),
                },
                BatchCheckItem {
                    user_id: Some("batch-user-2".to_string()),
                    ip: None,
                    path: Some("/api".to_string()),
                    method: Some("GET".to_string()),
                },
            ],
        };
        let resp = check_batch(State(state), Json(body)).await;
        assert_eq!(resp.0, StatusCode::OK);
        assert!(resp.1.0.success);
        let data = resp.1.0.data.unwrap();
        let results = data["results"].as_array().unwrap();
        assert_eq!(results.len(), 2, "one decision per key");
        assert_eq!(results[0]["index"], serde_json::json!(0));
        assert_eq!(results[1]["index"], serde_json::json!(1));
        assert_eq!(results[0]["decision"], serde_json::json!("Allowed"));
    }

    #[tokio::test]
    async fn test_t613_check_batch_empty_body_rejected() {
        let state = make_state().await;
        let body = BatchCheckBody { requests: vec![] };
        let resp = check_batch(State(state), Json(body)).await;
        assert_eq!(resp.0, StatusCode::BAD_REQUEST);
        assert!(!resp.1.0.success);
    }

    #[tokio::test]
    async fn test_t613_check_batch_over_limit_rejected() {
        let state = make_state().await;
        let body = BatchCheckBody {
            requests: (0..=BATCH_MAX_ITEMS)
                .map(|_| BatchCheckItem {
                    user_id: Some("u".to_string()),
                    ip: None,
                    path: None,
                    method: None,
                })
                .collect(),
        };
        let resp = check_batch(State(state), Json(body)).await;
        assert_eq!(resp.0, StatusCode::BAD_REQUEST, "over-limit batch → 400");
    }

    #[tokio::test]
    async fn test_t613_prefetch_tokens_grants_batch() {
        let body = TokenPrefetchBody {
            items: vec![
                TokenPrefetchItem {
                    key: "pf-key-1".to_string(),
                    tokens: 5,
                },
                TokenPrefetchItem {
                    key: "pf-key-2".to_string(),
                    tokens: 5,
                },
            ],
        };
        let resp = prefetch_tokens(Json(body)).await;
        assert_eq!(resp.0, StatusCode::OK);
        assert!(resp.1.0.success);
        assert_eq!(resp.1.0.message, "2/2 granted");
        let data = resp.1.0.data.unwrap();
        let results = data.as_array().unwrap();
        assert_eq!(results.len(), 2);
        assert_eq!(results[0]["granted"], serde_json::json!(true));
    }

    #[tokio::test]
    async fn test_t613_prefetch_tokens_empty_rejected() {
        let body = TokenPrefetchBody { items: vec![] };
        let resp = prefetch_tokens(Json(body)).await;
        assert_eq!(resp.0, StatusCode::BAD_REQUEST);
    }
}