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
+221 -43
+221 -43
View File
@@ -114,69 +114,247 @@ async fn call(app: &Router, method: Method, uri: &str) -> (StatusCode, Value) {
(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`.
fn api_route_literals() -> Vec<String> {
let dir = Path::new(MANIFEST).join("src/api");
fn api_routes() -> Vec<Route> {
let mut out = Vec::new();
let mut files: Vec<_> = fs::read_dir(&dir)
.unwrap()
.map(|entry| entry.unwrap().path())
.filter(|path| path.extension().is_some_and(|e| e == "rs"))
.collect();
files.sort();
for file in files {
for file in api_files() {
let source = fs::read_to_string(&file).unwrap();
out.extend(route_literals(&source).into_iter().map(|route| {
assert!(route.starts_with('/'), "{}: {route}", file.display());
format!("/api/v1{route}")
let routes = route_calls(&source);
// A new file that builds a router but contributes no route would be
// 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
}
/// Route literals declared outside the API router: `/healthz` and the `/mcp`
/// mount in `server.rs`.
fn server_route_literals() -> Vec<String> {
/// Routes declared outside the API router: `/healthz` and the `/mcp` mount in
/// `server.rs`. `nest_service` accepts every method, so `/mcp` has none here.
fn server_routes() -> Vec<Route> {
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\"";
assert!(source.contains(mount), "server.rs no longer mounts /mcp");
out.push("/mcp".to_owned());
out.sort();
out.push(Route {
path: "/mcp".to_owned(),
methods: None,
});
out.sort_by(|a, b| a.path.cmp(&b.path));
out
}
/// The path argument of every `.route("...")` call. Splitting on the marker
/// keeps this independent of how the call is formatted. Mount points
/// (`.nest`, `.nest_service`) are added by the caller.
fn route_literals(source: &str) -> Vec<String> {
let marker = ".route(\"";
source
.match_indices(marker)
.map(|(index, _)| {
let rest = &source[index + marker.len()..];
let end = rest.find('"').expect("a route literal ends");
rest[..end].to_owned()
})
.collect()
/// Every `.route(...)` call, independent of how rustfmt breaks the line.
fn route_calls(source: &str) -> Vec<Route> {
let mut out = Vec::new();
let mut from = 0;
while let Some(index) = source[from..].find(".route") {
let marker = from + index;
let mut cursor = marker + ".route".len();
cursor = skip_space(source, cursor);
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");
(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]
async fn every_router_route_is_documented() {
let doc = document(true);
let mut routes = api_route_literals();
routes.extend(server_route_literals());
// A scan that stops matching would make the check below vacuous.
assert!(
routes.len() >= 13,
"route scan found too little: {routes:?}"
);
let mut routes = api_routes();
routes.extend(server_routes());
// A scan that stops matching would make the checks below vacuous.
assert_eq!(routes.len(), 15, "route scan found: {routes:?}");
for route in routes {
let route = openapi_path(&route);
assert!(
doc.paths.paths.contains_key(&route),
"{route} is routed but missing from the OpenAPI document"
);
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!(
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"
);
}
}
}