ailloli_ui_bench/process.rs
1//! Out-of-band operating-system process resource sampling.
2//!
3//! Linux reads procfs without entering the measured UI frame path. Other
4//! platforms return a typed unsupported result rather than fabricating values.
5
6use std::io;
7
8use thiserror::Error;
9
10/// One out-of-band sample of a benchmark process.
11///
12/// Sampling is deliberately independent from UI build/layout/paint so process
13/// inspection cannot become part of the measured frame path.
14///
15/// Byte counters are exact values parsed from procfs KiB fields. MiB accessors
16/// use binary units (`1 MiB = 1_048_576 bytes`).
17///
18/// # Examples
19///
20/// ```no_run
21/// use ailloli_ui_bench::sample_current_process;
22/// let snapshot = sample_current_process()?;
23/// assert!(snapshot.threads() >= 1);
24/// # Ok::<(), ailloli_ui_bench::ProcessSampleError>(())
25/// ```
26#[non_exhaustive]
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub struct ProcessResourceSnapshot {
29 /// Resident set size in bytes sampled from the current process.
30 rss_bytes: u64,
31 /// Proportional set size in bytes, or the platform fallback value.
32 pss_bytes: u64,
33 /// Number of process threads observed at sampling time.
34 threads: usize,
35 /// Number of open file descriptors or platform handles observed.
36 file_descriptors: usize,
37}
38
39impl ProcessResourceSnapshot {
40 /// Returns resident set size in bytes.
41 ///
42 /// # Examples
43 ///
44 /// ```no_run
45 /// let bytes = ailloli_ui_bench::sample_current_process()?.rss_bytes();
46 /// assert!(bytes > 0);
47 /// # Ok::<(), ailloli_ui_bench::ProcessSampleError>(())
48 /// ```
49 pub const fn rss_bytes(self) -> u64 {
50 self.rss_bytes
51 }
52
53 /// Returns proportional set size in bytes.
54 ///
55 /// # Examples
56 ///
57 /// ```no_run
58 /// let bytes = ailloli_ui_bench::sample_current_process()?.pss_bytes();
59 /// assert!(bytes > 0);
60 /// # Ok::<(), ailloli_ui_bench::ProcessSampleError>(())
61 /// ```
62 pub const fn pss_bytes(self) -> u64 {
63 self.pss_bytes
64 }
65
66 /// Returns the operating-system thread count.
67 ///
68 /// # Examples
69 ///
70 /// ```no_run
71 /// let count = ailloli_ui_bench::sample_current_process()?.threads();
72 /// assert!(count >= 1);
73 /// # Ok::<(), ailloli_ui_bench::ProcessSampleError>(())
74 /// ```
75 pub const fn threads(self) -> usize {
76 self.threads
77 }
78
79 /// Returns the number of open file descriptors.
80 ///
81 /// On Linux this includes descriptors briefly opened while enumerating
82 /// `/proc/<pid>/fd`.
83 ///
84 /// # Examples
85 ///
86 /// ```no_run
87 /// let count = ailloli_ui_bench::sample_current_process()?.file_descriptors();
88 /// let _ = count;
89 /// # Ok::<(), ailloli_ui_bench::ProcessSampleError>(())
90 /// ```
91 pub const fn file_descriptors(self) -> usize {
92 self.file_descriptors
93 }
94
95 /// Returns RSS in binary mebibytes.
96 ///
97 /// # Examples
98 ///
99 /// ```no_run
100 /// let mib = ailloli_ui_bench::sample_current_process()?.rss_mib();
101 /// assert!(mib > 0.0);
102 /// # Ok::<(), ailloli_ui_bench::ProcessSampleError>(())
103 /// ```
104 pub fn rss_mib(self) -> f64 {
105 self.rss_bytes as f64 / (1024.0 * 1024.0)
106 }
107
108 /// Returns PSS in binary mebibytes.
109 ///
110 /// # Examples
111 ///
112 /// ```no_run
113 /// let mib = ailloli_ui_bench::sample_current_process()?.pss_mib();
114 /// assert!(mib > 0.0);
115 /// # Ok::<(), ailloli_ui_bench::ProcessSampleError>(())
116 /// ```
117 pub fn pss_mib(self) -> f64 {
118 self.pss_bytes as f64 / (1024.0 * 1024.0)
119 }
120}
121
122#[non_exhaustive]
123#[derive(Debug, Error)]
124/// Failure to obtain an exact process-resource snapshot.
125///
126/// # Examples
127///
128/// ```
129/// use ailloli_ui_bench::ProcessSampleError;
130/// let error = ProcessSampleError::UnsupportedPlatform { platform: "example" };
131/// assert!(error.to_string().contains("example"));
132/// ```
133pub enum ProcessSampleError {
134 #[error("process resource sampling is unsupported on {platform}")]
135 /// The current platform has no implemented sampler.
136 UnsupportedPlatform {
137 /// `std::env::consts::OS`-style platform identifier.
138 platform: &'static str,
139 },
140 #[error("failed to read {path}: {source}")]
141 /// A required procfs file or directory could not be read.
142 Read {
143 /// Procfs path that failed.
144 path: String,
145 /// Underlying I/O error.
146 source: io::Error,
147 },
148 #[error("missing or invalid {field} in {path}")]
149 /// A required procfs field was absent, malformed, or overflowed bytes.
150 InvalidField {
151 /// Procfs file containing the field.
152 path: String,
153 /// Expected field name without its colon.
154 field: &'static str,
155 },
156}
157
158/// Samples the current process from the operating system's process interface.
159///
160/// # Errors
161///
162/// Propagates [`sample_process`] errors for the current process ID.
163///
164/// # Examples
165///
166/// ```no_run
167/// let snapshot = ailloli_ui_bench::sample_current_process()?;
168/// assert!(snapshot.rss_bytes() > 0);
169/// # Ok::<(), ailloli_ui_bench::ProcessSampleError>(())
170/// ```
171pub fn sample_current_process() -> Result<ProcessResourceSnapshot, ProcessSampleError> {
172 sample_process(std::process::id())
173}
174
175/// Samples RSS, proportional set size, threads, and open descriptors.
176///
177/// Linux uses `/proc/<pid>/smaps_rollup`, `/proc/<pid>/status`, and
178/// `/proc/<pid>/fd`. Other platforms return a typed unsupported error and are
179/// reported as named benchmark skips.
180///
181/// # Errors
182///
183/// On Linux, returns [`ProcessSampleError::Read`] for inaccessible procfs state
184/// and [`ProcessSampleError::InvalidField`] for missing, malformed, or
185/// byte-overflowing fields. Other platforms return `UnsupportedPlatform`.
186///
187/// # Examples
188///
189/// ```no_run
190/// let snapshot = ailloli_ui_bench::sample_process(std::process::id())?;
191/// assert!(snapshot.threads() >= 1);
192/// # Ok::<(), ailloli_ui_bench::ProcessSampleError>(())
193/// ```
194#[cfg(target_os = "linux")]
195pub fn sample_process(pid: u32) -> Result<ProcessResourceSnapshot, ProcessSampleError> {
196 use std::fs;
197
198 let root = format!("/proc/{pid}");
199 let smaps_path = format!("{root}/smaps_rollup");
200 let status_path = format!("{root}/status");
201 let fd_path = format!("{root}/fd");
202 let smaps = fs::read_to_string(&smaps_path).map_err(|source| ProcessSampleError::Read {
203 path: smaps_path.clone(),
204 source,
205 })?;
206 let status = fs::read_to_string(&status_path).map_err(|source| ProcessSampleError::Read {
207 path: status_path.clone(),
208 source,
209 })?;
210 let rss_bytes = parse_kib_field(&smaps, "Rss:").ok_or(ProcessSampleError::InvalidField {
211 path: smaps_path.clone(),
212 field: "Rss",
213 })?;
214 let pss_bytes = parse_kib_field(&smaps, "Pss:").ok_or(ProcessSampleError::InvalidField {
215 path: smaps_path,
216 field: "Pss",
217 })?;
218 let threads =
219 parse_count_field(&status, "Threads:").ok_or(ProcessSampleError::InvalidField {
220 path: status_path,
221 field: "Threads",
222 })?;
223 let file_descriptors = fs::read_dir(&fd_path)
224 .map_err(|source| ProcessSampleError::Read {
225 path: fd_path.clone(),
226 source,
227 })?
228 .try_fold(0_usize, |count, entry| {
229 entry.map(|_| count.saturating_add(1))
230 })
231 .map_err(|source| ProcessSampleError::Read {
232 path: fd_path,
233 source,
234 })?;
235
236 Ok(ProcessResourceSnapshot {
237 rss_bytes,
238 pss_bytes,
239 threads,
240 file_descriptors,
241 })
242}
243
244#[cfg(not(target_os = "linux"))]
245/// Returns an explicit unsupported-platform result outside Linux.
246///
247/// # Errors
248///
249/// Always returns [`ProcessSampleError::UnsupportedPlatform`].
250///
251/// # Examples
252///
253/// ```no_run
254/// let result = ailloli_ui_bench::sample_process(std::process::id());
255/// assert!(result.is_err());
256/// ```
257pub fn sample_process(_pid: u32) -> Result<ProcessResourceSnapshot, ProcessSampleError> {
258 Err(ProcessSampleError::UnsupportedPlatform {
259 platform: std::env::consts::OS,
260 })
261}
262
263#[cfg(target_os = "linux")]
264/// Parses a named procfs KiB field and converts it to bytes with checked math.
265fn parse_kib_field(contents: &str, field: &str) -> Option<u64> {
266 contents.lines().find_map(|line| {
267 let rest = line.strip_prefix(field)?.trim();
268 let value = rest.split_ascii_whitespace().next()?.parse::<u64>().ok()?;
269 value.checked_mul(1024)
270 })
271}
272
273#[cfg(target_os = "linux")]
274/// Parses a named procfs integer-count field.
275fn parse_count_field(contents: &str, field: &str) -> Option<usize> {
276 contents
277 .lines()
278 .find_map(|line| line.strip_prefix(field)?.trim().parse().ok())
279}
280
281#[cfg(test)]
282/// Verifies Linux unit conversion and live current-process observability.
283mod tests {
284 use super::*;
285
286 #[cfg(target_os = "linux")]
287 #[test]
288 fn parses_linux_process_fields_without_unit_ambiguity() {
289 let smaps = "00400000-00452000 r-xp 00000000 00:00 0\nRss: 2048 kB\nPss: 1536 kB\n";
290 assert_eq!(parse_kib_field(smaps, "Rss:"), Some(2 * 1024 * 1024));
291 assert_eq!(parse_kib_field(smaps, "Pss:"), Some(1536 * 1024));
292 assert_eq!(
293 parse_count_field("Name:\ttest\nThreads:\t7\n", "Threads:"),
294 Some(7)
295 );
296 }
297
298 #[cfg(target_os = "linux")]
299 #[test]
300 fn current_linux_process_is_observable() {
301 let sample = sample_current_process().unwrap();
302 assert!(sample.rss_bytes() > 0);
303 assert!(sample.pss_bytes() > 0);
304 assert!(sample.threads() >= 1);
305 assert!(sample.file_descriptors() >= 3);
306 }
307}