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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
/*!
Elasticsearch REST API Client

A lightweight implementation of the Elasticsearch API based on the [`reqwest`][reqwest] HTTP client.

Each API endpoint is represented as its own type, that only accept a valid combination of route parameters.
This library makes very few assumptions, leaving it up to you to decide what to invest your precious CPU cycles into.

The API is generated from the official Elasticsearch spec, so it's always current.

# Supported Versions

 `elastic_types` | Elasticsearch
 --------------- | -------------
 `0.x`           | `5.x`

# Usage

This crate is on [crates.io][crates].
To get started, add `elastic_reqwest` and `reqwest` to your `Cargo.toml`:

```ignore
[dependencies]
elastic_reqwest = "*"
reqwest = "*"
```

Then reference in your crate root:

```
extern crate elastic_reqwest;
# fn main() {}
```

# Making synchronous requests

- Create a [`SyncClient`][default_sync]
- Call [`elastic_req`][elastic_req_sync] on the client
- Work with the raw http response
- Or call [`parse`][parse] to get a concrete response or API error

## Minimal Example

Execute a search request synchronously and parse the response:

```no_run
//HTTP POST /myindex/mytype/_search

#[macro_use]
extern crate serde_json;
extern crate elastic_reqwest;

use serde_json::Value;
use elastic_reqwest::{SyncElasticClient, SyncFromResponse, parse};
use elastic_reqwest::req::SearchRequest;
use elastic_reqwest::res::SearchResponse;

# fn main() {
let (client, params) = elastic_reqwest::sync::default().unwrap();

let search = SearchRequest::for_index_ty(
    "myindex", "mytype",
    json!({
        "query": {
            "filtered": {
                "query": {
                    "match_all": {}
                },
                "filter": {
                    "geo_distance": {
                        "distance": "20km",
                        "location": {
                            "lat": 37.776,
                            "lon": -122.41
                        }
                    }
                }
            }
        }
    })
);

let http_res = client.elastic_req(&params, search).unwrap();
let search_res = parse::<SearchResponse<Value>>().from_response(http_res).unwrap();
# }
```

# Making asynchronous requests

- Create an [`AsyncClient`][default_async]
- Call [`elastic_req`][elastic_req_async] on the client
- Work with the raw http response
- Or call [`parse`][parse] to get a concrete response or API error

## Minimal Example

Execute a search request asynchronously and parse the response:

```no_run
//HTTP POST /myindex/mytype/_search

#[macro_use]
extern crate serde_json;
extern crate elastic_reqwest;
extern crate tokio_core;
extern crate futures;

use tokio_core::reactor::Core;
use futures::Future;
use serde_json::Value;
use elastic_reqwest::{AsyncElasticClient, AsyncFromResponse, parse};
use elastic_reqwest::req::SearchRequest;
use elastic_reqwest::res::SearchResponse;

# fn main() {
let mut core = Core::new().unwrap();

let (client, params) = elastic_reqwest::async::default(&core.handle()).unwrap();

let search = SearchRequest::for_index_ty(
    "myindex", "mytype",
    json!({
        "query": {
            "filtered": {
                "query": {
                    "match_all": {}
                },
                "filter": {
                    "geo_distance": {
                        "distance": "20km",
                        "location": {
                            "lat": 37.776,
                            "lon": -122.41
                        }
                    }
                }
            }
        }
    })
);

let search_future = client
    .elastic_req(&params, search)
    .and_then(|http_res| parse::<SearchResponse<Value>>().from_response(http_res))
    .and_then(|search_res| {
        println!("{:?}", search_res);
        Ok(())  
    });

core.run(search_future).unwrap();
# }
```

## Search Request with Url Param

Execute a search request with a url parameter:

```no_run
//HTTP GET /myindex/mytype/_search?q=*

extern crate serde_json;
extern crate elastic_reqwest;

use serde_json::Value;
use elastic_reqwest::{ SyncElasticClient, SyncFromResponse, RequestParams, parse };
use elastic_reqwest::req::SimpleSearchRequest;
use elastic_reqwest::res::SearchResponse;

# fn main() {
let (client, _) = elastic_reqwest::sync::default().unwrap();

let params = RequestParams::default()
    .url_param("pretty", true)
    .url_param("q", "*");

let search = SimpleSearchRequest::for_index_ty(
    "myindex", "mytype"
);

let http_res = client.elastic_req(&params, search).unwrap();
let search_res = parse::<SearchResponse<Value>>().from_response(http_res).unwrap();
# }
```

# See Also

- [`elastic`][elastic].
A higher-level Elasticsearch client that uses `elastic_reqwest` as its HTTP layer.
- [`rs-es`][rs-es].
A higher-level Elasticsearch client that provides strongly-typed Query DSL buiilders.
- [`json_str`][json_str]
A library for generating minified json strings from Rust syntax.

# Links
- [Elasticsearch Docs][es-docs]
- [Github][repo]

[default_sync]: sync/fn.default.html
[default_async]: async/fn.default.html
[elastic_req_sync]: sync/trait.SyncElasticClient.html#tymethod.elastic_req
[elastic_req_async]: async/trait.AsyncElasticClient.html#tymethod.elastic_req
[parse]: fn.parse.html
[elastic]: https://github.com/elastic-rs/elastic
[rs-es]: https://github.com/benashford/rs-es
[json_str]: https://github.com/KodrAus/json_str
[reqwest]: https://github.com/seanmonstar/reqwest/
[es-docs]: https://www.elastic.co/guide/en/elasticsearch/reference/master/index.html
[repo]: https://github.com/elastic-rs/elastic-reqwest
[crates]: https://crates.io/crates/elastic_reqwest
*/

#![deny(warnings)]
#![deny(missing_docs)]

#[macro_use]
extern crate quick_error;

extern crate bytes;
extern crate elastic_requests;
extern crate elastic_responses;
extern crate futures;
extern crate reqwest;
extern crate serde;
#[cfg_attr(test, macro_use)]
extern crate serde_json;
extern crate tokio_core;
extern crate url;

mod private {
    pub trait Sealed {}
}

pub mod sync;
pub mod async;

pub use self::sync::{SyncBody, SyncElasticClient, SyncFromResponse};
pub use self::async::{AsyncBody, AsyncElasticClient, AsyncFromResponse};

/**
Request types.

These are re-exported from `elastic_requests` for convenience.
*/
pub mod req {
    pub use elastic_requests::*;
}

/**
Response types.

These are re-exported from `elastic_responses` for convenience.
*/
pub mod res {
    pub use elastic_responses::*;
}

pub use self::res::parse;

use std::sync::Arc;
use std::collections::BTreeMap;
use std::str;
use reqwest::Error as ReqwestError;
use reqwest::header::{ContentType, Header, Headers};
use url::form_urlencoded::Serializer;

use self::res::error::ResponseError;
use self::req::HttpMethod;

quick_error! {
    /** An error sending a request or parsing a response. */
    #[derive(Debug)]
    pub enum Error {
        /** A http error. */
        Http(err: ReqwestError) {
            from()
            description("http error")
            display("http error: {}", err)
            cause(err)
        }
        /** A response error. */
        Response(err: ResponseError) {
            from()
            description("response error")
            display("response error: {}", err)
            cause(err)
        }
        #[doc(hidden)]
        __NonExhaustive
    }
}

/**
Misc parameters for any request.

The `RequestParams` struct allows you to set headers and url parameters for your requests.
By default, the `ContentType::json` header will always be added.
Url parameters are added as simple key-value pairs, and serialised by [rust-url](http://servo.github.io/rust-url/url/index.html).

# Examples

With default query parameters:

```
# use elastic_reqwest::RequestParams;
let params = RequestParams::default();
```

With a custom base url:

```
# use elastic_reqwest::RequestParams;
let params = RequestParams::new("http://mybaseurl:9200");
```

With custom headers:

```
# extern crate reqwest;
# extern crate elastic_reqwest;
# use elastic_reqwest::RequestParams;
# use reqwest::header::Authorization;
# fn main() {
let params = RequestParams::default()
    .header(Authorization("let me in".to_owned()));
# }
```

With url query parameters:

```
# extern crate elastic_reqwest;
# use elastic_reqwest::RequestParams;
# fn main() {
let params = RequestParams::default()
    .url_param("pretty", true)
    .url_param("q", "*");
# }
```
*/
#[derive(Clone)]
pub struct RequestParams {
    /** Base url for Elasticsearch. */ base_url: String,
    /** Simple key-value store for url query params. */ url_params: BTreeMap<&'static str, String>,
    /** The complete set of headers that will be sent with the request. */ headers_factory: Option<Arc<Fn(&mut Headers) + Send + Sync + 'static>>,
}

impl RequestParams {
    /** 
    Create a new container for request parameters.
    
    This method takes a fully-qualified url for the Elasticsearch node.
    It will also set the `Content-Type` header to `application/json`.
    */
    pub fn new<T: Into<String>>(base: T) -> Self {
        RequestParams {
            base_url: base.into(),
            headers_factory: None,
            url_params: BTreeMap::new(),
        }
    }

    /** Set the base url for the Elasticsearch node. */
    pub fn base_url<T: Into<String>>(mut self, base: T) -> Self {
        self.base_url = base.into();

        self
    }

    /** 
    Set a url param value.
    
    These parameters are added as query parameters to request urls.
    */
    pub fn url_param<T: ToString>(mut self, key: &'static str, value: T) -> Self {
        self.url_params.insert(key, value.to_string());
        self
    }

    /** Set a request header. */
    pub fn header<H>(self, header: H) -> Self
    where
        H: Header + Clone,
    {
        self.headers(move |h| h.set(header.clone()))
    }

    /** 
    Set a header value on the params.
    
    Each call to `headers` will chain to the end of the last call.
    This function allocates a new `Box` for each call.

    Once we can depend on `http` this might go away.
    */
    fn headers<F>(mut self, headers_factory: F) -> Self
    where
        F: Fn(&mut Headers) + Send + Sync + 'static,
    {
        if let Some(old_headers_factory) = self.headers_factory {
            let headers_factory = move |mut headers: &mut Headers| {
                old_headers_factory(&mut headers);
                headers_factory(&mut headers);
            };

            self.headers_factory = Some(Arc::new(headers_factory));
        } else {
            self.headers_factory = Some(Arc::new(headers_factory));
        }

        self
    }

    /** Get the base url. */
    pub fn get_base_url(&self) -> &str {
        &self.base_url
    }

    /** Create a new `Headers` structure, and thread it through the configuration functions. */
    pub fn get_headers(&self) -> Headers {
        let mut headers = Headers::new();
        headers.set(ContentType::json());

        if let Some(ref headers_factory) = self.headers_factory {
            headers_factory(&mut headers);
        }

        headers
    }

    /** 
    Get the url query params as a formatted string.
    
    Follows the `application/x-www-form-urlencoded` format.
    This method returns the length of the query string and an optional value.
    If the value is `None`, then the length will be `0`.
    */
    pub fn get_url_qry(&self) -> (usize, Option<String>) {
        if self.url_params.len() > 0 {
            let qry: String = Serializer::for_suffix(String::from("?"), 1)
                .extend_pairs(self.url_params.iter())
                .finish();

            (qry.len(), Some(qry))
        } else {
            (0, None)
        }
    }
}

impl Default for RequestParams {
    fn default() -> Self {
        RequestParams::new("http://localhost:9200")
    }
}

fn build_url<'a>(req_url: &str, params: &RequestParams) -> String {
    let (qry_len, qry) = params.get_url_qry();

    let mut url = String::with_capacity(params.base_url.len() + req_url.len() + qry_len);

    url.push_str(&params.base_url);
    url.push_str(&req_url);

    if let Some(qry) = qry {
        url.push_str(&qry);
    }

    url
}

fn build_method(method: HttpMethod) -> reqwest::Method {
    match method {
        HttpMethod::Get => reqwest::Method::Get,
        HttpMethod::Post => reqwest::Method::Post,
        HttpMethod::Head => reqwest::Method::Head,
        HttpMethod::Delete => reqwest::Method::Delete,
        HttpMethod::Put => reqwest::Method::Put,
        HttpMethod::Patch => reqwest::Method::Patch,
    }
}

#[cfg(test)]
fn assert_send<T: Send>() {}

#[cfg(test)]
fn assert_sync<T: Sync>() {}

#[cfg(test)]
mod tests {
    use reqwest::header::{Authorization, ContentType, Referer};
    use super::*;

    #[test]
    fn assert_send_sync() {
        assert_send::<RequestParams>();
        assert_sync::<RequestParams>();
    }

    #[test]
    fn request_params_has_default_content_type() {
        let req = RequestParams::default();

        let headers = req.get_headers();

        assert_eq!(Some(&ContentType::json()), headers.get::<ContentType>());
    }

    #[test]
    fn set_multiple_headers() {
        let req = RequestParams::default()
            .headers(|h| h.set(Referer::new("/not-the-value")))
            .headers(|h| h.set(Referer::new("/People.html#tim")))
            .headers(|h| h.set(Authorization("let me in".to_owned())));

        let headers = req.get_headers();

        assert_eq!(Some(&ContentType::json()), headers.get::<ContentType>());
        assert_eq!(
            Some(&Referer::new("/People.html#tim")),
            headers.get::<Referer>()
        );
        assert_eq!(
            Some(&Authorization("let me in".to_owned())),
            headers.get::<Authorization<String>>()
        );
    }

    #[test]
    fn request_params_has_default_base_url() {
        let req = RequestParams::default();

        assert_eq!("http://localhost:9200", req.base_url);
    }

    #[test]
    fn request_params_can_set_base_url() {
        let req = RequestParams::default().base_url("http://eshost:9200");

        assert_eq!("http://eshost:9200", req.base_url);
    }

    #[test]
    fn request_params_can_set_url_query() {
        let req = RequestParams::default()
            .url_param("pretty", false)
            .url_param("pretty", true)
            .url_param("q", "*");

        assert_eq!(
            (16, Some(String::from("?pretty=true&q=*"))),
            req.get_url_qry()
        );
    }

    #[test]
    fn empty_request_params_returns_empty_string() {
        let req = RequestParams::default();

        assert_eq!((0, None), req.get_url_qry());
    }
}