yang-base 0.6.0

个人使用构建后端服务器
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
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
//! Axum 0.8 HTTP 传输适配器。
//!
//! 把冻结的 [`BuiltApp`] 一次性暴露为生产可用的 HTTP 服务:
//!
//! - 启动时从 Catalog 逐 Action 生成真实路由(方法 + 路径模板),请求期零字符串查找;
//! - 请求体上限(413)、非法 JSON / query(400)在派发前拒绝;
//! - `x-request-id` 上游透传(沿用 [`RequestId::parse_hex`] 语义,失败则新生成);
//! - 成功状态码按 Action 声明的 `success_status`,错误按 [`BaseError`] 类别映射,
//!   5xx 对外统一遮蔽 message(内部细节只进 tracing);
//! - [`ResponseAttachment`] 映射:文件下载 / 预览 / 302 重定向;
//! - tower-http 横切:tracing、显式白名单 CORS、超时、压缩;
//! - `/health/live` 与 `/health/ready`(对接 [`Tools::health_check`](crate::tools::Tools))。
//!
//! # 示例
//!
//! ```rust,ignore
//! use std::sync::Arc;
//! use yang_base::transport::axum::{serve, AxumTransportConfig};
//!
//! let app = Arc::new(build_app()?);
//! serve("0.0.0.0:8080".parse()?, app, AxumTransportConfig::default()).await?;
//! ```

use crate::action::{
    ApiResponse, Request, RequestId, RequestMeta, ResponseAttachment, TENANT_ID_HEADER,
};
use crate::definition::{
    schema_subtree_contains_binary, ActionHandle, ActionMediaType, ActionRef, BuiltApp,
    MultipartSpec,
};
use crate::error::{BaseError, ErrorCategory};
use axum::body::{to_bytes, Body};
use axum::error_handling::HandleErrorLayer;
use axum::extract::{
    ConnectInfo, DefaultBodyLimit, FromRequest, MatchedPath, Multipart, Path,
    Request as AxumRequest, State,
};
use axum::http::{header, HeaderName, HeaderValue, Method, StatusCode};
use axum::middleware::{self, Next};
use axum::response::{IntoResponse, Response};
use axum::routing::{on, MethodFilter};
use axum::{BoxError, Json, Router};
use serde_json::json;
use serde_json::{map::Entry, Map, Value};
use std::collections::HashMap;
use std::future::Future;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::io::AsyncWriteExt;
use tower::limit::GlobalConcurrencyLimitLayer;
use tower::load_shed::LoadShedLayer;
use tower::ServiceBuilder;
use tower_http::compression::CompressionLayer;
use tower_http::cors::{Any, CorsLayer};
use tracing::Instrument;

/// 默认请求体上限:2 MiB。
const DEFAULT_MAX_BODY_BYTES: usize = 2 * 1024 * 1024;

/// 默认单附件响应字节上限:64 MiB。
const DEFAULT_MAX_ATTACHMENT_BYTES: u64 = 64 * 1024 * 1024;

/// CORS 配置(显式白名单语义)。
///
/// 安全约束在构建期强制:`origins` 含 `"*"` 时禁止同时开启 `credentials`
/// (该组合被浏览器规范拒绝,且是常见的配置性安全事故)。
#[derive(Debug, Clone)]
pub struct CorsConfig {
    /// 允许的来源白名单;空列表表示不启用 CORS 层;`["*"]` 表示任意来源。
    pub origins: Vec<String>,
    /// 允许的方法。
    pub methods: Vec<String>,
    /// 允许的请求头。
    pub headers: Vec<String>,
    /// 是否允许携带凭据(Cookie / Authorization)。
    pub credentials: bool,
    /// 预检结果缓存秒数。
    pub max_age_secs: u64,
}

impl Default for CorsConfig {
    fn default() -> Self {
        Self {
            origins: Vec::new(),
            methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]
                .iter()
                .map(|method| (*method).to_string())
                .collect(),
            headers: [
                "content-type",
                "authorization",
                "x-request-id",
                "x-step-up-proof",
                TENANT_ID_HEADER,
            ]
            .iter()
            .map(|name| (*name).to_string())
            .collect(),
            credentials: false,
            max_age_secs: 86400,
        }
    }
}

/// Axum 传输配置。
#[derive(Debug, Clone)]
pub struct AxumTransportConfig {
    /// 请求体字节上限;超过返回 413。默认 2 MiB。
    pub max_body_bytes: usize,
    /// JSON 请求体独立上限;`None` 沿用 `max_body_bytes`,不得大于总量上限。
    pub max_json_body_bytes: Option<usize>,
    /// CORS 配置;默认不启用 CORS 层。
    pub cors: CorsConfig,
    /// 单请求总超时;`None`(默认)关闭超时层。
    pub request_timeout: Option<Duration>,
    /// 同时进入应用的最大请求数;`None`(默认)不额外限制。
    ///
    /// 所有路径、方法和 Router 克隆共享容量,超出立即返回 503,不排队。
    pub max_concurrency: Option<usize>,
    /// 是否按 `Accept-Encoding` 协商压缩响应。默认开启。
    pub compression: bool,
    /// 单个附件响应的字节上限;超过返回 413。`None` 表示不限制。
    pub max_attachment_bytes: Option<u64>,
}

impl Default for AxumTransportConfig {
    fn default() -> Self {
        Self {
            max_body_bytes: DEFAULT_MAX_BODY_BYTES,
            max_json_body_bytes: None,
            cors: CorsConfig::default(),
            request_timeout: None,
            max_concurrency: None,
            compression: true,
            max_attachment_bytes: Some(DEFAULT_MAX_ATTACHMENT_BYTES),
        }
    }
}

/// 路由共享状态。
#[derive(Clone)]
struct HttpState {
    app: Arc<BuiltApp>,
    /// 实际监听地址(`serve` 填入;`router` 单独构建时为 None)。
    local_addr: Option<SocketAddr>,
    max_body_bytes: usize,
    max_json_body_bytes: usize,
    max_attachment_bytes: Option<u64>,
}

#[derive(Clone)]
enum RequestDecoder {
    Json,
    Multipart {
        // spec / input_schema 在路由构建期一次成型、之后只读,改持 Arc 后
        // `decoder.clone()`(每个请求一次)只做引用计数自增,不再深拷贝 Schema 与
        // allowed_content_types;多请求之间共享的仍是同一份不可变数据。
        spec: Arc<MultipartSpec>,
        input_schema: Arc<Value>,
    },
}

struct DecodedBody {
    value: Value,
    resource_guard: Option<Arc<tempfile::TempDir>>,
}

/// 由冻结应用构建 Axum [`Router`](不绑定端口,可用 tower `oneshot` 直接驱动测试)。
///
/// # 返回
///
/// - `Ok(Router)`:含健康端点、Catalog 全部 Action 路由与已配置横切层
/// - `Err(BaseError::ConfigError)`:CORS 配置非法(如通配来源 + credentials)、
///   Action 未预编译到 Registry、或路由方法不受支持
pub fn router(app: Arc<BuiltApp>, config: AxumTransportConfig) -> Result<Router, BaseError> {
    router_with_addr(app, config, None)
}

/// 绑定地址并启动 HTTP 服务,直至收到关闭信号(Ctrl+C 或 Unix SIGTERM)后优雅停机。
pub async fn serve(
    bind: SocketAddr,
    app: Arc<BuiltApp>,
    config: AxumTransportConfig,
) -> Result<(), BaseError> {
    serve_with_shutdown(
        bind,
        app,
        config,
        crate::lifecycle::wait_for_shutdown_signal(),
    )
    .await
}

/// 使用调用方提供的关闭触发器启动 HTTP 服务。
///
/// 与 [`serve`] 的唯一区别是信号所有权交给调用方,使上层可以从同一个关闭
/// 事件开始,为 HTTP drain、后台任务和资源释放共享一个进程级总预算。
pub async fn serve_with_shutdown<S>(
    bind: SocketAddr,
    app: Arc<BuiltApp>,
    config: AxumTransportConfig,
    shutdown: S,
) -> Result<(), BaseError>
where
    S: Future<Output = ()> + Send + 'static,
{
    let listener = tokio::net::TcpListener::bind(bind)
        .await
        .map_err(|error| BaseError::ConfigError(format!("绑定 HTTP 地址失败 {bind}: {error}")))?;
    serve_listener_with_shutdown(listener, app, config, shutdown).await
}

/// 服务调用方已经绑定的监听器,允许上层在确认端口占用成功后再开放 readiness。
pub async fn serve_listener_with_shutdown<S>(
    listener: tokio::net::TcpListener,
    app: Arc<BuiltApp>,
    config: AxumTransportConfig,
    shutdown: S,
) -> Result<(), BaseError>
where
    S: Future<Output = ()> + Send + 'static,
{
    let local_addr = listener
        .local_addr()
        .map_err(|error| BaseError::ConfigError(format!("读取 HTTP 监听地址失败: {error}")))?;
    let router = router_with_addr(app, config, Some(local_addr))?;
    tracing::info!(address = %local_addr, "HTTP 服务已启动");
    axum::serve(
        listener,
        router.into_make_service_with_connect_info::<SocketAddr>(),
    )
    .with_graceful_shutdown(shutdown)
    .await
    .map_err(|error| BaseError::ConfigError(format!("HTTP 服务运行失败: {error}")))
}

fn router_with_addr(
    app: Arc<BuiltApp>,
    config: AxumTransportConfig,
    local_addr: Option<SocketAddr>,
) -> Result<Router, BaseError> {
    let max_json_body_bytes = config.max_json_body_bytes.unwrap_or(config.max_body_bytes);
    if config.max_body_bytes == 0
        || max_json_body_bytes == 0
        || max_json_body_bytes > config.max_body_bytes
    {
        return Err(BaseError::ConfigError(
            "HTTP 请求体上限必须大于 0,JSON 上限不得超过总量上限".to_string(),
        ));
    }
    let state = HttpState {
        app,
        local_addr,
        max_body_bytes: config.max_body_bytes,
        max_json_body_bytes,
        max_attachment_bytes: config.max_attachment_bytes,
    };

    // 框架保留路由由 definition 侧的常量派生注册,禁止两处硬编码漂移。
    let mut router = Router::new();
    for &(method, path) in crate::definition::RESERVED_FRAMEWORK_ROUTES {
        debug_assert_eq!(method, "GET");
        router = match path {
            "/health/live" => router.route(path, axum::routing::get(live)),
            "/health/ready" => router.route(path, axum::routing::get(ready)),
            other => {
                return Err(BaseError::ConfigError(format!(
                    "框架保留路由缺少处理器: {other}"
                )))
            }
        };
    }

    for addon in state.app.catalog().addons() {
        for module in &addon.modules {
            for action in module.actions() {
                let method_filter = method_filter(action.route.method.as_str())?;
                let path = action.route.path.clone();
                let reference = ActionRef::new(module.name.clone(), action.name.clone());
                let handle = state.app.registry().resolve(&reference).ok_or_else(|| {
                    BaseError::ConfigError(format!("Action 未预编译到 Registry: {reference}"))
                })?;
                let success_status = action.success_status;
                let (decoder, body_limit) = match action.request_media_type {
                    ActionMediaType::Json => (RequestDecoder::Json, state.max_json_body_bytes),
                    ActionMediaType::Multipart => {
                        let spec = action.multipart.clone().ok_or_else(|| {
                            BaseError::ConfigError(format!(
                                "multipart Action 缺少资源限制: {reference}"
                            ))
                        })?;
                        let action_limit = usize::try_from(spec.max_total_bytes).map_err(|_| {
                            BaseError::ConfigError(format!(
                                "multipart Action 请求上限超出平台 usize: {reference}"
                            ))
                        })?;
                        if action_limit > state.max_body_bytes {
                            return Err(BaseError::ConfigError(format!(
                                "multipart Action {reference} 的 max_total_bytes={} 超过 AxumTransportConfig.max_body_bytes={}",
                                spec.max_total_bytes, state.max_body_bytes
                            )));
                        }
                        (
                            RequestDecoder::Multipart {
                                // spec 已按值解构出来,直接 Arc::new 避免多一次 clone;
                                // input_schema 的深拷贝只发生在构建期(每路由一次),
                                // 请求期不再复制。
                                spec: Arc::new(spec),
                                input_schema: Arc::new(action.input_schema.clone()),
                            },
                            action_limit,
                        )
                    }
                };
                let method_router = on(
                    method_filter,
                    move |State(state): State<HttpState>,
                          ConnectInfo(peer): ConnectInfo<SocketAddr>,
                          Path(path_params): Path<HashMap<String, String>>,
                          request: AxumRequest| {
                        let decoder = decoder.clone();
                        async move {
                            dispatch_request(
                                state,
                                peer,
                                path_params,
                                request,
                                handle,
                                success_status,
                                decoder,
                            )
                            .await
                        }
                    },
                )
                .layer(DefaultBodyLimit::max(body_limit));
                router = router.route(&path, method_router);
            }
        }
    }

    let mut router = router
        .fallback(|| async {
            error_response(
                StatusCode::NOT_FOUND,
                BaseError::ActionNotFound("HTTP 路由".to_string()),
            )
        })
        .method_not_allowed_fallback(|| async {
            error_response(
                StatusCode::METHOD_NOT_ALLOWED,
                BaseError::ParamInvalid("method".to_string(), "请求方法不受支持".to_string()),
            )
        })
        .with_state(state);

    // 横切层:后调用者先生效;统计和 request ID 在最外层覆盖所有出口。
    if config.compression {
        router = router.layer(CompressionLayer::new());
    }
    if let Some(max_concurrency) = config.max_concurrency {
        if max_concurrency == 0 {
            return Err(BaseError::ConfigError(
                "HTTP max_concurrency 必须大于 0".to_string(),
            ));
        }
        // 必须在同一 ServiceBuilder:若分别 Router::layer,Axum Route 的
        // poll_ready 永远 Ready,会隐藏 permit 等待,让 LoadShed 静默失效。
        router = router.layer(
            ServiceBuilder::new()
                .layer(HandleErrorLayer::new(|_: BoxError| async {
                    (
                        StatusCode::SERVICE_UNAVAILABLE,
                        Json(ApiResponse::fail(
                            crate::error::NOT_READY_CODE,
                            "服务繁忙,请稍后重试",
                        )),
                    )
                        .into_response()
                }))
                .layer(LoadShedLayer::new())
                .layer(GlobalConcurrencyLimitLayer::new(max_concurrency)),
        );
    }
    if let Some(timeout) = config.request_timeout {
        router = router.layer(middleware::from_fn(
            move |request: AxumRequest, next: Next| async move {
                match tokio::time::timeout(timeout, next.run(request)).await {
                    Ok(response) => response,
                    Err(_) => error_response(StatusCode::REQUEST_TIMEOUT, BaseError::HttpTimeout),
                }
            },
        ));
    }
    if let Some(cors) = cors_layer(&config.cors)? {
        router = router.layer(cors);
    }
    Ok(router.layer(middleware::from_fn(observe_inbound_request)))
}

async fn observe_inbound_request(mut request: AxumRequest, next: Next) -> Response {
    let request_id = request
        .headers()
        .get("x-request-id")
        .and_then(|value| value.to_str().ok())
        .and_then(RequestId::parse_hex)
        .unwrap_or_default();
    request.extensions_mut().insert(request_id);
    // 只使用固定方法和匹配模板;未知路由不得把原始路径/query 变成日志或指标标签。
    let method = match *request.method() {
        Method::GET => "GET",
        Method::HEAD => "HEAD",
        Method::POST => "POST",
        Method::PUT => "PUT",
        Method::PATCH => "PATCH",
        Method::DELETE => "DELETE",
        Method::OPTIONS => "OPTIONS",
        Method::CONNECT => "CONNECT",
        Method::TRACE => "TRACE",
        _ => "OTHER",
    };
    let route = request
        .extensions()
        .get::<MatchedPath>()
        .map(|path| path.as_str())
        .unwrap_or("__unmatched")
        .to_string();
    let started = Instant::now();
    let span = tracing::info_span!("http.request", %request_id, method, route);
    let response = next.run(request).instrument(span).await;
    let elapsed = started.elapsed().as_secs_f64();
    let status = response.status().as_u16();
    tracing::info!(target: "yang_base::transport::http", %request_id, method, route, status, elapsed_seconds = elapsed, "HTTP 入站请求完成");
    #[cfg(feature = "metrics")]
    {
        let status = status.to_string();
        metrics::counter!("yang_http_inbound_requests_total", "method" => method, "route" => route.clone(), "status" => status.clone()).increment(1);
        metrics::histogram!("yang_http_inbound_request_duration_seconds", "method" => method, "route" => route, "status" => status).record(elapsed);
    }
    with_request_id_header(response, request_id)
}

/// 按 CORS 配置构建白名单层;空 origins 表示不启用。
fn cors_layer(config: &CorsConfig) -> Result<Option<CorsLayer>, BaseError> {
    if config.origins.is_empty() {
        return Ok(None);
    }
    let wildcard = config.origins.iter().any(|origin| origin == "*");
    if wildcard && config.credentials {
        return Err(BaseError::ConfigError(
            "CORS 禁止通配来源与 credentials 同用(浏览器规范拒绝该组合)".to_string(),
        ));
    }

    let methods = config
        .methods
        .iter()
        .map(|method| {
            Method::from_bytes(method.as_bytes()).map_err(|_| {
                BaseError::ConfigError(format!("CORS 配置包含非法 HTTP 方法: {method}"))
            })
        })
        .collect::<Result<Vec<_>, _>>()?;
    let headers = config
        .headers
        .iter()
        .map(|name| {
            HeaderName::from_bytes(name.as_bytes())
                .map_err(|_| BaseError::ConfigError(format!("CORS 配置包含非法请求头: {name}")))
        })
        .collect::<Result<Vec<_>, _>>()?;

    let layer = CorsLayer::new()
        .allow_methods(methods)
        .allow_headers(headers)
        .max_age(Duration::from_secs(config.max_age_secs));
    let layer = if wildcard {
        layer.allow_origin(Any)
    } else {
        let origins = config
            .origins
            .iter()
            .map(|origin| {
                HeaderValue::from_str(origin)
                    .map_err(|_| BaseError::ConfigError(format!("CORS 配置包含非法来源: {origin}")))
            })
            .collect::<Result<Vec<_>, _>>()?;
        layer.allow_origin(origins)
    };
    let layer = if config.credentials {
        layer.allow_credentials(true)
    } else {
        layer
    };
    Ok(Some(layer))
}

async fn live() -> impl IntoResponse {
    Json(ApiResponse::success_value(
        json!({"status": "live"}),
        "服务存活",
    ))
}

async fn ready(State(state): State<HttpState>) -> Response {
    let health = state.app.tools().health_check().await;
    if health.is_healthy() {
        (
            StatusCode::OK,
            Json(ApiResponse::success_value(
                json!({"status": "ready"}),
                "服务就绪",
            )),
        )
            .into_response()
    } else {
        tracing::warn!(?health, "就绪检查失败");
        (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiResponse::fail(
                crate::error::NOT_READY_CODE,
                "服务尚未就绪",
            )),
        )
            .into_response()
    }
}

async fn dispatch_request(
    state: HttpState,
    peer: SocketAddr,
    path_params: HashMap<String, String>,
    request: AxumRequest,
    handle: ActionHandle,
    success_status: u16,
    decoder: RequestDecoder,
) -> Response {
    let method = request.method().clone();
    let uri = request.uri().clone();
    let headers: HashMap<String, String> = request
        .headers()
        .iter()
        .filter_map(|(name, value)| {
            value
                .to_str()
                .ok()
                .map(|value| (name.as_str().to_string(), value.to_string()))
        })
        .collect();
    // 每个进入 Action 传输边界的请求都只有一个确定 request_id:合法上游值规范化
    // 后沿用,否则在读取请求体前生成。这样即使 query/body 解码失败,调用方仍能用
    // 响应头关联服务端日志。
    let request_id = request
        .extensions()
        .get::<RequestId>()
        .copied()
        .unwrap_or_default();
    let query = match uri.query() {
        Some(raw) => match parse_query_pairs(raw) {
            Ok(query) => query,
            Err(()) => {
                return with_request_id_header(
                    error_response(
                        StatusCode::BAD_REQUEST,
                        BaseError::ParamInvalid(
                            "query".to_string(),
                            "查询参数编码无效".to_string(),
                        ),
                    ),
                    request_id,
                );
            }
        },
        None => HashMap::new(),
    };
    let decoded = match decode_request_body(&state, request, decoder).await {
        Ok(decoded) => decoded,
        Err((status, error)) => {
            return with_request_id_header(error_response(status, error), request_id);
        }
    };

    let mut action_request = Request::new(decoded.value)
        .headers(headers)
        .queries(query)
        .path_params(path_params);
    if let Some(resource_guard) = decoded.resource_guard {
        action_request = action_request.retain_resource(resource_guard);
    }
    let request_meta = RequestMeta::new()
        .with_method(method.to_string())
        .with_original_uri(uri.to_string())
        .with_scheme(uri.scheme_str().unwrap_or("http"))
        .with_peer_addr(peer);
    let request_meta = match state.local_addr {
        Some(addr) => request_meta.with_local_addr(addr),
        None => request_meta,
    };
    let context = state
        .app
        .context(action_request)
        .with_request_meta(request_meta)
        .with_request_id(request_id);

    let response = match state.app.dispatch_context(handle, context).await {
        Ok(response) => {
            let status = response
                .http_status()
                .and_then(|status| StatusCode::from_u16(status).ok())
                .unwrap_or_else(|| StatusCode::from_u16(success_status).unwrap_or(StatusCode::OK));
            let response_headers = response.response_headers().to_vec();
            let mut http_response = match response.attachment.clone() {
                Some(attachment) => {
                    attachment_response(attachment, state.max_attachment_bytes).await
                }
                None => (status, Json(response)).into_response(),
            };
            if let Err(error) =
                append_action_response_headers(http_response.headers_mut(), &response_headers)
            {
                tracing::error!(error = %error, "Action 响应头无效");
                http_response = error_response(StatusCode::INTERNAL_SERVER_ERROR, error);
            }
            http_response
        }
        Err(error) => {
            let status = status_for_error(&error);
            if status.is_server_error() {
                log_dispatch_server_error(&error);
            }
            error_response(status, error)
        }
    };
    with_request_id_header(response, request_id)
}

/// 把 query 字符串解析为 `HashMap`,同名参数按 TS `URLSearchParams.get` 语义取第一个值。
///
/// `serde_urlencoded` 直接解码到 `HashMap` 时重复键由后者覆盖(last-wins),与原型相反;
/// 因此先解码为有序键值对,再逐对插入且不覆盖已有键。解析仍走同一个
/// `serde_urlencoded` 解析器,错误语义与空值 / 无值参数行为不变。
fn parse_query_pairs(raw: &str) -> Result<HashMap<String, String>, ()> {
    let pairs = serde_urlencoded::from_str::<Vec<(String, String)>>(raw).map_err(|_| ())?;
    let mut query = HashMap::with_capacity(pairs.len());
    for (key, value) in pairs {
        // first-wins:同名参数只保留首次出现的值。
        query.entry(key).or_insert(value);
    }
    Ok(query)
}

fn append_action_response_headers(
    target: &mut axum::http::HeaderMap,
    headers: &[(String, String)],
) -> Result<(), BaseError> {
    for (name, value) in headers {
        let name = HeaderName::from_bytes(name.as_bytes())
            .map_err(|_| BaseError::ConfigError("Action 响应头名称无效".to_string()))?;
        if matches!(
            name.as_str(),
            "content-length" | "transfer-encoding" | "connection" | "x-request-id"
        ) {
            return Err(BaseError::ConfigError(format!(
                "Action 不得覆盖传输层响应头: {name}"
            )));
        }
        let value = HeaderValue::from_str(value)
            .map_err(|_| BaseError::ConfigError("Action 响应头值无效".to_string()))?;
        target.append(name, value);
    }
    Ok(())
}

async fn decode_request_body(
    state: &HttpState,
    request: AxumRequest,
    decoder: RequestDecoder,
) -> Result<DecodedBody, (StatusCode, BaseError)> {
    match decoder {
        RequestDecoder::Json => {
            let body = to_bytes(request.into_body(), state.max_json_body_bytes)
                .await
                .map_err(|error| {
                    // to_bytes 内部有限性判定基于 http_body_util::Limited:只有真正超出
                    // max_json_body_bytes 时错误源才是 LengthLimitError(见 axum::body::to_bytes
                    // 文档);其余为底层 body 流失败(连接中止 / chunked 分帧损坏 / hyper IO 错误),
                    // 与 multipart 分支一致归入 400,不能冒充 413。
                    let limit_hit = std::error::Error::source(&error)
                        .is_some_and(|source| source.is::<http_body_util::LengthLimitError>());
                    if limit_hit {
                        (
                            StatusCode::PAYLOAD_TOO_LARGE,
                            BaseError::ParamInvalid("body".to_string(), "请求体过大".to_string()),
                        )
                    } else {
                        // 原始错误只进日志,不进响应体(400 的 message 会原样回给客户端)
                        tracing::warn!(error = %error, "读取请求体失败");
                        (
                            StatusCode::BAD_REQUEST,
                            BaseError::ParamInvalid(
                                "body".to_string(),
                                "请求体读取失败".to_string(),
                            ),
                        )
                    }
                })?;
            let value = if body.is_empty() {
                json!({})
            } else {
                serde_json::from_slice(&body).map_err(|_| {
                    (
                        StatusCode::BAD_REQUEST,
                        BaseError::ParamInvalid(
                            "body".to_string(),
                            "请求体必须是 JSON".to_string(),
                        ),
                    )
                })?
            };
            Ok(DecodedBody {
                value,
                resource_guard: None,
            })
        }
        RequestDecoder::Multipart { spec, input_schema } => {
            decode_multipart(state, request, &spec, &input_schema).await
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum MultipartPartKind {
    Text,
    File,
}

async fn decode_multipart(
    state: &HttpState,
    request: AxumRequest,
    spec: &MultipartSpec,
    input_schema: &Value,
) -> Result<DecodedBody, (StatusCode, BaseError)> {
    let content_type = request
        .headers()
        .get(header::CONTENT_TYPE)
        .and_then(|value| value.to_str().ok())
        .unwrap_or_default();
    let media_type = content_type.split(';').next().unwrap_or_default().trim();
    if !media_type.eq_ignore_ascii_case("multipart/form-data") {
        // TS 原型 req.formData() 失败一律 400 INVALID_FORM,而不是 415;
        // 文案与原型逐字一致。
        return Err(multipart_error(
            StatusCode::BAD_REQUEST,
            "body",
            "请使用 multipart/form-data 上传文件",
        ));
    }
    if request
        .headers()
        .get(header::CONTENT_LENGTH)
        .and_then(|value| value.to_str().ok())
        .and_then(|value| value.parse::<u64>().ok())
        .is_some_and(|length| length > spec.max_total_bytes)
    {
        return Err(multipart_error(
            StatusCode::PAYLOAD_TOO_LARGE,
            "body",
            "multipart 请求体过大",
        ));
    }

    let scope = Arc::new(tempfile::tempdir().map_err(|error| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            BaseError::IoError(format!("创建上传临时目录失败: {error}")),
        )
    })?);
    let mut multipart = Multipart::from_request(request, state)
        .await
        .map_err(|rejection| {
            let status = rejection.status();
            let status = if status == StatusCode::PAYLOAD_TOO_LARGE {
                status
            } else {
                StatusCode::BAD_REQUEST
            };
            multipart_error(status, "body", "multipart 请求格式无效")
        })?;
    let mut body = Map::new();
    let mut kinds = HashMap::new();
    let mut field_count = 0_u16;
    let mut file_count = 0_u16;
    let mut payload_bytes = 0_u64;

    while let Some(mut field) = multipart.next_field().await.map_err(|error| {
        let status = error.status();
        let status = if status == StatusCode::PAYLOAD_TOO_LARGE {
            status
        } else {
            StatusCode::BAD_REQUEST
        };
        multipart_error(status, "body", "multipart 字段读取失败")
    })? {
        let name = field
            .name()
            .filter(|name| !name.is_empty() && name.len() <= 255)
            .map(str::to_string)
            .ok_or_else(|| {
                multipart_error(
                    StatusCode::BAD_REQUEST,
                    "body",
                    "multipart 字段名缺失或过长",
                )
            })?;
        let raw_filename = field.file_name().map(str::to_string);

        if let Some(raw_filename) = raw_filename {
            file_count = file_count.checked_add(1).ok_or_else(|| {
                multipart_error(StatusCode::PAYLOAD_TOO_LARGE, &name, "文件数量超过上限")
            })?;
            if file_count > spec.max_files {
                return Err(multipart_error(
                    StatusCode::PAYLOAD_TOO_LARGE,
                    &name,
                    "文件数量超过上限",
                ));
            }
            // 浏览器/脚本客户端可能不给文件 part 带 Content-Type,而 TS 原型从不校验
            // 文件 part 的 MIME(导入端点只按扩展名判断);缺头时回退
            // application/octet-stream,白名单声明通配符 "*/*" 时直接放行。
            let content_type = field
                .content_type()
                .map(|value| {
                    value
                        .split(';')
                        .next()
                        .unwrap_or_default()
                        .trim()
                        .to_ascii_lowercase()
                })
                .unwrap_or_else(|| "application/octet-stream".to_string());
            if !allows_any_content_type(spec)
                && !spec
                    .allowed_content_types
                    .iter()
                    .any(|allowed| allowed == &content_type)
            {
                return Err(multipart_error(
                    StatusCode::UNSUPPORTED_MEDIA_TYPE,
                    &name,
                    "上传文件 Content-Type 不在 Action 白名单中",
                ));
            }

            let named = tempfile::Builder::new()
                .prefix("yang-upload-")
                .tempfile_in(scope.path())
                .map_err(|error| {
                    (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        BaseError::IoError(format!("创建上传临时文件失败: {error}")),
                    )
                })?;
            let (file, path) = named.keep().map_err(|error| {
                (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    BaseError::IoError(format!("持有上传临时文件失败: {}", error.error)),
                )
            })?;
            let mut output = tokio::fs::File::from_std(file);
            let mut file_bytes = 0_u64;
            while let Some(chunk) = field.chunk().await.map_err(|error| {
                let status = error.status();
                let status = if status == StatusCode::PAYLOAD_TOO_LARGE {
                    status
                } else {
                    StatusCode::BAD_REQUEST
                };
                multipart_error(status, &name, "上传文件读取失败")
            })? {
                file_bytes = checked_payload_size(file_bytes, chunk.len(), spec.max_file_bytes)
                    .map_err(|_| {
                        multipart_error(StatusCode::PAYLOAD_TOO_LARGE, &name, "单文件大小超过上限")
                    })?;
                payload_bytes =
                    checked_payload_size(payload_bytes, chunk.len(), spec.max_total_bytes)
                        .map_err(|_| {
                            multipart_error(
                                StatusCode::PAYLOAD_TOO_LARGE,
                                "body",
                                "multipart 请求体过大",
                            )
                        })?;
                output.write_all(&chunk).await.map_err(|error| {
                    (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        BaseError::IoError(format!("写入上传临时文件失败: {error}")),
                    )
                })?;
            }
            output.flush().await.map_err(|error| {
                (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    BaseError::IoError(format!("刷新上传临时文件失败: {error}")),
                )
            })?;
            drop(output);

            // 服务端构造上传文件句柄:注入受信临时根,标记该实例允许 copy_to。
            // 伪造通道已双向封闭:构建期强制 binary 字段只走 multipart;本通道内
            // 目标子树含文件字段的文本 part 一律拒绝(见上方文本分支),因此携带
            // temp_root 的文件字段 JSON 对象只能由本传输层生成。
            let value = json!({
                "field_name": name,
                "original_filename": sanitize_filename(&raw_filename),
                "content_type": content_type,
                "size": file_bytes,
                "path": path,
                "temp_root": scope.path()
            });
            insert_multipart_value(&mut body, &mut kinds, name, MultipartPartKind::File, value)?;
        } else {
            field_count = field_count.checked_add(1).ok_or_else(|| {
                multipart_error(StatusCode::PAYLOAD_TOO_LARGE, &name, "表单字段数量超过上限")
            })?;
            if field_count > spec.max_fields {
                return Err(multipart_error(
                    StatusCode::PAYLOAD_TOO_LARGE,
                    &name,
                    "表单字段数量超过上限",
                ));
            }
            let mut bytes = Vec::new();
            let mut field_bytes = 0_u64;
            while let Some(chunk) = field.chunk().await.map_err(|error| {
                let status = error.status();
                let status = if status == StatusCode::PAYLOAD_TOO_LARGE {
                    status
                } else {
                    StatusCode::BAD_REQUEST
                };
                multipart_error(status, &name, "表单字段读取失败")
            })? {
                field_bytes =
                    checked_payload_size(field_bytes, chunk.len(), spec.max_text_field_bytes)
                        .map_err(|_| {
                            multipart_error(
                                StatusCode::PAYLOAD_TOO_LARGE,
                                &name,
                                "表单字段大小超过上限",
                            )
                        })?;
                payload_bytes =
                    checked_payload_size(payload_bytes, chunk.len(), spec.max_total_bytes)
                        .map_err(|_| {
                            multipart_error(
                                StatusCode::PAYLOAD_TOO_LARGE,
                                "body",
                                "multipart 请求体过大",
                            )
                        })?;
                bytes.extend_from_slice(&chunk);
            }
            let text = String::from_utf8(bytes).map_err(|_| {
                multipart_error(
                    StatusCode::BAD_REQUEST,
                    &name,
                    "multipart 文本字段必须是 UTF-8",
                )
            })?;
            // C-1 复审:含文件字段(format: binary,$ref 递归解析)的子树必须以文件
            // part 到达;否则文本 part 可原样透传 JSON 走私 temp_root 伪造受信实例。
            if text_part_targets_binary(input_schema, &name) {
                return Err(multipart_error(
                    StatusCode::BAD_REQUEST,
                    &name,
                    "包含文件字段的字段必须以文件形式上传",
                ));
            }
            let value = decode_text_value(input_schema, &name, text)?;
            insert_multipart_value(&mut body, &mut kinds, name, MultipartPartKind::Text, value)?;
        }
    }

    Ok(DecodedBody {
        value: Value::Object(body),
        resource_guard: Some(scope),
    })
}

fn checked_payload_size(current: u64, added: usize, limit: u64) -> Result<u64, ()> {
    let added = u64::try_from(added).map_err(|_| ())?;
    let next = current.checked_add(added).ok_or(())?;
    (next <= limit).then_some(next).ok_or(())
}

fn insert_multipart_value(
    body: &mut Map<String, Value>,
    kinds: &mut HashMap<String, MultipartPartKind>,
    name: String,
    kind: MultipartPartKind,
    value: Value,
) -> Result<(), (StatusCode, BaseError)> {
    if kinds.get(&name).is_some_and(|existing| *existing != kind) {
        return Err(multipart_error(
            StatusCode::BAD_REQUEST,
            &name,
            "同名 multipart 字段不能混用文本和文件",
        ));
    }
    kinds.entry(name.clone()).or_insert(kind);
    match body.entry(name) {
        Entry::Vacant(entry) => {
            entry.insert(value);
        }
        Entry::Occupied(mut entry) => match entry.get_mut() {
            Value::Array(values) => values.push(value),
            existing => {
                let first = std::mem::take(existing);
                *existing = Value::Array(vec![first, value]);
            }
        },
    }
    Ok(())
}

/// 判定 multipart 文本 part 的目标字段子树是否声明二进制文件字段(`format: "binary"`,
/// 本地 `$ref` 递归解析);字段不在 schema 中时放行(由输入反序列化拒绝未知字段)。
fn text_part_targets_binary(input_schema: &Value, name: &str) -> bool {
    input_schema
        .get("properties")
        .and_then(|properties| properties.get(name))
        .is_some_and(|property| schema_subtree_contains_binary(input_schema, property))
}

/// 按 input_schema 中字段声明的类型把文本 part 解码为 JSON 值。
///
/// 类型来源按序回退:字段子 schema 的平铺 `type`(含 schemars nullable 形态
/// `"type": ["integer", "null"]`),再到 schemars `anyOf`(含 null 分支的
/// `Option<T>` 形态),取第一个非 null 类型。
/// 已知限制:本地 `$ref`(如 `Option<UploadedFile>` 的 `#/definitions/...` 分支)
/// 暂不解析——该分支没有 `type`,字段按字符串处理;指向二进制子树的文本
/// part 已在 [`text_part_targets_binary`] 处先行拒绝,其余 `$ref` 字段的解码
/// 精度损失由输入反序列化兜底报错。
fn decode_text_value(
    input_schema: &Value,
    name: &str,
    text: String,
) -> Result<Value, (StatusCode, BaseError)> {
    let property = input_schema
        .get("properties")
        .and_then(|properties| properties.get(name));
    let schema_type = property
        .and_then(non_null_type)
        .or_else(|| property.and_then(any_of_non_null_type));
    match schema_type {
        Some("integer") => text
            .parse::<i64>()
            .map(Value::from)
            .map_err(|_| multipart_error(StatusCode::BAD_REQUEST, name, "表单字段必须是整数")),
        Some("number") => text
            .parse::<f64>()
            .ok()
            .and_then(serde_json::Number::from_f64)
            .map(Value::Number)
            .ok_or_else(|| {
                multipart_error(StatusCode::BAD_REQUEST, name, "表单字段必须是有限数值")
            }),
        Some("boolean") => match text.as_str() {
            "true" => Ok(Value::Bool(true)),
            "false" => Ok(Value::Bool(false)),
            _ => Err(multipart_error(
                StatusCode::BAD_REQUEST,
                name,
                "表单字段必须是 true 或 false",
            )),
        },
        Some("object" | "array") => serde_json::from_str(&text)
            .map_err(|_| multipart_error(StatusCode::BAD_REQUEST, name, "表单字段 JSON 格式无效")),
        _ => Ok(Value::String(text)),
    }
}

/// 取子 schema 的非 null 类型:兼容平铺字符串(`"type": "integer"`)与 schemars
/// nullable 形态(`"type": ["integer", "null"]`)。
fn non_null_type(schema: &Value) -> Option<&str> {
    match schema.get("type") {
        Some(Value::String(kind)) if kind != "null" => Some(kind.as_str()),
        Some(Value::Array(kinds)) => kinds
            .iter()
            .filter_map(Value::as_str)
            .find(|kind| *kind != "null"),
        _ => None,
    }
}

/// 从 `anyOf` 分支中取第一个带非 null `type` 的分支类型(schemars 为 `Option<T>`
/// 生成的形态);`$ref` 分支无 `type` 键,自然跳过。
fn any_of_non_null_type(schema: &Value) -> Option<&str> {
    schema
        .get("anyOf")?
        .as_array()?
        .iter()
        .find_map(non_null_type)
}

fn sanitize_filename(raw: &str) -> String {
    let leaf = raw.rsplit(['/', '\\']).next().unwrap_or_default().trim();
    let mut safe = String::new();
    for character in leaf.chars().filter(|character| !character.is_control()) {
        if safe.len() + character.len_utf8() > 255 {
            break;
        }
        safe.push(character);
    }
    if safe.is_empty() || matches!(safe.as_str(), "." | "..") {
        "upload.bin".to_string()
    } else {
        safe
    }
}

fn multipart_error(status: StatusCode, field: &str, message: &str) -> (StatusCode, BaseError) {
    (
        status,
        BaseError::ParamInvalid(field.to_string(), message.to_string()),
    )
}

/// Action 白名单是否声明通配符 `"*/*"`;声明后不校验文件 part 的客户端 MIME
/// (对齐 TS 导入端点只按扩展名校验的行为)。
fn allows_any_content_type(spec: &MultipartSpec) -> bool {
    spec.allowed_content_types
        .iter()
        .any(|allowed| allowed == "*/*")
}

/// 把附件响应映射为真实 HTTP 响应。
async fn attachment_response(
    attachment: ResponseAttachment,
    max_attachment_bytes: Option<u64>,
) -> Response {
    match attachment {
        ResponseAttachment::Redirect { url } => match HeaderValue::from_str(&url) {
            Ok(location) => (StatusCode::FOUND, [(header::LOCATION, location)]).into_response(),
            Err(_) => error_response(
                StatusCode::INTERNAL_SERVER_ERROR,
                BaseError::ConfigError("重定向地址包含非法字符".to_string()),
            ),
        },
        ResponseAttachment::Download { path, filename } => {
            file_response(
                &path,
                Disposition::Attachment(&filename),
                max_attachment_bytes,
            )
            .await
        }
        ResponseAttachment::Preview { path } => {
            file_response(&path, Disposition::Inline, max_attachment_bytes).await
        }
        ResponseAttachment::Raw { body, content_type } => {
            // 附件大小上限只在 file_response 内校验,Raw 不经过它,必须自己比对,
            // 否则会完全绕过 max_attachment_bytes(默认 64 MiB)。
            if let Some(max_bytes) = max_attachment_bytes {
                if body.len() as u64 > max_bytes {
                    return error_response(
                        StatusCode::PAYLOAD_TOO_LARGE,
                        BaseError::ParamInvalid(
                            "attachment".to_string(),
                            "附件超过大小上限".to_string(),
                        ),
                    );
                }
            }
            match HeaderValue::from_str(&content_type) {
                Ok(value) => {
                    (StatusCode::OK, [(header::CONTENT_TYPE, value)], body).into_response()
                }
                Err(_) => error_response(
                    StatusCode::INTERNAL_SERVER_ERROR,
                    BaseError::ConfigError("Raw 附件响应 content-type 非法".to_string()),
                ),
            }
        }
    }
}

/// 文件响应的 Content-Disposition 形态。
enum Disposition<'a> {
    /// 下载:attachment + 安全编码的 filename。
    Attachment(&'a str),
    /// 预览:inline + 按扩展名推断的 Content-Type。
    Inline,
}

async fn file_response(
    path: &std::path::Path,
    disposition: Disposition<'_>,
    max_attachment_bytes: Option<u64>,
) -> Response {
    // 先取元数据拿长度:既做 Content-Length,也在打开前做大小上限的快速失败。
    let len = match tokio::fs::metadata(path).await {
        Ok(metadata) if metadata.is_file() => metadata.len(),
        _ => {
            // 4xx 的 message 会原样回给客户端,绝对路径只进日志、不进响应体
            tracing::warn!(path = %path.display(), "附件文件不存在或不可读");
            return error_response(
                StatusCode::NOT_FOUND,
                BaseError::RecordNotFound("文件不存在".to_string()),
            );
        }
    };

    if let Some(max_bytes) = max_attachment_bytes {
        if len > max_bytes {
            return error_response(
                StatusCode::PAYLOAD_TOO_LARGE,
                BaseError::ParamInvalid("attachment".to_string(), "附件超过大小上限".to_string()),
            );
        }
    }

    let file = match tokio::fs::File::open(path).await {
        Ok(file) => file,
        Err(error) => {
            tracing::warn!(path = %path.display(), error = %error, "附件文件打开失败");
            return if error.kind() == std::io::ErrorKind::NotFound {
                error_response(
                    StatusCode::NOT_FOUND,
                    BaseError::RecordNotFound("文件不存在".to_string()),
                )
            } else {
                error_response(StatusCode::INTERNAL_SERVER_ERROR, BaseError::from(error))
            };
        }
    };

    // 流式返回:避免把整个附件一次读入内存(H3)。
    let stream = tokio_util::io::ReaderStream::with_capacity(file, 64 * 1024);
    let mut response = Response::new(Body::from_stream(stream));
    if let Ok(value) = HeaderValue::from_str(&len.to_string()) {
        response.headers_mut().insert(header::CONTENT_LENGTH, value);
    }
    let headers = response.headers_mut();
    match disposition {
        Disposition::Attachment(filename) => {
            headers.insert(
                header::CONTENT_DISPOSITION,
                content_disposition_value(filename),
            );
            headers.insert(
                header::CONTENT_TYPE,
                HeaderValue::from_static("application/octet-stream"),
            );
        }
        Disposition::Inline => {
            headers.insert(
                header::CONTENT_DISPOSITION,
                HeaderValue::from_static("inline"),
            );
            headers.insert(
                header::CONTENT_TYPE,
                HeaderValue::from_static(mime_for(path)),
            );
        }
    }
    response
}

/// 构造安全的 `attachment` 处置值:ASCII 兜底名 + RFC 5987 `filename*` 原样保留中文名。
fn content_disposition_value(filename: &str) -> HeaderValue {
    // 兜底名剔除引号与空白控制字符,防止头注入
    let fallback: String = filename
        .chars()
        .map(|ch| match ch {
            '"' | '\r' | '\n' | '\\' => '_',
            ch if ch.is_ascii() => ch,
            _ => '_',
        })
        .collect();
    let fallback = if fallback.trim_matches('_').is_empty() {
        "download".to_string()
    } else {
        fallback
    };
    let encoded = percent_encode(filename.as_bytes());
    let value = format!("attachment; filename=\"{fallback}\"; filename*=UTF-8''{encoded}");
    // 上面的构造已剔除全部非法头字符;失败时退化为固定值而非 panic
    HeaderValue::from_str(&value)
        .unwrap_or_else(|_| HeaderValue::from_static("attachment; filename=\"download\""))
}

/// RFC 5987 attr-char 百分号编码。
fn percent_encode(bytes: &[u8]) -> String {
    let mut out = String::with_capacity(bytes.len());
    for byte in bytes {
        match byte {
            b'A'..=b'Z'
            | b'a'..=b'z'
            | b'0'..=b'9'
            | b'!'
            | b'#'
            | b'$'
            | b'&'
            | b'+'
            | b'-'
            | b'.'
            | b'^'
            | b'_'
            | b'`'
            | b'|'
            | b'~' => out.push(*byte as char),
            _ => out.push_str(&format!("%{byte:02X}")),
        }
    }
    out
}

/// 按扩展名推断预览 Content-Type(未知类型按二进制流)。
fn mime_for(path: &std::path::Path) -> &'static str {
    let extension = path
        .extension()
        .and_then(|ext| ext.to_str())
        .map(|ext| ext.to_ascii_lowercase());
    match extension.as_deref() {
        Some("txt") | Some("log") | Some("md") | Some("csv") => "text/plain",
        Some("html") | Some("htm") => "text/html",
        Some("json") => "application/json",
        Some("pdf") => "application/pdf",
        Some("png") => "image/png",
        Some("jpg") | Some("jpeg") => "image/jpeg",
        Some("gif") => "image/gif",
        Some("svg") => "image/svg+xml",
        Some("webp") => "image/webp",
        Some("mp4") => "video/mp4",
        Some("mp3") => "audio/mpeg",
        _ => "application/octet-stream",
    }
}

fn method_filter(method: &str) -> Result<MethodFilter, BaseError> {
    match method {
        "GET" => Ok(MethodFilter::GET),
        "POST" => Ok(MethodFilter::POST),
        "PUT" => Ok(MethodFilter::PUT),
        "PATCH" => Ok(MethodFilter::PATCH),
        "DELETE" => Ok(MethodFilter::DELETE),
        "HEAD" => Ok(MethodFilter::HEAD),
        "OPTIONS" => Ok(MethodFilter::OPTIONS),
        "TRACE" => Ok(MethodFilter::TRACE),
        other => Err(BaseError::ConfigError(format!(
            "不支持的 HTTP 方法: {other}"
        ))),
    }
}

fn status_for_error(error: &BaseError) -> StatusCode {
    match error {
        #[cfg(feature = "token")]
        BaseError::StepUpRequired(_) => StatusCode::PRECONDITION_REQUIRED,
        BaseError::RateLimitExceeded { .. } => StatusCode::TOO_MANY_REQUESTS,
        BaseError::Unauthorized(_)
        | BaseError::InvalidPassword
        | BaseError::TokenKeyInvalid(_)
        | BaseError::TokenGenerateFailed(_)
        | BaseError::TokenVerifyFailed(_)
        | BaseError::TokenParseFailed(_)
        | BaseError::TokenExpired
        | BaseError::TokenRevoked
        | BaseError::AuthorizationStale
        | BaseError::AuthorizationVersionInvalid
        | BaseError::TokenTypeInvalid(_) => StatusCode::UNAUTHORIZED,
        BaseError::AuthorizationCheckUnavailable => StatusCode::SERVICE_UNAVAILABLE,
        BaseError::PermissionDenied(_) | BaseError::FieldPermissionDenied(_, _, _) => {
            StatusCode::FORBIDDEN
        }
        _ => match error.category() {
            ErrorCategory::Client => StatusCode::BAD_REQUEST,
            ErrorCategory::Auth => StatusCode::UNAUTHORIZED,
            ErrorCategory::NotFound => StatusCode::NOT_FOUND,
            ErrorCategory::Conflict => StatusCode::CONFLICT,
            ErrorCategory::Transient => StatusCode::SERVICE_UNAVAILABLE,
            _ => StatusCode::INTERNAL_SERVER_ERROR,
        },
    }
}

/// 记录 5xx 派发失败的 ERROR 日志。
///
/// [`BaseError::HttpRequestFailed`] 的 `Display` 内嵌 `reqwest::Error`:reqwest 在
/// 超时等路径会把完整出站 URL(含 query 中的 token / userinfo)拼进错误消息。
/// 该变体只记录稳定错误码与脱敏摘要;原始错误串由 `yang_base::http` 的出站日志
/// (URL 已脱敏)承担,避免出站凭证经入站错误日志二次落盘。
fn log_dispatch_server_error(error: &BaseError) {
    if matches!(error, BaseError::HttpRequestFailed(_)) {
        tracing::error!(
            error = "HTTP 请求失败(详情已脱敏,见 yang_base::http 出站日志)",
            code = error.code(),
            "请求处理失败"
        );
    } else {
        tracing::error!(error = %error, code = error.code(), "请求处理失败");
    }
}

fn with_request_id_header(mut response: Response, request_id: RequestId) -> Response {
    // RequestId::Display 固定输出 32 位 ASCII hex;仍通过 HeaderValue 校验守住
    // HTTP 边界,避免未来展示格式演进时把非法字节写入响应头。
    match HeaderValue::from_str(&request_id.to_string()) {
        Ok(value) => {
            response
                .headers_mut()
                .insert(HeaderName::from_static("x-request-id"), value);
        }
        Err(error) => {
            tracing::error!(%request_id, %error, "request_id 无法写入 HTTP 响应头");
        }
    }
    response
}

fn error_response(status: StatusCode, error: BaseError) -> Response {
    // 5xx 对外遮蔽内部细节(只进 tracing),4xx 保留业务 message
    #[cfg(feature = "token")]
    if let BaseError::StepUpRequired(challenge) = &error {
        let mut response = ApiResponse::from_error(&error);
        response.data = Some(serde_json::json!({
            "challenge": challenge.challenge,
            "expires_in": challenge.expires_in,
        }));
        return (status, Json(response)).into_response();
    }

    if let BaseError::RateLimitExceeded {
        retry_after_seconds,
    } = &error
    {
        let mut response = (status, Json(ApiResponse::from_error(&error))).into_response();
        if let Ok(value) = HeaderValue::from_str(&retry_after_seconds.to_string()) {
            response.headers_mut().insert(header::RETRY_AFTER, value);
        }
        return response;
    }

    let response = if status.is_server_error() {
        let message = if status == StatusCode::SERVICE_UNAVAILABLE {
            "服务暂时不可用"
        } else {
            "服务器内部错误"
        };
        ApiResponse::fail(error.code(), message)
    } else {
        ApiResponse::from_error(&error)
    };
    (status, Json(response)).into_response()
}

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

    #[test]
    fn authorization_freshness_errors_have_stable_http_semantics() {
        assert_eq!(
            status_for_error(&BaseError::AuthorizationStale),
            StatusCode::UNAUTHORIZED
        );
        assert_eq!(
            status_for_error(&BaseError::AuthorizationVersionInvalid),
            StatusCode::UNAUTHORIZED
        );
        assert_eq!(
            status_for_error(&BaseError::AuthorizationCheckUnavailable),
            StatusCode::SERVICE_UNAVAILABLE
        );
    }

    /// 捕获 `run` 期间 ERROR 级别日志输出(scoped subscriber,不污染全局)。
    fn capture_error_logs(run: impl FnOnce()) -> String {
        use std::io::Write;
        use std::sync::{Arc, Mutex};
        use tracing::subscriber::with_default;

        struct Writer(Arc<Mutex<Vec<u8>>>);
        impl Write for Writer {
            fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
                let mut guard = self.0.lock().expect("日志锁");
                std::io::Write::write(&mut *guard, bytes)
            }
            fn flush(&mut self) -> std::io::Result<()> {
                Ok(())
            }
        }

        let buffer = Arc::new(Mutex::new(Vec::new()));
        let writer_buffer = Arc::clone(&buffer);
        let subscriber = tracing_subscriber::fmt()
            .with_ansi(false)
            .with_max_level(tracing::Level::ERROR)
            .with_writer(move || Writer(Arc::clone(&writer_buffer)))
            .finish();
        with_default(subscriber, run);
        let captured = buffer.lock().expect("日志锁").clone();
        String::from_utf8(captured).expect("日志 UTF8")
    }

    /// F020 RED 场景:旧实现 `error = %error` 会把 HttpRequestFailed 的完整
    /// Display(内嵌 reqwest 错误,可能含出站 URL 的 query token/userinfo)
    /// 写入 ERROR 日志。这里用确定的 builder 错误验证日志走脱敏摘要。
    #[cfg(feature = "http")]
    #[test]
    fn http_request_failed_server_log_uses_redacted_summary() {
        let _ = rustls::crypto::ring::default_provider().install_default();
        let client = reqwest::Client::builder()
            .no_proxy()
            .build()
            .expect("HTTP 客户端应构建成功");
        let failure = client
            .request(reqwest::Method::GET, "http://[::1")
            .build()
            .expect_err("非法 URL 必须返回 builder 错误");
        assert!(failure.is_builder(), "应得到 builder 错误: {failure:?}");
        let error = BaseError::HttpRequestFailed(failure);
        assert!(status_for_error(&error).is_server_error());
        assert_eq!(error.code(), 300002);

        let logs = capture_error_logs(|| log_dispatch_server_error(&error));
        assert!(logs.contains("请求处理失败"), "缺少事件消息: {logs}");
        assert!(logs.contains("300002"), "缺少错误码: {logs}");
        assert!(logs.contains("详情已脱敏"), "应输出脱敏摘要: {logs}");
        assert!(
            !logs.contains("HTTP 请求失败:"),
            "不得渲染 BaseError 的 Display: {logs}"
        );
    }

    /// 非 HTTP 请求错误继续输出 Display,保留排障信息。
    #[test]
    fn other_server_errors_keep_display_in_log() {
        let error = BaseError::DatabaseInitFailed("db init failed".to_string());
        assert!(status_for_error(&error).is_server_error());

        let logs = capture_error_logs(|| log_dispatch_server_error(&error));
        assert!(logs.contains("请求处理失败"), "{logs}");
        assert!(logs.contains("db init failed"), "{logs}");
    }

    #[test]
    fn duplicate_query_parameters_take_first_value() {
        // Q1:TS URLSearchParams.get 取第一个同名参数;后出现的值不得覆盖它。
        let query = parse_query_pairs("a=1&a=2&b=3").expect("合法 query 必须解析成功");
        assert_eq!(query.get("a").map(String::as_str), Some("1"));
        assert_eq!(query.get("b").map(String::as_str), Some("3"));
    }

    #[test]
    fn query_parsing_keeps_empty_and_valueless_parameters() {
        // 空值(a=)与无值(b)参数与 serde_urlencoded 原行为一致:都得到空字符串。
        let query = parse_query_pairs("a=&b&a=x").expect("合法 query 必须解析成功");
        assert_eq!(query.get("a").map(String::as_str), Some(""));
        assert_eq!(query.get("b").map(String::as_str), Some(""));
        assert!(parse_query_pairs("")
            .expect("空 query 必须解析成功")
            .is_empty());
    }

    #[test]
    fn wildcard_content_type_bypasses_upload_whitelist() {
        // Z5:TS 导入端点只按扩展名校验;"*/*" 表示跳过文件 part 的 MIME 白名单。
        assert!(allows_any_content_type(&MultipartSpec::new(["*/*"])));
        assert!(!allows_any_content_type(&MultipartSpec::new([
            "application/pdf"
        ])));
    }

    #[test]
    fn multipart_decoder_clone_shares_schema_and_spec_allocation() {
        // M16 回归:multipart 解码器持 Arc<Value> / Arc<MultipartSpec>,每请求的
        // `decoder.clone()`(axum.rs 闭包内)必须只做引用计数自增。若改回按值持有,
        // 这里除 Arc::ptr_eq 失败外还会在每个请求上重新深拷贝 Schema 与
        // allowed_content_types。
        let spec = Arc::new(MultipartSpec::new(["text/plain"]));
        let input_schema = Arc::new(json!({
            "type": "object",
            "properties": {
                "title": { "type": "string" },
                "file": { "type": "string", "format": "binary" }
            }
        }));
        let decoder = RequestDecoder::Multipart {
            spec: Arc::clone(&spec),
            input_schema: Arc::clone(&input_schema),
        };

        let cloned = decoder.clone();
        let RequestDecoder::Multipart {
            spec: cloned_spec,
            input_schema: cloned_schema,
        } = cloned
        else {
            panic!("multipart 解码器 clone 后必须仍是 Multipart 变体");
        };
        assert!(
            Arc::ptr_eq(&spec, &cloned_spec),
            "clone 必须共享同一份 MultipartSpec 分配"
        );
        assert!(
            Arc::ptr_eq(&input_schema, &cloned_schema),
            "clone 必须共享同一份 input_schema 分配"
        );
    }
}