use std::collections::HashMap;
use super::{Task, TaskStatus};
use crate::store::TaskStore;
use crate::store::{Command, Reply};
pub(crate) const MOVED_PREFIX: &str = "moved:";
impl TaskStore {
pub fn runs_elsewhere(&self, task: &Task) -> bool {
let Some(node) = self.node() else {
return false;
};
match task.owner_node.as_deref() {
Some(owner) => owner != node.name(),
None => !node.is_leader(),
}
}
pub fn reconciles_here(&self, task: &Task) -> bool {
!self.runs_elsewhere(task) || (task.owner_node.is_none() && task.status == TaskStatus::Done)
}
pub async fn runs_elsewhere_by_ref(&self, repo: &str, task_id: &str) -> bool {
if self.node().is_none() {
return false;
}
match self.resolve_task_id(repo, task_id).await {
Ok(Some(id)) => self.get(id).await.is_ok_and(|t| self.runs_elsewhere(&t)),
_ => false,
}
}
pub async fn running_per_node(
&self,
status: TaskStatus,
) -> anyhow::Result<HashMap<String, usize>> {
let rows: Vec<(String, i64)> = sqlx::query_as(
"SELECT owner_node, COUNT(*) FROM tasks
WHERE status = ? AND owner_node IS NOT NULL GROUP BY owner_node",
)
.bind(status.as_str())
.fetch_all(&self.pool)
.await?;
Ok(rows
.into_iter()
.map(|(node, n)| (node, usize::try_from(n).unwrap_or(0)))
.collect())
}
pub async fn list_owned(&self, node: &str, status: TaskStatus) -> anyhow::Result<Vec<Task>> {
Ok(self
.list_all_by_status_global(status)
.await?
.into_iter()
.filter(|t| t.owner_node.as_deref() == Some(node))
.collect())
}
pub async fn renew_leases(&self, ttl_secs: i64) -> anyhow::Result<u64> {
let Some(node) = self.node() else {
return Ok(0);
};
match self
.write(Command::TaskRenewLeases {
node: node.name().to_string(),
secs: ttl_secs,
})
.await?
{
Reply::Count(n) => Ok(n),
other => anyhow::bail!("expected a count reply, got {other:?}"),
}
}
pub async fn release_assignment(
&self,
id: i64,
node: &str,
term: i64,
status: TaskStatus,
) -> anyhow::Result<bool> {
self.write_bool(Command::TaskRelease {
id,
node: node.to_string(),
term,
status,
})
.await
}
pub fn moved_away(&self, task: &Task) -> bool {
let Some(node) = self.node() else {
return false;
};
task.owner_node.as_deref().is_some_and(|o| o != node.name())
}
pub async fn move_to_node(
&self,
id: i64,
node: &str,
from: Option<&str>,
) -> anyhow::Result<bool> {
self.write_bool(Command::TaskMove {
id,
node: node.to_string(),
from: from.map(str::to_string),
})
.await
}
pub async fn moved_from(&self, node: &str) -> anyhow::Result<Vec<i64>> {
Ok(self
.kv_list_prefix(MOVED_PREFIX)
.await?
.into_iter()
.filter(|(_, from)| from == node)
.filter_map(|(key, _)| key.strip_prefix(MOVED_PREFIX)?.parse().ok())
.collect())
}
pub async fn clear_moved(&self, id: i64) -> anyhow::Result<()> {
self.kv_delete(&format!("{MOVED_PREFIX}{id}")).await
}
}