Skip to main content

mockforge_core/config/
mod.rs

1//! Configuration management for MockForge
2
3mod auth;
4mod contracts;
5mod operational;
6mod protocol;
7mod routes;
8
9pub use auth::*;
10pub use contracts::*;
11pub use operational::*;
12pub use protocol::*;
13pub use routes::*;
14
15use crate::{Config as CoreConfig, Error, RealityLevel, Result};
16use serde::{Deserialize, Serialize};
17use std::collections::HashMap;
18use std::path::Path;
19use tokio::fs;
20
21/// Reality slider configuration for YAML config files
22///
23/// This is a simplified configuration that stores just the level.
24/// The full RealityConfig with all subsystem settings is generated
25/// automatically from the level via the RealityEngine.
26#[derive(Debug, Clone, Serialize, Deserialize)]
27#[serde(default)]
28#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
29pub struct RealitySliderConfig {
30    /// Reality level (1-5)
31    pub level: RealityLevel,
32    /// Whether to enable reality slider (if false, uses individual subsystem configs)
33    pub enabled: bool,
34}
35
36impl Default for RealitySliderConfig {
37    fn default() -> Self {
38        Self {
39            level: RealityLevel::ModerateRealism,
40            enabled: true,
41        }
42    }
43}
44
45/// Server configuration
46#[derive(Debug, Clone, Serialize, Deserialize, Default)]
47#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
48#[serde(default)]
49pub struct ServerConfig {
50    /// HTTP server configuration
51    pub http: HttpConfig,
52    /// WebSocket server configuration
53    pub websocket: WebSocketConfig,
54    /// GraphQL server configuration
55    pub graphql: GraphQLConfig,
56    /// gRPC server configuration
57    pub grpc: GrpcConfig,
58    /// MQTT server configuration
59    pub mqtt: MqttConfig,
60    /// SMTP server configuration
61    pub smtp: SmtpConfig,
62    /// FTP server configuration
63    pub ftp: FtpConfig,
64    /// Kafka server configuration
65    pub kafka: KafkaConfig,
66    /// AMQP server configuration
67    pub amqp: AmqpConfig,
68    /// TCP server configuration
69    pub tcp: TcpConfig,
70    /// Admin UI configuration
71    pub admin: AdminConfig,
72    /// Request chaining configuration
73    pub chaining: ChainingConfig,
74    /// Core MockForge configuration
75    pub core: CoreConfig,
76    /// Logging configuration
77    pub logging: LoggingConfig,
78    /// Data generation configuration
79    pub data: DataConfig,
80    /// MockAI (Behavioral Mock Intelligence) configuration
81    #[serde(default)]
82    pub mockai: MockAIConfig,
83    /// Observability configuration (metrics, tracing)
84    pub observability: ObservabilityConfig,
85    /// Multi-tenant workspace configuration
86    pub multi_tenant: crate::multi_tenant::MultiTenantConfig,
87    /// Custom routes configuration
88    #[serde(default)]
89    pub routes: Vec<RouteConfig>,
90    /// Protocol enable/disable configuration
91    #[serde(default)]
92    pub protocols: ProtocolsConfig,
93    /// Named configuration profiles (dev, ci, demo, etc.)
94    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
95    pub profiles: HashMap<String, ProfileConfig>,
96    /// Deceptive deploy configuration for production-like mock APIs
97    #[serde(default)]
98    pub deceptive_deploy: DeceptiveDeployConfig,
99    /// Behavioral cloning configuration
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub behavioral_cloning: Option<BehavioralCloningConfig>,
102    /// Reality slider configuration for unified realism control
103    #[serde(default)]
104    pub reality: RealitySliderConfig,
105    /// Reality Continuum configuration for blending mock and real data sources
106    #[serde(default)]
107    pub reality_continuum: crate::reality_continuum::ContinuumConfig,
108    /// Security monitoring and SIEM configuration
109    #[serde(default)]
110    pub security: SecurityConfig,
111    /// Drift budget and contract monitoring configuration
112    #[serde(default)]
113    pub drift_budget: crate::contract_drift::DriftBudgetConfig,
114    /// Incident management configuration
115    #[serde(default)]
116    pub incidents: IncidentConfig,
117    /// PR generation configuration
118    #[serde(default)]
119    pub pr_generation: crate::pr_generation::PRGenerationConfig,
120    /// Consumer contracts configuration
121    #[serde(default)]
122    pub consumer_contracts: ConsumerContractsConfig,
123    /// Contracts configuration (fitness rules, etc.)
124    #[serde(default)]
125    pub contracts: ContractsConfig,
126    /// Behavioral Economics Engine configuration
127    #[serde(default)]
128    pub behavioral_economics: BehavioralEconomicsConfig,
129    /// Drift Learning configuration
130    #[serde(default)]
131    pub drift_learning: DriftLearningConfig,
132    /// Organization AI controls configuration (YAML defaults, DB overrides)
133    #[serde(default)]
134    pub org_ai_controls: crate::ai_studio::org_controls::OrgAiControlsConfig,
135    /// Performance and resource configuration
136    #[serde(default)]
137    pub performance: PerformanceConfig,
138    /// Plugin resource limits configuration
139    #[serde(default)]
140    pub plugins: PluginResourceConfig,
141    /// Configuration hot-reload settings
142    #[serde(default)]
143    pub hot_reload: ConfigHotReloadConfig,
144    /// Secret backend configuration
145    #[serde(default)]
146    pub secrets: SecretBackendConfig,
147}
148
149/// Profile configuration - a partial ServerConfig that overrides base settings
150#[derive(Debug, Clone, Serialize, Deserialize, Default)]
151#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
152#[serde(default)]
153pub struct ProfileConfig {
154    /// HTTP server configuration overrides
155    #[serde(skip_serializing_if = "Option::is_none")]
156    pub http: Option<HttpConfig>,
157    /// WebSocket server configuration overrides
158    #[serde(skip_serializing_if = "Option::is_none")]
159    pub websocket: Option<WebSocketConfig>,
160    /// GraphQL server configuration overrides
161    #[serde(skip_serializing_if = "Option::is_none")]
162    pub graphql: Option<GraphQLConfig>,
163    /// gRPC server configuration overrides
164    #[serde(skip_serializing_if = "Option::is_none")]
165    pub grpc: Option<GrpcConfig>,
166    /// MQTT server configuration overrides
167    #[serde(skip_serializing_if = "Option::is_none")]
168    pub mqtt: Option<MqttConfig>,
169    /// SMTP server configuration overrides
170    #[serde(skip_serializing_if = "Option::is_none")]
171    pub smtp: Option<SmtpConfig>,
172    /// FTP server configuration overrides
173    #[serde(skip_serializing_if = "Option::is_none")]
174    pub ftp: Option<FtpConfig>,
175    /// Kafka server configuration overrides
176    #[serde(skip_serializing_if = "Option::is_none")]
177    pub kafka: Option<KafkaConfig>,
178    /// AMQP server configuration overrides
179    #[serde(skip_serializing_if = "Option::is_none")]
180    pub amqp: Option<AmqpConfig>,
181    /// TCP server configuration overrides
182    #[serde(skip_serializing_if = "Option::is_none")]
183    pub tcp: Option<TcpConfig>,
184    /// Admin UI configuration overrides
185    #[serde(skip_serializing_if = "Option::is_none")]
186    pub admin: Option<AdminConfig>,
187    /// Request chaining configuration overrides
188    #[serde(skip_serializing_if = "Option::is_none")]
189    pub chaining: Option<ChainingConfig>,
190    /// Core MockForge configuration overrides
191    #[serde(skip_serializing_if = "Option::is_none")]
192    pub core: Option<CoreConfig>,
193    /// Logging configuration overrides
194    #[serde(skip_serializing_if = "Option::is_none")]
195    pub logging: Option<LoggingConfig>,
196    /// Data generation configuration overrides
197    #[serde(skip_serializing_if = "Option::is_none")]
198    pub data: Option<DataConfig>,
199    /// MockAI configuration overrides
200    #[serde(skip_serializing_if = "Option::is_none")]
201    pub mockai: Option<MockAIConfig>,
202    /// Observability configuration overrides
203    #[serde(skip_serializing_if = "Option::is_none")]
204    pub observability: Option<ObservabilityConfig>,
205    /// Multi-tenant workspace configuration overrides
206    #[serde(skip_serializing_if = "Option::is_none")]
207    pub multi_tenant: Option<crate::multi_tenant::MultiTenantConfig>,
208    /// Custom routes configuration overrides
209    #[serde(skip_serializing_if = "Option::is_none")]
210    pub routes: Option<Vec<RouteConfig>>,
211    /// Protocol enable/disable configuration overrides
212    #[serde(skip_serializing_if = "Option::is_none")]
213    pub protocols: Option<ProtocolsConfig>,
214    /// Deceptive deploy configuration overrides
215    #[serde(skip_serializing_if = "Option::is_none")]
216    pub deceptive_deploy: Option<DeceptiveDeployConfig>,
217    /// Reality slider configuration overrides
218    #[serde(skip_serializing_if = "Option::is_none")]
219    pub reality: Option<RealitySliderConfig>,
220    /// Reality Continuum configuration overrides
221    #[serde(skip_serializing_if = "Option::is_none")]
222    pub reality_continuum: Option<crate::reality_continuum::ContinuumConfig>,
223    /// Security configuration overrides
224    #[serde(skip_serializing_if = "Option::is_none")]
225    pub security: Option<SecurityConfig>,
226}
227
228impl ServerConfig {
229    /// Create a minimal configuration with all defaults.
230    pub fn minimal() -> Self {
231        Self::default()
232    }
233
234    /// Create a development-friendly configuration with admin UI enabled and
235    /// debug-level logging.
236    pub fn development() -> Self {
237        let mut cfg = Self::default();
238        cfg.admin.enabled = true;
239        cfg.logging.level = "debug".to_string();
240        cfg
241    }
242
243    /// Create a CI-oriented configuration with latency and failure injection
244    /// disabled for deterministic test runs.
245    pub fn ci() -> Self {
246        let mut cfg = Self::default();
247        cfg.core.latency_enabled = false;
248        cfg.core.failures_enabled = false;
249        cfg
250    }
251
252    /// Builder: set the HTTP port.
253    #[must_use]
254    pub fn with_http_port(mut self, port: u16) -> Self {
255        self.http.port = port;
256        self
257    }
258
259    /// Builder: enable the admin UI on the given port.
260    #[must_use]
261    pub fn with_admin(mut self, port: u16) -> Self {
262        self.admin.enabled = true;
263        self.admin.port = port;
264        self
265    }
266
267    /// Builder: enable gRPC on the given port.
268    #[must_use]
269    pub fn with_grpc(mut self, port: u16) -> Self {
270        self.grpc.enabled = true;
271        self.grpc.port = port;
272        self.protocols.grpc.enabled = true;
273        self
274    }
275
276    /// Builder: enable WebSocket on the given port.
277    #[must_use]
278    pub fn with_websocket(mut self, port: u16) -> Self {
279        self.websocket.enabled = true;
280        self.websocket.port = port;
281        self.protocols.websocket.enabled = true;
282        self
283    }
284
285    /// Builder: set the log level.
286    #[must_use]
287    pub fn with_log_level(mut self, level: &str) -> Self {
288        self.logging.level = level.to_string();
289        self
290    }
291
292    /// Check whether any advanced features (MockAI, behavioral cloning,
293    /// reality continuum) are enabled.
294    pub fn has_advanced_features(&self) -> bool {
295        self.mockai.enabled
296            || self.behavioral_cloning.as_ref().is_some_and(|bc| bc.enabled)
297            || self.reality_continuum.enabled
298    }
299
300    /// Check whether any enterprise features (multi-tenant, federation,
301    /// security monitoring) are enabled.
302    pub fn has_enterprise_features(&self) -> bool {
303        self.multi_tenant.enabled || self.security.monitoring.siem.enabled
304    }
305}
306
307/// Load configuration from file
308pub async fn load_config<P: AsRef<Path>>(path: P) -> Result<ServerConfig> {
309    let content = fs::read_to_string(&path)
310        .await
311        .map_err(|e| Error::io_with_context("reading config file", e.to_string()))?;
312
313    // Parse config with improved error messages
314    let config: ServerConfig = if path.as_ref().extension().and_then(|s| s.to_str()) == Some("yaml")
315        || path.as_ref().extension().and_then(|s| s.to_str()) == Some("yml")
316    {
317        serde_yaml::from_str(&content).map_err(|e| {
318            // Improve error message with field path context
319            let error_msg = e.to_string();
320            let mut full_msg = format!("Failed to parse YAML config: {}", error_msg);
321
322            // Add helpful context for common errors
323            if error_msg.contains("missing field") {
324                full_msg.push_str(
325                    "\n\n\u{1f4a1} Most configuration fields are optional with defaults.",
326                );
327                full_msg.push_str(
328                    "\n   Omit fields you don't need - MockForge will use sensible defaults.",
329                );
330                full_msg.push_str("\n   See config.template.yaml for all available options.");
331            } else if error_msg.contains("unknown field") {
332                full_msg.push_str("\n\n\u{1f4a1} Check for typos in field names.");
333                full_msg.push_str("\n   See config.template.yaml for valid field names.");
334            }
335
336            Error::config(full_msg)
337        })?
338    } else {
339        serde_json::from_str(&content).map_err(|e| {
340            // Improve error message with field path context
341            let error_msg = e.to_string();
342            let mut full_msg = format!("Failed to parse JSON config: {}", error_msg);
343
344            // Add helpful context for common errors
345            if error_msg.contains("missing field") {
346                full_msg.push_str(
347                    "\n\n\u{1f4a1} Most configuration fields are optional with defaults.",
348                );
349                full_msg.push_str(
350                    "\n   Omit fields you don't need - MockForge will use sensible defaults.",
351                );
352                full_msg.push_str("\n   See config.template.yaml for all available options.");
353            } else if error_msg.contains("unknown field") {
354                full_msg.push_str("\n\n\u{1f4a1} Check for typos in field names.");
355                full_msg.push_str("\n   See config.template.yaml for valid field names.");
356            }
357
358            Error::config(full_msg)
359        })?
360    };
361
362    Ok(config)
363}
364
365/// Save configuration to file
366pub async fn save_config<P: AsRef<Path>>(path: P, config: &ServerConfig) -> Result<()> {
367    let content = if path.as_ref().extension().and_then(|s| s.to_str()) == Some("yaml")
368        || path.as_ref().extension().and_then(|s| s.to_str()) == Some("yml")
369    {
370        serde_yaml::to_string(config)
371            .map_err(|e| Error::config(format!("Failed to serialize config to YAML: {}", e)))?
372    } else {
373        serde_json::to_string_pretty(config)
374            .map_err(|e| Error::config(format!("Failed to serialize config to JSON: {}", e)))?
375    };
376
377    fs::write(path, content)
378        .await
379        .map_err(|e| Error::io_with_context("writing config file", e.to_string()))?;
380
381    Ok(())
382}
383
384/// Load configuration with fallback to default
385pub async fn load_config_with_fallback<P: AsRef<Path>>(path: P) -> ServerConfig {
386    match load_config(&path).await {
387        Ok(config) => {
388            tracing::info!("Loaded configuration from {:?}", path.as_ref());
389            config
390        }
391        Err(e) => {
392            tracing::warn!(
393                "Failed to load config from {:?}: {}. Using defaults.",
394                path.as_ref(),
395                e
396            );
397            ServerConfig::default()
398        }
399    }
400}
401
402/// Create default configuration file
403pub async fn create_default_config<P: AsRef<Path>>(path: P) -> Result<()> {
404    let config = ServerConfig::default();
405    save_config(path, &config).await?;
406    Ok(())
407}
408
409/// Environment variable overrides for configuration
410pub fn apply_env_overrides(mut config: ServerConfig) -> ServerConfig {
411    // HTTP server overrides
412    if let Ok(port) = std::env::var("MOCKFORGE_HTTP_PORT") {
413        if let Ok(port_num) = port.parse() {
414            config.http.port = port_num;
415        }
416    }
417
418    if let Ok(host) = std::env::var("MOCKFORGE_HTTP_HOST") {
419        config.http.host = host;
420    }
421
422    // WebSocket server overrides
423    if let Ok(port) = std::env::var("MOCKFORGE_WS_PORT") {
424        if let Ok(port_num) = port.parse() {
425            config.websocket.port = port_num;
426        }
427    }
428
429    // gRPC server overrides
430    if let Ok(port) = std::env::var("MOCKFORGE_GRPC_PORT") {
431        if let Ok(port_num) = port.parse() {
432            config.grpc.port = port_num;
433        }
434    }
435
436    // SMTP server overrides
437    if let Ok(port) = std::env::var("MOCKFORGE_SMTP_PORT") {
438        if let Ok(port_num) = port.parse() {
439            config.smtp.port = port_num;
440        }
441    }
442
443    if let Ok(host) = std::env::var("MOCKFORGE_SMTP_HOST") {
444        config.smtp.host = host;
445    }
446
447    if let Ok(enabled) = std::env::var("MOCKFORGE_SMTP_ENABLED") {
448        config.smtp.enabled = enabled == "1" || enabled.eq_ignore_ascii_case("true");
449    }
450
451    if let Ok(hostname) = std::env::var("MOCKFORGE_SMTP_HOSTNAME") {
452        config.smtp.hostname = hostname;
453    }
454
455    // TCP server overrides
456    if let Ok(port) = std::env::var("MOCKFORGE_TCP_PORT") {
457        if let Ok(port_num) = port.parse() {
458            config.tcp.port = port_num;
459        }
460    }
461
462    if let Ok(host) = std::env::var("MOCKFORGE_TCP_HOST") {
463        config.tcp.host = host;
464    }
465
466    if let Ok(enabled) = std::env::var("MOCKFORGE_TCP_ENABLED") {
467        config.tcp.enabled = enabled == "1" || enabled.eq_ignore_ascii_case("true");
468    }
469
470    // Admin UI overrides
471    if let Ok(port) = std::env::var("MOCKFORGE_ADMIN_PORT") {
472        if let Ok(port_num) = port.parse() {
473            config.admin.port = port_num;
474        }
475    }
476
477    if std::env::var("MOCKFORGE_ADMIN_ENABLED").unwrap_or_default() == "true" {
478        config.admin.enabled = true;
479    }
480
481    // Admin UI host override - critical for Docker deployments
482    if let Ok(host) = std::env::var("MOCKFORGE_ADMIN_HOST") {
483        config.admin.host = host;
484    }
485
486    if let Ok(mount_path) = std::env::var("MOCKFORGE_ADMIN_MOUNT_PATH") {
487        if !mount_path.trim().is_empty() {
488            config.admin.mount_path = Some(mount_path);
489        }
490    }
491
492    if let Ok(api_enabled) = std::env::var("MOCKFORGE_ADMIN_API_ENABLED") {
493        let on = api_enabled == "1" || api_enabled.eq_ignore_ascii_case("true");
494        config.admin.api_enabled = on;
495    }
496
497    if let Ok(prometheus_url) = std::env::var("PROMETHEUS_URL") {
498        config.admin.prometheus_url = prometheus_url;
499    }
500
501    // Core configuration overrides
502    if let Ok(latency_enabled) = std::env::var("MOCKFORGE_LATENCY_ENABLED") {
503        let enabled = latency_enabled == "1" || latency_enabled.eq_ignore_ascii_case("true");
504        config.core.latency_enabled = enabled;
505    }
506
507    if let Ok(failures_enabled) = std::env::var("MOCKFORGE_FAILURES_ENABLED") {
508        let enabled = failures_enabled == "1" || failures_enabled.eq_ignore_ascii_case("true");
509        config.core.failures_enabled = enabled;
510    }
511
512    if let Ok(overrides_enabled) = std::env::var("MOCKFORGE_OVERRIDES_ENABLED") {
513        let enabled = overrides_enabled == "1" || overrides_enabled.eq_ignore_ascii_case("true");
514        config.core.overrides_enabled = enabled;
515    }
516
517    if let Ok(traffic_shaping_enabled) = std::env::var("MOCKFORGE_TRAFFIC_SHAPING_ENABLED") {
518        let enabled =
519            traffic_shaping_enabled == "1" || traffic_shaping_enabled.eq_ignore_ascii_case("true");
520        config.core.traffic_shaping_enabled = enabled;
521    }
522
523    // Traffic shaping overrides
524    if let Ok(bandwidth_enabled) = std::env::var("MOCKFORGE_BANDWIDTH_ENABLED") {
525        let enabled = bandwidth_enabled == "1" || bandwidth_enabled.eq_ignore_ascii_case("true");
526        config.core.traffic_shaping.bandwidth.enabled = enabled;
527    }
528
529    if let Ok(max_bytes_per_sec) = std::env::var("MOCKFORGE_BANDWIDTH_MAX_BYTES_PER_SEC") {
530        if let Ok(bytes) = max_bytes_per_sec.parse() {
531            config.core.traffic_shaping.bandwidth.max_bytes_per_sec = bytes;
532            config.core.traffic_shaping.bandwidth.enabled = true;
533        }
534    }
535
536    if let Ok(burst_capacity) = std::env::var("MOCKFORGE_BANDWIDTH_BURST_CAPACITY_BYTES") {
537        if let Ok(bytes) = burst_capacity.parse() {
538            config.core.traffic_shaping.bandwidth.burst_capacity_bytes = bytes;
539        }
540    }
541
542    if let Ok(burst_loss_enabled) = std::env::var("MOCKFORGE_BURST_LOSS_ENABLED") {
543        let enabled = burst_loss_enabled == "1" || burst_loss_enabled.eq_ignore_ascii_case("true");
544        config.core.traffic_shaping.burst_loss.enabled = enabled;
545    }
546
547    if let Ok(burst_probability) = std::env::var("MOCKFORGE_BURST_LOSS_PROBABILITY") {
548        if let Ok(prob) = burst_probability.parse::<f64>() {
549            config.core.traffic_shaping.burst_loss.burst_probability = prob.clamp(0.0, 1.0);
550            config.core.traffic_shaping.burst_loss.enabled = true;
551        }
552    }
553
554    if let Ok(burst_duration) = std::env::var("MOCKFORGE_BURST_LOSS_DURATION_MS") {
555        if let Ok(ms) = burst_duration.parse() {
556            config.core.traffic_shaping.burst_loss.burst_duration_ms = ms;
557        }
558    }
559
560    if let Ok(loss_rate) = std::env::var("MOCKFORGE_BURST_LOSS_RATE") {
561        if let Ok(rate) = loss_rate.parse::<f64>() {
562            config.core.traffic_shaping.burst_loss.loss_rate_during_burst = rate.clamp(0.0, 1.0);
563        }
564    }
565
566    if let Ok(recovery_time) = std::env::var("MOCKFORGE_BURST_LOSS_RECOVERY_MS") {
567        if let Ok(ms) = recovery_time.parse() {
568            config.core.traffic_shaping.burst_loss.recovery_time_ms = ms;
569        }
570    }
571
572    // Logging overrides
573    if let Ok(level) = std::env::var("MOCKFORGE_LOG_LEVEL") {
574        config.logging.level = level;
575    }
576
577    config
578}
579
580/// Validate configuration
581pub fn validate_config(config: &ServerConfig) -> Result<()> {
582    // Validate port ranges
583    if config.http.port == 0 {
584        return Err(Error::config("HTTP port cannot be 0"));
585    }
586    if config.websocket.port == 0 {
587        return Err(Error::config("WebSocket port cannot be 0"));
588    }
589    if config.grpc.port == 0 {
590        return Err(Error::config("gRPC port cannot be 0"));
591    }
592    if config.admin.port == 0 {
593        return Err(Error::config("Admin port cannot be 0"));
594    }
595
596    // Check for port conflicts
597    let ports = [
598        ("HTTP", config.http.port),
599        ("WebSocket", config.websocket.port),
600        ("gRPC", config.grpc.port),
601        ("Admin", config.admin.port),
602    ];
603
604    for i in 0..ports.len() {
605        for j in (i + 1)..ports.len() {
606            if ports[i].1 == ports[j].1 {
607                return Err(Error::config(format!(
608                    "Port conflict: {} and {} both use port {}",
609                    ports[i].0, ports[j].0, ports[i].1
610                )));
611            }
612        }
613    }
614
615    // Validate log level
616    let valid_levels = ["trace", "debug", "info", "warn", "error"];
617    if !valid_levels.contains(&config.logging.level.as_str()) {
618        return Err(Error::config(format!(
619            "Invalid log level: {}. Valid levels: {}",
620            config.logging.level,
621            valid_levels.join(", ")
622        )));
623    }
624
625    Ok(())
626}
627
628/// Apply a profile to a base configuration
629pub fn apply_profile(mut base: ServerConfig, profile: ProfileConfig) -> ServerConfig {
630    // Macro to merge optional fields
631    macro_rules! merge_field {
632        ($field:ident) => {
633            if let Some(override_val) = profile.$field {
634                base.$field = override_val;
635            }
636        };
637    }
638
639    merge_field!(http);
640    merge_field!(websocket);
641    merge_field!(graphql);
642    merge_field!(grpc);
643    merge_field!(mqtt);
644    merge_field!(smtp);
645    merge_field!(ftp);
646    merge_field!(kafka);
647    merge_field!(amqp);
648    merge_field!(tcp);
649    merge_field!(admin);
650    merge_field!(chaining);
651    merge_field!(core);
652    merge_field!(logging);
653    merge_field!(data);
654    merge_field!(mockai);
655    merge_field!(observability);
656    merge_field!(multi_tenant);
657    merge_field!(routes);
658    merge_field!(protocols);
659
660    base
661}
662
663/// Load configuration with profile support
664pub async fn load_config_with_profile<P: AsRef<Path>>(
665    path: P,
666    profile_name: Option<&str>,
667) -> Result<ServerConfig> {
668    // Use load_config_auto to support all formats
669    let mut config = load_config_auto(&path).await?;
670
671    // Apply profile if specified
672    if let Some(profile) = profile_name {
673        if let Some(profile_config) = config.profiles.remove(profile) {
674            tracing::info!("Applying profile: {}", profile);
675            config = apply_profile(config, profile_config);
676        } else {
677            return Err(Error::config(format!(
678                "Profile '{}' not found in configuration. Available profiles: {}",
679                profile,
680                config.profiles.keys().map(|k| k.as_str()).collect::<Vec<_>>().join(", ")
681            )));
682        }
683    }
684
685    // Clear profiles from final config to save memory
686    config.profiles.clear();
687
688    Ok(config)
689}
690
691/// Load configuration from TypeScript/JavaScript file
692#[cfg(feature = "scripting")]
693pub async fn load_config_from_js<P: AsRef<Path>>(path: P) -> Result<ServerConfig> {
694    use rquickjs::{Context, Runtime};
695
696    let content = fs::read_to_string(&path)
697        .await
698        .map_err(|e| Error::io_with_context("reading JS/TS config file", e.to_string()))?;
699
700    // Create a JavaScript runtime
701    let runtime =
702        Runtime::new().map_err(|e| Error::config(format!("Failed to create JS runtime: {}", e)))?;
703    let context = Context::full(&runtime)
704        .map_err(|e| Error::config(format!("Failed to create JS context: {}", e)))?;
705
706    context.with(|ctx| {
707        // For TypeScript files, we need to strip type annotations
708        // This is a simple approach - for production, consider using a proper TS compiler
709        let js_content = if path
710            .as_ref()
711            .extension()
712            .and_then(|s| s.to_str())
713            .map(|ext| ext == "ts")
714            .unwrap_or(false)
715        {
716            strip_typescript_types(&content)?
717        } else {
718            content
719        };
720
721        // Evaluate the config file — uses rquickjs sandboxed JS runtime (not arbitrary code execution)
722        let result: rquickjs::Value = ctx
723            .eval(js_content.as_bytes())
724            .map_err(|e| Error::config(format!("Failed to evaluate JS config: {}", e)))?;
725
726        // Convert to JSON string
727        let json_str: String = ctx
728            .json_stringify(result)
729            .map_err(|e| Error::config(format!("Failed to stringify JS config: {}", e)))?
730            .ok_or_else(|| Error::config("JS config returned undefined"))?
731            .get()
732            .map_err(|e| Error::config(format!("Failed to get JSON string: {}", e)))?;
733
734        // Parse JSON into ServerConfig
735        serde_json::from_str(&json_str)
736            .map_err(|e| Error::config(format!("Failed to parse JS config as ServerConfig: {}", e)))
737    })
738}
739
740/// Simple TypeScript type stripper (removes type annotations)
741/// Note: This is a basic implementation. For production use, consider using swc or esbuild
742///
743/// # Errors
744/// Returns an error if regex compilation fails. This should never happen with static patterns,
745/// but we handle it gracefully to prevent panics.
746#[cfg(feature = "scripting")]
747fn strip_typescript_types(content: &str) -> Result<String> {
748    use regex::Regex;
749
750    let mut result = content.to_string();
751
752    // Compile regex patterns with error handling
753    // Note: These patterns are statically known and should never fail,
754    // but we handle errors to prevent panics in edge cases
755
756    // Remove interface declarations (handles multi-line)
757    let interface_re = Regex::new(r"(?ms)interface\s+\w+\s*\{[^}]*\}\s*")
758        .map_err(|e| Error::config(format!("Failed to compile interface regex: {}", e)))?;
759    result = interface_re.replace_all(&result, "").to_string();
760
761    // Remove type aliases
762    let type_alias_re = Regex::new(r"(?m)^type\s+\w+\s*=\s*[^;]+;\s*")
763        .map_err(|e| Error::config(format!("Failed to compile type alias regex: {}", e)))?;
764    result = type_alias_re.replace_all(&result, "").to_string();
765
766    // Remove type annotations (: Type)
767    let type_annotation_re = Regex::new(r":\s*[A-Z]\w*(<[^>]+>)?(\[\])?")
768        .map_err(|e| Error::config(format!("Failed to compile type annotation regex: {}", e)))?;
769    result = type_annotation_re.replace_all(&result, "").to_string();
770
771    // Remove type imports and exports
772    let type_import_re = Regex::new(r"(?m)^(import|export)\s+type\s+.*$")
773        .map_err(|e| Error::config(format!("Failed to compile type import regex: {}", e)))?;
774    result = type_import_re.replace_all(&result, "").to_string();
775
776    // Remove as Type
777    let as_type_re = Regex::new(r"\s+as\s+\w+")
778        .map_err(|e| Error::config(format!("Failed to compile 'as type' regex: {}", e)))?;
779    result = as_type_re.replace_all(&result, "").to_string();
780
781    Ok(result)
782}
783
784/// Enhanced load_config that supports multiple formats including JS/TS
785pub async fn load_config_auto<P: AsRef<Path>>(path: P) -> Result<ServerConfig> {
786    let ext = path.as_ref().extension().and_then(|s| s.to_str()).unwrap_or("");
787
788    match ext {
789        #[cfg(feature = "scripting")]
790        "ts" | "js" => load_config_from_js(&path).await,
791        #[cfg(not(feature = "scripting"))]
792        "ts" | "js" => Err(Error::config(
793            "JS/TS config files require the 'scripting' feature (rquickjs). \
794             Enable it with: cargo build --features scripting"
795                .to_string(),
796        )),
797        "yaml" | "yml" | "json" => load_config(&path).await,
798        _ => Err(Error::config(format!(
799            "Unsupported config file format: {}. Supported: .yaml, .yml, .json{}",
800            ext,
801            if cfg!(feature = "scripting") {
802                ", .ts, .js"
803            } else {
804                ""
805            }
806        ))),
807    }
808}
809
810/// Discover configuration file with support for all formats
811pub async fn discover_config_file_all_formats() -> Result<std::path::PathBuf> {
812    let current_dir = std::env::current_dir()
813        .map_err(|e| Error::config(format!("Failed to get current directory: {}", e)))?;
814
815    let config_names = vec![
816        "mockforge.config.ts",
817        "mockforge.config.js",
818        "mockforge.yaml",
819        "mockforge.yml",
820        ".mockforge.yaml",
821        ".mockforge.yml",
822    ];
823
824    // Check current directory
825    for name in &config_names {
826        let path = current_dir.join(name);
827        if fs::metadata(&path).await.is_ok() {
828            return Ok(path);
829        }
830    }
831
832    // Check parent directories (up to 5 levels)
833    let mut dir = current_dir.clone();
834    for _ in 0..5 {
835        if let Some(parent) = dir.parent() {
836            for name in &config_names {
837                let path = parent.join(name);
838                if fs::metadata(&path).await.is_ok() {
839                    return Ok(path);
840                }
841            }
842            dir = parent.to_path_buf();
843        } else {
844            break;
845        }
846    }
847
848    Err(Error::config(
849        "No configuration file found. Expected one of: mockforge.config.ts, mockforge.config.js, mockforge.yaml, mockforge.yml",
850    ))
851}
852
853#[cfg(test)]
854mod tests {
855    use super::*;
856
857    #[test]
858    fn test_default_config() {
859        let config = ServerConfig::default();
860        assert_eq!(config.http.port, 3000);
861        assert_eq!(config.websocket.port, 3001);
862        assert_eq!(config.grpc.port, 50051);
863        assert_eq!(config.admin.port, 9080);
864    }
865
866    #[test]
867    fn test_config_validation() {
868        let mut config = ServerConfig::default();
869        assert!(validate_config(&config).is_ok());
870
871        // Test port conflict
872        config.websocket.port = config.http.port;
873        assert!(validate_config(&config).is_err());
874
875        // Test invalid log level
876        config.websocket.port = 3001; // Fix port conflict
877        config.logging.level = "invalid".to_string();
878        assert!(validate_config(&config).is_err());
879    }
880
881    #[test]
882    fn test_apply_profile() {
883        let base = ServerConfig::default();
884        assert_eq!(base.http.port, 3000);
885
886        let profile = ProfileConfig {
887            http: Some(HttpConfig {
888                port: 8080,
889                ..Default::default()
890            }),
891            logging: Some(LoggingConfig {
892                level: "debug".to_string(),
893                ..Default::default()
894            }),
895            ..Default::default()
896        };
897
898        let merged = apply_profile(base, profile);
899        assert_eq!(merged.http.port, 8080);
900        assert_eq!(merged.logging.level, "debug");
901        assert_eq!(merged.websocket.port, 3001); // Unchanged
902    }
903
904    #[test]
905    fn test_minimal_config() {
906        let config = ServerConfig::minimal();
907        assert_eq!(config.http.port, 3000);
908        assert!(!config.admin.enabled);
909    }
910
911    #[test]
912    fn test_development_config() {
913        let config = ServerConfig::development();
914        assert!(config.admin.enabled);
915        assert_eq!(config.logging.level, "debug");
916    }
917
918    #[test]
919    fn test_ci_config() {
920        let config = ServerConfig::ci();
921        assert!(!config.core.latency_enabled);
922        assert!(!config.core.failures_enabled);
923    }
924
925    #[test]
926    fn test_builder_with_http_port() {
927        let config = ServerConfig::minimal().with_http_port(8080);
928        assert_eq!(config.http.port, 8080);
929    }
930
931    #[test]
932    fn test_builder_with_admin() {
933        let config = ServerConfig::minimal().with_admin(9090);
934        assert!(config.admin.enabled);
935        assert_eq!(config.admin.port, 9090);
936    }
937
938    #[test]
939    fn test_builder_with_grpc() {
940        let config = ServerConfig::minimal().with_grpc(50052);
941        assert!(config.grpc.enabled);
942        assert_eq!(config.grpc.port, 50052);
943        assert!(config.protocols.grpc.enabled);
944    }
945
946    #[test]
947    fn test_builder_with_websocket() {
948        let config = ServerConfig::minimal().with_websocket(3002);
949        assert!(config.websocket.enabled);
950        assert_eq!(config.websocket.port, 3002);
951    }
952
953    #[test]
954    fn test_builder_with_log_level() {
955        let config = ServerConfig::minimal().with_log_level("trace");
956        assert_eq!(config.logging.level, "trace");
957    }
958
959    #[test]
960    fn test_has_advanced_features_default() {
961        let config = ServerConfig::minimal();
962        assert!(!config.has_advanced_features());
963    }
964
965    #[test]
966    fn test_has_enterprise_features_default() {
967        let config = ServerConfig::minimal();
968        assert!(!config.has_enterprise_features());
969    }
970
971    #[test]
972    #[cfg(feature = "scripting")]
973    fn test_strip_typescript_types() {
974        let ts_code = r#"
975interface Config {
976    port: number;
977    host: string;
978}
979
980const config: Config = {
981    port: 3000,
982    host: "localhost"
983} as Config;
984"#;
985
986        let stripped = strip_typescript_types(ts_code).expect("Should strip TypeScript types");
987        assert!(!stripped.contains("interface"));
988        assert!(!stripped.contains(": Config"));
989        assert!(!stripped.contains("as Config"));
990    }
991}