use serde_json::Value as JsonValue;
use std::collections::HashMap;
use std::sync::Arc;
use super::traits::{Plugin, PluginError, PluginLifecycleStage};
use super::{normalize_plugin_lookup_name, normalize_plugin_name};
use crate::error::BaseError;
pub struct PluginRegistry {
plugins: HashMap<String, Arc<dyn Plugin>>,
sorted_plugins: Vec<Arc<dyn Plugin>>,
configs: HashMap<String, JsonValue>,
}
impl PluginRegistry {
pub(super) fn new(
plugins: HashMap<String, Arc<dyn Plugin>>,
configs: HashMap<String, JsonValue>,
) -> Result<Self, BaseError> {
let sorted_plugins = Self::compute_topological_sort(&plugins)?;
Ok(Self {
plugins,
sorted_plugins,
configs,
})
}
pub fn get(&self, name: &str) -> Option<&Arc<dyn Plugin>> {
let name = normalize_plugin_lookup_name(name)?;
self.plugins.get(name)
}
pub fn get_all(&self) -> &[Arc<dyn Plugin>] {
&self.sorted_plugins
}
pub fn get_config(&self, name: &str) -> Option<&JsonValue> {
let name = normalize_plugin_lookup_name(name)?;
self.configs.get(name)
}
pub async fn shutdown(&self) -> Result<(), BaseError> {
let mut errors: Vec<(String, PluginError)> = Vec::new();
for plugin in self.sorted_plugins.iter().rev() {
let name = plugin.name();
if let Err(e) = plugin.on_shutdown().await {
log::error!("插件 {} 关闭失败: {}", name, e);
errors.push((name.to_string(), e));
} else {
log::info!("插件已关闭: {}", name);
}
}
if let Some((plugin, source)) = errors.into_iter().next() {
Err(BaseError::PluginLifecycleFailed {
plugin,
stage: PluginLifecycleStage::Shutdown,
source,
})
} else {
Ok(())
}
}
fn compute_topological_sort(
plugins: &HashMap<String, Arc<dyn Plugin>>,
) -> Result<Vec<Arc<dyn Plugin>>, BaseError> {
let mut in_degree: HashMap<String, usize> = HashMap::new();
let mut graph: HashMap<String, Vec<String>> = HashMap::new();
for (name, plugin) in plugins {
let name = name.clone();
in_degree.entry(name.clone()).or_insert(0);
for dep in plugin.dependencies() {
let dep = normalize_plugin_name(dep)?;
graph.entry(dep.to_string()).or_default().push(name.clone());
*in_degree.entry(name.clone()).or_insert(0) += 1;
}
}
let mut queue: Vec<String> = in_degree
.iter()
.filter(|(_, °ree)| degree == 0)
.map(|(name, _)| name.clone())
.collect();
let mut sorted_names: Vec<String> = Vec::new();
while let Some(node) = queue.pop() {
sorted_names.push(node.clone());
if let Some(neighbors) = graph.get(&node) {
for neighbor in neighbors {
if let Some(degree) = in_degree.get_mut(neighbor) {
*degree -= 1;
if *degree == 0 {
queue.push(neighbor.clone());
}
}
}
}
}
if sorted_names.len() < plugins.len() {
let unsorted: Vec<String> = plugins
.keys()
.filter(|name| !sorted_names.contains(name))
.cloned()
.collect();
let unsorted_str = unsorted.join(", ");
return Err(BaseError::PluginCircularDependency(format!(
"循环依赖涉及的插件: {}",
unsorted_str
)));
}
let sorted_plugins: Vec<Arc<dyn Plugin>> = sorted_names
.iter()
.filter_map(|name| plugins.get(name).cloned())
.collect();
Ok(sorted_plugins)
}
}