-
Notifications
You must be signed in to change notification settings - Fork 1
/
route.rs
219 lines (192 loc) · 5.79 KB
/
route.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
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
use std::any::Any;
use std::borrow::Cow;
use std::convert::Infallible;
use std::fmt::{self, Display};
use std::future::Future;
use std::panic::AssertUnwindSafe;
use std::sync::Arc;
use anyhow::Result;
use futures::future::{self, FutureExt, TryFutureExt};
use hyper::service::{service_fn, Service};
use hyper::Body;
use once_cell::sync::Lazy;
use regex::{Regex, RegexSet};
use serde::de::{self, Deserialize, Deserializer};
use crate::config::Config;
use crate::handler::Handler;
use crate::response;
#[derive(Debug)]
pub struct Router {
regex_set: RegexSet,
handlers: Vec<Handler>,
}
#[derive(Debug)]
pub struct Route {
precedence: Precedence,
path: String,
regex: String,
}
#[derive(Copy, Clone, Debug, Default, PartialOrd, Ord, Eq, PartialEq)]
struct Precedence {
multi_wildcards: u32,
wildcards: u32,
}
impl Router {
pub async fn new(mut config: Config) -> Result<Self> {
config.routes.sort_by_key(|route| route.route.precedence);
let regex_set = RegexSet::new(config.routes.iter().map(|route| &route.route.regex))
.expect("error in generated regex");
let handlers = future::try_join_all(config.routes.into_iter().map(Handler::new)).await?;
Ok(Router {
regex_set,
handlers,
})
}
}
impl Router {
pub async fn try_handle(
self: Arc<Self>,
mut request: http::Request<Body>,
) -> http::Response<Body> {
let mut response = response::from_status(http::StatusCode::NOT_FOUND);
let matches = self.regex_set.matches(request.uri().path());
if matches.matched_any() {
for match_index in matches {
match self.handlers[match_index].handle(request).await {
Ok(response) => return response,
Err(parts) => {
request = parts.0;
response = parts.1;
}
}
}
} else {
log::info!("Path `{}` did not match any route", request.uri().path());
}
response
}
pub fn handle(
self: Arc<Self>,
request: http::Request<Body>,
) -> impl Future<Output = http::Response<Body>> {
AssertUnwindSafe(self.try_handle(request))
.catch_unwind()
.unwrap_or_else(|payload| {
log::error!(
"Panic while handling request: {}",
fmt_panic_payload(payload)
);
response::from_status(http::StatusCode::INTERNAL_SERVER_ERROR)
})
}
pub fn into_service(
self,
) -> impl Service<
http::Request<Body>,
Response = http::Response<Body>,
Error = Infallible,
Future = impl Future<Output = Result<http::Response<Body>, Infallible>> + Send + 'static,
> + Clone {
let this = Arc::new(self);
service_fn(move |request: http::Request<Body>| this.clone().handle(request).never_error())
}
}
impl Route {
pub fn new(path: String) -> Result<Self, impl Display> {
macro_rules! chars {
() => {
r"[\w\-\.~%!$&'()*+,;=:@]*"
};
}
const PATH_SEGMENT_PATTERN: &str = concat!(r"(/", chars!(), ")");
const MULTI_PATH_SEGMENT_PATTERN: &str = concat!("((?:/", chars!(), ")*)");
static PATH_CHARS_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(chars!()).unwrap());
let mut regex = String::with_capacity(path.len() + 5);
let mut precedence = Precedence::default();
regex.push('^');
for segment in path.split('/') {
if segment.is_empty() {
continue;
}
if !PATH_CHARS_REGEX.is_match(segment) {
return Err("invalid character in path");
}
match segment {
"*" => {
precedence.wildcards += 1;
regex.push_str(PATH_SEGMENT_PATTERN);
}
"**" => {
precedence.multi_wildcards += 1;
regex.push_str(MULTI_PATH_SEGMENT_PATTERN);
}
_ => {
regex.push('/');
regex_syntax::escape_into(segment, &mut regex);
}
}
}
regex.push_str(r"/?$");
Ok(Route {
precedence,
regex,
path,
})
}
pub fn to_regex(&self) -> Regex {
Regex::new(&self.regex).expect("error in generated regex")
}
}
impl Display for Route {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.path.fmt(f)
}
}
impl<'de> Deserialize<'de> for Route {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let path = String::deserialize(deserializer)?;
Route::new(path).map_err(de::Error::custom)
}
}
fn fmt_panic_payload(payload: Box<dyn Any + Send + 'static>) -> impl Display {
if let Some(string) = payload.downcast_ref::<&'static str>() {
Cow::Borrowed(*string)
} else if let Ok(string) = payload.downcast::<String>() {
Cow::Owned(*string)
} else {
Cow::Borrowed("Box<Any>")
}
}
#[test]
fn test_precedence() {
assert!(
Precedence {
multi_wildcards: 0,
wildcards: 0,
} < Precedence {
multi_wildcards: 0,
wildcards: 1,
}
);
assert!(
Precedence {
multi_wildcards: 0,
wildcards: 1,
} < Precedence {
multi_wildcards: 1,
wildcards: 0,
}
);
assert!(
Precedence {
multi_wildcards: 1,
wildcards: 0,
} < Precedence {
multi_wildcards: 1,
wildcards: 1,
}
);
}