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
use iron::prelude::*;
use ::Config;
mod definition;
mod file;
mod completion;
mod ping;
use ::engine::SemanticEngine;
use iron::typemap::Key;
use iron_hmac::Hmac256Authentication;
#[derive(Debug)]
pub enum Error {
HttpServer(::hyper::Error),
}
impl From<::hyper::Error> for Error {
fn from(err: ::hyper::Error) -> Error {
Error::HttpServer(err)
}
}
pub type Result<T> = ::std::result::Result<T, Error>;
#[derive(Debug, Clone)]
pub struct EngineProvider;
impl Key for EngineProvider {
type Value = Box<SemanticEngine + Send + Sync>;
}
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));
let (log_before, log_after) = Logger::new(None);
if config.print_http_logs {
chain.link_before(log_before);
}
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)
};
chain.link_before(Write::<EngineProvider>::one(Box::new(engine)));
chain.link_before(Read::<::bodyparser::MaxBodyLength>::one(1024 * 1024 * 10));
if let Some(hmac) = hmac_before {
chain.link_before(hmac);
}
if let Some(hmac) = hmac_after {
chain.link_after(hmac);
}
if config.print_http_logs {
chain.link_after(log_after);
}
let app = Iron::new(chain);
Ok(Server {
inner: try!(app.http(("localhost", config.port)))
})
}
#[derive(Debug)]
pub struct Server {
inner: ::hyper::server::Listening,
}
impl Server {
pub fn close(&mut self) -> Result<()> {
Ok(try!(self.inner.close()))
}
pub fn addr(&self) -> String {
format!("{}", self.inner.socket)
}
}