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