use std::collections::{BTreeMap, BTreeSet};
use std::time::Duration;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use super::version::Version;
use crate::store::TaskStore;
const PREFIX: &str = "node:";
pub const HEARTBEAT: Duration = Duration::from_secs(30);
pub const OFFLINE_AFTER: Duration = Duration::from_secs(90);
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Entry {
pub node: String,
pub projects: Vec<String>,
pub agents: Vec<String>,
pub max_parallel: usize,
#[serde(default)]
pub version: Option<Version>,
#[serde(default)]
pub witness: bool,
pub seen: String,
}
impl Entry {
pub fn online_at(&self, now: DateTime<Utc>) -> bool {
DateTime::parse_from_rfc3339(&self.seen).is_ok_and(|seen| {
now.signed_duration_since(seen)
.to_std()
.map_or(true, |age| age <= OFFLINE_AFTER)
})
}
pub fn hosts(&self, repo: &str) -> bool {
self.projects.iter().any(|p| p == repo)
}
pub fn can_run(&self, repo: &str, agent: Option<&str>) -> bool {
!self.witness
&& self.hosts(repo)
&& match agent {
Some(agent) => self.agents.iter().any(|a| a == agent),
None => !self.agents.is_empty(),
}
}
}
pub async fn write(store: &TaskStore, entry: &Entry) -> anyhow::Result<()> {
store
.kv_set(
&format!("{PREFIX}{}", entry.node),
&serde_json::to_string(entry)?,
)
.await
}
pub async fn read(store: &TaskStore) -> anyhow::Result<Vec<Entry>> {
Ok(store
.kv_list_prefix(PREFIX)
.await?
.into_iter()
.filter_map(|(key, value)| match serde_json::from_str(&value) {
Ok(entry) => Some(entry),
Err(e) => {
tracing::warn!(key, err = %e, "skipping a node registry row that does not parse");
None
}
})
.collect())
}
pub fn hosts_by_project(entries: &[Entry]) -> BTreeMap<String, BTreeSet<String>> {
let mut by_project: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
for entry in entries.iter().filter(|e| !e.witness) {
for project in &entry.projects {
by_project
.entry(project.clone())
.or_default()
.insert(entry.node.clone());
}
}
by_project
}