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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
use std::{
    collections::{HashSet, VecDeque},
    sync::{Arc, RwLock},
};

use crate::{
    batch::BatchResult,
    config::{self, RqliteClientConfig, RqliteClientConfigBuilder},
    error::{ClientBuilderError, RequestError},
    node::{Node, NodeResponse, RemoveNodeRequest},
    query::{self, QueryArgs, RqliteQuery},
    query_result::QueryResult,
    request::{RequestOptions, RqliteQueryParam, RqliteQueryParams},
    response::{RqliteResponseRaw, RqliteResult},
    select::RqliteSelectResults,
};
use base64::{engine::general_purpose, Engine};
use reqwest::header;
use rqlite_rs_core::Row;

/// A client for interacting with a rqlite cluster.
pub struct RqliteClient {
    client: reqwest::Client,
    hosts: Arc<RwLock<VecDeque<String>>>,
    config: RqliteClientConfig,
}

/// A builder for creating a [`RqliteClient`].
#[derive(Default)]
pub struct RqliteClientBuilder {
    /// This uses a HashSet to ensure that no duplicate hosts are added.
    hosts: HashSet<String>,
    /// The configration for the client.
    config: RqliteClientConfigBuilder,
    // The base64 encoded credentials used to make authorized requests to the Rqlite cluster
    basic_auth: Option<String>,
}

impl RqliteClientBuilder {
    /// Creates a new [`RqliteClientBuilder`].
    pub fn new() -> Self {
        RqliteClientBuilder::default()
    }

    /// Adds basic auth credentials
    pub fn auth(mut self, user: &str, password: &str) -> Self {
        self.basic_auth = Some(general_purpose::STANDARD.encode(format!("{}:{}", user, password)));
        self
    }

    /// Adds a known host to the builder.
    pub fn known_host(mut self, host: impl ToString) -> Self {
        self.hosts.insert(host.to_string());
        self
    }

    /// Adds a default query parameter to the builder.
    pub fn default_query_params(mut self, params: Vec<RqliteQueryParam>) -> Self {
        self.config = self.config.default_query_params(params);
        self
    }

    /// Sets the scheme for the client.
    pub fn scheme(mut self, scheme: config::Scheme) -> Self {
        self.config = self.config.scheme(scheme);
        self
    }

    /// Builds the [`RqliteClient`] with the provided hosts.
    pub fn build(self) -> Result<RqliteClient, ClientBuilderError> {
        if self.hosts.is_empty() {
            return Err(ClientBuilderError::NoHostsProvided);
        }

        let hosts = VecDeque::from(self.hosts.into_iter().collect::<Vec<String>>());

        let mut headers = header::HeaderMap::new();
        headers.insert(
            header::CONTENT_TYPE,
            header::HeaderValue::from_static("application/json"),
        );

        if let Some(credentials) = self.basic_auth {
            let basic_auth_fmt = format!("Basic {}", credentials);
            headers.insert(
                header::AUTHORIZATION,
                header::HeaderValue::from_str(basic_auth_fmt.as_str())?,
            );
        }

        let mut client = reqwest::ClientBuilder::new()
            .timeout(std::time::Duration::from_secs(5))
            .default_headers(headers);

        if let Some(config::Scheme::Https) = self.config.scheme {
            client = client.https_only(true)
        }

        Ok(RqliteClient {
            client: client.build()?,
            hosts: Arc::new(RwLock::new(hosts)),
            config: self.config.build(),
        })
    }
}

impl RqliteClient {
    fn shift_host(&self) {
        let mut hosts = self.hosts.write().unwrap();
        hosts.rotate_left(1);
    }

    async fn try_request(
        &self,
        mut options: RequestOptions,
    ) -> Result<reqwest::Response, RequestError> {
        let (mut host, host_count) = {
            let hosts = self.hosts.read().unwrap();
            (hosts[0].clone(), hosts.len())
        };

        if let Some(default_params) = &self.config.default_query_params {
            options.merge_default_query_params(default_params);
        };

        for _ in 0..host_count {
            let req = options.to_reqwest_request(&self.client, host.as_str(), &self.config.scheme);

            match req.send().await {
                Ok(res) if res.status().is_success() => return Ok(res),
                Ok(res) => match res.status() {
                    reqwest::StatusCode::UNAUTHORIZED => {
                        return Err(RequestError::Unauthorized);
                    }
                    status => {
                        return Err(RequestError::ReqwestError {
                            body: res.text().await?,
                            status,
                        });
                    }
                },
                Err(e) => self.handle_request_error(e, &mut host)?,
            }
        }

        Err(RequestError::NoAvailableHosts)
    }

    fn handle_request_error(
        &self,
        e: reqwest::Error,
        host: &mut String,
    ) -> Result<(), RequestError> {
        if e.is_connect() || e.is_timeout() {
            let previous_host = host.clone();
            self.shift_host();
            let hosts = self.hosts.read().unwrap();
            *host = hosts[0].clone();
            println!("Connection to {} failed, trying {}", previous_host, *host);
            Ok(())
        } else {
            Err(RequestError::SwitchoverWrongError(e.to_string()))
        }
    }

    async fn exec_query<T>(&self, q: query::RqliteQuery) -> Result<RqliteResult<T>, RequestError>
    where
        T: serde::de::DeserializeOwned + Clone,
    {
        let res = self
            .try_request(RequestOptions {
                endpoint: q.endpoint(),
                body: Some(
                    q.into_json()
                        .map_err(RequestError::FailedParseRequestBody)?,
                ),
                ..Default::default()
            })
            .await?;

        let body = res.text().await?;

        let response = serde_json::from_str::<RqliteResponseRaw<T>>(&body)
            .map_err(RequestError::FailedParseResponseBody)?;

        response
            .results
            .into_iter()
            .next()
            .ok_or(RequestError::NoRowsReturned)
    }

    // To be implemented for different types of queries such as batch or qeued queries
    //async fn exec_many<T>(
    //    &self,
    //    qs: Vec<query::RqliteQuery>,
    //    params: impl Into<Option<Vec<RequestQueryParam>>>,
    //) -> anyhow::Result<Vec<RqliteResult<T>>>
    //where
    //    T: serde::de::DeserializeOwned + Clone,
    //{
    //    let args = QueryArgs::from(qs);
    //    let body = serde_json::to_string(&args)?;
    //
    //    let res = self.try_request("request", body, None).await?;
    //
    //    let body = res.text().await?;
    //
    //    let response = serde_json::from_str::<RqliteResponseRaw<T>>(&body)?;
    //
    //    Ok(response.results)
    //}

    /// Executes a query that returns results.
    /// Returns a vector of [`Row`]s if the query was successful, otherwise an error.
    pub async fn fetch<Q>(&self, q: Q) -> Result<Vec<Row>, RequestError>
    where
        Q: TryInto<RqliteQuery>,
        RequestError: From<Q::Error>,
    {
        let result = self
            .exec_query::<RqliteSelectResults>(q.try_into()?)
            .await?;

        match result {
            RqliteResult::Success(qr) => Ok(qr.rows()),
            RqliteResult::Error(qe) => Err(RequestError::DatabaseError(qe.error)),
        }
    }

    /// Executes a query that does not return any results.
    /// Returns the [`QueryResult`] if the query was successful, otherwise an error.
    /// Is primarily used for `INSERT`, `UPDATE`, `DELETE` and `CREATE` queries.
    pub async fn exec<Q>(&self, q: Q) -> Result<QueryResult, RequestError>
    where
        Q: TryInto<RqliteQuery>,
        RequestError: From<Q::Error>,
    {
        let query_result = self.exec_query::<QueryResult>(q.try_into()?).await?;

        match query_result {
            RqliteResult::Success(qr) => Ok(qr),
            RqliteResult::Error(qe) => Err(RequestError::DatabaseError(qe.error)),
        }
    }

    /// Executes a batch of queries.
    /// It allows sending multiple queries in a single request.
    /// This can be more efficient and reduces round-trips to the database.
    /// Returns a vector of [`RqliteResult`]s.
    /// Each result contains the result of the corresponding query in the batch.
    /// If a query fails, the corresponding result will contain an error.
    ///
    /// For more information on batch queries, see the [rqlite documentation](https://rqlite.io/docs/api/bulk-api/).
    pub async fn batch<Q>(&self, qs: Vec<Q>) -> Result<Vec<RqliteResult<BatchResult>>, RequestError>
    where
        Q: TryInto<RqliteQuery>,
        RequestError: From<Q::Error>,
    {
        let queries = qs
            .into_iter()
            .map(|q| q.try_into())
            .collect::<Result<Vec<RqliteQuery>, _>>()?;

        let batch = QueryArgs::from(queries);
        let body = serde_json::to_string(&batch).map_err(RequestError::FailedParseRequestBody)?;

        let res = self
            .try_request(RequestOptions {
                endpoint: "db/request".to_string(),
                body: Some(body),
                ..Default::default()
            })
            .await?;

        let body = res.text().await?;

        let results = serde_json::from_str::<RqliteResponseRaw<BatchResult>>(&body)
            .map_err(RequestError::FailedParseResponseBody)?
            .results;

        Ok(results)
    }

    /// Executes a transaction.
    /// A transaction is a set of queries that are executed as a single unit.
    /// If any of the queries fail, the entire transaction is rolled back.
    /// Returns a vector of [`RqliteResult`]s.
    ///
    /// For more information on transactions, see the [rqlite documentation](https://rqlite.io/docs/api/api/#transactions).
    pub async fn transaction<Q>(
        &self,
        qs: Vec<Q>,
    ) -> Result<Vec<RqliteResult<QueryResult>>, RequestError>
    where
        Q: TryInto<RqliteQuery>,
        RequestError: From<Q::Error>,
    {
        let queries = qs
            .into_iter()
            .map(|q| q.try_into())
            .collect::<Result<Vec<RqliteQuery>, _>>()?;

        let batch = QueryArgs::from(queries);
        let body = serde_json::to_string(&batch).map_err(RequestError::FailedParseRequestBody)?;

        let res = self
            .try_request(RequestOptions {
                endpoint: "db/execute".to_string(),
                body: Some(body),
                params: Some(
                    RqliteQueryParams::new()
                        .transaction()
                        .into_request_query_params(),
                ),
                ..Default::default()
            })
            .await?;

        let body = res.text().await?;

        let results = serde_json::from_str::<RqliteResponseRaw<QueryResult>>(&body)
            .map_err(RequestError::FailedParseResponseBody)?
            .results;

        Ok(results)
    }

    /// Asynchronously executes multiple queries.
    /// This results in much higher write performance.
    ///
    /// For more information on queued queries, see the [rqlite documentation](https://rqlite.io/docs/api/queued-writes/).
    pub async fn queue<Q>(&self, qs: Vec<Q>) -> Result<(), RequestError>
    where
        Q: TryInto<RqliteQuery>,
        RequestError: From<Q::Error>,
    {
        let queries = qs
            .into_iter()
            .map(|q| q.try_into())
            .collect::<Result<Vec<RqliteQuery>, _>>()?;

        let batch = QueryArgs::from(queries);
        let body = serde_json::to_string(&batch).map_err(RequestError::FailedParseRequestBody)?;

        self.try_request(RequestOptions {
            endpoint: "db/execute".to_string(),
            body: Some(body),
            params: Some(RqliteQueryParams::new().queue().into_request_query_params()),
            ..Default::default()
        })
        .await?;

        Ok(())
    }

    /// Checks if the rqlite cluster is ready.
    /// Returns `true` if the cluster is ready, otherwise `false`.
    pub async fn ready(&self) -> bool {
        match self
            .try_request(RequestOptions {
                endpoint: "readyz".to_string(),
                method: reqwest::Method::GET,
                ..Default::default()
            })
            .await
        {
            Ok(res) => res.status() == reqwest::StatusCode::OK,
            Err(_) => false,
        }
    }

    /// Retrieves the nodes in the rqlite cluster.
    /// Returns a vector of [`Node`]s.
    pub async fn nodes(&self) -> Result<Vec<Node>, RequestError> {
        let res = self
            .try_request(RequestOptions {
                endpoint: "nodes".to_string(),
                params: Some(
                    RqliteQueryParams::new()
                        .ver("2".to_string())
                        .into_request_query_params(),
                ),
                method: reqwest::Method::GET,
                ..Default::default()
            })
            .await?;

        let body = res.text().await?;

        let response = serde_json::from_str::<NodeResponse>(&body)
            .map_err(RequestError::FailedParseResponseBody)?;

        Ok(response.nodes)
    }

    /// Retrieves current the leader of the rqlite cluster.
    /// Returns a [`Node`] if a leader is found, otherwise `None`.
    pub async fn leader(&self) -> Result<Option<Node>, RequestError> {
        let nodes = self.nodes().await?;

        Ok(nodes.into_iter().find(|n| n.leader))
    }

    /// Removes a node from the rqlite cluster.
    /// Returns Ok on success and Err in case of an error.
    pub async fn remove_node(&self, id: &str) -> Result<(), RequestError> {
        let body = serde_json::to_string(&RemoveNodeRequest { id: id.to_string() })
            .map_err(RequestError::FailedParseRequestBody)?;

        let res = self
            .try_request(RequestOptions {
                endpoint: "remove".to_string(),
                body: Some(body),
                method: reqwest::Method::DELETE,
                ..Default::default()
            })
            .await?;

        if res.status().is_success() {
            Ok(())
        } else {
            Err(RequestError::DatabaseError(format!(
                "Failed to remove node: {}",
                res.text()
                    .await
                    .map_err(RequestError::FailedReadingResponse)?
            )))
        }
    }
}