G: F4 scan multiline routes and their methods
This commit is contained in:
1 parent
e6a9453c7a
commit
abd5b12cd0
1 file changed
+221
-43
+221
-43
@@ -114,69 +114,247 @@ async fn call(app: &Router, method: Method, uri: &str) -> (StatusCode, Value) {
|
|||||||
(status, json)
|
(status, json)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// One `.route(...)` call: path plus the methods its builder names, or
|
||||||
|
/// `None` for a mount where the mounted service decides.
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct Route {
|
||||||
|
path: String,
|
||||||
|
methods: Option<Vec<Method>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every `.rs` file below `src/api`, recursively, in stable order.
|
||||||
|
fn api_files() -> Vec<std::path::PathBuf> {
|
||||||
|
fn walk(dir: &Path, out: &mut Vec<std::path::PathBuf>) {
|
||||||
|
let mut entries: Vec<_> = fs::read_dir(dir)
|
||||||
|
.unwrap()
|
||||||
|
.map(|entry| entry.unwrap().path())
|
||||||
|
.collect();
|
||||||
|
entries.sort();
|
||||||
|
for path in entries {
|
||||||
|
if path.is_dir() {
|
||||||
|
walk(&path, out);
|
||||||
|
} else if path.extension().is_some_and(|e| e == "rs") {
|
||||||
|
out.push(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut files = Vec::new();
|
||||||
|
walk(&Path::new(MANIFEST).join("src/api"), &mut files);
|
||||||
|
files
|
||||||
|
}
|
||||||
|
|
||||||
/// Route literals under `src/api`, which `server.rs` nests at `/api/v1`.
|
/// Route literals under `src/api`, which `server.rs` nests at `/api/v1`.
|
||||||
fn api_route_literals() -> Vec<String> {
|
fn api_routes() -> Vec<Route> {
|
||||||
let dir = Path::new(MANIFEST).join("src/api");
|
|
||||||
let mut out = Vec::new();
|
let mut out = Vec::new();
|
||||||
let mut files: Vec<_> = fs::read_dir(&dir)
|
for file in api_files() {
|
||||||
.unwrap()
|
|
||||||
.map(|entry| entry.unwrap().path())
|
|
||||||
.filter(|path| path.extension().is_some_and(|e| e == "rs"))
|
|
||||||
.collect();
|
|
||||||
files.sort();
|
|
||||||
for file in files {
|
|
||||||
let source = fs::read_to_string(&file).unwrap();
|
let source = fs::read_to_string(&file).unwrap();
|
||||||
out.extend(route_literals(&source).into_iter().map(|route| {
|
let routes = route_calls(&source);
|
||||||
assert!(route.starts_with('/'), "{}: {route}", file.display());
|
// A new file that builds a router but contributes no route would be
|
||||||
format!("/api/v1{route}")
|
// invisible to the scan.
|
||||||
|
if source.contains("Router::new") {
|
||||||
|
assert!(
|
||||||
|
!routes.is_empty(),
|
||||||
|
"{}: builds a router but contributes no route",
|
||||||
|
file.display()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
!source.contains(".nest(\"") && !source.contains(".nest_service(\""),
|
||||||
|
"{}: nested routers need to be added to the scan",
|
||||||
|
file.display()
|
||||||
|
);
|
||||||
|
out.extend(routes.into_iter().map(|mut route| {
|
||||||
|
assert!(route.path.starts_with('/'), "{}: {route:?}", file.display());
|
||||||
|
route.path = format!("/api/v1{}", route.path);
|
||||||
|
route
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
out
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Route literals declared outside the API router: `/healthz` and the `/mcp`
|
/// Routes declared outside the API router: `/healthz` and the `/mcp` mount in
|
||||||
/// mount in `server.rs`.
|
/// `server.rs`. `nest_service` accepts every method, so `/mcp` has none here.
|
||||||
fn server_route_literals() -> Vec<String> {
|
fn server_routes() -> Vec<Route> {
|
||||||
let source = fs::read_to_string(Path::new(MANIFEST).join("src/server.rs")).unwrap();
|
let source = fs::read_to_string(Path::new(MANIFEST).join("src/server.rs")).unwrap();
|
||||||
let mut out = route_literals(&source);
|
let mut out = route_calls(&source);
|
||||||
let mount = ".nest_service(\"/mcp\"";
|
let mount = ".nest_service(\"/mcp\"";
|
||||||
assert!(source.contains(mount), "server.rs no longer mounts /mcp");
|
assert!(source.contains(mount), "server.rs no longer mounts /mcp");
|
||||||
out.push("/mcp".to_owned());
|
out.push(Route {
|
||||||
out.sort();
|
path: "/mcp".to_owned(),
|
||||||
|
methods: None,
|
||||||
|
});
|
||||||
|
out.sort_by(|a, b| a.path.cmp(&b.path));
|
||||||
out
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The path argument of every `.route("...")` call. Splitting on the marker
|
/// Every `.route(...)` call, independent of how rustfmt breaks the line.
|
||||||
/// keeps this independent of how the call is formatted. Mount points
|
fn route_calls(source: &str) -> Vec<Route> {
|
||||||
/// (`.nest`, `.nest_service`) are added by the caller.
|
let mut out = Vec::new();
|
||||||
fn route_literals(source: &str) -> Vec<String> {
|
let mut from = 0;
|
||||||
let marker = ".route(\"";
|
while let Some(index) = source[from..].find(".route") {
|
||||||
source
|
let marker = from + index;
|
||||||
.match_indices(marker)
|
let mut cursor = marker + ".route".len();
|
||||||
.map(|(index, _)| {
|
cursor = skip_space(source, cursor);
|
||||||
let rest = &source[index + marker.len()..];
|
if !source[cursor..].starts_with('(') {
|
||||||
let end = rest.find('"').expect("a route literal ends");
|
from = cursor;
|
||||||
rest[..end].to_owned()
|
continue;
|
||||||
})
|
}
|
||||||
.collect()
|
let end = matching_paren(source, cursor);
|
||||||
|
let call = &source[cursor + 1..end];
|
||||||
|
let (path, rest) = string_literal(call);
|
||||||
|
out.push(Route {
|
||||||
|
path,
|
||||||
|
methods: Some(method_calls(rest)),
|
||||||
|
});
|
||||||
|
from = end + 1;
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn skip_space(source: &str, mut cursor: usize) -> usize {
|
||||||
|
while source[cursor..]
|
||||||
|
.chars()
|
||||||
|
.next()
|
||||||
|
.is_some_and(char::is_whitespace)
|
||||||
|
{
|
||||||
|
cursor += source[cursor..].chars().next().unwrap().len_utf8();
|
||||||
|
}
|
||||||
|
cursor
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Index of the `)` matching the `(` at `open`, ignoring string contents.
|
||||||
|
fn matching_paren(source: &str, open: usize) -> usize {
|
||||||
|
let bytes = source.as_bytes();
|
||||||
|
let mut depth = 0;
|
||||||
|
let mut in_string = false;
|
||||||
|
let mut escaped = false;
|
||||||
|
let mut index = open;
|
||||||
|
while index < bytes.len() {
|
||||||
|
let byte = bytes[index];
|
||||||
|
if in_string {
|
||||||
|
if escaped {
|
||||||
|
escaped = false;
|
||||||
|
} else if byte == b'\\' {
|
||||||
|
escaped = true;
|
||||||
|
} else if byte == b'"' {
|
||||||
|
in_string = false;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
match byte {
|
||||||
|
b'"' => in_string = true,
|
||||||
|
b'(' => depth += 1,
|
||||||
|
b')' => {
|
||||||
|
depth -= 1;
|
||||||
|
if depth == 0 {
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
index += 1;
|
||||||
|
}
|
||||||
|
panic!("unclosed .route( call at byte {open}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The leading string literal of a route call and the rest of the call.
|
||||||
|
fn string_literal(call: &str) -> (String, &str) {
|
||||||
|
let start = skip_space(call, 0);
|
||||||
|
let rest = &call[start..];
|
||||||
|
let rest = rest
|
||||||
|
.strip_prefix('"')
|
||||||
|
.unwrap_or_else(|| panic!("route call does not start with a path: {call}"));
|
||||||
|
let end = rest.find('"').expect("a route literal ends");
|
||||||
|
(rest[..end].to_owned(), &rest[end + 1..])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Method builders named in the handler argument (`get`, `post`, ...).
|
||||||
|
fn method_calls(rest: &str) -> Vec<Method> {
|
||||||
|
let mut methods = Vec::new();
|
||||||
|
let mut remaining = rest;
|
||||||
|
while let Some(index) = remaining.find(|c: char| c.is_ascii_alphabetic()) {
|
||||||
|
remaining = &remaining[index..];
|
||||||
|
let end = remaining
|
||||||
|
.find(|c: char| !c.is_ascii_alphanumeric() && c != '_')
|
||||||
|
.unwrap_or(remaining.len());
|
||||||
|
let word = &remaining[..end];
|
||||||
|
if let Some(method) = method(word) {
|
||||||
|
if remaining[end..].trim_start().starts_with('(') {
|
||||||
|
methods.push(method);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
remaining = &remaining[end..];
|
||||||
|
}
|
||||||
|
methods.sort_by(|a, b| a.as_str().cmp(b.as_str()));
|
||||||
|
methods.dedup();
|
||||||
|
methods
|
||||||
|
}
|
||||||
|
|
||||||
|
fn method(name: &str) -> Option<Method> {
|
||||||
|
Some(match name {
|
||||||
|
"get" => Method::GET,
|
||||||
|
"post" => Method::POST,
|
||||||
|
"put" => Method::PUT,
|
||||||
|
"delete" => Method::DELETE,
|
||||||
|
"patch" => Method::PATCH,
|
||||||
|
"head" => Method::HEAD,
|
||||||
|
"options" => Method::OPTIONS,
|
||||||
|
_ => return None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The scan must survive rustfmt breaking a long route and must read the
|
||||||
|
/// method builders, not just the path.
|
||||||
|
#[test]
|
||||||
|
fn route_scan_handles_multiline_calls_and_methods() {
|
||||||
|
let source = r#"
|
||||||
|
Router::new()
|
||||||
|
.route(
|
||||||
|
"/long/path",
|
||||||
|
get(one).post(two),
|
||||||
|
)
|
||||||
|
.route("/short", delete(three))
|
||||||
|
"#;
|
||||||
|
let routes = route_calls(source);
|
||||||
|
assert_eq!(routes.len(), 2);
|
||||||
|
assert_eq!(routes[0].path, "/long/path");
|
||||||
|
assert_eq!(
|
||||||
|
routes[0].methods.as_ref().unwrap(),
|
||||||
|
&[Method::GET, Method::POST]
|
||||||
|
);
|
||||||
|
assert_eq!(routes[1].path, "/short");
|
||||||
|
assert_eq!(routes[1].methods.as_ref().unwrap(), &[Method::DELETE]);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn every_router_route_is_documented() {
|
async fn every_router_route_is_documented() {
|
||||||
let doc = document(true);
|
let doc = document(true);
|
||||||
let mut routes = api_route_literals();
|
let mut routes = api_routes();
|
||||||
routes.extend(server_route_literals());
|
routes.extend(server_routes());
|
||||||
// A scan that stops matching would make the check below vacuous.
|
// A scan that stops matching would make the checks below vacuous.
|
||||||
assert!(
|
assert_eq!(routes.len(), 15, "route scan found: {routes:?}");
|
||||||
routes.len() >= 13,
|
|
||||||
"route scan found too little: {routes:?}"
|
|
||||||
);
|
|
||||||
for route in routes {
|
for route in routes {
|
||||||
let route = openapi_path(&route);
|
let path = openapi_path(&route.path);
|
||||||
assert!(
|
let item =
|
||||||
doc.paths.paths.contains_key(&route),
|
doc.paths.paths.get(&path).unwrap_or_else(|| {
|
||||||
"{route} is routed but missing from the OpenAPI document"
|
panic!("{path} is routed but missing from the OpenAPI document")
|
||||||
);
|
});
|
||||||
|
let Some(methods) = route.methods else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let documented = documented_methods(item);
|
||||||
|
for method in &methods {
|
||||||
|
assert!(
|
||||||
|
documented.contains(method),
|
||||||
|
"{method} {path} is routed but missing from the OpenAPI document"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for method in documented {
|
||||||
|
assert!(
|
||||||
|
methods.contains(&method),
|
||||||
|
"{method} {path} is documented but not routed"
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user