aws_smithy_runtime/client/
defaults.rs1use 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#[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
64pub 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 #[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 #[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 #[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
108pub 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
118pub 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
128pub 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
150pub fn default_retry_config_plugin_v2(
155 params: &DefaultPluginParams,
156) -> Option<SharedRuntimePlugin> {
157 let default_partition_name = params.retry_partition_name.as_ref()?.clone();
158 let is_aws_sdk = params.is_aws_sdk;
159 let retry_partition = RetryPartition::new(default_partition_name);
160 Some(
161 default_plugin("default_retry_config_plugin", |components| {
162 components
163 .with_retry_strategy(Some(StandardRetryStrategy::new()))
164 .with_config_validator(SharedConfigValidator::base_client_config_fn(
165 validate_retry_config,
166 ))
167 .with_interceptor(TokenBucketProvider::new(retry_partition.clone()))
168 })
169 .with_config(layer("default_retry_config", |layer| {
170 let retry_config = if is_aws_sdk {
171 RetryConfig::standard()
172 } else {
173 RetryConfig::disabled()
174 };
175 layer.store_put(retry_config);
176 layer.store_put(retry_partition);
177 }))
178 .into_shared(),
179 )
180}
181
182fn validate_retry_config(
183 components: &RuntimeComponentsBuilder,
184 cfg: &ConfigBag,
185) -> Result<(), BoxError> {
186 if let Some(retry_config) = cfg.load::<RetryConfig>() {
187 if retry_config.has_retry() && components.sleep_impl().is_none() {
188 Err("An async sleep implementation is required for retry to work. Please provide a `sleep_impl` on \
189 the config, or disable timeouts.".into())
190 } else {
191 Ok(())
192 }
193 } else {
194 Err(
195 "The default retry config was removed, and no other config was put in its place."
196 .into(),
197 )
198 }
199}
200
201pub fn default_timeout_config_plugin() -> Option<SharedRuntimePlugin> {
203 Some(
204 default_plugin("default_timeout_config_plugin", |components| {
205 components.with_config_validator(SharedConfigValidator::base_client_config_fn(
206 validate_timeout_config,
207 ))
208 })
209 .with_config(layer("default_timeout_config", |layer| {
210 layer.store_put(TimeoutConfig::disabled());
211 }))
212 .into_shared(),
213 )
214}
215
216pub fn default_timeout_config_plugin_v2(
221 params: &DefaultPluginParams,
222) -> Option<SharedRuntimePlugin> {
223 let is_aws_sdk = params.is_aws_sdk;
224 Some(
225 default_plugin("default_timeout_config_plugin", |components| {
226 components.with_config_validator(SharedConfigValidator::base_client_config_fn(
227 validate_timeout_config,
228 ))
229 })
230 .with_config(layer("default_timeout_config", |layer| {
231 let timeout_config = if is_aws_sdk {
232 TimeoutConfig::builder()
234 .connect_timeout(Duration::from_millis(3100))
235 .build()
236 } else {
237 TimeoutConfig::disabled()
239 };
240 layer.store_put(timeout_config);
241 }))
242 .into_shared(),
243 )
244}
245
246fn validate_timeout_config(
247 components: &RuntimeComponentsBuilder,
248 cfg: &ConfigBag,
249) -> Result<(), BoxError> {
250 if let Some(timeout_config) = cfg.load::<TimeoutConfig>() {
251 if timeout_config.has_timeouts() && components.sleep_impl().is_none() {
252 Err("An async sleep implementation is required for timeouts to work. Please provide a `sleep_impl` on \
253 the config, or disable timeouts.".into())
254 } else {
255 Ok(())
256 }
257 } else {
258 Err(
259 "The default timeout config was removed, and no other config was put in its place."
260 .into(),
261 )
262 }
263}
264
265pub fn default_identity_cache_plugin() -> Option<SharedRuntimePlugin> {
267 Some(
268 default_plugin("default_identity_cache_plugin", |components| {
269 components.with_identity_cache(Some(IdentityCache::lazy().build()))
270 })
271 .into_shared(),
272 )
273}
274
275#[deprecated(
280 since = "1.2.0",
281 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."
282)]
283pub fn default_stalled_stream_protection_config_plugin() -> Option<SharedRuntimePlugin> {
284 #[allow(deprecated)]
285 default_stalled_stream_protection_config_plugin_v2(BehaviorVersion::v2023_11_09())
286}
287fn default_stalled_stream_protection_config_plugin_v2(
288 behavior_version: BehaviorVersion,
289) -> Option<SharedRuntimePlugin> {
290 Some(
291 default_plugin(
292 "default_stalled_stream_protection_config_plugin",
293 |components| {
294 components.with_config_validator(SharedConfigValidator::base_client_config_fn(
295 validate_stalled_stream_protection_config,
296 ))
297 },
298 )
299 .with_config(layer("default_stalled_stream_protection_config", |layer| {
300 let mut config =
301 StalledStreamProtectionConfig::enabled().grace_period(Duration::from_secs(5));
302 #[allow(deprecated)]
304 if !behavior_version.is_at_least(BehaviorVersion::v2024_03_28()) {
305 config = config.upload_enabled(false);
306 }
307 layer.store_put(config.build());
308 }))
309 .into_shared(),
310 )
311}
312
313fn enforce_content_length_runtime_plugin() -> Option<SharedRuntimePlugin> {
314 Some(EnforceContentLengthRuntimePlugin::new().into_shared())
315}
316
317fn validate_stalled_stream_protection_config(
318 components: &RuntimeComponentsBuilder,
319 cfg: &ConfigBag,
320) -> Result<(), BoxError> {
321 if let Some(stalled_stream_protection_config) = cfg.load::<StalledStreamProtectionConfig>() {
322 if stalled_stream_protection_config.is_enabled() {
323 if components.sleep_impl().is_none() {
324 return Err(
325 "An async sleep implementation is required for stalled stream protection to work. \
326 Please provide a `sleep_impl` on the config, or disable stalled stream protection.".into());
327 }
328
329 if components.time_source().is_none() {
330 return Err(
331 "A time source is required for stalled stream protection to work.\
332 Please provide a `time_source` on the config, or disable stalled stream protection.".into());
333 }
334 }
335
336 Ok(())
337 } else {
338 Err(
339 "The default stalled stream protection config was removed, and no other config was put in its place."
340 .into(),
341 )
342 }
343}
344
345#[non_exhaustive]
349#[derive(Debug, Default)]
350pub struct DefaultPluginParams {
351 retry_partition_name: Option<Cow<'static, str>>,
352 behavior_version: Option<BehaviorVersion>,
353 is_aws_sdk: bool,
354}
355
356impl DefaultPluginParams {
357 pub fn new() -> Self {
359 Default::default()
360 }
361
362 pub fn with_retry_partition_name(mut self, name: impl Into<Cow<'static, str>>) -> Self {
364 self.retry_partition_name = Some(name.into());
365 self
366 }
367
368 pub fn with_behavior_version(mut self, version: BehaviorVersion) -> Self {
370 self.behavior_version = Some(version);
371 self
372 }
373
374 pub fn with_is_aws_sdk(mut self, is_aws_sdk: bool) -> Self {
376 self.is_aws_sdk = is_aws_sdk;
377 self
378 }
379}
380
381pub fn default_plugins(
383 params: DefaultPluginParams,
384) -> impl IntoIterator<Item = SharedRuntimePlugin> {
385 let behavior_version = params
386 .behavior_version
387 .unwrap_or_else(BehaviorVersion::latest);
388
389 [
390 default_http_client_plugin_v2(behavior_version),
391 default_identity_cache_plugin(),
392 default_retry_config_plugin_v2(¶ms),
393 default_sleep_impl_plugin(),
394 default_time_source_plugin(),
395 default_timeout_config_plugin_v2(¶ms),
396 enforce_content_length_runtime_plugin(),
397 default_stalled_stream_protection_config_plugin_v2(behavior_version),
398 ]
399 .into_iter()
400 .flatten()
401 .collect::<Vec<SharedRuntimePlugin>>()
402}
403
404#[cfg(test)]
405mod tests {
406 use super::*;
407 use aws_smithy_runtime_api::client::runtime_plugin::{RuntimePlugin, RuntimePlugins};
408
409 fn test_plugin_params(version: BehaviorVersion) -> DefaultPluginParams {
410 DefaultPluginParams::new()
411 .with_behavior_version(version)
412 .with_retry_partition_name("dontcare")
413 .with_is_aws_sdk(false) }
415 fn config_for(plugins: impl IntoIterator<Item = SharedRuntimePlugin>) -> ConfigBag {
416 let mut config = ConfigBag::base();
417 let plugins = RuntimePlugins::new().with_client_plugins(plugins);
418 plugins.apply_client_configuration(&mut config).unwrap();
419 config
420 }
421
422 #[test]
423 #[allow(deprecated)]
424 fn v2024_03_28_stalled_stream_protection_difference() {
425 let latest = config_for(default_plugins(test_plugin_params(
426 BehaviorVersion::latest(),
427 )));
428 let v2023 = config_for(default_plugins(test_plugin_params(
429 BehaviorVersion::v2023_11_09(),
430 )));
431
432 assert!(
433 latest
434 .load::<StalledStreamProtectionConfig>()
435 .unwrap()
436 .upload_enabled(),
437 "stalled stream protection on uploads MUST be enabled after v2024_03_28"
438 );
439 assert!(
440 !v2023
441 .load::<StalledStreamProtectionConfig>()
442 .unwrap()
443 .upload_enabled(),
444 "stalled stream protection on uploads MUST NOT be enabled before v2024_03_28"
445 );
446 }
447
448 #[test]
449 fn test_retry_enabled_for_aws_sdk() {
450 let params = DefaultPluginParams::new()
451 .with_retry_partition_name("test-partition")
452 .with_is_aws_sdk(true);
453 let plugin = default_retry_config_plugin_v2(¶ms)
454 .expect("plugin should be created");
455
456 let config = plugin.config().expect("config should exist");
457 let retry_config = config
458 .load::<RetryConfig>()
459 .expect("retry config should exist");
460
461 assert_eq!(
462 retry_config.max_attempts(),
463 3,
464 "retries should be enabled with max_attempts=3 for AWS SDK"
465 );
466 }
467
468 #[test]
469 fn test_retry_disabled_for_non_aws_sdk() {
470 let params = DefaultPluginParams::new()
471 .with_retry_partition_name("test-partition")
472 .with_is_aws_sdk(false);
473 let plugin = default_retry_config_plugin_v2(¶ms)
474 .expect("plugin should be created");
475
476 let config = plugin.config().expect("config should exist");
477 let retry_config = config
478 .load::<RetryConfig>()
479 .expect("retry config should exist");
480
481 assert_eq!(
482 retry_config.max_attempts(),
483 1,
484 "retries should be disabled for non-AWS SDK clients"
485 );
486 }
487}