serve.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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. // The inverse direction: a container in the fleet with NO local ledger
  198. // run (the add-on machine) still renders as running.
  199. crate::report::stale::mark_fleet_up(rows, &live);
  200. }
  201. /// `GET /events` — the latest rows JSON on connect, then one message per
  202. /// refresher update. The stream ends when the refresher (the sender) drops.
  203. async fn events_stream(
  204. axum::extract::State(s): axum::extract::State<AppState>,
  205. ) -> Sse<impl Stream<Item = Result<SseEvent, Infallible>>> {
  206. let mut rx = s.data;
  207. let first = rx.borrow_and_update().clone();
  208. let first = futures::stream::once(async move { Ok(SseEvent::default().data(first)) });
  209. let rest = futures::stream::unfold(rx, |mut rx| async move {
  210. if rx.changed().await.is_err() {
  211. return None;
  212. }
  213. let json = rx.borrow_and_update().clone();
  214. Some((Ok(SseEvent::default().data(json)), rx))
  215. });
  216. Sse::new(first.chain(rest))
  217. // the rows only change when a bench report changes — a silent
  218. // stream would be indistinguishable from a dead one for anything
  219. // between the server and the browser
  220. .keep_alive(axum::response::sse::KeepAlive::new().interval(Duration::from_secs(15)))
  221. }
  222. /// `GET /r/<recipe>/<file>` — full file text (report, log, json, or the
  223. /// recipe's own `recipe.toml`) served through the viewer page. Both path
  224. /// parts must be plain names (no traversal); the resolve walks every
  225. /// recipe dir, so stay strict.
  226. pub(crate) fn load_report(config: &Config, recipe: &str, file: &str) -> Option<String> {
  227. let plain = |s: &str| {
  228. !s.contains("..")
  229. && s.chars()
  230. .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
  231. };
  232. if !plain(recipe) || !plain(file) {
  233. return None;
  234. }
  235. crate::config::recipe_dirs(config)
  236. .into_iter()
  237. .find_map(|dir| {
  238. let base = dir.join(recipe);
  239. // "recipe.toml" resolves from the recipe dir root, everything
  240. // else from its reports/ subdir
  241. let p = if file == "recipe.toml" {
  242. base.join("recipe.toml")
  243. } else {
  244. base.join("reports").join(file)
  245. };
  246. p.is_file()
  247. .then(|| std::fs::read_to_string(p).ok())
  248. .flatten()
  249. })
  250. }
  251. /// Braille spinner frame or progress bar — llama-benchy's rich in-place
  252. /// progress redraws.
  253. fn is_spinner_frame(line: &str) -> bool {
  254. let t = line.trim_start();
  255. t.starts_with(['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']) || t.contains('━')
  256. }
  257. /// Progress-redraw identity: the spinner frames differ only by the glyph,
  258. /// the elapsed clock and the run/progress counters — same key = same phase
  259. /// redrawn in place.
  260. fn progress_key(line: &str) -> String {
  261. line.split_whitespace()
  262. .filter(|t| {
  263. // keep only wordish tokens (the test name): bars — the tip glyph
  264. // varies as the bar advances (━╸╺…) — spinner glyphs, @ signs and
  265. // other graphics carry no alphanumerics; counters (0/18), elapsed
  266. // clocks (0:01:48) and the "run N" pair are progress churn.
  267. t.chars().any(|c| c.is_alphanumeric())
  268. && !t.chars().all(|c| c.is_ascii_digit() || c == '/')
  269. && !t.contains(':')
  270. && *t != "run"
  271. })
  272. .collect::<Vec<_>>()
  273. .join(" ")
  274. }
  275. /// Make old pty-captured bench logs read like the new ones: drop pty
  276. /// control-char artifacts (`^D`/backspace echoes), collapse each spinner
  277. /// phase's redraw run down to its last frame, drop consecutive duplicate
  278. /// lines. Idempotent on logs that are already clean.
  279. pub(crate) fn clean_log(content: &str) -> String {
  280. let lines: Vec<String> = content
  281. .lines()
  282. .map(|l| {
  283. let l: String = l
  284. .chars()
  285. .filter(|c| !matches!(c, '\u{4}' | '\u{8}'))
  286. .collect();
  287. // the pty echoes control chars as caret notation (^D, ^H) —
  288. // printable '^' + @.._ pairs at the line start
  289. let mut l = l.as_str();
  290. while l.starts_with('^')
  291. && l[1..]
  292. .chars()
  293. .next()
  294. .is_some_and(|c| ('@'..='_').contains(&c))
  295. {
  296. l = &l[2..];
  297. }
  298. l.to_string()
  299. })
  300. .collect();
  301. let mut keep = vec![true; lines.len()];
  302. let mut i = 0;
  303. while i < lines.len() {
  304. let prog = is_spinner_frame(&lines[i]);
  305. let key = if prog {
  306. progress_key(&lines[i])
  307. } else {
  308. String::new()
  309. };
  310. let mut j = i + 1;
  311. while j < lines.len() {
  312. let same = if prog {
  313. is_spinner_frame(&lines[j]) && progress_key(&lines[j]) == key
  314. } else {
  315. !lines[i].is_empty() && lines[j] == lines[i]
  316. };
  317. if !same {
  318. break;
  319. }
  320. keep[j] = false;
  321. j += 1;
  322. }
  323. if j > i + 1 && prog {
  324. // a redraw run keeps only its final frame (exact dups keep the first)
  325. keep[i] = false;
  326. keep[j - 1] = true;
  327. }
  328. i = j;
  329. }
  330. lines
  331. .iter()
  332. .enumerate()
  333. .filter(|(k, _)| keep[*k])
  334. .map(|(_, l)| l.as_str())
  335. .collect::<Vec<_>>()
  336. .join("\n")
  337. }
  338. /// `GET /r/<recipe>/<file>` with `?follow=1` — SSE stream of a `.log`
  339. /// report file, updated as the file grows (the bench-log follow). The first
  340. /// message carries the full cleaned content (the client's baseline); each
  341. /// subsequent message carries only the appended tail (the delta since the
  342. /// last poll). The client appends deltas to its baseline. The stream polls
  343. /// the file every 2 s and ends when the client disconnects. Non-`.log`
  344. /// files and a missing `?follow=1` fall through to the static `report_file`.
  345. async fn report_file_or_stream(
  346. axum::extract::State(state): axum::extract::State<AppState>,
  347. axum::extract::Path((recipe, file)): Path<(String, String)>,
  348. axum::extract::Query(params): axum::extract::Query<std::collections::HashMap<String, String>>,
  349. ) -> axum::response::Response {
  350. use axum::response::IntoResponse;
  351. let follow = params.get("follow").is_some_and(|s| s == "1");
  352. if !follow || !file.ends_with(".log") {
  353. return report_file(state, Path((recipe, file))).await;
  354. }
  355. let config = state.config.clone();
  356. type SseRes = Result<SseEvent, std::convert::Infallible>;
  357. let stream = futures::stream::unfold(
  358. (config, recipe, file, 0usize),
  359. |mut st: (Arc<Config>, String, String, usize)| async move {
  360. let (cfg, recipe, file, last_len) = &mut st;
  361. if let Some(content) = load_report(cfg, recipe, file) {
  362. let clean = crate::ansi::strip_ansi(content.as_bytes());
  363. let clean = String::from_utf8_lossy(&clean)
  364. .replace("\r\n", "\n")
  365. .replace('\r', "\n");
  366. let clean = clean_log(&clean);
  367. if clean.len() > *last_len {
  368. let delta = clean.split_at(*last_len).1.to_string();
  369. *last_len = clean.len();
  370. return Some((
  371. Ok(SseEvent::default().data(delta)) as SseRes,
  372. (cfg.clone(), recipe.clone(), file.clone(), *last_len),
  373. ));
  374. }
  375. }
  376. tokio::time::sleep(Duration::from_secs(2)).await;
  377. Some((
  378. Ok(SseEvent::default().comment("keepalive")) as SseRes,
  379. (cfg.clone(), recipe.clone(), file.clone(), *last_len),
  380. ))
  381. },
  382. );
  383. Sse::new(stream)
  384. .keep_alive(axum::response::sse::KeepAlive::new().interval(Duration::from_secs(15)))
  385. .into_response()
  386. }
  387. /// `GET /r/<recipe>/<file>` — file viewer page: rendered markdown (with a
  388. /// raw toggle), syntax-highlighted TOML/JSON, plain logs.
  389. pub(crate) const VIEW_TEMPLATE: &str = include_str!("view.html");
  390. async fn report_file(
  391. state: AppState,
  392. axum::extract::Path((recipe, file)): Path<(String, String)>,
  393. ) -> Response {
  394. use axum::http::StatusCode;
  395. use axum::response::IntoResponse;
  396. match load_report(&state.config, &recipe, &file) {
  397. Some(text) => {
  398. // Strip ANSI escapes (old logs were saved raw; new ones are
  399. // already clean) and normalize line ends: the old pty-saved
  400. // logs carry CRLF (ONLCR) and the Live-soup ones bare \r —
  401. // CRLF first, then lone \r, so nothing doubles.
  402. let clean = crate::ansi::strip_ansi(text.as_bytes());
  403. let clean = String::from_utf8_lossy(&clean)
  404. .replace("\r\n", "\n")
  405. .replace('\r', "\n");
  406. // old pty-captured logs carry spinner-redraw soup and pty
  407. // control-char artifacts — render them like the clean ones
  408. let clean = if file.ends_with(".log") {
  409. clean_log(&clean)
  410. } else {
  411. clean
  412. };
  413. let links = if file == "recipe.toml" {
  414. super::repo::toml_links(&clean, &recipe, &state.base)
  415. } else {
  416. Vec::new()
  417. };
  418. let meta = serde_json::json!({ "recipe": recipe, "file": file, "content": clean, "links": links, "base": state.base });
  419. let meta = serde_json::to_string(&meta)
  420. .unwrap_or_default()
  421. .replace('<', "\\u003c");
  422. axum::response::Html(VIEW_TEMPLATE.replace("{{META}}", &meta)).into_response()
  423. }
  424. None => (
  425. StatusCode::NOT_FOUND,
  426. axum::response::Html(
  427. "<!doctype html><meta charset=\"utf-8\"><title>404</title>report not found"
  428. .to_string(),
  429. ),
  430. )
  431. .into_response(),
  432. }
  433. }
  434. /// Build the report server router: static page at `/`, live SSE at
  435. /// `/events`, full report text at `/r/<recipe>/<file>`. `initial` is the
  436. /// rows JSON snapshot used to seed the watch channel (from the same
  437. /// `collect` that rendered the page, so the first paint and the first SSE
  438. /// message agree).
  439. pub(crate) fn router(
  440. config: Arc<Config>,
  441. page: String,
  442. initial: String,
  443. archived: bool,
  444. base: &str,
  445. fleet_rx: Option<tokio::sync::broadcast::Receiver<crate::web::events::Event>>,
  446. ) -> Router {
  447. let (tx, rx) = tokio::sync::watch::channel(initial);
  448. tokio::spawn(refresh_loop(
  449. config.clone(),
  450. tx,
  451. KEEPALIVE,
  452. archived,
  453. fleet_rx,
  454. ));
  455. Router::new()
  456. .route(
  457. "/",
  458. get(move || {
  459. let page = page.clone();
  460. async move { axum::response::Html(page) }
  461. }),
  462. )
  463. .route("/events", get(events_stream))
  464. .route("/r/{recipe}/{file}", get(report_file_or_stream))
  465. .route("/repo/{*path}", get(super::repo::repo_route))
  466. .with_state(AppState {
  467. config,
  468. data: rx,
  469. base: base.to_string(),
  470. })
  471. }