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
//! Plugin discovery and auto-registration system

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};

use crate::core::{Plugin, PluginError, PluginMetadata, PluginResult};

/// Factory function type for creating plugin instances
pub type PluginFactoryFn = fn() -> Box<dyn Plugin>;

/// Plugin factory for auto-discovery and registration
#[derive(Debug, Clone)]
pub struct PluginFactory {
    /// Unique name of the plugin
    pub name: &'static str,
    /// Factory function to create plugin instances
    pub create: PluginFactoryFn,
    /// Plugin metadata for discovery
    pub metadata: fn() -> PluginMetadata,
    /// Plugin version for compatibility checking
    pub version: &'static str,
    /// Description of what the plugin does
    pub description: &'static str,
}

impl PluginFactory {
    /// Create a new plugin factory
    pub const fn new(
        name: &'static str,
        create: PluginFactoryFn,
        metadata: fn() -> PluginMetadata,
        version: &'static str,
        description: &'static str,
    ) -> Self {
        Self {
            name,
            create,
            metadata,
            version,
            description,
        }
    }

    /// Create a plugin instance using this factory
    pub fn create_plugin(&self) -> Box<dyn Plugin> {
        (self.create)()
    }

    /// Get plugin metadata
    pub fn get_metadata(&self) -> PluginMetadata {
        (self.metadata)()
    }
}

// Use inventory to collect plugin factories
inventory::collect!(PluginFactory);

/// Plugin discovery manager for finding and registering plugins
#[derive(Debug)]
pub struct PluginDiscovery {
    /// Discovered plugin factories by name
    factories: HashMap<String, PluginFactory>,
    /// Search paths for plugin discovery
    search_paths: Vec<PathBuf>,
    /// Cache of discovered plugins
    discovery_cache: Arc<Mutex<Option<Vec<PluginFactory>>>>,
}

impl PluginDiscovery {
    /// Create a new plugin discovery manager
    pub fn new() -> Self {
        Self {
            factories: HashMap::new(),
            search_paths: Vec::new(),
            discovery_cache: Arc::new(Mutex::new(None)),
        }
    }

    /// Add a search path for plugin discovery
    pub fn add_search_path(&mut self, path: PathBuf) {
        self.search_paths.push(path);
        // Clear cache when search paths change
        *self.discovery_cache.lock().unwrap() = None;
    }

    /// Get all search paths
    pub fn search_paths(&self) -> &[PathBuf] {
        &self.search_paths
    }

    /// Discover all available plugins using the inventory system
    pub fn discover_plugins(&mut self) -> PluginResult<Vec<PluginFactory>> {
        // Check cache first
        {
            let cache = self.discovery_cache.lock().unwrap();
            if let Some(ref cached) = *cache {
                return Ok(cached.clone());
            }
        }

        let mut discovered = Vec::new();
        self.factories.clear();

        // Collect all registered plugin factories
        for factory in inventory::iter::<PluginFactory> {
            let factory_clone = factory.clone();

            // Validate factory
            if let Err(e) = self.validate_factory(&factory_clone) {
                eprintln!(
                    "Warning: Invalid plugin factory '{}': {}",
                    factory_clone.name, e
                );
                continue;
            }

            self.factories
                .insert(factory_clone.name.to_string(), factory_clone.clone());
            discovered.push(factory_clone);
        }

        // Cache the results
        *self.discovery_cache.lock().unwrap() = Some(discovered.clone());

        Ok(discovered)
    }

    /// Get a plugin factory by name
    pub fn get_factory(&self, name: &str) -> Option<&PluginFactory> {
        self.factories.get(name)
    }

    /// Get all discovered plugin factories
    pub fn get_all_factories(&self) -> Vec<&PluginFactory> {
        self.factories.values().collect()
    }

    /// Create a plugin instance by name
    pub fn create_plugin(&self, name: &str) -> PluginResult<Box<dyn Plugin>> {
        let factory = self
            .factories
            .get(name)
            .ok_or_else(|| PluginError::PluginNotFound(name.to_string()))?;

        Ok(factory.create_plugin())
    }

    /// Get plugin metadata by name
    pub fn get_plugin_metadata(&self, name: &str) -> PluginResult<PluginMetadata> {
        let factory = self
            .factories
            .get(name)
            .ok_or_else(|| PluginError::PluginNotFound(name.to_string()))?;

        Ok(factory.get_metadata())
    }

    /// List all available plugin names
    pub fn list_plugin_names(&self) -> Vec<String> {
        self.factories.keys().cloned().collect()
    }

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

    /// Clear the discovery cache
    pub fn clear_cache(&mut self) {
        *self.discovery_cache.lock().unwrap() = None;
    }

    /// Get discovery statistics
    pub fn get_stats(&self) -> DiscoveryStats {
        DiscoveryStats {
            total_factories: self.factories.len(),
            search_paths: self.search_paths.len(),
            cached: self.discovery_cache.lock().unwrap().is_some(),
        }
    }

    /// Validate a plugin factory
    pub fn validate_factory(&self, factory: &PluginFactory) -> PluginResult<()> {
        // Check if name is not empty
        if factory.name.is_empty() {
            return Err(PluginError::InvalidMetadata(
                "Plugin name cannot be empty".to_string(),
            ));
        }

        // Check if version is not empty
        if factory.version.is_empty() {
            return Err(PluginError::InvalidMetadata(
                "Plugin version cannot be empty".to_string(),
            ));
        }

        // Try to create an instance to validate the factory function
        let _test_instance = (factory.create)();

        // Try to get metadata to validate the metadata function
        let _test_metadata = (factory.metadata)();

        Ok(())
    }

    /// Auto-register all discovered plugins into a registry
    pub fn auto_register_all<R>(&mut self, registry: &mut R) -> PluginResult<usize>
    where
        R: PluginRegistryTrait,
    {
        let factories = self.discover_plugins()?;
        let mut registered_count = 0;

        for factory in factories {
            match factory.create_plugin() {
                plugin => {
                    if let Err(e) = registry.register_plugin(plugin) {
                        eprintln!(
                            "Warning: Failed to register plugin '{}': {}",
                            factory.name, e
                        );
                        continue;
                    }
                    registered_count += 1;
                }
            }
        }

        Ok(registered_count)
    }
}

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

/// Statistics about plugin discovery
#[derive(Debug, Clone)]
pub struct DiscoveryStats {
    /// Total number of discovered factories
    pub total_factories: usize,
    /// Number of search paths configured
    pub search_paths: usize,
    /// Whether results are cached
    pub cached: bool,
}

/// Trait for plugin registries that support auto-registration
pub trait PluginRegistryTrait {
    /// Register a plugin
    fn register_plugin(&mut self, plugin: Box<dyn Plugin>) -> PluginResult<()>;
}

/// Macro for easy plugin registration
#[macro_export]
macro_rules! register_plugin {
    ($plugin_type:ty, $name:literal) => {
        $crate::register_plugin!(
            $plugin_type,
            $name,
            env!("CARGO_PKG_VERSION"),
            env!("CARGO_PKG_DESCRIPTION")
        );
    };

    ($plugin_type:ty, $name:literal, $version:literal, $description:literal) => {
        inventory::submit! {
            $crate::core::discovery::PluginFactory::new(
                $name,
                || Box::new(<$plugin_type>::default()),
                || <$plugin_type>::default().metadata().clone(),
                $version,
                $description,
            )
        }
    };
}

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

    #[derive(Default)]
    struct TestPlugin {
        metadata: PluginMetadata,
    }

    impl TestPlugin {
        fn new() -> Self {
            Self {
                metadata: PluginMetadata::new("test-plugin", "1.0.0"),
            }
        }
    }

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

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

        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!({"test": true})))
        }

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

    #[test]
    fn test_plugin_factory_creation() {
        let factory = PluginFactory::new(
            "test",
            || Box::new(TestPlugin::new()),
            || TestPlugin::new().metadata().clone(),
            "1.0.0",
            "Test plugin",
        );

        assert_eq!(factory.name, "test");
        assert_eq!(factory.version, "1.0.0");
        assert_eq!(factory.description, "Test plugin");

        let plugin = factory.create_plugin();
        assert_eq!(plugin.metadata().name, "test-plugin");
    }

    #[test]
    fn test_plugin_discovery_basic() {
        let discovery = PluginDiscovery::new();

        assert_eq!(discovery.search_paths().len(), 0);
        assert_eq!(discovery.get_all_factories().len(), 0);
        assert!(!discovery.has_plugin("nonexistent"));
    }

    #[test]
    fn test_plugin_discovery_search_paths() {
        let mut discovery = PluginDiscovery::new();

        discovery.add_search_path(PathBuf::from("/test/path1"));
        discovery.add_search_path(PathBuf::from("/test/path2"));

        assert_eq!(discovery.search_paths().len(), 2);
        assert_eq!(discovery.search_paths()[0], PathBuf::from("/test/path1"));
        assert_eq!(discovery.search_paths()[1], PathBuf::from("/test/path2"));
    }

    #[test]
    fn test_discovery_stats() {
        let discovery = PluginDiscovery::new();
        let stats = discovery.get_stats();

        assert_eq!(stats.total_factories, 0);
        assert_eq!(stats.search_paths, 0);
        assert!(!stats.cached);
    }

    #[test]
    fn test_factory_validation() {
        let discovery = PluginDiscovery::new();

        // Valid factory
        let valid_factory = PluginFactory::new(
            "valid",
            || Box::new(TestPlugin::new()),
            || TestPlugin::new().metadata().clone(),
            "1.0.0",
            "Valid plugin",
        );
        assert!(discovery.validate_factory(&valid_factory).is_ok());

        // Invalid factory with empty name
        let invalid_factory = PluginFactory::new(
            "",
            || Box::new(TestPlugin::new()),
            || TestPlugin::new().metadata().clone(),
            "1.0.0",
            "Invalid plugin",
        );
        assert!(discovery.validate_factory(&invalid_factory).is_err());

        // Invalid factory with empty version
        let invalid_factory2 = PluginFactory::new(
            "invalid",
            || Box::new(TestPlugin::new()),
            || TestPlugin::new().metadata().clone(),
            "",
            "Invalid plugin",
        );
        assert!(discovery.validate_factory(&invalid_factory2).is_err());
    }
}