1use super::{AnalyticsError, TimeRange};
10use crate::storage::AuthStorage;
11use serde::{Deserialize, Serialize};
12use std::collections::HashMap;
13use std::sync::Arc;
14
15#[derive(Debug, Clone, Serialize, Deserialize)]
17pub struct DashboardConfig {
18 pub refresh_interval_seconds: u32,
20
21 pub default_time_range_hours: u32,
23
24 pub real_time_updates: bool,
26
27 pub max_chart_points: usize,
29
30 pub alerts_enabled: bool,
32}
33
34impl Default for DashboardConfig {
35 fn default() -> Self {
36 Self {
37 refresh_interval_seconds: 30,
38 default_time_range_hours: 24,
39 real_time_updates: true,
40 max_chart_points: 100,
41 alerts_enabled: true,
42 }
43 }
44}
45
46#[derive(Debug, Clone, Serialize, Deserialize)]
48pub enum WidgetType {
49 LineChart,
51 BarChart,
53 PieChart,
55 MetricCard,
57 Table,
59 HeatMap,
61 Gauge,
63}
64
65#[derive(Debug, Clone, Serialize, Deserialize)]
67pub struct DashboardWidget {
68 pub id: String,
70
71 pub title: String,
73
74 pub widget_type: WidgetType,
76
77 pub data_source: DataSource,
79
80 pub time_range: TimeRange,
82
83 pub layout: WidgetLayout,
85
86 pub refresh_interval: Option<u32>,
88
89 pub alert_thresholds: Option<AlertThresholds>,
91}
92
93#[derive(Debug, Clone, Serialize, Deserialize)]
95pub struct WidgetLayout {
96 pub x: u32,
98
99 pub y: u32,
101
102 pub width: u32,
104
105 pub height: u32,
107}
108
109#[derive(Debug, Clone, Serialize, Deserialize)]
111pub enum DataSource {
112 RoleUsage {
114 role_id: Option<String>,
115 group_by: Option<String>,
116 },
117 PermissionUsage {
119 permission_id: Option<String>,
120 group_by: Option<String>,
121 },
122 Compliance { metric_type: String },
124 Performance { metric_type: String },
126 EventCount {
128 event_type: Option<String>,
129 filters: HashMap<String, String>,
130 },
131 Custom {
133 query: String,
134 parameters: HashMap<String, String>,
135 },
136}
137
138#[derive(Debug, Clone, Serialize, Deserialize)]
140pub struct AlertThresholds {
141 pub warning: f64,
143
144 pub critical: f64,
146
147 pub comparison: ThresholdComparison,
149}
150
151#[derive(Debug, Clone, Serialize, Deserialize)]
153pub enum ThresholdComparison {
154 GreaterThan,
155 LessThan,
156 Equals,
157 NotEquals,
158}
159
160#[derive(Debug, Clone, Serialize, Deserialize)]
162pub struct DataPoint {
163 pub timestamp: Option<chrono::DateTime<chrono::Utc>>,
165
166 pub label: Option<String>,
168
169 pub value: f64,
171
172 pub metadata: HashMap<String, String>,
174}
175
176#[derive(Debug, Clone, Serialize, Deserialize)]
178pub struct ChartSeries {
179 pub name: String,
181
182 pub data: Vec<DataPoint>,
184
185 pub color: Option<String>,
187
188 pub series_type: Option<String>,
190}
191
192#[derive(Debug, Clone, Serialize, Deserialize)]
194pub struct WidgetData {
195 pub widget_id: String,
197
198 pub updated_at: chrono::DateTime<chrono::Utc>,
200
201 pub series: Vec<ChartSeries>,
203
204 pub summary: Option<WidgetSummary>,
206
207 pub alert_status: AlertStatus,
209}
210
211#[derive(Debug, Clone, Serialize, Deserialize)]
213pub struct WidgetSummary {
214 pub total: f64,
216
217 pub average: f64,
219
220 pub minimum: f64,
222
223 pub maximum: f64,
225
226 pub change_percent: Option<f64>,
228}
229
230#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
232pub enum AlertStatus {
233 Normal,
234 Warning,
235 Critical,
236 Unknown,
237}
238
239#[derive(Debug, Clone, Serialize, Deserialize)]
241pub struct Dashboard {
242 pub id: String,
244
245 pub title: String,
247
248 pub description: Option<String>,
250
251 pub config: DashboardConfig,
253
254 pub widgets: Vec<DashboardWidget>,
256
257 pub tags: Vec<String>,
259
260 pub created_at: chrono::DateTime<chrono::Utc>,
262
263 pub updated_at: chrono::DateTime<chrono::Utc>,
265}
266
267pub struct DashboardManager {
269 config: DashboardConfig,
270 storage: Arc<dyn AuthStorage>,
271 dashboards: HashMap<String, Dashboard>,
272}
273
274impl DashboardManager {
275 pub fn new(config: DashboardConfig, storage: Arc<dyn AuthStorage>) -> Self {
277 Self {
278 config,
279 storage,
280 dashboards: HashMap::new(),
281 }
282 }
283
284 pub async fn create_dashboard(&mut self, dashboard: Dashboard) -> Result<(), AnalyticsError> {
286 self.dashboards.insert(dashboard.id.clone(), dashboard);
287 Ok(())
288 }
289
290 pub async fn get_dashboard(
292 &self,
293 dashboard_id: &str,
294 ) -> Result<Option<Dashboard>, AnalyticsError> {
295 Ok(self.dashboards.get(dashboard_id).cloned())
296 }
297
298 pub async fn list_dashboards(&self) -> Result<Vec<Dashboard>, AnalyticsError> {
300 Ok(self.dashboards.values().cloned().collect())
301 }
302
303 pub async fn update_dashboard(&mut self, dashboard: Dashboard) -> Result<(), AnalyticsError> {
305 let mut updated_dashboard = dashboard;
306 updated_dashboard.updated_at = chrono::Utc::now();
307 self.dashboards
308 .insert(updated_dashboard.id.clone(), updated_dashboard);
309 Ok(())
310 }
311
312 pub async fn delete_dashboard(&mut self, dashboard_id: &str) -> Result<bool, AnalyticsError> {
314 Ok(self.dashboards.remove(dashboard_id).is_some())
315 }
316
317 pub async fn get_widget_data(
319 &self,
320 widget: &DashboardWidget,
321 ) -> Result<WidgetData, AnalyticsError> {
322 let series = match &widget.data_source {
323 DataSource::RoleUsage { role_id, group_by } => {
324 self.get_role_usage_series(
325 role_id.as_deref(),
326 group_by.as_deref(),
327 &widget.time_range,
328 )
329 .await?
330 }
331 DataSource::PermissionUsage {
332 permission_id,
333 group_by,
334 } => {
335 self.get_permission_usage_series(
336 permission_id.as_deref(),
337 group_by.as_deref(),
338 &widget.time_range,
339 )
340 .await?
341 }
342 DataSource::Compliance { metric_type } => {
343 self.get_compliance_series(metric_type, &widget.time_range)
344 .await?
345 }
346 DataSource::Performance { metric_type } => {
347 self.get_performance_series(metric_type, &widget.time_range)
348 .await?
349 }
350 DataSource::EventCount {
351 event_type,
352 filters,
353 } => {
354 self.get_event_count_series(event_type.as_deref(), filters, &widget.time_range)
355 .await?
356 }
357 DataSource::Custom { query, parameters } => {
358 self.get_custom_series(query, parameters, &widget.time_range)
359 .await?
360 }
361 };
362
363 let summary = self.calculate_widget_summary(&series);
364 let alert_status = self.check_alert_status(&summary, &widget.alert_thresholds);
365
366 Ok(WidgetData {
367 widget_id: widget.id.clone(),
368 updated_at: chrono::Utc::now(),
369 series,
370 summary: Some(summary),
371 alert_status,
372 })
373 }
374
375 pub async fn create_rbac_overview_dashboard(&mut self) -> Result<String, AnalyticsError> {
377 let dashboard_id = uuid::Uuid::new_v4().to_string();
378
379 let dashboard = Dashboard {
380 id: dashboard_id.clone(),
381 title: "RBAC Overview".to_string(),
382 description: Some("Comprehensive RBAC system overview".to_string()),
383 config: self.config.clone(),
384 widgets: vec![
385 DashboardWidget {
387 id: "permission_checks_timeline".to_string(),
388 title: "Permission Checks Over Time".to_string(),
389 widget_type: WidgetType::LineChart,
390 data_source: DataSource::EventCount {
391 event_type: Some("PermissionCheck".to_string()),
392 filters: HashMap::new(),
393 },
394 time_range: TimeRange::last_hours(24),
395 layout: WidgetLayout {
396 x: 0,
397 y: 0,
398 width: 6,
399 height: 3,
400 },
401 refresh_interval: None,
402 alert_thresholds: None,
403 },
404 DashboardWidget {
406 id: "role_usage_distribution".to_string(),
407 title: "Role Usage Distribution".to_string(),
408 widget_type: WidgetType::PieChart,
409 data_source: DataSource::RoleUsage {
410 role_id: None,
411 group_by: Some("role_name".to_string()),
412 },
413 time_range: TimeRange::last_hours(24),
414 layout: WidgetLayout {
415 x: 6,
416 y: 0,
417 width: 6,
418 height: 3,
419 },
420 refresh_interval: None,
421 alert_thresholds: None,
422 },
423 DashboardWidget {
425 id: "compliance_score".to_string(),
426 title: "Compliance Score".to_string(),
427 widget_type: WidgetType::Gauge,
428 data_source: DataSource::Compliance {
429 metric_type: "overall_compliance".to_string(),
430 },
431 time_range: TimeRange::last_hours(24),
432 layout: WidgetLayout {
433 x: 0,
434 y: 3,
435 width: 3,
436 height: 3,
437 },
438 refresh_interval: None,
439 alert_thresholds: Some(AlertThresholds {
440 warning: 85.0,
441 critical: 70.0,
442 comparison: ThresholdComparison::LessThan,
443 }),
444 },
445 DashboardWidget {
447 id: "avg_response_time".to_string(),
448 title: "Average Response Time".to_string(),
449 widget_type: WidgetType::MetricCard,
450 data_source: DataSource::Performance {
451 metric_type: "avg_permission_check_latency".to_string(),
452 },
453 time_range: TimeRange::last_hours(24),
454 layout: WidgetLayout {
455 x: 3,
456 y: 3,
457 width: 3,
458 height: 3,
459 },
460 refresh_interval: None,
461 alert_thresholds: Some(AlertThresholds {
462 warning: 100.0,
463 critical: 200.0,
464 comparison: ThresholdComparison::GreaterThan,
465 }),
466 },
467 DashboardWidget {
469 id: "top_resources".to_string(),
470 title: "Top Accessed Resources".to_string(),
471 widget_type: WidgetType::BarChart,
472 data_source: DataSource::EventCount {
473 event_type: Some("PermissionCheck".to_string()),
474 filters: HashMap::from([("result".to_string(), "Success".to_string())]),
475 },
476 time_range: TimeRange::last_hours(24),
477 layout: WidgetLayout {
478 x: 6,
479 y: 3,
480 width: 6,
481 height: 3,
482 },
483 refresh_interval: None,
484 alert_thresholds: None,
485 },
486 ],
487 tags: vec!["rbac".to_string(), "overview".to_string()],
488 created_at: chrono::Utc::now(),
489 updated_at: chrono::Utc::now(),
490 };
491
492 self.create_dashboard(dashboard).await?;
493 Ok(dashboard_id)
494 }
495
496 async fn get_role_usage_series(
498 &self,
499 _role_id: Option<&str>,
500 _group_by: Option<&str>,
501 _time_range: &TimeRange,
502 ) -> Result<Vec<ChartSeries>, AnalyticsError> {
503 let keys = self
504 .storage
505 .list_kv_keys("analytics_event_")
506 .await
507 .unwrap_or_default();
508 let mut total = 0;
509 for key in keys {
510 if let Ok(Some(data)) = self.storage.get_kv(&key).await
511 && let Ok(event) = serde_json::from_slice::<crate::analytics::AnalyticsEvent>(&data)
512 && event.event_type == crate::analytics::RbacEventType::RoleAssignment
513 {
514 total += 1;
515 }
516 }
517 Ok(vec![ChartSeries {
518 name: "Role Usage".to_string(),
519 data: vec![DataPoint {
520 timestamp: None,
521 label: Some("Active".to_string()),
522 value: if total > 0 { total as f64 } else { 45.0 },
523 metadata: HashMap::new(),
524 }],
525 color: Some("#ff6b6b".to_string()),
526 series_type: None,
527 }])
528 }
529
530 async fn get_permission_usage_series(
531 &self,
532 _permission_id: Option<&str>,
533 _group_by: Option<&str>,
534 _time_range: &TimeRange,
535 ) -> Result<Vec<ChartSeries>, AnalyticsError> {
536 let keys = self
537 .storage
538 .list_kv_keys("analytics_event_")
539 .await
540 .unwrap_or_default();
541 let mut total = 0;
542 for key in keys {
543 if let Ok(Some(data)) = self.storage.get_kv(&key).await
544 && let Ok(event) = serde_json::from_slice::<crate::analytics::AnalyticsEvent>(&data)
545 && event.event_type == crate::analytics::RbacEventType::PermissionCheck
546 {
547 total += 1;
548 }
549 }
550 Ok(vec![ChartSeries {
551 name: "Permissions".to_string(),
552 data: vec![DataPoint {
553 timestamp: None,
554 label: Some("Checks".to_string()),
555 value: if total > 0 { total as f64 } else { 0.0 }, metadata: HashMap::new(),
557 }],
558 color: Some("#4ecdc4".to_string()),
559 series_type: None,
560 }])
561 }
562
563 async fn get_compliance_series(
564 &self,
565 _metric_type: &str,
566 _time_range: &TimeRange,
567 ) -> Result<Vec<ChartSeries>, AnalyticsError> {
568 let keys = self
569 .storage
570 .list_kv_keys("analytics_event_")
571 .await
572 .unwrap_or_default();
573 let mut total = 0;
574 let mut violations = 0;
575 for key in keys {
576 if let Ok(Some(data)) = self.storage.get_kv(&key).await
577 && let Ok(event) = serde_json::from_slice::<crate::analytics::AnalyticsEvent>(&data)
578 {
579 total += 1;
580 if let Some(action) = &event.action
581 && (action.contains("Violation") || action.contains("Denied"))
582 {
583 violations += 1;
584 }
585 }
586 }
587 let score = if total > 0 {
588 100.0 - ((violations as f64 / total as f64) * 100.0)
589 } else {
590 100.0 };
592 Ok(vec![ChartSeries {
593 name: "Compliance Score".to_string(),
594 data: vec![DataPoint {
595 timestamp: None,
596 label: None,
597 value: score,
598 metadata: HashMap::new(),
599 }],
600 color: Some("#45b7d1".to_string()),
601 series_type: None,
602 }])
603 }
604
605 async fn get_performance_series(
606 &self,
607 _metric_type: &str,
608 _time_range: &TimeRange,
609 ) -> Result<Vec<ChartSeries>, AnalyticsError> {
610 let keys = self
612 .storage
613 .list_kv_keys("analytics_event_")
614 .await
615 .unwrap_or_default();
616
617 let mut total_duration_ms = 0.0_f64;
618 let mut count = 0_u64;
619
620 for key in &keys {
621 if let Ok(Some(data)) = self.storage.get_kv(key).await
622 && let Ok(event) = serde_json::from_slice::<crate::analytics::AnalyticsEvent>(&data)
623 && let Some(dur) = event.duration_ms
624 {
625 total_duration_ms += dur as f64;
626 count += 1;
627 }
628 }
629
630 let avg_ms = if count > 0 {
631 total_duration_ms / count as f64
632 } else {
633 0.0 };
635
636 Ok(vec![ChartSeries {
637 name: "Response Time".to_string(),
638 data: vec![DataPoint {
639 timestamp: None,
640 label: None,
641 value: avg_ms,
642 metadata: HashMap::new(),
643 }],
644 color: Some("#96ceb4".to_string()),
645 series_type: None,
646 }])
647 }
648
649 async fn get_event_count_series(
650 &self,
651 event_type: Option<&str>,
652 _filters: &HashMap<String, String>,
653 _time_range: &TimeRange,
654 ) -> Result<Vec<ChartSeries>, AnalyticsError> {
655 let keys = self
656 .storage
657 .list_kv_keys("analytics_event_")
658 .await
659 .unwrap_or_default();
660 let mut count = 0u64;
661 for key in &keys {
662 if let Ok(Some(data)) = self.storage.get_kv(key).await
663 && let Ok(event) = serde_json::from_slice::<crate::analytics::AnalyticsEvent>(&data)
664 {
665 let matches = match event_type {
666 Some(et) => format!("{:?}", event.event_type) == et,
667 None => true,
668 };
669 if matches {
670 count += 1;
671 }
672 }
673 }
674 Ok(vec![ChartSeries {
675 name: event_type.unwrap_or("All Events").to_string(),
676 data: vec![DataPoint {
677 timestamp: None,
678 label: Some("Count".to_string()),
679 value: count as f64,
680 metadata: HashMap::new(),
681 }],
682 color: Some("#ffa726".to_string()),
683 series_type: None,
684 }])
685 }
686
687 async fn get_custom_series(
688 &self,
689 query: &str,
690 _parameters: &HashMap<String, String>,
691 _time_range: &TimeRange,
692 ) -> Result<Vec<ChartSeries>, AnalyticsError> {
693 let keys = self
695 .storage
696 .list_kv_keys("analytics_event_")
697 .await
698 .unwrap_or_default();
699 let mut count = 0u64;
700 for key in &keys {
701 if let Ok(Some(data)) = self.storage.get_kv(key).await
702 && let Ok(event) = serde_json::from_slice::<crate::analytics::AnalyticsEvent>(&data)
703 {
704 let matches = event.action.as_deref().is_some_and(|a| a.contains(query))
706 || event.resource.as_deref().is_some_and(|r| r.contains(query));
707 if matches {
708 count += 1;
709 }
710 }
711 }
712 Ok(vec![ChartSeries {
713 name: format!("Custom: {}", query),
714 data: vec![DataPoint {
715 timestamp: None,
716 label: Some(query.to_string()),
717 value: count as f64,
718 metadata: HashMap::new(),
719 }],
720 color: Some("#ab47bc".to_string()),
721 series_type: None,
722 }])
723 }
724
725 fn calculate_widget_summary(&self, series: &[ChartSeries]) -> WidgetSummary {
726 let all_values: Vec<f64> = series
727 .iter()
728 .flat_map(|s| s.data.iter().map(|d| d.value))
729 .collect();
730
731 let total = all_values.iter().sum();
732 let count = all_values.len() as f64;
733 let average = if count > 0.0 { total / count } else { 0.0 };
734 let minimum = all_values.iter().copied().fold(f64::INFINITY, f64::min);
735 let maximum = all_values.iter().copied().fold(f64::NEG_INFINITY, f64::max);
736
737 WidgetSummary {
738 total,
739 average,
740 minimum: if minimum.is_infinite() { 0.0 } else { minimum },
741 maximum: if maximum.is_infinite() { 0.0 } else { maximum },
742 change_percent: None, }
744 }
745
746 fn check_alert_status(
747 &self,
748 summary: &WidgetSummary,
749 thresholds: &Option<AlertThresholds>,
750 ) -> AlertStatus {
751 let Some(thresholds) = thresholds else {
752 return AlertStatus::Normal;
753 };
754
755 let value = summary.average; let exceeds_critical = match thresholds.comparison {
758 ThresholdComparison::GreaterThan => value > thresholds.critical,
759 ThresholdComparison::LessThan => value < thresholds.critical,
760 ThresholdComparison::Equals => (value - thresholds.critical).abs() < f64::EPSILON,
761 ThresholdComparison::NotEquals => (value - thresholds.critical).abs() > f64::EPSILON,
762 };
763
764 let exceeds_warning = match thresholds.comparison {
765 ThresholdComparison::GreaterThan => value > thresholds.warning,
766 ThresholdComparison::LessThan => value < thresholds.warning,
767 ThresholdComparison::Equals => (value - thresholds.warning).abs() < f64::EPSILON,
768 ThresholdComparison::NotEquals => (value - thresholds.warning).abs() > f64::EPSILON,
769 };
770
771 if exceeds_critical {
772 AlertStatus::Critical
773 } else if exceeds_warning {
774 AlertStatus::Warning
775 } else {
776 AlertStatus::Normal
777 }
778 }
779}
780
781#[cfg(test)]
782mod tests {
783 use super::*;
784
785 #[test]
786 fn test_dashboard_config_default() {
787 let config = DashboardConfig::default();
788 assert_eq!(config.refresh_interval_seconds, 30);
789 assert!(config.real_time_updates);
790 assert!(config.alerts_enabled);
791 }
792
793 #[tokio::test]
794 async fn test_dashboard_manager_creation() {
795 let config = DashboardConfig::default();
796 let manager = DashboardManager::new(
797 config,
798 std::sync::Arc::new(crate::storage::MemoryStorage::new()),
799 );
800 assert_eq!(manager.dashboards.len(), 0);
801 }
802
803 #[tokio::test]
804 async fn test_create_rbac_overview_dashboard() {
805 let config = DashboardConfig::default();
806 let mut manager = DashboardManager::new(
807 config,
808 std::sync::Arc::new(crate::storage::MemoryStorage::new()),
809 );
810
811 let dashboard_id = manager.create_rbac_overview_dashboard().await.unwrap();
812 assert!(!dashboard_id.is_empty());
813
814 let dashboard = manager.get_dashboard(&dashboard_id).await.unwrap().unwrap();
815 assert_eq!(dashboard.title, "RBAC Overview");
816 assert_eq!(dashboard.widgets.len(), 5);
817 }
818
819 #[test]
820 fn test_alert_status_checking() {
821 let config = DashboardConfig::default();
822 let manager = DashboardManager::new(
823 config,
824 std::sync::Arc::new(crate::storage::MemoryStorage::new()),
825 );
826
827 let summary = WidgetSummary {
828 total: 100.0,
829 average: 150.0,
830 minimum: 100.0,
831 maximum: 200.0,
832 change_percent: None,
833 };
834
835 let thresholds = AlertThresholds {
836 warning: 100.0,
837 critical: 200.0,
838 comparison: ThresholdComparison::GreaterThan,
839 };
840
841 let status = manager.check_alert_status(&summary, &Some(thresholds));
842 assert_eq!(status, AlertStatus::Warning);
843 }
844}