Skip to main content

pluggable/core/
config_loader.rs

1//! Configuration loading and management
2
3use std::collections::HashMap;
4use std::path::{Path, PathBuf};
5
6use crate::core::config::SandboxConfig as ConfigSandboxConfig;
7use crate::core::{ConfigValidator, PluginError, PluginResult, PluginSystemConfig, SystemConfig};
8
9/// Configuration sources that can be loaded
10#[derive(Debug, Clone)]
11pub enum ConfigSource {
12    /// Load from a file path
13    File(PathBuf),
14    /// Load from a JSON string
15    Json(String),
16    /// Load from TOML string
17    Toml(String),
18    /// Load from YAML string  
19    Yaml(String),
20    /// Load from environment variables
21    Environment { prefix: String },
22    /// Load from multiple sources (merged in order)
23    Multiple(Vec<ConfigSource>),
24}
25
26/// Configuration loading options
27#[derive(Debug, Clone)]
28pub struct LoadOptions {
29    /// Whether to validate configuration after loading
30    pub validate: bool,
31    /// Whether to merge with default configuration
32    pub use_defaults: bool,
33    /// Whether to allow missing files (for file sources)
34    pub allow_missing: bool,
35    /// Whether to expand environment variables in config values
36    pub expand_env_vars: bool,
37}
38
39impl Default for LoadOptions {
40    fn default() -> Self {
41        Self {
42            validate: true,
43            use_defaults: true,
44            allow_missing: false,
45            expand_env_vars: true,
46        }
47    }
48}
49
50/// Configuration loader for the plugin system
51#[derive(Debug)]
52pub struct ConfigLoader {
53    validator: ConfigValidator,
54    options: LoadOptions,
55}
56
57impl ConfigLoader {
58    /// Create a new configuration loader
59    pub fn new() -> Self {
60        Self {
61            validator: ConfigValidator::new(),
62            options: LoadOptions::default(),
63        }
64    }
65
66    /// Create a configuration loader with custom options
67    pub fn with_options(options: LoadOptions) -> Self {
68        Self {
69            validator: ConfigValidator::new(),
70            options,
71        }
72    }
73
74    /// Create a configuration loader with custom validator
75    pub fn with_validator(validator: ConfigValidator) -> Self {
76        Self {
77            validator,
78            options: LoadOptions::default(),
79        }
80    }
81
82    /// Load configuration from a source
83    pub async fn load(&self, source: ConfigSource) -> PluginResult<PluginSystemConfig> {
84        let mut config = if self.options.use_defaults {
85            PluginSystemConfig::default()
86        } else {
87            PluginSystemConfig {
88                system: SystemConfig {
89                    max_parallel_plugins: 1, // Minimal defaults
90                    workspace: None,
91                    debug: false,
92                    plugin_directories: vec![],
93                    max_execution_timeout: None,
94                    enable_sandbox: false,
95                    sandbox: Default::default(),
96                },
97                plugins: HashMap::new(),
98                global_permissions: vec![],
99                autoload_plugins: vec![],
100            }
101        };
102
103        // Load from source
104        let loaded_config = self.load_from_source(source).await?;
105
106        // Merge with existing config
107        self.merge_configs(&mut config, loaded_config)?;
108
109        // Expand environment variables if requested
110        if self.options.expand_env_vars {
111            self.expand_environment_variables(&mut config)?;
112        }
113
114        // Validate if requested
115        if self.options.validate {
116            self.validator.validate_system_config(&config)?;
117        }
118
119        Ok(config)
120    }
121
122    /// Load configuration from a specific source
123    fn load_from_source(
124        &self,
125        source: ConfigSource,
126    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = PluginResult<PluginSystemConfig>> + '_>>
127    {
128        Box::pin(async move {
129            match source {
130                ConfigSource::File(path) => self.load_from_file(&path).await,
131                ConfigSource::Json(json_str) => self.load_from_json(&json_str),
132                ConfigSource::Toml(toml_str) => self.load_from_toml(&toml_str),
133                ConfigSource::Yaml(yaml_str) => self.load_from_yaml(&yaml_str),
134                ConfigSource::Environment { prefix } => self.load_from_environment(&prefix),
135                ConfigSource::Multiple(sources) => {
136                    let mut merged_config = PluginSystemConfig::default();
137                    for source in sources {
138                        let source_config = self.load_from_source(source).await?;
139                        self.merge_configs(&mut merged_config, source_config)?;
140                    }
141                    Ok(merged_config)
142                }
143            }
144        })
145    }
146
147    /// Load configuration from a file
148    async fn load_from_file(&self, path: &Path) -> PluginResult<PluginSystemConfig> {
149        if !path.exists() {
150            if self.options.allow_missing {
151                return Ok(PluginSystemConfig::default());
152            } else {
153                return Err(PluginError::ConfigurationError(format!(
154                    "Configuration file not found: {}",
155                    path.display()
156                )));
157            }
158        }
159
160        let content = tokio::fs::read_to_string(path).await.map_err(|e| {
161            PluginError::ConfigurationError(format!(
162                "Failed to read configuration file {}: {}",
163                path.display(),
164                e
165            ))
166        })?;
167
168        // Determine format from file extension
169        match path.extension().and_then(|ext| ext.to_str()) {
170            Some("json") => self.load_from_json(&content),
171            Some("toml") => self.load_from_toml(&content),
172            Some("yaml") | Some("yml") => self.load_from_yaml(&content),
173            _ => {
174                // Try to parse as JSON first, then TOML, then YAML
175                self.load_from_json(&content)
176                    .or_else(|_| self.load_from_toml(&content))
177                    .or_else(|_| self.load_from_yaml(&content))
178                    .map_err(|_| {
179                        PluginError::ConfigurationError(format!(
180                            "Unable to parse configuration file {} (tried JSON, TOML, and YAML)",
181                            path.display()
182                        ))
183                    })
184            }
185        }
186    }
187
188    /// Load configuration from JSON string
189    fn load_from_json(&self, json_str: &str) -> PluginResult<PluginSystemConfig> {
190        serde_json::from_str(json_str).map_err(|e| {
191            PluginError::ConfigurationError(format!("Failed to parse JSON configuration: {e}"))
192        })
193    }
194
195    /// Load configuration from TOML string
196    fn load_from_toml(&self, toml_str: &str) -> PluginResult<PluginSystemConfig> {
197        toml::from_str(toml_str).map_err(|e| {
198            PluginError::ConfigurationError(format!("Failed to parse TOML configuration: {e}"))
199        })
200    }
201
202    /// Load configuration from YAML string
203    fn load_from_yaml(&self, yaml_str: &str) -> PluginResult<PluginSystemConfig> {
204        serde_yaml::from_str(yaml_str).map_err(|e| {
205            PluginError::ConfigurationError(format!("Failed to parse YAML configuration: {e}"))
206        })
207    }
208
209    /// Load configuration from environment variables
210    fn load_from_environment(&self, prefix: &str) -> PluginResult<PluginSystemConfig> {
211        let mut config = PluginSystemConfig::default();
212
213        // Load system configuration from environment
214        if let Ok(max_parallel) = std::env::var(format!("{prefix}_MAX_PARALLEL_PLUGINS")) {
215            config.system.max_parallel_plugins = max_parallel.parse().map_err(|e| {
216                PluginError::ConfigurationError(format!(
217                    "Invalid value for {prefix}_MAX_PARALLEL_PLUGINS: {e}"
218                ))
219            })?;
220        }
221
222        if let Ok(debug) = std::env::var(format!("{prefix}_DEBUG")) {
223            config.system.debug = debug.parse().unwrap_or(false);
224        }
225
226        if let Ok(workspace) = std::env::var(format!("{prefix}_WORKSPACE")) {
227            config.system.workspace = Some(PathBuf::from(workspace));
228        }
229
230        if let Ok(enable_sandbox) = std::env::var(format!("{prefix}_ENABLE_SANDBOX")) {
231            config.system.enable_sandbox = enable_sandbox.parse().unwrap_or(true);
232        }
233
234        // Load plugin directories
235        if let Ok(plugin_dirs) = std::env::var(format!("{prefix}_PLUGIN_DIRECTORIES")) {
236            config.system.plugin_directories = plugin_dirs
237                .split(':')
238                .map(|s| PathBuf::from(s.trim()))
239                .collect();
240        }
241
242        Ok(config)
243    }
244
245    /// Merge two configurations (source into target)
246    fn merge_configs(
247        &self,
248        target: &mut PluginSystemConfig,
249        source: PluginSystemConfig,
250    ) -> PluginResult<()> {
251        // Merge system configuration
252        self.merge_system_config(&mut target.system, source.system);
253
254        // Merge plugin configurations
255        for (name, plugin_config) in source.plugins {
256            target.plugins.insert(name, plugin_config);
257        }
258
259        // Merge global permissions (append, don't replace)
260        target.global_permissions.extend(source.global_permissions);
261
262        // Merge autoload plugins (append, don't replace)
263        target.autoload_plugins.extend(source.autoload_plugins);
264
265        Ok(())
266    }
267
268    /// Merge system configurations
269    fn merge_system_config(&self, target: &mut SystemConfig, source: SystemConfig) {
270        if source.max_parallel_plugins != SystemConfig::default().max_parallel_plugins {
271            target.max_parallel_plugins = source.max_parallel_plugins;
272        }
273
274        if source.workspace.is_some() {
275            target.workspace = source.workspace;
276        }
277
278        if source.debug != SystemConfig::default().debug {
279            target.debug = source.debug;
280        }
281
282        if !source.plugin_directories.is_empty() {
283            target.plugin_directories.extend(source.plugin_directories);
284        }
285
286        if source.max_execution_timeout.is_some() {
287            target.max_execution_timeout = source.max_execution_timeout;
288        }
289
290        if source.enable_sandbox != SystemConfig::default().enable_sandbox {
291            target.enable_sandbox = source.enable_sandbox;
292        }
293
294        // Merge sandbox configuration
295        self.merge_sandbox_config(&mut target.sandbox, source.sandbox);
296    }
297
298    /// Merge sandbox configurations
299    fn merge_sandbox_config(&self, target: &mut ConfigSandboxConfig, source: ConfigSandboxConfig) {
300        if source.temp_base_directory.is_some() {
301            target.temp_base_directory = source.temp_base_directory;
302        }
303
304        if source.max_memory.is_some() {
305            target.max_memory = source.max_memory;
306        }
307
308        if source.max_execution_time.is_some() {
309            target.max_execution_time = source.max_execution_time;
310        }
311
312        if !source.allowed_env_vars.is_empty() {
313            target.allowed_env_vars = source.allowed_env_vars;
314        }
315
316        if source.network_isolation != ConfigSandboxConfig::default().network_isolation {
317            target.network_isolation = source.network_isolation;
318        }
319    }
320
321    /// Expand environment variables in configuration values
322    fn expand_environment_variables(&self, config: &mut PluginSystemConfig) -> PluginResult<()> {
323        // Expand workspace path
324        if let Some(workspace) = &config.system.workspace {
325            config.system.workspace = Some(self.expand_env_in_path(workspace)?);
326        }
327
328        // Expand plugin directories
329        config.system.plugin_directories = config
330            .system
331            .plugin_directories
332            .iter()
333            .map(|path| self.expand_env_in_path(path))
334            .collect::<Result<Vec<_>, _>>()?;
335
336        // Expand sandbox temp base directory
337        if let Some(temp_base) = &config.system.sandbox.temp_base_directory {
338            config.system.sandbox.temp_base_directory = Some(self.expand_env_in_path(temp_base)?);
339        }
340
341        Ok(())
342    }
343
344    /// Expand environment variables in a path
345    fn expand_env_in_path(&self, path: &Path) -> PluginResult<PathBuf> {
346        let path_str = path.to_string_lossy();
347        let expanded = shellexpand::full(&path_str).map_err(|e| {
348            PluginError::ConfigurationError(format!(
349                "Failed to expand environment variables in path '{path_str}': {e}"
350            ))
351        })?;
352        Ok(PathBuf::from(expanded.as_ref()))
353    }
354
355    /// Save configuration to a file
356    pub async fn save(&self, config: &PluginSystemConfig, path: &Path) -> PluginResult<()> {
357        // Determine format from file extension
358        let content = match path.extension().and_then(|ext| ext.to_str()) {
359            Some("json") => serde_json::to_string_pretty(config).map_err(|e| {
360                PluginError::ConfigurationError(format!("Failed to serialize to JSON: {e}"))
361            })?,
362            Some("toml") => toml::to_string_pretty(config).map_err(|e| {
363                PluginError::ConfigurationError(format!("Failed to serialize to TOML: {e}"))
364            })?,
365            Some("yaml") | Some("yml") => serde_yaml::to_string(config).map_err(|e| {
366                PluginError::ConfigurationError(format!("Failed to serialize to YAML: {e}"))
367            })?,
368            _ => {
369                return Err(PluginError::ConfigurationError(format!(
370                    "Unsupported file format for path: {}",
371                    path.display()
372                )));
373            }
374        };
375
376        // Create parent directory if it doesn't exist
377        if let Some(parent) = path.parent() {
378            tokio::fs::create_dir_all(parent).await.map_err(|e| {
379                PluginError::ConfigurationError(format!(
380                    "Failed to create directory {}: {}",
381                    parent.display(),
382                    e
383                ))
384            })?;
385        }
386
387        // Write the file
388        tokio::fs::write(path, content).await.map_err(|e| {
389            PluginError::ConfigurationError(format!(
390                "Failed to write configuration to {}: {}",
391                path.display(),
392                e
393            ))
394        })
395    }
396
397    /// Get the validator
398    pub fn validator(&self) -> &ConfigValidator {
399        &self.validator
400    }
401
402    /// Get a mutable reference to the validator
403    pub fn validator_mut(&mut self) -> &mut ConfigValidator {
404        &mut self.validator
405    }
406}
407
408impl Default for ConfigLoader {
409    fn default() -> Self {
410        Self::new()
411    }
412}
413
414#[cfg(test)]
415mod tests {
416    use super::*;
417    use tempfile::TempDir;
418
419    #[tokio::test]
420    async fn test_load_from_json_string() {
421        let loader = ConfigLoader::new();
422        let json_config = r#"
423        {
424            "system": {
425                "max_parallel_plugins": 8,
426                "debug": true
427            },
428            "plugins": {
429                "test-plugin": {
430                    "enabled": true,
431                    "priority": 10
432                }
433            }
434        }
435        "#;
436
437        let config = loader
438            .load(ConfigSource::Json(json_config.to_string()))
439            .await
440            .unwrap();
441        assert_eq!(config.system.max_parallel_plugins, 8);
442        assert!(config.system.debug);
443        assert!(config.plugins.contains_key("test-plugin"));
444    }
445
446    #[tokio::test]
447    async fn test_load_from_toml_string() {
448        let loader = ConfigLoader::new();
449        let toml_config = r#"
450        [system]
451        max_parallel_plugins = 6
452        debug = false
453
454        [plugins.test-plugin]
455        enabled = true
456        priority = 5
457        "#;
458
459        let config = loader
460            .load(ConfigSource::Toml(toml_config.to_string()))
461            .await
462            .unwrap();
463        assert_eq!(config.system.max_parallel_plugins, 6);
464        assert!(!config.system.debug);
465        assert!(config.plugins.contains_key("test-plugin"));
466    }
467
468    #[tokio::test]
469    async fn test_load_from_yaml_string() {
470        let loader = ConfigLoader::new();
471        let yaml_config = r#"
472        system:
473          max_parallel_plugins: 12
474          debug: true
475        plugins:
476          test-plugin:
477            enabled: true
478            priority: 15
479        "#;
480
481        let config = loader
482            .load(ConfigSource::Yaml(yaml_config.to_string()))
483            .await
484            .unwrap();
485        assert_eq!(config.system.max_parallel_plugins, 12);
486        assert!(config.system.debug);
487        assert!(config.plugins.contains_key("test-plugin"));
488    }
489
490    #[tokio::test]
491    async fn test_load_from_environment() {
492        let loader = ConfigLoader::new();
493
494        // Set environment variables
495        std::env::set_var("TEST_MAX_PARALLEL_PLUGINS", "16");
496        std::env::set_var("TEST_DEBUG", "true");
497        std::env::set_var("TEST_ENABLE_SANDBOX", "false");
498
499        let config = loader
500            .load(ConfigSource::Environment {
501                prefix: "TEST".to_string(),
502            })
503            .await
504            .unwrap();
505
506        assert_eq!(config.system.max_parallel_plugins, 16);
507        assert!(config.system.debug);
508        assert!(!config.system.enable_sandbox);
509
510        // Clean up environment variables
511        std::env::remove_var("TEST_MAX_PARALLEL_PLUGINS");
512        std::env::remove_var("TEST_DEBUG");
513        std::env::remove_var("TEST_ENABLE_SANDBOX");
514    }
515
516    #[tokio::test]
517    async fn test_load_from_file() {
518        let temp_dir = TempDir::new().unwrap();
519        let config_path = temp_dir.path().join("test_config.json");
520
521        let json_config = serde_json::json!({
522            "system": {
523                "max_parallel_plugins": 20,
524                "debug": true
525            },
526            "plugins": {
527                "file-plugin": {
528                    "enabled": true,
529                    "priority": 100
530                }
531            }
532        });
533
534        // Write config file
535        tokio::fs::write(
536            &config_path,
537            serde_json::to_string_pretty(&json_config).unwrap(),
538        )
539        .await
540        .unwrap();
541
542        let loader = ConfigLoader::new();
543        let config = loader.load(ConfigSource::File(config_path)).await.unwrap();
544
545        assert_eq!(config.system.max_parallel_plugins, 20);
546        assert!(config.system.debug);
547        assert!(config.plugins.contains_key("file-plugin"));
548    }
549
550    #[tokio::test]
551    async fn test_config_merging() {
552        let loader = ConfigLoader::new();
553
554        let sources = vec![
555            ConfigSource::Json(
556                r#"
557            {
558                "system": { "max_parallel_plugins": 4 },
559                "plugins": { "plugin-a": { "enabled": true } }
560            }
561            "#
562                .to_string(),
563            ),
564            ConfigSource::Json(
565                r#"
566            {
567                "system": { "debug": true },
568                "plugins": { "plugin-b": { "enabled": false } }
569            }
570            "#
571                .to_string(),
572            ),
573        ];
574
575        let config = loader.load(ConfigSource::Multiple(sources)).await.unwrap();
576
577        assert_eq!(config.system.max_parallel_plugins, 4);
578        assert!(config.system.debug);
579        assert!(config.plugins.contains_key("plugin-a"));
580        assert!(config.plugins.contains_key("plugin-b"));
581    }
582
583    #[tokio::test]
584    async fn test_save_configuration() {
585        let temp_dir = TempDir::new().unwrap();
586        let config_path = temp_dir.path().join("saved_config.json");
587
588        let mut config = PluginSystemConfig::default();
589        config.system.max_parallel_plugins = 42;
590        config.system.debug = true;
591
592        let loader = ConfigLoader::new();
593        loader.save(&config, &config_path).await.unwrap();
594
595        // Load it back and verify
596        let loaded_config = loader.load(ConfigSource::File(config_path)).await.unwrap();
597        assert_eq!(loaded_config.system.max_parallel_plugins, 42);
598        assert!(loaded_config.system.debug);
599    }
600
601    #[tokio::test]
602    async fn test_load_options() {
603        let loader = ConfigLoader::with_options(LoadOptions {
604            validate: false,
605            use_defaults: false,
606            allow_missing: true,
607            expand_env_vars: false,
608        });
609
610        let non_existent_path = PathBuf::from("/non/existent/config.json");
611        let config = loader
612            .load(ConfigSource::File(non_existent_path))
613            .await
614            .unwrap();
615
616        // Should get minimal config when use_defaults is false and file is missing
617        assert_eq!(config.system.max_parallel_plugins, 1); // Minimal default
618    }
619}