orch-cli 0.117.0

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
Documentation
//! The `cluster:` section of the global config

use super::discovery::Tailnet;
use super::{NodeId, discovery};
use crate::config;
use crate::security::secret_ref;
use std::collections::BTreeMap;
use std::fmt;

pub const DEFAULT_PORT: u16 = 7420;

#[derive(Clone, PartialEq, Eq)]
pub struct ClusterConfig {
    pub secret: String,
    pub port: u16,
    /// Node names, as the first label of each machine's MagicDNS name
    pub voters: Vec<String>,
    /// Votes but never leads, runs no agents
    pub witness: bool,
    /// Upgrade this machine to the highest orch version in the cluster
    pub auto_upgrade: bool,
}

impl fmt::Debug for ClusterConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ClusterConfig")
            .field("secret", &"<redacted>")
            .field("port", &self.port)
            .field("voters", &self.voters)
            .field("witness", &self.witness)
            .field("auto_upgrade", &self.auto_upgrade)
            .finish()
    }
}

impl ClusterConfig {
    /// None without a `cluster.secret`, which keeps orch on one machine. Blocking, a secret
    /// reference waits on passbox or 1Password, so call it from `spawn_blocking`
    pub fn load() -> anyhow::Result<Option<Self>> {
        Self::load_with(secret_ref::resolve)
    }

    fn load_with(
        resolve: impl FnOnce(&str) -> anyhow::Result<String>,
    ) -> anyhow::Result<Option<Self>> {
        let Ok(raw) = config::get("cluster.secret") else {
            return Ok(None);
        };
        if raw.is_empty() {
            return Ok(None);
        }

        // An unreadable reference stops the cluster, its text must never become the secret
        let secret = resolve(&raw).map_err(|e| match secret_ref::kind(&raw) {
            Some(kind) => e.context(format!("cluster.secret: could not read the {kind}")),
            None => e.context("cluster.secret: could not read the value"),
        })?;
        anyhow::ensure!(
            !secret.is_empty(),
            "cluster.secret resolved to an empty value"
        );

        let port = match config::get("cluster.port") {
            Ok(p) => p.parse()?,
            Err(_) => DEFAULT_PORT,
        };
        let voters = config::get_list("cluster.voters")?
            .into_iter()
            .map(|v| v.to_ascii_lowercase())
            .collect();
        let witness = config::get("cluster.witness").is_ok_and(|w| w == "true");
        let auto_upgrade = config::get("cluster.auto_upgrade").is_ok_and(|w| w == "true");
        Ok(Some(Self {
            secret,
            port,
            voters,
            witness,
            auto_upgrade,
        }))
    }
}

/// How this machine takes part, worked out from the config and the tailnet
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Plan {
    pub name: String,
    pub id: NodeId,
    pub addr: String,
    /// The voters to initialize with. Empty for a witness or a learner
    pub voters: BTreeMap<NodeId, String>,
    pub elect: bool,
    pub learner: bool,
}

pub fn plan(cfg: &ClusterConfig, tailnet: &Tailnet) -> anyhow::Result<Plan> {
    let name = tailnet.me.name.clone();
    let mut voters = BTreeMap::new();
    let mut missing = Vec::new();
    for voter in &cfg.voters {
        let found = tailnet.all_named(voter);
        anyhow::ensure!(
            found.len() <= 1,
            "cluster.voters names {voter}, and {} machines on the tailnet have that name",
            found.len()
        );
        match found.first() {
            Some(host) => {
                voters.insert(
                    discovery::node_id(voter),
                    format!("{}:{}", host.ip, cfg.port),
                );
            }
            None => missing.push(voter.as_str()),
        }
    }

    anyhow::ensure!(
        missing.is_empty(),
        "cluster.voters names machines the tailnet does not know: {}",
        missing.join(", ")
    );
    let is_voter = cfg.voters.contains(&name);
    anyhow::ensure!(
        !cfg.witness || is_voter,
        "{name} has cluster.witness set but is not in cluster.voters"
    );
    let elect = is_voter && !cfg.witness;
    Ok(Plan {
        id: discovery::node_id(&name),
        addr: format!("{}:{}", tailnet.me.ip, cfg.port),
        voters: if elect { voters } else { BTreeMap::new() },
        elect,
        learner: !is_voter,
        name,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::store::cluster::discovery::Host;
    use std::env;
    use std::fs;
    use tempfile::TempDir;

    /// A home whose config holds `secret` as `cluster.secret`, or no cluster section for None
    fn home_with(secret: Option<&str>) -> TempDir {
        let home = tempfile::tempdir().unwrap();
        let yaml = secret.map_or_else(
            || "engine:\n  tick_interval: 10\n".to_string(),
            |s| format!("cluster:\n  secret: '{s}'\n  voters: [node-a]\n"),
        );
        fs::write(home.path().join("config.yml"), yaml).unwrap();
        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
        unsafe { env::set_var("ORCH_HOME", home.path()) };
        home
    }

    fn load_in(
        secret: Option<&str>,
        resolve: impl FnOnce(&str) -> anyhow::Result<String>,
    ) -> anyhow::Result<Option<ClusterConfig>> {
        let _home = home_with(secret);
        let got = ClusterConfig::load_with(resolve);
        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
        unsafe { env::remove_var("ORCH_HOME") };
        got
    }

    fn real(value: &str) -> anyhow::Result<String> {
        secret_ref::resolve_with("/nonexistent", "/nonexistent", value)
    }

    #[test]
    #[serial_test::serial(orch_home)]
    fn a_plain_secret_loads_unchanged() {
        let cfg = load_in(Some("plain-secret"), real).unwrap().unwrap();
        assert_eq!(cfg.secret, "plain-secret");
        assert_eq!(cfg.voters, vec!["node-a".to_string()]);
    }

    #[test]
    #[serial_test::serial(orch_home)]
    fn an_env_reference_loads_the_variable() {
        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
        unsafe { env::set_var("ORCH_CLUSTER_SECRET_TEST_SET", "from-env") };
        let cfg = load_in(Some("${ORCH_CLUSTER_SECRET_TEST_SET}"), real)
            .unwrap()
            .unwrap();
        assert_eq!(cfg.secret, "from-env");
    }

    #[test]
    #[serial_test::serial(orch_home)]
    fn an_unset_env_reference_fails_and_names_the_key() {
        let err = load_in(Some("${ORCH_CLUSTER_SECRET_TEST_UNSET}"), real).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("cluster.secret"), "{msg}");
        assert!(msg.contains("environment variable reference"), "{msg}");
    }

    #[test]
    #[serial_test::serial(orch_home)]
    fn a_failed_passbox_read_fails_and_never_uses_the_reference_text() {
        let err = load_in(Some("passbox:orch/cluster"), real).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("cluster.secret"), "{msg}");
        assert!(msg.contains("passbox reference"), "{msg}");

        let failing = |_: &str| anyhow::bail!("passbox could not read orch/cluster: denied");
        assert!(load_in(Some("passbox:orch/cluster"), failing).is_err());
    }

    #[test]
    #[serial_test::serial(orch_home)]
    fn a_resolved_secret_stays_out_of_errors_and_debug() {
        let err = load_in(Some("passbox:orch/cluster"), |_| Ok(String::new())).unwrap_err();
        assert!(err.to_string().contains("cluster.secret"), "{err}");

        let cfg = load_in(Some("passbox:orch/cluster"), |_| Ok("hunter2".into()))
            .unwrap()
            .unwrap();
        assert_eq!(cfg.secret, "hunter2");
        assert!(!format!("{cfg:?}").contains("hunter2"));
    }

    #[test]
    #[serial_test::serial(orch_home)]
    fn no_secret_keeps_the_cluster_off() {
        let resolve = |_: &str| -> anyhow::Result<String> { panic!("nothing to resolve") };
        assert!(load_in(None, resolve).unwrap().is_none());
    }

    fn host(name: &str, ip: &str, online: bool) -> Host {
        Host {
            name: name.into(),
            ip: ip.into(),
            online,
        }
    }

    fn tailnet(me: &str) -> Tailnet {
        let all = [
            host("m1-max", "100.1.1.1", true),
            host("legion", "100.1.1.2", true),
            host("vpsbr", "100.1.1.3", false),
            host("m4", "100.1.1.4", true),
        ];
        Tailnet {
            me: all.iter().find(|h| h.name == me).unwrap().clone(),
            peers: all.into_iter().filter(|h| h.name != me).collect(),
        }
    }

    fn cfg(witness: bool) -> ClusterConfig {
        ClusterConfig {
            secret: "s".into(),
            port: 7420,
            voters: vec!["m1-max".into(), "legion".into(), "vpsbr".into()],
            witness,
            auto_upgrade: false,
        }
    }

    #[test]
    fn a_voter_initializes_with_every_voter_even_one_that_is_offline() {
        let p = plan(&cfg(false), &tailnet("m1-max")).unwrap();
        assert!(p.elect && !p.learner);
        assert_eq!(p.addr, "100.1.1.1:7420");
        assert_eq!(p.voters.len(), 3);
        assert_eq!(p.voters[&discovery::node_id("vpsbr")], "100.1.1.3:7420");
    }

    #[test]
    fn a_witness_votes_without_leading_or_initializing() {
        let p = plan(&cfg(true), &tailnet("vpsbr")).unwrap();
        assert!(!p.elect && !p.learner);
        assert!(p.voters.is_empty());
    }

    #[test]
    fn a_machine_outside_the_voters_is_a_learner() {
        let p = plan(&cfg(false), &tailnet("m4")).unwrap();
        assert!(p.learner && !p.elect);
        assert!(p.voters.is_empty());
    }

    #[test]
    fn plan_rejects_an_unknown_voter_and_a_witness_outside_the_voters() {
        let mut c = cfg(false);
        c.voters.push("ghost".into());
        let err = plan(&c, &tailnet("m1-max")).unwrap_err().to_string();
        assert!(err.contains("ghost"), "{err}");
        assert!(plan(&cfg(true), &tailnet("m4")).is_err());
    }

    #[test]
    fn plan_rejects_a_voter_name_two_machines_share() {
        let mut t = tailnet("m1-max");
        t.peers.push(host("legion", "100.1.1.9", true));
        let err = plan(&cfg(false), &t).unwrap_err().to_string();
        assert!(err.contains("2 machines"), "{err}");
    }
}