//! `midas stats --chart FILE.svg`: waiting for a node, per day, against how //! many nodes there were — the picture that shows what another machine buys. //! //! Top: the hours agents spent waiting each day (bars), and the nodes in the //! pool (a line, right axis). Bottom: each day's takes, straight away or after //! a wait. A dashed line marks the day a node was added or removed. Plain SVG, //! written by hand: no dependency for one picture. use std::collections::BTreeMap; use std::fmt::Write; use chrono::{DateTime, NaiveDate, Utc}; use serde_json::Value; #[derive(Default, Clone)] pub struct Day { pub takes: usize, pub waited: usize, pub wait_hours: f64, /// Average nodes in the pool over the day's samples, if any were taken. pub pool: Option, } fn day_of(v: &Value) -> Option { v["ts"].as_str().and_then(|t| DateTime::parse_from_rfc3339(t).ok()).map(|t| t.with_timezone(&Utc).date_naive()) } /// The days from `from` to `to`, filled from the history. pub fn days(takes: &[Value], pool: &[Value], from: NaiveDate, to: NaiveDate) -> BTreeMap { let mut out: BTreeMap = BTreeMap::new(); let mut d = from; while d <= to { out.insert(d, Day::default()); d = d.succ_opt().unwrap(); } for t in takes { let Some(day) = day_of(t).and_then(|d| out.get_mut(&d)) else { continue }; let w = t["waited_s"].as_f64().unwrap_or(0.0); if t["gave_up"] != true { day.takes += 1; } if w > 0.0 || t["gave_up"] == true { day.waited += 1; day.wait_hours += w / 3600.0; } } let mut samples: BTreeMap> = BTreeMap::new(); for p in pool { if let (Some(d), Some(n)) = (day_of(p), p["in_pool"].as_f64()) { samples.entry(d).or_default().push(n); } } for (d, v) in samples { if let Some(day) = out.get_mut(&d) { day.pool = Some(v.iter().sum::() / v.len() as f64); } } out } /// Node additions and removals: (day, label). /// A node added and removed on the same day (a test) is left out. pub fn markers(pool: &[Value]) -> Vec<(NaiveDate, String)> { let changes: Vec<(NaiveDate, &str, &str)> = pool.iter().filter_map(|p| { Some((day_of(p)?, p["event"].as_str()?, p["node"].as_str().unwrap_or("?"))) }).collect(); let mut by_day: BTreeMap> = BTreeMap::new(); for (d, event, node) in &changes { let sign = match *event { "node_added" => "+", "node_removed" => "−", _ => continue }; let other = if *event == "node_added" { "node_removed" } else { "node_added" }; if changes.iter().any(|(d2, e2, n2)| d2 == d && *e2 == other && n2 == node) { continue; } by_day.entry(*d).or_default().push(format!("{sign}{node}")); } by_day.into_iter().map(|(d, v)| (d, v.join(" "))).collect() } fn esc(s: &str) -> String { s.replace('&', "&").replace('<', "<").replace('>', ">") } pub fn svg(days: &BTreeMap, marks: &[(NaiveDate, String)], title: &str) -> String { let (w, h) = (960.0, 480.0); let (left, right) = (64.0, 56.0); let plot_w = w - left - right; let n = days.len().max(1) as f64; let step = plot_w / n; let bar = (step * 0.7).max(1.0); let x = |i: usize| left + step * i as f64 + (step - bar) / 2.0; let mid = |i: usize| left + step * i as f64 + step / 2.0; let index: BTreeMap = days.keys().enumerate().map(|(i, d)| (*d, i)).collect(); let max_h = days.values().map(|d| d.wait_hours).fold(0.0, f64::max).max(0.5); let max_pool = days.values().filter_map(|d| d.pool).fold(0.0, f64::max).max(2.0).ceil(); let max_takes = days.values().map(|d| d.takes + d.waited.saturating_sub(d.takes.min(d.waited))).max().unwrap_or(1).max(1) as f64; let (top_y, top_h) = (70.0, 200.0); let (bot_y, bot_h) = (330.0, 100.0); let mut s = String::new(); let _ = write!(s, r##" {t} bars: hours agents spent waiting for a node · line: nodes in the pool (right axis) "##, t = esc(title)); // Top panel: grid and axis. for k in 0..=4 { let v = max_h * k as f64 / 4.0; let y = top_y + top_h - top_h * k as f64 / 4.0; let _ = write!(s, r##"{:.1}h "##, w - right, left - 6.0, y + 4.0, v); } for k in 0..=(max_pool as usize) { let y = top_y + top_h - top_h * k as f64 / max_pool; let _ = write!(s, r##"{k} "##, w - right + 8.0, y + 4.0); } for (i, d) in days.values().enumerate() { let bh = top_h * d.wait_hours / max_h; if bh > 0.0 { let _ = write!(s, r##" "##, x(i), top_y + top_h - bh); } } // The pool, as a stepped line through the days that were sampled. let pts: Vec = days.values().enumerate().filter_map(|(i, d)| { d.pool.map(|p| format!("{:.1},{:.1}", mid(i), top_y + top_h - top_h * p / max_pool)) }).collect(); if pts.len() > 1 { let _ = write!(s, r##" "##, pts.join(" ")); } // Bottom panel: takes per day. let _ = write!(s, r##"takes per day: grey straight away, orange after waiting "##, bot_y - 10.0); for (i, d) in days.values().enumerate() { let straight = d.takes.saturating_sub(d.waited) as f64; let waited = d.waited as f64; let hs = bot_h * straight / max_takes; let hw = bot_h * waited / max_takes; let base = bot_y + bot_h; if hs > 0.0 { let _ = write!(s, r##" "##, x(i), base - hs); } if hw > 0.0 { let _ = write!(s, r##" "##, x(i), base - hs - hw); } } let _ = write!(s, r##"{} "##, left - 6.0, bot_y + 4.0, max_takes, w - right, bot_y + bot_h, bot_y + bot_h); // Dates along the bottom, about eight of them. let every = (days.len() / 8).max(1); for (i, d) in days.keys().enumerate() { if i % every == 0 { let _ = write!(s, r##"{} "##, mid(i), bot_y + bot_h + 18.0, d.format("%d %b")); } } // Nodes added and removed. for (d, label) in marks { let Some(i) = index.get(d) else { continue }; let mx = left + step * *i as f64; let _ = write!(s, r##"{} "##, top_y - 6.0, bot_y + bot_h, mx + 4.0, top_y + 6.0, esc(label)); } s += "\n"; s } #[cfg(test)] mod tests { use super::*; use serde_json::json; #[test] fn days_count_takes_waits_and_the_pool() { let takes = vec![ json!({"ts": "2026-10-12T08:00:00Z", "waited_s": 0}), json!({"ts": "2026-10-12T09:00:00Z", "waited_s": 1800}), json!({"ts": "2026-10-12T10:00:00Z", "waited_s": 3600, "gave_up": true}), json!({"ts": "2026-10-13T08:00:00Z", "waited_s": 0}), ]; let pool = vec![ json!({"ts": "2026-10-12T08:00:00Z", "in_pool": 2}), json!({"ts": "2026-10-13T08:00:00Z", "in_pool": 3}), json!({"ts": "2026-10-13T09:00:00Z", "event": "node_added", "node": "mac-1"}), json!({"ts": "2026-10-13T10:00:00Z", "event": "node_added", "node": "test-9"}), json!({"ts": "2026-10-13T11:00:00Z", "event": "node_removed", "node": "test-9"}), ]; let d = days(&takes, &pool, "2026-10-12".parse().unwrap(), "2026-10-13".parse().unwrap()); let a = &d[&"2026-10-12".parse().unwrap()]; assert_eq!((a.takes, a.waited), (2, 2), "the give-up counts as a wait, not a take"); assert!((a.wait_hours - 1.5).abs() < 1e-9); assert_eq!(d[&"2026-10-13".parse().unwrap()].pool, Some(3.0)); let m = markers(&pool); assert_eq!(m, vec![("2026-10-13".parse().unwrap(), "+mac-1".to_string())]); let s = svg(&d, &m, "test"); assert!(s.starts_with("