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
use semver::Version;
use serde_json::to_string_pretty;
use std::collections::HashMap;
use std::fs;
use std::sync::Arc;
use thiserror::Error;
use tokio::sync::RwLock;

use crate::VanguardPlugin;

/// Represents the current state of a plugin version
#[derive(Debug, Clone, PartialEq)]
pub enum PluginState {
    /// Plugin is active and ready to use
    Active,
    /// Plugin is installed but not currently active
    Inactive,
    /// Plugin failed to load or operate with given error message
    Failed(String),
}

/// Errors that can occur during plugin registry operations
#[derive(Error, Debug)]
pub enum RegistryError {
    /// Plugin was not found in the registry
    #[error("Plugin not found: {0}")]
    NotFound(String),

    /// A version conflict occurred between plugins
    #[error("Version conflict: {plugin} {version} conflicts with existing version")]
    VersionConflict {
        /// Name of the plugin with conflict
        plugin: String,
        /// Version string that caused the conflict
        version: String,
    },

    /// The provided version string is invalid
    #[error("Invalid version: {0}")]
    InvalidVersion(String),

    /// Attempted to register a plugin version that already exists
    #[error("Plugin already registered: {plugin} {version}")]
    AlreadyRegistered {
        /// Name of the plugin that was already registered
        plugin: String,
        /// Version that was already registered
        version: String,
    },
}

/// A versioned plugin instance with its state
#[derive(Debug)]
struct VersionedPlugin {
    /// Semantic version of the plugin
    version: Version,
    /// The plugin instance
    plugin: Arc<dyn VanguardPlugin>,
    /// Current state of the plugin
    state: PluginState,
}

/// Registry for managing multiple versions of plugins
///
/// The registry keeps track of all installed plugin versions and their states,
/// as well as which version is currently active for each plugin.
#[derive(Debug)]
pub struct PluginRegistry {
    /// Map of plugin names to their available versions
    plugins: RwLock<HashMap<String, Vec<VersionedPlugin>>>,
    /// Map of plugin names to their currently active version
    active_versions: RwLock<HashMap<String, Version>>,
}

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

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

    /// Register a new plugin version
    pub async fn register_plugin(
        &self,
        plugin: Arc<dyn VanguardPlugin>,
    ) -> Result<(), RegistryError> {
        let name = plugin.metadata().name.clone();
        let version_str = plugin.metadata().version.clone();
        let version = Version::parse(&version_str)
            .map_err(|_| RegistryError::InvalidVersion(version_str.clone()))?;

        let mut plugins = self.plugins.write().await;

        // Get or create the version list for this plugin
        let versions = plugins.entry(name.clone()).or_insert_with(Vec::new);

        // Check if version already exists
        if versions.iter().any(|v| v.version == version) {
            return Err(RegistryError::AlreadyRegistered {
                plugin: name,
                version: version_str,
            });
        }

        // Add new version
        versions.push(VersionedPlugin {
            version: version.clone(),
            plugin,
            state: PluginState::Active,
        });

        // Sort versions descending
        versions.sort_by(|a, b| b.version.cmp(&a.version));

        // Always set the latest version as active
        let mut active_versions = self.active_versions.write().await;
        let latest_version = &versions[0].version;
        active_versions.insert(name, latest_version.clone());

        Ok(())
    }

    /// Get the currently active version of a plugin
    pub async fn get_active_version(
        &self,
        name: &str,
    ) -> Result<Arc<dyn VanguardPlugin>, RegistryError> {
        let active_versions = self.active_versions.read().await;
        let plugins = self.plugins.read().await;

        let version = active_versions
            .get(name)
            .ok_or_else(|| RegistryError::NotFound(name.to_string()))?;

        let versions = plugins
            .get(name)
            .ok_or_else(|| RegistryError::NotFound(name.to_string()))?;

        let plugin = versions
            .iter()
            .find(|v| v.version == *version)
            .ok_or_else(|| RegistryError::NotFound(name.to_string()))?;

        Ok(plugin.plugin.clone())
    }

    /// Get any version of a plugin (usually the latest)
    pub async fn get_plugin(&self, name: &str) -> Option<Arc<dyn VanguardPlugin>> {
        let plugins = self.plugins.read().await;
        plugins
            .get(name)
            .and_then(|versions| versions.first().map(|v| v.plugin.clone()))
    }

    /// Activate a specific version of a plugin
    pub async fn activate_version(
        &self,
        name: &str,
        version_str: &str,
    ) -> Result<(), RegistryError> {
        let version = Version::parse(version_str)
            .map_err(|_| RegistryError::InvalidVersion(version_str.to_string()))?;

        let plugins = self.plugins.read().await;

        // Verify version exists
        let versions = plugins
            .get(name)
            .ok_or_else(|| RegistryError::NotFound(name.to_string()))?;

        if !versions.iter().any(|v| v.version == version) {
            return Err(RegistryError::NotFound(format!("{} {}", name, version_str)));
        }

        // Update active version
        let mut active_versions = self.active_versions.write().await;
        active_versions.insert(name.to_string(), version);

        Ok(())
    }

    /// Get the state of a specific plugin version
    pub async fn get_plugin_state(
        &self,
        name: &str,
        version_str: &str,
    ) -> Result<PluginState, RegistryError> {
        let version = Version::parse(version_str)
            .map_err(|_| RegistryError::InvalidVersion(version_str.to_string()))?;

        let plugins = self.plugins.read().await;

        let versions = plugins
            .get(name)
            .ok_or_else(|| RegistryError::NotFound(name.to_string()))?;

        let plugin = versions
            .iter()
            .find(|v| v.version == version)
            .ok_or_else(|| RegistryError::NotFound(format!("{} {}", name, version_str)))?;

        Ok(plugin.state.clone())
    }

    /// Set the state of a specific plugin version
    pub async fn set_plugin_state(
        &self,
        name: &str,
        version_str: &str,
        state: PluginState,
    ) -> Result<(), RegistryError> {
        let version = Version::parse(version_str)
            .map_err(|_| RegistryError::InvalidVersion(version_str.to_string()))?;

        let mut plugins = self.plugins.write().await;

        let versions = plugins
            .get_mut(name)
            .ok_or_else(|| RegistryError::NotFound(name.to_string()))?;

        let plugin = versions
            .iter_mut()
            .find(|v| v.version == version)
            .ok_or_else(|| RegistryError::NotFound(format!("{} {}", name, version_str)))?;

        plugin.state = state;
        Ok(())
    }

    /// Remove a specific version of a plugin
    pub async fn remove_plugin(&self, name: &str, version_str: &str) -> Result<(), RegistryError> {
        let version = Version::parse(version_str)
            .map_err(|_| RegistryError::InvalidVersion(version_str.to_string()))?;

        let mut plugins = self.plugins.write().await;

        let versions = plugins
            .get_mut(name)
            .ok_or_else(|| RegistryError::NotFound(name.to_string()))?;

        // Find and remove the version
        let index = versions
            .iter()
            .position(|v| v.version == version)
            .ok_or_else(|| RegistryError::NotFound(format!("{} {}", name, version_str)))?;

        versions.remove(index);

        // If we removed all versions, remove the plugin entirely
        if versions.is_empty() {
            plugins.remove(name);

            // Also remove from active versions
            let mut active_versions = self.active_versions.write().await;
            active_versions.remove(name);
        }

        Ok(())
    }

    /// Save plugin information to the registry directory
    pub async fn save_plugin_info(
        &self,
        plugin_info: &crate::PluginInfo,
    ) -> Result<(), RegistryError> {
        // Create registry directory if it doesn't exist
        let home_dir = dirs::home_dir().ok_or_else(|| {
            RegistryError::NotFound("Could not determine home directory".to_string())
        })?;
        let registry_dir = home_dir.join(".vanguard").join("registry");
        fs::create_dir_all(&registry_dir).map_err(|e| {
            RegistryError::NotFound(format!("Failed to create registry directory: {}", e))
        })?;

        // Serialize plugin info to JSON
        let json = to_string_pretty(plugin_info).map_err(|e| {
            RegistryError::NotFound(format!("Failed to serialize plugin info: {}", e))
        })?;

        // Write to file
        let plugin_info_path = registry_dir.join(format!("{}.json", plugin_info.name));
        fs::write(&plugin_info_path, json).map_err(|e| {
            RegistryError::NotFound(format!("Failed to write plugin info file: {}", e))
        })?;

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{PluginMetadata, ValidationResult};
    use async_trait::async_trait;

    // Test plugin implementation
    #[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(())
        }
    }

    fn create_test_plugin(name: &str, version: &str) -> Arc<dyn VanguardPlugin> {
        Arc::new(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_register_plugin() {
        let registry = PluginRegistry::new();
        let plugin = create_test_plugin("test-plugin", "1.0.0");

        assert!(registry.register_plugin(plugin.clone()).await.is_ok());

        // Verify plugin is registered
        let registered = registry.get_plugin("test-plugin").await;
        assert!(registered.is_some());

        // Try registering same version again
        let duplicate = create_test_plugin("test-plugin", "1.0.0");
        assert!(matches!(
            registry.register_plugin(duplicate).await,
            Err(RegistryError::AlreadyRegistered { .. })
        ));
    }

    #[tokio::test]
    async fn test_version_management() {
        let registry = PluginRegistry::new();

        // Register multiple versions
        let v1 = create_test_plugin("test-plugin", "1.0.0");
        let v2 = create_test_plugin("test-plugin", "1.1.0");

        registry.register_plugin(v1).await.unwrap();
        registry.register_plugin(v2).await.unwrap();

        // Latest version should be active by default
        let active = registry.get_active_version("test-plugin").await.unwrap();
        assert_eq!(active.metadata().version, "1.1.0");

        // Switch to older version
        registry
            .activate_version("test-plugin", "1.0.0")
            .await
            .unwrap();
        let active = registry.get_active_version("test-plugin").await.unwrap();
        assert_eq!(active.metadata().version, "1.0.0");
    }

    #[tokio::test]
    async fn test_plugin_state() {
        let registry = PluginRegistry::new();
        let plugin = create_test_plugin("test-plugin", "1.0.0");

        registry.register_plugin(plugin).await.unwrap();

        // Should be active by default
        let state = registry
            .get_plugin_state("test-plugin", "1.0.0")
            .await
            .unwrap();
        assert_eq!(state, PluginState::Active);

        // Test state transition
        registry
            .set_plugin_state("test-plugin", "1.0.0", PluginState::Inactive)
            .await
            .unwrap();
        let state = registry
            .get_plugin_state("test-plugin", "1.0.0")
            .await
            .unwrap();
        assert_eq!(state, PluginState::Inactive);
    }

    #[tokio::test]
    async fn test_plugin_removal() {
        let registry = PluginRegistry::new();
        let plugin = create_test_plugin("test-plugin", "1.0.0");

        registry.register_plugin(plugin).await.unwrap();
        assert!(registry.remove_plugin("test-plugin", "1.0.0").await.is_ok());

        // Verify plugin is removed
        assert!(registry.get_plugin("test-plugin").await.is_none());

        // Try removing non-existent plugin
        assert!(matches!(
            registry.remove_plugin("non-existent", "1.0.0").await,
            Err(RegistryError::NotFound(_))
        ));
    }
}