BlueGit

ict rusty-teams

Files

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

diagnostics.rs

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