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
//! Configuration loading and management

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use crate::core::config::SandboxConfig as ConfigSandboxConfig;
use crate::core::{ConfigValidator, PluginError, PluginResult, PluginSystemConfig, SystemConfig};

/// Configuration sources that can be loaded
#[derive(Debug, Clone)]
pub enum ConfigSource {
    /// Load from a file path
    File(PathBuf),
    /// Load from a JSON string
    Json(String),
    /// Load from TOML string
    Toml(String),
    /// Load from YAML string  
    Yaml(String),
    /// Load from environment variables
    Environment { prefix: String },
    /// Load from multiple sources (merged in order)
    Multiple(Vec<ConfigSource>),
}

/// Configuration loading options
#[derive(Debug, Clone)]
pub struct LoadOptions {
    /// Whether to validate configuration after loading
    pub validate: bool,
    /// Whether to merge with default configuration
    pub use_defaults: bool,
    /// Whether to allow missing files (for file sources)
    pub allow_missing: bool,
    /// Whether to expand environment variables in config values
    pub expand_env_vars: bool,
}

impl Default for LoadOptions {
    fn default() -> Self {
        Self {
            validate: true,
            use_defaults: true,
            allow_missing: false,
            expand_env_vars: true,
        }
    }
}

/// Configuration loader for the plugin system
#[derive(Debug)]
pub struct ConfigLoader {
    validator: ConfigValidator,
    options: LoadOptions,
}

impl ConfigLoader {
    /// Create a new configuration loader
    pub fn new() -> Self {
        Self {
            validator: ConfigValidator::new(),
            options: LoadOptions::default(),
        }
    }

    /// Create a configuration loader with custom options
    pub fn with_options(options: LoadOptions) -> Self {
        Self {
            validator: ConfigValidator::new(),
            options,
        }
    }

    /// Create a configuration loader with custom validator
    pub fn with_validator(validator: ConfigValidator) -> Self {
        Self {
            validator,
            options: LoadOptions::default(),
        }
    }

    /// Load configuration from a source
    pub async fn load(&self, source: ConfigSource) -> PluginResult<PluginSystemConfig> {
        let mut config = if self.options.use_defaults {
            PluginSystemConfig::default()
        } else {
            PluginSystemConfig {
                system: SystemConfig {
                    max_parallel_plugins: 1, // Minimal defaults
                    workspace: None,
                    debug: false,
                    plugin_directories: vec![],
                    max_execution_timeout: None,
                    enable_sandbox: false,
                    sandbox: Default::default(),
                },
                plugins: HashMap::new(),
                global_permissions: vec![],
                autoload_plugins: vec![],
            }
        };

        // Load from source
        let loaded_config = self.load_from_source(source).await?;

        // Merge with existing config
        self.merge_configs(&mut config, loaded_config)?;

        // Expand environment variables if requested
        if self.options.expand_env_vars {
            self.expand_environment_variables(&mut config)?;
        }

        // Validate if requested
        if self.options.validate {
            self.validator.validate_system_config(&config)?;
        }

        Ok(config)
    }

    /// Load configuration from a specific source
    fn load_from_source(
        &self,
        source: ConfigSource,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = PluginResult<PluginSystemConfig>> + '_>>
    {
        Box::pin(async move {
            match source {
                ConfigSource::File(path) => self.load_from_file(&path).await,
                ConfigSource::Json(json_str) => self.load_from_json(&json_str),
                ConfigSource::Toml(toml_str) => self.load_from_toml(&toml_str),
                ConfigSource::Yaml(yaml_str) => self.load_from_yaml(&yaml_str),
                ConfigSource::Environment { prefix } => self.load_from_environment(&prefix),
                ConfigSource::Multiple(sources) => {
                    let mut merged_config = PluginSystemConfig::default();
                    for source in sources {
                        let source_config = self.load_from_source(source).await?;
                        self.merge_configs(&mut merged_config, source_config)?;
                    }
                    Ok(merged_config)
                }
            }
        })
    }

    /// Load configuration from a file
    async fn load_from_file(&self, path: &Path) -> PluginResult<PluginSystemConfig> {
        if !path.exists() {
            if self.options.allow_missing {
                return Ok(PluginSystemConfig::default());
            } else {
                return Err(PluginError::ConfigurationError(format!(
                    "Configuration file not found: {}",
                    path.display()
                )));
            }
        }

        let content = tokio::fs::read_to_string(path).await.map_err(|e| {
            PluginError::ConfigurationError(format!(
                "Failed to read configuration file {}: {}",
                path.display(),
                e
            ))
        })?;

        // Determine format from file extension
        match path.extension().and_then(|ext| ext.to_str()) {
            Some("json") => self.load_from_json(&content),
            Some("toml") => self.load_from_toml(&content),
            Some("yaml") | Some("yml") => self.load_from_yaml(&content),
            _ => {
                // Try to parse as JSON first, then TOML, then YAML
                self.load_from_json(&content)
                    .or_else(|_| self.load_from_toml(&content))
                    .or_else(|_| self.load_from_yaml(&content))
                    .map_err(|_| {
                        PluginError::ConfigurationError(format!(
                            "Unable to parse configuration file {} (tried JSON, TOML, and YAML)",
                            path.display()
                        ))
                    })
            }
        }
    }

    /// Load configuration from JSON string
    fn load_from_json(&self, json_str: &str) -> PluginResult<PluginSystemConfig> {
        serde_json::from_str(json_str).map_err(|e| {
            PluginError::ConfigurationError(format!("Failed to parse JSON configuration: {e}"))
        })
    }

    /// Load configuration from TOML string
    fn load_from_toml(&self, toml_str: &str) -> PluginResult<PluginSystemConfig> {
        toml::from_str(toml_str).map_err(|e| {
            PluginError::ConfigurationError(format!("Failed to parse TOML configuration: {e}"))
        })
    }

    /// Load configuration from YAML string
    fn load_from_yaml(&self, yaml_str: &str) -> PluginResult<PluginSystemConfig> {
        serde_yaml::from_str(yaml_str).map_err(|e| {
            PluginError::ConfigurationError(format!("Failed to parse YAML configuration: {e}"))
        })
    }

    /// Load configuration from environment variables
    fn load_from_environment(&self, prefix: &str) -> PluginResult<PluginSystemConfig> {
        let mut config = PluginSystemConfig::default();

        // Load system configuration from environment
        if let Ok(max_parallel) = std::env::var(format!("{prefix}_MAX_PARALLEL_PLUGINS")) {
            config.system.max_parallel_plugins = max_parallel.parse().map_err(|e| {
                PluginError::ConfigurationError(format!(
                    "Invalid value for {prefix}_MAX_PARALLEL_PLUGINS: {e}"
                ))
            })?;
        }

        if let Ok(debug) = std::env::var(format!("{prefix}_DEBUG")) {
            config.system.debug = debug.parse().unwrap_or(false);
        }

        if let Ok(workspace) = std::env::var(format!("{prefix}_WORKSPACE")) {
            config.system.workspace = Some(PathBuf::from(workspace));
        }

        if let Ok(enable_sandbox) = std::env::var(format!("{prefix}_ENABLE_SANDBOX")) {
            config.system.enable_sandbox = enable_sandbox.parse().unwrap_or(true);
        }

        // Load plugin directories
        if let Ok(plugin_dirs) = std::env::var(format!("{prefix}_PLUGIN_DIRECTORIES")) {
            config.system.plugin_directories = plugin_dirs
                .split(':')
                .map(|s| PathBuf::from(s.trim()))
                .collect();
        }

        Ok(config)
    }

    /// Merge two configurations (source into target)
    fn merge_configs(
        &self,
        target: &mut PluginSystemConfig,
        source: PluginSystemConfig,
    ) -> PluginResult<()> {
        // Merge system configuration
        self.merge_system_config(&mut target.system, source.system);

        // Merge plugin configurations
        for (name, plugin_config) in source.plugins {
            target.plugins.insert(name, plugin_config);
        }

        // Merge global permissions (append, don't replace)
        target.global_permissions.extend(source.global_permissions);

        // Merge autoload plugins (append, don't replace)
        target.autoload_plugins.extend(source.autoload_plugins);

        Ok(())
    }

    /// Merge system configurations
    fn merge_system_config(&self, target: &mut SystemConfig, source: SystemConfig) {
        if source.max_parallel_plugins != SystemConfig::default().max_parallel_plugins {
            target.max_parallel_plugins = source.max_parallel_plugins;
        }

        if source.workspace.is_some() {
            target.workspace = source.workspace;
        }

        if source.debug != SystemConfig::default().debug {
            target.debug = source.debug;
        }

        if !source.plugin_directories.is_empty() {
            target.plugin_directories.extend(source.plugin_directories);
        }

        if source.max_execution_timeout.is_some() {
            target.max_execution_timeout = source.max_execution_timeout;
        }

        if source.enable_sandbox != SystemConfig::default().enable_sandbox {
            target.enable_sandbox = source.enable_sandbox;
        }

        // Merge sandbox configuration
        self.merge_sandbox_config(&mut target.sandbox, source.sandbox);
    }

    /// Merge sandbox configurations
    fn merge_sandbox_config(&self, target: &mut ConfigSandboxConfig, source: ConfigSandboxConfig) {
        if source.temp_base_directory.is_some() {
            target.temp_base_directory = source.temp_base_directory;
        }

        if source.max_memory.is_some() {
            target.max_memory = source.max_memory;
        }

        if source.max_execution_time.is_some() {
            target.max_execution_time = source.max_execution_time;
        }

        if !source.allowed_env_vars.is_empty() {
            target.allowed_env_vars = source.allowed_env_vars;
        }

        if source.network_isolation != ConfigSandboxConfig::default().network_isolation {
            target.network_isolation = source.network_isolation;
        }
    }

    /// Expand environment variables in configuration values
    fn expand_environment_variables(&self, config: &mut PluginSystemConfig) -> PluginResult<()> {
        // Expand workspace path
        if let Some(workspace) = &config.system.workspace {
            config.system.workspace = Some(self.expand_env_in_path(workspace)?);
        }

        // Expand plugin directories
        config.system.plugin_directories = config
            .system
            .plugin_directories
            .iter()
            .map(|path| self.expand_env_in_path(path))
            .collect::<Result<Vec<_>, _>>()?;

        // Expand sandbox temp base directory
        if let Some(temp_base) = &config.system.sandbox.temp_base_directory {
            config.system.sandbox.temp_base_directory = Some(self.expand_env_in_path(temp_base)?);
        }

        Ok(())
    }

    /// Expand environment variables in a path
    fn expand_env_in_path(&self, path: &Path) -> PluginResult<PathBuf> {
        let path_str = path.to_string_lossy();
        let expanded = shellexpand::full(&path_str).map_err(|e| {
            PluginError::ConfigurationError(format!(
                "Failed to expand environment variables in path '{path_str}': {e}"
            ))
        })?;
        Ok(PathBuf::from(expanded.as_ref()))
    }

    /// Save configuration to a file
    pub async fn save(&self, config: &PluginSystemConfig, path: &Path) -> PluginResult<()> {
        // Determine format from file extension
        let content = match path.extension().and_then(|ext| ext.to_str()) {
            Some("json") => serde_json::to_string_pretty(config).map_err(|e| {
                PluginError::ConfigurationError(format!("Failed to serialize to JSON: {e}"))
            })?,
            Some("toml") => toml::to_string_pretty(config).map_err(|e| {
                PluginError::ConfigurationError(format!("Failed to serialize to TOML: {e}"))
            })?,
            Some("yaml") | Some("yml") => serde_yaml::to_string(config).map_err(|e| {
                PluginError::ConfigurationError(format!("Failed to serialize to YAML: {e}"))
            })?,
            _ => {
                return Err(PluginError::ConfigurationError(format!(
                    "Unsupported file format for path: {}",
                    path.display()
                )));
            }
        };

        // Create parent directory if it doesn't exist
        if let Some(parent) = path.parent() {
            tokio::fs::create_dir_all(parent).await.map_err(|e| {
                PluginError::ConfigurationError(format!(
                    "Failed to create directory {}: {}",
                    parent.display(),
                    e
                ))
            })?;
        }

        // Write the file
        tokio::fs::write(path, content).await.map_err(|e| {
            PluginError::ConfigurationError(format!(
                "Failed to write configuration to {}: {}",
                path.display(),
                e
            ))
        })
    }

    /// Get the validator
    pub fn validator(&self) -> &ConfigValidator {
        &self.validator
    }

    /// Get a mutable reference to the validator
    pub fn validator_mut(&mut self) -> &mut ConfigValidator {
        &mut self.validator
    }
}

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

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

    #[tokio::test]
    async fn test_load_from_json_string() {
        let loader = ConfigLoader::new();
        let json_config = r#"
        {
            "system": {
                "max_parallel_plugins": 8,
                "debug": true
            },
            "plugins": {
                "test-plugin": {
                    "enabled": true,
                    "priority": 10
                }
            }
        }
        "#;

        let config = loader
            .load(ConfigSource::Json(json_config.to_string()))
            .await
            .unwrap();
        assert_eq!(config.system.max_parallel_plugins, 8);
        assert!(config.system.debug);
        assert!(config.plugins.contains_key("test-plugin"));
    }

    #[tokio::test]
    async fn test_load_from_toml_string() {
        let loader = ConfigLoader::new();
        let toml_config = r#"
        [system]
        max_parallel_plugins = 6
        debug = false

        [plugins.test-plugin]
        enabled = true
        priority = 5
        "#;

        let config = loader
            .load(ConfigSource::Toml(toml_config.to_string()))
            .await
            .unwrap();
        assert_eq!(config.system.max_parallel_plugins, 6);
        assert!(!config.system.debug);
        assert!(config.plugins.contains_key("test-plugin"));
    }

    #[tokio::test]
    async fn test_load_from_yaml_string() {
        let loader = ConfigLoader::new();
        let yaml_config = r#"
        system:
          max_parallel_plugins: 12
          debug: true
        plugins:
          test-plugin:
            enabled: true
            priority: 15
        "#;

        let config = loader
            .load(ConfigSource::Yaml(yaml_config.to_string()))
            .await
            .unwrap();
        assert_eq!(config.system.max_parallel_plugins, 12);
        assert!(config.system.debug);
        assert!(config.plugins.contains_key("test-plugin"));
    }

    #[tokio::test]
    async fn test_load_from_environment() {
        let loader = ConfigLoader::new();

        // Set environment variables
        std::env::set_var("TEST_MAX_PARALLEL_PLUGINS", "16");
        std::env::set_var("TEST_DEBUG", "true");
        std::env::set_var("TEST_ENABLE_SANDBOX", "false");

        let config = loader
            .load(ConfigSource::Environment {
                prefix: "TEST".to_string(),
            })
            .await
            .unwrap();

        assert_eq!(config.system.max_parallel_plugins, 16);
        assert!(config.system.debug);
        assert!(!config.system.enable_sandbox);

        // Clean up environment variables
        std::env::remove_var("TEST_MAX_PARALLEL_PLUGINS");
        std::env::remove_var("TEST_DEBUG");
        std::env::remove_var("TEST_ENABLE_SANDBOX");
    }

    #[tokio::test]
    async fn test_load_from_file() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("test_config.json");

        let json_config = serde_json::json!({
            "system": {
                "max_parallel_plugins": 20,
                "debug": true
            },
            "plugins": {
                "file-plugin": {
                    "enabled": true,
                    "priority": 100
                }
            }
        });

        // Write config file
        tokio::fs::write(
            &config_path,
            serde_json::to_string_pretty(&json_config).unwrap(),
        )
        .await
        .unwrap();

        let loader = ConfigLoader::new();
        let config = loader.load(ConfigSource::File(config_path)).await.unwrap();

        assert_eq!(config.system.max_parallel_plugins, 20);
        assert!(config.system.debug);
        assert!(config.plugins.contains_key("file-plugin"));
    }

    #[tokio::test]
    async fn test_config_merging() {
        let loader = ConfigLoader::new();

        let sources = vec![
            ConfigSource::Json(
                r#"
            {
                "system": { "max_parallel_plugins": 4 },
                "plugins": { "plugin-a": { "enabled": true } }
            }
            "#
                .to_string(),
            ),
            ConfigSource::Json(
                r#"
            {
                "system": { "debug": true },
                "plugins": { "plugin-b": { "enabled": false } }
            }
            "#
                .to_string(),
            ),
        ];

        let config = loader.load(ConfigSource::Multiple(sources)).await.unwrap();

        assert_eq!(config.system.max_parallel_plugins, 4);
        assert!(config.system.debug);
        assert!(config.plugins.contains_key("plugin-a"));
        assert!(config.plugins.contains_key("plugin-b"));
    }

    #[tokio::test]
    async fn test_save_configuration() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("saved_config.json");

        let mut config = PluginSystemConfig::default();
        config.system.max_parallel_plugins = 42;
        config.system.debug = true;

        let loader = ConfigLoader::new();
        loader.save(&config, &config_path).await.unwrap();

        // Load it back and verify
        let loaded_config = loader.load(ConfigSource::File(config_path)).await.unwrap();
        assert_eq!(loaded_config.system.max_parallel_plugins, 42);
        assert!(loaded_config.system.debug);
    }

    #[tokio::test]
    async fn test_load_options() {
        let loader = ConfigLoader::with_options(LoadOptions {
            validate: false,
            use_defaults: false,
            allow_missing: true,
            expand_env_vars: false,
        });

        let non_existent_path = PathBuf::from("/non/existent/config.json");
        let config = loader
            .load(ConfigSource::File(non_existent_path))
            .await
            .unwrap();

        // Should get minimal config when use_defaults is false and file is missing
        assert_eq!(config.system.max_parallel_plugins, 1); // Minimal default
    }
}