libkeri/keri/core/routing/
route.rs1use regex::Regex;
2use std::collections::HashSet;
3
4pub struct Route {
9 pub regex: Regex,
11
12 pub fields: HashSet<String>,
14
15 pub resource: Box<dyn RouteResource>,
17
18 pub suffix: Option<String>,
20}
21
22impl Route {
23 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
39pub trait RouteResource: Send + Sync {
41 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 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
83pub 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 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 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 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 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()); assert!(compile_uri_template("/books//test").is_err()); }
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}