use std::collections::HashMap;
use std::sync::Arc;
use shep_core::protocol::{Lamb, ProcessInfo};
use crate::limits::stats::StatsState;
use super::context::RpcContext;
pub(super) async fn dog_staleness(ctx: &RpcContext) -> (Vec<String>, Vec<String>) {
let stale = ctx.dog_refusals.stale();
let mut pending = ctx.dog_refusals.restarting();
if let Ok(infos) = ctx.supervisor.list_checked().await {
pending.extend(crate::dogs::silent_dogs(&infos, &ctx.dog_refusals));
}
pending.sort();
pending.dedup();
(stale, pending)
}
#[cfg(unix)]
pub(super) async fn handover_refusal(ctx: &RpcContext) -> Option<String> {
match ctx.supervisor.handover_fitness().await {
Ok(crate::handover::Fitness::Carryable) => None,
Ok(crate::handover::Fitness::Refused(reason)) => Some(reason.to_string()),
Err(err) => Some(format!(
"this shepherd could not check whether its flock can be handed over ({err})"
)),
}
}
#[cfg(windows)]
#[expect(
clippy::unused_async,
reason = "one signature for both platforms; the unix arm awaits the supervisor"
)]
pub(super) async fn handover_refusal(_ctx: &RpcContext) -> Option<String> {
Some(
"this shepherd runs on Windows, which has no `execve`, so its flock cannot be handed to \
a successor in place"
.to_string(),
)
}
pub(super) async fn with_live_stats(
stats: &Arc<StatsState>,
mut infos: Vec<ProcessInfo>,
) -> Vec<ProcessInfo> {
let stats = Arc::clone(stats);
let Ok(sample) = tokio::task::spawn_blocking(move || stats.sample_now()).await else {
return infos;
};
for info in &mut infos {
if let Some(reading) = info.pid.and_then(|pid| sample.get(&pid)) {
info.cpu_percent = reading.cpu_percent;
info.memory_bytes = Some(reading.memory_bytes);
info.cpu_ms = Some(reading.cpu_ms);
}
}
infos
}
pub(super) fn with_dog_contact(
refusals: &crate::dogs::DogRefusals,
mut infos: Vec<ProcessInfo>,
) -> Vec<ProcessInfo> {
let stale = refusals.stale();
for info in &mut infos {
if info.dog.is_some() {
info.handshook = Some(refusals.has_handshook(&info.name));
info.dog_stale = Some(stale.contains(&info.name));
}
}
infos
}
pub(super) async fn with_lambs(
stats: &Arc<StatsState>,
mut infos: Vec<ProcessInfo>,
) -> Vec<ProcessInfo> {
if infos.iter().all(|info| info.pid.is_none()) {
return infos;
}
let stats = Arc::clone(stats);
let pids: Vec<u32> = infos.iter().filter_map(|info| info.pid).collect();
let Ok(walked) = tokio::task::spawn_blocking(move || {
let index = stats.lamb_index();
pids.into_iter()
.map(|pid| (pid, stats.lambs_of(&index, pid)))
.collect::<HashMap<u32, Vec<Lamb>>>()
})
.await
else {
return infos;
};
for info in &mut infos {
if let Some(lambs) = info.pid.and_then(|pid| walked.get(&pid)) {
info.lambs = Some(lambs.clone());
}
}
infos
}