orch-cli 0.113.0

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
Documentation
//! Which node runs a task, for assignment in a cluster

use std::collections::HashMap;

use super::{Task, TaskStatus};
use crate::store::Command;
use crate::store::TaskStore;

impl TaskStore {
    /**
     * True when another node runs the task, so this node's tmux sessions say nothing about it. A
     * task with no owner runs on the leader, as before assignment existed. Always false on one
     * machine
     **/
    pub fn runs_elsewhere(&self, task: &Task) -> bool {
        let Some(node) = self.node() else {
            return false;
        };
        match task.owner_node.as_deref() {
            Some(owner) => owner != node.name(),
            None => !node.is_leader(),
        }
    }

    /// `runs_elsewhere` for a task known by its repo and id. False when the task is not found
    pub async fn runs_elsewhere_by_ref(&self, repo: &str, task_id: &str) -> bool {
        if self.node().is_none() {
            return false;
        }

        match self.resolve_task_id(repo, task_id).await {
            Ok(Some(id)) => self.get(id).await.is_ok_and(|t| self.runs_elsewhere(&t)),
            _ => false,
        }
    }

    /// How many tasks in `status` each node runs
    pub async fn running_per_node(
        &self,
        status: TaskStatus,
    ) -> anyhow::Result<HashMap<String, usize>> {
        let rows: Vec<(String, i64)> = sqlx::query_as(
            "SELECT owner_node, COUNT(*) FROM tasks
             WHERE status = ? AND owner_node IS NOT NULL GROUP BY owner_node",
        )
        .bind(status.as_str())
        .fetch_all(&self.pool)
        .await?;
        Ok(rows
            .into_iter()
            .map(|(node, n)| (node, usize::try_from(n).unwrap_or(0)))
            .collect())
    }

    /// The tasks in `status` that `node` runs, across every repo
    pub async fn list_owned(&self, node: &str, status: TaskStatus) -> anyhow::Result<Vec<Task>> {
        Ok(self
            .list_all_by_status_global(status)
            .await?
            .into_iter()
            .filter(|t| t.owner_node.as_deref() == Some(node))
            .collect())
    }

    /// Give back a run `node` holds under `term`, see `apply::release`
    pub async fn release_assignment(
        &self,
        id: i64,
        node: &str,
        term: i64,
        status: TaskStatus,
    ) -> anyhow::Result<bool> {
        self.write_bool(Command::TaskRelease {
            id,
            node: node.to_string(),
            term,
            status,
        })
        .await
    }
}