code-mesh-core 0.1.0

High-performance, WASM-powered distributed swarm intelligence core library for concurrent code execution and neural mesh computing
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
622
623
624
//! Event system for Code Mesh Core
//!
//! This module provides a comprehensive event system for communication
//! between different components of the Code Mesh ecosystem.

use crate::{Error, Result};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::sync::Arc;
use uuid::Uuid;

#[cfg(feature = "native")]
use tokio::sync::{broadcast, RwLock};

#[cfg(feature = "wasm")]
use parking_lot::RwLock;

/// Event trait that all events must implement
pub trait Event: Send + Sync + Clone + std::fmt::Debug + 'static {
    /// Event type identifier
    fn event_type(&self) -> &'static str;
    
    /// Event priority
    fn priority(&self) -> EventPriority {
        EventPriority::Normal
    }
    
    /// Whether this event should be persisted
    fn persistent(&self) -> bool {
        false
    }
}

/// Event priority levels
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum EventPriority {
    Low = 0,
    Normal = 1,
    High = 2,
    Critical = 3,
}

/// Event handler trait
#[async_trait]
pub trait EventHandler<E: Event>: Send + Sync {
    /// Handle an event
    async fn handle(&self, event: &E) -> Result<()>;
    
    /// Handler priority (higher values are called first)
    fn priority(&self) -> i32 {
        0
    }
    
    /// Whether this handler should receive events before others
    fn early(&self) -> bool {
        false
    }
}

/// Boxed event handler that can handle any event
type BoxedHandler = Box<dyn EventHandlerDyn + Send + Sync>;

/// Dynamic event handler trait for type erasure
#[async_trait]
trait EventHandlerDyn {
    async fn handle_dyn(&self, event: &(dyn Any + Send + Sync)) -> Result<()>;
    fn priority(&self) -> i32;
    fn early(&self) -> bool;
}

/// Wrapper to implement EventHandlerDyn for concrete handlers
struct EventHandlerWrapper<E: Event, H: EventHandler<E>> {
    handler: H,
    _phantom: std::marker::PhantomData<E>,
}

#[async_trait]
impl<E: Event, H: EventHandler<E>> EventHandlerDyn for EventHandlerWrapper<E, H> {
    async fn handle_dyn(&self, event: &(dyn Any + Send + Sync)) -> Result<()> {
        if let Some(typed_event) = event.downcast_ref::<E>() {
            self.handler.handle(typed_event).await
        } else {
            Err(Error::Other(anyhow::anyhow!("Event type mismatch")))
        }
    }

    fn priority(&self) -> i32 {
        self.handler.priority()
    }

    fn early(&self) -> bool {
        self.handler.early()
    }
}

/// Event bus for managing event distribution
pub struct EventBus {
    #[cfg(feature = "native")]
    handlers: RwLock<HashMap<TypeId, Vec<BoxedHandler>>>,
    
    #[cfg(feature = "native")]
    broadcast_senders: RwLock<HashMap<TypeId, broadcast::Sender<Arc<dyn Any + Send + Sync>>>>,
    
    #[cfg(feature = "wasm")]
    handlers: RwLock<HashMap<TypeId, Vec<BoxedHandler>>>,
    
    /// Maximum number of queued events per type
    max_queue_size: usize,
    
    /// Whether to enable event tracing
    tracing_enabled: bool,
}

impl EventBus {
    /// Create a new event bus
    pub fn new() -> Self {
        Self {
            handlers: RwLock::new(HashMap::new()),
            #[cfg(feature = "native")]
            broadcast_senders: RwLock::new(HashMap::new()),
            max_queue_size: 1000,
            tracing_enabled: true,
        }
    }

    /// Create a new event bus with custom configuration
    pub fn with_config(max_queue_size: usize, tracing_enabled: bool) -> Self {
        Self {
            handlers: RwLock::new(HashMap::new()),
            #[cfg(feature = "native")]
            broadcast_senders: RwLock::new(HashMap::new()),
            max_queue_size,
            tracing_enabled,
        }
    }

    /// Subscribe to events of a specific type
    pub async fn subscribe<E: Event, H: EventHandler<E> + 'static>(&self, handler: H) -> Result<()> {
        let type_id = TypeId::of::<E>();
        let boxed_handler = Box::new(EventHandlerWrapper {
            handler,
            _phantom: std::marker::PhantomData::<E>,
        });

        #[cfg(feature = "native")]
        {
            let mut handlers = self.handlers.write().await;
            let handlers_list = handlers.entry(type_id).or_insert_with(Vec::new);
            handlers_list.push(boxed_handler);
            
            // Sort by priority and early flag
            handlers_list.sort_by(|a, b| {
                match (a.early(), b.early()) {
                    (true, false) => std::cmp::Ordering::Less,
                    (false, true) => std::cmp::Ordering::Greater,
                    _ => b.priority().cmp(&a.priority()),
                }
            });
        }

        #[cfg(feature = "wasm")]
        {
            let mut handlers = self.handlers.write();
            let handlers_list = handlers.entry(type_id).or_insert_with(Vec::new);
            handlers_list.push(boxed_handler);
            
            // Sort by priority and early flag
            handlers_list.sort_by(|a, b| {
                match (a.early(), b.early()) {
                    (true, false) => std::cmp::Ordering::Less,
                    (false, true) => std::cmp::Ordering::Greater,
                    _ => b.priority().cmp(&a.priority()),
                }
            });
        }

        if self.tracing_enabled {
            tracing::debug!("Subscribed to event type: {}", std::any::type_name::<E>());
        }

        Ok(())
    }

    /// Publish an event to all subscribers
    pub async fn publish<E: Event>(&self, event: E) -> Result<()> {
        let type_id = TypeId::of::<E>();
        
        if self.tracing_enabled {
            tracing::debug!(
                "Publishing event: {} with priority: {:?}",
                event.event_type(),
                event.priority()
            );
        }

        // Handle direct subscriptions
        #[cfg(feature = "native")]
        {
            let handlers = self.handlers.read().await;
            if let Some(handlers_list) = handlers.get(&type_id) {
                for handler in handlers_list {
                    if let Err(e) = handler.handle_dyn(&event as &(dyn Any + Send + Sync)).await {
                        tracing::error!("Error handling event: {}", e);
                        // Continue processing other handlers
                    }
                }
            }

            // Handle broadcast subscriptions
            let senders = self.broadcast_senders.read().await;
            if let Some(sender) = senders.get(&type_id) {
                let arc_event: Arc<dyn Any + Send + Sync> = Arc::new(event.clone());
                if sender.send(arc_event).is_err() {
                    // No receivers, which is fine
                }
            }
        }

        #[cfg(feature = "wasm")]
        {
            let handlers = self.handlers.read();
            if let Some(handlers_list) = handlers.get(&type_id) {
                for handler in handlers_list {
                    if let Err(e) = handler.handle_dyn(&event as &(dyn Any + Send + Sync)).await {
                        tracing::error!("Error handling event: {}", e);
                        // Continue processing other handlers
                    }
                }
            }
        }

        Ok(())
    }

    /// Create a broadcast channel for streaming events
    #[cfg(feature = "native")]
    pub async fn create_stream<E: Event>(&self) -> broadcast::Receiver<Arc<dyn Any + Send + Sync>> {
        let type_id = TypeId::of::<E>();
        
        let mut senders = self.broadcast_senders.write().await;
        let sender = senders.entry(type_id).or_insert_with(|| {
            let (sender, _) = broadcast::channel(self.max_queue_size);
            sender
        });
        
        sender.subscribe()
    }

    /// Unsubscribe from all events (clears all handlers)
    pub async fn clear(&self) {
        #[cfg(feature = "native")]
        {
            self.handlers.write().await.clear();
            self.broadcast_senders.write().await.clear();
        }

        #[cfg(feature = "wasm")]
        {
            self.handlers.write().clear();
        }
    }

    /// Get the number of handlers for a specific event type
    pub async fn handler_count<E: Event>(&self) -> usize {
        let type_id = TypeId::of::<E>();
        
        #[cfg(feature = "native")]
        {
            self.handlers.read().await
                .get(&type_id)
                .map(|h| h.len())
                .unwrap_or(0)
        }

        #[cfg(feature = "wasm")]
        {
            self.handlers.read()
                .get(&type_id)
                .map(|h| h.len())
                .unwrap_or(0)
        }
    }
}

impl Default for EventBus {
    fn default() -> Self {
        Self::new()
    }
}

/// Common events used throughout Code Mesh
pub mod events {
    use super::*;
    use chrono::{DateTime, Utc};

    /// Session-related events
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct SessionCreated {
        pub session_id: String,
        pub timestamp: DateTime<Utc>,
        pub metadata: HashMap<String, serde_json::Value>,
    }

    impl Event for SessionCreated {
        fn event_type(&self) -> &'static str {
            "session.created"
        }

        fn persistent(&self) -> bool {
            true
        }
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct SessionEnded {
        pub session_id: String,
        pub timestamp: DateTime<Utc>,
        pub reason: String,
    }

    impl Event for SessionEnded {
        fn event_type(&self) -> &'static str {
            "session.ended"
        }

        fn persistent(&self) -> bool {
            true
        }
    }

    /// Message-related events
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct MessageSent {
        pub session_id: String,
        pub message_id: String,
        pub role: String,
        pub content: String,
        pub timestamp: DateTime<Utc>,
    }

    impl Event for MessageSent {
        fn event_type(&self) -> &'static str {
            "message.sent"
        }

        fn priority(&self) -> EventPriority {
            EventPriority::Normal
        }
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct MessageReceived {
        pub session_id: String,
        pub message_id: String,
        pub role: String,
        pub content: String,
        pub timestamp: DateTime<Utc>,
        pub tokens_used: Option<u32>,
    }

    impl Event for MessageReceived {
        fn event_type(&self) -> &'static str {
            "message.received"
        }

        fn priority(&self) -> EventPriority {
            EventPriority::Normal
        }
    }

    /// Tool-related events
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct ToolExecuted {
        pub session_id: String,
        pub tool_id: String,
        pub tool_name: String,
        pub arguments: serde_json::Value,
        pub result: serde_json::Value,
        pub duration_ms: u64,
        pub timestamp: DateTime<Utc>,
    }

    impl Event for ToolExecuted {
        fn event_type(&self) -> &'static str {
            "tool.executed"
        }

        fn priority(&self) -> EventPriority {
            EventPriority::Normal
        }

        fn persistent(&self) -> bool {
            true
        }
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct ToolFailed {
        pub session_id: String,
        pub tool_id: String,
        pub tool_name: String,
        pub arguments: serde_json::Value,
        pub error: String,
        pub duration_ms: u64,
        pub timestamp: DateTime<Utc>,
    }

    impl Event for ToolFailed {
        fn event_type(&self) -> &'static str {
            "tool.failed"
        }

        fn priority(&self) -> EventPriority {
            EventPriority::High
        }

        fn persistent(&self) -> bool {
            true
        }
    }

    /// Provider-related events
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct ProviderConnected {
        pub provider_id: String,
        pub provider_name: String,
        pub timestamp: DateTime<Utc>,
    }

    impl Event for ProviderConnected {
        fn event_type(&self) -> &'static str {
            "provider.connected"
        }

        fn priority(&self) -> EventPriority {
            EventPriority::High
        }
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct ProviderDisconnected {
        pub provider_id: String,
        pub provider_name: String,
        pub reason: String,
        pub timestamp: DateTime<Utc>,
    }

    impl Event for ProviderDisconnected {
        fn event_type(&self) -> &'static str {
            "provider.disconnected"
        }

        fn priority(&self) -> EventPriority {
            EventPriority::High
        }
    }

    /// Storage-related events
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct DataStored {
        pub key: String,
        pub size_bytes: u64,
        pub timestamp: DateTime<Utc>,
    }

    impl Event for DataStored {
        fn event_type(&self) -> &'static str {
            "storage.stored"
        }
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct DataRetrieved {
        pub key: String,
        pub size_bytes: u64,
        pub timestamp: DateTime<Utc>,
    }

    impl Event for DataRetrieved {
        fn event_type(&self) -> &'static str {
            "storage.retrieved"
        }
    }

    /// Error-related events
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct ErrorOccurred {
        pub error_id: String,
        pub component: String,
        pub error_message: String,
        pub error_code: Option<String>,
        pub context: HashMap<String, serde_json::Value>,
        pub timestamp: DateTime<Utc>,
    }

    impl Event for ErrorOccurred {
        fn event_type(&self) -> &'static str {
            "error.occurred"
        }

        fn priority(&self) -> EventPriority {
            EventPriority::Critical
        }

        fn persistent(&self) -> bool {
            true
        }
    }

    /// System-related events
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct SystemStarted {
        pub version: String,
        pub features: Vec<String>,
        pub timestamp: DateTime<Utc>,
    }

    impl Event for SystemStarted {
        fn event_type(&self) -> &'static str {
            "system.started"
        }

        fn priority(&self) -> EventPriority {
            EventPriority::High
        }

        fn persistent(&self) -> bool {
            true
        }
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct SystemShutdown {
        pub reason: String,
        pub timestamp: DateTime<Utc>,
    }

    impl Event for SystemShutdown {
        fn event_type(&self) -> &'static str {
            "system.shutdown"
        }

        fn priority(&self) -> EventPriority {
            EventPriority::Critical
        }

        fn persistent(&self) -> bool {
            true
        }
    }
}

/// Convenience macro for creating simple event handlers
#[macro_export]
macro_rules! event_handler {
    ($event_type:ty, $handler_fn:expr) => {
        struct SimpleEventHandler {
            handler: fn(&$event_type) -> Result<()>,
        }

        #[async_trait]
        impl EventHandler<$event_type> for SimpleEventHandler {
            async fn handle(&self, event: &$event_type) -> Result<()> {
                (self.handler)(event)
            }
        }

        SimpleEventHandler {
            handler: $handler_fn,
        }
    };
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicU32, Ordering};

    #[derive(Debug, Clone)]
    struct TestEvent {
        message: String,
    }

    impl Event for TestEvent {
        fn event_type(&self) -> &'static str {
            "test.event"
        }
    }

    struct TestHandler {
        counter: Arc<AtomicU32>,
    }

    #[async_trait]
    impl EventHandler<TestEvent> for TestHandler {
        async fn handle(&self, _event: &TestEvent) -> Result<()> {
            self.counter.fetch_add(1, Ordering::SeqCst);
            Ok(())
        }
    }

    #[cfg(feature = "native")]
    #[tokio::test]
    async fn test_event_bus() {
        let bus = EventBus::new();
        let counter = Arc::new(AtomicU32::new(0));
        
        let handler = TestHandler {
            counter: counter.clone(),
        };

        bus.subscribe(handler).await.unwrap();

        let event = TestEvent {
            message: "Hello, World!".to_string(),
        };

        bus.publish(event).await.unwrap();

        assert_eq!(counter.load(Ordering::SeqCst), 1);
    }
}