aws_sdk_s3/operation/
get_object.rs

1// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
2/// Orchestration and serialization glue logic for `GetObject`.
3#[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)]
4#[non_exhaustive]
5pub struct GetObject;
6impl GetObject {
7    /// Creates a new `GetObject`
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::get_object::GetObjectInput,
14    ) -> ::std::result::Result<
15        crate::operation::get_object::GetObjectOutput,
16        ::aws_smithy_runtime_api::client::result::SdkError<
17            crate::operation::get_object::GetObjectError,
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::get_object::GetObjectError>()
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::get_object::GetObjectOutput>()
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::get_object::GetObjectInput,
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", "GetObject", 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 GetObject {
85    fn config(&self) -> ::std::option::Option<::aws_smithy_types::config_bag::FrozenLayer> {
86        let mut cfg = ::aws_smithy_types::config_bag::Layer::new("GetObject");
87
88        cfg.store_put(::aws_smithy_runtime_api::client::ser_de::SharedRequestSerializer::new(
89            GetObjectRequestSerializer,
90        ));
91        cfg.store_put(::aws_smithy_runtime_api::client::ser_de::SharedResponseDeserializer::new(
92            GetObjectResponseDeserializer,
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("GetObject", "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("GetObject")
121            .with_interceptor(::aws_smithy_runtime::client::stalled_stream_protection::StalledStreamProtectionInterceptor::default())
122            .with_interceptor(GetObjectEndpointParamsInterceptor)
123            .with_interceptor(crate::http_response_checksum::ResponseChecksumInterceptor::new(
124                ["crc32", "crc32c", "sha256", "sha1"].as_slice(),
125                |input: &::aws_smithy_runtime_api::client::interceptors::context::Input| {
126                    let input: &crate::operation::get_object::GetObjectInput = input.downcast_ref().expect("correct type");
127                    matches!(input.checksum_mode(), ::std::option::Option::Some(crate::types::ChecksumMode::Enabled))
128                },
129            ))
130            .with_retry_classifier(::aws_smithy_runtime::client::retries::classifiers::TransientErrorClassifier::<
131                crate::operation::get_object::GetObjectError,
132            >::new())
133            .with_retry_classifier(::aws_smithy_runtime::client::retries::classifiers::ModeledAsRetryableClassifier::<
134                crate::operation::get_object::GetObjectError,
135            >::new())
136            .with_retry_classifier(::aws_runtime::retries::classifiers::AwsErrorCodeClassifier::<
137                crate::operation::get_object::GetObjectError,
138            >::new());
139
140        ::std::borrow::Cow::Owned(rcb)
141    }
142}
143
144#[derive(Debug)]
145struct GetObjectResponseDeserializer;
146impl ::aws_smithy_runtime_api::client::ser_de::DeserializeResponse for GetObjectResponseDeserializer {
147    fn deserialize_streaming(
148        &self,
149        response: &mut ::aws_smithy_runtime_api::client::orchestrator::HttpResponse,
150    ) -> ::std::option::Option<::aws_smithy_runtime_api::client::interceptors::context::OutputOrError> {
151        #[allow(unused_mut)]
152        let mut force_error = false;
153        ::tracing::debug!(extended_request_id = ?crate::s3_request_id::RequestIdExt::extended_request_id(response));
154        ::tracing::debug!(request_id = ?::aws_types::request_id::RequestId::request_id(response));
155
156        // If this is an error, defer to the non-streaming parser
157        if (!response.status().is_success() && response.status().as_u16() != 200) || force_error {
158            return ::std::option::Option::None;
159        }
160        ::std::option::Option::Some(crate::protocol_serde::type_erase_result(
161            crate::protocol_serde::shape_get_object::de_get_object_http_response(response),
162        ))
163    }
164
165    fn deserialize_nonstreaming(
166        &self,
167        response: &::aws_smithy_runtime_api::client::orchestrator::HttpResponse,
168    ) -> ::aws_smithy_runtime_api::client::interceptors::context::OutputOrError {
169        // For streaming operations, we only hit this case if its an error
170        let body = response.body().bytes().expect("body loaded");
171        crate::protocol_serde::type_erase_result(crate::protocol_serde::shape_get_object::de_get_object_http_error(
172            response.status().as_u16(),
173            response.headers(),
174            body,
175        ))
176    }
177}
178#[derive(Debug)]
179struct GetObjectRequestSerializer;
180impl ::aws_smithy_runtime_api::client::ser_de::SerializeRequest for GetObjectRequestSerializer {
181    #[allow(unused_mut, clippy::let_and_return, clippy::needless_borrow, clippy::useless_conversion)]
182    fn serialize_input(
183        &self,
184        input: ::aws_smithy_runtime_api::client::interceptors::context::Input,
185        _cfg: &mut ::aws_smithy_types::config_bag::ConfigBag,
186    ) -> ::std::result::Result<::aws_smithy_runtime_api::client::orchestrator::HttpRequest, ::aws_smithy_runtime_api::box_error::BoxError> {
187        let input = input.downcast::<crate::operation::get_object::GetObjectInput>().expect("correct type");
188        let _header_serialization_settings = _cfg
189            .load::<crate::serialization_settings::HeaderSerializationSettings>()
190            .cloned()
191            .unwrap_or_default();
192        let mut request_builder = {
193            fn uri_base(
194                _input: &crate::operation::get_object::GetObjectInput,
195                output: &mut ::std::string::String,
196            ) -> ::std::result::Result<(), ::aws_smithy_types::error::operation::BuildError> {
197                use ::std::fmt::Write as _;
198                let input_1 = &_input.key;
199                let input_1 = input_1
200                    .as_ref()
201                    .ok_or_else(|| ::aws_smithy_types::error::operation::BuildError::missing_field("key", "cannot be empty or unset"))?;
202                let key = ::aws_smithy_http::label::fmt_string(input_1, ::aws_smithy_http::label::EncodingStrategy::Greedy);
203                if key.is_empty() {
204                    return ::std::result::Result::Err(::aws_smithy_types::error::operation::BuildError::missing_field(
205                        "key",
206                        "cannot be empty or unset",
207                    ));
208                }
209                ::std::write!(output, "/{Key}", Key = key).expect("formatting should succeed");
210                ::std::result::Result::Ok(())
211            }
212            fn uri_query(
213                _input: &crate::operation::get_object::GetObjectInput,
214                mut output: &mut ::std::string::String,
215            ) -> ::std::result::Result<(), ::aws_smithy_types::error::operation::BuildError> {
216                let mut query = ::aws_smithy_http::query::Writer::new(output);
217                query.push_kv("x-id", "GetObject");
218                if let ::std::option::Option::Some(inner_2) = &_input.response_cache_control {
219                    {
220                        query.push_kv("response-cache-control", &::aws_smithy_http::query::fmt_string(inner_2));
221                    }
222                }
223                if let ::std::option::Option::Some(inner_3) = &_input.response_content_disposition {
224                    {
225                        query.push_kv("response-content-disposition", &::aws_smithy_http::query::fmt_string(inner_3));
226                    }
227                }
228                if let ::std::option::Option::Some(inner_4) = &_input.response_content_encoding {
229                    {
230                        query.push_kv("response-content-encoding", &::aws_smithy_http::query::fmt_string(inner_4));
231                    }
232                }
233                if let ::std::option::Option::Some(inner_5) = &_input.response_content_language {
234                    {
235                        query.push_kv("response-content-language", &::aws_smithy_http::query::fmt_string(inner_5));
236                    }
237                }
238                if let ::std::option::Option::Some(inner_6) = &_input.response_content_type {
239                    {
240                        query.push_kv("response-content-type", &::aws_smithy_http::query::fmt_string(inner_6));
241                    }
242                }
243                if let ::std::option::Option::Some(inner_7) = &_input.response_expires {
244                    {
245                        query.push_kv(
246                            "response-expires",
247                            &::aws_smithy_http::query::fmt_timestamp(inner_7, ::aws_smithy_types::date_time::Format::HttpDate)?,
248                        );
249                    }
250                }
251                if let ::std::option::Option::Some(inner_8) = &_input.version_id {
252                    {
253                        query.push_kv("versionId", &::aws_smithy_http::query::fmt_string(inner_8));
254                    }
255                }
256                if let ::std::option::Option::Some(inner_9) = &_input.part_number {
257                    {
258                        query.push_kv("partNumber", ::aws_smithy_types::primitive::Encoder::from(*inner_9).encode());
259                    }
260                }
261                ::std::result::Result::Ok(())
262            }
263            #[allow(clippy::unnecessary_wraps)]
264            fn update_http_builder(
265                input: &crate::operation::get_object::GetObjectInput,
266                builder: ::http::request::Builder,
267            ) -> ::std::result::Result<::http::request::Builder, ::aws_smithy_types::error::operation::BuildError> {
268                let mut uri = ::std::string::String::new();
269                uri_base(input, &mut uri)?;
270                uri_query(input, &mut uri)?;
271                let builder = crate::protocol_serde::shape_get_object::ser_get_object_headers(input, builder)?;
272                ::std::result::Result::Ok(builder.method("GET").uri(uri))
273            }
274            let mut builder = update_http_builder(&input, ::http::request::Builder::new())?;
275            builder
276        };
277        let body = ::aws_smithy_types::body::SdkBody::from("");
278
279        ::std::result::Result::Ok(request_builder.body(body).expect("valid request").try_into().unwrap())
280    }
281}
282#[derive(Debug)]
283struct GetObjectEndpointParamsInterceptor;
284
285impl ::aws_smithy_runtime_api::client::interceptors::Intercept for GetObjectEndpointParamsInterceptor {
286    fn name(&self) -> &'static str {
287        "GetObjectEndpointParamsInterceptor"
288    }
289
290    fn read_before_execution(
291        &self,
292        context: &::aws_smithy_runtime_api::client::interceptors::context::BeforeSerializationInterceptorContextRef<
293            '_,
294            ::aws_smithy_runtime_api::client::interceptors::context::Input,
295            ::aws_smithy_runtime_api::client::interceptors::context::Output,
296            ::aws_smithy_runtime_api::client::interceptors::context::Error,
297        >,
298        cfg: &mut ::aws_smithy_types::config_bag::ConfigBag,
299    ) -> ::std::result::Result<(), ::aws_smithy_runtime_api::box_error::BoxError> {
300        let _input = context
301            .input()
302            .downcast_ref::<GetObjectInput>()
303            .ok_or("failed to downcast to GetObjectInput")?;
304
305        let params = crate::config::endpoint::Params::builder()
306            .set_region(cfg.load::<::aws_types::region::Region>().map(|r| r.as_ref().to_owned()))
307            .set_use_fips(cfg.load::<::aws_types::endpoint_config::UseFips>().map(|ty| ty.0))
308            .set_use_dual_stack(cfg.load::<::aws_types::endpoint_config::UseDualStack>().map(|ty| ty.0))
309            .set_endpoint(cfg.load::<::aws_types::endpoint_config::EndpointUrl>().map(|ty| ty.0.clone()))
310            .set_force_path_style(cfg.load::<crate::config::ForcePathStyle>().map(|ty| ty.0))
311            .set_use_arn_region(cfg.load::<crate::config::UseArnRegion>().map(|ty| ty.0))
312            .set_disable_multi_region_access_points(cfg.load::<crate::config::DisableMultiRegionAccessPoints>().map(|ty| ty.0))
313            .set_accelerate(cfg.load::<crate::config::Accelerate>().map(|ty| ty.0))
314            .set_disable_s3_express_session_auth(cfg.load::<crate::config::DisableS3ExpressSessionAuth>().map(|ty| ty.0))
315            .set_bucket(Some(
316                _input
317                    .bucket
318                    .clone()
319                    .filter(|f| !AsRef::<str>::as_ref(f).trim().is_empty())
320                    .ok_or_else(|| ::aws_smithy_types::error::operation::BuildError::missing_field("bucket", "A required field was not set"))?,
321            ))
322            .set_key(Some(
323                _input
324                    .key
325                    .clone()
326                    .filter(|f| !AsRef::<str>::as_ref(f).trim().is_empty())
327                    .ok_or_else(|| ::aws_smithy_types::error::operation::BuildError::missing_field("key", "A required field was not set"))?,
328            ))
329            .build()
330            .map_err(|err| {
331                ::aws_smithy_runtime_api::client::interceptors::error::ContextAttachedError::new("endpoint params could not be built", err)
332            })?;
333        cfg.interceptor_state()
334            .store_put(::aws_smithy_runtime_api::client::endpoint::EndpointResolverParams::new(params));
335        ::std::result::Result::Ok(())
336    }
337}
338
339/// Error type for the `GetObjectError` operation.
340#[non_exhaustive]
341#[derive(::std::fmt::Debug)]
342pub enum GetObjectError {
343    /// <p>Object is archived and inaccessible until restored.</p>
344    /// <p>If the object you are retrieving is stored in the S3 Glacier Flexible Retrieval storage class, the S3 Glacier Deep Archive storage class, the S3 Intelligent-Tiering Archive Access tier, or the S3 Intelligent-Tiering Deep Archive Access tier, before you can retrieve the object you must first restore a copy using <a href="https://docs.aws.amazon.com/AmazonS3/latest/API/API_RestoreObject.html">RestoreObject</a>. Otherwise, this operation returns an <code>InvalidObjectState</code> error. For information about restoring archived objects, see <a href="https://docs.aws.amazon.com/AmazonS3/latest/dev/restoring-objects.html">Restoring Archived Objects</a> in the <i>Amazon S3 User Guide</i>.</p>
345    InvalidObjectState(crate::types::error::InvalidObjectState),
346    /// <p>The specified key does not exist.</p>
347    NoSuchKey(crate::types::error::NoSuchKey),
348    /// An unexpected error occurred (e.g., invalid JSON returned by the service or an unknown error code).
349    #[deprecated(note = "Matching `Unhandled` directly is not forwards compatible. Instead, match using a \
350    variable wildcard pattern and check `.code()`:
351     \
352    &nbsp;&nbsp;&nbsp;`err if err.code() == Some(\"SpecificExceptionCode\") => { /* handle the error */ }`
353     \
354    See [`ProvideErrorMetadata`](#impl-ProvideErrorMetadata-for-GetObjectError) for what information is available for the error.")]
355    Unhandled(crate::error::sealed_unhandled::Unhandled),
356}
357impl GetObjectError {
358    /// Creates the `GetObjectError::Unhandled` variant from any error type.
359    pub fn unhandled(
360        err: impl ::std::convert::Into<::std::boxed::Box<dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static>>,
361    ) -> Self {
362        Self::Unhandled(crate::error::sealed_unhandled::Unhandled {
363            source: err.into(),
364            meta: ::std::default::Default::default(),
365        })
366    }
367
368    /// Creates the `GetObjectError::Unhandled` variant from an [`ErrorMetadata`](::aws_smithy_types::error::ErrorMetadata).
369    pub fn generic(err: ::aws_smithy_types::error::ErrorMetadata) -> Self {
370        Self::Unhandled(crate::error::sealed_unhandled::Unhandled {
371            source: err.clone().into(),
372            meta: err,
373        })
374    }
375    ///
376    /// Returns error metadata, which includes the error code, message,
377    /// request ID, and potentially additional information.
378    ///
379    pub fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata {
380        match self {
381            Self::InvalidObjectState(e) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(e),
382            Self::NoSuchKey(e) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(e),
383            Self::Unhandled(e) => &e.meta,
384        }
385    }
386    /// Returns `true` if the error kind is `GetObjectError::InvalidObjectState`.
387    pub fn is_invalid_object_state(&self) -> bool {
388        matches!(self, Self::InvalidObjectState(_))
389    }
390    /// Returns `true` if the error kind is `GetObjectError::NoSuchKey`.
391    pub fn is_no_such_key(&self) -> bool {
392        matches!(self, Self::NoSuchKey(_))
393    }
394}
395impl ::std::error::Error for GetObjectError {
396    fn source(&self) -> ::std::option::Option<&(dyn ::std::error::Error + 'static)> {
397        match self {
398            Self::InvalidObjectState(_inner) => ::std::option::Option::Some(_inner),
399            Self::NoSuchKey(_inner) => ::std::option::Option::Some(_inner),
400            Self::Unhandled(_inner) => ::std::option::Option::Some(&*_inner.source),
401        }
402    }
403}
404impl ::std::fmt::Display for GetObjectError {
405    fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
406        match self {
407            Self::InvalidObjectState(_inner) => _inner.fmt(f),
408            Self::NoSuchKey(_inner) => _inner.fmt(f),
409            Self::Unhandled(_inner) => {
410                if let ::std::option::Option::Some(code) = ::aws_smithy_types::error::metadata::ProvideErrorMetadata::code(self) {
411                    write!(f, "unhandled error ({code})")
412                } else {
413                    f.write_str("unhandled error")
414                }
415            }
416        }
417    }
418}
419impl ::aws_smithy_types::retry::ProvideErrorKind for GetObjectError {
420    fn code(&self) -> ::std::option::Option<&str> {
421        ::aws_smithy_types::error::metadata::ProvideErrorMetadata::code(self)
422    }
423    fn retryable_error_kind(&self) -> ::std::option::Option<::aws_smithy_types::retry::ErrorKind> {
424        ::std::option::Option::None
425    }
426}
427impl ::aws_smithy_types::error::metadata::ProvideErrorMetadata for GetObjectError {
428    fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata {
429        match self {
430            Self::InvalidObjectState(_inner) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(_inner),
431            Self::NoSuchKey(_inner) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(_inner),
432            Self::Unhandled(_inner) => &_inner.meta,
433        }
434    }
435}
436impl ::aws_smithy_runtime_api::client::result::CreateUnhandledError for GetObjectError {
437    fn create_unhandled_error(
438        source: ::std::boxed::Box<dyn ::std::error::Error + ::std::marker::Send + ::std::marker::Sync + 'static>,
439        meta: ::std::option::Option<::aws_smithy_types::error::ErrorMetadata>,
440    ) -> Self {
441        Self::Unhandled(crate::error::sealed_unhandled::Unhandled {
442            source,
443            meta: meta.unwrap_or_default(),
444        })
445    }
446}
447impl crate::s3_request_id::RequestIdExt for crate::operation::get_object::GetObjectError {
448    fn extended_request_id(&self) -> Option<&str> {
449        self.meta().extended_request_id()
450    }
451}
452impl ::aws_types::request_id::RequestId for crate::operation::get_object::GetObjectError {
453    fn request_id(&self) -> Option<&str> {
454        self.meta().request_id()
455    }
456}
457
458pub use crate::operation::get_object::_get_object_output::GetObjectOutput;
459
460pub use crate::operation::get_object::_get_object_input::GetObjectInput;
461
462mod _get_object_input;
463
464mod _get_object_output;
465
466/// Builders
467pub mod builders;