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
9/// A `moved:<id>` row holds the node a task moved away from, until that node ends its session
10pub(crate) const MOVED_PREFIX: &str = "moved:";
11
12impl TaskStore {
13    /**
14     * True when another node runs the task, so this node's tmux sessions say nothing about it. A
15     * task with no owner runs on the leader, as before assignment existed. Always false on one
16     * machine
17     **/
18    pub fn runs_elsewhere(&self, task: &Task) -> bool {
19        let Some(node) = self.node() else {
20            return false;
21        };
22        match task.owner_node.as_deref() {
23            Some(owner) => owner != node.name(),
24            None => !node.is_leader(),
25        }
26    }
27
28    /**
29     * True when startup reconciliation on this node may act on the task's worktree. A task another
30     * node holds is that node's. On a follower, a task with no owner is the leader's to decide,
31     * except a done one, whose worktree here only waits for removal
32     **/
33    pub fn reconciles_here(&self, task: &Task) -> bool {
34        !self.runs_elsewhere(task) || (task.owner_node.is_none() && task.status == TaskStatus::Done)
35    }
36
37    /// `runs_elsewhere` for a task known by its repo and id. False when the task is not found
38    pub async fn runs_elsewhere_by_ref(&self, repo: &str, task_id: &str) -> bool {
39        if self.node().is_none() {
40            return false;
41        }
42
43        match self.resolve_task_id(repo, task_id).await {
44            Ok(Some(id)) => self.get(id).await.is_ok_and(|t| self.runs_elsewhere(&t)),
45            _ => false,
46        }
47    }
48
49    /// How many tasks in `status` each node runs
50    pub async fn running_per_node(
51        &self,
52        status: TaskStatus,
53    ) -> anyhow::Result<HashMap<String, usize>> {
54        let rows: Vec<(String, i64)> = sqlx::query_as(
55            "SELECT owner_node, COUNT(*) FROM tasks
56             WHERE status = ? AND owner_node IS NOT NULL GROUP BY owner_node",
57        )
58        .bind(status.as_str())
59        .fetch_all(&self.pool)
60        .await?;
61        Ok(rows
62            .into_iter()
63            .map(|(node, n)| (node, usize::try_from(n).unwrap_or(0)))
64            .collect())
65    }
66
67    /// The tasks in `status` that `node` runs, across every repo
68    pub async fn list_owned(&self, node: &str, status: TaskStatus) -> anyhow::Result<Vec<Task>> {
69        Ok(self
70            .list_all_by_status_global(status)
71            .await?
72            .into_iter()
73            .filter(|t| t.owner_node.as_deref() == Some(node))
74            .collect())
75    }
76
77    /// Renew this node's lease on every run it holds for `ttl_secs`. 0 ends them at once. Does
78    /// nothing on one machine
79    pub async fn renew_leases(&self, ttl_secs: i64) -> anyhow::Result<u64> {
80        let Some(node) = self.node() else {
81            return Ok(0);
82        };
83        match self
84            .write(Command::TaskRenewLeases {
85                node: node.name().to_string(),
86                secs: ttl_secs,
87            })
88            .await?
89        {
90            Reply::Count(n) => Ok(n),
91            other => anyhow::bail!("expected a count reply, got {other:?}"),
92        }
93    }
94
95    /// Give back a run `node` holds under `term`, see `apply::release`
96    pub async fn release_assignment(
97        &self,
98        id: i64,
99        node: &str,
100        term: i64,
101        status: TaskStatus,
102    ) -> anyhow::Result<bool> {
103        self.write_bool(Command::TaskRelease {
104            id,
105            node: node.to_string(),
106            term,
107            status,
108        })
109        .await
110    }
111
112    /**
113     * True when another node holds the task, as after `orch task move`, while this node ran it. This
114     * node then applies nothing from its run. Always false on one machine
115     **/
116    pub fn moved_away(&self, task: &Task) -> bool {
117        let Some(node) = self.node() else {
118            return false;
119        };
120        task.owner_node.as_deref().is_some_and(|o| o != node.name())
121    }
122
123    /// Give the task to `node`, see `apply::move_to`. False when the task is done or waiting
124    pub async fn move_to_node(
125        &self,
126        id: i64,
127        node: &str,
128        from: Option<&str>,
129    ) -> anyhow::Result<bool> {
130        self.write_bool(Command::TaskMove {
131            id,
132            node: node.to_string(),
133            from: from.map(str::to_string),
134        })
135        .await
136    }
137
138    /// The ids of the tasks that moved away from `node` and may still have a session there
139    pub async fn moved_from(&self, node: &str) -> anyhow::Result<Vec<i64>> {
140        Ok(self
141            .kv_list_prefix(MOVED_PREFIX)
142            .await?
143            .into_iter()
144            .filter(|(_, from)| from == node)
145            .filter_map(|(key, _)| key.strip_prefix(MOVED_PREFIX)?.parse().ok())
146            .collect())
147    }
148
149    /// Forget a move once the old node ended its session
150    pub async fn clear_moved(&self, id: i64) -> anyhow::Result<()> {
151        self.kv_delete(&format!("{MOVED_PREFIX}{id}")).await
152    }
153}