use serde_json::Value as JsonValue;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
use super::traits::{Plugin, PluginError, PluginLifecycleStage};
use super::{normalize_plugin_lookup_name, normalize_plugin_name};
use crate::error::BaseError;
pub struct PluginManager {
plugins: Arc<RwLock<HashMap<String, Arc<dyn Plugin>>>>,
configs: Arc<RwLock<HashMap<String, JsonValue>>>,
}
impl PluginManager {
pub fn new() -> Self {
Self {
plugins: Arc::new(RwLock::new(HashMap::new())),
configs: Arc::new(RwLock::new(HashMap::new())),
}
}
pub async fn register<P: Plugin + 'static>(&self, plugin: P) -> Result<(), BaseError> {
let name = normalize_plugin_name(plugin.name())?.to_string();
let plugin = Arc::new(plugin);
{
let plugins = self.plugins.read().await;
if plugins.contains_key(&name) {
return Err(BaseError::PluginAlreadyRegistered(name));
}
}
plugin
.on_register()
.await
.map_err(|source| BaseError::PluginLifecycleFailed {
plugin: name.clone(),
stage: PluginLifecycleStage::Register,
source,
})?;
{
let mut plugins = self.plugins.write().await;
if plugins.contains_key(&name) {
return Err(BaseError::PluginAlreadyRegistered(name));
}
plugins.insert(name.clone(), plugin);
}
log::info!("插件已注册: {}", name);
Ok(())
}
pub async fn get(&self, name: &str) -> Option<Arc<dyn Plugin>> {
let name = normalize_plugin_lookup_name(name)?;
let plugins = self.plugins.read().await;
plugins.get(name).cloned()
}
pub async fn get_all(&self) -> Vec<Arc<dyn Plugin>> {
let plugins = self.plugins.read().await;
let mut plugin_list: Vec<(String, Arc<dyn Plugin>)> = plugins
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
self.topological_sort(&mut plugin_list);
plugin_list.into_iter().map(|(_, p)| p).collect()
}
pub async fn load_config(&self, name: &str, config: JsonValue) -> Result<(), BaseError> {
let normalized_name = normalize_plugin_lookup_name(name)
.ok_or_else(|| BaseError::PluginNotFound(name.to_string()))?;
let plugin = self
.get(normalized_name)
.await
.ok_or_else(|| BaseError::PluginNotFound(normalized_name.to_string()))?;
if let Some(schema) = plugin.config_schema() {
self.validate_config(normalized_name, &config, &schema)?;
}
{
let mut configs = self.configs.write().await;
configs.insert(normalized_name.to_string(), config);
}
Ok(())
}
pub async fn get_config(&self, name: &str) -> Option<JsonValue> {
let name = normalize_plugin_lookup_name(name)?;
let configs = self.configs.read().await;
configs.get(name).cloned()
}
fn topological_sort(&self, plugins: &mut Vec<(String, Arc<dyn Plugin>)>) {
let mut in_degree: HashMap<String, usize> = HashMap::new();
let mut graph: HashMap<String, Vec<String>> = HashMap::new();
for (name, plugin) in plugins.iter() {
in_degree.entry(name.clone()).or_insert(0);
for dep in plugin.dependencies() {
let Ok(dep) = normalize_plugin_name(dep) else {
continue;
};
if !plugins.iter().any(|(n, _)| n == dep) {
log::warn!("插件 {} 声明的依赖 {:?} 未注册,无法建立依赖边", 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: Vec<String> = Vec::new();
while let Some(node) = queue.pop() {
sorted.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.len() < plugins.len() {
let circular: Vec<String> = plugins
.iter()
.map(|(n, _)| n.clone())
.filter(|n| !sorted.contains(n))
.collect();
log::error!(
"插件依赖图无法排序(存在环或断边),以下插件降级到最后: {}",
circular.join(", ")
);
sorted.extend(circular);
}
plugins.sort_by_key(|(n, _)| sorted.iter().position(|s| s == n).unwrap_or(usize::MAX));
}
fn validate_config(
&self,
plugin_name: &str,
config: &JsonValue,
schema: &JsonValue,
) -> Result<(), BaseError> {
#[cfg(feature = "plugin-schema")]
{
let validator = jsonschema::validator_for(schema).map_err(|e| {
BaseError::PluginConfigInvalid(
plugin_name.to_string(),
format!("Schema 编译失败: {}", e),
)
})?;
let error_msgs: Vec<String> = validator
.iter_errors(config)
.map(|e| e.to_string())
.collect();
if !error_msgs.is_empty() {
return Err(BaseError::PluginConfigInvalid(
plugin_name.to_string(),
error_msgs.join("; "),
));
}
}
#[cfg(not(feature = "plugin-schema"))]
{
let _ = (plugin_name, config, schema);
}
Ok(())
}
pub async fn shutdown(&self) -> Result<(), BaseError> {
let mut plugins = self.get_all().await;
plugins.reverse();
let mut errors: Vec<(String, PluginError)> = Vec::new();
for plugin in plugins {
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(())
}
}
}
impl Default for PluginManager {
fn default() -> Self {
Self::new()
}
}