garage44.eu/jeroen/midas

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

.. /src/deploy.rs

raw

//! `midas deploy <target>`: build a commit that has landed on a node, and
//! publish it on the hub's machine — with no CI system in between.
//!
//! The landing gate already ran the tests on a node (`midas verified` records
//! that it passed, for the commit); building the same commit again on a CI
//! runner, only to copy the result into a directory on this same machine, was
//! the whole of what the deploy workflows did. So a deploy is three steps, split
//! where the privilege changes:
//!
//! 1. **asked for** (`POST /v1/deploy`, the hub): the target must be one of
//!    `hub.conf`'s `deploy` recipes, the commit must be on the warm branch, and
//!    it must carry a verification receipt (or a stated reason for none). The
//!    request goes into `deploy/queue/`.
//! 2. **built** (`midas hub deploy-build`, as the hub's unprivileged user, like
//!    the warmer): a node is taken like any agent takes one, its checkout is set
//!    to exactly that commit with nothing else in it, the recipe's steps run,
//!    and the artifacts are copied back into `deploy/work/<id>/files`. The
//!    request moves to `deploy/ready/`.
//! 3. **published** (`midas hub deploy-publish`, as root, started by a `.path`
//!    unit on `deploy/ready/`): what to publish where, which checks run first
//!    and as whom, all come from the root-owned `hub.conf`. The artifacts are
//!    read out of the hub user's directory without following a symlink at any
//!    level, into root's own staging directory; the checks run there as the
//!    service's user; then each is installed atomically and the restart stamp
//!    written. Root never writes into the hub user's directories — it reports
//!    by events, which go to the hub over HTTP, so no log file becomes root's.
//!
//! What a deploy is, step by step, is in the event log (`midas log --kind
//! deploy_…`), keyed by the deploy's id.

use std::collections::{BTreeMap, HashMap};
use std::ffi::{CStr, CString, OsStr, OsString};
use std::fs::{self, File, OpenOptions};
use std::io::{Read, Write};
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
use std::os::unix::io::{AsRawFd, FromRawFd};
use std::path::{Component, Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

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

use crate::conf::Deploy;
use crate::events;
use crate::registry::{self, Locked};
use crate::warm::{shell_quote, ssh, ssh_raw, SSH_CONFIG};

const OWNER: &str = "deployer";
const TTL: i64 = 7200;
/// How long a deploy waits in line for a node before it gives up.
const WAIT_FOR_NODE_S: u64 = 3600;
/// How long the queue for a machine must sit still before its builder takes a batch.
const SETTLE_S: u64 = 4;
const CHECKOUT: &str = "/work/checkout";

/// The hub user's side: `queue/`, `work/<id>/`, `ready/`.
pub fn dir() -> PathBuf {
    std::env::var_os("MIDAS_DEPLOY_DIR").map(PathBuf::from).unwrap_or_else(|| crate::mirror::base().join("deploy"))
}

/// Root's side: what is about to be published, copied out of the hub user's reach.
fn staging() -> PathBuf {
    std::env::var_os("MIDAS_DEPLOY_STAGING").map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/var/lib/midas/deploy"))
}

pub fn is_sha(s: &str) -> bool {
    s.len() == 40 && s.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}

/// A deploy's id: when, what and which commit — and nothing a path could misread.
fn id_ok(id: &str) -> bool {
    !id.is_empty() && id.len() <= 80 && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
}

fn write_atomic(path: &Path, text: &str) -> Result<()> {
    let tmp = path.with_extension("tmp");
    fs::write(&tmp, text)?;
    fs::rename(&tmp, path)?;
    Ok(())
}

// ── Verification receipts ────────────────────────────────────────────────────

fn verified_file() -> PathBuf {
    registry::root().join("verified.jsonl")
}

/// The landing gate passed at `sha`: what ran, where, by whom. The deploy's
/// precondition, so a commit nobody tested is not published by accident. It
/// is a record, not a proof — whoever holds a caller key could write one, and
/// whoever holds a caller key can already run anything on a node.
pub fn record_verified(sha: &str, by: &str, fields: &Value) -> Result<Value> {
    if !is_sha(sha) {
        bail!("a receipt is for a full commit sha, not {sha:?}");
    }
    let mut r = json!({"sha": sha, "by": by, "at": registry::now()});
    for k in ["steps", "scope", "node"] {
        if let Some(v) = fields[k].as_str() {
            r[k] = json!(v.chars().take(200).collect::<String>());
        }
    }
    let mut f = OpenOptions::new().create(true).append(true).open(verified_file())?;
    f.write_all(format!("{r}\n").as_bytes())?;
    events::emit("verified", json!({"sha": sha, "actor": by, "steps": r["steps"], "node": r["node"]}));
    Ok(r)
}

/// The latest receipt for `sha`, if there is one.
pub fn verification(sha: &str) -> Option<Value> {
    fs::read_to_string(verified_file()).ok()?.lines().rev()
        .filter_map(|l| serde_json::from_str::<Value>(l).ok())
        .find(|r| r["sha"] == sha)
}

// ── 1. Asking ────────────────────────────────────────────────────────────────

/// `POST /v1/deploy`: check the request and queue it. `sha` none means the tip
/// of the warm branch, fetched now — a deploy is usually asked for seconds
/// after the landing it publishes.
pub fn request(target: &str, sha: Option<&str>, by: &str, unverified: Option<&str>) -> Result<Value> {
    let t = crate::conf::hub().target(target)?;
    t.deploy.check()?;
    let repo = crate::mirror::repo_name(&t.repo)?;
    crate::mirror::fetch_now(&repo).context("fetching the repository")?;
    let branch = &t.branch;
    let tip = git(&repo, &["rev-parse", &format!("refs/heads/{branch}")])?;
    let sha = match sha {
        None => tip.clone(),
        Some(s) => git(&repo, &["rev-parse", "--verify", "--quiet", &format!("{s}^{{commit}}")])
            .map_err(|_| anyhow!("{s} is not a commit in {repo}"))?,
    };
    if !is_ancestor(&repo, &sha, &tip)? {
        bail!("{} is not on {branch}: a deploy publishes what has landed", &sha[..8]);
    }
    let receipt = verification(&sha);
    let unverified = unverified.map(str::trim).filter(|r| !r.is_empty());
    if receipt.is_none() && unverified.is_none() {
        bail!("{} has no receipt from the landing gate (finish-branch records one with `midas verified`); \
               run the gate, or deploy it anyway with --unverified \"why\"", &sha[..8]);
    }
    let id = format!("{}-{target}-{}", chrono::Utc::now().format("%Y%m%d-%H%M%S"), &sha[..8]);
    if !id_ok(&id) {
        bail!("deploy targets are lowercase letters, digits and dashes");
    }
    let req = json!({
        "id": id, "target": target, "repo": t.repo, "sha": sha, "by": by, "at": registry::now(),
        "verified": receipt, "unverified": unverified,
    });
    for d in ["queue", "work", "ready"] {
        fs::create_dir_all(dir().join(d))?;
    }
    write_atomic(&dir().join("queue").join(format!("{id}.json")), &req.to_string())?;
    events::emit("deploy_queued", json!({
        "deploy": id, "target": target, "repo": t.repo, "sha": sha, "actor": by, "unverified": unverified,
        "verified_on": receipt.as_ref().and_then(|r| r["node"].as_str().map(str::to_string)),
    }));
    Ok(req)
}

/// git in a repository's mirror on the hub.
fn git(repo: &str, args: &[&str]) -> Result<String> {
    crate::util::git(&crate::mirror::mirror_path(repo), args)
}

fn is_ancestor(repo: &str, sha: &str, tip: &str) -> Result<bool> {
    Ok(Command::new("git").arg("--git-dir").arg(crate::mirror::mirror_path(repo))
        .args(["merge-base", "--is-ancestor", sha, tip]).status()?.success())
}

/// What happened to one deploy, from the event log.
pub fn status(id: &str) -> Result<Value> {
    if !id_ok(id) {
        bail!("no such deploy");
    }
    let evs: Vec<Value> = events::read_at(&registry::root(), &events::Filter {
        since: chrono::Duration::days(3), kinds: vec![], node: None, actor: None,
    }).into_iter().filter(|e| e["deploy"] == id).collect();
    let state = match evs.last().and_then(|e| e["kind"].as_str()) {
        Some("deploy_published") => "published",
        Some("deploy_failed") => "failed",
        Some("deploy_built") => "publishing",
        Some(_) => "building",
        None => "unknown",
    };
    Ok(json!({"id": id, "state": state, "events": evs}))
}

/// The targets, and the deploys of the last week.
pub fn overview() -> Value {
    let recent: Vec<Value> = events::read_at(&registry::root(), &events::Filter {
        since: chrono::Duration::days(7),
        kinds: vec!["deploy_queued".into(), "deploy_published".into(), "deploy_failed".into()],
        node: None, actor: None,
    });
    json!({
        "targets": crate::conf::hub().targets().iter().map(|t| json!({"target": t.name, "repo": t.repo, "machine": t.deploy.machine,
            "after_landing": t.deploy.after_landing,
            "publishes": t.deploy.publish.iter().map(|p| p.to.clone()).collect::<Vec<_>>()})).collect::<Vec<_>>(),
        "recent": recent,
    })
}

/// Who asked for a deploy, as the session (`owner`) it came from: from the
/// hub's own `deploy_queued`, never one posted to `/v1/events` (anyone may post
/// there), and none for a person who asked without a session.
fn requester(evs: &[Value], id: &str) -> Option<String> {
    let by = evs.iter().find(|e| e["kind"] == "deploy_queued" && e["deploy"] == id && e.get("via_hub_from").is_none())?
        ["actor"].as_str()?;
    let owner = by.split_once(':')?.1;
    Some(owner.strip_prefix("gate-").unwrap_or(owner).to_string()).filter(|o| !o.is_empty())
}

/// The deploys not yet published or failed, by the session that asked for
/// each: what a session's page shows while its agent waits on one.
pub fn in_flight() -> BTreeMap<String, Vec<Value>> {
    let evs: Vec<Value> = events::read_at(&registry::root(), &events::Filter {
        since: chrono::Duration::hours(6),
        kinds: ["deploy_queued", "deploy_waiting", "deploy_building", "deploy_step", "deploy_built", "deploy_published", "deploy_failed"]
            .map(String::from).to_vec(),
        node: None, actor: None,
    });
    by_requester(&evs, running_in(&evs))
}

fn by_requester(evs: &[Value], running: Vec<Value>) -> BTreeMap<String, Vec<Value>> {
    let mut out = BTreeMap::new();
    for d in running {
        if let Some(owner) = d["deploy"].as_str().and_then(|id| requester(evs, id)) {
            out.entry(owner).or_insert_with(Vec::new).push(d);
        }
    }
    out
}

/// Every deploy not yet published or failed, each with its steps (`progress`),
/// whoever asked: the hub's own after landings too, which the page's landing
/// track follows.
pub fn running() -> Vec<Value> {
    running_in(&events::read_at(&registry::root(), &events::Filter {
        since: chrono::Duration::hours(6),
        kinds: ["deploy_queued", "deploy_waiting", "deploy_building", "deploy_step", "deploy_built", "deploy_published", "deploy_failed"]
            .map(String::from).to_vec(),
        node: None, actor: None,
    }))
}

fn running_in(evs: &[Value]) -> Vec<Value> {
    if open_ids(evs).is_empty() {
        return Vec::new();
    }
    // What each kind of step took before: only asked for when something runs.
    let usual = Usual::of(&events::read_at(&registry::root(), &events::Filter {
        since: chrono::Duration::days(14),
        kinds: ["deploy_queued", "deploy_building", "deploy_step", "deploy_built", "deploy_published"].map(String::from).to_vec(),
        node: None, actor: None,
    }));
    let targets = crate::conf::hub().targets();
    let steps_of = |t: &str| targets.iter().find(|x| x.name == t).map(|x| x.deploy.steps.clone()).unwrap_or_default();
    all_pending(evs, &steps_of, &usual)
}

/// The deploys asked for in these events that have not ended.
fn open_ids(evs: &[Value]) -> Vec<&str> {
    evs.iter()
        .filter(|e| e["kind"] == "deploy_queued" && e.get("via_hub_from").is_none())
        .filter_map(|e| e["deploy"].as_str())
        .filter(|id| !evs.iter().any(|e| e["deploy"] == *id && matches!(e["kind"].as_str(), Some("deploy_published" | "deploy_failed"))))
        .collect()
}

fn all_pending(evs: &[Value], steps_of: &dyn Fn(&str) -> Vec<String>, usual: &Usual) -> Vec<Value> {
    open_ids(evs).into_iter().filter_map(|id| pending(evs, id, steps_of, usual)).collect()
}

fn ts_of(e: &Value) -> Option<i64> {
    e["ts"].as_str().and_then(|t| chrono::DateTime::parse_from_rfc3339(t).ok()).map(|t| t.timestamp())
}

fn median(mut v: Vec<i64>) -> i64 {
    v.sort();
    v[v.len() / 2]
}

/// How long deploys take as a rule, in seconds, from those of the last weeks
/// that were published: the whole of one per target, from asked for to
/// published; each build step by what it runs; publishing per target.
#[derive(Default)]
struct Usual {
    total: BTreeMap<String, i64>,
    steps: BTreeMap<String, i64>,
    publish: BTreeMap<String, i64>,
}

impl Usual {
    fn of(evs: &[Value]) -> Usual {
        let mut asked: HashMap<&str, (&str, i64)> = HashMap::new();
        let mut built: HashMap<&str, i64> = HashMap::new();
        let (mut total, mut steps, mut publish): (BTreeMap<String, Vec<i64>>, BTreeMap<String, Vec<i64>>, BTreeMap<String, Vec<i64>>) = Default::default();
        for e in evs {
            let (Some(id), Some(at)) = (e["deploy"].as_str(), ts_of(e)) else { continue };
            match e["kind"].as_str() {
                Some("deploy_queued") if e.get("via_hub_from").is_none() => {
                    if let Some(t) = e["target"].as_str() {
                        asked.insert(id, (t, at));
                    }
                }
                Some("deploy_step") if e["ok"] == true => {
                    if let (Some(s), Some(secs)) = (e["step"].as_str(), e["seconds"].as_i64()) {
                        steps.entry(s.to_string()).or_default().push(secs);
                    }
                }
                Some("deploy_built") => {
                    built.insert(id, at);
                }
                Some("deploy_published") => {
                    if let Some((t, from)) = asked.get(id) {
                        total.entry(t.to_string()).or_default().push(at - from);
                        if let Some(b) = built.get(id) {
                            publish.entry(t.to_string()).or_default().push(at - b);
                        }
                    }
                }
                _ => {}
            }
        }
        let med = |m: BTreeMap<String, Vec<i64>>| m.into_iter().map(|(k, v)| (k, median(v))).collect();
        Usual { total: med(total), steps: med(steps), publish: med(publish) }
    }
}

/// The step of a deploy that fetches what it built off the node (`build_batch`).
const FETCH: &str = "fetch the artifacts";
/// The step that checks the commit out on the node, once for a whole batch (`build_batch`).
const CHECK_OUT: &str = "checkout";

/// One deploy not yet published or failed, and how far it is: each step —
/// getting a node, the target's build steps, fetching, publishing — done (and
/// what it took), running (since when), or to come, each with what it takes as
/// a rule. None for one that has ended.
fn pending(evs: &[Value], id: &str, steps_of: &dyn Fn(&str) -> Vec<String>, usual: &Usual) -> Option<Value> {
    let mine: Vec<&Value> = evs.iter().filter(|e| e["deploy"] == id).collect();
    let q = mine.iter().find(|e| e["kind"] == "deploy_queued" && e.get("via_hub_from").is_none())?;
    if mine.iter().any(|e| matches!(e["kind"].as_str(), Some("deploy_published" | "deploy_failed"))) {
        return None;
    }
    let target = q["target"].as_str().unwrap_or_default();
    let node = mine.iter().rev().find_map(|e| e["node"].as_str());
    let phase = match mine.last().and_then(|e| e["kind"].as_str()) {
        Some("deploy_waiting") => format!("waiting for a {} node", mine.last().unwrap()["machine"].as_str().unwrap_or("free")),
        Some("deploy_building" | "deploy_step") => format!("building on {}", node.unwrap_or("a node")),
        Some("deploy_built") => "publishing".to_string(),
        _ => "queued".to_string(),
    };
    let building = mine.iter().rfind(|e| e["kind"] == "deploy_building").and_then(|e| ts_of(e));
    let built = mine.iter().find(|e| e["kind"] == "deploy_built").and_then(|e| ts_of(e));
    // The build node's steps, by name: those the hub posts itself once it is built
    // (`staged`, its checks) are publishing's.
    let done: Vec<&&Value> = mine.iter().filter(|e| e["kind"] == "deploy_step" && e.get("via_hub_from").is_none()).collect();
    let ended = |name: &str| done.iter().find(|e| e["step"] == name);
    let mut names = steps_of(target);
    names.push(FETCH.into());
    // A batch checks out once, as its first deploy's step: another's has none to wait for.
    if ended(CHECK_OUT).is_some() || done.is_empty() {
        names.insert(0, CHECK_OUT.into());
    }
    let mut steps = vec![match building {
        Some(b) => json!({"name": "get a node", "state": "done", "seconds": ts_of(q).map(|a| b - a)}),
        None => json!({"name": "get a node", "state": "now", "since": ts_of(q)}),
    }];
    // Each build step ends with its event; the next one begins then.
    let mut from = building;
    let mut running = building.is_some() && built.is_none();
    for name in &names {
        let typical = usual.steps.get(name);
        steps.push(match ended(name) {
            Some(e) => {
                let end = ts_of(e);
                // Fetching says no seconds of its own: from the step before it.
                let took = e["seconds"].as_i64().or_else(|| Some(end? - from?));
                from = end.or(from);
                json!({"name": name, "state": "done", "seconds": took, "typical": typical})
            }
            None if running => {
                running = false;
                json!({"name": name, "state": "now", "since": from, "typical": typical})
            }
            None => json!({"name": name, "state": "todo", "typical": typical}),
        });
    }
    steps.push(json!({"name": "publish", "state": if built.is_some() { "now" } else { "todo" }, "since": built, "typical": usual.publish.get(target)}));
    Some(json!({
        "deploy": id, "target": target, "sha": q["sha"], "since": q["ts"], "phase": phase,
        "typical": usual.total.get(target), "steps": steps,
    }))
}

/// A deploy has ended: tell the session that asked, as a note read at its next
/// prompt or tool call. It wakes no idle session (`collab::wakes`): the page
/// shows the deploy to the person already. The words are the hub's own —
/// an outcome posted to `/v1/events` names only the deploy — and a reason is
/// passed on only from the hub's own log line.
pub fn finished(ev: &Value) {
    let Some(id) = ev["deploy"].as_str() else { return };
    let evs = events::read_at(&registry::root(), &events::Filter {
        since: chrono::Duration::days(2), kinds: vec!["deploy_queued".into()], node: None, actor: None,
    });
    let Some(owner) = requester(&evs, id) else { return };
    let Some(q) = evs.iter().find(|e| e["deploy"] == id && e.get("via_hub_from").is_none()) else { return };
    let what = format!("{} deploy of {}", q["target"].as_str().unwrap_or("the"), q["sha"].as_str().unwrap_or("").get(..8).unwrap_or("?"));
    let text = if ev["kind"] == "deploy_published" {
        format!("The {what} you asked for is live (deploy {id}).")
    } else {
        let stage = if ev["stage"] == "publish" { "publishing" } else { "building" };
        let why: String = ev["what"].as_str().filter(|_| ev.get("via_hub_from").is_none())
            .map(|w| format!(": {}", w.chars().take(600).collect::<String>())).unwrap_or_default();
        format!("The {what} you asked for failed while {stage}{why}. Each step is at /v1/deploys/{id} on the hub.")
    };
    let _ = crate::collab::say("hub", &owner, &text, "deploy");
}

// ── 2. Building (the hub's user) ─────────────────────────────────────────────

/// Who a deploy built on `machine` takes its node as: one name per machine, so
/// the builders of two machines each keep their own place in a node line.
fn owner(machine: &str) -> String {
    format!("{OWNER}:{machine}")
}

/// The queued requests, oldest first, with the machine each is built on (none
/// for one whose target hub.conf no longer has: it fails where it is built).
fn queued() -> Vec<(PathBuf, Value, Option<String>)> {
    let conf = crate::conf::hub();
    let mut paths: Vec<PathBuf> = fs::read_dir(dir().join("queue")).into_iter().flatten().flatten()
        .map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "json")).collect();
    paths.sort();
    paths.into_iter().map(|p| {
        let req: Value = serde_json::from_str(&fs::read_to_string(&p).unwrap_or_default()).unwrap_or(Value::Null);
        let machine = conf.target(req["target"].as_str().unwrap_or("")).ok().map(|t| t.deploy.machine);
        (p, req, machine)
    }).collect()
}

/// `midas hub deploy-build`: every queued request, oldest first — a builder
/// for each machine at once, so an APK built on a Mac never holds back a
/// server built on the vps (it held every vps target back for the Mac's 8
/// minutes and more, 2026-10-28). Each builder takes the requests of one
/// commit of one project together, on one node, from one checkout.
///
/// The queue is looked at again while the builders run, not only once they
/// have all ended: a landing queues its targets one request at a time, and
/// this starts on the first. Looked at once, the APK queued a second before
/// the servers was all it saw, and the vps sat idle through the Mac's build
/// (2026-10-29).
pub fn build_pending() -> Result<i32> {
    let mut running: HashMap<String, std::thread::JoinHandle<Result<bool>>> = HashMap::new();
    // Machines this process leaves alone: another process holds their builder
    // and takes what is queued for them, or this one's failed to start.
    let mut elsewhere = std::collections::BTreeSet::new();
    loop {
        for (m, b) in running.extract_if(|_, b| b.is_finished()) {
            if !matches!(b.join(), Ok(Ok(true))) {
                elsewhere.insert(m);
            }
        }
        for (_, _, m) in queued() {
            let m = m.unwrap_or_default();
            if !running.contains_key(&m) && !elsewhere.contains(&m) {
                let name = m.clone();
                running.insert(m, std::thread::spawn(move || build_on(&name)));
            }
        }
        if running.is_empty() {
            return Ok(0);
        }
        std::thread::sleep(std::time::Duration::from_secs(2));
    }
}

/// Build what is queued for `machine` until nothing is; false when another
/// process holds its builder already.
fn build_on(machine: &str) -> Result<bool> {
    let name: String = machine.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' { c } else { '_' }).collect();
    let lock = OpenOptions::new().create(true).append(true).open(dir().join(format!(".build-{name}.lock")))?;
    // SAFETY: flock on a descriptor we own.
    if unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 {
        return Ok(false);
    }
    loop {
        let mine: Vec<(PathBuf, Value)> = queued().into_iter()
            .filter(|(_, _, m)| m.as_deref().unwrap_or("") == machine).map(|(p, r, _)| (p, r)).collect();
        let Some((_, first)) = mine.first() else { return Ok(true) };
        // A landing queues its targets one request at a time, a second or so
        // apart: let them all arrive, or the first is built alone and the rest
        // wait out its whole build for the next batch (the APK alone, then the
        // web page, 2026-10-29).
        if mine.iter().any(|(p, _)| fs::metadata(p).and_then(|m| m.modified()).ok()
            .and_then(|t| t.elapsed().ok()).is_some_and(|age| age < Duration::from_secs(SETTLE_S))) {
            std::thread::sleep(Duration::from_secs(1));
            continue;
        }
        // The oldest, and every other queued for the same commit of the same project.
        let key = |r: &Value| (crate::conf::hub().target(r["target"].as_str().unwrap_or("")).ok().map(|t| t.repo), r["sha"].clone());
        let k = key(first);
        let mut batch = Vec::new();
        for (path, req) in mine.iter().filter(|(_, r)| key(r) == k) {
            let id = req["id"].as_str().unwrap_or("").to_string();
            if !id_ok(&id) || path.file_stem().is_none_or(|s| s != id.as_str()) {
                let _ = fs::remove_file(path);
                continue;
            }
            let work = dir().join("work").join(&id);
            let _ = fs::remove_dir_all(&work);
            fs::create_dir_all(&work)?;
            fs::rename(path, work.join("request.json"))?;
            batch.push((id, req.clone(), work));
        }
        build_batch(machine, &batch);
    }
}

/// What `request` checked, again, for one request: a request is a file in the
/// queue, and anything that can write a file there must not get an unlanded or
/// ungated commit built and published by root. The project is the target's,
/// from hub.conf, never the request's.
fn vet(req: &Value) -> Result<(crate::conf::Target, String)> {
    let conf = crate::conf::hub();
    let target = req["target"].as_str().unwrap_or("");
    let sha = req["sha"].as_str().filter(|s| is_sha(s)).ok_or_else(|| anyhow!("the request has no commit"))?;
    let t = conf.target(target)?;
    t.deploy.check()?;
    let repo = crate::mirror::repo_name(&t.repo)?;
    let tip = git(&repo, &["rev-parse", &format!("refs/heads/{}", t.branch)])?;
    if !is_ancestor(&repo, sha, &tip)? {
        bail!("{} is not on {}: a deploy publishes what has landed", &sha[..8], t.branch);
    }
    if verification(sha).is_none() && req["unverified"].as_str().is_none_or(|r| r.trim().is_empty()) {
        bail!("{} has no receipt from the landing gate, and the request gives no reason to deploy it anyway", &sha[..8]);
    }
    Ok((t, sha.to_string()))
}

fn failed(id: &str, req: &Value, work: &Path, e: &anyhow::Error) {
    let _ = fs::remove_dir_all(work);
    events::emit("deploy_failed", json!({
        "deploy": id, "target": req["target"], "sha": req["sha"], "stage": "build", "what": format!("{e:#}"),
    }));
}

/// Build one commit's requests for `machine` on one node: one take, one
/// checkout, then each target's steps and artifacts in turn. One that fails
/// fails alone; the checkout failing fails them all.
fn build_batch(machine: &str, batch: &[(String, Value, PathBuf)]) {
    let mut ok = Vec::new();
    for (id, req, work) in batch {
        match vet(req) {
            Ok(v) => ok.push((id, req, work, v)),
            Err(e) => failed(id, req, work, &e),
        }
    }
    // Lower `order` first; the sort is stable, so ties keep the order asked.
    ok.sort_by_key(|(_, _, _, (t, _))| t.deploy.order);
    let Some((first_id, _, _, (t0, sha))) = ok.first() else { return };
    let names: Vec<&str> = ok.iter().map(|(_, _, _, (t, _))| t.name.as_str()).collect();
    let node = match take_node(first_id, &names.join(", "), sha, machine, &t0.branch) {
        Ok(n) => n,
        Err(e) => {
            for (id, req, work, _) in &ok {
                failed(id, req, work, &e);
            }
            return;
        }
    };
    let conf = crate::conf::hub();
    let dir = checkout_of(&conf, &t0.repo);
    for (id, _, _, (t, _)) in &ok {
        events::emit("deploy_building", json!({"deploy": id, "node": node}));
        events::emit("deploy_build_start", json!({"deploy": id, "target": t.name, "sha": sha, "node": node}));
    }

    // A build outlives a lease's renewal interval; keep it held while it runs.
    let stop = Arc::new(AtomicBool::new(false));
    let beat = {
        let (stop, node) = (stop.clone(), node.clone());
        std::thread::spawn(move || {
            while !stop.load(Ordering::Relaxed) {
                for _ in 0..120 {
                    if stop.load(Ordering::Relaxed) {
                        return;
                    }
                    std::thread::sleep(Duration::from_secs(1));
                }
                let _ = registry::renew(None, Some(&node), Some("deploy"));
            }
        })
    };
    let checkout = (|| -> Result<()> {
        step(first_id, &node, CHECK_OUT, &format!(
            "{} && git fetch --quiet origin && git checkout --quiet --force --detach {sha} \
             && git reset --quiet --hard {sha} && git clean -qfdx -e /target -e '/.midas*'", enter(&dir, &t0.repo)))?;
        // Exactly that commit and nothing beside it: an agent's flush may have
        // left edits here, and they must not ride along into production. So no
        // `-e node_modules` here, as the warmer has: what a session installed
        // there is not what the lockfile says until a build installs it afresh.
        let state = ssh(&node, &format!("cd {} && git rev-parse HEAD && git status --porcelain", shell_quote(&dir)))?;
        let mut lines = state.lines();
        if lines.next() != Some(sha.as_str()) || lines.any(|l| !l.trim().is_empty()) {
            bail!("the checkout on {node} is not exactly {}: {}", &sha[..8], state.trim());
        }
        Ok(())
    })();
    for (id, req, work, (t, _)) in &ok {
        let started = Instant::now();
        let built = checkout.as_ref().map_err(|e| anyhow!("{e:#}")).and_then(|_| {
            for s in &t.deploy.steps {
                step(id, &node, s, &format!("cd {} && nice -n 10 bash -c {}", shell_quote(&dir), shell_quote(s)))?;
            }
            fetch(&node, &dir, &t.deploy, &work.join("files"))?;
            events::emit("deploy_step", json!({"deploy": id, "node": node, "step": "fetch the artifacts", "ok": true}));
            Ok(())
        });
        match built.and_then(|_| write_atomic(&dir_ready(id), &req.to_string())) {
            Ok(()) => events::emit("deploy_built", json!({
                "deploy": id, "target": req["target"], "sha": req["sha"], "node": node, "seconds": started.elapsed().as_secs(),
            })),
            Err(e) => failed(id, req, work, &e),
        }
    }
    stop.store(true, Ordering::Relaxed);
    let _ = beat.join();
    if let Ok(mut reg) = Locked::open() {
        if reg.leases().get(&node).is_some_and(|l| l["owner"] == owner(machine)) {
            reg.leases_mut().remove(&node);
            reg.mark();
            let _ = reg.commit();
        }
    }
}

fn dir_ready(id: &str) -> PathBuf {
    dir().join("ready").join(format!("{id}.json"))
}

/// Where a project's checkout is on a node: the node's own (`/work/checkout`)
/// for the first repository, which is what it keeps warm; beside it, as a
/// session's flush puts it (`flush::checkout_for`), for any other.
fn checkout_of(conf: &crate::conf::HubConf, repo: &str) -> String {
    if conf.first_repo().as_deref() == Some(repo) {
        CHECKOUT.to_string()
    } else {
        format!("/work/repos/{repo}")
    }
}

/// The shell that makes `dir` a checkout of `repo` with an `origin` on the
/// hub, and goes into it. The node's own has one already; another project's
/// may not exist yet, or be one a session's flush made with no origin: its
/// origin is the node's own with the repository's name in place of its own
/// (`midas@<hub>:<owner>/<name>.git`, `mirror.rs`).
fn enter(dir: &str, repo: &str) -> String {
    if dir == CHECKOUT {
        return format!("cd {CHECKOUT}");
    }
    let d = shell_quote(dir);
    let url = format!("\"${{u%:*}}\":{}", shell_quote(&format!("{repo}.git")));
    format!("mkdir -p {d} && cd {d} && {{ [ -d .git ] || git init --quiet; }} \
             && u=$(git -C {CHECKOUT} remote get-url origin) \
             && {{ git remote set-url origin {url} 2>/dev/null || git remote add origin {url}; }}")
}

/// A node from the recipe's machine, taken like any agent takes one: in line
/// behind whoever asked first, and never one that is held.
fn take_node(id: &str, target: &str, sha: &str, machine: &str, branch: &str) -> Result<String> {
    let started = Instant::now();
    let mut said = false;
    loop {
        let claim = registry::claim(&registry::Claim {
            owner: owner(machine), machine: machine.into(), node: None, branch: Some(branch.into()),
            purpose: Some(format!("deploying {target} at {}", &sha[..8])), ttl: TTL, queue: true,
            mode: registry::Mode::Build, rank: None,
        })?;
        match claim {
            Ok(n) => {
                let node = n["id"].as_str().map(str::to_string).ok_or_else(|| anyhow!("the claim named no node"))?;
                events::emit("deploy_building", json!({"deploy": id, "node": node}));
                return Ok(node);
            }
            Err(why) => {
                if !said {
                    events::emit("deploy_waiting", json!({"deploy": id, "machine": machine, "position": why["position"]}));
                    said = true;
                }
                if started.elapsed() > Duration::from_secs(WAIT_FOR_NODE_S) {
                    let _ = registry::unqueue(&owner(machine));
                    bail!("no {machine} node came free in {} minutes", WAIT_FOR_NODE_S / 60);
                }
                std::thread::sleep(Duration::from_secs(15));
            }
        }
    }
}

fn step(id: &str, node: &str, name: &str, cmd: &str) -> Result<()> {
    let t = Instant::now();
    let out = ssh_raw(node, cmd)?;
    let ok = out.status.success();
    let all = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
    let lines: Vec<&str> = all.lines().filter(|l| !l.trim().is_empty()).collect();
    let tail = lines[lines.len().saturating_sub(12)..].join("\n");
    events::emit("deploy_step", json!({
        "deploy": id, "node": node, "step": name, "ok": ok, "seconds": t.elapsed().as_secs(),
        "tail": if ok { None } else { Some(tail.clone()) },
    }));
    if !ok {
        bail!("{name} failed on {node}:\n{tail}");
    }
    Ok(())
}

/// The artifacts, streamed out of the node's checkout as one tar. GNU tar
/// strips `..` and creates symbolic links last, and the publish step refuses a
/// symbolic link anywhere in what it is given anyway.
fn fetch(node: &str, dir: &str, recipe: &Deploy, into: &Path) -> Result<()> {
    fs::create_dir_all(into)?;
    let froms: Vec<String> = recipe.publish.iter().map(|p| shell_quote(&p.from)).collect();
    let mut src = Command::new("ssh")
        .args(["-F", SSH_CONFIG, "-o", "BatchMode=yes", "-o", "ConnectTimeout=15", node])
        // COPYFILE_DISABLE: macOS's tar otherwise adds an AppleDouble `._name`
        // beside every file with extended attributes, and they would be published.
        .arg(format!("COPYFILE_DISABLE=1 tar -C {} -cf - -- {}", shell_quote(dir), froms.join(" ")))
        .stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped())
        .spawn().context("starting ssh")?;
    let out = src.stdout.take().ok_or_else(|| anyhow!("no output from ssh"))?;
    // Read as it comes: read only after the unpack, enough warnings from the node's tar filled
    // the pipe, that tar stopped, and the unpack waited on it until the unit's timeout.
    let errs = src.stderr.take().map(|mut e| std::thread::spawn(move || {
        let mut s = String::new();
        let _ = std::io::Read::read_to_string(&mut e, &mut s);
        s
    }));
    let unpack = Command::new("tar").args(["-xf", "-", "--no-same-owner", "-C"]).arg(into)
        .stdin(out).output().context("running tar")?;
    let status = src.wait()?;
    let said = errs.and_then(|t| t.join().ok()).unwrap_or_default();
    if !status.success() {
        bail!("taking the artifacts off {node}: {}", said.trim());
    }
    if !unpack.status.success() {
        bail!("unpacking the artifacts: {}", String::from_utf8_lossy(&unpack.stderr).trim());
    }
    Ok(())
}

// ── 3. Publishing (root) ─────────────────────────────────────────────────────

/// `midas hub deploy-publish`: every built deploy, as root.
pub fn publish_ready() -> Result<i32> {
    if unsafe { libc::geteuid() } != 0 {
        bail!("publishing is root's: the publish service runs it");
    }
    fs::create_dir_all(staging())?;
    fs::set_permissions(staging(), fs::Permissions::from_mode(0o755))?;
    let lock = OpenOptions::new().create(true).append(true).open(staging().join(".lock"))?;
    // SAFETY: flock on a descriptor we own.
    if unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 {
        return Ok(0);
    }
    let ready = dir().join("ready");
    let mut names: Vec<String> = fs::read_dir(&ready).into_iter().flatten().flatten()
        .filter_map(|e| e.file_name().to_str().map(str::to_string))
        .filter(|n| n.strip_suffix(".json").is_some_and(id_ok))
        .collect();
    names.sort();
    for name in names {
        let id = name.trim_end_matches(".json").to_string();
        let path = ready.join(&name);
        let req = read_nofollow(&path, 64 * 1024).ok()
            .and_then(|b| serde_json::from_slice::<Value>(&b).ok()).unwrap_or(Value::Null);
        // Taken off the list first: a request that fails half-way must not be
        // started again by the path unit, for ever.
        let _ = fs::remove_file(&path);
        let started = Instant::now();
        let outcome = if req["id"] != id.as_str() {
            Err(anyhow!("the request does not match its file"))
        } else {
            publish_one(&id, &req)
        };
        match outcome {
            Ok(()) => root_emit("deploy_published", json!({
                "deploy": id, "target": req["target"], "sha": req["sha"], "actor": req["by"],
                "seconds": started.elapsed().as_secs(),
            })),
            Err(e) => root_emit("deploy_failed", json!({
                "deploy": id, "target": req["target"], "sha": req["sha"], "stage": "publish", "what": format!("{e:#}"),
            })),
        }
        let _ = fs::remove_dir_all(staging().join(&id));
        let _ = fs::remove_dir_all(staging().join(format!("{id}.check")));
        let _ = fs::remove_dir_all(staging().join(format!("{id}.prepare")));
        let _ = fs::remove_dir_all(dir().join("work").join(&id));
    }
    Ok(0)
}

fn publish_one(id: &str, req: &Value) -> Result<()> {
    let target = req["target"].as_str().unwrap_or("");
    let sha = req["sha"].as_str().filter(|s| is_sha(s)).ok_or_else(|| anyhow!("the request has no commit"))?;
    let t = crate::conf::hub().target(target)?;
    let recipe = &t.deploy;
    recipe.check()?;

    // Out of the hub user's reach first, so nothing can change under the checks.
    let staged = staging().join(id);
    let _ = fs::remove_dir_all(&staged);
    fs::create_dir_all(&staged)?;
    fs::set_permissions(&staged, fs::Permissions::from_mode(0o755))?;
    let files = dir().join("work").join(id).join("files");
    for (i, p) in recipe.publish.iter().enumerate() {
        // One artifact may lie inside another (a site's directory, and one file
        // of it published somewhere else too): it is already staged then.
        if recipe.publish[..i].iter().any(|q| Path::new(&p.from).starts_with(&q.from)) {
            continue;
        }
        copy_out(&files.join(&p.from), &staged.join(&p.from)).with_context(|| format!("taking {}", p.from))?;
    }
    root_emit("deploy_step", json!({"deploy": id, "step": "staged", "ok": true}));

    // What only this machine may do to them (sign with a key no node sees), as
    // a user that may read that key; then the tree is root's again, and is
    // checked for links afresh, since that user could have made some.
    if !recipe.prepare.is_empty() {
        let user = recipe.prepare_user.clone().unwrap_or_else(|| "nobody".into());
        chown_tree(&staged, &user)?;
        let r = run_as(id, "prepare", &user, &recipe.prepare, &staged, sha, &format!("{id}.prepare"));
        chown_tree(&staged, "root:root")?;
        r?;
        normalise_tree(&staged)?;
    }

    // The checks, as the service's own user, against the staged artifacts.
    if !recipe.checks.is_empty() {
        let user = recipe.check_user.clone().unwrap_or_else(|| "nobody".into());
        run_as(id, "check", &user, &recipe.checks, &staged, sha, &format!("{id}.check"))
            .context("a check failed, so nothing was replaced")?;
    }

    for p in &recipe.publish {
        install(&staged.join(&p.from), Path::new(&p.to)).with_context(|| format!("publishing to {}", p.to))?;
    }
    if let Some(s) = &recipe.restart_stamp {
        // Last, so the restart can never race the copy.
        install_text(Path::new(s), &format!("{} {id}\n", chrono::Utc::now().to_rfc3339()))?;
    }
    Ok(())
}

/// Run `commands` in order as `user`, in a home of their own (private: a check
/// may copy what the service holds — the simulator's migrate a copy of the
/// live database, every account's row), with `STAGED` and `SHA`.
fn run_as(id: &str, stage: &str, user: &str, commands: &[String], staged: &Path, sha: &str, home: &str) -> Result<()> {
    let home = staging().join(home);
    let _ = fs::remove_dir_all(&home);
    fs::create_dir_all(&home)?;
    let out = Command::new("chown").arg(user).arg(&home).output()?;
    if !out.status.success() {
        bail!("no user {user} to run the {stage} as: {}", String::from_utf8_lossy(&out.stderr).trim());
    }
    fs::set_permissions(&home, fs::Permissions::from_mode(0o700))?;
    for c in commands {
        let t = Instant::now();
        let out = Command::new("runuser").args(["-u", user, "--", "env", "-i"])
            .arg("PATH=/usr/local/bin:/usr/bin:/bin")
            .arg(format!("HOME={}", home.display()))
            .arg(format!("STAGED={}", staged.display()))
            .arg(format!("SHA={sha}"))
            .args(["bash", "-c", c])
            .current_dir(&home).stdin(Stdio::null()).output().with_context(|| format!("running the {stage}"))?;
        let ok = out.status.success();
        let all = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
        let lines: Vec<&str> = all.lines().filter(|l| !l.trim().is_empty()).collect();
        let tail = lines[lines.len().saturating_sub(12)..].join("\n");
        root_emit("deploy_step", json!({
            "deploy": id, "step": format!("{stage}: {}", c.lines().next().unwrap_or("")), "ok": ok,
            "seconds": t.elapsed().as_secs(), "tail": if ok { None } else { Some(tail.clone()) },
        }));
        if !ok {
            bail!("the {stage} failed:\n{tail}");
        }
    }
    Ok(())
}

fn chown_tree(dir: &Path, owner: &str) -> Result<()> {
    // -h: a link is never followed, should one be there to be refused later.
    let out = Command::new("chown").args(["-R", "-h", owner]).arg(dir).output()?;
    if !out.status.success() {
        bail!("chown {owner}: {}", String::from_utf8_lossy(&out.stderr).trim());
    }
    Ok(())
}

/// After a `prepare`: nothing but files and directories, with the modes
/// `copy_out` gives them.
fn normalise_tree(dir: &Path) -> Result<()> {
    for e in fs::read_dir(dir)? {
        let e = e?;
        let m = fs::symlink_metadata(e.path())?;
        if m.is_dir() {
            fs::set_permissions(e.path(), fs::Permissions::from_mode(0o755))?;
            normalise_tree(&e.path())?;
        } else if m.is_file() {
            let mode = if m.permissions().mode() & 0o111 != 0 { 0o755 } else { 0o644 };
            fs::set_permissions(e.path(), fs::Permissions::from_mode(mode))?;
        } else {
            bail!("the prepare left {} — neither a file nor a directory", e.path().display());
        }
    }
    Ok(())
}

/// Open `path` refusing a symbolic link at every component, from `/` down: the
/// hub user owns everything under its directory, and could swap any part of a
/// path for a link to somewhere only root may read.
fn open_nofollow(path: &Path, dir: bool) -> Result<File> {
    open_nofollow_in(path, dir, false)
}

/// `open_nofollow`, and with `make`, a directory level that is missing is made
/// on the way (root's, 0755) rather than refused.
fn open_nofollow_in(path: &Path, dir: bool, make: bool) -> Result<File> {
    if !path.is_absolute() {
        bail!("{} is not absolute", path.display());
    }
    let root = CString::new("/")?;
    // SAFETY: plain open(2); the descriptor is owned by the File made below.
    let mut fd = unsafe { libc::open(root.as_ptr(), libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC) };
    if fd < 0 {
        bail!("opening /: {}", std::io::Error::last_os_error());
    }
    let parts: Vec<&OsStr> = path.components().filter_map(|c| match c {
        Component::Normal(n) => Some(Ok(n)),
        Component::RootDir => None,
        _ => Some(Err(())),
    }).collect::<std::result::Result<_, _>>().map_err(|_| anyhow!("{} is not a plain path", path.display()))?;
    for (i, name) in parts.iter().enumerate() {
        let last = i + 1 == parts.len();
        let mut flags = libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_CLOEXEC | libc::O_NONBLOCK;
        if !last || dir {
            flags |= libc::O_DIRECTORY;
        }
        let c = CString::new(std::os::unix::ffi::OsStrExt::as_bytes(*name))?;
        // SAFETY: openat(2) relative to a descriptor this function owns.
        let mut next = unsafe { libc::openat(fd, c.as_ptr(), flags) };
        if next < 0 && make && (!last || dir) && std::io::Error::last_os_error().kind() == std::io::ErrorKind::NotFound {
            // SAFETY: mkdirat(2) relative to the same descriptor; a race that
            // made it meanwhile is fine, the open below decides.
            unsafe { libc::mkdirat(fd, c.as_ptr(), 0o755) };
            next = unsafe { libc::openat(fd, c.as_ptr(), flags) };
        }
        let err = std::io::Error::last_os_error();
        // SAFETY: closing the descriptor opened above, exactly once.
        unsafe { libc::close(fd) };
        if next < 0 {
            bail!("{}: {} (a symbolic link is refused)", path.display(), err);
        }
        fd = next;
    }
    // SAFETY: `fd` is a fresh descriptor nothing else owns.
    Ok(unsafe { File::from_raw_fd(fd) })
}

// What root does inside a destination directory, it does relative to that
// directory's descriptor, opened above without following a link: a path would
// be resolved again at every call, and the directory's owner (the agents'
// container, for the copy of midas it runs; the hub's user, for a site it
// serves) could swap any level of it for a link between two calls and have
// root write, or delete, wherever that pointed.

fn cstr(name: &OsStr) -> Result<CString> {
    Ok(CString::new(std::os::unix::ffi::OsStrExt::as_bytes(name))?)
}

fn os_name(c: &CStr) -> &OsStr {
    std::os::unix::ffi::OsStrExt::from_bytes(c.to_bytes())
}

/// What is at `name` in `dir`, without following it: its type bits, or None.
fn kind_at(dir: &File, name: &CStr) -> Option<u32> {
    let mut st: libc::stat = unsafe { std::mem::zeroed() };
    // SAFETY: fstatat(2) into a zeroed stat buffer of the right type.
    let r = unsafe { libc::fstatat(dir.as_raw_fd(), name.as_ptr(), &mut st, libc::AT_SYMLINK_NOFOLLOW) };
    (r == 0).then(|| st.st_mode as u32 & libc::S_IFMT as u32)
}

fn unlink_at(dir: &File, name: &CStr, is_dir: bool) -> std::io::Result<()> {
    // SAFETY: unlinkat(2) relative to a descriptor the caller owns.
    if unsafe { libc::unlinkat(dir.as_raw_fd(), name.as_ptr(), if is_dir { libc::AT_REMOVEDIR } else { 0 }) } != 0 {
        return Err(std::io::Error::last_os_error());
    }
    Ok(())
}

/// The directory `name` in `dir`, refusing a link; made (0755) when `make` and missing.
fn child_dir(dir: &File, name: &CStr, make: bool) -> Result<File> {
    let flags = libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC;
    // SAFETY: openat(2)/mkdirat(2) relative to a descriptor the caller owns.
    let mut fd = unsafe { libc::openat(dir.as_raw_fd(), name.as_ptr(), flags) };
    if fd < 0 && make && std::io::Error::last_os_error().kind() == std::io::ErrorKind::NotFound {
        unsafe { libc::mkdirat(dir.as_raw_fd(), name.as_ptr(), 0o755) };
        fd = unsafe { libc::openat(dir.as_raw_fd(), name.as_ptr(), flags) };
    }
    if fd < 0 {
        bail!("{}: {} (a symbolic link is refused)", name.to_string_lossy(), std::io::Error::last_os_error());
    }
    // SAFETY: a fresh descriptor nothing else owns.
    Ok(unsafe { File::from_raw_fd(fd) })
}

/// The names in `dir`, by its descriptor.
fn names_in(dir: &File) -> Result<Vec<CString>> {
    // SAFETY: fdopendir takes the descriptor over, so it gets a duplicate; closedir frees it.
    let fd = unsafe { libc::dup(dir.as_raw_fd()) };
    if fd < 0 {
        bail!("dup: {}", std::io::Error::last_os_error());
    }
    let d = unsafe { libc::fdopendir(fd) };
    if d.is_null() {
        let e = std::io::Error::last_os_error();
        unsafe { libc::close(fd) };
        bail!("listing a directory: {e}");
    }
    let mut out = Vec::new();
    unsafe {
        libc::rewinddir(d);
        loop {
            let e = libc::readdir(d);
            if e.is_null() {
                break;
            }
            let name = CStr::from_ptr((*e).d_name.as_ptr());
            if name.to_bytes() != b"." && name.to_bytes() != b".." {
                out.push(name.to_owned());
            }
        }
        libc::closedir(d);
    }
    out.sort();
    Ok(out)
}

/// Remove `name` in `dir`, a tree if it is one, never following a link.
fn remove_at(dir: &File, name: &CStr) -> Result<()> {
    let Some(kind) = kind_at(dir, name) else { return Ok(()) };
    if kind == libc::S_IFDIR as u32 {
        let sub = child_dir(dir, name, false)?;
        for n in names_in(&sub)? {
            remove_at(&sub, &n)?;
        }
        drop(sub);
        unlink_at(dir, name, true)?;
    } else {
        unlink_at(dir, name, false)?;
    }
    Ok(())
}

/// A file `staged` (root's own, already checked) put at `name` in `dir`
/// atomically: written beside it, then renamed over whatever was there — never
/// a truncated binary for `Restart=always` to loop on, never a running
/// executable overwritten.
fn install_in(dir: &File, staged: &Path, name: &OsStr) -> Result<()> {
    let tmp = cstr(&OsString::from(format!(".{}.midas-new", name.to_string_lossy())))?;
    let name = cstr(name)?;
    let _ = unlink_at(dir, &tmp, false);
    let mode = fs::metadata(staged)?.permissions().mode() & 0o777;
    // SAFETY: openat(2) relative to a descriptor the caller owns; the new descriptor is owned by the File below.
    let fd = unsafe { libc::openat(dir.as_raw_fd(), tmp.as_ptr(),
        libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL | libc::O_NOFOLLOW | libc::O_CLOEXEC, mode as libc::c_uint) };
    if fd < 0 {
        bail!("creating {}: {}", tmp.to_string_lossy(), std::io::Error::last_os_error());
    }
    let mut dst = unsafe { File::from_raw_fd(fd) };
    let mut src = File::open(staged)?;
    std::io::copy(&mut src, &mut dst)?;
    dst.sync_all()?;
    // SAFETY: fchmod(2) on the descriptor above.
    unsafe { libc::fchmod(fd, mode as libc::mode_t) };
    drop(dst);
    // SAFETY: renameat(2) within the directory the caller owns a descriptor of.
    if unsafe { libc::renameat(dir.as_raw_fd(), tmp.as_ptr(), dir.as_raw_fd(), name.as_ptr()) } != 0 {
        let e = std::io::Error::last_os_error();
        let _ = unlink_at(dir, &tmp, false);
        bail!("putting {} in place: {e}", name.to_string_lossy());
    }
    Ok(())
}

/// Make the directory `dir` hold what `staged` holds: every file installed as
/// above, then whatever `dir` has that `staged` does not, removed. Not one
/// rename of the whole tree, because the directory may be a bind mount's
/// source (a site a web server serves), which a rename would leave behind.
fn sync_into(staged: &Path, dir: &File) -> Result<()> {
    let mut keep = std::collections::BTreeSet::new();
    let mut names: Vec<OsString> = fs::read_dir(staged)?.flatten().map(|e| e.file_name()).collect();
    names.sort();
    for n in names {
        let (from, c) = (staged.join(&n), cstr(&n)?);
        let there = kind_at(dir, &c);
        if fs::symlink_metadata(&from)?.is_dir() {
            if there.is_some_and(|k| k != libc::S_IFDIR as u32) {
                unlink_at(dir, &c, false)?;
            }
            let sub = child_dir(dir, &c, true)?;
            sync_into(&from, &sub)?;
        } else {
            if there == Some(libc::S_IFDIR as u32) {
                remove_at(dir, &c)?;
            }
            install_in(dir, &from, &n)?;
        }
        keep.insert(n);
    }
    for c in names_in(dir)? {
        if !keep.contains(os_name(&c)) {
            remove_at(dir, &c)?;
        }
    }
    Ok(())
}

fn read_nofollow(path: &Path, limit: u64) -> Result<Vec<u8>> {
    let f = open_nofollow(path, false)?;
    if !f.metadata()?.is_file() {
        bail!("{} is not a file", path.display());
    }
    let mut buf = Vec::new();
    f.take(limit).read_to_end(&mut buf)?;
    Ok(buf)
}

/// Copy a file or a directory tree, every open refusing a symbolic link and
/// anything that is neither a file nor a directory. Files keep only whether
/// they are executable.
fn copy_out(from: &Path, to: &Path) -> Result<()> {
    let probe = open_nofollow(from, false)?;
    let meta = probe.metadata()?;
    if meta.is_dir() {
        drop(probe);
        fs::create_dir_all(to)?;
        fs::set_permissions(to, fs::Permissions::from_mode(0o755))?;
        // Listing by path is safe: every entry is opened again, from `/`, refusing links.
        let mut names: Vec<std::ffi::OsString> = fs::read_dir(from)?.flatten().map(|e| e.file_name()).collect();
        names.sort();
        for n in names {
            copy_out(&from.join(&n), &to.join(&n))?;
        }
        Ok(())
    } else if meta.is_file() {
        let mode = if meta.permissions().mode() & 0o111 != 0 { 0o755 } else { 0o644 };
        if let Some(parent) = to.parent() {
            fs::create_dir_all(parent)?;
        }
        let mut src = probe;
        let mut dst = OpenOptions::new().write(true).create_new(true).mode(mode).open(to)
            .with_context(|| format!("creating {}", to.display()))?;
        std::io::copy(&mut src, &mut dst)?;
        dst.sync_all()?;
        fs::set_permissions(to, fs::Permissions::from_mode(mode))?;
        Ok(())
    } else {
        bail!("{} is neither a file nor a directory", from.display())
    }
}

/// A file replaces `to` atomically; a directory is synchronised into `to`,
/// deleting what it no longer has. `to`'s directory is opened refusing a link
/// at every level (and made where missing), and everything from there on is
/// done relative to that descriptor (`install_in`, `sync_into`).
fn install(staged: &Path, to: &Path) -> Result<()> {
    let parent = to.parent().ok_or_else(|| anyhow!("{} has no directory", to.display()))?;
    let name = to.file_name().ok_or_else(|| anyhow!("{} has no name", to.display()))?;
    let dir = open_nofollow_in(parent, true, true).with_context(|| format!("the directory of {}", to.display()))?;
    let c = cstr(name)?;
    if fs::symlink_metadata(staged)?.is_dir() {
        if kind_at(&dir, &c).is_some_and(|k| k != libc::S_IFDIR as u32) {
            unlink_at(&dir, &c, false)?;
        }
        return sync_into(staged, &child_dir(&dir, &c, true)?);
    }
    if kind_at(&dir, &c) == Some(libc::S_IFDIR as u32) {
        bail!("{} is a directory, and the artifact a file", to.display());
    }
    install_in(&dir, staged, name)
}

/// `text` put at `to` as `install` puts a file: written in root's staging
/// directory first, then installed, so the destination's directory is never
/// trusted by path.
fn install_text(to: &Path, text: &str) -> Result<()> {
    let tmp = staging().join(format!(".text-{}", std::process::id()));
    let _ = fs::remove_file(&tmp);
    OpenOptions::new().write(true).create_new(true).mode(0o644).open(&tmp)?.write_all(text.as_bytes())?;
    let r = install(&tmp, to);
    let _ = fs::remove_file(&tmp);
    r
}

/// An event from root: sent to the hub, never written into its log directly,
/// which would leave a log file the hub's own user can no longer append to.
pub(crate) fn root_emit(kind: &str, fields: Value) {
    let ev = events::build(kind, fields);
    eprintln!("{ev}");
    // With root's own caller key (`hub setup` makes it): a deploy's outcome is
    // believed only from a caller, so nothing on the tunnel can post one.
    let key = fs::read_to_string(crate::hubsetup::PUBLISHER_KEY).ok().map(|s| s.trim().to_string()).filter(|k| !k.is_empty());
    let _ = crate::hub::request_auth(&crate::conf::hub().url(), "POST", "/v1/events", Some(&ev.to_string()), key.as_deref());
}

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

    fn scratch(name: &str) -> PathBuf {
        let d = std::env::temp_dir().join(format!("midas-deploy-{name}-{}", std::process::id()));
        let _ = fs::remove_dir_all(&d);
        fs::create_dir_all(&d).unwrap();
        // The temporary directory is itself a symlink on macOS (/var → /private/var).
        fs::canonicalize(&d).unwrap()
    }

    #[test]
    fn a_session_sees_its_own_deploys_until_they_end_and_never_one_posted_in_its_name() {
        let evs = vec![
            json!({"kind": "deploy_queued", "deploy": "a", "target": "atlas", "sha": "0123", "actor": "agent:session-s2"}),
            json!({"kind": "deploy_waiting", "deploy": "a", "machine": "vps"}),
            json!({"kind": "deploy_queued", "deploy": "b", "target": "web", "sha": "4567", "actor": "agent:gate-t7"}),
            json!({"kind": "deploy_building", "deploy": "b", "node": "vps-1"}),
            json!({"kind": "deploy_step", "deploy": "b", "node": "vps-1", "step": "build"}),
            json!({"kind": "deploy_queued", "deploy": "c", "target": "sim", "sha": "89ab", "actor": "sam"}),
            json!({"kind": "deploy_queued", "deploy": "d", "target": "wasm", "sha": "cdef", "actor": "agent:session-s2", "via_hub_from": "10.44.0.9"}),
            json!({"kind": "deploy_queued", "deploy": "e", "target": "apk", "sha": "0000", "actor": "agent:session-s2"}),
            json!({"kind": "deploy_built", "deploy": "e"}),
            json!({"kind": "deploy_published", "deploy": "e"}),
        ];
        let p = by_requester(&evs, all_pending(&evs, &|_| vec![], &Usual::default()));
        assert_eq!(p.keys().collect::<Vec<_>>(), ["session-s2", "t7"]);
        let s2: Vec<(&str, &str)> = p["session-s2"].iter().map(|d| (d["deploy"].as_str().unwrap(), d["phase"].as_str().unwrap())).collect();
        assert_eq!(s2, [("a", "waiting for a vps node")]);
        assert_eq!(p["t7"][0]["phase"], "building on vps-1");
        assert_eq!(requester(&evs, "c"), None, "a person asked: no session to tell");
        assert_eq!(requester(&evs, "d"), None, "posted to /v1/events: anyone could have");
    }

    #[test]
    fn a_deploy_takes_as_a_rule_the_median_from_asked_to_published() {
        let ev = |kind: &str, id: &str, min: u32| json!({"kind": kind, "deploy": id, "target": "web", "ts": format!("2026-10-29T10:{min:02}:00Z")});
        let evs = vec![
            ev("deploy_queued", "a", 0), ev("deploy_published", "a", 4),
            ev("deploy_queued", "b", 10), ev("deploy_published", "b", 16),
            ev("deploy_queued", "c", 20), ev("deploy_published", "c", 25),
            ev("deploy_queued", "d", 30), ev("deploy_failed", "d", 31),
        ];
        assert_eq!(Usual::of(&evs).total.get("web"), Some(&300), "a failed one says nothing of how long one takes");
    }

    #[test]
    fn a_running_deploy_says_each_step_done_running_or_to_come() {
        let at = |s: u32| format!("2026-10-29T10:{:02}:{:02}Z", s / 60, s % 60);
        let before = vec![
            json!({"kind": "deploy_queued", "deploy": "x", "target": "web", "ts": at(0)}),
            json!({"kind": "deploy_step", "deploy": "x", "step": "bun run build", "ok": true, "seconds": 90, "ts": at(100)}),
            json!({"kind": "deploy_step", "deploy": "x", "step": FETCH, "ok": true, "seconds": 4, "ts": at(104)}),
            json!({"kind": "deploy_built", "deploy": "x", "target": "web", "ts": at(104)}),
            json!({"kind": "deploy_published", "deploy": "x", "ts": at(110)}),
        ];
        let usual = Usual::of(&before);
        assert_eq!((usual.steps.get("bun run build"), usual.publish.get("web"), usual.total.get("web")), (Some(&90), Some(&6), Some(&110)));
        let evs = vec![
            json!({"kind": "deploy_queued", "deploy": "y", "target": "web", "ts": at(200), "actor": "agent:session-s2"}),
            json!({"kind": "deploy_building", "deploy": "y", "node": "vps-1", "ts": at(212)}),
            json!({"kind": "deploy_step", "deploy": "y", "step": CHECK_OUT, "ok": true, "seconds": 1, "ts": at(213)}),
            json!({"kind": "deploy_step", "deploy": "y", "step": "bun install", "ok": true, "seconds": 20, "ts": at(233)}),
        ];
        let steps_of = |_: &str| vec!["bun install".to_string(), "bun run build".to_string()];
        let said = |evs: &[Value]| -> Vec<String> {
            let d = &all_pending(evs, &steps_of, &usual)[0];
            d["steps"].as_array().unwrap().iter().map(|s| format!("{} {}", s["name"].as_str().unwrap(), s["state"].as_str().unwrap())).collect()
        };
        assert_eq!(said(&evs), ["get a node done", "checkout done", "bun install done", "bun run build now", "fetch the artifacts todo", "publish todo"]);
        let d = &all_pending(&evs, &steps_of, &usual)[0];
        assert_eq!(d["steps"][0]["seconds"], 12, "the wait for a node is a step of its own");
        assert_eq!((d["steps"][3]["since"].as_i64(), d["steps"][3]["typical"].as_i64()), (Some(ts_of(&evs[3]).unwrap()), Some(90)), "it began when the one before ended");
        assert_eq!(d["typical"], 110);
        // Built: the hub's own steps after it are publishing's, not the build's.
        let mut built = evs.clone();
        built.extend([
            json!({"kind": "deploy_step", "deploy": "y", "step": "bun run build", "ok": true, "seconds": 80, "ts": at(313)}),
            json!({"kind": "deploy_step", "deploy": "y", "step": FETCH, "ok": true, "ts": at(316)}),
            json!({"kind": "deploy_built", "deploy": "y", "ts": at(316)}),
            json!({"kind": "deploy_step", "deploy": "y", "step": "staged", "ok": true, "ts": at(317), "via_hub_from": "10.44.0.1"}),
        ]);
        assert_eq!(said(&built), ["get a node done", "checkout done", "bun install done", "bun run build done", "fetch the artifacts done", "publish now"]);
        assert_eq!(all_pending(&built, &steps_of, &usual)[0]["steps"][4]["seconds"], 3, "fetching is timed from the step before");
        // A second deploy of the batch: the first one's checkout was not its own.
        let second = vec![evs[0].clone(), evs[1].clone(), json!({"kind": "deploy_step", "deploy": "y", "step": "bun install", "ok": true, "seconds": 20, "ts": at(233)})];
        assert_eq!(said(&second)[1], "bun install done");
    }

    #[test]
    fn a_tree_is_copied_out_with_its_executables_and_no_symbolic_link() {
        let d = scratch("copy");
        let src = d.join("files/dist");
        fs::create_dir_all(src.join("sub")).unwrap();
        fs::write(src.join("index.html"), "hi").unwrap();
        fs::write(src.join("sub/run"), "#!/bin/sh\n").unwrap();
        fs::set_permissions(src.join("sub/run"), fs::Permissions::from_mode(0o700)).unwrap();
        copy_out(&src, &d.join("out")).unwrap();
        assert_eq!(fs::read_to_string(d.join("out/index.html")).unwrap(), "hi");
        assert_eq!(fs::metadata(d.join("out/sub/run")).unwrap().permissions().mode() & 0o777, 0o755);
        assert_eq!(fs::metadata(d.join("out/index.html")).unwrap().permissions().mode() & 0o777, 0o644);

        // A link anywhere — inside the tree, or as a directory on the way to it.
        fs::write(d.join("secret"), "root's").unwrap();
        std::os::unix::fs::symlink(d.join("secret"), src.join("leak")).unwrap();
        assert!(copy_out(&src, &d.join("out2")).is_err(), "a link inside the tree");
        fs::remove_file(src.join("leak")).unwrap();
        std::os::unix::fs::symlink(d.join("files"), d.join("via")).unwrap();
        assert!(copy_out(&d.join("via/dist"), &d.join("out3")).is_err(), "a link on the way to it");
        assert!(read_nofollow(&d.join("via/dist/index.html"), 10).is_err());
        assert_eq!(read_nofollow(&src.join("index.html"), 10).unwrap(), b"hi");
    }

    #[test]
    fn a_file_is_replaced_atomically_and_a_directory_synchronised() {
        let d = scratch("install");
        fs::write(d.join("new"), "v2").unwrap();
        fs::set_permissions(d.join("new"), fs::Permissions::from_mode(0o755)).unwrap();
        fs::write(d.join("live"), "v1").unwrap();
        install(&d.join("new"), &d.join("live")).unwrap();
        assert_eq!(fs::read_to_string(d.join("live")).unwrap(), "v2");
        assert_eq!(fs::metadata(d.join("live")).unwrap().permissions().mode() & 0o777, 0o755);
        assert!(!d.join(".live.midas-new").exists());

        fs::create_dir_all(d.join("dist")).unwrap();
        fs::write(d.join("dist/a"), "a").unwrap();
        fs::create_dir_all(d.join("site")).unwrap();
        fs::write(d.join("site/stale"), "old").unwrap();
        fs::create_dir_all(d.join("dist/js")).unwrap();
        fs::write(d.join("dist/js/app.js"), "v2").unwrap();
        fs::create_dir_all(d.join("site/old-dir")).unwrap();
        fs::write(d.join("site/old-dir/x"), "old").unwrap();
        fs::write(d.join("site/js"), "a file where a directory now is").unwrap();
        install(&d.join("dist"), &d.join("site")).unwrap();
        assert_eq!(fs::read_to_string(d.join("site/a")).unwrap(), "a");
        assert_eq!(fs::read_to_string(d.join("site/js/app.js")).unwrap(), "v2");
        assert!(!d.join("site/stale").exists() && !d.join("site/old-dir").exists(), "what the new one does not have goes");
    }

    #[test]
    fn root_never_follows_a_link_in_a_destination() {
        let d = scratch("nofollow");
        fs::create_dir_all(d.join("elsewhere")).unwrap();
        std::os::unix::fs::symlink(d.join("elsewhere"), d.join("bin")).unwrap();
        fs::write(d.join("new"), "v2").unwrap();
        // The destination's directory swapped for a link: refused, nothing written where it points.
        let e = format!("{:#}", install(&d.join("new"), &d.join("bin/midas")).unwrap_err());
        assert!(e.contains("symbolic link"), "{e}");
        assert!(!d.join("elsewhere/midas").exists() && !d.join("elsewhere/.midas.midas-new").exists());
        // A directory that is missing is made on the way.
        install(&d.join("new"), &d.join("made/here/midas")).unwrap();
        assert_eq!(fs::read_to_string(d.join("made/here/midas")).unwrap(), "v2");
        // In a synchronised directory a link is an entry to replace or remove, never a place to write.
        fs::create_dir_all(d.join("dist")).unwrap();
        fs::write(d.join("dist/a"), "a").unwrap();
        fs::create_dir_all(d.join("site")).unwrap();
        std::os::unix::fs::symlink(d.join("elsewhere"), d.join("site/a")).unwrap();
        std::os::unix::fs::symlink(d.join("elsewhere"), d.join("site/gone")).unwrap();
        install(&d.join("dist"), &d.join("site")).unwrap();
        assert!(fs::symlink_metadata(d.join("site/a")).unwrap().is_file());
        assert!(fs::symlink_metadata(d.join("site/gone")).is_err());
        assert!(d.join("elsewhere").is_dir() && fs::read_dir(d.join("elsewhere")).unwrap().next().is_none(), "the link's target is untouched");
    }

    #[test]
    fn what_a_prepare_leaves_is_files_and_directories_only() {
        let d = scratch("normalise");
        fs::create_dir_all(d.join("t/sub")).unwrap();
        fs::write(d.join("t/sub/app.apk"), "x").unwrap();
        fs::set_permissions(d.join("t/sub/app.apk"), fs::Permissions::from_mode(0o600)).unwrap();
        normalise_tree(&d.join("t")).unwrap();
        assert_eq!(fs::metadata(d.join("t/sub/app.apk")).unwrap().permissions().mode() & 0o777, 0o644);
        std::os::unix::fs::symlink("/etc/passwd", d.join("t/sub/leak")).unwrap();
        assert!(normalise_tree(&d.join("t")).is_err(), "a link it made is refused");
    }

    #[test]
    fn ids_and_shas_are_what_a_path_cannot_misread() {
        assert!(id_ok("20261016-071500-sim-0123abcd"));
        assert!(!id_ok("../x") && !id_ok("a/b") && !id_ok("") && !id_ok("A"));
        assert!(is_sha("0123456789abcdef0123456789abcdef01234567"));
        assert!(!is_sha("0123abcd") && !is_sha("0123456789ABCDEF0123456789abcdef01234567"));
    }
}