aws_sdk_s3/operation/
put_object.rs

1// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
2/// Orchestration and serialization glue logic for `PutObject`.
3#[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)]
4#[non_exhaustive]
5pub struct PutObject;
6impl PutObject {
7    /// Creates a new `PutObject`
8    pub fn new() -> Self {
9        Self
10    }
11    pub(crate) async fn orchestrate(
12        runtime_plugins: &::aws_smithy_runtime_api::client::runtime_plugin::RuntimePlugins,
13        input: crate::operation::put_object::PutObjectInput,
14    ) -> ::std::result::Result<
15        crate::operation::put_object::PutObjectOutput,
16        ::aws_smithy_runtime_api::client::result::SdkError<
17            crate::operation::put_object::PutObjectError,
18            ::aws_smithy_runtime_api::client::orchestrator::HttpResponse,
19        >,
20    > {
21        let map_err = |err: ::aws_smithy_runtime_api::client::result::SdkError<
22            ::aws_smithy_runtime_api::client::interceptors::context::Error,
23            ::aws_smithy_runtime_api::client::orchestrator::HttpResponse,
24        >| {
25            err.map_service_error(|err| {
26                err.downcast::<crate::operation::put_object::PutObjectError>()
27                    .expect("correct error type")
28            })
29        };
30        let context = Self::orchestrate_with_stop_point(runtime_plugins, input, ::aws_smithy_runtime::client::orchestrator::StopPoint::None)
31            .await
32            .map_err(map_err)?;
33        let output = context.finalize().map_err(map_err)?;
34        ::std::result::Result::Ok(
35            output
36                .downcast::<crate::operation::put_object::PutObjectOutput>()
37                .expect("correct output type"),
38        )
39    }
40
41    pub(crate) async fn orchestrate_with_stop_point(
42        runtime_plugins: &::aws_smithy_runtime_api::client::runtime_plugin::RuntimePlugins,
43        input: crate::operation::put_object::PutObjectInput,
44        stop_point: ::aws_smithy_runtime::client::orchestrator::StopPoint,
45    ) -> ::std::result::Result<
46        ::aws_smithy_runtime_api::client::interceptors::context::InterceptorContext,
47        ::aws_smithy_runtime_api::client::result::SdkError<
48            ::aws_smithy_runtime_api::client::interceptors::context::Error,
49            ::aws_smithy_runtime_api::client::orchestrator::HttpResponse,
50        >,
51    > {
52        let input = ::aws_smithy_runtime_api::client::interceptors::context::Input::erase(input);
53        ::aws_smithy_runtime::client::orchestrator::invoke_with_stop_point("s3", "PutObject", input, runtime_plugins, stop_point).await
54    }
55
56    pub(crate) fn operation_runtime_plugins(
57        client_runtime_plugins: ::aws_smithy_runtime_api::client::runtime_plugin::RuntimePlugins,
58        client_config: &crate::config::Config,
59        config_override: ::std::option::Option<crate::config::Builder>,
60    ) -> ::aws_smithy_runtime_api::client::runtime_plugin::RuntimePlugins {
61        let mut runtime_plugins = client_runtime_plugins.with_operation_plugin(Self::new());
62        runtime_plugins = runtime_plugins.with_client_plugin(crate::auth_plugin::DefaultAuthOptionsPlugin::new(vec![
63            ::aws_runtime::auth::sigv4::SCHEME_ID,
64            #[cfg(feature = "sigv4a")]
65            {
66                ::aws_runtime::auth::sigv4a::SCHEME_ID
67            },
68            crate::s3_express::auth::SCHEME_ID,
69            ::aws_smithy_runtime::client::auth::no_auth::NO_AUTH_SCHEME_ID,
70        ]));
71        if let ::std::option::Option::Some(config_override) = config_override {
72            for plugin in config_override.runtime_plugins.iter().cloned() {
73                runtime_plugins = runtime_plugins.with_operation_plugin(plugin);
74            }
75            runtime_plugins = runtime_plugins.with_operation_plugin(crate::config::ConfigOverrideRuntimePlugin::new(
76                config_override,
77                client_config.config.clone(),
78                &client_config.runtime_components,
79            ));
80        }
81        runtime_plugins
82    }
83}
84impl ::aws_smithy_runtime_api::client::runtime_plugin::RuntimePlugin for PutObject {
85    fn config(&self) -> ::std::option::Option<::aws_smithy_types::config_bag::FrozenLayer> {
86        let mut cfg = ::aws_smithy_types::config_bag::Layer::new("PutObject");
87
88        cfg.store_put(::aws_smithy_runtime_api::client::ser_de::SharedRequestSerializer::new(
89            PutObjectRequestSerializer,
90        ));
91        cfg.store_put(::aws_smithy_runtime_api::client::ser_de::SharedResponseDeserializer::new(
92            PutObjectResponseDeserializer,
93        ));
94
95        cfg.store_put(::aws_smithy_runtime_api::client::auth::AuthSchemeOptionResolverParams::new(
96            ::aws_smithy_runtime_api::client::auth::static_resolver::StaticAuthSchemeOptionResolverParams::new(),
97        ));
98
99        cfg.store_put(::aws_smithy_runtime_api::client::orchestrator::SensitiveOutput);
100        cfg.store_put(::aws_smithy_runtime_api::client::orchestrator::Metadata::new("PutObject", "s3"));
101        let mut signing_options = ::aws_runtime::auth::SigningOptions::default();
102        signing_options.double_uri_encode = false;
103        signing_options.content_sha256_header = true;
104        signing_options.normalize_uri_path = false;
105        signing_options.payload_override = None;
106
107        cfg.store_put(::aws_runtime::auth::SigV4OperationSigningConfig {
108            signing_options,
109            ..::std::default::Default::default()
110        });
111
112        ::std::option::Option::Some(cfg.freeze())
113    }
114
115    fn runtime_components(
116        &self,
117        _: &::aws_smithy_runtime_api::client::runtime_components::RuntimeComponentsBuilder,
118    ) -> ::std::borrow::Cow<'_, ::aws_smithy_runtime_api::client::runtime_components::RuntimeComponentsBuilder> {
119        #[allow(unused_mut)]
120        let mut rcb = ::aws_smithy_runtime_api::client::runtime_components::RuntimeComponentsBuilder::new("PutObject")
121            .with_interceptor(::aws_smithy_runtime::client::stalled_stream_protection::StalledStreamProtectionInterceptor::default())
122            .with_interceptor(PutObjectEndpointParamsInterceptor)
123            .with_interceptor(crate::http_request_checksum::RequestChecksumInterceptor::new(
124                |input: &::aws_smithy_runtime_api::client::interceptors::context::Input| {
125                    let input: &crate::operation::put_object::PutObjectInput = input.downcast_ref().expect("correct type");
126                    let checksum_algorithm = input.checksum_algorithm();
127                    let checksum_algorithm = checksum_algorithm.map(|algorithm| algorithm.as_str());
128                    let checksum_algorithm = match checksum_algorithm {
129                        Some(algo) => Some(
130                            algo.parse::<::aws_smithy_checksums::ChecksumAlgorithm>()
131                                .map_err(::aws_smithy_types::error::operation::BuildError::other)?,
132                        ),
133                        None => None,
134                    };
135                    ::std::result::Result::<_, ::aws_smithy_runtime_api::box_error::BoxError>::Ok(checksum_algorithm)
136                },
137            ))
138            .with_retry_classifier(::aws_smithy_runtime::client::retries::classifiers::TransientErrorClassifier::<
139                crate::operation::put_object::PutObjectError,
140            >::new())
141            .with_retry_classifier(::aws_smithy_runtime::client::retries::classifiers::ModeledAsRetryableClassifier::<
142                crate::operation::put_object::PutObjectError,
143            >::new())
144            .with_retry_classifier(::aws_runtime::retries::classifiers::AwsErrorCodeClassifier::<
145                crate::operation::put_object::PutObjectError,
146            >::new());
147
148        ::std::borrow::Cow::Owned(rcb)
149    }
150}
151
152#[derive(Debug)]
153struct PutObjectResponseDeserializer;
154impl ::aws_smithy_runtime_api::client::ser_de::DeserializeResponse for PutObjectResponseDeserializer {
155    fn deserialize_nonstreaming(
156        &self,
157        response: &::aws_smithy_runtime_api::client::orchestrator::HttpResponse,
158    ) -> ::aws_smithy_runtime_api::client::interceptors::context::OutputOrError {
159        let (success, status) = (response.status().is_success(), response.status().as_u16());
160        let headers = response.headers();
161        let body = response.body().bytes().expect("body loaded");
162        #[allow(unused_mut)]
163        let mut force_error = false;
164        ::tracing::debug!(extended_request_id = ?crate::s3_request_id::RequestIdExt::extended_request_id(response));
165        if matches!(crate::rest_xml_unwrapped_errors::body_is_error(body), Ok(true)) {
166            force_error = true;
167        }
168        ::tracing::debug!(request_id = ?::aws_types::request_id::RequestId::request_id(response));
169        let parse_result = if !success && status != 200 || force_error {
170            crate::protocol_serde::shape_put_object::de_put_object_http_error(status, headers, body)
171        } else {
172            crate::protocol_serde::shape_put_object::de_put_object_http_response(status, headers, body)
173        };
174        crate::protocol_serde::type_erase_result(parse_result)
175    }
176}
177#[derive(Debug)]
178struct PutObjectRequestSerializer;
179impl ::aws_smithy_runtime_api::client::ser_de::SerializeRequest for PutObjectRequestSerializer {
180    #[allow(unused_mut, clippy::let_and_return, clippy::needless_borrow, clippy::useless_conversion)]
181    fn serialize_input(
182        &self,
183        input: ::aws_smithy_runtime_api::client::interceptors::context::Input,
184        _cfg: &mut ::aws_smithy_types::config_bag::ConfigBag,
185    ) -> ::std::result::Result<::aws_smithy_runtime_api::client::orchestrator::HttpRequest, ::aws_smithy_runtime_api::box_error::BoxError> {
186        let input = input.downcast::<crate::operation::put_object::PutObjectInput>().expect("correct type");
187        let _header_serialization_settings = _cfg
188            .load::<crate::serialization_settings::HeaderSerializationSettings>()
189            .cloned()
190            .unwrap_or_default();
191        let mut request_builder = {
192            fn uri_base(
193                _input: &crate::operation::put_object::PutObjectInput,
194                output: &mut ::std::string::String,
195            ) -> ::std::result::Result<(), ::aws_smithy_types::error::operation::BuildError> {
196                use ::std::fmt::Write as _;
197                let input_1 = &_input.key;
198                let input_1 = input_1
199                    .as_ref()
200                    .ok_or_else(|| ::aws_smithy_types::error::operation::BuildError::missing_field("key", "cannot be empty or unset"))?;
201                let key = ::aws_smithy_http::label::fmt_string(input_1, ::aws_smithy_http::label::EncodingStrategy::Greedy);
202                if key.is_empty() {
203                    return ::std::result::Result::Err(::aws_smithy_types::error::operation::BuildError::missing_field(
204                        "key",
205                        "cannot be empty or unset",
206                    ));
207                }
208                ::std::write!(output, "/{Key}", Key = key).expect("formatting should succeed");
209                ::std::result::Result::Ok(())
210            }
211            fn uri_query(
212                _input: &crate::operation::put_object::PutObjectInput,
213                mut output: &mut ::std::string::String,
214            ) -> ::std::result::Result<(), ::aws_smithy_types::error::operation::BuildError> {
215                let mut query = ::aws_smithy_http::query::Writer::new(output);
216                query.push_kv("x-id", "PutObject");
217                ::std::result::Result::Ok(())
218            }
219            #[allow(clippy::unnecessary_wraps)]
220            fn update_http_builder(
221                input: &crate::operation::put_object::PutObjectInput,
222                builder: ::http::request::Builder,
223            ) -> ::std::result::Result<::http::request::Builder, ::aws_smithy_types::error::operation::BuildError> {
224                let mut uri = ::std::string::String::new();
225                uri_base(input, &mut uri)?;
226                uri_query(input, &mut uri)?;
227                let builder = crate::protocol_serde::shape_put_object::ser_put_object_headers(input, builder)?;
228                ::std::result::Result::Ok(builder.method("PUT").uri(uri))
229            }
230            let mut builder = update_http_builder(&input, ::http::request::Builder::new())?;
231            builder = _header_serialization_settings.set_default_header(builder, ::http::header::CONTENT_TYPE, "application/octet-stream");
232            builder
233        };
234        let body = crate::protocol_serde::shape_put_object_input::ser_body_http_payload(input.body)?.into_inner();
235        if let Some(content_length) = body.content_length() {
236            let content_length = content_length.to_string();
237            request_builder = _header_serialization_settings.set_default_header(request_builder, ::http::header::CONTENT_LENGTH, &content_length);
238        }
239        ::std::result::Result::Ok(request_builder.body(body).expect("valid request").try_into().unwrap())
240    }
241}
242#[derive(Debug)]
243struct PutObjectEndpointParamsInterceptor;
244
245impl ::aws_smithy_runtime_api::client::interceptors::Intercept for PutObjectEndpointParamsInterceptor {
246    fn name(&self) -> &'static str {
247        "PutObjectEndpointParamsInterceptor"
248    }
249
250    fn read_before_execution(
251        &self,
252        context: &::aws_smithy_runtime_api::client::interceptors::context::BeforeSerializationInterceptorContextRef<
253            '_,
254            ::aws_smithy_runtime_api::client::interceptors::context::Input,
255            ::aws_smithy_runtime_api::client::interceptors::context::Output,
256            ::aws_smithy_runtime_api::client::interceptors::context::Error,
257        >,
258        cfg: &mut ::aws_smithy_types::config_bag::ConfigBag,
259    ) -> ::std::result::Result<(), ::aws_smithy_runtime_api::box_error::BoxError> {
260        let _input = context
261            .input()
262            .downcast_ref::<PutObjectInput>()
263            .ok_or("failed to downcast to PutObjectInput")?;
264
265        let params = crate::config::endpoint::Params::builder()
266            .set_region(cfg.load::<::aws_types::region::Region>().map(|r| r.as_ref().to_owned()))
267            .set_use_fips(cfg.load::<::aws_types::endpoint_config::UseFips>().map(|ty| ty.0))
268            .set_use_dual_stack(cfg.load::<::aws_types::endpoint_config::UseDualStack>().map(|ty| ty.0))
269            .set_endpoint(cfg.load::<::aws_types::endpoint_config::EndpointUrl>().map(|ty| ty.0.clone()))
270            .set_force_path_style(cfg.load::<crate::config::ForcePathStyle>().map(|ty| ty.0))
271            .set_use_arn_region(cfg.load::<crate::config::UseArnRegion>().map(|ty| ty.0))
272            .set_disable_multi_region_access_points(cfg.load::<crate::config::DisableMultiRegionAccessPoints>().map(|ty| ty.0))
273            .set_accelerate(cfg.load::<crate::config::Accelerate>().map(|ty| ty.0))
274            .set_disable_s3_express_session_auth(cfg.load::<crate::config::DisableS3ExpressSessionAuth>().map(|ty| ty.0))
275            .set_bucket(Some(
276                _input
277                    .bucket
278                    .clone()
279                    .filter(|f| !AsRef::<str>::as_ref(f).trim().is_empty())
280                    .ok_or_else(|| ::aws_smithy_types::error::operation::BuildError::missing_field("bucket", "A required field was not set"))?,
281            ))
282            .set_key(Some(
283                _input
284                    .key
285                    .clone()
286                    .filter(|f| !AsRef::<str>::as_ref(f).trim().is_empty())
287                    .ok_or_else(|| ::aws_smithy_types::error::operation::BuildError::missing_field("key", "A required field was not set"))?,
288            ))
289            .build()
290            .map_err(|err| {
291                ::aws_smithy_runtime_api::client::interceptors::error::ContextAttachedError::new("endpoint params could not be built", err)
292            })?;
293        cfg.interceptor_state()
294            .store_put(::aws_smithy_runtime_api::client::endpoint::EndpointResolverParams::new(params));
295        ::std::result::Result::Ok(())
296    }
297}
298#[allow(unreachable_code, unused_variables)]
299#[cfg(test)]
300mod put_object_request_test {
301    /// This test validates that if a content-type is specified, that only one content-type header is sent
302    /// Test ID: DontSendDuplicateContentType
303    #[::tokio::test]
304    #[allow(unused_mut)]
305    async fn dont_send_duplicate_content_type_request() {
306        let (http_client, request_receiver) = ::aws_smithy_runtime::client::http::test_util::capture_request(None);
307        let config_builder = crate::config::Config::builder().with_test_defaults().endpoint_url("https://example.com");
308        let config_builder = config_builder.region(::aws_types::region::Region::new("us-east-1"));
309        let mut config_builder = config_builder;
310        config_builder.set_region(Some(crate::config::Region::new("us-east-1")));
311
312        let config = config_builder.http_client(http_client).build();
313        let client = crate::Client::from_conf(config);
314        let result = client
315            .put_object()
316            .set_bucket(::std::option::Option::Some("test-bucket".to_owned()))
317            .set_key(::std::option::Option::Some("test-key".to_owned()))
318            .set_content_type(::std::option::Option::Some("text/html".to_owned()))
319            .send()
320            .await;
321        let _ = dbg!(result);
322        let http_request = request_receiver.expect_request();
323        let expected_headers = [("content-type", "text/html")];
324        ::aws_smithy_protocol_test::assert_ok(::aws_smithy_protocol_test::validate_headers(http_request.headers(), expected_headers));
325        let uri: ::http::Uri = http_request.uri().parse().expect("invalid URI sent");
326        ::pretty_assertions::assert_eq!(http_request.method(), "PUT", "method was incorrect");
327        ::pretty_assertions::assert_eq!(uri.path(), "/test-key", "path was incorrect");
328    }
329    /// This test validates that if a content-length is specified, that only one content-length header is sent
330    /// Test ID: DontSendDuplicateContentLength
331    #[::tokio::test]
332    #[allow(unused_mut)]
333    async fn dont_send_duplicate_content_length_request() {
334        let (http_client, request_receiver) = ::aws_smithy_runtime::client::http::test_util::capture_request(None);
335        let config_builder = crate::config::Config::builder().with_test_defaults().endpoint_url("https://example.com");
336        let config_builder = config_builder.region(::aws_types::region::Region::new("us-east-1"));
337        let mut config_builder = config_builder;
338        config_builder.set_region(Some(crate::config::Region::new("us-east-1")));
339
340        let config = config_builder.http_client(http_client).build();
341        let client = crate::Client::from_conf(config);
342        let result = client
343            .put_object()
344            .set_bucket(::std::option::Option::Some("test-bucket".to_owned()))
345            .set_key(::std::option::Option::Some("test-key".to_owned()))
346            .set_content_length(::std::option::Option::Some(2))
347            .set_body(::std::option::Option::Some(::aws_smithy_types::byte_stream::ByteStream::from_static(
348                b"ab",
349            )))
350            .send()
351            .await;
352        let _ = dbg!(result);
353        let http_request = request_receiver.expect_request();
354        let expected_headers = [("content-length", "2")];
355        ::aws_smithy_protocol_test::assert_ok(::aws_smithy_protocol_test::validate_headers(http_request.headers(), expected_headers));
356        let uri: ::http::Uri = http_request.uri().parse().expect("invalid URI sent");
357        ::pretty_assertions::assert_eq!(http_request.method(), "PUT", "method was incorrect");
358        ::pretty_assertions::assert_eq!(uri.path(), "/test-key", "path was incorrect");
359    }
360}
361
362/// Error type for the `PutObjectError` operation.
363#[non_exhaustive]
364#[derive(::std::fmt::Debug)]
365pub enum PutObjectError {
366    /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unknown error code).
367    #[deprecated(note = "Matching `Unhandled` directly is not forwards compatible. Instead, match using a \
368    variable wildcard pattern and check `.code()`:
369     \
370    &nbsp;&nbsp;&nbsp;`err if err.code() == Some(\"SpecificExceptionCode\") => { /* handle the error */ }`
371     \
372    See [`ProvideErrorMetadata`](#impl-ProvideErrorMetadata-for-PutObjectError) for what information is available for the error.")]
373    Unhandled(crate::error::sealed_unhandled::Unhandled),
374}
375impl PutObjectError {
376    /// Creates the `PutObjectError::Unhandled` variant from any error type.
377    pub fn unhandled(
378        err: impl ::std::convert::Into<::std::boxed::Box<dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static>>,
379    ) -> Self {
380        Self::Unhandled(crate::error::sealed_unhandled::Unhandled {
381            source: err.into(),
382            meta: ::std::default::Default::default(),
383        })
384    }
385
386    /// Creates the `PutObjectError::Unhandled` variant from an [`ErrorMetadata`](::aws_smithy_types::error::ErrorMetadata).
387    pub fn generic(err: ::aws_smithy_types::error::ErrorMetadata) -> Self {
388        Self::Unhandled(crate::error::sealed_unhandled::Unhandled {
389            source: err.clone().into(),
390            meta: err,
391        })
392    }
393    ///
394    /// Returns error metadata, which includes the error code, message,
395    /// request ID, and potentially additional information.
396    ///
397    pub fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata {
398        match self {
399            Self::Unhandled(e) => &e.meta,
400        }
401    }
402}
403impl ::std::error::Error for PutObjectError {
404    fn source(&self) -> ::std::option::Option<&(dyn ::std::error::Error + 'static)> {
405        match self {
406            Self::Unhandled(_inner) => ::std::option::Option::Some(&*_inner.source),
407        }
408    }
409}
410impl ::std::fmt::Display for PutObjectError {
411    fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
412        match self {
413            Self::Unhandled(_inner) => {
414                if let ::std::option::Option::Some(code) = ::aws_smithy_types::error::metadata::ProvideErrorMetadata::code(self) {
415                    write!(f, "unhandled error ({code})")
416                } else {
417                    f.write_str("unhandled error")
418                }
419            }
420        }
421    }
422}
423impl ::aws_smithy_types::retry::ProvideErrorKind for PutObjectError {
424    fn code(&self) -> ::std::option::Option<&str> {
425        ::aws_smithy_types::error::metadata::ProvideErrorMetadata::code(self)
426    }
427    fn retryable_error_kind(&self) -> ::std::option::Option<::aws_smithy_types::retry::ErrorKind> {
428        ::std::option::Option::None
429    }
430}
431impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for PutObjectError {
432    fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata {
433        match self {
434            Self::Unhandled(_inner) => &_inner.meta,
435        }
436    }
437}
438impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for PutObjectError {
439    fn create_unhandled_error(
440        source: ::std::boxed::Box<dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static>,
441        meta: ::std::option::Option<::aws_smithy_types::error::ErrorMetadata>,
442    ) -> Self {
443        Self::Unhandled(crate::error::sealed_unhandled::Unhandled {
444            source,
445            meta: meta.unwrap_or_default(),
446        })
447    }
448}
449impl crate::s3_request_id::RequestIdExt for crate::operation::put_object::PutObjectError {
450    fn extended_request_id(&self) -> Option<&str> {
451        self.meta().extended_request_id()
452    }
453}
454impl ::aws_types::request_id::RequestId for crate::operation::put_object::PutObjectError {
455    fn request_id(&self) -> Option<&str> {
456        self.meta().request_id()
457    }
458}
459
460pub use crate::operation::put_object::_put_object_output::PutObjectOutput;
461
462pub use crate::operation::put_object::_put_object_input::PutObjectInput;
463
464mod _put_object_input;
465
466mod _put_object_output;
467
468/// Builders
469pub mod builders;