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::generic(format!("Failed to read config file: {}", e)))?;
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::generic(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::generic(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::generic(format!("Failed to serialize config to YAML: {}", e)))?
372    } else {
373        serde_json::to_string_pretty(config)
374            .map_err(|e| Error::generic(format!("Failed to serialize config to JSON: {}", e)))?
375    };
376
377    fs::write(path, content)
378        .await
379        .map_err(|e| Error::generic(format!("Failed to write config file: {}", e)))?;
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::generic("HTTP port cannot be 0"));
585    }
586    if config.websocket.port == 0 {
587        return Err(Error::generic("WebSocket port cannot be 0"));
588    }
589    if config.grpc.port == 0 {
590        return Err(Error::generic("gRPC port cannot be 0"));
591    }
592    if config.admin.port == 0 {
593        return Err(Error::generic("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::generic(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::generic(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::generic(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::generic(format!("Failed to read JS/TS config file: {}", e)))?;
699
700    // Create a JavaScript runtime
701    let runtime = Runtime::new()
702        .map_err(|e| Error::generic(format!("Failed to create JS runtime: {}", e)))?;
703    let context = Context::full(&runtime)
704        .map_err(|e| Error::generic(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::generic(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::generic(format!("Failed to stringify JS config: {}", e)))?
730            .ok_or_else(|| Error::generic("JS config returned undefined"))?
731            .get()
732            .map_err(|e| Error::generic(format!("Failed to get JSON string: {}", e)))?;
733
734        // Parse JSON into ServerConfig
735        serde_json::from_str(&json_str).map_err(|e| {
736            Error::generic(format!("Failed to parse JS config as ServerConfig: {}", e))
737        })
738    })
739}
740
741/// Simple TypeScript type stripper (removes type annotations)
742/// Note: This is a basic implementation. For production use, consider using swc or esbuild
743///
744/// # Errors
745/// Returns an error if regex compilation fails. This should never happen with static patterns,
746/// but we handle it gracefully to prevent panics.
747#[cfg(feature = "scripting")]
748fn strip_typescript_types(content: &str) -> Result<String> {
749    use regex::Regex;
750
751    let mut result = content.to_string();
752
753    // Compile regex patterns with error handling
754    // Note: These patterns are statically known and should never fail,
755    // but we handle errors to prevent panics in edge cases
756
757    // Remove interface declarations (handles multi-line)
758    let interface_re = Regex::new(r"(?ms)interface\s+\w+\s*\{[^}]*\}\s*")
759        .map_err(|e| Error::generic(format!("Failed to compile interface regex: {}", e)))?;
760    result = interface_re.replace_all(&result, "").to_string();
761
762    // Remove type aliases
763    let type_alias_re = Regex::new(r"(?m)^type\s+\w+\s*=\s*[^;]+;\s*")
764        .map_err(|e| Error::generic(format!("Failed to compile type alias regex: {}", e)))?;
765    result = type_alias_re.replace_all(&result, "").to_string();
766
767    // Remove type annotations (: Type)
768    let type_annotation_re = Regex::new(r":\s*[A-Z]\w*(<[^>]+>)?(\[\])?")
769        .map_err(|e| Error::generic(format!("Failed to compile type annotation regex: {}", e)))?;
770    result = type_annotation_re.replace_all(&result, "").to_string();
771
772    // Remove type imports and exports
773    let type_import_re = Regex::new(r"(?m)^(import|export)\s+type\s+.*$")
774        .map_err(|e| Error::generic(format!("Failed to compile type import regex: {}", e)))?;
775    result = type_import_re.replace_all(&result, "").to_string();
776
777    // Remove as Type
778    let as_type_re = Regex::new(r"\s+as\s+\w+")
779        .map_err(|e| Error::generic(format!("Failed to compile 'as type' regex: {}", e)))?;
780    result = as_type_re.replace_all(&result, "").to_string();
781
782    Ok(result)
783}
784
785/// Enhanced load_config that supports multiple formats including JS/TS
786pub async fn load_config_auto<P: AsRef<Path>>(path: P) -> Result<ServerConfig> {
787    let ext = path.as_ref().extension().and_then(|s| s.to_str()).unwrap_or("");
788
789    match ext {
790        #[cfg(feature = "scripting")]
791        "ts" | "js" => load_config_from_js(&path).await,
792        #[cfg(not(feature = "scripting"))]
793        "ts" | "js" => Err(Error::generic(
794            "JS/TS config files require the 'scripting' feature (rquickjs). \
795             Enable it with: cargo build --features scripting"
796                .to_string(),
797        )),
798        "yaml" | "yml" | "json" => load_config(&path).await,
799        _ => Err(Error::generic(format!(
800            "Unsupported config file format: {}. Supported: .yaml, .yml, .json{}",
801            ext,
802            if cfg!(feature = "scripting") {
803                ", .ts, .js"
804            } else {
805                ""
806            }
807        ))),
808    }
809}
810
811/// Discover configuration file with support for all formats
812pub async fn discover_config_file_all_formats() -> Result<std::path::PathBuf> {
813    let current_dir = std::env::current_dir()
814        .map_err(|e| Error::generic(format!("Failed to get current directory: {}", e)))?;
815
816    let config_names = vec![
817        "mockforge.config.ts",
818        "mockforge.config.js",
819        "mockforge.yaml",
820        "mockforge.yml",
821        ".mockforge.yaml",
822        ".mockforge.yml",
823    ];
824
825    // Check current directory
826    for name in &config_names {
827        let path = current_dir.join(name);
828        if fs::metadata(&path).await.is_ok() {
829            return Ok(path);
830        }
831    }
832
833    // Check parent directories (up to 5 levels)
834    let mut dir = current_dir.clone();
835    for _ in 0..5 {
836        if let Some(parent) = dir.parent() {
837            for name in &config_names {
838                let path = parent.join(name);
839                if fs::metadata(&path).await.is_ok() {
840                    return Ok(path);
841                }
842            }
843            dir = parent.to_path_buf();
844        } else {
845            break;
846        }
847    }
848
849    Err(Error::generic(
850        "No configuration file found. Expected one of: mockforge.config.ts, mockforge.config.js, mockforge.yaml, mockforge.yml",
851    ))
852}
853
854#[cfg(test)]
855mod tests {
856    use super::*;
857
858    #[test]
859    fn test_default_config() {
860        let config = ServerConfig::default();
861        assert_eq!(config.http.port, 3000);
862        assert_eq!(config.websocket.port, 3001);
863        assert_eq!(config.grpc.port, 50051);
864        assert_eq!(config.admin.port, 9080);
865    }
866
867    #[test]
868    fn test_config_validation() {
869        let mut config = ServerConfig::default();
870        assert!(validate_config(&config).is_ok());
871
872        // Test port conflict
873        config.websocket.port = config.http.port;
874        assert!(validate_config(&config).is_err());
875
876        // Test invalid log level
877        config.websocket.port = 3001; // Fix port conflict
878        config.logging.level = "invalid".to_string();
879        assert!(validate_config(&config).is_err());
880    }
881
882    #[test]
883    fn test_apply_profile() {
884        let base = ServerConfig::default();
885        assert_eq!(base.http.port, 3000);
886
887        let profile = ProfileConfig {
888            http: Some(HttpConfig {
889                port: 8080,
890                ..Default::default()
891            }),
892            logging: Some(LoggingConfig {
893                level: "debug".to_string(),
894                ..Default::default()
895            }),
896            ..Default::default()
897        };
898
899        let merged = apply_profile(base, profile);
900        assert_eq!(merged.http.port, 8080);
901        assert_eq!(merged.logging.level, "debug");
902        assert_eq!(merged.websocket.port, 3001); // Unchanged
903    }
904
905    #[test]
906    fn test_minimal_config() {
907        let config = ServerConfig::minimal();
908        assert_eq!(config.http.port, 3000);
909        assert!(!config.admin.enabled);
910    }
911
912    #[test]
913    fn test_development_config() {
914        let config = ServerConfig::development();
915        assert!(config.admin.enabled);
916        assert_eq!(config.logging.level, "debug");
917    }
918
919    #[test]
920    fn test_ci_config() {
921        let config = ServerConfig::ci();
922        assert!(!config.core.latency_enabled);
923        assert!(!config.core.failures_enabled);
924    }
925
926    #[test]
927    fn test_builder_with_http_port() {
928        let config = ServerConfig::minimal().with_http_port(8080);
929        assert_eq!(config.http.port, 8080);
930    }
931
932    #[test]
933    fn test_builder_with_admin() {
934        let config = ServerConfig::minimal().with_admin(9090);
935        assert!(config.admin.enabled);
936        assert_eq!(config.admin.port, 9090);
937    }
938
939    #[test]
940    fn test_builder_with_grpc() {
941        let config = ServerConfig::minimal().with_grpc(50052);
942        assert!(config.grpc.enabled);
943        assert_eq!(config.grpc.port, 50052);
944        assert!(config.protocols.grpc.enabled);
945    }
946
947    #[test]
948    fn test_builder_with_websocket() {
949        let config = ServerConfig::minimal().with_websocket(3002);
950        assert!(config.websocket.enabled);
951        assert_eq!(config.websocket.port, 3002);
952    }
953
954    #[test]
955    fn test_builder_with_log_level() {
956        let config = ServerConfig::minimal().with_log_level("trace");
957        assert_eq!(config.logging.level, "trace");
958    }
959
960    #[test]
961    fn test_has_advanced_features_default() {
962        let config = ServerConfig::minimal();
963        assert!(!config.has_advanced_features());
964    }
965
966    #[test]
967    fn test_has_enterprise_features_default() {
968        let config = ServerConfig::minimal();
969        assert!(!config.has_enterprise_features());
970    }
971
972    #[test]
973    #[cfg(feature = "scripting")]
974    fn test_strip_typescript_types() {
975        let ts_code = r#"
976interface Config {
977    port: number;
978    host: string;
979}
980
981const config: Config = {
982    port: 3000,
983    host: "localhost"
984} as Config;
985"#;
986
987        let stripped = strip_typescript_types(ts_code).expect("Should strip TypeScript types");
988        assert!(!stripped.contains("interface"));
989        assert!(!stripped.contains(": Config"));
990        assert!(!stripped.contains("as Config"));
991    }
992}