bws-rs 0.1.1

rust s3 backend service framework, quick build yourself s3 gateway, or object storage
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
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
use std::{
    collections::HashMap,
    fmt::{Debug, Display},
    io::Write,
    str::FromStr,
    sync::Mutex,
};
static OWNER_ID: &str = "ffffffffffffffff";
pub type DateTime = chrono::DateTime<chrono::Utc>;
pub struct Error(String);
impl From<String> for Error {
    fn from(value: String) -> Self {
        Self(value)
    }
}
impl From<&str> for Error {
    fn from(value: &str) -> Self {
        Self(value.to_string())
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}
impl Debug for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("Error").field(&self.0).finish()
    }
}
impl std::error::Error for Error {}
pub trait VRequest: crate::authorization::v4::VHeader {
    fn method(&self) -> String;
    fn url_path(&self) -> String;
    fn get_query(&self, k: &str) -> Option<String>;
    fn all_query(&self, cb: impl FnMut(&str, &str) -> bool);
}
pub trait BodyWriter {
    type BodyWriter<'a>: crate::utils::io::PollWrite + Send + Unpin
    where
        Self: 'a;
    fn get_body_writer<'b>(
        &'b mut self,
    ) -> std::pin::Pin<
        Box<dyn 'b + Send + std::future::Future<Output = Result<Self::BodyWriter<'_>, String>>>,
    >;
}
pub trait BodyReader {
    type BodyReader: crate::utils::io::PollRead + Send;
    fn get_body_reader<'b>(
        self,
    ) -> std::pin::Pin<
        Box<dyn 'b + Send + std::future::Future<Output = Result<Self::BodyReader, String>>>,
    >;
}
pub trait HeaderTaker {
    type Head: crate::authorization::v4::VHeader;
    fn take_header(&self) -> Self::Head;
}
pub trait VRequestPlus: VRequest {
    fn body<'a>(
        self,
    ) -> std::pin::Pin<
        Box<dyn 'a + Send + std::future::Future<Output = Result<Vec<u8>, std::io::Error>>>,
    >;
}
pub trait VResponse: crate::authorization::v4::VHeader + BodyWriter {
    fn set_status(&mut self, status: u16);
    fn send_header(&mut self);
}

#[derive(Default, Debug, Serialize)]
pub struct HeadObjectResult {
    #[serde(rename = "AcceptRanges")]
    pub accept_ranges: Option<String>,
    #[serde(rename = "ArchiveStatus")]
    pub archive_status: Option<String>, // 可用枚举替代
    #[serde(rename = "BucketKeyEnabled")]
    pub bucket_key_enabled: Option<bool>,
    #[serde(rename = "CacheControl")]
    pub cache_control: Option<String>,
    #[serde(rename = "ChecksumCRC32")]
    pub checksum_crc32: Option<String>,
    #[serde(rename = "ChecksumCRC32C")]
    pub checksum_crc32c: Option<String>,
    #[serde(rename = "ChecksumCRC64")]
    pub checksum_crc64: Option<String>,
    #[serde(rename = "ChecksumSHA1")]
    pub checksum_sha1: Option<String>,
    #[serde(rename = "ChecksumSHA256")]
    pub checksum_sha256: Option<String>,
    #[serde(rename = "ChecksumType")]
    pub checksum_type: Option<String>,
    #[serde(rename = "ContentDisposition")]
    pub content_disposition: Option<String>,
    #[serde(rename = "ContentEncoding")]
    pub content_encoding: Option<String>,
    #[serde(rename = "ContentLanguage")]
    pub content_language: Option<String>,
    #[serde(rename = "ContentLength")]
    pub content_length: Option<usize>,
    #[serde(rename = "ContentRange")]
    pub content_range: Option<String>,
    #[serde(rename = "ContentType")]
    pub content_type: Option<String>,
    #[serde(rename = "DeleteMarker")]
    pub delete_marker: Option<bool>,
    #[serde(rename = "ETag")]
    pub etag: Option<String>,
    #[serde(rename = "Expiration")]
    pub expiration: Option<String>,
    #[serde(rename = "Expires")]
    pub expires: Option<String>, // 原是 `time.Time`,可转换为 ISO8601 字符串
    #[serde(rename = "ExpiresString")]
    pub expires_string: Option<String>,
    #[serde(rename = "LastModified")]
    pub last_modified: Option<String>, // 可考虑使用 chrono::DateTime 类型
    #[serde(rename = "Metadata")]
    pub metadata: Option<HashMap<String, String>>,
    #[serde(rename = "MissingMeta")]
    pub missing_meta: Option<i32>,
    #[serde(rename = "ObjectLockLegalHoldStatus")]
    pub object_lock_legal_hold_status: Option<String>,
    #[serde(rename = "ObjectLockMode")]
    pub object_lock_mode: Option<String>,
    #[serde(rename = "ObjectLockRetainUntilDate")]
    pub object_lock_retain_until_date: Option<String>,
    #[serde(rename = "PartsCount")]
    pub parts_count: Option<i32>,
    #[serde(rename = "ReplicationStatus")]
    pub replication_status: Option<String>,
    #[serde(rename = "RequestCharged")]
    pub request_charged: Option<String>,
    #[serde(rename = "Restore")]
    pub restore: Option<String>,
    #[serde(rename = "SSECustomerAlgorithm")]
    pub sse_customer_algorithm: Option<String>,
    #[serde(rename = "SSECustomerKeyMD5")]
    pub sse_customer_key_md5: Option<String>,
    #[serde(rename = "SSEKMSKeyId")]
    pub sse_kms_key_id: Option<String>,
    #[serde(rename = "ServerSideEncryption")]
    pub server_side_encryption: Option<String>,
    #[serde(rename = "StorageClass")]
    pub storage_class: Option<String>,
    #[serde(rename = "VersionId")]
    pub version_id: Option<String>,
    #[serde(rename = "WebsiteRedirectLocation")]
    pub website_redirect_location: Option<String>,
}

pub trait HeadHandler {
    fn lookup<'a>(
        &self,
        bucket: &str,
        object: &str,
    ) -> std::pin::Pin<
        Box<
            dyn 'a
                + Send
                + Sync
                + std::future::Future<Output = Result<Option<HeadObjectResult>, Error>>,
        >,
    >;
}
#[derive(Default)]
pub struct GetObjectOption {
    // pub range:(Option<usize>,Option<usize>),
    // pub accept_encoding:Option<Vec<String>>,
}

pub trait GetObjectHandler: HeadHandler {
    fn handle<'a>(
        &'a self,
        bucket: &str,
        object: &str,
        opt: GetObjectOption,
        out: tokio::sync::Mutex<
            std::pin::Pin<Box<dyn 'a + Send + crate::utils::io::PollWrite + Unpin>>,
        >,
    ) -> std::pin::Pin<Box<dyn 'a + Send + std::future::Future<Output = Result<(), String>>>>;
}
extern crate serde;
use serde::Serialize;
use sha1::Digest;
use tokio::io::AsyncSeekExt;

use crate::utils::io::PollWrite;

#[derive(Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
#[serde(rename = "ListBucketResult")]
pub struct ListObjectResult {
    pub name: String,
    pub prefix: Option<String>,
    pub key_count: Option<u32>,
    pub max_keys: Option<u32>,
    pub delimiter: Option<String>,
    pub is_truncated: bool,
    #[serde(default)]
    pub contents: Vec<ListObjectContent>,
    #[serde(default)]
    pub common_prefixes: Vec<CommonPrefix>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct ListObjectContent {
    pub key: String,
    pub last_modified: Option<String>,
    pub etag: Option<String>,
    pub size: u64,
    pub storage_class: Option<String>,
    pub owner: Option<Owner>,
}

#[derive(Debug, Serialize)]
#[serde(rename = "ListAllMyBucketsResult")]
#[serde(rename_all = "PascalCase")]
pub struct ListAllMyBucketsResult {
    #[serde(
        rename = "xmlns",
        default = "s3_namespace",
        skip_serializing_if = "String::is_empty"
    )]
    pub xmlns: String,

    pub owner: Owner,

    pub buckets: Buckets,
}
#[derive(Debug, Serialize)]
pub struct Buckets {
    #[serde(rename = "Bucket")]
    pub bucket: Vec<Bucket>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct Bucket {
    pub name: String,
    pub creation_date: String,
    pub bucket_region: String,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct Owner {
    pub id: String,
    pub display_name: String,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct CommonPrefix {
    pub prefix: String,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct ListObjectOption {
    pub bucket: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub continuation_token: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub delimiter: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub encoding_type: Option<String>, // Usually "url"

    #[serde(skip_serializing_if = "Option::is_none")]
    pub expected_bucket_owner: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub fetch_owner: Option<bool>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_keys: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub optional_object_attributes: Option<Vec<String>>, // e.g. ["RestoreStatus"]

    #[serde(skip_serializing_if = "Option::is_none")]
    pub prefix: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub request_payer: Option<String>, // e.g. "requester"

    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_after: Option<String>,
}

pub trait ListObjectHandler {
    fn handle<'a>(
        &'a self,
        opt: &'a ListObjectOption,
        bucket: &'a str,
    ) -> std::pin::Pin<
        Box<dyn 'a + Send + std::future::Future<Output = Result<Vec<ListObjectContent>, String>>>,
    >;
}
pub fn handle_head_object<T: VRequest, F: VResponse, E: HeadHandler>(
    req: &T,
    resp: &mut F,
    handler: &E,
) {
    todo!()
}
pub async fn handle_get_object<T: VRequest, F: VResponse>(
    req: T,
    resp: &mut F,
    handler: &std::sync::Arc<dyn GetObjectHandler + Send + Sync>,
) {
    use tokio::io::AsyncWriteExt;
    if req.method() != "GET" {
        resp.set_status(405);
        resp.send_header();
        return;
    }
    let rpath = req.url_path();
    let raw = rpath.trim_matches('/');
    let r = raw.find('/');
    if r.is_none() {
        resp.set_status(400);
        resp.send_header();
        return;
    }
    let opt = GetObjectOption::default();
    let next = r.unwrap();
    let bucket = &raw[..next];
    let object = &raw[next + 1..];

    let head = handler.lookup(bucket, object).await;
    if let Err(e) = head {
        log::error!("lookup {bucket} {object} error: {e}");
        resp.set_status(500);
        resp.send_header();
        return;
    }
    let head = head.unwrap();
    if head.is_none() {
        log::info!("not found {bucket} {object}");
        resp.set_status(404);
        resp.send_header();
        return;
    }
    //send header info to client
    let head = head.unwrap();
    if let Some(v) = head.content_length {
        resp.set_header("content-length", v.to_string().as_str())
    }
    if let Some(v) = head.etag {
        resp.set_header("etag", &v)
    }
    if let Some(v) = head.content_type {
        resp.set_header("content-type", &v)
    }
    if let Some(v) = head.last_modified {
        resp.set_header("last-modified", &v)
    }
    //
    resp.set_status(200);
    resp.send_header();
    let ret = {
        match resp.get_body_writer().await {
            Ok(body) => {
                let ret = handler
                    .handle(bucket, object, opt, tokio::sync::Mutex::new(Box::pin(body)))
                    .await;
                if let Err(err) = ret {
                    Err(err)
                } else {
                    Ok(())
                }
            }
            Err(err) => Err(err),
        }
    };
    if let Err(err) = ret {
        log::error!("body handle error {err}");
        resp.set_status(500);
    }
}

//query list-type=2, return ListObjectResult
pub async fn handle_get_list_object<T: VRequest, F: VResponse>(
    req: T,
    resp: &mut F,
    handler: &std::sync::Arc<dyn ListObjectHandler + Send + Sync>,
) {
    if req.method() != "GET" {
        resp.set_status(405);
        resp.send_header();
        return;
    }
    let rpath = req.url_path();
    let bucket = rpath.trim_matches('/').to_string();
    let opt = ListObjectOption {
        bucket: bucket.clone(),
        continuation_token: req.get_query("continuation-token"),
        delimiter: req.get_query("delimiter"),
        expected_bucket_owner: req.get_query("expected-bucket-owner"),
        max_keys: req
            .get_query("max-keys")
            .and_then(|v| v.parse::<i32>().ok()),
        optional_object_attributes: None, //todo: support option_object_attributes on v2
        request_payer: req.get_header("x-amz-request-layer"),
        start_after: req.get_query("start-after"),
        encoding_type: req.get_query("encoding-type"),
        fetch_owner: req.get_query("fetch-owner").and_then(|v| {
            if v == "true" {
                Some(true)
            } else if v == "false" {
                Some(false)
            } else {
                None
            }
        }),
        prefix: req.get_query("prefix"),
    };
    let ret = handler.handle(&opt, rpath.trim_matches('/')).await;
    match ret {
        Ok(ans) => {
            let result = ListObjectResult {
                name: bucket,
                prefix: opt.prefix,
                key_count: Some(ans.len() as u32),
                max_keys: opt.max_keys.map(|v| v as u32),
                delimiter: opt.delimiter,
                is_truncated: false,
                contents: ans,
                common_prefixes: vec![],
            };
            match quick_xml::se::to_string(&result) {
                Ok(data) => {
                    resp.set_header("content-type", "application/xml");
                    resp.set_header("content-length", data.len().to_string().as_str());
                    resp.set_status(200);
                    resp.send_header();
                    let ret = match resp.get_body_writer().await {
                        Ok(mut body) => {
                            if let Err(err) = body.poll_write(data.as_bytes()).await {
                                log::info!("write to response body error {err}");
                            }
                            Ok(())
                        }
                        Err(err) => Err(err),
                    };
                    if let Err(err) = ret {
                        log::error!("write body error {err}");
                        resp.set_status(500);
                        resp.send_header();
                        return;
                    }
                    // resp.get_body_writer().map_ok_or_else(
                    //     |e| log::error!("get_body_writer error:{e}"),
                    //     |mut bw| {
                    //         let _ = bw.write_all(data.as_bytes());
                    //     },
                    // );
                }
                Err(err) => {
                    log::error!("xml marshal failed {err}");
                }
            }
        }
        Err(err) => log::error!("get_list_object error {err}"),
    }
}

pub trait ListBucketHandler {
    fn handle<'a>(
        &'a self,
        opt: &'a ListBucketsOption,
    ) -> std::pin::Pin<Box<dyn 'a + Send + std::future::Future<Output = Result<Vec<Bucket>, String>>>>;
}
pub trait GetBucketLocationHandler {
    fn handle<'a>(
        &'a self,
        loc: Option<&'a str>,
    ) -> std::pin::Pin<
        Box<dyn 'a + Send + std::future::Future<Output = Result<Option<&'static str>, ()>>>,
    > {
        Box::pin(async { Ok(Some("us-west-1")) })
    }
}
#[derive(Debug)]
pub struct ListBucketsOption {
    pub bucket_region: Option<String>,
    pub continuation_token: Option<String>,
    pub max_buckets: Option<i32>,
    pub prefix: Option<String>,
}
pub async fn handle_get_list_buckets<T: VRequest, F: VResponse>(
    req: T,
    resp: &mut F,
    handler: &std::sync::Arc<dyn ListBucketHandler + Send + Sync>,
) {
    if req.method() != "GET" {
        resp.set_status(405);
        resp.send_header();
        return;
    }
    let opt = ListBucketsOption {
        bucket_region: req.get_query("bucket-region"),
        continuation_token: req.get_query("continuation-token"),
        max_buckets: req
            .get_query("max-buckets")
            .and_then(|v| v.parse::<i32>().ok()),
        prefix: req.get_query("prefix"),
    };
    match handler.handle(&opt).await {
        Ok(v) => {
            let res = ListAllMyBucketsResult {
                xmlns: r#"xmlns="http://s3.amazonaws.com/doc/2006-03-01/""#.to_string(),
                owner: Owner {
                    id: OWNER_ID.to_string(),
                    display_name: "bws".to_string(),
                },
                buckets: Buckets { bucket: v },
            };
            match quick_xml::se::to_string(&res) {
                Ok(v) => match resp.get_body_writer().await {
                    Ok(mut w) => {
                        if let Err(err) = w.poll_write(v.as_bytes()).await {
                            log::info!("write to client body error {err}");
                        }
                    }
                    Err(e) => log::error!("get_body_writer error: {e}"),
                },
                Err(e) => {
                    resp.set_status(500);
                    resp.send_header();
                    log::error!("xml serde error: {e}")
                }
            }
        }
        Err(e) => {
            log::info!("listbucket handle error: {e}");
            resp.set_status(500);
            resp.send_header();
        }
    }
}
#[derive(Default)]
pub struct PutObjectOption {
    // pub acl: ObjectCannedACL,
    pub cache_control: Option<String>,
    pub checksum_algorithm: Option<ChecksumAlgorithm>,
    pub checksum_crc32: Option<String>,
    pub checksum_crc32c: Option<String>,
    pub checksum_crc64nvme: Option<String>,
    pub checksum_sha1: Option<String>,
    pub checksum_sha256: Option<String>,
    pub content_disposition: Option<String>,
    pub content_encoding: Option<String>,
    pub content_language: Option<String>,
    pub content_length: Option<i64>,
    pub content_md5: Option<String>,
    pub content_type: Option<String>,
    pub expected_bucket_owner: Option<String>,
    pub expires: Option<DateTime>,
    pub grant_full_control: Option<String>,
    pub grant_read: Option<String>,
    pub if_match: Option<String>,
    pub if_none_match: Option<String>,
    // pub metadata: Option<HashMap<String, String>>,
    pub object_lock_legal_hold_status: Option<ObjectLockLegalHoldStatus>,
    pub object_lock_mode: Option<ObjectLockMode>,
    pub object_lock_retain_until_date: Option<DateTime>,
    pub request_payer: Option<RequestPayer>,
    pub storage_class: Option<String>,
    // pub tagging: Option<String>,
    // pub website_redirect_location: Option<String>,
    pub write_offset_bytes: Option<i64>,
}
impl PutObjectOption {
    pub fn invalid(&self) -> bool {
        if self.content_length.is_none() {
            return false;
        } else if self.content_md5.is_none() {
            return false;
        }
        true
    }
}

#[derive(Debug, PartialEq)]
pub enum ChecksumAlgorithm {
    Crc32,
    Crc32c,
    Sha1,
    Sha256,
    Crc64nvme,
}

impl std::str::FromStr for ChecksumAlgorithm {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "CRC32" => Ok(ChecksumAlgorithm::Crc32),
            "CRC32C" => Ok(ChecksumAlgorithm::Crc32c),
            "SHA1" => Ok(ChecksumAlgorithm::Sha1),
            "SHA256" => Ok(ChecksumAlgorithm::Sha256),
            "CRC64NVME" => Ok(ChecksumAlgorithm::Crc64nvme),
            _ => Err(format!("Invalid checksum algorithm: {}", s)),
        }
    }
}

#[derive(Debug)]
pub enum RequestPayer {
    Requester,
}
impl std::str::FromStr for RequestPayer {
    type Err = Error;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "requester" => Ok(RequestPayer::Requester),
            _ => Err(Error(format!("Invalid RequestPayer value: {}", s))),
        }
    }
}
#[derive(Debug)]
pub enum ObjectLockMode {
    Governance,
    Compliance,
}
impl std::str::FromStr for ObjectLockMode {
    type Err = Error;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "GOVERNANCE" => Ok(ObjectLockMode::Governance),
            "COMPLIANCE" => Ok(ObjectLockMode::Compliance),
            _ => Err(Error(format!("Invalid ObjectLockMode value: {}", s))),
        }
    }
}
#[derive(Debug)]
pub enum ObjectLockLegalHoldStatus {
    On,
    Off,
}
impl std::str::FromStr for ObjectLockLegalHoldStatus {
    type Err = Error;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "ON" => Ok(ObjectLockLegalHoldStatus::On),
            "OFF" => Ok(ObjectLockLegalHoldStatus::Off),
            _ => Err(Error(format!(
                "Invalid ObjectLockLegalHoldStatus value: {}",
                s
            ))),
        }
    }
}

pub trait PutObjectHandler {
    fn handle<'a>(
        &'a self,
        opt: &PutObjectOption,
        bucket: &'a str,
        object: &'a str,
        body: &'a mut (dyn tokio::io::AsyncRead + Unpin + Send),
    ) -> std::pin::Pin<Box<dyn 'a + Send + std::future::Future<Output = Result<(), String>>>>;
}
pub async fn handle_put_object<T: VRequest + BodyReader, F: VResponse>(
    mut v4head: crate::authorization::v4::V4Head,
    mut req: T,
    resp: &mut F,
    handler: &std::sync::Arc<dyn PutObjectHandler + Send + Sync>,
) {
    if req.method() != "PUT" {
        resp.set_status(405);
        resp.send_header();
        return;
    }
    let url_path = req.url_path();
    let url_path = url_path.trim_matches('/');
    let ret = url_path.find('/');
    if ret.is_none() {
        resp.set_status(400);
        resp.send_header();
        return;
    }
    let next = ret.unwrap();
    let bucket = &url_path[..next];
    let object = &url_path[next + 1..];
    let opt = PutObjectOption {
        cache_control: req.get_header("cache-control"),
        checksum_algorithm: req
            .get_header("checksum-algorithm")
            .and_then(|v| ChecksumAlgorithm::from_str(&v).ok()),
        checksum_crc32: req.get_header("x-amz-checksum-crc32"),
        checksum_crc32c: req.get_header("x-amz-checksum-crc32c"),
        checksum_crc64nvme: req.get_header("x-amz-checksum-crc64vme"),
        checksum_sha1: req.get_header("x-amz-checksum-sha1"),
        checksum_sha256: req.get_header("x-amz-checksum-sha256"),
        content_disposition: req.get_header("content-disposition"),
        content_encoding: req.get_header("cotent-encoding"),
        content_language: req.get_header("content-language"),
        content_length: req
            .get_header("content-length")
            .and_then(|v| v.parse::<i64>().map_or(Some(-1), Some)),
        content_md5: req.get_header("content-md5"),
        content_type: req.get_header("content-type"),
        expected_bucket_owner: req.get_header("x-amz-expected-bucket-owner"),
        expires: req.get_header("expire").and_then(|v| {
            chrono::NaiveDateTime::parse_from_str(&v, "%a, %d %b %Y %H:%M:%S GMT")
                .map_or(None, |v| {
                    Some(chrono::DateTime::from_naive_utc_and_offset(v, chrono::Utc))
                })
        }),
        grant_full_control: req.get_header("x-amz-grant-full-control"),
        grant_read: req.get_header("x-amz-grant-read"),
        if_match: req.get_header("if-match"),
        if_none_match: req.get_header("if-none-match"),
        // metadata: todo!(),
        object_lock_legal_hold_status: req
            .get_header("x-amz-object-lock-legal-hold-status")
            .and_then(|v| ObjectLockLegalHoldStatus::from_str(&v).ok()),
        object_lock_mode: req
            .get_header("x-amz-object-lock-mode")
            .and_then(|v| ObjectLockMode::from_str(&v).ok()),
        object_lock_retain_until_date: req
            .get_header("x-amz-object-lock-retain_until_date")
            .and_then(|v| {
                chrono::NaiveDateTime::parse_from_str(&v, "%a, %d %b %Y %H:%M:%S GMT")
                    .map_or(None, |v| {
                        Some(chrono::DateTime::from_naive_utc_and_offset(v, chrono::Utc))
                    })
            }),
        request_payer: req
            .get_header("x-amz-request-payer")
            .and_then(|v| RequestPayer::from_str(&v).ok()),
        storage_class: req.get_header("x-amz-storage-class"),
        // tagging: todo!(),
        // website_redirect_location: todo!(),
        write_offset_bytes: req
            .get_header("x-amz-write-offset-bytes")
            .and_then(|v| v.parse::<i64>().ok()),
    };

    //todo:parse from body,then derive into handle
    enum ContentSha256 {
        Hash(String),
        Streaming,
    }
    let content_sha256 = req.get_header("x-amz-content-sha256").map_or_else(
        || None,
        |content_sha256| {
            if content_sha256.as_str() == "STREAMING-AWS4-HMAC-SHA256-PAYLOAD" {
                Some(ContentSha256::Streaming)
            } else {
                Some(ContentSha256::Hash(content_sha256))
            }
        },
    );
    if content_sha256.is_none() {
        resp.set_status(403);
        return;
    }
    let content_sha256 = content_sha256.unwrap();
    let ret = req.get_body_reader().await;
    if let Err(err) = ret {
        resp.set_status(500);
        resp.send_header();
        log::error!("get body reader error: {err}");
        return;
    }
    let r = ret.unwrap();
    let ret: Result<(), String> = match content_sha256 {
        ContentSha256::Hash(cs) => {
            if opt.content_length.is_none() {
                resp.set_status(403);
                resp.send_header();
                return;
            }
            let content_length = opt.content_length.unwrap() as usize;
            if content_length <= 10 << 20 {
                let mut buff = vec![0u8; content_length];
                match parse_body(r, &mut buff, &cs, content_length).await {
                    Ok(_) => {
                        let mut buff = tokio::io::BufReader::new(std::io::Cursor::new(buff));
                        handler.handle(&opt, bucket, object, &mut buff).await
                    }
                    Err(err) => match err {
                        ParseBodyError::HashNoMatch => {
                            log::warn!("put object hash not match");
                            resp.set_status(400);
                            resp.send_header();
                            return;
                        }
                        ParseBodyError::ContentLengthIncorrect => {
                            log::warn!("content length invalid");
                            resp.set_status(400);
                            resp.send_header();
                            return;
                        }
                        ParseBodyError::Io(err) => {
                            log::error!("parse body io error {err}");
                            resp.set_status(500);
                            resp.send_header();
                            return;
                        }
                    },
                }
            } else {
                match tokio::fs::OpenOptions::new()
                    .create_new(true)
                    .write(true)
                    .read(true)
                    .mode(0o644)
                    .open(format!(".sys_bws/{}", cs))
                    .await
                {
                    Ok(mut fd) => match parse_body(r, &mut fd, &cs, content_length).await {
                        Ok(_) => {
                            if let Err(err) = fd.seek(std::io::SeekFrom::Start(0)).await {
                                log::error!("fd seek failed {err}");
                                resp.set_status(500);
                                resp.send_header();
                                return;
                            }
                            handler.handle(&opt, bucket, object, &mut fd).await
                        }
                        Err(err) => match err {
                            ParseBodyError::HashNoMatch => {
                                log::warn!("put object hash not match");
                                resp.set_status(400);
                                resp.send_header();
                                return;
                            }
                            ParseBodyError::ContentLengthIncorrect => {
                                log::warn!("content length invalid");
                                resp.set_status(400);
                                resp.send_header();
                                return;
                            }
                            ParseBodyError::Io(err) => {
                                log::error!("parse body io error {err}");
                                resp.set_status(500);
                                resp.send_header();
                                return;
                            }
                        },
                    },
                    Err(err) => {
                        log::error!("open local path error {err}");
                        resp.set_status(500);
                        resp.send_header();
                        return;
                    }
                }
            }
        }
        ContentSha256::Streaming => {
            let file_name = crate::random_str!(4);
            let file_name = format!(".sys_bws/{}", file_name);
            let ret = match tokio::fs::OpenOptions::new()
                .create_new(true)
                .write(true)
                .read(true)
                .mode(0o644)
                .open(file_name.as_str())
                .await
            {
                Ok(mut fd) => crate::utils::chunk_parse(r, &mut fd, v4head.hasher()).await,
                Err(err) => {
                    log::error!("open local temp file error {err}");
                    resp.set_status(500);
                    resp.send_header();
                    return;
                }
            };
            if let Err(err) = ret {
                tokio::fs::remove_file(file_name.as_str())
                    .await
                    .unwrap_or_else(|err| log::error!("remove file {file_name} error {err}"));
                match err {
                    crate::utils::ChunkParseError::HashNoMatch => {
                        log::warn!("accept hash no match request");
                        resp.set_status(400);
                        resp.send_header();
                        return;
                    }
                    crate::utils::ChunkParseError::IllegalContent => {
                        log::warn!("accept illegal content request");
                        resp.set_status(400);
                        resp.send_header();
                        return;
                    }
                    crate::utils::ChunkParseError::Io(err) => {
                        log::error!("local io error {err}");
                        resp.set_status(500);
                        resp.send_header();
                        return;
                    }
                }
            }
            match tokio::fs::OpenOptions::new()
                .read(true)
                .open(file_name.as_str())
                .await
            {
                Ok(mut fd) => {
                    let ret = handler.handle(&opt, bucket, object, &mut fd).await;
                    tokio::fs::remove_file(file_name.as_str())
                        .await
                        .unwrap_or_else(|err| log::error!("remove file {file_name} error {err}"));
                    ret
                }
                Err(err) => {
                    log::error!("open file {file_name} error {err}");
                    resp.set_status(500);
                    resp.send_header();
                    tokio::fs::remove_file(file_name.as_str())
                        .await
                        .unwrap_or_else(|err| log::error!("remove file {file_name} error {err}"));
                    return;
                }
            }
        }
    };
    //
    match ret {
        Ok(_) => {
            resp.set_status(200);
            resp.send_header();
        }
        Err(err) => {
            resp.set_status(500);
            resp.send_header();
            log::error!("put object handle error: {err}");
        }
    }
}
pub struct DeleteObjectOption {}
pub trait DeleteObjectHandler {
    fn handle<'a>(
        &'a self,
        opt: &'a DeleteObjectOption,
        object: &'a str,
    ) -> std::pin::Pin<Box<dyn 'a + Send + std::future::Future<Output = Result<(), String>>>>;
}

pub async fn handle_delete_object<T: VRequest, F: VResponse>(
    req: T,
    resp: &mut F,
    handler: &std::sync::Arc<dyn DeleteObjectHandler + Send + Sync>,
) {
    let opt = DeleteObjectOption {};
    let url_path = req.url_path();
    if let Err(e) = handler.handle(&opt, url_path.trim_matches('/')).await {
        resp.set_status(500);
        log::info!("delete object handler error: {e}");
    } else {
        resp.set_status(204);
    }
}
pub struct MultiUploadObjectCompleteOption {
    pub if_match: Option<String>,
    pub if_none_match: Option<String>,
}
pub trait MultiUploadObjectHandler {
    fn handle_create_session<'a>(
        &'a self,
        bucket: &'a str,
        key: &'a str,
    ) -> std::pin::Pin<Box<dyn 'a + Send + std::future::Future<Output = Result<String, ()>>>>;
    ///return etag
    fn handle_upload_part<'a>(
        &'a self,
        bucket: &'a str,
        key: &'a str,
        upload_id: &'a str,
        part_number: u32,
        body: &'a mut (dyn tokio::io::AsyncRead + Unpin + Send),
    ) -> std::pin::Pin<Box<dyn 'a + Send + std::future::Future<Output = Result<String, ()>>>>;
    fn handle_complete<'a>(
        &'a self,
        bucket: &'a str,
        key: &'a str,
        upload_id: &'a str,
        //(etag,part number)
        data: &'a [(&'a str, u32)],
        opts: MultiUploadObjectCompleteOption,
    ) -> std::pin::Pin<Box<dyn 'a + Send + std::future::Future<Output = Result<String, ()>>>>;
    fn handle_abort<'a>(
        &'a self,
        bucket: &'a str,
        key: &'a str,
        upload_id: &'a str,
    ) -> std::pin::Pin<Box<dyn 'a + Send + std::future::Future<Output = Result<(), ()>>>>;
}
pub async fn handle_multipart_create_session<T: VRequest, F: VResponse>(
    req: T,
    resp: &mut F,
    handler: &std::sync::Arc<dyn MultiUploadObjectHandler + Send + Sync>,
) {
    let raw_path = req.url_path();
    let raw = raw_path
        .trim_start_matches('/')
        .splitn(2, '/')
        .collect::<Vec<&str>>();
    if raw.len() != 2 {
        resp.set_status(400);
        resp.send_header();
        return;
    }
    let bucket = raw[0];
    let key = raw[1];
    match handler.handle_create_session(bucket, key).await {
        Ok(upload_id) => {
            #[derive(Debug, serde::Serialize)]
            #[serde(rename_all = "PascalCase")]
            pub struct MultipartInitResponse<'a> {
                #[serde(rename = "Bucket")]
                pub bucket: &'a str,
                #[serde(rename = "Key")]
                pub key: &'a str,
                #[serde(rename = "UploadId")]
                pub upload_id: &'a str,
            }
            let r = MultipartInitResponse {
                bucket,
                key,
                upload_id: &upload_id,
            };
            let is_err = match quick_xml::se::to_string(&r) {
                Ok(content) => match resp.get_body_writer().await {
                    Ok(mut w) => {
                        let _ = w.poll_write(content.as_bytes()).await;
                        None
                    }
                    Err(err) => {
                        log::error!("get body writer error {err}");
                        Some(())
                    }
                },
                Err(err) => {
                    log::error!("xml encode error {err}");
                    Some(())
                }
            };
            if is_err.is_some() {
                resp.set_status(500);
                resp.send_header();
            }
        }
        Err(_) => {
            log::error!("handle create session error");
            resp.set_status(500);
            resp.send_header();
        }
    }
}
pub async fn handle_multipart_upload_part<T: VRequest + BodyReader + HeaderTaker, F: VResponse>(
    req: T,
    resp: &mut F,
    handler: &std::sync::Arc<dyn MultiUploadObjectHandler + Send + Sync>,
) {
    let upload_id = req.get_query("uploadId");
    let part_number = req.get_query("partNumber");
    if upload_id.is_none() || part_number.is_none() {
        resp.set_status(400);
    } else {
        let ret = u32::from_str_radix(part_number.unwrap().as_str(), 10);
        if ret.is_err() {
            resp.set_status(400);
            return;
        }
        let part_number = ret.unwrap();
        let raw_path = req.url_path();
        let raw = raw_path
            .trim_start_matches('/')
            .splitn(2, '/')
            .collect::<Vec<&str>>();
        if raw.len() != 2 {
            resp.set_status(400);
            return;
        }
        let header = req.take_header();
        let body_reader = match req.get_body_reader().await {
            Ok(body_reader) => body_reader,
            Err(err) => {
                log::error!("get body reader failed {err}");
                resp.set_status(500);
                resp.send_header();
                return;
            }
        };
        let (body, release) = match get_body_stream(body_reader, &header).await {
            Ok(data) => data,
            Err(err) => {
                log::error!("get body stream error {err}");
                resp.set_status(500);
                resp.send_header();
                return;
            }
        };
        let ret = match body {
            StreamType::File(mut file) => {
                handler
                    .handle_upload_part(
                        raw[0],
                        raw[1],
                        upload_id.unwrap().as_str(),
                        part_number,
                        &mut file,
                    )
                    .await
            }
            StreamType::Buff(mut buf_reader) => {
                handler
                    .handle_upload_part(
                        raw[0],
                        raw[1],
                        upload_id.unwrap().as_str(),
                        part_number,
                        &mut buf_reader,
                    )
                    .await
            }
        };
        if let Some(release) = release {
            release.await;
        }
        if let Ok(etag) = ret {
            resp.set_header("etag", &etag);
        } else {
            resp.set_status(500);
            resp.send_header();
        }
    }
}
pub async fn handle_multipart_complete_session<T: VRequestPlus, F: VResponse>(
    req: T,
    resp: &mut F,
    handler: &std::sync::Arc<dyn MultiUploadObjectHandler + Send + Sync>,
) {
    let raw_path = req.url_path();
    let raw = raw_path
        .trim_start_matches('/')
        .splitn(2, '/')
        .collect::<Vec<&str>>();
    if raw.len() != 2 {
        resp.set_status(400);
        resp.send_header();
        return;
    }
    let bucket = raw[0];
    let key = raw[1];
    let upload_id = req.get_query("uploadId");
    if let Some(upload_id) = upload_id {
        #[derive(Debug, serde::Deserialize)]
        #[serde(rename_all = "PascalCase")]
        pub struct CompleteMultiPartUploadRequest {
            #[serde(rename = "Part")]
            pub parts: Vec<CompletedPart>,
        }
        #[derive(Debug, serde::Deserialize)]
        #[serde(rename_all = "PascalCase")]
        pub struct CompletedPart {
            #[serde(rename = "ETag")]
            pub etag: String,
            #[serde(rename = "PartNumber")]
            pub part_number: u32,
        }
        match req.body().await {
            Ok(body) => {
                match quick_xml::de::from_str::<CompleteMultiPartUploadRequest>(unsafe {
                    std::str::from_utf8_unchecked(&body)
                }) {
                    Ok(upload_request) => {
                        let data = upload_request
                            .parts
                            .iter()
                            .map(|data| (data.etag.as_str(), data.part_number))
                            .collect::<Vec<(&str, u32)>>();
                        match handler
                            .handle_complete(
                                bucket,
                                key,
                                &upload_id,
                                &data,
                                MultiUploadObjectCompleteOption {
                                    if_match: None,
                                    if_none_match: None,
                                },
                            )
                            .await
                        {
                            Ok(etag) => {
                                use serde::{Deserialize, Serialize};
                                #[derive(Debug, Serialize, Deserialize)]
                                #[serde(rename_all = "PascalCase")]
                                pub struct CompleteMultipartUploadResponse<'a> {
                                    #[serde(rename = "Location")]
                                    pub location: &'a str,
                                    #[serde(rename = "Bucket")]
                                    pub bucket: &'a str,
                                    #[serde(rename = "Key")]
                                    pub key: &'a str,
                                    #[serde(rename = "ETag")]
                                    pub etag: &'a str,
                                }
                                let r = CompleteMultipartUploadResponse {
                                    location: "",
                                    bucket,
                                    key,
                                    etag: &etag,
                                };
                                match quick_xml::se::to_string(&r) {
                                    Ok(content) => {
                                        let err = match resp.get_body_writer().await {
                                            Ok(mut w) => {
                                                let _ = w.poll_write(content.as_bytes()).await;
                                                None
                                            }
                                            Err(err) => Some(err),
                                        };
                                        if let Some(err) = err {
                                            log::error!("get body writer error {err}");
                                            resp.set_status(500);
                                            resp.send_header();
                                        }
                                    }
                                    Err(err) => {
                                        log::error!("quick xml encode error {err}");
                                        resp.set_status(500);
                                        resp.send_header();
                                    }
                                }
                            }
                            Err(_) => {
                                log::error!("handle_complete error");
                                resp.set_status(500);
                                resp.send_header();
                            }
                        }
                    }
                    Err(_) => {
                        resp.set_status(400);
                        resp.send_header();
                    }
                }
            }
            Err(err) => {
                log::error!("read body error {err}");
                resp.set_status(500);
                resp.send_header();
            }
        }
    } else {
        resp.set_status(400);
        resp.send_header();
    }
}
pub async fn handle_multipart_abort_session<T: VRequest, F: VResponse>(
    req: T,
    resp: &mut F,
    handler: &std::sync::Arc<dyn MultiUploadObjectHandler + Send + Sync>,
) {
    todo!()
}
pub struct CreateBucketOption {
    pub grant_full_control: Option<String>,
    pub grant_read: Option<String>,
    pub grant_read_acp: Option<String>,
    pub grant_write: Option<String>,
    pub grant_write_acp: Option<String>,
    pub object_lock_enabled_for_bucket: Option<bool>,
    pub object_ownership: Option<ObjectOwnership>,
}
pub enum ObjectOwnership {
    BucketOwnerPreferred,
    ObjectWriter,
    BucketOwnerEnforced,
}
impl FromStr for ObjectOwnership {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "BucketOwnerPreferred" => Ok(ObjectOwnership::BucketOwnerPreferred),
            "ObjectWriter" => Ok(ObjectOwnership::ObjectWriter),
            "BucketOwnerEnforced" => Ok(ObjectOwnership::BucketOwnerEnforced),
            _ => Err(Error(s.to_string())),
        }
    }
}
pub struct CreateBucketConfiguration {
    pub bucket: Option<BucketInfo>,
    pub location: Option<LocationInfo>,
    pub location_constraint: Option<BucketLocationConstraint>,
}
pub struct BucketInfo {
    pub data_redundancy: DataRedundancy,
    pub bucket_type: BucketType,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DataRedundancy {
    SingleAvailabilityZone,
    SingleLocalZone,
    Unknown(String),
}

impl From<&str> for DataRedundancy {
    fn from(s: &str) -> Self {
        match s {
            "SingleAvailabilityZone" => Self::SingleAvailabilityZone,
            "SingleLocalZone" => Self::SingleLocalZone,
            other => Self::Unknown(other.to_string()),
        }
    }
}
impl Display for DataRedundancy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(
            match self {
                DataRedundancy::SingleAvailabilityZone => "SingleAvailabilityZone".to_string(),
                DataRedundancy::SingleLocalZone => "SingleLocalZone".to_string(),
                DataRedundancy::Unknown(s) => s.clone(),
            }
            .as_str(),
        )
    }
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BucketType {
    Directory,
    Unknown(String),
}

impl From<&str> for BucketType {
    fn from(s: &str) -> Self {
        match s {
            "Directory" => Self::Directory,
            other => Self::Unknown(other.to_string()),
        }
    }
}

impl Display for BucketType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(
            match self {
                Self::Directory => "Directory".to_string(),
                Self::Unknown(s) => s.clone(),
            }
            .as_str(),
        )
    }
}

pub struct LocationInfo {
    pub name: Option<String>,
    pub location_type: LocationType,
}

pub enum LocationType {
    AvailabilityZone,
    LocalZone,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BucketLocationConstraint {
    AfSouth1,
    ApEast1,
    ApNortheast1,
    ApNortheast2,
    ApNortheast3,
    ApSouth1,
    ApSouth2,
    ApSoutheast1,
    ApSoutheast2,
    ApSoutheast3,
    ApSoutheast4,
    ApSoutheast5,
    CaCentral1,
    CnNorth1,
    CnNorthwest1,
    Eu,
    EuCentral1,
    EuCentral2,
    EuNorth1,
    EuSouth1,
    EuSouth2,
    EuWest1,
    EuWest2,
    EuWest3,
    IlCentral1,
    MeCentral1,
    MeSouth1,
    SaEast1,
    UsEast2,
    UsGovEast1,
    UsGovWest1,
    UsWest1,
    UsWest2,
    Unknown(String),
}
impl From<&str> for BucketLocationConstraint {
    fn from(s: &str) -> Self {
        match s {
            "af-south-1" => Self::AfSouth1,
            "ap-east-1" => Self::ApEast1,
            "ap-northeast-1" => Self::ApNortheast1,
            "ap-northeast-2" => Self::ApNortheast2,
            "ap-northeast-3" => Self::ApNortheast3,
            "ap-south-1" => Self::ApSouth1,
            "ap-south-2" => Self::ApSouth2,
            "ap-southeast-1" => Self::ApSoutheast1,
            "ap-southeast-2" => Self::ApSoutheast2,
            "ap-southeast-3" => Self::ApSoutheast3,
            "ap-southeast-4" => Self::ApSoutheast4,
            "ap-southeast-5" => Self::ApSoutheast5,
            "ca-central-1" => Self::CaCentral1,
            "cn-north-1" => Self::CnNorth1,
            "cn-northwest-1" => Self::CnNorthwest1,
            "EU" => Self::Eu,
            "eu-central-1" => Self::EuCentral1,
            "eu-central-2" => Self::EuCentral2,
            "eu-north-1" => Self::EuNorth1,
            "eu-south-1" => Self::EuSouth1,
            "eu-south-2" => Self::EuSouth2,
            "eu-west-1" => Self::EuWest1,
            "eu-west-2" => Self::EuWest2,
            "eu-west-3" => Self::EuWest3,
            "il-central-1" => Self::IlCentral1,
            "me-central-1" => Self::MeCentral1,
            "me-south-1" => Self::MeSouth1,
            "sa-east-1" => Self::SaEast1,
            "us-east-2" => Self::UsEast2,
            "us-gov-east-1" => Self::UsGovEast1,
            "us-gov-west-1" => Self::UsGovWest1,
            "us-west-1" => Self::UsWest1,
            "us-west-2" => Self::UsWest2,
            other => Self::Unknown(other.to_string()),
        }
    }
}

impl Display for BucketLocationConstraint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::AfSouth1 => "af-south-1",
            Self::ApEast1 => "ap-east-1",
            Self::ApNortheast1 => "ap-northeast-1",
            Self::ApNortheast2 => "ap-northeast-2",
            Self::ApNortheast3 => "ap-northeast-3",
            Self::ApSouth1 => "ap-south-1",
            Self::ApSouth2 => "ap-south-2",
            Self::ApSoutheast1 => "ap-southeast-1",
            Self::ApSoutheast2 => "ap-southeast-2",
            Self::ApSoutheast3 => "ap-southeast-3",
            Self::ApSoutheast4 => "ap-southeast-4",
            Self::ApSoutheast5 => "ap-southeast-5",
            Self::CaCentral1 => "ca-central-1",
            Self::CnNorth1 => "cn-north-1",
            Self::CnNorthwest1 => "cn-northwest-1",
            Self::Eu => "EU",
            Self::EuCentral1 => "eu-central-1",
            Self::EuCentral2 => "eu-central-2",
            Self::EuNorth1 => "eu-north-1",
            Self::EuSouth1 => "eu-south-1",
            Self::EuSouth2 => "eu-south-2",
            Self::EuWest1 => "eu-west-1",
            Self::EuWest2 => "eu-west-2",
            Self::EuWest3 => "eu-west-3",
            Self::IlCentral1 => "il-central-1",
            Self::MeCentral1 => "me-central-1",
            Self::MeSouth1 => "me-south-1",
            Self::SaEast1 => "sa-east-1",
            Self::UsEast2 => "us-east-2",
            Self::UsGovEast1 => "us-gov-east-1",
            Self::UsGovWest1 => "us-gov-west-1",
            Self::UsWest1 => "us-west-1",
            Self::UsWest2 => "us-west-2",
            Self::Unknown(s) => s,
        })
    }
}

pub trait CreateBucketHandler {
    fn handle<'a>(
        &'a self,
        opt: &'a CreateBucketOption,
        bucket: &'a str,
    ) -> std::pin::Pin<Box<dyn 'a + Send + std::future::Future<Output = Result<(), String>>>>;
}
pub async fn handle_create_bucket<T: VRequest, F: VResponse>(
    req: T,
    resp: &mut F,
    handler: &std::sync::Arc<dyn CreateBucketHandler + Send + Sync>,
) {
    if req.method() != "PUT" {
        resp.set_status(405);
        resp.send_header();
        return;
    }

    let opt = CreateBucketOption {
        grant_full_control: req.get_header("x-amz-grant-full-control"),
        grant_read: req.get_header("x-amz-grant-read"),
        grant_read_acp: req.get_header("x-amz-grant-read-acp"),
        grant_write: req.get_header("x-amz-grant-write"),
        grant_write_acp: req.get_header("x-amz-grant-write-acp"),
        object_lock_enabled_for_bucket: req
            .get_header("x-amz-bucket-object-lock-enabled")
            .and_then(|v| {
                if v == "true" {
                    Some(true)
                } else if v == "false" {
                    Some(false)
                } else {
                    None
                }
            }),
        object_ownership: req
            .get_header("x-amz-object-ownership")
            .and_then(|v| v.parse().ok()),
    };
    let url_path = req.url_path();
    if let Err(e) = handler.handle(&opt, url_path.trim_matches('/')).await {
        resp.set_status(500);
        log::info!("delete object handler error: {e}")
    }
}

pub struct DeleteBucketOption {
    pub expected_owner: Option<String>,
}
pub trait DeleteBucketHandler {
    fn handle<'a>(
        &'a self,
        opt: &'a DeleteBucketOption,
        bucket: &'a str,
    ) -> std::pin::Pin<Box<dyn 'a + Send + std::future::Future<Output = Result<(), String>>>>;
}

pub async fn handle_delete_bucket<T: VRequest, F: VResponse>(
    req: T,
    resp: &mut F,
    handler: &std::sync::Arc<dyn DeleteBucketHandler + Send + Sync>,
) {
    if req.method() != "DELETE" {
        resp.set_status(405);
        resp.send_header();
        return;
    }
    let opt = DeleteBucketOption {
        expected_owner: req.get_header("x-amz-expected-bucket-owner"),
    };
    let url_path = req.url_path();
    match handler.handle(&opt, url_path.trim_matches('/')).await {
        Ok(_) => {
            resp.set_status(204);
            resp.send_header();
        }
        Err(e) => {
            resp.set_status(500);
            log::error!("delete object handler error: {e}")
        }
    }
}

//utils
#[derive(Debug)]
enum ParseBodyError {
    HashNoMatch,
    ContentLengthIncorrect,
    Io(String),
}
impl Display for ParseBodyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            ParseBodyError::HashNoMatch => "hash no match",
            ParseBodyError::ContentLengthIncorrect => "content length incorrect",
            ParseBodyError::Io(err) => err.as_str(),
        })
    }
}
impl std::error::Error for ParseBodyError {}
enum StreamType {
    File(tokio::fs::File),
    Buff(tokio::io::BufReader<std::io::Cursor<Vec<u8>>>),
}
async fn get_body_stream<
    T: crate::utils::io::PollRead + Send,
    H: crate::authorization::v4::VHeader,
>(
    src: T,
    header: &H,
) -> Result<
    (
        StreamType,
        Option<std::pin::Pin<Box<dyn Send + std::future::Future<Output = ()>>>>,
    ),
    ParseBodyError,
> {
    let cl = header.get_header("content-length");
    let acs = header
        .get_header("x-amz-content-sha256")
        .ok_or(ParseBodyError::HashNoMatch)?;
    if let Some(cl) = cl {
        let cl = cl
            .as_str()
            .parse::<usize>()
            .or(Err(ParseBodyError::ContentLengthIncorrect))?;
        if acs.as_str() != "STREAMING-AWS4-HMAC-SHA256-PAYLOAD" {
            if cl <= 10 << 20 {
                let mut buff = vec![0u8; cl];
                parse_body(src, &mut buff, &acs, cl).await?;
                return Ok((
                    StreamType::Buff(tokio::io::BufReader::new(std::io::Cursor::new(buff))),
                    None,
                ));
            } else {
                let file_name = format!(".sys_bws/{}", crate::random_str!(4));
                let mut fd = tokio::fs::OpenOptions::new()
                    .create_new(true)
                    .write(true)
                    .mode(0o644)
                    .open(file_name.as_str())
                    .await
                    .map_err(|err| ParseBodyError::Io(err.to_string()))?;
                parse_body(src, &mut fd, &acs, cl).await?;
                drop(fd);
                match tokio::fs::OpenOptions::new()
                    .read(true)
                    .open(file_name.as_str())
                    .await
                {
                    Ok(fd) => {
                        return Ok((
                            StreamType::File(fd),
                            Some({
                                Box::pin(async move {
                                    let _ = tokio::fs::remove_file(file_name.as_str()).await;
                                })
                            }),
                        ))
                    }
                    Err(err) => {
                        let _ = tokio::fs::remove_file(file_name.as_str()).await;
                        return Err(ParseBodyError::Io(err.to_string()));
                    }
                }
                // return Ok(())
            }
        }
    }
    //chunk
    todo!()
}

async fn parse_body<
    T: crate::utils::io::PollRead + Send,
    E: tokio::io::AsyncWrite + Send + Unpin,
>(
    mut src: T,
    dst: &mut E,
    content_sha256: &str,
    mut content_length: usize,
) -> Result<(), ParseBodyError> {
    use tokio::io::AsyncWriteExt;
    let mut hsh = sha2::Sha256::new();
    // if content length > 10MB, it will store on disk instead memory
    while let Some(buff) = src.poll_read().await.map_err(ParseBodyError::Io)? {
        let buff_len = buff.len();
        if content_length < buff_len {
            return Err(ParseBodyError::ContentLengthIncorrect);
        }
        content_length -= buff_len;
        let _ = hsh.write_all(&buff);
        dst.write_all(&buff)
            .await
            .map_err(|err| ParseBodyError::Io(format!("write error {err}")))?;
    }
    let ret = hsh.finalize();
    let real_sha256 = hex::encode(ret);
    if real_sha256.as_str() != content_sha256 {
        Err(ParseBodyError::HashNoMatch)
    } else {
        Ok(())
    }
}

async fn parse_streaming_body<
    T: crate::utils::io::PollRead + Send,
    E: tokio::io::AsyncWrite + Send + Unpin,
>(
    mut src: T,
    dst: &mut E,
    content_sha256: &str,
) -> Result<(), ParseBodyError> {
    todo!()
}
// #[cfg(test)]
// mod req_test {
//     use std::{collections::HashMap, sync::RwLock};
//     static FAKE_ETAG: &str = "ffffffffffffffff";
//     struct HttpRequest {
//         url_path: String,
//         query: Vec<(String, String)>,
//         method: String,
//         headers: HashMap<String, String>,
//     }
//     impl crate::authorization::v4::VHeader for HttpRequest {
//         fn get_header(&self, key: &str) -> Option<String> {
//             self.headers
//                 .get(key)
//                 .map_or_else(|| None, |v| Some(v.clone()))
//         }

//         fn set_header(&mut self, key: &str, val: &str) {
//             self.headers.insert(key.to_string(), val.to_string());
//         }

//         fn delete_header(&mut self, key: &str) {
//             self.headers.remove(key);
//         }

//         fn rng_header(&self, mut cb: impl FnMut(&str, &str) -> bool) {
//             self.headers.iter().all(|(k, v)| cb(k, v));
//         }
//     }
//     impl super::VRequest for HttpRequest {
//         fn method(&self) -> String {
//             self.method.clone()
//         }

//         fn url_path(&self) -> String {
//             self.url_path.clone()
//         }

//         fn get_query(&self, target: &str) -> Option<String> {
//             let ans: Vec<_> = self.query.iter().filter(|(k, v)| k == target).collect();
//             if !ans.is_empty() {
//                 Some(ans.first().unwrap().1.clone())
//             } else {
//                 None
//             }
//         }

//         fn all_query(&self, mut cb: impl FnMut(&str, &str) -> bool) {
//             self.query.iter().all(|(k, v)| cb(k, v));
//         }
//     }
//     #[derive(Default)]
//     struct HttpResponse {
//         status: u16,
//         headers: HashMap<String, String>,
//         body: Vec<u8>,
//     }
//     impl crate::authorization::v4::VHeader for HttpResponse {
//         fn get_header(&self, key: &str) -> Option<String> {
//             self.headers
//                 .get(key)
//                 .map_or_else(|| None, |v| Some(v.clone()))
//         }

//         fn set_header(&mut self, key: &str, val: &str) {
//             self.headers.insert(key.to_string(), val.to_string());
//         }

//         fn delete_header(&mut self, key: &str) {
//             self.headers.remove(key);
//         }

//         fn rng_header(&self, mut cb: impl FnMut(&str, &str) -> bool) {
//             self.headers.iter().all(|(k, v)| cb(k, v));
//         }
//     }
//     struct VecWriter<'a>(&'a mut Vec<u8>);
//     impl<'a> std::io::Write for VecWriter<'_> {
//         fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
//             self.0.extend_from_slice(buf);
//             Ok(buf.len())
//         }

//         fn flush(&mut self) -> std::io::Result<()> {
//             Ok(())
//         }
//     }
//     impl super::BodyWriter for HttpResponse {
//         type BodyWriter<'a> = VecWriter<'a>;

//         fn get_body_writer(&mut self) -> Result<Self::BodyWriter<'_>, String> {
//             Ok(VecWriter(&mut self.body))
//         }
//     }
//     impl super::VResponse for HttpResponse {
//         fn set_status(&mut self, status: u16) {
//             if self.status != 0 {
//                 return;
//             }
//             self.status = status;
//         }

//         fn send_header(&mut self) {}
//     }

//     pub struct ListBucket(Vec<String>);
//     impl super::ListObjectHandler for ListBucket {
//         fn handle(
//             &self,
//             _: &super::ListObjectOption,
//             bucket: &str,
//         ) -> Result<Vec<super::ListObjectContent>, String> {
//             let last_modified = chrono::Utc::now().to_rfc2822();
//             Ok(self
//                 .0
//                 .iter()
//                 .filter_map(|v| {
//                     if v.starts_with(bucket) {
//                         return Some(super::ListObjectContent {
//                             key: v.trim_start_matches(bucket).to_string(),
//                             last_modified: Some(last_modified.clone()),
//                             etag: Some("801cbd6952577c28310fd5002670132a".to_string()),
//                             size: 20,
//                             owner: Some(super::Owner {
//                                 id: "123456789".to_string(),
//                                 display_name: "root".to_string(),
//                             }),
//                             storage_class: Some("standard".to_string()),
//                         });
//                     }
//                     None
//                 })
//                 .collect())
//         }
//     }

//     impl super::ListBucketHandler for ListBucket {
//         fn handle(
//             &self,
//             opt: &super::ListBucketsOption,
//         ) -> Result<Vec<super::Bucket>, String> {
//             let date = chrono::Utc::now().to_rfc2822();
//             Ok(self
//                 .0
//                 .iter()
//                 .map(|v| super::Bucket {
//                     name: v.find('/').map_or(v.clone(), |next| v[..next].to_string()),
//                     creation_date: date.clone(),
//                     bucket_region: "us-east-1".to_string(),
//                 })
//                 .collect())
//         }
//     }

//     #[test]
//     fn list_object() {
//         let lb = ListBucket(vec![
//             "test/hello.txt".to_string(),
//             "test/test.dat".to_string(),
//             "one/jack.json".to_string(),
//             "one/jim.json".to_string(),
//         ]);
//         let hm = HashMap::default();
//         let req = HttpRequest {
//             url_path: "/test".to_string(),
//             query: vec![],
//             method: "GET".to_string(),
//             headers: hm,
//         };
//         let mut resp = HttpResponse {
//             status: 0,
//             headers: HashMap::default(),
//             body: vec![],
//         };
//         super::handle_get_list_object(&req, &mut resp, &lb);
//         String::from_utf8(resp.body)
//             .map_or_else(|e| eprintln!("not ascii {e}"), |v| println!("{v}"));
//     }
//     #[test]
//     fn list_buckets() {
//         let hm = HashMap::default();
//         let req = HttpRequest {
//             url_path: "/".to_string(),
//             query: vec![],
//             method: "GET".to_string(),
//             headers: hm,
//         };
//         let mut resp = HttpResponse {
//             status: 0,
//             headers: HashMap::default(),
//             body: vec![],
//         };
//         let lb = ListBucket(vec![
//             "test/hello.txt".to_string(),
//             "test/test.dat".to_string(),
//             "one/jack.json".to_string(),
//             "one/jim.json".to_string(),
//         ]);
//         super::handle_get_list_buckets(&req, &mut resp, &lb);
//         String::from_utf8(resp.body)
//             .map_or_else(|e| eprintln!("not ascii {e}"), |v| println!("{v}"));
//     }

//     impl super::CreateBucketHandler for RwLock<ListBucket> {
//         fn handle(
//             &self,
//             opt: &super::CreateBucketOption,
//             bucket: &str,
//         ) -> Result<(), String> {
//             self.write().map_or(
//                 Err(Box::new(super::Error("write lock failed".to_string()))),
//                 |mut raw| {
//                     for v in raw.0.iter() {
//                         if v == bucket {
//                             return Ok(());
//                         }
//                     }
//                     raw.0.push(bucket.to_string());
//                     Ok(())
//                 },
//             )
//         }
//     }
//     impl super::DeleteBucketHandler for RwLock<ListBucket> {
//         fn handle(
//             &self,
//             opt: &super::DeleteBucketOption,
//             bucket: &str,
//         ) -> Result<(), String> {
//             self.write().map_or(
//                 Err(Box::new(super::Error("write lock failed".to_string()))),
//                 |mut v| {
//                     let mut index = 0;
//                     let mut remove_index = -1;
//                     for vv in v.0.iter() {
//                         if vv == bucket {
//                             remove_index = index;
//                             break;
//                         }
//                         index += 1;
//                     }
//                     if remove_index >= 0 {
//                         v.0.remove(remove_index as usize);
//                     }
//                     Ok(())
//                 },
//             )
//         }
//     }
//     #[test]
//     fn create_bucket() {
//         let hm = HashMap::default();
//         let mut req = HttpRequest {
//             url_path: "/t10".to_string(),
//             query: vec![],
//             method: "PUT".to_string(),
//             headers: hm,
//         };
//         let mut resp = HttpResponse {
//             status: 0,
//             headers: HashMap::default(),
//             body: vec![],
//         };
//         let lb = ListBucket(vec![]);
//         let lb = RwLock::new(lb);
//         super::handle_create_bucket(&req, &mut resp, &lb);
//         assert!(
//             lb.read().expect("read lock error").0.len() == 1,
//             "create bucket failed {}",
//             resp.status
//         );
//         req.method = "DELETE".to_string();
//         resp = HttpResponse {
//             status: 0,
//             headers: HashMap::default(),
//             body: vec![],
//         };
//         super::handle_delete_bucket(&req, &mut resp, &lb);
//         assert!(
//             lb.read().unwrap().0.is_empty(),
//             "delete failed {}",
//             resp.status
//         );
//     }
//     impl super::LookupHandler for HashMap<String, String> {
//         fn lookup(
//             &self,
//             bucket: &str,
//             object: &str,
//         ) -> Result<Option<super::HeadObjectResult>, super::Error> {
//             let ret = self.get(object);
//             if let None = ret {
//                 return Ok(None);
//             }
//             let info = ret.unwrap();
//             Ok(Some(super::HeadObjectResult {
//                 content_length: Some(info.len()),
//                 content_type: Some("text/plain".to_string()),
//                 etag: Some(FAKE_ETAG.to_string()),
//                 last_modified: Some(chrono::Utc::now().to_rfc2822().to_string()),
//                 ..Default::default()
//             }))
//         }
//     }
//     impl super::GetObjectHandler for HashMap<String, String> {
//         fn handle(
//             &self,
//             bucket: &str,
//             object: &str,
//             mut out: impl FnMut(&[u8]) -> Result<(), String>,
//         ) -> Result<(), String> {
//             let ret = self.get(object);
//             if let None = ret {
//                 return Err(Box::new(super::Error("content not found".to_string())));
//             }
//             let info = ret.unwrap();
//             out(info.as_bytes())
//         }
//     }

//     #[test]
//     fn get_object() {
//         let hm = HashMap::default();
//         let req = HttpRequest {
//             url_path: "/test/test.txt".to_string(),
//             query: vec![],
//             method: "GET".to_string(),
//             headers: hm,
//         };
//         let mut resp = HttpResponse::default();
//         let mut objstore = HashMap::default();
//         objstore.insert("test.txt".to_string(), "im test!".to_string());
//         super::handle_get_object(&req, &mut resp, &objstore);
//         assert!(
//             resp.status == 200,
//             "response status is not 200 {}",
//             resp.status
//         );
//         let val = String::from_utf8(resp.body).map_or("NoAscii".to_string(), |v| v);
//         assert!(
//             val == "im test!",
//             "response content is not 'im test!' got {}",
//             val
//         );

//         let mut resp = HttpResponse::default();
//         let mut objstore = HashMap::default();
//         objstore.insert("hello.txt".to_string(), "im test!".to_string());
//         super::handle_get_object(&req, &mut resp, &objstore);
//         assert!(
//             resp.status == 404,
//             "response status is not 404 {}",
//             resp.status
//         );
//     }
//     #[test]
//     fn put_and_delete_object() {}
// }