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
/*! 
Response type parsing.
*/

use std::marker::PhantomData;
use std::io::{Cursor, Read};
use serde::de::DeserializeOwned;
use serde_json::{self, Value};

use error::*;

/** A parser that separates taking a response type from the readable body type. */
pub struct Parse<T> {
    _marker: PhantomData<T>,
}

/* 
Try parse a http response into a concrete type.

Parsing is split between two calls:

- `parse` where you can specify the response type
- `from_slice`/`from_reader` wher you can specify the kind of body to read from

The reason for splitting the functions is so we can infer the types of arguments to `from_slice` and `from_reader`,
but provide the concrete response type in cases it can't be inferred.

# Examples

Provide an explicit response type in the `parse` function:

```no_run
# extern crate serde_json;
# extern crate elastic_responses;
# use serde_json::*;
# use elastic_responses::*;
# use elastic_responses::error::*;
# fn do_request() -> (u16, Vec<u8>) { unimplemented!() }
# fn main() {
# let (response_status, response_body) = do_request();
let get_response = parse::<GetResponse<Value>>().from_slice(response_status, response_body);
# }
```

Provide an explicit response type on the result ident:

```no_run
# extern crate serde_json;
# extern crate elastic_responses;
# use serde_json::Value;
# use elastic_responses::*;
# use elastic_responses::error::*;
# fn do_request() -> (u16, Vec<u8>) { unimplemented!() }
# fn main() {
# let (response_status, response_body) = do_request();
let get_response: Result<GetResponse<Value>, ResponseError> = parse().from_slice(response_status, response_body);
# }
```

If Rust can infer the concrete response type then you can avoid specifying it at all:

```no_run
# extern crate serde_json;
# extern crate elastic_responses;
# use serde_json::Value;
# use elastic_responses::*;
# use elastic_responses::error::*;
# fn do_request() -> (u16, Vec<u8>) { unimplemented!() }
# fn main() {
# fn parse_response() -> Result<GetResponse<Value>, ResponseError> {
# let (response_status, response_body) = do_request();
let get_response = parse().from_slice(response_status, response_body);
# get_response
# }
# }
```
*/
pub fn parse<T: IsOk + DeserializeOwned>() -> Parse<T> {
    Parse {
        _marker: PhantomData,
    }
}

impl<T: IsOk + DeserializeOwned> Parse<T> {
    /** Try parse a contiguous slice of bytes into a concrete response. */
    pub fn from_slice<B: AsRef<[u8]>, H: Into<HttpResponseHead>>(self, head: H, body: B) -> Result<T, ResponseError> {
        from_body(head.into(), SliceBody(body))
    }

    /** Try parse an arbitrary reader into a concrete response. */
    pub fn from_reader<B: Read, H: Into<HttpResponseHead>>(self, head: H, body: B) -> Result<T, ResponseError> {
        from_body(head.into(), ReadBody(body))
    }
}

fn from_body<B: ResponseBody, T: IsOk + DeserializeOwned>(head: HttpResponseHead, body: B) -> Result<T, ResponseError> {
    let maybe = T::is_ok(head, Unbuffered(body))?;

    match maybe.ok {
        true => {
            let ok = maybe.res.parse_ok()?;
            Ok(ok)
        }
        false => {
            let err = maybe.res.parse_err()?;
            Err(ResponseError::Api(err))
        }
    }
}

/** The non-body component of the HTTP response. */
pub struct HttpResponseHead {
    code: u16,
}

impl HttpResponseHead {
    /** Get the status code. */
    pub fn status(&self) -> u16 {
        self.code
    }
}

impl From<u16> for HttpResponseHead {
    fn from(status: u16) -> Self {
        HttpResponseHead {
            code: status
        }
    }
}

/** A http response body that can be buffered into a json value. */
pub trait ResponseBody where Self: Sized
{
    /** The type of a buffered response body. */
    type Buffered: ResponseBody;

    /** Buffer the response body to a json value and return a new buffered representation. */
    fn body(self) -> Result<(Value, Self::Buffered), ParseResponseError>;

    /** Parse the body as a success result. */
    fn parse_ok<T: DeserializeOwned>(self) -> Result<T, ParseResponseError>;

    /** Parse the body as an API error. */
    fn parse_err(self) -> Result<ApiError, ParseResponseError>;
}

struct ReadBody<B>(B);

impl<B: Read> ResponseBody for ReadBody<B> {
    type Buffered = SliceBody<Vec<u8>>;

    fn body(mut self) -> Result<(Value, Self::Buffered), ParseResponseError> {
        let mut buf = Vec::new();
        self.0.read_to_end(&mut buf)?;

        let body: Value = serde_json::from_reader(Cursor::new(&buf))?;

        Ok((body, SliceBody(buf)))
    }

    fn parse_ok<T: DeserializeOwned>(self) -> Result<T, ParseResponseError> {
        serde_json::from_reader(self.0).map_err(|e| e.into())
    }

    fn parse_err(self) -> Result<ApiError, ParseResponseError> {
        serde_json::from_reader(self.0).map_err(|e| e.into())
    }
}

struct SliceBody<B>(B);

impl<B: AsRef<[u8]>> ResponseBody for SliceBody<B> {
    type Buffered = Self;

    fn body(self) -> Result<(Value, Self::Buffered), ParseResponseError> {
        let buf = self.0;

        let body: Value = serde_json::from_slice(buf.as_ref())?;

        Ok((body, SliceBody(buf)))
    }

    fn parse_ok<T: DeserializeOwned>(self) -> Result<T, ParseResponseError> {
        serde_json::from_slice(self.0.as_ref()).map_err(|e| e.into())
    }

    fn parse_err(self) -> Result<ApiError, ParseResponseError> {
        serde_json::from_slice(self.0.as_ref()).map_err(|e| e.into())
    }
}

/**
Convert a response message into a either a success
or failure result.

This is the main trait that drives response parsing by inspecting the http status and potentially
buffering the response to determine whether or not it represents a successful operation.
This trait doesn't do the actual deserialisation, it just passes on a `MaybeOkResponse`.

Some endpoints may not map success or error responses directly to a status code.
In this case, the `Unbuffered` body can be buffered into an anonymous json object and inspected
for an error node.
The `Unbuffered` type takes care of response bodies that can only be buffered once.

Any type that implements `IsOk` can be deserialised by `parse`.
Implementations should behave in the following way:

- If the response is successful, this trait should return `Ok(MaybeOkResponse::ok)`.
- If the response is an error, this trait should return `Ok(MaybeOkResponse::err)`.
- If the response isn't recognised or is otherwise invalid, this trait should return `Err`.

# Examples

Implement `IsOk` for a custom response type, where a http `404` might still contain a valid response:

```
# #[macro_use] extern crate serde_derive;
# extern crate serde;
# extern crate elastic_responses;
# use elastic_responses::parsing::*;
# use elastic_responses::error::*;
# fn main() {}
# #[derive(Deserialize)]
# struct MyResponse;
impl IsOk for MyResponse {
    fn is_ok<B: ResponseBody>(head: HttpResponseHead, unbuffered: Unbuffered<B>) -> Result<MaybeOkResponse<B>, ParseResponseError> {
        match head.status() {
            200...299 => Ok(MaybeOkResponse::ok(unbuffered)),
            404 => {
                // If we get a 404, it could be an IndexNotFound error or ok
                // Check if the response contains a root 'error' node
                let (body, buffered) = unbuffered.body()?;

                let is_ok = body.as_object()
                    .and_then(|body| body.get("error"))
                    .is_none();

                Ok(MaybeOkResponse::new(is_ok, buffered))
            }
            _ => Ok(MaybeOkResponse::err(unbuffered)),
        }
    }
}
```
*/
pub trait IsOk
{
    /** Inspect the http response to determine whether or not it succeeded. */
    fn is_ok<B: ResponseBody>(head: HttpResponseHead, unbuffered: Unbuffered<B>) -> Result<MaybeOkResponse<B>, ParseResponseError>;
}

impl IsOk for Value {
    fn is_ok<B: ResponseBody>(head: HttpResponseHead, body: Unbuffered<B>) -> Result<MaybeOkResponse<B>, ParseResponseError> {
        match head.status() {
            200...299 => Ok(MaybeOkResponse::ok(body)),
            _ => Ok(MaybeOkResponse::err(body)),
        }
    }
}

/** A response that might be successful or an `ApiError`. */
pub struct MaybeOkResponse<B> 
    where B: ResponseBody
{
    ok: bool,
    res: MaybeBufferedResponse<B>,
}

impl<B> MaybeOkResponse<B> where B: ResponseBody
{
    /** 
    Create a new response that indicates where or not the
    body is successful or an `ApiError`.
    */
    pub fn new<I>(ok: bool, res: I) -> Self
        where I: Into<MaybeBufferedResponse<B>>
    {
        MaybeOkResponse {
            ok: ok,
            res: res.into(),
        }
    }

    /** Create a response where the body is successful. */
    pub fn ok<I>(res: I) -> Self
        where I: Into<MaybeBufferedResponse<B>>
    {
        Self::new(true, res)
    }

    /** Create a resposne where the body is an error. */
    pub fn err<I>(res: I) -> Self
        where I: Into<MaybeBufferedResponse<B>>
    {
        Self::new(false, res)
    }
}

/** A response body that hasn't been buffered yet. */
pub struct Unbuffered<B>(B);

impl<B: ResponseBody> Unbuffered<B> {
    /** Buffer the response body to a json value and return a new buffered representation. */
    pub fn body(self) -> Result<(Value, Buffered<B>), ParseResponseError> {
        self.0.body().map(|(value, body)| (value, Buffered(body)))
    }
}

/** A response body that has been buffered. */
pub struct Buffered<B: ResponseBody>(B::Buffered);

/** 
A response body that may or may not have been buffered.

This type makes it possible to inspect the response body for
an error type before passing it along to be deserialised properly.
*/
pub enum MaybeBufferedResponse<B>
    where B: ResponseBody
{
    Unbuffered(B),
    Buffered(B::Buffered),
}

impl<B> MaybeBufferedResponse<B>
    where B: ResponseBody
{
    fn parse_ok<T: DeserializeOwned>(self) -> Result<T, ParseResponseError> {
        match self {
            MaybeBufferedResponse::Unbuffered(b) => b.parse_ok(),
            MaybeBufferedResponse::Buffered(b) => b.parse_ok()
        }
    }

    fn parse_err(self) -> Result<ApiError, ParseResponseError> {
        match self {
            MaybeBufferedResponse::Unbuffered(b) => b.parse_err(),
            MaybeBufferedResponse::Buffered(b) => b.parse_err()
        }
    }
}

impl<B> From<Unbuffered<B>> for MaybeBufferedResponse<B>
    where B: ResponseBody
{
    fn from(value: Unbuffered<B>) -> Self {
        MaybeBufferedResponse::Unbuffered(value.0)
    }
}

impl<B> From<Buffered<B>> for MaybeBufferedResponse<B>
    where B: ResponseBody
{
    fn from(value: Buffered<B>) -> Self {
        MaybeBufferedResponse::Buffered(value.0)
    }
}