serve.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. //! Live-update plumbing for `report --serve`: a background refresher that
  2. //! re-scans the recipe `reports/` dirs when the file system says something
  3. //! changed, and an SSE endpoint (`/events`) that pushes the rows JSON to the
  4. //! page whenever the scan result differs (a new report file, a bench
  5. //! finishing, a log growing).
  6. //!
  7. //! The refresher is event-driven, not a fixed poll: a `notify` watcher
  8. //! (FSEvents on macOS, inotify on Linux) over the recipe dirs feeds an mpsc
  9. //! channel; after a short debounce burst the rows are re-collected and
  10. //! published on the `watch` channel only when the serialization changed.
  11. //! Filesystem events are filtered to the report-relevant paths (anything
  12. //! under a `reports/` dir, or a `recipe.toml`), so build churn elsewhere in
  13. //! the repo is ignored. A slow keepalive scan stays as a safety net for
  14. //! missed notifications (legacy log-only reports, dirs created late).
  15. //!
  16. //! One refresher serves all clients: each SSE connection forwards its own
  17. //! `watch::Receiver`.
  18. use crate::config::Config;
  19. use crate::report::collect;
  20. use axum::{
  21. Router,
  22. extract::Path,
  23. response::{Response, Sse, sse::Event as SseEvent},
  24. routing::get,
  25. };
  26. use futures::{Stream, StreamExt};
  27. use notify::Watcher;
  28. use std::convert::Infallible;
  29. use std::sync::Arc;
  30. use std::time::Duration;
  31. /// Safety-net rescan interval: covers missed watcher notifications (a
  32. /// legacy `.log`-only report whose score lands in a Modify the filter
  33. /// ignores, a source dir created after startup). The normal path is the
  34. /// event-driven one, so this can stay slow.
  35. pub(crate) const KEEPALIVE: Duration = Duration::from_secs(30);
  36. /// Wait after a filesystem event before re-scanning, so a write burst
  37. /// (the launcher copying a report triplet) collapses into one collect.
  38. const DEBOUNCE: Duration = Duration::from_millis(500);
  39. /// Shared server state: the config (for `/r/...` file loads) plus the
  40. /// latest rows JSON (each SSE connection clones the receiver).
  41. #[derive(Clone)]
  42. pub(crate) struct AppState {
  43. pub(crate) config: Arc<Config>,
  44. pub(crate) data: tokio::sync::watch::Receiver<String>,
  45. }
  46. /// True when the event touches a report-relevant path: anything under a
  47. /// `reports/` directory, or a `recipe.toml` (row fields come from it).
  48. /// Everything else (build churn, git, the rest of the repo) is ignored so
  49. /// the watcher can watch a wide tree cheaply.
  50. fn is_relevant(ev: &notify::Event) -> bool {
  51. ev.paths.iter().any(|p| {
  52. p.ancestors()
  53. .any(|a| a.file_name().is_some_and(|n| n == "reports"))
  54. || p.file_name().is_some_and(|n| n == "recipe.toml")
  55. })
  56. }
  57. /// Background refresher: watch the recipe dirs, re-collect after a debounced
  58. /// filesystem event (or the keepalive safety net), publish the rows JSON on
  59. /// the watch channel only when it changed. The first collect runs
  60. /// immediately so clients see current data without waiting. If the watcher
  61. /// cannot be created (unsupported FS), the keepalive alone keeps the data
  62. /// fresh.
  63. pub(crate) async fn refresh_loop(
  64. cfg: Arc<Config>,
  65. tx: tokio::sync::watch::Sender<String>,
  66. keepalive: Duration,
  67. archived: bool,
  68. ) {
  69. let (ev_tx, mut ev_rx) = tokio::sync::mpsc::unbounded_channel::<()>();
  70. let watcher = notify::recommended_watcher(move |res: Result<notify::Event, notify::Error>| {
  71. if let Ok(ev) = res
  72. && is_relevant(&ev)
  73. {
  74. let _ = ev_tx.send(());
  75. }
  76. });
  77. let mut watcher = watcher.ok();
  78. if let Some(w) = &mut watcher {
  79. for dir in crate::config::recipe_dirs(&cfg) {
  80. if dir.is_dir() {
  81. let _ = w.watch(&dir, notify::RecursiveMode::Recursive);
  82. }
  83. }
  84. }
  85. let mut last = String::new();
  86. loop {
  87. tokio::select! {
  88. _ = ev_rx.recv() => {}
  89. _ = tokio::time::sleep(keepalive) => {}
  90. }
  91. // debounce: let the burst settle, then drain the remaining events
  92. tokio::time::sleep(DEBOUNCE).await;
  93. while ev_rx.try_recv().is_ok() {}
  94. let json = serde_json::to_string(&collect(&cfg, archived)).unwrap_or_default();
  95. if json != last {
  96. last = json;
  97. let _ = tx.send(last.clone());
  98. }
  99. }
  100. }
  101. /// `GET /events` — the latest rows JSON on connect, then one message per
  102. /// refresher update. The stream ends when the refresher (the sender) drops.
  103. async fn events_stream(
  104. axum::extract::State(s): axum::extract::State<AppState>,
  105. ) -> Sse<impl Stream<Item = Result<SseEvent, Infallible>>> {
  106. let mut rx = s.data;
  107. let first = rx.borrow_and_update().clone();
  108. let first = futures::stream::once(async move { Ok(SseEvent::default().data(first)) });
  109. let rest = futures::stream::unfold(rx, |mut rx| async move {
  110. if rx.changed().await.is_err() {
  111. return None;
  112. }
  113. let json = rx.borrow_and_update().clone();
  114. Some((Ok(SseEvent::default().data(json)), rx))
  115. });
  116. Sse::new(first.chain(rest))
  117. }
  118. /// `GET /r/<recipe>/<file>` — full file text (report, log, json, or the
  119. /// recipe's own `recipe.toml`) served through the viewer page. Both path
  120. /// parts must be plain names (no traversal); the resolve walks every
  121. /// recipe dir, so stay strict.
  122. pub(crate) fn load_report(config: &Config, recipe: &str, file: &str) -> Option<String> {
  123. let plain = |s: &str| {
  124. !s.contains("..")
  125. && s.chars()
  126. .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
  127. };
  128. if !plain(recipe) || !plain(file) {
  129. return None;
  130. }
  131. crate::config::recipe_dirs(config)
  132. .into_iter()
  133. .find_map(|dir| {
  134. let base = dir.join(recipe);
  135. // "recipe.toml" resolves from the recipe dir root, everything
  136. // else from its reports/ subdir
  137. let p = if file == "recipe.toml" {
  138. base.join("recipe.toml")
  139. } else {
  140. base.join("reports").join(file)
  141. };
  142. p.is_file()
  143. .then(|| std::fs::read_to_string(p).ok())
  144. .flatten()
  145. })
  146. }
  147. /// Braille spinner frame or progress bar — llama-benchy's rich in-place
  148. /// progress redraws.
  149. fn is_spinner_frame(line: &str) -> bool {
  150. let t = line.trim_start();
  151. t.starts_with(['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']) || t.contains('━')
  152. }
  153. /// Progress-redraw identity: the spinner frames differ only by the glyph,
  154. /// the elapsed clock and the run/progress counters — same key = same phase
  155. /// redrawn in place.
  156. fn progress_key(line: &str) -> String {
  157. line.split_whitespace()
  158. .filter(|t| {
  159. // keep only wordish tokens (the test name): bars — the tip glyph
  160. // varies as the bar advances (━╸╺…) — spinner glyphs, @ signs and
  161. // other graphics carry no alphanumerics; counters (0/18), elapsed
  162. // clocks (0:01:48) and the "run N" pair are progress churn.
  163. t.chars().any(|c| c.is_alphanumeric())
  164. && !t.chars().all(|c| c.is_ascii_digit() || c == '/')
  165. && !t.contains(':')
  166. && *t != "run"
  167. })
  168. .collect::<Vec<_>>()
  169. .join(" ")
  170. }
  171. /// Make old pty-captured bench logs read like the new ones: drop pty
  172. /// control-char artifacts (`^D`/backspace echoes), collapse each spinner
  173. /// phase's redraw run down to its last frame, drop consecutive duplicate
  174. /// lines. Idempotent on logs that are already clean.
  175. pub(crate) fn clean_log(content: &str) -> String {
  176. let lines: Vec<String> = content
  177. .lines()
  178. .map(|l| {
  179. let l: String = l
  180. .chars()
  181. .filter(|c| !matches!(c, '\u{4}' | '\u{8}'))
  182. .collect();
  183. // the pty echoes control chars as caret notation (^D, ^H) —
  184. // printable '^' + @.._ pairs at the line start
  185. let mut l = l.as_str();
  186. while l.starts_with('^')
  187. && l[1..]
  188. .chars()
  189. .next()
  190. .is_some_and(|c| ('@'..='_').contains(&c))
  191. {
  192. l = &l[2..];
  193. }
  194. l.to_string()
  195. })
  196. .collect();
  197. let mut keep = vec![true; lines.len()];
  198. let mut i = 0;
  199. while i < lines.len() {
  200. let prog = is_spinner_frame(&lines[i]);
  201. let key = if prog {
  202. progress_key(&lines[i])
  203. } else {
  204. String::new()
  205. };
  206. let mut j = i + 1;
  207. while j < lines.len() {
  208. let same = if prog {
  209. is_spinner_frame(&lines[j]) && progress_key(&lines[j]) == key
  210. } else {
  211. !lines[i].is_empty() && lines[j] == lines[i]
  212. };
  213. if !same {
  214. break;
  215. }
  216. keep[j] = false;
  217. j += 1;
  218. }
  219. if j > i + 1 && prog {
  220. // a redraw run keeps only its final frame (exact dups keep the first)
  221. keep[i] = false;
  222. keep[j - 1] = true;
  223. }
  224. i = j;
  225. }
  226. lines
  227. .iter()
  228. .enumerate()
  229. .filter(|(k, _)| keep[*k])
  230. .map(|(_, l)| l.as_str())
  231. .collect::<Vec<_>>()
  232. .join("\n")
  233. }
  234. /// `GET /r/<recipe>/<file>` — file viewer page: rendered markdown (with a
  235. /// raw toggle), syntax-highlighted TOML/JSON, plain logs.
  236. const VIEW_TEMPLATE: &str = include_str!("view.html");
  237. async fn report_file(
  238. axum::extract::State(state): axum::extract::State<AppState>,
  239. axum::extract::Path((recipe, file)): Path<(String, String)>,
  240. ) -> Response {
  241. use axum::http::StatusCode;
  242. use axum::response::IntoResponse;
  243. match load_report(&state.config, &recipe, &file) {
  244. Some(text) => {
  245. // Strip ANSI escapes (old logs were saved raw; new ones are
  246. // already clean) and normalize line ends: the old pty-saved
  247. // logs carry CRLF (ONLCR) and the Live-soup ones bare \r —
  248. // CRLF first, then lone \r, so nothing doubles.
  249. let clean = crate::ansi::strip_ansi(text.as_bytes());
  250. let clean = String::from_utf8_lossy(&clean)
  251. .replace("\r\n", "\n")
  252. .replace('\r', "\n");
  253. // old pty-captured logs carry spinner-redraw soup and pty
  254. // control-char artifacts — render them like the clean ones
  255. let clean = if file.ends_with(".log") {
  256. clean_log(&clean)
  257. } else {
  258. clean
  259. };
  260. let meta = serde_json::json!({ "recipe": recipe, "file": file, "content": clean });
  261. let meta = serde_json::to_string(&meta)
  262. .unwrap_or_default()
  263. .replace('<', "\\u003c");
  264. axum::response::Html(VIEW_TEMPLATE.replace("{{META}}", &meta)).into_response()
  265. }
  266. None => (
  267. StatusCode::NOT_FOUND,
  268. axum::response::Html(
  269. "<!doctype html><meta charset=\"utf-8\"><title>404</title>report not found"
  270. .to_string(),
  271. ),
  272. )
  273. .into_response(),
  274. }
  275. }
  276. /// Build the report server router: static page at `/`, live SSE at
  277. /// `/events`, full report text at `/r/<recipe>/<file>`. `initial` is the
  278. /// rows JSON snapshot used to seed the watch channel (from the same
  279. /// `collect` that rendered the page, so the first paint and the first SSE
  280. /// message agree).
  281. pub(crate) fn router(config: Arc<Config>, page: String, initial: String, archived: bool) -> Router {
  282. let (tx, rx) = tokio::sync::watch::channel(initial);
  283. tokio::spawn(refresh_loop(config.clone(), tx, KEEPALIVE, archived));
  284. Router::new()
  285. .route(
  286. "/",
  287. get(move || {
  288. let page = page.clone();
  289. async move { axum::response::Html(page) }
  290. }),
  291. )
  292. .route("/events", get(events_stream))
  293. .route("/r/{recipe}/{file}", get(report_file))
  294. .with_state(AppState { config, data: rx })
  295. }