paper/daemon/
resource_guard.rs1use std::sync::Arc;
14use std::time::Duration;
15use sysinfo::System;
16use tokio::sync::{mpsc, RwLock};
17use tokio::time::interval;
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum PauseReason {
22 LowBattery,
23 HighCpu,
24 MeteredNetwork,
25 Resumed,
26}
27
28#[derive(Debug, Clone)]
30pub struct ResourceGuardConfig {
31 pub battery_threshold: u8,
33 pub cpu_threshold: u8,
35 pub check_interval: Duration,
37 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54struct BatteryStatus {
55 percent: u8,
56 charging: bool,
57}
58
59fn 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 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
126fn any_battery_low(batteries: &[BatteryStatus], threshold: u8) -> bool {
129 batteries
130 .iter()
131 .any(|b| b.percent < threshold && !b.charging)
132}
133
134pub struct ResourceGuard {
136 pub config: ResourceGuardConfig,
138 system: Arc<RwLock<System>>,
139 high_cpu_count: Arc<RwLock<u32>>,
141 paused: Arc<RwLock<Option<PauseReason>>>,
143}
144
145impl ResourceGuard {
146 pub fn new() -> Self {
148 Self::with_config(ResourceGuardConfig::default())
149 }
150
151 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 async fn evaluate(&self) -> Option<PauseReason> {
168 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 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 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 *self.paused.write().await = None;
206 None
207 }
208
209 pub async fn should_pause(&self) -> bool {
211 self.evaluate().await.is_some()
212 }
213
214 pub async fn pause_reason(&self) -> Option<PauseReason> {
216 *self.paused.read().await
217 }
218
219 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 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}