scirs2_metrics/visualization/advanced_interactive/
events.rs1#![allow(clippy::too_many_arguments)]
7#![allow(dead_code)]
8
9use super::widgets::{WidgetEvent, WidgetEventResponse};
10use crate::error::{MetricsError, Result};
11use serde::{Deserialize, Serialize};
12use serde_json::Value;
13use std::collections::{HashMap, VecDeque};
14use std::sync::{Arc, Mutex};
15use std::time::Instant;
16
17#[derive(Debug)]
19pub struct EventSystem {
20 handlers: HashMap<String, Vec<Box<dyn EventHandler + Send + Sync>>>,
22 event_queue: VecDeque<DashboardEvent>,
24 event_history: VecDeque<DashboardEvent>,
26 config: EventSystemConfig,
28}
29
30pub trait EventHandler: std::fmt::Debug + Send + Sync {
32 fn handle_event(&self, event: &DashboardEvent) -> Result<Option<EventResponse>>;
34
35 fn priority(&self) -> u32;
37
38 fn can_handle(&self, event_type: &str) -> bool;
40}
41
42#[derive(Debug, Clone)]
44pub struct DashboardEvent {
45 pub id: String,
47 pub event_type: String,
49 pub source: String,
51 pub target: Option<String>,
53 pub timestamp: Instant,
55 pub data: HashMap<String, Value>,
57 pub metadata: EventMetadata,
59}
60
61#[derive(Debug, Clone)]
63pub struct EventMetadata {
64 pub session_id: Option<String>,
66 pub user_id: Option<String>,
68 pub priority: EventPriority,
70 pub propagation: PropagationSettings,
72 pub context: HashMap<String, Value>,
74}
75
76#[derive(Debug, Clone, Serialize, Deserialize)]
78pub enum EventPriority {
79 Low,
81 Normal,
83 High,
85 Critical,
87}
88
89#[derive(Debug, Clone)]
91pub struct PropagationSettings {
92 pub stop_propagation: bool,
94 pub prevent_default: bool,
96 pub bubble: bool,
98 pub capture: bool,
100}
101
102#[derive(Debug, Clone)]
104pub struct EventResponse {
105 pub id: String,
107 pub actions: Vec<EventAction>,
109 pub data: HashMap<String, Value>,
111 pub stop_propagation: bool,
113}
114
115#[derive(Debug, Clone)]
117pub enum EventAction {
118 UpdateWidget {
120 widget_id: String,
121 updates: HashMap<String, Value>,
122 },
123 TriggerEvent(DashboardEvent),
125 ExecuteScript {
127 script: String,
128 context: HashMap<String, Value>,
129 },
130 SendNotification {
132 message: String,
133 level: NotificationLevel,
134 },
135 UpdateDataSource { source_id: String, data: Value },
137 Custom {
139 action_type: String,
140 parameters: HashMap<String, Value>,
141 },
142}
143
144#[derive(Debug, Clone, Serialize, Deserialize)]
146pub enum NotificationLevel {
147 Info,
149 Success,
151 Warning,
153 Error,
155}
156
157#[derive(Debug, Clone, Serialize, Deserialize)]
159pub struct EventSystemConfig {
160 pub max_queue_size: usize,
162 pub max_history_size: usize,
164 pub batch_size: usize,
166 pub debug_enabled: bool,
168 pub performance_monitoring: bool,
170}
171
172impl EventSystem {
173 pub fn new(config: EventSystemConfig) -> Self {
175 Self {
176 handlers: HashMap::new(),
177 event_queue: VecDeque::new(),
178 event_history: VecDeque::new(),
179 config,
180 }
181 }
182
183 pub fn register_handler(
185 &mut self,
186 event_type: String,
187 handler: Box<dyn EventHandler + Send + Sync>,
188 ) {
189 self.handlers.entry(event_type).or_default().push(handler);
190 }
191
192 pub fn queue_event(&mut self, event: DashboardEvent) -> Result<()> {
194 if self.event_queue.len() >= self.config.max_queue_size {
195 return Err(MetricsError::ComputationError(
196 "Event queue is full".to_string(),
197 ));
198 }
199
200 self.event_queue.push_back(event);
201 Ok(())
202 }
203
204 pub fn process_events(&mut self) -> Result<Vec<EventResponse>> {
206 let mut responses = Vec::new();
207 let batch_size = self.config.batch_size.min(self.event_queue.len());
208
209 for _ in 0..batch_size {
210 if let Some(event) = self.event_queue.pop_front() {
211 if let Ok(response) = self.process_single_event(&event) {
212 if let Some(resp) = response {
213 responses.push(resp);
214 }
215 }
216
217 self.add_to_history(event);
219 }
220 }
221
222 Ok(responses)
223 }
224
225 fn process_single_event(&self, event: &DashboardEvent) -> Result<Option<EventResponse>> {
227 if let Some(handlers) = self.handlers.get(&event.event_type) {
228 let mut sorted_handlers: Vec<_> = handlers.iter().collect();
230 sorted_handlers.sort_by(|a, b| b.priority().cmp(&a.priority()));
231
232 for handler in sorted_handlers {
233 if handler.can_handle(&event.event_type) {
234 if let Ok(Some(response)) = handler.handle_event(event) {
235 if response.stop_propagation {
236 return Ok(Some(response));
237 }
238 return Ok(Some(response));
239 }
240 }
241 }
242 }
243
244 Ok(None)
245 }
246
247 fn add_to_history(&mut self, event: DashboardEvent) {
249 if self.event_history.len() >= self.config.max_history_size {
250 self.event_history.pop_front();
251 }
252 self.event_history.push_back(event);
253 }
254
255 pub fn get_history(&self, limit: Option<usize>) -> Vec<DashboardEvent> {
257 let limit = limit.unwrap_or(self.event_history.len());
258 self.event_history
259 .iter()
260 .rev()
261 .take(limit)
262 .cloned()
263 .collect()
264 }
265
266 pub fn clear_queue(&mut self) {
268 self.event_queue.clear();
269 }
270
271 pub fn queue_size(&self) -> usize {
273 self.event_queue.len()
274 }
275}
276
277impl Default for EventSystemConfig {
278 fn default() -> Self {
279 Self {
280 max_queue_size: 1000,
281 max_history_size: 5000,
282 batch_size: 50,
283 debug_enabled: false,
284 performance_monitoring: true,
285 }
286 }
287}
288
289impl Default for EventMetadata {
290 fn default() -> Self {
291 Self {
292 session_id: None,
293 user_id: None,
294 priority: EventPriority::Normal,
295 propagation: PropagationSettings::default(),
296 context: HashMap::new(),
297 }
298 }
299}
300
301impl Default for PropagationSettings {
302 fn default() -> Self {
303 Self {
304 stop_propagation: false,
305 prevent_default: false,
306 bubble: true,
307 capture: false,
308 }
309 }
310}