use chrono::{DateTime, Utc};
use crate::engine::tick::assign;
use crate::store::cluster::registry::{self, Entry};
use crate::store::{Task, TaskStatus, TaskStore};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Moved {
pub from: Option<String>,
pub from_online: bool,
pub to: String,
pub to_online: bool,
pub branch: String,
}
fn refusal(entry: &Entry, repo: &str, agent: Option<&str>) -> Option<String> {
let node = &entry.node;
if entry.witness {
return Some(format!("{node} is a witness and runs no tasks"));
}
if !entry.hosts(repo) {
return Some(format!("{node} does not host {repo}"));
}
match agent {
Some(agent) if !entry.agents.iter().any(|a| a == agent) => {
Some(format!("{node} has no {agent} agent"))
}
None if entry.agents.is_empty() => Some(format!("{node} has no agent")),
_ => None,
}
}
async fn target(
store: &TaskStore,
entries: &[Entry],
task: &Task,
agent: Option<&str>,
wanted: Option<&str>,
now: DateTime<Utc>,
) -> anyhow::Result<String> {
let owner = task.owner_node.as_deref();
if let Some(wanted) = wanted {
anyhow::ensure!(
owner != Some(wanted),
"task {} is already on {wanted}",
task.id
);
let entry = entries
.iter()
.find(|e| e.node == wanted)
.ok_or_else(|| anyhow::anyhow!("no node named {wanted} in the cluster"))?;
if let Some(why) = refusal(entry, &task.repo, agent) {
anyhow::bail!("cannot move task {} to {wanted}: {why}", task.id);
}
return Ok(wanted.to_string());
}
let others: Vec<Entry> = entries
.iter()
.filter(|e| Some(e.node.as_str()) != owner)
.cloned()
.collect();
let running = store.running_per_node(TaskStatus::InProgress).await?;
assign::choose(&others, &running, "", &task.repo, agent, now).ok_or_else(|| {
anyhow::anyhow!(
"no other online node hosts {} with {} and has a free slot",
task.repo,
agent.unwrap_or("an agent")
)
})
}
pub async fn move_task(
store: &TaskStore,
task: &Task,
wanted: Option<&str>,
now: DateTime<Utc>,
) -> anyhow::Result<Moved> {
anyhow::ensure!(
task.status != TaskStatus::Done,
"task {} is done, a done task never moves",
task.id
);
anyhow::ensure!(
task.status != TaskStatus::Waiting,
"task {} waits on an open dependency, it has no run to move",
task.id
);
let agent = task.agent.as_deref().filter(|a| !a.is_empty());
anyhow::ensure!(
agent.is_some(),
"task {} has no agent yet, it moves once it is routed",
task.id
);
let entries = registry::read(store).await?;
anyhow::ensure!(
!entries.is_empty(),
"the node registry is empty, is the cluster running?"
);
let to = target(store, &entries, task, agent, wanted, now).await?;
let from = task.owner_node.clone();
anyhow::ensure!(
store.move_to_node(task.id, &to, from.as_deref()).await?,
"task {} changed status before the move, nothing moved",
task.id
);
let online = |node: &str| entries.iter().any(|e| e.node == node && e.online_at(now));
Ok(Moved {
from_online: from.as_deref().is_some_and(online),
to_online: online(&to),
from,
to,
branch: task.branch.clone(),
})
}
#[cfg(test)]
mod tests;