use std::collections::{HashMap, HashSet};
use chrono::{DateTime, Utc};
use crate::store::Task;
use crate::store::TaskStatus;
use crate::store::TaskStore;
use crate::store::cluster::lease::{self, Lease};
use crate::store::cluster::registry::{self, Entry};
pub(crate) const WAITING_PREFIX: &str = "waiting for a node with ";
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Assignment {
pub(crate) node: String,
pub(crate) term: u64,
}
impl Assignment {
pub(crate) fn fields(&self) -> [(&'static str, serde_json::Value); 3] {
[
("owner_node", serde_json::json!(self.node)),
("owner_term", serde_json::json!(self.term)),
(
"lease_until",
serde_json::json!(Lease::load().until(Utc::now())),
),
]
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Placement {
Single,
Here(Assignment),
There(Assignment),
Waiting,
}
pub(crate) fn choose(
entries: &[Entry],
running: &HashMap<String, usize>,
me: &str,
repo: &str,
agent: Option<&str>,
now: DateTime<Utc>,
) -> Option<String> {
entries
.iter()
.filter(|e| e.online_at(now) && e.can_run(repo, agent))
.filter_map(|e| {
let busy = running.get(&e.node).copied().unwrap_or(0);
let free = e.max_parallel.checked_sub(busy).filter(|f| *f > 0)?;
Some((free, e))
})
.max_by(|(fa, a), (fb, b)| {
fa.cmp(fb)
.then_with(|| (a.node == me).cmp(&(b.node == me)))
.then_with(|| b.node.cmp(&a.node))
})
.map(|(_, e)| e.node.clone())
}
pub(crate) async fn place(
store: &TaskStore,
repo: &str,
agent: Option<&str>,
status: TaskStatus,
) -> Placement {
let Some(node) = store.node() else {
return Placement::Single;
};
let entries = match registry::read(store).await {
Ok(entries) => entries,
Err(e) => {
tracing::warn!(repo, err = %e, "cannot read the node registry, the run waits");
return Placement::Waiting;
}
};
let running = match store.running_per_node(status).await {
Ok(running) => running,
Err(e) => {
tracing::warn!(repo, err = %e, "cannot count the runs per node, the run waits");
return Placement::Waiting;
}
};
let Some(chosen) = choose(&entries, &running, node.name(), repo, agent, Utc::now()) else {
return Placement::Waiting;
};
let assignment = Assignment {
term: node.term(),
node: chosen,
};
if assignment.node == node.name() {
Placement::Here(assignment)
} else {
Placement::There(assignment)
}
}
pub(crate) async fn host_agents(store: &TaskStore, repo: &str) -> Option<HashSet<String>> {
store.node()?;
let entries = registry::read(store).await.ok()?;
let now = Utc::now();
let agents: HashSet<String> = entries
.iter()
.filter(|e| e.online_at(now) && !e.witness && e.hosts(repo))
.flat_map(|e| e.agents.iter().cloned())
.collect();
(!agents.is_empty()).then_some(agents)
}
pub(crate) async fn note_waiting(store: &TaskStore, repo: &str, task_id: &str) {
let Ok(Some(id)) = store.resolve_task_id(repo, task_id).await else {
return;
};
let Ok(task) = store.get(id).await else {
return;
};
if task.last_error.starts_with(WAITING_PREFIX) {
tracing::debug!(task_id, repo, "still waiting for a node");
return;
}
tracing::info!(task_id, repo, "no online node can run the task, it waits");
let reason = format!("{WAITING_PREFIX}{repo}");
if let Err(e) = store
.set_fields_silent(id, &[("last_error", serde_json::json!(reason))])
.await
{
tracing::warn!(task_id, err = %e, "failed to record the wait for a node");
}
}
pub(crate) fn owner_waiting(node: &str) -> String {
format!("waiting for {node}, its lease expired")
}
pub(crate) async fn held_elsewhere(store: &TaskStore, task: &Task) -> bool {
if !store.runs_elsewhere(task) {
return false;
}
let Some(owner) = task.owner_node.as_deref() else {
return true;
};
let note = owner_waiting(owner);
let alive = lease::valid(task.lease_until.as_deref(), Utc::now());
let last_error = match (alive, task.last_error == note) {
(true, true) => {
tracing::info!(
task_id = task.id,
node = owner,
"the owner renewed its lease"
);
String::new()
}
(false, false) => {
tracing::warn!(
task_id = task.id,
node = owner,
lease_until = task.lease_until.as_deref().unwrap_or("-"),
"the owner's lease expired, the task waits for it"
);
note
}
_ => return true,
};
if let Err(e) = store
.set_fields_silent(task.id, &[("last_error", serde_json::json!(last_error))])
.await
{
tracing::warn!(task_id = task.id, err = %e, "failed to record the owner's lease state");
}
true
}
pub(crate) async fn held_elsewhere_by_ref(store: &TaskStore, repo: &str, task_id: &str) -> bool {
if store.node().is_none() {
return false;
}
let Ok(Some(id)) = store.resolve_task_id(repo, task_id).await else {
return false;
};
match store.get(id).await {
Ok(task) => held_elsewhere(store, &task).await,
Err(_) => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::Duration;
fn entry(node: &str, projects: &[&str], agents: &[&str], max: usize) -> Entry {
Entry {
node: node.into(),
projects: projects.iter().map(ToString::to_string).collect(),
agents: agents.iter().map(ToString::to_string).collect(),
max_parallel: max,
version: None,
witness: false,
seen: Utc::now().to_rfc3339(),
}
}
#[test]
fn a_repo_only_one_node_hosts_goes_to_that_node() {
let entries = [
entry("a", &["o/one"], &["claude"], 4),
entry("b", &["o/one", "o/two"], &["claude"], 4),
];
let got = choose(
&entries,
&HashMap::new(),
"a",
"o/two",
Some("claude"),
Utc::now(),
);
assert_eq!(got.as_deref(), Some("b"));
}
#[test]
fn an_agent_only_one_node_has_goes_to_that_node() {
let entries = [
entry("a", &["o/r"], &["claude"], 4),
entry("b", &["o/r"], &["claude", "codex"], 4),
];
let got = choose(
&entries,
&HashMap::new(),
"a",
"o/r",
Some("codex"),
Utc::now(),
);
assert_eq!(got.as_deref(), Some("b"));
}
#[test]
fn a_full_node_gets_nothing() {
let entries = [
entry("a", &["o/r"], &["claude"], 2),
entry("b", &["o/r"], &["claude"], 1),
];
let running = HashMap::from([("a".to_string(), 2), ("b".to_string(), 0)]);
let got = choose(&entries, &running, "a", "o/r", Some("claude"), Utc::now());
assert_eq!(got.as_deref(), Some("b"));
let running = HashMap::from([("a".to_string(), 2), ("b".to_string(), 1)]);
assert_eq!(
choose(&entries, &running, "a", "o/r", Some("claude"), Utc::now()),
None
);
}
#[test]
fn offline_nodes_and_witnesses_get_nothing() {
let mut offline = entry("b", &["o/r"], &["claude"], 4);
offline.seen = (Utc::now() - Duration::minutes(10)).to_rfc3339();
let mut witness = entry("w", &["o/r"], &["claude"], 4);
witness.witness = true;
let entries = [offline, witness];
assert_eq!(
choose(
&entries,
&HashMap::new(),
"a",
"o/r",
Some("claude"),
Utc::now()
),
None
);
}
#[test]
fn a_tie_goes_to_this_node() {
let entries = [
entry("a", &["o/r"], &["claude"], 2),
entry("b", &["o/r"], &["claude"], 2),
];
let got = choose(&entries, &HashMap::new(), "b", "o/r", None, Utc::now());
assert_eq!(got.as_deref(), Some("b"));
let got = choose(&entries, &HashMap::new(), "c", "o/r", None, Utc::now());
assert_eq!(got.as_deref(), Some("a"));
}
}