orch-cli 0.118.1

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
Documentation
//! The node registry: what each node hosts and runs, in replicated kv rows `node:<name>`

use std::collections::{BTreeMap, BTreeSet};
use std::time::Duration;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use super::version::Version;
use crate::store::TaskStore;

const PREFIX: &str = "node:";

/// How often a node rewrites its entry. The entry's `seen` time is how the leader tells it is online
pub const HEARTBEAT: Duration = Duration::from_secs(30);

/// A node whose entry is older than this is offline. It keeps its entry, so its projects stay known
pub const OFFLINE_AFTER: Duration = Duration::from_secs(90);

/// One node as its own config describes it
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Entry {
    pub node: String,
    /// The repos this node has a checkout of
    pub projects: Vec<String>,
    /// The agent CLIs this node's config lists and finds on its `PATH`
    pub agents: Vec<String>,
    /// `engine.max_parallel`, for task runs and for review runs each
    pub max_parallel: usize,
    #[serde(default)]
    pub version: Option<Version>,
    /// A witness votes and never runs anything
    #[serde(default)]
    pub witness: bool,
    /// When the node last wrote its entry, RFC 3339
    pub seen: String,
}

impl Entry {
    pub fn online_at(&self, now: DateTime<Utc>) -> bool {
        DateTime::parse_from_rfc3339(&self.seen).is_ok_and(|seen| {
            now.signed_duration_since(seen)
                .to_std()
                .map_or(true, |age| age <= OFFLINE_AFTER)
        })
    }

    pub fn hosts(&self, repo: &str) -> bool {
        self.projects.iter().any(|p| p == repo)
    }

    /// May run a task for `repo` with `agent`. No agent means any, as for a review, which picks
    /// its agent on the node that runs it
    pub fn can_run(&self, repo: &str, agent: Option<&str>) -> bool {
        !self.witness
            && self.hosts(repo)
            && match agent {
                Some(agent) => self.agents.iter().any(|a| a == agent),
                None => !self.agents.is_empty(),
            }
    }
}

/// Write this node's entry through Raft
pub async fn write(store: &TaskStore, entry: &Entry) -> anyhow::Result<()> {
    store
        .kv_set(
            &format!("{PREFIX}{}", entry.node),
            &serde_json::to_string(entry)?,
        )
        .await
}

/// Every entry, online or not. A row that does not parse is skipped
pub async fn read(store: &TaskStore) -> anyhow::Result<Vec<Entry>> {
    Ok(store
        .kv_list_prefix(PREFIX)
        .await?
        .into_iter()
        .filter_map(|(key, value)| match serde_json::from_str(&value) {
            Ok(entry) => Some(entry),
            Err(e) => {
                tracing::warn!(key, err = %e, "skipping a node registry row that does not parse");
                None
            }
        })
        .collect())
}

/// Each project of the cluster and the nodes that host it, online or not
pub fn hosts_by_project(entries: &[Entry]) -> BTreeMap<String, BTreeSet<String>> {
    let mut by_project: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
    for entry in entries.iter().filter(|e| !e.witness) {
        for project in &entry.projects {
            by_project
                .entry(project.clone())
                .or_default()
                .insert(entry.node.clone());
        }
    }

    by_project
}