rama_http/matcher/path/
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
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
use crate::{IntoResponse, Request, StatusCode};
use rama_core::{context::Extensions, Context};
use std::collections::HashMap;

mod de;

#[derive(Debug, Clone, Default)]
/// parameters that are inserted in the [`Context`],
/// in case the [`PathMatcher`] found a match for the given [`Request`].
pub struct UriParams {
    params: Option<HashMap<String, String>>,
    glob: Option<String>,
}

impl UriParams {
    fn insert(&mut self, name: String, value: String) {
        self.params
            .get_or_insert_with(HashMap::new)
            .insert(name, value);
    }

    /// Some str slice will be returned in case a param could be found for the given name.
    pub fn get(&self, name: impl AsRef<str>) -> Option<&str> {
        self.params
            .as_ref()
            .and_then(|params| params.get(name.as_ref()))
            .map(String::as_str)
    }

    fn append_glob(&mut self, value: &str) {
        match self.glob {
            Some(ref mut glob) => {
                glob.push('/');
                glob.push_str(value);
            }
            None => self.glob = Some(format!("/{}", value)),
        }
    }

    /// Some str slice will be returned in case a glob value was captured
    /// for the last part of the Path that was matched on.
    pub fn glob(&self) -> Option<&str> {
        self.glob.as_deref()
    }

    /// Deserialize the [`UriParams`] into a given type.
    pub fn deserialize<T>(&self) -> Result<T, UriParamsDeserializeError>
    where
        T: serde::de::DeserializeOwned,
    {
        match self.params {
            Some(ref params) => {
                let params: Vec<_> = params
                    .iter()
                    .map(|(k, v)| (k.as_str(), v.as_str()))
                    .collect();
                let deserializer = de::PathDeserializer::new(&params);
                T::deserialize(deserializer)
            }
            None => Err(de::PathDeserializationError::new(de::ErrorKind::NoParams)),
        }
        .map_err(UriParamsDeserializeError)
    }
}

#[derive(Debug)]
/// Error that can occur during the deserialization of the [`UriParams`].
///
/// See [`UriParams::deserialize`] for more information.
pub struct UriParamsDeserializeError(de::PathDeserializationError);

impl UriParamsDeserializeError {
    /// Get the response body text used for this rejection.
    pub fn body_text(&self) -> String {
        use de::ErrorKind;
        match self.0.kind {
            ErrorKind::Message(_)
            | ErrorKind::NoParams
            | ErrorKind::ParseError { .. }
            | ErrorKind::ParseErrorAtIndex { .. }
            | ErrorKind::ParseErrorAtKey { .. } => format!("Invalid URL: {}", self.0.kind),
            ErrorKind::WrongNumberOfParameters { .. } | ErrorKind::UnsupportedType { .. } => {
                self.0.kind.to_string()
            }
        }
    }

    /// Get the status code used for this rejection.
    pub fn status(&self) -> StatusCode {
        use de::ErrorKind;
        match self.0.kind {
            ErrorKind::Message(_)
            | ErrorKind::NoParams
            | ErrorKind::ParseError { .. }
            | ErrorKind::ParseErrorAtIndex { .. }
            | ErrorKind::ParseErrorAtKey { .. } => StatusCode::BAD_REQUEST,
            ErrorKind::WrongNumberOfParameters { .. } | ErrorKind::UnsupportedType { .. } => {
                StatusCode::INTERNAL_SERVER_ERROR
            }
        }
    }
}

impl std::fmt::Display for UriParamsDeserializeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl std::error::Error for UriParamsDeserializeError {}

impl IntoResponse for UriParamsDeserializeError {
    fn into_response(self) -> crate::Response {
        crate::utils::macros::log_http_rejection!(
            rejection_type = UriParamsDeserializeError,
            body_text = self.body_text(),
            status = self.status(),
        );
        (self.status(), self.body_text()).into_response()
    }
}

#[derive(Debug, Clone)]
enum PathFragment {
    Literal(String),
    Param(String),
    Glob,
}

#[derive(Debug, Clone)]
enum PathMatcherKind {
    Literal(String),
    FragmentList(Vec<PathFragment>),
}

#[derive(Debug, Clone)]
/// Matcher based on the URI path.
pub struct PathMatcher {
    kind: PathMatcherKind,
}

impl PathMatcher {
    /// Create a new [`PathMatcher`] for the given path.
    pub fn new(path: impl AsRef<str>) -> Self {
        let path = path.as_ref();
        let path = path.trim().trim_matches('/');

        if !path.contains([':', '*']) {
            return Self {
                kind: PathMatcherKind::Literal(path.to_lowercase()),
            };
        }

        let path_parts: Vec<_> = path.split('/').filter(|s| !s.is_empty()).collect();
        let fragment_length = path_parts.len();
        if fragment_length == 1 && path_parts[0].is_empty() {
            return Self {
                kind: PathMatcherKind::FragmentList(vec![PathFragment::Glob]),
            };
        }

        let fragments: Vec<PathFragment> = path_parts
            .into_iter()
            .enumerate()
            .filter_map(|(index, s)| {
                if s.is_empty() {
                    return None;
                }
                if s.starts_with(':') {
                    Some(PathFragment::Param(
                        s.trim_start_matches(':').to_lowercase(),
                    ))
                } else if s == "*" && index == fragment_length - 1 {
                    Some(PathFragment::Glob)
                } else {
                    Some(PathFragment::Literal(s.to_lowercase()))
                }
            })
            .collect();

        Self {
            kind: PathMatcherKind::FragmentList(fragments),
        }
    }

    pub(crate) fn matches_path(&self, path: &str) -> Option<UriParams> {
        let path = path.trim().trim_matches('/');
        match &self.kind {
            PathMatcherKind::Literal(literal) => {
                if literal.eq_ignore_ascii_case(path) {
                    Some(UriParams::default())
                } else {
                    None
                }
            }
            PathMatcherKind::FragmentList(fragments) => {
                let fragments_iter = fragments.iter().map(Some).chain(std::iter::repeat(None));
                let mut params = UriParams::default();
                for (segment, fragment) in path
                    .split('/')
                    .map(Some)
                    .chain(std::iter::repeat(None))
                    .zip(fragments_iter)
                {
                    match (segment, fragment) {
                        (Some(segment), Some(fragment)) => match fragment {
                            PathFragment::Literal(literal) => {
                                if !literal.eq_ignore_ascii_case(segment) {
                                    return None;
                                }
                            }
                            PathFragment::Param(name) => {
                                if segment.is_empty() {
                                    return None;
                                }
                                let segment = percent_encoding::percent_decode(segment.as_bytes())
                                    .decode_utf8()
                                    .map(|s| s.to_string())
                                    .unwrap_or_else(|_| segment.to_owned());
                                params.insert(name.to_owned(), segment);
                            }
                            PathFragment::Glob => {
                                params.append_glob(segment);
                            }
                        },
                        (None, None) => {
                            break;
                        }
                        (Some(segment), None) => {
                            params.glob()?;
                            params.append_glob(segment);
                        }
                        _ => {
                            return None;
                        }
                    }
                }

                Some(params)
            }
        }
    }
}

impl<State, Body> rama_core::matcher::Matcher<State, Request<Body>> for PathMatcher {
    fn matches(
        &self,
        ext: Option<&mut Extensions>,
        _ctx: &Context<State>,
        req: &Request<Body>,
    ) -> bool {
        match self.matches_path(req.uri().path()) {
            None => false,
            Some(params) => {
                if let Some(ext) = ext {
                    ext.insert(params);
                }
                true
            }
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_path_matcher_match_path() {
        struct TestCase {
            path: &'static str,
            matcher_path: &'static str,
            result: Option<UriParams>,
        }

        impl TestCase {
            fn some(path: &'static str, matcher_path: &'static str, result: UriParams) -> Self {
                Self {
                    path,
                    matcher_path,
                    result: Some(result),
                }
            }

            fn none(path: &'static str, matcher_path: &'static str) -> Self {
                Self {
                    path,
                    matcher_path,
                    result: None,
                }
            }
        }

        let test_cases = vec![
            TestCase::some("/", "/", UriParams::default()),
            TestCase::some("", "/", UriParams::default()),
            TestCase::some("/", "", UriParams::default()),
            TestCase::some("", "", UriParams::default()),
            TestCase::some("/foo", "/foo", UriParams::default()),
            TestCase::some("/foo", "//foo//", UriParams::default()),
            TestCase::some("/*foo", "/*foo", UriParams::default()),
            TestCase::some("/foo/*bar/baz", "/foo/*bar/baz", UriParams::default()),
            TestCase::none("/foo/*bar/baz", "/foo/*bar"),
            TestCase::none("/", "/:foo"),
            TestCase::some(
                "/",
                "/*",
                UriParams {
                    glob: Some("/".to_owned()),
                    ..UriParams::default()
                },
            ),
            TestCase::none("/", "//:foo"),
            TestCase::none("", "/:foo"),
            TestCase::none("/foo", "/bar"),
            TestCase::some(
                "/person/glen%20dc/age",
                "/person/:name/age",
                UriParams {
                    params: Some({
                        let mut params = HashMap::new();
                        params.insert("name".to_owned(), "glen dc".to_owned());
                        params
                    }),
                    ..UriParams::default()
                },
            ),
            TestCase::none("/foo", "/bar"),
            TestCase::some("/foo", "foo", UriParams::default()),
            TestCase::some("/foo/bar/", "foo/bar", UriParams::default()),
            TestCase::none("/foo/bar/", "foo/baz"),
            TestCase::some("/foo/bar/", "/foo/bar", UriParams::default()),
            TestCase::some("/foo/bar", "/foo/bar", UriParams::default()),
            TestCase::some("/foo/bar", "foo/bar", UriParams::default()),
            TestCase::some("/book/oxford-dictionary/author", "/book/:title/author", {
                let mut params = UriParams::default();
                params.insert("title".to_owned(), "oxford-dictionary".to_owned());
                params
            }),
            TestCase::some(
                "/book/oxford-dictionary/author/0",
                "/book/:title/author/:index",
                {
                    let mut params = UriParams::default();
                    params.insert("title".to_owned(), "oxford-dictionary".to_owned());
                    params.insert("index".to_owned(), "0".to_owned());
                    params
                },
            ),
            TestCase::none("/book/oxford-dictionary", "/book/:title/author"),
            TestCase::none(
                "/book/oxford-dictionary/author/birthdate",
                "/book/:title/author",
            ),
            TestCase::none("oxford-dictionary/author", "/book/:title/author"),
            TestCase::none("/foo", "/"),
            TestCase::none("/foo", "/*f"),
            TestCase::some(
                "/foo",
                "/*",
                UriParams {
                    glob: Some("/foo".to_owned()),
                    ..UriParams::default()
                },
            ),
            TestCase::some(
                "/assets/css/reset.css",
                "/assets/*",
                UriParams {
                    glob: Some("/css/reset.css".to_owned()),
                    ..UriParams::default()
                },
            ),
            TestCase::some("/assets/eu/css/reset.css", "/assets/:local/*", {
                let mut params = UriParams::default();
                params.insert("local".to_owned(), "eu".to_owned());
                params.glob = Some("/css/reset.css".to_owned());
                params
            }),
            TestCase::some("/assets/eu/css/reset.css", "/assets/:local/css/*", {
                let mut params = UriParams::default();
                params.insert("local".to_owned(), "eu".to_owned());
                params.glob = Some("/reset.css".to_owned());
                params
            }),
        ];
        for test_case in test_cases.into_iter() {
            let matcher = PathMatcher::new(test_case.matcher_path);
            let result = matcher.matches_path(test_case.path);
            match (result.as_ref(), test_case.result.as_ref()) {
                (None, None) => (),
                (Some(result), Some(expected_result)) => {
                    assert_eq!(
                        result.params,
                        expected_result.params,
                        "unexpected result params: ({}).matcher({}) => {:?} != {:?}",
                        test_case.matcher_path,
                        test_case.path,
                        result.params,
                        expected_result.params,
                    );
                    assert_eq!(
                        result.glob, expected_result.glob,
                        "unexpected result glob: ({}).matcher({}) => {:?} != {:?}",
                        test_case.matcher_path, test_case.path, result.glob, expected_result.glob,
                    );
                }
                _ => {
                    panic!(
                        "unexpected result: ({}).matcher({}) => {:?} != {:?}",
                        test_case.matcher_path, test_case.path, result, test_case.result
                    )
                }
            }
        }
    }

    #[test]
    fn test_deserialize_uri_params() {
        let params = UriParams {
            params: Some({
                let mut params = HashMap::new();
                params.insert("name".to_owned(), "glen dc".to_owned());
                params.insert("age".to_owned(), "42".to_owned());
                params
            }),
            glob: Some("/age".to_owned()),
        };

        #[derive(serde::Deserialize)]
        struct Person {
            name: String,
            age: u8,
        }

        let person: Person = params.deserialize().unwrap();
        assert_eq!(person.name, "glen dc");
        assert_eq!(person.age, 42);
    }
}