pandrs 0.3.0

A high-performance DataFrame library for Rust, providing pandas-like API with advanced features including SIMD optimization, parallel processing, and distributed computing capabilities
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
//! Alerting System for Analytics Dashboard
//!
//! Provides configurable alerts based on metric thresholds.

use super::{Dashboard, MetricStats, OperationCategory};
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant};

/// Alert severity levels
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum AlertSeverity {
    /// Informational alert
    Info,
    /// Warning level
    Warning,
    /// Critical level
    Critical,
}

impl std::fmt::Display for AlertSeverity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AlertSeverity::Info => write!(f, "INFO"),
            AlertSeverity::Warning => write!(f, "WARNING"),
            AlertSeverity::Critical => write!(f, "CRITICAL"),
        }
    }
}

/// Comparison operators for thresholds
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ThresholdOperator {
    /// Greater than
    GreaterThan,
    /// Greater than or equal
    GreaterThanOrEqual,
    /// Less than
    LessThan,
    /// Less than or equal
    LessThanOrEqual,
    /// Equal
    Equal,
    /// Not equal
    NotEqual,
}

impl ThresholdOperator {
    /// Evaluate the operator
    pub fn evaluate(&self, value: f64, threshold: f64) -> bool {
        match self {
            ThresholdOperator::GreaterThan => value > threshold,
            ThresholdOperator::GreaterThanOrEqual => value >= threshold,
            ThresholdOperator::LessThan => value < threshold,
            ThresholdOperator::LessThanOrEqual => value <= threshold,
            ThresholdOperator::Equal => (value - threshold).abs() < f64::EPSILON,
            ThresholdOperator::NotEqual => (value - threshold).abs() >= f64::EPSILON,
        }
    }
}

/// Alert rule definition
#[derive(Debug, Clone)]
pub struct AlertRule {
    /// Rule name
    pub name: String,
    /// Description
    pub description: String,
    /// Metric to monitor
    pub metric: AlertMetric,
    /// Threshold operator
    pub operator: ThresholdOperator,
    /// Threshold value
    pub threshold: f64,
    /// Alert severity
    pub severity: AlertSeverity,
    /// Minimum duration before alerting (debounce)
    pub duration: Duration,
    /// Whether the rule is enabled
    pub enabled: bool,
    /// Labels/tags
    pub labels: HashMap<String, String>,
}

impl AlertRule {
    /// Create a new alert rule
    pub fn new(name: impl Into<String>, metric: AlertMetric) -> Self {
        AlertRule {
            name: name.into(),
            description: String::new(),
            metric,
            operator: ThresholdOperator::GreaterThan,
            threshold: 0.0,
            severity: AlertSeverity::Warning,
            duration: Duration::from_secs(0),
            enabled: true,
            labels: HashMap::new(),
        }
    }

    /// Set description
    pub fn with_description(mut self, desc: impl Into<String>) -> Self {
        self.description = desc.into();
        self
    }

    /// Set operator and threshold
    pub fn when(mut self, operator: ThresholdOperator, threshold: f64) -> Self {
        self.operator = operator;
        self.threshold = threshold;
        self
    }

    /// Set severity
    pub fn with_severity(mut self, severity: AlertSeverity) -> Self {
        self.severity = severity;
        self
    }

    /// Set duration
    pub fn for_duration(mut self, duration: Duration) -> Self {
        self.duration = duration;
        self
    }

    /// Add a label
    pub fn with_label(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.labels.insert(key.into(), value.into());
        self
    }

    /// Enable/disable the rule
    pub fn enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }
}

/// Metrics that can be monitored for alerts
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AlertMetric {
    /// Error rate (0-1)
    ErrorRate,
    /// Average latency in microseconds
    AvgLatency,
    /// P99 latency in microseconds
    P99Latency,
    /// Operations per second
    OpsPerSecond,
    /// Rows per second
    RowsPerSecond,
    /// Bytes per second
    BytesPerSecond,
    /// Category-specific latency
    CategoryLatency(OperationCategory),
    /// Category-specific error rate
    CategoryErrorRate(OperationCategory),
    /// Custom metric by name
    Custom(String),
}

/// An active alert instance
#[derive(Debug, Clone)]
pub struct ActiveAlert {
    /// The rule that triggered this alert
    pub rule_name: String,
    /// Current value that triggered the alert
    pub current_value: f64,
    /// Threshold value
    pub threshold: f64,
    /// Severity
    pub severity: AlertSeverity,
    /// When the alert first triggered
    pub triggered_at: Instant,
    /// Alert message
    pub message: String,
}

impl ActiveAlert {
    /// Format as a string
    pub fn format(&self) -> String {
        format!(
            "[{}] {}: {} (current: {:.2}, threshold: {:.2})",
            self.severity, self.rule_name, self.message, self.current_value, self.threshold
        )
    }
}

/// Alert state for tracking firing duration
#[derive(Debug)]
struct AlertState {
    /// When the condition first became true
    first_triggered: Option<Instant>,
    /// Whether alert is currently firing
    firing: bool,
}

/// Alert manager for processing rules
#[derive(Debug)]
pub struct AlertManager {
    /// Configured rules
    rules: RwLock<Vec<AlertRule>>,
    /// Current state per rule
    states: RwLock<HashMap<String, AlertState>>,
    /// Active alerts
    active: RwLock<Vec<ActiveAlert>>,
    /// Alert handlers
    handlers: RwLock<Vec<Box<dyn AlertHandler>>>,
    /// Whether alerting is enabled
    enabled: bool,
}

impl AlertManager {
    /// Create a new alert manager
    pub fn new() -> Self {
        AlertManager {
            rules: RwLock::new(Vec::new()),
            states: RwLock::new(HashMap::new()),
            active: RwLock::new(Vec::new()),
            handlers: RwLock::new(Vec::new()),
            enabled: true,
        }
    }

    /// Add an alert rule
    pub fn add_rule(&self, rule: AlertRule) {
        if let Ok(mut rules) = self.rules.write() {
            if let Ok(mut states) = self.states.write() {
                states.insert(
                    rule.name.clone(),
                    AlertState {
                        first_triggered: None,
                        firing: false,
                    },
                );
            }
            rules.push(rule);
        }
    }

    /// Remove a rule by name
    pub fn remove_rule(&self, name: &str) {
        if let Ok(mut rules) = self.rules.write() {
            rules.retain(|r| r.name != name);
        }
        if let Ok(mut states) = self.states.write() {
            states.remove(name);
        }
    }

    /// Add an alert handler
    pub fn add_handler(&self, handler: Box<dyn AlertHandler>) {
        if let Ok(mut handlers) = self.handlers.write() {
            handlers.push(handler);
        }
    }

    /// Evaluate all rules against current metrics
    pub fn evaluate(&self, dashboard: &Dashboard) {
        if !self.enabled {
            return;
        }

        let rules = match self.rules.read() {
            Ok(r) => r.clone(),
            Err(_) => return,
        };

        for rule in rules.iter().filter(|r| r.enabled) {
            let value = self.get_metric_value(dashboard, &rule.metric);

            if let Some(value) = value {
                self.evaluate_rule(rule, value);
            }
        }
    }

    /// Get the current value of a metric
    fn get_metric_value(&self, dashboard: &Dashboard, metric: &AlertMetric) -> Option<f64> {
        match metric {
            AlertMetric::ErrorRate => Some(dashboard.error_rate()),
            AlertMetric::AvgLatency => Some(dashboard.avg_latency_us()),
            AlertMetric::P99Latency => Some(dashboard.p99_latency_us()),
            AlertMetric::OpsPerSecond => Some(dashboard.ops_per_second()),
            AlertMetric::RowsPerSecond => Some(dashboard.rows_per_second()),
            AlertMetric::BytesPerSecond => Some(dashboard.bytes_per_second()),
            AlertMetric::CategoryLatency(cat) => {
                let stats = dashboard.category_stats(*cat);
                if stats.count > 0 {
                    Some(stats.mean)
                } else {
                    None
                }
            }
            AlertMetric::CategoryErrorRate(_cat) => {
                // Would need to track per-category error rates
                None
            }
            AlertMetric::Custom(name) => dashboard.metrics().get(name).map(|m| m.current()),
        }
    }

    /// Evaluate a single rule
    fn evaluate_rule(&self, rule: &AlertRule, value: f64) {
        let condition_met = rule.operator.evaluate(value, rule.threshold);

        let mut states = match self.states.write() {
            Ok(s) => s,
            Err(_) => return,
        };

        let state = states.entry(rule.name.clone()).or_insert(AlertState {
            first_triggered: None,
            firing: false,
        });

        if condition_met {
            let now = Instant::now();

            if state.first_triggered.is_none() {
                state.first_triggered = Some(now);
            }

            // Check if duration threshold is met
            let duration_met = state
                .first_triggered
                .map(|t| now.duration_since(t) >= rule.duration)
                .unwrap_or(false);

            if duration_met && !state.firing {
                // Fire the alert
                state.firing = true;
                drop(states); // Release lock before calling handlers

                let alert = ActiveAlert {
                    rule_name: rule.name.clone(),
                    current_value: value,
                    threshold: rule.threshold,
                    severity: rule.severity,
                    triggered_at: now,
                    message: rule.description.clone(),
                };

                self.fire_alert(alert);
            }
        } else {
            // Condition no longer met
            if state.firing {
                // Resolve the alert
                state.firing = false;
                let rule_name = rule.name.clone();
                drop(states);
                self.resolve_alert(&rule_name);
            } else {
                state.first_triggered = None;
            }
        }
    }

    /// Fire an alert
    fn fire_alert(&self, alert: ActiveAlert) {
        // Add to active alerts
        if let Ok(mut active) = self.active.write() {
            active.push(alert.clone());
        }

        // Call handlers
        if let Ok(handlers) = self.handlers.read() {
            for handler in handlers.iter() {
                handler.on_alert(&alert);
            }
        }
    }

    /// Resolve an alert
    fn resolve_alert(&self, rule_name: &str) {
        // Remove from active alerts
        if let Ok(mut active) = self.active.write() {
            active.retain(|a| a.rule_name != rule_name);
        }

        // Call handlers
        if let Ok(handlers) = self.handlers.read() {
            for handler in handlers.iter() {
                handler.on_resolve(rule_name);
            }
        }
    }

    /// Get all active alerts
    pub fn active_alerts(&self) -> Vec<ActiveAlert> {
        self.active.read().map(|a| a.clone()).unwrap_or_default()
    }

    /// Get count of active alerts by severity
    pub fn alert_counts(&self) -> HashMap<AlertSeverity, usize> {
        let mut counts = HashMap::new();
        counts.insert(AlertSeverity::Info, 0);
        counts.insert(AlertSeverity::Warning, 0);
        counts.insert(AlertSeverity::Critical, 0);

        if let Ok(active) = self.active.read() {
            for alert in active.iter() {
                *counts.entry(alert.severity).or_insert(0) += 1;
            }
        }

        counts
    }

    /// Check if there are any critical alerts
    pub fn has_critical(&self) -> bool {
        self.active
            .read()
            .map(|a| {
                a.iter()
                    .any(|alert| alert.severity == AlertSeverity::Critical)
            })
            .unwrap_or(false)
    }

    /// Clear all active alerts
    pub fn clear_all(&self) {
        if let Ok(mut active) = self.active.write() {
            active.clear();
        }
        if let Ok(mut states) = self.states.write() {
            for state in states.values_mut() {
                state.firing = false;
                state.first_triggered = None;
            }
        }
    }
}

impl Default for AlertManager {
    fn default() -> Self {
        Self::new()
    }
}

/// Trait for alert handlers
pub trait AlertHandler: Send + Sync + std::fmt::Debug {
    /// Called when an alert fires
    fn on_alert(&self, alert: &ActiveAlert);

    /// Called when an alert is resolved
    fn on_resolve(&self, rule_name: &str);
}

/// Simple logging alert handler
#[derive(Debug)]
pub struct LoggingAlertHandler {
    /// Prefix for log messages
    prefix: String,
}

impl LoggingAlertHandler {
    /// Create a new logging handler
    pub fn new(prefix: impl Into<String>) -> Self {
        LoggingAlertHandler {
            prefix: prefix.into(),
        }
    }
}

impl AlertHandler for LoggingAlertHandler {
    fn on_alert(&self, alert: &ActiveAlert) {
        log::warn!("{} ALERT: {}", self.prefix, alert.format());
    }

    fn on_resolve(&self, rule_name: &str) {
        log::info!("{} RESOLVED: {}", self.prefix, rule_name);
    }
}

/// Create common alert rules
pub fn create_default_rules() -> Vec<AlertRule> {
    vec![
        AlertRule::new("high_error_rate", AlertMetric::ErrorRate)
            .with_description("Error rate is above 5%")
            .when(ThresholdOperator::GreaterThan, 0.05)
            .with_severity(AlertSeverity::Warning)
            .for_duration(Duration::from_secs(60)),
        AlertRule::new("critical_error_rate", AlertMetric::ErrorRate)
            .with_description("Error rate is above 20%")
            .when(ThresholdOperator::GreaterThan, 0.20)
            .with_severity(AlertSeverity::Critical)
            .for_duration(Duration::from_secs(30)),
        AlertRule::new("high_latency", AlertMetric::P99Latency)
            .with_description("P99 latency exceeds 1 second")
            .when(ThresholdOperator::GreaterThan, 1_000_000.0)
            .with_severity(AlertSeverity::Warning)
            .for_duration(Duration::from_secs(60)),
        AlertRule::new("very_high_latency", AlertMetric::P99Latency)
            .with_description("P99 latency exceeds 5 seconds")
            .when(ThresholdOperator::GreaterThan, 5_000_000.0)
            .with_severity(AlertSeverity::Critical)
            .for_duration(Duration::from_secs(30)),
    ]
}

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

    #[test]
    fn test_threshold_operators() {
        assert!(ThresholdOperator::GreaterThan.evaluate(10.0, 5.0));
        assert!(!ThresholdOperator::GreaterThan.evaluate(5.0, 10.0));

        assert!(ThresholdOperator::LessThan.evaluate(5.0, 10.0));
        assert!(!ThresholdOperator::LessThan.evaluate(10.0, 5.0));

        assert!(ThresholdOperator::GreaterThanOrEqual.evaluate(10.0, 10.0));
        assert!(ThresholdOperator::LessThanOrEqual.evaluate(10.0, 10.0));
    }

    #[test]
    fn test_alert_rule_builder() {
        let rule = AlertRule::new("test", AlertMetric::ErrorRate)
            .with_description("Test alert")
            .when(ThresholdOperator::GreaterThan, 0.1)
            .with_severity(AlertSeverity::Critical)
            .for_duration(Duration::from_secs(60))
            .with_label("team", "backend");

        assert_eq!(rule.name, "test");
        assert_eq!(rule.threshold, 0.1);
        assert_eq!(rule.severity, AlertSeverity::Critical);
        assert_eq!(rule.duration, Duration::from_secs(60));
        assert_eq!(rule.labels.get("team"), Some(&"backend".to_string()));
    }

    #[test]
    fn test_alert_manager() {
        let manager = AlertManager::new();

        manager.add_rule(
            AlertRule::new("test_error_rate", AlertMetric::ErrorRate)
                .when(ThresholdOperator::GreaterThan, 0.1)
                .with_severity(AlertSeverity::Warning),
        );

        let dashboard = Dashboard::default();

        // Initial evaluation - no alerts
        manager.evaluate(&dashboard);
        assert!(manager.active_alerts().is_empty());
    }

    #[test]
    fn test_default_rules() {
        let rules = create_default_rules();
        assert!(!rules.is_empty());

        // Check we have both warning and critical rules
        let has_warning = rules.iter().any(|r| r.severity == AlertSeverity::Warning);
        let has_critical = rules.iter().any(|r| r.severity == AlertSeverity::Critical);

        assert!(has_warning);
        assert!(has_critical);
    }

    #[test]
    fn test_alert_severity_ordering() {
        assert!(AlertSeverity::Info < AlertSeverity::Warning);
        assert!(AlertSeverity::Warning < AlertSeverity::Critical);
    }

    #[test]
    fn test_active_alert_format() {
        let alert = ActiveAlert {
            rule_name: "test_rule".to_string(),
            current_value: 0.15,
            threshold: 0.1,
            severity: AlertSeverity::Warning,
            triggered_at: Instant::now(),
            message: "Error rate too high".to_string(),
        };

        let formatted = alert.format();
        assert!(formatted.contains("WARNING"));
        assert!(formatted.contains("test_rule"));
    }
}