vanguard-plugin 0.1.1

Plugin system for the Vanguard version manager
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
447
use std::{collections::HashMap, fs, path::PathBuf, sync::Arc};

use async_trait::async_trait;
use semver::Version;
use thiserror::Error;
use tokio::sync::RwLock;

use crate::{PluginMetadata, ValidationResult, VanguardPlugin};

/// A test plugin implementation for development and testing
#[derive(Debug)]
struct TestPlugin {
    metadata: PluginMetadata,
}

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

    async fn validate(&self) -> ValidationResult {
        ValidationResult::Passed
    }

    async fn initialize(&self) -> Result<(), String> {
        Ok(())
    }

    async fn cleanup(&self) -> Result<(), String> {
        Ok(())
    }
}

/// Errors that can occur during plugin loading
#[derive(Error, Debug)]
pub enum LoaderError {
    /// Plugin not found
    #[error("Plugin not found: {0}")]
    NotFound(String),

    /// Plugin already loaded
    #[error("Plugin already loaded: {0}")]
    AlreadyLoaded(String),

    /// Plugin loading failed
    #[error("Failed to load plugin: {0}")]
    LoadFailed(String),

    /// Plugin validation failed
    #[error("Plugin validation failed: {0}")]
    ValidationFailed(String),

    /// Plugin dependency error
    #[error("Plugin dependency error: {name} requires {dependency} {version}")]
    DependencyError {
        /// Name of the plugin that has the dependency
        name: String,
        /// Name of the required dependency
        dependency: String,
        /// Required version of the dependency
        version: String,
    },

    /// IO error
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
}

/// Configuration for the plugin loader
#[derive(Debug, Clone)]
pub struct LoaderConfig {
    /// Base directory for plugin discovery
    pub plugin_dir: PathBuf,
    /// Current Vanguard version
    pub vanguard_version: Version,
    /// Whether to validate plugins on load
    pub validate_on_load: bool,
    /// Whether to check dependencies on load
    pub check_dependencies: bool,
}

impl Default for LoaderConfig {
    fn default() -> Self {
        Self {
            plugin_dir: PathBuf::from(".vanguard/plugins"),
            vanguard_version: Version::new(0, 1, 0),
            validate_on_load: true,
            check_dependencies: true,
        }
    }
}

/// A plugin loader that manages plugin discovery, loading, and lifecycle
#[derive(Debug)]
pub struct PluginLoader {
    /// Configuration for the plugin loader
    config: LoaderConfig,
    /// Map of loaded plugins by name
    plugins: RwLock<HashMap<String, Arc<dyn VanguardPlugin>>>,
}

impl PluginLoader {
    /// Create a new plugin loader with the given configuration
    pub fn new(config: LoaderConfig) -> Self {
        Self {
            config,
            plugins: RwLock::new(HashMap::new()),
        }
    }

    /// Get the current configuration
    pub fn config(&self) -> &LoaderConfig {
        &self.config
    }

    /// Load a plugin by name
    pub async fn load_plugin(&self, name: &str) -> Result<Arc<dyn VanguardPlugin>, LoaderError> {
        // Check if already loaded before acquiring write lock
        {
            let plugins = self.plugins.read().await;
            if plugins.contains_key(name) {
                return Err(LoaderError::AlreadyLoaded(name.to_string()));
            }
        }

        // Find plugin metadata file
        let plugin_path = self.config.plugin_dir.join(format!("{}.json", name));
        if !plugin_path.exists() {
            return Err(LoaderError::NotFound(name.to_string()));
        }

        // Read and parse plugin metadata
        let content = fs::read_to_string(&plugin_path).map_err(LoaderError::Io)?;

        let metadata: PluginMetadata = serde_json::from_str(&content).map_err(|e| {
            LoaderError::ValidationFailed(format!("Invalid plugin metadata: {}", e))
        })?;

        // Create test plugin instance for now
        // TODO: Replace with actual plugin loading from dynamic library
        let plugin = Arc::new(TestPlugin { metadata }) as Arc<dyn VanguardPlugin>;

        // Validate plugin if enabled
        if self.config.validate_on_load {
            match plugin.validate().await {
                ValidationResult::Passed => {}
                ValidationResult::Failed(reason) => {
                    return Err(LoaderError::ValidationFailed(reason));
                }
            }
        }

        // Check dependencies if enabled
        if self.config.check_dependencies {
            self.check_dependencies(plugin.as_ref()).await?;
        }

        // Only acquire write lock after all validation is done
        let mut plugins = self.plugins.write().await;

        // Double-check it wasn't loaded while we were validating
        if plugins.contains_key(name) {
            return Err(LoaderError::AlreadyLoaded(name.to_string()));
        }

        // Store and return the plugin
        plugins.insert(name.to_string(), plugin.clone());
        Ok(plugin)
    }

    /// Get a loaded plugin by name
    pub async fn get_plugin(&self, name: &str) -> Option<Arc<dyn VanguardPlugin>> {
        self.plugins.read().await.get(name).cloned()
    }

    /// List all loaded plugins
    pub async fn list_plugins(&self) -> Vec<PluginMetadata> {
        self.plugins
            .read()
            .await
            .values()
            .map(|p| p.metadata().clone())
            .collect()
    }

    /// Unload a plugin by name
    pub async fn unload_plugin(&self, name: &str) -> Result<(), LoaderError> {
        let mut plugins = self.plugins.write().await;

        if let Some(plugin) = plugins.remove(name) {
            // Clean up plugin resources
            if let Err(e) = plugin.cleanup().await {
                // Re-insert the plugin if cleanup fails
                plugins.insert(name.to_string(), plugin);
                return Err(LoaderError::LoadFailed(format!(
                    "Failed to cleanup plugin: {}",
                    e
                )));
            }
            Ok(())
        } else {
            Err(LoaderError::NotFound(name.to_string()))
        }
    }

    /// Check if all plugin dependencies are satisfied
    #[allow(dead_code)] // Will be used when implementing plugin loading
    async fn check_dependencies(&self, plugin: &dyn VanguardPlugin) -> Result<(), LoaderError> {
        // Get a snapshot of current dependencies to avoid holding the lock
        let dependencies: Vec<_> = {
            let plugins = self.plugins.read().await;
            plugin
                .metadata()
                .dependencies
                .iter()
                .map(|dep| {
                    let loaded_version =
                        plugins.get(&dep.name).map(|p| p.metadata().version.clone());
                    (dep.clone(), loaded_version)
                })
                .collect()
        };

        // Check each dependency without holding the lock
        for (dep, loaded_version) in dependencies {
            match loaded_version {
                Some(version) => {
                    // Simple version match for now, can be enhanced with semver requirements later
                    if version != dep.version {
                        return Err(LoaderError::DependencyError {
                            name: plugin.metadata().name.clone(),
                            dependency: dep.name,
                            version: dep.version,
                        });
                    }
                }
                None => {
                    return Err(LoaderError::DependencyError {
                        name: plugin.metadata().name.clone(),
                        dependency: dep.name,
                        version: dep.version,
                    });
                }
            }
        }

        Ok(())
    }

    /// Discover available plugins in the plugin directory
    pub async fn discover_plugins(&self) -> Result<Vec<PluginMetadata>, LoaderError> {
        let mut discovered = Vec::new();

        // Create plugin directory if it doesn't exist
        if !self.config.plugin_dir.exists() {
            fs::create_dir_all(&self.config.plugin_dir).map_err(LoaderError::Io)?;
            return Ok(discovered);
        }

        // Read plugin directory
        let entries = fs::read_dir(&self.config.plugin_dir).map_err(LoaderError::Io)?;

        // Process each entry
        for entry in entries {
            let entry = entry.map_err(LoaderError::Io)?;
            let path = entry.path();

            // Only process .json files
            if path.extension().and_then(|ext| ext.to_str()) != Some("json") {
                continue;
            }

            // Read and parse plugin metadata
            let content = fs::read_to_string(&path).map_err(LoaderError::Io)?;

            match serde_json::from_str::<PluginMetadata>(&content) {
                Ok(metadata) => {
                    discovered.push(metadata);
                }
                Err(e) => {
                    // Log invalid plugin but continue processing others
                    eprintln!("Failed to parse plugin metadata from {:?}: {}", path, e);
                }
            }
        }

        Ok(discovered)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[allow(dead_code)]
    fn create_test_plugin(name: &str, version: &str) -> TestPlugin {
        TestPlugin {
            metadata: PluginMetadata {
                name: name.to_string(),
                version: version.to_string(),
                description: "Test Plugin".to_string(),
                author: "Test Author".to_string(),
                min_vanguard_version: Some("0.1.0".to_string()),
                max_vanguard_version: Some("2.0.0".to_string()),
                dependencies: vec![],
            },
        }
    }

    #[tokio::test]
    async fn test_loader_config() {
        let config = LoaderConfig {
            plugin_dir: PathBuf::from("/test/plugins"),
            vanguard_version: Version::new(1, 0, 0),
            validate_on_load: true,
            check_dependencies: true,
        };

        let loader = PluginLoader::new(config.clone());
        assert_eq!(loader.config().plugin_dir, PathBuf::from("/test/plugins"));
        assert_eq!(loader.config().vanguard_version, Version::new(1, 0, 0));
    }

    #[tokio::test]
    async fn test_plugin_not_found() {
        let loader = PluginLoader::new(LoaderConfig::default());
        let result = loader.load_plugin("nonexistent").await;
        assert!(matches!(result, Err(LoaderError::NotFound(_))));
    }

    #[tokio::test]
    async fn test_list_plugins() {
        let loader = PluginLoader::new(LoaderConfig::default());
        let plugins = loader.list_plugins().await;
        assert!(plugins.is_empty());
    }

    #[tokio::test]
    async fn test_unload_nonexistent() {
        let loader = PluginLoader::new(LoaderConfig::default());
        let result = loader.unload_plugin("nonexistent").await;
        assert!(matches!(result, Err(LoaderError::NotFound(_))));
    }

    #[tokio::test]
    async fn test_discover_plugins() {
        let temp_dir = TempDir::new().unwrap();
        let plugin_dir = temp_dir.path().join("plugins");
        fs::create_dir_all(&plugin_dir).unwrap();

        // Create a mock plugin file
        let plugin_path = plugin_dir.join("test-plugin.json");
        let plugin_meta = serde_json::json!({
            "name": "test-plugin",
            "version": "1.0.0",
            "author": "Test Author",
            "description": "Test Plugin",
            "license": "MIT",
            "min_vanguard_version": "0.1.0",
            "max_vanguard_version": null,
            "supported_platforms": [
                { "os": "linux", "arch": "x86_64" }
            ],
            "dependencies": []
        });
        fs::write(&plugin_path, plugin_meta.to_string()).unwrap();

        let config = LoaderConfig {
            plugin_dir,
            vanguard_version: Version::new(0, 1, 0),
            validate_on_load: true,
            check_dependencies: true,
        };

        let loader = PluginLoader::new(config);
        let discovered = loader.discover_plugins().await.unwrap();

        assert_eq!(discovered.len(), 1);
        assert_eq!(discovered[0].name, "test-plugin");
    }

    #[tokio::test]
    async fn test_load_plugin_validation() {
        let temp_dir = TempDir::new().unwrap();
        let plugin_dir = temp_dir.path().join("plugins");
        fs::create_dir_all(&plugin_dir).unwrap();

        // Create an invalid plugin (missing required fields)
        let plugin_path = plugin_dir.join("invalid-plugin.json");
        let plugin_meta = serde_json::json!({
            "name": "invalid-plugin"
        });
        fs::write(&plugin_path, plugin_meta.to_string()).unwrap();

        let config = LoaderConfig {
            plugin_dir,
            vanguard_version: Version::new(0, 1, 0),
            validate_on_load: true,
            check_dependencies: true,
        };

        let loader = PluginLoader::new(config);
        let result = loader.load_plugin("invalid-plugin").await;

        assert!(matches!(result, Err(LoaderError::ValidationFailed(_))));
    }

    #[tokio::test]
    async fn test_load_plugin_dependencies() {
        let temp_dir = TempDir::new().unwrap();
        let plugin_dir = temp_dir.path().join("plugins");
        fs::create_dir_all(&plugin_dir).unwrap();

        // Create a plugin with a dependency
        let plugin_path = plugin_dir.join("dependent-plugin.json");
        let plugin_meta = serde_json::json!({
            "name": "dependent-plugin",
            "version": "1.0.0",
            "author": "Test Author",
            "description": "Test Plugin",
            "license": "MIT",
            "min_vanguard_version": "0.1.0",
            "max_vanguard_version": null,
            "dependencies": [
                {
                    "name": "base-plugin",
                    "version": "1.0.0"
                }
            ]
        });
        fs::write(&plugin_path, plugin_meta.to_string()).unwrap();

        let config = LoaderConfig {
            plugin_dir,
            vanguard_version: Version::new(0, 1, 0),
            validate_on_load: true,
            check_dependencies: true,
        };

        let loader = PluginLoader::new(config);
        let result = loader.load_plugin("dependent-plugin").await;

        assert!(matches!(result, Err(LoaderError::DependencyError { .. })));
    }
}