rust-consul 0.1.4

A tokio based rust client for consul.
Documentation
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
//! Future-aware client for consul
//!
//! This library is an client for consul that gives you stream of changes
//! done in consul

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

extern crate hyper;
extern crate hyper_tls;
#[macro_use] extern crate log;
extern crate futures;
extern crate native_tls;
extern crate serde;
#[macro_use] extern crate serde_derive;
extern crate serde_json;
extern crate tokio;
extern crate url;

use std::error::{Error as StdError};
use std::fmt::{self, Write};
use std::io;
use std::mem;
use std::net::IpAddr;
use std::num::ParseIntError;
use std::str::FromStr;
use std::time::{Duration, Instant};
use std::marker::PhantomData;

use serde_json::{from_slice, Error as JsonError, Value as JsonValue};
use futures::{Stream, Future, Poll, Async};
use futures::future::{empty as empty_future, Empty};
use hyper::{Chunk, Body, StatusCode, Uri};
use hyper::client::{Client as HttpClient, ResponseFuture, HttpConnector};
use hyper::header::{CONTENT_TYPE, HeaderMap, HeaderValue};
use hyper::error::{Error as HyperError};
use hyper_tls::HttpsConnector;
use native_tls::{Error as TlsError};
use tokio::reactor::Handle;
use tokio::timer::Timeout;
use url::{Url, ParseError as UrlParseError};
use native_tls::TlsConnector;

type Headers = HeaderMap<HeaderValue>;

/// General errors that breaks the stream
#[derive(Debug)]
pub enum Error {
    /// Error given internaly by hyper
    Http(HyperError),
    /// You have polled the watcher from two different threads
    InvalidState,
    /// You have given us an invalid url
    InvalidUrl(UrlParseError),
    /// Error while initializing tls
    Tls(TlsError),
    /// uncatched io error
    Io(io::Error),
    /// consul response failed to parse
    BodyParse(ParseError),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        match *self {
            Error::Http(ref he) => write!(f, "http error: {}", he),
            Error::InvalidState => write!(f, "invalid state reached"),
            Error::InvalidUrl(ref pe) => write!(f, "invalid url: {}", pe),
            Error::Tls(ref te) => write!(f, "{}", te),
            Error::Io(ref ie) => write!(f, "{}", ie),
            Error::BodyParse(ref be) => write!(f, "{}", be),
        }
    }
}

impl StdError for Error {
    fn description(&self) -> &str {
        match *self {
            Error::Http(_) => "http error",
            Error::InvalidState => "invalid state reached",
            Error::InvalidUrl(_) => "invalid url",
            Error::Tls(_) => "Tls initialization problem",
            Error::Io(_) => "io problem",
            Error::BodyParse(_) => "body parse problem",
        }
    }
}

impl From<UrlParseError> for Error {
    fn from(e: UrlParseError) -> Error {
        Error::InvalidUrl(e)
    }
}

impl From<TlsError> for Error {
    fn from(e: TlsError) -> Error {
        Error::Tls(e)
    }
}

impl From<HyperError> for Error {
    fn from(e: HyperError) -> Error {
        Error::Http(e)
    }
}

impl From<io::Error> for Error {
    fn from(e: io::Error) -> Error {
        Error::Io(e)
    }
}

impl From<ParseError> for Error {
    fn from(e: ParseError) -> Error {
        Error::BodyParse(e)
    }
}

/// Errors related to blocking protocol as defined by consul
#[derive(Debug, Copy, Clone)]
pub enum ProtocolError {
    /// Consul did not reply with X-Consul-Index header
    BlockingMissing,
    /// Consul did not reply with Content-Type: application/json
    ContentTypeNotJson,
    /// Consul did not reply with 200 Ok status
    NonOkResult(StatusCode),
    /// connection refused to consul
    ConnectionRefused,
    /// we had an error, and consumer resetted the stream
    StreamRestarted,
}

impl fmt::Display for ProtocolError {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        match *self {
            ProtocolError::BlockingMissing => write!(f, "{}", self.description()),
            ProtocolError::ContentTypeNotJson => write!(f, "{}", self.description()),
            ProtocolError::NonOkResult(ref status) => write!(f, "Non ok result from consul: {}", status),
            ProtocolError::ConnectionRefused => write!(f, "connection refused to consul"),
            ProtocolError::StreamRestarted => write!(f, "consumer restarted the stream"),
        }
    }
}

impl StdError for ProtocolError {
    fn description(&self) -> &str {
        match *self {
            ProtocolError::BlockingMissing => "X-Consul-Index missing from response",
            ProtocolError::ContentTypeNotJson => "Consul replied with a non-json content",
            ProtocolError::NonOkResult(_) => "Non ok result from consul",
            ProtocolError::ConnectionRefused => "connection refused to consul",
            ProtocolError::StreamRestarted => "consumer restarted the stream",
        }
    }
}

/// Error that Watch may yield *in the stream*
#[derive(Debug)]
pub enum ParseError {
    /// Consul protocol error (missing header, unknown return format)
    Protocol(ProtocolError),
    /// Json result does not fit expected format
    UnexpectedJsonFormat,
    /// The data is not in json format
    BodyParsing(JsonError),
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        match *self {
            ParseError::Protocol(ref pe) => write!(f, "Protocol error: {}", pe),
            ParseError::UnexpectedJsonFormat => write!(f, "{}", self.description()),
            ParseError::BodyParsing(ref je) => write!(f, "Data not in json format: {}", je),
        }
    }
}

impl StdError for ParseError {
    fn description(&self) -> &str {
        match *self {
            ParseError::Protocol(_) => "Protocol error",
            ParseError::UnexpectedJsonFormat => "Unexpected json format",
            ParseError::BodyParsing(_) => "Data not in json format",
        }
    }
}

impl From<ProtocolError> for ParseError {
    fn from(e: ProtocolError) -> ParseError {
        ParseError::Protocol(e)
    }
}

#[derive(Clone, Copy, Debug)]
struct Blocking {
    index: u64,
}

impl Blocking {
    fn from(headers: &HeaderMap<HeaderValue>) -> Result<Self, ()> {
        let raw_header: Result<&HeaderValue, ()> = headers.get("X-Consul-Index")
            .ok_or(());
        raw_header
            .and_then(|res| res.to_str().map_err(|_| ()))
            .and_then(|res| Self::from_str(res).map_err(|_| ()))
    }

    fn to_string(&self) -> String {
        let mut out = String::new();
        let _ = write!(out, "{}", self.index);
        out
    }

    fn add_to_uri(&self, uri: &Url) -> Url {
        let mut uri = uri.clone();
        uri.query_pairs_mut()
            .append_pair("index", self.to_string().as_str())

            .finish();
        uri
    }
}

impl Default for Blocking {
    fn default() -> Blocking {
        Blocking {
            index: 0,
        }
    }
}

//impl Header for Blocking {
//    fn header_name() -> &'static str {
//        static NAME: &'static str = "X-Consul-Index";
//        NAME
//    }
//
//    fn parse_header(raw: &Raw) -> HyperResult<Self> {
//        from_one_raw_str(raw)
//    }
//
//    fn fmt_header(&self, f: &mut HyperFormatter) -> fmt::Result {
//        f.fmt_line(self)
//    }
//}

impl FromStr for Blocking {
    type Err = ParseIntError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let index = s.parse::<u64>()?;
        Ok(Blocking {
            index
        })
    }
}

impl fmt::Display for Blocking {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.index)
    }
}

#[derive(Debug)]
struct BodyBuffer {
    inner: Body,
    buffer: Chunk,
}

impl BodyBuffer {
    fn new(inner: Body) -> BodyBuffer {
        BodyBuffer {
            inner,
            buffer: Chunk::default(),
        }
    }
}

impl Future for BodyBuffer {
    type Item = Chunk;
    type Error = Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        trace!("polling BodyBuffer");
        loop {
            match self.inner.poll() {
                Ok(Async::NotReady) => return Ok(Async::NotReady),
                Ok(Async::Ready(None)) => {
                    let buffer = mem::replace(&mut self.buffer, Chunk::default());

                    return Ok(Async::Ready(buffer));
                },
                Ok(Async::Ready(Some(data))) => {
                    self.buffer.extend(data);
                    // loop, see if there is any more data here
                },
                Err(e) => return Err(Error::Http(e)),
            }
        }
    }
}

/// Consul client
#[derive(Debug, Clone)]
pub struct Client {
    http_client: HttpClient<HttpsConnector<HttpConnector>>,
    base_uri: Url,
    handle: Handle,
}

impl Client {
    /// Allocate a new consul client
    pub fn new(base_uri: &str, handle: &Handle) -> Result<Client, Error> {
        let base_uri = Url::parse(base_uri)?;
        let threads = 4;

        let mut http = HttpConnector::new(threads);
        http.enforce_http(false);
        http.set_reactor(Some(handle.clone()));
        let tls = TlsConnector::builder().build()?;

        let connector = HttpsConnector::from((http, tls));

        let http_client = HttpClient::builder()
            .keep_alive(true)
            .build(connector);

        Ok(Client{
            http_client,
            base_uri,
            handle: handle.clone(),
        })
    }

    /// List services in the kernel and watch them
    pub fn services(&self) -> Watcher<Services> {
        let mut base_uri = self.base_uri.clone();
        base_uri.set_path("/v1/catalog/services");

        Watcher{
            state: WatcherState::Init{
                base_uri,
                client: self.clone(),
                error_strategy: ErrorStrategy::default(),
            },
            phantom: PhantomData::<Services>
        }
    }

    /// Watch changes of nodes on a service
    pub fn watch_service(&self, name: &str, passing: bool) -> Watcher<ServiceNodes> {
        let mut base_uri = self.base_uri.clone();
        base_uri.set_path("/v1/health/service/");
        let mut base_uri = base_uri.join(name).unwrap();
        if passing {
            base_uri.query_pairs_mut()
                .append_pair("passing", "true")
                .finish();
        }

        Watcher{
            state: WatcherState::Init{
                base_uri,
                client: self.clone(),
                error_strategy: ErrorStrategy::default(),
            },
            phantom: PhantomData::<ServiceNodes>
        }
    }

    /// Get agent informations
    pub fn agent(&self) -> FutureConsul<Agent> {
        let mut base_uri = self.base_uri.clone();
        base_uri.set_path("/v1/agent/self");

        FutureConsul{
            state: FutureState::Init{
                base_uri,
                client: self.clone(),
            },
            phantom: PhantomData::<Agent>
        }
    }
}

#[derive(Debug)]
enum ErrorHandling {
    RetryBackoff,
}

#[derive(Debug)]
struct ErrorStrategy {
    request_timeout: Duration,
    on_error: ErrorHandling,
}

impl Default for ErrorStrategy {
    fn default() -> ErrorStrategy {
        ErrorStrategy {
            request_timeout: Duration::new(5, 0),
            on_error: ErrorHandling::RetryBackoff,
        }
    }
}

#[derive(Debug)]
struct ErrorState{
    strategy: ErrorStrategy,
    current_retries: u64,
    last_try: Option<Instant>,
    last_contact: Option<Instant>,
    last_ok: Option<Instant>,
    last_error: Option<ProtocolError>,
}

impl ErrorState {
    pub fn next_timeout(&self) -> DebugTimeout {
        let retries = if self.current_retries > 10 {
            10
        } else {
            self.current_retries
        };

        debug!("Will sleep for {} seconds and retry", retries);
        let duration = Duration::new(retries, 0);

        DebugTimeout::new(duration)
    }
}

impl From<ErrorStrategy> for ErrorState {
    fn from(strategy: ErrorStrategy) -> ErrorState {
        ErrorState {
            strategy,
            current_retries: 0,
            last_try: None,
            last_contact: None,
            last_ok: None,
            last_error: None,
        }
    }
}

struct DebugTimeout(Timeout<Empty<(), io::Error>>);

impl DebugTimeout {
    pub fn new(duration: Duration) -> Self {
        DebugTimeout(Timeout::new(empty_future(), duration))
    }
}

impl fmt::Debug for DebugTimeout {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        write!(f, "Timeout")
    }
}

impl Future for DebugTimeout {
    type Item = ();
    type Error = io::Error;

    #[inline]
    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        trace!("Timeout::poll() called");
        let res = self.0.poll();

        trace!("res {:?}", res);
        match res {
            Err(err) => match err.into_inner() {
                Some(err) => Err(err),
                None => Ok(Async::Ready(())),
            },
            Ok(ready) => Ok(ready),
        }
    }
}

fn url_to_uri(uri: &Url) -> Uri {
    let out = Uri::from_str(uri.as_str());
    if out.is_err() {
        error!("url malformed: {:?}", uri);
    }

    // TODO: meh unwrap()
    out.unwrap()
}

#[derive(Debug)]
enum WatcherState{
    Init{
        base_uri: Url,
        client: Client,
        error_strategy: ErrorStrategy,
    },
    Completed {
        base_uri: Url,
        client: Client,
        error_state: ErrorState,
        blocking: Blocking,
    },
    Error {
        base_uri: Url,
        client: Client,
        blocking: Blocking,
        error_state: ErrorState,
        retry: Option<DebugTimeout>,
    },
    PendingHeaders {
        base_uri: Url,
        client: Client,
        error_state: ErrorState,
        request: ResponseFuture,
        blocking: Blocking,
    },
    PendingBody {
        base_uri: Url,
        client: Client,
        error_state: ErrorState,
        blocking: Blocking,
        headers: Headers,
        body: BodyBuffer,
    },
    Working,
}

impl Stream for WatcherState {
    type Item = Result<Chunk, ProtocolError>;
    type Error = Error;

    fn poll(&mut self) -> Poll<Option<Self::Item>, <WatcherState as Stream>::Error> {
        trace!("polling WatcherState");
        loop {
            match mem::replace(self, WatcherState::Working) {
                WatcherState::Init{base_uri, client, error_strategy} => {
                    trace!("querying uri: {}", base_uri);

                    let request = client.http_client.get(url_to_uri(&base_uri));
                    trace!("{}: no response for now => PendingHeader", base_uri);
                    *self = WatcherState::PendingHeaders {
                        base_uri,
                        client,
                        request,
                        error_state: error_strategy.into(),
                        blocking: Blocking::default(),
                    };
                },
                WatcherState::Completed{base_uri, client, blocking, mut error_state} => {
                    let uri = blocking.add_to_uri(&base_uri);
                    trace!("querying uri: {}", uri);

                    error_state.last_try = Some(Instant::now());

                    let request = client.http_client.get(url_to_uri(&uri));
                    trace!("{}: no response for now => PendingHeader", base_uri);
                    *self = WatcherState::PendingHeaders {
                        base_uri,
                        client,
                        request,
                        blocking,
                        error_state,
                    };
                },
                WatcherState::PendingHeaders{base_uri, client, blocking, mut request, mut error_state} => {
                    trace!("{}: polling headers", base_uri);

                    match request.poll() {
                        Err(e) => {
                            if e.is_connect() {
                                warn!("{}: got io error: {}", base_uri, e);
                                let err = ProtocolError::ConnectionRefused;
                                error_state.last_error = Some(err);
                                error_state.current_retries += 1;
                                *self = WatcherState::Error{
                                     base_uri,
                                     client,
                                     blocking,
                                     error_state,
                                     retry: None,
                                };
                                return Ok(Async::Ready(Some(Err(err))));
                            } else {
                                error!("{}: got error, stopping: {}", base_uri, e);
                                return Err(e.into());
                            }
                        },
                        Ok(Async::Ready(response_headers)) => {
                            let status = response_headers.status();
                            let headers = response_headers.headers().clone();
                            let response_has_json_content_type = headers.get(CONTENT_TYPE).map(|h| h.eq("application/json")).unwrap_or(false);
                            error_state.last_contact = Some(Instant::now());

                            if status != StatusCode::OK {
                                warn!("{}: got non-200 status: {}", base_uri, status);
                                let err = ProtocolError::NonOkResult(status);
                                error_state.last_error = Some(err);
                                error_state.current_retries += 1;
                                *self = WatcherState::Error{
                                     base_uri,
                                     client,
                                     blocking,
                                     error_state,
                                     retry: None,
                                };
                                return Ok(Async::Ready(Some(Err(err))))
                            }


                            if !response_has_json_content_type {
                                warn!("{}: got non-json content: {:?}", base_uri, headers);
                                error_state.last_error = Some(ProtocolError::ContentTypeNotJson);
                                *self = WatcherState::Error{
                                     base_uri,
                                     client,
                                     blocking,
                                     error_state,
                                     retry: None,
                                };
                            } else {

                                trace!("{}: got headers {} {:?} => PendingBody", base_uri, status, headers);
                                let body = BodyBuffer::new(response_headers.into_body());

                                *self = WatcherState::PendingBody {
                                    base_uri,
                                    client,
                                    blocking,
                                    headers,
                                    body,
                                    error_state,
                                };
                            };
                        },
                        Ok(Async::NotReady) => {
                            trace!("{}: still no headers => PendingHeaders", base_uri);
                            *self = WatcherState::PendingHeaders {
                                base_uri,
                                client,
                                blocking,
                                request,
                                error_state,
                            };
                            return Ok(Async::NotReady);
                        }
                    }
                },
                WatcherState::PendingBody{base_uri, client, blocking, headers, mut body, mut error_state} => {
                    trace!("{}: polling body", base_uri);

                    if let Async::Ready(body) = body.poll()? {
                        debug!("{}: got content: {:?}", base_uri, body);
                        let new_blocking = Blocking::from(&headers).map_err(|_| ProtocolError::BlockingMissing);
                        match new_blocking {
                            Err(err) => {
                                error!("{}: got error while parsing blocking headers: {:?}, {:?}", base_uri, headers, err);
                                error_state.last_error = Some(err);
                                error_state.current_retries += 1;
                                *self = WatcherState::Error{
                                     base_uri,
                                     client,
                                     error_state,
                                     blocking,

                                     // The next call to poll() will start the
                                     // timer (don't generate a timer ifclient
                                     // does not need)
                                     retry: None,
                                };
                                return Ok(Async::Ready(Some(Err(err))));
                            },
                            Ok(blocking) => {
                                info!("{}: got blocking headers: {}", base_uri, blocking);
                                error_state.last_ok = Some(Instant::now());
                                error_state.last_error = None;
                                error_state.current_retries = 0;

                                *self = WatcherState::Completed{
                                    base_uri,
                                    client,
                                    blocking,
                                    error_state
                                };

                                return Ok(Async::Ready(Some(Ok(body))));
                            }
                        }
                    } else {
                        trace!("{}: still no body => PendingBody", base_uri);

                        *self = WatcherState::PendingBody {
                            base_uri,
                            client,
                            headers,
                            blocking,
                            body,
                            error_state,
                        };
                        return Ok(Async::NotReady);
                    }
                },

                WatcherState::Error{base_uri, client, blocking, error_state, retry} => {
                    trace!("{}: still no body => PendingBody", base_uri);
                    if let Some(mut retry) = retry {
                        // We have a timeout loaded, see if it resolved
                        if let Async::Ready(_) = retry.poll()? {
                            trace!("{}: timeout completed", base_uri);
                            *self = WatcherState::Completed{
                                base_uri,
                                client,
                                blocking,
                                error_state
                            };
                        } else {
                            trace!("{}: timeout not completed", base_uri);
                            *self = WatcherState::Error{
                                base_uri,
                                client,
                                blocking,
                                error_state,
                                retry: Some(retry)
                            };
                            return Ok(Async::NotReady);
                        }
                    } else {
                        let next_timeout = error_state.next_timeout();
                        trace!("{}: setting timeout", base_uri);
                        *self = WatcherState::Error{
                            base_uri,
                            client,
                            blocking,
                            error_state,
                            retry: Some(next_timeout),
                        };
                        // loop will consume the poll
                    }
                }

                // Dead end
                WatcherState::Working => {
                    error!("watcher in working state, weird");
                    return Err(Error::InvalidState);
                },
            }
        }
    }
}

/// Watch changes made in consul and parse those changes
#[derive(Debug)]
pub struct Watcher<T>{
    state: WatcherState,
    phantom: PhantomData<T>,
}

impl<T> Watcher<T> {
    /// Whenever the stream yield an error. The stream closes and
    /// can't be consumed anymore. In such cases, you are required to reset
    /// the stream. It will then, sleep (according to the error strategy)
    /// and reconnect to consul.
    pub fn reset(&mut self) {
        let (base_uri, client, blocking, mut error_state) = match mem::replace(&mut self.state, WatcherState::Working) {
            WatcherState::Init{base_uri, client, error_strategy, ..} =>
                (base_uri, client, Blocking::default(), ErrorState::from(error_strategy)),
            WatcherState::Completed{base_uri, client, blocking, error_state, ..} |
            WatcherState::Error{base_uri, client, blocking, error_state, ..} |
            WatcherState::PendingHeaders{base_uri, client, blocking, error_state, ..} |
            WatcherState::PendingBody{base_uri, client, blocking, error_state, ..} =>
                (base_uri, client, blocking, error_state),
            WatcherState::Working => panic!("stream resetted while polled. State is invalid"),
        };
        error_state.last_error = Some(ProtocolError::StreamRestarted);
        self.state = WatcherState::Error{
             base_uri,
             client,
             blocking,
             error_state,
             retry: None,
        };
    }
}

impl<T> Stream for Watcher<T>
    where T: ConsulType {
    type Item = Result<T::Reply, ParseError>;
    type Error = Error;

    #[inline]
    fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
        // poll()? pattern will bubble up the error
        match self.state.poll()? {
            Async::NotReady => Ok(Async::NotReady),
            Async::Ready(None) => Ok(Async::Ready(None)),
            Async::Ready(Some(Err(e))) => Ok(Async::Ready(Some(Err(e.into())))),
            Async::Ready(Some(Ok(body))) => {
                Ok(Async::Ready(Some(T::parse(&body))))
            }
        }
    }
}


/// Trait for parsing types out of consul
pub trait ConsulType {
    /// The kind of replies this parser yields
    type Reply;

    /// Parse an http body and give back a result
    fn parse(buf: &Chunk) -> Result<Self::Reply, ParseError>;
}

fn read_map_service_name(value: &JsonValue) -> Result<Vec<ServiceName>, ParseError> {
    if let &JsonValue::Object(ref map) = value {
        let mut out = Vec::with_capacity(map.len());
        for (k, v) in map.iter() {
            if let &JsonValue::Array(ref _values) = v {
                if k != "consul" {
                    out.push(k.clone());
                }
            } else {
                return Err(ParseError::UnexpectedJsonFormat)
            }
        }
        Ok(out)
    } else {
        Err(ParseError::UnexpectedJsonFormat)
    }
}

/// Services name used in consul
pub type ServiceName = String;

/// Parse services list in consul
#[derive(Debug)]
pub struct Services {}
impl ConsulType for Services {
    type Reply = Vec<ServiceName>;

    fn parse(buf: &Chunk) -> Result<Self::Reply, ParseError> {
         let v: JsonValue = from_slice(&buf).map_err(ParseError::BodyParsing)?;
         let res = read_map_service_name(&v)?;

         Ok(res)
    }
}

/// Parse node list from services in consul
#[derive(Debug)]
pub struct ServiceNodes {}
impl ConsulType for ServiceNodes {
    type Reply = Vec<Node>;

    fn parse(buf: &Chunk) -> Result<Self::Reply, ParseError> {
         let v: Vec<TempNode> = from_slice(&buf).map_err(ParseError::BodyParsing)?;

         Ok(v.into_iter().map(|x| x.node).collect())
    }
}

#[derive(Deserialize)]
struct TempNode {
    #[serde(rename = "Node")]
    node: Node,
}

/// Node hosting services
#[derive(Debug, Deserialize, PartialEq, Clone)]
pub struct Node {
    /// Node name
    #[serde(rename = "Node")]
    pub name: String,

    /// Node address
    #[serde(rename = "Address")]
    pub address: IpAddr,
}

/// A future response from consul
#[derive(Debug)]
pub struct FutureConsul<T> {
    state: FutureState,
    phantom: PhantomData<T>,
}

impl<T> Future for FutureConsul<T>
    where T: ConsulType {
    type Item = T::Reply;
    type Error = Error;

    #[inline]
    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        // poll()? pattern will bubble up the error
        match self.state.poll()? {
            Async::NotReady => Ok(Async::NotReady),
            Async::Ready(body) => {
                T::parse(&body).map(|res| {
                   Async::Ready(res)
                }).map_err(|e| Error::BodyParse(e))
            },
        }
    }
}

#[derive(Debug)]
enum FutureState {
    Init {
        base_uri: Url,
        client: Client,
    },
    PendingHeaders {
        base_uri: Url,
        client: Client,
        request: ResponseFuture,
    },
    PendingBody {
        base_uri: Url,
        client: Client,
        headers: Headers,
        body: BodyBuffer,
    },
    Done,
    Working,
}

impl Future for FutureState {
    type Item = Chunk;
    type Error = Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        trace!("polling FutureState");
        loop {
            match mem::replace(self, FutureState::Working) {
                FutureState::Init{base_uri, client} => {
                    trace!("querying uri: {}", base_uri);

                    let request = client.http_client.get(url_to_uri(&base_uri));
                    trace!("no response for now => PendingHeader");
                    *self = FutureState::PendingHeaders {
                        base_uri,
                        client,
                        request,
                    };
                },
                FutureState::PendingHeaders{base_uri, client, mut request} => {
                    trace!("polling headers");

                    match request.poll()? {
                        Async::Ready(response_headers) => {
                            let status = response_headers.status();
                            let headers = response_headers.headers().clone();
                            let response_has_json_content_type = headers.get(CONTENT_TYPE).map(|h| h.eq("application/json")).unwrap_or(false);
                            if status != StatusCode::OK {
                                let err = ProtocolError::NonOkResult(status);
                                return Err(Error::BodyParse(ParseError::Protocol(err)))
                            } else if !response_has_json_content_type {
                                let err = ProtocolError::ContentTypeNotJson;
                                return Err(Error::BodyParse(ParseError::Protocol(err)))
                            } else {
                                trace!("got headers {} {:?} => PendingBody", status, headers);
                                let body = BodyBuffer::new(response_headers.into_body());
                                *self = FutureState::PendingBody {
                                    base_uri,
                                    client,
                                    headers,
                                    body,
                                };
                            }
                        },
                        Async::NotReady => {
                            trace!("still no headers => PendingHeaders");
                            *self = FutureState::PendingHeaders {
                                base_uri,
                                client,
                                request,
                            };
                            return Ok(Async::NotReady);
                        },
                    }
                },
                FutureState::PendingBody{base_uri, client, headers, mut body} => {
                    trace!("polling body");

                    if let Async::Ready(body) = body.poll()? {
                        *self = FutureState::Done;
                        return Ok(Async::Ready(body));
                    } else {
                        *self = FutureState::PendingBody{
                            base_uri,
                            client,
                            headers,
                            body
                        };
                        return Ok(Async::NotReady);
                    }
                }

                // Dead end
                FutureState::Working | FutureState::Done => {
                    return Err(Error::InvalidState);
                },
            }
        }
    }
}

#[derive(Deserialize)]
struct InnerAgent {
    #[serde(rename = "Member")]
    member: InnerMember,
}

#[derive(Deserialize)]
struct InnerMember {
    #[serde(rename = "Addr")]
    addr: IpAddr,
}

/// Parse node list from services in consul
#[derive(Debug)]
pub struct Agent {
    /// public ip address used by this address
    pub member_address: IpAddr,
}

impl ConsulType for Agent {
    type Reply = Agent;

    fn parse(buf: &Chunk) -> Result<Self::Reply, ParseError> {
        let agent: InnerAgent = serde_json::from_slice(&buf).map_err(ParseError::BodyParsing)?;
        Ok(Agent {
            member_address: agent.member.addr,
        })
    }
}