orch-cli 0.117.0

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
Documentation
//! `orch task move`: hand a task to another node of the cluster. The new node starts from the task
//! branch as last pushed, see `docs/content/docs/cluster.md`

use chrono::{DateTime, Utc};

use crate::engine::tick::assign;
use crate::store::cluster::registry::{self, Entry};
use crate::store::{Task, TaskStatus, TaskStore};

/// What a move did, for the CLI to print
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Moved {
    /// The node that held the task, None when no node did
    pub from: Option<String>,
    /// Whether that node is online, so it ends its session now and not when it is back
    pub from_online: bool,
    pub to: String,
    /// Whether the new node is online, a task for an offline node waits for it
    pub to_online: bool,
    pub branch: String,
}

/// Why `node` cannot run a task of `repo` with `agent`, or None when it can
fn refusal(entry: &Entry, repo: &str, agent: Option<&str>) -> Option<String> {
    let node = &entry.node;
    if entry.witness {
        return Some(format!("{node} is a witness and runs no tasks"));
    }

    if !entry.hosts(repo) {
        return Some(format!("{node} does not host {repo}"));
    }

    match agent {
        Some(agent) if !entry.agents.iter().any(|a| a == agent) => {
            Some(format!("{node} has no {agent} agent"))
        }
        None if entry.agents.is_empty() => Some(format!("{node} has no agent")),
        _ => None,
    }
}

/// The node a move goes to: `wanted` once it passes the checks, or the one the assignment rules pick
async fn target(
    store: &TaskStore,
    entries: &[Entry],
    task: &Task,
    agent: Option<&str>,
    wanted: Option<&str>,
    now: DateTime<Utc>,
) -> anyhow::Result<String> {
    let owner = task.owner_node.as_deref();
    if let Some(wanted) = wanted {
        anyhow::ensure!(
            owner != Some(wanted),
            "task {} is already on {wanted}",
            task.id
        );
        let entry = entries
            .iter()
            .find(|e| e.node == wanted)
            .ok_or_else(|| anyhow::anyhow!("no node named {wanted} in the cluster"))?;
        if let Some(why) = refusal(entry, &task.repo, agent) {
            anyhow::bail!("cannot move task {} to {wanted}: {why}", task.id);
        }

        return Ok(wanted.to_string());
    }

    let others: Vec<Entry> = entries
        .iter()
        .filter(|e| Some(e.node.as_str()) != owner)
        .cloned()
        .collect();
    let running = store.running_per_node(TaskStatus::InProgress).await?;
    assign::choose(&others, &running, "", &task.repo, agent, now).ok_or_else(|| {
        anyhow::anyhow!(
            "no other online node hosts {} with {} and has a free slot",
            task.repo,
            agent.unwrap_or("an agent")
        )
    })
}

/**
 * Give `task` to `wanted`, or to the node the assignment rules pick. One command sets the owner,
 * clears the lease and returns the task to `routed`, and the leader dispatches it there. The old
 * node kills its session when it sees the move and keeps its worktree and local branch
 **/
pub async fn move_task(
    store: &TaskStore,
    task: &Task,
    wanted: Option<&str>,
    now: DateTime<Utc>,
) -> anyhow::Result<Moved> {
    anyhow::ensure!(
        task.status != TaskStatus::Done,
        "task {} is done, a done task never moves",
        task.id
    );
    anyhow::ensure!(
        task.status != TaskStatus::Waiting,
        "task {} waits on an open dependency, it has no run to move",
        task.id
    );
    let agent = task.agent.as_deref().filter(|a| !a.is_empty());
    anyhow::ensure!(
        agent.is_some(),
        "task {} has no agent yet, it moves once it is routed",
        task.id
    );

    let entries = registry::read(store).await?;
    anyhow::ensure!(
        !entries.is_empty(),
        "the node registry is empty, is the cluster running?"
    );
    let to = target(store, &entries, task, agent, wanted, now).await?;
    let from = task.owner_node.clone();
    anyhow::ensure!(
        store.move_to_node(task.id, &to, from.as_deref()).await?,
        "task {} changed status before the move, nothing moved",
        task.id
    );

    let online = |node: &str| entries.iter().any(|e| e.node == node && e.online_at(now));
    Ok(Moved {
        from_online: from.as_deref().is_some_and(online),
        to_online: online(&to),
        from,
        to,
        branch: task.branch.clone(),
    })
}

#[cfg(test)]
mod tests;