pluggable 0.1.0

A comprehensive, async plugin system for Rust applications with dependency management and security
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
//! Plugin registry for managing and discovering plugins

use petgraph::Graph;
use std::collections::HashMap;

use crate::core::discovery::{PluginDiscovery, PluginRegistryTrait};
use crate::core::{Plugin, PluginError, PluginResult};

/// Registry for managing plugins and their dependencies
pub struct PluginRegistry {
    plugins: HashMap<String, Box<dyn Plugin>>,
    dependency_graph: Graph<String, ()>,
    name_to_index: HashMap<String, petgraph::graph::NodeIndex>,
}

impl PluginRegistry {
    /// Create a new empty plugin registry
    pub fn new() -> Self {
        Self {
            plugins: HashMap::new(),
            dependency_graph: Graph::new(),
            name_to_index: HashMap::new(),
        }
    }

    /// Register a plugin with the registry
    pub fn register<P: Plugin + 'static>(&mut self, plugin: P) -> PluginResult<()> {
        let metadata = plugin.metadata();
        let plugin_name = metadata.name.clone();

        // Check if plugin is already registered
        if self.plugins.contains_key(&plugin_name) {
            return Err(PluginError::InvalidMetadata(format!(
                "Plugin '{plugin_name}' is already registered"
            )));
        }

        // Add plugin to the dependency graph
        let node_index = self.dependency_graph.add_node(plugin_name.clone());
        self.name_to_index.insert(plugin_name.clone(), node_index);

        // Store the plugin
        self.plugins.insert(plugin_name.clone(), Box::new(plugin));

        // Rebuild all dependency edges since we might have new dependencies to connect
        self.rebuild_dependency_edges();

        Ok(())
    }

    /// Rebuild all dependency edges in the graph
    fn rebuild_dependency_edges(&mut self) {
        // Clear existing edges
        self.dependency_graph.clear_edges();

        // Add all dependency edges
        for (plugin_name, plugin) in &self.plugins {
            let plugin_node = self.name_to_index[plugin_name];
            let metadata = plugin.metadata();

            for dependency in &metadata.dependencies {
                if let Some(&dep_node) = self.name_to_index.get(dependency) {
                    self.dependency_graph.add_edge(dep_node, plugin_node, ());
                }
            }
        }
    }

    /// Get a plugin by name
    pub fn get_plugin(&self, name: &str) -> Option<&dyn Plugin> {
        self.plugins.get(name).map(|p| p.as_ref())
    }

    /// Get a mutable reference to a plugin by name
    /// Note: This method temporarily takes ownership to work around lifetime issues
    pub fn take_plugin(&mut self, name: &str) -> Option<Box<dyn Plugin>> {
        self.plugins.remove(name)
    }

    /// Put a plugin back into the registry (used with take_plugin)
    pub fn put_plugin(&mut self, plugin: Box<dyn Plugin>) -> PluginResult<()> {
        let name = plugin.metadata().name.clone();
        if self.plugins.contains_key(&name) {
            return Err(PluginError::InvalidMetadata(format!(
                "Plugin '{name}' already exists"
            )));
        }
        self.plugins.insert(name, plugin);
        Ok(())
    }

    /// Get all registered plugin names
    pub fn plugin_names(&self) -> Vec<String> {
        self.plugins.keys().cloned().collect()
    }

    /// Check if a plugin is registered
    pub fn has_plugin(&self, name: &str) -> bool {
        self.plugins.contains_key(name)
    }

    /// Validate that all plugin dependencies are satisfied
    pub fn validate_dependencies(&self) -> PluginResult<()> {
        for (plugin_name, plugin) in &self.plugins {
            let metadata = plugin.metadata();
            for dependency in &metadata.dependencies {
                if !self.has_plugin(dependency) {
                    return Err(PluginError::DependencyNotSatisfied {
                        plugin: plugin_name.clone(),
                        dependency: dependency.clone(),
                    });
                }
            }
        }
        Ok(())
    }

    /// Resolve plugin execution order based on dependencies
    /// Returns plugins grouped in execution batches (plugins in same batch can run in parallel)
    pub fn resolve_execution_order(&self) -> PluginResult<Vec<Vec<String>>> {
        // First validate all dependencies are satisfied
        self.validate_dependencies()?;

        // If no plugins, return empty
        if self.plugins.is_empty() {
            return Ok(vec![]);
        }

        // Group plugins into execution batches using a simpler approach
        let mut batches = Vec::new();
        let mut remaining_plugins: std::collections::HashSet<_> =
            self.plugins.keys().cloned().collect();

        while !remaining_plugins.is_empty() {
            let mut current_batch = Vec::new();

            // Find all plugins whose dependencies have been satisfied
            for plugin_name in &remaining_plugins {
                let plugin = self.plugins.get(plugin_name).unwrap();
                let metadata = plugin.metadata();

                let dependencies_satisfied = metadata
                    .dependencies
                    .iter()
                    .all(|dep| !remaining_plugins.contains(dep));

                if dependencies_satisfied {
                    current_batch.push(plugin_name.clone());
                }
            }

            if current_batch.is_empty() {
                return Err(PluginError::ConfigurationError(
                    "Unable to resolve execution order - possible circular dependency".to_string(),
                ));
            }

            // Remove plugins from remaining set
            for plugin_name in &current_batch {
                remaining_plugins.remove(plugin_name);
            }

            batches.push(current_batch);
        }

        Ok(batches)
    }

    /// Get the number of registered plugins
    pub fn len(&self) -> usize {
        self.plugins.len()
    }

    /// Check if the registry is empty
    pub fn is_empty(&self) -> bool {
        self.plugins.is_empty()
    }

    /// Auto-discover and register plugins using the discovery system
    pub fn auto_discover(&mut self) -> PluginResult<usize> {
        use crate::core::discovery::PluginDiscovery;

        let mut discovery = PluginDiscovery::new();
        discovery.auto_register_all(self)
    }

    /// Register plugins from a discovery instance
    pub fn register_from_discovery(
        &mut self,
        discovery: &PluginDiscovery,
        plugin_names: &[String],
    ) -> PluginResult<usize> {
        let mut registered_count = 0;

        for name in plugin_names {
            match discovery.create_plugin(name) {
                Ok(plugin) => {
                    if let Err(e) = self.register_plugin(plugin) {
                        eprintln!("Warning: Failed to register plugin '{name}': {e}");
                        continue;
                    }
                    registered_count += 1;
                }
                Err(e) => {
                    eprintln!("Warning: Failed to create plugin '{name}': {e}");
                    continue;
                }
            }
        }

        Ok(registered_count)
    }

    /// Register all plugins from a discovery instance
    pub fn register_all_from_discovery(
        &mut self,
        discovery: &mut PluginDiscovery,
    ) -> PluginResult<usize> {
        discovery.auto_register_all(self)
    }
}

impl Default for PluginRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl PluginRegistryTrait for PluginRegistry {
    fn register_plugin(&mut self, plugin: Box<dyn Plugin>) -> PluginResult<()> {
        let metadata = plugin.metadata();
        let plugin_name = metadata.name.clone();

        // Check if plugin is already registered
        if self.plugins.contains_key(&plugin_name) {
            return Err(PluginError::InvalidMetadata(format!(
                "Plugin '{plugin_name}' is already registered"
            )));
        }

        // Add plugin to the dependency graph
        let node_index = self.dependency_graph.add_node(plugin_name.clone());
        self.name_to_index.insert(plugin_name.clone(), node_index);

        // Store the plugin
        self.plugins.insert(plugin_name, plugin);

        // Rebuild all dependency edges since we might have new dependencies to connect
        self.rebuild_dependency_edges();

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::{PluginContext, PluginMetadata, PluginOutput};
    use async_trait::async_trait;
    use serde_json::json;

    // Test plugin implementations
    struct TestPluginA {
        metadata: PluginMetadata,
    }

    impl TestPluginA {
        fn new() -> Self {
            let mut metadata = PluginMetadata::new("plugin-a", "1.0.0");
            metadata.dependencies = vec![];
            Self { metadata }
        }
    }

    #[async_trait]
    impl Plugin for TestPluginA {
        fn metadata(&self) -> &PluginMetadata {
            &self.metadata
        }

        fn schema(&self) -> serde_json::Value {
            json!({})
        }

        async fn initialize(
            &mut self,
            _config: serde_json::Value,
            _context: &PluginContext,
        ) -> PluginResult<()> {
            Ok(())
        }

        async fn execute(&mut self, _context: &mut PluginContext) -> PluginResult<PluginOutput> {
            Ok(PluginOutput::success(json!({"plugin": "a"})))
        }

        async fn cleanup(&mut self, _context: &PluginContext) -> PluginResult<()> {
            Ok(())
        }
    }

    struct TestPluginB {
        metadata: PluginMetadata,
    }

    impl TestPluginB {
        fn new() -> Self {
            let mut metadata = PluginMetadata::new("plugin-b", "1.0.0");
            metadata.dependencies = vec!["plugin-a".to_string()];
            Self { metadata }
        }
    }

    #[async_trait]
    impl Plugin for TestPluginB {
        fn metadata(&self) -> &PluginMetadata {
            &self.metadata
        }

        fn schema(&self) -> serde_json::Value {
            json!({})
        }

        async fn initialize(
            &mut self,
            _config: serde_json::Value,
            _context: &PluginContext,
        ) -> PluginResult<()> {
            Ok(())
        }

        async fn execute(&mut self, _context: &mut PluginContext) -> PluginResult<PluginOutput> {
            Ok(PluginOutput::success(json!({"plugin": "b"})))
        }

        async fn cleanup(&mut self, _context: &PluginContext) -> PluginResult<()> {
            Ok(())
        }
    }

    #[test]
    fn test_registry_creation() {
        let registry = PluginRegistry::new();
        assert!(registry.is_empty());
        assert_eq!(registry.len(), 0);
    }

    #[test]
    fn test_plugin_registration() {
        let mut registry = PluginRegistry::new();
        let plugin = TestPluginA::new();

        assert!(registry.register(plugin).is_ok());
        assert_eq!(registry.len(), 1);
        assert!(registry.has_plugin("plugin-a"));
        assert!(!registry.has_plugin("plugin-b"));
    }

    #[test]
    fn test_duplicate_plugin_registration() {
        let mut registry = PluginRegistry::new();
        let plugin1 = TestPluginA::new();
        let plugin2 = TestPluginA::new();

        assert!(registry.register(plugin1).is_ok());
        let result = registry.register(plugin2);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            PluginError::InvalidMetadata(_)
        ));
    }

    #[test]
    fn test_plugin_retrieval() {
        let mut registry = PluginRegistry::new();
        let plugin = TestPluginA::new();

        registry.register(plugin).unwrap();

        let retrieved = registry.get_plugin("plugin-a");
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().metadata().name, "plugin-a");

        let not_found = registry.get_plugin("nonexistent");
        assert!(not_found.is_none());
    }

    #[test]
    fn test_dependency_validation_success() {
        let mut registry = PluginRegistry::new();
        let plugin_a = TestPluginA::new();
        let plugin_b = TestPluginB::new();

        registry.register(plugin_a).unwrap();
        registry.register(plugin_b).unwrap();

        assert!(registry.validate_dependencies().is_ok());
    }

    #[test]
    fn test_dependency_validation_failure() {
        let mut registry = PluginRegistry::new();
        let plugin_b = TestPluginB::new(); // Depends on plugin-a

        registry.register(plugin_b).unwrap();

        let result = registry.validate_dependencies();
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            PluginError::DependencyNotSatisfied { .. }
        ));
    }

    #[test]
    fn test_execution_order_resolution() {
        let mut registry = PluginRegistry::new();
        let plugin_a = TestPluginA::new();
        let plugin_b = TestPluginB::new();

        registry.register(plugin_a).unwrap();
        registry.register(plugin_b).unwrap();

        let execution_order = registry.resolve_execution_order().unwrap();

        // Should have 2 batches: [plugin-a], [plugin-b]
        assert_eq!(execution_order.len(), 2);
        assert_eq!(execution_order[0], vec!["plugin-a"]);
        assert_eq!(execution_order[1], vec!["plugin-b"]);
    }

    #[test]
    fn test_plugin_names() {
        let mut registry = PluginRegistry::new();
        let plugin_a = TestPluginA::new();
        let plugin_b = TestPluginB::new();

        registry.register(plugin_a).unwrap();
        registry.register(plugin_b).unwrap();

        let mut names = registry.plugin_names();
        names.sort();
        assert_eq!(names, vec!["plugin-a", "plugin-b"]);
    }
}