1use std::collections::BTreeSet;
6use std::fmt;
7
8pub const RESERVED_FIRST_SEGMENTS: [&str; 4] = ["_fn", "_meta", "_jobs", "graphql"];
11
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub enum Segment {
14 Literal(String),
15 Param(String),
16 CatchAll(String),
17}
18
19#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct RoutePattern {
22 segments: Vec<Segment>,
23}
24
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub enum RoutePathError {
27 NotAbsolute,
28 EmptySegment,
29 InvalidParamName(String),
30 DuplicateParam(String),
31 CatchAllNotLast,
32 ReservedPrefix(String),
33 InvalidLiteral(String),
34}
35
36impl fmt::Display for RoutePathError {
37 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38 match self {
39 Self::NotAbsolute => write!(f, "a route path must start with '/'"),
40 Self::EmptySegment => write!(f, "a route path may not contain an empty segment"),
41 Self::InvalidParamName(name) => {
42 write!(f, "path parameter '{name}' must match [a-z_][a-z0-9_]*")
43 }
44 Self::DuplicateParam(name) => {
45 write!(f, "path parameter '{name}' appears more than once")
46 }
47 Self::CatchAllNotLast => {
48 write!(f, "a catch-all parameter must be the last segment")
49 }
50 Self::ReservedPrefix(prefix) => write!(
51 f,
52 "the first segment '{prefix}' is reserved by the platform"
53 ),
54 Self::InvalidLiteral(literal) => write!(
55 f,
56 "path segment '{literal}' may contain only letters, digits and . _ ~ -"
57 ),
58 }
59 }
60}
61
62impl std::error::Error for RoutePathError {}
63
64impl RoutePattern {
65 pub fn parse(path: &str) -> Result<Self, RoutePathError> {
68 let rest = path.strip_prefix('/').ok_or(RoutePathError::NotAbsolute)?;
69 let raw: Vec<&str> = if rest.is_empty() {
70 Vec::new()
71 } else {
72 rest.split('/').collect()
73 };
74 let last = raw.len().saturating_sub(1);
75 let segments = raw
76 .iter()
77 .enumerate()
78 .map(|(index, raw)| parse_segment(raw, index == last))
79 .collect::<Result<Vec<_>, _>>()?;
80 let pattern = Self { segments };
81 pattern.check_unique_params()?;
82 match pattern.first_literal() {
83 Some(first) if RESERVED_FIRST_SEGMENTS.contains(&first) => {
84 Err(RoutePathError::ReservedPrefix(first.to_string()))
85 }
86 _ => Ok(pattern),
87 }
88 }
89
90 fn check_unique_params(&self) -> Result<(), RoutePathError> {
91 let mut seen = BTreeSet::new();
92 self.params()
93 .find(|name| !seen.insert(*name))
94 .map_or(Ok(()), |name| {
95 Err(RoutePathError::DuplicateParam(name.to_string()))
96 })
97 }
98
99 pub fn segments(&self) -> &[Segment] {
100 &self.segments
101 }
102
103 pub fn params(&self) -> impl Iterator<Item = &str> {
105 self.segments.iter().filter_map(|segment| match segment {
106 Segment::Param(name) | Segment::CatchAll(name) => Some(name.as_str()),
107 Segment::Literal(_) => None,
108 })
109 }
110
111 pub fn to_matchit(&self) -> String {
113 self.render(|name| format!("{{*{name}}}"))
114 }
115
116 pub fn to_openapi(&self) -> String {
118 self.render(|name| format!("{{{name}}}"))
119 }
120
121 fn render(&self, catch_all: impl Fn(&str) -> String) -> String {
122 if self.segments.is_empty() {
123 return "/".to_string();
124 }
125 self.segments
126 .iter()
127 .map(|segment| match segment {
128 Segment::Literal(literal) => format!("/{literal}"),
129 Segment::Param(name) => format!("/{{{name}}}"),
130 Segment::CatchAll(name) => format!("/{}", catch_all(name)),
131 })
132 .collect()
133 }
134
135 pub fn first_literal(&self) -> Option<&str> {
137 match self.segments.first() {
138 Some(Segment::Literal(literal)) => Some(literal),
139 _ => None,
140 }
141 }
142}
143
144fn parse_segment(raw: &str, last: bool) -> Result<Segment, RoutePathError> {
145 if raw.is_empty() {
146 return Err(RoutePathError::EmptySegment);
147 }
148 let param = raw
149 .strip_prefix('{')
150 .and_then(|inner| inner.strip_suffix('}'))
151 .or_else(|| raw.strip_prefix(':'));
152 match param {
153 Some(inner) => match inner.strip_prefix('*') {
154 Some(_) if !last => Err(RoutePathError::CatchAllNotLast),
155 Some(name) if raw.starts_with('{') => param_name(name).map(Segment::CatchAll),
156 Some(_) => Err(RoutePathError::InvalidParamName(inner.to_string())),
157 None => param_name(inner).map(Segment::Param),
158 },
159 None if is_literal(raw) => Ok(Segment::Literal(raw.to_string())),
160 None => Err(RoutePathError::InvalidLiteral(raw.to_string())),
161 }
162}
163
164fn param_name(name: &str) -> Result<String, RoutePathError> {
165 let mut bytes = name.bytes();
166 let valid = bytes
167 .next()
168 .is_some_and(|b| b.is_ascii_lowercase() || b == b'_')
169 && bytes.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_');
170 if valid {
171 Ok(name.to_string())
172 } else {
173 Err(RoutePathError::InvalidParamName(name.to_string()))
174 }
175}
176
177pub fn is_literal(segment: &str) -> bool {
179 !segment.is_empty() && segment.bytes().all(is_literal_byte)
180}
181
182fn is_literal_byte(b: u8) -> bool {
183 b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'~' | b'-')
184}
185
186#[cfg(test)]
187mod tests {
188 use super::*;
189
190 fn lit(s: &str) -> Segment {
191 Segment::Literal(s.into())
192 }
193
194 fn param(s: &str) -> Segment {
195 Segment::Param(s.into())
196 }
197
198 #[test]
199 fn parses_literals_params_and_a_trailing_catch_all() {
200 for (path, segments) in [
201 ("/", vec![]),
202 ("/books", vec![lit("books")]),
203 (
204 "/books/{book_id}/due-date",
205 vec![lit("books"), param("book_id"), lit("due-date")],
206 ),
207 (
208 "/books/:book_id/close",
209 vec![lit("books"), param("book_id"), lit("close")],
210 ),
211 (
212 "/files/{*rest}",
213 vec![lit("files"), Segment::CatchAll("rest".into())],
214 ),
215 ("/{_id}/v1.2~x", vec![param("_id"), lit("v1.2~x")]),
216 ] {
217 assert_eq!(
218 RoutePattern::parse(path).map(|p| p.segments),
219 Ok(segments),
220 "{path}"
221 );
222 }
223 }
224
225 #[test]
226 fn rejects_malformed_paths_with_the_reason() {
227 for (path, error) in [
228 ("books", RoutePathError::NotAbsolute),
229 ("", RoutePathError::NotAbsolute),
230 ("/books/", RoutePathError::EmptySegment),
231 ("//books", RoutePathError::EmptySegment),
232 (
233 "/books/{Book}",
234 RoutePathError::InvalidParamName("Book".into()),
235 ),
236 ("/books/{1d}", RoutePathError::InvalidParamName("1d".into())),
237 ("/books/{}", RoutePathError::InvalidParamName("".into())),
238 (
239 "/books/:*rest",
240 RoutePathError::InvalidParamName("*rest".into()),
241 ),
242 (
243 "/a/{id}/b/{id}",
244 RoutePathError::DuplicateParam("id".into()),
245 ),
246 ("/a/{id}/{*id}", RoutePathError::DuplicateParam("id".into())),
247 ("/files/{*rest}/x", RoutePathError::CatchAllNotLast),
248 ("/_fn/x", RoutePathError::ReservedPrefix("_fn".into())),
249 ("/_meta", RoutePathError::ReservedPrefix("_meta".into())),
250 ("/_jobs/x", RoutePathError::ReservedPrefix("_jobs".into())),
251 ("/graphql", RoutePathError::ReservedPrefix("graphql".into())),
252 ("/books/a b", RoutePathError::InvalidLiteral("a b".into())),
253 (
254 "/books/{id}x",
255 RoutePathError::InvalidLiteral("{id}x".into()),
256 ),
257 ("/books/%20", RoutePathError::InvalidLiteral("%20".into())),
258 ] {
259 assert_eq!(RoutePattern::parse(path), Err(error), "{path}");
260 }
261 }
262
263 #[test]
264 fn renders_matchit_and_openapi_templates() {
265 let pattern = RoutePattern::parse("/files/:bucket/{*rest}").expect("parses");
266 assert_eq!(pattern.to_matchit(), "/files/{bucket}/{*rest}");
267 assert_eq!(pattern.to_openapi(), "/files/{bucket}/{rest}");
268 assert_eq!(pattern.params().collect::<Vec<_>>(), ["bucket", "rest"]);
269 assert_eq!(pattern.first_literal(), Some("files"));
270 let root = RoutePattern::parse("/").expect("root");
271 assert_eq!(
272 (root.to_matchit(), root.to_openapi()),
273 ("/".into(), "/".into())
274 );
275 assert_eq!(
276 RoutePattern::parse("/{id}").expect("param").first_literal(),
277 None
278 );
279 }
280
281 #[test]
282 fn errors_read_as_sentences() {
283 assert_eq!(
284 RoutePathError::ReservedPrefix("_fn".into()).to_string(),
285 "the first segment '_fn' is reserved by the platform"
286 );
287 }
288}