BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-base / src / diagnostics.rs

diagnostics.rs

diagnostics.rs 10.2 KiB Download Raw
1use std::fs::{self, OpenOptions};
2use std::io::Write;
3use std::path::{Path, PathBuf};
4use std::sync::OnceLock;
5use std::sync::atomic::{AtomicBool, Ordering};
6
7pub const DIAGNOSTICS_FILE: &str = "diagnostics.log";
8pub const DIAGNOSTICS_SETTING_KEY: &str = "diagnostics_enabled";
9pub const ENV_DEBUG_LOG: &str = "RUSTY_TEAMS_DEBUG_LOG";
10
11const MAX_BYTES: u64 = 1024 * 1024;
12const RING_SLOTS: u32 = 2;
13const MERGE_CAP_BYTES: u64 = 1024 * 1024;
14const SLOW_UI_HANDLER: std::time::Duration = std::time::Duration::from_millis(30);
15
16static PATH: OnceLock<PathBuf> = OnceLock::new();
17static ENABLED: AtomicBool = AtomicBool::new(false);
18
19const OWN_CRATE_PREFIXES: [&str; 10] = [
20 "app", "app_base", "state", "calling", "chatsvc", "session", "webview", "mcp", "agents",
21 "teams",
22];
23
24const WEBRTC_AUDIO_MARKERS: [&str; 5] = [
25 "AdmProxy",
26 "audio_device",
27 "core_audio",
28 "WebRtcVoiceEngine",
29 "webrtc_voice_engine",
30];
31const WEBRTC_SKIPPED: [&str; 3] = ["audio_device_buffer", "requesting data", "will write"];
32const ENDPOINT_DUMP_LINES: std::ops::Range<u32> = 4040..4170;
33
34pub fn install(path: PathBuf) {
35 let _ = PATH.set(path);
36 if log::set_logger(&DiagnosticsLog).is_ok() {
37 log::set_max_level(log::LevelFilter::Debug);
38 }
39 crate::support::install_panic_diagnostics_hook();
40}
41
42pub fn is_enabled() -> bool {
43 ENABLED.load(Ordering::Relaxed)
44}
45
46pub fn set_enabled(on: bool) {
47 ENABLED.store(on, Ordering::Relaxed);
48}
49
50pub fn enable_from_override() -> bool {
51 let on = std::env::args().any(|arg| arg == "--debug-log")
52 || std::env::var(ENV_DEBUG_LOG)
53 .map(|value| matches!(value.as_str(), "1" | "true" | "TRUE" | "yes" | "YES"))
54 .unwrap_or(false);
55 if on {
56 set_enabled(true);
57 }
58 on
59}
60
61pub fn load_enabled_from_store(stored: Option<&str>) -> bool {
62 let on = stored == Some("1");
63 set_enabled(on || is_enabled());
64 is_enabled()
65}
66
67pub fn directory() -> Option<PathBuf> {
68 PATH.get().and_then(|path| path.parent()).map(PathBuf::from)
69}
70
71pub fn path() -> Option<PathBuf> {
72 PATH.get().cloned()
73}
74
75pub fn record_if_slow(label: &str, elapsed: std::time::Duration) {
76 if elapsed >= SLOW_UI_HANDLER {
77 record(format!(
78 "slow ui handler: {label} took {} ms",
79 elapsed.as_millis()
80 ));
81 }
82}
83
84pub fn record(message: impl AsRef<str>) {
85 let message = message.as_ref();
86 eprintln!("{message}");
87 let Some(path) = PATH.get() else {
88 return;
89 };
90 if let Err(error) = append_rotated(
91 path,
92 MAX_BYTES,
93 RING_SLOTS,
94 &format!("{} {message}\n", line_prefix()),
95 ) {
96 eprintln!("diagnostics write failed: {error}");
97 }
98}
99
100/// Chronological merge of rotated slots then current (capped), for support packages.
101pub fn read_merged(max_bytes: u64) -> String {
102 let Some(path) = PATH.get() else {
103 return String::new();
104 };
105 read_ring_merged(path, RING_SLOTS, max_bytes.min(MERGE_CAP_BYTES).max(1))
106}
107
108pub fn clear_logs() -> std::io::Result<()> {
109 let Some(root) = directory() else {
110 return Ok(());
111 };
112 for name in [
113 DIAGNOSTICS_FILE,
114 &format!("{DIAGNOSTICS_FILE}.1"),
115 &format!("{DIAGNOSTICS_FILE}.2"),
116 crate::crash_log::CRASH_LOG_FILE,
117 &format!("{}.1", crate::crash_log::CRASH_LOG_FILE),
118 ] {
119 let path = root.join(name);
120 if path.exists() {
121 let _ = fs::remove_file(&path);
122 }
123 }
124 let dumps = root.join(crate::support::CALL_DUMPS_DIR);
125 if dumps.is_dir() {
126 for entry in fs::read_dir(&dumps)?.flatten() {
127 let path = entry.path();
128 if path.is_dir() {
129 let _ = fs::remove_dir_all(path);
130 } else {
131 let _ = fs::remove_file(path);
132 }
133 }
134 }
135 Ok(())
136}
137
138pub(crate) fn append_rotated(
139 path: &Path,
140 max_bytes: u64,
141 ring_slots: u32,
142 line: &str,
143) -> std::io::Result<()> {
144 if path
145 .metadata()
146 .map(|meta| meta.len() >= max_bytes)
147 .unwrap_or(false)
148 {
149 rotate_ring(path, ring_slots)?;
150 }
151 if let Some(parent) = path.parent() {
152 fs::create_dir_all(parent)?;
153 }
154 let mut file = OpenOptions::new().create(true).append(true).open(path)?;
155 file.write_all(line.as_bytes())
156}
157
158fn rotate_ring(path: &Path, ring_slots: u32) -> std::io::Result<()> {
159 for slot in (1..ring_slots).rev() {
160 let from = ring_path(path, slot);
161 let to = ring_path(path, slot + 1);
162 if from.exists() {
163 let _ = fs::remove_file(&to);
164 fs::rename(&from, &to)?;
165 }
166 }
167 let first = ring_path(path, 1);
168 let _ = fs::remove_file(&first);
169 if path.exists() {
170 fs::rename(path, &first)?;
171 }
172 Ok(())
173}
174
175fn ring_path(path: &Path, slot: u32) -> PathBuf {
176 path.with_file_name(format!(
177 "{}.{}",
178 path.file_name()
179 .and_then(|name| name.to_str())
180 .unwrap_or(DIAGNOSTICS_FILE),
181 slot
182 ))
183}
184
185pub(crate) fn read_ring_merged(path: &Path, slots: u32, max_bytes: u64) -> String {
186 let mut parts = Vec::new();
187 for slot in (1..=slots).rev() {
188 let sibling = ring_path(path, slot);
189 if let Ok(text) = fs::read_to_string(&sibling) {
190 parts.push(text);
191 }
192 }
193 if let Ok(text) = fs::read_to_string(path) {
194 parts.push(text);
195 }
196 let merged = parts.join("");
197 if merged.len() as u64 <= max_bytes {
198 return merged;
199 }
200 let mut start = merged.len() - max_bytes as usize;
201 while !merged.is_char_boundary(start) {
202 start += 1;
203 }
204 merged[start..].to_owned()
205}
206
207fn line_prefix() -> String {
208 format!(
209 "{} {}",
210 chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ"),
211 crate::version::build_version()
212 )
213}
214
215struct DiagnosticsLog;
216
217impl log::Log for DiagnosticsLog {
218 fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
219 let target = metadata.target();
220 if target == "libwebrtc" {
221 return true;
222 }
223 if !is_enabled() {
224 return false;
225 }
226 if is_own_crate(target) {
227 return metadata.level() <= log::Level::Info;
228 }
229 metadata.level() <= log::Level::Warn
230 }
231
232 fn log(&self, entry: &log::Record<'_>) {
233 if !self.enabled(entry.metadata()) {
234 return;
235 }
236 let target = entry.metadata().target();
237 let text = entry.args().to_string();
238 if target == "libwebrtc" {
239 if keeps_webrtc_line(entry.metadata().level(), &text) {
240 record(format!("webrtc: {text}"));
241 }
242 return;
243 }
244 let level = entry.metadata().level().as_str().to_ascii_lowercase();
245 let short = target.split("::").next().unwrap_or(target);
246 record(format!("{level} {short}: {text}"));
247 }
248
249 fn flush(&self) {}
250}
251
252fn is_own_crate(target: &str) -> bool {
253 let root = target.split("::").next().unwrap_or(target);
254 OWN_CRATE_PREFIXES
255 .iter()
256 .any(|prefix| root == *prefix || root.starts_with(&format!("{prefix}_")))
257}
258
259fn keeps_webrtc_line(level: log::Level, text: &str) -> bool {
260 if level <= log::Level::Warn
261 && (text.contains("peer_connection")
262 || text.contains("PeerConnection")
263 || text.contains("ICE")
264 || text.contains("ice_"))
265 {
266 return true;
267 }
268 WEBRTC_AUDIO_MARKERS
269 .iter()
270 .any(|marker| text.contains(marker))
271 && !WEBRTC_SKIPPED.iter().any(|skipped| text.contains(skipped))
272 && !is_endpoint_dump(text)
273}
274
275fn is_endpoint_dump(text: &str) -> bool {
276 text.split_once("audio_device_core_win.cc:")
277 .and_then(|(_, rest)| rest.split_once(')'))
278 .and_then(|(line, _)| line.parse::<u32>().ok())
279 .is_some_and(|line| ENDPOINT_DUMP_LINES.contains(&line))
280}
281
282#[cfg(test)]
283mod tests {
284 use super::*;
285 use tempfile::tempdir;
286
287 #[test]
288 fn audio_lines_are_kept_and_endpoint_dumps_and_noise_are_skipped() {
289 assert!(keeps_webrtc_line(
290 log::Level::Debug,
291 "(audio_device_impl.cc:123): Init"
292 ));
293 assert!(keeps_webrtc_line(
294 log::Level::Debug,
295 "(webrtc_voice_engine.cc:10): WebRtcVoiceEngine::Init"
296 ));
297 assert!(!keeps_webrtc_line(
298 log::Level::Debug,
299 "(audio_device_core_win.cc:4090): endpoint 3"
300 ));
301 assert!(keeps_webrtc_line(
302 log::Level::Debug,
303 "(audio_device_core_win.cc:412): AvRevertMmThreadCharacteristics() is OK"
304 ));
305 assert!(!keeps_webrtc_line(
306 log::Level::Debug,
307 "(audio_device_buffer.cc:450): [REC : 10000msec, 48kHz] callbacks: 1000"
308 ));
309 assert!(!keeps_webrtc_line(
310 log::Level::Debug,
311 "(audio_device_pulse_linux.cc:2236): requesting data"
312 ));
313 assert!(!keeps_webrtc_line(
314 log::Level::Debug,
315 "(audio_device_pulse_linux.cc:2256): will write"
316 ));
317 assert!(!keeps_webrtc_line(
318 log::Level::Debug,
319 "(peer_connection.cc:55): something"
320 ));
321 assert!(keeps_webrtc_line(
322 log::Level::Warn,
323 "(peer_connection.cc:55): ICE failed"
324 ));
325 }
326
327 #[test]
328 fn enabled_gate_defaults_and_toggles() {
329 set_enabled(false);
330 assert!(!is_enabled());
331 set_enabled(true);
332 assert!(is_enabled());
333 set_enabled(false);
334 assert!(!is_enabled());
335 }
336
337 #[test]
338 fn ring_rotation_preserves_previous_content() {
339 let root = tempdir().unwrap();
340 let path = root.path().join(DIAGNOSTICS_FILE);
341 fs::write(&path, "a".repeat(MAX_BYTES as usize)).unwrap();
342 append_rotated(&path, MAX_BYTES, RING_SLOTS, "fresh-line\n").unwrap();
343 assert!(ring_path(&path, 1).exists());
344 let current = fs::read_to_string(&path).unwrap();
345 assert!(current.contains("fresh-line"));
346 assert!(!current.contains(&"a".repeat(32)));
347 let previous = fs::read_to_string(ring_path(&path, 1)).unwrap();
348 assert!(previous.starts_with('a'));
349 }
350
351 #[test]
352 fn own_crate_prefixes_match() {
353 assert!(is_own_crate("app::linux_browser"));
354 assert!(is_own_crate("state::notice"));
355 assert!(is_own_crate("app_base::diagnostics"));
356 assert!(!is_own_crate("hyper::client"));
357 }
358}