yang_base/plugin/manager.rs
1//! 插件管理器:运行期可变的插件注册、查找、配置加载与关闭。
2
3use serde_json::Value as JsonValue;
4use std::collections::HashMap;
5use std::sync::Arc;
6use tokio::sync::RwLock;
7
8use super::traits::{Plugin, PluginError, PluginLifecycleStage};
9use super::{normalize_plugin_lookup_name, normalize_plugin_name};
10use crate::error::BaseError;
11
12/// 插件管理器
13///
14/// 负责插件的注册、查找和生命周期管理
15///
16/// # 示例
17///
18/// ```rust,ignore
19/// use yang_base::plugin::{Plugin, PluginManager};
20///
21/// #[tokio::main]
22/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
23/// let manager = PluginManager::new();
24///
25/// // 注册插件
26/// manager.register(MyPlugin).await?;
27///
28/// // 查找插件
29/// if let Some(plugin) = manager.get("my_plugin").await {
30/// println!("找到插件: {}", plugin.name());
31/// }
32///
33/// // 获取所有插件(按依赖顺序)
34/// let plugins = manager.get_all().await;
35///
36/// // 关闭所有插件
37/// manager.shutdown().await?;
38///
39/// Ok(())
40/// }
41/// ```
42pub struct PluginManager {
43 /// 已注册的插件
44 /// Key: 插件名称, Value: 插件实例
45 plugins: Arc<RwLock<HashMap<String, Arc<dyn Plugin>>>>,
46
47 /// 插件配置
48 /// Key: 插件名称, Value: 配置 JSON
49 configs: Arc<RwLock<HashMap<String, JsonValue>>>,
50}
51
52impl PluginManager {
53 /// 创建新的插件管理器
54 ///
55 /// # 返回
56 /// - 新的 PluginManager 实例
57 ///
58 /// # 示例
59 ///
60 /// ```rust
61 /// use yang_base::plugin::PluginManager;
62 ///
63 /// let manager = PluginManager::new();
64 /// ```
65 pub fn new() -> Self {
66 Self {
67 plugins: Arc::new(RwLock::new(HashMap::new())),
68 configs: Arc::new(RwLock::new(HashMap::new())),
69 }
70 }
71
72 /// 注册插件
73 ///
74 /// # 参数
75 /// - plugin: 插件实例
76 ///
77 /// # 返回
78 /// - Ok(()): 注册成功
79 /// - Err(BaseError): 注册失败(如插件名称重复)
80 ///
81 /// # 示例
82 ///
83 /// ```rust,ignore
84 /// use yang_base::plugin::{Plugin, PluginManager};
85 ///
86 /// let manager = PluginManager::new();
87 /// manager.register(MyPlugin).await?;
88 /// ```
89 pub async fn register<P: Plugin + 'static>(&self, plugin: P) -> Result<(), BaseError> {
90 let name = normalize_plugin_name(plugin.name())?.to_string();
91 let plugin = Arc::new(plugin);
92
93 // 第一阶段:读锁检查(快速路径,避免持写锁跨 await)
94 {
95 let plugins = self.plugins.read().await;
96 if plugins.contains_key(&name) {
97 return Err(BaseError::PluginAlreadyRegistered(name));
98 }
99 } // 尽早释放读锁
100
101 // 调用注册回调(不持任何锁)
102 plugin
103 .on_register()
104 .await
105 .map_err(|source| BaseError::PluginLifecycleFailed {
106 plugin: name.clone(),
107 stage: PluginLifecycleStage::Register,
108 source,
109 })?;
110
111 // 第二阶段:写锁 + 二次校验(防止 TOCTOU 竞态)
112 {
113 let mut plugins = self.plugins.write().await;
114 if plugins.contains_key(&name) {
115 return Err(BaseError::PluginAlreadyRegistered(name));
116 }
117 plugins.insert(name.clone(), plugin);
118 }
119
120 log::info!("插件已注册: {}", name);
121 Ok(())
122 }
123
124 /// 查找插件
125 ///
126 /// # 参数
127 /// - name: 插件名称
128 ///
129 /// # 返回
130 /// - `Some(Arc<dyn Plugin>)`: 找到插件
131 /// - None: 插件不存在
132 ///
133 /// # 示例
134 ///
135 /// ```rust,ignore
136 /// use yang_base::plugin::PluginManager;
137 ///
138 /// let manager = PluginManager::new();
139 /// if let Some(plugin) = manager.get("my_plugin").await {
140 /// println!("找到插件: {}", plugin.name());
141 /// }
142 /// ```
143 pub async fn get(&self, name: &str) -> Option<Arc<dyn Plugin>> {
144 let name = normalize_plugin_lookup_name(name)?;
145 let plugins = self.plugins.read().await;
146 plugins.get(name).cloned()
147 }
148
149 /// 获取所有已注册插件
150 ///
151 /// # 返回
152 /// - 插件列表(按依赖关系排序)
153 ///
154 /// # 示例
155 ///
156 /// ```rust,ignore
157 /// use yang_base::plugin::PluginManager;
158 ///
159 /// let manager = PluginManager::new();
160 /// let plugins = manager.get_all().await;
161 /// for plugin in plugins {
162 /// println!("插件: {} v{}", plugin.name(), plugin.version());
163 /// }
164 /// ```
165 pub async fn get_all(&self) -> Vec<Arc<dyn Plugin>> {
166 let plugins = self.plugins.read().await;
167 let mut plugin_list: Vec<_> = plugins.values().cloned().collect();
168
169 // 按依赖关系排序
170 self.topological_sort(&mut plugin_list);
171
172 plugin_list
173 }
174
175 /// 加载插件配置
176 ///
177 /// # 参数
178 /// - name: 插件名称
179 /// - config: 配置 JSON
180 ///
181 /// # 返回
182 /// - Ok(()): 加载成功
183 /// - Err(BaseError): 加载失败(如配置验证失败)
184 ///
185 /// # 示例
186 ///
187 /// ```rust,ignore
188 /// use yang_base::plugin::PluginManager;
189 /// use serde_json::json;
190 ///
191 /// let manager = PluginManager::new();
192 /// let config = json!({"key": "value"});
193 /// manager.load_config("my_plugin", config).await?;
194 /// ```
195 pub async fn load_config(&self, name: &str, config: JsonValue) -> Result<(), BaseError> {
196 let normalized_name = normalize_plugin_lookup_name(name)
197 .ok_or_else(|| BaseError::PluginNotFound(name.to_string()))?;
198
199 // 获取插件
200 let plugin = self
201 .get(normalized_name)
202 .await
203 .ok_or_else(|| BaseError::PluginNotFound(normalized_name.to_string()))?;
204
205 // 验证配置(插件未定义 config_schema 时跳过验证)
206 if let Some(schema) = plugin.config_schema() {
207 self.validate_config(normalized_name, &config, &schema)?;
208 }
209
210 // 存储配置
211 {
212 let mut configs = self.configs.write().await;
213 configs.insert(normalized_name.to_string(), config);
214 }
215
216 Ok(())
217 }
218
219 /// 获取插件配置
220 ///
221 /// # 参数
222 /// - name: 插件名称
223 ///
224 /// # 返回
225 /// - Some(JsonValue): 插件配置
226 /// - None: 配置不存在
227 ///
228 /// # 示例
229 ///
230 /// ```rust,ignore
231 /// use yang_base::plugin::PluginManager;
232 ///
233 /// let manager = PluginManager::new();
234 /// if let Some(config) = manager.get_config("my_plugin").await {
235 /// println!("配置: {:?}", config);
236 /// }
237 /// ```
238 pub async fn get_config(&self, name: &str) -> Option<JsonValue> {
239 let name = normalize_plugin_lookup_name(name)?;
240 let configs = self.configs.read().await;
241 configs.get(name).cloned()
242 }
243
244 /// 拓扑排序(按依赖关系排序)
245 ///
246 /// # 参数
247 /// - plugins: 插件列表
248 ///
249 /// # 说明
250 /// 使用 Kahn 算法进行拓扑排序,确保依赖插件先于当前插件
251 fn topological_sort(&self, plugins: &mut Vec<Arc<dyn Plugin>>) {
252 // 构建依赖图
253 let mut in_degree: HashMap<String, usize> = HashMap::new();
254 let mut graph: HashMap<String, Vec<String>> = HashMap::new();
255
256 for plugin in plugins.iter() {
257 let name = plugin.name().to_string();
258 in_degree.entry(name.clone()).or_insert(0);
259
260 for dep in plugin.dependencies() {
261 graph.entry(dep.to_string()).or_default().push(name.clone());
262 *in_degree.entry(name.clone()).or_insert(0) += 1;
263 }
264 }
265
266 // Kahn 算法
267 let mut queue: Vec<String> = in_degree
268 .iter()
269 .filter(|(_, °ree)| degree == 0)
270 .map(|(name, _)| name.clone())
271 .collect();
272
273 let mut sorted = Vec::new();
274
275 while let Some(node) = queue.pop() {
276 sorted.push(node.clone());
277
278 if let Some(neighbors) = graph.get(&node) {
279 for neighbor in neighbors {
280 if let Some(degree) = in_degree.get_mut(neighbor) {
281 *degree -= 1;
282 if *degree == 0 {
283 queue.push(neighbor.clone());
284 }
285 }
286 }
287 }
288 }
289
290 // 检测循环依赖:Kahn 算法结束后,未被排序的节点构成环
291 if sorted.len() < plugins.len() {
292 let circular: Vec<String> = plugins
293 .iter()
294 .filter(|p| !sorted.iter().any(|n| n == p.name()))
295 .map(|p| p.name().to_string())
296 .collect();
297 log::error!(
298 "检测到循环依赖,以下插件将无法按依赖顺序加载: {}",
299 circular.join(", ")
300 );
301 // 将循环中的插件追加到排序末尾,保证所有插件都出现在结果中
302 sorted.extend(circular);
303 }
304
305 // 重新排序插件列表
306 plugins.sort_by_key(|p| {
307 sorted
308 .iter()
309 .position(|n| n == p.name())
310 .unwrap_or(usize::MAX)
311 });
312 }
313
314 /// 验证配置
315 ///
316 /// 使用 jsonschema crate 对配置进行 JSON Schema 验证。
317 /// 未启用 `plugin-schema` feature 时跳过验证。
318 ///
319 /// # 参数
320 /// - `plugin_name`: 插件名称(用于错误信息)
321 /// - `config`: 配置 JSON
322 /// - `schema`: JSON Schema
323 ///
324 /// # 返回
325 /// - `Ok(())`: 验证通过
326 /// - `Err(BaseError::PluginConfigInvalid)`: 配置不符合 Schema
327 fn validate_config(
328 &self,
329 plugin_name: &str,
330 config: &JsonValue,
331 schema: &JsonValue,
332 ) -> Result<(), BaseError> {
333 // 使用 jsonschema crate 进行 JSON Schema 验证
334 #[cfg(feature = "plugin-schema")]
335 {
336 // 构建可复用的验证器
337 let validator = jsonschema::validator_for(schema).map_err(|e| {
338 BaseError::PluginConfigInvalid(
339 plugin_name.to_string(),
340 format!("Schema 编译失败: {}", e),
341 )
342 })?;
343
344 // 收集所有验证错误信息
345 let error_msgs: Vec<String> = validator
346 .iter_errors(config)
347 .map(|e| e.to_string())
348 .collect();
349
350 if !error_msgs.is_empty() {
351 return Err(BaseError::PluginConfigInvalid(
352 plugin_name.to_string(),
353 error_msgs.join("; "),
354 ));
355 }
356 }
357
358 // 未启用 plugin-schema feature 时,跳过验证直接返回成功
359 #[cfg(not(feature = "plugin-schema"))]
360 {
361 let _ = (plugin_name, config, schema);
362 }
363
364 Ok(())
365 }
366
367 /// 关闭所有插件
368 ///
369 /// 按照依赖关系的逆序调用插件的 on_shutdown 方法
370 ///
371 /// # 返回
372 /// - Ok(()): 关闭成功
373 /// - Err(BaseError): 关闭失败
374 ///
375 /// # 示例
376 ///
377 /// ```rust,ignore
378 /// use yang_base::plugin::PluginManager;
379 ///
380 /// let manager = PluginManager::new();
381 /// // ... 注册插件 ...
382 /// manager.shutdown().await?;
383 /// ```
384 pub async fn shutdown(&self) -> Result<(), BaseError> {
385 let mut plugins = self.get_all().await;
386 plugins.reverse(); // 逆序关闭
387
388 let mut errors: Vec<(String, PluginError)> = Vec::new();
389
390 for plugin in plugins {
391 let name = plugin.name();
392 if let Err(e) = plugin.on_shutdown().await {
393 log::error!("插件 {} 关闭失败: {}", name, e);
394 errors.push((name.to_string(), e));
395 } else {
396 log::info!("插件已关闭: {}", name);
397 }
398 }
399
400 if let Some((plugin, source)) = errors.into_iter().next() {
401 Err(BaseError::PluginLifecycleFailed {
402 plugin,
403 stage: PluginLifecycleStage::Shutdown,
404 source,
405 })
406 } else {
407 Ok(())
408 }
409 }
410}
411
412impl Default for PluginManager {
413 fn default() -> Self {
414 Self::new()
415 }
416}