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
use ::measurement::Measurement;
use ::serializer::Serializer;
use ::client::{Precision, Client, Credentials, ClientError, ClientReadResult, ClientWriteResult};
use ::hurl::{Hurl, Request, Response, Method, Auth};
use std::collections::HashMap;

const MAX_BATCH: u16 = 5000;

pub enum WriteStatus {
    Success,
    CouldNotComplete,
}

// fixme
pub struct Options {
    pub max_batch: Option<u16>,
    pub precision: Option<Precision>,
    
    pub epoch: Option<Precision>,
    pub chunk_size: Option<u16>
}

pub struct HttpClient<'a> {
    credentials: Credentials<'a>,
    serializer: Box<Serializer>,
    hurl: Box<Hurl>,
    hosts: Vec<&'a str>,
    pub max_batch: u16
}

impl<'a> HttpClient<'a> {
    pub fn new(credentials: Credentials<'a>, serializer: Box<Serializer>, hurl: Box<Hurl>) -> HttpClient<'a> {
        HttpClient {
            credentials: credentials,
            serializer: serializer,
            hurl: hurl,
            hosts: vec![],
            max_batch: MAX_BATCH
        }
    }

    pub fn add_host(&mut self, host: &'a str) {
        self.hosts.push(host);
    }

    fn get_host(&self) -> &'a str {
        match self.hosts.first() {
            Some(host) => host,
            None => panic!("Could not get host")
        }
    }
}

impl<'a> Client for HttpClient<'a> {
    fn query(&self, q: String, epoch: Option<Precision>) -> ClientReadResult {
        let host = self.get_host();

        let mut query = HashMap::new();
        query.insert("db", self.credentials.database.to_string());
        query.insert("q", q);

        match epoch {
            Some(ref epoch) => {
                query.insert("epoch", epoch.to_string());
            }
            _ => {}
        };

        let request = Request {
            url: &*{host.to_string() + "/query"},
            method: Method::GET,
            auth: Some(Auth {
                username: self.credentials.username,
                password: self.credentials.password
            }),
            query: Some(query),
            body: None
        };

        match self.hurl.request(request) {
            Ok(ref resp) if resp.status == 200 => Ok(resp.to_string()),
            Ok(ref resp) if resp.status == 400 => Err(ClientError::Syntax(resp.to_string())),
            Ok(ref resp) => Err(ClientError::Unexpected(format!("Unexpected response. Status: {}; Body: \"{}\"", resp.status, resp.to_string()))),
            Err(reason) => Err(ClientError::Communication(reason))
        }
    }

    fn write_one(&self, measurement: Measurement, precision: Option<Precision>) -> ClientWriteResult {
        self.write_many(&[measurement], precision)
    }

    fn write_many(&self, measurements: &[Measurement], precision: Option<Precision>) -> ClientWriteResult {
        let host = self.get_host();

        for chunk in measurements.chunks(self.max_batch as usize) {
            let mut lines = Vec::new();

            for measurement in chunk {
                lines.push(self.serializer.serialize(measurement));
            }

            let mut query = HashMap::new();
            query.insert("db", self.credentials.database.to_string());

            match precision {
                Some(ref precision) => {
                    query.insert("precision", precision.to_string());
                }
                _ => {}
            };

            let request = Request {
                url: &*{host.to_string() + "/write"},
                method: Method::POST,
                auth: Some(Auth {
                    username: self.credentials.username,
                    password: self.credentials.password
                }),
                query: Some(query),
                body: Some(lines.connect("\n"))
            };

            match self.hurl.request(request) {
                Ok(ref resp) if resp.status == 204 => {},
                Ok(ref resp) if resp.status == 200 => return Err(ClientError::CouldNotComplete(resp.to_string())),
                Ok(ref resp) if resp.status == 400 => return Err(ClientError::Syntax(resp.to_string())),
                Ok(ref resp) => return Err(ClientError::Unexpected(format!("Unexpected response. Status: {}; Body: \"{}\"", resp.status, resp.to_string()))),
                Err(reason) => return Err(ClientError::Communication(reason))
            };
        }

        Ok(())
    }
}



#[cfg(test)]
mod tests {
    use ::serializer::Serializer;
    use ::client::{Client};
    use super::HttpClient;
    use ::client::{Credentials, Precision};
    use ::hurl::{Hurl, Request, Response, HurlResult};
    use ::measurement::Measurement;
    use std::cell::Cell;
    use std::clone::Clone;

    const serialized : &'static str = "serialized";

    struct MockSerializer {
        serialize_count: Cell<u16>
    }

    impl MockSerializer {
        fn new() -> MockSerializer {
            MockSerializer {
                serialize_count: Cell::new(0)
            }
        }
    }

    impl Serializer for MockSerializer {
        fn serialize(&self, measurement: &Measurement) -> String {
            println!("serializing: {:?}", measurement);
            self.serialize_count.set(self.serialize_count.get() + 1);
            serialized.to_string()
        }
    }

    struct MockHurl {
        request_count: Cell<u16>,
        result: Box<Fn() -> HurlResult>
    }

    impl MockHurl {
        fn new(result: Box<Fn() -> HurlResult>) -> MockHurl {
            MockHurl {
                request_count: Cell::new(0),
                result: result
            }
        }
    }

    impl Hurl for MockHurl {
        fn request(&self, req: Request) -> HurlResult {
            self.request_count.set(self.request_count.get() + 1);
            println!("sending: {:?}", req);
            let ref f = self.result;
            f()
        }
    }

    fn before<'a>(result: Box<Fn() -> HurlResult>) -> HttpClient<'a> {        
        let credentials = Credentials {
            username: "gobwas",
            password: "1234",
            database: "test"
        };

        let serializer = MockSerializer::new();
        let hurl = MockHurl::new(result);

        HttpClient::new(credentials, Box::new(serializer), Box::new(hurl))
    }

    #[test]
    fn test_write_one() {
        let mut client = before(Box::new(|| Ok(Response { status: 200, body: "Ok".to_string() })));
        client.add_host("http://localhost:8086");
        client.write_one(Measurement::new("key"), Some(Precision::Nanoseconds));
    }

    #[test]
    fn test_write_many() {
        let mut client = before(Box::new(|| Ok(Response { status: 200, body: "Ok".to_string() })));
        client.add_host("http://localhost:8086");
        client.write_many(&[Measurement::new("key")], Some(Precision::Nanoseconds));
    }
}