yup_oauth2/
client.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
//! Module containing the HTTP client used for sending requests
use std::time::Duration;

use http::Uri;
use hyper_util::client::legacy::{connect::Connect, Error as LegacyHyperError};
#[cfg(all(feature = "aws-lc-rs", feature = "hyper-rustls", not(feature = "ring")))]
use rustls::crypto::aws_lc_rs::default_provider as default_crypto_provider;
#[cfg(all(feature = "ring", feature = "hyper-rustls"))]
use rustls::crypto::ring::default_provider as default_crypto_provider;
#[cfg(all(
    feature = "hyper-rustls",
    not(any(feature = "ring", feature = "aws-lc-rs"))
))]
compile_error!(
    "The `hyper-rustls` feature requires either the `ring` or `aws-lc-rs` feature to be enabled"
);
use thiserror::Error as ThisError;

use crate::Error;

type HyperResponse = http::Response<hyper::body::Incoming>;
pub(crate) type LegacyClient<C> = hyper_util::client::legacy::Client<C, String>;

#[derive(Debug, ThisError)]
/// Errors that can happen when a request is sent
pub enum SendError {
    /// Request could not complete before timeout elapsed
    #[error("Request timed out")]
    Timeout,
    /// Wrapper for hyper errors
    #[error("Hyper error: {0}")]
    Hyper(#[source] LegacyHyperError),
}

/// A trait implemented for any hyper_util::client::legacy::Client as well as the DefaultHyperClient.
pub trait HyperClientBuilder {
    /// The hyper connector that the resulting hyper client will use.
    type Connector: Connect + Clone + Send + Sync + 'static;

    /// Sets duration after which a request times out
    fn with_timeout(self, timeout: Duration) -> Self;

    /// Create a hyper::Client
    fn build_hyper_client(self) -> Result<HttpClient<Self::Connector>, Error>;
}

/// Client that can be configured that a request will timeout after a specified
/// duration.
#[derive(Clone)]
pub struct HttpClient<C>
where
    C: Connect + Clone + Send + Sync + 'static,
{
    client: LegacyClient<C>,
    timeout: Option<Duration>,
}

impl<C> HttpClient<C>
where
    C: Connect + Clone + Send + Sync + 'static,
{
    pub(crate) fn new(hyper_client: LegacyClient<C>, timeout: Option<Duration>) -> Self {
        Self {
            client: hyper_client,
            timeout,
        }
    }

    pub(crate) fn set_timeout(&mut self, timeout: Duration) {
        self.timeout = Some(timeout);
    }

    /// Execute a get request with the underlying hyper client
    #[doc(hidden)]
    pub async fn get(&self, uri: Uri) -> Result<HyperResponse, hyper_util::client::legacy::Error> {
        self.client.get(uri).await
    }
}

impl<C> HyperClientBuilder for HttpClient<C>
where
    C: Connect + Clone + Send + Sync + 'static,
{
    type Connector = C;

    fn with_timeout(mut self, timeout: Duration) -> Self {
        self.set_timeout(timeout);
        self
    }

    fn build_hyper_client(self) -> Result<HttpClient<Self::Connector>, Error> {
        Ok(self)
    }
}

impl<C> SendRequest for HttpClient<C>
where
    C: Connect + Clone + Send + Sync + 'static,
{
    async fn request(&self, payload: http::Request<String>) -> Result<HyperResponse, SendError> {
        let future = self.client.request(payload);
        match self.timeout {
            Some(duration) => tokio::time::timeout(duration, future)
                .await
                .map_err(|_| SendError::Timeout)?,
            None => future.await,
        }
        .map_err(SendError::Hyper)
    }
}

pub(crate) trait SendRequest {
    async fn request(&self, payload: http::Request<String>) -> Result<HyperResponse, SendError>;
}

/// The builder value used when the default hyper client should be used.
#[cfg(any(feature = "hyper-rustls", feature = "hyper-tls"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "hyper-rustls", feature = "hyper-tls"))))]
#[derive(Default)]
pub struct DefaultHyperClientBuilder {
    timeout: Option<Duration>,
}

#[cfg(any(feature = "hyper-rustls", feature = "hyper-tls"))]
impl DefaultHyperClientBuilder {
    /// Set the duration after which a request times out
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }
}

#[cfg(any(feature = "hyper-rustls", feature = "hyper-tls"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "hyper-rustls", feature = "hyper-tls"))))]
impl HyperClientBuilder for DefaultHyperClientBuilder {
    #[cfg(feature = "hyper-rustls")]
    type Connector =
        hyper_rustls::HttpsConnector<hyper_util::client::legacy::connect::HttpConnector>;
    #[cfg(all(not(feature = "hyper-rustls"), feature = "hyper-tls"))]
    type Connector = hyper_tls::HttpsConnector<hyper_util::client::legacy::connect::HttpConnector>;

    fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    fn build_hyper_client(self) -> Result<HttpClient<Self::Connector>, Error> {
        #[cfg(feature = "hyper-rustls")]
        let connector = hyper_rustls::HttpsConnectorBuilder::new()
            .with_provider_and_native_roots(default_crypto_provider())?
            .https_or_http()
            .enable_http1()
            .enable_http2()
            .build();
        #[cfg(all(not(feature = "hyper-rustls"), feature = "hyper-tls"))]
        let connector = hyper_tls::HttpsConnector::new();

        Ok(HttpClient::new(
            hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new())
                .pool_max_idle_per_host(0)
                .build::<_, String>(connector),
            self.timeout,
        ))
    }
}

/// Intended for using an existing hyper client with `yup-oauth2`. Instantiate
/// with [`CustomHyperClientBuilder::from`]
pub struct CustomHyperClientBuilder<C>
where
    C: Connect + Clone + Send + Sync + 'static,
{
    client: HttpClient<C>,
    timeout: Option<Duration>,
}

impl<C> From<LegacyClient<C>> for CustomHyperClientBuilder<C>
where
    C: Connect + Clone + Send + Sync + 'static,
{
    fn from(client: LegacyClient<C>) -> Self {
        Self {
            client: HttpClient::new(client, None),
            timeout: None,
        }
    }
}

impl<C> HyperClientBuilder for CustomHyperClientBuilder<C>
where
    C: Connect + Clone + Send + Sync + 'static,
{
    type Connector = C;

    fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    fn build_hyper_client(self) -> Result<HttpClient<Self::Connector>, Error> {
        Ok(self.client)
    }
}