potato 0.3.12

A very simple and high performance http library.
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
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
#[cfg(feature = "http2")]
mod http2;
#[cfg(feature = "http3")]
mod http3;

use crate::utils::enums::HttpConnection;
use crate::utils::refstr::HeaderItem;
use crate::utils::tcp_stream::HttpStream;
use crate::CompressMode;
use crate::{
    HttpHandler, HttpMethod, HttpRequest, HttpRequestTargetForm, HttpResponse, PreflightResult,
};
use crate::{RequestHandlerFlag, TransferSession};
use std::any::TypeId;
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::fs::Metadata;
use std::future::Future;
use std::io::{Read, Seek, SeekFrom};
use std::net::SocketAddr;
use std::path::{Component, Path, PathBuf};
use std::pin::Pin;
use std::sync::{Arc, LazyLock};
use std::time::UNIX_EPOCH;
use tokio::net::TcpListener;
use tokio::select;
use tokio::sync::{oneshot, Mutex};
use tokio::time::{interval, Duration};
#[cfg(any(feature = "tls", feature = "http3"))]
use tokio_rustls::rustls;
#[cfg(any(feature = "tls", feature = "http3"))]
use tokio_rustls::rustls::pki_types::{pem::PemObject, CertificateDer, PrivateKeyDer};
#[cfg(feature = "tls")]
use tokio_rustls::TlsAcceptor;

/// CORS配置
#[derive(Debug, Clone)]
pub struct CorsConfig {
    pub origin: Option<String>,         // Access-Control-Allow-Origin
    pub methods: Option<String>,        // Access-Control-Allow-Methods
    pub headers: Option<String>,        // Access-Control-Allow-Headers
    pub max_age: Option<String>,        // Access-Control-Max-Age
    pub credentials: bool,              // Access-Control-Allow-Credentials
    pub expose_headers: Option<String>, // Access-Control-Expose-Headers
}

impl CorsConfig {
    /// 创建最小限制默认配置
    pub fn default_minimal() -> Self {
        Self {
            origin: Some("*".to_string()),
            methods: None, // 自动计算
            headers: Some("*".to_string()),
            max_age: Some("86400".to_string()),
            credentials: false,
            expose_headers: None,
        }
    }
}

type AsyncCustomHandler = dyn Fn(&mut HttpRequest) -> Pin<Box<dyn Future<Output = Option<HttpResponse>> + Send + '_>>
    + Send
    + Sync;

type SyncCustomHandler = dyn Fn(&mut HttpRequest) -> Option<HttpResponse> + Send + Sync;

type GlobalPreprocessHandler = for<'a> fn(
    &'a mut HttpRequest,
) -> Pin<
    Box<dyn Future<Output = anyhow::Result<Option<HttpResponse>>> + Send + 'a>,
>;

type GlobalPostprocessHandler =
    for<'a> fn(
        &'a mut HttpRequest,
        &'a mut HttpResponse,
    ) -> Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send + 'a>>;

// Re-export WebTransport types from http3 module
#[cfg(feature = "http3")]
pub use http3::{WebTransportConfig, WebTransportHandler, WebTransportSession, WebTransportStream};

#[derive(Clone)]
pub enum CustomHandler {
    Sync(Arc<SyncCustomHandler>),
    Async(Arc<AsyncCustomHandler>),
}

#[derive(Clone)]
pub enum PreprocessHandler {
    Fn(GlobalPreprocessHandler),
}

#[derive(Clone)]
pub enum PostprocessHandler {
    Fn(GlobalPostprocessHandler),
}

static HANDLERS: LazyLock<HashMap<&'static str, HashMap<HttpMethod, &'static RequestHandlerFlag>>> =
    LazyLock::new(|| {
        let mut handlers = HashMap::with_capacity(16);
        for flag in inventory::iter::<RequestHandlerFlag> {
            handlers
                .entry(flag.path)
                .or_insert_with(|| HashMap::with_capacity(16))
                .insert(flag.method, flag);
        }
        handlers
    });

static HANDLERS_FLAT: LazyLock<HashMap<(&'static str, HttpMethod), &'static RequestHandlerFlag>> =
    LazyLock::new(|| {
        let mut handlers = HashMap::with_capacity(64);
        for flag in inventory::iter::<RequestHandlerFlag> {
            handlers.insert((flag.path, flag.method), flag);
        }
        handlers
    });

pub enum PipeContextItem {
    Handlers,
    LocationRoute((String, String, bool)),
    EmbeddedRoute(HashMap<String, Cow<'static, [u8]>>),
    FinalRoute(HttpResponse),
    Custom(CustomHandler),
    Preprocess(PreprocessHandler),
    Postprocess(PostprocessHandler),
    LimitSize(usize, usize), // (max_header_bytes, max_body_bytes)
    TransferRate(u64, u64),  // (入站速率限制 bits/sec, 出站速率限制 bits/sec)
    ReverseProxy(String, String, bool),
    #[cfg(all(feature = "jemalloc", not(target_os = "windows")))]
    Jemalloc(String),
    #[cfg(feature = "webdav")]
    Webdav((String, dav_server::DavHandler)),
    #[cfg(feature = "http3")]
    WebTransport((String, WebTransportConfig, WebTransportHandler)),
    #[cfg(feature = "webrtc")]
    WebRTC((crate::webrtc::WebRTCConfig, crate::webrtc::WebRTCEvents)),
}

// 手动实现 Clone,因为 WebTransportHandler 不能 Clone
impl Clone for PipeContextItem {
    fn clone(&self) -> Self {
        match self {
            PipeContextItem::Handlers => PipeContextItem::Handlers,
            PipeContextItem::LocationRoute(v) => PipeContextItem::LocationRoute(v.clone()),
            PipeContextItem::EmbeddedRoute(v) => PipeContextItem::EmbeddedRoute(v.clone()),
            PipeContextItem::FinalRoute(v) => PipeContextItem::FinalRoute(v.clone()),
            PipeContextItem::Custom(v) => PipeContextItem::Custom(v.clone()),
            PipeContextItem::Preprocess(v) => PipeContextItem::Preprocess(v.clone()),
            PipeContextItem::Postprocess(v) => PipeContextItem::Postprocess(v.clone()),
            PipeContextItem::LimitSize(h, b) => PipeContextItem::LimitSize(*h, *b),
            PipeContextItem::TransferRate(r1, r2) => PipeContextItem::TransferRate(*r1, *r2),
            PipeContextItem::ReverseProxy(v1, v2, v3) => {
                PipeContextItem::ReverseProxy(v1.clone(), v2.clone(), *v3)
            }
            #[cfg(all(feature = "jemalloc", not(target_os = "windows")))]
            PipeContextItem::Jemalloc(v) => PipeContextItem::Jemalloc(v.clone()),
            #[cfg(feature = "webdav")]
            PipeContextItem::Webdav(v) => PipeContextItem::Webdav(v.clone()),
            #[cfg(feature = "http3")]
            PipeContextItem::WebTransport(_) => panic!("WebTransport handler cannot be cloned"),
            #[cfg(feature = "webrtc")]
            PipeContextItem::WebRTC(v) => PipeContextItem::WebRTC(v.clone()),
        }
    }
}

pub struct PipeContext {
    items: Vec<PipeContextItem>,
}

impl PipeContext {
    fn sanitize_location_route_path(loc_path: &str, request_suffix: &str) -> Option<PathBuf> {
        let mut path = PathBuf::from(loc_path);
        for component in Path::new(request_suffix).components() {
            match component {
                Component::CurDir => {}
                Component::Normal(part) => path.push(part),
                Component::ParentDir | Component::RootDir | Component::Prefix(_) => return None,
            }
        }
        Some(path)
    }

    fn path_stays_inside_root(path: &Path, root: &Path) -> bool {
        std::fs::canonicalize(path)
            .map(|resolved| resolved.starts_with(root))
            .unwrap_or(false)
    }

    fn static_file_etag(meta: &Metadata) -> Option<String> {
        if let Ok(modified) = meta.modified() {
            if let Ok(duration) = modified.duration_since(UNIX_EPOCH) {
                let modified_secs = duration.as_secs();
                let file_size = meta.len();
                return Some(format!("\"{:x}-{:x}\"", modified_secs, file_size));
            }
        }
        None
    }

    fn add_static_validators(res: &mut HttpResponse, meta: &Metadata, etag: Option<&str>) {
        if let Ok(modified) = meta.modified() {
            if let Ok(duration) = modified.duration_since(UNIX_EPOCH) {
                let modified_time = chrono::DateTime::<chrono::Utc>::from(UNIX_EPOCH + duration);
                res.add_header(
                    "Last-Modified".into(),
                    modified_time
                        .format("%a, %d %b %Y %H:%M:%S GMT")
                        .to_string()
                        .into(),
                );
            }
        }
        if let Some(etag) = etag {
            res.add_header("ETag".into(), etag.to_string().into());
        }
    }

    fn add_embedded_validators(res: &mut HttpResponse, meta: Option<&Metadata>, etag: &str) {
        if let Some(meta) = meta {
            if let Ok(modified) = meta.modified() {
                if let Ok(duration) = modified.duration_since(UNIX_EPOCH) {
                    let modified_time =
                        chrono::DateTime::<chrono::Utc>::from(UNIX_EPOCH + duration);
                    res.add_header(
                        "Last-Modified".into(),
                        modified_time
                            .format("%a, %d %b %Y %H:%M:%S GMT")
                            .to_string()
                            .into(),
                    );
                }
            }
        }
        res.add_header("ETag".into(), etag.to_string().into());
    }

    fn should_apply_range_for_embedded(
        req: &HttpRequest,
        meta: Option<&Metadata>,
        etag: &str,
    ) -> bool {
        if req.get_header_key(HeaderItem::Range).is_none() {
            return false;
        }
        let Some(if_range) = req.get_header_key(HeaderItem::If_Range) else {
            return true;
        };
        let if_range = if_range.trim();
        if if_range.is_empty() {
            return false;
        }
        if if_range.starts_with('"') {
            return etag == if_range;
        }
        let Some(meta) = meta else {
            return false;
        };
        let Some(modified_secs) = meta
            .modified()
            .ok()
            .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
            .map(|d| d.as_secs())
        else {
            return false;
        };
        match crate::parse_http_date(if_range) {
            Ok(since_timestamp) => modified_secs <= since_timestamp,
            Err(_) => false,
        }
    }

    fn should_apply_range(req: &HttpRequest, meta: &Metadata, etag: Option<&str>) -> bool {
        if req.get_header_key(HeaderItem::Range).is_none() {
            return false;
        }
        let Some(if_range) = req.get_header_key(HeaderItem::If_Range) else {
            return true;
        };
        let if_range = if_range.trim();
        if if_range.is_empty() {
            return false;
        }
        if if_range.starts_with('"') {
            return etag.is_some_and(|tag| tag == if_range);
        }
        let Some(modified_secs) = meta
            .modified()
            .ok()
            .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
            .map(|d| d.as_secs())
        else {
            return false;
        };
        match crate::parse_http_date(if_range) {
            Ok(since_timestamp) => modified_secs <= since_timestamp,
            Err(_) => false,
        }
    }

    fn parse_single_byte_range(range_header: &str, file_size: u64) -> Option<Option<(u64, u64)>> {
        let range_header = range_header.trim();
        if file_size == 0 {
            return Some(None);
        }
        let Some(spec) = range_header.strip_prefix("bytes=") else {
            return None;
        };
        if spec.contains(',') {
            return None;
        }
        let spec = spec.trim();
        if spec.is_empty() {
            return None;
        }

        if let Some(suffix) = spec.strip_prefix('-') {
            let Ok(suffix_len) = suffix.parse::<u64>() else {
                return None;
            };
            if suffix_len == 0 {
                return Some(None);
            }
            let start = if suffix_len >= file_size {
                0
            } else {
                file_size - suffix_len
            };
            return Some(Some((start, file_size - 1)));
        }

        let Some((start_str, end_str)) = spec.split_once('-') else {
            return None;
        };
        let Ok(start) = start_str.trim().parse::<u64>() else {
            return None;
        };
        if start >= file_size {
            return Some(None);
        }

        if end_str.trim().is_empty() {
            return Some(Some((start, file_size - 1)));
        }

        let Ok(mut end) = end_str.trim().parse::<u64>() else {
            return None;
        };
        if end >= file_size {
            end = file_size - 1;
        }
        if start > end {
            return Some(None);
        }
        Some(Some((start, end)))
    }

    fn read_file_range(path: &str, start: u64, end: u64) -> anyhow::Result<Vec<u8>> {
        let mut file = std::fs::File::open(path)?;
        file.seek(SeekFrom::Start(start))?;
        let read_len_u64 = end - start + 1;
        let read_len = usize::try_from(read_len_u64)?;
        let mut buffer = vec![0u8; read_len];
        file.read_exact(&mut buffer)?;
        Ok(buffer)
    }

    fn from_static_file(req: &HttpRequest, path: &str, meta: &Metadata) -> HttpResponse {
        let etag = Self::static_file_etag(meta);
        match req.check_precondition_headers(Some(meta), etag.as_deref()) {
            PreflightResult::NotModified => {
                let mut res = HttpResponse::empty();
                res.http_code = 304;
                Self::add_static_validators(&mut res, meta, etag.as_deref());
                return res;
            }
            PreflightResult::PreconditionFailed => {
                let mut res = HttpResponse::error("Precondition Failed");
                res.http_code = 412;
                Self::add_static_validators(&mut res, meta, etag.as_deref());
                return res;
            }
            PreflightResult::Proceed => {}
        }

        if Self::should_apply_range(req, meta, etag.as_deref()) {
            if let Some(parsed_range) = req
                .get_header_key(HeaderItem::Range)
                .and_then(|range| Self::parse_single_byte_range(range, meta.len()))
            {
                match parsed_range {
                    Some((start, end)) => {
                        let data = match Self::read_file_range(path, start, end) {
                            Ok(data) => data,
                            Err(err) => return HttpResponse::error(format!("{err}")),
                        };
                        let mut res = HttpResponse::from_mem_file(path, data, false, None);
                        res.http_code = 206;
                        res.add_header(
                            "Content-Range".into(),
                            format!("bytes {start}-{end}/{}", meta.len()).into(),
                        );
                        res.add_header("Accept-Ranges".into(), "bytes".into());
                        Self::add_static_validators(&mut res, meta, etag.as_deref());
                        return res;
                    }
                    None => {
                        let mut res = HttpResponse::empty();
                        res.http_code = 416;
                        res.add_header(
                            "Content-Range".into(),
                            format!("bytes */{}", meta.len()).into(),
                        );
                        res.add_header("Accept-Ranges".into(), "bytes".into());
                        Self::add_static_validators(&mut res, meta, etag.as_deref());
                        return res;
                    }
                }
            }
        }

        let mut res = HttpResponse::from_file(path, false, Some(meta.clone()));
        res.add_header("Accept-Ranges".into(), "bytes".into());
        res
    }

    pub fn new() -> Self {
        Self {
            items: vec![PipeContextItem::Handlers],
        }
    }

    pub fn empty() -> Self {
        Self { items: vec![] }
    }

    pub fn clone_items(&self) -> Vec<PipeContextItem> {
        self.items.clone()
    }

    pub fn use_handlers(&mut self) {
        self.items.push(PipeContextItem::Handlers);
    }

    pub fn use_location_route(
        &mut self,
        url_path: impl Into<String>,
        loc_path: impl Into<String>,
        allow_symlink_escape: bool,
    ) {
        let (url_path, loc_path) = (url_path.into(), loc_path.into());
        self.items.push(PipeContextItem::LocationRoute((
            url_path,
            loc_path,
            allow_symlink_escape,
        )));
    }

    pub fn use_embedded_route(
        &mut self,
        url_path: impl Into<String>,
        assets: HashMap<String, Cow<'static, [u8]>>,
    ) {
        let mut ret = HashMap::with_capacity(16);
        let url_path = {
            let mut url_path: String = url_path.into();
            if url_path.ends_with('/') {
                url_path.pop();
            }
            url_path
        };
        for (key, value) in assets.into_iter() {
            ret.insert(format!("{url_path}/{key}"), value);
        }
        self.items.push(PipeContextItem::EmbeddedRoute(ret));
    }

    pub fn use_custom<F, Fut>(&mut self, callback: F)
    where
        F: Fn(&mut HttpRequest) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Option<HttpResponse>> + Send + 'static,
    {
        self.items
            .push(PipeContextItem::Custom(CustomHandler::Async(Arc::new(
                move |req| {
                    let fut = callback(req);
                    Box::pin(async move { fut.await })
                },
            ))));
    }

    pub fn use_custom_sync<F>(&mut self, callback: F)
    where
        F: Fn(&mut HttpRequest) -> Option<HttpResponse> + Send + Sync + 'static,
    {
        self.items
            .push(PipeContextItem::Custom(CustomHandler::Sync(Arc::new(
                callback,
            ))));
    }

    pub fn use_custom_async<F>(&mut self, callback: F)
    where
        F: for<'a> Fn(
                &'a mut HttpRequest,
            )
                -> Pin<Box<dyn Future<Output = Option<HttpResponse>> + Send + 'a>>
            + Send
            + Sync
            + 'static,
    {
        self.items
            .push(PipeContextItem::Custom(CustomHandler::Async(Arc::new(
                callback,
            ))));
    }

    /// 添加全局预处理函数
    ///
    /// 预处理函数在所有路由处理之前执行,可以用于认证检查、日志记录等。
    /// 如果返回 `Some(response)`,则直接返回该响应,跳过后续所有处理。
    ///
    /// # 参数
    /// * `handler` - 通过 `#[potato::preprocess]` 宏标注的预处理函数
    ///
    /// # 示例
    /// ```rust,ignore
    /// #[potato::preprocess]
    /// async fn my_preprocess(req: &mut HttpRequest) -> Option<HttpResponse> {
    ///     // 预处理逻辑
    ///     None
    /// }
    ///
    /// server.configure(|ctx| {
    ///     ctx.use_preprocess(my_preprocess);
    ///     ctx.use_handlers();
    /// });
    /// ```
    pub fn use_preprocess(&mut self, handler: GlobalPreprocessHandler) {
        self.items
            .push(PipeContextItem::Preprocess(PreprocessHandler::Fn(handler)));
    }

    /// 添加全局后处理函数
    ///
    /// 后处理函数在 handler 生成响应后执行,可以修改响应内容(如添加响应头)。
    ///
    /// # 参数
    /// * `handler` - 通过 `#[potato::postprocess]` 宏标注的后处理函数
    ///
    /// # 示例
    /// ```rust,ignore
    /// #[potato::postprocess]
    /// async fn my_postprocess(req: &mut HttpRequest, res: &mut HttpResponse) {
    ///     res.add_header("X-Custom".into(), "value".into());
    /// }
    ///
    /// server.configure(|ctx| {
    ///     ctx.use_postprocess(my_postprocess);
    ///     ctx.use_handlers();
    /// });
    /// ```
    pub fn use_postprocess(&mut self, handler: GlobalPostprocessHandler) {
        self.items
            .push(PipeContextItem::Postprocess(PostprocessHandler::Fn(
                handler,
            )));
    }

    /// 添加请求体大小限制中间件
    ///
    /// # 参数
    /// * `max_header_bytes` - Header 总大小限制 (字节)
    /// * `max_body_bytes` - Body 总大小限制 (字节)
    ///
    /// # 示例
    /// ```rust
    /// let mut server = potato::HttpServer::new("127.0.0.1:8080");
    /// server.configure(|ctx| {
    ///     ctx.use_limit_size(1024 * 1024, 50 * 1024 * 1024); // 1MB header, 50MB body
    ///     ctx.use_handlers();
    /// });
    /// ```
    pub fn use_limit_size(&mut self, max_header_bytes: usize, max_body_bytes: usize) {
        self.items.push(PipeContextItem::LimitSize(
            max_header_bytes.max(1),
            max_body_bytes.max(1),
        ));
    }

    /// 添加传输速率限制中间件
    ///
    /// # 参数
    /// * `inbound_rate_bits_per_sec` - 入站最大传输速率(bits/sec),接收请求数据的速率限制
    /// * `outbound_rate_bits_per_sec` - 出站最大传输速率(bits/sec),发送响应数据的速率限制
    ///
    /// # 示例
    /// ```rust
    /// let mut server = potato::HttpServer::new("127.0.0.1:8080");
    /// server.configure(|ctx| {
    ///     ctx.use_transfer_limit(10_000_000, 20_000_000); // 入站 10 Mbps,出站 20 Mbps
    ///     ctx.use_handlers();
    /// });
    /// ```
    pub fn use_transfer_limit(
        &mut self,
        inbound_rate_bits_per_sec: u64,
        outbound_rate_bits_per_sec: u64,
    ) {
        if inbound_rate_bits_per_sec == 0 {
            panic!("Inbound transfer rate limit must be greater than 0");
        }
        if outbound_rate_bits_per_sec == 0 {
            panic!("Outbound transfer rate limit must be greater than 0");
        }
        self.items.push(PipeContextItem::TransferRate(
            inbound_rate_bits_per_sec,
            outbound_rate_bits_per_sec,
        ));
    }

    pub fn use_reverse_proxy(
        &mut self,
        url_path: impl Into<String>,
        proxy_url: impl Into<String>,
        modify_content: bool,
    ) {
        self.items.push(PipeContextItem::ReverseProxy(
            url_path.into(),
            proxy_url.into(),
            modify_content,
        ));
    }

    #[cfg(all(feature = "jemalloc", not(target_os = "windows")))]
    pub fn use_jemalloc(&mut self, url_path: impl Into<String>) {
        self.items.push(PipeContextItem::Jemalloc(url_path.into()));
    }

    #[cfg(feature = "openapi")]
    fn openapi_index_json() -> String {
        use crate::utils::number::HttpCodeExt;
        let mut any_use_auth = false;
        static AUTHOR_REGEX: std::sync::LazyLock<Result<regex::Regex, regex::Error>> =
            std::sync::LazyLock::new(|| regex::Regex::new(r"([[:word:]]+)\s*<([^>]+)>"));
        let contact = {
            match AUTHOR_REGEX
                .as_ref()
                .ok()
                .and_then(|re| re.captures(env!("CARGO_PKG_AUTHORS")))
            {
                Some(caps) => {
                    let name = caps.get(1).map_or("", |m| m.as_str());
                    let email = caps.get(2).map_or("", |m| m.as_str());
                    serde_json::json!({ "name": name, "email": email })
                }
                None => serde_json::json!({}),
            }
        };
        let (tags, paths) = {
            let mut tags = HashMap::with_capacity(16);
            let mut paths = std::collections::HashMap::with_capacity(16);
            for flag in inventory::iter::<RequestHandlerFlag> {
                if !flag.doc.show {
                    continue;
                }
                let mut response_http_codes = vec![200, 500];
                let mut root_cur_path = serde_json::json!({
                    "summary": flag.doc.summary,
                    "description": flag.doc.desp,
                });
                let otag = {
                    // 优先使用 flag.doc.tag(controller 名称)
                    if !flag.doc.tag.is_empty() {
                        Some(flag.doc.tag.to_string())
                    } else {
                        // 回退到原有逻辑(基于路径)
                        let mut otag = None;
                        if let Some(idx) = flag.path.rfind('/') {
                            if idx > 0 {
                                otag = Some(flag.path[1..idx].replace('/', "_"));
                            }
                        }
                        otag
                    }
                };
                if let Some(tag) = otag {
                    tags.insert(tag.clone(), "");
                    root_cur_path["tags"] = serde_json::json!([tag]);
                };
                let arg_pairs = {
                    let mut arg_pairs = vec![];
                    if let Ok(args) = serde_json::from_str::<serde_json::Value>(flag.doc.args) {
                        if let Some(args) = args.as_array() {
                            for arg in args.iter() {
                                let arg_name = arg["name"].as_str().unwrap_or("");
                                let arg_type = {
                                    let arg_type = arg["type"].as_str().unwrap_or("");
                                    match arg_type.starts_with('i') || arg_type.starts_with('u') {
                                        true => "number",
                                        false if arg_type == "PostFile" => "file",
                                        false => "string",
                                    }
                                };
                                arg_pairs.push((arg_name.to_string(), arg_type.to_string()));
                            }
                        }
                    }
                    arg_pairs
                };
                if !arg_pairs.is_empty() {
                    if flag.method == HttpMethod::GET {
                        let mut parameters = vec![];
                        for (arg_name, arg_type) in arg_pairs.iter() {
                            parameters.push(serde_json::json!({
                                "name": arg_name,
                                "in": "query",
                                "description": "",
                                "required": true,
                                "schema": { "type": arg_type },
                            }));
                        }
                        root_cur_path["parameters"] = serde_json::Value::Array(parameters);
                    } else {
                        let mut properties = serde_json::json!({});
                        let mut required = vec![];
                        for (arg_name, arg_type) in arg_pairs.iter() {
                            properties[arg_name] = match arg_type == "file" {
                                true => {
                                    serde_json::json!({ "type": "string", "format": "binary" })
                                }
                                false => serde_json::json!({ "type": arg_type }),
                            };
                            required.push(arg_name);
                        }
                        // TODO add file
                        root_cur_path["requestBody"]["content"] = serde_json::json!({
                            "multipart/form-data": {
                                "schema": {
                                    "type": "object",
                                    "properties": properties,
                                    "required": required
                                }
                            }
                        });
                    }
                }
                if flag.doc.auth {
                    root_cur_path["security"] = serde_json::json!([{ "bearerAuth": [] }]);
                    response_http_codes = vec![200u16, 401, 500];
                    any_use_auth = true;
                }
                for http_code in response_http_codes.into_iter() {
                    let http_code_str = http_code.to_string();
                    root_cur_path["responses"][http_code_str]["description"] =
                        http_code.http_code_to_desp().into();
                }
                paths
                    .entry(flag.path)
                    .or_insert_with(|| HashMap::with_capacity(16))
                    .insert(flag.method.to_string().to_lowercase(), root_cur_path);
            }
            let mut tags: Vec<_> = tags.into_iter().collect::<Vec<_>>();
            tags.sort_by(|a, b| a.0.cmp(&b.0));
            let tags: Vec<_> = tags
                .into_iter()
                .map(|(k, v)| serde_json::json!({"name": k, "description": v}))
                .collect();
            (tags, paths)
        };
        let mut root = serde_json::json!({
            "openapi": "3.1.0",
            "info": {
                "title": env!("CARGO_PKG_NAME"),
                "version": env!("CARGO_PKG_VERSION"),
                "description": env!("CARGO_PKG_DESCRIPTION"),
                "contact": contact,
            },
            "paths": paths,
            "tags": tags,
        });
        if any_use_auth {
            root["components"]["securitySchemes"]["bearerAuth"] = serde_json::json!({
                "description": "Bearer token using a JWT",
                "type": "http",
                "scheme": "Bearer",
                "bearerFormat": "JWT",
            });
        }
        serde_json::to_string(&root).unwrap_or("{}".to_string())
    }

    #[cfg(feature = "openapi")]
    pub fn use_openapi(&mut self, url_path: impl Into<String>) {
        #[derive(rust_embed::Embed)]
        #[folder = "swagger_res"]
        struct DocAsset;

        let mut ret = HashMap::with_capacity(16);
        let url_path = {
            let mut url_path: String = url_path.into();
            if !url_path.ends_with('/') {
                url_path.push('/');
            }
            url_path
        };
        //
        ret.insert(format!("{url_path}index.json"), {
            let bytes = Self::openapi_index_json().into_bytes();
            let static_bytes: &'static [u8] = Box::leak(bytes.into_boxed_slice());
            Cow::Borrowed(static_bytes)
        });
        //
        for name in DocAsset::iter().into_iter() {
            if name == "swagger-initializer.js" {
                ret.insert(
                    format!("{url_path}{name}"),
                    Cow::Borrowed(
                        r#"window.onload = function() {
  window.ui = SwaggerUIBundle({
    url: "index.json",
    dom_id: '#swagger-ui',
    deepLinking: true,
    presets: [ SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset ],
    plugins: [ SwaggerUIBundle.plugins.DownloadUrl ],
    layout: "StandaloneLayout"
  });
};"#
                        .as_bytes(),
                    ),
                );
            } else if let Some(file) = DocAsset::get(&name) {
                if name.ends_with("index.htm") || name.ends_with("index.html") {
                    if let Some(path) = std::path::Path::new(&format!("{url_path}{name}")).parent()
                    {
                        if let Some(path) = path.to_str() {
                            let mut path = path.to_string();
                            if !path.ends_with('/') {
                                path.push('/');
                            }
                            ret.insert(path, file.data.clone());
                        }
                    }
                }
                ret.insert(format!("{url_path}{name}"), file.data);
            }
        }
        self.items.push(PipeContextItem::EmbeddedRoute(ret));
    }

    #[cfg(feature = "webdav")]
    pub fn use_webdav_localfs(
        &mut self,
        url_path: impl Into<String>,
        local_path: impl Into<String>,
    ) {
        let dav_server = dav_server::DavHandler::builder()
            .filesystem(dav_server::localfs::LocalFs::new(
                local_path.into(),
                true,
                false,
                false,
            ))
            .locksystem(dav_server::fakels::FakeLs::new())
            .build_handler();
        self.items
            .push(PipeContextItem::Webdav((url_path.into(), dav_server)));
    }

    #[cfg(feature = "webdav")]
    pub fn use_webdav_memfs(&mut self, url_path: impl Into<String>) {
        let dav_server = dav_server::DavHandler::builder()
            .filesystem(dav_server::memfs::MemFs::new())
            .locksystem(dav_server::fakels::FakeLs::new())
            .build_handler();
        self.items
            .push(PipeContextItem::Webdav((url_path.into(), dav_server)));
    }

    #[cfg(feature = "http3")]
    pub fn use_webtransport<F, Fut>(&mut self, url_path: impl Into<String>, handler: F)
    where
        F: Fn(WebTransportSession) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        self.items.push(PipeContextItem::WebTransport((
            url_path.into(),
            WebTransportConfig::default(),
            Box::new(move |session| Box::pin(handler(session))),
        )));
    }

    #[cfg(feature = "webrtc")]
    pub fn use_webrtc(&mut self) -> crate::webrtc::WebRTCBuilder<'_> {
        crate::webrtc::WebRTCBuilder::new(self)
    }

    #[cfg(feature = "webrtc")]
    pub(crate) fn add_webrtc(
        &mut self,
        config: crate::webrtc::WebRTCConfig,
        events: crate::webrtc::WebRTCEvents,
    ) {
        self.items.push(PipeContextItem::WebRTC((config, events)));
    }

    pub async fn handle_request(
        self2: &PipeContext,
        req: &mut HttpRequest,
        skip: usize,
    ) -> HttpResponse {
        if req.method == HttpMethod::CONNECT {
            let mut res = HttpResponse::text("CONNECT method is not implemented");
            res.http_code = 501;
            return res;
        }

        // 收集所有 Postprocess handlers
        let postprocess_handlers: Vec<&PostprocessHandler> = self2
            .items
            .iter()
            .filter_map(|item| {
                if let PipeContextItem::Postprocess(handler) = item {
                    Some(handler)
                } else {
                    None
                }
            })
            .collect();

        // 执行 Postprocess 的辅助函数
        async fn execute_postprocess(
            handlers: &[&PostprocessHandler],
            req: &mut HttpRequest,
            res: &mut HttpResponse,
        ) {
            for handler in handlers {
                match handler {
                    PostprocessHandler::Fn(fn_handler) => {
                        if let Err(e) = fn_handler(req, res).await {
                            eprintln!("[Postprocess] Error: {}", e);
                        }
                    }
                }
            }
        }

        for (_idx, item) in self2.items.iter().enumerate().skip(skip) {
            match item {
                PipeContextItem::Postprocess(_) => {
                    // Postprocess 已在函数开始时收集,在此跳过
                    continue;
                }
                PipeContextItem::Handlers => {
                    let handler_ref = HANDLERS_FLAT
                        .get(&(&req.url_path[..], req.method))
                        .map(|p| p.handler);
                    if let Some(handler_ref) = handler_ref {
                        let mut res = match handler_ref {
                            HttpHandler::Async(handler) => handler(req).await,
                            HttpHandler::Sync(handler) => handler(req),
                        };
                        execute_postprocess(&postprocess_handlers, req, &mut res).await;
                        return res;
                    } else {
                        if req.method == HttpMethod::HEAD {
                            if let Some(get_handler_ref) = HANDLERS_FLAT
                                .get(&(&req.url_path[..], HttpMethod::GET))
                                .map(|p| p.handler)
                            {
                                req.method = HttpMethod::GET;
                                let mut res = match get_handler_ref {
                                    HttpHandler::Async(handler) => handler(req).await,
                                    HttpHandler::Sync(handler) => handler(req),
                                };
                                req.method = HttpMethod::HEAD;
                                res.body = crate::HttpResponseBody::Data(vec![]);
                                execute_postprocess(&postprocess_handlers, req, &mut res).await;
                                return res;
                            }

                            // If no GET fallback exists, continue the pipeline so
                            // other route handlers (static/custom/proxy) can answer HEAD.
                            continue;
                        } else if req.method == HttpMethod::OPTIONS {
                            let mut res2 = HttpResponse::html("");
                            let methods_str: Cow<'static, str> = {
                                let mut options: HashSet<_> =
                                    [HttpMethod::OPTIONS].into_iter().collect();
                                if req.target_form == HttpRequestTargetForm::Asterisk {
                                    options.extend(HANDLERS_FLAT.keys().map(|(_, method)| *method));
                                    if HANDLERS_FLAT
                                        .keys()
                                        .any(|(_, method)| *method == HttpMethod::GET)
                                    {
                                        options.insert(HttpMethod::HEAD);
                                    }
                                } else if let Some(handlers) = HANDLERS.get(&req.url_path[..]) {
                                    options.extend(handlers.keys().map(|p| *p));
                                    if handlers.contains_key(&HttpMethod::GET) {
                                        options.insert(HttpMethod::HEAD);
                                    }
                                }
                                options
                                    .into_iter()
                                    .map(|m| m.to_string())
                                    .collect::<Vec<_>>()
                                    .join(",")
                                    .into()
                            };

                            res2.add_header("Allow".into(), methods_str);
                            execute_postprocess(&postprocess_handlers, req, &mut res2).await;
                            return res2;
                        } else {
                            continue;
                        }
                    }
                }
                PipeContextItem::LocationRoute((url_path, loc_path, allow_symlink_escape)) => {
                    if !req.url_path.starts_with(url_path) {
                        continue;
                    }
                    let canonical_root = if *allow_symlink_escape {
                        None
                    } else {
                        std::fs::canonicalize(loc_path).ok()
                    };
                    let req_suffix = req.url_path[url_path.len()..].trim_start_matches('/');
                    let path = match Self::sanitize_location_route_path(loc_path, req_suffix) {
                        Some(path) => path,
                        None => {
                            let mut res = HttpResponse::error("url path over directory");
                            execute_postprocess(&postprocess_handlers, req, &mut res).await;
                            return res;
                        }
                    };
                    if let Ok(meta) = std::fs::metadata(&path) {
                        if meta.is_file() {
                            if let Some(root) = canonical_root.as_ref() {
                                if !Self::path_stays_inside_root(&path, root) {
                                    let mut res = HttpResponse::error("url path over directory");
                                    execute_postprocess(&postprocess_handlers, req, &mut res).await;
                                    return res;
                                }
                            }
                            if let Some(path) = path.to_str() {
                                let mut res = Self::from_static_file(req, path, &meta);
                                execute_postprocess(&postprocess_handlers, req, &mut res).await;
                                return res;
                            }
                        } else if meta.is_dir() {
                            if let Some(root) = canonical_root.as_ref() {
                                if !Self::path_stays_inside_root(&path, root) {
                                    let mut res = HttpResponse::error("url path over directory");
                                    execute_postprocess(&postprocess_handlers, req, &mut res).await;
                                    return res;
                                }
                            }
                            let mut tmp_path = path.clone();
                            tmp_path.push("index.htm");
                            if let Ok(tmp_meta) = std::fs::metadata(&tmp_path) {
                                if tmp_meta.is_file() {
                                    if let Some(root) = canonical_root.as_ref() {
                                        if !Self::path_stays_inside_root(&tmp_path, root) {
                                            let mut res =
                                                HttpResponse::error("url path over directory");
                                            execute_postprocess(
                                                &postprocess_handlers,
                                                req,
                                                &mut res,
                                            )
                                            .await;
                                            return res;
                                        }
                                    }
                                    if let Some(path) = tmp_path.to_str() {
                                        let mut res = Self::from_static_file(req, path, &tmp_meta);
                                        execute_postprocess(&postprocess_handlers, req, &mut res)
                                            .await;
                                        return res;
                                    }
                                }
                            }
                            let mut tmp_path = path.clone();
                            tmp_path.push("index.html");
                            if let Ok(tmp_meta) = std::fs::metadata(&tmp_path) {
                                if tmp_meta.is_file() {
                                    if let Some(root) = canonical_root.as_ref() {
                                        if !Self::path_stays_inside_root(&tmp_path, root) {
                                            let mut res =
                                                HttpResponse::error("url path over directory");
                                            execute_postprocess(
                                                &postprocess_handlers,
                                                req,
                                                &mut res,
                                            )
                                            .await;
                                            return res;
                                        }
                                    }
                                    if let Some(path) = tmp_path.to_str() {
                                        let mut res = Self::from_static_file(req, path, &tmp_meta);
                                        execute_postprocess(&postprocess_handlers, req, &mut res)
                                            .await;
                                        return res;
                                    }
                                }
                            }
                        }
                    }
                    continue;
                }
                PipeContextItem::EmbeddedRoute(embedded_items) => {
                    if let Some(item) = embedded_items.get(&req.url_path[..]) {
                        let meta = std::env::current_exe()
                            .ok()
                            .map(|p| std::fs::metadata(&p).ok())
                            .flatten();

                        // Generate ETag (based on content hash and file size)
                        let etag = {
                            use std::collections::hash_map::DefaultHasher;
                            use std::hash::{Hash, Hasher};
                            let mut hasher = DefaultHasher::new();
                            item.hash(&mut hasher);
                            let content_hash = hasher.finish();
                            format!("\"{:x}-{:x}\"", content_hash, item.len())
                        };

                        // Execute preflight check
                        match req.check_precondition_headers(meta.as_ref(), Some(etag.as_str())) {
                            PreflightResult::NotModified => {
                                let mut res = HttpResponse::empty();
                                res.http_code = 304;
                                Self::add_embedded_validators(
                                    &mut res,
                                    meta.as_ref(),
                                    etag.as_str(),
                                );
                                execute_postprocess(&postprocess_handlers, req, &mut res).await;
                                return res;
                            }
                            PreflightResult::PreconditionFailed => {
                                let mut res = HttpResponse::error("Precondition Failed");
                                res.http_code = 412;
                                Self::add_embedded_validators(
                                    &mut res,
                                    meta.as_ref(),
                                    etag.as_str(),
                                );
                                execute_postprocess(&postprocess_handlers, req, &mut res).await;
                                return res;
                            }
                            PreflightResult::Proceed => {
                                // Continue processing
                            }
                        }

                        if Self::should_apply_range_for_embedded(req, meta.as_ref(), etag.as_str())
                        {
                            if let Some(parsed_range) =
                                req.get_header_key(HeaderItem::Range).and_then(|range| {
                                    Self::parse_single_byte_range(range, item.len() as u64)
                                })
                            {
                                match parsed_range {
                                    Some((start, end)) => {
                                        let data = item[start as usize..=end as usize].to_vec();
                                        let mut res = HttpResponse::from_mem_file(
                                            &req.url_path,
                                            data,
                                            false,
                                            None,
                                        );
                                        res.http_code = 206;
                                        res.add_header(
                                            "Content-Range".into(),
                                            format!("bytes {start}-{end}/{}", item.len()).into(),
                                        );
                                        res.add_header("Accept-Ranges".into(), "bytes".into());
                                        Self::add_embedded_validators(
                                            &mut res,
                                            meta.as_ref(),
                                            etag.as_str(),
                                        );
                                        execute_postprocess(&postprocess_handlers, req, &mut res)
                                            .await;
                                        return res;
                                    }
                                    None => {
                                        let mut res = HttpResponse::empty();
                                        res.http_code = 416;
                                        res.add_header(
                                            "Content-Range".into(),
                                            format!("bytes */{}", item.len()).into(),
                                        );
                                        res.add_header("Accept-Ranges".into(), "bytes".into());
                                        Self::add_embedded_validators(
                                            &mut res,
                                            meta.as_ref(),
                                            etag.as_str(),
                                        );
                                        execute_postprocess(&postprocess_handlers, req, &mut res)
                                            .await;
                                        return res;
                                    }
                                }
                            }
                        }

                        let mut ret =
                            HttpResponse::from_mem_file(&req.url_path, item.to_vec(), false, None);
                        ret.add_header("Accept-Ranges".into(), "bytes".into());
                        Self::add_embedded_validators(&mut ret, meta.as_ref(), etag.as_str());
                        execute_postprocess(&postprocess_handlers, req, &mut ret).await;
                        return ret;
                    }
                    continue;
                }
                PipeContextItem::FinalRoute(res) => {
                    let mut res = res.clone();
                    execute_postprocess(&postprocess_handlers, req, &mut res).await;
                    return res;
                }
                PipeContextItem::LimitSize(_max_header, max_body) => {
                    // 检查 body 大小
                    let body_len = req.body.len();
                    if body_len > *max_body {
                        let mut res = HttpResponse::text(format!(
                            "Payload Too Large: body size {} bytes exceeds limit {} bytes",
                            body_len, max_body
                        ));
                        res.http_code = 413;
                        execute_postprocess(&postprocess_handlers, req, &mut res).await;
                        return res;
                    }
                    // Header 大小已在解析阶段检查,此处为双重保险
                    continue;
                }
                PipeContextItem::TransferRate(_inbound_rate, _outbound_rate) => {
                    // 速率限制在连接层处理,此处不需要额外处理
                    continue;
                }
                PipeContextItem::Custom(handler) => match handler {
                    CustomHandler::Sync(handler) => match handler.as_ref()(req) {
                        Some(mut res) => {
                            execute_postprocess(&postprocess_handlers, req, &mut res).await;
                            return res;
                        }
                        None => continue,
                    },
                    CustomHandler::Async(handler) => match handler.as_ref()(req).await {
                        Some(mut res) => {
                            execute_postprocess(&postprocess_handlers, req, &mut res).await;
                            return res;
                        }
                        None => continue,
                    },
                },
                PipeContextItem::Preprocess(handler) => {
                    match handler {
                        PreprocessHandler::Fn(fn_handler) => {
                            match fn_handler(req).await {
                                Ok(Some(mut response)) => {
                                    execute_postprocess(&postprocess_handlers, req, &mut response)
                                        .await;
                                    return response;
                                }
                                Ok(None) => {} // 继续处理
                                Err(e) => {
                                    let mut res =
                                        HttpResponse::error(format!("Preprocess error: {e}"));
                                    execute_postprocess(&postprocess_handlers, req, &mut res).await;
                                    return res;
                                }
                            }
                        }
                    }
                }
                PipeContextItem::ReverseProxy(path, proxy_url, modify_content) => {
                    if !req.url_path.starts_with(path) {
                        continue;
                    }

                    let mut transfer_session =
                        TransferSession::from_reverse_proxy(path.clone(), proxy_url.clone());

                    match transfer_session.transfer(req, *modify_content).await {
                        Ok(mut response) => {
                            execute_postprocess(&postprocess_handlers, req, &mut response).await;
                            return response;
                        }
                        Err(err) => {
                            let mut res = HttpResponse::error(format!("{err}"));
                            execute_postprocess(&postprocess_handlers, req, &mut res).await;
                            return res;
                        }
                    }
                }

                #[cfg(all(feature = "jemalloc", not(target_os = "windows")))]
                PipeContextItem::Jemalloc(path) => {
                    if path == &req.url_path[..] {
                        let mut res = match crate::dump_jemalloc_profile().await {
                            Ok(data) => {
                                // Generate ETag (based on content hash and file size)
                                let etag = {
                                    use std::collections::hash_map::DefaultHasher;
                                    use std::hash::{Hash, Hasher};
                                    let data: Vec<u8> = data;
                                    let mut hasher = DefaultHasher::new();
                                    data.hash(&mut hasher);
                                    let content_hash = hasher.finish();
                                    Some(format!("\"{:x}-{:x}\"", content_hash, data.len()))
                                };

                                // Execute preflight check
                                match req.check_precondition_headers(None, etag.as_deref()) {
                                    PreflightResult::NotModified => {
                                        let mut res = HttpResponse::empty();
                                        res.http_code = 304;
                                        res
                                    }
                                    PreflightResult::PreconditionFailed => {
                                        let mut res = HttpResponse::error("Precondition Failed");
                                        res.http_code = 412;
                                        res
                                    }
                                    PreflightResult::Proceed => HttpResponse::from_mem_file(
                                        "profile.pdf",
                                        data,
                                        false,
                                        None,
                                    ),
                                }
                            }
                            Err(err) => HttpResponse::error(format!("{err}")),
                        };
                        execute_postprocess(&postprocess_handlers, req, &mut res).await;
                        return res;
                    }
                }
                #[cfg(feature = "webdav")]
                PipeContextItem::Webdav((path, dav_server)) => {
                    use crate::utils::string::StringExt;
                    use futures_util::StreamExt;
                    if !req.url_path.starts_with(path) {
                        continue;
                    }
                    let new_req = {
                        let mut new_req = http::Request::new(match req.body.len() {
                            0 => dav_server::body::Body::empty(),
                            _ => {
                                let bytes = bytes::Bytes::copy_from_slice(&req.body[..]);
                                dav_server::body::Body::from(bytes)
                            }
                        });

                        if let Ok(method) =
                            http::Method::from_bytes(req.method.to_string().as_bytes())
                        {
                            *new_req.method_mut() = method;
                        }
                        *new_req.version_mut() = match req.version {
                            9 => http::Version::HTTP_09,
                            10 => http::Version::HTTP_10,
                            11 => http::Version::HTTP_11,
                            20 => http::Version::HTTP_2,
                            30 => http::Version::HTTP_3,
                            _ => http::Version::HTTP_11,
                        };
                        // Modify URI to remove the specified path prefix and preserve original scheme and authority
                        let adjusted_path = if req.url_path.starts_with(path) {
                            // Remove the path prefix from the original path
                            &req.url_path[path.len()..]
                        } else {
                            &req.url_path[..]
                        };

                        // Ensure the path starts with / for valid URI
                        let final_path = if adjusted_path.is_empty() {
                            "/"
                        } else {
                            adjusted_path
                        };

                        // Try to get original URI and preserve scheme/authority if available
                        match req.get_uri(false) {
                            Ok(original_uri) => {
                                *new_req.uri_mut() = match http::uri::Builder::new()
                                    .scheme(
                                        original_uri.scheme().map(|s| s.as_str()).unwrap_or("http"),
                                    )
                                    .authority(
                                        original_uri
                                            .authority()
                                            .map(|a| a.as_str())
                                            .unwrap_or("127.0.0.1"),
                                    )
                                    .path_and_query(final_path)
                                    .build()
                                {
                                    Ok(uri) => uri,
                                    Err(e) => {
                                        return HttpResponse::error(format!(
                                            "Failed to build URI: {e}"
                                        ));
                                    }
                                };
                            }
                            Err(_) => {
                                // If original URI is not available, construct with path only
                                *new_req.uri_mut() = match http::uri::Builder::new()
                                    .path_and_query(final_path)
                                    .build()
                                {
                                    Ok(uri) => uri,
                                    Err(e) => {
                                        return HttpResponse::error(format!(
                                            "Failed to build URI: {e}"
                                        ));
                                    }
                                };
                            }
                        };
                        for (k, v) in req.headers.iter() {
                            if let Ok(v) = http::HeaderValue::from_str(&v[..]) {
                                let k: &'static str = unsafe { std::mem::transmute(k.to_str()) };
                                new_req.headers_mut().append(k, v);
                            }
                        }
                        new_req
                    };
                    let res = {
                        let mut new_res = dav_server.handle(new_req).await;
                        let mut res = HttpResponse::empty();
                        let headers: Vec<(String, String)> = new_res
                            .headers()
                            .iter()
                            .map(|(k, v)| {
                                (
                                    k.as_str().http_std_case(),
                                    v.to_str().unwrap_or("").to_string(),
                                )
                            })
                            .collect();
                        for (k, v) in headers {
                            res.add_header(k.into(), v.into());
                        }
                        res.http_code = new_res.status().as_u16();
                        res.version = format!("{:?}", new_res.version());
                        let body = new_res.body_mut();
                        let mut body_data = Vec::new();
                        while let Some(Ok(part)) = body.next().await {
                            body_data.extend(part.iter());
                        }
                        res.body = crate::HttpResponseBody::Data(body_data);
                        res
                    };
                    let mut res = res;
                    execute_postprocess(&postprocess_handlers, req, &mut res).await;
                    return res;
                }
                #[cfg(feature = "webrtc")]
                PipeContextItem::WebRTC((config, _events)) => {
                    // WebRTC信令处理
                    // WebSocket信令在WebSocket upgrade时处理
                    // REST信令在这里处理
                    if req.url_path.starts_with(&config.rest_prefix) {
                        // 处理REST信令请求
                        // TODO: 实现完整的REST信令处理逻辑
                        // 目前返回提示信息
                        let host = req.get_header("Host").unwrap_or("127.0.0.1:8080");
                        let json_response = serde_json::json!({
                            "status": "WebRTC REST signaling endpoint",
                            "ws_url": format!("ws://{host}{}", config.ws_path),
                            "rest_prefix": config.rest_prefix,
                        });
                        let mut res = HttpResponse::json(json_response.to_string());
                        res.add_header("Content-Type".into(), "application/json".into());
                        execute_postprocess(&postprocess_handlers, req, &mut res).await;
                        return res;
                    }
                }
                #[cfg(feature = "http3")]
                PipeContextItem::WebTransport(_) => {
                    // WebTransport 在 HTTP/3 层处理,这里不会到达
                    // CONNECT 请求已经在 serve_http3_impl 中处理
                }
            }
        }

        HttpResponse::not_found()
    }
}

pub struct HttpServer {
    addr: String,
    pipe_ctx: Arc<PipeContext>,
    shutdown_signal: Option<oneshot::Receiver<()>>,
    #[cfg(feature = "acme")]
    acme_manager: Option<crate::acme::AcmeManager>,
    #[cfg(feature = "acme")]
    acme_acceptor: Option<crate::acme::DynamicTlsAcceptor>,
}

impl HttpServer {
    pub fn new(addr: impl Into<String>) -> Self {
        HttpServer {
            addr: addr.into(),
            pipe_ctx: Arc::new(PipeContext::new()),
            shutdown_signal: None,
            #[cfg(feature = "acme")]
            acme_manager: None,
            #[cfg(feature = "acme")]
            acme_acceptor: None,
        }
    }

    /// 启动后台SessionCache清理任务
    /// 该任务会定期清理过期的session缓存
    fn start_session_cache_cleanup() {
        use std::sync::atomic::{AtomicBool, Ordering};
        static CLEANUP_STARTED: AtomicBool = AtomicBool::new(false);

        // 确保只启动一次
        if CLEANUP_STARTED.swap(true, Ordering::Relaxed) {
            return;
        }

        tokio::spawn(async {
            let mut interval = interval(Duration::from_secs(60)); // 每60秒清理一次
            loop {
                interval.tick().await;
                // 调用SessionCache的清理方法
                crate::SessionCache::cleanup_expired_sessions();
            }
        });
    }

    pub fn configure(&mut self, callback: impl Fn(&mut PipeContext)) {
        let mut ctx = PipeContext::empty();
        callback(&mut ctx);
        self.pipe_ctx = Arc::new(ctx);
    }

    pub fn shutdown_signal(&mut self) -> Option<oneshot::Sender<()>> {
        if self.shutdown_signal.is_some() {
            return None; // Signal already set
        }
        let (tx, rx) = oneshot::channel();
        self.shutdown_signal = Some(rx);
        Some(tx)
    }

    pub async fn serve_http(&mut self) -> anyhow::Result<()> {
        let shutdown_signal = self.shutdown_signal.take();
        match shutdown_signal {
            Some(shutdown_signal) => {
                select! {
                    result = self.serve_http_impl() => result,
                    _ = shutdown_signal => Ok(()),
                }
            }
            None => self.serve_http_impl().await,
        }
    }

    #[cfg(feature = "tls")]
    pub async fn serve_https(&mut self, cert_file: &str, key_file: &str) -> anyhow::Result<()> {
        let shutdown_signal = self.shutdown_signal.take();
        match shutdown_signal {
            Some(shutdown_signal) => {
                select! {
                    result = self.serve_https_impl(cert_file, key_file) => result,
                    _ = shutdown_signal => Ok(()),
                }
            }
            None => self.serve_https_impl(cert_file, key_file).await,
        }
    }

    #[cfg(feature = "http2")]
    pub async fn serve_http2(&mut self, cert_file: &str, key_file: &str) -> anyhow::Result<()> {
        let shutdown_signal = self.shutdown_signal.take();
        let pipe_ctx = Arc::clone(&self.pipe_ctx);
        let addr = self.addr.clone();
        match shutdown_signal {
            Some(shutdown_signal) => {
                select! {
                    result = http2::serve_http2_impl(&addr, cert_file, key_file, pipe_ctx) => result,
                    _ = shutdown_signal => Ok(()),
                }
            }
            None => {
                http2::serve_http2_impl(&self.addr, cert_file, key_file, Arc::clone(&self.pipe_ctx))
                    .await
            }
        }
    }

    #[cfg(feature = "http3")]
    pub async fn serve_http3(&mut self, cert_file: &str, key_file: &str) -> anyhow::Result<()> {
        let shutdown_signal = self.shutdown_signal.take();
        let pipe_ctx = Arc::clone(&self.pipe_ctx);
        let addr = self.addr.clone();
        match shutdown_signal {
            Some(shutdown_signal) => {
                select! {
                    result = http3::serve_http3_impl(&addr, cert_file, key_file, pipe_ctx) => result,
                    _ = shutdown_signal => Ok(()),
                }
            }
            None => {
                http3::serve_http3_impl(&self.addr, cert_file, key_file, Arc::clone(&self.pipe_ctx))
                    .await
            }
        }
    }

    /// 启动 HTTP/3 服务器(无加密模式,使用 http:// 协议)
    #[cfg(feature = "http3")]
    pub async fn serve_http3_without_encrypt(&mut self) -> anyhow::Result<()> {
        let shutdown_signal = self.shutdown_signal.take();
        let pipe_ctx = Arc::clone(&self.pipe_ctx);
        let addr = self.addr.clone();
        match shutdown_signal {
            Some(shutdown_signal) => {
                select! {
                    result = http3::serve_http3_without_encrypt_impl(&addr, pipe_ctx) => result,
                    _ = shutdown_signal => Ok(()),
                }
            }
            None => {
                http3::serve_http3_without_encrypt_impl(&self.addr, Arc::clone(&self.pipe_ctx))
                    .await
            }
        }
    }

    #[cfg(feature = "acme")]
    pub async fn serve_acme(
        &mut self,
        domain: impl Into<String>,
        email: impl Into<String>,
    ) -> anyhow::Result<()> {
        let opts = crate::acme::AcmeOptions::new(domain, email);
        self.serve_acme_with_opts(opts).await
    }

    #[cfg(feature = "acme")]
    pub async fn serve_acme_with_opts(
        &mut self,
        opts: crate::acme::AcmeOptions,
    ) -> anyhow::Result<()> {
        let (acme_manager, acme_acceptor) = crate::acme::AcmeManager::new(opts).await?;

        // 启动后台续期循环
        let manager_clone = acme_manager.clone();
        let acceptor_clone = acme_acceptor.clone();
        tokio::spawn(async move {
            if let Err(e) = manager_clone.start_renewal_loop(acceptor_clone).await {
                eprintln!("[ACME] Renewal loop error: {e}");
            }
        });

        self.acme_manager = Some(acme_manager);
        self.acme_acceptor = Some(acme_acceptor);

        let shutdown_signal = self.shutdown_signal.take();
        match shutdown_signal {
            Some(shutdown_signal) => {
                select! {
                    result = self.serve_acme_impl() => result,
                    _ = shutdown_signal => Ok(()),
                }
            }
            None => self.serve_acme_impl().await,
        }
    }

    pub(crate) fn spawn_http1_connection(
        pipe_ctx: Arc<PipeContext>,
        client_addr: SocketAddr,
        stream: HttpStream,
    ) {
        // 检查是否有速率限制配置
        let rate_limit = pipe_ctx.items.iter().find_map(|item| {
            if let PipeContextItem::TransferRate(inbound, outbound) = item {
                Some((*inbound, *outbound))
            } else {
                None
            }
        });

        // 如果有速率限制,使用 RateLimitedStream 包装
        let stream: HttpStream = if let Some((inbound_rate, outbound_rate)) = rate_limit {
            HttpStream::RateLimited(crate::utils::tcp_stream::RateLimitedStream::new(
                stream,
                inbound_rate,
                outbound_rate,
            ))
        } else {
            stream
        };

        let mut stream = Arc::new(Mutex::new(stream));
        _ = tokio::task::spawn(async move {
            let mut buf: Vec<u8> = Vec::with_capacity(4096);
            loop {
                let (mut req, n) = {
                    match HttpRequest::from_stream(&mut buf, Arc::clone(&stream)).await {
                        Ok((req, n)) => (req, n),
                        Err(err) => {
                            if let Some(mut res) = HttpRequest::parse_error_response(&err) {
                                let mut stream_guard = stream.lock().await;
                                let _ = res
                                    .write_to_stream(&mut stream_guard, CompressMode::None, None)
                                    .await;
                            }
                            break;
                        }
                    }
                };
                req.client_addr = Some(client_addr);
                req.add_ext(Arc::clone(&stream));
                let cmode = req.get_header_accept_encoding();
                let conn = req.get_header_connection();
                let mut res = PipeContext::handle_request(pipe_ctx.as_ref(), &mut req, 0).await;
                if conn != HttpConnection::KeepAlive {
                    res.add_header("Connection".into(), "close".into());
                }
                let stream_for_write = req.exts.remove(&TypeId::of::<Mutex<HttpStream>>());
                match stream_for_write {
                    Some(stream_in_req) => {
                        drop(stream_in_req);
                        let write_res = if let Some(stream_mutex) = Arc::get_mut(&mut stream) {
                            res.write_to_stream(stream_mutex.get_mut(), cmode, Some(req.method))
                                .await
                        } else {
                            let mut stream = stream.lock().await;
                            res.write_to_stream(&mut stream, cmode, Some(req.method))
                                .await
                        };
                        match write_res {
                            Ok(()) => {
                                if n > 0 {
                                    let remain = buf.len().saturating_sub(n);
                                    if remain > 0 {
                                        buf.copy_within(n.., 0);
                                    }
                                    buf.truncate(remain);
                                }
                            }
                            Err(_) => break,
                        }
                    }
                    None => break,
                }
                if conn != HttpConnection::KeepAlive {
                    break;
                }
            }
        });
    }

    #[cfg(feature = "tls")]
    fn tls_acceptor_with_alpn(
        cert_file: &str,
        key_file: &str,
        alpn: Option<Vec<Vec<u8>>>,
    ) -> anyhow::Result<TlsAcceptor> {
        // 初始化 rustls CryptoProvider(如果尚未初始化)
        {
            use rustls::crypto::ring::default_provider;
            use rustls::crypto::CryptoProvider;
            let _ = CryptoProvider::install_default(default_provider());
        }

        let certs = CertificateDer::pem_file_iter(cert_file)?.collect::<Result<Vec<_>, _>>()?;
        let key = PrivateKeyDer::from_pem_file(key_file)?;
        let mut config = rustls::ServerConfig::builder()
            .with_no_client_auth()
            .with_single_cert(certs, key)?;
        if let Some(alpn) = alpn {
            config.alpn_protocols = alpn;
        }
        Ok(TlsAcceptor::from(Arc::new(config)))
    }

    async fn serve_http_impl(&mut self) -> anyhow::Result<()> {
        #[cfg(all(feature = "jemalloc", not(target_os = "windows")))]
        crate::init_jemalloc()?;

        // 启动后台SessionCache清理任务
        Self::start_session_cache_cleanup();

        let addr: SocketAddr = self.addr.parse()?;
        let listener = TcpListener::bind(&addr).await?;
        let pipe_ctx = Arc::clone(&self.pipe_ctx);

        loop {
            let (stream, client_addr) = listener.accept().await?;
            _ = stream.set_nodelay(true);
            Self::spawn_http1_connection(
                Arc::clone(&pipe_ctx),
                client_addr,
                HttpStream::from_tcp(stream),
            );
        }
    }

    #[cfg(feature = "tls")]
    async fn serve_https_impl(&mut self, cert_file: &str, key_file: &str) -> anyhow::Result<()> {
        #[cfg(all(feature = "jemalloc", not(target_os = "windows")))]
        crate::init_jemalloc()?;

        let addr: SocketAddr = self.addr.parse()?;
        let listener = TcpListener::bind(&addr).await?;
        let acceptor = Self::tls_acceptor_with_alpn(cert_file, key_file, None)?;
        let pipe_ctx = Arc::clone(&self.pipe_ctx);

        loop {
            let (stream, client_addr) = listener.accept().await?;
            _ = stream.set_nodelay(true);
            let acceptor = acceptor.clone();
            let pipe_ctx2 = Arc::clone(&pipe_ctx);
            _ = tokio::task::spawn(async move {
                let stream = match acceptor.accept(stream).await {
                    Ok(stream) => stream,
                    Err(_) => return,
                };
                Self::spawn_http1_connection(
                    pipe_ctx2,
                    client_addr,
                    HttpStream::from_server_tls(stream),
                );
            });
        }
    }

    #[cfg(feature = "acme")]
    async fn serve_acme_impl(&mut self) -> anyhow::Result<()> {
        #[cfg(all(feature = "jemalloc", not(target_os = "windows")))]
        crate::init_jemalloc()?;

        let addr: SocketAddr = self.addr.parse()?;
        let listener = TcpListener::bind(&addr).await?;
        let acme_acceptor = self
            .acme_acceptor
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("ACME acceptor not initialized"))?;
        let pipe_ctx = Arc::clone(&self.pipe_ctx);
        let acme_manager = self
            .acme_manager
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("ACME manager not initialized"))?;
        let acme_manager_clone = acme_manager.clone();

        loop {
            let (stream, client_addr) = listener.accept().await?;
            _ = stream.set_nodelay(true);
            let acceptor = acme_acceptor.get_acceptor().await;
            let pipe_ctx2 = Arc::clone(&pipe_ctx);
            let acme_manager2 = acme_manager_clone.clone();
            let acceptor_clone = acceptor.clone();

            _ = tokio::task::spawn(async move {
                let stream = match acceptor_clone.accept(stream).await {
                    Ok(stream) => stream,
                    Err(_) => return,
                };

                // 直接处理ACME挑战请求
                Self::handle_acme_or_normal(
                    pipe_ctx2,
                    client_addr,
                    HttpStream::from_server_tls(stream),
                    &acme_manager2,
                )
                .await;
            });
        }
    }

    #[cfg(feature = "acme")]
    async fn handle_acme_or_normal(
        pipe_ctx: Arc<PipeContext>,
        client_addr: SocketAddr,
        mut stream: HttpStream,
        acme_manager: &crate::acme::AcmeManager,
    ) {
        // 先读取部分数据检查是否是ACME挑战
        let mut buf = vec![0u8; 4096];
        let n = match stream.read(&mut buf).await {
            Ok(n) => n,
            Err(_) => return,
        };

        if n == 0 {
            return;
        }

        // 检查是否是ACME挑战请求
        let initial_data = String::from_utf8_lossy(&buf[..n]);
        if initial_data.contains("/.well-known/acme-challenge/") {
            // 解析请求路径
            if let Some(path_start) = initial_data.find("/.well-known/acme-challenge/") {
                let path_end = initial_data[path_start..]
                    .find(|c: char| c.is_whitespace() || c == ' ')
                    .map(|e| path_start + e)
                    .unwrap_or(initial_data.len());
                let full_path = &initial_data[path_start..path_end];
                let token = &full_path["/.well-known/acme-challenge/".len()..];

                let challenges = acme_manager.get_challenges().await;
                for challenge in challenges {
                    if challenge.token == token {
                        // 返回ACME挑战响应
                        let response = format!(
                            "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                            challenge.key_authorization.len(),
                            challenge.key_authorization
                        );
                        let _ = stream.write_all(response.as_bytes()).await;
                        return;
                    }
                }
            }
        }

        // 正常HTTP请求处理 - 需要重新实现完整请求处理
        // 这里简化处理,实际应该将initial_data和后续数据一起处理
        // 由于复杂度较高,暂时只支持已缓存证书的常规请求
        Self::spawn_http1_connection_with_initial(pipe_ctx, client_addr, stream, &buf[..n]);
    }

    #[cfg(feature = "acme")]
    fn spawn_http1_connection_with_initial(
        pipe_ctx: Arc<PipeContext>,
        client_addr: SocketAddr,
        stream: HttpStream,
        initial_data: &[u8],
    ) {
        // 使用WithPreRead包装流,将initial_data作为预读取数据
        let stream_with_pre_read = HttpStream::with_pre_read(stream, initial_data.to_vec());
        Self::spawn_http1_connection(pipe_ctx, client_addr, stream_with_pre_read);
    }
}