orch-cli 0.111.0

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
Documentation
//! The orch version of each node. Nodes apply the same commands to their own schema, so an older
//! node must not apply what a newer one wrote

use std::fmt;
use std::fmt::Display;
use std::fmt::Formatter;
use std::str::FromStr;
use std::sync::Mutex;
use std::sync::PoisonError;

use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
use tokio::sync::watch;

/// Major, minor and patch. A pre-release or build suffix is dropped, so `1.2.3-rc1` is `1.2.3`
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Version(pub u64, pub u64, pub u64);

impl Version {
    /// The version this binary was built as
    pub fn current() -> Self {
        env!("CARGO_PKG_VERSION").parse().unwrap_or(Self(0, 0, 0))
    }
}

impl Display for Version {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}.{}.{}", self.0, self.1, self.2)
    }
}

impl FromStr for Version {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, String> {
        let core = s
            .trim()
            .trim_start_matches('v')
            .split(['-', '+'])
            .next()
            .unwrap_or_default();
        let mut parts = core.split('.').map(str::parse::<u64>);
        match (parts.next(), parts.next(), parts.next(), parts.next()) {
            (Some(Ok(a)), Some(Ok(b)), Some(Ok(c)), None) => Ok(Self(a, b, c)),
            _ => Err(format!("not a version: {s:?}")),
        }
    }
}

impl Serialize for Version {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.collect_str(self)
    }
}

impl<'de> Deserialize<'de> for Version {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let s = String::deserialize(d)?;
        s.parse().map_err(de::Error::custom)
    }
}

/// True when a node on `mine` may apply what `stamp` wrote. No stamp is older than any version
pub fn may_apply(mine: Version, stamp: Option<Version>) -> bool {
    stamp.is_none_or(|v| v <= mine)
}

/**
 * What one node knows about versions: its own, the newer version an entry or snapshot asked for
 * once the node stopped applying, and the highest version a peer that proved the secret reported.
 * `mine` is None on a single node, which checks nothing
 **/
#[derive(Debug)]
pub struct Versions {
    mine: Option<Version>,
    needs: watch::Sender<Option<Version>>,
    highest_peer: Mutex<Option<Version>>,
}

impl Versions {
    pub fn new(mine: Option<Version>) -> Self {
        Self {
            mine,
            needs: watch::Sender::new(None),
            highest_peer: Mutex::new(None),
        }
    }

    pub fn mine(&self) -> Option<Version> {
        self.mine
    }

    /// The version this node must run before it applies again, or None while it applies
    pub fn needs_upgrade(&self) -> Option<Version> {
        *self.needs.borrow()
    }

    pub(crate) fn hold(&self, needed: Version) {
        self.needs.send_if_modified(|cur| {
            let next = cur.map_or(needed, |c| c.max(needed));
            let changed = *cur != Some(next);
            *cur = Some(next);
            changed
        });
    }

    pub(crate) fn subscribe(&self) -> watch::Receiver<Option<Version>> {
        self.needs.subscribe()
    }

    /// Record a version a peer reported after it proved the secret
    pub fn saw_peer(&self, v: Version) {
        let mut highest = self
            .highest_peer
            .lock()
            .unwrap_or_else(PoisonError::into_inner);
        if highest.is_none_or(|h| v > h) {
            *highest = Some(v);
        }
    }

    /// The highest version any peer that proved the secret reported
    pub fn highest_peer(&self) -> Option<Version> {
        *self
            .highest_peer
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
    }
}