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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
//! Configuration system for plugins and the plugin framework

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;

use crate::core::security::Permission;
use crate::core::{PluginError, PluginResult};

/// Configuration for the entire plugin system
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct PluginSystemConfig {
    /// Global settings for the plugin system
    pub system: SystemConfig,
    /// Plugin-specific configurations
    pub plugins: HashMap<String, PluginConfig>,
    /// Global permissions that apply to all plugins
    pub global_permissions: Vec<Permission>,
    /// Plugins to load on startup
    pub autoload_plugins: Vec<String>,
}

/// System-wide configuration settings
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SystemConfig {
    /// Maximum number of plugins that can run in parallel
    pub max_parallel_plugins: usize,
    /// Default workspace directory for plugin execution
    pub workspace: Option<PathBuf>,
    /// Enable debug logging
    pub debug: bool,
    /// Plugin discovery directories
    pub plugin_directories: Vec<PathBuf>,
    /// Maximum plugin execution timeout in seconds
    pub max_execution_timeout: Option<u64>,
    /// Enable sandbox isolation by default
    pub enable_sandbox: bool,
    /// Default sandbox configuration
    pub sandbox: SandboxConfig,
}

impl Default for SystemConfig {
    fn default() -> Self {
        Self {
            max_parallel_plugins: 4,
            workspace: None,
            debug: false,
            plugin_directories: vec![],
            max_execution_timeout: Some(300), // 5 minutes
            enable_sandbox: true,
            sandbox: SandboxConfig::default(),
        }
    }
}

/// Sandbox configuration settings
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SandboxConfig {
    /// Base directory for sandbox temporary directories
    pub temp_base_directory: Option<PathBuf>,
    /// Maximum memory usage per plugin (in bytes)
    pub max_memory: Option<u64>,
    /// Maximum execution time per plugin (in seconds)
    pub max_execution_time: Option<u64>,
    /// Default environment variables to allow
    pub allowed_env_vars: Vec<String>,
    /// Enable network isolation by default
    pub network_isolation: bool,
}

impl Default for SandboxConfig {
    fn default() -> Self {
        Self {
            temp_base_directory: None,
            max_memory: Some(128 * 1024 * 1024), // 128MB
            max_execution_time: Some(300),       // 5 minutes
            allowed_env_vars: vec!["PATH".to_string(), "HOME".to_string(), "USER".to_string()],
            network_isolation: false,
        }
    }
}

/// Configuration for a specific plugin
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct PluginConfig {
    /// Whether the plugin is enabled
    pub enabled: bool,
    /// Plugin-specific configuration data
    pub config: serde_json::Value,
    /// Permissions granted to this plugin
    pub permissions: Vec<Permission>,
    /// Plugin execution priority (higher = earlier execution)
    pub priority: i32,
    /// Override system-wide sandbox settings for this plugin
    pub sandbox_override: Option<SandboxConfig>,
    /// Plugin dependencies (must be executed before this plugin)
    pub dependencies: Vec<String>,
    /// Optional dependencies (executed before this plugin if available)
    pub optional_dependencies: Vec<String>,
    /// Retry configuration
    pub retry: RetryConfig,
}

impl Default for PluginConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            config: serde_json::json!({}),
            permissions: vec![],
            priority: 0,
            sandbox_override: None,
            dependencies: vec![],
            optional_dependencies: vec![],
            retry: RetryConfig::default(),
        }
    }
}

/// Retry configuration for plugin execution
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct RetryConfig {
    /// Maximum number of retry attempts
    pub max_attempts: u32,
    /// Delay between retry attempts in milliseconds
    pub delay_ms: u64,
    /// Exponential backoff multiplier
    pub backoff_multiplier: f64,
    /// Maximum delay between retries in milliseconds
    pub max_delay_ms: u64,
}

impl Default for RetryConfig {
    fn default() -> Self {
        Self {
            max_attempts: 3,
            delay_ms: 1000, // 1 second
            backoff_multiplier: 2.0,
            max_delay_ms: 30000, // 30 seconds
        }
    }
}

/// Configuration validation errors
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationError {
    /// Field that failed validation
    pub field: String,
    /// Error message
    pub message: String,
    /// Suggested fix (if any)
    pub suggestion: Option<String>,
}

impl ValidationError {
    pub fn new(field: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            field: field.into(),
            message: message.into(),
            suggestion: None,
        }
    }

    pub fn with_suggestion(mut self, suggestion: impl Into<String>) -> Self {
        self.suggestion = Some(suggestion.into());
        self
    }
}

/// Configuration validator for plugins and system settings
#[derive(Debug, Default)]
pub struct ConfigValidator {
    /// Known plugin schemas for validation
    plugin_schemas: HashMap<String, serde_json::Value>,
}

impl ConfigValidator {
    /// Create a new configuration validator
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a plugin's configuration schema
    pub fn register_plugin_schema(&mut self, plugin_name: String, schema: serde_json::Value) {
        self.plugin_schemas.insert(plugin_name, schema);
    }

    /// Validate the entire plugin system configuration
    pub fn validate_system_config(&self, config: &PluginSystemConfig) -> PluginResult<()> {
        let mut errors = Vec::new();

        // Validate system configuration
        if let Err(system_errors) = self.validate_system_settings(&config.system) {
            errors.extend(
                system_errors
                    .into_iter()
                    .map(|e| format!("system.{}: {}", e.field, e.message)),
            );
        }

        // Validate plugin configurations
        for (plugin_name, plugin_config) in &config.plugins {
            if let Err(plugin_errors) = self.validate_plugin_config(plugin_name, plugin_config) {
                errors.extend(
                    plugin_errors
                        .into_iter()
                        .map(|e| format!("plugins.{}.{}: {}", plugin_name, e.field, e.message)),
                );
            }
        }

        // Validate plugin dependencies
        if let Err(dep_errors) = self.validate_plugin_dependencies(config) {
            errors.extend(
                dep_errors
                    .into_iter()
                    .map(|e| format!("dependencies.{}: {}", e.field, e.message)),
            );
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(PluginError::ConfigurationError(format!(
                "Configuration validation failed:\n{}",
                errors.join("\n")
            )))
        }
    }

    /// Validate system-wide configuration settings
    fn validate_system_settings(&self, config: &SystemConfig) -> Result<(), Vec<ValidationError>> {
        let mut errors = Vec::new();

        // Validate max_parallel_plugins
        if config.max_parallel_plugins == 0 {
            errors.push(
                ValidationError::new("max_parallel_plugins", "Must be greater than 0")
                    .with_suggestion("Set to a value like 4 or 8"),
            );
        }

        // Validate plugin directories exist (if specified)
        for (i, dir) in config.plugin_directories.iter().enumerate() {
            if !dir.exists() {
                errors.push(
                    ValidationError::new(
                        format!("plugin_directories[{i}]"),
                        format!("Directory does not exist: {}", dir.display()),
                    )
                    .with_suggestion("Create the directory or remove it from the configuration"),
                );
            }
        }

        // Validate execution timeout
        if let Some(timeout) = config.max_execution_timeout {
            if timeout == 0 {
                errors.push(
                    ValidationError::new(
                        "max_execution_timeout",
                        "Timeout must be greater than 0 seconds",
                    )
                    .with_suggestion("Set to a reasonable value like 300 (5 minutes)"),
                );
            }
        }

        // Validate sandbox configuration
        if let Err(sandbox_errors) = self.validate_sandbox_config(&config.sandbox) {
            for error in sandbox_errors {
                errors.push(ValidationError::new(
                    format!("sandbox.{}", error.field),
                    error.message,
                ));
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    /// Validate sandbox configuration
    fn validate_sandbox_config(&self, config: &SandboxConfig) -> Result<(), Vec<ValidationError>> {
        let mut errors = Vec::new();

        // Validate memory limit
        if let Some(memory) = config.max_memory {
            if memory < 1024 * 1024 {
                // 1MB minimum
                errors.push(
                    ValidationError::new("max_memory", "Memory limit too low, minimum is 1MB")
                        .with_suggestion("Set to at least 1048576 bytes (1MB)"),
                );
            }
        }

        // Validate execution time
        if let Some(time) = config.max_execution_time {
            if time == 0 {
                errors.push(ValidationError::new(
                    "max_execution_time",
                    "Execution time must be greater than 0 seconds",
                ));
            }
        }

        // Validate base directory exists (if specified)
        if let Some(base_dir) = &config.temp_base_directory {
            if !base_dir.exists() {
                errors.push(
                    ValidationError::new(
                        "temp_base_directory",
                        format!("Base directory does not exist: {}", base_dir.display()),
                    )
                    .with_suggestion(
                        "Create the directory or remove the setting to use system temp",
                    ),
                );
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    /// Validate plugin configuration
    fn validate_plugin_config(
        &self,
        plugin_name: &str,
        config: &PluginConfig,
    ) -> Result<(), Vec<ValidationError>> {
        let mut errors = Vec::new();

        // Validate plugin configuration against schema (if available)
        if let Some(schema) = self.plugin_schemas.get(plugin_name) {
            if let Err(schema_errors) = self.validate_json_against_schema(&config.config, schema) {
                errors.extend(schema_errors);
            }
        }

        // Validate retry configuration
        if let Err(retry_errors) = self.validate_retry_config(&config.retry) {
            for error in retry_errors {
                errors.push(ValidationError::new(
                    format!("retry.{}", error.field),
                    error.message,
                ));
            }
        }

        // Validate sandbox override (if present)
        if let Some(sandbox_config) = &config.sandbox_override {
            if let Err(sandbox_errors) = self.validate_sandbox_config(sandbox_config) {
                for error in sandbox_errors {
                    errors.push(ValidationError::new(
                        format!("sandbox_override.{}", error.field),
                        error.message,
                    ));
                }
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    /// Validate retry configuration
    fn validate_retry_config(&self, config: &RetryConfig) -> Result<(), Vec<ValidationError>> {
        let mut errors = Vec::new();

        if config.backoff_multiplier <= 0.0 {
            errors.push(
                ValidationError::new("backoff_multiplier", "Must be greater than 0.0")
                    .with_suggestion("Use a value like 2.0 for exponential backoff"),
            );
        }

        if config.max_delay_ms < config.delay_ms {
            errors.push(ValidationError::new(
                "max_delay_ms",
                "Must be greater than or equal to delay_ms",
            ));
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    /// Validate plugin dependencies
    fn validate_plugin_dependencies(
        &self,
        config: &PluginSystemConfig,
    ) -> Result<(), Vec<ValidationError>> {
        let mut errors = Vec::new();

        for (plugin_name, plugin_config) in &config.plugins {
            // Check that all dependencies exist in the configuration
            for dep in &plugin_config.dependencies {
                if !config.plugins.contains_key(dep) && !config.autoload_plugins.contains(dep) {
                    errors.push(
                        ValidationError::new(
                            format!("{plugin_name}.dependencies"),
                            format!("Dependency '{dep}' is not configured"),
                        )
                        .with_suggestion(format!(
                            "Add '{dep}' to plugins configuration or autoload_plugins"
                        )),
                    );
                }
            }

            // Check optional dependencies
            for dep in &plugin_config.optional_dependencies {
                if !config.plugins.contains_key(dep) && !config.autoload_plugins.contains(dep) {
                    // This is just a warning, not an error, but we'll track it
                    eprintln!(
                        "Warning: Optional dependency '{dep}' for plugin '{plugin_name}' is not configured"
                    );
                }
            }
        }

        // Check for circular dependencies
        if let Err(cycle_error) = self.detect_circular_dependencies(config) {
            errors.push(cycle_error);
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    /// Detect circular dependencies in plugin configuration
    fn detect_circular_dependencies(
        &self,
        config: &PluginSystemConfig,
    ) -> Result<(), ValidationError> {
        // Simple cycle detection using DFS
        let mut visited = std::collections::HashSet::new();
        let mut rec_stack = std::collections::HashSet::new();

        for plugin_name in config.plugins.keys() {
            if !visited.contains(plugin_name)
                && Self::has_cycle_dfs(plugin_name, config, &mut visited, &mut rec_stack)
            {
                return Err(ValidationError::new(
                    "circular_dependency",
                    format!("Circular dependency detected involving plugin '{plugin_name}'"),
                )
                .with_suggestion("Review plugin dependencies to remove circular references"));
            }
        }

        Ok(())
    }

    /// DFS helper for cycle detection
    fn has_cycle_dfs(
        plugin: &str,
        config: &PluginSystemConfig,
        visited: &mut std::collections::HashSet<String>,
        rec_stack: &mut std::collections::HashSet<String>,
    ) -> bool {
        visited.insert(plugin.to_string());
        rec_stack.insert(plugin.to_string());

        if let Some(plugin_config) = config.plugins.get(plugin) {
            for dep in &plugin_config.dependencies {
                if !visited.contains(dep) {
                    if Self::has_cycle_dfs(dep, config, visited, rec_stack) {
                        return true;
                    }
                } else if rec_stack.contains(dep) {
                    return true;
                }
            }
        }

        rec_stack.remove(plugin);
        false
    }

    /// Validate JSON against a schema (basic implementation)
    fn validate_json_against_schema(
        &self,
        _value: &serde_json::Value,
        _schema: &serde_json::Value,
    ) -> Result<(), Vec<ValidationError>> {
        // For now, this is a placeholder. In a full implementation, we'd use a JSON Schema library
        // like `jsonschema` or `valico` to perform proper schema validation
        Ok(())
    }

    /// Get validation errors as strings
    pub fn get_validation_errors(&self, config: &PluginSystemConfig) -> Vec<String> {
        match self.validate_system_config(config) {
            Ok(()) => vec![],
            Err(PluginError::ConfigurationError(msg)) => {
                msg.lines().map(|line| line.to_string()).collect()
            }
            Err(e) => vec![e.to_string()],
        }
    }
}

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

    #[test]
    fn test_default_configurations() {
        let system_config = SystemConfig::default();
        assert_eq!(system_config.max_parallel_plugins, 4);
        assert!(system_config.enable_sandbox);

        let plugin_config = PluginConfig::default();
        assert!(plugin_config.enabled);
        assert_eq!(plugin_config.priority, 0);

        let retry_config = RetryConfig::default();
        assert_eq!(retry_config.max_attempts, 3);
        assert_eq!(retry_config.delay_ms, 1000);
    }

    #[test]
    fn test_plugin_system_config_serialization() {
        let config = PluginSystemConfig::default();
        let json_str = serde_json::to_string_pretty(&config).unwrap();
        let deserialized: PluginSystemConfig = serde_json::from_str(&json_str).unwrap();

        assert_eq!(
            config.system.max_parallel_plugins,
            deserialized.system.max_parallel_plugins
        );
        assert_eq!(
            config.system.enable_sandbox,
            deserialized.system.enable_sandbox
        );
    }

    #[test]
    fn test_config_validator_system_validation() {
        let validator = ConfigValidator::new();

        // Valid configuration
        let valid_config = SystemConfig::default();
        assert!(validator.validate_system_settings(&valid_config).is_ok());

        // Invalid configuration - zero parallel plugins
        let invalid_config = SystemConfig {
            max_parallel_plugins: 0,
            ..Default::default()
        };
        assert!(validator.validate_system_settings(&invalid_config).is_err());
    }

    #[test]
    fn test_config_validator_sandbox_validation() {
        let validator = ConfigValidator::new();

        // Valid sandbox config
        let valid_config = SandboxConfig::default();
        assert!(validator.validate_sandbox_config(&valid_config).is_ok());

        // Invalid sandbox config - too low memory
        let invalid_config = SandboxConfig {
            max_memory: Some(1000), // Less than 1MB
            ..Default::default()
        };
        assert!(validator.validate_sandbox_config(&invalid_config).is_err());
    }

    #[test]
    fn test_config_validator_plugin_dependencies() {
        let validator = ConfigValidator::new();

        let mut config = PluginSystemConfig::default();

        // Add plugin with valid dependency
        let plugin_a = PluginConfig::default();
        let plugin_b = PluginConfig {
            dependencies: vec!["plugin-a".to_string()],
            ..Default::default()
        };

        config.plugins.insert("plugin-a".to_string(), plugin_a);
        config.plugins.insert("plugin-b".to_string(), plugin_b);

        assert!(validator.validate_plugin_dependencies(&config).is_ok());

        // Add plugin with missing dependency
        let plugin_c = PluginConfig {
            dependencies: vec!["non-existent".to_string()],
            ..Default::default()
        };
        config.plugins.insert("plugin-c".to_string(), plugin_c);

        assert!(validator.validate_plugin_dependencies(&config).is_err());
    }

    #[test]
    fn test_circular_dependency_detection() {
        let validator = ConfigValidator::new();

        let mut config = PluginSystemConfig::default();

        // Create circular dependency: A -> B -> A
        let plugin_a = PluginConfig {
            dependencies: vec!["plugin-b".to_string()],
            ..Default::default()
        };

        let plugin_b = PluginConfig {
            dependencies: vec!["plugin-a".to_string()],
            ..Default::default()
        };

        config.plugins.insert("plugin-a".to_string(), plugin_a);
        config.plugins.insert("plugin-b".to_string(), plugin_b);

        assert!(validator.validate_plugin_dependencies(&config).is_err());
    }

    #[test]
    fn test_retry_config_validation() {
        let validator = ConfigValidator::new();

        // Valid retry config
        let valid_config = RetryConfig::default();
        assert!(validator.validate_retry_config(&valid_config).is_ok());

        // Invalid retry config - zero backoff multiplier
        let invalid_config = RetryConfig {
            backoff_multiplier: 0.0,
            ..Default::default()
        };
        assert!(validator.validate_retry_config(&invalid_config).is_err());

        // Invalid retry config - max_delay_ms < delay_ms
        let invalid_config2 = RetryConfig {
            delay_ms: 5000,
            max_delay_ms: 1000,
            ..Default::default()
        };
        assert!(validator.validate_retry_config(&invalid_config2).is_err());
    }

    #[test]
    fn test_validation_error_with_suggestion() {
        let error = ValidationError::new("test_field", "Test error message")
            .with_suggestion("Try this fix");

        assert_eq!(error.field, "test_field");
        assert_eq!(error.message, "Test error message");
        assert_eq!(error.suggestion, Some("Try this fix".to_string()));
    }
}