Skip to main content

axa_openapi_docs/
routes.rs

1//! Route listing and drift checks: run [`drift`] and [`dangling_refs`] in a test, so a route cannot
2//! be added, removed, or renamed without the document following.
3//!
4//! ```
5//! use axa_openapi_docs::{dangling_refs, drift};
6//! use serde_json::json;
7//!
8//! // What `AppRoutes::mounted` gives.
9//! let routes = [("GET".to_string(), "/api/things/{pid}".to_string())];
10//! let document = json!({ "paths": { "/api/things/{id}": { "get": {} } } });
11//!
12//! assert!(drift(&routes, &document, &[]).is_empty());
13//! assert!(dangling_refs(&document).is_empty());
14//! ```
15
16use std::collections::{BTreeMap, BTreeSet};
17
18use serde_json::Value;
19
20/// A path with its parameter names removed: `/things/{pid}` and `/things/{id}` are one route.
21#[must_use]
22pub fn shape(path: &str) -> String {
23    let mut shaped = String::with_capacity(path.len());
24    let mut inside = false;
25    for character in path.chars() {
26        match character {
27            '{' => {
28                inside = true;
29                shaped.push_str("{}");
30            }
31            '}' => inside = false,
32            _ if !inside => shaped.push(character),
33            _ => {}
34        }
35    }
36    shaped
37}
38
39/// Where a document and the mounted routes disagree. Each entry reads `get /things/{}`.
40#[derive(Clone, Debug, Default, PartialEq, Eq)]
41pub struct Drift {
42    /// Mounted, and missing from the document.
43    pub undocumented: Vec<String>,
44    /// In the document, and not mounted.
45    pub unmounted: Vec<String>,
46}
47
48impl Drift {
49    /// Whether the two agree.
50    #[must_use]
51    pub fn is_empty(&self) -> bool {
52        self.undocumented.is_empty() && self.unmounted.is_empty()
53    }
54}
55
56/// Keys of an `OpenAPI` path item that are not operations.
57const NOT_OPERATIONS: [&str; 5] = ["description", "parameters", "servers", "summary", "$ref"];
58
59type Operations = BTreeMap<String, BTreeSet<String>>;
60
61fn missing_from(from: &Operations, other: &Operations) -> Vec<String> {
62    from.iter()
63        .flat_map(|(path, methods)| methods.iter().map(move |method| (path, method)))
64        .filter(|(path, method)| !other.get(*path).is_some_and(|m| m.contains(*method)))
65        .map(|(path, method)| format!("{method} {path}"))
66        .collect()
67}
68
69/// Compare the mounted `routes`, as `(method, full path)` from `AppRoutes::mounted`, with
70/// `document`'s `paths`, ignoring parameter names. `not_documented` lists paths a service keeps
71/// out on purpose, such as its health probes.
72#[must_use]
73pub fn drift(routes: &[(String, String)], document: &Value, not_documented: &[&str]) -> Drift {
74    let skipped: BTreeSet<String> = not_documented.iter().map(|path| shape(path)).collect();
75    let mut mounted = Operations::new();
76    for (method, path) in routes {
77        let path = shape(path);
78        if !skipped.contains(&path) {
79            mounted
80                .entry(path)
81                .or_default()
82                .insert(method.to_lowercase());
83        }
84    }
85    let mut documented = Operations::new();
86    for (path, item) in document["paths"].as_object().into_iter().flatten() {
87        let methods = item.as_object().into_iter().flatten().map(|(key, _)| key);
88        documented.entry(shape(path)).or_default().extend(
89            methods
90                .filter(|key| !NOT_OPERATIONS.contains(&key.as_str()))
91                .cloned(),
92        );
93    }
94    Drift {
95        undocumented: missing_from(&mounted, &documented),
96        unmounted: missing_from(&documented, &mounted),
97    }
98}
99
100fn walk(value: &Value, document: &Value, dangling: &mut Vec<String>) {
101    match value {
102        Value::Object(map) => {
103            for (key, child) in map {
104                if key == "$ref"
105                    && let Some(target) = child.as_str()
106                    && target
107                        .strip_prefix('#')
108                        .is_some_and(|pointer| document.pointer(pointer).is_none())
109                {
110                    dangling.push(target.to_string());
111                }
112                walk(child, document, dangling);
113            }
114        }
115        Value::Array(items) => {
116            for child in items {
117                walk(child, document, dangling);
118            }
119        }
120        _ => {}
121    }
122}
123
124/// Every `$ref` inside `document` that points at nothing in it. A reference to another file is
125/// not followed, and not reported.
126#[must_use]
127pub fn dangling_refs(document: &Value) -> Vec<String> {
128    let mut dangling = Vec::new();
129    walk(document, document, &mut dangling);
130    dangling
131}
132
133#[cfg(test)]
134mod tests {
135    use serde_json::json;
136
137    use super::*;
138
139    fn route(path: &str, methods: &[&str]) -> Vec<(String, String)> {
140        methods
141            .iter()
142            .map(|method| ((*method).to_string(), path.to_string()))
143            .collect()
144    }
145
146    #[test]
147    fn parameter_names_do_not_change_a_shape() {
148        assert_eq!(shape("/a/{pid}/b/{entity_pid}"), "/a/{}/b/{}");
149        assert_eq!(shape("/a/b"), "/a/b");
150    }
151
152    #[test]
153    fn agreement_is_empty_whatever_the_parameters_are_called() {
154        let document = json!({ "paths": { "/a/{id}": { "get": {}, "post": {} } } });
155        let routes = route("/a/{pid}", &["GET", "POST"]);
156        assert!(drift(&routes, &document, &[]).is_empty());
157    }
158
159    #[test]
160    fn a_mounted_route_missing_from_the_document_is_reported() {
161        let document = json!({ "paths": { "/a": { "get": {} } } });
162        let routes = [route("/a", &["GET", "PUT"]), route("/b", &["GET"])].concat();
163        let found = drift(&routes, &document, &[]);
164        assert_eq!(found.undocumented, ["put /a", "get /b"]);
165        assert_eq!(found.unmounted, Vec::<String>::new());
166    }
167
168    #[test]
169    fn a_documented_operation_with_no_route_is_reported() {
170        let document =
171            json!({ "paths": { "/a": { "get": {}, "put": {} }, "/gone": { "get": {} } } });
172        let found = drift(&route("/a", &["GET"]), &document, &[]);
173        assert_eq!(found.unmounted, ["put /a", "get /gone"]);
174        assert_eq!(found.undocumented, Vec::<String>::new());
175    }
176
177    #[test]
178    fn a_path_kept_out_on_purpose_is_not_reported() {
179        let document = json!({ "paths": {} });
180        let routes = route("/_health", &["GET"]);
181        assert!(drift(&routes, &document, &["/_health"]).is_empty());
182    }
183
184    #[test]
185    fn a_path_items_other_members_are_not_operations() {
186        let document =
187            json!({ "paths": { "/a": { "summary": "A", "parameters": [], "get": {} } } });
188        assert!(drift(&route("/a", &["GET"]), &document, &[]).is_empty());
189    }
190
191    #[test]
192    fn a_document_with_no_paths_reports_every_route() {
193        let found = drift(&route("/a", &["GET"]), &json!({}), &[]);
194        assert_eq!(found.undocumented, ["get /a"]);
195    }
196
197    #[test]
198    fn a_reference_that_resolves_is_not_reported() {
199        let document = json!({
200            "components": { "schemas": { "Thing": {} } },
201            "paths": { "/a": { "get": { "schema": { "$ref": "#/components/schemas/Thing" } } } }
202        });
203        assert_eq!(dangling_refs(&document), Vec::<String>::new());
204    }
205
206    #[test]
207    fn a_reference_to_nothing_is_reported_wherever_it_is() {
208        let document = json!({
209            "components": { "schemas": {} },
210            "list": [{ "nested": { "$ref": "#/components/schemas/Gone" } }]
211        });
212        assert_eq!(dangling_refs(&document), ["#/components/schemas/Gone"]);
213    }
214
215    #[test]
216    fn a_reference_to_another_file_is_left_alone() {
217        let document = json!({ "a": { "$ref": "other.json#/Thing" } });
218        assert_eq!(dangling_refs(&document), Vec::<String>::new());
219    }
220}