garage44.eu/jeroen/midas

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

.. /src/ship.rs

raw

//! Shipping: what lands on the warm branch goes out by itself, in batches.
//!
//! A session used to land and then deploy (`land --deploy web`), so three
//! sessions landing within the hour built and published the same targets
//! three times, each time on a node somebody else could have used, and the
//! first two were overtaken before anyone looked at them. Deploying is not a
//! session's decision either: the person approves a branch, and that it then
//! reaches users is the workspace's job.
//!
//! So the hub deploys, for each `hub.conf` target marked `after_landing`: when
//! the tip of its project's main is not what the target was last asked for, it is
//! asked for — but not while another landing is queued or running, since that
//! one would follow minutes later and a single deploy carries both. A tip that
//! has waited [`MAX_WAIT_S`] goes anyway, so a busy afternoon cannot hold
//! everything back. It never deploys a commit without the landing gate's
//! receipt, never asks again for one that failed (the next landing moves the
//! tip), and waits while a person holds deploys (`midas deploy --hold`, or a
//! landing that said `--hold-deploy`): a hold ends when a person deploys or
//! releases it.

use std::collections::{BTreeMap, HashSet};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};

use anyhow::{anyhow, Result};
use serde_json::{json, Value};

use crate::events;
use crate::registry;

/// The longest a landed tip waits for the landings behind it before it goes anyway.
pub const MAX_WAIT_S: i64 = 1800;

/// The most the sessions may put off an announced deploy, all their asks together,
/// counted from the announcement: a session that forgets cannot hold it for ever.
pub const MAX_DEFER_S: i64 = 3600;

/// The longest one ask puts it off.
pub const DEFER_STEP_S: i64 = 1800;

/// How recently a session must have done something to hear an announcement: one
/// idle longer is not using what restarts, and is not woken for it.
const ACTIVE_S: i64 = 1800;

fn file() -> PathBuf {
    registry::root().join("ship.json")
}

fn read() -> Value {
    std::fs::read_to_string(file()).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_else(|| json!({}))
}

/// Change it under its lock. Read, changed and written back by hand, the heartbeat's announcement
/// and a person's hold made at once kept only one of them: a deploy held went out anyway.
fn change<R>(f: impl FnOnce(&mut Value) -> Result<R>) -> Result<R> {
    crate::store::update(file(), |s: &mut Value| {
        if !s.is_object() {
            *s = json!({});
        }
        f(s)
    })
}

/// Hold the deploys that follow landings, saying why, until a person deploys or releases.
pub fn hold(by: &str, why: &str) -> Result<Value> {
    let why: String = why.trim().chars().take(300).collect();
    let held = json!({"by": by, "why": if why.is_empty() { Value::Null } else { json!(why) }, "at": registry::now()});
    change(|s| {
        s["held"] = held.clone();
        Ok(())
    })?;
    events::emit("deploy_held", json!({"actor": by, "why": held["why"]}));
    Ok(held)
}

/// End a hold; false when there was none.
pub fn release(by: &str) -> Result<bool> {
    let was = change(|s| Ok(!std::mem::take(&mut s["held"]).is_null()))?;
    if was {
        events::emit("deploy_released", json!({"actor": by}));
    }
    Ok(was)
}

/// What one landing changes for one target, worked out where the commits are
/// (`midas land targets`, in the session's worktree; the hub's mirror has no
/// branch that is not pushed yet).
#[derive(Debug, Clone, PartialEq)]
pub struct Facts {
    pub target: String,
    /// It changes what the target is built from (`Deploy::paths`).
    pub changed: bool,
    pub optional: bool,
    /// It changes what the target must stay in step with (`Deploy::required_by`).
    pub required: bool,
}

/// The targets a landing builds: by default every changed one that is not
/// optional; `asked` names them instead (`sim,web`), or changes the default
/// (`+wasm`, `-apk`), or is `all` (every changed one). What a target must
/// stay in step with changing builds it whatever was asked. Unchanged ones are
/// left out: nothing they are built from moved.
pub fn pick(facts: &[Facts], asked: Option<&str>) -> Result<Vec<String>> {
    let default: Vec<&str> = facts.iter().filter(|f| f.changed && (!f.optional || f.required)).map(|f| f.target.as_str()).collect();
    let words: Vec<&str> = asked.unwrap_or("").split([',', ' ']).map(str::trim).filter(|w| !w.is_empty()).collect();
    for w in &words {
        let name = w.trim_start_matches(['+', '-']);
        if name != "all" && !facts.iter().any(|f| f.target == name) {
            anyhow::bail!("no target {name:?} is deployed after landings here ({})",
                facts.iter().map(|f| f.target.as_str()).collect::<Vec<_>>().join(", "));
        }
    }
    let mut out: Vec<&str> = if words.iter().any(|w| !w.starts_with(['+', '-'])) {
        vec![]
    } else {
        default.clone()
    };
    for w in &words {
        match (w.chars().next(), w.trim_start_matches(['+', '-'])) {
            (Some('-'), name) => out.retain(|t| *t != name),
            (_, "all") => out.extend(facts.iter().filter(|f| f.changed).map(|f| f.target.as_str())),
            (_, name) => out.push(name),
        }
    }
    out.extend(facts.iter().filter(|f| f.changed && f.required).map(|f| f.target.as_str()));
    // In the listed order, once each, and only what changed.
    Ok(facts.iter().filter(|f| f.changed && out.contains(&f.target.as_str())).map(|f| f.target.clone()).collect())
}

/// Remember which targets the landing of `sha` builds ([`pick`]): the planner
/// builds a target for the landings since what it serves only when one of them
/// picked it, and that landing is live once those it picked serve it. Said
/// before main moves, so the planner never sees the landing without it.
pub fn choose(repo: &str, sha: &str, picked: &[String], asked: Option<&str>, by: &str) -> Result<Value> {
    if sha.len() != 40 || !sha.chars().all(|c| c.is_ascii_hexdigit()) {
        anyhow::bail!("a choice is for a full commit sha, not {sha:?}");
    }
    let known = targets(repo.trim_end_matches(".git"));
    if let Some(t) = picked.iter().find(|t| !known.contains(t)) {
        anyhow::bail!("{repo} deploys no {t:?} after landings ({})", known.join(", "));
    }
    let c = json!({"repo": repo.trim_end_matches(".git"), "targets": picked, "asked": asked, "by": by, "at": registry::now()});
    change(|s| {
        if !s["chosen"].is_object() {
            s["chosen"] = json!({});
        }
        let m = s["chosen"].as_object_mut().expect("made an object above");
        m.insert(sha.to_string(), c.clone());
        // The last few hundred landings: older ones are long deployed.
        while m.len() > 300 {
            let oldest = m.iter().min_by_key(|(_, v)| v["at"].as_i64().unwrap_or(0)).map(|(k, _)| k.clone());
            match oldest {
                Some(k) => { m.remove(&k); }
                None => break,
            }
        }
        Ok(())
    })?;
    events::emit("deploy_chosen", json!({"actor": by, "repo": c["repo"], "sha": sha, "targets": picked, "asked": asked}));
    Ok(c)
}

/// Whether a landing since `published` picked `target`: one that said so, or,
/// when none of them said anything (landed before landings picked), every
/// target that is not optional. A target nothing serves yet is always wanted;
/// so is one whose `required_by` changed since.
fn picked_since(repo: &str, chosen: &Value, target: &str, recipe: Option<&crate::conf::Deploy>, published: Option<&str>, tip: &str) -> bool {
    let Some(p) = published.filter(|p| contains(repo, tip, p)) else { return true };
    let Ok(range) = git(repo, &["rev-list", &format!("{p}..{tip}")]) else { return true };
    let said: Vec<&Value> = range.lines().filter_map(|c| chosen.get(c.trim())).collect();
    if said.iter().any(|c| c["targets"].as_array().is_some_and(|t| t.iter().any(|x| x == target))) {
        return true;
    }
    let Some(r) = recipe else { return said.is_empty() };
    if !r.required_by.is_empty() {
        let mut args = vec!["diff", "--name-only", p, tip, "--"];
        args.extend(r.required_by.iter().map(String::as_str));
        if git(repo, &args).is_ok_and(|d| !d.trim().is_empty()) {
            return true;
        }
    }
    said.is_empty() && !r.optional
}

/// A project's targets deployed after landings, by name.
pub fn targets(repo: &str) -> Vec<String> {
    crate::conf::hub().targets().into_iter().filter(|t| t.deploy.after_landing && t.repo == repo).map(|t| t.name).collect()
}

/// git in a project's mirror (`owner/name`), which a push note refreshes at once.
fn git(repo: &str, args: &[&str]) -> Result<String> {
    let repo = crate::mirror::repo_name(repo).map_err(|_| anyhow!("no repository {repo:?}"))?;
    crate::util::git(&crate::mirror::mirror_path(&repo), args)
}

/// Whether `sha` is in `tip`'s history: what it means for a landing to be live.
/// Remembered, as two commits' ancestry never changes: the board asks it of
/// every landing of the day for every target each time it is made, and a git
/// process each held up every change on the page. A `sha` the mirror lacks is
/// remembered as not in `tip` too, which holds, as `tip` came through the mirror.
pub fn contains(repo: &str, tip: &str, sha: &str) -> bool {
    static KNOWN: Mutex<BTreeMap<(String, String, String), bool>> = Mutex::new(BTreeMap::new());
    if tip == sha {
        return true;
    }
    let key = (repo.to_string(), tip.to_string(), sha.to_string());
    if let Some(&known) = KNOWN.lock().unwrap_or_else(|p| p.into_inner()).get(&key) {
        return known;
    }
    let is = git(repo, &["merge-base", "--is-ancestor", sha, tip]).is_ok();
    let mut known = KNOWN.lock().unwrap_or_else(|p| p.into_inner());
    // Tips come and go with deploys: start again rather than grow without end.
    if known.len() > 4096 {
        known.clear();
    }
    known.insert(key, is);
    is
}

/// The commits `tip` has and `base` had not (`git rev-list base..tip`), or none
/// when the mirror lacks either. Remembered, as that never changes: one git
/// process per deploy, where asking [`contains`] of every landing for every
/// deploy took 18 000 of them for a week of the Services tab, more than its
/// memory holds, and half a minute each time.
pub fn added(repo: &str, base: &str, tip: &str) -> Option<Arc<HashSet<String>>> {
    static KNOWN: Mutex<BTreeMap<(String, String, String), Arc<HashSet<String>>>> = Mutex::new(BTreeMap::new());
    let key = (repo.to_string(), base.to_string(), tip.to_string());
    if let Some(known) = KNOWN.lock().unwrap_or_else(|p| p.into_inner()).get(&key) {
        return Some(known.clone());
    }
    let out: Arc<HashSet<String>> = Arc::new(git(repo, &["rev-list", &format!("{base}..{tip}")]).ok()?.lines().map(str::to_string).collect());
    // Only an answer is remembered: a commit the mirror lacks may come with its next fetch.
    let mut known = KNOWN.lock().unwrap_or_else(|p| p.into_inner());
    if known.len() > 4096 {
        known.clear();
    }
    known.insert(key, out.clone());
    Some(out)
}

/// Per target, from the log: the last deploy asked for (its sha, and whether it
/// is still going or failed), and the last one published.
#[derive(Default, Debug, PartialEq)]
pub struct Last {
    pub asked: Option<String>,
    pub going: bool,
    pub failed: bool,
    pub published: Option<String>,
}

pub fn last_deploys(evs: &[Value]) -> BTreeMap<String, Last> {
    let mut out: BTreeMap<String, Last> = BTreeMap::new();
    let mut asked_id: BTreeMap<String, String> = BTreeMap::new();
    for e in evs {
        let (Some(target), Some(id)) = (e["target"].as_str(), e["deploy"].as_str()) else { continue };
        let l = out.entry(target.to_string()).or_default();
        match e["kind"].as_str() {
            Some("deploy_queued") if e.get("via_hub_from").is_none() => {
                l.asked = e["sha"].as_str().map(str::to_string);
                l.going = true;
                l.failed = false;
                asked_id.insert(target.to_string(), id.to_string());
            }
            // Not built: nothing it is built from changed, so what it serves is this tip already.
            Some("deploy_skipped") if e.get("via_hub_from").is_none() => {
                l.asked = e["sha"].as_str().map(str::to_string);
                l.published = l.asked.clone();
                l.going = false;
                l.failed = false;
            }
            Some(k @ ("deploy_published" | "deploy_failed")) => {
                if k == "deploy_published" {
                    l.published = e["sha"].as_str().map(str::to_string);
                }
                if asked_id.get(target).map(String::as_str) == Some(id) {
                    l.going = false;
                    l.failed = k == "deploy_failed";
                }
            }
            _ => {}
        }
    }
    out
}

/// For a target announced before it goes (`Deploy::announce_s`): how long, when
/// the tip was announced, and a session's ask to put it off (`by`, `why`, `until`);
/// and, for one that names what it is built from (`Deploy::paths`), the commit it
/// serves when the tip changes none of that since.
#[derive(Default, Debug, PartialEq)]
pub struct Notice {
    pub announce_s: Option<i64>,
    pub announced_at: Option<i64>,
    pub deferred: Option<Value>,
    pub unchanged_since: Option<String>,
}

/// "in 4 min", for words about a time to come.
fn in_min(s: i64) -> String {
    format!("in {} min", (s.max(0) + 59) / 60)
}

/// What each target's next deploy waits for, or `go`: the decision, from what
/// the hub knows. Pure, for the tests. A target announced first is `announce`
/// until [`tick`] has told the sessions, then waits out the notice and any
/// session's ask to put it off.
#[allow(clippy::too_many_arguments)]
pub fn decide(tip: &str, landed_at: i64, busy: bool, held: &Value, gated: bool, last: &Last, notice: &Notice, t: i64) -> (&'static str, String) {
    if last.asked.as_deref() == Some(tip) {
        return if last.going {
            ("deploying", "deploying the tip".into())
        } else if last.failed {
            ("failed", "the last deploy of the tip failed; the next landing tries again".into())
        } else {
            ("live", "the tip is live".into())
        };
    }
    if last.going {
        return ("waiting", "waits for the deploy running now".into());
    }
    // Nothing it is built from changed: the build would be what it serves. Neither a
    // hold nor a receipt is needed for that, nor the sessions told.
    if let Some(p) = &notice.unchanged_since {
        return ("skip", format!("nothing it is built from changed since {}", crate::util::sha8(p)));
    }
    if held.is_object() {
        let why = held["why"].as_str().map(|w| format!(": {w}")).unwrap_or_default();
        return ("held", format!("held by {}{why}", held["by"].as_str().unwrap_or("someone")));
    }
    if !gated {
        return ("ungated", format!("{} has no receipt from the landing gate", crate::util::sha8(&tip)));
    }
    if busy && t - landed_at < MAX_WAIT_S {
        return ("waiting", "waits for the landings in line, to go out with them".into());
    }
    if let Some(s) = notice.announce_s {
        let Some(at) = notice.announced_at else {
            return ("announce", "tells the sessions at work first".into());
        };
        let d = &notice.deferred;
        if let Some(until) = d.as_ref().and_then(|d| d["until"].as_i64()).filter(|u| *u > t) {
            let d = d.as_ref().expect("read above");
            let why = d["why"].as_str().filter(|w| !w.is_empty()).map(|w| format!(": {w}")).unwrap_or_default();
            return ("deferred", format!("put off by {} {}{why}", d["by"].as_str().unwrap_or("a session"), in_min(until - t).replacen("in", "for", 1)));
        }
        if t < at + s {
            return ("announced", format!("announced to the sessions at work; goes {}, unless one puts it off", in_min(at + s - t)));
        }
    }
    ("go", "deploying".into())
}

/// A state on its way to a deploy of the tip: one a landing that did not pick
/// the target turns into `unpicked` instead.
fn waits_to_go(state: &str) -> bool {
    matches!(state, "go" | "announce" | "announced" | "deferred" | "waiting" | "held" | "ungated")
}

/// When a target's deploy of the tip starts, in unix seconds, as far as the hub
/// can say (`decide`'s state): the end of its notice or of being put off; for
/// one waiting on the landings in line, the latest it waits; now, for one that
/// goes. None where nothing is planned: live, held, running, waiting on a deploy.
pub fn goes_at(state: &str, busy: bool, landed_at: i64, notice: &Notice, t: i64) -> Option<i64> {
    match state {
        "go" => Some(t),
        "announce" => notice.announce_s.map(|s| t + s),
        "announced" => Some(notice.announced_at? + notice.announce_s?),
        "deferred" => notice.deferred.as_ref()?["until"].as_i64(),
        "waiting" if busy => Some(landed_at + MAX_WAIT_S),
        _ => None,
    }
}

/// The notice for `target` at `tip`, from the ship file. An announcement of an
/// older tip still stands while that tip was never asked for (`asked`, the
/// commit the target's last deploy was for): the sessions were told a deploy
/// is coming, and a landing after it rides along. Announced afresh, each
/// landing started the five minutes again, and a busy hour kept what landed
/// first off the page (2026-10-29). One of a tip deployed or failed is over:
/// the next tip is announced anew. An ask to put it off goes with its
/// announcement.
fn notice_of(s: &Value, target: &str, tip: &str, announce_s: Option<i64>, asked: Option<&str>) -> Notice {
    let a = &s["announced"][target];
    let stands = a["sha"].as_str().is_some_and(|sha| sha == tip || asked != Some(sha));
    let d = &s["deferred"][target];
    Notice {
        announce_s,
        announced_at: if stands { a["at"].as_i64() } else { None },
        deferred: (stands && (d["sha"] == tip || d["sha"] == a["sha"])).then(|| d.clone()),
        unchanged_since: None,
    }
}

/// The commit a target serves, when `tip` changes none of what it is built from
/// (`paths`) since: none when it names nothing, serves nothing yet, or serves
/// something `tip` does not contain (a deploy by hand of another branch).
fn unchanged_since(repo: &str, tip: &str, published: Option<&str>, paths: &[String]) -> Option<String> {
    let p = published.filter(|p| !paths.is_empty() && *p != tip && contains(repo, tip, p))?;
    let mut args = vec!["diff", "--name-only", p, tip, "--"];
    args.extend(paths.iter().map(String::as_str));
    git(repo, &args).ok().filter(|changed| changed.trim().is_empty()).map(|_| p.to_string())
}

/// The sessions at work now, to hear what is about to restart under them: seen
/// in the last [`ACTIVE_S`], not ended, and not a landing's gate.
fn at_work() -> Vec<String> {
    let t = registry::now();
    crate::collab::names().as_object().into_iter().flatten()
        .filter(|(o, n)| !o.starts_with("gate-") && n["ended"].is_null() && n["last"].as_i64().is_some_and(|l| t - l < ACTIVE_S))
        .map(|(o, _)| o.clone()).collect()
}

/// Tell the sessions at work, without waking an idle one: it uses nothing that restarts.
fn tell_sessions(text: &str, except: Option<&str>) {
    for o in at_work().iter().filter(|o| Some(o.as_str()) != except) {
        if let Err(e) = crate::collab::tell("hub", o, text, "deploy") {
            events::emit("error", json!({"what": format!("telling {o} of a deploy: {e:#}")}));
        }
    }
}

/// Announce `target`'s deploy of `tip`: written down, then told to the sessions at work.
fn announce(target: &str, tip: &str, announce_s: i64) -> Result<()> {
    change(|s| {
        s["announced"][target] = json!({"sha": tip, "at": registry::now()});
        Ok(())
    })?;
    events::emit("deploy_announced", json!({"actor": "hub", "target": target, "sha": tip, "in_s": announce_s}));
    tell_sessions(&format!(
        "Deploy of {target} ({}) {}: it restarts what the sessions use (midas: the hub for a few seconds, and the sessions runner between turns). \
         Mid-way through something it would break? `midas deploy --defer {target} --minutes N --why \"…\"` puts it off (at most {} min in all).",
        crate::util::sha8(&tip), in_min(announce_s), MAX_DEFER_S / 60), None);
    Ok(())
}

/// A session's ask to put off `target`'s announced deploy by `minutes`, saying why:
/// to the later of what is asked already and this, within [`MAX_DEFER_S`] of the
/// announcement. The other sessions at work hear of it.
pub fn defer(target: &str, minutes: i64, why: &str, by: &str) -> Result<Value> {
    let t = crate::conf::hub().target(target)?;
    if t.deploy.announce_s.is_none() {
        anyhow::bail!("{target} is not announced before it goes, so there is nothing to put off");
    }
    let p = plan(&t.repo);
    let tip = p["tip"].as_str().ok_or_else(|| anyhow!("{} has no tip to deploy", t.repo))?.to_string();
    let why: String = why.trim().chars().take(200).collect();
    let now = registry::now();
    let (d, until) = change(|s| {
        let asked = p["targets"].as_array().into_iter().flatten().find(|x| x["target"] == target).and_then(|x| x["asked"].as_str());
        let n = notice_of(s, target, &tip, t.deploy.announce_s, asked);
        let Some(at) = n.announced_at else {
            anyhow::bail!("no deploy of {target} is announced now: nothing to put off");
        };
        let step = (minutes.max(1) * 60).min(DEFER_STEP_S);
        let before = n.deferred.as_ref().and_then(|d| d["until"].as_i64()).unwrap_or(0);
        let until = (now + step).max(before).min(at + MAX_DEFER_S);
        if until <= now {
            anyhow::bail!("{target}'s deploy has been put off as long as it may be ({} min after it was announced)", MAX_DEFER_S / 60);
        }
        let d = json!({"sha": tip, "by": by, "why": why, "until": until});
        s["deferred"][target] = d.clone();
        Ok((d, until))
    })?;
    events::emit("deploy_deferred", json!({"actor": by, "target": target, "sha": tip, "until": until, "why": why}));
    // The session that asked (`caller:owner`, as the hub records who), which needs no telling.
    let who = by.rsplit(':').next().unwrap_or(by).to_string();
    tell_sessions(&format!("{who} put off the deploy of {target} {}{}.", in_min(until - now).replacen("in", "for", 1),
        if why.is_empty() { String::new() } else { format!(": {why}") }), Some(&who));
    Ok(d)
}

/// The plans of every project deployed after landings, the first
/// repository's first: what the page shows beside the deploys, and what
/// [`tick`] acts on.
pub fn plans() -> Vec<Value> {
    crate::conf::hub().shipped_repos().iter().map(|r| plan(r)).filter(|p| p["tip"].is_string()).collect()
}

/// One project's plan: its tip, the hold, and each of its targets' state.
pub fn plan(repo: &str) -> Value {
    let names = targets(repo);
    let none = json!({"repo": repo, "targets": []});
    if names.is_empty() {
        return none;
    }
    let branch = crate::conf::hub().targets().into_iter().find(|t| t.repo == repo).map(|t| t.branch).unwrap_or_else(|| "main".into());
    let Ok(tip) = git(repo, &["rev-parse", &format!("refs/heads/{branch}")]) else { return none };
    let landed_at = git(repo, &["log", "-1", "--format=%ct", &tip]).ok().and_then(|s| s.trim().parse().ok()).unwrap_or(0);
    let state = registry::snapshot().unwrap_or(Value::Null);
    let busy = state["landing"]["holder"].is_object() || state["landing"]["queue"].as_object().is_some_and(|q| !q.is_empty());
    let ship = read();
    let held = ship["held"].clone();
    let recipes: BTreeMap<String, crate::conf::Deploy> = crate::conf::hub().targets().into_iter()
        .filter(|t| t.repo == repo).map(|t| (t.name, t.deploy)).collect();
    let gated = crate::deploy::verification(&tip).is_some();
    let evs = events::read_at(&registry::root(), &events::Filter {
        since: chrono::Duration::days(14),
        kinds: ["deploy_queued", "deploy_published", "deploy_failed", "deploy_skipped"].map(String::from).to_vec(),
        node: None, actor: None,
    });
    let last = last_deploys(&evs);
    let t = registry::now();
    let none = Last::default();
    // Nobody at work and nobody landing: what no landing picked catches up now,
    // on nodes nobody waits for.
    let quiet = !busy && at_work().is_empty();
    let each: Vec<Value> = names.iter().map(|n| {
        let l = last.get(n).unwrap_or(&none);
        let recipe = recipes.get(n);
        let mut notice = notice_of(&ship, n, &tip, recipe.and_then(|r| r.announce_s), l.asked.as_deref());
        notice.unchanged_since = recipe.and_then(|r| unchanged_since(repo, &tip, l.published.as_deref(), &r.paths));
        let (mut state, mut words) = decide(&tip, landed_at, busy, &held, gated, l, &notice, t);
        if waits_to_go(state) && !quiet && !picked_since(repo, &ship["chosen"], n, recipe, l.published.as_deref(), &tip) {
            state = "unpicked";
            words = format!("no landing since {} picked it: it goes with the next one that does, or once no session is at work",
                            l.published.as_deref().map(crate::util::sha8).unwrap_or("what it serves"));
        }
        json!({"target": n, "state": state, "words": words, "asked": l.asked, "published": l.published,
               "announce_s": notice.announce_s, "deferred": notice.deferred, "goes_at": goes_at(state, busy && !l.going, landed_at, &notice, t)})
    }).collect();
    // The project these deploys follow (`owner/name`): a landing in another one is not theirs.
    json!({"tip": tip, "repo": repo, "landed_at": landed_at, "held": held, "max_wait_s": MAX_WAIT_S, "targets": each})
}

/// The hub's watch, every half minute: ask for each deploy whose time has come.
pub fn tick() {
    for p in plans() {
        let Some(tip) = p["tip"].as_str() else { continue };
        for t in p["targets"].as_array().into_iter().flatten().filter(|t| t["state"] == "skip") {
            let target = t["target"].as_str().unwrap_or("");
            events::emit("deploy_skipped", json!({
                "actor": "hub", "deploy": format!("skip-{target}-{}", crate::util::sha8(&tip)), "target": target, "sha": tip,
                "serves": t["published"], "why": t["words"],
            }));
        }
        for t in p["targets"].as_array().into_iter().flatten().filter(|t| t["state"] == "announce") {
            let target = t["target"].as_str().unwrap_or("");
            if let Err(e) = announce(target, tip, t["announce_s"].as_i64().unwrap_or(0)) {
                events::emit("error", json!({"what": format!("announcing {target}'s deploy: {e:#}")}));
            }
        }
        for t in p["targets"].as_array().into_iter().flatten().filter(|t| t["state"] == "go") {
            let target = t["target"].as_str().unwrap_or("");
            if let Err(e) = crate::deploy::request(target, Some(tip), "hub", None) {
                events::emit("error", json!({"what": format!("deploying {target} after landing: {e:#}")}));
            }
        }
    }
}

/// What each project's targets deployed after landings serve now, by
/// project: a landing is live once every one of its project's publishes a
/// commit that contains it ([`contains`]). A project with no such targets is
/// not in it, and nothing of it is ever live. Beside it, what each landing
/// picked ([`choose`]).
#[derive(Default)]
pub struct Serving(BTreeMap<String, Vec<(String, Option<String>)>>, Value);

pub fn serving() -> Serving {
    let conf = crate::conf::hub();
    let repos = conf.shipped_repos();
    if repos.is_empty() {
        return Serving::default();
    }
    let evs = events::read_at(&registry::root(), &events::Filter {
        since: chrono::Duration::days(14), kinds: vec!["deploy_published".into(), "deploy_skipped".into()], node: None, actor: None,
    });
    let last = last_deploys(&evs);
    Serving(repos.into_iter().map(|r| {
        let each = targets(&r).into_iter().map(|n| {
            let p = last.get(&n).and_then(|l| l.published.clone());
            (n, p)
        }).collect();
        (r, each)
    }).collect(), read()["chosen"].clone())
}

impl Serving {
    /// Whether the hub deploys `repo` (`owner/name`) after landings.
    pub fn ships(&self, repo: &str) -> bool {
        self.0.contains_key(repo.trim_end_matches(".git"))
    }

    /// Whether a commit landed in `repo` is in everything its targets serve:
    /// everything its landing picked, when it picked ([`choose`]). One that
    /// picked none of them is live as it lands.
    pub fn is_live(&self, repo: &str, sha: &str) -> bool {
        let repo = repo.trim_end_matches(".git");
        let picked = self.1[sha]["targets"].as_array();
        self.0.get(repo).is_some_and(|s| {
            let s: Vec<Option<String>> = s.iter()
                .filter(|(n, _)| picked.is_none_or(|p| p.iter().any(|x| x == n.as_str())))
                .map(|(_, p)| p.clone()).collect();
            picked.is_some() && s.is_empty() || is_live(&s, |p| contains(repo, p, sha))
        })
    }
}

/// Whether every target serves something, and each of those `has` the commit.
fn is_live(serving: &[Option<String>], has: impl Fn(&str) -> bool) -> bool {
    !serving.is_empty() && serving.iter().all(|p| p.as_deref().is_some_and(&has))
}

#[cfg(test)]
mod tests {
    use super::*;

    const TIP: &str = "a1b2c3d4e5f60718293a4b5c6d7e8f9012345678";
    const OLD: &str = "0000000000000000000000000000000000000001";

    fn ev(kind: &str, id: &str, sha: &str) -> Value {
        json!({"kind": kind, "deploy": id, "target": "web", "sha": sha})
    }

    #[test]
    fn the_log_says_what_each_target_was_last_asked_for_and_serves() {
        let last = last_deploys(&[
            ev("deploy_queued", "d1", OLD), ev("deploy_published", "d1", OLD),
            ev("deploy_queued", "d2", TIP),
        ]);
        assert_eq!(last["web"], Last {asked: Some(TIP.into()), going: true, failed: false, published: Some(OLD.into())});
        let last = last_deploys(&[ev("deploy_queued", "d2", TIP), ev("deploy_failed", "d2", TIP)]);
        assert!(last["web"].failed && !last["web"].going);
        // One posted to /v1/events by anybody is not a deploy the hub asked for.
        let mut forged = ev("deploy_queued", "d3", TIP);
        forged["via_hub_from"] = json!("10.44.0.9");
        assert_eq!(last_deploys(&[forged])["web"].asked, None);
    }

    #[test]
    fn what_restarts_the_sessions_tools_is_announced_and_may_be_put_off_a_while() {
        let t = 10_000;
        let (none, held) = (Last::default(), Value::Null);
        let go = |n: &Notice| decide(TIP, t - 60, false, &held, true, &none, n, t).0;
        // Not yet told: tell them first.
        assert_eq!(go(&Notice {announce_s: Some(300), ..Default::default()}), "announce");
        // Told a minute ago: the notice runs; then it goes.
        assert_eq!(go(&Notice {announce_s: Some(300), announced_at: Some(t - 60), deferred: None, ..Default::default()}), "announced");
        assert_eq!(go(&Notice {announce_s: Some(300), announced_at: Some(t - 300), deferred: None, ..Default::default()}), "go");
        // A session put it off: until then, and not after.
        let put_off = |until: i64| Notice {announce_s: Some(300), announced_at: Some(t - 600),
            deferred: Some(json!({"by": "session-s9", "why": "mid-landing", "until": until})), ..Default::default()};
        let (state, words) = decide(TIP, t - 60, false, &held, true, &none, &put_off(t + 120), t);
        assert_eq!((state, words.contains("session-s9") && words.contains("mid-landing")), ("deferred", true));
        assert_eq!(go(&put_off(t - 1)), "go");
        // Waiting for others, held, or ungated come first: nothing is announced that cannot go.
        assert_eq!(decide(TIP, t - 60, true, &held, true, &none, &Notice {announce_s: Some(300), ..Default::default()}, t).0, "waiting");
        // What only announces what is not deployed after landings, or a tip already asked for, is untouched.
        let asked = Last {asked: Some(TIP.into()), ..Default::default()};
        assert_eq!(decide(TIP, t - 60, false, &held, true, &asked, &Notice {announce_s: Some(300), ..Default::default()}, t).0, "live");
    }

    #[test]
    fn the_page_is_told_when_a_deploy_starts() {
        let t = 10_000;
        let told = Notice {announce_s: Some(300), announced_at: Some(t - 60), ..Default::default()};
        assert_eq!(goes_at("announced", false, t - 70, &told, t), Some(t + 240));
        assert_eq!(goes_at("announce", false, t - 5, &Notice {announce_s: Some(300), ..Default::default()}, t), Some(t + 300));
        let put_off = Notice {deferred: Some(json!({"until": t + 900})), ..told};
        assert_eq!(goes_at("deferred", false, t - 70, &put_off, t), Some(t + 900));
        assert_eq!(goes_at("waiting", true, t - 600, &Notice::default(), t), Some(t - 600 + MAX_WAIT_S), "at the latest");
        assert_eq!(goes_at("waiting", false, t - 600, &Notice::default(), t), None, "a deploy that runs now ends when it ends");
        assert_eq!(goes_at("live", false, t - 600, &Notice::default(), t), None);
    }

    #[test]
    fn a_target_whose_inputs_did_not_change_is_not_built_and_reads_live() {
        let t = 10_000;
        let (none, held) = (Last::default(), Value::Null);
        let same = Notice {unchanged_since: Some(OLD.into()), announce_s: Some(300), ..Default::default()};
        // Skipped before anything else: no hold, receipt or announcement is needed to build nothing.
        assert_eq!(decide(TIP, t - 60, true, &json!({"by": "ana"}), false, &none, &same, t).0, "skip");
        // But never under a deploy still running, nor once the tip was asked for.
        let going = Last {asked: Some(OLD.into()), going: true, ..Default::default()};
        assert_eq!(decide(TIP, t - 60, false, &held, true, &going, &same, t).0, "waiting");
        // A skip counts as publishing the tip: the target serves it, and asks nothing more.
        let mut skipped = ev("deploy_skipped", "skip-web-a1b2c3d4", TIP);
        skipped["actor"] = json!("hub");
        let last = last_deploys(&[ev("deploy_queued", "d1", OLD), ev("deploy_published", "d1", OLD), skipped]);
        assert_eq!(last["web"], Last {asked: Some(TIP.into()), going: false, failed: false, published: Some(TIP.into())});
        assert_eq!(decide(TIP, t - 60, false, &held, true, &last["web"], &same, t).0, "live");
    }

    #[test]
    fn an_announcement_of_a_tip_since_deployed_is_over_and_one_never_deployed_stands() {
        let s = json!({"announced": {"midas": {"sha": OLD, "at": 5}}, "deferred": {"midas": {"sha": OLD, "until": 99}}});
        // OLD went out: TIP is announced anew.
        assert_eq!(notice_of(&s, "midas", TIP, Some(300), Some(OLD)), Notice {announce_s: Some(300), announced_at: None, deferred: None, ..Default::default()});
        // OLD never went: TIP landed on top of it and goes with it, on its clock and its ask.
        let n = notice_of(&s, "midas", TIP, Some(300), Some("0000000000000000000000000000000000000000"));
        assert_eq!((n.announced_at, n.deferred.map(|d| d["until"].clone())), (Some(5), Some(json!(99))));
        assert_eq!(notice_of(&s, "midas", TIP, Some(300), None).announced_at, Some(5));
        let s = json!({"announced": {"midas": {"sha": TIP, "at": 5}}, "deferred": {"midas": {"sha": "f".repeat(40), "until": 99}}});
        assert_eq!(notice_of(&s, "midas", TIP, Some(300), Some(OLD)).announced_at, Some(5));
        assert_eq!(notice_of(&s, "midas", TIP, Some(300), Some(OLD)).deferred, None);
    }

    #[test]
    fn a_landing_waits_for_the_ones_behind_it_then_goes_once() {
        let t = 10_000;
        let none = Last::default();
        let held = Value::Null;
        // Others in line: wait for them, so one deploy carries all of them.
        assert_eq!(decide(TIP, t - 60, true, &held, true, &none, &Notice::default(), t).0, "waiting");
        // But not for ever.
        assert_eq!(decide(TIP, t - MAX_WAIT_S - 1, true, &held, true, &none, &Notice::default(), t).0, "go");
        // Nobody in line: now.
        assert_eq!(decide(TIP, t - 60, false, &held, true, &none, &Notice::default(), t).0, "go");
        // Asked for already: never twice, and a failure is not retried on the same tip.
        let asked = Last {asked: Some(TIP.into()), ..Default::default()};
        assert_eq!(decide(TIP, t - 60, false, &held, true, &asked, &Notice::default(), t).0, "live");
        let failed = Last {asked: Some(TIP.into()), failed: true, ..Default::default()};
        assert_eq!(decide(TIP, t - 60, false, &held, true, &failed, &Notice::default(), t).0, "failed");
        // A deploy of an older tip still running: after it.
        let going = Last {asked: Some(OLD.into()), going: true, ..Default::default()};
        assert_eq!(decide(TIP, t - 60, false, &held, true, &going, &Notice::default(), t).0, "waiting");
        // Held, or never gated: not at all.
        assert_eq!(decide(TIP, t - 60, false, &json!({"by": "web:ana", "why": "demo at 3"}), true, &none, &Notice::default(), t).0, "held");
        assert_eq!(decide(TIP, t - 60, false, &held, false, &none, &Notice::default(), t).0, "ungated");
    }

    #[test]
    fn nothing_is_live_where_nothing_is_deployed_after_landings() {
        assert!(!is_live(&[], |_| true));
        assert!(!is_live(&[None], |_| true));
        assert!(is_live(&[Some(TIP.into()), Some(OLD.into())], |_| true));
        assert!(!is_live(&[Some(TIP.into()), Some(OLD.into())], |p| p == TIP), "every target serves it");
        let s = Serving([("acme/cartopolis".to_string(), vec![("web".to_string(), Some(TIP.to_string()))])].into(), Value::Null);
        assert!(s.ships("acme/cartopolis.git") && !s.ships("acme/dardasha"));
        assert!(s.is_live("acme/cartopolis", TIP));
        assert!(!s.is_live("acme/dardasha", TIP), "a project nobody deploys is never live by another's deploys");
    }

    #[test]
    fn a_landing_is_live_once_what_it_picked_serves_it() {
        // web serves the landing, wasm still an older commit.
        let each = vec![("web".to_string(), Some(TIP.to_string())), ("wasm".to_string(), Some(OLD.to_string()))];
        let s = |chosen: Value| Serving([("acme/cartopolis".to_string(), each.clone())].into(), chosen);
        // OLD is no mirror's commit, so nothing serving it holds the landing.
        let live = |s: &Serving| s.is_live("acme/cartopolis", TIP);
        assert!(!live(&s(Value::Null)), "picking nothing said, every target counts");
        assert!(live(&s(json!({TIP: {"targets": ["web"]}}))), "wasm was left to later");
        assert!(!live(&s(json!({TIP: {"targets": ["web", "wasm"]}}))));
        assert!(s(json!({TIP: {"targets": []}})).is_live("acme/cartopolis", TIP), "nothing picked: live as it lands");
    }

    fn facts(v: &[(&str, bool, bool, bool)]) -> Vec<Facts> {
        v.iter().map(|(t, changed, optional, required)| Facts {target: t.to_string(), changed: *changed, optional: *optional, required: *required}).collect()
    }

    #[test]
    fn a_landing_builds_what_it_changed_but_optional_ones_only_when_picked_or_required() {
        // sim and wasm changed; wasm is optional; atlas did not change.
        let f = facts(&[("sim", true, false, false), ("atlas", false, false, false), ("wasm", true, true, false)]);
        assert_eq!(pick(&f, None).unwrap(), ["sim"]);
        assert_eq!(pick(&f, Some("+wasm")).unwrap(), ["sim", "wasm"]);
        assert_eq!(pick(&f, Some("-sim")).unwrap(), Vec::<String>::new());
        assert_eq!(pick(&f, Some("wasm")).unwrap(), ["wasm"], "a list names them");
        assert_eq!(pick(&f, Some("all")).unwrap(), ["sim", "wasm"]);
        assert_eq!(pick(&f, Some("+atlas")).unwrap(), ["sim"], "nothing atlas is built from changed");
        assert!(pick(&f, Some("+apk")).is_err(), "no such target");
        // The wire protocol changed: wasm goes whatever was asked.
        let f = facts(&[("sim", true, false, false), ("wasm", true, true, true)]);
        assert_eq!(pick(&f, None).unwrap(), ["sim", "wasm"]);
        assert_eq!(pick(&f, Some("-wasm")).unwrap(), ["sim", "wasm"]);
        assert_eq!(pick(&f, Some("sim")).unwrap(), ["sim", "wasm"]);
    }
}