Skip to main content

orch/store/tasks/
owner.rs

1//! Which node runs a task, for assignment in a cluster
2
3use std::collections::HashMap;
4
5use super::{Task, TaskStatus};
6use crate::store::TaskStore;
7use crate::store::{Command, Reply};
8
9impl TaskStore {
10    /**
11     * True when another node runs the task, so this node's tmux sessions say nothing about it. A
12     * task with no owner runs on the leader, as before assignment existed. Always false on one
13     * machine
14     **/
15    pub fn runs_elsewhere(&self, task: &Task) -> bool {
16        let Some(node) = self.node() else {
17            return false;
18        };
19        match task.owner_node.as_deref() {
20            Some(owner) => owner != node.name(),
21            None => !node.is_leader(),
22        }
23    }
24
25    /**
26     * True when startup reconciliation on this node may act on the task's worktree. A task another
27     * node holds is that node's. On a follower, a task with no owner is the leader's to decide,
28     * except a done one, whose worktree here only waits for removal
29     **/
30    pub fn reconciles_here(&self, task: &Task) -> bool {
31        !self.runs_elsewhere(task) || (task.owner_node.is_none() && task.status == TaskStatus::Done)
32    }
33
34    /// `runs_elsewhere` for a task known by its repo and id. False when the task is not found
35    pub async fn runs_elsewhere_by_ref(&self, repo: &str, task_id: &str) -> bool {
36        if self.node().is_none() {
37            return false;
38        }
39
40        match self.resolve_task_id(repo, task_id).await {
41            Ok(Some(id)) => self.get(id).await.is_ok_and(|t| self.runs_elsewhere(&t)),
42            _ => false,
43        }
44    }
45
46    /// How many tasks in `status` each node runs
47    pub async fn running_per_node(
48        &self,
49        status: TaskStatus,
50    ) -> anyhow::Result<HashMap<String, usize>> {
51        let rows: Vec<(String, i64)> = sqlx::query_as(
52            "SELECT owner_node, COUNT(*) FROM tasks
53             WHERE status = ? AND owner_node IS NOT NULL GROUP BY owner_node",
54        )
55        .bind(status.as_str())
56        .fetch_all(&self.pool)
57        .await?;
58        Ok(rows
59            .into_iter()
60            .map(|(node, n)| (node, usize::try_from(n).unwrap_or(0)))
61            .collect())
62    }
63
64    /// The tasks in `status` that `node` runs, across every repo
65    pub async fn list_owned(&self, node: &str, status: TaskStatus) -> anyhow::Result<Vec<Task>> {
66        Ok(self
67            .list_all_by_status_global(status)
68            .await?
69            .into_iter()
70            .filter(|t| t.owner_node.as_deref() == Some(node))
71            .collect())
72    }
73
74    /// Renew this node's lease on every run it holds for `ttl_secs`. 0 ends them at once. Does
75    /// nothing on one machine
76    pub async fn renew_leases(&self, ttl_secs: i64) -> anyhow::Result<u64> {
77        let Some(node) = self.node() else {
78            return Ok(0);
79        };
80        match self
81            .write(Command::TaskRenewLeases {
82                node: node.name().to_string(),
83                secs: ttl_secs,
84            })
85            .await?
86        {
87            Reply::Count(n) => Ok(n),
88            other => anyhow::bail!("expected a count reply, got {other:?}"),
89        }
90    }
91
92    /// Give back a run `node` holds under `term`, see `apply::release`
93    pub async fn release_assignment(
94        &self,
95        id: i64,
96        node: &str,
97        term: i64,
98        status: TaskStatus,
99    ) -> anyhow::Result<bool> {
100        self.write_bool(Command::TaskRelease {
101            id,
102            node: node.to_string(),
103            term,
104            status,
105        })
106        .await
107    }
108}