This repository has been archived by the owner on Jun 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 24
/
mod.rs
155 lines (129 loc) · 4.27 KB
/
mod.rs
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
//! http server for semantic engines
use iron::prelude::*;
use crate::Config;
mod completion;
mod definition;
mod file;
mod ping;
use crate::engine::SemanticEngine;
use iron::typemap::Key;
use iron_hmac::Hmac256Authentication;
use iron_hmac::SecretKey;
use std::sync::{Arc, Mutex};
/// Errors occurring in the http module
#[derive(Debug)]
pub enum Error {
/// Error occurred in underlying http server lib
HttpServer(iron::error::HttpError),
}
impl From<iron::error::HttpError> for Error {
fn from(err: iron::error::HttpError) -> 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<dyn SemanticEngine + Send + Sync + 'static>;
}
// -------------------------------------------------------------------------------------------------
/// 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 + Send + Sync + 'static>(
config: &Config,
engine: E,
) -> Result<Server> {
use logger::Format;
use logger::Logger;
use persistent::{Read, Write};
let mut chain = Chain::new(router!(
parse: post "/parse_file" => file::parse,
find: post "/find_definition" => definition::find,
list: post "/list_completions" => completion::list,
ping: get "/ping" => ping::pong));
// Logging middleware
let log_fmt = Format::new("{method} {uri} -> {status} ({response-time})");
let (log_before, log_after) = Logger::new(log_fmt);
// 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 = SecretKey::new(&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
// where Box<E>: PersistentInto<Arc<Mutex<Box<SemanticEngine + Sync + Send + 'static>>>>
let x: Arc<Mutex<Box<dyn SemanticEngine + Sync + Send + 'static>>> =
Arc::new(Mutex::new(Box::new(engine)));
chain.link_before(Write::<EngineProvider>::one(x));
// 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: app.http((&config.addr[..], 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: iron::Listening,
}
impl Server {
/// Stop accepting connections
pub fn close(&mut self) -> Result<()> {
self.inner.close().map_err(|e| e.into())
}
/// 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)
}
}