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
//! HTTP(S) client traits for hanling API calls

pub mod error;
pub mod url_params;

use crate::credentials::Credentials;
use bytes::Bytes;
use error::{ApiClientError, FireBaseAPIErrorResponse};
use error_stack::{Report, ResultExt};
use http::Method;
use serde::{de::DeserializeOwned, Serialize};
use std::future::Future;
use std::iter::Iterator;
use url_params::UrlParams;

pub trait ApiHttpClient: Send + Sync + 'static {
    fn send_request<ResponseT: Send + DeserializeOwned>(
        &self,
        uri: String,
        method: Method,
        oauth_scopes: &[&str],
    ) -> impl Future<Output = Result<ResponseT, Report<ApiClientError>>> + Send;

    fn send_request_with_params<
        ResponseT: DeserializeOwned + Send,
        ParamsT: Iterator<Item = (String, String)> + Send,
    >(
        &self,
        uri: String,
        params: ParamsT,
        method: Method,
        oauth_scopes: &[&str],
    ) -> impl Future<Output = Result<ResponseT, Report<ApiClientError>>> + Send;

    fn send_request_body<RequestT: Serialize + Send, ResponseT: DeserializeOwned + Send>(
        &self,
        uri: String,
        method: Method,
        request_body: RequestT,
        oauth_scopes: &[&str],
    ) -> impl Future<Output = Result<ResponseT, Report<ApiClientError>>> + Send;

    fn send_request_body_get_bytes<RequestT: Serialize + Send>(
        &self,
        uri: String,
        method: Method,
        request_body: RequestT,
        oauth_scopes: &[&str],
    ) -> impl Future<Output = Result<Bytes, Report<ApiClientError>>> + Send;

    fn send_request_body_empty_response<RequestT: Serialize + Send>(
        &self,
        uri: String,
        method: Method,
        request_body: RequestT,
        oauth_scopes: &[&str],
    ) -> impl Future<Output = Result<(), Report<ApiClientError>>> + Send;
}

trait SetReqBody<T: Serialize> {
    fn set_request_body(self, body: Option<T>) -> Self;
}

impl<T: Serialize> SetReqBody<T> for reqwest::RequestBuilder {
    fn set_request_body(self, body: Option<T>) -> Self {
        if let Some(body) = body {
            return self.json(&body);
        }

        self
    }
}

pub struct ReqwestApiClient<C> {
    client: reqwest::Client,
    credentials: C,
}

impl<C: Credentials> ReqwestApiClient<C> {
    pub fn new(client: reqwest::Client, credentials: C) -> Self {
        Self {
            client,
            credentials,
        }
    }

    async fn handle_response(
        resp: reqwest::Response,
    ) -> Result<reqwest::Response, Report<ApiClientError>> {
        if resp.status() != reqwest::StatusCode::OK {
            let error_response: FireBaseAPIErrorResponse = resp
                .json()
                .await
                .change_context(ApiClientError::FailedToReceiveResponse)?;

            return Err(Report::new(ApiClientError::ServerError(
                error_response.error,
            )));
        }

        Ok(resp)
    }

    async fn handle_request<B: Serialize + Send>(
        &self,
        url: &str,
        method: Method,
        oauth_scopes: &[&str],
        body: Option<B>,
    ) -> Result<reqwest::Response, Report<ApiClientError>> {
        self.client
            .request(method, url)
            .bearer_auth(
                self.credentials
                    .get_access_token(oauth_scopes)
                    .await
                    .change_context(ApiClientError::FailedToSendRequest)?,
            )
            .set_request_body(body)
            .send()
            .await
            .change_context(ApiClientError::FailedToSendRequest)
    }
}

impl<C: Credentials> ApiHttpClient for ReqwestApiClient<C> {
    async fn send_request<ResponseT: Send + DeserializeOwned>(
        &self,
        url: String,
        method: Method,
        oauth_scopes: &[&str],
    ) -> Result<ResponseT, Report<ApiClientError>> {
        Self::handle_response(
            self.handle_request::<()>(&url, method, oauth_scopes, None)
                .await?,
        )
        .await?
        .json()
        .await
        .change_context(ApiClientError::FailedToReceiveResponse)
    }

    async fn send_request_with_params<
        ResponseT: DeserializeOwned + Send,
        ParamsT: Iterator<Item = (String, String)> + Send,
    >(
        &self,
        url: String,
        params: ParamsT,
        method: Method,
        oauth_scopes: &[&str],
    ) -> Result<ResponseT, Report<ApiClientError>> {
        let url: String = url + &params.into_url_params();
        Self::handle_response(
            self.handle_request::<()>(&url, method, oauth_scopes, None)
                .await?,
        )
        .await?
        .json()
        .await
        .change_context(ApiClientError::FailedToReceiveResponse)
    }

    async fn send_request_body<RequestT: Serialize + Send, ResponseT: DeserializeOwned + Send>(
        &self,
        url: String,
        method: Method,
        request_body: RequestT,
        oauth_scopes: &[&str],
    ) -> Result<ResponseT, Report<ApiClientError>> {
        Self::handle_response(
            self.handle_request(&url, method, oauth_scopes, Some(request_body))
                .await?,
        )
        .await?
        .json()
        .await
        .change_context(ApiClientError::FailedToReceiveResponse)
    }

    async fn send_request_body_get_bytes<RequestT: Serialize + Send>(
        &self,
        url: String,
        method: Method,
        request_body: RequestT,
        oauth_scopes: &[&str],
    ) -> Result<Bytes, Report<ApiClientError>> {
        Self::handle_response(
            self.handle_request(&url, method, oauth_scopes, Some(request_body))
                .await?,
        )
        .await?
        .bytes()
        .await
        .change_context(ApiClientError::FailedToReceiveResponse)
    }

    async fn send_request_body_empty_response<RequestT: Serialize + Send>(
        &self,
        url: String,
        method: Method,
        request_body: RequestT,
        oauth_scopes: &[&str],
    ) -> Result<(), Report<ApiClientError>> {
        Self::handle_response(
            self.handle_request(&url, method, oauth_scopes, Some(request_body))
                .await?,
        )
        .await?;

        Ok(())
    }
}