Skip to main content

soothfast_spec/
router.rs

1//! Router drift for generated specs: the routes an axum-style router
2//! registers, read from source, against the operations the spec declares.
3//!
4//! Advisory by design. A generated spec cannot disagree with its `#[route]`
5//! markers, but the markers are written by hand and can disagree with the
6//! router that actually serves requests.
7
8use crate::DeclaredOp;
9
10const ANY: &str = "ANY";
11const VERBS: [&str; 7] = ["get", "post", "put", "delete", "patch", "head", "options"];
12
13/// One `.route("path", verb(handler))` registration.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct RouterRoute {
16    /// Upper-case HTTP verb, or `ANY` when the registration names none.
17    pub method: String,
18    /// The path literal as written, relative to any `.nest` prefix.
19    pub path: String,
20}
21
22/// What the router and the spec disagree on.
23#[derive(Debug, Default)]
24pub struct RouterDrift {
25    /// Registered by the router; no operation in the spec serves it.
26    pub unspecified: Vec<RouterRoute>,
27    /// Declared by the spec; no registration in the router serves it.
28    pub unserved: Vec<DeclaredOp>,
29}
30
31/// Every `.route("<literal>", verb(..)[.verb(..)])` registration in `source`,
32/// one entry per verb. A call naming no verb, such as `any(h)`, is one entry
33/// with method `ANY`. `#[cfg(test)] mod` blocks are skipped.
34pub fn scan_routes(source: &str) -> Vec<RouterRoute> {
35    let live = &strip_test_mods(&strip_comments(source));
36    let bytes = live.as_bytes();
37    let mut out = Vec::new();
38    let mut at = 0;
39    while let Some(found) = live[at..].find(".route(") {
40        let open = at + found + ".route(".len();
41        at = open;
42        let Some(close) = matching_paren(bytes, open - 1) else {
43            continue;
44        };
45        let args = &live[open..close];
46        let Some((path, rest)) = leading_literal(args) else {
47            continue;
48        };
49        let mut methods: Vec<String> = verbs(rest).iter().map(|v| v.to_uppercase()).collect();
50        if methods.is_empty() {
51            methods.push(ANY.to_string());
52        }
53        for method in methods {
54            out.push(RouterRoute {
55                method,
56                path: path.to_string(),
57            });
58        }
59    }
60    out
61}
62
63/// Compare registrations with declared operations. Paths match on shape
64/// (`{id}`, `:id` and `{symbol}` are the same segment) and by suffix, since
65/// a `.nest("/v2", ..)` prefix is applied away from the registration.
66pub fn compare(routes: &[RouterRoute], declared: &[DeclaredOp]) -> RouterDrift {
67    RouterDrift {
68        unspecified: routes
69            .iter()
70            .filter(|r| !declared.iter().any(|d| serves(r, d)))
71            .cloned()
72            .collect(),
73        unserved: declared
74            .iter()
75            .filter(|d| !routes.iter().any(|r| serves(r, d)))
76            .cloned()
77            .collect(),
78    }
79}
80
81fn serves(route: &RouterRoute, declared: &DeclaredOp) -> bool {
82    (route.method == ANY || route.method.eq_ignore_ascii_case(&declared.method))
83        && suffix_of(&declared.path, &route.path)
84}
85
86fn suffix_of(spec_path: &str, route_path: &str) -> bool {
87    let spec = segments(spec_path);
88    let route = segments(route_path);
89    if route.is_empty() {
90        return spec.is_empty();
91    }
92    spec.len() >= route.len() && spec[spec.len() - route.len()..] == route[..]
93}
94
95fn segments(path: &str) -> Vec<String> {
96    path.split('/')
97        .filter(|s| !s.is_empty())
98        .map(|s| {
99            if s.starts_with(':') || s.starts_with('*') || (s.starts_with('{') && s.ends_with('}'))
100            {
101                "{}".to_string()
102            } else {
103                s.to_string()
104            }
105        })
106        .collect()
107}
108
109/// `source` with line and block comments blanked, string literals kept.
110fn strip_comments(source: &str) -> String {
111    let bytes = source.as_bytes();
112    let mut out = String::with_capacity(source.len());
113    let mut i = 0;
114    while i < bytes.len() {
115        let end = match (bytes[i], bytes.get(i + 1)) {
116            (b'"', _) => string_end(bytes, i).map_or(bytes.len(), |e| e + 1),
117            (b'/', Some(b'/')) => source[i..].find('\n').map_or(bytes.len(), |n| i + n),
118            (b'/', Some(b'*')) => source[i + 2..]
119                .find("*/")
120                .map_or(bytes.len(), |n| i + 2 + n + 2),
121            _ => {
122                let ch = source[i..].chars().next().map_or(1, char::len_utf8);
123                out.push_str(&source[i..i + ch]);
124                i += ch;
125                continue;
126            }
127        };
128        if bytes[i] == b'"' {
129            out.push_str(&source[i..end]);
130        } else {
131            out.push(' ');
132        }
133        i = end;
134    }
135    out
136}
137
138/// `source` without its `#[cfg(test)] mod name { .. }` blocks.
139fn strip_test_mods(source: &str) -> String {
140    const MARK: &str = "#[cfg(test)]";
141    let mut out = String::with_capacity(source.len());
142    let mut rest = source;
143    while let Some(at) = rest.find(MARK) {
144        out.push_str(&rest[..at]);
145        let after = &rest[at + MARK.len()..];
146        let body = after.trim_start();
147        let close = body
148            .starts_with("mod ")
149            .then(|| body.find('{'))
150            .flatten()
151            .and_then(|open| matching_brace(body.as_bytes(), open));
152        match close {
153            Some(close) => rest = &body[close + 1..],
154            None => {
155                out.push_str(MARK);
156                rest = after;
157            }
158        }
159    }
160    out.push_str(rest);
161    out
162}
163
164/// The index of the `}` closing the `{` at `open`, skipping string literals.
165fn matching_brace(bytes: &[u8], open: usize) -> Option<usize> {
166    let mut depth = 0usize;
167    let mut i = open;
168    while i < bytes.len() {
169        match bytes[i] {
170            b'"' => i = string_end(bytes, i)?,
171            b'{' => depth += 1,
172            b'}' => {
173                depth -= 1;
174                if depth == 0 {
175                    return Some(i);
176                }
177            }
178            _ => {}
179        }
180        i += 1;
181    }
182    None
183}
184
185/// The index of the `)` closing the `(` at `open`, skipping string literals.
186fn matching_paren(bytes: &[u8], open: usize) -> Option<usize> {
187    let mut depth = 0usize;
188    let mut i = open;
189    while i < bytes.len() {
190        match bytes[i] {
191            b'"' => i = string_end(bytes, i)?,
192            b'(' => depth += 1,
193            b')' => {
194                depth -= 1;
195                if depth == 0 {
196                    return Some(i);
197                }
198            }
199            _ => {}
200        }
201        i += 1;
202    }
203    None
204}
205
206/// The index of the `"` closing the literal opened at `open`.
207fn string_end(bytes: &[u8], open: usize) -> Option<usize> {
208    let mut i = open + 1;
209    while i < bytes.len() {
210        match bytes[i] {
211            b'\\' => i += 1,
212            b'"' => return Some(i),
213            _ => {}
214        }
215        i += 1;
216    }
217    None
218}
219
220/// The leading `"literal"` of a call's arguments and what follows its comma.
221fn leading_literal(args: &str) -> Option<(&str, &str)> {
222    let args = args.trim_start().strip_prefix('"')?;
223    let end = args.find('"')?;
224    let rest = args[end + 1..].trim_start().strip_prefix(',')?;
225    Some((&args[..end], rest))
226}
227
228/// The verbs called at the top level of a method-router expression, such as
229/// `get(a).post(b)` or `routing::get(a)`.
230fn verbs(expr: &str) -> Vec<&'static str> {
231    let bytes = expr.as_bytes();
232    let mut found = Vec::new();
233    let mut depth = 0usize;
234    let mut i = 0;
235    while i < bytes.len() {
236        match bytes[i] {
237            b'"' => match string_end(bytes, i) {
238                Some(end) => i = end,
239                None => break,
240            },
241            b'(' => depth += 1,
242            b')' => depth = depth.saturating_sub(1),
243            c if depth == 0 && c.is_ascii_alphabetic() => {
244                let start = i;
245                while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') {
246                    i += 1;
247                }
248                let word = &expr[start..i];
249                let boundary =
250                    start == 0 || !matches!(bytes[start - 1], b'a'..=b'z' | b'A'..=b'Z' | b'_');
251                if boundary
252                    && bytes.get(i) == Some(&b'(')
253                    && let Some(verb) = VERBS.iter().find(|v| **v == word)
254                {
255                    found.push(*verb);
256                }
257                continue;
258            }
259            _ => {}
260        }
261        i += 1;
262    }
263    found
264}
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269
270    fn op(method: &str, path: &str) -> DeclaredOp {
271        DeclaredOp {
272            operation: format!("{method}{path}"),
273            method: method.into(),
274            path: path.into(),
275        }
276    }
277
278    fn route(method: &str, path: &str) -> RouterRoute {
279        RouterRoute {
280            method: method.into(),
281            path: path.into(),
282        }
283    }
284
285    #[test]
286    fn reads_one_route_per_verb() {
287        let src =
288            r#"Router::new().route("/graphql", post(run).get(playground)).route("/h", get(h))"#;
289        assert_eq!(
290            scan_routes(src),
291            [
292                route("POST", "/graphql"),
293                route("GET", "/graphql"),
294                route("GET", "/h")
295            ]
296        );
297    }
298
299    #[test]
300    fn reads_multiline_registrations_and_qualified_verbs() {
301        let src = "r.route(\n    \"/a/{id}\",\n    routing::get(handlers::a).layer(L::new()),\n)";
302        assert_eq!(scan_routes(src), [route("GET", "/a/{id}")]);
303    }
304
305    #[test]
306    fn ignores_handler_names_that_contain_a_verb() {
307        let src = r#"r.route("/x", get(forget_all))"#;
308        assert_eq!(scan_routes(src), [route("GET", "/x")]);
309    }
310
311    #[test]
312    fn skips_test_modules_and_non_literal_paths() {
313        let src = "r.route(PATH, get(a)).route(\"/live\", get(b))\n#[cfg(test)]\nmod t { fn f() { r.route(\"/t\", get(c)); } }";
314        assert_eq!(scan_routes(src), [route("GET", "/live")]);
315    }
316
317    #[test]
318    fn ignores_commented_out_routes_but_not_slashes_in_strings() {
319        let src = "// r.route(\"/old\", get(h))\n/* r.route(\"/older\", get(h)) */\nr.route(\"/a//b\", get(h))";
320        assert_eq!(scan_routes(src), [route("GET", "/a//b")]);
321    }
322
323    #[test]
324    fn the_root_route_serves_only_the_root_path() {
325        let drift = compare(&[route("GET", "/")], &[op("GET", "/items"), op("GET", "/")]);
326        assert_eq!(drift.unserved, [op("GET", "/items")]);
327        assert!(drift.unspecified.is_empty());
328    }
329
330    #[test]
331    fn wildcard_segments_are_one_placeholder() {
332        let drift = compare(
333            &[route("GET", "/files/*rest")],
334            &[op("GET", "/files/{*path}")],
335        );
336        assert!(drift.unserved.is_empty() && drift.unspecified.is_empty());
337    }
338
339    #[test]
340    fn code_after_a_test_mod_or_a_cfg_test_use_is_still_read() {
341        let src = "#[cfg(test)]\nuse x::y;\nr.route(\"/a\", get(h));\n#[cfg(test)]\nmod t { fn f() { r.route(\"/t\", get(c)); } }\nr.route(\"/b\", get(h));";
342        assert_eq!(scan_routes(src), [route("GET", "/a"), route("GET", "/b")]);
343    }
344
345    #[test]
346    fn a_route_with_no_verb_serves_any_method() {
347        let routes = scan_routes(r#"r.route("/ws", any(ws))"#);
348        assert_eq!(routes, [route("ANY", "/ws")]);
349        let drift = compare(&routes, &[op("GET", "/ws")]);
350        assert!(drift.unserved.is_empty() && drift.unspecified.is_empty());
351    }
352
353    #[test]
354    fn finds_nothing_in_another_framework() {
355        assert!(scan_routes("#[get(\"/x\")] async fn x() {}").is_empty());
356    }
357
358    #[test]
359    fn matches_across_nest_prefix_and_param_spelling() {
360        let routes = [route("GET", "/analysis/{type}"), route("GET", "/health")];
361        let declared = [
362            op("GET", "/v2/analysis/{analysis_type}"),
363            op("GET", "/v2/health"),
364        ];
365        let drift = compare(&routes, &declared);
366        assert!(drift.unspecified.is_empty() && drift.unserved.is_empty());
367    }
368
369    #[test]
370    fn reports_both_directions() {
371        let routes = [route("GET", "/a"), route("POST", "/b")];
372        let declared = [op("GET", "/v2/a"), op("GET", "/v2/c")];
373        let drift = compare(&routes, &declared);
374        assert_eq!(drift.unspecified, [route("POST", "/b")]);
375        assert_eq!(drift.unserved, [op("GET", "/v2/c")]);
376    }
377
378    #[test]
379    fn a_shorter_spec_path_is_not_served_by_a_longer_route() {
380        let drift = compare(&[route("GET", "/v2/a")], &[op("GET", "/a")]);
381        assert_eq!(drift.unserved.len(), 1);
382        assert_eq!(drift.unspecified.len(), 1);
383    }
384}