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
use std;
use std::cell::RefCell;
use std::rc::Rc;

use futures::future::*;
use hyper;
use hyper::server::conn::Http;
use hyper::{Body, Request, Response};
use tokio::net::TcpListener;
use tokio_current_thread as current_thread;
use url;

use error::*;
use resp_serv_err;
use HyperService;
use HyperServiceSend;

enum RoutePath {
    Exact(String),
    Prefix(String),
}

enum RouteService {
    NotSend(RefCell<HyperService>),
    Send(RefCell<HyperServiceSend>),
}
impl From<HyperService> for RouteService {
    fn from(s: HyperService) -> RouteService {
        RouteService::NotSend(RefCell::new(s))
    }
}
impl From<HyperServiceSend> for RouteService {
    fn from(s: HyperServiceSend) -> RouteService {
        RouteService::Send(RefCell::new(s))
    }
}

#[cfg(feature = "fst")]
type FstMap = ::fst::Map;
#[cfg(not(feature = "fst"))]
type FstMap = ();

#[derive(Default)]
pub struct Routes {
    routes: Vec<(String, RouteService)>,
    #[allow(unused)]
    map: FstMap,
}

impl Routes {
    pub fn new() -> Self {
        Self {
            routes: Vec::new(),
            map: Default::default(),
        }
    }

    fn push_serv<S>(&mut self, method: hyper::Method, path: RoutePath, service: S)
    where
        S: Into<RouteService>,
    {
        let key = match path {
            RoutePath::Exact(s) => format!("{}?{}?", method, s),
            RoutePath::Prefix(s) => format!("{}?{}", method, s),
        };
        self.routes.push((key, service.into()));
    }

    pub fn push(&mut self, method: hyper::Method, path: &str, service: HyperService) {
        self.push_serv(method, RoutePath::Exact(path.to_owned()), service)
    }

    pub fn push_prefix(&mut self, method: hyper::Method, prefix: &str, service: HyperService) {
        self.push_serv(method, RoutePath::Prefix(prefix.to_owned()), service)
    }

    pub fn push_send(&mut self, method: hyper::Method, path: &str, service: HyperServiceSend) {
        self.push_serv(method, RoutePath::Exact(path.to_owned()), service)
    }

    pub fn push_send_prefix(
        &mut self,
        method: hyper::Method,
        prefix: &str,
        service: HyperServiceSend,
    ) {
        self.push_serv(method, RoutePath::Prefix(prefix.to_owned()), service)
    }

    #[cfg(feature = "fst")]
    fn build(&mut self) {
        self.routes.sort_by(|(k1, _s1), (k2, _s2)| k1.cmp(k2));
        self.map = ::fst::Map::from_iter(
            self.routes
                .iter()
                .enumerate()
                .map(|(idx, (key, _serv))| (key.to_owned(), idx as u64)),
        ).expect("failed to build map");
    }

    #[cfg(feature = "fst")]
    fn longest_match(&self, key: &[u8]) -> Option<usize> {
        let fst = self.map.as_fst();
        let mut node = fst.root();
        let mut last_out = None;
        let mut out = ::fst::raw::Output::zero();
        for b in key {
            node = match node.find_input(*b) {
                None => {
                    break;
                }
                Some(i) => {
                    let t = node.transition(i);
                    out = out.cat(t.out);
                    fst.node(t.addr)
                }
            };
            if node.is_final() {
                last_out = Some(out);
            }
        }
        last_out.map(|o| o.value() as usize)
    }

    #[cfg(feature = "fst")]
    fn route(&self, method: hyper::Method, path: &str) -> Option<&RouteService> {
        let s = format!("{}?{}?", method, path);
        let idx = self.longest_match(s.as_bytes())?;
        self.routes.get(idx).map(|(_key, serv)| serv)
    }

    #[cfg(not(feature = "fst"))]
    fn build(&mut self) {}

    #[cfg(not(feature = "fst"))]
    fn route(&self, method: hyper::Method, path: &str) -> Option<&RouteService> {
        let s = format!("{}?{}?", method, path);
        for (ref key, ref route) in &self.routes {
            if s.starts_with(key) {
                return Some(route);
            }
        }
        None
    }
}

#[derive(Default, Clone)]
pub struct Server {
    routes: Rc<Routes>,
}

impl Server {
    pub fn new(mut routes: Routes) -> Self {
        routes.build();
        Self {
            routes: Rc::new(routes),
        }
    }

    #[cfg(feature = "uds")]
    pub fn run_uds(self, url: url::Url) -> Box<Future<Item = (), Error = Error>> {
        use tokio_uds;

        let path = url.path();
        if let Err(_) = std::fs::remove_file(path) {
            //ignore error?
        }

        let listener = tokio_uds::UnixListener::bind(path).unwrap();
        let exec = current_thread::TaskExecutor::current();
        let f = hyper::server::Builder::new(listener.incoming(), Http::new())
            .executor(exec)
            .serve(self)
            .map_err(Error::from);
        Box::new(f)
    }

    pub fn run_tcp(self, addr: std::net::SocketAddr) -> Box<Future<Item = (), Error = Error>> {
        let listener = TcpListener::bind(&addr).unwrap();
        let exec = current_thread::TaskExecutor::current();
        let f = hyper::server::Builder::new(listener.incoming(), Http::new())
            .executor(exec)
            .serve(self)
            .map_err(Error::from);
        Box::new(f)
    }

    #[cfg(not(feature = "uds"))]
    pub fn run_uds(self, _url: url::Url) -> Box<Future<Item = (), Error = Error>> {
        panic!("uds not supported: {:?}", _url);
    }

    pub fn run(self, url: url::Url) -> Box<Future<Item = (), Error = Error>> {
        let is_unix = match url.scheme() {
            "http" => false,
            "http+unix" => true,
            schema => {
                panic!("unexpected schema: {}", schema);
            }
        };

        if is_unix {
            self.run_uds(url)
        } else {
            //TODO: with_deault_port
            let addr_str = format!(
                "{}:{}",
                url.host().expect("failed to get host"),
                url.port().expect("failed to get port")
            );
            let addr = addr_str.parse().expect("failed to parse addr");
            self.run_tcp(addr)
        }
    }
}

impl hyper::service::Service for Server {
    type ReqBody = Body;
    type ResBody = Body;
    type Error = hyper::Error;
    type Future = Box<Future<Item = Response<Self::ResBody>, Error = Self::Error>>;

    fn call(&mut self, req: Request<Body>) -> Self::Future {
        let method = req.method().clone();
        let uri = req.uri().clone();
        info!("req: {} {}", method, uri);

        let path = uri.path();
        if let Some(serv) = self.routes.route(method, path) {
            match serv {
                RouteService::NotSend(serv) => serv.borrow_mut().call(req),
                RouteService::Send(serv) => serv.borrow_mut().call(req),
            }
        } else {
            let e = Error::from(ErrorKind::InvalidEndpoint);
            Box::new(ok(resp_serv_err(e, hyper::StatusCode::NOT_FOUND)))
        }
    }
}

impl hyper::service::NewService for Server {
    type ReqBody = Body;
    type ResBody = Body;
    type Error = hyper::Error;
    type Service = Self;
    type Future = FutureResult<Self::Service, Self::InitError>;
    type InitError = hyper::Error;

    fn new_service(&self) -> Self::Future {
        ok(self.clone())
    }
}