aws_types/
sdk_config.rs

1/*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6#![deny(missing_docs)]
7
8//! AWS Shared Config
9//!
10//! This module contains a shared configuration representation that is agnostic from a specific service.
11
12use crate::app_name::AppName;
13use crate::docs_for;
14use crate::endpoint_config::AccountIdEndpointMode;
15use crate::origin::Origin;
16use crate::region::Region;
17use crate::service_config::LoadServiceConfig;
18use aws_credential_types::provider::token::SharedTokenProvider;
19pub use aws_credential_types::provider::SharedCredentialsProvider;
20use aws_smithy_async::rt::sleep::AsyncSleep;
21pub use aws_smithy_async::rt::sleep::SharedAsyncSleep;
22pub use aws_smithy_async::time::{SharedTimeSource, TimeSource};
23use aws_smithy_runtime_api::client::behavior_version::BehaviorVersion;
24use aws_smithy_runtime_api::client::http::HttpClient;
25pub use aws_smithy_runtime_api::client::http::SharedHttpClient;
26use aws_smithy_runtime_api::client::identity::{ResolveCachedIdentity, SharedIdentityCache};
27pub use aws_smithy_runtime_api::client::stalled_stream_protection::StalledStreamProtectionConfig;
28use aws_smithy_runtime_api::shared::IntoShared;
29pub use aws_smithy_types::checksum_config::{
30    RequestChecksumCalculation, ResponseChecksumValidation,
31};
32pub use aws_smithy_types::retry::RetryConfig;
33pub use aws_smithy_types::timeout::TimeoutConfig;
34use std::collections::HashMap;
35use std::sync::Arc;
36
37/// Unified docstrings to keep crates in sync. Not intended for public use
38pub mod unified_docs {
39    /// A macro that generates docs for selected fields of `SdkConfig`.
40    #[macro_export]
41    macro_rules! docs_for {
42        (use_fips) => {
43"When true, send this request to the FIPS-compliant regional endpoint.
44
45If no FIPS-compliant endpoint can be determined, dispatching the request will return an error."
46        };
47        (use_dual_stack) => {
48"When true, send this request to the dual-stack endpoint.
49
50If no dual-stack endpoint is available the request MAY return an error.
51
52**Note**: Some services do not offer dual-stack as a configurable parameter (e.g. Code Catalyst). For
53these services, this setting has no effect"
54        };
55        (time_source) => {
56"The time source use to use for this client.
57
58This only needs to be required for creating deterministic tests or platforms where `SystemTime::now()` is not supported."};
59        (disable_request_compression) => {
60"When `true`, disable request compression. Defaults to `false`.
61
62**Only some services support request compression.** For services
63that don't support request compression, this setting does nothing.
64" };
65        (request_min_compression_size_bytes) => {
66"The minimum size of request that should be compressed. Defaults to `10240` bytes.
67
68When a request body's size is lower than this, request compression will be skipped.
69This is useful for request bodies because, for small request bodies, compression may actually increase their size.
70
71**Only some services support request compression.** For services
72that don't support request compression, this setting does nothing.
73" };
74        (account_id_endpoint_mode) => {
75"Controls the account ID-based routing behavior.
76
77By default, the routing behavior is set to `preferred`.
78Customers can adjust this setting to other values to switch between different routing patterns or temporarily disable the feature.
79
80See the developer guide on [account-based endpoints](https://docs.aws.amazon.com/sdkref/latest/guide/feature-account-endpoints.html)
81for more information.
82
83For services that do not use the account-based endpoints, this setting does nothing.
84" };
85    }
86}
87
88/// AWS Shared Configuration
89#[derive(Debug, Clone)]
90pub struct SdkConfig {
91    app_name: Option<AppName>,
92    identity_cache: Option<SharedIdentityCache>,
93    credentials_provider: Option<SharedCredentialsProvider>,
94    token_provider: Option<SharedTokenProvider>,
95    region: Option<Region>,
96    account_id_endpoint_mode: Option<AccountIdEndpointMode>,
97    endpoint_url: Option<String>,
98    retry_config: Option<RetryConfig>,
99    sleep_impl: Option<SharedAsyncSleep>,
100    time_source: Option<SharedTimeSource>,
101    timeout_config: Option<TimeoutConfig>,
102    stalled_stream_protection_config: Option<StalledStreamProtectionConfig>,
103    http_client: Option<SharedHttpClient>,
104    use_fips: Option<bool>,
105    use_dual_stack: Option<bool>,
106    behavior_version: Option<BehaviorVersion>,
107    service_config: Option<Arc<dyn LoadServiceConfig>>,
108    config_origins: HashMap<&'static str, Origin>,
109    disable_request_compression: Option<bool>,
110    request_min_compression_size_bytes: Option<u32>,
111    request_checksum_calculation: Option<RequestChecksumCalculation>,
112    response_checksum_validation: Option<ResponseChecksumValidation>,
113}
114
115/// Builder for AWS Shared Configuration
116///
117/// _Important:_ Using the `aws-config` crate to configure the SDK is preferred to invoking this
118/// builder directly. Using this builder directly won't pull in any AWS recommended default
119/// configuration values.
120#[derive(Debug, Default)]
121pub struct Builder {
122    app_name: Option<AppName>,
123    identity_cache: Option<SharedIdentityCache>,
124    credentials_provider: Option<SharedCredentialsProvider>,
125    token_provider: Option<SharedTokenProvider>,
126    region: Option<Region>,
127    account_id_endpoint_mode: Option<AccountIdEndpointMode>,
128    endpoint_url: Option<String>,
129    retry_config: Option<RetryConfig>,
130    sleep_impl: Option<SharedAsyncSleep>,
131    time_source: Option<SharedTimeSource>,
132    timeout_config: Option<TimeoutConfig>,
133    stalled_stream_protection_config: Option<StalledStreamProtectionConfig>,
134    http_client: Option<SharedHttpClient>,
135    use_fips: Option<bool>,
136    use_dual_stack: Option<bool>,
137    behavior_version: Option<BehaviorVersion>,
138    service_config: Option<Arc<dyn LoadServiceConfig>>,
139    config_origins: HashMap<&'static str, Origin>,
140    disable_request_compression: Option<bool>,
141    request_min_compression_size_bytes: Option<u32>,
142    request_checksum_calculation: Option<RequestChecksumCalculation>,
143    response_checksum_validation: Option<ResponseChecksumValidation>,
144}
145
146impl Builder {
147    /// Set the region for the builder
148    ///
149    /// # Examples
150    /// ```rust
151    /// use aws_types::SdkConfig;
152    /// use aws_types::region::Region;
153    /// let config = SdkConfig::builder().region(Region::new("us-east-1")).build();
154    /// ```
155    pub fn region(mut self, region: impl Into<Option<Region>>) -> Self {
156        self.set_region(region);
157        self
158    }
159
160    /// Set the region for the builder
161    ///
162    /// # Examples
163    /// ```rust
164    /// fn region_override() -> Option<Region> {
165    ///     // ...
166    ///     # None
167    /// }
168    /// use aws_types::SdkConfig;
169    /// use aws_types::region::Region;
170    /// let mut builder = SdkConfig::builder();
171    /// if let Some(region) = region_override() {
172    ///     builder.set_region(region);
173    /// }
174    /// let config = builder.build();
175    /// ```
176    pub fn set_region(&mut self, region: impl Into<Option<Region>>) -> &mut Self {
177        self.region = region.into();
178        self
179    }
180
181    #[doc = docs_for!(account_id_endpoint_mode)]
182    pub fn account_id_endpoint_mode(
183        mut self,
184        account_id_endpoint_mode: AccountIdEndpointMode,
185    ) -> Self {
186        self.set_account_id_endpoint_mode(Some(account_id_endpoint_mode));
187        self
188    }
189
190    #[doc = docs_for!(account_id_endpoint_mode)]
191    pub fn set_account_id_endpoint_mode(
192        &mut self,
193        account_id_endpoint_mode: Option<AccountIdEndpointMode>,
194    ) -> &mut Self {
195        self.account_id_endpoint_mode = account_id_endpoint_mode;
196        self
197    }
198
199    /// Set the endpoint URL to use when making requests.
200    /// # Examples
201    /// ```
202    /// use aws_types::SdkConfig;
203    /// let config = SdkConfig::builder().endpoint_url("http://localhost:8080").build();
204    /// ```
205    pub fn endpoint_url(mut self, endpoint_url: impl Into<String>) -> Self {
206        self.set_endpoint_url(Some(endpoint_url.into()));
207        self
208    }
209
210    /// Set the endpoint URL to use when making requests.
211    pub fn set_endpoint_url(&mut self, endpoint_url: Option<String>) -> &mut Self {
212        self.endpoint_url = endpoint_url;
213        self
214    }
215
216    /// Set the checksum calculation strategy to use when making requests.
217    /// # Examples
218    /// ```
219    /// use aws_types::SdkConfig;
220    /// use aws_smithy_types::checksum_config::RequestChecksumCalculation;
221    /// let config = SdkConfig::builder().request_checksum_calculation(RequestChecksumCalculation::WhenSupported).build();
222    /// ```
223    pub fn request_checksum_calculation(
224        mut self,
225        request_checksum_calculation: RequestChecksumCalculation,
226    ) -> Self {
227        self.set_request_checksum_calculation(Some(request_checksum_calculation));
228        self
229    }
230
231    /// Set the checksum calculation strategy to use when making requests.
232    pub fn set_request_checksum_calculation(
233        &mut self,
234        request_checksum_calculation: Option<RequestChecksumCalculation>,
235    ) -> &mut Self {
236        self.request_checksum_calculation = request_checksum_calculation;
237        self
238    }
239
240    /// Set the checksum calculation strategy to use for responses.
241    /// # Examples
242    /// ```
243    /// use aws_types::SdkConfig;
244    /// use aws_smithy_types::checksum_config::ResponseChecksumValidation;
245    /// let config = SdkConfig::builder().response_checksum_validation(ResponseChecksumValidation::WhenSupported).build();
246    /// ```
247    pub fn response_checksum_validation(
248        mut self,
249        response_checksum_validation: ResponseChecksumValidation,
250    ) -> Self {
251        self.set_response_checksum_validation(Some(response_checksum_validation));
252        self
253    }
254
255    /// Set the checksum calculation strategy to use for responses.
256    pub fn set_response_checksum_validation(
257        &mut self,
258        response_checksum_validation: Option<ResponseChecksumValidation>,
259    ) -> &mut Self {
260        self.response_checksum_validation = response_checksum_validation;
261        self
262    }
263
264    /// Set the retry_config for the builder
265    ///
266    /// _Note:_ Retries require a sleep implementation in order to work. When enabling retry, make
267    /// sure to set one with [Self::sleep_impl] or [Self::set_sleep_impl].
268    ///
269    /// # Examples
270    /// ```rust
271    /// use aws_types::SdkConfig;
272    /// use aws_smithy_types::retry::RetryConfig;
273    ///
274    /// let retry_config = RetryConfig::standard().with_max_attempts(5);
275    /// let config = SdkConfig::builder().retry_config(retry_config).build();
276    /// ```
277    pub fn retry_config(mut self, retry_config: RetryConfig) -> Self {
278        self.set_retry_config(Some(retry_config));
279        self
280    }
281
282    /// Set the retry_config for the builder
283    ///
284    /// _Note:_ Retries require a sleep implementation in order to work. When enabling retry, make
285    /// sure to set one with [Self::sleep_impl] or [Self::set_sleep_impl].
286    ///
287    /// # Examples
288    /// ```rust
289    /// use aws_types::sdk_config::{SdkConfig, Builder};
290    /// use aws_smithy_types::retry::RetryConfig;
291    ///
292    /// fn disable_retries(builder: &mut Builder) {
293    ///     let retry_config = RetryConfig::standard().with_max_attempts(1);
294    ///     builder.set_retry_config(Some(retry_config));
295    /// }
296    ///
297    /// let mut builder = SdkConfig::builder();
298    /// disable_retries(&mut builder);
299    /// ```
300    pub fn set_retry_config(&mut self, retry_config: Option<RetryConfig>) -> &mut Self {
301        self.retry_config = retry_config;
302        self
303    }
304
305    /// Set the [`TimeoutConfig`] for the builder
306    ///
307    /// _Note:_ Timeouts require a sleep implementation in order to work.
308    /// When enabling timeouts, be sure to set one with [Self::sleep_impl] or
309    /// [Self::set_sleep_impl].
310    ///
311    /// # Examples
312    ///
313    /// ```rust
314    /// # use std::time::Duration;
315    /// use aws_types::SdkConfig;
316    /// use aws_smithy_types::timeout::TimeoutConfig;
317    ///
318    /// let timeout_config = TimeoutConfig::builder()
319    ///     .operation_attempt_timeout(Duration::from_secs(2))
320    ///     .operation_timeout(Duration::from_secs(5))
321    ///     .build();
322    /// let config = SdkConfig::builder()
323    ///     .timeout_config(timeout_config)
324    ///     .build();
325    /// ```
326    pub fn timeout_config(mut self, timeout_config: TimeoutConfig) -> Self {
327        self.set_timeout_config(Some(timeout_config));
328        self
329    }
330
331    /// Set the [`TimeoutConfig`] for the builder
332    ///
333    /// _Note:_ Timeouts require a sleep implementation in order to work.
334    /// When enabling timeouts, be sure to set one with [Self::sleep_impl] or
335    /// [Self::set_sleep_impl].
336    ///
337    /// # Examples
338    /// ```rust
339    /// # use std::time::Duration;
340    /// use aws_types::sdk_config::{SdkConfig, Builder};
341    /// use aws_smithy_types::timeout::TimeoutConfig;
342    ///
343    /// fn set_preferred_timeouts(builder: &mut Builder) {
344    ///     let timeout_config = TimeoutConfig::builder()
345    ///         .operation_attempt_timeout(Duration::from_secs(2))
346    ///         .operation_timeout(Duration::from_secs(5))
347    ///         .build();
348    ///     builder.set_timeout_config(Some(timeout_config));
349    /// }
350    ///
351    /// let mut builder = SdkConfig::builder();
352    /// set_preferred_timeouts(&mut builder);
353    /// let config = builder.build();
354    /// ```
355    pub fn set_timeout_config(&mut self, timeout_config: Option<TimeoutConfig>) -> &mut Self {
356        self.timeout_config = timeout_config;
357        self
358    }
359
360    /// Set the sleep implementation for the builder.
361    ///
362    /// The sleep implementation is used to create timeout futures.
363    ///
364    /// _Note:_ If you're using the Tokio runtime, a `TokioSleep` implementation is available in
365    /// the `aws-smithy-async` crate.
366    ///
367    /// # Examples
368    ///
369    /// ```rust
370    /// use aws_smithy_async::rt::sleep::{AsyncSleep, SharedAsyncSleep, Sleep};
371    /// use aws_types::SdkConfig;
372    ///
373    /// ##[derive(Debug)]
374    /// pub struct ForeverSleep;
375    ///
376    /// impl AsyncSleep for ForeverSleep {
377    ///     fn sleep(&self, duration: std::time::Duration) -> Sleep {
378    ///         Sleep::new(std::future::pending())
379    ///     }
380    /// }
381    ///
382    /// let sleep_impl = SharedAsyncSleep::new(ForeverSleep);
383    /// let config = SdkConfig::builder().sleep_impl(sleep_impl).build();
384    /// ```
385    pub fn sleep_impl(mut self, sleep_impl: impl AsyncSleep + 'static) -> Self {
386        self.set_sleep_impl(Some(sleep_impl.into_shared()));
387        self
388    }
389
390    /// Set the sleep implementation for the builder. The sleep implementation is used to create
391    /// timeout futures.
392    ///
393    /// _Note:_ If you're using the Tokio runtime, a `TokioSleep` implementation is available in
394    /// the `aws-smithy-async` crate.
395    ///
396    /// # Examples
397    /// ```rust
398    /// # use aws_smithy_async::rt::sleep::{AsyncSleep, SharedAsyncSleep, Sleep};
399    /// # use aws_types::sdk_config::{Builder, SdkConfig};
400    /// #[derive(Debug)]
401    /// pub struct ForeverSleep;
402    ///
403    /// impl AsyncSleep for ForeverSleep {
404    ///     fn sleep(&self, duration: std::time::Duration) -> Sleep {
405    ///         Sleep::new(std::future::pending())
406    ///     }
407    /// }
408    ///
409    /// fn set_never_ending_sleep_impl(builder: &mut Builder) {
410    ///     let sleep_impl = SharedAsyncSleep::new(ForeverSleep);
411    ///     builder.set_sleep_impl(Some(sleep_impl));
412    /// }
413    ///
414    /// let mut builder = SdkConfig::builder();
415    /// set_never_ending_sleep_impl(&mut builder);
416    /// let config = builder.build();
417    /// ```
418    pub fn set_sleep_impl(&mut self, sleep_impl: Option<SharedAsyncSleep>) -> &mut Self {
419        self.sleep_impl = sleep_impl;
420        self
421    }
422
423    /// Set the identity cache for caching credentials and SSO tokens.
424    ///
425    /// The default identity cache will wait until the first request that requires authentication
426    /// to load an identity. Once the identity is loaded, it is cached until shortly before it
427    /// expires.
428    ///
429    /// # Examples
430    /// Disabling identity caching:
431    /// ```rust
432    /// # use aws_types::SdkConfig;
433    /// use aws_smithy_runtime::client::identity::IdentityCache;
434    /// let config = SdkConfig::builder()
435    ///     .identity_cache(IdentityCache::no_cache())
436    ///     .build();
437    /// ```
438    /// Changing settings on the default cache implementation:
439    /// ```rust
440    /// # use aws_types::SdkConfig;
441    /// use aws_smithy_runtime::client::identity::IdentityCache;
442    /// use std::time::Duration;
443    ///
444    /// let config = SdkConfig::builder()
445    ///     .identity_cache(
446    ///         IdentityCache::lazy()
447    ///             .load_timeout(Duration::from_secs(10))
448    ///             .build()
449    ///     )
450    ///     .build();
451    /// ```
452    pub fn identity_cache(mut self, cache: impl ResolveCachedIdentity + 'static) -> Self {
453        self.set_identity_cache(Some(cache.into_shared()));
454        self
455    }
456
457    /// Set the identity cache for caching credentials and SSO tokens.
458    ///
459    /// The default identity cache will wait until the first request that requires authentication
460    /// to load an identity. Once the identity is loaded, it is cached until shortly before it
461    /// expires.
462    ///
463    /// # Examples
464    /// ```rust
465    /// # use aws_types::SdkConfig;
466    /// use aws_smithy_runtime::client::identity::IdentityCache;
467    ///
468    /// fn override_identity_cache() -> bool {
469    ///   // ...
470    ///   # true
471    /// }
472    ///
473    /// let mut builder = SdkConfig::builder();
474    /// if override_identity_cache() {
475    ///     builder.set_identity_cache(Some(IdentityCache::lazy().build()));
476    /// }
477    /// let config = builder.build();
478    /// ```
479    pub fn set_identity_cache(&mut self, cache: Option<SharedIdentityCache>) -> &mut Self {
480        self.identity_cache = cache;
481        self
482    }
483
484    /// Set the credentials provider for the builder
485    ///
486    /// # Examples
487    /// ```rust
488    /// use aws_credential_types::provider::{ProvideCredentials, SharedCredentialsProvider};
489    /// use aws_types::SdkConfig;
490    /// fn make_provider() -> impl ProvideCredentials {
491    ///   // ...
492    ///   # use aws_credential_types::Credentials;
493    ///   # Credentials::new("test", "test", None, None, "example")
494    /// }
495    ///
496    /// let config = SdkConfig::builder()
497    ///     .credentials_provider(SharedCredentialsProvider::new(make_provider()))
498    ///     .build();
499    /// ```
500    pub fn credentials_provider(mut self, provider: SharedCredentialsProvider) -> Self {
501        self.set_credentials_provider(Some(provider));
502        self
503    }
504
505    /// Set the credentials provider for the builder
506    ///
507    /// # Examples
508    /// ```rust
509    /// use aws_credential_types::provider::{ProvideCredentials, SharedCredentialsProvider};
510    /// use aws_types::SdkConfig;
511    /// fn make_provider() -> impl ProvideCredentials {
512    ///   // ...
513    ///   # use aws_credential_types::Credentials;
514    ///   # Credentials::new("test", "test", None, None, "example")
515    /// }
516    ///
517    /// fn override_provider() -> bool {
518    ///   // ...
519    ///   # true
520    /// }
521    ///
522    /// let mut builder = SdkConfig::builder();
523    /// if override_provider() {
524    ///     builder.set_credentials_provider(Some(SharedCredentialsProvider::new(make_provider())));
525    /// }
526    /// let config = builder.build();
527    /// ```
528    pub fn set_credentials_provider(
529        &mut self,
530        provider: Option<SharedCredentialsProvider>,
531    ) -> &mut Self {
532        self.credentials_provider = provider;
533        self
534    }
535
536    /// Set the bearer auth token provider for the builder
537    ///
538    /// # Examples
539    /// ```rust
540    /// use aws_credential_types::provider::token::{ProvideToken, SharedTokenProvider};
541    /// use aws_types::SdkConfig;
542    ///
543    /// fn make_provider() -> impl ProvideToken {
544    ///   // ...
545    ///   # aws_credential_types::Token::new("example", None)
546    /// }
547    ///
548    /// let config = SdkConfig::builder()
549    ///     .token_provider(SharedTokenProvider::new(make_provider()))
550    ///     .build();
551    /// ```
552    pub fn token_provider(mut self, provider: SharedTokenProvider) -> Self {
553        self.set_token_provider(Some(provider));
554        self
555    }
556
557    /// Set the bearer auth token provider for the builder
558    ///
559    /// # Examples
560    /// ```rust
561    /// use aws_credential_types::provider::token::{ProvideToken, SharedTokenProvider};
562    /// use aws_types::SdkConfig;
563    ///
564    /// fn make_provider() -> impl ProvideToken {
565    ///   // ...
566    ///   # aws_credential_types::Token::new("example", None)
567    /// }
568    ///
569    /// fn override_provider() -> bool {
570    ///   // ...
571    ///   # true
572    /// }
573    ///
574    /// let mut builder = SdkConfig::builder();
575    /// if override_provider() {
576    ///     builder.set_token_provider(Some(SharedTokenProvider::new(make_provider())));
577    /// }
578    /// let config = builder.build();
579    /// ```
580    pub fn set_token_provider(&mut self, provider: Option<SharedTokenProvider>) -> &mut Self {
581        self.token_provider = provider;
582        self
583    }
584
585    /// Sets the name of the app that is using the client.
586    ///
587    /// This _optional_ name is used to identify the application in the user agent that
588    /// gets sent along with requests.
589    pub fn app_name(mut self, app_name: AppName) -> Self {
590        self.set_app_name(Some(app_name));
591        self
592    }
593
594    /// Sets the name of the app that is using the client.
595    ///
596    /// This _optional_ name is used to identify the application in the user agent that
597    /// gets sent along with requests.
598    pub fn set_app_name(&mut self, app_name: Option<AppName>) -> &mut Self {
599        self.app_name = app_name;
600        self
601    }
602
603    /// Sets the HTTP client to use when making requests.
604    ///
605    /// ## Examples
606    /// ```no_run
607    /// # #[cfg(feature = "examples")]
608    /// # fn example() {
609    /// use aws_types::sdk_config::{SdkConfig, TimeoutConfig};
610    /// use aws_smithy_runtime::client::http::hyper_014::HyperClientBuilder;
611    /// use std::time::Duration;
612    ///
613    /// // Create a connector that will be used to establish TLS connections
614    /// let tls_connector = hyper_rustls::HttpsConnectorBuilder::new()
615    ///     .with_webpki_roots()
616    ///     .https_only()
617    ///     .enable_http1()
618    ///     .enable_http2()
619    ///     .build();
620    /// // Create a HTTP client that uses the TLS connector. This client is
621    /// // responsible for creating and caching a HttpConnector when given HttpConnectorSettings.
622    /// // This hyper client will create HttpConnectors backed by hyper and the tls_connector.
623    /// let http_client = HyperClientBuilder::new().build(tls_connector);
624    /// let sdk_config = SdkConfig::builder()
625    ///     .http_client(http_client)
626    ///     // Connect/read timeouts are passed to the HTTP client when servicing a request
627    ///     .timeout_config(
628    ///         TimeoutConfig::builder()
629    ///             .connect_timeout(Duration::from_secs(5))
630    ///             .build()
631    ///     )
632    ///     .build();
633    /// # }
634    /// ```
635    pub fn http_client(mut self, http_client: impl HttpClient + 'static) -> Self {
636        self.set_http_client(Some(http_client.into_shared()));
637        self
638    }
639
640    /// Sets the HTTP client to use when making requests.
641    ///
642    /// ## Examples
643    /// ```no_run
644    /// # #[cfg(feature = "examples")]
645    /// # fn example() {
646    /// use aws_types::sdk_config::{Builder, SdkConfig, TimeoutConfig};
647    /// use aws_smithy_runtime::client::http::hyper_014::HyperClientBuilder;
648    /// use std::time::Duration;
649    ///
650    /// fn override_http_client(builder: &mut Builder) {
651    ///     // Create a connector that will be used to establish TLS connections
652    ///     let tls_connector = hyper_rustls::HttpsConnectorBuilder::new()
653    ///         .with_webpki_roots()
654    ///         .https_only()
655    ///         .enable_http1()
656    ///         .enable_http2()
657    ///         .build();
658    ///     // Create a HTTP client that uses the TLS connector. This client is
659    ///     // responsible for creating and caching a HttpConnector when given HttpConnectorSettings.
660    ///     // This hyper client will create HttpConnectors backed by hyper and the tls_connector.
661    ///     let http_client = HyperClientBuilder::new().build(tls_connector);
662    ///
663    ///     builder.set_http_client(Some(http_client));
664    /// }
665    ///
666    /// let mut builder = SdkConfig::builder();
667    /// override_http_client(&mut builder);
668    /// let config = builder.build();
669    /// # }
670    /// ```
671    pub fn set_http_client(&mut self, http_client: Option<SharedHttpClient>) -> &mut Self {
672        self.http_client = http_client;
673        self
674    }
675
676    #[doc = docs_for!(use_fips)]
677    pub fn use_fips(mut self, use_fips: bool) -> Self {
678        self.set_use_fips(Some(use_fips));
679        self
680    }
681
682    #[doc = docs_for!(use_fips)]
683    pub fn set_use_fips(&mut self, use_fips: Option<bool>) -> &mut Self {
684        self.use_fips = use_fips;
685        self
686    }
687
688    #[doc = docs_for!(use_dual_stack)]
689    pub fn use_dual_stack(mut self, use_dual_stack: bool) -> Self {
690        self.set_use_dual_stack(Some(use_dual_stack));
691        self
692    }
693
694    #[doc = docs_for!(use_dual_stack)]
695    pub fn set_use_dual_stack(&mut self, use_dual_stack: Option<bool>) -> &mut Self {
696        self.use_dual_stack = use_dual_stack;
697        self
698    }
699
700    #[doc = docs_for!(time_source)]
701    pub fn time_source(mut self, time_source: impl TimeSource + 'static) -> Self {
702        self.set_time_source(Some(SharedTimeSource::new(time_source)));
703        self
704    }
705
706    #[doc = docs_for!(time_source)]
707    pub fn set_time_source(&mut self, time_source: Option<SharedTimeSource>) -> &mut Self {
708        self.time_source = time_source;
709        self
710    }
711
712    #[doc = docs_for!(disable_request_compression)]
713    pub fn disable_request_compression(mut self, disable_request_compression: bool) -> Self {
714        self.set_disable_request_compression(Some(disable_request_compression));
715        self
716    }
717
718    #[doc = docs_for!(disable_request_compression)]
719    pub fn set_disable_request_compression(
720        &mut self,
721        disable_request_compression: Option<bool>,
722    ) -> &mut Self {
723        self.disable_request_compression = disable_request_compression;
724        self
725    }
726
727    #[doc = docs_for!(request_min_compression_size_bytes)]
728    pub fn request_min_compression_size_bytes(
729        mut self,
730        request_min_compression_size_bytes: u32,
731    ) -> Self {
732        self.set_request_min_compression_size_bytes(Some(request_min_compression_size_bytes));
733        self
734    }
735
736    #[doc = docs_for!(request_min_compression_size_bytes)]
737    pub fn set_request_min_compression_size_bytes(
738        &mut self,
739        request_min_compression_size_bytes: Option<u32>,
740    ) -> &mut Self {
741        self.request_min_compression_size_bytes = request_min_compression_size_bytes;
742        self
743    }
744
745    /// Sets the [`BehaviorVersion`] for the [`SdkConfig`]
746    pub fn behavior_version(mut self, behavior_version: BehaviorVersion) -> Self {
747        self.set_behavior_version(Some(behavior_version));
748        self
749    }
750
751    /// Sets the [`BehaviorVersion`] for the [`SdkConfig`]
752    pub fn set_behavior_version(&mut self, behavior_version: Option<BehaviorVersion>) -> &mut Self {
753        self.behavior_version = behavior_version;
754        self
755    }
756
757    /// Sets the service config provider for the [`SdkConfig`].
758    ///
759    /// This provider is used when creating a service-specific config from an
760    /// `SdkConfig` and provides access to config defined in the environment
761    /// which would otherwise be inaccessible.
762    pub fn service_config(mut self, service_config: impl LoadServiceConfig + 'static) -> Self {
763        self.set_service_config(Some(service_config));
764        self
765    }
766
767    /// Sets the service config provider for the [`SdkConfig`].
768    ///
769    /// This provider is used when creating a service-specific config from an
770    /// `SdkConfig` and provides access to config defined in the environment
771    /// which would otherwise be inaccessible.
772    pub fn set_service_config(
773        &mut self,
774        service_config: Option<impl LoadServiceConfig + 'static>,
775    ) -> &mut Self {
776        self.service_config = service_config.map(|it| Arc::new(it) as Arc<dyn LoadServiceConfig>);
777        self
778    }
779
780    /// Set the origin of a setting.
781    ///
782    /// This is used internally to understand how to merge config structs while
783    /// respecting precedence of origins.
784    pub fn insert_origin(&mut self, setting: &'static str, origin: Origin) {
785        self.config_origins.insert(setting, origin);
786    }
787
788    /// Build a [`SdkConfig`] from this builder.
789    pub fn build(self) -> SdkConfig {
790        SdkConfig {
791            app_name: self.app_name,
792            identity_cache: self.identity_cache,
793            credentials_provider: self.credentials_provider,
794            token_provider: self.token_provider,
795            region: self.region,
796            account_id_endpoint_mode: self.account_id_endpoint_mode,
797            endpoint_url: self.endpoint_url,
798            retry_config: self.retry_config,
799            sleep_impl: self.sleep_impl,
800            timeout_config: self.timeout_config,
801            http_client: self.http_client,
802            use_fips: self.use_fips,
803            use_dual_stack: self.use_dual_stack,
804            time_source: self.time_source,
805            behavior_version: self.behavior_version,
806            stalled_stream_protection_config: self.stalled_stream_protection_config,
807            service_config: self.service_config,
808            config_origins: self.config_origins,
809            disable_request_compression: self.disable_request_compression,
810            request_min_compression_size_bytes: self.request_min_compression_size_bytes,
811            request_checksum_calculation: self.request_checksum_calculation,
812            response_checksum_validation: self.response_checksum_validation,
813        }
814    }
815}
816
817impl Builder {
818    /// Set the [`StalledStreamProtectionConfig`] to configure protection for stalled streams.
819    ///
820    /// This configures stalled stream protection. When enabled, download streams
821    /// that stall (stream no data) for longer than a configured grace period will return an error.
822    ///
823    /// _Note:_ Stalled stream protection requires both a sleep implementation and a time source
824    /// in order to work. When enabling stalled stream protection, make sure to set
825    /// - A sleep impl with [Self::sleep_impl] or [Self::set_sleep_impl].
826    /// - A time source with [Self::time_source] or [Self::set_time_source].
827    ///
828    /// # Examples
829    /// ```rust
830    /// use std::time::Duration;
831    /// use aws_types::SdkConfig;
832    /// pub use aws_smithy_runtime_api::client::stalled_stream_protection::StalledStreamProtectionConfig;
833    ///
834    /// let stalled_stream_protection_config = StalledStreamProtectionConfig::enabled()
835    ///     .grace_period(Duration::from_secs(1))
836    ///     .build();
837    /// let config = SdkConfig::builder()
838    ///     .stalled_stream_protection(stalled_stream_protection_config)
839    ///     .build();
840    /// ```
841    pub fn stalled_stream_protection(
842        mut self,
843        stalled_stream_protection_config: StalledStreamProtectionConfig,
844    ) -> Self {
845        self.set_stalled_stream_protection(Some(stalled_stream_protection_config));
846        self
847    }
848
849    /// Set the [`StalledStreamProtectionConfig`] to configure protection for stalled streams.
850    ///
851    /// This configures stalled stream protection. When enabled, download streams
852    /// that stall (stream no data) for longer than a configured grace period will return an error.
853    ///
854    /// By default, streams that transmit less than one byte per-second for five seconds will
855    /// be cancelled.
856    ///
857    /// _Note:_ Stalled stream protection requires both a sleep implementation and a time source
858    /// in order to work. When enabling stalled stream protection, make sure to set
859    /// - A sleep impl with [Self::sleep_impl] or [Self::set_sleep_impl].
860    /// - A time source with [Self::time_source] or [Self::set_time_source].
861    ///
862    /// # Examples
863    /// ```rust
864    /// use std::time::Duration;
865    /// use aws_types::sdk_config::{SdkConfig, Builder};
866    /// pub use aws_smithy_runtime_api::client::stalled_stream_protection::StalledStreamProtectionConfig;
867    ///
868    /// fn set_stalled_stream_protection(builder: &mut Builder) {
869    ///     let stalled_stream_protection_config = StalledStreamProtectionConfig::enabled()
870    ///         .grace_period(Duration::from_secs(1))
871    ///         .build();
872    ///     builder.set_stalled_stream_protection(Some(stalled_stream_protection_config));
873    /// }
874    ///
875    /// let mut builder = SdkConfig::builder();
876    /// set_stalled_stream_protection(&mut builder);
877    /// let config = builder.build();
878    /// ```
879    pub fn set_stalled_stream_protection(
880        &mut self,
881        stalled_stream_protection_config: Option<StalledStreamProtectionConfig>,
882    ) -> &mut Self {
883        self.stalled_stream_protection_config = stalled_stream_protection_config;
884        self
885    }
886}
887
888impl SdkConfig {
889    /// Configured region
890    pub fn region(&self) -> Option<&Region> {
891        self.region.as_ref()
892    }
893
894    /// Configured account ID endpoint mode
895    pub fn account_id_endpoint_mode(&self) -> Option<&AccountIdEndpointMode> {
896        self.account_id_endpoint_mode.as_ref()
897    }
898
899    /// Configured endpoint URL
900    pub fn endpoint_url(&self) -> Option<&str> {
901        self.endpoint_url.as_deref()
902    }
903
904    /// Configured retry config
905    pub fn retry_config(&self) -> Option<&RetryConfig> {
906        self.retry_config.as_ref()
907    }
908
909    /// Configured timeout config
910    pub fn timeout_config(&self) -> Option<&TimeoutConfig> {
911        self.timeout_config.as_ref()
912    }
913
914    /// Configured sleep implementation
915    pub fn sleep_impl(&self) -> Option<SharedAsyncSleep> {
916        self.sleep_impl.clone()
917    }
918
919    /// Configured identity cache
920    pub fn identity_cache(&self) -> Option<SharedIdentityCache> {
921        self.identity_cache.clone()
922    }
923
924    /// Configured credentials provider
925    pub fn credentials_provider(&self) -> Option<SharedCredentialsProvider> {
926        self.credentials_provider.clone()
927    }
928
929    /// Configured bearer auth token provider
930    pub fn token_provider(&self) -> Option<SharedTokenProvider> {
931        self.token_provider.clone()
932    }
933
934    /// Configured time source
935    pub fn time_source(&self) -> Option<SharedTimeSource> {
936        self.time_source.clone()
937    }
938
939    /// Configured app name
940    pub fn app_name(&self) -> Option<&AppName> {
941        self.app_name.as_ref()
942    }
943
944    /// Configured HTTP client
945    pub fn http_client(&self) -> Option<SharedHttpClient> {
946        self.http_client.clone()
947    }
948
949    /// Use FIPS endpoints
950    pub fn use_fips(&self) -> Option<bool> {
951        self.use_fips
952    }
953
954    /// Use dual-stack endpoint
955    pub fn use_dual_stack(&self) -> Option<bool> {
956        self.use_dual_stack
957    }
958
959    /// When true, request compression is disabled.
960    pub fn disable_request_compression(&self) -> Option<bool> {
961        self.disable_request_compression
962    }
963
964    /// Configured checksum request behavior.
965    pub fn request_checksum_calculation(&self) -> Option<RequestChecksumCalculation> {
966        self.request_checksum_calculation
967    }
968
969    /// Configured checksum response behavior.
970    pub fn response_checksum_validation(&self) -> Option<ResponseChecksumValidation> {
971        self.response_checksum_validation
972    }
973
974    /// Configured minimum request compression size.
975    pub fn request_min_compression_size_bytes(&self) -> Option<u32> {
976        self.request_min_compression_size_bytes
977    }
978
979    /// Configured stalled stream protection
980    pub fn stalled_stream_protection(&self) -> Option<StalledStreamProtectionConfig> {
981        self.stalled_stream_protection_config.clone()
982    }
983
984    /// Behavior version configured for this client
985    pub fn behavior_version(&self) -> Option<BehaviorVersion> {
986        self.behavior_version
987    }
988
989    /// Return an immutable reference to the service config provider configured for this client.
990    pub fn service_config(&self) -> Option<&dyn LoadServiceConfig> {
991        self.service_config.as_deref()
992    }
993
994    /// Config builder
995    ///
996    /// _Important:_ Using the `aws-config` crate to configure the SDK is preferred to invoking this
997    /// builder directly. Using this builder directly won't pull in any AWS recommended default
998    /// configuration values.
999    pub fn builder() -> Builder {
1000        Builder::default()
1001    }
1002
1003    /// Convert this [`SdkConfig`] into a [`Builder`] by cloning it first
1004    pub fn to_builder(&self) -> Builder {
1005        self.clone().into_builder()
1006    }
1007
1008    /// Get the origin of a setting.
1009    ///
1010    /// This is used internally to understand how to merge config structs while
1011    /// respecting precedence of origins.
1012    pub fn get_origin(&self, setting: &'static str) -> Origin {
1013        self.config_origins
1014            .get(setting)
1015            .cloned()
1016            .unwrap_or_default()
1017    }
1018
1019    /// Convert this [`SdkConfig`] back to a builder to enable modification
1020    pub fn into_builder(self) -> Builder {
1021        Builder {
1022            app_name: self.app_name,
1023            identity_cache: self.identity_cache,
1024            credentials_provider: self.credentials_provider,
1025            token_provider: self.token_provider,
1026            region: self.region,
1027            account_id_endpoint_mode: self.account_id_endpoint_mode,
1028            endpoint_url: self.endpoint_url,
1029            retry_config: self.retry_config,
1030            sleep_impl: self.sleep_impl,
1031            time_source: self.time_source,
1032            timeout_config: self.timeout_config,
1033            http_client: self.http_client,
1034            use_fips: self.use_fips,
1035            use_dual_stack: self.use_dual_stack,
1036            behavior_version: self.behavior_version,
1037            stalled_stream_protection_config: self.stalled_stream_protection_config,
1038            service_config: self.service_config,
1039            config_origins: self.config_origins,
1040            disable_request_compression: self.disable_request_compression,
1041            request_min_compression_size_bytes: self.request_min_compression_size_bytes,
1042            request_checksum_calculation: self.request_checksum_calculation,
1043            response_checksum_validation: self.response_checksum_validation,
1044        }
1045    }
1046}