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
use std::io;
use std::mem;

use futures::{Future, Poll};
use http::Response;
use hyper::body::Payload;
use tokio::executor::thread_pool::Builder as ThreadPoolBuilder;
use tokio::runtime;
use tokio::runtime::Runtime;
use tower_service::{NewService, Service};

use crate::service::http::imp::{HttpRequestImpl, HttpResponseImpl};
use crate::service::http::{HttpRequest, HttpResponse};
use crate::CritError;

use super::data::{Data, Receive};
use super::input::Input;

/// A local server which emulates an HTTP service without using
/// the low-level transport.
///
/// The value of this struct conttains an instance of `NewHttpService`
/// and a Tokio runtime.
#[derive(Debug)]
pub struct LocalServer<S> {
    new_service: S,
    runtime: Runtime,
}

impl<S> LocalServer<S>
where
    S: NewService + Send + 'static,
    S::Request: HttpRequest,
    S::Response: HttpResponse,
    S::Error: Into<CritError>,
    S::Future: Send + 'static,
    S::Service: Send + 'static,
    S::InitError: Send + 'static,
{
    /// Creates a new instance of `LocalServer` from a `NewHttpService`.
    ///
    /// This function will return an error if the construction of the runtime is failed.
    pub fn new(new_service: S) -> io::Result<LocalServer<S>> {
        let mut pool = ThreadPoolBuilder::new();
        pool.pool_size(1);

        let runtime = runtime::Builder::new()
            .core_threads(1)
            .blocking_threads(1)
            .build()?;

        Ok(LocalServer {
            new_service,
            runtime,
        })
    }

    /// Create a `Client` associated with this server.
    pub fn client(&mut self) -> Result<Client<'_, S::Service>, S::InitError> {
        let service = self.runtime.block_on(self.new_service.new_service())?;
        Ok(Client {
            service,
            runtime: &mut self.runtime,
        })
    }
}

/// A type which emulates a connection to a peer.
#[derive(Debug)]
pub struct Client<'a, S> {
    service: S,
    runtime: &'a mut Runtime,
}

impl<'a, S> Client<'a, S>
where
    S: Service + Send + 'static,
    S::Request: HttpRequest,
    S::Response: HttpResponse,
    S::Error: Into<CritError>,
    S::Future: Send + 'static,
{
    /// Applies an HTTP request to this client and get its response.
    pub fn perform<T>(&mut self, input: T) -> Result<Response<Data>, CritError>
    where
        T: Input,
    {
        let input = input.build_request()?;
        let request = S::Request::from_request(input);
        let future = TestResponseFuture::Initial(self.service.call(request));
        self.runtime.block_on(future)
    }

    /// Returns the reference to the underlying Tokio runtime.
    pub fn runtime(&mut self) -> &mut Runtime {
        &mut *self.runtime
    }
}

#[cfg_attr(feature = "cargo-clippy", allow(large_enum_variant))]
#[derive(Debug)]
enum TestResponseFuture<F, Bd: Payload> {
    Initial(F),
    Receive(http::response::Parts, Receive<Bd>),
    Done,
}

impl<F, Bd> Future for TestResponseFuture<F, Bd>
where
    F: Future,
    F::Item: HttpResponse<Body = Bd>,
    F::Error: Into<CritError>,
    Bd: Payload,
{
    type Item = Response<Data>;
    type Error = CritError;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        use self::TestResponseFuture::*;
        loop {
            let response = match *self {
                Initial(ref mut f) => {
                    let response = try_ready!(f.poll().map_err(Into::into));
                    Some(response)
                }
                Receive(_, ref mut receive) => {
                    try_ready!(receive.poll_ready().map_err(Into::into));
                    None
                }
                _ => unreachable!("unexpected state"),
            };

            match mem::replace(self, TestResponseFuture::Done) {
                TestResponseFuture::Initial(..) => {
                    let response = response.expect("unexpected condition");
                    let (parts, body) = response.into_response().into_parts();
                    let receive = self::Receive::new(body);
                    *self = TestResponseFuture::Receive(parts, receive);
                }
                TestResponseFuture::Receive(parts, receive) => {
                    let data = receive.into_data().expect("unexpected condition");
                    let response = Response::from_parts(parts, data);
                    return Ok(response.into());
                }
                _ => unreachable!("unexpected state"),
            }
        }
    }
}