| 1 | use std::fs::{self, OpenOptions}; |
| 2 | use std::io::Write; |
| 3 | use std::path::{Path, PathBuf}; |
| 4 | use std::sync::OnceLock; |
| 5 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 6 | |
| 7 | pub const DIAGNOSTICS_FILE: &str = "diagnostics.log"; |
| 8 | pub const DIAGNOSTICS_SETTING_KEY: &str = "diagnostics_enabled"; |
| 9 | pub const ENV_DEBUG_LOG: &str = "RUSTY_TEAMS_DEBUG_LOG"; |
| 10 | |
| 11 | const MAX_BYTES: u64 = 1024 * 1024; |
| 12 | const RING_SLOTS: u32 = 2; |
| 13 | const MERGE_CAP_BYTES: u64 = 1024 * 1024; |
| 14 | const SLOW_UI_HANDLER: std::time::Duration = std::time::Duration::from_millis(30); |
| 15 | |
| 16 | static PATH: OnceLock<PathBuf> = OnceLock::new(); |
| 17 | static ENABLED: AtomicBool = AtomicBool::new(false); |
| 18 | |
| 19 | const OWN_CRATE_PREFIXES: [&str; 10] = [ |
| 20 | "app", "app_base", "state", "calling", "chatsvc", "session", "webview", "mcp", "agents", |
| 21 | "teams", |
| 22 | ]; |
| 23 | |
| 24 | const WEBRTC_KEPT_MARKERS: [&str; 6] = [ |
| 25 | "MFH264", |
| 26 | "AdmProxy", |
| 27 | "audio_device", |
| 28 | "core_audio", |
| 29 | "WebRtcVoiceEngine", |
| 30 | "webrtc_voice_engine", |
| 31 | ]; |
| 32 | const WEBRTC_SKIPPED: [&str; 3] = ["audio_device_buffer", "requesting data", "will write"]; |
| 33 | const ENDPOINT_DUMP_LINES: std::ops::Range<u32> = 4040..4170; |
| 34 | |
| 35 | pub 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 | |
| 43 | pub fn is_enabled() -> bool { |
| 44 | ENABLED.load(Ordering::Relaxed) |
| 45 | } |
| 46 | |
| 47 | pub fn set_enabled(on: bool) { |
| 48 | ENABLED.store(on, Ordering::Relaxed); |
| 49 | } |
| 50 | |
| 51 | pub 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 | |
| 62 | pub 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 | |
| 68 | pub fn directory() -> Option<PathBuf> { |
| 69 | PATH.get().and_then(|path| path.parent()).map(PathBuf::from) |
| 70 | } |
| 71 | |
| 72 | pub fn path() -> Option<PathBuf> { |
| 73 | PATH.get().cloned() |
| 74 | } |
| 75 | |
| 76 | pub 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 | |
| 85 | pub 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. |
| 102 | pub 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 | |
| 109 | pub 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 | |
| 139 | pub(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 | |
| 159 | fn 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 | |
| 176 | fn 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 | |
| 186 | pub(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 | |
| 208 | fn 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 | |
| 216 | struct DiagnosticsLog; |
| 217 | |
| 218 | impl 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 | |
| 253 | fn 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 | |
| 260 | fn 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 | && !is_adm_enumeration_dump(text) |
| 275 | } |
| 276 | |
| 277 | /// Device-name lines from each `list_devices` poll. Linux prints the function |
| 278 | /// name; MSVC prefixes it with `virtual webrtc::AudioDeviceModuleImpl::`. |
| 279 | /// Numeric `output:` / `input:` lines are return values (`Recording`, `Playing`) |
| 280 | /// and stay. `Initialized:` is the per-poll flag, not that return value. |
| 281 | fn is_adm_enumeration_dump(text: &str) -> bool { |
| 282 | let Some(message) = text |
| 283 | .split_once("audio_device_impl.cc:") |
| 284 | .and_then(|(_, rest)| rest.split_once("): ").map(|(_, message)| message)) |
| 285 | else { |
| 286 | return false; |
| 287 | }; |
| 288 | let head = adm_function_name(message); |
| 289 | const CALLS: [&str; 4] = [ |
| 290 | "PlayoutDeviceName", |
| 291 | "RecordingDeviceName", |
| 292 | "PlayoutDevices", |
| 293 | "RecordingDevices", |
| 294 | ]; |
| 295 | const DUMPS: [&str; 4] = ["output: name", "output: guid", "input: name", "input: guid"]; |
| 296 | CALLS.iter().any(|prefix| head.starts_with(prefix)) |
| 297 | || DUMPS.iter().any(|prefix| head.starts_with(prefix)) |
| 298 | || head.starts_with("Initialized") |
| 299 | } |
| 300 | |
| 301 | /// Drops an optional MSVC `__FUNCTION__` prefix so Linux and Windows share one check. |
| 302 | fn adm_function_name(message: &str) -> &str { |
| 303 | let rest = message.strip_prefix("virtual ").unwrap_or(message); |
| 304 | rest.strip_prefix("webrtc::AudioDeviceModuleImpl::") |
| 305 | .unwrap_or(rest) |
| 306 | } |
| 307 | |
| 308 | fn is_endpoint_dump(text: &str) -> bool { |
| 309 | text.split_once("audio_device_core_win.cc:") |
| 310 | .and_then(|(_, rest)| rest.split_once(')')) |
| 311 | .and_then(|(line, _)| line.parse::<u32>().ok()) |
| 312 | .is_some_and(|line| ENDPOINT_DUMP_LINES.contains(&line)) |
| 313 | } |
| 314 | |
| 315 | #[cfg(test)] |
| 316 | mod tests { |
| 317 | use super::*; |
| 318 | use tempfile::tempdir; |
| 319 | |
| 320 | #[test] |
| 321 | fn hardware_encoder_lines_are_kept() { |
| 322 | assert!(keeps_webrtc_line( |
| 323 | log::Level::Info, |
| 324 | "(mf_h264_encoder_impl.cc:250): MFH264: initialized 868x488 @30fps" |
| 325 | )); |
| 326 | } |
| 327 | |
| 328 | #[test] |
| 329 | fn audio_lines_are_kept_and_endpoint_dumps_and_noise_are_skipped() { |
| 330 | assert!(keeps_webrtc_line( |
| 331 | log::Level::Debug, |
| 332 | "(audio_device_impl.cc:123): Init" |
| 333 | )); |
| 334 | assert!(!keeps_webrtc_line( |
| 335 | log::Level::Debug, |
| 336 | "(audio_device_impl.cc:655): PlayoutDeviceName(0, ...)" |
| 337 | )); |
| 338 | assert!(!keeps_webrtc_line( |
| 339 | log::Level::Debug, |
| 340 | "(audio_device_impl.cc:632): PlayoutDevices" |
| 341 | )); |
| 342 | assert!(!keeps_webrtc_line( |
| 343 | log::Level::Debug, |
| 344 | "(audio_device_impl.cc:640): RecordingDevices" |
| 345 | )); |
| 346 | assert!(!keeps_webrtc_line( |
| 347 | log::Level::Debug, |
| 348 | "(audio_device_impl.cc:648): RecordingDeviceName(1, ...)" |
| 349 | )); |
| 350 | assert!(!keeps_webrtc_line( |
| 351 | log::Level::Debug, |
| 352 | "(audio_device_impl.cc:664): output: name = Headset Game" |
| 353 | )); |
| 354 | assert!(!keeps_webrtc_line( |
| 355 | log::Level::Debug, |
| 356 | "(audio_device_impl.cc:667): output: guid = " |
| 357 | )); |
| 358 | assert!(!keeps_webrtc_line( |
| 359 | log::Level::Debug, |
| 360 | "(audio_device_impl.cc:680): input: name = Headset Chat" |
| 361 | )); |
| 362 | assert!(!keeps_webrtc_line( |
| 363 | log::Level::Debug, |
| 364 | "(audio_device_impl.cc:683): input: guid = " |
| 365 | )); |
| 366 | assert!(!keeps_webrtc_line( |
| 367 | log::Level::Debug, |
| 368 | "(audio_device_impl.cc:620): Initialized: 1" |
| 369 | )); |
| 370 | assert!(keeps_webrtc_line( |
| 371 | log::Level::Debug, |
| 372 | "(audio_device_impl.cc:700): output: 1" |
| 373 | )); |
| 374 | assert!(keeps_webrtc_line( |
| 375 | log::Level::Debug, |
| 376 | "(audio_device_impl.cc:710): input: 0" |
| 377 | )); |
| 378 | assert!(!keeps_webrtc_line( |
| 379 | log::Level::Debug, |
| 380 | "(audio_device_impl.cc:655): virtual webrtc::AudioDeviceModuleImpl::PlayoutDeviceName(0, ...)" |
| 381 | )); |
| 382 | assert!(!keeps_webrtc_line( |
| 383 | log::Level::Debug, |
| 384 | "(audio_device_impl.cc:632): virtual webrtc::AudioDeviceModuleImpl::PlayoutDevices" |
| 385 | )); |
| 386 | assert!(keeps_webrtc_line( |
| 387 | log::Level::Debug, |
| 388 | "(audio_device_impl.cc:635): output: 4" |
| 389 | )); |
| 390 | assert!(keeps_webrtc_line( |
| 391 | log::Level::Debug, |
| 392 | "(audio_device_pulse_linux.cc:1161): disconnected recording" |
| 393 | )); |
| 394 | assert!(keeps_webrtc_line( |
| 395 | log::Level::Debug, |
| 396 | "(audio_device_pulse_linux.cc:1366): failed" |
| 397 | )); |
| 398 | assert!(keeps_webrtc_line( |
| 399 | log::Level::Debug, |
| 400 | "(audio_device_pulse_linux.cc:1735): PulseAudio terminated" |
| 401 | )); |
| 402 | assert!(keeps_webrtc_line( |
| 403 | log::Level::Debug, |
| 404 | "(webrtc_voice_engine.cc:10): WebRtcVoiceEngine::Init" |
| 405 | )); |
| 406 | assert!(!keeps_webrtc_line( |
| 407 | log::Level::Debug, |
| 408 | "(audio_device_core_win.cc:4090): endpoint 3" |
| 409 | )); |
| 410 | assert!(keeps_webrtc_line( |
| 411 | log::Level::Debug, |
| 412 | "(audio_device_core_win.cc:412): AvRevertMmThreadCharacteristics() is OK" |
| 413 | )); |
| 414 | assert!(!keeps_webrtc_line( |
| 415 | log::Level::Debug, |
| 416 | "(audio_device_buffer.cc:450): [REC : 10000msec, 48kHz] callbacks: 1000" |
| 417 | )); |
| 418 | assert!(!keeps_webrtc_line( |
| 419 | log::Level::Debug, |
| 420 | "(audio_device_pulse_linux.cc:2236): requesting data" |
| 421 | )); |
| 422 | assert!(!keeps_webrtc_line( |
| 423 | log::Level::Debug, |
| 424 | "(audio_device_pulse_linux.cc:2256): will write" |
| 425 | )); |
| 426 | assert!(!keeps_webrtc_line( |
| 427 | log::Level::Debug, |
| 428 | "(peer_connection.cc:55): something" |
| 429 | )); |
| 430 | assert!(keeps_webrtc_line( |
| 431 | log::Level::Warn, |
| 432 | "(peer_connection.cc:55): ICE failed" |
| 433 | )); |
| 434 | } |
| 435 | |
| 436 | #[test] |
| 437 | fn enabled_gate_defaults_and_toggles() { |
| 438 | set_enabled(false); |
| 439 | assert!(!is_enabled()); |
| 440 | set_enabled(true); |
| 441 | assert!(is_enabled()); |
| 442 | set_enabled(false); |
| 443 | assert!(!is_enabled()); |
| 444 | } |
| 445 | |
| 446 | #[test] |
| 447 | fn ring_rotation_preserves_previous_content() { |
| 448 | let root = tempdir().unwrap(); |
| 449 | let path = root.path().join(DIAGNOSTICS_FILE); |
| 450 | fs::write(&path, "a".repeat(MAX_BYTES as usize)).unwrap(); |
| 451 | append_rotated(&path, MAX_BYTES, RING_SLOTS, "fresh-line\n").unwrap(); |
| 452 | assert!(ring_path(&path, 1).exists()); |
| 453 | let current = fs::read_to_string(&path).unwrap(); |
| 454 | assert!(current.contains("fresh-line")); |
| 455 | assert!(!current.contains(&"a".repeat(32))); |
| 456 | let previous = fs::read_to_string(ring_path(&path, 1)).unwrap(); |
| 457 | assert!(previous.starts_with('a')); |
| 458 | } |
| 459 | |
| 460 | #[test] |
| 461 | fn own_crate_prefixes_match() { |
| 462 | assert!(is_own_crate("app::linux_browser")); |
| 463 | assert!(is_own_crate("state::notice")); |
| 464 | assert!(is_own_crate("app_base::diagnostics")); |
| 465 | assert!(!is_own_crate("hyper::client")); |
| 466 | } |
| 467 | } |