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
//! http server for semantic engines

use iron::prelude::*;

use ::Config;

mod definition;
mod file;
mod completion;
mod ping;

use ::engine::SemanticEngine;

use iron::typemap::Key;
use iron_hmac::Hmac256Authentication;

/// Errors occurring in the http module
#[derive(Debug)]
pub enum Error {
    /// Error occurred in underlying http server lib
    HttpServer(::hyper::Error),
    // Error occurred in http framework layer
    // HttpApp(::iron::IronError),
}

impl From<::hyper::Error> for Error {
    fn from(err: ::hyper::Error) -> Error {
        Error::HttpServer(err)
    }
}

pub type Result<T> = ::std::result::Result<T, Error>;

// -------------------------------------------------------------------------------------------------
/// Iron middleware responsible for attaching a semantic engine to each request
#[derive(Debug, Clone)]
pub struct EngineProvider;

impl Key for EngineProvider {
    type Value = Box<SemanticEngine + Send + Sync>;
}

// -------------------------------------------------------------------------------------------------

/// Start the http server using the given configuration
///
/// `serve` is non-blocking.
///
/// # Example
///
/// ```no_run
/// # use libracerd::{Config};
/// let mut cfg = Config::new();
/// cfg.port = 3000;
///
/// let engine = ::libracerd::engine::Racer::new();
///
/// let mut server = ::libracerd::http::serve(&cfg, engine).unwrap();
/// // ... later
/// server.close().unwrap();
/// ```
///
pub fn serve<E: SemanticEngine + 'static>(config: &Config, engine: E) -> Result<Server> {
    use persistent::{Read, Write};
    use logger::Logger;

    let mut chain = Chain::new(router!(
        post "/parse_file"       => file::parse,
        post "/find_definition"  => definition::find,
        post "/list_completions" => completion::list,
        get  "/ping"             => ping::pong));

    // Logging middleware
    let (log_before, log_after) = Logger::new(None);

    // log_before must be first middleware in before chain
    if config.print_http_logs {
        chain.link_before(log_before);
    }

    // Get HMAC Middleware
    let (hmac_before, hmac_after) = if config.secret_file.is_some() {
        let secret = config.read_secret_file();
        let hmac_header = "x-racerd-hmac";
        let (before, after) = Hmac256Authentication::middleware(secret, hmac_header);
        (Some(before), Some(after))
    } else {
        (None, None)
    };

    // This middleware provides a semantic engine to the request handlers
    chain.link_before(Write::<EngineProvider>::one(Box::new(engine)));

    // Body parser middlerware
    chain.link_before(Read::<::bodyparser::MaxBodyLength>::one(1024 * 1024 * 10));

    // Maybe link hmac middleware
    if let Some(hmac) = hmac_before {
        chain.link_before(hmac);
    }

    if let Some(hmac) = hmac_after {
        chain.link_after(hmac);
    }


    // log_after must be last middleware in after chain
    if config.print_http_logs {
        chain.link_after(log_after);
    }

    let app = Iron::new(chain);

    Ok(Server {
        inner: try!(app.http(("localhost", config.port)))
    })
}

/// Wrapper type with information and control of the underlying HTTP server
///
/// This type can only be created via the [`serve`](fn.serve.html) function.
#[derive(Debug)]
pub struct Server {
    inner: ::hyper::server::Listening,
}

impl Server {
    /// Stop accepting connections
    pub fn close(&mut self) -> Result<()> {
        Ok(try!(self.inner.close()))
    }

    /// Get listening address of server (eg. "127.0.0.1:59369")
    ///
    /// # Example
    /// ```no_run
    /// let mut config = ::libracerd::Config::new();
    /// config.port = 3000;
    ///
    /// let engine = ::libracerd::engine::Racer::new();
    /// let server = ::libracerd::http::serve(&config, engine).unwrap();
    ///
    /// assert_eq!(server.addr(), "0.0.0.0:3000");
    /// ```
    pub fn addr(&self) -> String {
        format!("{}", self.inner.socket)
    }
}