Skip to main content

orch/engine/tasks/
handoff.rs

1//! `orch task move`: hand a task to another node of the cluster. The new node starts from the task
2//! branch as last pushed, see `docs/content/docs/cluster.md`
3
4use chrono::{DateTime, Utc};
5
6use crate::engine::tick::assign;
7use crate::store::cluster::registry::{self, Entry};
8use crate::store::{Task, TaskStatus, TaskStore};
9
10/// What a move did, for the CLI to print
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct Moved {
13    /// The node that held the task, None when no node did
14    pub from: Option<String>,
15    /// Whether that node is online, so it ends its session now and not when it is back
16    pub from_online: bool,
17    pub to: String,
18    /// Whether the new node is online, a task for an offline node waits for it
19    pub to_online: bool,
20    pub branch: String,
21}
22
23/// Why `node` cannot run a task of `repo` with `agent`, or None when it can
24fn refusal(entry: &Entry, repo: &str, agent: Option<&str>) -> Option<String> {
25    let node = &entry.node;
26    if entry.witness {
27        return Some(format!("{node} is a witness and runs no tasks"));
28    }
29
30    if !entry.hosts(repo) {
31        return Some(format!("{node} does not host {repo}"));
32    }
33
34    match agent {
35        Some(agent) if !entry.agents.iter().any(|a| a == agent) => {
36            Some(format!("{node} has no {agent} agent"))
37        }
38        None if entry.agents.is_empty() => Some(format!("{node} has no agent")),
39        _ => None,
40    }
41}
42
43/// The node a move goes to: `wanted` once it passes the checks, or the one the assignment rules pick
44async fn target(
45    store: &TaskStore,
46    entries: &[Entry],
47    task: &Task,
48    agent: Option<&str>,
49    wanted: Option<&str>,
50    now: DateTime<Utc>,
51) -> anyhow::Result<String> {
52    let owner = task.owner_node.as_deref();
53    if let Some(wanted) = wanted {
54        anyhow::ensure!(
55            owner != Some(wanted),
56            "task {} is already on {wanted}",
57            task.id
58        );
59        let entry = entries
60            .iter()
61            .find(|e| e.node == wanted)
62            .ok_or_else(|| anyhow::anyhow!("no node named {wanted} in the cluster"))?;
63        if let Some(why) = refusal(entry, &task.repo, agent) {
64            anyhow::bail!("cannot move task {} to {wanted}: {why}", task.id);
65        }
66
67        return Ok(wanted.to_string());
68    }
69
70    let others: Vec<Entry> = entries
71        .iter()
72        .filter(|e| Some(e.node.as_str()) != owner)
73        .cloned()
74        .collect();
75    let running = store.running_per_node(TaskStatus::InProgress).await?;
76    assign::choose(&others, &running, "", &task.repo, agent, now).ok_or_else(|| {
77        anyhow::anyhow!(
78            "no other online node hosts {} with {} and has a free slot",
79            task.repo,
80            agent.unwrap_or("an agent")
81        )
82    })
83}
84
85/**
86 * Give `task` to `wanted`, or to the node the assignment rules pick. One command sets the owner,
87 * clears the lease and returns the task to `routed`, and the leader dispatches it there. The old
88 * node kills its session when it sees the move and keeps its worktree and local branch
89 **/
90pub async fn move_task(
91    store: &TaskStore,
92    task: &Task,
93    wanted: Option<&str>,
94    now: DateTime<Utc>,
95) -> anyhow::Result<Moved> {
96    anyhow::ensure!(
97        task.status != TaskStatus::Done,
98        "task {} is done, a done task never moves",
99        task.id
100    );
101    anyhow::ensure!(
102        task.status != TaskStatus::Waiting,
103        "task {} waits on an open dependency, it has no run to move",
104        task.id
105    );
106    let agent = task.agent.as_deref().filter(|a| !a.is_empty());
107    anyhow::ensure!(
108        agent.is_some(),
109        "task {} has no agent yet, it moves once it is routed",
110        task.id
111    );
112
113    let entries = registry::read(store).await?;
114    anyhow::ensure!(
115        !entries.is_empty(),
116        "the node registry is empty, is the cluster running?"
117    );
118    let to = target(store, &entries, task, agent, wanted, now).await?;
119    let from = task.owner_node.clone();
120    anyhow::ensure!(
121        store.move_to_node(task.id, &to, from.as_deref()).await?,
122        "task {} changed status before the move, nothing moved",
123        task.id
124    );
125
126    let online = |node: &str| entries.iter().any(|e| e.node == node && e.online_at(now));
127    Ok(Moved {
128        from_online: from.as_deref().is_some_and(online),
129        to_online: online(&to),
130        from,
131        to,
132        branch: task.branch.clone(),
133    })
134}
135
136#[cfg(test)]
137mod tests;