orch-cli 0.117.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::TaskStore;
use crate::store::{Command, Reply};

/// A `moved:<id>` row holds the node a task moved away from, until that node ends its session
pub(crate) const MOVED_PREFIX: &str = "moved:";

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(),
        }
    }

    /**
     * True when startup reconciliation on this node may act on the task's worktree. A task another
     * node holds is that node's. On a follower, a task with no owner is the leader's to decide,
     * except a done one, whose worktree here only waits for removal
     **/
    pub fn reconciles_here(&self, task: &Task) -> bool {
        !self.runs_elsewhere(task) || (task.owner_node.is_none() && task.status == TaskStatus::Done)
    }

    /// `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())
    }

    /// Renew this node's lease on every run it holds for `ttl_secs`. 0 ends them at once. Does
    /// nothing on one machine
    pub async fn renew_leases(&self, ttl_secs: i64) -> anyhow::Result<u64> {
        let Some(node) = self.node() else {
            return Ok(0);
        };
        match self
            .write(Command::TaskRenewLeases {
                node: node.name().to_string(),
                secs: ttl_secs,
            })
            .await?
        {
            Reply::Count(n) => Ok(n),
            other => anyhow::bail!("expected a count reply, got {other:?}"),
        }
    }

    /// 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
    }

    /**
     * True when another node holds the task, as after `orch task move`, while this node ran it. This
     * node then applies nothing from its run. Always false on one machine
     **/
    pub fn moved_away(&self, task: &Task) -> bool {
        let Some(node) = self.node() else {
            return false;
        };
        task.owner_node.as_deref().is_some_and(|o| o != node.name())
    }

    /// Give the task to `node`, see `apply::move_to`. False when the task is done or waiting
    pub async fn move_to_node(
        &self,
        id: i64,
        node: &str,
        from: Option<&str>,
    ) -> anyhow::Result<bool> {
        self.write_bool(Command::TaskMove {
            id,
            node: node.to_string(),
            from: from.map(str::to_string),
        })
        .await
    }

    /// The ids of the tasks that moved away from `node` and may still have a session there
    pub async fn moved_from(&self, node: &str) -> anyhow::Result<Vec<i64>> {
        Ok(self
            .kv_list_prefix(MOVED_PREFIX)
            .await?
            .into_iter()
            .filter(|(_, from)| from == node)
            .filter_map(|(key, _)| key.strip_prefix(MOVED_PREFIX)?.parse().ok())
            .collect())
    }

    /// Forget a move once the old node ended its session
    pub async fn clear_moved(&self, id: i64) -> anyhow::Result<()> {
        self.kv_delete(&format!("{MOVED_PREFIX}{id}")).await
    }
}