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::Command;
7use crate::store::TaskStore;
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    /// `runs_elsewhere` for a task known by its repo and id. False when the task is not found
26    pub async fn runs_elsewhere_by_ref(&self, repo: &str, task_id: &str) -> bool {
27        if self.node().is_none() {
28            return false;
29        }
30
31        match self.resolve_task_id(repo, task_id).await {
32            Ok(Some(id)) => self.get(id).await.is_ok_and(|t| self.runs_elsewhere(&t)),
33            _ => false,
34        }
35    }
36
37    /// How many tasks in `status` each node runs
38    pub async fn running_per_node(
39        &self,
40        status: TaskStatus,
41    ) -> anyhow::Result<HashMap<String, usize>> {
42        let rows: Vec<(String, i64)> = sqlx::query_as(
43            "SELECT owner_node, COUNT(*) FROM tasks
44             WHERE status = ? AND owner_node IS NOT NULL GROUP BY owner_node",
45        )
46        .bind(status.as_str())
47        .fetch_all(&self.pool)
48        .await?;
49        Ok(rows
50            .into_iter()
51            .map(|(node, n)| (node, usize::try_from(n).unwrap_or(0)))
52            .collect())
53    }
54
55    /// The tasks in `status` that `node` runs, across every repo
56    pub async fn list_owned(&self, node: &str, status: TaskStatus) -> anyhow::Result<Vec<Task>> {
57        Ok(self
58            .list_all_by_status_global(status)
59            .await?
60            .into_iter()
61            .filter(|t| t.owner_node.as_deref() == Some(node))
62            .collect())
63    }
64
65    /// Give back a run `node` holds under `term`, see `apply::release`
66    pub async fn release_assignment(
67        &self,
68        id: i64,
69        node: &str,
70        term: i64,
71        status: TaskStatus,
72    ) -> anyhow::Result<bool> {
73        self.write_bool(Command::TaskRelease {
74            id,
75            node: node.to_string(),
76            term,
77            status,
78        })
79        .await
80    }
81}