Skip to main content

quickgui_system/
metrics.rs

1//! Bounded process and system metrics: CPU time, memory footprint, thread count, and uptime.
2//!
3//! Every reading is a single explicit call; nothing is sampled in the background and no thread is
4//! started. Fields that an operating system does not expose are `None` rather than guessed, and
5//! platforms without an implementation return [`SystemIntegrationError::Unsupported`].
6
7use std::time::Duration;
8
9use crate::Result;
10
11/// Maximum accepted CPU-sampler interval; longer gaps are reported without a percentage.
12pub const MAX_CPU_SAMPLE_INTERVAL: Duration = Duration::from_secs(24 * 60 * 60);
13
14/// One immutable snapshot of the current process.
15#[derive(Clone, Copy, Debug, Default, PartialEq)]
16pub struct ProcessMetrics {
17    /// Accumulated user-mode CPU time.
18    pub cpu_user: Duration,
19    /// Accumulated kernel-mode CPU time.
20    pub cpu_system: Duration,
21    /// Resident set size in bytes.
22    pub resident_bytes: u64,
23    /// macOS `phys_footprint`: the memory the system charges to this process. `None` elsewhere.
24    pub footprint_bytes: Option<u64>,
25    /// Reserved virtual address space in bytes.
26    pub virtual_bytes: u64,
27    /// Live threads, when the platform exposes an inexpensive count.
28    pub thread_count: Option<u32>,
29    /// Time since the process started.
30    pub uptime: Duration,
31}
32
33impl ProcessMetrics {
34    /// Read the current process's metrics.
35    pub fn current() -> Result<Self> {
36        platform::process_metrics()
37    }
38
39    /// Total CPU time charged to the process.
40    pub fn cpu_total(&self) -> Duration {
41        self.cpu_user.saturating_add(self.cpu_system)
42    }
43}
44
45/// Whole-system physical memory, in bytes.
46#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
47pub struct SystemMemory {
48    pub total_bytes: u64,
49    /// Memory available to new allocations without swapping.
50    pub available_bytes: u64,
51    /// Completely unused memory.
52    pub free_bytes: u64,
53    /// `total_bytes - available_bytes`.
54    pub used_bytes: u64,
55}
56
57impl SystemMemory {
58    /// Read whole-system physical memory.
59    pub fn current() -> Result<Self> {
60        platform::system_memory()
61    }
62}
63
64/// One CPU-usage reading produced by [`CpuUsageSampler::sample`].
65#[derive(Clone, Copy, Debug, Default, PartialEq)]
66pub struct CpuUsage {
67    /// Percent of one core consumed since the previous sample. `None` for the first sample.
68    pub percent: Option<f64>,
69    /// Wall-clock time covered by this sample.
70    pub interval: Duration,
71    /// CPU time consumed during `interval`.
72    pub cpu_time: Duration,
73    /// Total CPU time charged to the process so far.
74    pub total_cpu_time: Duration,
75}
76
77/// Stateful sampler that converts cumulative CPU time into a per-interval percentage.
78///
79/// The sampler stores exactly one previous reading; it never allocates and never polls in the
80/// background. The caller decides how often to sample.
81#[derive(Clone, Copy, Debug, Default)]
82pub struct CpuUsageSampler {
83    previous: Option<(std::time::Instant, Duration)>,
84}
85
86impl CpuUsageSampler {
87    pub fn new() -> Self {
88        Self::default()
89    }
90
91    /// Read process CPU time and report usage since the previous call.
92    pub fn sample(&mut self) -> Result<CpuUsage> {
93        let metrics = ProcessMetrics::current()?;
94        let now = std::time::Instant::now();
95        let total = metrics.cpu_total();
96        let usage = match self.previous {
97            Some((instant, previous_total)) => {
98                let interval = now.saturating_duration_since(instant);
99                let cpu_time = total.saturating_sub(previous_total);
100                CpuUsage {
101                    percent: cpu_usage_percent(cpu_time, interval),
102                    interval,
103                    cpu_time,
104                    total_cpu_time: total,
105                }
106            }
107            None => CpuUsage {
108                percent: None,
109                interval: Duration::ZERO,
110                cpu_time: Duration::ZERO,
111                total_cpu_time: total,
112            },
113        };
114        self.previous = Some((now, total));
115        Ok(usage)
116    }
117}
118
119/// Percent of one core, or `None` when the interval is empty or implausibly long.
120fn cpu_usage_percent(cpu_time: Duration, interval: Duration) -> Option<f64> {
121    if interval.is_zero() || interval > MAX_CPU_SAMPLE_INTERVAL {
122        return None;
123    }
124    Some((cpu_time.as_secs_f64() / interval.as_secs_f64()) * 100.0)
125}
126
127#[cfg(target_os = "macos")]
128mod platform {
129    use super::{ProcessMetrics, SystemMemory};
130    use crate::{Result, SystemIntegrationError};
131    use std::{
132        sync::Arc,
133        time::{Duration, SystemTime, UNIX_EPOCH},
134    };
135
136    pub(super) fn process_metrics() -> Result<ProcessMetrics> {
137        // SAFETY: `proc_pidinfo` writes at most `size` bytes into the zeroed structure and
138        // reports how many it wrote.
139        let (info, written) = unsafe {
140            let mut info: libc::proc_taskallinfo = std::mem::zeroed();
141            let size = size_of::<libc::proc_taskallinfo>() as libc::c_int;
142            let written = libc::proc_pidinfo(
143                std::process::id() as libc::c_int,
144                libc::PROC_PIDTASKALLINFO,
145                0,
146                std::ptr::from_mut(&mut info).cast(),
147                size,
148            );
149            (info, written)
150        };
151        if written < size_of::<libc::proc_taskallinfo>() as libc::c_int {
152            return Err(platform_error("proc_pidinfo(PROC_PIDTASKALLINFO) failed"));
153        }
154        let started = Duration::from_secs(info.pbsd.pbi_start_tvsec)
155            + Duration::from_micros(info.pbsd.pbi_start_tvusec);
156        let now = SystemTime::now()
157            .duration_since(UNIX_EPOCH)
158            .unwrap_or_default();
159        Ok(ProcessMetrics {
160            cpu_user: Duration::from_nanos(info.ptinfo.pti_total_user),
161            cpu_system: Duration::from_nanos(info.ptinfo.pti_total_system),
162            resident_bytes: info.ptinfo.pti_resident_size,
163            footprint_bytes: physical_footprint(),
164            virtual_bytes: info.ptinfo.pti_virtual_size,
165            thread_count: u32::try_from(info.ptinfo.pti_threadnum).ok(),
166            uptime: now.saturating_sub(started),
167        })
168    }
169
170    fn physical_footprint() -> Option<u64> {
171        // SAFETY: `proc_pid_rusage` fills the zeroed flavor-2 structure it is handed.
172        unsafe {
173            let mut usage: libc::rusage_info_v2 = std::mem::zeroed();
174            let status = libc::proc_pid_rusage(
175                std::process::id() as libc::c_int,
176                libc::RUSAGE_INFO_V2,
177                std::ptr::from_mut(&mut usage).cast(),
178            );
179            (status == 0).then_some(usage.ri_phys_footprint)
180        }
181    }
182
183    // `libc` deprecates its Mach re-exports in favour of the `mach2` crate. QuickGUI does not add
184    // that dependency for one host statistics call, so the deprecated path is used deliberately.
185    #[allow(deprecated)]
186    pub(super) fn system_memory() -> Result<SystemMemory> {
187        let total = physical_memory()?;
188        // SAFETY: the call fills `statistics` with exactly `count` 32-bit words.
189        let (statistics, status) = unsafe {
190            let mut statistics: libc::vm_statistics64 = std::mem::zeroed();
191            let mut count = libc::HOST_VM_INFO64_COUNT;
192            let status = libc::host_statistics64(
193                libc::mach_host_self(),
194                libc::HOST_VM_INFO64,
195                std::ptr::from_mut(&mut statistics).cast(),
196                &raw mut count,
197            );
198            (statistics, status)
199        };
200        if status != 0 {
201            return Err(platform_error("host_statistics64(HOST_VM_INFO64) failed"));
202        }
203        // SAFETY: `sysconf` reads a static system value.
204        let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) }.max(4096) as u64;
205        let free = u64::from(statistics.free_count) * page;
206        let inactive = u64::from(statistics.inactive_count) * page;
207        let purgeable = u64::from(statistics.purgeable_count) * page;
208        let speculative = u64::from(statistics.speculative_count) * page;
209        let available = free
210            .saturating_add(inactive)
211            .saturating_add(purgeable)
212            .saturating_sub(speculative)
213            .min(total);
214        Ok(SystemMemory {
215            total_bytes: total,
216            available_bytes: available,
217            free_bytes: free.min(total),
218            used_bytes: total.saturating_sub(available),
219        })
220    }
221
222    fn physical_memory() -> Result<u64> {
223        let mut value = 0_u64;
224        let mut length = size_of::<u64>();
225        // SAFETY: the name is a NUL-terminated literal and the output buffer matches `length`.
226        let status = unsafe {
227            libc::sysctlbyname(
228                c"hw.memsize".as_ptr(),
229                std::ptr::from_mut(&mut value).cast(),
230                &raw mut length,
231                std::ptr::null_mut(),
232                0,
233            )
234        };
235        if status != 0 || value == 0 {
236            return Err(platform_error("sysctlbyname(hw.memsize) failed"));
237        }
238        Ok(value)
239    }
240
241    fn platform_error(message: &str) -> SystemIntegrationError {
242        SystemIntegrationError::Platform(Arc::from(message))
243    }
244}
245
246#[cfg(target_os = "linux")]
247mod platform {
248    use super::{ProcessMetrics, SystemMemory, parse_proc_meminfo, parse_proc_self_stat};
249    use crate::{Result, SystemIntegrationError};
250    use std::{sync::Arc, time::Duration};
251
252    pub(super) fn process_metrics() -> Result<ProcessMetrics> {
253        let stat = std::fs::read_to_string("/proc/self/stat").map_err(io_error)?;
254        let uptime = std::fs::read_to_string("/proc/uptime").map_err(io_error)?;
255        // SAFETY: `sysconf` reads a static system value.
256        let ticks = unsafe { libc::sysconf(libc::_SC_CLK_TCK) }.max(1) as u64;
257        // SAFETY: `sysconf` reads a static system value.
258        let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) }.max(4096) as u64;
259        let parsed = parse_proc_self_stat(&stat, ticks, page)
260            .ok_or_else(|| platform_error("could not parse /proc/self/stat"))?;
261        let system_uptime = uptime
262            .split_whitespace()
263            .next()
264            .and_then(|value| value.parse::<f64>().ok())
265            .unwrap_or_default();
266        Ok(ProcessMetrics {
267            uptime: Duration::from_secs_f64(
268                (system_uptime - parsed.started_seconds).clamp(0.0, f64::from(u32::MAX)),
269            ),
270            ..parsed.metrics
271        })
272    }
273
274    pub(super) fn system_memory() -> Result<SystemMemory> {
275        let text = std::fs::read_to_string("/proc/meminfo").map_err(io_error)?;
276        parse_proc_meminfo(&text).ok_or_else(|| platform_error("could not parse /proc/meminfo"))
277    }
278
279    fn io_error(error: std::io::Error) -> SystemIntegrationError {
280        SystemIntegrationError::Platform(Arc::from(error.to_string()))
281    }
282
283    fn platform_error(message: &str) -> SystemIntegrationError {
284        SystemIntegrationError::Platform(Arc::from(message))
285    }
286}
287
288#[cfg(windows)]
289mod platform {
290    use super::{ProcessMetrics, SystemMemory};
291    use crate::{Result, SystemIntegrationError};
292    use std::{sync::Arc, time::Duration};
293    use windows_sys::Win32::{
294        Foundation::FILETIME,
295        System::{
296            ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS},
297            SystemInformation::{GetSystemTimeAsFileTime, GlobalMemoryStatusEx, MEMORYSTATUSEX},
298            Threading::{GetCurrentProcess, GetProcessTimes},
299        },
300    };
301
302    fn duration_from_filetime(time: FILETIME) -> Duration {
303        let ticks = (u64::from(time.dwHighDateTime) << 32) | u64::from(time.dwLowDateTime);
304        Duration::from_nanos(ticks.saturating_mul(100))
305    }
306
307    pub(super) fn process_metrics() -> Result<ProcessMetrics> {
308        // SAFETY: every output structure is zeroed before the call and sized exactly.
309        unsafe {
310            let process = GetCurrentProcess();
311            let mut creation: FILETIME = std::mem::zeroed();
312            let mut exit: FILETIME = std::mem::zeroed();
313            let mut kernel: FILETIME = std::mem::zeroed();
314            let mut user: FILETIME = std::mem::zeroed();
315            if GetProcessTimes(
316                process,
317                &raw mut creation,
318                &raw mut exit,
319                &raw mut kernel,
320                &raw mut user,
321            ) == 0
322            {
323                return Err(platform_error("GetProcessTimes failed"));
324            }
325            let mut counters: PROCESS_MEMORY_COUNTERS = std::mem::zeroed();
326            counters.cb = size_of::<PROCESS_MEMORY_COUNTERS>() as u32;
327            if K32GetProcessMemoryInfo(process, &raw mut counters, counters.cb) == 0 {
328                return Err(platform_error("GetProcessMemoryInfo failed"));
329            }
330            let mut now: FILETIME = std::mem::zeroed();
331            GetSystemTimeAsFileTime(&raw mut now);
332            Ok(ProcessMetrics {
333                cpu_user: duration_from_filetime(user),
334                cpu_system: duration_from_filetime(kernel),
335                resident_bytes: counters.WorkingSetSize as u64,
336                footprint_bytes: None,
337                virtual_bytes: counters.PagefileUsage as u64,
338                thread_count: None,
339                uptime: duration_from_filetime(now)
340                    .saturating_sub(duration_from_filetime(creation)),
341            })
342        }
343    }
344
345    pub(super) fn system_memory() -> Result<SystemMemory> {
346        // SAFETY: the structure is zeroed and its `dwLength` set before the call.
347        unsafe {
348            let mut status: MEMORYSTATUSEX = std::mem::zeroed();
349            status.dwLength = size_of::<MEMORYSTATUSEX>() as u32;
350            if GlobalMemoryStatusEx(&raw mut status) == 0 {
351                return Err(platform_error("GlobalMemoryStatusEx failed"));
352            }
353            Ok(SystemMemory {
354                total_bytes: status.ullTotalPhys,
355                available_bytes: status.ullAvailPhys,
356                free_bytes: status.ullAvailPhys,
357                used_bytes: status.ullTotalPhys.saturating_sub(status.ullAvailPhys),
358            })
359        }
360    }
361
362    fn platform_error(message: &str) -> SystemIntegrationError {
363        SystemIntegrationError::Platform(Arc::from(message))
364    }
365}
366
367#[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
368mod platform {
369    use super::{ProcessMetrics, SystemMemory};
370    use crate::{Result, SystemIntegrationError};
371
372    pub(super) fn process_metrics() -> Result<ProcessMetrics> {
373        Err(SystemIntegrationError::Unsupported)
374    }
375
376    pub(super) fn system_memory() -> Result<SystemMemory> {
377        Err(SystemIntegrationError::Unsupported)
378    }
379}
380
381/// Parsed `/proc/self/stat` fields, kept separate so tests can feed fixture text on any host.
382#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
383#[derive(Clone, Copy, Debug, PartialEq)]
384struct ProcSelfStat {
385    metrics: ProcessMetrics,
386    started_seconds: f64,
387}
388
389/// Parse the fields QuickGUI needs from `/proc/self/stat`.
390///
391/// The executable name in field 2 may contain spaces and parentheses, so parsing resumes after
392/// the final `)`.
393#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
394fn parse_proc_self_stat(
395    text: &str,
396    ticks_per_second: u64,
397    page_bytes: u64,
398) -> Option<ProcSelfStat> {
399    let tail = text.rsplit_once(')')?.1;
400    let fields: Vec<&str> = tail.split_whitespace().collect();
401    // `fields[0]` is field 3 (state); field N of the manual page is `fields[N - 3]`.
402    let field = |index: usize| -> Option<u64> { fields.get(index - 3)?.parse::<u64>().ok() };
403    let user = field(14)?;
404    let system = field(15)?;
405    let threads = field(20)?;
406    let started = field(22)?;
407    let virtual_bytes = field(23)?;
408    let resident_pages = field(24)?;
409    let ticks = ticks_per_second.max(1);
410    Some(ProcSelfStat {
411        metrics: ProcessMetrics {
412            cpu_user: Duration::from_secs_f64(user as f64 / ticks as f64),
413            cpu_system: Duration::from_secs_f64(system as f64 / ticks as f64),
414            resident_bytes: resident_pages.saturating_mul(page_bytes),
415            footprint_bytes: None,
416            virtual_bytes,
417            thread_count: u32::try_from(threads).ok(),
418            uptime: Duration::ZERO,
419        },
420        started_seconds: started as f64 / ticks as f64,
421    })
422}
423
424/// Parse `MemTotal`, `MemAvailable`, and `MemFree` from `/proc/meminfo`.
425#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
426fn parse_proc_meminfo(text: &str) -> Option<SystemMemory> {
427    let mut total = None;
428    let mut available = None;
429    let mut free = None;
430    for line in text.lines().take(256) {
431        let (key, rest) = line.split_once(':')?;
432        let value = rest
433            .split_whitespace()
434            .next()
435            .and_then(|value| value.parse::<u64>().ok());
436        match key {
437            "MemTotal" => total = value,
438            "MemAvailable" => available = value,
439            "MemFree" => free = value,
440            _ => {}
441        }
442        if total.is_some() && available.is_some() && free.is_some() {
443            break;
444        }
445    }
446    let total = total?.saturating_mul(1024);
447    let free = free.unwrap_or_default().saturating_mul(1024);
448    let available = available
449        .map_or(free, |value| value.saturating_mul(1024))
450        .min(total);
451    Some(SystemMemory {
452        total_bytes: total,
453        available_bytes: available,
454        free_bytes: free.min(total),
455        used_bytes: total.saturating_sub(available),
456    })
457}
458
459#[cfg(test)]
460mod tests {
461    use super::*;
462
463    /// A real `/proc/self/stat` line, including a command name with a space and parentheses.
464    const PROC_SELF_STAT: &str = "42 (my app (1)) R 1 42 42 0 -1 4194560 1234 0 0 0 250 125 0 0 20 0 7 0 900 104857600 512 18446744073709551615 1 1 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0\n";
465
466    const PROC_MEMINFO: &str = "MemTotal:       16316360 kB\nMemFree:          210268 kB\nMemAvailable:    8127384 kB\nBuffers:          123456 kB\n";
467
468    #[test]
469    fn parses_proc_self_stat_with_a_spaced_command_name() {
470        let parsed = parse_proc_self_stat(PROC_SELF_STAT, 100, 4096).unwrap();
471        assert_eq!(parsed.metrics.cpu_user, Duration::from_millis(2_500));
472        assert_eq!(parsed.metrics.cpu_system, Duration::from_millis(1_250));
473        assert_eq!(parsed.metrics.thread_count, Some(7));
474        assert_eq!(parsed.metrics.virtual_bytes, 104_857_600);
475        assert_eq!(parsed.metrics.resident_bytes, 512 * 4096);
476        assert_eq!(parsed.started_seconds, 9.0);
477    }
478
479    #[test]
480    fn rejects_truncated_proc_self_stat() {
481        assert!(parse_proc_self_stat("42 (app) R 1 2 3", 100, 4096).is_none());
482        assert!(parse_proc_self_stat("no-parenthesis", 100, 4096).is_none());
483    }
484
485    #[test]
486    fn parses_proc_meminfo_kilobyte_values() {
487        let memory = parse_proc_meminfo(PROC_MEMINFO).unwrap();
488        assert_eq!(memory.total_bytes, 16_316_360 * 1024);
489        assert_eq!(memory.available_bytes, 8_127_384 * 1024);
490        assert_eq!(memory.free_bytes, 210_268 * 1024);
491        assert_eq!(
492            memory.used_bytes,
493            memory.total_bytes - memory.available_bytes
494        );
495    }
496
497    #[test]
498    fn falls_back_to_free_memory_without_a_mem_available_line() {
499        let memory = parse_proc_meminfo("MemTotal: 1024 kB\nMemFree: 256 kB\n").unwrap();
500        assert_eq!(memory.available_bytes, 256 * 1024);
501        assert_eq!(memory.used_bytes, 768 * 1024);
502    }
503
504    #[test]
505    fn converts_cpu_time_into_a_percentage_of_one_core() {
506        assert_eq!(
507            cpu_usage_percent(Duration::from_millis(500), Duration::from_secs(1)),
508            Some(50.0)
509        );
510        assert_eq!(
511            cpu_usage_percent(Duration::from_millis(1), Duration::ZERO),
512            None
513        );
514        assert_eq!(
515            cpu_usage_percent(
516                Duration::from_secs(1),
517                MAX_CPU_SAMPLE_INTERVAL + Duration::from_secs(1)
518            ),
519            None
520        );
521    }
522
523    #[cfg(any(target_os = "macos", target_os = "linux", windows))]
524    #[test]
525    fn reads_monotonically_sane_host_metrics() {
526        let first = ProcessMetrics::current().unwrap();
527        assert!(first.resident_bytes > 0);
528        assert!(first.virtual_bytes >= first.resident_bytes);
529        let mut sampler = CpuUsageSampler::new();
530        let initial = sampler.sample().unwrap();
531        assert!(initial.percent.is_none());
532        let mut sink = 0_u64;
533        for value in 0..2_000_000_u64 {
534            sink = sink.wrapping_add(value);
535        }
536        assert!(sink > 0);
537        let second = sampler.sample().unwrap();
538        assert!(second.percent.is_some_and(|percent| percent >= 0.0));
539        assert!(second.total_cpu_time >= initial.total_cpu_time);
540
541        let later = ProcessMetrics::current().unwrap();
542        assert!(later.cpu_total() >= first.cpu_total());
543        assert!(later.uptime >= first.uptime);
544    }
545
546    #[cfg(any(target_os = "macos", target_os = "linux", windows))]
547    #[test]
548    fn reads_plausible_system_memory() {
549        let memory = SystemMemory::current().unwrap();
550        assert!(memory.total_bytes > 64 * 1024 * 1024);
551        assert!(memory.available_bytes <= memory.total_bytes);
552        assert_eq!(
553            memory.used_bytes,
554            memory.total_bytes - memory.available_bytes
555        );
556    }
557
558    #[cfg(target_os = "macos")]
559    #[test]
560    fn reports_a_macos_physical_footprint() {
561        let metrics = ProcessMetrics::current().unwrap();
562        assert!(metrics.footprint_bytes.is_some_and(|bytes| bytes > 0));
563        assert!(metrics.thread_count.is_some_and(|count| count >= 1));
564    }
565}