Skip to main content

mockforge_core/
lib.rs

1//! # MockForge Core
2//!
3//! Core functionality and shared logic for the MockForge mocking framework.
4//!
5//! This crate provides the foundational building blocks used across all MockForge protocols
6//! (HTTP, WebSocket, gRPC, GraphQL). It can be used as a library to programmatically create
7//! and manage mock servers, or to build custom mocking solutions.
8//!
9//! ## Overview
10//!
11//! MockForge Core includes:
12//!
13//! - **Routing & Validation**: OpenAPI-based route registration and request validation
14//! - **Request/Response Processing**: Template expansion, data generation, and transformation
15//! - **Chaos Engineering**: Latency injection, failure simulation, and traffic shaping
16//! - **Proxy & Hybrid Mode**: Forward requests to real backends with intelligent fallback
17//! - **Request Chaining**: Multi-step request workflows with context passing
18//! - **Workspace Management**: Organize and persist mock configurations
19//! - **Observability**: Request logging, metrics collection, and tracing
20//!
21//! ## Quick Start: Embedding MockForge
22//!
23//! ### Creating a Simple HTTP Mock Server
24//!
25//! ```rust,no_run
26//! use mockforge_core::{
27//!     Config, LatencyProfile, OpenApiRouteRegistry, OpenApiSpec, Result, ValidationOptions,
28//! };
29//!
30//! #[tokio::main]
31//! async fn main() -> Result<()> {
32//!     // Load OpenAPI specification
33//!     let spec = OpenApiSpec::from_file("api.json").await?;
34//!
35//!     // Create route registry with validation
36//!     let registry = OpenApiRouteRegistry::new_with_options(spec, ValidationOptions::default());
37//!
38//!     // Configure core features
39//!     let config = Config {
40//!         latency_enabled: true,
41//!         failures_enabled: false,
42//!         default_latency: LatencyProfile::with_normal_distribution(400, 120.0),
43//!         ..Default::default()
44//!     };
45//!
46//!     // Build your HTTP server with the registry
47//!     // (See mockforge-http crate for router building)
48//!
49//!     Ok(())
50//! }
51//! ```
52//!
53//! ### Request Chaining
54//!
55//! Chain multiple requests together with shared context:
56//!
57//! ```rust,no_run
58//! use mockforge_core::{
59//!     ChainConfig, ChainDefinition, ChainLink, ChainRequest, RequestChainRegistry, Result,
60//! };
61//! use mockforge_core::request_chaining::RequestBody;
62//! use serde_json::json;
63//! use std::collections::HashMap;
64//!
65//! # async fn example() -> Result<()> {
66//! let registry = RequestChainRegistry::new(ChainConfig::default());
67//!
68//! // Define a chain: create user → add to group → verify membership
69//! let chain = ChainDefinition {
70//!     id: "user_onboarding".to_string(),
71//!     name: "User Onboarding".to_string(),
72//!     description: Some("Create user → add to group".to_string()),
73//!     config: ChainConfig {
74//!         enabled: true,
75//!         ..ChainConfig::default()
76//!     },
77//!     links: vec![
78//!         ChainLink {
79//!             request: ChainRequest {
80//!                 id: "create_user".to_string(),
81//!                 method: "POST".to_string(),
82//!                 url: "https://api.example.com/users".to_string(),
83//!                 headers: HashMap::new(),
84//!                 body: Some(RequestBody::json(json!({"name": "{{faker.name}}"}))),
85//!                 depends_on: Vec::new(),
86//!                 timeout_secs: None,
87//!                 expected_status: None,
88//!                 scripting: None,
89//!             },
90//!             extract: HashMap::from([("user_id".to_string(), "create_user.body.id".to_string())]),
91//!             store_as: Some("create_user_response".to_string()),
92//!         },
93//!         ChainLink {
94//!             request: ChainRequest {
95//!                 id: "add_to_group".to_string(),
96//!                 method: "POST".to_string(),
97//!                 url: "https://api.example.com/groups/{{user_id}}/members".to_string(),
98//!                 headers: HashMap::new(),
99//!                 body: None,
100//!                 depends_on: vec!["create_user".to_string()],
101//!                 timeout_secs: None,
102//!                 expected_status: None,
103//!                 scripting: None,
104//!             },
105//!             extract: HashMap::new(),
106//!             store_as: None,
107//!         },
108//!     ],
109//!     variables: HashMap::new(),
110//!     tags: vec!["onboarding".to_string()],
111//! };
112//!
113//! registry.store().register_chain(chain).await?;
114//! # Ok(())
115//! # }
116//! ```
117//!
118//! ### Latency & Failure Injection
119//!
120//! Simulate realistic network conditions and errors:
121//!
122//! ```rust,no_run
123//! use mockforge_core::{LatencyProfile, FailureConfig, create_failure_injector};
124//!
125//! // Configure latency simulation
126//! let latency = LatencyProfile::with_normal_distribution(400, 120.0)
127//!     .with_min_ms(100)
128//!     .with_max_ms(800);
129//!
130//! // Configure failure injection
131//! let failure_config = FailureConfig {
132//!     global_error_rate: 0.05, // 5% of requests fail
133//!     default_status_codes: vec![500, 502, 503],
134//!     ..Default::default()
135//! };
136//!
137//! let injector = create_failure_injector(true, Some(failure_config));
138//! ```
139//!
140//! ## Key Modules
141//!
142//! ### OpenAPI Support
143//! - [`openapi`]: Parse and work with OpenAPI specifications
144//! - [`openapi_routes`]: Register routes from OpenAPI specs with validation
145//! - [`validation`]: Request/response validation against schemas
146//!
147//! ### Request Processing
148//! - [`routing`]: Route matching and registration
149//! - [`templating`]: Template variable expansion ({{uuid}}, {{now}}, etc.)
150//! - [`request_chaining`]: Multi-step request workflows
151//! - [`overrides`]: Dynamic request/response modifications
152//!
153//! ### Chaos Engineering
154//! - [`latency`]: Latency injection with configurable profiles
155//! - [`failure_injection`]: Simulate service failures and errors
156//! - [`traffic_shaping`]: Bandwidth limiting and packet loss
157//!
158//! ### Proxy & Hybrid
159//! - [`proxy`]: Forward requests to upstream services
160//! - [`ws_proxy`]: WebSocket proxy with message transformation
161//!
162//! ### Persistence & Import
163//! - [`workspace`]: Workspace management for organizing mocks
164//! - [`workspace_import`]: Import from Postman, Insomnia, cURL, HAR
165//! - [`record_replay`]: Record real requests and replay as fixtures
166//!
167//! ### Observability
168//! - [`request_logger`]: Centralized request logging
169//! - [`performance`]: Performance metrics and profiling
170//!
171//! ## Feature Flags
172//!
173//! This crate supports several optional features:
174//!
175//! - `openapi`: OpenAPI specification support (enabled by default)
176//! - `validation`: Request/response validation (enabled by default)
177//! - `templating`: Template expansion (enabled by default)
178//! - `chaos`: Chaos engineering features (enabled by default)
179//! - `proxy`: Proxy and hybrid mode (enabled by default)
180//! - `workspace`: Workspace management (enabled by default)
181//!
182//! ## Examples
183//!
184//! See the [examples directory](https://github.com/SaaSy-Solutions/mockforge/tree/main/examples)
185//! for complete working examples.
186//!
187//! ## Related Crates
188//!
189//! - [`mockforge-http`](https://docs.rs/mockforge-http): HTTP/REST mock server
190//! - [`mockforge-grpc`](https://docs.rs/mockforge-grpc): gRPC mock server
191//! - [`mockforge-ws`](https://docs.rs/mockforge-ws): WebSocket mock server
192//! - [`mockforge-graphql`](https://docs.rs/mockforge-graphql): GraphQL mock server
193//! - [`mockforge-plugin-core`](https://docs.rs/mockforge-plugin-core): Plugin development
194//! - [`mockforge-data`](https://docs.rs/mockforge-data): Synthetic data generation
195//!
196//! ## Documentation
197//!
198//! - [MockForge Book](https://docs.mockforge.dev/)
199//! - [API Reference](https://docs.rs/mockforge-core)
200//! - [GitHub Repository](https://github.com/SaaSy-Solutions/mockforge)
201
202#![allow(deprecated)]
203
204pub mod ab_testing;
205#[deprecated(note = "Will be extracted to mockforge-intelligence crate")]
206pub mod ai_contract_diff;
207#[deprecated(note = "Will be extracted to mockforge-intelligence crate")]
208pub mod ai_response;
209/// AI Studio - Unified AI Copilot for all AI-powered features
210#[deprecated(note = "Will be extracted to mockforge-intelligence crate")]
211pub mod ai_studio;
212/// Behavioral cloning of backends - learn from recorded traffic to create realistic mock behavior
213#[deprecated(note = "Will be extracted to mockforge-intelligence crate")]
214pub mod behavioral_cloning;
215#[deprecated(note = "Will be extracted to mockforge-intelligence crate")]
216pub mod behavioral_economics;
217pub(crate) mod cache;
218pub mod chain_execution;
219pub mod chaos_utilities;
220#[deprecated(note = "Will be extracted to mockforge-import crate")]
221pub mod codegen;
222/// Collection export utilities for exporting mock data in various formats
223pub(crate) mod collection_export;
224pub mod conditions;
225pub mod config;
226/// Connection pooling for HTTP clients with health checks and idle management
227pub(crate) mod connection_pool;
228/// Cross-protocol consistency engine for unified state across all protocols
229pub mod consistency;
230#[deprecated(note = "Will be extracted to mockforge-contracts crate")]
231/// Consumer-driven contracts for tracking usage and detecting consumer-specific breaking changes
232pub mod consumer_contracts;
233#[deprecated(note = "Will be extracted to mockforge-contracts crate")]
234/// Contract validation for ensuring API contracts match specifications
235pub mod contract_drift;
236#[deprecated(note = "Will be extracted to mockforge-contracts crate")]
237/// Contract validation for ensuring API contracts match specifications
238pub mod contract_validation;
239/// Contract webhooks for notifying external systems about contract changes
240pub(crate) mod contract_webhooks;
241pub mod custom_fixture;
242/// Data source abstraction for loading test data from multiple sources
243pub mod data_source;
244/// Deceptive canary mode for routing team traffic to deceptive deploys
245pub mod deceptive_canary;
246/// Docker Compose integration for containerized mock deployments
247pub(crate) mod docker_compose;
248#[deprecated(note = "Will be extracted to mockforge-contracts crate")]
249/// GitOps integration for drift budget violations
250pub mod drift_gitops;
251#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
252pub mod encryption;
253pub mod error;
254pub mod failure_analysis;
255pub mod failure_injection;
256pub mod fidelity;
257pub mod generate_config;
258pub(crate) mod generative_schema;
259#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
260pub mod git_watch;
261pub mod graph;
262#[deprecated(note = "Will be extracted to mockforge-import crate")]
263pub mod import;
264pub mod incidents;
265#[deprecated(note = "Will be extracted to mockforge-intelligence crate")]
266pub mod intelligent_behavior;
267pub mod latency;
268pub mod lifecycle;
269#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
270pub mod multi_tenant;
271pub mod network_profiles;
272/// OData function call URI rewrite middleware
273pub mod odata_rewrite;
274pub mod openapi;
275pub mod openapi_routes;
276pub mod output_control;
277pub mod overrides;
278pub mod performance;
279/// Pillar usage tracking utilities
280pub mod pillar_tracking;
281/// Pillar metadata system for compile-time pillar tagging
282pub mod pillars;
283pub mod pr_generation;
284pub mod priority_handler;
285pub mod protocol_abstraction;
286/// Protocol server lifecycle trait for uniform server startup and shutdown
287pub mod protocol_server;
288#[deprecated(note = "Will be extracted to mockforge-proxy crate")]
289pub mod proxy;
290pub mod reality;
291pub mod reality_continuum;
292pub mod record_replay;
293pub mod request_capture;
294pub mod request_chaining;
295pub mod request_fingerprint;
296pub mod request_logger;
297pub(crate) mod request_scripting;
298// Route chaos has been moved to mockforge-route-chaos crate to avoid Send issues
299// Import directly from mockforge-route-chaos crate instead of re-exporting here
300// to avoid circular dependency (mockforge-route-chaos depends on mockforge-core for config types)
301pub(crate) mod persona_lifecycle_time;
302pub mod routing;
303/// Runtime validation for SDKs (request/response validation at runtime)
304pub mod runtime_validation;
305/// Scenario Studio - Visual editor for co-editing business flows
306pub mod scenario_studio;
307pub mod scenarios;
308#[deprecated(note = "Will be extracted to mockforge-contracts crate")]
309pub mod schema_diff;
310pub mod security;
311pub mod server_utils;
312/// Time travel and snapshot functionality for saving and restoring system states
313pub mod snapshots;
314pub mod spec_parser;
315pub mod stateful_handler;
316#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
317pub mod sync_watcher;
318/// Template expansion utilities (Send-safe, isolated from templating module)
319pub mod template_expansion;
320/// Template library system for shared templates, versioning, and marketplace
321pub mod template_library;
322pub mod templating;
323pub mod time_travel;
324pub mod time_travel_handler;
325/// Shared TLS utilities for building rustls server and client configurations.
326pub mod tls;
327pub mod traffic_shaping;
328pub mod validation;
329pub mod verification;
330pub mod voice;
331#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
332pub mod workspace;
333#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
334pub mod workspace_import;
335#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
336pub mod workspace_persistence;
337pub mod ws_proxy;
338
339pub use ab_testing::{
340    apply_variant_to_response, select_variant, ABTestConfig, ABTestReport,
341    ABTestingMiddlewareState, MockVariant, VariantAllocation, VariantAnalytics, VariantComparison,
342    VariantManager, VariantSelectionStrategy,
343};
344#[deprecated(note = "Will be extracted to mockforge-intelligence crate")]
345pub use behavioral_cloning::{
346    AmplificationScope, BehavioralSequence, EdgeAmplificationConfig, EdgeAmplifier,
347    EndpointProbabilityModel, ErrorPattern, LatencyDistribution, PayloadVariation,
348    ProbabilisticModel, SequenceLearner, SequenceStep,
349};
350pub use chain_execution::{ChainExecutionEngine, ChainExecutionResult, ChainExecutionStatus};
351#[deprecated(note = "Use mockforge_chaos::core_chaos_utilities instead")]
352pub use chaos_utilities::{ChaosConfig, ChaosEngine, ChaosResult, ChaosStatistics};
353pub use conditions::{evaluate_condition, ConditionContext, ConditionError};
354pub use config::{
355    apply_env_overrides, load_config, load_config_with_fallback, save_config, ApiKeyConfig,
356    AuthConfig, ServerConfig,
357};
358pub use consistency::{
359    ConsistencyEngine, EntityState, ProtocolState, SessionInfo, StateChangeEvent, UnifiedState,
360};
361pub use custom_fixture::{CustomFixture, CustomFixtureLoader, NestedFixture};
362pub use data_source::{
363    DataSource, DataSourceConfig, DataSourceContent, DataSourceFactory, DataSourceManager,
364    DataSourceType, GitDataSource, HttpDataSource, LocalDataSource,
365};
366pub use deceptive_canary::{
367    CanaryRoutingStrategy, CanaryStats, DeceptiveCanaryConfig, DeceptiveCanaryRouter,
368    TeamIdentifiers,
369};
370pub use error::{Error, Result};
371pub use failure_analysis::{
372    ContributingFactor, FailureContext, FailureContextCollector, FailureNarrative,
373    FailureNarrativeGenerator, NarrativeFrame,
374};
375#[deprecated(note = "Use mockforge_chaos::core_failure_injection instead")]
376pub use failure_injection::{
377    create_failure_injector, FailureConfig, FailureInjector, TagFailureConfig,
378};
379pub use fidelity::{FidelityCalculator, FidelityScore, SampleComparator, SchemaComparator};
380pub use generate_config::{
381    discover_config_file, load_generate_config, load_generate_config_with_fallback,
382    save_generate_config, BarrelType, GenerateConfig, GenerateOptions, InputConfig, OutputConfig,
383    PluginConfig,
384};
385#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
386pub use git_watch::{GitWatchConfig, GitWatchService};
387pub use graph::{
388    builder::GraphBuilder, relationships, ClusterType, EdgeType, GraphCluster, GraphData,
389    GraphEdge, GraphNode, NodeType, Protocol as GraphProtocol,
390};
391pub use latency::LatencyProfile;
392pub use lifecycle::{
393    LifecycleHook, LifecycleHookRegistry, MockLifecycleEvent, RequestContext, ResponseContext,
394    ServerLifecycleEvent,
395};
396#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
397pub use multi_tenant::{
398    MultiTenantConfig, MultiTenantWorkspaceRegistry, RoutingStrategy, TenantWorkspace,
399    WorkspaceContext, WorkspaceRouter, WorkspaceStats,
400};
401#[deprecated(note = "Use mockforge_chaos::core_network_profiles instead")]
402pub use network_profiles::{NetworkProfile, NetworkProfileCatalog};
403pub use openapi::{
404    OpenApiOperation, OpenApiRoute, OpenApiSchema, OpenApiSecurityRequirement, OpenApiSpec,
405};
406pub use openapi_routes::{
407    create_registry_from_file, create_registry_from_json, OpenApiRouteRegistry, ValidationOptions,
408};
409pub use output_control::{
410    apply_banner, apply_extension, apply_file_naming_template, build_file_naming_context,
411    process_generated_file, BarrelGenerator, FileNamingContext, GeneratedFile,
412};
413pub use overrides::{OverrideMode, OverrideRule, Overrides, PatchOp};
414pub use pillars::{Pillar, PillarMetadata};
415pub use priority_handler::{
416    MockGenerator, MockResponse, PriorityHttpHandler, PriorityResponse, SimpleMockGenerator,
417};
418pub use protocol_abstraction::{
419    MessagePattern, MiddlewareChain, Protocol, ProtocolMiddleware, ProtocolRequest,
420    ProtocolResponse, RequestMatcher, ResponseStatus, SpecOperation, SpecRegistry,
421    ValidationError as ProtocolValidationError, ValidationResult as ProtocolValidationResult,
422};
423#[deprecated(note = "Will be extracted to mockforge-proxy crate")]
424pub use proxy::{ProxyConfig, ProxyHandler, ProxyResponse};
425pub use reality::{PresetMetadata, RealityConfig, RealityEngine, RealityLevel, RealityPreset};
426pub use reality_continuum::{
427    ContinuumConfig, ContinuumRule, MergeStrategy, RealityContinuumEngine, ResponseBlender,
428    TimeSchedule, TransitionCurve, TransitionMode,
429};
430pub use record_replay::{
431    clean_old_fixtures, list_fixtures, list_ready_fixtures, list_smoke_endpoints, RecordHandler,
432    RecordReplayHandler, RecordedRequest, ReplayHandler,
433};
434pub use request_chaining::{
435    ChainConfig, ChainContext, ChainDefinition, ChainExecutionContext, ChainLink, ChainRequest,
436    ChainResponse, ChainStore, ChainTemplatingContext, RequestChainRegistry,
437};
438pub use request_fingerprint::{
439    RequestFingerprint, RequestHandlerResult, ResponsePriority, ResponseSource,
440};
441pub use request_logger::{
442    create_grpc_log_entry, create_http_log_entry, create_http_log_entry_with_query,
443    create_websocket_log_entry, get_global_logger, init_global_logger, log_request_global,
444    CentralizedRequestLogger, RequestLogEntry,
445};
446// Route chaos types moved to mockforge-route-chaos crate
447// Import directly: use mockforge_route_chaos::{RouteChaosInjector, RouteFaultResponse, RouteMatcher};
448pub use routing::{HttpMethod, Route, RouteRegistry};
449pub use runtime_validation::{
450    RuntimeValidationError, RuntimeValidationResult, RuntimeValidatorConfig, SchemaMetadata,
451};
452pub use scenario_studio::{
453    ConditionOperator, FlowCondition, FlowConnection, FlowDefinition, FlowExecutionResult,
454    FlowExecutor, FlowPosition, FlowStep, FlowStepResult, FlowType, FlowVariant, StepType,
455};
456pub use scenarios::types::StepResult;
457pub use scenarios::{
458    ScenarioDefinition, ScenarioExecutor, ScenarioParameter, ScenarioRegistry, ScenarioResult,
459    ScenarioStep,
460};
461#[deprecated(note = "Will be extracted to mockforge-contracts crate")]
462pub use schema_diff::{to_enhanced_422_json, validation_diff, ValidationError};
463pub use server_utils::errors::{json_error, json_success};
464pub use server_utils::{create_socket_addr, localhost_socket_addr, wildcard_socket_addr};
465pub use snapshots::{SnapshotComponents, SnapshotManager, SnapshotManifest, SnapshotMetadata};
466pub use spec_parser::{GraphQLValidator, OpenApiValidator, SpecFormat};
467pub use stateful_handler::{
468    ResourceIdExtract, StateInfo, StateResponse, StatefulConfig, StatefulResponse,
469    StatefulResponseHandler, TransitionTrigger,
470};
471#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
472pub use sync_watcher::{FileChange, SyncEvent, SyncService, SyncWatcher};
473pub use template_library::{
474    TemplateLibrary, TemplateLibraryEntry, TemplateLibraryManager, TemplateMarketplace,
475    TemplateMetadata, TemplateVersion,
476};
477pub use templating::{expand_str, expand_tokens};
478pub use time_travel::{
479    cron::{CronJob, CronJobAction, CronScheduler},
480    get_global_clock, is_time_travel_enabled, now as time_travel_now, register_global_clock,
481    unregister_global_clock, RepeatConfig, ResponseScheduler, ScheduledResponse, TimeScenario,
482    TimeTravelConfig, TimeTravelManager, TimeTravelStatus, VirtualClock,
483};
484pub use time_travel_handler::{
485    time_travel_middleware, ScheduledResponseWrapper, TimeTravelHandler,
486};
487#[deprecated(note = "Use mockforge_chaos::core_traffic_shaping instead")]
488pub use traffic_shaping::{BandwidthConfig, BurstLossConfig, TrafficShaper, TrafficShapingConfig};
489pub use uuid::Uuid;
490pub use validation::{validate_openapi_operation_security, validate_openapi_security, Validator};
491pub use verification::{
492    matches_verification_pattern, verify_at_least, verify_never, verify_requests, verify_sequence,
493    VerificationCount, VerificationRequest, VerificationResult,
494};
495pub use voice::{
496    ConversationContext, ConversationManager, ConversationState, GeneratedWorkspaceScenario,
497    HookTranspiler, ParsedCommand, ParsedWorkspaceScenario, VoiceCommandParser, VoiceSpecGenerator,
498    WorkspaceConfigSummary, WorkspaceScenarioGenerator,
499};
500#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
501pub use workspace::promotion_trait::PromotionService;
502#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
503pub use workspace::{EntityId, Folder, MockRequest, Workspace, WorkspaceConfig, WorkspaceRegistry};
504#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
505pub use workspace_import::{
506    create_workspace_from_curl, create_workspace_from_har, create_workspace_from_insomnia,
507    create_workspace_from_postman, import_postman_to_existing_workspace,
508    import_postman_to_workspace, WorkspaceImportConfig, WorkspaceImportResult,
509};
510#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
511pub use workspace_persistence::WorkspacePersistence;
512pub use ws_proxy::{WsProxyConfig, WsProxyHandler, WsProxyRule};
513// Note: ValidationError and ValidationResult from spec_parser conflict with schema_diff::ValidationError
514// Use qualified paths: spec_parser::ValidationError, spec_parser::ValidationResult
515
516/// Core configuration for MockForge
517#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
518#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
519#[serde(default)]
520pub struct Config {
521    /// Enable latency simulation
522    pub latency_enabled: bool,
523    /// Enable failure simulation
524    pub failures_enabled: bool,
525    /// Enable response overrides
526    pub overrides_enabled: bool,
527    /// Enable traffic shaping (bandwidth + burst loss)
528    pub traffic_shaping_enabled: bool,
529    /// Failure injection configuration
530    pub failure_config: Option<FailureConfig>,
531    /// Proxy configuration
532    pub proxy: Option<ProxyConfig>,
533    /// Default latency profile
534    pub default_latency: LatencyProfile,
535    /// Traffic shaping configuration
536    pub traffic_shaping: TrafficShapingConfig,
537    /// Random chaos configuration
538    pub chaos_random: Option<ChaosConfig>,
539    /// Maximum number of request logs to keep in memory (default: 1000)
540    /// Helps prevent unbounded memory growth from request logging
541    pub max_request_logs: usize,
542    /// Time travel configuration for temporal testing
543    pub time_travel: TimeTravelConfig,
544}
545
546/// Default configuration
547impl Default for Config {
548    fn default() -> Self {
549        Self {
550            latency_enabled: true,
551            failures_enabled: false,
552            overrides_enabled: true,
553            traffic_shaping_enabled: false,
554            failure_config: None,
555            proxy: None,
556            default_latency: LatencyProfile::default(),
557            traffic_shaping: TrafficShapingConfig::default(),
558            chaos_random: None,
559            max_request_logs: 1000, // Default: keep last 1000 requests
560            time_travel: TimeTravelConfig::default(),
561        }
562    }
563}
564
565impl Config {
566    /// Create a ChaosEngine from the chaos_random configuration if enabled
567    pub fn create_chaos_engine(&self) -> Option<ChaosEngine> {
568        self.chaos_random.as_ref().map(|config| ChaosEngine::new(config.clone()))
569    }
570
571    /// Check if random chaos mode is enabled
572    pub fn is_chaos_random_enabled(&self) -> bool {
573        self.chaos_random.as_ref().map(|c| c.enabled).unwrap_or(false)
574    }
575}
576
577#[cfg(test)]
578mod tests {
579    use super::*;
580
581    #[test]
582    fn test_config_default() {
583        let config = Config::default();
584        assert!(config.latency_enabled);
585        assert!(!config.failures_enabled);
586        assert!(config.overrides_enabled);
587        assert!(!config.traffic_shaping_enabled);
588        assert!(config.failure_config.is_none());
589        assert!(config.proxy.is_none());
590    }
591
592    #[test]
593    fn test_config_serialization() {
594        let config = Config::default();
595        let json = serde_json::to_string(&config).unwrap();
596        assert!(json.contains("latency_enabled"));
597        assert!(json.contains("failures_enabled"));
598    }
599
600    #[test]
601    fn test_config_deserialization() {
602        // Use default config and modify
603        let config = Config {
604            latency_enabled: false,
605            failures_enabled: true,
606            ..Default::default()
607        };
608
609        // Serialize and deserialize
610        let json = serde_json::to_string(&config).unwrap();
611        let deserialized: Config = serde_json::from_str(&json).unwrap();
612
613        assert!(!deserialized.latency_enabled);
614        assert!(deserialized.failures_enabled);
615        assert!(deserialized.overrides_enabled);
616    }
617
618    #[test]
619    fn test_config_with_custom_values() {
620        let config = Config {
621            latency_enabled: false,
622            failures_enabled: true,
623            ..Default::default()
624        };
625
626        assert!(!config.latency_enabled);
627        assert!(config.failures_enabled);
628    }
629}