Skip to main content

ntex/web/
rmap.rs

1use std::{cell::RefCell, rc::Rc};
2
3use urly::{Url, quoting::Component, quoting::quote};
4
5use crate::router::{BuildPathError, ResourceDef};
6use crate::util::HashMap;
7use crate::web::{error::UrlGenerationError, httprequest::HttpRequest};
8
9/// Map of registered resources, used for URL generation.
10///
11/// The map is built from the application's resource definitions and is used
12/// by [`HttpRequest::url_for()`](crate::web::HttpRequest::url_for) to resolve
13/// named and external resources.
14#[derive(Clone, Debug)]
15pub struct ResourceMap {
16    #[allow(dead_code)]
17    root: ResourceDef,
18    parent: RefCell<Option<Rc<ResourceMap>>>,
19    named: HashMap<String, ResourceDef>,
20    patterns: Vec<(ResourceDef, Option<Rc<ResourceMap>>)>,
21}
22
23impl ResourceMap {
24    /// Create an empty resource map for the `root` resource.
25    pub fn new(root: ResourceDef) -> Self {
26        ResourceMap {
27            root,
28            parent: RefCell::new(None),
29            named: HashMap::default(),
30            patterns: Vec::new(),
31        }
32    }
33
34    /// Add a resource pattern, optionally with the resource map of a nested
35    /// scope.
36    ///
37    /// Assigns the pattern its id within this map. Named patterns can be used
38    /// for URL generation.
39    ///
40    /// # Panics
41    ///
42    /// Panics if a pattern with the same name is already added to this map.
43    pub fn add(&mut self, pattern: &mut ResourceDef, nested: Option<Rc<ResourceMap>>) {
44        pattern.set_id(self.patterns.len() as u16);
45        if !pattern.name().is_empty() {
46            let prev = self
47                .named
48                .insert(pattern.name().to_string(), pattern.clone());
49            assert!(
50                prev.is_none(),
51                "Resource name {:?} is already used",
52                pattern.name()
53            );
54        }
55        self.patterns.push((pattern.clone(), nested));
56    }
57
58    pub(crate) fn build(&self, current: &Rc<ResourceMap>) {
59        for (_, nested) in &self.patterns {
60            if let Some(nested) = nested {
61                *nested.parent.borrow_mut() = Some(current.clone());
62                nested.build(nested);
63            }
64        }
65    }
66}
67
68impl ResourceMap {
69    /// Generate url for named resource
70    ///
71    /// Check [`HttpRequest::url_for()`](crate::web::HttpRequest::url_for) for detailed information.
72    pub fn url_for<U, I>(
73        &self,
74        req: &HttpRequest,
75        name: &str,
76        elements: U,
77    ) -> Result<Url, UrlGenerationError>
78    where
79        U: IntoIterator<Item = I>,
80        I: AsRef<str>,
81    {
82        let mut path = String::new();
83        let mut elements = elements.into_iter();
84
85        if self.patterns_for(name, &mut path, &mut elements)?.is_some() {
86            if elements.next().is_some() {
87                return Err(UrlGenerationError::TooManyElements);
88            }
89            if path.starts_with('/') {
90                let conn = req.connection_info();
91                let (scheme, host) = (conn.scheme(), conn.host());
92                let mut url = String::with_capacity(scheme.len() + host.len() + path.len() + 3);
93                url.push_str(scheme);
94                url.push_str("://");
95                url.push_str(host);
96                url.push_str(&path);
97                path = url;
98            }
99            Ok(Url::try_from(path)?)
100        } else {
101            Err(UrlGenerationError::ResourceNotFound)
102        }
103    }
104
105    // pub fn has_resource(&self, path: &str) -> bool {
106    // let _path = if path.is_empty() { "/" } else { path };
107
108    // for (pattern, rmap) in &self.patterns {
109    //     if let Some(ref rmap) = rmap {
110    //         if let Some(plen) = pattern.is_prefix_match(path) {
111    //             return rmap.has_resource(&path[plen..]);
112    //         }
113    //     } else if pattern.is_match(path) {
114    //         return true;
115    //     }
116    // }
117    // false
118    // }
119
120    fn patterns_for<U, I>(
121        &self,
122        name: &str,
123        path: &mut String,
124        elements: &mut U,
125    ) -> Result<Option<()>, UrlGenerationError>
126    where
127        U: Iterator<Item = I>,
128        I: AsRef<str>,
129    {
130        if self.pattern_for(name, path, elements)?.is_some() {
131            Ok(Some(()))
132        } else {
133            self.parent_pattern_for(name, path, elements)
134        }
135    }
136
137    fn pattern_for<U, I>(
138        &self,
139        name: &str,
140        path: &mut String,
141        elements: &mut U,
142    ) -> Result<Option<()>, UrlGenerationError>
143    where
144        U: Iterator<Item = I>,
145        I: AsRef<str>,
146    {
147        if let Some(pattern) = self.named.get(name) {
148            if pattern.pattern().starts_with('/') {
149                self.fill_root(path, elements)?;
150            }
151            build_path(pattern, path, elements)?;
152            Ok(Some(()))
153        } else {
154            for (_, rmap) in &self.patterns {
155                if let Some(rmap) = rmap
156                    && rmap.pattern_for(name, path, elements)?.is_some()
157                {
158                    return Ok(Some(()));
159                }
160            }
161            Ok(None)
162        }
163    }
164
165    fn fill_root<U, I>(&self, path: &mut String, elements: &mut U) -> Result<(), UrlGenerationError>
166    where
167        U: Iterator<Item = I>,
168        I: AsRef<str>,
169    {
170        if let Some(ref parent) = *self.parent.borrow() {
171            parent.fill_root(path, elements)?;
172        }
173        build_path(&self.root, path, elements)
174    }
175
176    fn parent_pattern_for<U, I>(
177        &self,
178        name: &str,
179        path: &mut String,
180        elements: &mut U,
181    ) -> Result<Option<()>, UrlGenerationError>
182    where
183        U: Iterator<Item = I>,
184        I: AsRef<str>,
185    {
186        if let Some(ref parent) = *self.parent.borrow() {
187            parent.patterns_for(name, path, elements)
188        } else {
189            Ok(None)
190        }
191    }
192}
193
194/// Build the path of `pattern`, each element must match its segment pattern
195/// and is percent-encoded as one literal URL component.
196fn build_path<U, I>(
197    pattern: &ResourceDef,
198    path: &mut String,
199    elements: &mut U,
200) -> Result<(), UrlGenerationError>
201where
202    U: Iterator<Item = I>,
203    I: AsRef<str>,
204{
205    pattern
206        .try_build_path(path, elements, |path, el| {
207            path.push_str(&quote(el, Component::Opaque));
208        })
209        .map_err(|err| match err {
210            BuildPathError::InvalidElement => UrlGenerationError::InvalidElement,
211            _ => UrlGenerationError::NotEnoughElements,
212        })
213}
214
215#[cfg(test)]
216mod tests {
217    use super::*;
218    use crate::web::test::TestRequest;
219
220    /// STATEMENT: Nested resource maps resolve parent and sibling names without adding spurious prefixes.
221    ///
222    /// HOW:
223    /// - Build root, nested, sibling, and external named resources and link the maps.
224    /// - Resolve each name from root and nested maps and assert the correct absolute URL.
225    /// - Check reserved characters are escaped and missing elements or names return errors.
226    #[test]
227    fn url_for_parent() {
228        // regression: names of the parent map were prefixed with the nested root
229        let mut root = ResourceMap::new(ResourceDef::new(""));
230        let mut index = ResourceDef::new("/index/{id}");
231        index.set_name("index");
232        root.add(&mut index, None);
233        let mut ext = ResourceDef::new("https://youtube.com/watch/{id}");
234        ext.set_name("youtube");
235        root.add(&mut ext, None);
236
237        let mut nested = ResourceMap::new(ResourceDef::root_prefix("/a"));
238        let mut res = ResourceDef::new("/{id}");
239        res.set_name("nested");
240        nested.add(&mut res, None);
241        let nested = Rc::new(nested);
242        root.add(&mut ResourceDef::root_prefix("/a"), Some(nested.clone()));
243
244        let mut sibling = ResourceMap::new(ResourceDef::root_prefix("/b"));
245        let mut res = ResourceDef::new("/{id}");
246        res.set_name("sibling");
247        sibling.add(&mut res, None);
248        root.add(&mut ResourceDef::root_prefix("/b"), Some(Rc::new(sibling)));
249
250        let root = Rc::new(root);
251        root.build(&root);
252
253        let req = TestRequest::default().to_http_request();
254        for rmap in [&root, &nested] {
255            assert_eq!(
256                rmap.url_for(&req, "index", ["1"]).unwrap().as_str(),
257                "http://localhost:8080/index/1"
258            );
259            assert_eq!(
260                rmap.url_for(&req, "youtube", ["2"]).unwrap().as_str(),
261                "https://youtube.com/watch/2"
262            );
263            assert_eq!(
264                rmap.url_for(&req, "nested", ["3"]).unwrap().as_str(),
265                "http://localhost:8080/a/3"
266            );
267            assert_eq!(
268                rmap.url_for(&req, "sibling", ["4"]).unwrap().as_str(),
269                "http://localhost:8080/b/4"
270            );
271            assert_eq!(
272                rmap.url_for(&req, "index", ["a/b?c#d%"]).unwrap().as_str(),
273                "http://localhost:8080/index/a%2Fb%3Fc%23d%25"
274            );
275            assert_eq!(
276                rmap.url_for(&req, "youtube", ["a/b?c#d%"])
277                    .unwrap()
278                    .as_str(),
279                "https://youtube.com/watch/a%2Fb%3Fc%23d%25"
280            );
281            assert!(rmap.url_for(&req, "index", [""; 0]).is_err());
282            assert!(rmap.url_for(&req, "unknown", [""; 0]).is_err());
283        }
284    }
285
286    /// STATEMENT: `url_for` rejects elements that do not match their segment patterns and
287    /// extra elements, including those of enclosing scopes.
288    ///
289    /// HOW:
290    /// - Register `/item/{id:[0-9]+}` in a scope with root `/{tenant:[a-z]+}`.
291    /// - Expect a URL for valid elements, with an encoded `/` in an unrestricted segment.
292    /// - Expect `InvalidElement` for a non-numeric id, a non-letter tenant and an empty
293    ///   tenant, and `TooManyElements` or `NotEnoughElements` for wrong element counts.
294    #[test]
295    fn url_for_validates_elements() {
296        let mut root = ResourceMap::new(ResourceDef::new(""));
297        let mut nested = ResourceMap::new(ResourceDef::root_prefix("/{tenant:[a-z]+}"));
298        let mut item = ResourceDef::new("/item/{id:[0-9]+}");
299        item.set_name("item");
300        nested.add(&mut item, None);
301        let mut file = ResourceDef::new("/file/{name}");
302        file.set_name("file");
303        root.add(&mut file, None);
304        root.add(
305            &mut ResourceDef::root_prefix("/{tenant:[a-z]+}"),
306            Some(Rc::new(nested)),
307        );
308        let root = Rc::new(root);
309        root.build(&root);
310
311        let req = TestRequest::default().to_http_request();
312        assert_eq!(
313            root.url_for(&req, "item", ["abc", "12"]).unwrap().as_str(),
314            "http://localhost:8080/abc/item/12"
315        );
316        assert_eq!(
317            root.url_for(&req, "file", ["a/b"]).unwrap().as_str(),
318            "http://localhost:8080/file/a%2Fb"
319        );
320        for elements in [["abc", "x1"], ["ab1", "12"], ["", "12"]] {
321            assert_eq!(
322                root.url_for(&req, "item", elements),
323                Err(UrlGenerationError::InvalidElement)
324            );
325        }
326        assert_eq!(
327            root.url_for(&req, "file", [""]),
328            Err(UrlGenerationError::InvalidElement)
329        );
330        assert_eq!(
331            root.url_for(&req, "item", ["abc", "12", "extra"]),
332            Err(UrlGenerationError::TooManyElements)
333        );
334        assert_eq!(
335            root.url_for(&req, "item", ["abc"]),
336            Err(UrlGenerationError::NotEnoughElements)
337        );
338    }
339
340    /// STATEMENT: A resource name can be used only once within a resource map.
341    ///
342    /// HOW:
343    /// - Add two resources named `index` to one map and expect a panic naming it.
344    #[test]
345    #[should_panic(expected = "Resource name \"index\" is already used")]
346    fn duplicate_name_panics() {
347        let mut rmap = ResourceMap::new(ResourceDef::new(""));
348        let mut a = ResourceDef::new("/a");
349        a.set_name("index");
350        rmap.add(&mut a, None);
351        let mut b = ResourceDef::new("/b");
352        b.set_name("index");
353        rmap.add(&mut b, None);
354    }
355}