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
335
336
337
338
use std::fmt;
use std::sync::Arc;

use crate::http::{Method, Url};
use crate::middleware::{Middleware, Next};
use crate::protocol::{EffectSender, HttpResult, ProtocolRequestBuilder};
use crate::{Config, Request, RequestBuilder, ResponseAsync, Result};

/// An HTTP client, capable of sending `Request`s
///
/// Users should only interact with this type from middlewares - normal crux code should
/// make use of the `Http` capability type instead.
///
/// # Examples
///
/// ```no_run
/// use futures_util::future::BoxFuture;
/// use crux_http::middleware::{Next, Middleware};
/// use crux_http::{client::Client, Request, RequestBuilder, ResponseAsync, Result};
/// use std::time;
/// use std::sync::Arc;
///
/// // Fetches an authorization token prior to making a request
/// fn fetch_auth<'a>(mut req: Request, client: Client, next: Next<'a>) -> BoxFuture<'a, Result<ResponseAsync>> {
///     Box::pin(async move {
///         let auth_token = client.get("https://httpbin.org/get")
///             .await?
///             .body_string()
///             .await?;
///         req.append_header("Authorization", format!("Bearer {auth_token}"));
///         next.run(req, client).await
///     })
/// }
/// ```
pub struct Client {
    config: Config,
    effect_sender: Arc<dyn EffectSender + Send + Sync>,
    /// Holds the middleware stack.
    ///
    /// Note(Fishrock123): We do actually want this structure.
    /// The outer Arc allows us to clone in .send() without cloning the array.
    /// The Vec allows us to add middleware at runtime.
    /// The inner Arc-s allow us to implement Clone without sharing the vector with the parent.
    /// We don't use a Mutex around the Vec here because adding a middleware during execution should be an error.
    #[allow(clippy::rc_buffer)]
    middleware: Arc<Vec<Arc<dyn Middleware>>>,
}

impl Clone for Client {
    /// Clones the Client.
    ///
    /// This copies the middleware stack from the original, but shares
    /// the `HttpClient` and http client config of the original.
    /// Note that individual middleware in the middleware stack are
    /// still shared by reference.
    fn clone(&self) -> Self {
        Self {
            config: self.config.clone(),
            effect_sender: Arc::clone(&self.effect_sender),
            middleware: Arc::new(self.middleware.iter().cloned().collect()),
        }
    }
}

impl fmt::Debug for Client {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Client {{}}")
    }
}

impl Client {
    pub(crate) fn new<Sender>(sender: Sender) -> Self
    where
        Sender: EffectSender + Send + Sync + 'static,
    {
        Self {
            config: Config::default(),
            effect_sender: Arc::new(sender),
            middleware: Arc::new(vec![]),
        }
    }

    // This is currently dead code because there's no easy way to configure a client.
    // TODO: fix that in some future PR
    #[allow(dead_code)]
    /// Push middleware onto the middleware stack.
    ///
    /// See the [middleware] submodule for more information on middleware.
    ///
    /// [middleware]: ../middleware/index.html
    pub(crate) fn with(mut self, middleware: impl Middleware) -> Self {
        let m = Arc::get_mut(&mut self.middleware)
            .expect("Registering middleware is not possible after the Client has been used");
        m.push(Arc::new(middleware));
        self
    }

    /// Send a `Request` using this client.
    pub async fn send(&self, req: impl Into<Request>) -> Result<ResponseAsync> {
        let mut req: Request = req.into();
        let middleware = self.middleware.clone();

        let mw_stack = match req.take_middleware() {
            Some(req_mw) => {
                let mut mw = Vec::with_capacity(middleware.len() + req_mw.len());
                mw.extend(middleware.iter().cloned());
                mw.extend(req_mw);
                Arc::new(mw)
            }
            None => middleware,
        };

        let next = Next::new(&mw_stack, &|req, client| {
            Box::pin(async move {
                let req = req.into_protocol_request().await.unwrap();
                match client.effect_sender.send(req).await {
                    HttpResult::Ok(res) => Ok(res.into()),
                    HttpResult::Err(e) => Err(e),
                }
            })
        });

        let client = Self {
            config: self.config.clone(),
            effect_sender: Arc::clone(&self.effect_sender),
            // Erase the middleware stack for the Client accessible from within middleware.
            // This avoids gratuitous circular borrow & logic issues.
            middleware: Arc::new(vec![]),
        };

        let res = next.run(req, client).await?;
        Ok(ResponseAsync::new(res.into()))
    }

    /// Submit a `Request` and get the response body as bytes.
    pub async fn recv_bytes(&self, req: impl Into<Request>) -> Result<Vec<u8>> {
        let mut res = self.send(req.into()).await?;
        res.body_bytes().await
    }

    /// Submit a `Request` and get the response body as a string.
    pub async fn recv_string(&self, req: impl Into<Request>) -> Result<String> {
        let mut res = self.send(req.into()).await?;
        res.body_string().await
    }

    /// Submit a `Request` and decode the response body from json into a struct.
    pub async fn recv_json<T: serde::de::DeserializeOwned>(
        &self,
        req: impl Into<Request>,
    ) -> Result<T> {
        let mut res = self.send(req.into()).await?;
        res.body_json::<T>().await
    }

    /// Submit a `Request` and decode the response body from form encoding into a struct.
    ///
    /// # Errors
    ///
    /// Any I/O error encountered while reading the body is immediately returned
    /// as an `Err`.
    ///
    /// If the body cannot be interpreted as valid json for the target type `T`,
    /// an `Err` is returned.
    pub async fn recv_form<T: serde::de::DeserializeOwned>(
        &self,
        req: impl Into<Request>,
    ) -> Result<T> {
        let mut res = self.send(req.into()).await?;
        res.body_form::<T>().await
    }

    /// Perform an HTTP `GET` request using the `Client` connection.
    ///
    /// # Panics
    ///
    /// This will panic if a malformed URL is passed.
    ///
    /// # Errors
    ///
    /// Returns errors from the middleware, http backend, and network sockets.
    pub fn get(&self, uri: impl AsRef<str>) -> RequestBuilder<()> {
        RequestBuilder::new_for_middleware(Method::Get, self.url(uri), self.clone())
    }

    /// Perform an HTTP `HEAD` request using the `Client` connection.
    ///
    /// # Panics
    ///
    /// This will panic if a malformed URL is passed.
    ///
    /// # Errors
    ///
    /// Returns errors from the middleware, http backend, and network sockets.
    pub fn head(&self, uri: impl AsRef<str>) -> RequestBuilder<()> {
        RequestBuilder::new_for_middleware(Method::Head, self.url(uri), self.clone())
    }

    /// Perform an HTTP `POST` request using the `Client` connection.
    ///
    /// # Panics
    ///
    /// This will panic if a malformed URL is passed.
    ///
    /// # Errors
    ///
    /// Returns errors from the middleware, http backend, and network sockets.
    pub fn post(&self, uri: impl AsRef<str>) -> RequestBuilder<()> {
        RequestBuilder::new_for_middleware(Method::Post, self.url(uri), self.clone())
    }

    /// Perform an HTTP `PUT` request using the `Client` connection.
    ///
    /// # Panics
    ///
    /// This will panic if a malformed URL is passed.
    ///
    /// # Errors
    ///
    /// Returns errors from the middleware, http backend, and network sockets.
    pub fn put(&self, uri: impl AsRef<str>) -> RequestBuilder<()> {
        RequestBuilder::new_for_middleware(Method::Put, self.url(uri), self.clone())
    }

    /// Perform an HTTP `DELETE` request using the `Client` connection.
    ///
    /// # Panics
    ///
    /// This will panic if a malformed URL is passed.
    ///
    /// # Errors
    ///
    /// Returns errors from the middleware, http backend, and network sockets.
    pub fn delete(&self, uri: impl AsRef<str>) -> RequestBuilder<()> {
        RequestBuilder::new_for_middleware(Method::Delete, self.url(uri), self.clone())
    }

    /// Perform an HTTP `CONNECT` request using the `Client` connection.
    ///
    /// # Panics
    ///
    /// This will panic if a malformed URL is passed.
    ///
    /// # Errors
    ///
    /// Returns errors from the middleware, http backend, and network sockets.
    pub fn connect(&self, uri: impl AsRef<str>) -> RequestBuilder<()> {
        RequestBuilder::new_for_middleware(Method::Connect, self.url(uri), self.clone())
    }

    /// Perform an HTTP `OPTIONS` request using the `Client` connection.
    ///
    /// # Panics
    ///
    /// This will panic if a malformed URL is passed.
    ///
    /// # Errors
    ///
    /// Returns errors from the middleware, http backend, and network sockets.
    pub fn options(&self, uri: impl AsRef<str>) -> RequestBuilder<()> {
        RequestBuilder::new_for_middleware(Method::Options, self.url(uri), self.clone())
    }

    /// Perform an HTTP `TRACE` request using the `Client` connection.
    ///
    /// # Panics
    ///
    /// This will panic if a malformed URL is passed.
    ///
    /// # Errors
    ///
    /// Returns errors from the middleware, http backend, and network sockets.
    pub fn trace(&self, uri: impl AsRef<str>) -> RequestBuilder<()> {
        RequestBuilder::new_for_middleware(Method::Trace, self.url(uri), self.clone())
    }

    /// Perform an HTTP `PATCH` request using the `Client` connection.
    ///
    /// # Panics
    ///
    /// This will panic if a malformed URL is passed.
    ///
    /// # Errors
    ///
    /// Returns errors from the middleware, http backend, and network sockets.
    pub fn patch(&self, uri: impl AsRef<str>) -> RequestBuilder<()> {
        RequestBuilder::new_for_middleware(Method::Patch, self.url(uri), self.clone())
    }

    /// Perform a HTTP request with the given verb using the `Client` connection.
    ///
    /// # Panics
    ///
    /// This will panic if a malformed URL is passed.
    ///
    /// # Errors
    ///
    /// Returns errors from the middleware, http backend, and network sockets.
    pub fn request(&self, verb: Method, uri: impl AsRef<str>) -> RequestBuilder<()> {
        RequestBuilder::new_for_middleware(verb, self.url(uri), self.clone())
    }

    /// Get the current configuration.
    pub fn config(&self) -> &Config {
        &self.config
    }

    // private function to generate a url based on the base_path
    fn url(&self, uri: impl AsRef<str>) -> Url {
        match &self.config.base_url {
            None => uri.as_ref().parse().unwrap(),
            Some(base) => base.join(uri.as_ref()).unwrap(),
        }
    }
}

#[cfg(test)]
mod client_tests {
    use super::Client;
    use crate::protocol::{HttpRequest, HttpResponse};
    use crate::testing::FakeShell;

    #[futures_test::test]
    async fn an_http_get() {
        let mut shell = FakeShell::default();
        shell.provide_response(HttpResponse::ok().body("Hello World!").build());

        let client = Client::new(shell.clone());

        let mut response = client.get("https://example.com").await.unwrap();
        assert_eq!(response.body_string().await.unwrap(), "Hello World!");

        assert_eq!(
            shell.take_requests_received(),
            vec![HttpRequest::get("https://example.com/").build()]
        )
    }
}