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. On Linux this returns every `BAT*`
60/// entry (multi-battery laptops), not just the first one (IM).
61fn battery_statuses() -> Option<Vec<BatteryStatus>> {
62    #[cfg(target_os = "linux")]
63    {
64        let base = std::path::Path::new("/sys/class/power_supply");
65        let entries = std::fs::read_dir(base).ok()?;
66        let mut batteries = Vec::new();
67        for entry in entries.flatten() {
68            let path = entry.path();
69            let is_battery = path
70                .file_name()
71                .map(|n| n.to_string_lossy().starts_with("BAT"))
72                .unwrap_or(false);
73            if !is_battery {
74                continue;
75            }
76            let Ok(contents) = std::fs::read_to_string(path.join("capacity")) else {
77                continue;
78            };
79            let Ok(percent) = contents.trim().parse() else {
80                continue;
81            };
82            let status = std::fs::read_to_string(path.join("status")).unwrap_or_default();
83            let charging = status.trim() == "Charging" || status.trim() == "Full";
84            batteries.push(BatteryStatus { percent, charging });
85        }
86        (!batteries.is_empty()).then_some(batteries)
87    }
88
89    #[cfg(target_os = "macos")]
90    {
91        // `pmset -g batt` output looks like:
92        //  -InternalBattery-0 (id=...)	100%; charged; 0:00 remaining
93        //  -InternalBattery-0 (id=...)	85%; discharging; 4:12 remaining
94        let output = std::process::Command::new("pmset")
95            .args(["-g", "batt"])
96            .output()
97            .ok()?;
98        let text = String::from_utf8_lossy(&output.stdout);
99        let mut batteries = Vec::new();
100        for line in text.lines() {
101            let Some(percent_part) = line.split('%').next() else {
102                continue;
103            };
104            let Some(digits) = percent_part
105                .rsplit(|c: char| !c.is_ascii_digit())
106                .find(|s| !s.is_empty())
107            else {
108                continue;
109            };
110            let Ok(percent) = digits.parse::<u8>() else {
111                continue;
112            };
113            let charging = line.contains("charging") && !line.contains("discharging")
114                || line.contains("charged");
115            batteries.push(BatteryStatus { percent, charging });
116        }
117        (!batteries.is_empty()).then_some(batteries)
118    }
119
120    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
121    {
122        None
123    }
124}
125
126/// Whether any battery is below `threshold` and discharging. Multi-battery
127/// safe: pauses if *any* battery is low and not charging (IM).
128fn any_battery_low(batteries: &[BatteryStatus], threshold: u8) -> bool {
129    batteries
130        .iter()
131        .any(|b| b.percent < threshold && !b.charging)
132}
133
134/// Resource guard for monitoring system resources.
135pub struct ResourceGuard {
136    /// Configuration (public so callers can tune thresholds before `with_config`).
137    pub config: ResourceGuardConfig,
138    system: Arc<RwLock<System>>,
139    /// Track consecutive high CPU readings
140    high_cpu_count: Arc<RwLock<u32>>,
141    /// Current pause state
142    paused: Arc<RwLock<Option<PauseReason>>>,
143}
144
145impl ResourceGuard {
146    /// Create a new resource guard with default configuration.
147    pub fn new() -> Self {
148        Self::with_config(ResourceGuardConfig::default())
149    }
150
151    /// Create a new resource guard with custom configuration.
152    pub fn with_config(config: ResourceGuardConfig) -> Self {
153        let mut system = System::new();
154        system.refresh_cpu_usage();
155
156        Self {
157            config,
158            system: Arc::new(RwLock::new(system)),
159            high_cpu_count: Arc::new(RwLock::new(0)),
160            paused: Arc::new(RwLock::new(None)),
161        }
162    }
163
164    /// Evaluate the current resource state and update the pause state.
165    ///
166    /// Returns the pause reason if indexing should pause, `None` otherwise.
167    async fn evaluate(&self) -> Option<PauseReason> {
168        // CPU: average across all cores. sysinfo needs two samples over time
169        // for meaningful numbers; the monitoring loop provides that cadence.
170        let cpu_usage = {
171            let mut system = self.system.write().await;
172            system.refresh_cpu_usage();
173            let cpus = system.cpus();
174            if cpus.is_empty() {
175                0.0
176            } else {
177                cpus.iter().map(|c| c.cpu_usage()).sum::<f32>() / cpus.len() as f32
178            }
179        };
180
181        // Battery: pause if any battery is below threshold and discharging
182        // (multi-battery safe, IM).
183        if let Some(batteries) = battery_statuses() {
184            if any_battery_low(&batteries, self.config.battery_threshold) {
185                *self.paused.write().await = Some(PauseReason::LowBattery);
186                return Some(PauseReason::LowBattery);
187            }
188        }
189
190        // CPU
191        let mut high_cpu_count = self.high_cpu_count.write().await;
192        if cpu_usage > self.config.cpu_threshold as f32 {
193            *high_cpu_count += 1;
194            if *high_cpu_count >= self.config.cpu_consecutive_checks {
195                *self.paused.write().await = Some(PauseReason::HighCpu);
196                return Some(PauseReason::HighCpu);
197            }
198        } else {
199            *high_cpu_count = 0;
200        }
201
202        // Metered network: conservative no-op (see module docs).
203
204        // Conditions are OK: clear any previous pause state.
205        *self.paused.write().await = None;
206        None
207    }
208
209    /// Check if indexing should be paused based on current resource state.
210    pub async fn should_pause(&self) -> bool {
211        self.evaluate().await.is_some()
212    }
213
214    /// Get the current pause reason, if any.
215    pub async fn pause_reason(&self) -> Option<PauseReason> {
216        *self.paused.read().await
217    }
218
219    /// Start monitoring resources and send pause/resume signals.
220    ///
221    /// Runs until the task is aborted. Sends a `PauseReason` whenever the
222    /// pause state changes: the specific reason on pause, `Resumed` on resume.
223    pub fn start_monitoring(&self, sender: mpsc::Sender<PauseReason>) {
224        let config = self.config.clone();
225        let system = self.system.clone();
226        let high_cpu_count = self.high_cpu_count.clone();
227        let paused = self.paused.clone();
228
229        tokio::spawn(async move {
230            let mut timer = interval(config.check_interval);
231            loop {
232                timer.tick().await;
233
234                let cpu_usage = {
235                    let mut system = system.write().await;
236                    system.refresh_cpu_usage();
237                    let cpus = system.cpus();
238                    if cpus.is_empty() {
239                        0.0
240                    } else {
241                        cpus.iter().map(|c| c.cpu_usage()).sum::<f32>() / cpus.len() as f32
242                    }
243                };
244
245                let mut reason = None;
246
247                if let Some(batteries) = battery_statuses() {
248                    if any_battery_low(&batteries, config.battery_threshold) {
249                        reason = Some(PauseReason::LowBattery);
250                    }
251                }
252
253                if reason.is_none() {
254                    let mut count = high_cpu_count.write().await;
255                    if cpu_usage > config.cpu_threshold as f32 {
256                        *count += 1;
257                        if *count >= config.cpu_consecutive_checks {
258                            reason = Some(PauseReason::HighCpu);
259                        }
260                    } else {
261                        *count = 0;
262                    }
263                }
264
265                let mut paused = paused.write().await;
266                match reason {
267                    Some(r) => {
268                        if *paused != Some(r) {
269                            *paused = Some(r);
270                            let _ = sender.send(r).await;
271                        }
272                    }
273                    None => {
274                        if paused.is_some() {
275                            *paused = None;
276                            let _ = sender.send(PauseReason::Resumed).await;
277                        }
278                    }
279                }
280            }
281        });
282    }
283
284    /// Force a resource check and return whether paused.
285    pub async fn check_now(&self) -> bool {
286        self.should_pause().await
287    }
288}
289
290impl Default for ResourceGuard {
291    fn default() -> Self {
292        Self::new()
293    }
294}