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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
//! HTTP(S) client traits for hanling API calls

pub mod error;
pub mod url_params;

use crate::credentials::Credentials;
use async_trait::async_trait;
use bytes::Bytes;
use error::{ApiClientError, FireBaseAPIErrorResponse};
use error_stack::{IntoReport, Report, ResultExt};
use headers::{ContentType, HeaderMapExt};
use http::{request::Builder, StatusCode, Uri};
use hyper::{
    client::{Client, HttpConnector},
    Body, Method, Request,
};
use hyper_openssl::HttpsConnector;
use serde::{de::DeserializeOwned, Serialize};
use serde_json;
use std::iter::Iterator;
use std::sync::Arc;
use url_params::UrlParams;

pub(crate) fn build_https_client() -> HyperClient {
    let https_connector =
        HttpsConnector::new().expect("Could not construct TLS connector for API client");

    Client::builder().build(https_connector)
}

#[async_trait]
pub trait ApiHttpClient: Send + Sync {
    async fn send_request<ResponseT>(
        &self,
        uri: Uri,
        method: Method,
        oauth_scopes: &[&str],
    ) -> Result<ResponseT, Report<ApiClientError>>
    where
        Self: Sized + Send + Sync,
        ResponseT: DeserializeOwned + Send + Sync;

    async fn send_request_with_params<ResponseT, ParamsT>(
        &self,
        uri: Uri,
        params: ParamsT,
        method: Method,
        oauth_scopes: &[&str],
    ) -> Result<ResponseT, Report<ApiClientError>>
    where
        Self: Sized + Send + Sync,
        ResponseT: DeserializeOwned + Send + Sync,
        ParamsT: Iterator<Item = (String, String)> + Send + Sync;

    async fn send_request_body<RequestT, ResponseT>(
        &self,
        uri: Uri,
        method: Method,
        request_body: RequestT,
        oauth_scopes: &[&str],
    ) -> Result<ResponseT, Report<ApiClientError>>
    where
        Self: Sized + Send + Sync,
        RequestT: Serialize + Send + Sync,
        ResponseT: DeserializeOwned + Send + Sync;

    async fn send_request_body_get_bytes<RequestT>(
        &self,
        uri: Uri,
        method: Method,
        request_body: RequestT,
        oauth_scopes: &[&str],
    ) -> Result<Bytes, Report<ApiClientError>>
    where
        Self: Sized + Send + Sync,
        RequestT: Serialize + Send + Sync;

    async fn send_request_body_empty_response<RequestT>(
        &self,
        uri: Uri,
        method: Method,
        request_body: RequestT,
        oauth_scopes: &[&str],
    ) -> Result<(), Report<ApiClientError>>
    where
        Self: Sized + Send + Sync,
        RequestT: Serialize + Send + Sync;
}

pub type HyperClient = Client<HttpsConnector<HttpConnector>>;

pub struct HyperApiClient<CredentialSourceT> {
    http_client: HyperClient,
    credential_source: Arc<CredentialSourceT>,
}

impl<CredentialSourceT> HyperApiClient<CredentialSourceT>
where
    CredentialSourceT: Credentials + Send + Sync + 'static,
{
    pub fn new(credential_source: Arc<CredentialSourceT>) -> Self {
        Self {
            http_client: build_https_client(),
            credential_source,
        }
    }

    fn deserialize_body<ResponseT: DeserializeOwned>(
        body: &Bytes,
    ) -> Result<ResponseT, Report<ApiClientError>> {
        let json_payload_view = std::str::from_utf8(body)
            .into_report()
            .change_context(ApiClientError::FailedToDeserializeResponse)?;

        let response = serde_json::from_str(json_payload_view)
            .into_report()
            .change_context(ApiClientError::FailedToDeserializeResponse)
            .attach_printable_lazy(|| format!("JSON: {json_payload_view}"))?;

        Ok(response)
    }

    async fn handle_response<ResponseT>(
        &self,
        request: Request<Body>,
    ) -> Result<ResponseT, Report<ApiClientError>>
    where
        ResponseT: DeserializeOwned + Send + Sync,
    {
        let response_body = self.handle_byte_response(request).await?;

        Self::deserialize_body(&response_body)
    }

    async fn handle_byte_response(
        &self,
        request: Request<Body>,
    ) -> Result<Bytes, Report<ApiClientError>> {
        let response = self
            .http_client
            .request(request)
            .await
            .into_report()
            .change_context(ApiClientError::FailedToReceiveResponse)?;

        let response_status = response.status();
        let response_body = hyper::body::to_bytes(response.into_body())
            .await
            .into_report()
            .change_context(ApiClientError::FailedToReceiveResponse)?;

        if response_status != StatusCode::OK {
            let error_response: FireBaseAPIErrorResponse = Self::deserialize_body(&response_body)?;
            return Err(Report::new(ApiClientError::ServerError(
                error_response.error,
            )));
        }

        Ok(response_body)
    }
}

#[async_trait]
impl<CredentialSourceT> ApiHttpClient for HyperApiClient<CredentialSourceT>
where
    CredentialSourceT: Credentials + Send + Sync + 'static,
{
    async fn send_request<ResponseT>(
        &self,
        uri: Uri,
        method: Method,
        oauth_scopes: &[&str],
    ) -> Result<ResponseT, Report<ApiClientError>>
    where
        Self: Sized + Send + Sync,
        ResponseT: DeserializeOwned + Send + Sync,
    {
        let request = Request::builder()
            .method(method)
            .uri(uri)
            .set_credentials(&*self.credential_source, oauth_scopes)
            .await?
            .body(Body::empty())
            .into_report()
            .change_context(ApiClientError::FailedToSendRequest)?;

        self.handle_response(request).await
    }

    async fn send_request_with_params<ResponseT, ParamsT>(
        &self,
        uri: Uri,
        params: ParamsT,
        method: Method,
        oauth_scopes: &[&str],
    ) -> Result<ResponseT, Report<ApiClientError>>
    where
        Self: Sized + Send + Sync,
        ResponseT: DeserializeOwned + Send + Sync,
        ParamsT: Iterator<Item = (String, String)> + Send + Sync,
    {
        let uri_str: String = uri.to_string() + &params.into_url_params();
        let uri = uri_str
            .parse()
            .into_report()
            .change_context(ApiClientError::FailedToSendRequest)?;

        self.send_request(uri, method, oauth_scopes).await
    }

    async fn send_request_body<RequestT, ResponseT>(
        &self,
        uri: Uri,
        method: Method,
        request_body: RequestT,
        oauth_scopes: &[&str],
    ) -> Result<ResponseT, Report<ApiClientError>>
    where
        Self: Sized + Send + Sync,
        RequestT: Serialize + Send + Sync,
        ResponseT: DeserializeOwned + Send + Sync,
    {
        let body: Body = serde_json::to_string(&request_body)
            .into_report()
            .change_context(ApiClientError::FailedToSerializeRequest)?
            .into();

        let request = Request::builder()
            .method(method)
            .uri(uri)
            .set_json_content_type()
            .set_credentials(&*self.credential_source, oauth_scopes)
            .await?
            .body(body)
            .into_report()
            .change_context(ApiClientError::FailedToSendRequest)?;

        self.handle_response(request).await
    }

    async fn send_request_body_get_bytes<RequestT>(
        &self,
        uri: Uri,
        method: Method,
        request_body: RequestT,
        oauth_scopes: &[&str],
    ) -> Result<Bytes, Report<ApiClientError>>
    where
        Self: Sized + Send + Sync,
        RequestT: Serialize + Send + Sync,
    {
        let body: Body = serde_json::to_string(&request_body)
            .into_report()
            .change_context(ApiClientError::FailedToSerializeRequest)?
            .into();

        let request = Request::builder()
            .method(method)
            .uri(uri)
            .set_json_content_type()
            .set_credentials(&*self.credential_source, oauth_scopes)
            .await?
            .body(body)
            .into_report()
            .change_context(ApiClientError::FailedToSendRequest)?;

        self.handle_byte_response(request).await
    }

    async fn send_request_body_empty_response<RequestT>(
        &self,
        uri: Uri,
        method: Method,
        request_body: RequestT,
        oauth_scopes: &[&str],
    ) -> Result<(), Report<ApiClientError>>
    where
        Self: Sized + Send + Sync,
        RequestT: Serialize + Send + Sync,
    {
        self.send_request_body_get_bytes(uri, method, request_body, oauth_scopes)
            .await?;

        Ok(())
    }
}

trait SetRequestJsonContentType {
    fn set_json_content_type(self) -> Self;
}

impl SetRequestJsonContentType for Builder {
    fn set_json_content_type(mut self) -> Self {
        if let Some(headers) = self.headers_mut() {
            headers.typed_insert(ContentType::json())
        }

        self
    }
}

#[async_trait]
trait SetRequestCredentials: Sized {
    async fn set_credentials<CredentialsT>(
        self,
        source: &CredentialsT,
        scopes: &[&str],
    ) -> Result<Self, Report<ApiClientError>>
    where
        CredentialsT: Credentials + Send + Sync;
}

#[async_trait]
impl SetRequestCredentials for Builder {
    async fn set_credentials<CredentialsT>(
        mut self,
        source: &CredentialsT,
        scopes: &[&str],
    ) -> Result<Self, Report<ApiClientError>>
    where
        CredentialsT: Credentials + Send + Sync,
    {
        let headers = self
            .headers_mut()
            .ok_or(Report::new(ApiClientError::FailedToSendRequest))?;

        source
            .set_credentials(headers, scopes)
            .await
            .change_context(ApiClientError::FailedToSendRequest)?;

        Ok(self)
    }
}