graphos_adapters/plugins/
registry.rs1use super::{Algorithm, Plugin};
4use graphos_common::utils::error::Result;
5use parking_lot::RwLock;
6use std::collections::HashMap;
7use std::sync::Arc;
8
9pub struct PluginRegistry {
11 plugins: RwLock<HashMap<String, Arc<dyn Plugin>>>,
13 algorithms: RwLock<HashMap<String, Arc<dyn Algorithm>>>,
15}
16
17impl PluginRegistry {
18 pub fn new() -> Self {
20 Self {
21 plugins: RwLock::new(HashMap::new()),
22 algorithms: RwLock::new(HashMap::new()),
23 }
24 }
25
26 pub fn register_plugin(&self, plugin: Arc<dyn Plugin>) -> Result<()> {
28 plugin.on_load()?;
29 self.plugins
30 .write()
31 .insert(plugin.name().to_string(), plugin);
32 Ok(())
33 }
34
35 pub fn unregister_plugin(&self, name: &str) -> Result<()> {
37 if let Some(plugin) = self.plugins.write().remove(name) {
38 plugin.on_unload()?;
39 }
40 Ok(())
41 }
42
43 pub fn get_plugin(&self, name: &str) -> Option<Arc<dyn Plugin>> {
45 self.plugins.read().get(name).cloned()
46 }
47
48 pub fn register_algorithm(&self, algorithm: Arc<dyn Algorithm>) {
50 self.algorithms
51 .write()
52 .insert(algorithm.name().to_string(), algorithm);
53 }
54
55 pub fn get_algorithm(&self, name: &str) -> Option<Arc<dyn Algorithm>> {
57 self.algorithms.read().get(name).cloned()
58 }
59
60 pub fn list_plugins(&self) -> Vec<String> {
62 self.plugins.read().keys().cloned().collect()
63 }
64
65 pub fn list_algorithms(&self) -> Vec<String> {
67 self.algorithms.read().keys().cloned().collect()
68 }
69}
70
71impl Default for PluginRegistry {
72 fn default() -> Self {
73 Self::new()
74 }
75}
76
77#[cfg(test)]
78mod tests {
79 use super::*;
80
81 struct TestPlugin;
82
83 impl Plugin for TestPlugin {
84 fn name(&self) -> &str {
85 "test"
86 }
87
88 fn version(&self) -> &str {
89 "1.0.0"
90 }
91 }
92
93 #[test]
94 fn test_plugin_registration() {
95 let registry = PluginRegistry::new();
96
97 let plugin = Arc::new(TestPlugin);
98 registry.register_plugin(plugin).unwrap();
99
100 assert!(registry.get_plugin("test").is_some());
101 assert_eq!(registry.list_plugins(), vec!["test"]);
102 }
103
104 #[test]
105 fn test_plugin_unregistration() {
106 let registry = PluginRegistry::new();
107
108 let plugin = Arc::new(TestPlugin);
109 registry.register_plugin(plugin).unwrap();
110
111 registry.unregister_plugin("test").unwrap();
112 assert!(registry.get_plugin("test").is_none());
113 }
114}