aliyun-oss-client 0.12.7

an aliyun oss client
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
//! lib 内置类型的定义模块

use std::{
    borrow::Cow,
    error::Error,
    fmt::{self, Debug, Display, Formatter},
    str::FromStr,
};

use chrono::{DateTime, TimeZone};
use http::header::{HeaderValue, InvalidHeaderValue, ToStrError};
use url::Url;

#[cfg(feature = "core")]
pub mod core;

pub mod object;
#[cfg(test)]
mod test;

use crate::consts::{TRUE1, TRUE2, TRUE3, TRUE4};

#[cfg(feature = "core")]
pub use self::core::{ContentRange, Query, QueryKey, QueryValue, SetOssQuery};
use self::object::{ObjectPathInner, SetObjectPath};

const OSS_DOMAIN_PREFIX: &str = "https://oss-";
#[allow(dead_code)]
const OSS_INTERNAL: &str = "-internal";
const OSS_DOMAIN_MAIN: &str = ".aliyuncs.com";
const OSS_HYPHEN: &str = "oss-";

const HANGZHOU: &str = "cn-hangzhou";
const SHANGHAI: &str = "cn-shanghai";
const QINGDAO: &str = "cn-qingdao";
const BEIJING: &str = "cn-beijing";
const ZHANGJIAKOU: &str = "cn-zhangjiakou";
const HONGKONG: &str = "cn-hongkong";
const SHENZHEN: &str = "cn-shenzhen";
const US_WEST1: &str = "us-west-1";
const US_EAST1: &str = "us-east-1";
const AP_SOUTH_EAST1: &str = "ap-southeast-1";

const HANGZHOU_L: &str = "hangzhou";
const SHANGHAI_L: &str = "shanghai";
const QINGDAO_L: &str = "qingdao";
const BEIJING_L: &str = "beijing";
const ZHANGJIAKOU_L: &str = "zhangjiakou";
const HONGKONG_L: &str = "hongkong";
const SHENZHEN_L: &str = "shenzhen";

const COM: &str = "com";
const ALIYUNCS: &str = "aliyuncs";

/// 阿里云 OSS 的签名 key
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct InnerKeyId<'a>(Cow<'a, str>);

/// 静态作用域的 InnerKeyId
pub type KeyId = InnerKeyId<'static>;

impl AsRef<str> for InnerKeyId<'_> {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl Display for InnerKeyId<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl TryInto<HeaderValue> for InnerKeyId<'_> {
    type Error = InvalidHeaderValue;
    fn try_into(self) -> Result<HeaderValue, InvalidHeaderValue> {
        HeaderValue::from_str(self.as_ref())
    }
}

impl From<String> for KeyId {
    fn from(s: String) -> KeyId {
        Self(Cow::Owned(s))
    }
}

impl<'a: 'b, 'b> From<&'a str> for InnerKeyId<'b> {
    fn from(key_id: &'a str) -> Self {
        Self(Cow::Borrowed(key_id))
    }
}

impl<'a> InnerKeyId<'a> {
    /// Creates a new `KeyId` from the given string.
    pub fn new(key_id: impl Into<Cow<'a, str>>) -> Self {
        Self(key_id.into())
    }

    /// Const function that creates a new `KeyId` from a static str.
    pub const fn from_static(key_id: &'static str) -> Self {
        Self(Cow::Borrowed(key_id))
    }
}

//===================================================================================================

/// 阿里云 OSS 的签名 secret
#[derive(Clone, PartialEq, Eq, Default)]
pub struct InnerKeySecret<'a>(Cow<'a, str>);

/// 静态作用域的 InnerKeySecret
pub type KeySecret = InnerKeySecret<'static>;

impl Display for InnerKeySecret<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "******secret******")
    }
}

impl Debug for InnerKeySecret<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_tuple("KeySecret").finish()
    }
}

impl From<String> for KeySecret {
    fn from(s: String) -> Self {
        Self(Cow::Owned(s))
    }
}

impl<'a: 'b, 'b> From<&'a str> for InnerKeySecret<'b> {
    fn from(secret: &'a str) -> Self {
        Self(Cow::Borrowed(secret))
    }
}

impl<'a> InnerKeySecret<'a> {
    /// Creates a new `KeySecret` from the given string.
    pub fn new(secret: impl Into<Cow<'a, str>>) -> Self {
        Self(secret.into())
    }

    /// Const function that creates a new `KeySecret` from a static str.
    pub const fn from_static(secret: &'static str) -> Self {
        Self(Cow::Borrowed(secret))
    }

    #[cfg(test)]
    pub(crate) fn as_str(&self) -> &str {
        &self.0
    }

    /// 加密 String 数据
    #[inline]
    pub fn encryption_string(
        &self,
        string: String,
    ) -> Result<String, hmac::digest::crypto_common::InvalidLength> {
        self.encryption(string.as_bytes())
    }

    /// # 加密数据
    /// 这种加密方式可保证秘钥明文只会存在于 `InnerKeySecret` 类型内,不会被读取或复制
    pub fn encryption(
        &self,
        data: &[u8],
    ) -> Result<String, hmac::digest::crypto_common::InvalidLength> {
        use base64::engine::general_purpose::STANDARD;
        use base64::Engine;
        use hmac::{Hmac, Mac};
        use sha1::Sha1;
        type HmacSha1 = Hmac<Sha1>;

        let secret = self.0.as_bytes();

        let mut mac = HmacSha1::new_from_slice(secret)?;

        mac.update(data);

        let sha1 = mac.finalize().into_bytes();

        Ok(STANDARD.encode(sha1))
    }
}

//===================================================================================================

/// # OSS 的可用区
/// [aliyun docs](https://help.aliyun.com/document_detail/31837.htm)
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct EndPoint {
    pub(crate) kind: EndPointKind,
    /// default false
    pub(crate) is_internal: bool,
}

// TODO
#[allow(non_upper_case_globals)]
impl EndPoint {
    /// 杭州
    #[deprecated(since = "0.13.0", note = "replace with EndPoint::CN_HANGZHOU")]
    pub const CnHangzhou: Self = Self {
        kind: EndPointKind::CnHangzhou,
        is_internal: false,
    };
    /// 杭州
    pub const CN_HANGZHOU: Self = Self {
        kind: EndPointKind::CnHangzhou,
        is_internal: false,
    };

    /// 上海
    #[deprecated(since = "0.13.0", note = "replace with EndPoint::CN_SHANGHAI")]
    pub const CnShanghai: Self = Self {
        kind: EndPointKind::CnShanghai,
        is_internal: false,
    };
    /// 上海
    pub const CN_SHANGHAI: Self = Self {
        kind: EndPointKind::CnShanghai,
        is_internal: false,
    };

    /// 青岛
    #[deprecated(since = "0.13.0", note = "replace with EndPoint::CN_QINGDAO")]
    pub const CnQingdao: Self = Self {
        kind: EndPointKind::CnQingdao,
        is_internal: false,
    };
    /// 青岛
    pub const CN_QINGDAO: Self = Self {
        kind: EndPointKind::CnQingdao,
        is_internal: false,
    };

    /// 北京
    #[deprecated(since = "0.13.0", note = "replace with EndPoint::CN_BEIJING")]
    pub const CnBeijing: Self = Self {
        kind: EndPointKind::CnBeijing,
        is_internal: false,
    };
    /// 北京
    pub const CN_BEIJING: Self = Self {
        kind: EndPointKind::CnBeijing,
        is_internal: false,
    };

    /// 张家口
    #[deprecated(since = "0.13.0", note = "replace with EndPoint::CN_ZHANGJIAKOU")]
    pub const CnZhangjiakou: Self = Self {
        kind: EndPointKind::CnZhangjiakou,
        is_internal: false,
    };
    /// 张家口
    pub const CN_ZHANGJIAKOU: Self = Self {
        kind: EndPointKind::CnZhangjiakou,
        is_internal: false,
    };

    /// 香港
    #[deprecated(since = "0.13.0", note = "replace with EndPoint::CN_HONGKONG")]
    pub const CnHongkong: Self = Self {
        kind: EndPointKind::CnHongkong,
        is_internal: false,
    };
    /// 香港
    pub const CN_HONGKONG: Self = Self {
        kind: EndPointKind::CnHongkong,
        is_internal: false,
    };

    /// 深圳
    #[deprecated(since = "0.13.0", note = "replace with EndPoint::CN_SHENZHEN")]
    pub const CnShenzhen: Self = Self {
        kind: EndPointKind::CnShenzhen,
        is_internal: false,
    };
    /// 深圳
    pub const CN_SHENZHEN: Self = Self {
        kind: EndPointKind::CnShenzhen,
        is_internal: false,
    };

    /// UsWest1
    #[deprecated(since = "0.13.0", note = "replace with EndPoint::US_WEST_1")]
    pub const UsWest1: Self = Self {
        kind: EndPointKind::UsWest1,
        is_internal: false,
    };
    /// UsWest1
    pub const US_WEST_1: Self = Self {
        kind: EndPointKind::UsWest1,
        is_internal: false,
    };

    /// UsEast1
    #[deprecated(since = "0.13.0", note = "replace with EndPoint::US_EAST_1")]
    pub const UsEast1: Self = Self {
        kind: EndPointKind::UsEast1,
        is_internal: false,
    };
    /// UsEast1
    pub const US_EAST_1: Self = Self {
        kind: EndPointKind::UsEast1,
        is_internal: false,
    };

    /// ApSouthEast1
    #[deprecated(since = "0.13.0", note = "replace with EndPoint::AP_SOUTH_EAST_1")]
    pub const ApSouthEast1: Self = Self {
        kind: EndPointKind::ApSouthEast1,
        is_internal: false,
    };
    /// ApSouthEast1
    pub const AP_SOUTH_EAST_1: Self = Self {
        kind: EndPointKind::ApSouthEast1,
        is_internal: false,
    };
}

/// # OSS 的可用区种类 enum
#[derive(Clone, Debug, PartialEq, Eq, Default)]
#[non_exhaustive]
pub(crate) enum EndPointKind {
    /// 杭州可用区
    #[default]
    CnHangzhou,
    /// 上海可用区
    CnShanghai,
    /// 青岛可用区
    CnQingdao,
    /// 北京可用区
    CnBeijing,
    /// 张家口可用区
    CnZhangjiakou, // 张家口 lenght=13
    /// 香港
    CnHongkong,
    /// 深圳
    CnShenzhen,
    /// 美国西部
    UsWest1,
    /// 美国东部
    UsEast1,
    /// 新加坡
    ApSouthEast1,
    /// 其他可用区 fuzhou,ap-southeast-6 等
    Other(Cow<'static, str>),
}

impl AsRef<str> for EndPoint {
    /// ```
    /// # use aliyun_oss_client::types::EndPoint;
    ///
    /// assert_eq!(EndPoint::CnHangzhou.as_ref(), "cn-hangzhou");
    /// assert_eq!(EndPoint::CnShanghai.as_ref(), "cn-shanghai");
    /// assert_eq!(EndPoint::CnQingdao.as_ref(), "cn-qingdao");
    /// assert_eq!(EndPoint::CnBeijing.as_ref(), "cn-beijing");
    /// assert_eq!(EndPoint::CnZhangjiakou.as_ref(), "cn-zhangjiakou");
    /// assert_eq!(EndPoint::CnHongkong.as_ref(), "cn-hongkong");
    /// assert_eq!(EndPoint::CnShenzhen.as_ref(), "cn-shenzhen");
    /// assert_eq!(EndPoint::UsWest1.as_ref(), "us-west-1");
    /// assert_eq!(EndPoint::UsEast1.as_ref(), "us-east-1");
    /// assert_eq!(EndPoint::ApSouthEast1.as_ref(), "ap-southeast-1");
    /// ```
    fn as_ref(&self) -> &str {
        use EndPointKind::*;
        match &self.kind {
            CnHangzhou => HANGZHOU,
            CnShanghai => SHANGHAI,
            CnQingdao => QINGDAO,
            CnBeijing => BEIJING,
            CnZhangjiakou => ZHANGJIAKOU,
            CnHongkong => HONGKONG,
            CnShenzhen => SHENZHEN,
            UsWest1 => US_WEST1,
            UsEast1 => US_EAST1,
            ApSouthEast1 => AP_SOUTH_EAST1,
            Other(str) => str,
        }
    }
}

impl Display for EndPoint {
    /// ```
    /// # use aliyun_oss_client::types::EndPoint;
    /// assert_eq!(format!("{}", EndPoint::CnHangzhou), "cn-hangzhou");
    /// ```
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_ref())
    }
}

impl TryFrom<String> for EndPoint {
    type Error = InvalidEndPoint;
    /// 字符串转 endpoint
    ///
    /// 举例
    /// ```
    /// # use aliyun_oss_client::types::EndPoint;
    /// let e: EndPoint = String::from("qingdao").try_into().unwrap();
    /// assert_eq!(e, EndPoint::CnQingdao);
    /// ```
    fn try_from(url: String) -> Result<Self, Self::Error> {
        Self::new(&url)
    }
}

impl<'a> TryFrom<&'a str> for EndPoint {
    type Error = InvalidEndPoint;
    /// 字符串字面量转 endpoint
    ///
    /// 举例
    /// ```
    /// # use aliyun_oss_client::types::EndPoint;
    /// let e: EndPoint = "qingdao".try_into().unwrap();
    /// assert_eq!(e, EndPoint::CnQingdao);
    /// ```
    fn try_from(url: &'a str) -> Result<Self, Self::Error> {
        Self::new(url)
    }
}

impl FromStr for EndPoint {
    type Err = InvalidEndPoint;
    fn from_str(url: &str) -> Result<Self, Self::Err> {
        Self::new(url)
    }
}

impl TryFrom<Url> for EndPoint {
    type Error = InvalidEndPoint;
    fn try_from(url: Url) -> Result<Self, Self::Error> {
        use url::Host;
        let domain = if let Some(Host::Domain(domain)) = url.host() {
            domain
        } else {
            return Err(InvalidEndPoint { _priv: () });
        };
        let mut url_pieces = domain.rsplit('.');

        match (url_pieces.next(), url_pieces.next()) {
            (Some(COM), Some(ALIYUNCS)) => (),
            _ => return Err(InvalidEndPoint { _priv: () }),
        }

        match url_pieces.next() {
            Some(endpoint) => match EndPoint::from_host_piece(endpoint) {
                Ok(end) => Ok(end),
                _ => Err(InvalidEndPoint { _priv: () }),
            },
            _ => Err(InvalidEndPoint { _priv: () }),
        }
    }
}

impl<'a> EndPoint {
    /// 通过字符串字面值初始化 endpoint
    ///
    /// 例如
    /// ```
    /// # use aliyun_oss_client::types::EndPoint;
    /// EndPoint::from_static("qingdao");
    /// ```
    pub fn from_static(url: &'a str) -> Self {
        Self::new(url).unwrap_or_else(|_| panic!("Unknown Endpoint :{}", url))
    }

    /// # Safety
    /// 用于静态定义其他可用区
    pub const unsafe fn from_static2(url: &'static str) -> Self {
        Self {
            kind: EndPointKind::Other(Cow::Borrowed(url)),
            is_internal: false,
        }
    }

    /// 初始化 endpoint enum
    /// ```rust
    /// # use aliyun_oss_client::types::EndPoint;
    /// # use std::borrow::Cow;
    /// assert!(matches!(
    ///     EndPoint::new("shanghai"),
    ///     Ok(EndPoint::CnShanghai)
    /// ));
    ///
    /// assert!(EndPoint::new("abc-").is_err());
    /// assert!(EndPoint::new("-abc").is_err());
    /// assert!(EndPoint::new("abc-def234ab").is_ok());
    /// assert!(EndPoint::new("abc-def*#$%^ab").is_err());
    /// assert!(EndPoint::new("cn-jinan").is_ok());
    /// assert!(EndPoint::new("cn-jinan").is_ok());
    /// assert!(EndPoint::new("oss-cn-jinan").is_err());
    /// ```
    pub fn new(url: &'a str) -> Result<Self, InvalidEndPoint> {
        const OSS_STR: &str = "oss";
        use EndPointKind::*;
        if url.is_empty() {
            return Err(InvalidEndPoint { _priv: () });
        }
        // 是否是内网
        let is_internal = url.ends_with(OSS_INTERNAL);
        let url = if is_internal {
            let len = url.len();
            &url[..len - 9]
        } else {
            url
        };

        let kind = if url.contains(SHANGHAI_L) {
            Ok(CnShanghai)
        } else if url.contains(HANGZHOU_L) {
            Ok(CnHangzhou)
        } else if url.contains(QINGDAO_L) {
            Ok(CnQingdao)
        } else if url.contains(BEIJING_L) {
            Ok(CnBeijing)
        } else if url.contains(ZHANGJIAKOU_L) {
            Ok(CnZhangjiakou)
        } else if url.contains(HONGKONG_L) {
            Ok(CnHongkong)
        } else if url.contains(SHENZHEN_L) {
            Ok(CnShenzhen)
        } else if url.contains(US_WEST1) {
            Ok(UsWest1)
        } else if url.contains(US_EAST1) {
            Ok(UsEast1)
        } else if url.contains(AP_SOUTH_EAST1) {
            Ok(ApSouthEast1)
        } else {
            if url.starts_with('-') || url.ends_with('-') || url.starts_with(OSS_STR) {
                return Err(InvalidEndPoint { _priv: () });
            }

            if !url.chars().all(valid_oss_character) {
                return Err(InvalidEndPoint { _priv: () });
            }

            Ok(Other(Cow::Owned(url.to_owned())))
        };

        kind.map(|kind| Self { kind, is_internal })
    }

    /// 从 oss 域名中提取 Endpoint 信息
    pub(crate) fn from_host_piece(url: &'a str) -> Result<Self, InvalidEndPoint> {
        if !url.starts_with(OSS_HYPHEN) {
            return Err(InvalidEndPoint { _priv: () });
        }
        Self::new(&url[4..])
    }

    /// use env init Endpoint
    pub fn from_env() -> Result<Self, InvalidEndPoint> {
        let endpoint =
            std::env::var("ALIYUN_ENDPOINT").map_err(|_| InvalidEndPoint { _priv: () })?;
        let mut endpoint: EndPoint = endpoint
            .parse()
            .map_err(|_| InvalidEndPoint { _priv: () })?;
        if let Ok(is_internal) = std::env::var("ALIYUN_OSS_INTERNAL") {
            if is_internal == TRUE1
                || is_internal == TRUE2
                || is_internal == TRUE3
                || is_internal == TRUE4
            {
                endpoint.set_internal(true);
            }
        }

        Ok(endpoint)
    }

    /// # 调整 API 指向是否为内网
    ///
    /// 当在 Aliyun ECS 上执行时,设为 true 会更高效,默认是 false
    pub fn set_internal(&mut self, is_internal: bool) {
        self.is_internal = is_internal;
    }

    /// 转化成 Url
    /// ```
    /// # use aliyun_oss_client::types::EndPoint;
    /// use reqwest::Url;
    /// let mut endpoint = EndPoint::new("shanghai").unwrap();
    /// assert_eq!(
    ///     endpoint.to_url(),
    ///     Url::parse("https://oss-cn-shanghai.aliyuncs.com").unwrap()
    /// );
    ///
    /// endpoint.set_internal(true);
    /// assert_eq!(
    ///     endpoint.to_url(),
    ///     Url::parse("https://oss-cn-shanghai-internal.aliyuncs.com").unwrap()
    /// );
    /// ```
    pub fn to_url(&self) -> Url {
        let mut url = String::from(OSS_DOMAIN_PREFIX);
        url.push_str(self.as_ref());

        // internal
        if self.is_internal {
            url.push_str(OSS_INTERNAL);
        }

        url.push_str(OSS_DOMAIN_MAIN);
        Url::parse(&url).unwrap_or_else(|_| panic!("covert to url failed, endpoint: {}", url))
    }
}

/// 无效的可用区
#[derive(PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct InvalidEndPoint {
    pub(crate) _priv: (),
}

impl Debug for InvalidEndPoint {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("InvalidEndPoint").finish()
    }
}

impl Error for InvalidEndPoint {}

impl fmt::Display for InvalidEndPoint {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "endpoint must not with `-` prefix or `-` suffix or `oss-` prefix"
        )
    }
}

impl PartialEq<&str> for EndPoint {
    /// # 相等比较
    /// ```
    /// # use aliyun_oss_client::types::EndPoint;
    /// let e: EndPoint = String::from("qingdao").try_into().unwrap();
    /// assert!(e == "cn-qingdao");
    /// ```
    #[inline]
    fn eq(&self, other: &&str) -> bool {
        &self.as_ref() == other
    }
}

impl PartialEq<EndPoint> for &str {
    /// # 相等比较
    /// ```
    /// # use aliyun_oss_client::types::EndPoint;
    /// let e: EndPoint = String::from("qingdao").try_into().unwrap();
    /// assert!("cn-qingdao" == e);
    /// ```
    #[inline]
    fn eq(&self, other: &EndPoint) -> bool {
        self == &other.as_ref()
    }
}

impl PartialEq<Url> for EndPoint {
    /// # 相等比较
    /// ```
    /// # use aliyun_oss_client::types::EndPoint;
    /// use reqwest::Url;
    /// let endpoint = EndPoint::new("shanghai").unwrap();
    /// assert!(endpoint == Url::parse("https://oss-cn-shanghai.aliyuncs.com").unwrap());
    /// ```
    #[inline]
    fn eq(&self, other: &Url) -> bool {
        &self.to_url() == other
    }
}

//===================================================================================================

/// 存储 bucket 名字的类型
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BucketName(Cow<'static, str>);

impl AsRef<str> for BucketName {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl Display for BucketName {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl Default for BucketName {
    fn default() -> BucketName {
        #[allow(clippy::unwrap_used)]
        BucketName::new("a").unwrap()
    }
}

// impl TryInto<HeaderValue> for BucketName {
//     type Error = InvalidHeaderValue;
//     fn try_into(self) -> Result<HeaderValue, InvalidHeaderValue> {
//         HeaderValue::from_str(self.as_ref())
//     }
// }
impl TryFrom<String> for BucketName {
    type Error = InvalidBucketName;
    /// ```
    /// # use aliyun_oss_client::types::BucketName;
    /// let b: BucketName = String::from("abc").try_into().unwrap();
    /// assert_eq!(b, BucketName::new("abc").unwrap());
    /// ```
    fn try_from(s: String) -> Result<Self, Self::Error> {
        Self::new(s)
    }
}

impl<'a> TryFrom<&'a str> for BucketName {
    type Error = InvalidBucketName;
    /// ```
    /// # use aliyun_oss_client::types::BucketName;
    /// let b: BucketName = "abc".try_into().unwrap();
    /// assert_eq!(b, BucketName::new("abc").unwrap());
    /// ```
    fn try_from(bucket: &'a str) -> Result<Self, Self::Error> {
        Self::from_static(bucket)
    }
}

impl FromStr for BucketName {
    type Err = InvalidBucketName;
    /// ```
    /// # use aliyun_oss_client::types::BucketName;
    /// let b: BucketName = "abc".parse().unwrap();
    /// assert_eq!(b, BucketName::new("abc").unwrap());
    /// ```
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::from_static(s)
    }
}

impl<'a> BucketName {
    /// Creates a new `BucketName` from the given string.
    /// 只允许小写字母、数字、短横线(-),且不能以短横线开头或结尾
    ///
    /// ```
    /// # use aliyun_oss_client::types::BucketName;
    ///
    /// assert!(BucketName::new("").is_err());
    /// assert!(BucketName::new("abc").is_ok());
    /// assert!(BucketName::new("abc-").is_err());
    /// assert!(BucketName::new("-abc").is_err());
    /// assert!(BucketName::new("abc-def234ab").is_ok());
    /// assert!(BucketName::new("abc-def*#$%^ab").is_err());
    /// ```
    pub fn new(bucket: impl Into<Cow<'static, str>>) -> Result<Self, InvalidBucketName> {
        let bucket = bucket.into();

        if bucket.is_empty() || bucket.starts_with('-') || bucket.ends_with('-') {
            return Err(InvalidBucketName { _priv: () });
        }

        if !bucket.chars().all(valid_oss_character) {
            return Err(InvalidBucketName { _priv: () });
        }

        Ok(Self(bucket))
    }

    /// use env init BucketName
    pub fn from_env() -> Result<Self, InvalidBucketName> {
        let string = std::env::var("ALIYUN_BUCKET").map_err(|_| InvalidBucketName { _priv: () })?;

        string.parse()
    }

    /// Const function that creates a new `BucketName` from a static str.
    /// ```
    /// # use aliyun_oss_client::types::BucketName;
    ///
    /// assert!(BucketName::from_static("").is_err());
    /// assert!(BucketName::from_static("abc").is_ok());
    /// assert!(BucketName::from_static("abc-").is_err());
    /// assert!(BucketName::from_static("-abc").is_err());
    /// assert!(BucketName::from_static("abc-def234ab").is_ok());
    /// assert!(BucketName::from_static("abc-def*#$%^ab").is_err());
    /// ```
    pub fn from_static(bucket: &'a str) -> Result<Self, InvalidBucketName> {
        if bucket.is_empty() || bucket.starts_with('-') || bucket.ends_with('-') {
            return Err(InvalidBucketName { _priv: () });
        }

        if !bucket.chars().all(valid_oss_character) {
            return Err(InvalidBucketName { _priv: () });
        }

        Ok(Self(Cow::Owned(bucket.to_owned())))
    }

    /// # Safety
    pub const unsafe fn from_static2(bucket: &'static str) -> Self {
        Self(Cow::Borrowed(bucket))
    }
}

fn valid_oss_character(c: char) -> bool {
    match c {
        _ if c.is_ascii_lowercase() => true,
        _ if c.is_numeric() => true,
        '-' => true,
        _ => false,
    }
}

impl PartialEq<&str> for BucketName {
    /// 相等比较
    /// ```
    /// # use aliyun_oss_client::types::BucketName;
    /// let path = BucketName::new("abc").unwrap();
    /// assert!(path == "abc");
    /// ```
    #[inline]
    fn eq(&self, other: &&str) -> bool {
        &self.0 == other
    }
}

impl PartialEq<BucketName> for &str {
    /// 相等比较
    /// ```
    /// # use aliyun_oss_client::types::BucketName;
    /// let path = BucketName::new("abc").unwrap();
    /// assert!("abc" == path);
    /// ```
    #[inline]
    fn eq(&self, other: &BucketName) -> bool {
        self == &other.0
    }
}

/// 无效的 bucket 名称
#[derive(PartialEq)]
#[non_exhaustive]
pub struct InvalidBucketName {
    pub(crate) _priv: (),
}

impl Debug for InvalidBucketName {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("InvalidBucketName").finish()
    }
}

impl Error for InvalidBucketName {}

impl fmt::Display for InvalidBucketName {
    /// ```
    /// # use aliyun_oss_client::types::BucketName;
    ///
    /// let err = BucketName::from_static("").unwrap_err();
    /// assert_eq!(
    ///     format!("{}", err),
    ///     "bucket name only allow `alphabet, digit, -`, and must not with `-` prefix or `-` suffix"
    /// );
    /// ```
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "bucket name only allow `alphabet, digit, -`, and must not with `-` prefix or `-` suffix"
        )
    }
}

//===================================================================================================

/// aliyun OSS 的配置 ContentMd5
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct InnerContentMd5<'a>(Cow<'a, str>);
/// 静态作用域的 InnerContentMd5
pub type ContentMd5 = InnerContentMd5<'static>;

impl AsRef<str> for InnerContentMd5<'_> {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl Display for InnerContentMd5<'_> {
    /// ```
    /// # use aliyun_oss_client::types::ContentMd5;
    /// let md5 = ContentMd5::new("abc");
    /// assert_eq!(format!("{md5}"), "abc");
    /// ```
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl TryInto<HeaderValue> for InnerContentMd5<'_> {
    type Error = InvalidHeaderValue;
    fn try_into(self) -> Result<HeaderValue, InvalidHeaderValue> {
        HeaderValue::from_str(self.as_ref())
    }
}

impl TryInto<HeaderValue> for &InnerContentMd5<'_> {
    type Error = InvalidHeaderValue;
    fn try_into(self) -> Result<HeaderValue, InvalidHeaderValue> {
        HeaderValue::from_str(self.as_ref())
    }
}
impl From<String> for ContentMd5 {
    /// ```
    /// # use aliyun_oss_client::types::ContentMd5;
    /// let md5: ContentMd5 = String::from("abc").into();
    /// assert_eq!(format!("{md5}"), "abc");
    /// ```
    fn from(s: String) -> Self {
        Self(Cow::Owned(s))
    }
}

impl<'a: 'b, 'b> From<&'a str> for InnerContentMd5<'b> {
    fn from(value: &'a str) -> Self {
        Self(Cow::Borrowed(value))
    }
}

impl<'a> InnerContentMd5<'a> {
    /// Creates a new `ContentMd5` from the given string.
    pub fn new(val: impl Into<Cow<'a, str>>) -> Self {
        Self(val.into())
    }

    /// Const function that creates a new `ContentMd5` from a static str.
    pub const fn from_static(val: &'static str) -> Self {
        Self(Cow::Borrowed(val))
    }
}

//===================================================================================================

/// aliyun OSS 的配置 ContentType
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct ContentType(Cow<'static, str>);

impl AsRef<str> for ContentType {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl Display for ContentType {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl TryInto<HeaderValue> for ContentType {
    type Error = InvalidHeaderValue;
    fn try_into(self) -> Result<HeaderValue, InvalidHeaderValue> {
        HeaderValue::from_str(self.as_ref())
    }
}
impl TryFrom<HeaderValue> for ContentType {
    type Error = ToStrError;
    fn try_from(value: HeaderValue) -> Result<Self, Self::Error> {
        Ok(Self(Cow::Owned(value.to_str()?.to_owned())))
    }
}
impl From<String> for ContentType {
    fn from(s: String) -> Self {
        Self(Cow::Owned(s))
    }
}

impl ContentType {
    /// Creates a new `ContentMd5` from the given string.
    pub fn new(val: impl Into<Cow<'static, str>>) -> Self {
        Self(val.into())
    }

    /// Const function that creates a new `ContentMd5` from a static str.
    pub const fn from_static(val: &'static str) -> Self {
        Self(Cow::Borrowed(val))
    }
}

//===================================================================================================

/// 用于计算签名的 Date
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct InnerDate<'a>(Cow<'a, str>);
/// 静态作用域的 InnerDate
pub type Date = InnerDate<'static>;

impl AsRef<str> for InnerDate<'_> {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl Display for InnerDate<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl TryInto<HeaderValue> for InnerDate<'_> {
    type Error = InvalidHeaderValue;
    fn try_into(self) -> Result<HeaderValue, InvalidHeaderValue> {
        HeaderValue::from_str(self.as_ref())
    }
}

impl<Tz: TimeZone> From<DateTime<Tz>> for Date
where
    Tz::Offset: fmt::Display,
{
    fn from(d: DateTime<Tz>) -> Self {
        Self(Cow::Owned(d.format("%a, %d %b %Y %T GMT").to_string()))
    }
}

impl<'a> InnerDate<'a> {
    /// # Safety
    /// Const function that creates a new `Date` from a static str.
    pub const unsafe fn from_static(val: &'static str) -> Self {
        Self(Cow::Borrowed(val))
    }
}

//===================================================================================================

/// 计算方式,参考 [aliyun 文档](https://help.aliyun.com/document_detail/31951.htm)
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct InnerCanonicalizedResource<'a>(Cow<'a, str>);
/// 静态作用域的 InnerCanonicalizedResource
pub type CanonicalizedResource = InnerCanonicalizedResource<'static>;

impl AsRef<str> for InnerCanonicalizedResource<'_> {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl Display for InnerCanonicalizedResource<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl TryInto<HeaderValue> for InnerCanonicalizedResource<'_> {
    type Error = InvalidHeaderValue;
    fn try_into(self) -> Result<HeaderValue, InvalidHeaderValue> {
        HeaderValue::from_str(self.as_ref())
    }
}
impl From<String> for CanonicalizedResource {
    fn from(s: String) -> Self {
        Self(Cow::Owned(s))
    }
}

impl<'a: 'b, 'b> From<&'a str> for InnerCanonicalizedResource<'b> {
    fn from(value: &'a str) -> Self {
        Self(Cow::Borrowed(value))
    }
}

impl Default for InnerCanonicalizedResource<'_> {
    fn default() -> Self {
        InnerCanonicalizedResource(Cow::Owned("/".to_owned()))
    }
}

#[cfg(any(feature = "core", feature = "auth"))]
pub(crate) const CONTINUATION_TOKEN: &str = "continuation-token";
#[cfg(any(feature = "core", feature = "auth"))]
pub(crate) const BUCKET_INFO: &str = "bucketInfo";
#[cfg(any(feature = "core", feature = "auth"))]
const QUERY_KEYWORD: [&str; 2] = ["acl", BUCKET_INFO];

impl<'a> InnerCanonicalizedResource<'a> {
    /// Creates a new `CanonicalizedResource` from the given string.
    pub fn new(val: impl Into<Cow<'a, str>>) -> Self {
        Self(val.into())
    }

    /// 只有 endpoint ,而没有 bucket 的时候
    #[inline(always)]
    pub fn from_endpoint() -> Self {
        Self::default()
    }

    /// Const function that creates a new `CanonicalizedResource` from a static str.
    pub const fn from_static(val: &'static str) -> Self {
        Self(Cow::Borrowed(val))
    }

    /// 获取 bucket 的签名参数
    #[cfg(feature = "core")]
    pub fn from_bucket<B: AsRef<BucketName>>(bucket: B, query: Option<&str>) -> Self {
        match query {
            Some(q) => {
                if QUERY_KEYWORD.iter().any(|&str| str == q) {
                    return Self::new(format!("/{}/?{}", bucket.as_ref().as_ref(), q));
                }

                Self::new(format!("/{}/", bucket.as_ref().as_ref()))
            }
            None => Self::default(),
        }
    }

    /// 获取 bucket 的签名参数
    #[cfg(feature = "auth")]
    pub fn from_bucket_name(bucket: &BucketName, query: Option<&str>) -> Self {
        match query {
            Some(q) => {
                if QUERY_KEYWORD.iter().any(|&str| str == q) {
                    return Self::new(format!("/{}/?{}", bucket.as_ref(), q));
                }

                Self::new(format!("/{}/", bucket.as_ref()))
            }
            None => Self::default(),
        }
    }

    /// 获取 bucket 的签名参数
    /// 带查询条件的
    ///
    /// 如果查询条件中有翻页的话,则忽略掉其他字段
    #[cfg(feature = "core")]
    #[inline]
    pub fn from_bucket_query<B: AsRef<BucketName>>(bucket: B, query: &Query) -> Self {
        Self::from_bucket_query2(bucket.as_ref(), query)
    }

    #[cfg(feature = "core")]
    #[doc(hidden)]
    pub fn from_bucket_query2(bucket: &BucketName, query: &Query) -> Self {
        match query.get(QueryKey::CONTINUATION_TOKEN) {
            Some(v) => Self::new(format!(
                "/{}/?continuation-token={}",
                bucket.as_ref(),
                v.as_ref()
            )),
            None => Self::new(format!("/{}/", bucket.as_ref())),
        }
    }

    /// 根据 OSS 存储对象(Object)查询签名参数
    #[cfg(feature = "core")]
    pub(crate) fn from_object<
        Q: IntoIterator<Item = (QueryKey, QueryValue)>,
        B: AsRef<str>,
        P: AsRef<str>,
    >(
        (bucket, path): (B, P),
        query: Q,
    ) -> Self {
        let query = Query::from_iter(query);
        if query.is_empty() {
            Self::new(format!("/{}/{}", bucket.as_ref(), path.as_ref()))
        } else {
            Self::new(format!(
                "/{}/{}?{}",
                bucket.as_ref(),
                path.as_ref(),
                query.to_url_query()
            ))
        }
    }

    pub(crate) fn from_object_str(bucket: &str, path: &str) -> Self {
        Self::new(format!("/{}/{}", bucket, path))
    }

    #[cfg(feature = "auth")]
    pub(crate) fn from_object_without_query<B: AsRef<str>, P: AsRef<str>>(
        bucket: B,
        path: P,
    ) -> Self {
        Self::new(format!("/{}/{}", bucket.as_ref(), path.as_ref()))
    }
}

impl PartialEq<&str> for InnerCanonicalizedResource<'_> {
    /// # 相等比较
    /// ```
    /// # use aliyun_oss_client::types::CanonicalizedResource;
    /// let res = CanonicalizedResource::new("abc");
    /// assert!(res == "abc");
    /// ```
    #[inline]
    fn eq(&self, other: &&str) -> bool {
        &self.0 == other
    }
}

impl PartialEq<InnerCanonicalizedResource<'_>> for &str {
    /// # 相等比较
    /// ```
    /// # use aliyun_oss_client::types::CanonicalizedResource;
    /// let res = CanonicalizedResource::new("abc");
    /// assert!("abc" == res);
    /// ```
    #[inline]
    fn eq(&self, other: &InnerCanonicalizedResource<'_>) -> bool {
        self == &other.0
    }
}

/// 根据 endpoint, bucket, path 获取接口信息
pub fn get_url_resource(
    endpoint: &EndPoint,
    bucket: &BucketName,
    path: &ObjectPathInner,
) -> (Url, CanonicalizedResource) {
    let mut url = url_from_bucket(endpoint, bucket);
    url.set_object_path(path);

    let resource = CanonicalizedResource::from_object_str(bucket.as_ref(), path.as_ref());

    (url, resource)
}

/// 根据 endpoint, bucket, path 获取接口信息
pub fn get_url_resource2<E: AsRef<EndPoint>, B: AsRef<BucketName>>(
    endpoint: E,
    bucket: B,
    path: &ObjectPathInner,
) -> (Url, CanonicalizedResource) {
    get_url_resource(endpoint.as_ref(), bucket.as_ref(), path)
}

pub(crate) fn url_from_bucket(endpoint: &EndPoint, bucket: &BucketName) -> Url {
    let url = format!(
        "https://{}.oss-{}.aliyuncs.com",
        bucket.as_ref(),
        endpoint.as_ref()
    );
    url.parse().unwrap_or_else(|_| {
        unreachable!("covert to url failed, bucket: {bucket}, endpoint: {endpoint}")
    })
}