-
Notifications
You must be signed in to change notification settings - Fork 164
/
s3_crt_client.rs
1692 lines (1492 loc) · 72 KB
/
s3_crt_client.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
use std::cmp;
use std::ffi::{OsStr, OsString};
use std::future::Future;
use std::num::NonZeroUsize;
use std::ops::Deref;
use std::ops::Range;
use std::os::unix::prelude::OsStrExt;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
use mountpoint_s3_crt::auth::credentials::{
CredentialsProvider, CredentialsProviderChainDefaultOptions, CredentialsProviderProfileOptions,
};
use mountpoint_s3_crt::auth::signing_config::SigningConfig;
use mountpoint_s3_crt::common::allocator::Allocator;
use mountpoint_s3_crt::common::string::AwsString;
use mountpoint_s3_crt::common::uri::Uri;
use mountpoint_s3_crt::http::request_response::{Header, Headers, HeadersError, Message};
use mountpoint_s3_crt::io::channel_bootstrap::{ClientBootstrap, ClientBootstrapOptions};
use mountpoint_s3_crt::io::event_loop::EventLoopGroup;
use mountpoint_s3_crt::io::host_resolver::{AddressKinds, HostResolver, HostResolverDefaultOptions};
use mountpoint_s3_crt::io::retry_strategy::{ExponentialBackoffJitterMode, RetryStrategy, StandardRetryOptions};
use mountpoint_s3_crt::io::stream::InputStream;
use mountpoint_s3_crt::s3::client::{
init_signing_config, BufferPoolUsageStats, ChecksumConfig, Client, ClientConfig, MetaRequest, MetaRequestOptions,
MetaRequestResult, MetaRequestType, RequestMetrics, RequestType,
};
use async_trait::async_trait;
use futures::channel::oneshot;
use percent_encoding::{percent_encode, AsciiSet, NON_ALPHANUMERIC};
use pin_project::{pin_project, pinned_drop};
use thiserror::Error;
use tracing::{debug, error, trace, Span};
use crate::checksums::crc32c_to_base64;
use crate::endpoint_config::EndpointError;
use crate::endpoint_config::{self, EndpointConfig};
use crate::error_metadata::{ClientErrorMetadata, ProvideErrorMetadata};
use crate::object_client::*;
use crate::user_agent::UserAgent;
macro_rules! request_span {
($self:expr, $method:expr, $($field:tt)*) => {{
let counter = $self.next_request_counter();
// I have confused myself at least 4 times about how to choose the level for tracing spans.
// We want this span to be constructed whenever events at WARN or lower severity (INFO,
// DEBUG, TRACE) are emitted. So we set its severity to WARN too.
let span = tracing::warn_span!(target: "mountpoint_s3_client::s3_crt_client::request", $method, id = counter, $($field)*);
span.in_scope(|| tracing::debug!("new request"));
span
}};
($self:expr, $method:expr) => { request_span!($self, $method,) };
}
pub(crate) mod copy_object;
pub(crate) mod delete_object;
pub(crate) mod get_object;
pub(crate) use get_object::S3GetObjectRequest;
pub(crate) mod get_object_attributes;
pub(crate) mod head_object;
pub(crate) mod list_objects;
pub(crate) mod head_bucket;
pub(crate) mod put_object;
pub use head_bucket::HeadBucketError;
pub(crate) use put_object::S3PutObjectRequest;
/// `tracing` doesn't allow dynamic levels but we want to dynamically choose the log level for
/// requests based on their response status. https://github.com/tokio-rs/tracing/issues/372
macro_rules! event {
($level:expr, $($args:tt)*) => {
match $level {
::tracing::Level::ERROR => ::tracing::event!(::tracing::Level::ERROR, $($args)*),
::tracing::Level::WARN => ::tracing::event!(::tracing::Level::WARN, $($args)*),
::tracing::Level::INFO => ::tracing::event!(::tracing::Level::INFO, $($args)*),
::tracing::Level::DEBUG => ::tracing::event!(::tracing::Level::DEBUG, $($args)*),
::tracing::Level::TRACE => ::tracing::event!(::tracing::Level::TRACE, $($args)*),
}
}
}
/// Configurations for the CRT-based S3 client
#[derive(Debug, Clone)]
pub struct S3ClientConfig {
auth_config: S3ClientAuthConfig,
throughput_target_gbps: f64,
read_part_size: usize,
write_part_size: usize,
endpoint_config: EndpointConfig,
user_agent: Option<UserAgent>,
request_payer: Option<String>,
bucket_owner: Option<String>,
max_attempts: Option<NonZeroUsize>,
read_backpressure: bool,
initial_read_window: usize,
network_interface_names: Vec<String>,
}
impl Default for S3ClientConfig {
fn default() -> Self {
const DEFAULT_PART_SIZE: usize = 8 * 1024 * 1024;
Self {
auth_config: Default::default(),
throughput_target_gbps: 10.0,
read_part_size: DEFAULT_PART_SIZE,
write_part_size: DEFAULT_PART_SIZE,
endpoint_config: EndpointConfig::new("us-east-1"),
user_agent: None,
request_payer: None,
bucket_owner: None,
max_attempts: None,
read_backpressure: false,
initial_read_window: DEFAULT_PART_SIZE,
network_interface_names: vec![],
}
}
}
impl S3ClientConfig {
pub fn new() -> Self {
Self::default()
}
/// Set the configuration for authenticating to S3
#[must_use = "S3ClientConfig follows a builder pattern"]
pub fn auth_config(mut self, auth_config: S3ClientAuthConfig) -> Self {
self.auth_config = auth_config;
self
}
/// Set the part size for multi-part operations to S3 (both PUT and GET)
#[must_use = "S3ClientConfig follows a builder pattern"]
pub fn part_size(mut self, part_size: usize) -> Self {
self.read_part_size = part_size;
self.write_part_size = part_size;
self
}
/// Set the part size for multi-part-get operations to S3.
#[must_use = "S3ClientConfig follows a builder pattern"]
pub fn read_part_size(mut self, size: usize) -> Self {
self.read_part_size = size;
self
}
/// Set the part size for multi-part-put operations to S3.
#[must_use = "S3ClientConfig follows a builder pattern"]
pub fn write_part_size(mut self, size: usize) -> Self {
self.write_part_size = size;
self
}
/// Set the target throughput in Gbps for the S3 client
#[must_use = "S3ClientConfig follows a builder pattern"]
pub fn throughput_target_gbps(mut self, throughput_target_gbps: f64) -> Self {
self.throughput_target_gbps = throughput_target_gbps;
self
}
/// Set the endpoint configuration for endpoint resolution
#[must_use = "S3ClientConfig follows a builder pattern"]
pub fn endpoint_config(mut self, endpoint_config: EndpointConfig) -> Self {
self.endpoint_config = endpoint_config;
self
}
/// Set a constructor for the HTTP User-agent header for S3 requests
#[must_use = "S3ClientConfig follows a builder pattern"]
pub fn user_agent(mut self, user_agent: UserAgent) -> Self {
self.user_agent = Some(user_agent);
self
}
/// Set a value for the request payer HTTP header for S3 requests
#[must_use = "S3ClientConfig follows a builder pattern"]
pub fn request_payer(mut self, request_payer: &str) -> Self {
self.request_payer = Some(request_payer.to_owned());
self
}
/// Set an expected bucket owner value
#[must_use = "S3ClientConfig follows a builder pattern"]
pub fn bucket_owner(mut self, bucket_owner: &str) -> Self {
self.bucket_owner = Some(bucket_owner.to_owned());
self
}
/// Set a maximum number of attempts for S3 requests. Will be overridden by the
/// `AWS_MAX_ATTEMPTS` environment variable if set.
#[must_use = "S3ClientConfig follows a builder pattern"]
pub fn max_attempts(mut self, max_attempts: NonZeroUsize) -> Self {
self.max_attempts = Some(max_attempts);
self
}
/// Set the flag for backpressure read
#[must_use = "S3ClientConfig follows a builder pattern"]
pub fn read_backpressure(mut self, read_backpressure: bool) -> Self {
self.read_backpressure = read_backpressure;
self
}
/// Set a value for initial backpressure read window size
#[must_use = "S3ClientConfig follows a builder pattern"]
pub fn initial_read_window(mut self, initial_read_window: usize) -> Self {
self.initial_read_window = initial_read_window;
self
}
/// Set a list of network interfaces to distribute S3 requests over
#[must_use = "S3ClientConfig follows a builder pattern"]
pub fn network_interface_names(mut self, network_interface_names: Vec<String>) -> Self {
self.network_interface_names = network_interface_names;
self
}
}
/// Authentication configuration for the CRT-based S3 client
#[derive(Debug, Clone, Default)]
pub enum S3ClientAuthConfig {
/// The default AWS credentials resolution chain, similar to the AWS CLI
#[default]
Default,
/// Do not sign requests at all
NoSigning,
/// Explicitly load the given profile name from the AWS CLI configuration file
Profile(String),
/// Use a custom credentials provider
Provider(CredentialsProvider),
}
/// An S3 client that uses the [AWS Common Runtime (CRT)][crt] to make requests.
///
/// The AWS CRT is a C library that provides a common set of functionality for AWS SDKs. Its S3
/// client provides high throughput by implementing S3 performance best practices, including
/// automatic parallelization of GET and PUT requests.
///
/// To use this client, invoke the methods from the [`ObjectClient`] trait.
///
/// [crt]: https://docs.aws.amazon.com/sdkref/latest/guide/common-runtime.html
#[derive(Debug, Clone)]
pub struct S3CrtClient {
inner: Arc<S3CrtClientInner>,
}
impl S3CrtClient {
/// Construct a new S3 client with the given configuration.
pub fn new(config: S3ClientConfig) -> Result<Self, NewClientError> {
Ok(Self {
inner: Arc::new(S3CrtClientInner::new(config)?),
})
}
/// Return a copy of the [EndpointConfig] for this client
pub fn endpoint_config(&self) -> EndpointConfig {
self.inner.endpoint_config.clone()
}
#[doc(hidden)]
pub fn event_loop_group(&self) -> EventLoopGroup {
self.inner.event_loop_group.clone()
}
}
#[derive(Debug)]
struct S3CrtClientInner {
s3_client: Client,
event_loop_group: EventLoopGroup,
endpoint_config: EndpointConfig,
allocator: Allocator,
next_request_counter: AtomicU64,
/// user_agent_header will be passed into CRT which add additional information "CRTS3NativeClient/0.1.x".
/// Here it will add the user agent prefix and s3 client information.
user_agent_header: String,
request_payer: Option<String>,
read_part_size: usize,
write_part_size: usize,
enable_backpressure: bool,
initial_read_window_size: usize,
bucket_owner: Option<String>,
credentials_provider: Option<CredentialsProvider>,
host_resolver: HostResolver,
}
impl S3CrtClientInner {
fn new(config: S3ClientConfig) -> Result<Self, NewClientError> {
let allocator = Allocator::default();
let mut event_loop_group = EventLoopGroup::new_default(&allocator, None, || {}).unwrap();
let resolver_options = HostResolverDefaultOptions {
max_entries: 8,
event_loop_group: &mut event_loop_group,
};
let mut host_resolver = HostResolver::new_default(&allocator, &resolver_options).unwrap();
let bootstrap_options = ClientBootstrapOptions {
event_loop_group: &mut event_loop_group,
host_resolver: &mut host_resolver,
};
let mut client_bootstrap = ClientBootstrap::new(&allocator, &bootstrap_options).unwrap();
let mut client_config = ClientConfig::new();
let retry_strategy = {
let mut retry_strategy_options = StandardRetryOptions::default(&mut event_loop_group);
let max_attempts = std::env::var("AWS_MAX_ATTEMPTS")
.ok()
.and_then(|s| s.parse::<usize>().ok())
.or_else(|| config.max_attempts.map(|m| m.get()))
.unwrap_or(3);
// Max *attempts* includes the initial attempt, the CRT's max *retries* does not, so
// decrement by one
retry_strategy_options.backoff_retry_options.max_retries = max_attempts.saturating_sub(1);
retry_strategy_options.backoff_retry_options.backoff_scale_factor = Duration::from_millis(500);
retry_strategy_options.backoff_retry_options.jitter_mode = ExponentialBackoffJitterMode::Full;
RetryStrategy::standard(&allocator, &retry_strategy_options).unwrap()
};
trace!("constructing client with auth config {:?}", config.auth_config);
let credentials_provider = match config.auth_config {
S3ClientAuthConfig::Default => {
let credentials_chain_default_options = CredentialsProviderChainDefaultOptions {
bootstrap: &mut client_bootstrap,
};
CredentialsProvider::new_chain_default(&allocator, credentials_chain_default_options)
.map_err(NewClientError::ProviderFailure)?
}
S3ClientAuthConfig::NoSigning => {
CredentialsProvider::new_anonymous(&allocator).map_err(NewClientError::ProviderFailure)?
}
S3ClientAuthConfig::Profile(profile_name) => {
let credentials_profile_options = CredentialsProviderProfileOptions {
bootstrap: &mut client_bootstrap,
profile_name_override: &profile_name,
};
CredentialsProvider::new_profile(&allocator, credentials_profile_options)
.map_err(NewClientError::ProviderFailure)?
}
S3ClientAuthConfig::Provider(provider) => provider,
};
let endpoint_config = config.endpoint_config;
client_config.region(endpoint_config.get_region());
let signing_config = init_signing_config(
endpoint_config.get_region(),
credentials_provider.clone(),
None,
None,
None,
);
let endpoint_config = match endpoint_config.get_endpoint() {
None => {
// No explicit endpoint was configured, let's try the environment variable
if let Ok(aws_endpoint_url) = std::env::var("AWS_ENDPOINT_URL") {
debug!("using AWS_ENDPOINT_URL {}", aws_endpoint_url);
let env_uri = Uri::new_from_str(&allocator, &aws_endpoint_url)
.map_err(|e| EndpointError::InvalidUri(endpoint_config::InvalidUriError::CouldNotParse(e)))?;
endpoint_config.endpoint(env_uri)
} else {
endpoint_config
}
}
Some(_) => endpoint_config,
};
client_config.express_support(true);
client_config.read_backpressure(config.read_backpressure);
client_config.initial_read_window(config.initial_read_window);
client_config.signing_config(signing_config);
client_config
.client_bootstrap(client_bootstrap)
.retry_strategy(retry_strategy);
client_config.throughput_target_gbps(config.throughput_target_gbps);
// max_part_size is 5GB or less depending on the platform (4GB on 32-bit)
let max_part_size = cmp::min(5_u64 * 1024 * 1024 * 1024, usize::MAX as u64) as usize;
// TODO: Review the part size validation for read_part_size, read_part_size can have a more relax limit.
for part_size in [config.read_part_size, config.write_part_size] {
if !(5 * 1024 * 1024..=max_part_size).contains(&part_size) {
return Err(NewClientError::InvalidConfiguration(format!(
"part size must be at between 5MiB and {}GiB",
max_part_size / 1024 / 1024 / 1024
)));
}
}
if !config.network_interface_names.is_empty() {
client_config.network_interface_names(config.network_interface_names);
}
let user_agent = config.user_agent.unwrap_or_else(|| UserAgent::new(None));
let user_agent_header = user_agent.build();
let s3_client = Client::new(&allocator, client_config).map_err(NewClientError::CrtError)?;
Ok(Self {
allocator,
s3_client,
event_loop_group,
endpoint_config,
next_request_counter: AtomicU64::new(0),
user_agent_header,
request_payer: config.request_payer,
read_part_size: config.read_part_size,
write_part_size: config.write_part_size,
enable_backpressure: config.read_backpressure,
initial_read_window_size: config.initial_read_window,
bucket_owner: config.bucket_owner,
credentials_provider: Some(credentials_provider),
host_resolver,
})
}
/// Create a new HTTP request template for the given HTTP method and S3 bucket name.
/// Pre-populates common headers used across all requests. Sets the "accept" header assuming the
/// response should be XML; this header should be overwritten for requests like GET that return
/// object data.
fn new_request_template(&self, method: &str, bucket: &str) -> Result<S3Message, ConstructionError> {
let endpoint = self.endpoint_config.resolve_for_bucket(bucket)?;
let uri = endpoint.uri()?;
trace!(?uri, "resolved endpoint");
let signing_config = if let Some(credentials_provider) = &self.credentials_provider {
let auth_scheme = match endpoint.auth_scheme() {
Ok(auth_scheme) => auth_scheme,
Err(e) => {
error!(error=?e, "no auth scheme for endpoint");
return Err(e.into());
}
};
trace!(?auth_scheme, "resolved auth scheme");
let algorithm = Some(auth_scheme.scheme_name());
let service = Some(auth_scheme.signing_name());
let use_double_uri_encode = Some(!auth_scheme.disable_double_encoding());
Some(init_signing_config(
auth_scheme.signing_region(),
credentials_provider.clone(),
algorithm,
service,
use_double_uri_encode,
))
} else {
None
};
let hostname = uri.host_name().to_str().unwrap();
let path_prefix = uri.path().to_os_string().into_string().unwrap();
let port = uri.host_port();
let hostname_header = if port > 0 {
format!("{}:{}", hostname, port)
} else {
hostname.to_string()
};
let mut message = Message::new_request(&self.allocator)?;
message.set_request_method(method)?;
message.add_header(&Header::new("Host", hostname_header))?;
message.add_header(&Header::new("accept", "application/xml"))?;
message.add_header(&Header::new("User-Agent", &self.user_agent_header))?;
if let Some(ref payer) = self.request_payer {
message.add_header(&Header::new("x-amz-request-payer", payer))?;
}
if let Some(ref owner) = self.bucket_owner {
message.add_header(&Header::new("x-amz-expected-bucket-owner", owner))?;
}
Ok(S3Message {
inner: message,
uri,
path_prefix,
checksum_config: None,
signing_config,
})
}
fn new_meta_request_options(message: S3Message, operation: S3Operation) -> MetaRequestOptions {
let mut options = MetaRequestOptions::new();
if let Some(checksum_config) = message.checksum_config {
options.checksum_config(checksum_config);
}
if let Some(signing_config) = message.signing_config {
options.signing_config(signing_config);
}
options
.message(message.inner)
.endpoint(message.uri)
.request_type(operation.meta_request_type());
if let Some(operation_name) = operation.operation_name() {
options.operation_name(operation_name);
}
options
}
/// Make an HTTP request using this S3 client that invokes the given callbacks as the request
/// makes progress.
///
/// The `on_finish` callback is invoked on both successful and failed requests; it should call
/// `.is_err()` on the [MetaRequestResult] to decide whether the underlying meta request
/// succeeded. This callback should return `Err(None)` if it considers the request to have
/// failed but doesn't have a request-specific failure reason. The client will apply some
/// generic error parsing in this case (e.g. for permissions errors).
fn make_meta_request<T: Send + 'static, E: std::error::Error + Send + 'static>(
&self,
message: S3Message,
operation: S3Operation,
request_span: Span,
on_headers: impl FnMut(&Headers, i32) + Send + 'static,
on_body: impl FnMut(u64, &[u8]) + Send + 'static,
on_finish: impl FnOnce(&MetaRequestResult) -> Result<T, Option<ObjectClientError<E, S3RequestError>>>
+ Send
+ 'static,
) -> Result<S3HttpRequest<T, E>, S3RequestError> {
let options = Self::new_meta_request_options(message, operation);
self.make_meta_request_from_options(options, request_span, |_| {}, on_headers, on_body, on_finish)
}
/// Make an HTTP request using this S3 client that invokes the given callbacks as the request
/// makes progress. See [make_meta_request] for arguments.
fn make_meta_request_from_options<T: Send + 'static, E: std::error::Error + Send + 'static>(
&self,
mut options: MetaRequestOptions,
request_span: Span,
on_request_finish: impl Fn(&RequestMetrics) + Send + 'static,
mut on_headers: impl FnMut(&Headers, i32) + Send + 'static,
mut on_body: impl FnMut(u64, &[u8]) + Send + 'static,
on_meta_request_finish: impl FnOnce(&MetaRequestResult) -> Result<T, Option<ObjectClientError<E, S3RequestError>>>
+ Send
+ 'static,
) -> Result<S3HttpRequest<T, E>, S3RequestError> {
let (tx, rx) = oneshot::channel::<ObjectClientResult<T, E, S3RequestError>>();
let span_telemetry = request_span.clone();
let span_body = request_span.clone();
let span_finish = request_span;
let endpoint = options.get_endpoint().expect("S3Message always has an endpoint");
let hostname = endpoint.host_name().to_str().unwrap().to_owned();
let host_resolver = self.host_resolver.clone();
let start_time = Instant::now();
let first_body_part = Arc::new(AtomicBool::new(true));
let first_body_part_clone = Arc::clone(&first_body_part);
let total_bytes = Arc::new(AtomicU64::new(0));
let total_bytes_clone = Arc::clone(&total_bytes);
options
.on_telemetry(move |metrics| {
let _guard = span_telemetry.enter();
on_request_finish(metrics);
let http_status = metrics.status_code();
let request_canceled = metrics.is_canceled();
let request_failure = http_status.map(|status| !(200..299).contains(&status)).unwrap_or(!request_canceled);
let crt_error = Some(metrics.error()).filter(|e| e.is_err());
let request_type = request_type_to_metrics_string(metrics.request_type());
let request_id = metrics.request_id().unwrap_or_else(|| "<unknown>".into());
let duration = metrics.total_duration();
let ttfb = metrics.time_to_first_byte();
let range = metrics.response_headers().and_then(|headers| extract_range_header(&headers));
let message = if request_failure {
"S3 request failed"
} else if request_canceled {
"S3 request canceled"
} else {
"S3 request finished"
};
debug!(%request_type, ?crt_error, http_status, ?range, ?duration, ?ttfb, %request_id, "{}", message);
trace!(detailed_metrics=?metrics, "S3 request completed");
let op = span_telemetry.metadata().map(|m| m.name()).unwrap_or("unknown");
if let Some(ttfb) = ttfb {
metrics::histogram!("s3.requests.first_byte_latency_us", "op" => op, "type" => request_type).record(ttfb.as_micros() as f64);
}
metrics::histogram!("s3.requests.total_latency_us", "op" => op, "type" => request_type).record(duration.as_micros() as f64);
metrics::counter!("s3.requests", "op" => op, "type" => request_type).increment(1);
if request_failure {
metrics::counter!("s3.requests.failures", "op" => op, "type" => request_type, "status" => http_status.unwrap_or(-1).to_string()).increment(1);
} else if request_canceled {
metrics::counter!("s3.requests.canceled", "op" => op, "type" => request_type).increment(1);
}
})
.on_headers(move |headers, response_status| {
(on_headers)(headers, response_status);
})
.on_body(move |range_start, data| {
let _guard = span_body.enter();
if first_body_part.compare_exchange(true, false, Ordering::SeqCst, Ordering::SeqCst).ok() == Some(true) {
let latency = start_time.elapsed().as_micros() as f64;
let op = span_body.metadata().map(|m| m.name()).unwrap_or("unknown");
metrics::histogram!("s3.meta_requests.first_byte_latency_us", "op" => op).record(latency);
}
total_bytes.fetch_add(data.len() as u64, Ordering::SeqCst);
trace!(start = range_start, length = data.len(), "body part received");
(on_body)(range_start, data);
})
.on_finish(move |request_result| {
let _guard = span_finish.enter();
let op = span_finish.metadata().map(|m| m.name()).unwrap_or("unknown");
let duration = start_time.elapsed();
metrics::counter!("s3.meta_requests", "op" => op).increment(1);
metrics::histogram!("s3.meta_requests.total_latency_us", "op" => op).record(duration.as_micros() as f64);
// Some HTTP requests (like HEAD) don't have a body to stream back, so calculate TTFB now
if first_body_part_clone.compare_exchange(true, false, Ordering::SeqCst, Ordering::SeqCst).ok() == Some(true) {
let latency = duration.as_micros() as f64;
metrics::histogram!("s3.meta_requests.first_byte_latency_us", "op" => op).record(latency);
}
let total_bytes = total_bytes_clone.load(Ordering::SeqCst);
// We only log throughput of object data. PUT needs to be measured in its stream
// implementation rather than these callbacks, so we can only do GET here.
if op == "get_object" {
emit_throughput_metric(total_bytes, duration, op);
}
let hostname_awsstring = AwsString::from_str(&hostname, &Allocator::default());
if let Ok(host_count) = host_resolver.get_host_address_count(&hostname_awsstring, AddressKinds::a()) {
metrics::gauge!("s3.client.host_count", "host" => hostname).set(host_count as f64);
}
let status_code = request_result.response_status;
let log_level = if (200..=399).contains(&status_code) || status_code == 404 || request_result.is_canceled() {
tracing::Level::DEBUG
} else {
tracing::Level::WARN
};
// The `on_finish` callback has a choice of whether to give us an error or not. If
// not, fall back to generic error parsing (e.g. for permissions errors), or just no
// error if that fails too.
let result = on_meta_request_finish(&request_result);
let result = result.map_err(|e| e.or_else(|| try_parse_generic_error(&request_result).map(ObjectClientError::ClientError)));
let result = match result {
Ok(t) => {
event!(log_level, ?duration, "meta request finished");
Ok(t)
}
Err(maybe_err) => {
// Try to parse request header out of the failure. We can't just use the
// telemetry callback because there might be multiple requests per meta
// request, but these headers are known to be from the failed request.
let request_id = match &request_result.error_response_headers {
Some(headers) => headers.get("x-amz-request-id").map(|s| s.value().to_string_lossy().to_string()).ok(),
None => None,
};
let request_id = request_id.unwrap_or_else(|| "<unknown>".into());
let message = if request_result.is_canceled() {
"meta request canceled"
} else {
"meta request failed"
};
if let Some(error) = &maybe_err {
event!(log_level, ?duration, %request_id, ?error, message);
debug!("meta request result: {:?}", request_result);
} else {
event!(log_level, ?duration, %request_id, ?request_result, message);
}
if request_result.is_canceled() {
metrics::counter!("s3.meta_requests.canceled", "op" => op).increment(1);
} else {
// If it's not a real HTTP status, encode the CRT error in the metric instead
let error_status = if request_result.response_status >= 100 {
request_result.response_status
} else {
-request_result.crt_error.raw_error()
};
metrics::counter!("s3.meta_requests.failures", "op" => op, "status" => format!("{error_status}")).increment(1);
}
// Fill in a generic error if we weren't able to parse one
Err(maybe_err.unwrap_or_else(|| ObjectClientError::ClientError(S3RequestError::ResponseError(request_result))))
}
};
let _ = tx.send(result);
});
// Issue the HTTP request using the CRT's S3 meta request API
let meta_request = self.s3_client.make_meta_request(options)?;
Self::poll_client_metrics(&self.s3_client);
Ok(S3HttpRequest {
receiver: rx,
meta_request,
})
}
/// Make an HTTP request using this S3 client that returns the body on success or invokes the
/// given callback to generate an error on failure.
///
/// The `on_error` callback can assume that `result.is_err()` is true for the result it
/// receives. It can return `None` if it considers the request to have failed but doesn't
/// have a request-specific failure reason; the client will apply some generic error parsing in
/// this case (e.g. for permissions errors).
fn make_simple_http_request<E: std::error::Error + Send + 'static>(
&self,
message: S3Message,
operation: S3Operation,
request_span: Span,
on_error: impl FnOnce(&MetaRequestResult) -> Option<E> + Send + 'static,
) -> Result<S3HttpRequest<Vec<u8>, E>, S3RequestError> {
let options = Self::new_meta_request_options(message, operation);
self.make_simple_http_request_from_options(options, request_span, |_| {}, on_error, |_, _| ())
}
/// Make an HTTP request using this S3 client that returns the body on success or invokes the
/// given callback on failure. See [make_simple_http_request] for arguments.
fn make_simple_http_request_from_options<E: std::error::Error + Send + 'static>(
&self,
options: MetaRequestOptions,
request_span: Span,
on_request_finish: impl Fn(&RequestMetrics) + Send + 'static,
on_error: impl FnOnce(&MetaRequestResult) -> Option<E> + Send + 'static,
on_headers: impl FnMut(&Headers, i32) + Send + 'static,
) -> Result<S3HttpRequest<Vec<u8>, E>, S3RequestError> {
// Accumulate the body of the response into this Vec<u8>
let body: Arc<Mutex<Vec<u8>>> = Default::default();
let body_clone = Arc::clone(&body);
self.make_meta_request_from_options(
options,
request_span,
on_request_finish,
on_headers,
move |offset, data| {
let mut body = body_clone.lock().unwrap();
assert_eq!(offset as usize, body.len());
body.extend_from_slice(data);
},
move |result| {
if result.is_err() {
Err(on_error(result).map(ObjectClientError::ServiceError))
} else {
Ok(std::mem::take(&mut *body.lock().unwrap()))
}
},
)
}
fn poll_client_metrics(s3_client: &Client) {
let metrics = s3_client.poll_client_metrics();
metrics::gauge!("s3.client.num_requests_being_processed").set(metrics.num_requests_tracked_requests as f64);
metrics::gauge!("s3.client.num_requests_being_prepared").set(metrics.num_requests_being_prepared as f64);
metrics::gauge!("s3.client.request_queue_size").set(metrics.request_queue_size as f64);
metrics::gauge!("s3.client.num_auto_default_network_io").set(metrics.num_auto_default_network_io as f64);
metrics::gauge!("s3.client.num_auto_ranged_get_network_io").set(metrics.num_auto_ranged_get_network_io as f64);
metrics::gauge!("s3.client.num_auto_ranged_put_network_io").set(metrics.num_auto_ranged_put_network_io as f64);
metrics::gauge!("s3.client.num_auto_ranged_copy_network_io")
.set(metrics.num_auto_ranged_copy_network_io as f64);
metrics::gauge!("s3.client.num_total_network_io").set(metrics.num_total_network_io() as f64);
metrics::gauge!("s3.client.num_requests_stream_queued_waiting")
.set(metrics.num_requests_stream_queued_waiting as f64);
metrics::gauge!("s3.client.num_requests_streaming_response")
.set(metrics.num_requests_streaming_response as f64);
// Buffer pool metrics
let start = Instant::now();
let buffer_pool_stats = s3_client.poll_buffer_pool_usage_stats();
metrics::histogram!("s3.client.buffer_pool.get_usage_latency_us").record(start.elapsed().as_micros() as f64);
metrics::gauge!("s3.client.buffer_pool.mem_limit").set(buffer_pool_stats.mem_limit as f64);
metrics::gauge!("s3.client.buffer_pool.primary_cutoff").set(buffer_pool_stats.primary_cutoff as f64);
metrics::gauge!("s3.client.buffer_pool.primary_used").set(buffer_pool_stats.primary_used as f64);
metrics::gauge!("s3.client.buffer_pool.primary_allocated").set(buffer_pool_stats.primary_allocated as f64);
metrics::gauge!("s3.client.buffer_pool.primary_reserved").set(buffer_pool_stats.primary_reserved as f64);
metrics::gauge!("s3.client.buffer_pool.primary_num_blocks").set(buffer_pool_stats.primary_num_blocks as f64);
metrics::gauge!("s3.client.buffer_pool.secondary_reserved").set(buffer_pool_stats.secondary_reserved as f64);
metrics::gauge!("s3.client.buffer_pool.secondary_used").set(buffer_pool_stats.secondary_used as f64);
metrics::gauge!("s3.client.buffer_pool.forced_used").set(buffer_pool_stats.forced_used as f64);
}
fn next_request_counter(&self) -> u64 {
self.next_request_counter.fetch_add(1, Ordering::SeqCst)
}
}
/// S3 operation supported by this client.
#[derive(Debug, Clone, Copy)]
enum S3Operation {
DeleteObject,
GetObject,
GetObjectAttributes,
HeadBucket,
HeadObject,
ListObjects,
PutObject,
CopyObject,
PutObjectSingle,
}
impl S3Operation {
/// The [MetaRequestType] to use for this operation.
fn meta_request_type(&self) -> MetaRequestType {
match self {
S3Operation::GetObject => MetaRequestType::GetObject,
S3Operation::PutObject => MetaRequestType::PutObject,
S3Operation::CopyObject => MetaRequestType::CopyObject,
_ => MetaRequestType::Default,
}
}
/// The operation name to set when configuring a request. Required for operations that
/// have MetaRequestType::Default (see [meta_request_type]). `None` otherwise.
fn operation_name(&self) -> Option<&'static str> {
match self {
S3Operation::DeleteObject => Some("DeleteObject"),
S3Operation::GetObject => None,
S3Operation::GetObjectAttributes => Some("GetObjectAttributes"),
S3Operation::HeadBucket => Some("HeadBucket"),
S3Operation::HeadObject => Some("HeadObject"),
S3Operation::ListObjects => Some("ListObjectsV2"),
S3Operation::PutObject => None,
S3Operation::CopyObject => None,
S3Operation::PutObjectSingle => Some("PutObject"),
}
}
}
/// A HTTP message to be sent to S3. This is a wrapper around a plain HTTP message, except that it
/// helps us correctly configure the endpoint and "Host" header to handle both path-style and
/// virtual-hosted-style addresses. The `path_prefix` is appended to the front of all paths, and
/// need not be terminated with a `/`.
#[derive(Debug)]
struct S3Message<'a> {
inner: Message<'a>,
uri: Uri,
path_prefix: String,
checksum_config: Option<ChecksumConfig>,
signing_config: Option<SigningConfig>,
}
impl<'a> S3Message<'a> {
/// Add a header to this message. The header is added if necessary and any existing values for
/// this header are removed.
fn set_header(
&mut self,
header: &Header<impl AsRef<OsStr>, impl AsRef<OsStr>>,
) -> Result<(), mountpoint_s3_crt::common::error::Error> {
self.inner.set_header(header)
}
/// Set the request path and query for this message. The components should not be URL-encoded;
/// this method will handle that.
fn set_request_path_and_query<P: AsRef<OsStr>>(
&mut self,
path: impl AsRef<OsStr>,
query: impl AsRef<[(P, P)]>,
) -> Result<(), mountpoint_s3_crt::common::error::Error> {
// This is RFC 3986 but with '/' also considered a safe character for path fragments.
const URLENCODE_QUERY_FRAGMENT: &AsciiSet =
&NON_ALPHANUMERIC.remove(b'-').remove(b'.').remove(b'_').remove(b'~');
const URLENCODE_PATH_FRAGMENT: &AsciiSet = &URLENCODE_QUERY_FRAGMENT.remove(b'/');
fn write_encoded_fragment(s: &mut OsString, piece: impl AsRef<OsStr>, encoding: &'static AsciiSet) {
let iter = percent_encode(piece.as_ref().as_bytes(), encoding);
s.extend(iter.map(|s| OsStr::from_bytes(s.as_bytes())));
}
// This estimate is exact if no characters need encoding, otherwise we'll end up
// reallocating a couple of times. The '?' for the query is counted in the first key-value
// pair.
let space_needed = self.path_prefix.len()
+ path.as_ref().len()
+ query
.as_ref()
.iter()
.map(|(key, value)| key.as_ref().len() + value.as_ref().len() + 2) // +2 for & and =
.sum::<usize>();
let mut full_path = OsString::with_capacity(space_needed);
write_encoded_fragment(&mut full_path, &self.path_prefix, URLENCODE_PATH_FRAGMENT);
write_encoded_fragment(&mut full_path, &path, URLENCODE_PATH_FRAGMENT);
// Build the query string
if !query.as_ref().is_empty() {
full_path.push("?");
for (i, (key, value)) in query.as_ref().iter().enumerate() {
if i != 0 {
full_path.push("&");
}
write_encoded_fragment(&mut full_path, key, URLENCODE_QUERY_FRAGMENT);
full_path.push("=");
write_encoded_fragment(&mut full_path, value, URLENCODE_QUERY_FRAGMENT);
}
}
self.inner.set_request_path(full_path)
}
/// Set the request path for this message. The path should not be URL-encoded; this method will
/// handle that.
fn set_request_path(&mut self, path: impl AsRef<OsStr>) -> Result<(), mountpoint_s3_crt::common::error::Error> {
self.set_request_path_and_query::<&str>(path, &[])
}
/// Sets the checksum configuration for this message.
fn set_checksum_config(&mut self, checksum_config: Option<ChecksumConfig>) {
self.checksum_config = checksum_config;
}
/// Sets the body input stream for this message, and returns any previously set input stream.
/// If input_stream is None, unsets the body.
fn set_body_stream(&mut self, input_stream: Option<InputStream<'a>>) -> Option<InputStream<'a>> {
self.inner.set_body_stream(input_stream)
}
/// Set the content length header.
fn set_content_length_header(
&mut self,
content_length: usize,
) -> Result<(), mountpoint_s3_crt::common::error::Error> {
self.inner
.set_header(&Header::new("Content-Length", content_length.to_string()))
}
/// Set the checksum header.
fn set_checksum_header(
&mut self,
checksum: &UploadChecksum,
) -> Result<(), mountpoint_s3_crt::common::error::Error> {
let header = match checksum {
UploadChecksum::Crc32c(crc32c) => Header::new("x-amz-checksum-crc32c", crc32c_to_base64(crc32c)),
};
self.inner.set_header(&header)
}
}
#[derive(Debug)]
#[pin_project(PinnedDrop)]
struct S3HttpRequest<T, E> {
#[pin]
receiver: oneshot::Receiver<ObjectClientResult<T, E, S3RequestError>>,
meta_request: MetaRequest,
}
impl<T: Send, E: Send> Future for S3HttpRequest<T, E> {
type Output = ObjectClientResult<T, E, S3RequestError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
this.receiver.poll(cx).map(|result| {
result.unwrap_or_else(|err| {
Err(ObjectClientError::ClientError(S3RequestError::InternalError(Box::new(
err,
))))
})
})
}
}
#[pinned_drop]
impl<T, E> PinnedDrop for S3HttpRequest<T, E> {
fn drop(self: Pin<&mut Self>) {
self.meta_request.cancel();
}
}
/// Failures to construct a new S3 client
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum NewClientError {
/// Invalid S3 endpoint
#[error("invalid S3 endpoint")]
InvalidEndpoint(#[from] EndpointError),
/// Invalid AWS credentials
#[error("invalid AWS credentials")]
ProviderFailure(#[source] mountpoint_s3_crt::common::error::Error),
/// Invalid configuration
#[error("invalid configuration: {0}")]
InvalidConfiguration(String),
/// An internal error from within the AWS Common Runtime
#[error("Unknown CRT error")]
CrtError(#[source] mountpoint_s3_crt::common::error::Error),
}
/// Errors returned by the CRT-based S3 client
#[derive(Error, Debug)]
pub enum S3RequestError {
/// An internal error from within the S3 client. The request may have been sent.
#[error("Internal S3 client error")]
InternalError(#[source] Box<dyn std::error::Error + Send + Sync>),