use serde::{Deserialize, Deserializer, Serialize};
use super::{
CheckStatus, Doctor, DoctorState, Insight, InsightKind, Insights, QueuedJob, Severity, Status,
Tone, View, Waiting,
};
pub const ATTENTION_MAX: usize = 50;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Attention {
pub instance: String,
pub revision: u64,
pub items: Vec<AttentionItem>,
#[serde(default, skip_serializing_if = "is_zero")]
pub omitted: u64,
}
#[expect(
clippy::trivially_copy_pass_by_ref,
reason = "serde's skip_serializing_if passes a reference"
)]
fn is_zero(count: &u64) -> bool {
*count == 0
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AttentionItem {
pub key: String,
pub kind: AttentionKind,
#[serde(deserialize_with = "tone_or_neutral")]
pub tone: Tone,
pub title: String,
pub subject: Subject,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub since: Option<u64>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "lenient"
)]
pub fix: Option<Fix>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum AttentionKind {
CannotStart,
HostMemory,
Doctor,
DoctorUnavailable,
Insight,
GithubListing,
GithubAuth,
RateLimited,
#[serde(other)]
Unknown,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", tag = "kind")]
pub enum Subject {
Job {
id: u64,
repository: String,
name: String,
},
Repository {
name: String,
},
Check {
name: String,
},
Insight {
key: String,
},
Host,
Github,
#[serde(other)]
Unknown,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", tag = "kind")]
pub enum Fix {
Command {
command: String,
},
Config {
key: String,
},
Open {
view: View,
},
Text {
text: String,
},
}
impl Fix {
pub fn line(&self) -> String {
match self {
Fix::Command { command } => command.clone(),
Fix::Config { key } => format!("Change {key} in the config"),
Fix::Open { view } => format!("Open {}", view.title()),
Fix::Text { text } => text.clone(),
}
}
}
impl Attention {
pub fn new(instance: String, revision: u64, mut items: Vec<AttentionItem>) -> Attention {
let omitted = items.len().saturating_sub(ATTENTION_MAX);
items.truncate(ATTENTION_MAX);
Attention {
instance,
revision,
items,
omitted: omitted as u64,
}
}
pub fn same_content(&self, other: &Attention) -> bool {
self.items == other.items && self.omitted == other.omitted
}
pub fn count(&self) -> u64 {
self.items.len() as u64 + self.omitted
}
pub fn more(&self, shown: usize) -> Option<String> {
let rest = self.items.len().saturating_sub(shown) as u64 + self.omitted;
(rest > 0).then(|| format!("and {rest} more"))
}
}
pub fn attention_items(
status: &Status,
doctor: &Doctor,
insights: Option<&Insights>,
now: u64,
) -> Vec<AttentionItem> {
let mut items = cannot_start(status);
items.extend(host_memory(status, insights));
items.extend(doctor_items(doctor, now));
items.extend(
insights
.into_iter()
.flat_map(|insights| &insights.insights)
.filter_map(insight_item),
);
items.extend(github(status, now));
items.sort_by(|a, b| {
rank(a.tone)
.cmp(&rank(b.tone))
.then_with(|| b.since.is_some().cmp(&a.since.is_some()))
.then_with(|| b.since.cmp(&a.since))
.then_with(|| a.key.cmp(&b.key))
});
items
}
fn rank(tone: Tone) -> u8 {
match tone {
Tone::Bad => 0,
Tone::Warn => 1,
Tone::Neutral => 2,
Tone::Quiet => 3,
Tone::Good => 4,
}
}
fn cannot_start(status: &Status) -> Vec<AttentionItem> {
let mut groups: Vec<(String, Vec<&QueuedJob>)> = Vec::new();
for job in &status.queued {
let Some(waiting) = job
.waiting
.as_ref()
.filter(|waiting| waiting.cannot_start())
else {
continue;
};
let key = match waiting {
Waiting::NoPool { labels } => format!(
"cannot-start:no-pool:{}:{}",
job.repository,
labels.join(",")
),
_ => format!("cannot-start:paused:{}", job.repository),
};
match groups.iter_mut().find(|(group, _)| *group == key) {
Some((_, jobs)) => jobs.push(job),
None => groups.push((key, vec![job])),
}
}
groups
.into_iter()
.filter_map(|(key, jobs)| {
let first = *jobs.first()?;
let repository = &first.repository;
let (what, subject) = match jobs.as_slice() {
[job] => (
format!("{} of {repository}", job.name),
Subject::Job {
id: job.id,
repository: repository.clone(),
name: job.name.clone(),
},
),
_ => (
format!("{} queued jobs of {repository}", jobs.len()),
Subject::Repository {
name: repository.clone(),
},
),
};
let (why, fix) = match first.waiting.as_ref()? {
Waiting::NoPool { labels } if labels.is_empty() => (
"it asks for no labels, so no profile serves it".to_owned(),
Fix::Config {
key: "repositories.labels".to_owned(),
},
),
Waiting::NoPool { labels } => (
format!(
"no profile of {repository} serves the {} {}",
if labels.len() == 1 { "label" } else { "labels" },
labels.join(", ")
),
Fix::Config {
key: "repositories.labels".to_owned(),
},
),
_ => (
format!("{repository} is paused"),
Fix::Command {
command: format!("runnerctl resume {repository}"),
},
),
};
Some(AttentionItem {
key,
kind: AttentionKind::CannotStart,
tone: Tone::Warn,
title: format!("runnerd cannot start {what} with the current configuration: {why}"),
subject,
since: jobs
.iter()
.map(|job| job.queued_at)
.filter(|at| *at > 0)
.min(),
fix: Some(fix),
})
})
.collect()
}
fn host_memory(status: &Status, insights: Option<&Insights>) -> Option<AttentionItem> {
let held = insights?
.insights
.iter()
.find(|insight| matches!(insight.kind, InsightKind::HostHeld { .. }))?;
status
.queued
.iter()
.any(|job| matches!(job.waiting, Some(Waiting::HostMemory { .. })))
.then(|| AttentionItem {
key: "host-memory".to_owned(),
kind: AttentionKind::HostMemory,
tone: Tone::Warn,
title: held.sentence.clone(),
subject: Subject::Host,
since: None,
fix: Some(Fix::Open {
view: View::Overview,
}),
})
}
fn doctor_items(doctor: &Doctor, now: u64) -> Vec<AttentionItem> {
let at = match &doctor.state {
None => None,
Some(DoctorState::Ready { at }) => Some(*at),
Some(
state @ (DoctorState::NotRun
| DoctorState::Stale { .. }
| DoctorState::Failed { .. }
| DoctorState::Unknown),
) => {
let (tone, since) = match state {
DoctorState::Failed { at, .. } => (Tone::Warn, Some(*at)),
DoctorState::Stale { at } => (Tone::Quiet, Some(*at)),
_ => (Tone::Quiet, None),
};
return state
.line(now)
.map(|title| AttentionItem {
key: "doctor-unavailable".to_owned(),
kind: AttentionKind::DoctorUnavailable,
tone,
title,
subject: Subject::Host,
since,
fix: Some(Fix::Open {
view: View::Settings,
}),
})
.into_iter()
.collect();
}
};
let shown: Vec<_> = doctor
.checks
.iter()
.filter(|check| matches!(check.status, CheckStatus::Fail | CheckStatus::Warn))
.filter(|check| check.name != super::JOB_ACTIONS_CHECK)
.collect();
let mut keys: Vec<String> = Vec::new();
shown
.iter()
.map(|check| {
let repeated = shown
.iter()
.filter(|other| other.name == check.name)
.count()
> 1;
let mut key = if repeated {
format!("doctor:{}:{}", check.name, check.detail)
} else {
format!("doctor:{}", check.name)
};
let twins = keys.iter().filter(|seen| **seen == key).count();
keys.push(key.clone());
if twins > 0 {
key = format!("{key}#{}", twins + 1);
}
AttentionItem {
key,
kind: AttentionKind::Doctor,
tone: check.status.tone(),
title: format!("{}: {}", check.name, check.detail),
subject: Subject::Check {
name: check.name.clone(),
},
since: at,
fix: Some(match &check.fix {
Some(text) => Fix::Text { text: text.clone() },
None => Fix::Open {
view: View::Settings,
},
}),
}
})
.collect()
}
fn insight_item(insight: &Insight) -> Option<AttentionItem> {
let current = !matches!(
insight.kind,
InsightKind::HostHeld { .. } | InsightKind::HostLow { .. } | InsightKind::Unknown
);
(insight.severity == Severity::Warning && current).then(|| AttentionItem {
key: format!("insight:{}", insight.key),
kind: AttentionKind::Insight,
tone: Tone::Warn,
title: insight.sentence.clone(),
subject: Subject::Insight {
key: insight.key.clone(),
},
since: insight.runs.first().map(|run| run.at),
fix: Some(Fix::Open {
view: View::Insights,
}),
})
}
fn github(status: &Status, now: u64) -> Vec<AttentionItem> {
let failing: Vec<_> = status
.repositories
.iter()
.filter_map(|repository| Some((repository.name.as_str(), repository.listing.as_ref()?)))
.collect();
let token = failing
.iter()
.filter(|(_, failure)| failure.problem.is_token())
.min_by_key(|(_, failure)| failure.since);
let mut items: Vec<AttentionItem> = token
.map(|(_, failure)| AttentionItem {
key: "github-auth".to_owned(),
kind: AttentionKind::GithubAuth,
tone: Tone::Bad,
title: match failure.problem {
super::ListingProblem::NoToken => {
"runnerd has no GitHub token, so it lists no repository's queued jobs"
.to_owned()
}
_ => {
"GitHub refuses runnerd's token (401), so it lists no repository's queued jobs"
.to_owned()
}
},
subject: Subject::Github,
since: Some(failure.since),
fix: Some(Fix::Open {
view: View::Settings,
}),
})
.into_iter()
.collect();
items.extend(
failing
.iter()
.filter(|(_, failure)| !failure.problem.is_token())
.map(|(name, failure)| AttentionItem {
key: format!("github-listing:{name}"),
kind: AttentionKind::GithubListing,
tone: Tone::Warn,
title: failure.line(name),
subject: Subject::Repository {
name: (*name).to_owned(),
},
since: Some(failure.since),
fix: matches!(failure.problem, super::ListingProblem::Refused { .. }).then_some(
Fix::Open {
view: View::Settings,
},
),
}),
);
let limited = status.github_limited_until.is_some_and(|until| until > now);
items.extend(
status
.github_line()
.filter(|_| limited)
.map(|line| AttentionItem {
key: "rate-limited".to_owned(),
kind: AttentionKind::RateLimited,
tone: Tone::Warn,
title: line.to_owned(),
subject: Subject::Github,
since: None,
fix: None,
}),
);
items
}
fn lenient<'de, D: Deserializer<'de>, T: Deserialize<'de>>(
deserializer: D,
) -> Result<Option<T>, D::Error> {
#[derive(Deserialize)]
#[serde(untagged)]
enum Read<T> {
Known(T),
Other(serde::de::IgnoredAny),
}
Ok(match Option::<Read<T>>::deserialize(deserializer)? {
Some(Read::Known(value)) => Some(value),
Some(Read::Other(_)) | None => None,
})
}
fn tone_or_neutral<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Tone, D::Error> {
Ok(lenient(deserializer)?.unwrap_or(Tone::Neutral))
}
#[cfg(all(test, any(feature = "host", feature = "client")))]
mod tests;