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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
//! Plugin testing framework and utilities
//!
//! This module provides testing utilities for plugin development,
//! including test harnesses, mock implementations, and integration testing tools.

pub mod benchmarks;
pub mod integration;

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

use async_trait::async_trait;
use serde_json::json;
use tempfile::TempDir;

use crate::core::{
    Permission, Plugin, PluginContext, PluginMetadata, PluginOutput, PluginRegistry, PluginResult,
    SecurityContext, SecurityManager,
};

/// Test harness for plugin development and testing
#[allow(dead_code)]
pub struct PluginTestHarness {
    registry: PluginRegistry,
    context: PluginContext,
    temp_workspace: TempDir,
    security_manager: SecurityManager,
    expected_outputs: HashMap<String, serde_json::Value>,
    expected_artifacts: Vec<PathBuf>,
    expected_permissions: Vec<Permission>,
}

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

        let context = PluginContext::new("test-plugin", temp_workspace.path().to_path_buf());
        let registry = PluginRegistry::new();
        let security_manager = SecurityManager::new();

        Ok(Self {
            registry,
            context,
            temp_workspace,
            security_manager,
            expected_outputs: HashMap::new(),
            expected_artifacts: Vec::new(),
            expected_permissions: Vec::new(),
        })
    }

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

    /// Add dependency output for testing plugin dependencies
    pub fn with_dependency_output(mut self, plugin_name: &str, output: PluginOutput) -> Self {
        self.context
            .add_dependency_output(plugin_name.to_string(), output);
        self
    }

    /// Set configuration for the plugin being tested
    pub fn with_config(self, _config: serde_json::Value) -> Self {
        // Configuration will be passed to the plugin during execution
        self
    }

    /// Set permissions for the plugin being tested
    pub fn with_permissions(mut self, permissions: Vec<Permission>) -> PluginResult<Self> {
        let permissions_set: std::collections::HashSet<_> = permissions.into_iter().collect();
        let security_context =
            SecurityContext::new(self.context.plugin_name.clone(), permissions_set);
        self.context.set_security_context(security_context);
        Ok(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(())
    }

    /// Execute the plugin and return the output
    pub async fn execute(&mut self, plugin_name: &str) -> PluginResult<PluginOutput> {
        let mut plugin = self
            .registry
            .take_plugin(plugin_name)
            .ok_or_else(|| crate::core::PluginError::PluginNotFound(plugin_name.to_string()))?;

        // Initialize the plugin
        plugin.initialize(json!({}), &self.context).await?;

        // Execute the plugin
        let output = plugin.execute(&mut self.context).await?;

        // Cleanup the plugin
        plugin.cleanup(&self.context).await?;

        // Put the plugin back
        self.registry.put_plugin(plugin)?;

        Ok(output)
    }

    /// Execute the plugin with custom configuration
    pub async fn execute_with_config(
        &mut self,
        plugin_name: &str,
        config: serde_json::Value,
    ) -> PluginResult<PluginOutput> {
        let mut plugin = self
            .registry
            .take_plugin(plugin_name)
            .ok_or_else(|| crate::core::PluginError::PluginNotFound(plugin_name.to_string()))?;

        // Initialize the plugin with config
        plugin.initialize(config, &self.context).await?;

        // Execute the plugin
        let output = plugin.execute(&mut self.context).await?;

        // Cleanup the plugin
        plugin.cleanup(&self.context).await?;

        // Put the plugin back
        self.registry.put_plugin(plugin)?;

        Ok(output)
    }

    /// Assert that the output contains specific data
    pub fn assert_output_contains(
        &self,
        output: &PluginOutput,
        key: &str,
        expected: &serde_json::Value,
    ) -> PluginResult<()> {
        let actual = output.data.get(key).ok_or_else(|| {
            crate::core::PluginError::ValidationError(format!(
                "Output does not contain key '{}'",
                key
            ))
        })?;

        if actual != expected {
            return Err(crate::core::PluginError::ValidationError(format!(
                "Expected '{}' = {}, but got {}",
                key, expected, actual
            )));
        }

        Ok(())
    }

    /// Assert that specific artifacts were created
    pub fn assert_artifacts_created(
        &self,
        output: &PluginOutput,
        expected_paths: &[&str],
    ) -> PluginResult<()> {
        for expected_path in expected_paths {
            let expected_full_path = self.temp_workspace.path().join(expected_path);

            if !output.artifacts.contains(&expected_full_path) {
                return Err(crate::core::PluginError::ValidationError(format!(
                    "Expected artifact '{}' was not created",
                    expected_path
                )));
            }

            if !expected_full_path.exists() {
                return Err(crate::core::PluginError::ValidationError(format!(
                    "Artifact '{}' was listed but file does not exist",
                    expected_path
                )));
            }
        }

        Ok(())
    }

    /// Assert that the plugin was successful
    pub fn assert_success(&self, output: &PluginOutput) -> PluginResult<()> {
        if !output.success {
            return Err(crate::core::PluginError::ValidationError(
                "Expected plugin execution to succeed".to_string(),
            ));
        }
        Ok(())
    }

    /// Assert that the plugin failed
    pub fn assert_failure(&self, output: &PluginOutput) -> PluginResult<()> {
        if output.success {
            return Err(crate::core::PluginError::ValidationError(
                "Expected plugin execution to fail".to_string(),
            ));
        }
        Ok(())
    }

    /// Get the workspace path for testing file operations
    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()))
    }
}

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

/// Mock plugin implementation for testing
#[allow(clippy::type_complexity)]
pub struct MockPlugin {
    metadata: PluginMetadata,
    schema: serde_json::Value,
    permissions: Vec<Permission>,
    execute_fn:
        Arc<Mutex<Box<dyn Fn(&mut PluginContext) -> PluginResult<PluginOutput> + Send + Sync>>>,
    initialize_fn: Arc<
        Mutex<
            Option<
                Box<dyn Fn(serde_json::Value, &PluginContext) -> PluginResult<()> + Send + Sync>,
            >,
        >,
    >,
    cleanup_fn: Arc<Mutex<Option<Box<dyn Fn(&PluginContext) -> PluginResult<()> + Send + Sync>>>>,
}

impl MockPlugin {
    /// Create a new mock plugin with default behavior
    pub fn new(name: &str, version: &str) -> Self {
        let metadata = PluginMetadata::new(name, version);

        let execute_fn = Arc::new(Mutex::new(Box::new(|_: &mut PluginContext| {
            Ok(PluginOutput::success(json!({"mock": true})))
        })
            as Box<dyn Fn(&mut PluginContext) -> PluginResult<PluginOutput> + Send + Sync>));

        Self {
            metadata,
            schema: json!({"type": "object"}),
            permissions: Vec::new(),
            execute_fn,
            initialize_fn: Arc::new(Mutex::new(None)),
            cleanup_fn: Arc::new(Mutex::new(None)),
        }
    }

    /// Set custom execute function
    pub fn with_execute<F>(self, execute_fn: F) -> Self
    where
        F: Fn(&mut PluginContext) -> PluginResult<PluginOutput> + Send + Sync + 'static,
    {
        *self.execute_fn.lock().unwrap() = Box::new(execute_fn);
        self
    }

    /// Set custom initialize function
    pub fn with_initialize<F>(self, initialize_fn: F) -> Self
    where
        F: Fn(serde_json::Value, &PluginContext) -> PluginResult<()> + Send + Sync + 'static,
    {
        *self.initialize_fn.lock().unwrap() = Some(Box::new(initialize_fn));
        self
    }

    /// Set custom cleanup function
    pub fn with_cleanup<F>(self, cleanup_fn: F) -> Self
    where
        F: Fn(&PluginContext) -> PluginResult<()> + Send + Sync + 'static,
    {
        *self.cleanup_fn.lock().unwrap() = Some(Box::new(cleanup_fn));
        self
    }

    /// Set plugin permissions
    pub fn with_permissions(mut self, permissions: Vec<Permission>) -> Self {
        self.permissions = permissions;
        self
    }

    /// Set plugin dependencies
    pub fn with_dependencies(mut self, dependencies: Vec<String>) -> Self {
        self.metadata.dependencies = dependencies;
        self
    }

    /// Set plugin schema
    pub fn with_schema(mut self, schema: serde_json::Value) -> Self {
        self.schema = schema;
        self
    }
}

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

    fn schema(&self) -> serde_json::Value {
        self.schema.clone()
    }

    fn permissions(&self) -> Vec<Permission> {
        self.permissions.clone()
    }

    async fn initialize(
        &mut self,
        config: serde_json::Value,
        context: &PluginContext,
    ) -> PluginResult<()> {
        if let Some(ref initialize_fn) = *self.initialize_fn.lock().unwrap() {
            initialize_fn(config, context)
        } else {
            Ok(())
        }
    }

    async fn execute(&mut self, context: &mut PluginContext) -> PluginResult<PluginOutput> {
        let execute_fn = self.execute_fn.lock().unwrap();
        execute_fn(context)
    }

    async fn cleanup(&mut self, context: &PluginContext) -> PluginResult<()> {
        if let Some(ref cleanup_fn) = *self.cleanup_fn.lock().unwrap() {
            cleanup_fn(context)
        } else {
            Ok(())
        }
    }
}

/// Utilities for creating test plugins with specific behaviors
pub mod test_plugins {
    use super::*;

    /// Create a plugin that always succeeds
    pub fn successful_plugin(name: &str) -> MockPlugin {
        MockPlugin::new(name, "1.0.0").with_execute(|_| {
            Ok(PluginOutput::success(json!({
                "status": "completed",
                "message": "Plugin executed successfully"
            })))
        })
    }

    /// Create a plugin that always fails
    pub fn failing_plugin(name: &str) -> MockPlugin {
        MockPlugin::new(name, "1.0.0").with_execute(|_| {
            Err(crate::core::PluginError::ExecutionError(
                "Mock plugin failure".to_string(),
            ))
        })
    }

    /// Create a plugin that creates a file
    pub fn file_creating_plugin(name: &str, filename: &str, content: &str) -> MockPlugin {
        let filename = filename.to_string();
        let content = content.to_string();

        MockPlugin::new(name, "1.0.0").with_execute(move |context| {
            let file_path = context.workspace.join(&filename);
            std::fs::write(&file_path, &content)
                .map_err(|e| crate::core::PluginError::IoError(e.to_string()))?;

            Ok(PluginOutput {
                success: true,
                data: json!({
                    "file_created": filename,
                    "content_length": content.len()
                }),
                artifacts: vec![file_path],
                metadata: HashMap::new(),
                execution_time: Duration::from_millis(10),
            })
        })
    }

    /// Create a plugin that depends on another plugin's output
    pub fn dependent_plugin(name: &str, dependency: &str) -> MockPlugin {
        let dependency = dependency.to_string();

        MockPlugin::new(name, "1.0.0")
            .with_dependencies(vec![dependency.clone()])
            .with_execute(move |context| {
                let dep_output = context.get_dependency_output(&dependency).ok_or_else(|| {
                    crate::core::PluginError::ExecutionError(format!(
                        "Dependency '{}' output not found",
                        dependency
                    ))
                })?;

                Ok(PluginOutput::success(json!({
                    "dependency_processed": true,
                    "dependency_data": dep_output.data
                })))
            })
    }

    /// Create a plugin that takes a long time to execute (for timeout testing)
    pub fn slow_plugin(name: &str, duration_ms: u64) -> MockPlugin {
        MockPlugin::new(name, "1.0.0").with_execute(move |_| {
            std::thread::sleep(Duration::from_millis(duration_ms));
            Ok(PluginOutput::success(json!({
                "execution_time_ms": duration_ms
            })))
        })
    }
}

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

    #[tokio::test]
    async fn test_plugin_test_harness_basic() {
        let mut harness = PluginTestHarness::new().unwrap();

        let plugin = test_plugins::successful_plugin("test");
        harness = harness.with_plugin(plugin).unwrap();

        let output = harness.execute("test").await.unwrap();

        harness.assert_success(&output).unwrap();
        harness
            .assert_output_contains(&output, "status", &json!("completed"))
            .unwrap();
    }

    #[tokio::test]
    async fn test_mock_plugin_file_creation() {
        let mut harness = PluginTestHarness::new().unwrap();

        let plugin =
            test_plugins::file_creating_plugin("file-creator", "test.txt", "Hello, World!");
        harness = harness.with_plugin(plugin).unwrap();

        let output = harness.execute("file-creator").await.unwrap();

        harness.assert_success(&output).unwrap();
        harness
            .assert_artifacts_created(&output, &["test.txt"])
            .unwrap();

        let content = harness.read_workspace_file("test.txt").unwrap();
        assert_eq!(content, "Hello, World!");
    }

    #[tokio::test]
    async fn test_dependency_plugin() {
        let mut harness = PluginTestHarness::new().unwrap();

        // Add dependency output
        let dep_output = PluginOutput::success(json!({"value": 42}));
        harness = harness.with_dependency_output("dependency", dep_output);

        // Add dependent plugin
        let plugin = test_plugins::dependent_plugin("dependent", "dependency");
        harness = harness.with_plugin(plugin).unwrap();

        let output = harness.execute("dependent").await.unwrap();

        harness.assert_success(&output).unwrap();
        harness
            .assert_output_contains(&output, "dependency_processed", &json!(true))
            .unwrap();
    }

    #[tokio::test]
    async fn test_failing_plugin() {
        let mut harness = PluginTestHarness::new().unwrap();

        let plugin = test_plugins::failing_plugin("failure");
        harness = harness.with_plugin(plugin).unwrap();

        let result = harness.execute("failure").await;
        assert!(result.is_err());
    }

    #[test]
    fn test_workspace_file_operations() {
        let harness = PluginTestHarness::new().unwrap();

        // Create a file in the workspace
        harness
            .with_workspace_file("test/nested/file.txt", "test content")
            .unwrap();

        // Read it back
        let content = harness.read_workspace_file("test/nested/file.txt").unwrap();
        assert_eq!(content, "test content");
    }
}