forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

doc_sync.rs477 lines, 18.4 KiBHistoryRawDownload
1//! The README's `## Endpoints` table is generated, not written by hand.
2//!
3//! A hand-maintained route table drifts the moment a handler changes: a prose
4//! review only catches a *missing* path, never a stale Auth
5//! cell nor a row for a route the code deleted. So this test renders the table
6//! from the served `/api-docs/openapi.json` and asserts the marker block in
7//! README.md matches it. Regenerate after any route change:
8//!
9//! ```text
10//! UPDATE_DOCS=1 cargo test --test doc_sync
11//! ```
12//!
13//! Two columns come straight out of the spec (Path/Method, and Description =
14//! the handler's doc comment, which utoipa publishes as the operation summary).
15//! The **Auth** column cannot: OpenAPI has no field for "minimum role", and the
16//! `403` descriptions only sometimes spell it out. So the floor is read from the
17//! two places that actually enforce it — the declared `403` when it names a role
18//! (`"Requires manager role or higher"`), otherwise the `Require*` extractor in
19//! the handler's own signature. Every operation must resolve to exactly one
20//! floor or this test fails naming it, so the column can never go quietly wrong.
21
22mod common;
23
24use std::collections::HashMap;
25
26use serde_json::Value;
27
28const BEGIN: &str = "<!-- BEGIN GENERATED: endpoint-table -->";
29const END: &str = "<!-- END GENERATED -->";
30
31fn repo() -> &'static std::path::Path {
32 std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
33}
34
35/// Routes no OpenAPI document can carry, in the shape the table wants them.
36/// `/` is a plain `axum::routing::get` (no `routes!` macro, so no operation);
37/// the two doc endpoints are mounted by `SwaggerUi`, outside the
38/// `OpenApiRouter`; the two `…/ws` rooms are WebSocket upgrades, which the spec
39/// itself calls out as "Not in this spec (WebSocket)" in their tag text.
40/// Everything else is derived — do not grow this list to paper over a missing
41/// `#[utoipa::path]`.
42const STATIC_ROWS: [(&str, &str, &str, &str); 5] = [
43 ("GET", "/", "no", "Same as `/health`"),
44 ("GET", "/api-docs/openapi.json", "no", "Raw OpenAPI 3 spec"),
45 (
46 "GET",
47 "/boards/{id}/ws",
48 "student",
49 "**WebSocket** board room: a `join` replays the current epoch, every accepted stroke fans out to the other participants (see \"Collaborative whiteboard\")",
50 ),
51 (
52 "GET",
53 "/exams/{id}/attempt/ws",
54 "student",
55 "**WebSocket** exam room (students only): state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see \"Taking an exam\")",
56 ),
57 ("GET", "/swagger", "no", "Interactive API docs (Swagger UI)"),
58];
59
60/// Table order within one path. The repo uses `GET`/`POST`/`PATCH`/`DELETE`
61/// only (AGENTS.md: no `PUT`); anything else sorts last.
62fn method_rank(m: &str) -> usize {
63 ["GET", "POST", "PATCH", "DELETE"]
64 .iter()
65 .position(|x| *x == m)
66 .unwrap_or(usize::MAX)
67}
68
69/// `s[open..]` starts at a `(`; returns the index of its matching `)`.
70fn matching_paren(s: &str, open: usize) -> usize {
71 let mut depth = 0usize;
72 for (i, byte) in s.as_bytes().iter().enumerate().skip(open) {
73 match byte {
74 b'(' => depth += 1,
75 b')' => {
76 depth -= 1;
77 if depth == 0 {
78 return i;
79 }
80 }
81 _ => {}
82 }
83 }
84 panic!("unbalanced `(` in source at byte {open}");
85}
86
87/// The value of a `key = "…"` entry inside a `#[utoipa::path(…)]` attribute.
88fn attr_str<'a>(attr: &'a str, key: &str) -> Option<&'a str> {
89 let start = attr.find(&format!("{key} = \""))? + key.len() + 4;
90 let len = attr[start..].find('"')?;
91 Some(&attr[start..start + len])
92}
93
94/// The role floor a handler's argument list enforces. `CurrentUser` and the
95/// bare extractors gate on a session only, which the README calls `student`
96/// ("any logged-in user").
97fn extractor_floor(params: &str) -> &'static str {
98 for (ty, role) in [
99 // Not a school role at all: the deployment's vendor, whose cookie is
100 // `401` on every school surface (see `web::builder`).
101 ("RequireBuilder", "builder"),
102 ("RequireAdmin", "admin"),
103 ("RequireManager", "manager"),
104 ("RequireTeacher", "teacher"),
105 ] {
106 if params.contains(ty) {
107 return role;
108 }
109 }
110 "student"
111}
112
113/// Every `#[utoipa::path]`-annotated handler in `src/`, keyed by the four
114/// things the spec also publishes: method, tag, operation id (= the fn name)
115/// and the route path *relative to its nest prefix*. That key needs no
116/// knowledge of how `lib.rs` nests routers, which is why it is used instead of
117/// reconstructing full paths.
118type HandlerKey = (String, String, String, String);
119
120/// Every `src/**/*.rs` as (path relative to the repo, contents).
121fn src_files() -> Vec<(String, String)> {
122 let mut out = Vec::new();
123 let mut stack = vec![repo().join("src")];
124 while let Some(dir) = stack.pop() {
125 for entry in std::fs::read_dir(&dir).expect("read src dir") {
126 let path = entry.expect("dir entry").path();
127 if path.is_dir() {
128 stack.push(path);
129 continue;
130 }
131 if path.extension().is_none_or(|e| e != "rs") {
132 continue;
133 }
134 let src = std::fs::read_to_string(&path).expect("read source file");
135 let name = path
136 .strip_prefix(repo())
137 .unwrap_or(&path)
138 .display()
139 .to_string();
140 out.push((name, src));
141 }
142 }
143 out
144}
145
146fn handlers() -> HashMap<HandlerKey, Vec<&'static str>> {
147 let mut out: HashMap<HandlerKey, Vec<&'static str>> = HashMap::new();
148 for (_, src) in src_files() {
149 let mut at = 0;
150 while let Some(hit) = src[at..].find("#[utoipa::path(") {
151 let open = at + hit + "#[utoipa::path".len();
152 let close = matching_paren(&src, open);
153 let attr = &src[open + 1..close];
154 at = close + 1;
155
156 // `)]`, then the item: `pub(crate) async fn name(params)`.
157 let rest = src[close + 1..].trim_start_matches(']').trim_start();
158 let rest = rest.trim_start_matches("pub").trim_start();
159 // `pub(crate)` / `pub(super)` visibility qualifier.
160 let rest = if rest.starts_with('(') {
161 rest[matching_paren(rest, 0) + 1..].trim_start()
162 } else {
163 rest
164 };
165 let rest = rest.trim_start_matches("async").trim_start();
166 let Some(rest) = rest.strip_prefix("fn ") else {
167 continue;
168 };
169 let Some(paren) = rest.find('(') else {
170 continue;
171 };
172 let name = rest[..paren].trim().to_string();
173 let params = &rest[paren + 1..matching_paren(rest, paren)];
174
175 let method = attr
176 .trim()
177 .split(',')
178 .next()
179 .expect("attribute has a method")
180 .trim()
181 .to_uppercase();
182 let key = (
183 method,
184 attr_str(attr, "tag").unwrap_or("").to_string(),
185 name,
186 attr_str(attr, "path")
187 .unwrap_or("")
188 .trim_end_matches('/')
189 .to_string(),
190 );
191 out.entry(key).or_default().push(extractor_floor(params));
192 }
193 }
194 out
195}
196
197/// The minimum role for one operation. `no` when the operation carries no
198/// security requirement at all; otherwise the role its `403` declares, and
199/// failing that the one its handler's extractor enforces.
200fn auth_of(
201 path: &str,
202 method: &str,
203 op: &Value,
204 handlers: &HashMap<HandlerKey, Vec<&str>>,
205) -> String {
206 let has_security = op["security"].as_array().is_some_and(|s| !s.is_empty());
207 if !has_security {
208 return "no".into();
209 }
210 let forbidden = op["responses"]["403"]["description"].as_str().unwrap_or("");
211 if let Some(rest) = forbidden.split_once("Requires ").map(|(_, r)| r) {
212 let mut words = rest.split_whitespace();
213 let first = words.next().unwrap_or("");
214 let role = if first == "the" {
215 words.next().unwrap_or("")
216 } else {
217 first
218 };
219 let role = role.trim_matches(|c: char| !c.is_ascii_alphabetic());
220 if ["parent", "student", "teacher", "manager", "admin"].contains(&role) {
221 return role.to_string();
222 }
223 }
224
225 let tag = op["tags"][0].as_str().unwrap_or("");
226 let operation_id = op["operationId"].as_str().unwrap_or("");
227 let mut floors: Vec<&str> = handlers
228 .iter()
229 .filter(|((m, t, n, rel), _)| {
230 m == method && t == tag && n == operation_id && (rel.is_empty() || path.ends_with(rel))
231 })
232 .flat_map(|(_, floors)| floors.iter().copied())
233 .collect();
234 floors.sort_unstable();
235 floors.dedup();
236 assert_eq!(
237 floors.len(),
238 1,
239 "cannot pin the role floor of `{method} {path}` (tag {tag}, operationId \
240 {operation_id}): matched {floors:?} in src/. Either its `#[utoipa::path]` \
241 `403` should name the role (\"Requires <role> role or higher\"), or the \
242 handler lookup above needs to learn a new shape."
243 );
244 floors[0].to_string()
245}
246
247/// The Description cell: the operation summary, which utoipa lifts from the
248/// first paragraph of the handler's doc comment. Folded to one line, with `|`
249/// escaped so a cell cannot break the table. A handler with no doc comment
250/// falls back to its success response's description — still spec text, never
251/// invented — and both cases mean "write a doc comment".
252fn description_of(op: &Value) -> String {
253 let summary = op["summary"].as_str().unwrap_or("").trim();
254 let text = if summary.is_empty() {
255 op["responses"]
256 .as_object()
257 .and_then(|r| {
258 r.iter()
259 .filter(|(k, _)| k.starts_with('2'))
260 .min_by_key(|(k, _)| k.to_string())
261 .and_then(|(_, v)| v["description"].as_str())
262 })
263 .unwrap_or("")
264 } else {
265 summary
266 };
267 text.split_whitespace()
268 .collect::<Vec<_>>()
269 .join(" ")
270 .replace('|', "\\|")
271}
272
273/// Render the whole table (header included) from the served spec.
274fn render(spec: &Value) -> String {
275 let handlers = handlers();
276 let mut rows: Vec<(String, String, String, String)> = STATIC_ROWS
277 .iter()
278 .map(|(m, p, a, d)| (m.to_string(), p.to_string(), a.to_string(), d.to_string()))
279 .collect();
280
281 let paths = spec["paths"]
282 .as_object()
283 .expect("the served spec has a paths object");
284 for (path, item) in paths {
285 for (method, op) in item.as_object().expect("path item is an object") {
286 // A path item also carries non-verb keys (`parameters`, `summary`);
287 // an operation is the thing with `responses`.
288 if !op.get("responses").is_some_and(Value::is_object) {
289 continue;
290 }
291 let method = method.to_uppercase();
292 let auth = auth_of(path, &method, op, &handlers);
293 rows.push((method, path.clone(), auth, description_of(op)));
294 }
295 }
296 rows.sort_by(|a, b| {
297 a.1.cmp(&b.1)
298 .then(method_rank(&a.0).cmp(&method_rank(&b.0)))
299 });
300
301 // Pad the fixed-width columns to their widest cell, as the hand-written
302 // table did; Description is last, so it never needs padding.
303 let path_w = rows.iter().map(|r| r.1.len() + 2).max().unwrap_or(4).max(4);
304 let auth_w = rows.iter().map(|r| r.2.len()).max().unwrap_or(4).max(4);
305 let mut out = format!(
306 "| Method | {:pw$} | {:aw$} | Description |\n|--------|{}|{}|-------------|\n",
307 "Path",
308 "Auth",
309 "-".repeat(path_w + 2),
310 "-".repeat(auth_w + 2),
311 pw = path_w,
312 aw = auth_w,
313 );
314 for (method, path, auth, desc) in &rows {
315 out.push_str(&format!(
316 "| {:6} | {:pw$} | {:aw$} | {desc} |\n",
317 method,
318 format!("`{path}`"),
319 auth,
320 pw = path_w,
321 aw = auth_w,
322 ));
323 }
324 out
325}
326
327/// The served OpenAPI document — the real router's, not a re-derived one.
328async fn spec() -> Value {
329 let (app, _db) = common::app_and_db().await;
330 common::send(&app, "GET", "/api-docs/openapi.json", None, None)
331 .await
332 .body
333}
334
335/// Split the README on the generated-block markers: (before, block, after).
336fn split_readme(readme: &str) -> (&str, &str, &str) {
337 let (before, rest) = readme
338 .split_once(BEGIN)
339 .unwrap_or_else(|| panic!("README.md has no `{BEGIN}` marker"));
340 let (block, after) = rest
341 .split_once(END)
342 .unwrap_or_else(|| panic!("README.md has no `{END}` marker"));
343 (before, block, after)
344}
345
346/// Compared (and written) whitespace-normalised: trailing spaces stripped per
347/// line, surrounding blank lines ignored. Cell padding still has to match,
348/// which keeps the checked-in table readable as a table.
349fn normalize(block: &str) -> String {
350 block
351 .lines()
352 .map(str::trim_end)
353 .collect::<Vec<_>>()
354 .join("\n")
355 .trim()
356 .to_string()
357}
358
359#[tokio::test]
360async fn readme_endpoint_table_matches_the_spec() {
361 let table = render(&spec().await);
362 let path = repo().join("README.md");
363 let readme = std::fs::read_to_string(&path).expect("read README.md");
364 let (before, block, after) = split_readme(&readme);
365
366 if std::env::var_os("UPDATE_DOCS").is_some() {
367 let updated = format!("{before}{BEGIN}\n\n{}\n\n{END}{after}", normalize(&table));
368 if updated != readme {
369 std::fs::write(&path, updated).expect("write README.md");
370 eprintln!("README.md endpoint table regenerated");
371 }
372 return;
373 }
374
375 // Reported as the first differing line, not as two 275-row tables: the
376 // whole-table dump was ~200KB of scrollback for a one-cell drift.
377 let (have, want) = (normalize(block), normalize(&table));
378 let (have, want): (Vec<&str>, Vec<&str>) = (have.lines().collect(), want.lines().collect());
379 if let Some(i) = (0..have.len().max(want.len())).find(|&i| have.get(i) != want.get(i)) {
380 panic!(
381 "README.md's endpoint table is stale at block line {}:\n README: {}\n spec: {}\n\
382 Regenerate with `UPDATE_DOCS=1 cargo test --test doc_sync`. The cells come from the \
383 handlers' `#[utoipa::path]` annotations and doc comments; fix them there, never in \
384 the README.",
385 i + 1,
386 have.get(i).unwrap_or(&"<line missing>"),
387 want.get(i).unwrap_or(&"<line missing>"),
388 );
389 }
390}
391
392/// Every plain `.route("…", …)` registered by production code, as (source
393/// file, path relative to its nest prefix). `#[cfg(test)]` modules are cut
394/// out first — `src/ai/server.rs` mounts throwaway routers in its own tests.
395/// Only test *modules* are cut, so a `.route()` inside a `#[cfg(test)] fn`
396/// would be reported as untabled; none exists, and the fix is to move it into
397/// the file's `mod tests`.
398fn plain_routes() -> Vec<(String, String)> {
399 let mut out = Vec::new();
400 for (file, src) in src_files() {
401 // A `#[cfg(test)] mod … { … }` at column 0, so its closing `}` is the
402 // next column-0 `}`. Brace counting is not an option: the sources are
403 // full of `{id}` path literals and `{}` format strings.
404 let mut kept = Vec::new();
405 let mut lines = src.lines().peekable();
406 while let Some(line) = lines.next() {
407 if line == "#[cfg(test)]" && lines.peek().is_some_and(|l| l.starts_with("mod ")) {
408 for l in lines.by_ref() {
409 if l == "}" {
410 break;
411 }
412 }
413 continue;
414 }
415 kept.push(line);
416 }
417 let src = kept.join("\n");
418
419 let mut at = 0;
420 while let Some(hit) = src[at..].find(".route(") {
421 let open = at + hit + ".route".len();
422 let lit = src[open..].find('"').expect("a route path literal") + open + 1;
423 let end = src[lit..].find('"').expect("closing quote") + lit;
424 out.push((file.clone(), src[lit..end].to_string()));
425 at = open + 1;
426 }
427 }
428 out
429}
430
431/// Hazard the generated table cannot see on its own: a route registered with
432/// `.route()` carries no `#[utoipa::path]`, so it never reaches `spec["paths"]`
433/// and never becomes a row unless someone remembered [`STATIC_ROWS`]. Assert
434/// every production `.route()` is accounted for by one of the two.
435#[tokio::test]
436async fn every_plain_route_is_in_the_table() {
437 let spec = spec().await;
438 let known: Vec<String> = spec["paths"]
439 .as_object()
440 .expect("the served spec has a paths object")
441 .keys()
442 .cloned()
443 .chain(STATIC_ROWS.iter().map(|(_, p, ..)| p.to_string()))
444 .collect();
445 for (file, rel) in plain_routes() {
446 // Suffix match on the nest-relative path, the same key `handlers()`
447 // uses, so this needs no model of how `lib.rs` nests routers.
448 assert!(
449 known.iter().any(|p| p == &rel || p.ends_with(&rel)),
450 "`{file}` registers `{rel}` with a plain `.route()`, so it is in no \
451 OpenAPI path and in no STATIC_ROWS row — it would be missing from \
452 the README's endpoint table entirely. Give the handler a \
453 `#[utoipa::path]`, or (for a WebSocket/doc route the spec cannot \
454 carry) add its row to STATIC_ROWS in this file."
455 );
456 }
457}
458
459/// The other half: [`STATIC_ROWS`] is hand-written, so a row whose route was
460/// renamed or deleted would sit in the README forever. Drive the real router
461/// and let it answer. Only `404`/`405` refute existence — every one of these
462/// is authenticated or a WebSocket upgrade, so `401`/`400`/`426`/a Swagger
463/// redirect all prove the route is there.
464#[tokio::test]
465async fn every_static_row_is_really_routed() {
466 let (app, _db) = common::app_and_db().await;
467 for (method, path, ..) in STATIC_ROWS {
468 let uri = path.replace("{id}", "nosuchid");
469 let status = common::send(&app, method, &uri, None, None).await.status;
470 assert!(
471 !matches!(status.as_u16(), 404 | 405),
472 "STATIC_ROWS claims `{method} {path}`, but the built router answers \
473 {status} for `{uri}` — the route was renamed or removed and the \
474 README row is stale. Fix STATIC_ROWS in this file."
475 );
476 }
477}