serve.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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::collections::HashMap;
  29. use std::convert::Infallible;
  30. use std::sync::Arc;
  31. use std::time::Duration;
  32. /// Safety-net rescan interval: covers missed watcher notifications (a
  33. /// legacy `.log`-only report whose score lands in a Modify the filter
  34. /// ignores, a source dir created after startup). The normal path is the
  35. /// event-driven one, so this can stay slow.
  36. pub(crate) const KEEPALIVE: Duration = Duration::from_secs(30);
  37. /// Wait after a filesystem event before re-scanning, so a write burst
  38. /// (the launcher copying a report triplet) collapses into one collect.
  39. const DEBOUNCE: Duration = Duration::from_millis(500);
  40. /// Shared server state: the config (for `/r/...` and `/repo/...` file
  41. /// loads) plus the latest rows JSON (each SSE connection clones the
  42. /// receiver) plus the URL base this server is mounted under ("" for
  43. /// `report --serve`, "/recipes" when the dashboard nests it) — the viewer
  44. /// link targets carry it.
  45. #[derive(Clone)]
  46. pub(crate) struct AppState {
  47. pub(crate) config: Arc<Config>,
  48. pub(crate) data: tokio::sync::watch::Receiver<String>,
  49. pub(crate) base: String,
  50. }
  51. /// True when the event touches a report-relevant path: anything under a
  52. /// `reports/` directory, or a `recipe.toml` (row fields come from it).
  53. /// Everything else (build churn, git, the rest of the repo) is ignored so
  54. /// the watcher can watch a wide tree cheaply.
  55. fn is_relevant(ev: &notify::Event) -> bool {
  56. ev.paths.iter().any(|p| {
  57. p.ancestors()
  58. .any(|a| a.file_name().is_some_and(|n| n == "reports"))
  59. || p.file_name().is_some_and(|n| n == "recipe.toml")
  60. })
  61. }
  62. /// Background refresher — lazy by design (the web process must stay small;
  63. /// a full collect scans every recipe + report file): a full re-collect runs
  64. /// ONLY on a debounced filesystem event (or once at startup); the keepalive
  65. /// tick just re-runs the live stale cross-check (the only row field that
  66. /// changes without a file change) and only when a run is open — otherwise it
  67. /// does zero work. The cross-check rides on the main dashboard's fleet
  68. /// probe (`fleet_rx` bus State events — no extra SSH) and falls back to a
  69. /// direct probe when no bus is wired (CLI `report --serve`).
  70. pub(crate) async fn refresh_loop(
  71. cfg: Arc<Config>,
  72. tx: tokio::sync::watch::Sender<String>,
  73. keepalive: Duration,
  74. archived: bool,
  75. fleet_rx: Option<tokio::sync::broadcast::Receiver<crate::web::events::Event>>,
  76. ) {
  77. let mut fleet_rx = fleet_rx;
  78. let (ev_tx, mut ev_rx) = tokio::sync::mpsc::unbounded_channel::<()>();
  79. let watcher = notify::recommended_watcher(move |res: Result<notify::Event, notify::Error>| {
  80. if let Ok(ev) = res
  81. && is_relevant(&ev)
  82. {
  83. let _ = ev_tx.send(());
  84. }
  85. });
  86. let mut watcher = watcher.ok();
  87. if let Some(w) = &mut watcher {
  88. for dir in crate::config::watchable_recipe_dirs(&cfg) {
  89. let _ = w.watch(&dir, notify::RecursiveMode::Recursive);
  90. }
  91. }
  92. let mut last = String::new();
  93. let mut rows: Vec<crate::report::ReportRow> = Vec::new();
  94. let mut fleet: Option<crate::web::events::Snapshot> = None;
  95. let cluster_nodes: HashMap<String, Vec<String>> = cfg
  96. .clusters
  97. .iter()
  98. .map(|c| {
  99. (
  100. c.name.clone(),
  101. c.nodes.iter().map(|n| n.name.clone()).collect(),
  102. )
  103. })
  104. .collect();
  105. let has_open_run = |rows: &[crate::report::ReportRow]| {
  106. rows.iter()
  107. .any(|r| r.up.is_some() && r.up_cluster.is_some())
  108. };
  109. loop {
  110. tokio::select! {
  111. // Filesystem event (debounced) → the only full-rescan trigger.
  112. _ = ev_rx.recv() => {
  113. // debounce: let the burst settle, then drain the remaining events
  114. tokio::time::sleep(DEBOUNCE).await;
  115. while ev_rx.try_recv().is_ok() {}
  116. rows = collect(&cfg, archived);
  117. cross_check(&cfg, &mut rows, &cluster_nodes, &mut fleet).await;
  118. let json = serde_json::to_string(&rows).unwrap_or_default();
  119. if json != last {
  120. last = json;
  121. let _ = tx.send(last.clone());
  122. }
  123. }
  124. // Bus State event (the main dashboard's 30 s fleet probe) →
  125. // just track the fleet; the keepalive tick consumes it.
  126. ev = async {
  127. match fleet_rx.as_mut() {
  128. Some(rx) => rx.recv().await,
  129. None => std::future::pending::<Result<
  130. crate::web::events::Event,
  131. tokio::sync::broadcast::error::RecvError,
  132. > >().await,
  133. }
  134. } => {
  135. if let Ok(crate::web::events::Event::State { snapshot, .. }) = ev {
  136. fleet = Some(snapshot);
  137. }
  138. }
  139. // Keepalive safety net (missed watcher events): full collect only
  140. // while uncollected (startup); afterwards only the cheap
  141. // cross-check — and only when a run is open.
  142. _ = tokio::time::sleep(keepalive) => {
  143. if rows.is_empty() {
  144. rows = collect(&cfg, archived);
  145. cross_check(&cfg, &mut rows, &cluster_nodes, &mut fleet).await;
  146. } else if has_open_run(&rows) {
  147. cross_check(&cfg, &mut rows, &cluster_nodes, &mut fleet).await;
  148. } else {
  149. continue; // nothing to do — zero work, zero allocation
  150. }
  151. let json = serde_json::to_string(&rows).unwrap_or_default();
  152. if json != last {
  153. last = json;
  154. let _ = tx.send(last.clone());
  155. }
  156. }
  157. }
  158. }
  159. }
  160. /// Reconcile the open-ledger rows against the live fleet: prefer the main
  161. /// dashboard's last fleet snapshot (no extra SSH); probe directly only when
  162. /// no snapshot has arrived yet (CLI `report --serve`, first 30 s of web).
  163. async fn cross_check(
  164. cfg: &Config,
  165. rows: &mut [crate::report::ReportRow],
  166. cluster_nodes: &HashMap<String, Vec<String>>,
  167. fleet: &mut Option<crate::web::events::Snapshot>,
  168. ) {
  169. let (reachable, live) = match fleet {
  170. Some(snap) => {
  171. let mut reachable: HashMap<String, bool> = HashMap::new();
  172. let mut live: std::collections::HashSet<String> = std::collections::HashSet::new();
  173. for c in &snap.clusters {
  174. for n in &c.nodes {
  175. reachable.insert(n.name.clone(), n.reachable);
  176. for ct in &n.containers {
  177. live.insert(ct.recipe.clone());
  178. }
  179. }
  180. }
  181. (reachable, live)
  182. }
  183. None => {
  184. let f = crate::web::probe::probe(cfg).await;
  185. let mut reachable: HashMap<String, bool> = HashMap::new();
  186. let mut live: std::collections::HashSet<String> = std::collections::HashSet::new();
  187. for (node, st) in &f.nodes {
  188. reachable.insert(node.clone(), st.reachable);
  189. for c in &st.containers {
  190. live.insert(c.recipe.clone());
  191. }
  192. }
  193. (reachable, live)
  194. }
  195. };
  196. crate::report::stale::mark_stale(rows, cluster_nodes, &reachable, &live);
  197. }
  198. /// `GET /events` — the latest rows JSON on connect, then one message per
  199. /// refresher update. The stream ends when the refresher (the sender) drops.
  200. async fn events_stream(
  201. axum::extract::State(s): axum::extract::State<AppState>,
  202. ) -> Sse<impl Stream<Item = Result<SseEvent, Infallible>>> {
  203. let mut rx = s.data;
  204. let first = rx.borrow_and_update().clone();
  205. let first = futures::stream::once(async move { Ok(SseEvent::default().data(first)) });
  206. let rest = futures::stream::unfold(rx, |mut rx| async move {
  207. if rx.changed().await.is_err() {
  208. return None;
  209. }
  210. let json = rx.borrow_and_update().clone();
  211. Some((Ok(SseEvent::default().data(json)), rx))
  212. });
  213. Sse::new(first.chain(rest))
  214. // the rows only change when a bench report changes — a silent
  215. // stream would be indistinguishable from a dead one for anything
  216. // between the server and the browser
  217. .keep_alive(axum::response::sse::KeepAlive::new().interval(Duration::from_secs(15)))
  218. }
  219. /// `GET /r/<recipe>/<file>` — full file text (report, log, json, or the
  220. /// recipe's own `recipe.toml`) served through the viewer page. Both path
  221. /// parts must be plain names (no traversal); the resolve walks every
  222. /// recipe dir, so stay strict.
  223. pub(crate) fn load_report(config: &Config, recipe: &str, file: &str) -> Option<String> {
  224. let plain = |s: &str| {
  225. !s.contains("..")
  226. && s.chars()
  227. .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
  228. };
  229. if !plain(recipe) || !plain(file) {
  230. return None;
  231. }
  232. crate::config::recipe_dirs(config)
  233. .into_iter()
  234. .find_map(|dir| {
  235. let base = dir.join(recipe);
  236. // "recipe.toml" resolves from the recipe dir root, everything
  237. // else from its reports/ subdir
  238. let p = if file == "recipe.toml" {
  239. base.join("recipe.toml")
  240. } else {
  241. base.join("reports").join(file)
  242. };
  243. p.is_file()
  244. .then(|| std::fs::read_to_string(p).ok())
  245. .flatten()
  246. })
  247. }
  248. /// Braille spinner frame or progress bar — llama-benchy's rich in-place
  249. /// progress redraws.
  250. fn is_spinner_frame(line: &str) -> bool {
  251. let t = line.trim_start();
  252. t.starts_with(['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']) || t.contains('━')
  253. }
  254. /// Progress-redraw identity: the spinner frames differ only by the glyph,
  255. /// the elapsed clock and the run/progress counters — same key = same phase
  256. /// redrawn in place.
  257. fn progress_key(line: &str) -> String {
  258. line.split_whitespace()
  259. .filter(|t| {
  260. // keep only wordish tokens (the test name): bars — the tip glyph
  261. // varies as the bar advances (━╸╺…) — spinner glyphs, @ signs and
  262. // other graphics carry no alphanumerics; counters (0/18), elapsed
  263. // clocks (0:01:48) and the "run N" pair are progress churn.
  264. t.chars().any(|c| c.is_alphanumeric())
  265. && !t.chars().all(|c| c.is_ascii_digit() || c == '/')
  266. && !t.contains(':')
  267. && *t != "run"
  268. })
  269. .collect::<Vec<_>>()
  270. .join(" ")
  271. }
  272. /// Make old pty-captured bench logs read like the new ones: drop pty
  273. /// control-char artifacts (`^D`/backspace echoes), collapse each spinner
  274. /// phase's redraw run down to its last frame, drop consecutive duplicate
  275. /// lines. Idempotent on logs that are already clean.
  276. pub(crate) fn clean_log(content: &str) -> String {
  277. let lines: Vec<String> = content
  278. .lines()
  279. .map(|l| {
  280. let l: String = l
  281. .chars()
  282. .filter(|c| !matches!(c, '\u{4}' | '\u{8}'))
  283. .collect();
  284. // the pty echoes control chars as caret notation (^D, ^H) —
  285. // printable '^' + @.._ pairs at the line start
  286. let mut l = l.as_str();
  287. while l.starts_with('^')
  288. && l[1..]
  289. .chars()
  290. .next()
  291. .is_some_and(|c| ('@'..='_').contains(&c))
  292. {
  293. l = &l[2..];
  294. }
  295. l.to_string()
  296. })
  297. .collect();
  298. let mut keep = vec![true; lines.len()];
  299. let mut i = 0;
  300. while i < lines.len() {
  301. let prog = is_spinner_frame(&lines[i]);
  302. let key = if prog {
  303. progress_key(&lines[i])
  304. } else {
  305. String::new()
  306. };
  307. let mut j = i + 1;
  308. while j < lines.len() {
  309. let same = if prog {
  310. is_spinner_frame(&lines[j]) && progress_key(&lines[j]) == key
  311. } else {
  312. !lines[i].is_empty() && lines[j] == lines[i]
  313. };
  314. if !same {
  315. break;
  316. }
  317. keep[j] = false;
  318. j += 1;
  319. }
  320. if j > i + 1 && prog {
  321. // a redraw run keeps only its final frame (exact dups keep the first)
  322. keep[i] = false;
  323. keep[j - 1] = true;
  324. }
  325. i = j;
  326. }
  327. lines
  328. .iter()
  329. .enumerate()
  330. .filter(|(k, _)| keep[*k])
  331. .map(|(_, l)| l.as_str())
  332. .collect::<Vec<_>>()
  333. .join("\n")
  334. }
  335. /// `GET /r/<recipe>/<file>` with `?follow=1` — SSE stream of a `.log`
  336. /// report file, updated as the file grows (the bench-log follow). The first
  337. /// message carries the full cleaned content (the client's baseline); each
  338. /// subsequent message carries only the appended tail (the delta since the
  339. /// last poll). The client appends deltas to its baseline. The stream polls
  340. /// the file every 2 s and ends when the client disconnects. Non-`.log`
  341. /// files and a missing `?follow=1` fall through to the static `report_file`.
  342. async fn report_file_or_stream(
  343. axum::extract::State(state): axum::extract::State<AppState>,
  344. axum::extract::Path((recipe, file)): Path<(String, String)>,
  345. axum::extract::Query(params): axum::extract::Query<std::collections::HashMap<String, String>>,
  346. ) -> axum::response::Response {
  347. use axum::response::IntoResponse;
  348. let follow = params.get("follow").is_some_and(|s| s == "1");
  349. if !follow || !file.ends_with(".log") {
  350. return report_file(state, Path((recipe, file))).await;
  351. }
  352. let config = state.config.clone();
  353. type SseRes = Result<SseEvent, std::convert::Infallible>;
  354. let stream = futures::stream::unfold(
  355. (config, recipe, file, 0usize),
  356. |mut st: (Arc<Config>, String, String, usize)| async move {
  357. let (cfg, recipe, file, last_len) = &mut st;
  358. if let Some(content) = load_report(cfg, recipe, file) {
  359. let clean = crate::ansi::strip_ansi(content.as_bytes());
  360. let clean = String::from_utf8_lossy(&clean)
  361. .replace("\r\n", "\n")
  362. .replace('\r', "\n");
  363. let clean = clean_log(&clean);
  364. if clean.len() > *last_len {
  365. let delta = clean.split_at(*last_len).1.to_string();
  366. *last_len = clean.len();
  367. return Some((
  368. Ok(SseEvent::default().data(delta)) as SseRes,
  369. (cfg.clone(), recipe.clone(), file.clone(), *last_len),
  370. ));
  371. }
  372. }
  373. tokio::time::sleep(Duration::from_secs(2)).await;
  374. Some((
  375. Ok(SseEvent::default().comment("keepalive")) as SseRes,
  376. (cfg.clone(), recipe.clone(), file.clone(), *last_len),
  377. ))
  378. },
  379. );
  380. Sse::new(stream)
  381. .keep_alive(axum::response::sse::KeepAlive::new().interval(Duration::from_secs(15)))
  382. .into_response()
  383. }
  384. /// `GET /r/<recipe>/<file>` — file viewer page: rendered markdown (with a
  385. /// raw toggle), syntax-highlighted TOML/JSON, plain logs.
  386. pub(crate) const VIEW_TEMPLATE: &str = include_str!("view.html");
  387. async fn report_file(
  388. state: AppState,
  389. axum::extract::Path((recipe, file)): Path<(String, String)>,
  390. ) -> Response {
  391. use axum::http::StatusCode;
  392. use axum::response::IntoResponse;
  393. match load_report(&state.config, &recipe, &file) {
  394. Some(text) => {
  395. // Strip ANSI escapes (old logs were saved raw; new ones are
  396. // already clean) and normalize line ends: the old pty-saved
  397. // logs carry CRLF (ONLCR) and the Live-soup ones bare \r —
  398. // CRLF first, then lone \r, so nothing doubles.
  399. let clean = crate::ansi::strip_ansi(text.as_bytes());
  400. let clean = String::from_utf8_lossy(&clean)
  401. .replace("\r\n", "\n")
  402. .replace('\r', "\n");
  403. // old pty-captured logs carry spinner-redraw soup and pty
  404. // control-char artifacts — render them like the clean ones
  405. let clean = if file.ends_with(".log") {
  406. clean_log(&clean)
  407. } else {
  408. clean
  409. };
  410. let links = if file == "recipe.toml" {
  411. super::repo::toml_links(&clean, &recipe, &state.base)
  412. } else {
  413. Vec::new()
  414. };
  415. let meta = serde_json::json!({ "recipe": recipe, "file": file, "content": clean, "links": links });
  416. let meta = serde_json::to_string(&meta)
  417. .unwrap_or_default()
  418. .replace('<', "\\u003c");
  419. axum::response::Html(VIEW_TEMPLATE.replace("{{META}}", &meta)).into_response()
  420. }
  421. None => (
  422. StatusCode::NOT_FOUND,
  423. axum::response::Html(
  424. "<!doctype html><meta charset=\"utf-8\"><title>404</title>report not found"
  425. .to_string(),
  426. ),
  427. )
  428. .into_response(),
  429. }
  430. }
  431. /// Build the report server router: static page at `/`, live SSE at
  432. /// `/events`, full report text at `/r/<recipe>/<file>`. `initial` is the
  433. /// rows JSON snapshot used to seed the watch channel (from the same
  434. /// `collect` that rendered the page, so the first paint and the first SSE
  435. /// message agree).
  436. pub(crate) fn router(
  437. config: Arc<Config>,
  438. page: String,
  439. initial: String,
  440. archived: bool,
  441. base: &str,
  442. fleet_rx: Option<tokio::sync::broadcast::Receiver<crate::web::events::Event>>,
  443. ) -> Router {
  444. let (tx, rx) = tokio::sync::watch::channel(initial);
  445. tokio::spawn(refresh_loop(
  446. config.clone(),
  447. tx,
  448. KEEPALIVE,
  449. archived,
  450. fleet_rx,
  451. ));
  452. Router::new()
  453. .route(
  454. "/",
  455. get(move || {
  456. let page = page.clone();
  457. async move { axum::response::Html(page) }
  458. }),
  459. )
  460. .route("/events", get(events_stream))
  461. .route("/r/{recipe}/{file}", get(report_file_or_stream))
  462. .route("/repo/{*path}", get(super::repo::repo_route))
  463. .with_state(AppState {
  464. config,
  465. data: rx,
  466. base: base.to_string(),
  467. })
  468. }