1use serde::{Deserialize, Deserializer, Serialize};
8
9use super::{
10 CheckStatus, Doctor, DoctorState, Insight, InsightKind, Insights, QueuedJob, Severity, Status,
11 Tone, View, Waiting,
12};
13
14pub const ATTENTION_MAX: usize = 50;
16
17#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
19pub struct Attention {
20 pub instance: String,
23 pub revision: u64,
27 pub items: Vec<AttentionItem>,
29 #[serde(default, skip_serializing_if = "is_zero")]
31 pub omitted: u64,
32}
33
34#[expect(
35 clippy::trivially_copy_pass_by_ref,
36 reason = "serde's skip_serializing_if passes a reference"
37)]
38fn is_zero(count: &u64) -> bool {
39 *count == 0
40}
41
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44pub struct AttentionItem {
45 pub key: String,
47 pub kind: AttentionKind,
49 #[serde(deserialize_with = "tone_or_neutral")]
51 pub tone: Tone,
52 pub title: String,
54 pub subject: Subject,
56 #[serde(default, skip_serializing_if = "Option::is_none")]
58 pub since: Option<u64>,
59 #[serde(
61 default,
62 skip_serializing_if = "Option::is_none",
63 deserialize_with = "lenient"
64 )]
65 pub fix: Option<Fix>,
66}
67
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
70#[serde(rename_all = "kebab-case")]
71pub enum AttentionKind {
72 CannotStart,
75 HostMemory,
77 Doctor,
79 DoctorUnavailable,
81 Insight,
83 GithubListing,
85 GithubAuth,
87 RateLimited,
89 #[serde(other)]
91 Unknown,
92}
93
94#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
96#[serde(rename_all = "kebab-case", tag = "kind")]
97pub enum Subject {
98 Job {
100 id: u64,
102 repository: String,
104 name: String,
106 },
107 Repository {
109 name: String,
111 },
112 Check {
114 name: String,
116 },
117 Insight {
119 key: String,
121 },
122 Host,
124 Github,
126 #[serde(other)]
128 Unknown,
129}
130
131#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
134#[serde(rename_all = "kebab-case", tag = "kind")]
135pub enum Fix {
136 Command {
138 command: String,
140 },
141 Config {
143 key: String,
145 },
146 Open {
148 view: View,
150 },
151 Text {
153 text: String,
155 },
156}
157
158impl Fix {
159 pub fn line(&self) -> String {
162 match self {
163 Fix::Command { command } => command.clone(),
164 Fix::Config { key } => format!("Change {key} in the config"),
165 Fix::Open { view } => format!("Open {}", view.title()),
166 Fix::Text { text } => text.clone(),
167 }
168 }
169}
170
171impl Attention {
172 pub fn new(instance: String, revision: u64, mut items: Vec<AttentionItem>) -> Attention {
175 let omitted = items.len().saturating_sub(ATTENTION_MAX);
176 items.truncate(ATTENTION_MAX);
177 Attention {
178 instance,
179 revision,
180 items,
181 omitted: omitted as u64,
182 }
183 }
184
185 pub fn same_content(&self, other: &Attention) -> bool {
187 self.items == other.items && self.omitted == other.omitted
188 }
189
190 pub fn count(&self) -> u64 {
192 self.items.len() as u64 + self.omitted
193 }
194
195 pub fn more(&self, shown: usize) -> Option<String> {
197 let rest = self.items.len().saturating_sub(shown) as u64 + self.omitted;
198 (rest > 0).then(|| format!("and {rest} more"))
199 }
200}
201
202pub fn attention_items(
206 status: &Status,
207 doctor: &Doctor,
208 insights: Option<&Insights>,
209 now: u64,
210) -> Vec<AttentionItem> {
211 let mut items = cannot_start(status);
212 items.extend(host_memory(status, insights));
213 items.extend(doctor_items(doctor, now));
214 items.extend(
215 insights
216 .into_iter()
217 .flat_map(|insights| &insights.insights)
218 .filter_map(insight_item),
219 );
220 items.extend(github(status, now));
221 items.sort_by(|a, b| {
222 rank(a.tone)
223 .cmp(&rank(b.tone))
224 .then_with(|| b.since.is_some().cmp(&a.since.is_some()))
225 .then_with(|| b.since.cmp(&a.since))
226 .then_with(|| a.key.cmp(&b.key))
227 });
228 items
229}
230
231fn rank(tone: Tone) -> u8 {
233 match tone {
234 Tone::Bad => 0,
235 Tone::Warn => 1,
236 Tone::Neutral => 2,
237 Tone::Quiet => 3,
238 Tone::Good => 4,
239 }
240}
241
242fn cannot_start(status: &Status) -> Vec<AttentionItem> {
244 let mut groups: Vec<(String, Vec<&QueuedJob>)> = Vec::new();
245 for job in &status.queued {
246 let Some(waiting) = job
247 .waiting
248 .as_ref()
249 .filter(|waiting| waiting.cannot_start())
250 else {
251 continue;
252 };
253 let key = match waiting {
254 Waiting::NoPool { labels } => format!(
255 "cannot-start:no-pool:{}:{}",
256 job.repository,
257 labels.join(",")
258 ),
259 _ => format!("cannot-start:paused:{}", job.repository),
260 };
261 match groups.iter_mut().find(|(group, _)| *group == key) {
262 Some((_, jobs)) => jobs.push(job),
263 None => groups.push((key, vec![job])),
264 }
265 }
266 groups
267 .into_iter()
268 .filter_map(|(key, jobs)| {
269 let first = *jobs.first()?;
270 let repository = &first.repository;
271 let (what, subject) = match jobs.as_slice() {
272 [job] => (
273 format!("{} of {repository}", job.name),
274 Subject::Job {
275 id: job.id,
276 repository: repository.clone(),
277 name: job.name.clone(),
278 },
279 ),
280 _ => (
281 format!("{} queued jobs of {repository}", jobs.len()),
282 Subject::Repository {
283 name: repository.clone(),
284 },
285 ),
286 };
287 let (why, fix) = match first.waiting.as_ref()? {
288 Waiting::NoPool { labels } if labels.is_empty() => (
289 "it asks for no labels, so no profile serves it".to_owned(),
290 Fix::Config {
291 key: "repositories.labels".to_owned(),
292 },
293 ),
294 Waiting::NoPool { labels } => (
295 format!(
296 "no profile of {repository} serves the {} {}",
297 if labels.len() == 1 { "label" } else { "labels" },
298 labels.join(", ")
299 ),
300 Fix::Config {
301 key: "repositories.labels".to_owned(),
302 },
303 ),
304 _ => (
305 format!("{repository} is paused"),
306 Fix::Command {
307 command: format!("runnerctl resume {repository}"),
308 },
309 ),
310 };
311 Some(AttentionItem {
312 key,
313 kind: AttentionKind::CannotStart,
314 tone: Tone::Warn,
315 title: format!("runnerd cannot start {what} with the current configuration: {why}"),
316 subject,
317 since: jobs
318 .iter()
319 .map(|job| job.queued_at)
320 .filter(|at| *at > 0)
321 .min(),
322 fix: Some(fix),
323 })
324 })
325 .collect()
326}
327
328fn host_memory(status: &Status, insights: Option<&Insights>) -> Option<AttentionItem> {
333 let held = insights?
334 .insights
335 .iter()
336 .find(|insight| matches!(insight.kind, InsightKind::HostHeld { .. }))?;
337 status
338 .queued
339 .iter()
340 .any(|job| matches!(job.waiting, Some(Waiting::HostMemory { .. })))
341 .then(|| AttentionItem {
342 key: "host-memory".to_owned(),
343 kind: AttentionKind::HostMemory,
344 tone: Tone::Warn,
345 title: held.sentence.clone(),
346 subject: Subject::Host,
347 since: None,
348 fix: Some(Fix::Open {
349 view: View::Overview,
350 }),
351 })
352}
353
354fn doctor_items(doctor: &Doctor, now: u64) -> Vec<AttentionItem> {
356 let at = match &doctor.state {
357 None => None,
359 Some(DoctorState::Ready { at }) => Some(*at),
360 Some(
361 state @ (DoctorState::NotRun
362 | DoctorState::Stale { .. }
363 | DoctorState::Failed { .. }
364 | DoctorState::Unknown),
365 ) => {
366 let (tone, since) = match state {
367 DoctorState::Failed { at, .. } => (Tone::Warn, Some(*at)),
368 DoctorState::Stale { at } => (Tone::Quiet, Some(*at)),
369 _ => (Tone::Quiet, None),
370 };
371 return state
372 .line(now)
373 .map(|title| AttentionItem {
374 key: "doctor-unavailable".to_owned(),
375 kind: AttentionKind::DoctorUnavailable,
376 tone,
377 title,
378 subject: Subject::Host,
379 since,
380 fix: Some(Fix::Open {
381 view: View::Settings,
382 }),
383 })
384 .into_iter()
385 .collect();
386 }
387 };
388 let shown: Vec<_> = doctor
389 .checks
390 .iter()
391 .filter(|check| matches!(check.status, CheckStatus::Fail | CheckStatus::Warn))
392 .filter(|check| check.name != super::JOB_ACTIONS_CHECK)
394 .collect();
395 let mut keys: Vec<String> = Vec::new();
396 shown
397 .iter()
398 .map(|check| {
399 let repeated = shown
402 .iter()
403 .filter(|other| other.name == check.name)
404 .count()
405 > 1;
406 let mut key = if repeated {
407 format!("doctor:{}:{}", check.name, check.detail)
408 } else {
409 format!("doctor:{}", check.name)
410 };
411 let twins = keys.iter().filter(|seen| **seen == key).count();
412 keys.push(key.clone());
413 if twins > 0 {
414 key = format!("{key}#{}", twins + 1);
415 }
416 AttentionItem {
417 key,
418 kind: AttentionKind::Doctor,
419 tone: check.status.tone(),
420 title: format!("{}: {}", check.name, check.detail),
421 subject: Subject::Check {
422 name: check.name.clone(),
423 },
424 since: at,
425 fix: Some(match &check.fix {
426 Some(text) => Fix::Text { text: text.clone() },
427 None => Fix::Open {
428 view: View::Settings,
429 },
430 }),
431 }
432 })
433 .collect()
434}
435
436fn insight_item(insight: &Insight) -> Option<AttentionItem> {
439 let current = !matches!(
440 insight.kind,
441 InsightKind::HostHeld { .. } | InsightKind::HostLow { .. } | InsightKind::Unknown
442 );
443 (insight.severity == Severity::Warning && current).then(|| AttentionItem {
444 key: format!("insight:{}", insight.key),
445 kind: AttentionKind::Insight,
446 tone: Tone::Warn,
447 title: insight.sentence.clone(),
448 subject: Subject::Insight {
449 key: insight.key.clone(),
450 },
451 since: insight.runs.first().map(|run| run.at),
452 fix: Some(Fix::Open {
453 view: View::Insights,
454 }),
455 })
456}
457
458fn github(status: &Status, now: u64) -> Vec<AttentionItem> {
460 let failing: Vec<_> = status
461 .repositories
462 .iter()
463 .filter_map(|repository| Some((repository.name.as_str(), repository.listing.as_ref()?)))
464 .collect();
465 let token = failing
466 .iter()
467 .filter(|(_, failure)| failure.problem.is_token())
468 .min_by_key(|(_, failure)| failure.since);
469 let mut items: Vec<AttentionItem> = token
470 .map(|(_, failure)| AttentionItem {
471 key: "github-auth".to_owned(),
472 kind: AttentionKind::GithubAuth,
473 tone: Tone::Bad,
474 title: match failure.problem {
475 super::ListingProblem::NoToken => {
476 "runnerd has no GitHub token, so it lists no repository's queued jobs"
477 .to_owned()
478 }
479 _ => {
480 "GitHub refuses runnerd's token (401), so it lists no repository's queued jobs"
481 .to_owned()
482 }
483 },
484 subject: Subject::Github,
485 since: Some(failure.since),
486 fix: Some(Fix::Open {
487 view: View::Settings,
488 }),
489 })
490 .into_iter()
491 .collect();
492 items.extend(
493 failing
494 .iter()
495 .filter(|(_, failure)| !failure.problem.is_token())
496 .map(|(name, failure)| AttentionItem {
497 key: format!("github-listing:{name}"),
498 kind: AttentionKind::GithubListing,
499 tone: Tone::Warn,
500 title: failure.line(name),
501 subject: Subject::Repository {
502 name: (*name).to_owned(),
503 },
504 since: Some(failure.since),
505 fix: matches!(failure.problem, super::ListingProblem::Refused { .. }).then_some(
506 Fix::Open {
507 view: View::Settings,
508 },
509 ),
510 }),
511 );
512 let limited = status.github_limited_until.is_some_and(|until| until > now);
514 items.extend(
515 status
516 .github_line()
517 .filter(|_| limited)
518 .map(|line| AttentionItem {
519 key: "rate-limited".to_owned(),
520 kind: AttentionKind::RateLimited,
521 tone: Tone::Warn,
522 title: line.to_owned(),
523 subject: Subject::Github,
524 since: None,
525 fix: None,
526 }),
527 );
528 items
529}
530
531fn lenient<'de, D: Deserializer<'de>, T: Deserialize<'de>>(
534 deserializer: D,
535) -> Result<Option<T>, D::Error> {
536 #[derive(Deserialize)]
537 #[serde(untagged)]
538 enum Read<T> {
539 Known(T),
540 Other(serde::de::IgnoredAny),
541 }
542 Ok(match Option::<Read<T>>::deserialize(deserializer)? {
543 Some(Read::Known(value)) => Some(value),
544 Some(Read::Other(_)) | None => None,
545 })
546}
547
548fn tone_or_neutral<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Tone, D::Error> {
549 Ok(lenient(deserializer)?.unwrap_or(Tone::Neutral))
550}
551
552#[cfg(all(test, any(feature = "host", feature = "client")))]
554mod tests;