Skip to main content

libkeri/keri/core/routing/
route.rs

1use regex::Regex;
2use std::collections::HashSet;
3
4/// Route class for registration of reply message handlers
5///
6/// This class represents a registered route internally to the Router.
7/// The properties are created by using the compile route utility method
8pub struct Route {
9    /// Compiled URI template regex
10    pub regex: Regex,
11
12    /// Field names for matches in regex
13    pub fields: HashSet<String>,
14
15    /// The handler for this route (stored as type-erased trait object)
16    pub resource: Box<dyn RouteResource>,
17
18    /// A suffix to be applied to the handler method
19    pub suffix: Option<String>,
20}
21
22impl Route {
23    /// Initialize instance of route
24    pub fn new(
25        regex: Regex,
26        fields: HashSet<String>,
27        resource: Box<dyn RouteResource>,
28        suffix: Option<String>,
29    ) -> Self {
30        Self {
31            regex,
32            fields,
33            resource,
34            suffix,
35        }
36    }
37}
38
39/// Trait that route resources must implement
40pub trait RouteResource: Send + Sync {
41    /// Default reply processing method
42    fn process_reply(
43        &self,
44        serder: &crate::keri::core::serdering::SerderKERI,
45        saider: &crate::cesr::saider::Saider,
46        route: &str,
47        cigars: Option<&[crate::cesr::indexing::siger::Siger]>,
48        tsgs: Option<
49            &[(
50                crate::cesr::prefixer::Prefixer,
51                crate::cesr::seqner::Seqner,
52                crate::cesr::saider::Saider,
53                Vec<crate::cesr::indexing::siger::Siger>,
54            )],
55        >,
56        params: std::collections::HashMap<String, String>,
57    ) -> Result<(), crate::keri::KERIError>;
58
59    /// Method called when a route is not found - can be overridden
60    fn process_route_not_found(
61        &self,
62        serder: &crate::keri::core::serdering::SerderKERI,
63        saider: &crate::cesr::saider::Saider,
64        route: &str,
65        cigars: Option<&[crate::cesr::indexing::siger::Siger]>,
66        tsgs: Option<
67            &[(
68                crate::cesr::prefixer::Prefixer,
69                crate::cesr::seqner::Seqner,
70                crate::cesr::saider::Saider,
71                Vec<crate::cesr::indexing::siger::Siger>,
72            )],
73        >,
74        params: std::collections::HashMap<String, String>,
75    ) -> Result<(), crate::keri::KERIError> {
76        Err(crate::keri::KERIError::ValueError(format!(
77            "Resource registered for route {} does not contain the correct processReply method",
78            route
79        )))
80    }
81}
82
83/// Compile the given URI template string into a pattern matcher
84///
85/// This function can be used to construct custom routing engines that
86/// iterate through a list of possible routes, attempting to match
87/// an incoming request against each route's compiled regular expression.
88///
89/// Each field is converted to a named group, so that when a match
90/// is found, the fields can be easily extracted using the capture groups.
91///
92/// This function does not support the more flexible templating
93/// syntax used in the default router. Only simple paths with bracketed
94/// field expressions are recognized. For example:
95///
96///
97/// /
98/// /books
99/// /books/{isbn}
100/// /books/{isbn}/characters
101/// /books/{isbn}/characters/{name}
102///
103///
104/// Also, note that if the template contains a trailing slash character,
105/// it will be stripped in order to normalize the routing logic.
106///
107/// # Arguments
108/// * `template` - The template to compile. Note that field names are
109///               restricted to ASCII a-z, A-Z, and the underscore character.
110///
111/// # Returns
112/// * `(template_field_names, template_regex)`
113pub fn compile_uri_template(
114    template: &str,
115) -> Result<(HashSet<String>, Regex), crate::keri::KERIError> {
116    if !template.starts_with('/') {
117        return Err(crate::keri::KERIError::ValueError(
118            "uri_template must start with '/'".to_string(),
119        ));
120    }
121
122    if template.contains("//") {
123        return Err(crate::keri::KERIError::ValueError(
124            "uri_template may not contain '//'".to_string(),
125        ));
126    }
127
128    let mut normalized_template = template.to_string();
129    if normalized_template != "/" && normalized_template.ends_with('/') {
130        normalized_template.pop();
131    }
132
133    // Template names should be able to start with A-Za-z
134    // but also contain 0-9_ in the remaining portion
135    let expression_pattern = regex::Regex::new(r"\{([a-zA-Z]\w*)\}")
136        .map_err(|e| crate::keri::KERIError::ValueError(format!("Invalid regex pattern: {}", e)))?;
137
138    // Get a list of field names
139    let mut fields = HashSet::new();
140    for caps in expression_pattern.captures_iter(&normalized_template) {
141        if let Some(field_name) = caps.get(1) {
142            fields.insert(field_name.as_str().to_string());
143        }
144    }
145
146    // Escape special regex characters except for our template patterns
147    let mut escaped = String::new();
148    for ch in normalized_template.chars() {
149        match ch {
150            '.' | '(' | ')' | '[' | ']' | '?' | '*' | '+' | '^' | '|' => {
151                escaped.push('\\');
152                escaped.push(ch);
153            }
154            _ => escaped.push(ch),
155        }
156    }
157
158    // Convert Level 1 var patterns to equivalent named regex groups
159    let pattern = expression_pattern.replace_all(&escaped, r"(?P<$1>[^/]+)");
160    let final_pattern = format!(r"^{}$", pattern);
161
162    let regex = Regex::new(&final_pattern).map_err(|e| {
163        crate::keri::KERIError::ValueError(format!("Invalid compiled regex: {}", e))
164    })?;
165
166    Ok((fields, regex))
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172
173    #[test]
174    fn test_compile_uri_template_simple() {
175        let (fields, regex) = compile_uri_template("/books").unwrap();
176        assert!(fields.is_empty());
177        assert!(regex.is_match("/books"));
178        assert!(!regex.is_match("/books/123"));
179    }
180
181    #[test]
182    fn test_compile_uri_template_with_param() {
183        let (fields, regex) = compile_uri_template("/books/{isbn}").unwrap();
184        assert_eq!(fields.len(), 1);
185        assert!(fields.contains("isbn"));
186        assert!(regex.is_match("/books/123"));
187        assert!(!regex.is_match("/books/123/characters"));
188    }
189
190    #[test]
191    fn test_compile_uri_template_multiple_params() {
192        let (fields, regex) = compile_uri_template("/books/{isbn}/characters/{name}").unwrap();
193        assert_eq!(fields.len(), 2);
194        assert!(fields.contains("isbn"));
195        assert!(fields.contains("name"));
196        assert!(regex.is_match("/books/123/characters/alice"));
197    }
198
199    #[test]
200    fn test_compile_uri_template_invalid() {
201        assert!(compile_uri_template("books").is_err()); // doesn't start with /
202        assert!(compile_uri_template("/books//test").is_err()); // contains //
203    }
204
205    #[test]
206    fn test_compile_uri_template_trailing_slash() {
207        let (fields, regex) = compile_uri_template("/books/").unwrap();
208        assert!(fields.is_empty());
209        assert!(regex.is_match("/books"));
210        assert!(!regex.is_match("/books/"));
211    }
212}