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
use {bincode, future, num_cpus};
use future::server::{Response, Shutdown};
use futures::{Future, future as futures};
use futures::sync::oneshot;
#[cfg(feature = "tls")]
use native_tls_inner::TlsAcceptor;
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::fmt;
use std::io;
use std::net::SocketAddr;
use std::time::Duration;
use std::usize;
use thread_pool::{self, Sender, Task, ThreadPool};
use tokio_core::reactor;
use tokio_service::{NewService, Service};

/// Additional options to configure how the server operates.
#[derive(Debug)]
pub struct Options {
    thread_pool: thread_pool::Builder,
    opts: future::server::Options,
}

impl Default for Options {
    fn default() -> Self {
        let num_cpus = num_cpus::get();
        Options {
            thread_pool: thread_pool::Builder::new()
                .keep_alive(Duration::from_secs(60))
                .max_pool_size(num_cpus * 100)
                .core_pool_size(num_cpus)
                .work_queue_capacity(usize::MAX)
                .name_prefix("request-thread-"),
            opts: future::server::Options::default(),
        }
    }
}

impl Options {
    /// Set the max payload size in bytes. The default is 2,000,000 (2 MB).
    pub fn max_payload_size(mut self, bytes: u64) -> Self {
        self.opts = self.opts.max_payload_size(bytes);
        self
    }

    /// Sets the thread pool builder to use when creating the server's thread pool.
    pub fn thread_pool(mut self, builder: thread_pool::Builder) -> Self {
        self.thread_pool = builder;
        self
    }

    /// Set the `TlsAcceptor`
    #[cfg(feature = "tls")]
    pub fn tls(mut self, tls_acceptor: TlsAcceptor) -> Self {
        self.opts = self.opts.tls(tls_acceptor);
        self
    }
}

/// A handle to a bound server. Must be run to start serving requests.
#[must_use = "A server does nothing until `run` is called."]
pub struct Handle {
    reactor: reactor::Core,
    handle: future::server::Handle,
    server: Box<Future<Item = (), Error = ()>>,
}

impl Handle {
    /// Runs the server on the current thread, blocking indefinitely.
    pub fn run(mut self) {
        trace!("Running...");
        match self.reactor.run(self.server) {
            Ok(()) => debug!("Server successfully shutdown."),
            Err(()) => debug!("Server shutdown due to error."),
        }
    }

    /// Returns a hook for shutting down the server.
    pub fn shutdown(&self) -> Shutdown {
        self.handle.shutdown().clone()
    }

    /// The socket address the server is bound to.
    pub fn addr(&self) -> SocketAddr {
        self.handle.addr()
    }
}

impl fmt::Debug for Handle {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        const CORE: &'static &'static str = &"Core { .. }";
        const SERVER: &'static &'static str = &"Box<Future<Item = (), Error = ()>>";

        f.debug_struct("Handle")
            .field("reactor", CORE)
            .field("handle", &self.handle)
            .field("server", SERVER)
            .finish()
    }
}

#[doc(hidden)]
pub fn listen<S, Req, Resp, E>(new_service: S,
                               addr: SocketAddr,
                               options: Options)
                               -> io::Result<Handle>
    where S: NewService<Request = Result<Req, bincode::Error>,
                        Response = Response<Resp, E>,
                        Error = io::Error> + 'static,
          <S::Instance as Service>::Future: Send + 'static,
          S::Response: Send,
          S::Error: Send,
          Req: DeserializeOwned + 'static,
          Resp: Serialize + 'static,
          E: Serialize + 'static
{
    let new_service = NewThreadService::new(new_service, options.thread_pool);
    let reactor = reactor::Core::new()?;
    let (handle, server) =
        future::server::listen(new_service, addr, &reactor.handle(), options.opts)?;
    let server = Box::new(server);
    Ok(Handle {
        reactor: reactor,
        handle: handle,
        server: server,
    })
}

/// A service that uses a thread pool.
struct NewThreadService<S>
where
    S: NewService,
{
    new_service: S,
    sender: Sender<ServiceTask<<S::Instance as Service>::Future>>,
    _pool: ThreadPool<ServiceTask<<S::Instance as Service>::Future>>,
}

/// A service that runs by executing request handlers in a thread pool.
struct ThreadService<S>
where
    S: Service,
{
    service: S,
    sender: Sender<ServiceTask<S::Future>>,
}

/// A task that handles a single request.
struct ServiceTask<F>
where
    F: Future,
{
    future: F,
    tx: oneshot::Sender<Result<F::Item, F::Error>>,
}

impl<S> NewThreadService<S>
where
    S: NewService,
    <S::Instance as Service>::Future: Send + 'static,
    S::Response: Send,
    S::Error: Send,
{
    /// Create a NewThreadService by wrapping another service.
    fn new(new_service: S, pool: thread_pool::Builder) -> Self {
        let (sender, _pool) = pool.build();
        NewThreadService {
            new_service,
            sender,
            _pool,
        }
    }
}

impl<S> NewService for NewThreadService<S>
where
    S: NewService,
    <S::Instance as Service>::Future: Send + 'static,
    S::Response: Send,
    S::Error: Send,
{
    type Request = S::Request;
    type Response = S::Response;
    type Error = S::Error;
    type Instance = ThreadService<S::Instance>;

    fn new_service(&self) -> io::Result<Self::Instance> {
        Ok(ThreadService {
            service: self.new_service.new_service()?,
            sender: self.sender.clone(),
        })
    }
}

impl<F> Task for ServiceTask<F>
where
    F: Future + Send + 'static,
    F::Item: Send,
    F::Error: Send,
{
    fn run(self) {
        // Don't care if sending fails. It just means the request is no longer
        // being handled (I think).
        let _ = self.tx.send(self.future.wait());
    }
}

impl<S> Service for ThreadService<S>
where
    S: Service,
    S::Future: Send + 'static,
    S::Response: Send,
    S::Error: Send,
{
    type Request = S::Request;
    type Response = S::Response;
    type Error = S::Error;
    type Future = futures::AndThen<
        futures::MapErr<
            oneshot::Receiver<Result<Self::Response, Self::Error>>,
            fn(oneshot::Canceled) -> Self::Error,
        >,
        Result<Self::Response, Self::Error>,
        fn(Result<Self::Response, Self::Error>)
            -> Result<Self::Response, Self::Error>,
    >;

    fn call(&self, request: Self::Request) -> Self::Future {
        let (tx, rx) = oneshot::channel();
        self.sender
            .send(ServiceTask {
                future: self.service.call(request),
                tx: tx,
            })
            .unwrap();
        rx.map_err(unreachable as _).and_then(ident)
    }
}

fn unreachable<T, U>(t: T) -> U
where
    T: fmt::Display,
{
    unreachable!(t)
}

fn ident<T>(t: T) -> T {
    t
}