Skip to main content

paper/daemon/
resource_guard.rs

1//! Resource guard for pausing indexing based on system conditions.
2//!
3//! Pauses when:
4//! - Battery < 20% and discharging (on laptops)
5//! - CPU > 80% sustained over several consecutive checks
6//! - Metered network connection (currently a conservative no-op; there is no
7//!   reliable cross-platform API without extra dependencies)
8//!
9//! CPU usage comes from `sysinfo`. Battery is read directly from the OS:
10//! Linux `/sys/class/power_supply/BAT*`, macOS `pmset -g batt`. Platforms
11//! without battery information simply never pause for low battery.
12
13use std::sync::Arc;
14use std::time::Duration;
15use sysinfo::System;
16use tokio::sync::{mpsc, RwLock};
17use tokio::time::interval;
18
19/// Reason for pausing indexing.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum PauseReason {
22    LowBattery,
23    HighCpu,
24    MeteredNetwork,
25    Resumed,
26}
27
28/// Resource guard configuration.
29#[derive(Debug, Clone)]
30pub struct ResourceGuardConfig {
31    /// Battery percentage threshold (pause below this)
32    pub battery_threshold: u8,
33    /// CPU usage threshold (pause above this)
34    pub cpu_threshold: u8,
35    /// Check interval
36    pub check_interval: Duration,
37    /// Number of consecutive checks above threshold before pausing
38    pub cpu_consecutive_checks: u32,
39}
40
41impl Default for ResourceGuardConfig {
42    fn default() -> Self {
43        Self {
44            battery_threshold: 20,
45            cpu_threshold: 80,
46            check_interval: Duration::from_secs(30),
47            cpu_consecutive_checks: 3,
48        }
49    }
50}
51
52/// Battery state snapshot: percentage (0-100) and whether charging.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54struct BatteryStatus {
55    percent: u8,
56    charging: bool,
57}
58
59/// Read battery status from the OS, if a battery exists.
60fn battery_status() -> Option<BatteryStatus> {
61    #[cfg(target_os = "linux")]
62    {
63        let base = std::path::Path::new("/sys/class/power_supply");
64        let entries = std::fs::read_dir(base).ok()?;
65        for entry in entries.flatten() {
66            let path = entry.path();
67            let is_battery = path
68                .file_name()
69                .map(|n| n.to_string_lossy().starts_with("BAT"))
70                .unwrap_or(false);
71            if !is_battery {
72                continue;
73            }
74            let percent: u8 = std::fs::read_to_string(path.join("capacity"))
75                .ok()?
76                .trim()
77                .parse()
78                .ok()?;
79            let status = std::fs::read_to_string(path.join("status")).unwrap_or_default();
80            let charging = status.trim() == "Charging" || status.trim() == "Full";
81            return Some(BatteryStatus { percent, charging });
82        }
83        None
84    }
85
86    #[cfg(target_os = "macos")]
87    {
88        // `pmset -g batt` output looks like:
89        //  -InternalBattery-0 (id=...)	100%; charged; 0:00 remaining
90        //  -InternalBattery-0 (id=...)	85%; discharging; 4:12 remaining
91        let output = std::process::Command::new("pmset")
92            .args(["-g", "batt"])
93            .output()
94            .ok()?;
95        let text = String::from_utf8_lossy(&output.stdout);
96        for line in text.lines() {
97            let Some(percent_part) = line.split('%').next() else {
98                continue;
99            };
100            let Some(digits) = percent_part
101                .rsplit(|c: char| !c.is_ascii_digit())
102                .find(|s| !s.is_empty())
103            else {
104                continue;
105            };
106            let Ok(percent) = digits.parse::<u8>() else {
107                continue;
108            };
109            let charging = line.contains("charging") && !line.contains("discharging")
110                || line.contains("charged");
111            return Some(BatteryStatus { percent, charging });
112        }
113        None
114    }
115
116    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
117    {
118        None
119    }
120}
121
122/// Resource guard for monitoring system resources.
123pub struct ResourceGuard {
124    /// Configuration (public so callers can tune thresholds before `with_config`).
125    pub config: ResourceGuardConfig,
126    system: Arc<RwLock<System>>,
127    /// Track consecutive high CPU readings
128    high_cpu_count: Arc<RwLock<u32>>,
129    /// Current pause state
130    paused: Arc<RwLock<Option<PauseReason>>>,
131}
132
133impl ResourceGuard {
134    /// Create a new resource guard with default configuration.
135    pub fn new() -> Self {
136        Self::with_config(ResourceGuardConfig::default())
137    }
138
139    /// Create a new resource guard with custom configuration.
140    pub fn with_config(config: ResourceGuardConfig) -> Self {
141        let mut system = System::new();
142        system.refresh_cpu_usage();
143
144        Self {
145            config,
146            system: Arc::new(RwLock::new(system)),
147            high_cpu_count: Arc::new(RwLock::new(0)),
148            paused: Arc::new(RwLock::new(None)),
149        }
150    }
151
152    /// Evaluate the current resource state and update the pause state.
153    ///
154    /// Returns the pause reason if indexing should pause, `None` otherwise.
155    async fn evaluate(&self) -> Option<PauseReason> {
156        // CPU: average across all cores. sysinfo needs two samples over time
157        // for meaningful numbers; the monitoring loop provides that cadence.
158        let cpu_usage = {
159            let mut system = self.system.write().await;
160            system.refresh_cpu_usage();
161            let cpus = system.cpus();
162            if cpus.is_empty() {
163                0.0
164            } else {
165                cpus.iter().map(|c| c.cpu_usage()).sum::<f32>() / cpus.len() as f32
166            }
167        };
168
169        // Battery
170        if let Some(battery) = battery_status() {
171            if battery.percent < self.config.battery_threshold && !battery.charging {
172                *self.paused.write().await = Some(PauseReason::LowBattery);
173                return Some(PauseReason::LowBattery);
174            }
175        }
176
177        // CPU
178        let mut high_cpu_count = self.high_cpu_count.write().await;
179        if cpu_usage > self.config.cpu_threshold as f32 {
180            *high_cpu_count += 1;
181            if *high_cpu_count >= self.config.cpu_consecutive_checks {
182                *self.paused.write().await = Some(PauseReason::HighCpu);
183                return Some(PauseReason::HighCpu);
184            }
185        } else {
186            *high_cpu_count = 0;
187        }
188
189        // Metered network: conservative no-op (see module docs).
190
191        // Conditions are OK: clear any previous pause state.
192        *self.paused.write().await = None;
193        None
194    }
195
196    /// Check if indexing should be paused based on current resource state.
197    pub async fn should_pause(&self) -> bool {
198        self.evaluate().await.is_some()
199    }
200
201    /// Get the current pause reason, if any.
202    pub async fn pause_reason(&self) -> Option<PauseReason> {
203        *self.paused.read().await
204    }
205
206    /// Start monitoring resources and send pause/resume signals.
207    ///
208    /// Runs until the task is aborted. Sends a `PauseReason` whenever the
209    /// pause state changes: the specific reason on pause, `Resumed` on resume.
210    pub fn start_monitoring(&self, sender: mpsc::Sender<PauseReason>) {
211        let config = self.config.clone();
212        let system = self.system.clone();
213        let high_cpu_count = self.high_cpu_count.clone();
214        let paused = self.paused.clone();
215
216        tokio::spawn(async move {
217            let mut timer = interval(config.check_interval);
218            loop {
219                timer.tick().await;
220
221                let cpu_usage = {
222                    let mut system = system.write().await;
223                    system.refresh_cpu_usage();
224                    let cpus = system.cpus();
225                    if cpus.is_empty() {
226                        0.0
227                    } else {
228                        cpus.iter().map(|c| c.cpu_usage()).sum::<f32>() / cpus.len() as f32
229                    }
230                };
231
232                let mut reason = None;
233
234                if let Some(battery) = battery_status() {
235                    if battery.percent < config.battery_threshold && !battery.charging {
236                        reason = Some(PauseReason::LowBattery);
237                    }
238                }
239
240                if reason.is_none() {
241                    let mut count = high_cpu_count.write().await;
242                    if cpu_usage > config.cpu_threshold as f32 {
243                        *count += 1;
244                        if *count >= config.cpu_consecutive_checks {
245                            reason = Some(PauseReason::HighCpu);
246                        }
247                    } else {
248                        *count = 0;
249                    }
250                }
251
252                let mut paused = paused.write().await;
253                match reason {
254                    Some(r) => {
255                        if *paused != Some(r) {
256                            *paused = Some(r);
257                            let _ = sender.send(r).await;
258                        }
259                    }
260                    None => {
261                        if paused.is_some() {
262                            *paused = None;
263                            let _ = sender.send(PauseReason::Resumed).await;
264                        }
265                    }
266                }
267            }
268        });
269    }
270
271    /// Force a resource check and return whether paused.
272    pub async fn check_now(&self) -> bool {
273        self.should_pause().await
274    }
275}
276
277impl Default for ResourceGuard {
278    fn default() -> Self {
279        Self::new()
280    }
281}