Skip to main content

cmtraceopen_parser/error_db/
lookup.rs

1use regex::Regex;
2use std::collections::HashMap;
3
4use super::codes::{ErrorCode, ERROR_CODES};
5use serde::{Deserialize, Serialize};
6use std::sync::OnceLock;
7
8/// Pre-built HashMap from error code values to their ErrorCode entries.
9/// Provides O(1) lookup instead of linear scan over the array.
10fn code_map() -> &'static HashMap<u32, &'static ErrorCode> {
11    static CELL: OnceLock<HashMap<u32, &'static ErrorCode>> = OnceLock::new();
12    CELL.get_or_init(|| ERROR_CODES.iter().map(|ec| (ec.code, ec)).collect())
13}
14
15/// Look up an error code with HRESULT decomposition.
16/// Tries direct hit first. If miss and code is FACILITY_WIN32 (0x8007xxxx),
17/// extracts lower 16 bits as a Win32 code and looks that up.
18/// Conversely, if the code is a small Win32 value (<=0xFFFF), tries its
19/// HRESULT form (0x80070000 | code).
20fn find_error_code(code: u32) -> Option<&'static ErrorCode> {
21    // Direct table hit (O(1) via HashMap)
22    if let Some(ec) = code_map().get(&code) {
23        return Some(ec);
24    }
25
26    // FACILITY_WIN32 decomposition: if code is 0x8007xxxx, the lower 16 bits
27    // are a Win32 error code. Some Win32 codes may be stored without the
28    // HRESULT wrapper in the table.
29    if (code & 0xFFFF_0000) == 0x8007_0000 {
30        let win32_code = code & 0x0000_FFFF;
31        if let Some(ec) = code_map().get(&win32_code) {
32            return Some(ec);
33        }
34    }
35
36    // Reverse: if user typed a small Win32 code (e.g., 5), try its HRESULT form
37    if code <= 0xFFFF {
38        let hresult = 0x8007_0000 | code;
39        if let Some(ec) = code_map().get(&hresult) {
40            return Some(ec);
41        }
42    }
43
44    None
45}
46
47#[derive(Debug, Clone, Serialize, Deserialize)]
48#[serde(rename_all = "camelCase")]
49pub struct ErrorCodeSpan {
50    pub start: usize,
51    pub end: usize,
52    pub code_hex: String,
53    pub code_decimal: String,
54    pub description: String,
55    pub category: String,
56}
57
58fn hex_code_re() -> &'static Regex {
59    static CELL: OnceLock<Regex> = OnceLock::new();
60    CELL.get_or_init(|| Regex::new(r"0[xX][0-9A-Fa-f]{8}").unwrap())
61}
62
63/// Scan a message string for recognized error codes and return their spans.
64/// Only returns spans for codes that exist in the error database.
65/// Short-circuits if the message contains no "0x" or "0X" prefix (common case).
66pub fn detect_error_code_spans(message: &str) -> Vec<ErrorCodeSpan> {
67    // Fast pre-check: skip the regex entirely if no hex prefix exists.
68    // Most log lines have no error codes, so this avoids regex overhead.
69    if !message.contains("0x") && !message.contains("0X") {
70        return Vec::new();
71    }
72
73    hex_code_re()
74        .find_iter(message)
75        .filter_map(|m| {
76            // Skip matches followed by more hex digits (e.g., GUIDs, longer hex values)
77            let after = &message[m.end()..];
78            if after.starts_with(|c: char| c.is_ascii_hexdigit()) {
79                return None;
80            }
81            let hex_str = &message[m.start()..m.end()];
82            let code_val = u32::from_str_radix(&hex_str[2..], 16).ok()?;
83            let ec = find_error_code(code_val)?;
84            // Convert byte offsets to UTF-16 code unit offsets for JavaScript interop.
85            // JS String.slice() uses UTF-16 indices, but regex::Match returns byte offsets.
86            let utf16_start = message[..m.start()].encode_utf16().count();
87            // The match itself is all ASCII hex digits, so its UTF-16 length equals byte length.
88            let char_start = utf16_start;
89            let char_end = utf16_start + (m.end() - m.start());
90            Some(ErrorCodeSpan {
91                start: char_start,
92                end: char_end,
93                code_hex: format!("0x{:08X}", ec.code),
94                code_decimal: format!("{}", ec.code as i32),
95                description: ec.description.to_string(),
96                category: ec.category.label().to_string(),
97            })
98        })
99        .collect()
100}
101
102/// Result type shared by both exact lookup and search operations.
103#[derive(Debug, Clone, Serialize, Deserialize)]
104#[serde(rename_all = "camelCase")]
105pub struct ErrorLookupResult {
106    pub code_hex: String,
107    pub code_decimal: String,
108    pub description: String,
109    pub category: String,
110    pub found: bool,
111}
112
113/// Alias for backward compatibility with IPC commands that reference `ErrorSearchResult`.
114pub type ErrorSearchResult = ErrorLookupResult;
115
116/// Try to parse an input string as an error code (hex or decimal).
117/// Accepts formats: "0x80070005", "80070005", "-2147024891", "2147942405"
118fn try_parse_error_code(input: &str) -> Option<u32> {
119    if input.starts_with("0x") || input.starts_with("0X") {
120        u32::from_str_radix(&input[2..], 16).ok()
121    } else if input.starts_with('-') {
122        // Negative decimal (signed representation of HRESULT)
123        input.parse::<i32>().ok().map(|v| v as u32)
124    } else if let Ok(hex_val) = u32::from_str_radix(input, 16) {
125        // Try as raw hex without prefix (if it looks like hex)
126        if input.len() >= 6 && input.chars().all(|c| c.is_ascii_hexdigit()) {
127            Some(hex_val)
128        } else {
129            // Try as decimal first
130            input.parse::<u32>().ok().or(Some(hex_val))
131        }
132    } else {
133        input.parse::<u32>().ok()
134    }
135}
136
137/// Look up an error code by its hex or decimal value.
138/// Accepts formats: "0x80070005", "80070005", "-2147024891", "2147942405"
139pub fn lookup_error_code(input: &str) -> ErrorLookupResult {
140    let input = input.trim();
141
142    match try_parse_error_code(input) {
143        Some(c) => {
144            if let Some(ec) = find_error_code(c) {
145                ErrorLookupResult {
146                    code_hex: format!("0x{:08X}", ec.code),
147                    code_decimal: format!("{}", ec.code as i32),
148                    description: ec.description.to_string(),
149                    category: ec.category.label().to_string(),
150                    found: true,
151                }
152            } else {
153                // Code not in database — still show the formatted values
154                ErrorLookupResult {
155                    code_hex: format!("0x{:08X}", c),
156                    code_decimal: format!("{}", c as i32),
157                    description: "Unknown error code".to_string(),
158                    category: String::new(),
159                    found: false,
160                }
161            }
162        }
163        None => ErrorLookupResult {
164            code_hex: String::new(),
165            code_decimal: String::new(),
166            description: "Invalid error code format".to_string(),
167            category: String::new(),
168            found: false,
169        },
170    }
171}
172
173/// Search error codes by exact hex/decimal match or by description substring.
174/// Returns up to 50 results sorted by relevance.
175pub fn search_error_codes(query: &str) -> Vec<ErrorSearchResult> {
176    let query = query.trim();
177    if query.is_empty() {
178        return Vec::new();
179    }
180
181    // Try exact code lookup first
182    if let Some(code_val) = try_parse_error_code(query) {
183        if let Some(ec) = find_error_code(code_val) {
184            return vec![ErrorSearchResult {
185                code_hex: format!("0x{:08X}", ec.code),
186                code_decimal: format!("{}", ec.code as i32),
187                description: ec.description.to_string(),
188                category: ec.category.label().to_string(),
189                found: true,
190            }];
191        }
192        // Known code format but not in DB
193        return vec![ErrorSearchResult {
194            code_hex: format!("0x{:08X}", code_val),
195            code_decimal: format!("{}", code_val as i32),
196            description: "Unknown error code".to_string(),
197            category: String::new(),
198            found: false,
199        }];
200    }
201
202    // Substring search across descriptions and category labels
203    let query_lower = query.to_lowercase();
204    let mut results: Vec<(usize, &super::codes::ErrorCode)> = ERROR_CODES
205        .iter()
206        .filter_map(|ec| {
207            let desc_lower = ec.description.to_lowercase();
208            let cat_lower = ec.category.label().to_lowercase();
209            if desc_lower.starts_with(&query_lower) {
210                Some((0, ec)) // description prefix match (highest priority)
211            } else if desc_lower.contains(&query_lower) {
212                Some((1, ec)) // description substring match
213            } else if cat_lower.contains(&query_lower) {
214                Some((2, ec)) // category label match (lowest priority)
215            } else {
216                None
217            }
218        })
219        .collect();
220
221    results.sort_by_key(|(priority, _)| *priority);
222    results.truncate(50);
223
224    results
225        .into_iter()
226        .map(|(_, ec)| ErrorSearchResult {
227            code_hex: format!("0x{:08X}", ec.code),
228            code_decimal: format!("{}", ec.code as i32),
229            description: ec.description.to_string(),
230            category: ec.category.label().to_string(),
231            found: true,
232        })
233        .collect()
234}
235
236#[cfg(test)]
237mod tests {
238    use super::*;
239
240    #[test]
241    fn test_lookup_hex_prefix() {
242        let result = lookup_error_code("0x80070005");
243        assert!(result.found);
244        assert!(result.description.contains("Access is denied"));
245    }
246
247    #[test]
248    fn test_lookup_hex_no_prefix() {
249        let result = lookup_error_code("80070005");
250        assert!(result.found);
251        assert!(result.description.contains("Access is denied"));
252    }
253
254    #[test]
255    fn test_lookup_negative_decimal() {
256        // 0x80070005 = -2147024891 as signed i32
257        let result = lookup_error_code("-2147024891");
258        assert!(result.found);
259        assert!(result.description.contains("Access is denied"));
260    }
261
262    #[test]
263    fn test_lookup_success_code() {
264        let result = lookup_error_code("0x00000000");
265        assert!(result.found);
266        assert!(result.description.contains("S_OK"));
267    }
268
269    #[test]
270    fn test_lookup_unknown() {
271        let result = lookup_error_code("0xDEADBEEF");
272        assert!(!result.found);
273        assert_eq!(result.code_hex, "0xDEADBEEF");
274    }
275
276    #[test]
277    fn test_error_codes_have_categories() {
278        use super::super::codes::{ErrorCategory, ERROR_CODES};
279        let intune_count = ERROR_CODES
280            .iter()
281            .filter(|ec| matches!(ec.category, ErrorCategory::Intune))
282            .count();
283        assert!(intune_count > 0, "Should have Intune-categorized codes");
284    }
285
286    #[test]
287    fn test_no_duplicate_error_codes() {
288        use super::super::codes::ERROR_CODES;
289        use std::collections::HashSet;
290        let mut seen = HashSet::new();
291        for ec in ERROR_CODES.iter() {
292            assert!(
293                seen.insert(ec.code),
294                "Duplicate error code: 0x{:08X}",
295                ec.code
296            );
297        }
298    }
299
300    #[test]
301    fn test_lookup_includes_category() {
302        let result = lookup_error_code("0x87D00215");
303        assert!(result.found);
304        assert_eq!(result.category, "Intune");
305    }
306
307    #[test]
308    fn test_search_exact_hex() {
309        let results = search_error_codes("0x80070005");
310        assert_eq!(results.len(), 1);
311        assert!(results[0].found);
312        assert!(results[0].description.contains("Access is denied"));
313        assert_eq!(results[0].category, "Windows");
314    }
315
316    #[test]
317    fn test_search_by_description() {
318        let results = search_error_codes("Access is denied");
319        assert!(!results.is_empty());
320        assert!(results
321            .iter()
322            .any(|r| r.description.contains("Access is denied")));
323    }
324
325    #[test]
326    fn test_search_empty_query() {
327        let results = search_error_codes("");
328        assert!(results.is_empty());
329    }
330
331    #[test]
332    fn test_search_no_match() {
333        let results = search_error_codes("xyznonexistentxyz");
334        assert!(results.is_empty());
335    }
336
337    #[test]
338    fn test_search_max_results() {
339        let results = search_error_codes("error");
340        assert!(results.len() <= 50, "Should cap at 50 results");
341    }
342
343    #[test]
344    fn test_detect_error_code_spans() {
345        let spans = detect_error_code_spans("Failed with error 0x80070005 during install");
346        assert_eq!(spans.len(), 1);
347        assert_eq!(spans[0].start, 18);
348        assert_eq!(spans[0].end, 28);
349        assert_eq!(spans[0].code_hex, "0x80070005");
350        assert!(spans[0].description.contains("Access is denied"));
351        assert_eq!(spans[0].category, "Windows");
352    }
353
354    #[test]
355    fn test_detect_multiple_error_code_spans() {
356        let spans = detect_error_code_spans("Error 0x80070005 and then 0x80070002");
357        assert_eq!(spans.len(), 2);
358    }
359
360    #[test]
361    fn test_detect_no_error_code_spans() {
362        let spans = detect_error_code_spans("Everything is fine, no errors here");
363        assert!(spans.is_empty());
364    }
365
366    #[test]
367    fn test_detect_unrecognized_code_ignored() {
368        let spans = detect_error_code_spans("Code 0xDEADBEEF is not in our database");
369        assert!(spans.is_empty());
370    }
371
372    // --- HRESULT decomposition tests ---
373
374    #[test]
375    fn test_lookup_win32_code_finds_hresult_entry() {
376        // Win32 code 5 should resolve via HRESULT form 0x80070005
377        let result = lookup_error_code("5");
378        assert!(result.found);
379        assert!(result.description.contains("Access is denied"));
380        // Should show the canonical HRESULT form, not 0x00000005
381        assert_eq!(result.code_hex, "0x80070005");
382    }
383
384    #[test]
385    fn test_lookup_hresult_facility_win32_direct() {
386        // 0x80070005 should resolve directly
387        let result = lookup_error_code("0x80070005");
388        assert!(result.found);
389        assert!(result.description.contains("Access is denied"));
390    }
391
392    #[test]
393    fn test_search_win32_code_finds_hresult_entry() {
394        // Searching for "5" as a code should find 0x80070005
395        let results = search_error_codes("5");
396        assert_eq!(results.len(), 1);
397        assert!(results[0].found);
398        assert!(results[0].description.contains("Access is denied"));
399    }
400
401    #[test]
402    fn test_find_error_code_direct_hit() {
403        let ec = find_error_code(0x80070005);
404        assert!(ec.is_some());
405        assert!(ec.unwrap().description.contains("Access is denied"));
406    }
407
408    #[test]
409    fn test_find_error_code_win32_to_hresult() {
410        // Small Win32 code 2 should map to 0x80070002
411        let ec = find_error_code(2);
412        assert!(ec.is_some());
413        assert!(ec.unwrap().description.contains("file"));
414    }
415
416    #[test]
417    fn test_find_error_code_no_match() {
418        let ec = find_error_code(0xDEADBEEF);
419        assert!(ec.is_none());
420    }
421
422    #[test]
423    fn test_expanded_database_size() {
424        use super::super::codes::ERROR_CODES;
425        assert!(
426            ERROR_CODES.len() >= 400,
427            "Expected at least 400 error codes, got {}",
428            ERROR_CODES.len()
429        );
430    }
431
432    /// Helper: simulate JS String.slice(start, end) using UTF-16 code unit offsets.
433    fn js_slice(s: &str, start: usize, end: usize) -> String {
434        let utf16: Vec<u16> = s.encode_utf16().collect();
435        String::from_utf16(&utf16[start..end]).unwrap()
436    }
437
438    #[test]
439    fn test_detect_spans_with_non_ascii_prefix() {
440        // "Ñoño" has multi-byte UTF-8 chars, so byte offsets diverge from char offsets
441        let msg = "Ñoño error: 0x80070005 failed";
442        let spans = detect_error_code_spans(msg);
443        assert_eq!(spans.len(), 1);
444        // Verify UTF-16 offsets work correctly with JS String.slice() semantics
445        assert_eq!(js_slice(msg, spans[0].start, spans[0].end), "0x80070005");
446    }
447
448    #[test]
449    fn test_detect_spans_with_emoji_prefix() {
450        // Emoji like 🔥 are non-BMP: 4 bytes in UTF-8, 2 code units in UTF-16,
451        // but only 1 Rust char. This test ensures we count UTF-16 code units,
452        // not Unicode scalar values.
453        let msg = "🔥🔥 error 0x80070005 done";
454        let spans = detect_error_code_spans(msg);
455        assert_eq!(spans.len(), 1);
456        // 🔥 = 2 UTF-16 code units each, so prefix "🔥🔥 error " = 4 + 7 = 11 UTF-16 units
457        assert_eq!(spans[0].start, 11);
458        assert_eq!(spans[0].end, 21);
459        assert_eq!(js_slice(msg, spans[0].start, spans[0].end), "0x80070005");
460    }
461}