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
#![doc(
    html_root_url = "https://docs.rs/spirit-hyper/0.3.0/spirit_hyper/",
    test(attr(deny(warnings)))
)]
#![forbid(unsafe_code)]
#![warn(missing_docs)]

//! [Spirit] helper for Hyper
//!
//! This allows having Hyper servers auto-spawned from configuration. It is possible to put them on
//! top of arbitrary stream-style IO objects (TcpStream, UdsStream, these wrapped in SSL...).
//!
//! # Examples
//!
//! ```rust
//! extern crate hyper;
//! extern crate serde;
//! #[macro_use]
//! extern crate serde_derive;
//! extern crate spirit;
//! extern crate spirit_hyper;
//! extern crate spirit_tokio;
//!
//! use hyper::{Body, Request, Response};
//! use spirit::{Empty, Spirit};
//! use spirit_hyper::HttpServer;
//!
//! const DEFAULT_CONFIG: &str = r#"
//! [server]
//! port = 1234
//! "#;
//!
//! #[derive(Default, Deserialize)]
//! struct Config {
//!     server: HttpServer,
//! }
//!
//! impl Config {
//!     fn server(&self) -> HttpServer {
//!         self.server.clone()
//!     }
//! }
//!
//! fn request(_req: Request<Body>) -> Response<Body> {
//!     Response::new(Body::from("Hello world\n"))
//! }
//!
//! fn main() {
//!     Spirit::<Empty, Config>::new()
//!         .config_defaults(DEFAULT_CONFIG)
//!         .config_helper(Config::server, spirit_hyper::server_ok(request), "server")
//!         .run(|spirit| {
//! #           let spirit = std::sync::Arc::clone(spirit);
//! #           std::thread::spawn(move || spirit.terminate());
//!             Ok(())
//!         });
//! }
//! ```
//!
//! Further examples are in the
//! [git repository](https://github.com/vorner/spirit/tree/master/spirit-hyper/examples).
//!
//! [Spirit]: https://crates.io/crates/spirit.

extern crate failure;
extern crate futures;
extern crate hyper;
#[macro_use]
extern crate log;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate spirit;
#[macro_use]
extern crate spirit_tokio;
extern crate tokio;

use std::error::Error;
use std::sync::Arc;

use failure::Error as FailError;
use futures::sync::oneshot::{self, Sender};
use futures::{Async, Future, IntoFuture, Poll};
use hyper::body::Payload;
use hyper::server::Server;
use hyper::service::{MakeService, Service};
use hyper::{Body, Request, Response};
use spirit::{Empty, Spirit};
use spirit_tokio::net::IntoIncoming;
use spirit_tokio::{ResourceConfig, ResourceConsumer, TcpListen};
use tokio::io::{AsyncRead, AsyncWrite};

/// Used to signal the graceful shutdown to hyper server.
struct SendOnDrop(Option<Sender<()>>);

impl Drop for SendOnDrop {
    fn drop(&mut self) {
        let _ = self.0.take().unwrap().send(());
    }
}

impl Future for SendOnDrop {
    type Item = ();
    type Error = FailError;
    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        Ok(Async::NotReady)
    }
}

/// Factory for [`MakeService`] implementations.
///
/// Each HTTP connection needs its own [`Service`] instance. As the hyper server accepts the
/// connections, it uses the [`MakeService`] factory to create them.
///
/// The configuration needs to spawn whole new servers (each with its own [`MakeService`]).
/// Therefore, we introduce another level ‒ this trait. It is passed to the [`server`] function.
///
/// There's a blanket implementation for compatible closures.
///
/// There are also functions similar to [`server`] which forgo some flexibility in favor of
/// convenience.
pub trait ConfiguredMakeService<O, C, Cfg>: Send + Sync + 'static
where
    Cfg: ResourceConfig<O, C>,
{
    /// The type of `MakeService` created.
    type MakeService;

    /// Create a new `MakeService` instance.
    ///
    /// # Parameters
    ///
    /// * `spirit`: The spirit instance.
    /// * `cfg`: The configuration fragment that caused creation of the server.
    /// * `resource`: The acceptor (eg. `TcpListener::accept`) the server will use.
    /// * `name`: Logging name.
    fn make(
        &self,
        spirit: &Arc<Spirit<O, C>>,
        cfg: &Arc<Cfg>,
        resource: &Cfg::Resource,
        name: &str,
    ) -> Self::MakeService;
}

impl<O, C, Cfg, F, R> ConfiguredMakeService<O, C, Cfg> for F
where
    Cfg: ResourceConfig<O, C>,
    F: Fn(&Arc<Spirit<O, C>>, &Arc<Cfg>, &Cfg::Resource, &str) -> R + Send + Sync + 'static,
{
    type MakeService = R;
    fn make(
        &self,
        spirit: &Arc<Spirit<O, C>>,
        cfg: &Arc<Cfg>,
        resource: &Cfg::Resource,
        name: &str,
    ) -> R {
        self(spirit, cfg, resource, name)
    }
}

/// Creates a [`ResourceConsumer`] from a [`ConfiguredMakeService`].
///
/// This is the lowest level constructor of the hyper resource consumers, when the full flexibility
/// is needed.
///
/// # Examples
///
/// ```rust
/// extern crate hyper;
/// extern crate serde;
/// #[macro_use]
/// extern crate serde_derive;
/// extern crate spirit;
/// extern crate spirit_hyper;
/// extern crate spirit_tokio;
///
/// use hyper::{Body, Request, Response};
/// use spirit::{Empty, Spirit};
/// use spirit_hyper::HttpServer;
///
/// #[derive(Default, Deserialize)]
/// struct Config {
///     #[serde(default)]
///     server: Vec<HttpServer>,
/// }
///
/// impl Config {
///     fn server(&self) -> Vec<HttpServer> {
///         self.server.clone()
///     }
/// }
///
/// fn request(_req: Request<Body>) -> Response<Body> {
///     Response::new(Body::from("Hello world\n"))
/// }
///
/// fn main() {
///     Spirit::<Empty, Config>::new()
///         .with(spirit_tokio::resources(
///             Config::server,
///             spirit_hyper::server(|_spirit: &_, _cfg: &_, _resource: &_, _name: &str| {
///                 || hyper::service::service_fn_ok(request)
///             }),
///             "server",
///         ))
///         .run(|spirit| {
/// #           let spirit = std::sync::Arc::clone(spirit);
/// #           std::thread::spawn(move || spirit.terminate());
///             Ok(())
///         });
/// }
/// ```
pub fn server<R, O, C, CMS, B, E, ME, S, F>(
    configured_make_service: CMS,
) -> impl ResourceConsumer<HyperServer<R>, O, C>
where
    R: ResourceConfig<O, C>,
    R::Resource: IntoIncoming,
    <R::Resource as IntoIncoming>::Connection: AsyncRead + AsyncWrite,
    CMS: ConfiguredMakeService<O, C, HyperServer<R>>,
    // TODO: Once hyper with the MakeServiceRef is released, migrate to that instead of this beast.
    CMS::MakeService: for<'a> MakeService<
            &'a <R::Resource as IntoIncoming>::Connection,
            ReqBody = Body,
            Error = E,
            MakeError = ME,
            Service = S,
            Future = F,
            ResBody = B,
        > + Send
        + Sync
        + 'static,
    E: Into<Box<Error + Send + Sync>>,
    ME: Into<Box<Error + Send + Sync>>,
    S: Service<ReqBody = Body, ResBody = B, Error = E> + Send + 'static,
    S::Future: Send,
    F: Future<Item = S, Error = ME> + Send + 'static,
    B: Payload,
{
    move |spirit: &Arc<Spirit<O, C>>,
          config: &Arc<HyperServer<R>>,
          resource: R::Resource,
          name: &str| {
        let (sender, receiver) = oneshot::channel();
        debug!("Starting hyper server {}", name);
        let name_success = name.to_owned();
        let name_err = name.to_owned();
        let make_service = configured_make_service.make(spirit, config, &resource, name);
        let (h1_only, h2_only) = match config.http_mode.http_mode {
            HttpMode::Both => (false, false),
            HttpMode::Http1Only => (true, false),
            HttpMode::Http2Only => (false, true),
        };
        let server = Server::builder(resource.into_incoming())
            .http1_keepalive(config.http1_keepalive)
            .http1_writev(config.http1_writev)
            .http1_only(h1_only)
            .http2_only(h2_only)
            .serve(make_service)
            .with_graceful_shutdown(receiver)
            .map(move |()| debug!("Hyper server {} shut down", name_success))
            .map_err(move |e| error!("Hyper server {} failed: {}", name_err, e));
        tokio::spawn(server);
        SendOnDrop(Some(sender))
    }
}

/// Creates a hyper [`ResourceConfig`] for a closure that returns the [`Response`] directly.
///
/// This is like [`server`], but the passed parameter is `Fn(Request) -> Response`. This means it
/// is not passed anything from `spirit`, it is synchronous and never fails. It must be cloneable.
pub fn server_ok<R, O, C, S, B>(service: S) -> impl ResourceConsumer<HyperServer<R>, O, C>
where
    R: ResourceConfig<O, C>,
    R::Resource: IntoIncoming,
    <R::Resource as IntoIncoming>::Connection: AsyncRead + AsyncWrite,
    S: Fn(Request<Body>) -> Response<B> + Clone + Send + Sync + 'static,
    B: Payload,
{
    let configure_service = move |_: &_, _: &_, _: &_, _: &_| {
        let service = service.clone();
        move || hyper::service::service_fn_ok(service.clone())
    };
    server(configure_service)
}

/// Creates a hyper [`ResourceConfig`] for a closure that returns a future of [`Response`].
///
/// This is like [`server`], but the passed parameter is
/// `Fn(Request) -> impl Future<Item = Response>`. This means it is not passed any configuration
/// from `spirit`. It also needs to be cloneable.
pub fn server_simple<R, O, C, S, Fut, B>(service: S) -> impl ResourceConsumer<HyperServer<R>, O, C>
where
    R: ResourceConfig<O, C>,
    R::Resource: IntoIncoming,
    <R::Resource as IntoIncoming>::Connection: AsyncRead + AsyncWrite,
    S: Fn(Request<Body>) -> Fut + Clone + Send + Sync + 'static,
    Fut: IntoFuture<Item = Response<B>> + Send + 'static,
    Fut::Future: Send + 'static,
    Fut::Error: Into<Box<Error + Send + Sync>>,
    B: Payload,
{
    let configure_service = move |_: &_, _: &_, _: &_, _: &_| {
        let service = service.clone();
        move || hyper::service::service_fn(service.clone())
    };
    server(configure_service)
}

/// Like [`server`], but taking a closure to answer request directly.
///
/// The closure taken is `Fn(spirit, cfg, request) -> impl Future<Response>`.
///
/// If the configuration is not needed, the [`server_simple`] or [`server_ok`] might be an
/// alternative.
///
/// # Examples
///
/// ```rust
/// extern crate hyper;
/// extern crate serde;
/// #[macro_use]
/// extern crate serde_derive;
/// extern crate spirit;
/// extern crate spirit_hyper;
/// extern crate spirit_tokio;
///
/// use std::collections::HashSet;
/// use std::sync::Arc;
///
/// use hyper::{Body, Request, Response};
/// use spirit::{Empty, Spirit};
/// use spirit_tokio::ExtraCfgCarrier;
/// use spirit_hyper::HttpServer;
///
/// const DEFAULT_CONFIG: &str = r#"
/// [[server]]
/// port = 3456
///
/// [ui]
/// msg = "Hello world"
/// "#;
///
///
/// #[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Hash)]
/// struct Signature {
///     signature: Option<String>,
/// }
///
/// #[derive(Default, Deserialize)]
/// struct Ui {
///     msg: String,
/// }
///
/// #[derive(Default, Deserialize)]
/// struct Config {
///     /// On which ports (and interfaces) to listen.
///     ///
///     /// With some additional configuration about listening, the http server...
///     ///
///     /// Also, signature of the given listening port.
///     #[serde(default)]
///     listen: HashSet<HttpServer<Signature>>,
///     /// The UI (there's only the message to send).
///     ui: Ui,
/// }
///
/// impl Config {
///     /// A function to extract the HTTP servers configuration
///     fn listen(&self) -> HashSet<HttpServer<Signature>> {
///         self.listen.clone()
///     }
/// }
///
/// fn hello(
///     spirit: &Arc<Spirit<Empty, Config>>,
///     cfg: &Arc<HttpServer<Signature>>,
///    _req: Request<Body>,
/// ) -> Result<Response<Body>, std::io::Error> {
///     // Get some global configuration
///     let mut msg = format!("{}\n", spirit.config().ui.msg);
///     // Get some listener-local configuration.
///     if let Some(ref signature) = cfg.extra().signature {
///         msg.push_str(&format!("Brought to you by {}\n", signature));
///     }
///     Ok(Response::new(Body::from(msg)))
/// }
///
/// fn main() {
///     Spirit::<Empty, Config>::new()
///         .config_defaults(DEFAULT_CONFIG)
///         .with(spirit_tokio::resources(
///             Config::listen,
///             spirit_hyper::server_configured(hello),
///             "server",
///         ))
///         .run(|spirit| {
/// #           let spirit = Arc::clone(spirit);
/// #           std::thread::spawn(move || spirit.terminate());
///             Ok(())
///         });
/// }
/// ```
pub fn server_configured<R, O, C, S, Fut, B>(
    service: S,
) -> impl ResourceConsumer<HyperServer<R>, O, C>
where
    C: Send + Sync + 'static,
    O: Send + Sync + 'static,
    R: ResourceConfig<O, C>,
    R::Resource: IntoIncoming,
    <R::Resource as IntoIncoming>::Connection: AsyncRead + AsyncWrite,
    S: Fn(&Arc<Spirit<O, C>>, &Arc<HyperServer<R>>, Request<Body>) -> Fut
        + Clone
        + Send
        + Sync
        + 'static,
    Fut: IntoFuture<Item = Response<B>> + Send + 'static,
    Fut::Future: Send + 'static,
    Fut::Error: Into<Box<Error + Send + Sync>>,
    B: Payload,
{
    let configure_service = move |spirit: &_, cfg: &_, _: &_, _: &_| {
        let service = service.clone();
        let spirit = Arc::clone(spirit);
        let cfg = Arc::clone(cfg);
        move || {
            let service = service.clone();
            let spirit = Arc::clone(&spirit);
            let cfg = Arc::clone(&cfg);
            hyper::service::service_fn(move |req| service(&spirit, &cfg, req))
        }
    };
    server(configure_service)
}

fn default_on() -> bool {
    true
}

#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[serde(rename_all = "kebab-case")]
enum HttpMode {
    Both,
    #[serde(rename = "http1-only")]
    Http1Only,
    #[serde(rename = "http2-only")]
    Http2Only,
}

impl Default for HttpMode {
    fn default() -> Self {
        HttpMode::Both
    }
}

#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[serde(rename_all = "kebab-case")]
struct HttpModeWorkaround {
    #[serde(default)]
    http_mode: HttpMode,
}

/// A [`ResourceConfig`] for hyper servers.
///
/// This is a wrapper around a `Transport` [`ResourceConfig`]. It takes something that accepts
/// connections ‒ like [`TcpListen`] and adds configuration specific for HTTP server.
///
/// This can then be paired with one of the [`ResourceConsumer`]s created by `server` functions to
/// spawn servers:
///
/// * [`server`]
/// * [`server_configured`]
/// * [`server_simple`]
/// * [`server_ok`]
///
/// See also the [`HttpServer`] type alias.
///
/// # Configuration options
///
/// In addition to options already provided by the `Transport`, these options are added:
///
/// * `http1-keepalive`: boolean, default true.
/// * `http1-writev`: boolean, default true.
/// * `http-mode`: One of `"both"`, `"http1-only"` or `"http2-only"`. Defaults to `"both"`.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[serde(rename_all = "kebab-case")]
pub struct HyperServer<Transport> {
    #[serde(flatten)]
    transport: Transport,
    #[serde(default = "default_on")]
    http1_keepalive: bool,
    #[serde(default = "default_on")]
    http1_writev: bool,
    #[serde(default, flatten)]
    http_mode: HttpModeWorkaround,
}

impl<Transport: Default> Default for HyperServer<Transport> {
    fn default() -> Self {
        HyperServer {
            transport: Transport::default(),
            http1_keepalive: true,
            http1_writev: true,
            http_mode: HttpModeWorkaround {
                http_mode: HttpMode::Both,
            },
        }
    }
}

delegate_resource_traits! {
    delegate ResourceConfig, ExtraCfgCarrier to transport on HyperServer;
}

cfg_helpers! {
    impl helpers for HyperServer<Transport> where;
}

/// A type alias for http (plain TCP) hyper server.
pub type HttpServer<ExtraCfg = Empty> = HyperServer<TcpListen<ExtraCfg>>;