1use std::{
207 collections::HashMap,
208 sync::{Arc, Mutex},
209 time::{Duration, SystemTime},
210};
211
212use log::{debug, error, info, trace, warn};
213use serde::{Deserialize, Serialize};
214use tokio::time::interval;
215use tauri::{AppHandle, Emitter, Manager};
216
217use crate::RunTime::ApplicationRunTime::ApplicationRunTime;
218
219#[derive(Clone)]
221pub struct AdvancedFeatures {
222 runtime:Arc<ApplicationRunTime>,
223 performance_stats:Arc<Mutex<PerformanceStats>>,
224 collaboration_sessions:Arc<Mutex<HashMap<String, CollaborationSession>>>,
225 message_cache:Arc<Mutex<MessageCache>>,
226}
227
228#[derive(Debug, Clone, Serialize, Deserialize)]
230pub struct PerformanceStats {
231 pub total_messages_sent:u64,
232 pub total_messages_received:u64,
233 pub average_processing_time_ms:f64,
234 pub peak_message_rate:u32,
235 pub error_count:u32,
236 pub last_update:u64,
237 pub connection_uptime:u64,
238}
239
240#[derive(Debug, Clone, Serialize, Deserialize)]
242pub struct CollaborationSession {
243 pub session_id:String,
244 pub participants:Vec<String>,
245 pub active_documents:Vec<String>,
246 pub last_activity:u64,
247 pub permissions:CollaborationPermissions,
248}
249
250#[derive(Debug, Clone, Serialize, Deserialize)]
252pub struct CollaborationPermissions {
253 pub can_edit:bool,
254 pub can_view:bool,
255 pub can_comment:bool,
256 pub can_share:bool,
257}
258
259#[derive(Debug, Clone, Serialize, Deserialize)]
261pub struct MessageCache {
262 pub cached_messages:HashMap<String, CachedMessage>,
263 pub cache_hits:u64,
264 pub cache_misses:u64,
265 pub cache_size:usize,
266}
267
268#[derive(Debug, Clone, Serialize, Deserialize)]
270pub struct CachedMessage {
271 pub data:serde_json::Value,
272 pub timestamp:u64,
274 pub ttl:u64,
276}
277
278impl AdvancedFeatures {
279 pub fn new(runtime:Arc<ApplicationRunTime>) -> Self {
281 info!("[AdvancedFeatures] Initializing advanced IPC features");
282
283 Self {
284 runtime,
285 performance_stats:Arc::new(Mutex::new(PerformanceStats {
286 total_messages_sent:0,
287 total_messages_received:0,
288 average_processing_time_ms:0.0,
289 peak_message_rate:0,
290 error_count:0,
291 last_update:SystemTime::now()
292 .duration_since(SystemTime::UNIX_EPOCH)
293 .unwrap_or_default()
294 .as_secs(),
295 connection_uptime:0,
296 })),
297 collaboration_sessions:Arc::new(Mutex::new(HashMap::new())),
298 message_cache:Arc::new(Mutex::new(MessageCache {
299 cached_messages:HashMap::new(),
300 cache_hits:0,
301 cache_misses:0,
302 cache_size:0,
303 })),
304 }
305 }
306
307 pub async fn start_monitoring(&self) -> Result<(), String> {
309 info!("[AdvancedFeatures] Starting advanced monitoring");
310
311 let features1 = self.clone_features();
312 let features2 = self.clone_features();
313 let features3 = self.clone_features();
314
315 tokio::spawn(async move {
317 features1.monitor_performance().await;
318 });
319
320 tokio::spawn(async move {
322 features2.cleanup_cache().await;
323 });
324
325 tokio::spawn(async move {
327 features3.monitor_collaboration_sessions().await;
328 });
329
330 Ok(())
331 }
332
333 async fn monitor_performance(&self) {
335 let mut interval = interval(Duration::from_secs(10));
336
337 loop {
338 interval.tick().await;
339
340 let stats = self.calculate_performance_stats().await;
341
342 if let Err(e) = self.runtime.Environment.ApplicationHandle.emit("ipc-performance-stats", &stats) {
344 error!("[AdvancedFeatures] Failed to emit performance stats: {}", e);
345 }
346
347 debug!("[AdvancedFeatures] Performance stats updated");
348 }
349 }
350
351 async fn calculate_performance_stats(&self) -> PerformanceStats {
353 let mut stats = self.performance_stats.lock().unwrap();
354
355 stats.connection_uptime = SystemTime::now()
357 .duration_since(SystemTime::UNIX_EPOCH)
358 .unwrap_or_default()
359 .as_secs()
360 - stats.last_update;
361
362 stats.last_update = SystemTime::now()
363 .duration_since(SystemTime::UNIX_EPOCH)
364 .unwrap_or_default()
365 .as_secs();
366
367 stats.clone()
368 }
369
370 async fn cleanup_cache(&self) {
372 let mut interval = interval(Duration::from_secs(60));
373
374 loop {
375 interval.tick().await;
376
377 let current_time = SystemTime::now()
378 .duration_since(SystemTime::UNIX_EPOCH)
379 .unwrap_or_default()
380 .as_secs();
381
382 let mut cache = self.message_cache.lock().unwrap();
383
384 cache
385 .cached_messages
386 .retain(|_, cached_message| current_time < cached_message.timestamp + cached_message.ttl);
387
388 cache.cache_size = cache.cached_messages.len();
389
390 debug!("[AdvancedFeatures] Cache cleaned, {} entries remaining", cache.cache_size);
391 }
392 }
393
394 async fn monitor_collaboration_sessions(&self) {
396 let mut interval = interval(Duration::from_secs(30));
397
398 loop {
399 interval.tick().await;
400
401 let current_time = SystemTime::now()
402 .duration_since(SystemTime::UNIX_EPOCH)
403 .unwrap_or_default()
404 .as_secs();
405
406 let mut sessions = self.collaboration_sessions.lock().unwrap();
407
408 sessions.retain(|_, session| {
410 current_time - session.last_activity < 300 });
412
413 let active_sessions:Vec<CollaborationSession> = sessions.values().cloned().collect();
415
416 if let Err(e) = self
417 .runtime
418 .Environment
419 .ApplicationHandle
420 .emit("collaboration-sessions-update", &active_sessions)
421 {
422 error!("[AdvancedFeatures] Failed to emit collaboration sessions: {}", e);
423 }
424
425 debug!("[AdvancedFeatures] Collaboration sessions monitored, {} active", sessions.len());
426 }
427 }
428
429 pub async fn cache_message(&self, message_id:String, data:serde_json::Value, ttl:u64) -> Result<(), String> {
431 let mut cache = self
432 .message_cache
433 .lock()
434 .map_err(|e| format!("Failed to access message cache: {}", e))?;
435
436 let cached_message = CachedMessage {
437 data,
438 timestamp:SystemTime::now()
439 .duration_since(SystemTime::UNIX_EPOCH)
440 .unwrap_or_default()
441 .as_secs(),
442 ttl,
443 };
444
445 cache.cached_messages.insert(message_id.clone(), cached_message);
446 cache.cache_size = cache.cached_messages.len();
447
448 debug!("[AdvancedFeatures] Message cached: {}, TTL: {}s", message_id, ttl);
449 Ok(())
450 }
451
452 pub async fn get_cached_message(&self, message_id:&str) -> Option<serde_json::Value> {
454 let mut cache = self.message_cache.lock().unwrap();
455
456 let result = cache
457 .cached_messages
458 .get(message_id)
459 .map(|cached_message| cached_message.data.clone());
460
461 if result.is_some() {
463 cache.cache_hits += 1;
464 } else {
465 cache.cache_misses += 1;
466 }
467
468 result
469 }
470
471 pub async fn create_collaboration_session(
473 &self,
474 session_id:String,
475 permissions:CollaborationPermissions,
476 ) -> Result<(), String> {
477 let mut sessions = self
478 .collaboration_sessions
479 .lock()
480 .map_err(|e| format!("Failed to access collaboration sessions: {}", e))?;
481
482 let session = CollaborationSession {
483 session_id:session_id.clone(),
484 participants:Vec::new(),
485 active_documents:Vec::new(),
486 last_activity:SystemTime::now()
487 .duration_since(SystemTime::UNIX_EPOCH)
488 .unwrap_or_default()
489 .as_secs(),
490 permissions,
491 };
492
493 sessions.insert(session_id, session);
494
495 info!("[AdvancedFeatures] Collaboration session created");
496 Ok(())
497 }
498
499 pub async fn add_participant(&self, session_id:&str, participant:String) -> Result<(), String> {
501 let mut sessions = self
502 .collaboration_sessions
503 .lock()
504 .map_err(|e| format!("Failed to access collaboration sessions: {}", e))?;
505
506 if let Some(session) = sessions.get_mut(session_id) {
507 if !session.participants.contains(&participant) {
508 session.participants.push(participant);
509 session.last_activity = SystemTime::now()
510 .duration_since(SystemTime::UNIX_EPOCH)
511 .unwrap_or_default()
512 .as_secs();
513
514 debug!("[AdvancedFeatures] Participant added to session: {}", session_id);
515 }
516 } else {
517 return Err(format!("Session not found: {}", session_id));
518 }
519
520 Ok(())
521 }
522
523 pub async fn record_message_statistics(&self, sent:bool, processing_time_ms:u64) {
525 let mut stats = self.performance_stats.lock().unwrap();
526
527 if sent {
528 stats.total_messages_sent += 1;
529 } else {
530 stats.total_messages_received += 1;
531 }
532
533 let total_messages = stats.total_messages_sent + stats.total_messages_received;
535 stats.average_processing_time_ms = (stats.average_processing_time_ms * (total_messages - 1) as f64
536 + processing_time_ms as f64)
537 / total_messages as f64;
538 }
539
540 pub async fn record_error(&self) {
542 let mut stats = self.performance_stats.lock().unwrap();
543 stats.error_count += 1;
544 }
545
546 pub async fn get_performance_stats(&self) -> Result<PerformanceStats, String> {
548 Ok(self.calculate_performance_stats().await)
549 }
550
551 pub async fn get_cache_stats(&self) -> Result<MessageCache, String> {
553 let cache = self.message_cache.lock().unwrap();
554 Ok(cache.clone())
555 }
556
557 pub async fn get_collaboration_sessions(&self) -> Vec<CollaborationSession> {
559 let sessions = self.collaboration_sessions.lock().unwrap();
560 sessions.values().cloned().collect()
561 }
562
563 fn clone_features(&self) -> AdvancedFeatures {
565 AdvancedFeatures {
566 runtime:self.runtime.clone(),
567 performance_stats:self.performance_stats.clone(),
568 collaboration_sessions:self.collaboration_sessions.clone(),
569 message_cache:self.message_cache.clone(),
570 }
571 }
572}
573
574#[tauri::command]
576pub async fn mountain_get_performance_stats(app_handle:tauri::AppHandle) -> Result<PerformanceStats, String> {
577 debug!("[AdvancedFeatures] Tauri command: get_performance_stats");
578
579 if let Some(features) = app_handle.try_state::<AdvancedFeatures>() {
580 Ok(features.get_performance_stats().await?)
581 } else {
582 Err("AdvancedFeatures not found in application state".to_string())
583 }
584}
585
586#[tauri::command]
588pub async fn mountain_get_cache_stats(app_handle:tauri::AppHandle) -> Result<MessageCache, String> {
589 debug!("[AdvancedFeatures] Tauri command: get_cache_stats");
590
591 if let Some(features) = app_handle.try_state::<AdvancedFeatures>() {
592 Ok(features.get_cache_stats().await?)
593 } else {
594 Err("AdvancedFeatures not found in application state".to_string())
595 }
596}
597
598#[tauri::command]
600pub async fn mountain_create_collaboration_session(
601 app_handle:tauri::AppHandle,
602 session_id:String,
603 permissions:CollaborationPermissions,
604) -> Result<(), String> {
605 debug!("[AdvancedFeatures] Tauri command: create_collaboration_session");
606
607 if let Some(features) = app_handle.try_state::<AdvancedFeatures>() {
608 features.create_collaboration_session(session_id, permissions).await
609 } else {
610 Err("AdvancedFeatures not found in application state".to_string())
611 }
612}
613
614#[tauri::command]
616pub async fn mountain_get_collaboration_sessions(
617 app_handle:tauri::AppHandle,
618) -> Result<Vec<CollaborationSession>, String> {
619 debug!("[AdvancedFeatures] Tauri command: get_collaboration_sessions");
620
621 if let Some(features) = app_handle.try_state::<AdvancedFeatures>() {
622 Ok(features.get_collaboration_sessions().await)
623 } else {
624 Err("AdvancedFeatures not found in application state".to_string())
625 }
626}
627
628pub fn initialize_advanced_features(
630 app_handle:&tauri::AppHandle,
631 runtime:Arc<ApplicationRunTime>,
632) -> Result<(), String> {
633 info!("[AdvancedFeatures] Initializing advanced IPC features");
634
635 let features = AdvancedFeatures::new(runtime);
636
637 app_handle.manage(features.clone_features());
639
640 let features_clone = features.clone();
642 tokio::spawn(async move {
643 if let Err(e) = features_clone.start_monitoring().await {
644 error!("[AdvancedFeatures] Failed to start monitoring: {}", e);
645 }
646 });
647
648 Ok(())
649}