Skip to main content

cool_plugin/
registry.rs

1//! 插件注册表
2
3use crate::plugin::{Plugin, PluginError, PluginInfo, PluginResult, PluginStatus};
4use parking_lot::RwLock;
5use std::collections::HashMap;
6use std::sync::Arc;
7use tokio::sync::Mutex;
8
9type PluginHandle = Arc<Mutex<Box<dyn Plugin>>>;
10type PluginMap = HashMap<String, PluginHandle>;
11
12/// 插件注册表
13pub struct PluginRegistry {
14    plugins: RwLock<PluginMap>,
15}
16
17impl PluginRegistry {
18    pub fn new() -> Self {
19        Self {
20            plugins: RwLock::new(HashMap::new()),
21        }
22    }
23
24    /// 注册插件
25    pub fn register<P: Plugin + 'static>(&self, plugin: P) {
26        let info = plugin.info();
27        let key = info.key.clone();
28
29        let mut plugins = self.plugins.write();
30        plugins.insert(key.clone(), Arc::new(Mutex::new(Box::new(plugin))));
31
32        tracing::info!("插件已注册: {} ({})", info.name, key);
33    }
34
35    /// 获取插件
36    pub fn get(&self, key: &str) -> Option<PluginHandle> {
37        let plugins = self.plugins.read();
38        plugins.get(key).cloned()
39    }
40
41    /// 移除插件
42    pub fn remove(&self, key: &str) -> Option<PluginHandle> {
43        let mut plugins = self.plugins.write();
44        plugins.remove(key)
45    }
46
47    /// 检查插件是否存在
48    pub fn contains(&self, key: &str) -> bool {
49        let plugins = self.plugins.read();
50        plugins.contains_key(key)
51    }
52
53    /// 获取所有插件信息
54    pub fn list(&self) -> Vec<PluginInfo> {
55        let plugins = self.plugins.read();
56        plugins.values().map(|p| p.blocking_lock().info()).collect()
57    }
58
59    /// 获取指定类型的插件
60    pub fn get_by_hook(&self, hook: &str) -> Vec<PluginHandle> {
61        let plugins = self.plugins.read();
62        plugins
63            .values()
64            .filter(|p| p.blocking_lock().info().hook == hook)
65            .cloned()
66            .collect()
67    }
68
69    /// 初始化所有插件
70    pub async fn init_all(&self, configs: HashMap<String, serde_json::Value>) -> PluginResult<()> {
71        let plugins: Vec<_> = {
72            let plugins = self.plugins.read();
73            plugins.values().cloned().collect()
74        };
75
76        for plugin in plugins {
77            let key = plugin.blocking_lock().info().key.clone();
78            let config = configs.get(&key).cloned().unwrap_or_default();
79
80            let mut plugin = plugin.lock().await;
81            plugin.init(config).await?;
82        }
83
84        Ok(())
85    }
86
87    /// 启动所有插件
88    pub async fn ready_all(&self) -> PluginResult<()> {
89        let plugins: Vec<_> = {
90            let plugins = self.plugins.read();
91            plugins.values().cloned().collect()
92        };
93
94        for plugin in plugins {
95            let mut plugin = plugin.lock().await;
96            plugin.ready().await?;
97        }
98
99        Ok(())
100    }
101
102    /// 销毁所有插件
103    pub async fn destroy_all(&self) -> PluginResult<()> {
104        let plugins: Vec<_> = {
105            let plugins = self.plugins.read();
106            plugins.values().cloned().collect()
107        };
108
109        for plugin in plugins.into_iter().rev() {
110            let mut plugin = plugin.lock().await;
111            plugin.destroy().await?;
112        }
113
114        Ok(())
115    }
116
117    /// 调用插件方法
118    pub async fn invoke(
119        &self,
120        key: &str,
121        method: &str,
122        params: serde_json::Value,
123    ) -> PluginResult<serde_json::Value> {
124        let plugin = self
125            .get(key)
126            .ok_or_else(|| PluginError::NotFound(key.to_string()))?;
127
128        let plugin = plugin.lock().await;
129        if plugin.status() == PluginStatus::Disabled {
130            return Err(PluginError::Disabled(key.to_string()));
131        }
132
133        plugin.invoke(method, params).await
134    }
135}
136
137impl Default for PluginRegistry {
138    fn default() -> Self {
139        Self::new()
140    }
141}
142
143/// 全局插件注册表
144static GLOBAL_PLUGIN_REGISTRY: once_cell::sync::Lazy<PluginRegistry> =
145    once_cell::sync::Lazy::new(PluginRegistry::new);
146
147/// 获取全局插件注册表
148pub fn global_plugin_registry() -> &'static PluginRegistry {
149    &GLOBAL_PLUGIN_REGISTRY
150}