torsh-profiler 0.1.2

Performance profiling and monitoring for ToRSh
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
//! Real-time Performance Dashboard
//!
//! This module provides a comprehensive real-time performance monitoring dashboard that can be
//! accessed via web interface, displaying live profiling data, alerts, analytics, and visualizations.
//!
//! The dashboard is organized into several focused modules:
//! - `types`: Core data structures and configuration types
//! - `metrics`: Performance, memory, and system metrics collection
//! - `websocket`: Real-time WebSocket streaming functionality
//! - `html`: Dashboard web interface generation
//! - `visualizations`: 3D landscapes and heatmap visualizations
//! - `alerts`: Comprehensive alert management system
//!
//! # Quick Start
//!
//! ```rust
//! use torsh_profiler::dashboard::{Dashboard, DashboardConfig, create_dashboard};
//! use torsh_profiler::{Profiler, MemoryProfiler};
//! use std::sync::Arc;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     // Create dashboard with default configuration
//!     let dashboard = create_dashboard();
//!
//!     // Or create with custom configuration
//!     let config = DashboardConfig {
//!         port: 9090,
//!         refresh_interval: 10,
//!         real_time_updates: true,
//!         max_data_points: 500,
//!         enable_stack_traces: true,
//!         custom_css: None,
//!         websocket_config: Default::default(),
//!     };
//!     let dashboard = Dashboard::new(config);
//!
//!     // Start the dashboard with profilers
//!     let profiler = Arc::new(Profiler::new());
//!     let memory_profiler = Arc::new(MemoryProfiler::new());
//!     dashboard.start(profiler, memory_profiler)?;
//!     Ok(())
//! }
//! ```
//!
//! # Features
//!
//! ## Real-time Monitoring
//! - Live performance metrics tracking
//! - Memory usage monitoring with leak detection
//! - System resource monitoring
//! - WebSocket streaming for real-time updates
//!
//! ## Advanced Visualizations
//! - 3D performance landscapes showing operation patterns over time
//! - Interactive heatmaps with multiple color schemes
//! - Customizable visualization configurations
//! - Export capabilities for external analysis tools
//!
//! ## Intelligent Alerting
//! - Configurable threshold-based alerts
//! - Automatic alert escalation and resolution
//! - Multiple severity levels (Info, Warning, Critical, Emergency)
//! - Real-time alert broadcasting to connected clients
//!
//! ## Web Interface
//! - Responsive HTML dashboard with modern styling
//! - Customizable themes and CSS
//! - Auto-refreshing data displays
//! - Mobile-friendly responsive design

// Re-export all module functionality
pub mod alerts;
pub mod html;
pub mod metrics;
pub mod types;
pub mod visualizations;
pub mod websocket;

// Re-export core types for convenience
pub use types::*;

// Re-export main dashboard functionality
pub use metrics::{
    collect_memory_metrics, collect_performance_metrics, collect_system_metrics, MetricsCollector,
};

pub use websocket::{
    handle_websocket_client, start_websocket_server, WebSocketManager, WebSocketStats,
};

pub use html::{build_html_document, generate_dashboard_html, DashboardRenderer};

pub use visualizations::{
    generate_3d_landscape, generate_performance_heatmap, PerformanceHeatmap, PerformanceLandscape,
};

pub use alerts::{
    create_alert_context, create_alert_manager, create_alert_manager_with_config, AlertConfig,
    AlertContext, AlertManager,
};

// Main Dashboard imports
use crate::{MemoryProfiler, ProfileEvent, Profiler, TorshResult};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use torsh_core::TorshError;

// =============================================================================
// Main Dashboard Implementation
// =============================================================================

/// Main Dashboard server that orchestrates all functionality
pub struct Dashboard {
    pub(crate) config: DashboardConfig,
    pub(crate) data_history: Arc<Mutex<Vec<DashboardData>>>,
    pub(crate) alerts: Arc<Mutex<Vec<DashboardAlert>>>,
    pub(crate) running: Arc<Mutex<bool>>,
    pub(crate) websocket_clients: Arc<Mutex<Vec<WebSocketClient>>>,
    pub(crate) alert_manager: Arc<Mutex<AlertManager>>,
    pub(crate) metrics_collector: Arc<MetricsCollector>,
    pub(crate) websocket_manager: Arc<WebSocketManager>,
    pub(crate) dashboard_renderer: Arc<DashboardRenderer>,
}

impl Dashboard {
    /// Create a new dashboard
    pub fn new(config: DashboardConfig) -> Self {
        let alert_config = alerts::AlertConfig::default();
        let alert_manager = AlertManager::new(alert_config);

        Self {
            config: config.clone(),
            data_history: Arc::new(Mutex::new(Vec::new())),
            alerts: Arc::new(Mutex::new(Vec::new())),
            running: Arc::new(Mutex::new(false)),
            websocket_clients: Arc::new(Mutex::new(Vec::new())),
            alert_manager: Arc::new(Mutex::new(alert_manager)),
            metrics_collector: Arc::new(MetricsCollector::new()),
            websocket_manager: Arc::new(WebSocketManager::new(config.websocket_config.clone())),
            dashboard_renderer: Arc::new(DashboardRenderer::new()),
        }
    }

    /// Start the dashboard server
    pub fn start(
        &self,
        profiler: Arc<Profiler>,
        memory_profiler: Arc<MemoryProfiler>,
    ) -> TorshResult<()> {
        {
            let mut running = self.running.lock().map_err(|_| {
                TorshError::SynchronizationError("Failed to acquire lock".to_string())
            })?;
            if *running {
                return Err(TorshError::RuntimeError(
                    "Dashboard already running".to_string(),
                ));
            }
            *running = true;
        }

        // Start data collection thread
        let data_history = Arc::clone(&self.data_history);
        let alerts = Arc::clone(&self.alerts);
        let alert_manager = Arc::clone(&self.alert_manager);
        let metrics_collector = Arc::clone(&self.metrics_collector);
        let config = self.config.clone();
        let running = Arc::clone(&self.running);
        let profiler_clone = Arc::clone(&profiler);
        let memory_profiler_clone = Arc::clone(&memory_profiler);

        thread::spawn(move || {
            Self::data_collection_loop(
                data_history,
                alerts,
                alert_manager,
                metrics_collector,
                config,
                running,
                profiler_clone,
                memory_profiler_clone,
            );
        });

        // Start WebSocket server if enabled
        if self.config.websocket_config.enabled {
            let websocket_data_history = Arc::clone(&self.data_history);
            let websocket_clients = Arc::clone(&self.websocket_clients);
            let websocket_manager = Arc::clone(&self.websocket_manager);
            let websocket_running = Arc::clone(&self.running);

            tokio::spawn(async move {
                websocket_manager
                    .start_server(websocket_data_history, websocket_clients, websocket_running)
                    .await;
            });
        }

        println!("Dashboard started on port {}", self.config.port);
        println!("Access dashboard at: http://localhost:{}", self.config.port);

        if self.config.websocket_config.enabled {
            println!(
                "WebSocket server started on port {}",
                self.config.websocket_config.port
            );
            println!(
                "WebSocket endpoint: ws://localhost:{}/ws",
                self.config.websocket_config.port
            );
        }

        Ok(())
    }

    /// Stop the dashboard server
    pub fn stop(&self) -> TorshResult<()> {
        let mut running = self
            .running
            .lock()
            .map_err(|_| TorshError::SynchronizationError("Failed to acquire lock".to_string()))?;
        *running = false;
        println!("Dashboard stopped");
        Ok(())
    }

    /// Get current dashboard data
    pub fn get_current_data(&self) -> TorshResult<Option<DashboardData>> {
        let data_history = self
            .data_history
            .lock()
            .map_err(|_| TorshError::SynchronizationError("Failed to acquire lock".to_string()))?;
        Ok(data_history.last().cloned())
    }

    /// Get data history
    pub fn get_data_history(&self) -> TorshResult<Vec<DashboardData>> {
        let data_history = self
            .data_history
            .lock()
            .map_err(|_| TorshError::SynchronizationError("Failed to acquire lock".to_string()))?;
        Ok(data_history.clone())
    }

    /// Add alert
    pub fn add_alert(&self, alert: DashboardAlert) -> TorshResult<()> {
        // Add to main alerts list
        let mut alerts = self
            .alerts
            .lock()
            .map_err(|_| TorshError::SynchronizationError("Failed to acquire lock".to_string()))?;
        alerts.push(alert.clone());

        // Keep only recent alerts
        if alerts.len() > 100 {
            alerts.remove(0);
        }

        // Also add to alert manager
        if let Ok(mut alert_manager) = self.alert_manager.lock() {
            let _ = alert_manager.add_alert(alert);
        }

        Ok(())
    }

    /// Get active alerts
    pub fn get_active_alerts(&self) -> TorshResult<Vec<DashboardAlert>> {
        let alerts = self
            .alerts
            .lock()
            .map_err(|_| TorshError::SynchronizationError("Failed to acquire lock".to_string()))?;
        Ok(alerts.iter().filter(|a| !a.resolved).cloned().collect())
    }

    /// Generate dashboard HTML
    pub fn generate_dashboard_html(&self) -> TorshResult<String> {
        let current_data = self.get_current_data()?.unwrap_or_else(create_default_data);
        let active_alerts = self.get_active_alerts()?;
        let theme = DashboardTheme::default();

        self.dashboard_renderer.generate_dashboard_html(
            &current_data,
            &active_alerts,
            &self.config,
            &theme,
        )
    }

    /// Export dashboard data to JSON
    pub fn export_data_json(&self, file_path: &str) -> TorshResult<()> {
        let data_history = self.get_data_history()?;
        let active_alerts = self.get_active_alerts()?;

        let export_data = serde_json::json!({
            "data_history": data_history,
            "active_alerts": active_alerts,
            "config": self.config
        });

        std::fs::write(
            file_path,
            serde_json::to_string_pretty(&export_data).map_err(|e| {
                TorshError::SerializationError(format!("Failed to serialize dashboard data: {e}"))
            })?,
        )
        .map_err(|e| TorshError::IoError(format!("Failed to write dashboard data: {e}")))?;

        Ok(())
    }

    /// Get WebSocket connection statistics
    pub fn get_websocket_stats(&self) -> TorshResult<WebSocketStats> {
        let clients = self
            .websocket_clients
            .lock()
            .map_err(|_| TorshError::SynchronizationError("Failed to acquire lock".to_string()))?;

        Ok(WebSocketStats {
            connected_clients: clients.len(),
            total_connections: clients.len(), // Simplified - would need persistent counter
            uptime_seconds: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
            subscription_stats: std::collections::HashMap::new(),
            active_clients: clients.len(),
        })
    }

    /// Broadcast visualization data to connected clients
    pub fn broadcast_visualization(
        &self,
        visualization_type: &str,
        data: &str,
    ) -> TorshResult<usize> {
        self.websocket_manager.broadcast_visualization(
            &self.websocket_clients,
            visualization_type,
            data,
        )
    }

    /// Broadcast real-time 3D performance landscape
    pub fn broadcast_3d_landscape(
        &self,
        profiler: &Profiler,
        config: &VisualizationConfig,
    ) -> TorshResult<usize> {
        let mut landscape = PerformanceLandscape::new(config.clone());
        landscape.generate_from_profiler(profiler)?;

        let landscape_data = serde_json::to_string(&landscape.get_points()).map_err(|e| {
            TorshError::SerializationError(format!("Failed to serialize landscape points: {e}"))
        })?;

        self.broadcast_visualization("3d_landscape", &landscape_data)
    }

    /// Broadcast real-time performance heatmap
    pub fn broadcast_heatmap(
        &self,
        profiler: &Profiler,
        config: &VisualizationConfig,
        width: usize,
        height: usize,
    ) -> TorshResult<usize> {
        let mut heatmap = PerformanceHeatmap::new(config.clone(), width, height);
        heatmap.generate_from_profiler(profiler)?;

        let heatmap_data = serde_json::to_string(&heatmap.get_cells()).map_err(|e| {
            TorshError::SerializationError(format!("Failed to serialize heatmap cells: {e}"))
        })?;

        self.broadcast_visualization("heatmap", &heatmap_data)
    }

    /// Broadcast custom alerts to connected clients
    pub fn broadcast_alert(&self, alert: &DashboardAlert) -> TorshResult<usize> {
        if let Ok(alert_manager) = self.alert_manager.lock() {
            alert_manager.broadcast_alert(alert, &self.websocket_clients)
        } else {
            Err(TorshError::SynchronizationError(
                "Failed to acquire alert manager lock".to_string(),
            ))
        }
    }

    /// Data collection loop
    fn data_collection_loop(
        data_history: Arc<Mutex<Vec<DashboardData>>>,
        _alerts: Arc<Mutex<Vec<DashboardAlert>>>,
        alert_manager: Arc<Mutex<AlertManager>>,
        metrics_collector: Arc<MetricsCollector>,
        config: DashboardConfig,
        running: Arc<Mutex<bool>>,
        profiler: Arc<Profiler>,
        memory_profiler: Arc<MemoryProfiler>,
    ) {
        while {
            let is_running = running.lock().map(|r| *r).unwrap_or(false);
            is_running
        } {
            // Collect current metrics
            if let Ok(data) = metrics_collector.collect_dashboard_data(&profiler, &memory_profiler)
            {
                if let Ok(mut history) = data_history.lock() {
                    history.push(data.clone());

                    // Keep only recent data points
                    if history.len() > config.max_data_points {
                        history.remove(0);
                    }
                }

                // Generate alerts based on current metrics
                if let Ok(mut alert_mgr) = alert_manager.lock() {
                    if let Ok(alert_context) = create_alert_context(&profiler, &memory_profiler) {
                        let _ = alert_mgr.generate_alerts(alert_context);
                    }
                }
            }

            // Sleep for refresh interval
            thread::sleep(Duration::from_secs(config.refresh_interval));
        }
    }
}

// =============================================================================
// Convenience Functions
// =============================================================================

/// Create a new dashboard with default configuration
pub fn create_dashboard() -> Dashboard {
    Dashboard::new(DashboardConfig::default())
}

/// Create a new dashboard with custom configuration
pub fn create_dashboard_with_config(config: DashboardConfig) -> Dashboard {
    Dashboard::new(config)
}

/// Export dashboard HTML to file
pub fn export_dashboard_html(
    profiler: &Profiler,
    memory_profiler: &MemoryProfiler,
    file_path: &str,
) -> TorshResult<()> {
    let dashboard = create_dashboard();
    let html = dashboard.generate_dashboard_html()?;

    std::fs::write(file_path, html)
        .map_err(|e| TorshError::IoError(format!("Failed to write dashboard HTML: {e}")))?;

    Ok(())
}

/// Create default dashboard data for empty state
pub fn create_default_data() -> DashboardData {
    DashboardData {
        timestamp: SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs(),
        performance_metrics: PerformanceMetrics {
            total_operations: 0,
            average_duration_ms: 0.0,
            operations_per_second: 0.0,
            total_flops: 0,
            gflops_per_second: 0.0,
            cpu_utilization: 0.0,
            thread_count: 0,
        },
        memory_metrics: MemoryMetrics {
            current_usage_mb: 0.0,
            peak_usage_mb: 0.0,
            total_allocations: 0,
            total_deallocations: 0,
            active_allocations: 0,
            fragmentation_ratio: 0.0,
            allocation_rate: 0.0,
        },
        system_metrics: SystemMetrics {
            uptime_seconds: 0,
            load_average: 0.0,
            available_memory_mb: 0.0,
            disk_usage_percent: 0.0,
            network_io_mbps: 0.0,
        },
        alerts: Vec::new(),
        top_operations: Vec::new(),
    }
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{memory::MemoryProfiler, ProfileEvent};

    #[test]
    fn test_dashboard_creation() {
        let dashboard = create_dashboard();
        assert_eq!(dashboard.config.port, 8080);
        assert_eq!(dashboard.config.refresh_interval, 5);
    }

    #[test]
    fn test_dashboard_config() {
        let config = DashboardConfig {
            port: 9090,
            refresh_interval: 10,
            real_time_updates: false,
            max_data_points: 500,
            enable_stack_traces: true,
            custom_css: Some("body { background: red; }".to_string()),
            websocket_config: WebSocketConfig::default(),
        };

        let dashboard = create_dashboard_with_config(config.clone());
        assert_eq!(dashboard.config.port, 9090);
        assert_eq!(dashboard.config.refresh_interval, 10);
        assert!(!dashboard.config.real_time_updates);
    }

    #[test]
    fn test_dashboard_alert() {
        let dashboard = create_dashboard();

        let alert = DashboardAlert {
            id: "test_alert".to_string(),
            severity: DashboardAlertSeverity::Warning,
            title: "Test Alert".to_string(),
            message: "This is a test alert".to_string(),
            timestamp: 12345,
            resolved: false,
        };

        dashboard
            .add_alert(alert)
            .expect("add alert should succeed");
        let active_alerts = dashboard
            .get_active_alerts()
            .expect("alert retrieval should succeed");
        assert_eq!(active_alerts.len(), 1);
    }

    #[test]
    fn test_dashboard_html_generation() {
        let dashboard = create_dashboard();
        let html = dashboard
            .generate_dashboard_html()
            .expect("dashboard HTML generation should succeed");

        assert!(html.contains("ToRSh Performance Dashboard"));
        assert!(html.contains("Performance Metrics"));
        assert!(html.contains("Memory Metrics"));
        assert!(html.contains("Active Alerts"));
        assert!(html.contains("Top Operations"));
    }

    #[test]
    fn test_default_data_creation() {
        let data = create_default_data();
        assert_eq!(data.performance_metrics.total_operations, 0);
        assert_eq!(data.memory_metrics.current_usage_mb, 0.0);
        assert_eq!(data.alerts.len(), 0);
        assert_eq!(data.top_operations.len(), 0);
    }

    #[test]
    fn test_websocket_stats() {
        let dashboard = create_dashboard();
        let stats = dashboard
            .get_websocket_stats()
            .expect("WebSocket statistics retrieval should succeed");
        assert_eq!(stats.connected_clients, 0);
        assert_eq!(stats.total_connections, 0);
    }

    #[test]
    fn test_data_export() {
        let dashboard = create_dashboard();

        // Add some test data
        let alert = DashboardAlert {
            id: "test_alert".to_string(),
            severity: DashboardAlertSeverity::Info,
            title: "Test".to_string(),
            message: "Test message".to_string(),
            timestamp: 12345,
            resolved: false,
        };
        dashboard
            .add_alert(alert)
            .expect("add alert should succeed");

        // Test export
        let temp_file = std::env::temp_dir().join("dashboard_export_test.json");
        let temp_str = temp_file.display().to_string();
        dashboard
            .export_data_json(&temp_str)
            .expect("Failed to export dashboard data to JSON");

        // Verify file exists and contains data
        let contents = std::fs::read_to_string(&temp_file).expect("Failed to read exported JSON");
        assert!(contents.contains("test_alert"));
        assert!(contents.contains("active_alerts"));
        assert!(contents.contains("config"));

        // Cleanup
        let _ = std::fs::remove_file(&temp_file);
    }
}