1use regex::Regex;
2
3use super::severity::detect_severity_from_text;
4use crate::models::log_entry::{LogEntry, LogFormat, Severity};
5use std::sync::OnceLock;
6
7fn guid_field_re() -> &'static Regex {
8 static CELL: OnceLock<Regex> = OnceLock::new();
9 CELL.get_or_init(|| {
10 Regex::new(
11 r"^\{[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\}$",
12 )
13 .unwrap()
14 })
15}
16
17fn timestamp_re() -> &'static Regex {
18 static CELL: OnceLock<Regex> = OnceLock::new();
19 CELL.get_or_init(|| {
20 Regex::new(
21 r"^(\d{4})[-/](\d{2})[-/](\d{2})\s+(\d{2}):(\d{2}):(\d{2})(?:(?::|\.)(\d{1,7}))?$",
22 )
23 .unwrap()
24 })
25}
26
27pub fn matches_reporting_events_record(line: &str) -> bool {
28 let fields: Vec<&str> = line.split('\t').collect();
29 if fields.len() < 11 {
30 return false;
31 }
32
33 guid_field_re().is_match(fields[0].trim()) && parse_timestamp(fields[1].trim()).is_some()
34}
35
36pub fn parse_lines(lines: &[&str], file_path: &str) -> (Vec<LogEntry>, u32) {
37 let mut entries = Vec::new();
38 let mut parse_errors = 0;
39 let mut next_id = 0;
40
41 for (index, line) in lines.iter().enumerate() {
42 let trimmed_end = line.trim_end();
43 if trimmed_end.trim().is_empty() {
44 continue;
45 }
46
47 if let Some(mut entry) = parse_line(trimmed_end, file_path) {
48 entry.id = next_id;
49 entry.line_number = (index + 1) as u32;
50 entries.push(entry);
51 } else {
52 entries.push(fallback_entry(
53 next_id,
54 (index + 1) as u32,
55 trimmed_end,
56 file_path,
57 ));
58 parse_errors += 1;
59 }
60
61 next_id += 1;
62 }
63
64 (entries, parse_errors)
65}
66
67fn parse_line(line: &str, file_path: &str) -> Option<LogEntry> {
68 let fields: Vec<&str> = line.split('\t').collect();
69 if fields.len() < 11 {
70 return None;
71 }
72
73 let record_guid = normalize_field(fields[0])?;
74 if !guid_field_re().is_match(record_guid) {
75 return None;
76 }
77
78 let (timestamp, timestamp_display) = parse_timestamp(fields[1].trim())?;
79 let event_id = normalize_field(fields[2]);
80 let category = normalize_field(fields[3]);
81 let level = normalize_field(fields[4]);
82 let update_guid = normalize_field(fields[5]);
83 let hresult = normalize_field(fields[6]);
84 let agent = normalize_field(fields[7]);
85 let status = normalize_field(fields[8]);
86 let operation = normalize_field(fields[9]);
87 let detail = join_message_fields(&fields[10..]);
88
89 let component = agent
90 .map(|value| value.to_string())
91 .or_else(|| category.map(|value| value.to_string()));
92
93 let message = build_message(
94 record_guid,
95 event_id,
96 category,
97 update_guid,
98 hresult,
99 status,
100 operation,
101 &detail,
102 );
103
104 let severity = determine_severity(level, status, operation, &detail, hresult);
105
106 Some(LogEntry {
107 id: 0,
108 line_number: 0,
109 message,
110 component,
111 timestamp: Some(timestamp),
112 timestamp_display: Some(timestamp_display),
113 severity,
114 thread: None,
115 thread_display: None,
116 source_file: None,
117 format: LogFormat::Timestamped,
118 file_path: file_path.to_string(),
119 timezone_offset: None,
120 error_code_spans: Vec::new(),
121 ip_address: None,
122 host_name: None,
123 mac_address: None,
124 result_code: None,
125 gle_code: None,
126 setup_phase: None,
127 operation_name: None,
128 http_method: None,
129 uri_stem: None,
130 uri_query: None,
131 status_code: None,
132 sub_status: None,
133 time_taken_ms: None,
134 client_ip: None,
135 server_ip: None,
136 user_agent: None,
137 server_port: None,
138 username: None,
139 win32_status: None,
140 query_name: None,
141 query_type: None,
142 response_code: None,
143 dns_direction: None,
144 dns_protocol: None,
145 source_ip: None,
146 dns_flags: None,
147 dns_event_id: None,
148 zone_name: None,
149 entry_kind: None,
150 whatif: None,
151 section_name: None,
152 section_color: None,
153 iteration: None,
154 tags: None,
155 })
156}
157
158fn parse_timestamp(value: &str) -> Option<(i64, String)> {
159 let caps = timestamp_re().captures(value)?;
160
161 let year: i32 = caps.get(1)?.as_str().parse().ok()?;
162 let month: u32 = caps.get(2)?.as_str().parse().ok()?;
163 let day: u32 = caps.get(3)?.as_str().parse().ok()?;
164 let hour: u32 = caps.get(4)?.as_str().parse().ok()?;
165 let minute: u32 = caps.get(5)?.as_str().parse().ok()?;
166 let second: u32 = caps.get(6)?.as_str().parse().ok()?;
167 let millis = parse_fractional_millis(caps.get(7).map(|m| m.as_str()));
168
169 let parsed = chrono::NaiveDate::from_ymd_opt(year, month, day)
170 .and_then(|date| date.and_hms_milli_opt(hour, minute, second, millis))?;
171
172 Some((
173 parsed.and_utc().timestamp_millis(),
174 format!(
175 "{:04}-{:02}-{:02} {:02}:{:02}:{:02}.{:03}",
176 year, month, day, hour, minute, second, millis
177 ),
178 ))
179}
180
181fn parse_fractional_millis(value: Option<&str>) -> u32 {
182 match value {
183 Some(raw) => {
184 let padded = format!("{:0<3}", raw);
185 padded[..3].parse::<u32>().unwrap_or(0)
186 }
187 None => 0,
188 }
189}
190
191#[allow(clippy::too_many_arguments)]
192fn build_message(
193 record_guid: &str,
194 event_id: Option<&str>,
195 category: Option<&str>,
196 update_guid: Option<&str>,
197 hresult: Option<&str>,
198 status: Option<&str>,
199 operation: Option<&str>,
200 detail: &str,
201) -> String {
202 let mut parts = Vec::new();
203
204 if let Some(status) = status {
205 parts.push(status.to_string());
206 }
207
208 if let Some(operation) = operation {
209 parts.push(operation.to_string());
210 }
211
212 if !detail.is_empty() {
213 parts.push(detail.to_string());
214 }
215
216 if let Some(hresult) = hresult.filter(|value| !is_zero_hresult(value)) {
217 parts.push(format!("HRESULT {}", hresult));
218 }
219
220 if let Some(event_id) = event_id {
221 parts.push(format!("EventId {}", event_id));
222 }
223
224 if let Some(category) = category {
225 parts.push(format!("Category {}", category));
226 }
227
228 if let Some(update_guid) = update_guid.filter(|value| !is_placeholder_guid(value)) {
229 parts.push(format!("Update {}", update_guid));
230 }
231
232 parts.push(format!("Record {}", record_guid));
233
234 parts.join(" | ")
235}
236
237fn determine_severity(
238 level: Option<&str>,
239 status: Option<&str>,
240 operation: Option<&str>,
241 detail: &str,
242 hresult: Option<&str>,
243) -> Severity {
244 if let Some(level) = level {
245 let normalized = level.trim().to_ascii_lowercase();
246 if matches!(normalized.as_str(), "3" | "error" | "failed" | "failure") {
247 return Severity::Error;
248 }
249 if matches!(normalized.as_str(), "2" | "warning" | "warn") {
250 return Severity::Warning;
251 }
252 }
253
254 if let Some(status) = status {
255 let normalized = status.trim().to_ascii_lowercase();
256 if normalized.contains("fail") || normalized.contains("error") {
257 return Severity::Error;
258 }
259 if normalized.contains("warn") {
260 return Severity::Warning;
261 }
262 }
263
264 if hresult.is_some_and(|value| !is_zero_hresult(value)) {
265 return Severity::Error;
266 }
267
268 let combined = [operation.unwrap_or(""), detail]
269 .join(" ")
270 .trim()
271 .to_string();
272 detect_severity_from_text(&combined)
273}
274
275fn normalize_field(value: &str) -> Option<&str> {
276 let trimmed = value.trim();
277 if trimmed.is_empty() || trimmed == "-" {
278 None
279 } else {
280 Some(trimmed)
281 }
282}
283
284fn join_message_fields(fields: &[&str]) -> String {
285 fields
286 .iter()
287 .map(|field| field.trim())
288 .filter(|field| !field.is_empty())
289 .collect::<Vec<_>>()
290 .join("\t")
291}
292
293fn is_zero_hresult(value: &str) -> bool {
294 let normalized = value.trim().to_ascii_lowercase();
295 matches!(normalized.as_str(), "0" | "0x0" | "0x00000000")
296}
297
298fn is_placeholder_guid(value: &str) -> bool {
299 value.eq_ignore_ascii_case("{00000000-0000-0000-0000-000000000000}")
300}
301
302fn fallback_entry(id: u64, line_number: u32, line: &str, file_path: &str) -> LogEntry {
303 LogEntry {
304 id,
305 line_number,
306 message: line.trim_end().to_string(),
307 component: None,
308 timestamp: None,
309 timestamp_display: None,
310 severity: detect_severity_from_text(line),
311 thread: None,
312 thread_display: None,
313 source_file: None,
314 format: LogFormat::Timestamped,
315 file_path: file_path.to_string(),
316 timezone_offset: None,
317 error_code_spans: Vec::new(),
318 ip_address: None,
319 host_name: None,
320 mac_address: None,
321 result_code: None,
322 gle_code: None,
323 setup_phase: None,
324 operation_name: None,
325 http_method: None,
326 uri_stem: None,
327 uri_query: None,
328 status_code: None,
329 sub_status: None,
330 time_taken_ms: None,
331 client_ip: None,
332 server_ip: None,
333 user_agent: None,
334 server_port: None,
335 username: None,
336 win32_status: None,
337 query_name: None,
338 query_type: None,
339 response_code: None,
340 dns_direction: None,
341 dns_protocol: None,
342 source_ip: None,
343 dns_flags: None,
344 dns_event_id: None,
345 zone_name: None,
346 entry_kind: None,
347 whatif: None,
348 section_name: None,
349 section_color: None,
350 iteration: None,
351 tags: None,
352 }
353}
354
355#[cfg(test)]
356mod tests {
357 use super::*;
358
359 #[test]
360 fn test_matches_reporting_events_record() {
361 assert!(matches_reporting_events_record(
362 "{11111111-1111-1111-1111-111111111111}\t2024-01-15 08:00:00:123\t1\tSoftware Update\t1\t{22222222-2222-2222-2222-222222222222}\t0x00000000\tWindows Update Agent\tSuccess\tInstallation\tInstallation Successful: KB5034123"
363 ));
364 assert!(!matches_reporting_events_record("plain text"));
365 }
366
367 #[test]
368 fn test_parse_lines_parses_structured_rows() {
369 let lines = [
370 "{11111111-1111-1111-1111-111111111111}\t2024-01-15 08:00:00:123\t1\tSoftware Update\t1\t{22222222-2222-2222-2222-222222222222}\t0x00000000\tWindows Update Agent\tSuccess\tInstallation\tInstallation Successful: KB5034123",
371 "{33333333-3333-3333-3333-333333333333}\t2024-01-15 08:05:00:456\t2\tSoftware Update\t3\t{44444444-4444-4444-4444-444444444444}\t0x80240022\tWindows Update Agent\tFailure\tInstallation\tInstallation failed for KB5034441",
372 ];
373
374 let (entries, parse_errors) = parse_lines(
375 &lines,
376 "C:/Windows/SoftwareDistribution/ReportingEvents.log",
377 );
378
379 assert_eq!(parse_errors, 0);
380 assert_eq!(entries.len(), 2);
381 assert_eq!(
382 entries[0].component.as_deref(),
383 Some("Windows Update Agent")
384 );
385 assert_eq!(
386 entries[0].timestamp_display.as_deref(),
387 Some("2024-01-15 08:00:00.123")
388 );
389 assert!(entries[0].message.contains("Success | Installation"));
390 assert_eq!(entries[1].severity, Severity::Error);
391 assert!(entries[1].message.contains("HRESULT 0x80240022"));
392 }
393
394 #[test]
395 fn test_parse_lines_keeps_fallback_for_malformed_rows() {
396 let lines = [
397 "{11111111-1111-1111-1111-111111111111}\t2024-01-15 08:00:00:123\t1\tSoftware Update\t1\t{22222222-2222-2222-2222-222222222222}\t0x00000000\tWindows Update Agent\tSuccess\tInstallation\tInstallation Successful: KB5034123",
398 "{33333333-3333-3333-3333-333333333333}\tnot-a-timestamp\t2\tSoftware Update\t3\t{44444444-4444-4444-4444-444444444444}\t0x80240022\tWindows Update Agent\tFailure\tInstallation\tInstallation failed for KB5034441",
399 "orphan raw line",
400 "{55555555-5555-5555-5555-555555555555}\t2024-01-15 08:10:00:789\t3\tSoftware Update\t2\t{66666666-6666-6666-6666-666666666666}\t0x00000000\tWindows Update Agent\tWarning\tScan\tRetry required",
401 ];
402
403 let (entries, parse_errors) = parse_lines(
404 &lines,
405 "C:/Windows/SoftwareDistribution/ReportingEvents.log",
406 );
407
408 assert_eq!(parse_errors, 2);
409 assert_eq!(entries.len(), 4);
410 assert_eq!(entries[1].message, lines[1]);
411 assert_eq!(entries[2].message, "orphan raw line");
412 assert_eq!(entries[3].severity, Severity::Warning);
413 assert_eq!(entries[3].line_number, 4);
414 }
415}