Skip to content

Commit c8b4ba3

Browse files
authored
Add raw pre_send method (#285)
* add raw pre_send method * introduce `http` crate for shared HTTP types
1 parent a6a0639 commit c8b4ba3

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

71 files changed

+4826
-4620
lines changed

examples/account_sample/src/ops/commands/ensure_bank_index_exists.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use serde_json::Error as JsonError;
44
use elastic::client::requests::IndicesExistsRequest;
55
use elastic::client::responses::CommandResponse;
66
use elastic::Error as ResponseError;
7+
use elastic::http::StatusCode;
78

89
use model;
910

@@ -19,9 +20,9 @@ impl EnsureBankIndexExists for Client {
1920

2021
match exists.status() {
2122
// Success, do nothing
22-
200 => (),
23+
StatusCode::OK => (),
2324
// Not found, create the index
24-
404 => {
25+
StatusCode::NOT_FOUND => {
2526
self.io
2627
.index_create(model::index::name())
2728
.body(model::index::body().to_string())

examples/account_sample/src/ops/commands/put_bulk_accounts.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,9 @@ use std::io::{Error as IoError, Result as IoResult};
22
use std::fs::File;
33
use std::path::Path;
44
use ops::Client;
5-
use elastic::client::requests::{BulkRequest, SyncBody};
5+
use elastic::client::requests::BulkRequest;
66
use elastic::client::responses::bulk::{BulkErrorsResponse, ErrorItem};
7+
use elastic::http::SyncBody;
78
use elastic::Error as ResponseError;
89

910
use model;

src/elastic/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,14 @@ log = "~0.3.8"
2020
uuid = { version = "~0.5.1", features = [ "v4" ] }
2121
url = "~1.5.1"
2222
bytes = "~0.4.5"
23+
http = "~0.1.0"
2324
serde = "~1"
2425
serde_json = "~1"
2526
serde_derive = "~1"
2627
reqwest = { version = "~0.8.0", features = ["unstable"] }
2728
futures = "~0.1.16"
2829
tokio-core = "~0.1.9"
30+
tokio-io = "~0.1.4"
2931
futures-cpupool = "~0.1.6"
3032
fluent_builder = "~0.5"
3133

src/elastic/examples/custom_response.rs

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -33,15 +33,9 @@ struct Hit {
3333
#[serde(rename = "_source")] pub source: Value,
3434
}
3535

36-
// Implement `IsOk` for our custom `SearchResponse` so it can be used in the call to `into_response`.
37-
impl IsOk for SearchResponse {
38-
fn is_ok<B: ResponseBody>(head: HttpResponseHead, body: Unbuffered<B>) -> Result<MaybeOkResponse<B>, ParseError> {
39-
match head.status() {
40-
200...299 => Ok(MaybeOkResponse::ok(body)),
41-
_ => Ok(MaybeOkResponse::err(body)),
42-
}
43-
}
44-
}
36+
// Implement `IsOkOnSuccess` for our custom `SearchResponse` so it can be used in the call to `into_response`.
37+
// `IsOkOnSuccess` will return `Ok` if the response is in the `200` range.
38+
impl IsOkOnSuccess for SearchResponse { }
4539

4640
fn run() -> Result<(), Box<Error>> {
4741
// A reqwest HTTP client and default parameters.

src/elastic/examples/pre_send.rs

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
//! Tweak the raw http request before sending.
2+
//!
3+
//! NOTE: This sample expects you have a node running on `localhost:9200`.
4+
5+
extern crate elastic;
6+
extern crate reqwest;
7+
extern crate env_logger;
8+
9+
use std::error::Error;
10+
use std::io::Read;
11+
use std::collections::hash_map::DefaultHasher;
12+
use std::hash::{Hash, Hasher};
13+
use elastic::prelude::*;
14+
use elastic::http::SyncHttpRequest;
15+
16+
fn hash_request(request: &mut SyncHttpRequest) -> Result<(), Box<Error + Send + Sync>> {
17+
let &mut SyncHttpRequest { ref mut url, ref mut method, ref mut body, ref mut headers, .. } = request;
18+
19+
// Read the body into a temporary buffer
20+
let mut buffered = Vec::new();
21+
if let &mut Some(ref mut body) = body {
22+
body.reader().read_to_end(&mut buffered)?;
23+
}
24+
25+
// Access the request data
26+
let mut hasher = DefaultHasher::new();
27+
28+
url.hash(&mut hasher);
29+
method.hash(&mut hasher);
30+
buffered.hash(&mut hasher);
31+
32+
for header in headers.iter() {
33+
header.to_string().hash(&mut hasher);
34+
}
35+
36+
// Add a raw header to the request
37+
let hash = hasher.finish();
38+
headers.set_raw("X-BadHash", hash.to_string());
39+
40+
Ok(())
41+
}
42+
43+
fn run() -> Result<(), Box<Error>> {
44+
// A HTTP client and request parameters
45+
let client = SyncClientBuilder::new()
46+
.pre_send_raw(hash_request)
47+
.build()?;
48+
49+
// Ping the cluster
50+
let ping = client.ping().send()?;
51+
52+
println!("{:?}", ping);
53+
54+
Ok(())
55+
}
56+
57+
fn main() {
58+
env_logger::init().unwrap();
59+
run().unwrap()
60+
}

src/elastic/examples/raw.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ fn run() -> Result<(), Box<Error>> {
2727

2828
// Check if the response is in the 200 range
2929
match res.status() {
30-
200...299 => (),
30+
status if status.is_success() => (),
3131
status => panic!("error: {:?}", status),
3232
}
3333

src/elastic/src/client/requests/async.rs

Lines changed: 0 additions & 50 deletions
This file was deleted.

src/elastic/src/client/requests/mod.rs

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,18 +10,13 @@ use fluent_builder::FluentBuilder;
1010
use client::Client;
1111
use client::sender::{AsyncSender, RequestParams, Sender};
1212

13-
pub use elastic_requests::{empty_body, DefaultBody, HttpMethod, HttpRequest, Url};
13+
pub use elastic_requests::{empty_body, DefaultBody, Endpoint, UrlPath};
1414
pub use elastic_requests::params;
1515
pub use elastic_requests::endpoints;
1616

1717
pub use self::params::*;
1818
pub use self::endpoints::*;
1919

20-
mod sync;
21-
mod async;
22-
pub use self::sync::*;
23-
pub use self::async::*;
24-
2520
pub mod raw;
2621
pub use self::raw::RawRequestBuilder;
2722

@@ -173,7 +168,7 @@ where
173168
*/
174169
pub fn params<I>(mut self, params: I) -> Self
175170
where
176-
I: Into<RequestParams>
171+
I: Into<RequestParams>,
177172
{
178173
self.params_builder = self.params_builder.value(params.into());
179174

src/elastic/src/client/requests/raw.rs

Lines changed: 21 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use fluent_builder::TryIntoValue;
77

88
use client::Client;
99
use client::sender::{NextParams, NodeAddresses, SendableRequest, SendableRequestParams, Sender};
10-
use client::requests::{HttpRequest, RequestBuilder};
10+
use client::requests::{Endpoint, RequestBuilder};
1111

1212
/**
1313
A raw request builder that can be configured before sending.
@@ -17,18 +17,18 @@ The `send` method will either send the request synchronously or asynchronously,
1717
1818
[Client.request]: ../../struct.Client.html#raw-request
1919
*/
20-
pub type RawRequestBuilder<TSender, TRequest, TBody> = RequestBuilder<TSender, RawRequestInner<TRequest, TBody>>;
20+
pub type RawRequestBuilder<TSender, TEndpoint, TBody> = RequestBuilder<TSender, RawRequestInner<TEndpoint, TBody>>;
2121

2222
#[doc(hidden)]
23-
pub struct RawRequestInner<TRequest, TBody> {
24-
req: TRequest,
23+
pub struct RawRequestInner<TEndpoint, TBody> {
24+
endpoint: TEndpoint,
2525
_marker: PhantomData<TBody>,
2626
}
2727

28-
impl<TRequest, TBody> RawRequestInner<TRequest, TBody> {
29-
pub(crate) fn new(req: TRequest) -> Self {
28+
impl<TEndpoint, TBody> RawRequestInner<TEndpoint, TBody> {
29+
pub(crate) fn new(endpoint: TEndpoint) -> Self {
3030
RawRequestInner {
31-
req: req,
31+
endpoint,
3232
_marker: PhantomData,
3333
}
3434
}
@@ -44,7 +44,7 @@ where
4444
/**
4545
Create a [`RawRequestBuilder`][RawRequestBuilder] with this `Client` that can be configured before sending.
4646
47-
The `request` method accepts any type that can be converted into a [`HttpRequest<'static>`][HttpRequest],
47+
The `request` method accepts any type that can be converted into a [`Endpoint<'static>`][Endpoint],
4848
which includes the endpoint types in the [`endpoints`][endpoints-mod] module.
4949
5050
# Examples
@@ -57,7 +57,7 @@ where
5757
# fn main() { run().unwrap() }
5858
# fn run() -> Result<(), Box<::std::error::Error>> {
5959
# let client = SyncClientBuilder::new().build()?;
60-
// `PingRequest` implements `Into<HttpRequest>`
60+
// `PingRequest` implements `Into<Endpoint>`
6161
let req = PingRequest::new();
6262
6363
// Turn the `PingRequest` into a `RequestBuilder`
@@ -71,23 +71,23 @@ where
7171
# }
7272
```
7373
74-
[HttpRequest]: requests/struct.HttpRequest.html
74+
[Endpoint]: requests/struct.Endpoint.html
7575
[RawRequestBuilder]: requests/raw/type.RawRequestBuilder.html
7676
[endpoints-mod]: requests/endpoints/index.html
7777
*/
78-
pub fn request<TRequest, TBody>(&self, req: TRequest) -> RawRequestBuilder<TSender, TRequest, TBody>
78+
pub fn request<TEndpoint, TBody>(&self, endpoint: TEndpoint) -> RawRequestBuilder<TSender, TEndpoint, TBody>
7979
where
80-
TRequest: Into<HttpRequest<'static, TBody>>,
80+
TEndpoint: Into<Endpoint<'static, TBody>>,
8181
TBody: Into<TSender::Body>,
8282
{
83-
RequestBuilder::initial(self.clone(), RawRequestInner::new(req))
83+
RequestBuilder::initial(self.clone(), RawRequestInner::new(endpoint))
8484
}
8585
}
8686

87-
impl<TSender, TRequest, TBody> RawRequestBuilder<TSender, TRequest, TBody>
87+
impl<TSender, TEndpoint, TBody> RawRequestBuilder<TSender, TEndpoint, TBody>
8888
where
8989
TSender: Sender,
90-
TRequest: Into<HttpRequest<'static, TBody>>,
90+
TEndpoint: Into<Endpoint<'static, TBody>>,
9191
TBody: Into<<TSender>::Body> + 'static,
9292
NodeAddresses<TSender>: NextParams,
9393
<NodeAddresses<TSender> as NextParams>::Params: Into<TSender::Params> + 'static,
@@ -162,22 +162,18 @@ where
162162
*/
163163
pub fn send(self) -> TSender::Response {
164164
let client = self.client;
165-
let req = self.inner.req.into();
165+
let endpoint = self.inner.endpoint.into();
166166

167167
// Only try fetch a next address if an explicit `RequestParams` hasn't been given
168168
let params = match self.params_builder.try_into_value() {
169-
TryIntoValue::Value(value) => {
170-
SendableRequestParams::Value(value)
169+
TryIntoValue::Value(value) => SendableRequestParams::Value(value),
170+
TryIntoValue::Builder(builder) => SendableRequestParams::Builder {
171+
params: client.addresses.next(),
172+
builder,
171173
},
172-
TryIntoValue::Builder(builder) => {
173-
SendableRequestParams::Builder {
174-
params: client.addresses.next(),
175-
builder,
176-
}
177-
}
178174
};
179175

180-
let req = SendableRequest::new(req, params);
176+
let req = SendableRequest::new(endpoint, params);
181177

182178
client.sender.send(req)
183179
}

src/elastic/src/client/requests/sync.rs

Lines changed: 0 additions & 57 deletions
This file was deleted.

0 commit comments

Comments
 (0)