AirLibrary/Plugins/
EventBus.rs1#![allow(unused_variables, dead_code, unused_imports)]
2
3use std::sync::Arc;
10
11use async_trait::async_trait;
12use serde::{Deserialize, Serialize};
13use tokio::sync::RwLock;
14
15use crate::{Result, dev_log};
16
17#[derive(Debug, Clone, Serialize, Deserialize)]
19pub enum PluginEvent {
20 Loaded { plugin_id:String },
21 Started { plugin_id:String },
22 Stopped { plugin_id:String },
23 Unloaded { plugin_id:String },
24 Error { plugin_id:String, error:String },
25 Message { from:String, to:String, action:String },
26 ConfigChanged { old:serde_json::Value, new:serde_json::Value },
27}
28
29#[async_trait]
31pub trait PluginEventHandler: Send + Sync {
32 async fn Event(&self, event:&PluginEvent) -> Result<()>;
33}
34
35pub struct PluginEventBus {
37 handlers:Arc<RwLock<Vec<Box<dyn PluginEventHandler>>>>,
38}
39
40impl PluginEventBus {
41 pub fn new() -> Self { Self { handlers:Arc::new(RwLock::new(vec![])) } }
42
43 pub async fn register_handler(&self, handler:Box<dyn PluginEventHandler>) {
44 self.handlers.write().await.push(handler);
45 }
46
47 pub async fn emit(&self, event:PluginEvent) {
50 let handlers = self.handlers.read().await;
51 for handler in handlers.iter() {
52 if let Err(Error) = handler.Event(&event).await {
53 dev_log!("extensions", "error: [PluginEventBus] Event handler error: {}", Error);
54 }
55 }
56 }
57}
58
59impl Default for PluginEventBus {
60 fn default() -> Self { Self::new() }
61}