use std::time::{Duration, Instant};
use super::ResourceTab;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StatsRequest {
pub tab: ResourceTab,
pub id: String,
pub name: String
}
#[derive(Debug, Clone, Default)]
pub struct ResourceStats {
pub id: String,
pub subject: String,
pub cpu: Vec<f64>,
pub ram: Vec<f64>,
pub net_in: Vec<f64>,
pub net_out: Vec<f64>
}
impl super::App {
const STATS_REFRESH: Duration = Duration::from_secs(30);
pub fn poll_stats_request(&mut self) -> Option<StatsRequest> {
let idx = self.selected_real_index();
let target = match self.active_tab {
ResourceTab::Servers => self
.servers
.get(idx)
.map(|s| (s.id.to_string(), s.name.clone())),
ResourceTab::Apps => self
.apps
.get(idx)
.map(|a| (a.id.to_string(), a.name.clone())),
_ => None
};
let target_id = target.as_ref().map(|(id, _)| id.clone());
let fresh = self
.stats_requested
.is_some_and(|at| at.elapsed() < Self::STATS_REFRESH);
if target_id == self.stats_loaded_for && fresh {
return None;
}
self.stats_loaded_for = target_id;
if let Some((id, name)) = target {
self.stats_requested = Some(Instant::now());
Some(StatsRequest {
tab: self.active_tab,
id,
name
})
} else {
self.stats_requested = None;
self.clear_stats();
None
}
}
fn clear_stats(&mut self) {
self.stats_subject = None;
self.cpu_history.clear();
self.ram_history.clear();
self.net_in_history.clear();
self.net_out_history.clear();
}
pub fn apply_stats(&mut self, stats: ResourceStats) {
if self.stats_loaded_for.as_deref() != Some(stats.id.as_str()) {
return;
}
self.stats_subject = Some(stats.subject);
self.cpu_history = stats.cpu.into_iter().collect();
self.ram_history = stats.ram.into_iter().collect();
self.net_in_history = stats.net_in.into_iter().collect();
self.net_out_history = stats.net_out.into_iter().collect();
}
#[allow(dead_code)]
pub fn push_cpu(&mut self, value: f64) {
if self.cpu_history.len() >= 60 {
self.cpu_history.pop_front();
}
self.cpu_history.push_back(value);
}
#[allow(dead_code)]
pub fn push_ram(&mut self, value: f64) {
if self.ram_history.len() >= 60 {
self.ram_history.pop_front();
}
self.ram_history.push_back(value);
}
#[allow(dead_code)]
pub fn push_net_in(&mut self, value: f64) {
if self.net_in_history.len() >= 60 {
self.net_in_history.pop_front();
}
self.net_in_history.push_back(value);
}
#[allow(dead_code)]
pub fn push_net_out(&mut self, value: f64) {
if self.net_out_history.len() >= 60 {
self.net_out_history.pop_front();
}
self.net_out_history.push_back(value);
}
}