aws_smithy_http_client/test_util/
legacy_infallible.rs

1/*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6use aws_smithy_runtime_api::client::connector_metadata::ConnectorMetadata;
7use aws_smithy_runtime_api::client::http::{
8    HttpClient, HttpConnector, HttpConnectorFuture, HttpConnectorSettings, SharedHttpClient,
9    SharedHttpConnector,
10};
11use aws_smithy_runtime_api::client::orchestrator::{HttpRequest, HttpResponse};
12use aws_smithy_runtime_api::client::result::ConnectorError;
13use aws_smithy_runtime_api::client::runtime_components::RuntimeComponents;
14use aws_smithy_runtime_api::shared::IntoShared;
15use aws_smithy_types::body::SdkBody;
16use std::fmt;
17use std::sync::Arc;
18
19/// Create a [`SharedHttpClient`] from `Fn(http:Request) -> http::Response`
20///
21/// # Examples
22///
23/// ```rust
24/// use aws_smithy_http_client::test_util::legacy_infallible::infallible_client_fn;
25/// let http_client = infallible_client_fn(|_req| http_02x::Response::builder().status(200).body("OK!").unwrap());
26/// ```
27pub fn infallible_client_fn<B>(
28    f: impl Fn(http_02x::Request<SdkBody>) -> http_02x::Response<B> + Send + Sync + 'static,
29) -> SharedHttpClient
30where
31    B: Into<SdkBody>,
32{
33    InfallibleClientFn::new(f).into_shared()
34}
35
36#[derive(Clone)]
37struct InfallibleClientFn {
38    #[allow(clippy::type_complexity)]
39    response: Arc<
40        dyn Fn(http_02x::Request<SdkBody>) -> Result<http_02x::Response<SdkBody>, ConnectorError>
41            + Send
42            + Sync,
43    >,
44}
45
46impl fmt::Debug for InfallibleClientFn {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        f.debug_struct("InfallibleClientFn").finish()
49    }
50}
51
52impl InfallibleClientFn {
53    fn new<B: Into<SdkBody>>(
54        f: impl Fn(http_02x::Request<SdkBody>) -> http_02x::Response<B> + Send + Sync + 'static,
55    ) -> Self {
56        Self {
57            response: Arc::new(move |request| Ok(f(request).map(|b| b.into()))),
58        }
59    }
60}
61
62impl HttpConnector for InfallibleClientFn {
63    fn call(&self, request: HttpRequest) -> HttpConnectorFuture {
64        HttpConnectorFuture::ready(
65            (self.response)(request.try_into_http02x().unwrap())
66                .map(|res| HttpResponse::try_from(res).unwrap()),
67        )
68    }
69}
70
71impl HttpClient for InfallibleClientFn {
72    fn http_connector(
73        &self,
74        _: &HttpConnectorSettings,
75        _: &RuntimeComponents,
76    ) -> SharedHttpConnector {
77        self.clone().into_shared()
78    }
79
80    fn connector_metadata(&self) -> Option<ConnectorMetadata> {
81        Some(ConnectorMetadata::new("infallible-client", None))
82    }
83}