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
mod request;
mod response;

pub use reqwest;
pub use response::Response;

use crate::request::RequestBuilder;
use http::Method;
use once_cell::sync::Lazy;
use reqwest::IntoUrl;
use std::time::Duration;
use tokio::runtime::{Builder as TokioBuilder, Runtime};

static DEFAULT_RUNTIME: Lazy<Runtime> = Lazy::new(|| {
    let runtime = TokioBuilder::new_multi_thread()
        .worker_threads(4)
        .thread_keep_alive(Duration::from_secs(60))
        .enable_time()
        .enable_io()
        .build()
        .unwrap();
    runtime
});

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error(transparent)]
    Sync(#[from] tarantool::cbus::RecvError),
    #[error(transparent)]
    Http(#[from] reqwest::Error),
    #[error("build request: {0}")]
    BuildRequest(reqwest::Error),
    #[error(transparent)]
    Decode(#[from] serde_json::Error),
}

pub type Result<T> = std::result::Result<T, Error>;

#[derive(Default)]
pub struct ClientBuilder<'a> {
    runtime: Option<&'a Runtime>,
    client: Option<reqwest::Client>,
}

impl<'a> ClientBuilder<'a> {
    /// Create a new builder.
    pub fn new() -> Self {
        Self::default()
    }

    /// Force http client to use given runtime over default tokio runtime.
    pub fn with_runtime(self, rt: &'a Runtime) -> Self {
        Self {
            runtime: Some(rt),
            ..self
        }
    }

    /// Change underline [`reqwest::Client`] instance to given.
    /// By default `radegast` create a default [`reqwest::Client`].
    pub fn with_reqwest_client(self, client: reqwest::Client) -> Self {
        Self {
            client: Some(client),
            ..self
        }
    }

    /// Create a [`Client`] instance.
    /// Note that, by default, using a [`DEFAULT_RUNTIME`] as tokio runtime.
    pub fn build(self, cbus_endpoint: &'a str) -> Result<Client> {
        let client = if let Some(client) = self.client {
            client
        } else {
            reqwest::ClientBuilder::new().build()?
        };

        Ok(Client {
            endpoint: cbus_endpoint,
            client,
            runtime: self.runtime.unwrap_or(&DEFAULT_RUNTIME),
        })
    }
}

#[derive(Clone)]
pub struct Client<'a> {
    endpoint: &'a str,
    client: reqwest::Client,
    runtime: &'a Runtime,
}

impl<'a> Client<'a> {
    /// Executes a `Request`.
    ///
    /// A `Request` can be built manually with `Request::new()` or obtained
    /// from a RequestBuilder with `RequestBuilder::build()`.
    ///
    /// You should prefer to use the `RequestBuilder` and
    /// `RequestBuilder::send()`.
    ///
    /// # Errors
    ///
    /// This method fails if there was an error while sending request,
    /// redirect loop was detected or redirect limit was exhausted.
    pub fn execute(&self, request: reqwest::Request) -> Result<Response<'a>> {
        let (tx, rx) = tarantool::cbus::oneshot::channel(self.endpoint);

        // clone client is ok, cause internally it's an `Arc`
        let client = self.client.clone();
        self.runtime.spawn(async move {
            let resp = client.execute(request).await;
            tx.send(resp)
        });

        let res = rx.receive()?.map(|reqwest_resp| Response {
            runtime: self.runtime,
            endpoint: self.endpoint,
            inner: reqwest_resp,
        });
        Ok(res?)
    }

    /// Start building a `Request` with the `Method` and `Url`.
    ///
    /// Returns a `RequestBuilder`, which will allow setting headers and
    /// the request body before sending.
    ///
    /// # Errors
    ///
    /// This method fails whenever the supplied `Url` cannot be parsed.
    pub fn request<U: IntoUrl>(&self, method: Method, url: U) -> RequestBuilder {
        RequestBuilder::new(self.clone(), method, url)
    }

    /// Convenience method to make a `GET` request to a URL.
    ///
    /// # Errors
    ///
    /// This method fails whenever the supplied `Url` cannot be parsed.
    pub fn get<U: IntoUrl>(&self, url: U) -> RequestBuilder {
        self.request(Method::GET, url)
    }

    /// Convenience method to make a `POST` request to a URL.
    ///
    /// # Errors
    ///
    /// This method fails whenever the supplied `Url` cannot be parsed.
    pub fn post<U: IntoUrl>(&self, url: U) -> RequestBuilder {
        self.request(Method::POST, url)
    }

    /// Convenience method to make a `PUT` request to a URL.
    ///
    /// # Errors
    ///
    /// This method fails whenever the supplied `Url` cannot be parsed.
    pub fn put<U: IntoUrl>(&self, url: U) -> RequestBuilder {
        self.request(Method::PUT, url)
    }

    /// Convenience method to make a `PATCH` request to a URL.
    ///
    /// # Errors
    ///
    /// This method fails whenever the supplied `Url` cannot be parsed.
    pub fn patch<U: IntoUrl>(&self, url: U) -> RequestBuilder {
        self.request(Method::PATCH, url)
    }

    /// Convenience method to make a `DELETE` request to a URL.
    ///
    /// # Errors
    ///
    /// This method fails whenever the supplied `Url` cannot be parsed.
    pub fn delete<U: IntoUrl>(&self, url: U) -> RequestBuilder {
        self.request(Method::DELETE, url)
    }

    /// Convenience method to make a `HEAD` request to a URL.
    ///
    /// # Errors
    ///
    /// This method fails whenever the supplied `Url` cannot be parsed.
    pub fn head<U: IntoUrl>(&self, url: U) -> RequestBuilder {
        self.request(Method::HEAD, url)
    }
}