G: F4 scan multiline routes and their methods

This commit is contained in:
ari committed 2026-10-20 15:54:13 -04:00
1 parent e6a9453c7a
commit abd5b12cd0
1 file changed
+216 -38
+216 -38
View File
@@ -114,70 +114,248 @@ async fn call(app: &Router, method: Method, uri: &str) -> (StatusCode, Value) {
(status, json) (status, json)
} }
/// Route literals under `src/api`, which `server.rs` nests at `/api/v1`. /// One `.route(...)` call: path plus the methods its builder names, or
fn api_route_literals() -> Vec<String> { /// `None` for a mount where the mounted service decides.
let dir = Path::new(MANIFEST).join("src/api"); #[derive(Debug)]
let mut out = Vec::new(); struct Route {
let mut files: Vec<_> = fs::read_dir(&dir) 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() .unwrap()
.map(|entry| entry.unwrap().path()) .map(|entry| entry.unwrap().path())
.filter(|path| path.extension().is_some_and(|e| e == "rs"))
.collect(); .collect();
files.sort(); entries.sort();
for file in files { 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`.
fn api_routes() -> Vec<Route> {
let mut out = Vec::new();
for file in api_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('(') {
from = cursor;
continue;
}
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"); let end = rest.find('"').expect("a route literal ends");
rest[..end].to_owned() (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,
}) })
.collect() }
/// 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);
let item =
doc.paths.paths.get(&path).unwrap_or_else(|| {
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!( assert!(
doc.paths.paths.contains_key(&route), documented.contains(method),
"{route} is routed but missing from the OpenAPI document" "{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"
);
}
}
} }
#[tokio::test] #[tokio::test]