Skip to main content

AirLibrary/Plugins/
EventBus.rs

1#![allow(unused_variables, dead_code, unused_imports)]
2
3//! Plugin event bus: publish/subscribe channel for plugin lifecycle events.
4//!
5//! Handlers register via `register_handler` and receive every subsequent
6//! `emit` call. Errors from individual handlers are logged but do not abort
7//! delivery to other handlers.
8
9use 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/// Events published through the bus during the plugin lifecycle.
18#[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 handler trait for plugin events.
30#[async_trait]
31pub trait PluginEventHandler: Send + Sync {
32	async fn Event(&self, event:&PluginEvent) -> Result<()>;
33}
34
35/// Fan-out event bus: each `emit` delivers to all registered handlers.
36pub 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	/// Deliver `event` to every registered handler. Handler errors are logged
48	/// and do not prevent delivery to subsequent handlers.
49	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}