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