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
//! 
//! Easy-to-use REST client for Rust programming language that provides
//! automatic serialization and deserialization from Rust structs. The library
//! is implemented using [Hyper](https://github.com/hyperium/hyper) and 
//! [Serde JSON](https://github.com/serde-rs/json).
//! 
//! # Examples
//! ```
//! extern crate restson;
//! #[macro_use]
//! extern crate serde_derive;
//! 
//! use restson::{RestClient,RestPath,Error};
//! 
//! // Data structure that matches with REST API JSON
//! #[derive(Serialize,Deserialize,Debug)]
//! struct HttpBinAnything {
//!     method: String,
//!     url: String,
//! }
//! 
//! // Path of the REST endpoint: e.g. http://<baseurl>/anything
//! impl RestPath<()> for HttpBinAnything {
//!     fn get_path(_: ()) -> Result<String,Error> { Ok(String::from("anything")) }
//! }
//!
//! fn main() {
//!     // Create new client with API base URL
//!     let mut client = RestClient::new("http://httpbin.org").unwrap();
//! 
//!     // GET http://httpbin.org/anything and deserialize the result automatically
//!     let data: HttpBinAnything = client.get(()).unwrap();
//!     println!("{:?}", data);
//! }
//! ```

extern crate futures;
extern crate hyper;
extern crate hyper_tls;
extern crate tokio_core;
extern crate serde;
extern crate serde_json;
extern crate url;
#[macro_use] 
extern crate log;

use futures::Future;
use futures::stream::Stream;
use futures::future::Either;
use hyper::{Client,Request,Method};
use hyper::header::*;
use hyper_tls::HttpsConnector;
use url::Url;
use tokio_core::reactor::Timeout;
use std::time::Duration;

static VERSION: &'static str = env!("CARGO_PKG_VERSION");

/// Type for URL query parameters. 
///
/// Slice of tuples in which the first field is parameter name and second is value.
/// These parameters are used with `get_with` and `post_with` functions.
///
/// # Examples
/// The vector
/// ```ignore
/// vec![("param1", "1234"), ("param2", "abcd")]
/// ```
/// would be parsed to **param1=1234&param2=abcd** in the request URL.
pub type Query<'a> = [(&'a str, &'a str)];


/// REST client to make HTTP GET and POST requests.
pub struct RestClient {
    core: tokio_core::reactor::Core,
    client: Client<HttpsConnector<hyper::client::HttpConnector>>,
    baseurl: url::Url,
    auth: Option<Authorization<Basic>>,
    headers: Headers,
    timeout: Duration,
}

/// Restson error return type.
#[derive(Debug)]
pub enum Error {
    /// HTTP client creation failed
    HttpClientError,

    /// Failed to parse final URL.
    UrlError,

    /// Failed to deserialize data to struct (in GET) or failed to 
    /// serialize struct to JSON (in POST).
    ParseError,

    /// Failed to make the outgoing request.
    RequestError,

    /// Server returned non-success status.
    HttpError(u16, String),

    /// Request has timed out
    TimeoutError,
}

/// Rest path builder trait for type.
///
/// Provides implementation for `rest_path` function that builds
/// type (and REST endpoint) specific API path from given parameter(s).
/// The built REST path is appended to the base URL given to `RestClient`.
/// If `Err` is returned, it is propagated directly to API caller.
pub trait RestPath<T> {
    /// Construct type specific REST API path from given parameters 
    /// (e.g. "api/devices/1234").
    fn get_path(par: T) -> Result<String, Error>;
}


impl RestClient {
    /// Construct new client to make HTTP requests.
    pub fn new(url: &str) -> Result<RestClient, Error> {
        let core = tokio_core::reactor::Core::new().map_err(|_| Error::HttpClientError)?;

        let handle = core.handle();
        let client = Client::configure()
            .connector(HttpsConnector::new(4, &handle).map_err(|_| Error::HttpClientError)?)
            .build(&handle);

        let baseurl = Url::parse(url).map_err(|_| Error::UrlError)?;

        debug!("new client for {}", baseurl);
        Ok(RestClient {
            core,
            client,
            baseurl,
            auth: None,
            headers: Headers::new(),
            // u64::MAX causes overflow when used with futures, u32::MAX is
            // sufficiently large for "no timeout"
            timeout: Duration::new(std::u32::MAX as u64, 0),
        })
    }

    /// Set credentials for HTTP Basic authentication.
    pub fn set_auth(&mut self, user: &str, pass: &str) { 
        self.auth = Some(Authorization(
            Basic {
                username: user.to_owned(),
                password: Some(pass.to_owned())
        }));
    }

    /// Set request timeout
    pub fn set_timeout(&mut self, timeout: Duration) {
        self.timeout = timeout;
    }

    /// Set HTTP header from string name and value.
    ///
    /// The header is added to all subsequent GET and POST requests
    /// unless the headers are cleared with `clear_headers()` call.
    pub fn set_header_raw(&mut self, name: &str, value: &str) {
        self.headers.set_raw(name.to_owned(), value)
    }

    /// Set HTTP header from hyper Header.
    ///
    /// The header is added to all subsequent GET and POST requests
    /// unless the headers are cleared with `clear_headers()` call.
    pub fn set_header<H: Header>(&mut self, header: H) {
        self.headers.set(header)
    }

    /// Clear all previously set headers
    pub fn clear_headers(&mut self) {
        self.headers.clear();
    }

    /// Make a GET request.
    pub fn get<U, T>(&mut self, params: U) -> Result<T, Error> where
        T: serde::de::DeserializeOwned + RestPath<U> {

        let req = self.make_request::<U,T>(Method::Get, params, None, None)?;
        let body = self.run_request(req)?;

        serde_json::from_str(body.as_str()).map_err(|_| Error::ParseError)
    }

    /// Make a GET request with query parameters.
    pub fn get_with<U, T>(&mut self, params: U, query: &Query) -> Result<T, Error> where
        T: serde::de::DeserializeOwned + RestPath<U> {
        let req = self.make_request::<U,T>(Method::Get, params, Some(query), None)?;
        let body = self.run_request(req)?;

        serde_json::from_str(body.as_str()).map_err(|_| Error::ParseError)
    }

    /// Make a POST request.
    pub fn post<U, T>(&mut self, params: U, data: &T) -> Result<(), Error> where 
        T: serde::Serialize + RestPath<U> {
        self.post_or_put(Method::Post, params, data)
    }

    /// Make a PUT request.
    pub fn put<U, T>(&mut self, params: U, data: &T) -> Result<(), Error> where 
        T: serde::Serialize + RestPath<U> {
        self.post_or_put(Method::Put, params, data)
    }

    fn post_or_put<U, T>(&mut self, method: Method, params: U, data: &T) -> Result<(), Error> where 
        T: serde::Serialize + RestPath<U> {
        let data = serde_json::to_string(data).map_err(|_| Error::ParseError)?;

        let req = self.make_request::<U,T>(method, params, None, Some(data))?;
        self.run_request(req)?;
        Ok(())
    }

    /// Make POST request with query parameters.
    pub fn post_with<U, T>(&mut self, params: U, data: &T, query: &Query) -> Result<(), Error> where 
        T: serde::Serialize + RestPath<U> {
        self.post_or_put_with(Method::Post, params, data, query)
    }

    /// Make PUT request with query parameters.
    pub fn put_with<U, T>(&mut self, params: U, data: &T, query: &Query) -> Result<(), Error> where 
        T: serde::Serialize + RestPath<U> {
        self.post_or_put_with(Method::Put, params, data, query)
    }

    fn post_or_put_with<U, T>(&mut self, method: Method, params: U, data: &T, query: &Query) -> Result<(), Error> where 
        T: serde::Serialize + RestPath<U> {
        let data = serde_json::to_string(data).map_err(|_| Error::ParseError)?;
        
        let req = self.make_request::<U,T>(method, params, Some(query), Some(data))?;
        self.run_request(req)?;
        Ok(())
    }

    /// Make a POST request and capture returned body.
    pub fn post_capture<U, T, K>(&mut self, params: U, data: &T) -> Result<K, Error> where 
        T: serde::Serialize + RestPath<U>,
        K: serde::de::DeserializeOwned {
        self.post_or_put_capture(Method::Post, params, data)
    }

    /// Make a PUT request and capture returned body.
    pub fn put_capture<U, T, K>(&mut self, params: U, data: &T) -> Result<K, Error> where 
        T: serde::Serialize + RestPath<U>,
        K: serde::de::DeserializeOwned {
        self.post_or_put_capture(Method::Put, params, data)
    }

    fn post_or_put_capture<U, T, K>(&mut self, method: Method, params: U, data: &T) -> Result<K, Error> where 
        T: serde::Serialize + RestPath<U>,
        K: serde::de::DeserializeOwned {
        let data = serde_json::to_string(data).map_err(|_| Error::ParseError)?;

        let req = self.make_request::<U,T>(method, params, None, Some(data))?;
        let body = self.run_request(req)?;
        serde_json::from_str(body.as_str()).map_err(|_| Error::ParseError)
    }

    /// Make a POST request with query parameters and capture returned body.
    pub fn post_capture_with<U, T, K>(&mut self, params: U, data: &T, query: &Query) -> Result<K, Error> where 
        T: serde::Serialize + RestPath<U>,
        K: serde::de::DeserializeOwned {
        self.post_or_put_capture_with(Method::Post, params, data, query)
    }

    /// Make a PUT request with query parameters and capture returned body.
    pub fn put_capture_with<U, T, K>(&mut self, params: U, data: &T, query: &Query) -> Result<K, Error> where 
        T: serde::Serialize + RestPath<U>,
        K: serde::de::DeserializeOwned {
        self.post_or_put_capture_with(Method::Put, params, data, query)
    }

    fn post_or_put_capture_with<U, T, K>(&mut self, method: Method, params: U, data: &T, query: &Query) -> Result<K, Error> where 
        T: serde::Serialize + RestPath<U>,
        K: serde::de::DeserializeOwned {
        let data = serde_json::to_string(data).map_err(|_| Error::ParseError)?;

        let req = self.make_request::<U,T>(method, params, Some(query), Some(data))?;
        let body = self.run_request(req)?;
        serde_json::from_str(body.as_str()).map_err(|_| Error::ParseError)
    }

    /// Make a DELETE request.
    pub fn delete<U, T>(&mut self, params: U) -> Result<(), Error> where
        T: RestPath<U> {

        let req = self.make_request::<U,T>(Method::Delete, params, None, None)?;
        self.run_request(req)?;
        Ok(())
    }

    fn run_request(&mut self, req: hyper::Request) -> Result<String, Error> {
        debug!("{} {}", req.method(), req.uri());
        trace!("{:?}", req);

        let req = self.client.request(req).and_then(|res| {
            trace!("response headers: {:?}", res.headers());

            let status = Box::new(res.status());
            res.body().map(|chunk| {
                String::from_utf8_lossy(&chunk).to_string()
            }).collect().map(|vec| {
                (status, vec.into_iter().collect())
            })
        });

        let timeout = Timeout::new(self.timeout, &self.core.handle()).map_err(|_| Error::RequestError)?;
        let work = req.select2(timeout).then(|res| match res {
            Ok(Either::A((got, _))) => Ok(got),
            Ok(Either::B((_, _))) => Err(Error::TimeoutError),
            Err(_) => Err(Error::RequestError)
        });

        match self.core.run(work) {
            Ok((status, body)) => {
                let status = *status;
                if !status.is_success() {
                    error!("server returned \"{}\" error", status);
                    return Err(Error::HttpError( status.as_u16(), body ));
                }
                trace!("response body: {}", body);
                Ok(body)
            },
            Err(e) => Err(e)
        }
    }

    pub fn make_request<U, T>(&mut self, method: Method, params: U, query: Option<&Query>, body: Option<String>) -> Result<Request,Error> where
        T: RestPath<U> {
        let uri = self.make_uri(T::get_path(params)?.as_str(), query)?;
        let mut req = Request::new(method, uri);

        if let Some(body) = body {
            req.headers_mut().set(ContentLength(body.len() as u64));
            req.headers_mut().set(ContentType(hyper::mime::APPLICATION_JSON));

            trace!("set request body: {}", body);
            req.set_body(body);
        }

        if let Some(ref auth) = self.auth {
            req.headers_mut().set(auth.clone());
        };

        req.headers_mut().extend(self.headers.iter());

        if req.headers().get::<UserAgent>().is_none() {
            req.headers_mut().set(UserAgent::new("restson/".to_owned() + VERSION));
        }

        Ok(req)
    }

    fn make_uri(&self, path: &str, params: Option<&Query>) -> Result<hyper::Uri, Error> {
        let mut url = self.baseurl.clone();
        url.set_path(path);

        if let Some(params) = params {
            for &(key, item) in params.iter() {
                url.query_pairs_mut().append_pair(key, item);
            }
        }

        url.as_str().parse::<hyper::Uri>().map_err(|_| Error::UrlError)
    }
}