pluggable 0.1.0

A comprehensive, async plugin system for Rust applications with dependency management and security
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
//! Event system for plugin communication and lifecycle hooks

use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use tokio::sync::broadcast;

use crate::core::{PluginError, PluginResult};

/// Unique identifier for events
pub type EventId = u64;

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

impl Default for EventPriority {
    fn default() -> Self {
        Self::Normal
    }
}

/// Core event data structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Event {
    /// Unique event identifier
    pub id: EventId,
    /// Event type/name
    pub event_type: String,
    /// Source plugin that generated the event (None for system events)
    pub source: Option<String>,
    /// Target plugin(s) for the event (None for broadcast)
    pub target: Option<Vec<String>>,
    /// Event payload data
    pub data: serde_json::Value,
    /// Event priority
    pub priority: EventPriority,
    /// Event timestamp
    pub timestamp: SystemTime,
    /// Event metadata
    pub metadata: HashMap<String, String>,
}

impl Event {
    /// Create a new event
    pub fn new(event_type: impl Into<String>, data: serde_json::Value) -> Self {
        Self {
            id: Self::generate_id(),
            event_type: event_type.into(),
            source: None,
            target: None,
            data,
            priority: EventPriority::default(),
            timestamp: SystemTime::now(),
            metadata: HashMap::new(),
        }
    }

    /// Create a new event with source
    pub fn from_plugin(
        event_type: impl Into<String>,
        source: impl Into<String>,
        data: serde_json::Value,
    ) -> Self {
        Self {
            id: Self::generate_id(),
            event_type: event_type.into(),
            source: Some(source.into()),
            target: None,
            data,
            priority: EventPriority::default(),
            timestamp: SystemTime::now(),
            metadata: HashMap::new(),
        }
    }

    /// Set event priority
    pub fn with_priority(mut self, priority: EventPriority) -> Self {
        self.priority = priority;
        self
    }

    /// Set event target(s)
    pub fn with_target(mut self, target: Vec<String>) -> Self {
        self.target = Some(target);
        self
    }

    /// Set single target
    pub fn with_single_target(mut self, target: impl Into<String>) -> Self {
        self.target = Some(vec![target.into()]);
        self
    }

    /// Add metadata
    pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }

    /// Check if event is targeted to a specific plugin
    pub fn is_targeted_to(&self, plugin_name: &str) -> bool {
        match &self.target {
            None => true, // Broadcast event
            Some(targets) => targets.contains(&plugin_name.to_string()),
        }
    }

    /// Generate unique event ID
    fn generate_id() -> EventId {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or(Duration::ZERO)
            .as_nanos() as EventId
    }
}

/// Event handler trait for processing events
#[async_trait]
pub trait EventHandler: Send + Sync {
    /// Handle an event
    async fn handle_event(&self, event: &Event) -> PluginResult<()>;

    /// Get the event types this handler is interested in
    fn event_types(&self) -> Vec<String>;

    /// Get handler priority (higher priority handlers are called first)
    fn priority(&self) -> EventPriority {
        EventPriority::Normal
    }
}

/// Event listener for plugin hooks
#[derive(Debug, Clone)]
pub struct HookEvent {
    /// The plugin name
    pub plugin_name: String,
    /// Hook type
    pub hook_type: HookType,
    /// Hook execution result (for post-hooks)
    pub result: Option<Result<(), PluginError>>,
    /// Additional context data
    pub context: serde_json::Value,
}

/// Types of plugin hooks
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum HookType {
    BeforeInitialize,
    AfterInitialize,
    BeforeExecute,
    AfterExecute,
    BeforeCleanup,
    AfterCleanup,
    OnError,
    OnSuccess,
}

impl std::fmt::Display for HookType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            HookType::BeforeInitialize => write!(f, "before_initialize"),
            HookType::AfterInitialize => write!(f, "after_initialize"),
            HookType::BeforeExecute => write!(f, "before_execute"),
            HookType::AfterExecute => write!(f, "after_execute"),
            HookType::BeforeCleanup => write!(f, "before_cleanup"),
            HookType::AfterCleanup => write!(f, "after_cleanup"),
            HookType::OnError => write!(f, "on_error"),
            HookType::OnSuccess => write!(f, "on_success"),
        }
    }
}

/// Type alias for event handler storage
type EventHandlers = Arc<RwLock<HashMap<String, Vec<Arc<dyn EventHandler>>>>>;

/// Event bus for managing event publishing and subscription
pub struct EventBus {
    /// Broadcast channel for events
    sender: broadcast::Sender<Event>,
    /// Event handlers by event type
    handlers: EventHandlers,
    /// Event history (limited size)
    history: Arc<RwLock<Vec<Event>>>,
    /// Maximum history size
    max_history: usize,
}

impl EventBus {
    /// Create a new event bus
    pub fn new() -> Self {
        let (sender, _) = broadcast::channel(1000);
        Self {
            sender,
            handlers: Arc::new(RwLock::new(HashMap::new())),
            history: Arc::new(RwLock::new(Vec::new())),
            max_history: 1000,
        }
    }

    /// Create a new event bus with custom capacity
    pub fn with_capacity(capacity: usize, max_history: usize) -> Self {
        let (sender, _) = broadcast::channel(capacity);
        Self {
            sender,
            handlers: Arc::new(RwLock::new(HashMap::new())),
            history: Arc::new(RwLock::new(Vec::new())),
            max_history,
        }
    }

    /// Publish an event
    pub async fn publish(&self, event: Event) -> PluginResult<()> {
        // Add to history
        {
            let mut history = self.history.write().unwrap();
            history.push(event.clone());
            if history.len() > self.max_history {
                history.remove(0);
            }
        }

        // Call registered handlers
        self.call_handlers(&event).await?;

        // Broadcast to subscribers
        if let Err(e) = self.sender.send(event) {
            return Err(PluginError::EventError(format!(
                "Failed to broadcast event: {e}"
            )));
        }

        Ok(())
    }

    /// Subscribe to events
    pub fn subscribe(&self) -> broadcast::Receiver<Event> {
        self.sender.subscribe()
    }

    /// Register an event handler
    pub fn register_handler(&self, handler: Arc<dyn EventHandler>) {
        let mut handlers = self.handlers.write().unwrap();
        for event_type in handler.event_types() {
            handlers
                .entry(event_type)
                .or_default()
                .push(handler.clone());
        }
    }

    /// Unregister event handlers for specific event types
    pub fn unregister_handlers(&self, event_types: &[String]) {
        let mut handlers = self.handlers.write().unwrap();
        for event_type in event_types {
            handlers.remove(event_type);
        }
    }

    /// Get event history
    pub fn get_history(&self) -> Vec<Event> {
        self.history.read().unwrap().clone()
    }

    /// Get event history filtered by type
    pub fn get_history_by_type(&self, event_type: &str) -> Vec<Event> {
        self.history
            .read()
            .unwrap()
            .iter()
            .filter(|e| e.event_type == event_type)
            .cloned()
            .collect()
    }

    /// Clear event history
    pub fn clear_history(&self) {
        self.history.write().unwrap().clear();
    }

    /// Call registered handlers for an event
    async fn call_handlers(&self, event: &Event) -> PluginResult<()> {
        let handlers = {
            let handlers_map = self.handlers.read().unwrap();
            handlers_map
                .get(&event.event_type)
                .cloned()
                .unwrap_or_default()
        };

        // Sort handlers by priority (highest first)
        let mut sorted_handlers = handlers;
        sorted_handlers.sort_by_key(|b| std::cmp::Reverse(b.priority()));

        // Call handlers in priority order
        for handler in sorted_handlers {
            if let Err(e) = handler.handle_event(event).await {
                // Log error but continue with other handlers
                eprintln!("Event handler error for {}: {}", event.event_type, e);
            }
        }

        Ok(())
    }
}

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

/// Standard system events
pub mod system_events {
    use super::*;

    pub const PLUGIN_REGISTERED: &str = "plugin.registered";
    pub const PLUGIN_UNREGISTERED: &str = "plugin.unregistered";
    pub const PLUGIN_INITIALIZED: &str = "plugin.initialized";
    pub const PLUGIN_EXECUTION_STARTED: &str = "plugin.execution.started";
    pub const PLUGIN_EXECUTION_COMPLETED: &str = "plugin.execution.completed";
    pub const PLUGIN_EXECUTION_FAILED: &str = "plugin.execution.failed";
    pub const PLUGIN_CLEANUP_STARTED: &str = "plugin.cleanup.started";
    pub const PLUGIN_CLEANUP_COMPLETED: &str = "plugin.cleanup.completed";
    pub const PIPELINE_STARTED: &str = "pipeline.started";
    pub const PIPELINE_COMPLETED: &str = "pipeline.completed";
    pub const PIPELINE_FAILED: &str = "pipeline.failed";

    /// Create a plugin registered event
    pub fn plugin_registered(plugin_name: impl Into<String>) -> Event {
        Event::new(
            PLUGIN_REGISTERED,
            serde_json::json!({
                "plugin_name": plugin_name.into()
            }),
        )
        .with_priority(EventPriority::Normal)
    }

    /// Create a plugin execution started event
    pub fn plugin_execution_started(plugin_name: impl Into<String>) -> Event {
        Event::from_plugin(
            PLUGIN_EXECUTION_STARTED,
            plugin_name.into(),
            serde_json::json!({}),
        )
        .with_priority(EventPriority::Normal)
    }

    /// Create a plugin execution completed event
    pub fn plugin_execution_completed(plugin_name: impl Into<String>, duration: Duration) -> Event {
        Event::from_plugin(
            PLUGIN_EXECUTION_COMPLETED,
            plugin_name.into(),
            serde_json::json!({
                "duration_ms": duration.as_millis()
            }),
        )
        .with_priority(EventPriority::Normal)
    }

    /// Create a plugin execution failed event
    pub fn plugin_execution_failed(plugin_name: impl Into<String>, error: &PluginError) -> Event {
        Event::from_plugin(
            PLUGIN_EXECUTION_FAILED,
            plugin_name.into(),
            serde_json::json!({
                "error": error.to_string()
            }),
        )
        .with_priority(EventPriority::High)
    }

    /// Create a plugin initialized event
    pub fn plugin_initialized(plugin_name: impl Into<String>) -> Event {
        Event::from_plugin(
            PLUGIN_INITIALIZED,
            plugin_name.into(),
            serde_json::json!({}),
        )
        .with_priority(EventPriority::Normal)
    }

    /// Create a plugin cleanup started event
    pub fn plugin_cleanup_started(plugin_name: impl Into<String>) -> Event {
        Event::from_plugin(
            PLUGIN_CLEANUP_STARTED,
            plugin_name.into(),
            serde_json::json!({}),
        )
        .with_priority(EventPriority::Normal)
    }

    /// Create a plugin cleanup completed event
    pub fn plugin_cleanup_completed(plugin_name: impl Into<String>) -> Event {
        Event::from_plugin(
            PLUGIN_CLEANUP_COMPLETED,
            plugin_name.into(),
            serde_json::json!({}),
        )
        .with_priority(EventPriority::Normal)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use tokio::time::{timeout, Duration};

    #[tokio::test]
    async fn test_event_creation() {
        let event = Event::new("test.event", json!({"key": "value"}));

        assert_eq!(event.event_type, "test.event");
        assert_eq!(event.data, json!({"key": "value"}));
        assert_eq!(event.priority, EventPriority::Normal);
        assert!(event.source.is_none());
        assert!(event.target.is_none());
    }

    #[tokio::test]
    async fn test_event_from_plugin() {
        let event = Event::from_plugin("plugin.event", "test-plugin", json!({"data": "test"}))
            .with_priority(EventPriority::High)
            .with_single_target("target-plugin")
            .with_metadata("key", "value");

        assert_eq!(event.event_type, "plugin.event");
        assert_eq!(event.source, Some("test-plugin".to_string()));
        assert_eq!(event.target, Some(vec!["target-plugin".to_string()]));
        assert_eq!(event.priority, EventPriority::High);
        assert_eq!(event.metadata.get("key"), Some(&"value".to_string()));
    }

    #[tokio::test]
    async fn test_event_targeting() {
        let broadcast_event = Event::new("broadcast", json!({}));
        assert!(broadcast_event.is_targeted_to("any-plugin"));

        let targeted_event = Event::new("targeted", json!({}))
            .with_target(vec!["plugin-a".to_string(), "plugin-b".to_string()]);

        assert!(targeted_event.is_targeted_to("plugin-a"));
        assert!(targeted_event.is_targeted_to("plugin-b"));
        assert!(!targeted_event.is_targeted_to("plugin-c"));
    }

    struct TestHandler {
        call_count: Arc<AtomicUsize>,
        event_types: Vec<String>,
        priority: EventPriority,
    }

    impl TestHandler {
        fn new(event_types: Vec<String>, priority: EventPriority) -> Self {
            Self {
                call_count: Arc::new(AtomicUsize::new(0)),
                event_types,
                priority,
            }
        }

        fn call_count(&self) -> usize {
            self.call_count.load(Ordering::Relaxed)
        }
    }

    #[async_trait]
    impl EventHandler for TestHandler {
        async fn handle_event(&self, _event: &Event) -> PluginResult<()> {
            self.call_count.fetch_add(1, Ordering::Relaxed);
            Ok(())
        }

        fn event_types(&self) -> Vec<String> {
            self.event_types.clone()
        }

        fn priority(&self) -> EventPriority {
            self.priority
        }
    }

    #[tokio::test]
    async fn test_event_bus_basic() {
        let bus = EventBus::new();
        let _receiver = bus.subscribe(); // Keep channel open
        let event = Event::new("test.event", json!({"test": true}));

        // Should publish without error
        bus.publish(event.clone()).await.unwrap();

        // Check history
        let history = bus.get_history();
        assert_eq!(history.len(), 1);
        assert_eq!(history[0].event_type, "test.event");
    }

    #[tokio::test]
    async fn test_event_bus_subscription() {
        let bus = EventBus::new();
        let mut receiver = bus.subscribe();

        let event = Event::new("subscription.test", json!({"data": "test"}));

        // Publish event
        bus.publish(event.clone()).await.unwrap();

        // Receive event
        let received = timeout(Duration::from_millis(100), receiver.recv())
            .await
            .unwrap()
            .unwrap();

        assert_eq!(received.event_type, "subscription.test");
        assert_eq!(received.data, json!({"data": "test"}));
    }

    #[tokio::test]
    async fn test_event_bus_handlers() {
        let bus = EventBus::new();
        let _receiver = bus.subscribe(); // Keep channel open

        let handler1 = Arc::new(TestHandler::new(
            vec!["test.event".to_string()],
            EventPriority::Normal,
        ));
        let handler2 = Arc::new(TestHandler::new(
            vec!["test.event".to_string(), "other.event".to_string()],
            EventPriority::High,
        ));

        bus.register_handler(handler1.clone());
        bus.register_handler(handler2.clone());

        // Publish test.event
        let event = Event::new("test.event", json!({}));
        bus.publish(event).await.unwrap();

        // Both handlers should be called
        assert_eq!(handler1.call_count(), 1);
        assert_eq!(handler2.call_count(), 1);

        // Publish other.event
        let event = Event::new("other.event", json!({}));
        bus.publish(event).await.unwrap();

        // Only handler2 should be called
        assert_eq!(handler1.call_count(), 1);
        assert_eq!(handler2.call_count(), 2);
    }

    #[tokio::test]
    async fn test_event_history() {
        let bus = EventBus::with_capacity(100, 5); // Small history for testing
        let _receiver = bus.subscribe(); // Keep channel open

        // Publish more events than history size
        for i in 0..10 {
            let event = Event::new(format!("event.{i}"), json!({"index": i}));
            bus.publish(event).await.unwrap();
        }

        let history = bus.get_history();
        assert_eq!(history.len(), 5); // Should be limited to max_history

        // Should contain the last 5 events
        for (i, event) in history.iter().enumerate() {
            assert_eq!(event.event_type, format!("event.{}", i + 5));
        }
    }

    #[tokio::test]
    async fn test_system_events() {
        let event = system_events::plugin_registered("test-plugin");
        assert_eq!(event.event_type, system_events::PLUGIN_REGISTERED);
        assert_eq!(event.data["plugin_name"], "test-plugin");

        let duration = Duration::from_millis(100);
        let event = system_events::plugin_execution_completed("test-plugin", duration);
        assert_eq!(event.event_type, system_events::PLUGIN_EXECUTION_COMPLETED);
        assert_eq!(event.data["duration_ms"], 100);
    }

    #[tokio::test]
    async fn test_hook_type_display() {
        assert_eq!(HookType::BeforeExecute.to_string(), "before_execute");
        assert_eq!(HookType::AfterExecute.to_string(), "after_execute");
        assert_eq!(HookType::OnError.to_string(), "on_error");
    }
}