Debian Codegraph @

src/app/data/store.rs

raw symbols SCIP
1 use std::{
2 borrow::Borrow,
3 hash::{Hash, Hasher},
4 time::{Duration, Instant},
5 vec::Vec,
6 };
7
8 use rustc_hash::FxHashMap;
9
10 use super::{ProcessData, TimeSeriesData};
11 #[cfg(feature = "battery")]
12 use crate::collection::batteries;
13 use crate::{
14 app::{AppConfigFields, DataFilters, filter::Filter, layout_manager::UsedWidgets},
15 collection::{
16 Data,
17 cpu::{CpuHarvest, LoadAvgHarvest},
18 disks::{DiskHarvest, IoHarvest},
19 memory::MemData,
20 network::NetworkHarvest,
21 },
22 utils::data_units::DataUnit,
23 widgets::{DiskWidgetData, TempWidgetData},
24 };
25
26 /// Because otherwise you can't do lookups for something like `(String, String)` as a key.
27 trait PairKey {
28 fn pair(&self) -> (&str, &str);
29 }
30
31 impl PairKey for (String, String) {
32 fn pair(&self) -> (&str, &str) {
33 (&self.0, &self.1)
34 }
35 }
36
37 impl PairKey for (&str, &str) {
38 fn pair(&self) -> (&str, &str) {
39 *self
40 }
41 }
42
43 impl<'a> Borrow<dyn PairKey + 'a> for (String, String) {
44 fn borrow(&self) -> &(dyn PairKey + 'a) {
45 self
46 }
47 }
48
49 impl Hash for dyn PairKey + '_ {
50 fn hash<H: Hasher>(&self, state: &mut H) {
51 self.pair().hash(state)
52 }
53 }
54
55 impl PartialEq for dyn PairKey + '_ {
56 fn eq(&self, other: &Self) -> bool {
57 self.pair() == other.pair()
58 }
59 }
60
61 impl Eq for dyn PairKey + '_ {}
62
63 #[derive(Debug, Clone)]
64 pub struct TotalNetworkData {
65 total_rx: u64,
66 total_tx: u64,
67 }
68
69 /// A collection of data. This is where we dump data into.
70 ///
71 /// TODO: Maybe reduce visibility of internal data, make it only accessible
72 /// through DataStore?
73 #[derive(Debug, Clone)]
74 pub struct InnerData {
75 // FIXME: (points_rework_v1) we could be able to remove this with some more refactoring.
76 last_update_time: Instant,
77
78 pub(crate) time_series_data: TimeSeriesData,
79 pub(crate) network_harvest: NetworkHarvest,
80 pub(crate) ram_harvest: Option<MemData>,
81 pub(crate) swap_harvest: Option<MemData>,
82 #[cfg(not(target_os = "windows"))]
83 pub(crate) cache_harvest: Option<MemData>,
84 #[cfg(feature = "zfs")]
85 pub(crate) arc_harvest: Option<MemData>,
86 #[cfg(feature = "gpu")]
87 pub(crate) gpu_harvest: Vec<(String, MemData)>,
88 pub(crate) cpu_harvest: CpuHarvest,
89 pub(crate) load_avg_harvest: LoadAvgHarvest,
90 pub(crate) process_data: ProcessData,
91 /// TODO: (points_rework_v1) Might be a better way to do this without having
92 /// to store here?
93 prev_io: FxHashMap<(String, String), (u64, u64)>,
94 pub(crate) disk_harvest: Vec<DiskWidgetData>,
95 pub(crate) temp_data: Vec<TempWidgetData>,
96 #[cfg(feature = "battery")]
97 pub(crate) battery_harvest: Vec<batteries::BatteryData>,
98
99 /// Used if we are zeroing out the network data.
100 starting_total_network: Option<TotalNetworkData>,
101 }
102
103 impl Default for InnerData {
104 fn default() -> Self {
105 InnerData {
106 last_update_time: Instant::now(),
107 time_series_data: TimeSeriesData::default(),
108 network_harvest: NetworkHarvest::default(),
109 ram_harvest: None,
110 #[cfg(not(target_os = "windows"))]
111 cache_harvest: None,
112 swap_harvest: None,
113 cpu_harvest: CpuHarvest::default(),
114 load_avg_harvest: LoadAvgHarvest::default(),
115 process_data: Default::default(),
116 prev_io: FxHashMap::default(),
117 disk_harvest: Vec::default(),
118 temp_data: Vec::default(),
119 #[cfg(feature = "battery")]
120 battery_harvest: Vec::default(),
121 #[cfg(feature = "zfs")]
122 arc_harvest: None,
123 #[cfg(feature = "gpu")]
124 gpu_harvest: Vec::default(),
125 starting_total_network: None,
126 }
127 }
128 }
129
130 impl InnerData {
131 #[allow(
132 clippy::boxed_local,
133 reason = "This avoids warnings on certain platforms (e.g. 32-bit)."
134 )]
135 fn eat_data(
136 &mut self, mut data: Box<Data>, settings: &AppConfigFields, used_widgets: &UsedWidgets,
137 filters: &DataFilters,
138 ) {
139 let harvested_time = data.collection_time;
140
141 // We must adjust all the network values to their selected type (defaults to
142 // bits).
143 if matches!(settings.network_unit_type, DataUnit::Byte)
144 && let Some(network) = &mut data.network
145 {
146 network.rx /= 8;
147 network.tx /= 8;
148 }
149
150 if !settings.use_basic_mode {
151 self.time_series_data
152 .add(&data, used_widgets, settings, filters);
153 }
154
155 if let Some(mut network) = data.network {
156 if settings.network_start_zeroed {
157 let TotalNetworkData {
158 total_rx: starting_total_rx,
159 total_tx: starting_total_tx,
160 } = self.starting_total_network.get_or_insert(TotalNetworkData {
161 total_rx: network.total_rx,
162 total_tx: network.total_tx,
163 });
164
165 network.total_rx = network.total_rx.saturating_sub(*starting_total_rx);
166 network.total_tx = network.total_tx.saturating_sub(*starting_total_tx);
167 }
168 self.network_harvest = network;
169 }
170
171 self.ram_harvest = data.memory;
172 self.swap_harvest = data.swap;
173
174 #[cfg(not(target_os = "windows"))]
175 {
176 self.cache_harvest = data.cache;
177 }
178
179 #[cfg(feature = "zfs")]
180 {
181 self.arc_harvest = data.arc;
182 }
183
184 #[cfg(feature = "gpu")]
185 if let Some(gpu) = data.gpu {
186 self.gpu_harvest = gpu;
187 }
188
189 if let Some(cpu) = data.cpu {
190 self.cpu_harvest = cpu;
191 }
192
193 if let Some(load_avg) = data.load_avg {
194 self.load_avg_harvest = load_avg;
195 }
196
197 self.temp_data = data
198 .temperature_sensors
199 .map(|sensors| {
200 sensors
201 .into_iter()
202 .filter(|temp| Filter::optional_should_keep(&filters.temp_filter, &temp.name))
203 .map(|temp| TempWidgetData {
204 sensor: temp.name,
205 temperature: temp
206 .temperature
207 .map(|c| settings.temperature_type.convert_temp_unit(c)),
208 })
209 .collect()
210 })
211 .unwrap_or_default();
212
213 if let Some(disks) = data.disks
214 && let Some(io) = data.io
215 {
216 self.eat_disks(disks, io, harvested_time);
217
218 if used_widgets.use_disk_io_graph {
219 self.time_series_data.update_disk_io(
220 &self.disk_harvest,
221 &filters.disk_io_graph_filter,
222 settings.disk_io_graph_show_unmounted,
223 );
224 }
225 }
226
227 if let Some(list_of_processes) = data.list_of_processes {
228 self.process_data.ingest(list_of_processes);
229 }
230
231 #[cfg(feature = "battery")]
232 {
233 if let Some(list_of_batteries) = data.list_of_batteries {
234 self.battery_harvest = list_of_batteries;
235 }
236 }
237
238 // And we're done eating. Update time and push the new entry!
239 self.last_update_time = harvested_time;
240 }
241
242 fn eat_disks(&mut self, disks: Vec<DiskHarvest>, io: IoHarvest, harvested_time: Instant) {
243 let time_since_last_harvest = harvested_time
244 .duration_since(self.last_update_time)
245 .as_secs_f64();
246
247 self.disk_harvest.clear();
248
249 for disk in disks {
250 let Some(checked_name) = ({
251 #[cfg(target_os = "windows")]
252 {
253 match &disk.volume_name {
254 Some(volume_name) => Some(volume_name.as_str()),
255 None => disk.name.split('/').next_back(),
256 }
257 }
258 #[cfg(not(target_os = "windows"))]
259 {
260 #[cfg(any(feature = "zfs", target_os = "freebsd"))]
261 {
262 if !disk.name.starts_with('/') {
263 Some(disk.name.as_str()) // use the whole name
264 } else {
265 #[cfg(target_os = "freebsd")]
266 {
267 Some(disk.mount_point.as_str()) // use mount_point for sysinfo
268 }
269 #[cfg(not(target_os = "freebsd"))]
270 {
271 disk.name.split('/').next_back() // use device name
272 }
273 }
274 }
275 #[cfg(not(any(feature = "zfs", target_os = "freebsd")))]
276 {
277 disk.name.split('/').next_back()
278 }
279 }
280 }) else {
281 continue;
282 };
283
284 let io_device = {
285 #[cfg(target_os = "macos")]
286 {
287 use std::sync::OnceLock;
288
289 use regex::Regex;
290
291 // Must trim one level further for macOS!
292 static DISK_REGEX: OnceLock<Regex> = OnceLock::new();
293
294 #[expect(
295 clippy::regex_creation_in_loops,
296 reason = "this is fine since it's done via a static OnceLock. In the future though, separate it out."
297 )]
298 if let Some(new_name) = DISK_REGEX
299 .get_or_init(|| Regex::new(r"disk\d+").expect("valid regex"))
300 .find(checked_name)
301 {
302 io.get(new_name.as_str())
303 } else {
304 None
305 }
306 }
307 #[cfg(not(target_os = "macos"))]
308 {
309 io.get(checked_name)
310 }
311 };
312
313 let (mut io_read_rate_bytes, mut io_write_rate_bytes) = (None, None);
314 if let Some(Some(io_device)) = io_device {
315 if let Some(prev_io) = self
316 .prev_io
317 .get_mut(&(disk.mount_point.as_str(), checked_name) as &dyn PairKey)
318 {
319 io_read_rate_bytes = Some(
320 ((io_device.read_bytes.saturating_sub(prev_io.0)) as f64
321 / time_since_last_harvest)
322 .round() as u64,
323 );
324
325 io_write_rate_bytes = Some(
326 ((io_device.write_bytes.saturating_sub(prev_io.1)) as f64
327 / time_since_last_harvest)
328 .round() as u64,
329 );
330
331 *prev_io = (io_device.read_bytes, io_device.write_bytes);
332 } else {
333 // Skip on first run.
334 io_read_rate_bytes = Some(0);
335 io_write_rate_bytes = Some(0);
336
337 // TODO: We probably want to also add some cleanup after a while if unused.
338 self.prev_io.insert(
339 (disk.mount_point.clone(), checked_name.to_string()),
340 (io_device.read_bytes, io_device.write_bytes),
341 );
342 }
343 }
344
345 let summed_total_bytes = match (disk.used_space, disk.free_space) {
346 (Some(used), Some(free)) => Some(used + free),
347 _ => None,
348 };
349
350 self.disk_harvest.push(DiskWidgetData {
351 name: disk.name,
352 mount_point: disk.mount_point,
353 free_bytes: disk.free_space,
354 used_bytes: disk.used_space,
355 total_bytes: disk.total_space,
356 summed_total_bytes,
357 io_read_rate_bytes,
358 io_write_rate_bytes,
359 });
360 }
361 }
362 }
363
364 /// If we freeze data collection updates, we want to return a "frozen" copy
365 /// of the data at the time, while still updating things in the background.
366 #[derive(Default)]
367 pub enum FrozenState {
368 #[default]
369 NotFrozen,
370 Frozen(Box<InnerData>),
371 }
372
373 /// What data to share to other parts of the application.
374 pub struct DataStore {
375 frozen_state: FrozenState,
376 inner: InnerData,
377 used_widgets: UsedWidgets,
378 filters: DataFilters,
379 }
380
381 impl DataStore {
382 /// Create a new [`DataStore`]
383 pub fn new(used_widgets: UsedWidgets) -> Self {
384 Self {
385 frozen_state: FrozenState::default(),
386 inner: InnerData::default(),
387 used_widgets,
388 filters: DataFilters::default(),
389 }
390 }
391
392 /// Toggle whether the [`DataState`] is frozen or not.
393 pub fn toggle_frozen(&mut self) {
394 match &self.frozen_state {
395 FrozenState::NotFrozen => {
396 self.frozen_state = FrozenState::Frozen(Box::new(self.inner.clone()));
397 }
398 FrozenState::Frozen(_) => self.frozen_state = FrozenState::NotFrozen,
399 }
400 }
401
402 /// Return whether the [`DataState`] is frozen or not.
403 pub fn is_frozen(&self) -> bool {
404 matches!(self.frozen_state, FrozenState::Frozen(_))
405 }
406
407 /// Return a reference to the currently available data. Note that if the
408 /// data is in a frozen state, it will return the snapshot of data from
409 /// when it was frozen.
410 pub fn get_data(&self) -> &InnerData {
411 match &self.frozen_state {
412 FrozenState::NotFrozen => &self.inner,
413 FrozenState::Frozen(collected_data) => collected_data,
414 }
415 }
416
417 pub fn set_filters(&mut self, filters: DataFilters) {
418 self.filters = filters;
419 }
420
421 /// Eat data.
422 pub fn eat_data(&mut self, data: Box<Data>, settings: &AppConfigFields) {
423 self.inner
424 .eat_data(data, settings, &self.used_widgets, &self.filters);
425 }
426
427 /// Clean data.
428 pub fn clean_data(&mut self, max_duration: Duration) {
429 self.inner.time_series_data.prune(max_duration);
430 }
431
432 /// Reset data state.
433 pub fn reset(&mut self) {
434 self.frozen_state = FrozenState::NotFrozen;
435 self.inner = InnerData::default();
436 }
437 }