-
Notifications
You must be signed in to change notification settings - Fork 513
/
Copy pathcore.rs
1306 lines (1127 loc) · 42.6 KB
/
core.rs
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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
use std::fmt;
use std::fmt::Debug;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Write;
use std::sync::atomic;
use std::sync::atomic::AtomicBool;
use std::time::Duration;
use base64::prelude::BASE64_STANDARD;
use base64::Engine;
use bytes::Bytes;
use http::header::HeaderName;
use http::header::CACHE_CONTROL;
use http::header::CONTENT_DISPOSITION;
use http::header::CONTENT_LENGTH;
use http::header::CONTENT_TYPE;
use http::header::HOST;
use http::header::IF_MATCH;
use http::header::IF_NONE_MATCH;
use http::HeaderValue;
use http::Request;
use http::Response;
use reqsign::AwsCredential;
use reqsign::AwsCredentialLoad;
use reqsign::AwsV4Signer;
use serde::Deserialize;
use serde::Serialize;
use crate::raw::*;
use crate::*;
pub mod constants {
pub const X_AMZ_COPY_SOURCE: &str = "x-amz-copy-source";
pub const X_AMZ_SERVER_SIDE_ENCRYPTION: &str = "x-amz-server-side-encryption";
pub const X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM: &str =
"x-amz-server-side-encryption-customer-algorithm";
pub const X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY: &str =
"x-amz-server-side-encryption-customer-key";
pub const X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5: &str =
"x-amz-server-side-encryption-customer-key-md5";
pub const X_AMZ_SERVER_SIDE_ENCRYPTION_AWS_KMS_KEY_ID: &str =
"x-amz-server-side-encryption-aws-kms-key-id";
pub const X_AMZ_STORAGE_CLASS: &str = "x-amz-storage-class";
pub const X_AMZ_COPY_SOURCE_SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM: &str =
"x-amz-copy-source-server-side-encryption-customer-algorithm";
pub const X_AMZ_COPY_SOURCE_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY: &str =
"x-amz-copy-source-server-side-encryption-customer-key";
pub const X_AMZ_COPY_SOURCE_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5: &str =
"x-amz-copy-source-server-side-encryption-customer-key-md5";
pub const X_AMZ_META_PREFIX: &str = "x-amz-meta-";
pub const RESPONSE_CONTENT_DISPOSITION: &str = "response-content-disposition";
pub const RESPONSE_CONTENT_TYPE: &str = "response-content-type";
pub const RESPONSE_CACHE_CONTROL: &str = "response-cache-control";
pub const S3_QUERY_VERSION_ID: &str = "versionId";
}
pub struct S3Core {
pub bucket: String,
pub endpoint: String,
pub root: String,
pub server_side_encryption: Option<HeaderValue>,
pub server_side_encryption_aws_kms_key_id: Option<HeaderValue>,
pub server_side_encryption_customer_algorithm: Option<HeaderValue>,
pub server_side_encryption_customer_key: Option<HeaderValue>,
pub server_side_encryption_customer_key_md5: Option<HeaderValue>,
pub default_storage_class: Option<HeaderValue>,
pub allow_anonymous: bool,
pub disable_stat_with_override: bool,
pub enable_versioning: bool,
pub signer: AwsV4Signer,
pub loader: Box<dyn AwsCredentialLoad>,
pub credential_loaded: AtomicBool,
pub client: HttpClient,
pub batch_max_operations: usize,
pub checksum_algorithm: Option<ChecksumAlgorithm>,
}
impl Debug for S3Core {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("S3Core")
.field("bucket", &self.bucket)
.field("endpoint", &self.endpoint)
.field("root", &self.root)
.finish_non_exhaustive()
}
}
impl S3Core {
/// If credential is not found, we will not sign the request.
async fn load_credential(&self) -> Result<Option<AwsCredential>> {
let cred = self
.loader
.load_credential(self.client.client())
.await
.map_err(new_request_credential_error)?;
if let Some(cred) = cred {
// Update credential_loaded to true if we have load credential successfully.
self.credential_loaded
.store(true, atomic::Ordering::Relaxed);
return Ok(Some(cred));
}
// If we have load credential before but failed to load this time, we should
// return error instead.
if self.credential_loaded.load(atomic::Ordering::Relaxed) {
return Err(Error::new(
ErrorKind::PermissionDenied,
"credential was previously loaded successfully but has failed this time",
)
.set_temporary());
}
// Credential is empty and users allow anonymous access, we will not sign the request.
if self.allow_anonymous {
return Ok(None);
}
Err(Error::new(
ErrorKind::PermissionDenied,
"no valid credential found and anonymous access is not allowed",
))
}
pub async fn sign<T>(&self, req: &mut Request<T>) -> Result<()> {
let cred = if let Some(cred) = self.load_credential().await? {
cred
} else {
return Ok(());
};
self.signer
.sign(req, &cred)
.map_err(new_request_sign_error)?;
// Always remove host header, let users' client to set it based on HTTP
// version.
//
// As discussed in <https://github.com/seanmonstar/reqwest/issues/1809>,
// google server could send RST_STREAM of PROTOCOL_ERROR if our request
// contains host header.
req.headers_mut().remove(HOST);
Ok(())
}
pub async fn sign_query<T>(&self, req: &mut Request<T>, duration: Duration) -> Result<()> {
let cred = if let Some(cred) = self.load_credential().await? {
cred
} else {
return Ok(());
};
self.signer
.sign_query(req, duration, &cred)
.map_err(new_request_sign_error)?;
// Always remove host header, let users' client to set it based on HTTP
// version.
//
// As discussed in <https://github.com/seanmonstar/reqwest/issues/1809>,
// google server could send RST_STREAM of PROTOCOL_ERROR if our request
// contains host header.
req.headers_mut().remove(HOST);
Ok(())
}
#[inline]
pub async fn send(&self, req: Request<Buffer>) -> Result<Response<Buffer>> {
self.client.send(req).await
}
/// # Note
///
/// header like X_AMZ_SERVER_SIDE_ENCRYPTION doesn't need to set while
/// get or stat.
pub fn insert_sse_headers(
&self,
mut req: http::request::Builder,
is_write: bool,
) -> http::request::Builder {
if is_write {
if let Some(v) = &self.server_side_encryption {
let mut v = v.clone();
v.set_sensitive(true);
req = req.header(
HeaderName::from_static(constants::X_AMZ_SERVER_SIDE_ENCRYPTION),
v,
)
}
if let Some(v) = &self.server_side_encryption_aws_kms_key_id {
let mut v = v.clone();
v.set_sensitive(true);
req = req.header(
HeaderName::from_static(constants::X_AMZ_SERVER_SIDE_ENCRYPTION_AWS_KMS_KEY_ID),
v,
)
}
}
if let Some(v) = &self.server_side_encryption_customer_algorithm {
let mut v = v.clone();
v.set_sensitive(true);
req = req.header(
HeaderName::from_static(constants::X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM),
v,
)
}
if let Some(v) = &self.server_side_encryption_customer_key {
let mut v = v.clone();
v.set_sensitive(true);
req = req.header(
HeaderName::from_static(constants::X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY),
v,
)
}
if let Some(v) = &self.server_side_encryption_customer_key_md5 {
let mut v = v.clone();
v.set_sensitive(true);
req = req.header(
HeaderName::from_static(constants::X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5),
v,
)
}
req
}
pub fn calculate_checksum(&self, body: &Buffer) -> Option<String> {
match self.checksum_algorithm {
None => None,
Some(ChecksumAlgorithm::Crc32c) => {
let mut crc = 0u32;
body.clone()
.for_each(|b| crc = crc32c::crc32c_append(crc, &b));
Some(BASE64_STANDARD.encode(crc.to_be_bytes()))
}
}
}
pub fn insert_checksum_header(
&self,
mut req: http::request::Builder,
checksum: &str,
) -> http::request::Builder {
if let Some(checksum_algorithm) = self.checksum_algorithm.as_ref() {
req = req.header(checksum_algorithm.to_header_name(), checksum);
}
req
}
pub fn insert_checksum_type_header(
&self,
mut req: http::request::Builder,
) -> http::request::Builder {
if let Some(checksum_algorithm) = self.checksum_algorithm.as_ref() {
req = req.header("x-amz-checksum-algorithm", checksum_algorithm.to_string());
}
req
}
}
impl S3Core {
pub fn s3_head_object_request(&self, path: &str, args: OpStat) -> Result<Request<Buffer>> {
let p = build_abs_path(&self.root, path);
let mut url = format!("{}/{}", self.endpoint, percent_encode_path(&p));
// Add query arguments to the URL based on response overrides
let mut query_args = Vec::new();
if let Some(override_content_disposition) = args.override_content_disposition() {
query_args.push(format!(
"{}={}",
constants::RESPONSE_CONTENT_DISPOSITION,
percent_encode_path(override_content_disposition)
))
}
if let Some(override_content_type) = args.override_content_type() {
query_args.push(format!(
"{}={}",
constants::RESPONSE_CONTENT_TYPE,
percent_encode_path(override_content_type)
))
}
if let Some(override_cache_control) = args.override_cache_control() {
query_args.push(format!(
"{}={}",
constants::RESPONSE_CACHE_CONTROL,
percent_encode_path(override_cache_control)
))
}
if let Some(version) = args.version() {
query_args.push(format!(
"{}={}",
constants::S3_QUERY_VERSION_ID,
percent_decode_path(version)
))
}
if !query_args.is_empty() {
url.push_str(&format!("?{}", query_args.join("&")));
}
let mut req = Request::head(&url);
req = self.insert_sse_headers(req, false);
if let Some(if_none_match) = args.if_none_match() {
req = req.header(IF_NONE_MATCH, if_none_match);
}
if let Some(if_match) = args.if_match() {
req = req.header(IF_MATCH, if_match);
}
let req = req.body(Buffer::new()).map_err(new_request_build_error)?;
Ok(req)
}
pub fn s3_get_object_request(
&self,
path: &str,
range: BytesRange,
args: &OpRead,
) -> Result<Request<Buffer>> {
let p = build_abs_path(&self.root, path);
// Construct headers to add to the request
let mut url = format!("{}/{}", self.endpoint, percent_encode_path(&p));
// Add query arguments to the URL based on response overrides
let mut query_args = Vec::new();
if let Some(override_content_disposition) = args.override_content_disposition() {
query_args.push(format!(
"{}={}",
constants::RESPONSE_CONTENT_DISPOSITION,
percent_encode_path(override_content_disposition)
))
}
if let Some(override_content_type) = args.override_content_type() {
query_args.push(format!(
"{}={}",
constants::RESPONSE_CONTENT_TYPE,
percent_encode_path(override_content_type)
))
}
if let Some(override_cache_control) = args.override_cache_control() {
query_args.push(format!(
"{}={}",
constants::RESPONSE_CACHE_CONTROL,
percent_encode_path(override_cache_control)
))
}
if let Some(version) = args.version() {
query_args.push(format!(
"{}={}",
constants::S3_QUERY_VERSION_ID,
percent_decode_path(version)
))
}
if !query_args.is_empty() {
url.push_str(&format!("?{}", query_args.join("&")));
}
let mut req = Request::get(&url);
if !range.is_full() {
req = req.header(http::header::RANGE, range.to_header());
}
if let Some(if_none_match) = args.if_none_match() {
req = req.header(IF_NONE_MATCH, if_none_match);
}
if let Some(if_match) = args.if_match() {
req = req.header(IF_MATCH, if_match);
}
// Set SSE headers.
// TODO: how will this work with presign?
req = self.insert_sse_headers(req, false);
let req = req.body(Buffer::new()).map_err(new_request_build_error)?;
Ok(req)
}
pub async fn s3_get_object(
&self,
path: &str,
range: BytesRange,
args: &OpRead,
) -> Result<Response<HttpBody>> {
let mut req = self.s3_get_object_request(path, range, args)?;
self.sign(&mut req).await?;
self.client.fetch(req).await
}
pub fn s3_put_object_request(
&self,
path: &str,
size: Option<u64>,
args: &OpWrite,
body: Buffer,
) -> Result<Request<Buffer>> {
let p = build_abs_path(&self.root, path);
let url = format!("{}/{}", self.endpoint, percent_encode_path(&p));
let mut req = Request::put(&url);
if let Some(size) = size {
req = req.header(CONTENT_LENGTH, size.to_string())
}
if let Some(mime) = args.content_type() {
req = req.header(CONTENT_TYPE, mime)
}
if let Some(pos) = args.content_disposition() {
req = req.header(CONTENT_DISPOSITION, pos)
}
if let Some(cache_control) = args.cache_control() {
req = req.header(CACHE_CONTROL, cache_control)
}
// Set storage class header
if let Some(v) = &self.default_storage_class {
req = req.header(HeaderName::from_static(constants::X_AMZ_STORAGE_CLASS), v);
}
// Set user metadata headers.
if let Some(user_metadata) = args.user_metadata() {
for (key, value) in user_metadata {
req = req.header(format!("{}{}", constants::X_AMZ_META_PREFIX, key), value)
}
}
// Set SSE headers.
req = self.insert_sse_headers(req, true);
// Calculate Checksum.
if let Some(checksum) = self.calculate_checksum(&body) {
// Set Checksum header.
req = self.insert_checksum_header(req, &checksum);
}
if let Some(if_none_match) = args.if_none_match() {
req = req.header(IF_NONE_MATCH, if_none_match);
}
// Set body
let req = req.body(body).map_err(new_request_build_error)?;
Ok(req)
}
pub async fn s3_head_object(&self, path: &str, args: OpStat) -> Result<Response<Buffer>> {
let mut req = self.s3_head_object_request(path, args)?;
self.sign(&mut req).await?;
self.send(req).await
}
pub async fn s3_delete_object(&self, path: &str, args: &OpDelete) -> Result<Response<Buffer>> {
let p = build_abs_path(&self.root, path);
let mut url = format!("{}/{}", self.endpoint, percent_encode_path(&p));
let mut query_args = Vec::new();
if let Some(version) = args.version() {
query_args.push(format!(
"{}={}",
constants::S3_QUERY_VERSION_ID,
percent_encode_path(version)
))
}
if !query_args.is_empty() {
url.push_str(&format!("?{}", query_args.join("&")));
}
let mut req = Request::delete(&url)
.body(Buffer::new())
.map_err(new_request_build_error)?;
self.sign(&mut req).await?;
self.send(req).await
}
pub async fn s3_copy_object(&self, from: &str, to: &str) -> Result<Response<Buffer>> {
let from = build_abs_path(&self.root, from);
let to = build_abs_path(&self.root, to);
let source = format!("{}/{}", self.bucket, percent_encode_path(&from));
let target = format!("{}/{}", self.endpoint, percent_encode_path(&to));
let mut req = Request::put(&target);
// Set SSE headers.
req = self.insert_sse_headers(req, true);
if let Some(v) = &self.server_side_encryption_customer_algorithm {
let mut v = v.clone();
v.set_sensitive(true);
req = req.header(
HeaderName::from_static(
constants::X_AMZ_COPY_SOURCE_SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM,
),
v,
)
}
if let Some(v) = &self.server_side_encryption_customer_key {
let mut v = v.clone();
v.set_sensitive(true);
req = req.header(
HeaderName::from_static(
constants::X_AMZ_COPY_SOURCE_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY,
),
v,
)
}
if let Some(v) = &self.server_side_encryption_customer_key_md5 {
let mut v = v.clone();
v.set_sensitive(true);
req = req.header(
HeaderName::from_static(
constants::X_AMZ_COPY_SOURCE_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5,
),
v,
)
}
let mut req = req
.header(constants::X_AMZ_COPY_SOURCE, &source)
.body(Buffer::new())
.map_err(new_request_build_error)?;
self.sign(&mut req).await?;
self.send(req).await
}
pub async fn s3_list_objects(
&self,
path: &str,
continuation_token: &str,
delimiter: &str,
limit: Option<usize>,
start_after: Option<String>,
) -> Result<Response<Buffer>> {
let p = build_abs_path(&self.root, path);
let mut url = format!("{}?list-type=2", self.endpoint);
if !p.is_empty() {
write!(url, "&prefix={}", percent_encode_path(&p))
.expect("write into string must succeed");
}
if !delimiter.is_empty() {
write!(url, "&delimiter={delimiter}").expect("write into string must succeed");
}
if let Some(limit) = limit {
write!(url, "&max-keys={limit}").expect("write into string must succeed");
}
if let Some(start_after) = start_after {
let start_after = build_abs_path(&self.root, &start_after);
write!(url, "&start-after={}", percent_encode_path(&start_after))
.expect("write into string must succeed");
}
if !continuation_token.is_empty() {
// AWS S3 could return continuation-token that contains `=`
// which could lead `reqsign` parse query wrongly.
// URL encode continuation-token before starting signing so that
// our signer will not be confused.
write!(
url,
"&continuation-token={}",
percent_encode_path(continuation_token)
)
.expect("write into string must succeed");
}
let mut req = Request::get(&url)
.body(Buffer::new())
.map_err(new_request_build_error)?;
self.sign(&mut req).await?;
self.send(req).await
}
pub async fn s3_initiate_multipart_upload(
&self,
path: &str,
args: &OpWrite,
) -> Result<Response<Buffer>> {
let p = build_abs_path(&self.root, path);
let url = format!("{}/{}?uploads", self.endpoint, percent_encode_path(&p));
let mut req = Request::post(&url);
if let Some(mime) = args.content_type() {
req = req.header(CONTENT_TYPE, mime)
}
if let Some(content_disposition) = args.content_disposition() {
req = req.header(CONTENT_DISPOSITION, content_disposition)
}
if let Some(cache_control) = args.cache_control() {
req = req.header(CACHE_CONTROL, cache_control)
}
// Set storage class header
if let Some(v) = &self.default_storage_class {
req = req.header(HeaderName::from_static(constants::X_AMZ_STORAGE_CLASS), v);
}
// Set SSE headers.
let req = self.insert_sse_headers(req, true);
// Set SSE headers.
let req = self.insert_checksum_type_header(req);
let mut req = req.body(Buffer::new()).map_err(new_request_build_error)?;
self.sign(&mut req).await?;
self.send(req).await
}
pub fn s3_upload_part_request(
&self,
path: &str,
upload_id: &str,
part_number: usize,
size: u64,
body: Buffer,
checksum: Option<String>,
) -> Result<Request<Buffer>> {
let p = build_abs_path(&self.root, path);
let url = format!(
"{}/{}?partNumber={}&uploadId={}",
self.endpoint,
percent_encode_path(&p),
part_number,
percent_encode_path(upload_id)
);
let mut req = Request::put(&url);
req = req.header(CONTENT_LENGTH, size);
// Set SSE headers.
req = self.insert_sse_headers(req, true);
if let Some(checksum) = checksum {
// Set Checksum header.
req = self.insert_checksum_header(req, &checksum);
}
// Set body
let req = req.body(body).map_err(new_request_build_error)?;
Ok(req)
}
pub async fn s3_complete_multipart_upload(
&self,
path: &str,
upload_id: &str,
parts: Vec<CompleteMultipartUploadRequestPart>,
) -> Result<Response<Buffer>> {
let p = build_abs_path(&self.root, path);
let url = format!(
"{}/{}?uploadId={}",
self.endpoint,
percent_encode_path(&p),
percent_encode_path(upload_id)
);
let req = Request::post(&url);
// Set SSE headers.
let req = self.insert_sse_headers(req, true);
let content = quick_xml::se::to_string(&CompleteMultipartUploadRequest { part: parts })
.map_err(new_xml_deserialize_error)?;
// Make sure content length has been set to avoid post with chunked encoding.
let req = req.header(CONTENT_LENGTH, content.len());
// Set content-type to `application/xml` to avoid mixed with form post.
let req = req.header(CONTENT_TYPE, "application/xml");
let mut req = req
.body(Buffer::from(Bytes::from(content)))
.map_err(new_request_build_error)?;
self.sign(&mut req).await?;
self.send(req).await
}
/// Abort an on-going multipart upload.
pub async fn s3_abort_multipart_upload(
&self,
path: &str,
upload_id: &str,
) -> Result<Response<Buffer>> {
let p = build_abs_path(&self.root, path);
let url = format!(
"{}/{}?uploadId={}",
self.endpoint,
percent_encode_path(&p),
percent_encode_path(upload_id)
);
let mut req = Request::delete(&url)
.body(Buffer::new())
.map_err(new_request_build_error)?;
self.sign(&mut req).await?;
self.send(req).await
}
pub async fn s3_delete_objects(&self, paths: Vec<String>) -> Result<Response<Buffer>> {
let url = format!("{}/?delete", self.endpoint);
let req = Request::post(&url);
let content = quick_xml::se::to_string(&DeleteObjectsRequest {
object: paths
.into_iter()
.map(|path| DeleteObjectsRequestObject {
key: build_abs_path(&self.root, &path),
})
.collect(),
})
.map_err(new_xml_deserialize_error)?;
// Make sure content length has been set to avoid post with chunked encoding.
let req = req.header(CONTENT_LENGTH, content.len());
// Set content-type to `application/xml` to avoid mixed with form post.
let req = req.header(CONTENT_TYPE, "application/xml");
// Set content-md5 as required by API.
let req = req.header("CONTENT-MD5", format_content_md5(content.as_bytes()));
let mut req = req
.body(Buffer::from(Bytes::from(content)))
.map_err(new_request_build_error)?;
self.sign(&mut req).await?;
self.send(req).await
}
pub async fn s3_list_object_versions(
&self,
prefix: &str,
delimiter: &str,
limit: Option<usize>,
key_marker: &str,
version_id_marker: &str,
) -> Result<Response<Buffer>> {
let p = build_abs_path(&self.root, prefix);
let mut url = format!("{}?versions", self.endpoint);
if !p.is_empty() {
write!(url, "&prefix={}", percent_encode_path(p.as_str()))
.expect("write into string must succeed");
}
if !delimiter.is_empty() {
write!(url, "&delimiter={}", delimiter).expect("write into string must succeed");
}
if let Some(limit) = limit {
write!(url, "&max-keys={}", limit).expect("write into string must succeed");
}
if !key_marker.is_empty() {
write!(url, "&key-marker={}", percent_encode_path(key_marker))
.expect("write into string must succeed");
}
if !version_id_marker.is_empty() {
write!(
url,
"&version-id-marker={}",
percent_encode_path(version_id_marker)
)
.expect("write into string must succeed");
}
let mut req = Request::get(&url)
.body(Buffer::new())
.map_err(new_request_build_error)?;
self.sign(&mut req).await?;
self.send(req).await
}
}
/// Result of CreateMultipartUpload
#[derive(Default, Debug, Deserialize)]
#[serde(default, rename_all = "PascalCase")]
pub struct InitiateMultipartUploadResult {
pub upload_id: String,
}
/// Request of CompleteMultipartUploadRequest
#[derive(Default, Debug, Serialize)]
#[serde(default, rename = "CompleteMultipartUpload", rename_all = "PascalCase")]
pub struct CompleteMultipartUploadRequest {
pub part: Vec<CompleteMultipartUploadRequestPart>,
}
#[derive(Clone, Default, Debug, Serialize)]
#[serde(default, rename_all = "PascalCase")]
pub struct CompleteMultipartUploadRequestPart {
#[serde(rename = "PartNumber")]
pub part_number: usize,
/// # TODO
///
/// quick-xml will do escape on `"` which leads to our serialized output is
/// not the same as aws s3's example.
///
/// Ideally, we could use `serialize_with` to address this (buf failed)
///
/// ```ignore
/// #[derive(Default, Debug, Serialize)]
/// #[serde(default, rename_all = "PascalCase")]
/// struct CompleteMultipartUploadRequestPart {
/// #[serde(rename = "PartNumber")]
/// part_number: usize,
/// #[serde(rename = "ETag", serialize_with = "partial_escape")]
/// etag: String,
/// }
///
/// fn partial_escape<S>(s: &str, ser: S) -> Result<S::Ok, S::Error>
/// where
/// S: serde::Serializer,
/// {
/// ser.serialize_str(&String::from_utf8_lossy(
/// &quick_xml::escape::partial_escape(s.as_bytes()),
/// ))
/// }
/// ```
///
/// ref: <https://github.com/tafia/quick-xml/issues/362>
#[serde(rename = "ETag")]
pub etag: String,
#[serde(rename = "ChecksumCRC32C", skip_serializing_if = "Option::is_none")]
pub checksum_crc32c: Option<String>,
}
/// Request of DeleteObjects.
#[derive(Default, Debug, Serialize)]
#[serde(default, rename = "Delete", rename_all = "PascalCase")]
pub struct DeleteObjectsRequest {
pub object: Vec<DeleteObjectsRequestObject>,
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct DeleteObjectsRequestObject {
pub key: String,
}
/// Result of DeleteObjects.
#[derive(Default, Debug, Deserialize)]
#[serde(default, rename = "DeleteResult", rename_all = "PascalCase")]
pub struct DeleteObjectsResult {
pub deleted: Vec<DeleteObjectsResultDeleted>,
pub error: Vec<DeleteObjectsResultError>,
}
#[derive(Default, Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct DeleteObjectsResultDeleted {
pub key: String,
}
#[derive(Default, Debug, Deserialize)]
#[serde(default, rename_all = "PascalCase")]
pub struct DeleteObjectsResultError {
pub code: String,
pub key: String,
pub message: String,
}
/// Output of ListBucket/ListObjects.
///
/// ## Note
///
/// Use `Option` in `is_truncated` and `next_continuation_token` to make
/// the behavior more clear so that we can be compatible to more s3 services.
///
/// And enable `serde(default)` so that we can keep going even when some field
/// is not exist.
#[derive(Default, Debug, Deserialize)]
#[serde(default, rename_all = "PascalCase")]
pub struct ListObjectsOutput {
pub is_truncated: Option<bool>,
pub next_continuation_token: Option<String>,
pub common_prefixes: Vec<OutputCommonPrefix>,
pub contents: Vec<ListObjectsOutputContent>,
}
#[derive(Default, Debug, Eq, PartialEq, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct ListObjectsOutputContent {
pub key: String,
pub size: u64,
pub last_modified: String,
#[serde(rename = "ETag")]
pub etag: Option<String>,
}
#[derive(Default, Debug, Eq, PartialEq, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct OutputCommonPrefix {
pub prefix: String,
}
/// Output of ListObjectVersions
#[derive(Default, Debug, Deserialize)]
#[serde(default, rename_all = "PascalCase")]
pub struct ListObjectVersionsOutput {
pub is_truncated: Option<bool>,
pub next_key_marker: Option<String>,
pub next_version_id_marker: Option<String>,
pub common_prefixes: Vec<OutputCommonPrefix>,
pub version: Vec<ListObjectVersionsOutputVersion>,
}
#[derive(Default, Debug, Eq, PartialEq, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct ListObjectVersionsOutputVersion {
pub key: String,
pub version_id: String,
pub is_latest: bool,
pub size: u64,
pub last_modified: String,
#[serde(rename = "ETag")]
pub etag: Option<String>,
}
pub enum ChecksumAlgorithm {
Crc32c,
}
impl ChecksumAlgorithm {
pub fn to_header_name(&self) -> HeaderName {
match self {
Self::Crc32c => HeaderName::from_static("x-amz-checksum-crc32c"),
}
}
}
impl Display for ChecksumAlgorithm {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(
f,