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_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 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
122pub struct ResourceGuard {
124 pub config: ResourceGuardConfig,
126 system: Arc<RwLock<System>>,
127 high_cpu_count: Arc<RwLock<u32>>,
129 paused: Arc<RwLock<Option<PauseReason>>>,
131}
132
133impl ResourceGuard {
134 pub fn new() -> Self {
136 Self::with_config(ResourceGuardConfig::default())
137 }
138
139 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 async fn evaluate(&self) -> Option<PauseReason> {
156 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 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 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 *self.paused.write().await = None;
193 None
194 }
195
196 pub async fn should_pause(&self) -> bool {
198 self.evaluate().await.is_some()
199 }
200
201 pub async fn pause_reason(&self) -> Option<PauseReason> {
203 *self.paused.read().await
204 }
205
206 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 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}