Spawn the background thread and return a handle to send it work.
()
| 30 | impl TelemetryWorker { |
| 31 | /// Spawn the background thread and return a handle to send it work. |
| 32 | fn spawn() -> Self { |
| 33 | let (sender, receiver) = channel::<WorkerMessage>(); |
| 34 | std::thread::spawn(move || { |
| 35 | let mut current_path: Option<PathBuf> = None; |
| 36 | let mut current_file: Option<File> = None; |
| 37 | let mut consecutive_errors: u32 = 0; |
| 38 | const MAX_CONSECUTIVE_ERRORS: u32 = 10; |
| 39 | |
| 40 | while let Ok(msg) = receiver.recv() { |
| 41 | match msg { |
| 42 | WorkerMessage::Log(entry) => { |
| 43 | // If we've had too many consecutive errors, skip this entry |
| 44 | // to avoid spamming the filesystem with failing operations. |
| 45 | if consecutive_errors >= MAX_CONSECUTIVE_ERRORS { |
| 46 | continue; |
| 47 | } |
| 48 | |
| 49 | let path_display = entry.path.display().to_string(); |
| 50 | |
| 51 | // Open (or re-open) the file if the path has changed. |
| 52 | if current_path.as_deref() != Some(entry.path.as_path()) { |
| 53 | match open_log_file(&entry.path) { |
| 54 | Ok(new_file) => { |
| 55 | current_path = Some(entry.path); |
| 56 | current_file = Some(new_file); |
| 57 | consecutive_errors = 0; |
| 58 | } |
| 59 | Err(e) => { |
| 60 | consecutive_errors += 1; |
| 61 | current_path = None; |
| 62 | current_file = None; |
| 63 | // Log to stderr as a fallback so the error is visible. |
| 64 | eprintln!( |
| 65 | "telemetry: failed to open {}: {} (consecutive errors: {})", |
| 66 | path_display, e, consecutive_errors |
| 67 | ); |
| 68 | } |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | // Write the entry, with flush to ensure durability. |
| 73 | if let Some(file) = current_file.as_mut() { |
| 74 | if let Err(e) = write_entry(file, &entry.line) { |
| 75 | consecutive_errors += 1; |
| 76 | eprintln!( |
| 77 | "telemetry: failed to write to {}: {} (consecutive errors: {})", |
| 78 | path_display, e, consecutive_errors |
| 79 | ); |
| 80 | // Drop the file handle so we re-open on next entry. |
| 81 | current_file = None; |
| 82 | current_path = None; |
| 83 | } else { |
| 84 | consecutive_errors = 0; |
| 85 | } |
| 86 | } |
| 87 | } |
| 88 | WorkerMessage::Shutdown => break, |
| 89 | } |
no test coverage detected