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
//! Integration testing framework for plugin pipelines
//!
//! This module provides tools for testing complete plugin pipelines,
//! including configuration loading, dependency resolution, and execution order.

use std::collections::HashMap;
use std::path::PathBuf;
use std::time::Duration;

use tempfile::TempDir;

use crate::core::{
    Plugin, PluginExecutor, PluginOutput, PluginRegistry, PluginResult, PluginSystemConfig,
    SecurityManager,
};

/// Test results from pipeline execution
#[derive(Debug, Clone)]
pub struct PipelineTestResults {
    pub success: bool,
    pub plugin_outputs: HashMap<String, PluginOutput>,
    pub execution_order: Vec<Vec<String>>,
    pub total_duration: Duration,
    pub failed_plugins: Vec<String>,
}

impl PipelineTestResults {
    /// Check if all expected plugins succeeded
    pub fn all_succeeded(&self, expected_plugins: &[&str]) -> bool {
        expected_plugins.iter().all(|plugin| {
            self.plugin_outputs
                .get(*plugin)
                .map(|output| output.success)
                .unwrap_or(false)
        })
    }

    /// Get the output of a specific plugin
    pub fn get_plugin_output(&self, plugin_name: &str) -> Option<&PluginOutput> {
        self.plugin_outputs.get(plugin_name)
    }

    /// Check if plugins executed in the expected order
    pub fn verify_execution_order(&self, expected_order: &[Vec<&str>]) -> bool {
        if self.execution_order.len() != expected_order.len() {
            return false;
        }

        for (actual_batch, expected_batch) in self.execution_order.iter().zip(expected_order.iter())
        {
            let mut actual_sorted = actual_batch.clone();
            actual_sorted.sort();

            let mut expected_sorted: Vec<String> =
                expected_batch.iter().map(|s| s.to_string()).collect();
            expected_sorted.sort();

            if actual_sorted != expected_sorted {
                return false;
            }
        }

        true
    }
}

/// Integration test suite for plugin pipelines
#[allow(dead_code)]
pub struct PipelineTestSuite {
    registry: PluginRegistry,
    config: Option<PluginSystemConfig>,
    temp_workspace: TempDir,
    expected_outputs: HashMap<String, serde_json::Value>,
    plugins: Vec<Box<dyn Plugin>>,
}

impl PipelineTestSuite {
    /// Create a new pipeline test suite
    pub fn new() -> PluginResult<Self> {
        let temp_workspace =
            TempDir::new().map_err(|e| crate::core::PluginError::IoError(e.to_string()))?;

        Ok(Self {
            registry: PluginRegistry::new(),
            config: None,
            temp_workspace,
            expected_outputs: HashMap::new(),
            plugins: Vec::new(),
        })
    }

    /// Create test suite from a configuration
    pub fn from_config(config: PluginSystemConfig) -> PluginResult<Self> {
        let mut suite = Self::new()?;
        suite.config = Some(config);
        Ok(suite)
    }

    /// Add a plugin to the test suite
    pub fn with_plugin<P: Plugin + 'static>(mut self, plugin: P) -> PluginResult<Self> {
        self.registry.register(plugin)?;
        Ok(self)
    }

    /// Add multiple plugins to the test suite
    pub fn with_plugins<P: Plugin + 'static>(mut self, plugins: Vec<P>) -> PluginResult<Self> {
        for plugin in plugins {
            self.registry.register(plugin)?;
        }
        Ok(self)
    }

    /// Set expected output for a plugin
    pub fn with_expected_output(
        mut self,
        plugin_name: &str,
        expected_output: serde_json::Value,
    ) -> Self {
        self.expected_outputs
            .insert(plugin_name.to_string(), expected_output);
        self
    }

    /// Add a file to the test workspace
    pub fn with_workspace_file(&self, relative_path: &str, content: &str) -> PluginResult<()> {
        let file_path = self.temp_workspace.path().join(relative_path);

        // Create parent directories if needed
        if let Some(parent) = file_path.parent() {
            std::fs::create_dir_all(parent)
                .map_err(|e| crate::core::PluginError::IoError(e.to_string()))?;
        }

        std::fs::write(&file_path, content)
            .map_err(|e| crate::core::PluginError::IoError(e.to_string()))?;

        Ok(())
    }

    /// Create a simple configuration for testing
    pub fn with_simple_config(mut self, plugin_configs: Vec<(&str, serde_json::Value)>) -> Self {
        let mut plugin_map = std::collections::HashMap::new();

        for (name, config) in plugin_configs {
            plugin_map.insert(
                name.to_string(),
                crate::core::config::PluginConfig {
                    enabled: true,
                    config,
                    permissions: vec![],
                    priority: 0,
                    sandbox_override: None,
                    dependencies: vec![],
                    optional_dependencies: vec![],
                    retry: crate::core::config::RetryConfig::default(),
                },
            );
        }

        self.config = Some(PluginSystemConfig {
            system: crate::core::config::SystemConfig {
                workspace: Some(self.temp_workspace.path().to_path_buf()),
                ..Default::default()
            },
            plugins: plugin_map,
            global_permissions: vec![],
            autoload_plugins: vec![],
        });

        self
    }

    /// Run the pipeline test
    pub async fn run_pipeline_test(&mut self) -> PluginResult<PipelineTestResults> {
        let config = self.config.take().ok_or_else(|| {
            crate::core::PluginError::ConfigurationError(
                "No configuration provided for pipeline test".to_string(),
            )
        })?;

        let mut executor = PluginExecutor::with_config(std::mem::take(&mut self.registry), config);

        let start_time = std::time::Instant::now();
        let result = executor.execute_pipeline().await?;
        // Put the registry back
        self.registry = std::mem::take(executor.registry_mut());
        let total_duration = start_time.elapsed();

        // Verify expected outputs
        for (plugin_name, expected_output) in &self.expected_outputs {
            if let Some(actual_output) = result.plugin_outputs.get(plugin_name) {
                self.verify_output_matches(&actual_output.data, expected_output)?;
            } else {
                return Err(crate::core::PluginError::ConfigurationError(format!(
                    "Expected output for plugin '{}' not found",
                    plugin_name
                )));
            }
        }

        Ok(PipelineTestResults {
            success: result.success,
            plugin_outputs: result.plugin_outputs,
            execution_order: result.execution_order,
            total_duration,
            failed_plugins: result.failed_plugins,
        })
    }

    /// Run a single plugin test
    pub async fn run_plugin_test(&mut self, plugin_name: &str) -> PluginResult<PluginOutput> {
        let _security_manager = SecurityManager::new();
        let mut executor = PluginExecutor::new(
            std::mem::take(&mut self.registry),
            self.temp_workspace.path().to_path_buf(),
        );
        // Note: PluginExecutor already has security manager, no need to set it

        let result = executor.execute_plugin(plugin_name).await;
        // Put the registry back
        self.registry = std::mem::take(executor.registry_mut());
        result
    }

    /// Get the workspace path
    pub fn workspace_path(&self) -> &std::path::Path {
        self.temp_workspace.path()
    }

    /// Read a file from the workspace
    pub fn read_workspace_file(&self, relative_path: &str) -> PluginResult<String> {
        let file_path = self.temp_workspace.path().join(relative_path);
        std::fs::read_to_string(&file_path)
            .map_err(|e| crate::core::PluginError::IoError(e.to_string()))
    }

    /// Verify that output matches expected values
    fn verify_output_matches(
        &self,
        actual: &serde_json::Value,
        expected: &serde_json::Value,
    ) -> PluginResult<()> {
        if actual != expected {
            return Err(crate::core::PluginError::ConfigurationError(format!(
                "Output mismatch: expected {}, got {}",
                expected, actual
            )));
        }
        Ok(())
    }
}

impl Default for PipelineTestSuite {
    fn default() -> Self {
        Self::new().expect("Failed to create default PipelineTestSuite")
    }
}

/// Builder for creating test configurations
pub struct TestConfigBuilder {
    plugins: Vec<(String, crate::core::config::PluginConfig)>,
    workspace: Option<PathBuf>,
}

impl TestConfigBuilder {
    /// Create a new test configuration builder
    pub fn new() -> Self {
        Self {
            plugins: Vec::new(),
            workspace: None,
        }
    }

    /// Add a plugin configuration
    pub fn add_plugin(
        mut self,
        name: &str,
        config: serde_json::Value,
        dependencies: Vec<&str>,
    ) -> Self {
        self.plugins.push((
            name.to_string(),
            crate::core::config::PluginConfig {
                enabled: true,
                config,
                dependencies: dependencies.iter().map(|s| s.to_string()).collect(),
                permissions: vec![],
                priority: 0,
                sandbox_override: None,
                optional_dependencies: vec![],
                retry: crate::core::config::RetryConfig::default(),
            },
        ));
        self
    }

    /// Set workspace path
    pub fn with_workspace(mut self, workspace: PathBuf) -> Self {
        self.workspace = Some(workspace);
        self
    }

    /// Build the configuration
    pub fn build(self) -> PluginSystemConfig {
        let mut plugin_map = std::collections::HashMap::new();
        for (name, plugin_config) in self.plugins {
            plugin_map.insert(name, plugin_config);
        }

        PluginSystemConfig {
            system: crate::core::config::SystemConfig {
                workspace: self.workspace,
                ..Default::default()
            },
            plugins: plugin_map,
            global_permissions: vec![],
            autoload_plugins: vec![],
        }
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::testing::test_plugins;
    use serde_json::json;

    #[tokio::test]
    async fn test_pipeline_test_suite_basic() {
        let mut suite = PipelineTestSuite::new().unwrap();

        let plugin1 = test_plugins::successful_plugin("plugin1");
        let plugin2 = test_plugins::successful_plugin("plugin2")
            .with_dependencies(vec!["plugin1".to_string()]);

        suite = suite.with_plugin(plugin1).unwrap();
        suite = suite.with_plugin(plugin2).unwrap();

        let config = TestConfigBuilder::new()
            .add_plugin("plugin1", json!({}), vec![])
            .add_plugin("plugin2", json!({}), vec!["plugin1"])
            .build();

        suite.config = Some(config);

        let results = suite.run_pipeline_test().await.unwrap();

        assert!(results.success);
        assert!(results.all_succeeded(&["plugin1", "plugin2"]));
        assert_eq!(results.execution_order.len(), 2); // Two batches due to dependency
    }

    #[tokio::test]
    async fn test_pipeline_with_file_creation() {
        let mut suite = PipelineTestSuite::new().unwrap();

        let workspace_path = suite.workspace_path().to_path_buf();
        let plugin =
            test_plugins::file_creating_plugin("file-creator", "output.txt", "test content")
                .with_permissions(vec![
                    crate::core::Permission::TempDir,
                    crate::core::Permission::fs_read_write(workspace_path.clone()),
                ]);
        suite = suite.with_plugin(plugin).unwrap();

        let config = TestConfigBuilder::new()
            .add_plugin("file-creator", json!({}), vec![])
            .with_workspace(workspace_path)
            .build();

        suite.config = Some(config);

        let results = suite.run_pipeline_test().await.unwrap();

        assert!(results.success);

        // Verify file was created
        let content = suite.read_workspace_file("output.txt").unwrap();
        assert_eq!(content, "test content");
    }

    #[tokio::test]
    async fn test_execution_order_verification() {
        let mut suite = PipelineTestSuite::new().unwrap();

        let plugin1 = test_plugins::successful_plugin("plugin1");
        let plugin2 = test_plugins::successful_plugin("plugin2")
            .with_dependencies(vec!["plugin1".to_string()]);
        let plugin3 = test_plugins::successful_plugin("plugin3");

        suite = suite.with_plugin(plugin1).unwrap();
        suite = suite.with_plugin(plugin2).unwrap();
        suite = suite.with_plugin(plugin3).unwrap();

        let config = TestConfigBuilder::new()
            .add_plugin("plugin1", json!({}), vec![])
            .add_plugin("plugin2", json!({}), vec!["plugin1"])
            .add_plugin("plugin3", json!({}), vec![])
            .build();

        suite.config = Some(config);

        let results = suite.run_pipeline_test().await.unwrap();

        // plugin1 and plugin3 can run in parallel, plugin2 runs after plugin1
        assert!(results.verify_execution_order(&[vec!["plugin1", "plugin3"], vec!["plugin2"]]));
    }
}