garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /src/graph.rs

raw

//! Goals ▸ Map (docs/screens/graph.html): every project at once, which one's
//! code another uses, the sessions that worked in two, and the techs in one that
//! need a tech in another. The page draws it at `/v1/hosted/graph`, and the
//! site's front page draws the public part of it for anyone ([`public`]).
//!
//! Every line is something recorded, never guessed:
//! - **code**: a `Cargo.toml` or `package.json` on a project's main branch naming
//!   another hosted project by URL (`https://<host>/<owner>/<name>.git` or
//!   `…/<owner>/<name>/archive/<sha>.tar.gz`), with the pinned commit and how far
//!   behind its main that pin is;
//! - **shared**: sessions whose `repos` hold both;
//! - **needs**: a tech of one project's that needs a tech of another's.
//!
//! The layout is the tree's: a project's column is one past the deepest project
//! whose code it uses, rows untangled by the mean row of what they use. Projects
//! that share no code with any other stand apart, in a column of their own.

use std::collections::{BTreeMap, BTreeSet};
use std::process::Command;
use std::sync::Mutex;
use std::time::{Duration, Instant};

use serde_json::{json, Value};

use crate::hosted;

/// How long one reading is served again: the front page is public, and every
/// reading runs git over every repository.
const FRESH: Duration = Duration::from_secs(60);

/// The last reading, with when and of which hub (its registry root: tests run several).
static CACHE: Mutex<Option<(Instant, std::path::PathBuf, Value)>> = Mutex::new(None);

fn git(repo: &str, args: &[&str]) -> Option<String> {
    let out = Command::new("git").arg("-C").arg(hosted::path(repo)).args(args).output().ok()?;
    out.status.success().then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())
}

/// One project's use of another's code, as its manifests say it.
#[derive(Debug, Clone, PartialEq)]
pub struct Use {
    pub from: String,
    pub rev: Option<String>,
    pub file: String,
}

/// What `text` (a manifest at `file`) names of the projects in `known`: each
/// URL `https://<host>/<owner>/<name>` followed by `.git` or `/archive/<sha>`,
/// with the commit a `rev = "…"` on the same line, or the archive's, pins.
pub fn uses(text: &str, file: &str, known: &BTreeSet<String>) -> Vec<Use> {
    let mut out: Vec<Use> = Vec::new();
    for line in text.lines() {
        let mut rest = line;
        while let Some(at) = rest.find("https://") {
            rest = &rest[at + 8..];
            let url: String = rest.chars().take_while(|c| !matches!(c, '"' | '\'' | ' ' | ',' | '}' | '#')).collect();
            let mut parts = url.splitn(4, '/');
            let (_, Some(owner), Some(name)) = (parts.next(), parts.next(), parts.next()) else { continue };
            let after = parts.next().unwrap_or("");
            let (name, rev) = if let Some(n) = name.strip_suffix(".git") {
                let rev = ["rev = \"", "rev=\""].iter().find_map(|k| line.split_once(k)).and_then(|(_, r)| r.split('"').next()).map(str::to_string);
                (n, rev)
            } else if let Some(sha) = after.strip_prefix("archive/") {
                (name, Some(sha.trim_end_matches(".tar.gz").to_string()))
            } else {
                continue;
            };
            let key = format!("{owner}/{name}");
            if known.contains(&key) && !out.iter().any(|u| u.from == key && u.rev == rev) {
                out.push(Use { from: key, rev, file: file.to_string() });
            }
        }
    }
    out
}

/// Every manifest of `repo`'s main branch, and what each names.
fn uses_of(repo: &str, known: &BTreeSet<String>) -> Vec<Use> {
    let Some(files) = git(repo, &["ls-tree", "-r", "--name-only", "HEAD"]) else { return vec![] };
    let mut out: Vec<Use> = Vec::new();
    for f in files.lines().filter(|f| f.ends_with("Cargo.toml") || f.ends_with("package.json")).filter(|f| !f.contains("node_modules/")) {
        let Some(text) = git(repo, &["cat-file", "blob", &format!("HEAD:{f}")]) else { continue };
        for u in uses(&text, f, known) {
            if u.from != repo && !out.iter().any(|x| x.from == u.from && x.rev == u.rev) {
                out.push(u);
            }
        }
    }
    out
}

/// How many commits of `repo`'s main are not in `rev`; none when the hub does not have `rev`.
fn behind(repo: &str, rev: &str) -> Option<u64> {
    if rev.starts_with('-') || !rev.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '/')) {
        return None;
    }
    git(repo, &["rev-list", "--count", &format!("{rev}..HEAD")])?.parse().ok()
}

/// Columns and rows: a project's column is one past the deepest it uses; projects with no code line stand
/// apart in the last column. Rows by the mean row of what a project uses, three passes, ties by size.
pub fn layout(names: &[String], code: &[(String, String)], size: &BTreeMap<String, u64>) -> BTreeMap<String, (usize, usize)> {
    let linked: BTreeSet<&String> = code.iter().flat_map(|(a, b)| [a, b]).collect();
    let mut depth: BTreeMap<&String, usize> = names.iter().map(|n| (n, 0)).collect();
    // Longest path, bounded by the number of projects so a cycle cannot loop for ever.
    for _ in 0..names.len() {
        let mut moved = false;
        for (a, b) in code {
            let d = depth.get(a).copied().unwrap_or(0) + 1;
            if depth.get(b).is_some_and(|&x| x < d) && d < names.len() {
                depth.insert(b, d);
                moved = true;
            }
        }
        if !moved {
            break;
        }
    }
    let apart = linked.iter().map(|n| depth[*n]).max().map(|d| d + 1).unwrap_or(0);
    let col = |n: &String| if linked.contains(n) { depth[n] } else { apart };
    let mut cols: BTreeMap<usize, Vec<String>> = BTreeMap::new();
    for n in names {
        cols.entry(col(n)).or_default().push(n.clone());
    }
    for c in cols.values_mut() {
        c.sort_by(|a, b| size.get(b).cmp(&size.get(a)).then(a.cmp(b)));
    }
    let mut row: BTreeMap<String, f64> = BTreeMap::new();
    for c in cols.values() {
        for (i, n) in c.iter().enumerate() {
            row.insert(n.clone(), i as f64);
        }
    }
    for _ in 0..3 {
        for (&k, c) in cols.iter_mut() {
            if k == 0 || k == apart {
                continue;
            }
            let mean = |n: &String| {
                let up: Vec<f64> = code.iter().filter(|(_, b)| b == n).filter_map(|(a, _)| row.get(a).copied()).collect();
                if up.is_empty() { row[n] } else { up.iter().sum::<f64>() / up.len() as f64 }
            };
            let mut keyed: Vec<(f64, String)> = c.iter().map(|n| (mean(n), n.clone())).collect();
            keyed.sort_by(|a, b| a.0.total_cmp(&b.0).then(size.get(&b.1).cmp(&size.get(&a.1))));
            *c = keyed.into_iter().map(|(_, n)| n).collect();
            for (i, n) in c.iter().enumerate() {
                row.insert(n.clone(), i as f64);
            }
        }
    }
    // The apart ones wrap into columns no taller than the tallest linked one (at least three), so the map
    // stays as wide as it is tall rather than one long column.
    let tall = cols.iter().filter(|(&k, _)| k != apart).map(|(_, c)| c.len()).max().unwrap_or(0).max(3);
    let loners = cols.remove(&apart).unwrap_or_default();
    let mut at: BTreeMap<String, (usize, usize)> =
        cols.into_iter().flat_map(|(k, c)| c.into_iter().enumerate().map(move |(i, n)| (n, (k, i)))).collect();
    for (i, n) in loners.into_iter().enumerate() {
        at.insert(n, (apart + i / tall, i % tall));
    }
    at
}

/// The whole map, as recorded now.
fn read() -> Value {
    let repos = hosted::repos();
    let known: BTreeSet<String> = repos.keys().cloned().collect();
    let sessions = crate::sessions::list();
    let mut count: BTreeMap<String, u64> = BTreeMap::new();
    let mut shared: BTreeMap<(String, String), u64> = BTreeMap::new();
    for s in sessions.as_array().into_iter().flatten() {
        let mut rs: Vec<String> = s["repos"].as_array().into_iter().flatten().filter_map(|r| r.as_str()).map(str::to_string).collect();
        if rs.is_empty() {
            rs.extend(s["repo"].as_str().map(str::to_string));
        }
        rs.retain(|r| known.contains(r));
        rs.sort();
        rs.dedup();
        for r in &rs {
            *count.entry(r.clone()).or_default() += 1;
        }
        for (i, a) in rs.iter().enumerate() {
            for b in &rs[i + 1..] {
                *shared.entry((a.clone(), b.clone())).or_default() += 1;
            }
        }
    }
    // Techs: how many each project has and has built, which need another project's, and the last built.
    let tree = crate::tree::all();
    let techs = tree["techs"].as_array().cloned().unwrap_or_default();
    let home = |t: &Value| t["repos"][0].as_str().map(str::to_string);
    let mut built: BTreeMap<String, (u64, u64)> = BTreeMap::new();
    let mut needs: BTreeMap<(String, String), u64> = BTreeMap::new();
    let mut landed: Vec<Value> = Vec::new();
    for t in techs.iter().filter(|t| t["state"] != "dropped") {
        let Some(r) = home(t) else { continue };
        let e = built.entry(r.clone()).or_default();
        e.0 += 1;
        if t["state"] == "built" {
            e.1 += 1;
            // What the scout found already there is built, but it did not land then.
            if t["built_by"] != "scout" {
                if let Some(at) = t["built_at"].as_i64() {
                    landed.push(json!({"name": t["name"], "repo": r, "at": at}));
                }
            }
        }
        for n in t["needs"].as_array().into_iter().flatten() {
            if let Some(from) = techs.iter().find(|x| &x["id"] == n).and_then(home).filter(|f| *f != r) {
                *needs.entry((from, r.clone())).or_default() += 1;
            }
        }
    }
    landed.sort_by_key(|l| std::cmp::Reverse(l["at"].as_i64().unwrap_or(0)));
    let mut code: Vec<Value> = Vec::new();
    for r in &known {
        for u in uses_of(r, &known) {
            let lag = u.rev.as_deref().and_then(|rev| behind(&u.from, rev));
            code.push(json!({"from": u.from, "to": r, "rev": u.rev, "file": u.file, "behind": lag}));
        }
    }
    let names: Vec<String> = known.iter().cloned().collect();
    let pairs: Vec<(String, String)> = code.iter().map(|c| (c["from"].as_str().unwrap_or("").to_string(), c["to"].as_str().unwrap_or("").to_string())).collect();
    let at = layout(&names, &pairs, &count);
    let projects: Vec<Value> = names.iter().map(|n| {
        let (techs, built) = built.get(n).copied().unwrap_or_default();
        let (col, row) = at[n];
        json!({"name": n, "public": repos[n]["visibility"] == "public", "description": repos[n]["description"],
               "sessions": count.get(n).copied().unwrap_or(0), "techs": techs, "built": built, "col": col, "row": row})
    }).collect();
    json!({
        "projects": projects,
        "code": code,
        "shared": shared.into_iter().map(|((a, b), n)| json!({"a": a, "b": b, "n": n})).collect::<Vec<_>>(),
        "needs": needs.into_iter().map(|((from, to), n)| json!({"from": from, "to": to, "n": n})).collect::<Vec<_>>(),
        "landed": landed.into_iter().take(40).collect::<Vec<_>>(),
    })
}

/// The map, read at most once a minute.
pub fn all() -> Value {
    let mut c = CACHE.lock().unwrap_or_else(|p| p.into_inner());
    let root = crate::registry::root();
    if let Some((_, _, v)) = c.as_ref().filter(|(at, r, _)| at.elapsed() < FRESH && *r == root) {
        return v.clone();
    }
    let v = read();
    *c = Some((Instant::now(), root, v.clone()));
    v
}

/// What anyone may see of `g`: public projects only, and only lines between two of them; no session
/// counts (sessions are the workspace's), techs and what landed when.
pub fn public(g: &Value) -> Value {
    let open: BTreeSet<&str> = g["projects"].as_array().into_iter().flatten()
        .filter(|p| p["public"] == true).filter_map(|p| p["name"].as_str()).collect();
    let both = |a: &Value, b: &Value| a.as_str().is_some_and(|a| open.contains(a)) && b.as_str().is_some_and(|b| open.contains(b));
    let names: Vec<String> = open.iter().map(|s| s.to_string()).collect();
    let code: Vec<Value> = g["code"].as_array().into_iter().flatten().filter(|c| both(&c["from"], &c["to"])).cloned().collect();
    let pairs: Vec<(String, String)> = code.iter().map(|c| (c["from"].as_str().unwrap_or("").to_string(), c["to"].as_str().unwrap_or("").to_string())).collect();
    let size: BTreeMap<String, u64> = g["projects"].as_array().into_iter().flatten()
        .filter_map(|p| Some((p["name"].as_str()?.to_string(), p["techs"].as_u64().unwrap_or(0)))).collect();
    let at = layout(&names, &pairs, &size);
    let projects: Vec<Value> = g["projects"].as_array().into_iter().flatten().filter(|p| p["name"].as_str().is_some_and(|n| open.contains(n)))
        .map(|p| {
            let (col, row) = at[p["name"].as_str().unwrap_or("")];
            json!({"name": p["name"], "public": true, "description": p["description"], "techs": p["techs"], "built": p["built"], "col": col, "row": row})
        }).collect();
    json!({
        "projects": projects,
        "code": code,
        "shared": [],
        "needs": [],
        "landed": g["landed"].as_array().into_iter().flatten().filter(|l| l["repo"].as_str().is_some_and(|r| open.contains(r))).take(12).cloned().collect::<Vec<_>>(),
    })
}

fn esc(s: &str) -> String {
    s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
}

/// Pins further behind than this are drawn amber.
const STALE: u64 = 5;
const COL_W: f64 = 230.0;
const ROW_H: f64 = 150.0;

/// The map as SVG, no script: each project a circle sized by its sessions (or, public, its techs), a ring
/// for the share built, arrows from the project used to the one using it. With `link`, each project is a
/// link to `link` + its name; else it carries `data-project` for the page to catch a tap.
pub fn svg(g: &Value, link: Option<&str>) -> String {
    let ps: Vec<&Value> = g["projects"].as_array().map(|a| a.iter().collect()).unwrap_or_default();
    let cols = ps.iter().filter_map(|p| p["col"].as_u64()).max().map(|c| c + 1).unwrap_or(1) as f64;
    let rows = ps.iter().filter_map(|p| p["row"].as_u64()).max().map(|r| r + 1).unwrap_or(1) as f64;
    // Room below for the odd columns, set a quarter row lower, and a name under its circle.
    let (w, h) = (cols * COL_W + 40.0, rows * ROW_H + ROW_H * 0.25 + 40.0);
    let pos = |name: &str| ps.iter().find(|p| p["name"] == name).map(|p| {
        let (c, r) = (p["col"].as_f64().unwrap_or(0.0), p["row"].as_f64().unwrap_or(0.0));
        // Odd columns sit half a row lower, so a line across two columns passes between, not through.
        (20.0 + COL_W * (c + 0.5), 20.0 + ROW_H * (r + 0.5) + if c as u64 % 2 == 1 { ROW_H * 0.25 } else { 0.0 })
    });
    let weight = |p: &Value| p["sessions"].as_f64().filter(|_| link.is_none()).unwrap_or(p["techs"].as_f64().unwrap_or(0.0) * 4.0);
    let short = |n: &str| n.rsplit('/').next().unwrap_or(n).to_string();
    let radius = |name: &str| ps.iter().find(|p| p["name"] == name).map(|p| 16.0 + 5.0 * (1.0 + weight(p)).log2()).unwrap_or(20.0);
    let col = |name: &str| ps.iter().find(|p| p["name"] == name).and_then(|p| p["col"].as_f64()).unwrap_or(0.0);
    let mut s = format!(
        "<svg class=\"pmap\" viewBox=\"0 0 {w} {h}\" xmlns=\"http://www.w3.org/2000/svg\" font-family=\"system-ui,sans-serif\" role=\"img\" aria-label=\"The projects and which uses which\">\
         <defs><marker id=\"pm-a\" viewBox=\"0 0 10 10\" refX=\"9\" refY=\"5\" markerWidth=\"7\" markerHeight=\"7\" orient=\"auto\"><path d=\"M0,0L10,5L0,10z\" fill=\"#2f7f7a\"/></marker>\
         <marker id=\"pm-o\" viewBox=\"0 0 10 10\" refX=\"9\" refY=\"5\" markerWidth=\"7\" markerHeight=\"7\" orient=\"auto\"><path d=\"M0,0L10,5L0,10z\" fill=\"#c79a3c\"/></marker></defs>");
    for x in g["shared"].as_array().into_iter().flatten() {
        let (Some(a), Some(b)) = (pos(x["a"].as_str().unwrap_or("")), pos(x["b"].as_str().unwrap_or(""))) else { continue };
        let n = x["n"].as_f64().unwrap_or(1.0);
        s += &format!("<line x1=\"{:.0}\" y1=\"{:.0}\" x2=\"{:.0}\" y2=\"{:.0}\" stroke=\"#cfe0df\" stroke-width=\"{:.1}\" stroke-linecap=\"round\" opacity=\".8\"><title>{} sessions in both</title></line>",
            a.0, a.1, b.0, b.1, 2.0 + 2.0 * n.sqrt(), n);
    }
    for x in g["needs"].as_array().into_iter().flatten() {
        let (Some(a), Some(b)) = (pos(x["from"].as_str().unwrap_or("")), pos(x["to"].as_str().unwrap_or(""))) else { continue };
        // Bent to the left of its way, so the two ways between one pair are two curves.
        let (dx, dy) = (b.0 - a.0, b.1 - a.1);
        let d = (dx * dx + dy * dy).sqrt().max(1.0);
        let (mx, my) = ((a.0 + b.0) / 2.0 + dy / d * 45.0, (a.1 + b.1) / 2.0 - dx / d * 45.0);
        let to = short(x["to"].as_str().unwrap_or(""));
        s += &format!("<path d=\"M{:.0},{:.0} Q{mx:.0},{my:.0} {:.0},{:.0}\" fill=\"none\" stroke=\"#8f6fc4\" stroke-width=\"1.6\" stroke-dasharray=\"5 4\" opacity=\".8\"><title>{n} techs of {} need one of {}</title></path>\
                       <text x=\"{:.0}\" y=\"{:.0}\" text-anchor=\"middle\" font-size=\"11\" fill=\"#8f6fc4\">{n} techs</text>",
            a.0, a.1, b.0, b.1, esc(&to), esc(&short(x["from"].as_str().unwrap_or(""))), (a.0 + b.0) / 4.0 + mx / 2.0, (a.1 + b.1) / 4.0 + my / 2.0 + 4.0, n = x["n"]);
    }
    // One arrow per pair: amber when its oldest pin is stale, labelled with how far.
    let mut arrows: BTreeMap<(String, String), Option<u64>> = BTreeMap::new();
    for c in g["code"].as_array().into_iter().flatten() {
        let k = (c["from"].as_str().unwrap_or("").to_string(), c["to"].as_str().unwrap_or("").to_string());
        let e = arrows.entry(k).or_default();
        *e = (*e).max(c["behind"].as_u64());
    }
    for ((from, to), lag) in &arrows {
        let (Some(a), Some(b)) = (pos(from), pos(to)) else { continue };
        let (dx, dy) = (b.0 - a.0, b.1 - a.1);
        let d = (dx * dx + dy * dy).sqrt().max(1.0);
        // An arrow over a column bends round what stands in it.
        let span = (col(to) - col(from)).abs();
        let bend = if span > 1.0 { (span - 1.0) * ROW_H * 0.5 } else { 0.0 };
        let c = ((a.0 + b.0) / 2.0 + dy / d * bend, (a.1 + b.1) / 2.0 - dx / d * bend);
        let unit = |p: (f64, f64), q: (f64, f64)| {
            let l = ((q.0 - p.0).powi(2) + (q.1 - p.1).powi(2)).sqrt().max(1.0);
            ((q.0 - p.0) / l, (q.1 - p.1) / l)
        };
        let (ua, ub) = (unit(a, c), unit(c, b));
        let (ra, rb) = (radius(from), radius(to) + 4.0);
        let (x1, y1, x2, y2) = (a.0 + ua.0 * ra, a.1 + ua.1 * ra, b.0 - ub.0 * rb, b.1 - ub.1 * rb);
        let stale = lag.is_some_and(|l| l > STALE);
        s += &format!("<path d=\"M{x1:.0},{y1:.0} Q{:.0},{:.0} {x2:.0},{y2:.0}\" fill=\"none\" stroke=\"{}\" stroke-width=\"2.5\" marker-end=\"url(#pm-{})\"><title>{} uses {}'s code</title></path>",
            c.0, c.1, if stale { "#c79a3c" } else { "#2f7f7a" }, if stale { "o" } else { "a" }, esc(&short(to)), esc(&short(from)));
        if let Some(l) = lag.filter(|&l| l > 0) {
            s += &format!("<text x=\"{:.0}\" y=\"{:.0}\" text-anchor=\"middle\" font-size=\"11\" font-weight=\"600\" fill=\"{}\" stroke=\"#fff\" stroke-width=\"4\" stroke-linejoin=\"round\" paint-order=\"stroke\">{l} behind</text>",
                (x1 + x2) / 4.0 + c.0 / 2.0, (y1 + y2) / 4.0 + c.1 / 2.0 - 5.0, if stale { "#8a6214" } else { "#6b8183" });
        }
    }
    for p in &ps {
        let name = p["name"].as_str().unwrap_or("");
        let Some((x, y)) = pos(name) else { continue };
        let r = radius(name);
        let (techs, built) = (p["techs"].as_u64().unwrap_or(0), p["built"].as_u64().unwrap_or(0));
        // A name wider than its circle goes under it.
        let inside = short(name).len() as f64 * 7.4 < 2.0 * r - 8.0;
        let open = match link {
            Some(l) => format!("<a href=\"{}{}\">", esc(l), esc(name)),
            None => format!("<g class=\"pmap__p\" data-project=\"{}\" tabindex=\"0\">", esc(name)),
        };
        s += &open;
        s += &format!("<circle cx=\"{x:.0}\" cy=\"{y:.0}\" r=\"{r:.0}\" fill=\"#fff\" stroke=\"#dfe7e7\" stroke-width=\"2\"/>");
        if techs > 0 {
            let rr = r - 5.0;
            let f = built as f64 / techs as f64;
            let a = std::f64::consts::TAU * f.min(0.9999);
            s += &format!("<circle cx=\"{x:.0}\" cy=\"{y:.0}\" r=\"{rr:.0}\" fill=\"none\" stroke=\"#e3eaea\" stroke-width=\"4\"/>");
            if built > 0 {
                s += &format!("<path d=\"M{x:.1},{:.1} A{rr:.1},{rr:.1} 0 {} 1 {:.1},{:.1}\" fill=\"none\" stroke=\"#2f8f5b\" stroke-width=\"4\" stroke-linecap=\"round\"/>",
                    y - rr, u8::from(f > 0.5), x + rr * a.sin(), y - rr * a.cos());
            }
        }
        let under = if link.is_some() {
            if techs > 0 { format!("{built} of {techs} techs built") } else { String::new() }
        } else {
            let n = p["sessions"].as_u64().unwrap_or(0);
            format!("{n} session{}{}", if n == 1 { "" } else { "s" }, if techs > 0 { format!(" · {built}/{techs}") } else { String::new() })
        };
        s += &format!("<text x=\"{x:.0}\" y=\"{:.0}\" text-anchor=\"middle\" font-size=\"13.5\" font-weight=\"600\" fill=\"#1d2a2c\" stroke=\"#fff\" stroke-width=\"4\" stroke-linejoin=\"round\" paint-order=\"stroke\">{}</text>",
            if inside { y + 4.5 } else { y + r + 16.0 }, esc(&short(name)));
        s += &format!("<text x=\"{x:.0}\" y=\"{:.0}\" text-anchor=\"middle\" font-size=\"11.5\" fill=\"#6b8183\">{}</text>",
            y + r + if inside { 15.0 } else { 30.0 }, esc(&under));
        s += if link.is_some() { "</a>" } else { "</g>" };
    }
    s += "</svg>";
    s
}