oxirs-gql 0.2.4

GraphQL façade for OxiRS with automatic schema generation from RDF ontologies
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
//! Error Aggregation and Grouping
//!
//! Provides intelligent error aggregation, grouping, and analysis
//! for GraphQL operations.
//!
//! # Features
//!
//! - Automatic error grouping by similarity
//! - Error frequency tracking
//! - Root cause analysis
//! - Error pattern detection
//! - Stack trace fingerprinting
//! - Error trend analysis

use std::cmp::Reverse;
use std::collections::HashMap;
use std::time::{Duration, SystemTime};

/// Error severity level
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ErrorSeverity {
    Low,
    Medium,
    High,
    Critical,
}

/// Error category
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ErrorCategory {
    Validation,
    Authorization,
    Network,
    Database,
    Internal,
    Timeout,
    RateLimit,
    Unknown,
}

/// Individual error occurrence
#[derive(Debug, Clone)]
pub struct ErrorOccurrence {
    pub timestamp: SystemTime,
    pub error_message: String,
    pub error_type: String,
    pub stack_trace: Option<String>,
    pub query_id: Option<String>,
    pub user_id: Option<String>,
    pub field_path: Option<Vec<String>>,
    pub context: HashMap<String, String>,
}

/// Grouped errors with statistics
#[derive(Debug, Clone)]
pub struct ErrorGroup {
    pub id: String,
    pub fingerprint: String,
    pub error_type: String,
    pub category: ErrorCategory,
    pub severity: ErrorSeverity,
    pub first_seen: SystemTime,
    pub last_seen: SystemTime,
    pub occurrences: Vec<ErrorOccurrence>,
    pub count: usize,
    pub affected_users: usize,
    pub affected_queries: usize,
    pub sample_message: String,
}

impl ErrorGroup {
    /// Calculate error rate (errors per minute)
    pub fn error_rate(&self) -> f64 {
        if self.occurrences.len() < 2 {
            return 0.0;
        }

        let duration = self
            .last_seen
            .duration_since(self.first_seen)
            .unwrap_or(Duration::ZERO);

        let minutes = duration.as_secs_f64() / 60.0;
        if minutes > 0.0 {
            self.count as f64 / minutes
        } else {
            0.0
        }
    }

    /// Check if error is trending up
    pub fn is_trending_up(&self, window: Duration) -> bool {
        let now = SystemTime::now();
        let cutoff = now - window;

        let recent_count = self
            .occurrences
            .iter()
            .filter(|e| e.timestamp >= cutoff)
            .count();

        let total_duration = now
            .duration_since(self.first_seen)
            .unwrap_or(Duration::ZERO);
        let window_fraction = window.as_secs_f64() / total_duration.as_secs_f64();

        recent_count as f64 > self.count as f64 * window_fraction * 1.5
    }
}

/// Error aggregation manager
pub struct ErrorAggregator {
    groups: HashMap<String, ErrorGroup>,
    max_occurrences_per_group: usize,
}

impl ErrorAggregator {
    /// Create a new error aggregator
    pub fn new(max_occurrences_per_group: usize) -> Self {
        Self {
            groups: HashMap::new(),
            max_occurrences_per_group,
        }
    }

    /// Record an error
    pub fn record_error(&mut self, occurrence: ErrorOccurrence) {
        let fingerprint = Self::generate_fingerprint(&occurrence);
        let category = Self::categorize_error(&occurrence);
        let severity = Self::assess_severity(&occurrence, &category);

        if let Some(group) = self.groups.get_mut(&fingerprint) {
            // Update existing group
            group.last_seen = occurrence.timestamp;
            group.count += 1;

            // Track unique users and queries
            if let Some(ref user_id) = occurrence.user_id {
                if !group
                    .occurrences
                    .iter()
                    .any(|e| e.user_id.as_ref() == Some(user_id))
                {
                    group.affected_users += 1;
                }
            }

            if let Some(ref query_id) = occurrence.query_id {
                if !group
                    .occurrences
                    .iter()
                    .any(|e| e.query_id.as_ref() == Some(query_id))
                {
                    group.affected_queries += 1;
                }
            }

            // Add occurrence
            group.occurrences.push(occurrence);

            // Trim if needed
            if group.occurrences.len() > self.max_occurrences_per_group {
                group.occurrences.drain(0..1);
            }
        } else {
            // Create new group
            let id = format!("group-{}", self.groups.len());
            let sample_message = occurrence.error_message.clone();
            let first_seen = occurrence.timestamp;

            let occurrences = vec![occurrence];
            let affected_users = occurrences[0].user_id.as_ref().map(|_| 1).unwrap_or(0);
            let affected_queries = occurrences[0].query_id.as_ref().map(|_| 1).unwrap_or(0);

            self.groups.insert(
                fingerprint.clone(),
                ErrorGroup {
                    id,
                    fingerprint,
                    error_type: occurrences[0].error_type.clone(),
                    category,
                    severity,
                    first_seen,
                    last_seen: first_seen,
                    occurrences,
                    count: 1,
                    affected_users,
                    affected_queries,
                    sample_message,
                },
            );
        }
    }

    /// Get all error groups
    pub fn get_all_groups(&self) -> Vec<&ErrorGroup> {
        self.groups.values().collect()
    }

    /// Get error groups by category
    pub fn get_groups_by_category(&self, category: ErrorCategory) -> Vec<&ErrorGroup> {
        self.groups
            .values()
            .filter(|g| g.category == category)
            .collect()
    }

    /// Get error groups by severity
    pub fn get_groups_by_severity(&self, severity: ErrorSeverity) -> Vec<&ErrorGroup> {
        self.groups
            .values()
            .filter(|g| g.severity == severity)
            .collect()
    }

    /// Get top error groups by count
    pub fn get_top_errors(&self, limit: usize) -> Vec<&ErrorGroup> {
        let mut groups: Vec<_> = self.groups.values().collect();
        groups.sort_by_key(|g| Reverse(g.count));
        groups.into_iter().take(limit).collect()
    }

    /// Get trending errors
    pub fn get_trending_errors(&self, window: Duration) -> Vec<&ErrorGroup> {
        self.groups
            .values()
            .filter(|g| g.is_trending_up(window))
            .collect()
    }

    /// Get error statistics
    pub fn get_statistics(&self) -> ErrorStatistics {
        let total_errors: usize = self.groups.values().map(|g| g.count).sum();
        let total_groups = self.groups.len();

        let mut by_category: HashMap<ErrorCategory, usize> = HashMap::new();
        let mut by_severity: HashMap<ErrorSeverity, usize> = HashMap::new();

        for group in self.groups.values() {
            *by_category.entry(group.category.clone()).or_insert(0) += group.count;
            *by_severity.entry(group.severity).or_insert(0) += group.count;
        }

        ErrorStatistics {
            total_errors,
            total_groups,
            by_category,
            by_severity,
        }
    }

    /// Clear all error data
    pub fn clear(&mut self) {
        self.groups.clear();
    }

    /// Generate error fingerprint for grouping
    fn generate_fingerprint(occurrence: &ErrorOccurrence) -> String {
        // Use error type and a normalized message
        let normalized_message = Self::normalize_message(&occurrence.error_message);

        // Hash for consistent fingerprint
        let mut hash: u64 = 5381;
        for byte in occurrence.error_type.bytes() {
            hash = hash.wrapping_mul(33).wrapping_add(byte as u64);
        }
        for byte in normalized_message.bytes() {
            hash = hash.wrapping_mul(33).wrapping_add(byte as u64);
        }

        format!("{:x}", hash)
    }

    /// Normalize error message for grouping
    fn normalize_message(message: &str) -> String {
        // Remove numbers, IDs, and variable parts
        let mut normalized = message.to_string();

        // Replace numbers with placeholder
        normalized = normalized
            .split_whitespace()
            .map(|word| {
                if word.chars().all(|c| c.is_numeric()) {
                    "<num>"
                } else {
                    word
                }
            })
            .collect::<Vec<_>>()
            .join(" ");

        // Normalize case
        normalized.to_lowercase()
    }

    /// Categorize error based on content
    fn categorize_error(occurrence: &ErrorOccurrence) -> ErrorCategory {
        let message_lower = occurrence.error_message.to_lowercase();
        let type_lower = occurrence.error_type.to_lowercase();

        if type_lower.contains("validation") || message_lower.contains("invalid") {
            ErrorCategory::Validation
        } else if type_lower.contains("auth") || message_lower.contains("unauthorized") {
            ErrorCategory::Authorization
        } else if type_lower.contains("database")
            || type_lower.contains("db")
            || message_lower.contains("database")
            || message_lower.contains("query")
        {
            ErrorCategory::Database
        } else if message_lower.contains("network") || message_lower.contains("connection") {
            ErrorCategory::Network
        } else if message_lower.contains("timeout") {
            ErrorCategory::Timeout
        } else if message_lower.contains("rate limit") {
            ErrorCategory::RateLimit
        } else if type_lower.contains("internal") {
            ErrorCategory::Internal
        } else {
            ErrorCategory::Unknown
        }
    }

    /// Assess error severity
    fn assess_severity(occurrence: &ErrorOccurrence, category: &ErrorCategory) -> ErrorSeverity {
        match category {
            ErrorCategory::Authorization => ErrorSeverity::High,
            ErrorCategory::Internal => ErrorSeverity::Critical,
            ErrorCategory::Database => ErrorSeverity::High,
            ErrorCategory::Timeout => ErrorSeverity::Medium,
            ErrorCategory::RateLimit => ErrorSeverity::Low,
            ErrorCategory::Validation => ErrorSeverity::Low,
            ErrorCategory::Network => ErrorSeverity::Medium,
            ErrorCategory::Unknown => {
                // Check message for severity hints
                let message_lower = occurrence.error_message.to_lowercase();
                if message_lower.contains("critical") || message_lower.contains("fatal") {
                    ErrorSeverity::Critical
                } else if message_lower.contains("error") {
                    ErrorSeverity::High
                } else {
                    ErrorSeverity::Medium
                }
            }
        }
    }

    /// Generate error report
    pub fn generate_report(&self) -> String {
        let mut report = String::from("=== Error Aggregation Report ===\n\n");

        let stats = self.get_statistics();
        report.push_str(&format!("Total Errors: {}\n", stats.total_errors));
        report.push_str(&format!("Error Groups: {}\n\n", stats.total_groups));

        // By category
        report.push_str("Errors by Category:\n");
        for (category, count) in &stats.by_category {
            report.push_str(&format!("  {:?}: {}\n", category, count));
        }
        report.push('\n');

        // By severity
        report.push_str("Errors by Severity:\n");
        for (severity, count) in &stats.by_severity {
            report.push_str(&format!("  {:?}: {}\n", severity, count));
        }
        report.push('\n');

        // Top errors
        report.push_str("Top 5 Errors:\n");
        for (i, group) in self.get_top_errors(5).iter().enumerate() {
            report.push_str(&format!(
                "{}. {} (count: {}, users: {})\n",
                i + 1,
                group.sample_message,
                group.count,
                group.affected_users
            ));
        }

        report
    }
}

/// Error statistics
#[derive(Debug)]
pub struct ErrorStatistics {
    pub total_errors: usize,
    pub total_groups: usize,
    pub by_category: HashMap<ErrorCategory, usize>,
    pub by_severity: HashMap<ErrorSeverity, usize>,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_record_error() {
        let mut aggregator = ErrorAggregator::new(100);

        let occurrence = ErrorOccurrence {
            timestamp: SystemTime::now(),
            error_message: "Invalid input".to_string(),
            error_type: "ValidationError".to_string(),
            stack_trace: None,
            query_id: Some("query-1".to_string()),
            user_id: Some("user-1".to_string()),
            field_path: None,
            context: HashMap::new(),
        };

        aggregator.record_error(occurrence);

        assert_eq!(aggregator.get_all_groups().len(), 1);
    }

    #[test]
    fn test_error_grouping() {
        let mut aggregator = ErrorAggregator::new(100);

        // Same error type, should group together
        for i in 0..3 {
            aggregator.record_error(ErrorOccurrence {
                timestamp: SystemTime::now(),
                error_message: format!("Invalid input {}", i),
                error_type: "ValidationError".to_string(),
                stack_trace: None,
                query_id: Some(format!("query-{}", i)),
                user_id: None,
                field_path: None,
                context: HashMap::new(),
            });
        }

        // Should be grouped into one
        let groups = aggregator.get_all_groups();
        assert_eq!(groups.len(), 1);
        assert_eq!(groups[0].count, 3);
    }

    #[test]
    fn test_error_categorization() {
        let mut aggregator = ErrorAggregator::new(100);

        aggregator.record_error(ErrorOccurrence {
            timestamp: SystemTime::now(),
            error_message: "Unauthorized access".to_string(),
            error_type: "AuthError".to_string(),
            stack_trace: None,
            query_id: None,
            user_id: None,
            field_path: None,
            context: HashMap::new(),
        });

        let groups = aggregator.get_groups_by_category(ErrorCategory::Authorization);
        assert_eq!(groups.len(), 1);
    }

    #[test]
    fn test_error_severity() {
        let mut aggregator = ErrorAggregator::new(100);

        aggregator.record_error(ErrorOccurrence {
            timestamp: SystemTime::now(),
            error_message: "Database connection failed".to_string(),
            error_type: "DatabaseError".to_string(),
            stack_trace: None,
            query_id: None,
            user_id: None,
            field_path: None,
            context: HashMap::new(),
        });

        let groups = aggregator.get_groups_by_severity(ErrorSeverity::High);
        assert_eq!(groups.len(), 1);
    }

    #[test]
    fn test_top_errors() {
        let mut aggregator = ErrorAggregator::new(100);

        // Error with 5 occurrences
        for _ in 0..5 {
            aggregator.record_error(ErrorOccurrence {
                timestamp: SystemTime::now(),
                error_message: "Error A".to_string(),
                error_type: "ErrorA".to_string(),
                stack_trace: None,
                query_id: None,
                user_id: None,
                field_path: None,
                context: HashMap::new(),
            });
        }

        // Error with 2 occurrences
        for _ in 0..2 {
            aggregator.record_error(ErrorOccurrence {
                timestamp: SystemTime::now(),
                error_message: "Error B".to_string(),
                error_type: "ErrorB".to_string(),
                stack_trace: None,
                query_id: None,
                user_id: None,
                field_path: None,
                context: HashMap::new(),
            });
        }

        let top = aggregator.get_top_errors(1);
        assert_eq!(top.len(), 1);
        assert_eq!(top[0].count, 5);
    }

    #[test]
    fn test_affected_users_tracking() {
        let mut aggregator = ErrorAggregator::new(100);

        aggregator.record_error(ErrorOccurrence {
            timestamp: SystemTime::now(),
            error_message: "Error".to_string(),
            error_type: "Error".to_string(),
            stack_trace: None,
            query_id: None,
            user_id: Some("user-1".to_string()),
            field_path: None,
            context: HashMap::new(),
        });

        aggregator.record_error(ErrorOccurrence {
            timestamp: SystemTime::now(),
            error_message: "Error".to_string(),
            error_type: "Error".to_string(),
            stack_trace: None,
            query_id: None,
            user_id: Some("user-2".to_string()),
            field_path: None,
            context: HashMap::new(),
        });

        let groups = aggregator.get_all_groups();
        assert_eq!(groups[0].affected_users, 2);
    }

    #[test]
    fn test_statistics() {
        let mut aggregator = ErrorAggregator::new(100);

        aggregator.record_error(ErrorOccurrence {
            timestamp: SystemTime::now(),
            error_message: "Invalid input".to_string(),
            error_type: "ValidationError".to_string(),
            stack_trace: None,
            query_id: None,
            user_id: None,
            field_path: None,
            context: HashMap::new(),
        });

        aggregator.record_error(ErrorOccurrence {
            timestamp: SystemTime::now(),
            error_message: "Unauthorized".to_string(),
            error_type: "AuthError".to_string(),
            stack_trace: None,
            query_id: None,
            user_id: None,
            field_path: None,
            context: HashMap::new(),
        });

        let stats = aggregator.get_statistics();
        assert_eq!(stats.total_errors, 2);
        assert_eq!(stats.total_groups, 2);
    }

    #[test]
    fn test_clear() {
        let mut aggregator = ErrorAggregator::new(100);

        aggregator.record_error(ErrorOccurrence {
            timestamp: SystemTime::now(),
            error_message: "Error".to_string(),
            error_type: "Error".to_string(),
            stack_trace: None,
            query_id: None,
            user_id: None,
            field_path: None,
            context: HashMap::new(),
        });

        assert_eq!(aggregator.get_all_groups().len(), 1);

        aggregator.clear();
        assert_eq!(aggregator.get_all_groups().len(), 0);
    }

    #[test]
    fn test_generate_report() {
        let mut aggregator = ErrorAggregator::new(100);

        aggregator.record_error(ErrorOccurrence {
            timestamp: SystemTime::now(),
            error_message: "Test error".to_string(),
            error_type: "TestError".to_string(),
            stack_trace: None,
            query_id: None,
            user_id: None,
            field_path: None,
            context: HashMap::new(),
        });

        let report = aggregator.generate_report();
        assert!(report.contains("Error Aggregation Report"));
        assert!(report.contains("Total Errors: 1"));
    }

    #[test]
    fn test_error_rate_calculation() {
        let mut aggregator = ErrorAggregator::new(100);

        let first_time = SystemTime::now();

        aggregator.record_error(ErrorOccurrence {
            timestamp: first_time,
            error_message: "Error".to_string(),
            error_type: "Error".to_string(),
            stack_trace: None,
            query_id: None,
            user_id: None,
            field_path: None,
            context: HashMap::new(),
        });

        aggregator.record_error(ErrorOccurrence {
            timestamp: first_time + Duration::from_secs(60),
            error_message: "Error".to_string(),
            error_type: "Error".to_string(),
            stack_trace: None,
            query_id: None,
            user_id: None,
            field_path: None,
            context: HashMap::new(),
        });

        let groups = aggregator.get_all_groups();
        let rate = groups[0].error_rate();
        assert!(rate > 0.0);
    }

    #[test]
    fn test_normalize_message() {
        let msg1 = "Error with ID 12345";
        let msg2 = "Error with ID 67890";

        let norm1 = ErrorAggregator::normalize_message(msg1);
        let norm2 = ErrorAggregator::normalize_message(msg2);

        // Should normalize to same pattern
        assert_eq!(norm1, norm2);
    }

    #[test]
    fn test_max_occurrences_per_group() {
        let mut aggregator = ErrorAggregator::new(2);

        for _ in 0..5 {
            aggregator.record_error(ErrorOccurrence {
                timestamp: SystemTime::now(),
                error_message: "Error".to_string(),
                error_type: "Error".to_string(),
                stack_trace: None,
                query_id: None,
                user_id: None,
                field_path: None,
                context: HashMap::new(),
            });
        }

        let groups = aggregator.get_all_groups();
        assert_eq!(groups[0].occurrences.len(), 2); // Limited to 2
        assert_eq!(groups[0].count, 5); // But count is still 5
    }
}