orch/store/tasks/
owner.rs1use std::collections::HashMap;
4
5use super::{Task, TaskStatus};
6use crate::store::TaskStore;
7use crate::store::{Command, Reply};
8
9impl TaskStore {
10 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 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 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 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 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 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 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}