Skip to main content

r2d2_influxdb/
lib.rs

1//! [r2d2](https://github.com/sfackler/r2d2) connection pool protocol for InfluxDB.
2
3pub extern crate influxdb;
4pub extern crate r2d2;
5
6pub mod ext;
7
8use ext::SyncClient;
9use influxdb::{Client, Error as InfluxDBError};
10
11use std::convert::From;
12use std::error;
13use std::error::Error as _StdError;
14use std::fmt;
15
16/// An extension for influxdb::Error for the Error trait
17#[derive(Debug)]
18pub enum Error {
19    Other(InfluxDBError),
20}
21
22impl fmt::Display for Error {
23    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
24        write!(fmt, "{}", self.description())
25    }
26}
27
28impl error::Error for Error {
29    fn description(&self) -> &str {
30        match *self {
31            Error::Other(ref err) => match err {
32                InfluxDBError::InvalidQueryError { .. } => "query is invalid",
33                InfluxDBError::UrlConstructionError { .. } => "failed to build URL",
34                InfluxDBError::ProtocolError { .. } => "http protocol error",
35                InfluxDBError::DeserializationError { .. } => "http protocol error",
36                InfluxDBError::DatabaseError { .. } => "database error",
37                InfluxDBError::AuthenticationError => "authentication error",
38                InfluxDBError::AuthorizationError => "authorization error",
39                InfluxDBError::ConnectionError { .. } => "connection error",
40            },
41        }
42    }
43}
44
45#[derive(Clone, Debug)]
46pub struct InfluxDBConnectionInfo {
47    url: String,
48    database: String,
49    username: Option<String>,
50    password: Option<String>,
51    is_auth: bool,
52}
53
54#[derive(Debug)]
55pub struct InfluxDBConnectionManager {
56    info: InfluxDBConnectionInfo,
57}
58
59impl InfluxDBConnectionManager {
60    pub fn new<T: Into<InfluxDBConnectionInfo>>(params: T) -> InfluxDBConnectionManager {
61        InfluxDBConnectionManager {
62            info: params.into(),
63        }
64    }
65}
66
67/// InfluxDB connection info
68pub struct SimpleInfo {
69    pub url: String,
70    pub database: String,
71}
72
73/// InfluxDB connection info with Authenticator
74pub struct AuthInfo {
75    pub url: String,
76    pub database: String,
77    pub username: String,
78    pub password: String,
79}
80
81impl From<SimpleInfo> for InfluxDBConnectionInfo {
82    fn from(item: SimpleInfo) -> Self {
83        InfluxDBConnectionInfo {
84            url: item.url,
85            database: item.database,
86            username: None,
87            password: None,
88            is_auth: false,
89        }
90    }
91}
92
93impl From<AuthInfo> for InfluxDBConnectionInfo {
94    fn from(item: AuthInfo) -> Self {
95        InfluxDBConnectionInfo {
96            url: item.url,
97            database: item.database,
98            username: Some(item.username),
99            password: Some(item.password),
100            is_auth: true,
101        }
102    }
103}
104
105/// An `r2d2::ConnectionManager` for `InfluxDB::Client`s.
106///
107/// ## Example
108///
109
110/// ```rust
111/// extern crate r2d2_influxdb;
112///
113/// use r2d2_influxdb::{r2d2, InfluxDBConnectionManager, SimpleInfo};
114/// use std::thread;
115///
116/// fn main() {
117///     let info = SimpleInfo {
118///         url: "http://localhost:8086".into(),
119///         database: "test".into(),
120///     };
121///     let manager = InfluxDBConnectionManager::new(info);
122///     let pool = r2d2::Pool::builder().build(manager).unwrap();
123///
124///     let mut handles = vec![];
125///
126///     for _i in 0..10i32 {
127///         let pool = pool.clone();
128///         handles.push(thread::spawn(move || {
129///             let conn = pool.get().unwrap();
130///             let reply = conn.ping();
131///             println!("{:?}", reply);
132///             assert!(reply.is_ok())
133///         }));
134///     }
135///
136///     for h in handles {
137///         h.join().unwrap();
138///     }
139/// }
140/// ```
141impl r2d2::ManageConnection for InfluxDBConnectionManager {
142    type Connection = SyncClient;
143    type Error = Error;
144
145    fn connect(&self) -> Result<SyncClient, Error> {
146        let client = if self.info.is_auth {
147            Client::new(self.info.url.to_owned(), self.info.database.to_owned()).with_auth(
148                self.info.username.to_owned().unwrap(),
149                self.info.password.to_owned().unwrap(),
150            )
151        } else {
152            Client::new(self.info.url.to_owned(), self.info.database.to_owned())
153        };
154        Ok(SyncClient::new(client))
155    }
156
157    fn is_valid(&self, conn: &mut SyncClient) -> Result<(), Error> {
158        conn.ping().map_err(Error::Other).map(|_| ())
159    }
160
161    fn has_broken(&self, conn: &mut SyncClient) -> bool {
162        self.is_valid(conn).is_err()
163    }
164}