orch-cli 0.112.0

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
Documentation
//! `cluster.auto_upgrade`: a node below the highest orch version in its cluster upgrades itself
//! and restarts, one node at a time

use std::env;
use std::ffi::OsString;
use std::iter;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::{Duration, Instant};

use tokio::process::Command;
use tokio::time;

use crate::cli::service as cli_service;
use crate::store::cluster;
use crate::store::cluster::version::{Version, Versions};
use crate::store::cluster::{Member, Node, NodeId};
use crate::sys::tmux::TmuxManager;

/// How often a node looks at the versions of its peers
const CHECK_EVERY: Duration = Duration::from_secs(60);
const FIRST_RETRY: Duration = Duration::from_secs(5 * 60);
const MAX_RETRY: Duration = Duration::from_secs(2 * 60 * 60);
/// `brew upgrade` updates the tap first, so it gets a long limit
const UPGRADE_TIMEOUT: Duration = Duration::from_secs(15 * 60);
/// The crate name orch publishes on crates.io
const CRATE: &str = "orch-cli";

/// How orch was installed, read from the path of the running binary
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Install {
    /// `brew` and the `opt` path of orch, which points at the newest keg after an upgrade
    Brew {
        brew: PathBuf,
        orch: PathBuf,
    },
    /// The bin directory orch runs from, and `cargo-binstall` when one was found
    Cargo {
        dir: PathBuf,
        binstall: Option<PathBuf>,
    },
    Other(PathBuf),
}

/// The service manager does not pass the shell's `PATH`, so every tool is found by full path
pub(crate) fn detect(exe: &Path, cargo_home: Option<&Path>, home: Option<&Path>) -> Install {
    let real = exe.canonicalize().unwrap_or_else(|_| exe.to_path_buf());
    let text = real.to_string_lossy();
    if let Some((prefix, _)) = text.split_once("/Cellar/orch/") {
        let prefix = Path::new(prefix);
        return Install::Brew {
            brew: prefix.join("bin/brew"),
            orch: prefix.join("opt/orch/bin/orch"),
        };
    }

    let Some(dir) = real.parent() else {
        return Install::Other(real);
    };
    let cargo_bins: Vec<PathBuf> = cargo_home
        .map(|c| c.join("bin"))
        .into_iter()
        .chain(home.map(|h| h.join(".cargo/bin")))
        .collect();
    if !cargo_bins.iter().any(|b| b == dir) && !dir.ends_with(".cargo/bin") {
        return Install::Other(real);
    }

    let binstall = iter::once(dir.to_path_buf())
        .chain(cargo_bins)
        .map(|d| d.join("cargo-binstall"))
        .find(|p| p.is_file());
    Install::Cargo {
        dir: dir.to_path_buf(),
        binstall,
    }
}

/// `cargo binstall` of exactly `target` into the directory orch runs from. The version is
/// printed from three numbers and passed as one argument, never through a shell
pub(crate) fn binstall_args(dir: &Path, target: Version) -> Vec<OsString> {
    vec![
        "binstall".into(),
        "--no-confirm".into(),
        "--disable-strategies".into(),
        "compile".into(),
        "--install-path".into(),
        dir.into(),
        format!("{CRATE}@{target}").into(),
    ]
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum UpgradeError {
    /// Orch cannot upgrade this install, so the node stays in needs upgrade
    Unsupported(String),
    /// Tried and failed, so it retries later
    Failed(String),
}

/// What the upgrader does to the machine, behind a trait so no test runs `brew` or `cargo`
pub(crate) trait Host {
    /// Task and review sessions running on this machine
    async fn live_sessions(&self) -> usize;
    /// Install `target` or later, and return the version now installed
    async fn upgrade(&self, target: Version) -> Result<Version, UpgradeError>;
    /// Restart the service the way `orch service restart` does, so graceful shutdown runs
    async fn restart(&self) -> anyhow::Result<()>;
}

/// A peer as this node sees it
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Peer {
    pub id: NodeId,
    pub voter: bool,
    /// It answered `hello` and proved the secret
    pub reachable: bool,
    pub version: Option<Version>,
    pub auto_upgrade: bool,
}

/// What one check knows: this node, the version to reach, and its peers
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct View {
    pub id: NodeId,
    pub voter: bool,
    pub mine: Version,
    pub target: Option<Version>,
    pub auto_upgrade: bool,
    pub peers: Vec<Peer>,
}

impl View {
    /// None on a single node, which has no peers to follow
    pub(crate) fn of(id: NodeId, versions: &Versions, members: &[Member]) -> Option<Self> {
        Some(Self {
            id,
            voter: members.iter().any(|m| m.me && m.voter),
            mine: versions.mine()?,
            target: versions.target(),
            auto_upgrade: versions.auto_upgrade(),
            peers: members
                .iter()
                .filter(|m| !m.me)
                .map(|m| Peer {
                    id: m.id,
                    voter: m.voter,
                    reachable: m.answered.is_some(),
                    version: m.version,
                    auto_upgrade: m.answered.as_ref().is_some_and(|a| a.auto_upgrade),
                })
                .collect(),
        })
    }
}

/// Why a check did not upgrade
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Wait {
    Off,
    Current,
    VoterUnreachable(NodeId),
    /// A lower node id that also upgrades itself goes first
    Behind(NodeId),
    Backoff,
    Sessions(usize),
    Unsupported,
}

/// The version to upgrade to now, or why not
pub(crate) fn turn(v: &View) -> Result<Version, Wait> {
    if !v.auto_upgrade {
        return Err(Wait::Off);
    }

    let Some(target) = v.target.filter(|t| *t > v.mine) else {
        return Err(Wait::Current);
    };
    if v.voter
        && let Some(p) = v.peers.iter().find(|p| p.voter && !p.reachable)
    {
        return Err(Wait::VoterUnreachable(p.id));
    }

    let first = v
        .peers
        .iter()
        .filter(|p| p.reachable && p.auto_upgrade && p.version.is_some_and(|x| x < target))
        .map(|p| p.id)
        .min();
    match first {
        Some(id) if id < v.id => Err(Wait::Behind(id)),
        _ => Ok(target),
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Step {
    Waited(Wait),
    Failed,
    Restarted,
}

/// The retry delay and the one warning live in memory, so a restart starts them over
pub(crate) struct Upgrader<H> {
    host: H,
    failures: u32,
    retry_at: Option<Instant>,
    warned: bool,
}

impl<H: Host> Upgrader<H> {
    pub(crate) fn new(host: H) -> Self {
        Self {
            host,
            failures: 0,
            retry_at: None,
            warned: false,
        }
    }

    #[cfg(test)]
    pub(crate) fn host(&self) -> &H {
        &self.host
    }

    pub(crate) async fn step(&mut self, view: &View, versions: &Versions, now: Instant) -> Step {
        let target = match turn(view) {
            Ok(t) => t,
            Err(w) => return Step::Waited(w),
        };
        if self.retry_at.is_some_and(|at| now < at) {
            return Step::Waited(Wait::Backoff);
        }

        let sessions = self.host.live_sessions().await;
        if sessions > 0 {
            return Step::Waited(Wait::Sessions(sessions));
        }

        tracing::info!(from = %view.mine, to = %target, "upgrading orch to the cluster's version");
        let done = match self.host.upgrade(target).await {
            Ok(installed) if installed > view.mine => {
                self.host.restart().await.map_err(|e| e.to_string())
            }
            Ok(installed) => Err(format!(
                "the upgrade left orch {installed}, which is not newer than {}",
                view.mine
            )),
            Err(UpgradeError::Unsupported(why)) => {
                if !self.warned {
                    tracing::warn!(target_version = %target, "cannot upgrade orch: {why}");
                    self.warned = true;
                }
                versions.set_upgrade_error(Some(why));
                return Step::Waited(Wait::Unsupported);
            }
            Err(UpgradeError::Failed(e)) => Err(e),
        };
        match done {
            Ok(()) => {
                versions.set_upgrade_error(None);
                Step::Restarted
            }
            Err(e) => {
                self.failures += 1;
                let delay = retry_delay(self.failures);
                self.retry_at = Some(now + delay);
                tracing::warn!(target_version = %target, retry_in = ?delay, err = %e, "orch upgrade failed");
                versions.set_upgrade_error(Some(e));
                Step::Failed
            }
        }
    }
}

fn retry_delay(failures: u32) -> Duration {
    let doubled = FIRST_RETRY.saturating_mul(2u32.saturating_pow(failures.saturating_sub(1)));
    doubled.min(MAX_RETRY)
}

/// Check the peers every minute and upgrade when it is this node's turn
pub(crate) async fn run(node: Node) {
    let exe = env::current_exe().unwrap_or_default();
    let install = detect(
        &exe,
        env::var_os("CARGO_HOME").map(PathBuf::from).as_deref(),
        env::var_os("HOME").map(PathBuf::from).as_deref(),
    );
    tracing::info!(?install, "cluster.auto_upgrade is on");
    let mut upgrader = Upgrader::new(SystemHost { install });
    let mut ticker = time::interval(CHECK_EVERY);
    loop {
        ticker.tick().await;
        let members = cluster::describe(&node).await;
        let Some(view) = View::of(node.id(), node.versions(), &members) else {
            return;
        };
        match upgrader.step(&view, node.versions(), Instant::now()).await {
            Step::Restarted => return,
            Step::Waited(why) => tracing::debug!(?why, "auto upgrade waits"),
            Step::Failed => {}
        }
    }
}

struct SystemHost {
    install: Install,
}

impl SystemHost {
    async fn run(program: &Path, args: &[OsString]) -> Result<(), UpgradeError> {
        let mut cmd = Command::new(program);
        cmd.args(args)
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .kill_on_drop(true);
        let out = time::timeout(UPGRADE_TIMEOUT, cmd.output())
            .await
            .map_err(|_| UpgradeError::Failed(format!("{} timed out", program.display())))?
            .map_err(|e| UpgradeError::Failed(format!("{}: {e}", program.display())))?;
        if out.status.success() {
            return Ok(());
        }

        let stderr = String::from_utf8_lossy(&out.stderr);
        let last = stderr.lines().rev().find(|l| !l.trim().is_empty());
        let last: String = last.unwrap_or_default().trim().chars().take(200).collect();
        Err(UpgradeError::Failed(format!(
            "{} exited with {}: {last}",
            program.display(),
            out.status
        )))
    }

    async fn installed(orch: &Path) -> Result<Version, UpgradeError> {
        let out = Command::new(orch)
            .arg("--version")
            .output()
            .await
            .map_err(|e| UpgradeError::Failed(format!("{}: {e}", orch.display())))?;
        let text = String::from_utf8_lossy(&out.stdout);
        text.split_whitespace()
            .last()
            .and_then(|v| v.parse().ok())
            .ok_or_else(|| UpgradeError::Failed(format!("{} printed no version", orch.display())))
    }
}

impl Host for SystemHost {
    async fn live_sessions(&self) -> usize {
        // An error means tmux could not start, so no session can be live
        TmuxManager::new()
            .list_sessions()
            .await
            .map_or(0, |s| s.len())
    }

    async fn upgrade(&self, target: Version) -> Result<Version, UpgradeError> {
        match &self.install {
            Install::Brew { brew, orch } => {
                Self::run(brew, &["upgrade".into(), "orch".into()]).await?;
                Self::installed(orch).await
            }
            Install::Cargo {
                dir,
                binstall: Some(binstall),
            } => {
                Self::run(binstall, &binstall_args(dir, target)).await?;
                Self::installed(&dir.join("orch")).await
            }
            Install::Cargo { binstall: None, .. } => Err(UpgradeError::Unsupported(
                "cargo-binstall is not next to orch or in the cargo bin directory".into(),
            )),
            Install::Other(path) => Err(UpgradeError::Unsupported(format!(
                "{} was not installed by Homebrew or cargo",
                path.display()
            ))),
        }
    }

    async fn restart(&self) -> anyhow::Result<()> {
        let (program, args) = cli_service::restart_command();
        let program = match &self.install {
            Install::Brew { brew, .. } if program == "brew" => brew.clone(),
            _ => PathBuf::from(program),
        };
        // Its own process group, so stopping the service does not stop the restart
        Command::new(program)
            .args(args)
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .process_group(0)
            .spawn()?;
        Ok(())
    }
}

#[cfg(test)]
mod tests;