aws_smithy_runtime/client/
defaults.rs

1/*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! Runtime plugins that provide defaults for clients.
7//!
8//! Note: these are the absolute base-level defaults. They may not be the defaults
9//! for _your_ client, since many things can change these defaults on the way to
10//! code generating and constructing a full client.
11
12use crate::client::http::body::content_length_enforcement::EnforceContentLengthRuntimePlugin;
13use crate::client::identity::IdentityCache;
14use crate::client::retries::strategy::standard::TokenBucketProvider;
15use crate::client::retries::strategy::StandardRetryStrategy;
16use crate::client::retries::RetryPartition;
17use aws_smithy_async::rt::sleep::default_async_sleep;
18use aws_smithy_async::time::SystemTimeSource;
19use aws_smithy_runtime_api::box_error::BoxError;
20use aws_smithy_runtime_api::client::behavior_version::BehaviorVersion;
21use aws_smithy_runtime_api::client::http::SharedHttpClient;
22use aws_smithy_runtime_api::client::runtime_components::{
23    RuntimeComponentsBuilder, SharedConfigValidator,
24};
25use aws_smithy_runtime_api::client::runtime_plugin::{
26    Order, SharedRuntimePlugin, StaticRuntimePlugin,
27};
28use aws_smithy_runtime_api::client::stalled_stream_protection::StalledStreamProtectionConfig;
29use aws_smithy_runtime_api::shared::IntoShared;
30use aws_smithy_types::config_bag::{ConfigBag, FrozenLayer, Layer};
31use aws_smithy_types::retry::RetryConfig;
32use aws_smithy_types::timeout::TimeoutConfig;
33use std::borrow::Cow;
34use std::time::Duration;
35
36fn default_plugin<CompFn>(name: &'static str, components_fn: CompFn) -> StaticRuntimePlugin
37where
38    CompFn: FnOnce(RuntimeComponentsBuilder) -> RuntimeComponentsBuilder,
39{
40    StaticRuntimePlugin::new()
41        .with_order(Order::Defaults)
42        .with_runtime_components((components_fn)(RuntimeComponentsBuilder::new(name)))
43}
44
45fn layer<LayerFn>(name: &'static str, layer_fn: LayerFn) -> FrozenLayer
46where
47    LayerFn: FnOnce(&mut Layer),
48{
49    let mut layer = Layer::new(name);
50    (layer_fn)(&mut layer);
51    layer.freeze()
52}
53
54/// Runtime plugin that provides a default connector.
55#[deprecated(
56    since = "1.8.0",
57    note = "This function wasn't intended to be public, and didn't take the behavior major version as an argument, so it couldn't be evolved over time."
58)]
59pub fn default_http_client_plugin() -> Option<SharedRuntimePlugin> {
60    #[allow(deprecated)]
61    default_http_client_plugin_v2(BehaviorVersion::v2024_03_28())
62}
63
64/// Runtime plugin that provides a default HTTPS connector.
65pub fn default_http_client_plugin_v2(
66    behavior_version: BehaviorVersion,
67) -> Option<SharedRuntimePlugin> {
68    let mut _default: Option<SharedHttpClient> = None;
69
70    #[allow(deprecated)]
71    if behavior_version.is_at_least(BehaviorVersion::v2025_01_17()) {
72        // the latest https stack takes precedence if the config flag
73        // is enabled otherwise try to fall back to the legacy connector
74        // if that feature flag is available.
75        #[cfg(all(
76            feature = "connector-hyper-0-14-x",
77            not(feature = "default-https-client")
78        ))]
79        #[allow(deprecated)]
80        {
81            _default = crate::client::http::hyper_014::default_client();
82        }
83
84        // takes precedence over legacy connector if enabled
85        #[cfg(feature = "default-https-client")]
86        {
87            let opts = crate::client::http::DefaultClientOptions::default()
88                .with_behavior_version(behavior_version);
89            _default = crate::client::http::default_https_client(opts);
90        }
91    } else {
92        // fallback to legacy hyper client for given behavior version
93        #[cfg(feature = "connector-hyper-0-14-x")]
94        #[allow(deprecated)]
95        {
96            _default = crate::client::http::hyper_014::default_client();
97        }
98    }
99
100    _default.map(|default| {
101        default_plugin("default_http_client_plugin", |components| {
102            components.with_http_client(Some(default))
103        })
104        .into_shared()
105    })
106}
107
108/// Runtime plugin that provides a default async sleep implementation.
109pub fn default_sleep_impl_plugin() -> Option<SharedRuntimePlugin> {
110    default_async_sleep().map(|default| {
111        default_plugin("default_sleep_impl_plugin", |components| {
112            components.with_sleep_impl(Some(default))
113        })
114        .into_shared()
115    })
116}
117
118/// Runtime plugin that provides a default time source.
119pub fn default_time_source_plugin() -> Option<SharedRuntimePlugin> {
120    Some(
121        default_plugin("default_time_source_plugin", |components| {
122            components.with_time_source(Some(SystemTimeSource::new()))
123        })
124        .into_shared(),
125    )
126}
127
128/// Runtime plugin that sets the default retry strategy, config (disabled), and partition.
129pub fn default_retry_config_plugin(
130    default_partition_name: impl Into<Cow<'static, str>>,
131) -> Option<SharedRuntimePlugin> {
132    let retry_partition = RetryPartition::new(default_partition_name);
133    Some(
134        default_plugin("default_retry_config_plugin", |components| {
135            components
136                .with_retry_strategy(Some(StandardRetryStrategy::new()))
137                .with_config_validator(SharedConfigValidator::base_client_config_fn(
138                    validate_retry_config,
139                ))
140                .with_interceptor(TokenBucketProvider::new(retry_partition.clone()))
141        })
142        .with_config(layer("default_retry_config", |layer| {
143            layer.store_put(RetryConfig::disabled());
144            layer.store_put(retry_partition);
145        }))
146        .into_shared(),
147    )
148}
149
150fn validate_retry_config(
151    components: &RuntimeComponentsBuilder,
152    cfg: &ConfigBag,
153) -> Result<(), BoxError> {
154    if let Some(retry_config) = cfg.load::<RetryConfig>() {
155        if retry_config.has_retry() && components.sleep_impl().is_none() {
156            Err("An async sleep implementation is required for retry to work. Please provide a `sleep_impl` on \
157                 the config, or disable timeouts.".into())
158        } else {
159            Ok(())
160        }
161    } else {
162        Err(
163            "The default retry config was removed, and no other config was put in its place."
164                .into(),
165        )
166    }
167}
168
169/// Runtime plugin that sets the default timeout config (no timeouts).
170pub fn default_timeout_config_plugin() -> Option<SharedRuntimePlugin> {
171    Some(
172        default_plugin("default_timeout_config_plugin", |components| {
173            components.with_config_validator(SharedConfigValidator::base_client_config_fn(
174                validate_timeout_config,
175            ))
176        })
177        .with_config(layer("default_timeout_config", |layer| {
178            layer.store_put(
179                TimeoutConfig::builder()
180                    .connect_timeout(Duration::from_millis(3100))
181                    .build(),
182            );
183        }))
184        .into_shared(),
185    )
186}
187
188/// Runtime plugin that sets the default timeout config (no timeouts).
189pub fn default_timeout_config_plugin_v2() -> Option<SharedRuntimePlugin> {
190    Some(
191        default_plugin("default_timeout_config_plugin", |components| {
192            components.with_config_validator(SharedConfigValidator::base_client_config_fn(
193                validate_timeout_config,
194            ))
195        })
196        .with_config(layer("default_timeout_config", |layer| {
197            let timeout_config = if default_sleep_impl_plugin().is_some() {
198                TimeoutConfig::builder()
199                    .connect_timeout(Duration::from_millis(3100))
200                    .disable_operation_attempt_timeout()
201                    .disable_operation_timeout()
202                    .build()
203            } else {
204                TimeoutConfig::disabled()
205            };
206            layer.store_put(timeout_config);
207        }))
208        .into_shared(),
209    )
210}
211
212fn validate_timeout_config(
213    components: &RuntimeComponentsBuilder,
214    cfg: &ConfigBag,
215) -> Result<(), BoxError> {
216    if let Some(timeout_config) = cfg.load::<TimeoutConfig>() {
217        if timeout_config.has_timeouts() && components.sleep_impl().is_none() {
218            Err("An async sleep implementation is required for timeouts to work. Please provide a `sleep_impl` on \
219                 the config, or disable timeouts.".into())
220        } else {
221            Ok(())
222        }
223    } else {
224        Err(
225            "The default timeout config was removed, and no other config was put in its place."
226                .into(),
227        )
228    }
229}
230
231/// Runtime plugin that registers the default identity cache implementation.
232pub fn default_identity_cache_plugin() -> Option<SharedRuntimePlugin> {
233    Some(
234        default_plugin("default_identity_cache_plugin", |components| {
235            components.with_identity_cache(Some(IdentityCache::lazy().build()))
236        })
237        .into_shared(),
238    )
239}
240
241/// Runtime plugin that sets the default stalled stream protection config.
242///
243/// By default, when throughput falls below 1/Bs for more than 5 seconds, the
244/// stream is cancelled.
245#[deprecated(
246    since = "1.2.0",
247    note = "This function wasn't intended to be public, and didn't take the behavior major version as an argument, so it couldn't be evolved over time."
248)]
249pub fn default_stalled_stream_protection_config_plugin() -> Option<SharedRuntimePlugin> {
250    #[allow(deprecated)]
251    default_stalled_stream_protection_config_plugin_v2(BehaviorVersion::v2023_11_09())
252}
253fn default_stalled_stream_protection_config_plugin_v2(
254    behavior_version: BehaviorVersion,
255) -> Option<SharedRuntimePlugin> {
256    Some(
257        default_plugin(
258            "default_stalled_stream_protection_config_plugin",
259            |components| {
260                components.with_config_validator(SharedConfigValidator::base_client_config_fn(
261                    validate_stalled_stream_protection_config,
262                ))
263            },
264        )
265        .with_config(layer("default_stalled_stream_protection_config", |layer| {
266            let mut config =
267                StalledStreamProtectionConfig::enabled().grace_period(Duration::from_secs(5));
268            // Before v2024_03_28, upload streams did not have stalled stream protection by default
269            #[allow(deprecated)]
270            if !behavior_version.is_at_least(BehaviorVersion::v2024_03_28()) {
271                config = config.upload_enabled(false);
272            }
273            layer.store_put(config.build());
274        }))
275        .into_shared(),
276    )
277}
278
279fn enforce_content_length_runtime_plugin() -> Option<SharedRuntimePlugin> {
280    Some(EnforceContentLengthRuntimePlugin::new().into_shared())
281}
282
283fn validate_stalled_stream_protection_config(
284    components: &RuntimeComponentsBuilder,
285    cfg: &ConfigBag,
286) -> Result<(), BoxError> {
287    if let Some(stalled_stream_protection_config) = cfg.load::<StalledStreamProtectionConfig>() {
288        if stalled_stream_protection_config.is_enabled() {
289            if components.sleep_impl().is_none() {
290                return Err(
291                    "An async sleep implementation is required for stalled stream protection to work. \
292                     Please provide a `sleep_impl` on the config, or disable stalled stream protection.".into());
293            }
294
295            if components.time_source().is_none() {
296                return Err(
297                    "A time source is required for stalled stream protection to work.\
298                     Please provide a `time_source` on the config, or disable stalled stream protection.".into());
299            }
300        }
301
302        Ok(())
303    } else {
304        Err(
305            "The default stalled stream protection config was removed, and no other config was put in its place."
306                .into(),
307        )
308    }
309}
310
311/// Arguments for the [`default_plugins`] method.
312///
313/// This is a struct to enable adding new parameters in the future without breaking the API.
314#[non_exhaustive]
315#[derive(Debug, Default)]
316pub struct DefaultPluginParams {
317    retry_partition_name: Option<Cow<'static, str>>,
318    behavior_version: Option<BehaviorVersion>,
319}
320
321impl DefaultPluginParams {
322    /// Creates a new [`DefaultPluginParams`].
323    pub fn new() -> Self {
324        Default::default()
325    }
326
327    /// Sets the retry partition name.
328    pub fn with_retry_partition_name(mut self, name: impl Into<Cow<'static, str>>) -> Self {
329        self.retry_partition_name = Some(name.into());
330        self
331    }
332
333    /// Sets the behavior major version.
334    pub fn with_behavior_version(mut self, version: BehaviorVersion) -> Self {
335        self.behavior_version = Some(version);
336        self
337    }
338}
339
340/// All default plugins.
341pub fn default_plugins(
342    params: DefaultPluginParams,
343) -> impl IntoIterator<Item = SharedRuntimePlugin> {
344    let behavior_version = params
345        .behavior_version
346        .unwrap_or_else(BehaviorVersion::latest);
347
348    [
349        default_http_client_plugin_v2(behavior_version),
350        default_identity_cache_plugin(),
351        default_retry_config_plugin(
352            params
353                .retry_partition_name
354                .expect("retry_partition_name is required"),
355        ),
356        default_sleep_impl_plugin(),
357        default_time_source_plugin(),
358        default_timeout_config_plugin_v2(),
359        enforce_content_length_runtime_plugin(),
360        default_stalled_stream_protection_config_plugin_v2(behavior_version),
361    ]
362    .into_iter()
363    .flatten()
364    .collect::<Vec<SharedRuntimePlugin>>()
365}
366
367#[cfg(test)]
368mod tests {
369    use super::*;
370    use aws_smithy_runtime_api::client::runtime_plugin::RuntimePlugins;
371
372    fn test_plugin_params(version: BehaviorVersion) -> DefaultPluginParams {
373        DefaultPluginParams::new()
374            .with_behavior_version(version)
375            .with_retry_partition_name("dontcare")
376    }
377    fn config_for(plugins: impl IntoIterator<Item = SharedRuntimePlugin>) -> ConfigBag {
378        let mut config = ConfigBag::base();
379        let plugins = RuntimePlugins::new().with_client_plugins(plugins);
380        plugins.apply_client_configuration(&mut config).unwrap();
381        config
382    }
383
384    #[test]
385    #[allow(deprecated)]
386    fn v2024_03_28_stalled_stream_protection_difference() {
387        let latest = config_for(default_plugins(test_plugin_params(
388            BehaviorVersion::latest(),
389        )));
390        let v2023 = config_for(default_plugins(test_plugin_params(
391            BehaviorVersion::v2023_11_09(),
392        )));
393
394        assert!(
395            latest
396                .load::<StalledStreamProtectionConfig>()
397                .unwrap()
398                .upload_enabled(),
399            "stalled stream protection on uploads MUST be enabled after v2024_03_28"
400        );
401        assert!(
402            !v2023
403                .load::<StalledStreamProtectionConfig>()
404                .unwrap()
405                .upload_enabled(),
406            "stalled stream protection on uploads MUST NOT be enabled before v2024_03_28"
407        );
408    }
409}