rqlite_client 0.0.1-alpha.7

rqlite database client with optional extra convenience
Documentation
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
//! Implemented [`Request`] handling utilizing _crate_ [`ureq`](https://crates.io/crates/ureq)
#![cfg(feature = "ureq")]

use std::marker::PhantomData;

use lazy_static::lazy_static;

#[allow(clippy::module_name_repetitions)]
pub use self::request_type::RequestType;
use self::request_type::{Get, Post};
use crate::response::Result;
use crate::{log, tracing, Connection, Response};
use crate::{
    query::{Query, State},
    Error, RequestBuilder,
};

#[allow(clippy::module_name_repetitions)]
pub mod request_type;
mod tls;

/// Implemented [`Request`] handling utilizing _crate_ [`ureq`](https://crates.io/crates/ureq)
///
/// Requires enabled feature `ureq`.
///
/// Requests can be initialized manually, but there should be little requirements for.  
/// The preferred usage is via [`Query`] and [`Query::request_run()`].
///
#[derive(Clone, Debug)]
pub struct Request<T>
where
    T: RequestType,
{
    agent: Option<ureq::Agent>,
    t: PhantomData<T>,
}

impl<T> Request<T>
where
    T: RequestType,
{
    /// Create new `Request`
    #[must_use]
    pub fn new() -> Self {
        Self {
            agent: None,
            t: PhantomData,
        }
    }

    /// Create new `Request` for [`Connection`]
    ///
    /// Build and use a new [`ureq::Agent`].
    ///
    #[must_use]
    #[inline]
    pub fn from_connection(connection: &Connection) -> Self {
        let mut r = Request::<T>::new();
        r.agent = Some(user_agent(Some(connection)));
        r
    }
}

#[inline]
pub(crate) fn user_agent(connection: Option<&Connection>) -> ureq::Agent {
    let agent = ureq::AgentBuilder::new().user_agent(&DEFAULT_USER_AGENT);

    let proxy = connection
        .and_then(|c| {
            c.proxy()
                .map(String::from)
                .or_else(Connection::detect_proxy)
        })
        .or_else(Connection::detect_proxy);

    let agent = if let Some(proxy) = proxy {
        log::debug!("try proxy {proxy}");
        tracing::debug!("try proxy {proxy}");
        #[allow(clippy::needless_borrow)]
        match ureq::Proxy::new(&proxy) {
            Ok(ureq_proxy) => {
                log::info!("use proxy {proxy}");
                tracing::info!("use roxy {proxy}");
                agent.proxy(ureq_proxy)
            }
            Err(err) => {
                let _ = err;
                log::warn!("fail proxy {proxy}: {err}");
                tracing::warn!("fail proxy {proxy}: {err}");
                agent
            }
        }
    } else {
        agent
    };

    agent.build()
}

lazy_static! {
    /// default HTTP User-Agent header
    static ref DEFAULT_USER_AGENT: String = {
        format!("rqlite_client/{}", crate::BUILD_TIME)
    };

    /// request agent singleton
    static ref UREQ_AGENT: ureq::Agent = user_agent(None);
}

impl Request<Get> {
    fn request<T: State>(agent: Option<&ureq::Agent>, query: &Query<T>) -> Result {
        log::debug!("[GET] {}: {:?}", query.to_string(), query.sql());
        tracing::debug!("[GET] {}: {:?}", query.to_string(), query.sql());

        let agent = if let Some(agent) = agent {
            agent
        } else {
            &UREQ_AGENT
        };

        let r = agent
            .get(&query.to_string())
            .set("Content-Type", "application/json");

        let r = if let Some(timeout) = query.timeout_request() {
            r.timeout(*timeout)
        } else {
            r
        };

        let r = r.call().map_err(Error::from)?;

        Response::try_from(r)
    }
}

impl Request<Post> {
    fn request<T: State>(agent: Option<&ureq::Agent>, query: &Query<T>) -> Result {
        log::debug!("[POST] {}: {:?}", query.to_string(), query.sql());
        tracing::debug!("[POST] {}: {:?}", query.to_string(), query.sql());

        let agent = if let Some(agent) = agent {
            agent
        } else {
            &UREQ_AGENT
        };

        let r = agent
            .post(&query.to_string())
            .set("Content-Type", "application/json");

        let r = if let Some(timeout) = query.timeout_request() {
            r.timeout(*timeout)
        } else {
            r
        };

        let r = r.send_json(query.sql()).map_err(Error::from)?;

        Response::try_from(r)
    }
}

impl<T> Default for Request<T>
where
    T: RequestType,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<T> From<&Connection> for Request<T>
where
    T: RequestType,
{
    fn from(connection: &Connection) -> Self {
        Self::from_connection(connection)
    }
}

impl<T> From<Connection> for Request<T>
where
    T: RequestType,
{
    fn from(connection: Connection) -> Self {
        Self::from_connection(&connection)
    }
}

impl From<Get> for Request<Get> {
    fn from(_value: Get) -> Self {
        Request::<Get>::new()
    }
}

impl From<Post> for Request<Post> {
    fn from(_value: Post) -> Self {
        Request::<Post>::new()
    }
}

impl<S> RequestBuilder<S> for Request<Get>
where
    S: State,
{
    #[inline]
    fn run(&self, query: &Query<S>) -> Result {
        Self::request(self.agent.as_ref(), query)
    }
}

impl<S> RequestBuilder<S> for Request<Post>
where
    S: State,
{
    #[inline]
    fn run(&self, query: &Query<S>) -> Result {
        Self::request(self.agent.as_ref(), query)
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use lazy_static::lazy_static;

    use crate::{
        query::Query,
        response::{
            self,
            mapping::{self, Mapping},
        },
        test_rqlited::TEST_RQLITED_DB,
        Connection, DataType, Request, RequestBuilder,
    };

    use super::request_type::{Get, Post};

    const TEST_CONNECTION_URL: &str = "http://localhost:4001/";
    const TEST_PROXY_URL: &str = "http://proxy.example.com:12345";
    const TEST_SOCKS_PROXY_URL: &str = "socks5://user:password@127.0.0.1:12345";

    #[cfg(feature = "url")]
    lazy_static! {
        static ref TEST_CONNECTION: Connection = Connection::new(TEST_CONNECTION_URL).unwrap();
        static ref TEST_PROXY_CONNECTION: Connection = Connection::new(TEST_CONNECTION_URL)
            .unwrap()
            .set_proxy(TEST_PROXY_URL);
        static ref TEST_SOCKS_PROXY_CONNECTION: Connection = Connection::new(TEST_CONNECTION_URL)
            .unwrap()
            .set_proxy(TEST_SOCKS_PROXY_URL);
    }
    #[cfg(not(feature = "url"))]
    lazy_static! {
        static ref TEST_CONNECTION: Connection = Connection::new(TEST_CONNECTION_URL);
        static ref TEST_PROXY_CONNECTION: Connection =
            Connection::new(TEST_CONNECTION_URL).set_proxy(TEST_PROXY_URL);
        static ref TEST_SOCKS_PROXY_CONNECTION: Connection =
            Connection::new(TEST_CONNECTION_URL).set_proxy(TEST_SOCKS_PROXY_URL);
    }

    #[test]
    fn nolevel_test() {
        TEST_RQLITED_DB.run_test(|| {
            let r = Request::from(Get).run(&Query::new(&TEST_CONNECTION).set_sql_str("SELECT 1"));

            assert!(r.is_ok(), "response error: {}", r.err().unwrap());

            let r = response::query::Query::from(r.unwrap());
            let result = r.results().next().unwrap();

            match result {
                Mapping::Standard(result) => {
                    assert_eq!(
                        result,
                        &mapping::Standard {
                            columns: vec!["1".to_string()],
                            time: None,
                            types: vec![DataType::Integer],
                            values: Some(vec![vec![1.into()]])
                        }
                    );
                }
                _ => unreachable!(),
            }
        });
    }

    #[test]
    fn nolevel_request_run_test() {
        TEST_RQLITED_DB.run_test(|| {
            let r = TEST_CONNECTION
                .query()
                .set_sql_str("SELECT 1")
                .request_run();

            assert!(r.is_ok(), "response error: {}", r.err().unwrap());

            let r = response::query::Query::from(r.unwrap());
            let result = r.results().next().unwrap();

            match result {
                Mapping::Standard(result) => {
                    assert_eq!(
                        result,
                        &mapping::Standard {
                            columns: vec!["1".to_string()],
                            time: None,
                            types: vec![DataType::Integer],
                            values: Some(vec![vec![1.into()]])
                        }
                    );
                }
                _ => unreachable!(),
            }
        });
    }

    #[test]
    fn proxy_test() {
        TEST_RQLITED_DB.run_test(|| {
            let r = Request::<Get>::from(&*TEST_PROXY_CONNECTION).run(
                &Query::new(&TEST_PROXY_CONNECTION)
                    .set_timeout_request(Duration::from_millis(10))
                    .set_sql_str("SELECT 1"),
            );

            assert!(r.is_err());
            let err_msg = r.unwrap_err().to_string();
            assert!(
                err_msg.contains("Dns Failed") || err_msg.contains("Connection Failed"),
                "{}",
                err_msg
            );
        });
    }

    #[test]
    fn query_post_switch_test() {
        TEST_RQLITED_DB.run_test(|| {
            let r = TEST_CONNECTION
                .query()
                .set_sql_str_slice(&["SELECT COUNT(*) FROM test4zc99f where val = ?", "test"])
                .request_run();

            assert!(r.is_ok(), "response error: {}", r.err().unwrap());

            let r = response::query::Query::from(r.unwrap());
            let result = r.results().next().unwrap();

            match result {
                Mapping::Error(result) => {
                    assert!(
                        result.error.contains("no such table: test4zc99f"),
                        "{}",
                        result.error
                    );
                }
                _ => unreachable!(),
            }
        });
    }

    #[test]
    fn request_timeout_test() {
        TEST_RQLITED_DB.run_test(|| {
            let r = Request::<Get>::new().run(
                &Query::new(&TEST_CONNECTION)
                    .set_timeout_request(Duration::from_nanos(10))
                    .set_sql_str("SELECT 1"),
            );

            assert!(r.is_err());
            let err_msg = r.unwrap_err().to_string();
            assert!(
                err_msg.contains("Network Error") && err_msg.contains("timed out"),
                "{}",
                err_msg
            );
        });
    }

    #[test]
    fn socks_proxy_test() {
        TEST_RQLITED_DB.run_test(|| {
            let r = Request::<Get>::from(&*TEST_SOCKS_PROXY_CONNECTION).run(
                &Query::new(&TEST_SOCKS_PROXY_CONNECTION)
                    .set_timeout_request(Duration::from_millis(10))
                    .set_sql_str("SELECT 1"),
            );

            assert!(r.is_err());
            let err_msg = r.unwrap_err().to_string();
            #[cfg(feature = "ureq_socks_proxy")]
            assert!(
                err_msg.contains("Dns Failed") || err_msg.contains("Connection Failed"),
                "{}",
                err_msg
            );
            #[cfg(not(feature = "ureq_socks_proxy"))]
            assert!(err_msg.contains("SOCKS feature disabled"), "{}", err_msg);
        });
    }

    #[test]
    fn weak_multi_test() {
        TEST_RQLITED_DB.run_test(|| {
            let r = Request::<Post>::new().run(
                &Query::new(&TEST_CONNECTION)
                    .set_weak()
                    .push_sql_str("SELECT 1")
                    .push_sql_str("SELECT date()"),
            );

            assert!(r.is_ok(), "response error: {}", r.err().unwrap());

            let r = response::query::Query::from(r.unwrap());

            let mut results = r.results();
            let result = results.next().unwrap();

            match result {
                Mapping::Standard(result) => {
                    assert_eq!(
                        result,
                        &mapping::Standard {
                            columns: vec!["1".to_string()],
                            time: None,
                            types: vec![DataType::Integer],
                            values: Some(vec![vec![1.into()]])
                        }
                    );
                }
                _ => unreachable!(),
            }

            let result = results.next().unwrap();

            match result {
                Mapping::Standard(result) => {
                    assert_eq!(
                        result,
                        &mapping::Standard {
                            columns: vec!["date()".to_string()],
                            time: None,
                            types: vec![DataType::Text],
                            values: Some(vec![vec![time::OffsetDateTime::now_utc()
                                .format(
                                    &time::format_description::parse("[year]-[month]-[day]")
                                        .unwrap()
                                )
                                .unwrap()
                                .into()]])
                        }
                    );
                }
                _ => unreachable!(),
            }
        });
    }
}