zenith-api 0.1.0

Zenith 公共 API 与类型定义:CanonicalRequest/Response、Method、Protocol、Transport 等核心类型
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
//! Zenith API - 公开API与类型定义
//!
//! 本 crate 定义 Zenith 框架的所有公开类型、特征和接口,
//! 是外部程序依赖的唯一入口点。
//!
//! # 设计原则
//! - 热路径零堆分配:使用固定容量数组替代 String/Vec
//! - Copy 语义:所有核心类型支持 Copy,避免昂贵的 Clone
//! - 编译期安全:类型系统保证所有权唯一

#![deny(unsafe_code)]
#![deny(missing_debug_implementations)]
#![warn(missing_docs)]

pub mod normalize;

// ---------------------------------------------------------------------------
// 固定容量常量
// ---------------------------------------------------------------------------

/// 最大路径长度(字节)
pub const MAX_PATH_LEN: usize = 1024;

/// 最大查询字符串长度(字节)
pub const MAX_QUERY_LEN: usize = 1024;

/// 最大授权主机长度(字节)
pub const MAX_AUTHORITY_LEN: usize = 256;

/// 最大头部数量
pub const MAX_HEADER_COUNT: usize = 32;

/// 最大头部名称长度(字节)
pub const MAX_HEADER_NAME_LEN: usize = 64;

/// 最大头部值长度(字节)
/// RFC 7230 建议整个头部块最小 8KB,单个值通常不超过 256 字节
pub const MAX_HEADER_VALUE_LEN: usize = 256;

/// 最大响应 Body 长度(字节)
/// 小于此值的 Body 使用栈上固定数组,超过时使用堆分配
pub const MAX_BODY_LEN: usize = 4096;

// ---------------------------------------------------------------------------
// 基础类型定义
// ---------------------------------------------------------------------------

/// 协议类型枚举
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Protocol {
    /// HTTP/1.1 协议
    Http1,
    /// HTTP/2 协议
    Http2,
    /// HTTP/3 协议
    Http3,
    /// TCP 协议
    Tcp,
    /// UDP 协议
    Udp,
    /// QUIC 协议
    Quic,
}

/// 传输层类型枚举
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Transport {
    /// 明文传输
    Plaintext,
    /// TLS 1.3 加密传输
    Tls13,
}

/// 请求方法枚举
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Method {
    /// GET 方法
    Get,
    /// POST 方法
    Post,
    /// PUT 方法
    Put,
    /// DELETE 方法
    Delete,
    /// PATCH 方法
    Patch,
    /// HEAD 方法
    Head,
    /// OPTIONS 方法
    Options,
    /// CONNECT 方法
    Connect,
    /// TRACE 方法
    Trace,
}

impl Method {
    /// 获取方法的字符串表示
    #[inline]
    pub fn as_str(&self) -> &'static str {
        match self {
            Method::Get => "GET",
            Method::Post => "POST",
            Method::Put => "PUT",
            Method::Delete => "DELETE",
            Method::Patch => "PATCH",
            Method::Head => "HEAD",
            Method::Options => "OPTIONS",
            Method::Connect => "CONNECT",
            Method::Trace => "TRACE",
        }
    }
}

/// Method 解析错误
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MethodParseError(());

impl std::fmt::Display for MethodParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("invalid HTTP method")
    }
}

impl std::error::Error for MethodParseError {}

impl std::str::FromStr for Method {
    type Err = MethodParseError;

    /// 将字符串解析为 Method(RFC 9110 严格大小写敏感)
    ///
    /// HTTP 方法令牌在语义上大小写敏感("GET" 与 "get" 是不同方法),
    /// 与 `zenith_web::normalize::parse_method` 保持全库语义统一,防止
    /// 双解析器分歧引入的规范化绕过(请求走私面)。零堆分配。
    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        // 严格精确匹配(RFC 9110 §9:method = token,大小写敏感)
        Ok(match s {
            "GET" => Method::Get,
            "POST" => Method::Post,
            "PUT" => Method::Put,
            "DELETE" => Method::Delete,
            "PATCH" => Method::Patch,
            "HEAD" => Method::Head,
            "OPTIONS" => Method::Options,
            "CONNECT" => Method::Connect,
            "TRACE" => Method::Trace,
            _ => return Err(MethodParseError(())),
        })
    }
}

// ---------------------------------------------------------------------------
// 规范化头条目(Copy 语义,零堆分配)
// ---------------------------------------------------------------------------

/// 规范化请求头(固定容量,Copy 语义)
///
/// 每个头部条目使用固定容量数组存储,避免堆分配。
#[derive(Debug, Clone, Copy)]
pub struct CanonicalHeader {
    /// 头名称(最大 MAX_HEADER_NAME_LEN 字节)
    pub name: [u8; MAX_HEADER_NAME_LEN],
    /// 头名称实际长度
    pub name_len: u8,
    /// 头值(最大 MAX_HEADER_VALUE_LEN 字节)
    pub value: [u8; MAX_HEADER_VALUE_LEN],
    /// 头值实际长度
    pub value_len: u16,
}

impl CanonicalHeader {
    /// 创建空头部
    #[inline]
    pub const fn empty() -> Self {
        Self {
            name: [0u8; MAX_HEADER_NAME_LEN],
            name_len: 0,
            value: [0u8; MAX_HEADER_VALUE_LEN],
            value_len: 0,
        }
    }

    /// 重置头部(清空内容)
    /// 用于对象池复用,避免重新创建对象的开销
    #[inline]
    pub fn reset(&mut self) {
        // 不需要清零数组,后续写入会覆盖
        self.name_len = 0;
        self.value_len = 0;
    }

    /// 从字节切片创建头部(fail-closed)
    ///
    /// # Arguments
    /// * `name` - 头名称(必须不超过 MAX_HEADER_NAME_LEN)
    /// * `value` - 头值(必须不超过 MAX_HEADER_VALUE_LEN)
    ///
    /// # Returns
    /// * `Some(CanonicalHeader)` - 创建成功
    /// * `None` - 名称或值超长(拒绝静默截断,防止截断后语义被篡改)
    pub fn from_bytes(name: &[u8], value: &[u8]) -> Option<Self> {
        if name.len() > MAX_HEADER_NAME_LEN || value.len() > MAX_HEADER_VALUE_LEN {
            return None;
        }
        let mut hdr = Self::empty();
        let name_len = name.len() as u8;
        hdr.name[..name.len()].copy_from_slice(name);
        hdr.name_len = name_len;

        let value_len = value.len() as u16;
        hdr.value[..value.len()].copy_from_slice(value);
        hdr.value_len = value_len;
        Some(hdr)
    }

    /// 获取名称为字符串切片
    #[inline]
    pub fn name_str(&self) -> &str {
        core::str::from_utf8(&self.name[..self.name_len as usize]).unwrap_or("")
    }

    /// 获取值为字符串切片
    #[inline]
    pub fn value_str(&self) -> &str {
        core::str::from_utf8(&self.value[..self.value_len as usize]).unwrap_or("")
    }

    /// 是否为空
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.name_len == 0
    }
}

// ---------------------------------------------------------------------------
// Body 流(单消费者,借用语义)
// ---------------------------------------------------------------------------

/// Body 流(单消费者,借用语义,零拷贝)
///
/// Body 只能被读取一次,消费后标记为已消费。
#[derive(Debug)]
pub struct BodyStream<'a> {
    /// Body 数据切片
    data: &'a [u8],
    /// 是否已消费
    consumed: bool,
}

impl<'a> BodyStream<'a> {
    /// 创建新 Body 流
    #[inline]
    pub fn new(data: &'a [u8]) -> Self {
        Self {
            data,
            consumed: false,
        }
    }

    /// 获取 Body 数据(仅首次调用有效)
    ///
    /// # Returns
    /// * `Some(data)` - 首次调用返回数据
    /// * `None` - 已消费或无数据
    #[inline]
    pub fn get_data(&mut self) -> Option<&'a [u8]> {
        if self.consumed || self.data.is_empty() {
            return None;
        }
        self.consumed = true;
        Some(self.data)
    }

    /// 检查是否已消费
    #[inline]
    pub fn is_consumed(&self) -> bool {
        self.consumed
    }

    /// 获取 Body 长度(不改变消费状态)
    #[inline]
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Body 是否为空
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }
}

// ---------------------------------------------------------------------------
// 规范化请求(零堆分配,固定容量,Copy 语义)
// ---------------------------------------------------------------------------

/// 统一规范化请求
///
/// 所有HTTP协议(HTTP/1.1、HTTP/2、HTTP/3)解析后都生成此结构,
/// 全链路统一使用,避免协议差分攻击。
///
/// # 设计特点
/// - 零堆分配(小 Body):Body <= MAX_BODY_LEN 使用栈上固定数组,避免堆分配
/// - 大 Body 溢出:超过 MAX_BODY_LEN 时使用堆分配(Option<Vec<u8>>),保证正确性
/// - 治理字段:generation、deadline、cancelled、resource_lease
///
/// # Copy 语义
/// 由于大 Body 场景下引入了 `Option<Vec<u8>>`,CanonicalRequest 不再是 `Copy`,
/// 仅保留 `Clone`。绝大多数小请求 (<= 4KiB body) 的 clone 开销仅为栈数组拷贝。
#[derive(Debug, Clone)]
pub struct CanonicalRequest {
    /// 请求方法
    pub method: Method,
    /// 请求方案(http/https,固定容量)
    scheme: [u8; 8],
    /// 方案长度
    scheme_len: u8,
    /// 授权主机(固定容量)
    authority: [u8; MAX_AUTHORITY_LEN],
    /// 授权主机长度
    authority_len: u16,
    /// 规范化后的路径(固定容量)
    normalized_path: [u8; MAX_PATH_LEN],
    /// 路径长度
    path_len: u16,
    /// 规范化后的查询字符串(固定容量)
    normalized_query: [u8; MAX_QUERY_LEN],
    /// 查询字符串长度
    query_len: u32,
    /// 头部数组(固定容量)
    headers: [CanonicalHeader; MAX_HEADER_COUNT],
    /// 头部数量
    header_count: u8,
    /// 协议类型
    pub protocol: Protocol,
    /// 传输层类型
    pub transport: Transport,
    /// 代际号(用于 ChangeSet 版本控制)
    pub generation: u64,
    /// 截止时间(毫秒,0 表示无限制)
    pub deadline_ms: u64,
    /// 是否已取消
    pub cancelled: bool,
    /// 资源租约(令牌数,用于限流/配额)
    pub resource_lease: u64,
    /// 请求 Body 栈上缓冲区(<= MAX_BODY_LEN 时使用,零堆分配)
    body_buffer: [u8; MAX_BODY_LEN],
    /// 请求 Body 实际长度
    body_len: u32,
    /// 请求 Body 溢出堆缓冲区(> MAX_BODY_LEN 时使用)
    body_overflow: Option<Vec<u8>>,
}

impl CanonicalRequest {
    /// 创建空请求
    pub const fn empty() -> Self {
        Self {
            method: Method::Get,
            scheme: [0u8; 8],
            scheme_len: 0,
            authority: [0u8; MAX_AUTHORITY_LEN],
            authority_len: 0,
            normalized_path: [0u8; MAX_PATH_LEN],
            path_len: 0,
            normalized_query: [0u8; MAX_QUERY_LEN],
            query_len: 0,
            headers: [CanonicalHeader::empty(); MAX_HEADER_COUNT],
            header_count: 0,
            protocol: Protocol::Http1,
            transport: Transport::Plaintext,
            generation: 0,
            deadline_ms: 0,
            cancelled: false,
            resource_lease: 0,
            body_buffer: [0u8; MAX_BODY_LEN],
            body_len: 0,
            body_overflow: None,
        }
    }

    /// 重置请求(清空所有字段)
    /// 用于对象池复用,避免重新创建对象的开销
    #[inline]
    pub fn reset(&mut self) {
        self.method = Method::Get;
        self.scheme_len = 0;
        self.authority_len = 0;
        self.path_len = 0;
        self.query_len = 0;
        // 只重置使用过的头部
        for i in 0..self.header_count as usize {
            self.headers[i].reset();
        }
        self.header_count = 0;
        self.protocol = Protocol::Http1;
        self.transport = Transport::Plaintext;
        self.generation = 0;
        self.deadline_ms = 0;
        self.cancelled = false;
        self.resource_lease = 0;
        // Body:不需要清零数组,后续写入会覆盖;清零堆溢出
        self.body_len = 0;
        self.body_overflow = None;
    }

    /// 设置请求 Body
    ///
    /// 性能设计:
    /// - Body 长度 <= MAX_BODY_LEN:使用栈上缓冲区,零堆分配
    /// - Body 长度 > MAX_BODY_LEN:使用堆分配,保证正确性不截断
    pub fn set_body(&mut self, body: impl Into<Vec<u8>>) {
        let body = body.into();
        if body.len() <= MAX_BODY_LEN {
            self.body_overflow = None;
            self.body_buffer[..body.len()].copy_from_slice(&body);
            self.body_len = body.len() as u32;
        } else {
            self.body_overflow = Some(body);
            self.body_len = self
                .body_overflow
                .as_ref()
                .map(|v| v.len())
                .unwrap_or(0) as u32;
        }
    }

    /// 获取请求 Body 的字节切片(零分配)
    #[inline]
    pub fn body(&self) -> &[u8] {
        if let Some(ref overflow) = self.body_overflow {
            overflow.as_slice()
        } else {
            &self.body_buffer[..self.body_len as usize]
        }
    }

    /// 获取方案字符串
    #[inline]
    pub fn scheme_str(&self) -> &str {
        core::str::from_utf8(&self.scheme[..self.scheme_len as usize]).unwrap_or("")
    }

    /// 设置方案(fail-closed)
    ///
    /// # Returns
    /// * `true` - 设置成功
    /// * `false` - 方案超长(拒绝静默截断,**不修改原值**直接返回 false;
    ///   截断会篡改语义,下游必须检查返回值)
    #[must_use]
    pub fn set_scheme(&mut self, scheme: &str) -> bool {
        if scheme.len() > 8 {
            return false;
        }
        let len = scheme.len() as u8;
        self.scheme[..scheme.len()].copy_from_slice(scheme.as_bytes());
        self.scheme_len = len;
        true
    }

    /// 获取授权主机字符串
    #[inline]
    pub fn authority_str(&self) -> &str {
        core::str::from_utf8(&self.authority[..self.authority_len as usize]).unwrap_or("")
    }

    /// 设置授权主机(fail-closed)
    ///
    /// # Returns
    /// * `true` - 设置成功
    /// * `false` - authority 超长(拒绝静默截断,**不修改原值**直接返回 false)
    #[must_use]
    pub fn set_authority(&mut self, authority: &str) -> bool {
        if authority.len() > MAX_AUTHORITY_LEN {
            return false;
        }
        let len = authority.len() as u16;
        self.authority[..authority.len()].copy_from_slice(authority.as_bytes());
        self.authority_len = len;
        true
    }

    /// 获取规范化路径
    #[inline]
    pub fn path_str(&self) -> &str {
        core::str::from_utf8(&self.normalized_path[..self.path_len as usize]).unwrap_or("")
    }

    /// 获取规范化路径的字节切片(零分配)
    #[inline]
    pub fn path_bytes(&self) -> &[u8] {
        &self.normalized_path[..self.path_len as usize]
    }

    /// 设置规范化路径(fail-closed)
    ///
    /// 输入为 request target 时,其中的 `?` 之后的部分会被拆分到 query 字段
    /// (路由只匹配路径部分;若不拆分,`/api?x=1` 会作为整体参与路由匹配而被击穿)。
    /// 输入不含 `?` 时 query 字段保持不变。
    ///
    /// # Returns
    /// * `true` - 设置成功
    /// * `false` - 路径部分超过 MAX_PATH_LEN 或拆分出的 query 超过
    ///   MAX_QUERY_LEN(拒绝静默截断,**path 与 query 均不修改**,原子拒绝)
    #[must_use]
    pub fn set_path(&mut self, path: &str) -> bool {
        // 拆分 request target 中的 query 部分
        let (path_part, query_part) = match path.find('?') {
            Some(pos) => (&path[..pos], Some(&path[pos + 1..])),
            None => (path, None),
        };
        // 全量预检:任何一部分超长都原子拒绝,不部分落盘
        if path_part.len() > MAX_PATH_LEN {
            return false;
        }
        if let Some(query) = query_part
            && query.len() > MAX_QUERY_LEN
        {
            return false;
        }
        self.normalized_path[..path_part.len()].copy_from_slice(path_part.as_bytes());
        self.path_len = path_part.len() as u16;
        if let Some(query) = query_part {
            // 长度已预检,set_query 必然返回 true
            let _ = self.set_query(query);
        }
        true
    }

    /// 获取规范化查询字符串
    #[inline]
    pub fn query_str(&self) -> &str {
        core::str::from_utf8(&self.normalized_query[..self.query_len as usize]).unwrap_or("")
    }

    /// 设置规范化查询字符串(fail-closed)
    ///
    /// # Returns
    /// * `true` - 设置成功
    /// * `false` - query 超长(拒绝静默截断,**不修改原值**直接返回 false)
    #[must_use]
    pub fn set_query(&mut self, query: &str) -> bool {
        if query.len() > MAX_QUERY_LEN {
            return false;
        }
        let len = query.len() as u32;
        self.normalized_query[..query.len()].copy_from_slice(query.as_bytes());
        self.query_len = len;
        true
    }

    /// 获取头部数量
    #[inline]
    pub fn header_count(&self) -> u8 {
        self.header_count
    }

    /// 按索引获取头部
    #[inline]
    pub fn get_header(&self, idx: usize) -> Option<&CanonicalHeader> {
        if idx < self.header_count as usize {
            Some(&self.headers[idx])
        } else {
            None
        }
    }

    /// 按名称查找头部(返回第一个匹配,ASCII 大小写不敏感)
    ///
    /// HTTP 头部名称按 RFC 7230 §3.2 为大小写不敏感;
    /// 大小写敏感查找会被 `Host`/`host` 差分击穿,故统一不敏感比较。
    #[inline]
    pub fn find_header(&self, name: &str) -> Option<&CanonicalHeader> {
        let name_bytes = name.as_bytes();
        for i in 0..self.header_count as usize {
            let hdr = &self.headers[i];
            if hdr.name_len as usize == name_bytes.len()
                && hdr.name[..hdr.name_len as usize].eq_ignore_ascii_case(name_bytes)
            {
                return Some(hdr);
            }
        }
        None
    }

    /// 添加头部(超过最大数量或字段超长时返回错误)
    ///
    /// # 安全
    /// - 拒绝包含 `\r` 或 `\n` 的头部名称和值,防止 HTTP 响应拆分攻击。
    /// - 名称/值超长时 fail-closed 拒绝,禁止静默截断(截断会篡改头部语义)。
    pub fn add_header(&mut self, name: &[u8], value: &[u8]) -> Result<(), &'static str> {
        if self.header_count as usize >= MAX_HEADER_COUNT {
            return Err("header count exceeded");
        }
        // 长度预检(fail-closed:超长直接拒绝)
        if name.len() > MAX_HEADER_NAME_LEN {
            return Err("header name too long");
        }
        if value.len() > MAX_HEADER_VALUE_LEN {
            return Err("header value too long");
        }
        // 拒绝包含 CRLF 的头部,防止 HTTP 响应拆分攻击
        if name.contains(&b'\r') || name.contains(&b'\n') {
            return Err("header name contains CRLF");
        }
        if value.contains(&b'\r') || value.contains(&b'\n') {
            return Err("header value contains CRLF");
        }
        let idx = self.header_count as usize;
        // 长度已预检,from_bytes 必然成功;仍按 fail-closed 处理 None 而非 unwrap
        self.headers[idx] = match CanonicalHeader::from_bytes(name, value) {
            Some(hdr) => hdr,
            None => return Err("header name or value too long"),
        };
        self.header_count += 1;
        Ok(())
    }

    /// 迭代所有头部
    #[inline]
    pub fn headers_iter(&self) -> &[CanonicalHeader] {
        &self.headers[..self.header_count as usize]
    }

    /// 设置已取消
    #[inline]
    pub fn cancel(&mut self) {
        self.cancelled = true;
    }

    /// 检查是否已取消
    #[inline]
    pub fn is_cancelled(&self) -> bool {
        self.cancelled
    }
}

// ---------------------------------------------------------------------------
// 规范化响应(零堆分配,固定容量)
// ---------------------------------------------------------------------------

/// 统一规范化响应
///
/// 所有HTTP协议处理后的统一响应结构。
///
/// # 设计特点
/// - 零堆分配:小 Body 使用栈上固定数组,超过 MAX_BODY_LEN 时才使用堆
/// - Copy 语义:仅当 Body 超过栈容量时放弃 Copy
#[derive(Debug, Clone)]
pub struct CanonicalResponse {
    /// 状态码
    pub status_code: u16,
    /// 头部数组(固定容量)
    headers: [CanonicalHeader; MAX_HEADER_COUNT],
    /// 头部数量
    header_count: u8,
    /// Body 数据(栈上固定容量)
    body_buffer: [u8; MAX_BODY_LEN],
    /// Body 实际长度
    body_len: u32,
    /// Body 溢出数据(超过 MAX_BODY_LEN 时使用堆分配)
    body_overflow: Option<Vec<u8>>,
}

impl CanonicalResponse {
    /// 创建响应(零堆分配)
    #[inline]
    pub const fn new(status_code: u16) -> Self {
        Self {
            status_code,
            headers: [CanonicalHeader::empty(); MAX_HEADER_COUNT],
            header_count: 0,
            body_buffer: [0u8; MAX_BODY_LEN],
            body_len: 0,
            body_overflow: None,
        }
    }

    /// 创建简单的成功响应
    #[inline]
    pub const fn ok() -> Self {
        Self::new(200)
    }

    /// 创建简单的错误响应
    #[inline]
    pub const fn error(status_code: u16) -> Self {
        Self::new(status_code)
    }

    /// 重置响应(保留状态码,清空其他字段)
    /// 用于对象池复用,避免重新创建对象的开销
    #[inline]
    pub fn reset(&mut self) {
        // 只重置使用过的字段,不重置整个数组
        for i in 0..self.header_count as usize {
            self.headers[i].reset();
        }
        self.header_count = 0;
        // 不需要重置 body_buffer,后续写入会覆盖
        self.body_len = 0;
        self.body_overflow = None;
    }

    /// 获取头部数量
    #[inline]
    pub fn header_count(&self) -> u8 {
        self.header_count
    }

    /// 添加头部
    ///
    /// # 安全
    /// 拒绝包含 `\r` 或 `\n` 的头部名称和值,防止 HTTP 响应拆分攻击。
    pub fn add_header(&mut self, name: &[u8], value: &[u8]) -> Result<(), &'static str> {
        if self.header_count as usize >= MAX_HEADER_COUNT {
            return Err("header count exceeded");
        }
        // 拒绝包含 CRLF 的头部,防止 HTTP 响应拆分攻击
        if name.contains(&b'\r') || name.contains(&b'\n') {
            return Err("header name contains CRLF");
        }
        if value.contains(&b'\r') || value.contains(&b'\n') {
            return Err("header value contains CRLF");
        }
        let idx = self.header_count as usize;
        // from_bytes 在 name/value 超限时返回 None,fail-closed 上抛错误
        self.headers[idx] = CanonicalHeader::from_bytes(name, value)
            .ok_or("header name/value too long")?;
        self.header_count += 1;
        Ok(())
    }

    /// 设置 Body
    ///
    /// # 性能
    /// - Body 长度 <= MAX_BODY_LEN:使用栈上缓冲区,零堆分配
    /// - Body 长度 > MAX_BODY_LEN:使用堆分配
    pub fn set_body(&mut self, body: impl Into<Vec<u8>>) {
        let body = body.into();
        if body.len() <= MAX_BODY_LEN {
            self.body_overflow = None;
            self.body_buffer[..body.len()].copy_from_slice(&body);
            self.body_len = body.len() as u32;
        } else {
            self.body_overflow = Some(body);
            self.body_len = self.body_overflow.as_ref().map(|v| v.len()).unwrap_or(0) as u32;
        }
    }

    /// 获取 Body 引用
    #[inline]
    pub fn body(&self) -> &[u8] {
        if let Some(ref overflow) = self.body_overflow {
            overflow
        } else {
            &self.body_buffer[..self.body_len as usize]
        }
    }

    /// 获取头部迭代器
    #[inline]
    pub fn headers_iter(&self) -> &[CanonicalHeader] {
        &self.headers[..self.header_count as usize]
    }

    /// 按名称查找头部(ASCII 大小写不敏感,RFC 7230 §3.2)
    #[inline]
    pub fn find_header(&self, name: &str) -> Option<&CanonicalHeader> {
        let name_bytes = name.as_bytes();
        for i in 0..self.header_count as usize {
            let hdr = &self.headers[i];
            if hdr.name_len as usize == name_bytes.len()
                && hdr.name[..hdr.name_len as usize].eq_ignore_ascii_case(name_bytes)
            {
                return Some(hdr);
            }
        }
        None
    }
}

impl Default for CanonicalRequest {
    #[inline]
    fn default() -> Self {
        Self::empty()
    }
}

impl Default for CanonicalResponse {
    #[inline]
    fn default() -> Self {
        Self::new(200)
    }
}

// ---------------------------------------------------------------------------
// 服务注册特征
// ---------------------------------------------------------------------------

/// 服务注册特征
pub trait Service: Send + Sync + 'static {
    /// 处理规范化请求,返回规范化响应
    fn handle(&self, request: CanonicalRequest) -> CanonicalResponse;
}

/// 服务工厂特征
pub trait ServiceFactory: Send + Sync + 'static {
    /// 创建新的服务实例
    fn create(&self) -> Box<dyn Service>;
}

// ---------------------------------------------------------------------------
// 测试
// ---------------------------------------------------------------------------

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

    #[test]
    fn test_method_from_str() {
        use std::str::FromStr;
        assert_eq!(Method::from_str("GET"), Ok(Method::Get));
        assert_eq!(Method::from_str("POST"), Ok(Method::Post));
        // RFC 9110 大小写敏感:非大写方法一律拒绝(与 zenith-web parse_method 统一)
        assert!(Method::from_str("post").is_err());
        assert!(Method::from_str("Get").is_err());
        assert!(Method::from_str("INVALID").is_err());
    }

    #[test]
    fn test_method_as_str() {
        assert_eq!(Method::Get.as_str(), "GET");
        assert_eq!(Method::Post.as_str(), "POST");
    }

    #[test]
    fn test_canonical_header_creation() {
        let hdr = CanonicalHeader::from_bytes(b"content-type", b"application/json").unwrap();
        assert_eq!(hdr.name_str(), "content-type");
        assert_eq!(hdr.value_str(), "application/json");
        assert_eq!(hdr.name_len, 12);
        assert_eq!(hdr.value_len, 16);
    }

    #[test]
    fn test_canonical_header_overlong_rejected() {
        // 构造一个 100 字节的超长名称:fail-closed 拒绝,禁止静默截断
        let long_name = b"this-is-a-very-long-header-name-that-should-exceed-the-maximum-sixty-four-bytes-limit-and-test-truncation";
        assert!(long_name.len() > MAX_HEADER_NAME_LEN);
        assert!(CanonicalHeader::from_bytes(long_name, b"value").is_none());

        // 边界:恰好等于上限时允许
        let exact_name = vec![b'n'; MAX_HEADER_NAME_LEN];
        let hdr = CanonicalHeader::from_bytes(&exact_name, b"value").unwrap();
        assert_eq!(hdr.name_len, MAX_HEADER_NAME_LEN as u8);
    }

    #[test]
    fn test_canonical_request_creation() {
        let mut request = CanonicalRequest::empty();
        request.method = Method::Get;
        assert!(request.set_scheme("https"));
        assert!(request.set_authority("example.com"));
        assert!(request.set_path("/api/test"));
        assert!(request.set_query("key=value"));
        request.protocol = Protocol::Http1;
        request.transport = Transport::Tls13;

        assert_eq!(request.method, Method::Get);
        assert_eq!(request.scheme_str(), "https");
        assert_eq!(request.authority_str(), "example.com");
        assert_eq!(request.path_str(), "/api/test");
        assert_eq!(request.query_str(), "key=value");
    }

    #[test]
    fn test_canonical_request_headers() {
        let mut request = CanonicalRequest::empty();
        request
            .add_header(b"content-type", b"application/json")
            .unwrap();
        request
            .add_header(b"accept", b"text/html")
            .unwrap();

        assert_eq!(request.header_count(), 2);
        assert!(request.find_header("content-type").is_some());
        assert!(request.find_header("non-existent").is_none());

        let hdr = request.find_header("accept").unwrap();
        assert_eq!(hdr.value_str(), "text/html");
    }

    #[test]
    fn test_canonical_request_header_limit() {
        let mut request = CanonicalRequest::empty();
        for i in 0..MAX_HEADER_COUNT {
            let name = format!("header-{}", i);
            request.add_header(name.as_bytes(), b"value").unwrap();
        }
        assert_eq!(request.header_count(), MAX_HEADER_COUNT as u8);

        // 超过限制应返回错误
        let result = request.add_header(b"overflow", b"value");
        assert!(result.is_err());
    }

    #[test]
    fn test_body_stream() {
        let data = b"test body data";
        let mut stream = BodyStream::new(data);

        assert!(!stream.is_consumed());
        assert_eq!(stream.len(), 14);
        assert!(!stream.is_empty());

        let result = stream.get_data();
        assert_eq!(result, Some(&data[..]));
        assert!(stream.is_consumed());

        // 再次调用返回 None
        let result2 = stream.get_data();
        assert!(result2.is_none());
    }

    #[test]
    fn test_body_stream_empty() {
        let mut stream = BodyStream::new(b"");
        assert!(stream.is_empty());
        let result = stream.get_data();
        assert!(result.is_none());
    }

    #[test]
    fn test_governance_fields() {
        let mut request = CanonicalRequest::empty();
        request.generation = 42;
        request.deadline_ms = 5000;
        request.resource_lease = 100;

        assert_eq!(request.generation, 42);
        assert_eq!(request.deadline_ms, 5000);

        request.cancel();
        assert!(request.is_cancelled());
    }

    #[test]
    fn test_canonical_response() {
        let mut response = CanonicalResponse::new(200);
        assert_eq!(response.status_code, 200);

        response
            .add_header(b"content-type", b"text/plain")
            .unwrap();
        assert_eq!(response.header_count(), 1);

        response.set_body(b"Hello".to_vec());
        assert_eq!(response.body(), b"Hello");
    }

    #[test]
    fn test_canonical_response_helpers() {
        let ok = CanonicalResponse::ok();
        assert_eq!(ok.status_code, 200);

        let error = CanonicalResponse::error(404);
        assert_eq!(error.status_code, 404);
    }

    #[test]
    fn test_request_copy_semantics() {
        let mut request = CanonicalRequest::empty();
        request.method = Method::Post;
        assert!(request.set_path("/test"));
        request.generation = 1;

        // Clone 语义:CanonicalRequest 不再实现 Copy(含 Option<Vec<u8>> body_overflow)
        let cloned = request.clone();
        assert_eq!(cloned.method, Method::Post);
        assert_eq!(cloned.path_str(), "/test");
        assert_eq!(cloned.generation, 1);

        // 修改原对象不影响克隆
        request.method = Method::Get;
        assert_ne!(request.method, cloned.method);
    }

    // ─────────────────────────────────────────────
    // Method 全变体测试
    // ─────────────────────────────────────────────

    #[test]
    fn test_method_all_variants_as_str() {
        assert_eq!(Method::Get.as_str(), "GET");
        assert_eq!(Method::Post.as_str(), "POST");
        assert_eq!(Method::Put.as_str(), "PUT");
        assert_eq!(Method::Delete.as_str(), "DELETE");
        assert_eq!(Method::Patch.as_str(), "PATCH");
        assert_eq!(Method::Head.as_str(), "HEAD");
        assert_eq!(Method::Options.as_str(), "OPTIONS");
        assert_eq!(Method::Connect.as_str(), "CONNECT");
        assert_eq!(Method::Trace.as_str(), "TRACE");
    }

    #[test]
    fn test_method_from_str_all_variants() {
        use std::str::FromStr;
        assert_eq!(Method::from_str("GET"), Ok(Method::Get));
        assert_eq!(Method::from_str("POST"), Ok(Method::Post));
        assert_eq!(Method::from_str("PUT"), Ok(Method::Put));
        assert_eq!(Method::from_str("DELETE"), Ok(Method::Delete));
        assert_eq!(Method::from_str("PATCH"), Ok(Method::Patch));
        assert_eq!(Method::from_str("HEAD"), Ok(Method::Head));
        assert_eq!(Method::from_str("OPTIONS"), Ok(Method::Options));
        assert_eq!(Method::from_str("CONNECT"), Ok(Method::Connect));
        assert_eq!(Method::from_str("TRACE"), Ok(Method::Trace));
    }

    #[test]
    fn test_method_from_str_case_sensitive_strict() {
        // RFC 9110:method = token 大小写敏感。任何非精确大写均被拒绝,
        // 与 zenith_web::normalize::parse_method 语义统一(防双解析器分歧)。
        use std::str::FromStr;
        assert!(Method::from_str("get").is_err());
        assert!(Method::from_str("Get").is_err());
        assert!(Method::from_str("gEt").is_err());
        assert!(Method::from_str("post").is_err());
        assert!(Method::from_str("Post").is_err());
        assert!(Method::from_str("delete").is_err());
        assert!(Method::from_str(" GET").is_err());
        assert!(Method::from_str("GET ").is_err());
    }

    #[test]
    fn test_method_from_str_invalid() {
        use std::str::FromStr;
        assert!(Method::from_str("").is_err());
        assert!(Method::from_str("UNKNOWN").is_err());
        assert!(Method::from_str("GET ").is_err());
        assert!(Method::from_str(" GET").is_err());
        assert!(Method::from_str("123").is_err());
    }

    #[test]
    fn test_method_parse_error_display() {
        use std::str::FromStr;
        let err = Method::from_str("INVALID").unwrap_err();
        assert_eq!(format!("{}", err), "invalid HTTP method");
        assert!(format!("{:?}", err).contains("MethodParseError"));
    }

    // ─────────────────────────────────────────────
    // Protocol / Transport 变体测试
    // ─────────────────────────────────────────────

    #[test]
    fn test_protocol_variants() {
        let protocols = [
            Protocol::Http1,
            Protocol::Http2,
            Protocol::Http3,
            Protocol::Tcp,
            Protocol::Udp,
            Protocol::Quic,
        ];
        for (i, p) in protocols.iter().enumerate() {
            for (j, q) in protocols.iter().enumerate() {
                if i == j {
                    assert_eq!(p, q);
                } else {
                    assert_ne!(p, q);
                }
            }
        }
    }

    #[test]
    fn test_transport_variants() {
        assert_eq!(Transport::Plaintext, Transport::Plaintext);
        assert_eq!(Transport::Tls13, Transport::Tls13);
        assert_ne!(Transport::Plaintext, Transport::Tls13);
    }

    // ─────────────────────────────────────────────
    // CanonicalHeader 边界测试
    // ─────────────────────────────────────────────

    #[test]
    fn test_canonical_header_empty() {
        let hdr = CanonicalHeader::empty();
        assert!(hdr.is_empty());
        assert_eq!(hdr.name_len, 0);
        assert_eq!(hdr.value_len, 0);
        assert_eq!(hdr.name_str(), "");
        assert_eq!(hdr.value_str(), "");
    }

    #[test]
    fn test_canonical_header_value_overlong_rejected() {
        // 超长值:fail-closed 拒绝,禁止静默截断
        let long_value = vec![b'x'; MAX_HEADER_VALUE_LEN + 100];
        assert!(CanonicalHeader::from_bytes(b"name", &long_value).is_none());

        // 边界:恰好等于上限时允许
        let exact_value = vec![b'x'; MAX_HEADER_VALUE_LEN];
        let hdr = CanonicalHeader::from_bytes(b"name", &exact_value).unwrap();
        assert_eq!(hdr.value_len, MAX_HEADER_VALUE_LEN as u16);
        assert_eq!(hdr.value_str().len(), MAX_HEADER_VALUE_LEN);
    }

    #[test]
    fn test_canonical_header_zero_length() {
        let hdr = CanonicalHeader::from_bytes(b"", b"").unwrap();
        assert!(hdr.is_empty());
        assert_eq!(hdr.name_str(), "");
        assert_eq!(hdr.value_str(), "");
    }

    #[test]
    fn test_canonical_header_invalid_utf8() {
        let invalid_utf8 = [0xFF, 0xFE, 0xFD];
        let hdr = CanonicalHeader::from_bytes(&invalid_utf8, b"value").unwrap();
        // 无效 UTF-8 应返回空字符串
        assert_eq!(hdr.name_str(), "");
    }

    // ─────────────────────────────────────────────
    // CanonicalRequest 全字段验证
    // ─────────────────────────────────────────────

    #[test]
    fn test_canonical_request_full_fields() {
        let mut req = CanonicalRequest::empty();
        req.method = Method::Put;
        assert!(req.set_scheme("https"));
        assert!(req.set_authority("api.example.com:8443"));
        assert!(req.set_path("/api/v1/users/42"));
        assert!(req.set_query("id=42&name=test&verbose=true"));
        req.protocol = Protocol::Http2;
        req.transport = Transport::Tls13;
        req.generation = 12345;
        req.deadline_ms = 30000;
        req.cancelled = false;
        req.resource_lease = 999;

        assert_eq!(req.method, Method::Put);
        assert_eq!(req.scheme_str(), "https");
        assert_eq!(req.authority_str(), "api.example.com:8443");
        assert_eq!(req.path_str(), "/api/v1/users/42");
        assert_eq!(req.query_str(), "id=42&name=test&verbose=true");
        assert_eq!(req.protocol, Protocol::Http2);
        assert_eq!(req.transport, Transport::Tls13);
        assert_eq!(req.generation, 12345);
        assert_eq!(req.deadline_ms, 30000);
        assert!(!req.is_cancelled());
        assert_eq!(req.resource_lease, 999);
    }

    #[test]
    fn test_canonical_request_scheme_overlong_rejected() {
        // fail-closed:超长方案原子拒绝(不修改原值),禁止静默截断
        let mut req = CanonicalRequest::empty();
        assert!(req.set_scheme("https"));
        assert!(!req.set_scheme("https-and-more"));
        // 原值保持不变
        assert_eq!(req.scheme_str(), "https");

        // 边界:恰好 8 字节允许
        let mut req2 = CanonicalRequest::empty();
        assert!(req2.set_scheme("12345678"));
        assert_eq!(req2.scheme_str(), "12345678");
    }

    #[test]
    fn test_canonical_request_path_overlong_rejected() {
        // fail-closed:超长路径原子拒绝(不修改原值),禁止静默截断
        let mut req = CanonicalRequest::empty();
        assert!(req.set_path("/original"));
        let long_path = "a".repeat(MAX_PATH_LEN + 100);
        assert!(!req.set_path(&long_path));
        assert_eq!(req.path_str(), "/original");

        // 边界:恰好等于上限时允许
        let exact_path = "a".repeat(MAX_PATH_LEN);
        assert!(req.set_path(&exact_path));
        assert_eq!(req.path_str().len(), MAX_PATH_LEN);
    }

    #[test]
    fn test_set_path_splits_query() {
        let mut req = CanonicalRequest::empty();
        // request target 中的 `?` 之后部分必须拆分到 query 字段,
        // 否则 "/api?x=1" 会作为整体参与路由匹配而被击穿
        assert!(req.set_path("/api/users?id=42&verbose=true"));
        assert_eq!(req.path_str(), "/api/users");
        assert_eq!(req.query_str(), "id=42&verbose=true");

        // 无 `?` 时 query 保持原状
        let mut req2 = CanonicalRequest::empty();
        assert!(req2.set_query("keep=1"));
        assert!(req2.set_path("/plain/path"));
        assert_eq!(req2.path_str(), "/plain/path");
        assert_eq!(req2.query_str(), "keep=1");

        // `?` 后为空:query 为空串
        let mut req3 = CanonicalRequest::empty();
        assert!(req3.set_path("/api?"));
        assert_eq!(req3.path_str(), "/api");
        assert_eq!(req3.query_str(), "");
    }

    #[test]
    fn test_set_path_overlong_split_query_atomic_rejected() {
        // 路径部分合法但拆分出的 query 超长:path 与 query 均不修改(原子拒绝)
        let mut req = CanonicalRequest::empty();
        assert!(req.set_query("keep=1"));
        let long_target = format!("/ok?{}", "a".repeat(MAX_QUERY_LEN + 1));
        assert!(!req.set_path(&long_target));
        assert_eq!(req.path_str(), "");
        assert_eq!(req.query_str(), "keep=1");
    }

    #[test]
    fn test_add_header_overlong_rejected() {
        let mut req = CanonicalRequest::empty();

        // 名称超长:fail-closed 拒绝
        let long_name = vec![b'n'; MAX_HEADER_NAME_LEN + 1];
        let result = req.add_header(&long_name, b"value");
        assert_eq!(result, Err("header name too long"));

        // 值超长:fail-closed 拒绝
        let long_value = vec![b'v'; MAX_HEADER_VALUE_LEN + 1];
        let result = req.add_header(b"name", &long_value);
        assert_eq!(result, Err("header value too long"));

        // 两次拒绝均未污染头部表
        assert_eq!(req.header_count(), 0);

        // 边界:恰好等于上限时允许
        let exact_name = vec![b'n'; MAX_HEADER_NAME_LEN];
        let exact_value = vec![b'v'; MAX_HEADER_VALUE_LEN];
        assert!(req.add_header(&exact_name, &exact_value).is_ok());
        assert_eq!(req.header_count(), 1);
    }

    #[test]
    fn test_response_add_header_overlong_rejected() {
        let mut resp = CanonicalResponse::new(200);

        let long_name = vec![b'n'; MAX_HEADER_NAME_LEN + 1];
        assert!(resp.add_header(&long_name, b"value").is_err());

        let long_value = vec![b'v'; MAX_HEADER_VALUE_LEN + 1];
        assert!(resp.add_header(b"name", &long_value).is_err());

        assert_eq!(resp.header_count(), 0);
    }

    #[test]
    fn test_canonical_request_query_overlong_rejected() {
        // fail-closed:超长 query 原子拒绝(不修改原值),禁止静默截断
        let mut req = CanonicalRequest::empty();
        assert!(req.set_query("keep=1"));
        let long_query = "a".repeat(MAX_QUERY_LEN + 100);
        assert!(!req.set_query(&long_query));
        assert_eq!(req.query_str(), "keep=1");

        // 边界:恰好等于上限时允许
        let exact_query = "a".repeat(MAX_QUERY_LEN);
        assert!(req.set_query(&exact_query));
        assert_eq!(req.query_str().len(), MAX_QUERY_LEN);
    }

    #[test]
    fn test_canonical_request_authority_overlong_rejected() {
        // fail-closed:超长 authority 原子拒绝(不修改原值),禁止静默截断
        let mut req = CanonicalRequest::empty();
        assert!(req.set_authority("example.com"));
        let long_auth = "a".repeat(MAX_AUTHORITY_LEN + 100);
        assert!(!req.set_authority(&long_auth));
        assert_eq!(req.authority_str(), "example.com");

        // 边界:恰好等于上限时允许
        let exact_auth = "a".repeat(MAX_AUTHORITY_LEN);
        assert!(req.set_authority(&exact_auth));
        assert_eq!(req.authority_str().len(), MAX_AUTHORITY_LEN);
    }

    #[test]
    fn test_canonical_request_empty_strings() {
        let mut req = CanonicalRequest::empty();
        assert!(req.set_scheme(""));
        assert!(req.set_authority(""));
        assert!(req.set_path(""));
        assert!(req.set_query(""));

        assert_eq!(req.scheme_str(), "");
        assert_eq!(req.authority_str(), "");
        assert_eq!(req.path_str(), "");
        assert_eq!(req.query_str(), "");
    }

    // ─────────────────────────────────────────────
    // CanonicalRequest Header 操作边界
    // ─────────────────────────────────────────────

    #[test]
    fn test_canonical_request_get_header_boundary() {
        let mut req = CanonicalRequest::empty();
        req.add_header(b"h1", b"v1").unwrap();
        req.add_header(b"h2", b"v2").unwrap();

        assert!(req.get_header(0).is_some());
        assert!(req.get_header(1).is_some());
        assert!(req.get_header(2).is_none());
        assert!(req.get_header(100).is_none());
    }

    #[test]
    fn test_canonical_request_find_header_case_insensitive() {
        let mut req = CanonicalRequest::empty();
        req.add_header(b"Content-Type", b"application/json").unwrap();

        // find_header 是 ASCII 大小写不敏感的(RFC 7230 §3.2)
        assert!(req.find_header("Content-Type").is_some());
        assert!(req.find_header("content-type").is_some());
        assert!(req.find_header("CONTENT-TYPE").is_some());
        assert!(req.find_header("cOnTeNt-tYpE").is_some());
        // 不同名称仍然不匹配
        assert!(req.find_header("content-length").is_none());
    }

    #[test]
    fn test_canonical_request_headers_iter() {
        let mut req = CanonicalRequest::empty();
        req.add_header(b"a", b"1").unwrap();
        req.add_header(b"b", b"2").unwrap();
        req.add_header(b"c", b"3").unwrap();

        let headers = req.headers_iter();
        assert_eq!(headers.len(), 3);
        assert_eq!(headers[0].name_str(), "a");
        assert_eq!(headers[1].name_str(), "b");
        assert_eq!(headers[2].name_str(), "c");
    }

    #[test]
    fn test_canonical_request_headers_iter_empty() {
        let req = CanonicalRequest::empty();
        assert!(req.headers_iter().is_empty());
    }

    // ─────────────────────────────────────────────
    // CanonicalRequest 治理字段
    // ─────────────────────────────────────────────

    #[test]
    fn test_canonical_request_cancel() {
        let mut req = CanonicalRequest::empty();
        assert!(!req.is_cancelled());
        req.cancel();
        assert!(req.is_cancelled());
        // 再次 cancel 应该还是 true
        req.cancel();
        assert!(req.is_cancelled());
    }

    #[test]
    fn test_canonical_request_deadline_zero() {
        let mut req = CanonicalRequest::empty();
        assert_eq!(req.deadline_ms, 0);
        req.deadline_ms = 0;
        assert_eq!(req.deadline_ms, 0);
    }

    #[test]
    fn test_canonical_request_resource_lease() {
        let mut req = CanonicalRequest::empty();
        assert_eq!(req.resource_lease, 0);
        req.resource_lease = u64::MAX;
        assert_eq!(req.resource_lease, u64::MAX);
    }

    // ─────────────────────────────────────────────
    // BodyStream 边界测试
    // ─────────────────────────────────────────────

    #[test]
    fn test_body_stream_single_use() {
        let data = b"hello";
        let mut stream = BodyStream::new(data);
        assert_eq!(stream.get_data(), Some(&data[..]));
        assert!(stream.is_consumed());
        assert!(stream.get_data().is_none());
        assert!(stream.get_data().is_none());
    }

    #[test]
    fn test_body_stream_len_unchanged_after_consume() {
        let data = b"test data";
        let mut stream = BodyStream::new(data);
        assert_eq!(stream.len(), 9);
        let _ = stream.get_data();
        assert_eq!(stream.len(), 9);
    }

    #[test]
    fn test_body_stream_empty_data_never_consumable() {
        let mut stream = BodyStream::new(b"");
        assert!(stream.is_empty());
        assert!(!stream.is_consumed());
        // 空数据即使首次调用也返回 None
        assert!(stream.get_data().is_none());
        // consumed 状态不变因为数据为空
        assert!(!stream.is_consumed());
    }

    #[test]
    fn test_body_stream_large_data() {
        let large_data = vec![b'x'; 10000];
        let mut stream = BodyStream::new(&large_data);
        assert_eq!(stream.len(), 10000);
        assert!(!stream.is_empty());
        let result = stream.get_data().unwrap();
        assert_eq!(result.len(), 10000);
    }

    // ─────────────────────────────────────────────
    // CanonicalResponse 全字段验证
    // ─────────────────────────────────────────────

    #[test]
    fn test_canonical_response_full_fields() {
        let mut resp = CanonicalResponse::new(418);
        resp.add_header(b"content-type", b"text/plain").unwrap();
        resp.add_header(b"x-custom", b"value").unwrap();
        resp.set_body(b"I'm a teapot".to_vec());

        assert_eq!(resp.status_code, 418);
        assert_eq!(resp.header_count(), 2);
        assert_eq!(resp.body(), b"I'm a teapot");
    }

    #[test]
    fn test_canonical_response_header_limit() {
        let mut resp = CanonicalResponse::new(200);
        for i in 0..MAX_HEADER_COUNT {
            let name = format!("h{}", i);
            resp.add_header(name.as_bytes(), b"v").unwrap();
        }
        assert_eq!(resp.header_count(), MAX_HEADER_COUNT as u8);
        assert!(resp.add_header(b"overflow", b"v").is_err());
    }

    #[test]
    fn test_canonical_response_find_header() {
        let mut resp = CanonicalResponse::new(200);
        resp.add_header(b"Server", b"zenith").unwrap();
        resp.add_header(b"Date", b"today").unwrap();

        assert!(resp.find_header("Server").is_some());
        assert!(resp.find_header("Date").is_some());
        // ASCII 大小写不敏感(RFC 7230 §3.2)
        assert!(resp.find_header("server").is_some());
        assert!(resp.find_header("DATE").is_some());
        assert!(resp.find_header("X-Missing").is_none());
    }

    #[test]
    fn test_canonical_response_headers_iter() {
        let mut resp = CanonicalResponse::new(200);
        resp.add_header(b"a", b"1").unwrap();
        resp.add_header(b"b", b"2").unwrap();

        let headers = resp.headers_iter();
        assert_eq!(headers.len(), 2);
    }

    #[test]
    fn test_canonical_response_body_empty() {
        let resp = CanonicalResponse::new(204);
        assert!(resp.body().is_empty());
    }

    #[test]
    fn test_canonical_response_body_replace() {
        let mut resp = CanonicalResponse::new(200);
        resp.set_body(b"first".to_vec());
        assert_eq!(resp.body(), b"first");
        resp.set_body(b"second".to_vec());
        assert_eq!(resp.body(), b"second");
    }

    // ─────────────────────────────────────────────
    // Service / ServiceFactory trait 对象测试
    // ─────────────────────────────────────────────

    struct EchoService;

    impl Service for EchoService {
        fn handle(&self, request: CanonicalRequest) -> CanonicalResponse {
            let mut resp = CanonicalResponse::ok();
            resp.set_body(request.path_str().as_bytes().to_vec());
            resp
        }
    }

    struct EchoServiceFactory;

    impl ServiceFactory for EchoServiceFactory {
        fn create(&self) -> Box<dyn Service> {
            Box::new(EchoService)
        }
    }

    #[test]
    fn test_service_trait_object() {
        let service: Box<dyn Service> = Box::new(EchoService);
        let mut req = CanonicalRequest::empty();
        assert!(req.set_path("/hello"));
        let resp = service.handle(req);
        assert_eq!(resp.status_code, 200);
        assert_eq!(resp.body(), b"/hello");
    }

    #[test]
    fn test_service_factory_trait() {
        let factory = EchoServiceFactory;
        let service = factory.create();
        let mut req = CanonicalRequest::empty();
        assert!(req.set_path("/test"));
        let resp = service.handle(req);
        assert_eq!(resp.body(), b"/test");
    }

    // ─────────────────────────────────────────────
    // add_header CRLF 注入拒绝(响应拆分防护)
    // ─────────────────────────────────────────────

    #[test]
    fn test_add_header_rejects_crlf() {
        let mut req = CanonicalRequest::empty();

        // 名称含 CR/LF → Err
        assert_eq!(
            req.add_header(b"bad\rname", b"v"),
            Err("header name contains CRLF")
        );
        assert_eq!(
            req.add_header(b"bad\nname", b"v"),
            Err("header name contains CRLF")
        );
        assert_eq!(
            req.add_header(b"bad\r\nname", b"v"),
            Err("header name contains CRLF")
        );

        // 值含 CR/LF → Err
        assert_eq!(
            req.add_header(b"name", b"bad\rvalue"),
            Err("header value contains CRLF")
        );
        assert_eq!(
            req.add_header(b"name", b"bad\nvalue"),
            Err("header value contains CRLF")
        );
        // 完整走私形态:值内注入整条头部
        assert!(req.add_header(b"name", b"ok\r\nEvil: x").is_err());

        // 全部拒绝后头部表未被污染
        assert_eq!(req.header_count(), 0);

        // CanonicalResponse 同样拒绝
        let mut resp = CanonicalResponse::new(200);
        assert_eq!(
            resp.add_header(b"bad\rname", b"v"),
            Err("header name contains CRLF")
        );
        assert_eq!(
            resp.add_header(b"name", b"bad\nvalue"),
            Err("header value contains CRLF")
        );
        assert_eq!(resp.header_count(), 0);
    }

    // ─────────────────────────────────────────────
    // CanonicalRequest set_body 溢出堆路径
    // ─────────────────────────────────────────────

    #[test]
    fn test_request_set_body_overflow_heap_path() {
        let mut req = CanonicalRequest::empty();

        // 5000 字节 > MAX_BODY_LEN(4096):走 body_overflow 堆路径
        let big = vec![b'x'; 5000];
        assert!(big.len() > MAX_BODY_LEN);
        req.set_body(big.clone());
        // body() 可读全量,溢出缓冲区为 Some
        assert!(req.body_overflow.is_some());
        assert_eq!(req.body().len(), 5000);
        assert_eq!(req.body(), &big[..]);

        // 回落到小 body:清空溢出,回到栈缓冲
        req.set_body(b"small".to_vec());
        assert!(req.body_overflow.is_none());
        assert_eq!(req.body(), b"small");
    }
}