Skip to main content

yang_base/plugin/
registry.rs

1//! 插件注册表:运行阶段使用的不可变、无锁插件集合。
2
3use serde_json::Value as JsonValue;
4use std::collections::HashMap;
5use std::sync::Arc;
6
7use super::traits::{Plugin, PluginError, PluginLifecycleStage};
8use super::{normalize_plugin_lookup_name, normalize_plugin_name};
9use crate::error::BaseError;
10
11/// 插件注册表(运行阶段使用,无锁)
12///
13/// 由 `PluginManagerBuilder::build()` 生成,存储不可变的插件集合。
14/// 运行阶段通过 HashMap 直接查找,无需获取任何锁,实现 O(1) 无锁查找。
15/// 拓扑排序结果在构建时计算一次并缓存,多次调用 `get_all()` 无需重新计算。
16///
17/// # 示例
18///
19/// ```rust,ignore
20/// use yang_base::plugin::{Plugin, PluginManagerBuilder};
21///
22/// #[tokio::main]
23/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
24///     let mut builder = PluginManagerBuilder::new();
25///     builder.register(MyPlugin).await?;
26///     let registry = builder.build();
27///
28///     // 无锁 O(1) 查找
29///     if let Some(plugin) = registry.get("my_plugin") {
30///         println!("找到插件: {}", plugin.name());
31///     }
32///
33///     // 获取缓存的排序结果(无需重新计算)
34///     let all_plugins = registry.get_all();
35///
36///     // 关闭所有插件
37///     registry.shutdown().await?;
38///
39///     Ok(())
40/// }
41/// ```
42pub struct PluginRegistry {
43    /// 不可变插件映射(无 RwLock 包装,运行阶段无锁访问)
44    /// Key: 插件名称, Value: 插件实例
45    plugins: HashMap<String, Arc<dyn Plugin>>,
46
47    /// 拓扑排序缓存(构建时计算一次,运行阶段直接返回引用)
48    sorted_plugins: Vec<Arc<dyn Plugin>>,
49
50    /// 插件配置
51    /// Key: 插件名称, Value: 配置 JSON
52    configs: HashMap<String, JsonValue>,
53}
54
55impl PluginRegistry {
56    /// 创建新的插件注册表(仅 `plugin` 模块内可见的构造方法)
57    ///
58    /// 接收 plugins 和 configs,调用 `compute_topological_sort` 并缓存排序结果。
59    /// 此方法仅由 `PluginManagerBuilder::build()` 调用。
60    ///
61    /// # 参数
62    /// - `plugins`: 插件 HashMap
63    /// - `configs`: 配置 HashMap
64    ///
65    /// # 返回
66    /// - `Ok(PluginRegistry)`: 构建成功
67    /// - `Err(BaseError::PluginCircularDependency)`: 存在循环依赖
68    pub(super) fn new(
69        plugins: HashMap<String, Arc<dyn Plugin>>,
70        configs: HashMap<String, JsonValue>,
71    ) -> Result<Self, BaseError> {
72        // 构建时执行一次拓扑排序并缓存结果(内部检测循环依赖)
73        let sorted_plugins = Self::compute_topological_sort(&plugins)?;
74        Ok(Self {
75            plugins,
76            sorted_plugins,
77            configs,
78        })
79    }
80
81    /// 查找插件(无锁,O(1) HashMap 查找)
82    ///
83    /// 直接通过 HashMap 查找,无需获取任何锁。
84    ///
85    /// # 参数
86    /// - `name`: 插件名称
87    ///
88    /// # 返回
89    /// - `Some(&Arc<dyn Plugin>)`: 找到插件
90    /// - `None`: 插件不存在
91    ///
92    /// # 示例
93    ///
94    /// ```rust,ignore
95    /// use yang_base::plugin::PluginManagerBuilder;
96    ///
97    /// let registry = PluginManagerBuilder::new().build();
98    /// if let Some(plugin) = registry.get("my_plugin") {
99    ///     println!("找到插件: {}", plugin.name());
100    /// }
101    /// ```
102    pub fn get(&self, name: &str) -> Option<&Arc<dyn Plugin>> {
103        let name = normalize_plugin_lookup_name(name)?;
104        self.plugins.get(name)
105    }
106
107    /// 获取所有已注册插件(返回缓存的排序结果引用)
108    ///
109    /// 直接返回构建时缓存的拓扑排序结果,无需重新计算。
110    ///
111    /// # 返回
112    /// - 按依赖关系排序的插件切片引用
113    ///
114    /// # 示例
115    ///
116    /// ```rust,ignore
117    /// use yang_base::plugin::PluginManagerBuilder;
118    ///
119    /// let registry = PluginManagerBuilder::new().build();
120    /// let plugins = registry.get_all();
121    /// for plugin in plugins {
122    ///     println!("插件: {} v{}", plugin.name(), plugin.version());
123    /// }
124    /// ```
125    pub fn get_all(&self) -> &[Arc<dyn Plugin>] {
126        &self.sorted_plugins
127    }
128
129    /// 获取插件配置
130    ///
131    /// # 参数
132    /// - `name`: 插件名称
133    ///
134    /// # 返回
135    /// - `Some(&JsonValue)`: 插件配置
136    /// - `None`: 配置不存在
137    pub fn get_config(&self, name: &str) -> Option<&JsonValue> {
138        let name = normalize_plugin_lookup_name(name)?;
139        self.configs.get(name)
140    }
141
142    /// 关闭所有插件(逆序关闭)
143    ///
144    /// 按照拓扑排序的逆序调用每个插件的 `on_shutdown` 方法,
145    /// 确保依赖其他插件的插件先被关闭。
146    ///
147    /// # 返回
148    /// - `Ok(())`: 所有插件关闭成功
149    /// - `Err(BaseError)`: 某个插件关闭失败
150    ///
151    /// # 示例
152    ///
153    /// ```rust,ignore
154    /// use yang_base::plugin::PluginManagerBuilder;
155    ///
156    /// let registry = PluginManagerBuilder::new().build();
157    /// // ... 使用插件 ...
158    /// registry.shutdown().await?;
159    /// ```
160    pub async fn shutdown(&self) -> Result<(), BaseError> {
161        // 逆序遍历缓存的排序结果,确保依赖插件最后关闭
162        let mut errors: Vec<(String, PluginError)> = Vec::new();
163
164        for plugin in self.sorted_plugins.iter().rev() {
165            let name = plugin.name();
166            if let Err(e) = plugin.on_shutdown().await {
167                log::error!("插件 {} 关闭失败: {}", name, e);
168                errors.push((name.to_string(), e));
169            } else {
170                log::info!("插件已关闭: {}", name);
171            }
172        }
173
174        if let Some((plugin, source)) = errors.into_iter().next() {
175            Err(BaseError::PluginLifecycleFailed {
176                plugin,
177                stage: PluginLifecycleStage::Shutdown,
178                source,
179            })
180        } else {
181            Ok(())
182        }
183    }
184
185    /// 计算拓扑排序(私有方法,构建时调用一次)
186    ///
187    /// 使用 Kahn 算法对插件进行拓扑排序,确保依赖插件先于当前插件出现。
188    /// 当排序后的节点数小于插件总数时,说明存在循环依赖。
189    ///
190    /// # 参数
191    /// - `plugins`: 插件 HashMap 引用
192    ///
193    /// # 返回
194    /// - `Ok(Vec<Arc<dyn Plugin>>)`: 按依赖关系排序的插件列表
195    /// - `Err(BaseError::PluginCircularDependency)`: 存在循环依赖,错误信息含未排序节点
196    fn compute_topological_sort(
197        plugins: &HashMap<String, Arc<dyn Plugin>>,
198    ) -> Result<Vec<Arc<dyn Plugin>>, BaseError> {
199        // 构建入度表和邻接图
200        let mut in_degree: HashMap<String, usize> = HashMap::new();
201        let mut graph: HashMap<String, Vec<String>> = HashMap::new();
202
203        for (name, plugin) in plugins {
204            let name = name.clone();
205            in_degree.entry(name.clone()).or_insert(0);
206
207            for dep in plugin.dependencies() {
208                let dep = normalize_plugin_name(dep)?;
209                // dep -> name 的边:dep 是 name 的依赖,dep 先执行
210                graph.entry(dep.to_string()).or_default().push(name.clone());
211                *in_degree.entry(name.clone()).or_insert(0) += 1;
212            }
213        }
214
215        // Kahn 算法:从入度为 0 的节点开始
216        let mut queue: Vec<String> = in_degree
217            .iter()
218            .filter(|(_, &degree)| degree == 0)
219            .map(|(name, _)| name.clone())
220            .collect();
221
222        let mut sorted_names: Vec<String> = Vec::new();
223
224        while let Some(node) = queue.pop() {
225            sorted_names.push(node.clone());
226
227            if let Some(neighbors) = graph.get(&node) {
228                for neighbor in neighbors {
229                    if let Some(degree) = in_degree.get_mut(neighbor) {
230                        *degree -= 1;
231                        if *degree == 0 {
232                            queue.push(neighbor.clone());
233                        }
234                    }
235                }
236            }
237        }
238
239        // 检测循环依赖:若排序后的节点数小于插件总数,说明存在循环
240        if sorted_names.len() < plugins.len() {
241            // 找出未被排序的节点(即循环中的插件)
242            let unsorted: Vec<String> = plugins
243                .keys()
244                .filter(|name| !sorted_names.contains(name))
245                .cloned()
246                .collect();
247            let unsorted_str = unsorted.join(", ");
248            return Err(BaseError::PluginCircularDependency(format!(
249                "循环依赖涉及的插件: {}",
250                unsorted_str
251            )));
252        }
253
254        // 按排序顺序构建插件列表。这里使用注册阶段规范化后的 HashMap key,
255        // 避免插件对象 `name()` 返回带边界空格时与内部索引不一致。
256        let sorted_plugins: Vec<Arc<dyn Plugin>> = sorted_names
257            .iter()
258            .filter_map(|name| plugins.get(name).cloned())
259            .collect();
260
261        Ok(sorted_plugins)
262    }
263}