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
pub mod builder;
pub use builder::{build_router, build_simple_router};
pub mod response;
pub mod route;
pub mod tree;
mod non_match;
pub use self::non_match::RouteNonMatch;
use std::pin::Pin;
use std::sync::Arc;
use futures_util::future::{self, FutureExt, TryFutureExt};
use hyper::header::ALLOW;
use hyper::{Body, Response, StatusCode};
use log::{error, trace};
use crate::handler::{Handler, HandlerFuture, IntoResponse, NewHandler};
use crate::helpers::http::request::path::RequestPathSegments;
use crate::helpers::http::response::create_empty_response;
use crate::router::response::ResponseFinalizer;
use crate::router::route::{Delegation, Route};
use crate::router::tree::segment::SegmentMapping;
use crate::router::tree::Tree;
use crate::state::{request_id, State};
struct RouterData {
tree: Tree,
response_finalizer: ResponseFinalizer,
}
impl RouterData {
fn new(tree: Tree, response_finalizer: ResponseFinalizer) -> RouterData {
RouterData {
tree,
response_finalizer,
}
}
}
#[derive(Clone)]
pub struct Router {
data: Arc<RouterData>,
}
impl NewHandler for Router {
type Instance = Router;
fn new_handler(&self) -> anyhow::Result<Self::Instance> {
trace!(" cloning instance");
Ok(self.clone())
}
}
impl Handler for Router {
fn handle(self, mut state: State) -> Pin<Box<HandlerFuture>> {
trace!("[{}] starting", request_id(&state));
let future = match state.try_take::<RequestPathSegments>() {
Some(rps) => {
if let Some((node, params, processed)) = self.data.tree.traverse(rps.segments()) {
match node.select_route(&state) {
Ok(route) => match route.delegation() {
Delegation::External => {
trace!("[{}] delegating to secondary router", request_id(&state));
state.put(rps.subsegments(processed));
route.dispatch(state)
}
Delegation::Internal => {
trace!("[{}] dispatching to route", request_id(&state));
self.dispatch(state, params, route)
}
},
Err(non_match) => {
let (status, allow) = non_match.deconstruct();
trace!("[{}] responding with error status", request_id(&state));
let mut res = create_empty_response(&state, status);
if let StatusCode::METHOD_NOT_ALLOWED = status {
for allowed in allow {
res.headers_mut().append(
ALLOW,
allowed.as_str().to_string().parse().unwrap(),
);
}
}
future::ok((state, res)).boxed()
}
}
} else {
trace!("[{}] did not find routable node", request_id(&state));
let res = create_empty_response(&state, StatusCode::NOT_FOUND);
future::ok((state, res)).boxed()
}
}
None => {
trace!("[{}] invalid request path segments", request_id(&state));
let res = create_empty_response(&state, StatusCode::INTERNAL_SERVER_ERROR);
future::ok((state, res)).boxed()
}
};
self.finalize_response(future)
}
}
impl Router {
fn new(tree: Tree, response_finalizer: ResponseFinalizer) -> Router {
let router_data = RouterData::new(tree, response_finalizer);
Router {
data: Arc::new(router_data),
}
}
fn dispatch<'a>(
&self,
mut state: State,
params: SegmentMapping<'a>,
route: &Box<dyn Route<ResBody = Body> + Send + Sync>,
) -> Pin<Box<HandlerFuture>> {
match route.extract_request_path(&mut state, params) {
Ok(()) => {
trace!("[{}] extracted request path", request_id(&state));
match route.extract_query_string(&mut state) {
Ok(()) => {
trace!("[{}] extracted query string", request_id(&state));
trace!("[{}] dispatching", request_id(&state));
route.dispatch(state)
}
Err(_) => {
error!("[{}] the server cannot or will not process the request due to a client error within the query string",
request_id(&state));
let mut res = Response::new(Body::empty());
route.extend_response_on_query_string_error(&mut state, &mut res);
future::ok((state, res)).boxed()
}
}
}
Err(_) => {
error!(
"[{}] the server cannot or will not process the request due to a client error on the request path",
request_id(&state)
);
let mut res = Response::new(Body::empty());
route.extend_response_on_path_error(&mut state, &mut res);
future::ok((state, res)).boxed()
}
}
}
fn finalize_response(&self, result: Pin<Box<HandlerFuture>>) -> Pin<Box<HandlerFuture>> {
let response_finalizer = self.data.response_finalizer.clone();
result
.or_else(|(state, err)| {
trace!(
"[{}] converting error into http response \
during finalization: {:?}",
request_id(&state),
err
);
let response = err.into_response(&state);
future::ok((state, response))
})
.and_then(move |(state, res)| {
trace!("[{}] handler complete", request_id(&state));
response_finalizer.finalize(state, res)
})
.boxed()
}
}
#[cfg(test)]
mod tests {
use super::*;
use hyper::header::{HeaderMap, CONTENT_LENGTH, CONTENT_TYPE};
use hyper::{Body, Method, Uri};
use mime::TEXT_PLAIN;
use std::str::FromStr;
use crate::extractor::{NoopPathExtractor, NoopQueryStringExtractor};
use crate::handler::HandlerError;
use crate::pipeline::{finalize_pipeline_set, new_pipeline_set};
use crate::router::response::ResponseFinalizerBuilder;
use crate::router::route::dispatch::DispatcherImpl;
use crate::router::route::matcher::{
AndRouteMatcher, ContentTypeHeaderRouteMatcher, MethodOnlyRouteMatcher,
};
use crate::router::route::{Extractors, RouteImpl};
use crate::router::tree::node::Node;
use crate::router::tree::segment::SegmentType;
use crate::router::tree::Tree;
use crate::state::set_request_id;
fn handler(state: State) -> (State, Response<Body>) {
(state, Response::new(Body::empty()))
}
fn send_request(
r: Router,
method: Method,
uri: &str,
) -> ::std::result::Result<(State, Response<Body>), (State, HandlerError)> {
let uri = Uri::from_str(uri).unwrap();
let mut headers = HeaderMap::new();
if method == Method::POST {
headers.insert(CONTENT_TYPE, "application/json".parse().unwrap());
headers.insert(CONTENT_LENGTH, 0.into());
}
let mut state = State::new();
state.put(RequestPathSegments::new(uri.path()));
state.put(method);
state.put(uri);
state.put(headers);
set_request_id(&mut state);
futures_executor::block_on(r.handle(state))
}
#[test]
fn internal_server_error_if_no_request_path_segments() {
let tree = Tree::new();
let router = Router::new(tree, ResponseFinalizerBuilder::new().finalize());
let method = Method::GET;
let uri = Uri::from_str("https://test.gotham.rs").unwrap();
let mut state = State::new();
state.put(method);
state.put(uri);
state.put(HeaderMap::new());
set_request_id(&mut state);
match futures_executor::block_on(router.handle(state)) {
Ok((_state, res)) => {
assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
Err(_) => unreachable!("Router should have handled request"),
};
}
#[test]
fn not_found_error_if_request_path_is_not_found() {
let tree = Tree::new();
let router = Router::new(tree, ResponseFinalizerBuilder::new().finalize());
match send_request(router, Method::GET, "https://test.gotham.rs") {
Ok((_state, res)) => {
assert_eq!(res.status(), StatusCode::NOT_FOUND);
}
Err(_) => unreachable!("Router should have handled request"),
};
}
#[test]
fn custom_error_if_leaf_found_but_matching_route_not_found() {
let pipeline_set = finalize_pipeline_set(new_pipeline_set());
let mut tree = Tree::new();
let route = {
let methods = vec![Method::POST];
let matcher = AndRouteMatcher::new(
MethodOnlyRouteMatcher::new(methods),
ContentTypeHeaderRouteMatcher::new(vec![TEXT_PLAIN]),
);
let dispatcher = Box::new(DispatcherImpl::new(|| Ok(handler), (), pipeline_set));
let extractors: Extractors<NoopPathExtractor, NoopQueryStringExtractor> =
Extractors::new();
let route = RouteImpl::new(matcher, dispatcher, extractors, Delegation::Internal);
Box::new(route)
};
tree.add_route(route);
let router = Router::new(tree, ResponseFinalizerBuilder::new().finalize());
match send_request(router.clone(), Method::GET, "https://test.gotham.rs") {
Ok((_state, res)) => {
assert_eq!(res.status(), StatusCode::METHOD_NOT_ALLOWED);
assert_eq!(
res.headers()
.get_all(ALLOW)
.iter()
.map(|it| it.to_str().unwrap())
.collect::<Vec<&str>>(),
vec!["POST"]
);
}
Err(_) => unreachable!("Router should have handled request"),
};
match send_request(router, Method::POST, "https://test.gotham.rs") {
Ok((_state, res)) => {
assert_eq!(res.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
assert!(res.headers().get_all(ALLOW).iter().next().is_none());
}
Err(_) => unreachable!("Router should have handled request"),
};
}
#[test]
fn success_if_leaf_and_route_found() {
let pipeline_set = finalize_pipeline_set(new_pipeline_set());
let mut tree = Tree::new();
let route = {
let methods = vec![Method::GET];
let matcher = MethodOnlyRouteMatcher::new(methods);
let dispatcher = Box::new(DispatcherImpl::new(|| Ok(handler), (), pipeline_set));
let extractors: Extractors<NoopPathExtractor, NoopQueryStringExtractor> =
Extractors::new();
let route = RouteImpl::new(matcher, dispatcher, extractors, Delegation::Internal);
Box::new(route)
};
tree.add_route(route);
let router = Router::new(tree, ResponseFinalizerBuilder::new().finalize());
match send_request(router, Method::GET, "https://test.gotham.rs") {
Ok((_state, res)) => {
assert_eq!(res.status(), StatusCode::OK);
}
Err(_) => unreachable!("Router should have handled request"),
};
}
#[test]
fn delegates_to_secondary_router() {
let delegated_router = {
let pipeline_set = finalize_pipeline_set(new_pipeline_set());
let mut tree = Tree::new();
let route = {
let methods = vec![Method::GET];
let matcher = MethodOnlyRouteMatcher::new(methods);
let dispatcher = Box::new(DispatcherImpl::new(|| Ok(handler), (), pipeline_set));
let extractors: Extractors<NoopPathExtractor, NoopQueryStringExtractor> =
Extractors::new();
let route = RouteImpl::new(matcher, dispatcher, extractors, Delegation::Internal);
Box::new(route)
};
tree.add_route(route);
Router::new(tree, ResponseFinalizerBuilder::new().finalize())
};
let pipeline_set = finalize_pipeline_set(new_pipeline_set());
let mut tree = Tree::new();
let mut delegated_node = Node::new("var", SegmentType::Dynamic);
let route = {
let methods = vec![Method::GET];
let matcher = MethodOnlyRouteMatcher::new(methods);
let dispatcher = Box::new(DispatcherImpl::new(delegated_router, (), pipeline_set));
let extractors: Extractors<NoopPathExtractor, NoopQueryStringExtractor> =
Extractors::new();
let route = RouteImpl::new(matcher, dispatcher, extractors, Delegation::External);
Box::new(route)
};
delegated_node.add_route(route);
tree.add_child(delegated_node);
let router = Router::new(tree, ResponseFinalizerBuilder::new().finalize());
match send_request(router.clone(), Method::GET, "https://test.gotham.rs") {
Ok((_state, res)) => {
assert_eq!(res.status(), StatusCode::NOT_FOUND);
}
Err(_) => unreachable!("Router should have handled request"),
};
match send_request(router, Method::GET, "https://test.gotham.rs/api") {
Ok((_state, res)) => {
assert_eq!(res.status(), StatusCode::OK);
}
Err(_) => unreachable!("Router should have handled request"),
};
}
#[test]
fn executes_response_finalizer_when_present() {
let tree = Tree::new();
let mut response_finalizer_builder = ResponseFinalizerBuilder::new();
let not_found_extender = |_s: &mut State, r: &mut Response<Body>| {
r.headers_mut()
.insert(CONTENT_LENGTH, "3".to_owned().parse().unwrap());
};
response_finalizer_builder.add(StatusCode::NOT_FOUND, Box::new(not_found_extender));
let response_finalizer = response_finalizer_builder.finalize();
let router = Router::new(tree, response_finalizer);
match send_request(router, Method::GET, "https://test.gotham.rs/api") {
Ok((_state, res)) => {
assert_eq!(res.headers().get(CONTENT_LENGTH).unwrap(), "3");
}
Err(_) => unreachable!("Router should have correctly handled request"),
};
}
}