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
204#[cfg(feature = "advanced")]
205pub mod ab_testing;
206#[cfg(feature = "ai")]
207#[deprecated(note = "Will be extracted to mockforge-intelligence crate")]
208pub mod ai_contract_diff;
209#[cfg(feature = "ai")]
210#[deprecated(note = "Will be extracted to mockforge-intelligence crate")]
211pub mod ai_response;
212/// AI Studio - Unified AI Copilot for all AI-powered features
213#[cfg(feature = "ai")]
214#[deprecated(note = "Will be extracted to mockforge-intelligence crate")]
215pub mod ai_studio;
216/// Behavioral cloning of backends - learn from recorded traffic to create realistic mock behavior
217#[cfg(feature = "ai")]
218#[deprecated(note = "Will be extracted to mockforge-intelligence crate")]
219pub mod behavioral_cloning;
220#[cfg(feature = "advanced")]
221#[deprecated(note = "Will be extracted to mockforge-intelligence crate")]
222pub mod behavioral_economics;
223#[allow(dead_code)]
224pub(crate) mod cache;
225pub mod chain_execution;
226pub mod chaos_utilities;
227#[cfg(feature = "advanced")]
228#[deprecated(note = "Will be extracted to mockforge-import crate")]
229pub mod codegen;
230/// Collection export utilities for exporting mock data in various formats
231#[allow(dead_code)]
232pub(crate) mod collection_export;
233pub mod conditions;
234pub mod config;
235/// Connection pooling for HTTP clients with health checks and idle management
236#[allow(dead_code)]
237pub(crate) mod connection_pool;
238/// Cross-protocol consistency engine for unified state across all protocols
239#[cfg(feature = "advanced")]
240pub mod consistency;
241#[cfg(feature = "contracts")]
242#[deprecated(note = "Will be extracted to mockforge-contracts crate")]
243/// Consumer-driven contracts for tracking usage and detecting consumer-specific breaking changes
244pub mod consumer_contracts;
245#[cfg(feature = "contracts")]
246#[deprecated(note = "Will be extracted to mockforge-contracts crate")]
247/// Contract validation for ensuring API contracts match specifications
248pub mod contract_drift;
249#[cfg(feature = "contracts")]
250#[deprecated(note = "Will be extracted to mockforge-contracts crate")]
251/// Contract validation for ensuring API contracts match specifications
252pub mod contract_validation;
253/// Contract webhooks for notifying external systems about contract changes
254#[cfg(feature = "contracts")]
255#[allow(dead_code)]
256pub(crate) mod contract_webhooks;
257pub mod custom_fixture;
258/// Data source abstraction for loading test data from multiple sources
259pub mod data_source;
260/// Deceptive canary mode for routing team traffic to deceptive deploys
261pub mod deceptive_canary;
262/// Docker Compose integration for containerized mock deployments
263#[allow(dead_code)]
264pub(crate) mod docker_compose;
265#[cfg(feature = "contracts")]
266#[deprecated(note = "Will be extracted to mockforge-contracts crate")]
267/// GitOps integration for drift budget violations
268pub mod drift_gitops;
269#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
270pub mod encryption;
271pub mod error;
272pub mod failure_analysis;
273pub mod failure_injection;
274pub mod fidelity;
275pub mod generate_config;
276#[allow(dead_code)]
277pub(crate) mod generative_schema;
278#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
279pub mod git_watch;
280#[cfg(feature = "advanced")]
281pub mod graph;
282#[cfg(feature = "workspace-mgmt")]
283#[deprecated(note = "Will be extracted to mockforge-import crate")]
284pub mod import;
285#[cfg(feature = "contracts")]
286pub mod incidents;
287#[cfg(feature = "ai")]
288#[deprecated(note = "Will be extracted to mockforge-intelligence crate")]
289pub mod intelligent_behavior;
290pub mod latency;
291pub mod lifecycle;
292#[cfg(feature = "advanced")]
293#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
294pub mod multi_tenant;
295pub mod network_profiles;
296/// OData function call URI rewrite middleware
297pub mod odata_rewrite;
298pub mod openapi;
299pub mod openapi_routes;
300pub mod output_control;
301pub mod overrides;
302pub mod performance;
303/// Pillar usage tracking utilities
304pub mod pillar_tracking;
305/// Pillar metadata system for compile-time pillar tagging
306pub mod pillars;
307#[cfg(feature = "contracts")]
308pub mod pr_generation;
309pub mod priority_handler;
310pub mod protocol_abstraction;
311/// Protocol server lifecycle trait for uniform server startup and shutdown
312pub mod protocol_server;
313#[deprecated(note = "Will be extracted to mockforge-proxy crate")]
314pub mod proxy;
315pub mod reality;
316#[cfg(feature = "advanced")]
317pub mod reality_continuum;
318pub mod record_replay;
319pub mod request_capture;
320pub mod request_chaining;
321pub mod request_fingerprint;
322pub mod request_logger;
323#[cfg(feature = "scripting")]
324pub(crate) mod request_scripting;
325// Route chaos has been moved to mockforge-route-chaos crate to avoid Send issues
326// Import directly from mockforge-route-chaos crate instead of re-exporting here
327// to avoid circular dependency (mockforge-route-chaos depends on mockforge-core for config types)
328#[allow(dead_code)]
329pub(crate) mod persona_lifecycle_time;
330pub mod routing;
331/// Runtime validation for SDKs (request/response validation at runtime)
332pub mod runtime_validation;
333/// Scenario Studio - Visual editor for co-editing business flows
334#[cfg(feature = "advanced")]
335pub mod scenario_studio;
336#[cfg(feature = "advanced")]
337pub mod scenarios;
338#[deprecated(note = "Will be extracted to mockforge-contracts crate")]
339pub mod schema_diff;
340pub mod security;
341pub mod server_utils;
342/// Time travel and snapshot functionality for saving and restoring system states
343#[cfg(feature = "advanced")]
344pub mod snapshots;
345pub mod spec_parser;
346pub mod stateful_handler;
347#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
348pub mod sync_watcher;
349/// Template expansion utilities (Send-safe, isolated from templating module)
350pub mod template_expansion;
351/// Template library system for shared templates, versioning, and marketplace
352pub mod template_library;
353pub mod templating;
354#[cfg(feature = "advanced")]
355pub mod time_travel;
356#[cfg(feature = "advanced")]
357pub mod time_travel_handler;
358/// Shared TLS utilities for building rustls server and client configurations.
359pub mod tls;
360pub mod traffic_shaping;
361pub mod validation;
362pub mod verification;
363#[cfg(feature = "voice")]
364pub mod voice;
365#[cfg(feature = "workspace-mgmt")]
366#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
367pub mod workspace;
368#[cfg(feature = "workspace-mgmt")]
369#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
370pub mod workspace_import;
371#[cfg(feature = "workspace-mgmt")]
372#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
373pub mod workspace_persistence;
374pub mod ws_proxy;
375
376#[cfg(feature = "advanced")]
377pub use ab_testing::{
378    apply_variant_to_response, select_variant, ABTestConfig, ABTestReport,
379    ABTestingMiddlewareState, MockVariant, VariantAllocation, VariantAnalytics, VariantComparison,
380    VariantManager, VariantSelectionStrategy,
381};
382#[cfg(feature = "ai")]
383#[deprecated(note = "Will be extracted to mockforge-intelligence crate")]
384pub use behavioral_cloning::{
385    AmplificationScope, BehavioralSequence, EdgeAmplificationConfig, EdgeAmplifier,
386    EndpointProbabilityModel, ErrorPattern, LatencyDistribution, PayloadVariation,
387    ProbabilisticModel, SequenceLearner, SequenceStep,
388};
389pub use chain_execution::{ChainExecutionEngine, ChainExecutionResult, ChainExecutionStatus};
390#[deprecated(note = "Use mockforge_chaos::core_chaos_utilities instead")]
391pub use chaos_utilities::{ChaosConfig, ChaosEngine, ChaosResult, ChaosStatistics};
392pub use conditions::{evaluate_condition, ConditionContext, ConditionError};
393pub use config::{
394    apply_env_overrides, load_config, load_config_with_fallback, save_config, ApiKeyConfig,
395    AuthConfig, ServerConfig,
396};
397#[cfg(feature = "advanced")]
398pub use consistency::{
399    ConsistencyEngine, EntityState, ProtocolState, SessionInfo, StateChangeEvent, UnifiedState,
400};
401pub use custom_fixture::{CustomFixture, CustomFixtureLoader, NestedFixture};
402pub use data_source::{
403    DataSource, DataSourceConfig, DataSourceContent, DataSourceFactory, DataSourceManager,
404    DataSourceType, GitDataSource, HttpDataSource, LocalDataSource,
405};
406pub use deceptive_canary::{
407    CanaryRoutingStrategy, CanaryStats, DeceptiveCanaryConfig, DeceptiveCanaryRouter,
408    TeamIdentifiers,
409};
410pub use error::{Error, Result};
411pub use failure_analysis::{
412    ContributingFactor, FailureContext, FailureContextCollector, FailureNarrative,
413    FailureNarrativeGenerator, NarrativeFrame,
414};
415#[deprecated(note = "Use mockforge_chaos::core_failure_injection instead")]
416pub use failure_injection::{
417    create_failure_injector, FailureConfig, FailureInjector, TagFailureConfig,
418};
419pub use fidelity::{FidelityCalculator, FidelityScore, SampleComparator, SchemaComparator};
420pub use generate_config::{
421    discover_config_file, load_generate_config, load_generate_config_with_fallback,
422    save_generate_config, BarrelType, GenerateConfig, GenerateOptions, InputConfig, OutputConfig,
423    PluginConfig,
424};
425#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
426pub use git_watch::{GitWatchConfig, GitWatchService};
427#[cfg(feature = "advanced")]
428pub use graph::{
429    builder::GraphBuilder, relationships, ClusterType, EdgeType, GraphCluster, GraphData,
430    GraphEdge, GraphNode, NodeType, Protocol as GraphProtocol,
431};
432pub use latency::LatencyProfile;
433pub use lifecycle::{
434    LifecycleHook, LifecycleHookRegistry, MockLifecycleEvent, RequestContext, ResponseContext,
435    ServerLifecycleEvent,
436};
437#[cfg(feature = "advanced")]
438#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
439pub use multi_tenant::{
440    MultiTenantConfig, MultiTenantWorkspaceRegistry, RoutingStrategy, TenantWorkspace,
441    WorkspaceContext, WorkspaceRouter, WorkspaceStats,
442};
443#[deprecated(note = "Use mockforge_chaos::core_network_profiles instead")]
444pub use network_profiles::{NetworkProfile, NetworkProfileCatalog};
445pub use openapi::{
446    OpenApiOperation, OpenApiRoute, OpenApiSchema, OpenApiSecurityRequirement, OpenApiSpec,
447};
448pub use openapi_routes::{
449    create_registry_from_file, create_registry_from_json, OpenApiRouteRegistry, ValidationOptions,
450};
451pub use output_control::{
452    apply_banner, apply_extension, apply_file_naming_template, build_file_naming_context,
453    process_generated_file, BarrelGenerator, FileNamingContext, GeneratedFile,
454};
455pub use overrides::{OverrideMode, OverrideRule, Overrides, PatchOp};
456pub use pillars::{Pillar, PillarMetadata};
457pub use priority_handler::{
458    MockGenerator, MockResponse, PriorityHttpHandler, PriorityResponse, SimpleMockGenerator,
459};
460pub use protocol_abstraction::{
461    MessagePattern, MiddlewareChain, Protocol, ProtocolMiddleware, ProtocolRequest,
462    ProtocolResponse, RequestMatcher, ResponseStatus, SpecOperation, SpecRegistry,
463    ValidationError as ProtocolValidationError, ValidationResult as ProtocolValidationResult,
464};
465#[deprecated(note = "Will be extracted to mockforge-proxy crate")]
466pub use proxy::{ProxyConfig, ProxyHandler, ProxyResponse};
467pub use reality::{PresetMetadata, RealityConfig, RealityEngine, RealityLevel, RealityPreset};
468#[cfg(feature = "advanced")]
469pub use reality_continuum::{
470    ContinuumConfig, ContinuumRule, MergeStrategy, RealityContinuumEngine, ResponseBlender,
471    TimeSchedule, TransitionCurve, TransitionMode,
472};
473pub use record_replay::{
474    clean_old_fixtures, list_fixtures, list_ready_fixtures, list_smoke_endpoints, RecordHandler,
475    RecordReplayHandler, RecordedRequest, ReplayHandler,
476};
477pub use request_chaining::{
478    ChainConfig, ChainContext, ChainDefinition, ChainExecutionContext, ChainLink, ChainRequest,
479    ChainResponse, ChainStore, ChainTemplatingContext, RequestChainRegistry,
480};
481pub use request_fingerprint::{
482    RequestFingerprint, RequestHandlerResult, ResponsePriority, ResponseSource,
483};
484pub use request_logger::{
485    create_grpc_log_entry, create_http_log_entry, create_http_log_entry_with_query,
486    create_websocket_log_entry, get_global_logger, init_global_logger, log_request_global,
487    CentralizedRequestLogger, RequestLogEntry,
488};
489// Route chaos types moved to mockforge-route-chaos crate
490// Import directly: use mockforge_route_chaos::{RouteChaosInjector, RouteFaultResponse, RouteMatcher};
491pub use routing::{HttpMethod, Route, RouteRegistry};
492pub use runtime_validation::{
493    RuntimeValidationError, RuntimeValidationResult, RuntimeValidatorConfig, SchemaMetadata,
494};
495#[cfg(feature = "advanced")]
496pub use scenario_studio::{
497    ConditionOperator, FlowCondition, FlowConnection, FlowDefinition, FlowExecutionResult,
498    FlowExecutor, FlowPosition, FlowStep, FlowStepResult, FlowType, FlowVariant, StepType,
499};
500#[cfg(feature = "advanced")]
501pub use scenarios::types::StepResult;
502#[cfg(feature = "advanced")]
503pub use scenarios::{
504    ScenarioDefinition, ScenarioExecutor, ScenarioParameter, ScenarioRegistry, ScenarioResult,
505    ScenarioStep,
506};
507#[cfg(feature = "contracts")]
508#[deprecated(note = "Will be extracted to mockforge-contracts crate")]
509pub use schema_diff::{to_enhanced_422_json, validation_diff, ValidationError};
510pub use server_utils::errors::{json_error, json_success};
511pub use server_utils::{create_socket_addr, localhost_socket_addr, wildcard_socket_addr};
512#[cfg(feature = "advanced")]
513pub use snapshots::{SnapshotComponents, SnapshotManager, SnapshotManifest, SnapshotMetadata};
514pub use spec_parser::{GraphQLValidator, OpenApiValidator, SpecFormat};
515pub use stateful_handler::{
516    ResourceIdExtract, StateInfo, StateResponse, StatefulConfig, StatefulResponse,
517    StatefulResponseHandler, TransitionTrigger,
518};
519#[cfg(feature = "workspace-mgmt")]
520#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
521pub use sync_watcher::{FileChange, SyncEvent, SyncService, SyncWatcher};
522pub use template_library::{
523    TemplateLibrary, TemplateLibraryEntry, TemplateLibraryManager, TemplateMarketplace,
524    TemplateMetadata, TemplateVersion,
525};
526pub use templating::{expand_str, expand_tokens};
527#[cfg(feature = "advanced")]
528pub use time_travel::{
529    cron::{CronJob, CronJobAction, CronScheduler},
530    get_global_clock, is_time_travel_enabled, now as time_travel_now, register_global_clock,
531    unregister_global_clock, RepeatConfig, ResponseScheduler, ScheduledResponse, TimeScenario,
532    TimeTravelConfig, TimeTravelManager, TimeTravelStatus, VirtualClock,
533};
534#[cfg(feature = "advanced")]
535pub use time_travel_handler::{
536    time_travel_middleware, ScheduledResponseWrapper, TimeTravelHandler,
537};
538#[deprecated(note = "Use mockforge_chaos::core_traffic_shaping instead")]
539pub use traffic_shaping::{BandwidthConfig, BurstLossConfig, TrafficShaper, TrafficShapingConfig};
540pub use uuid::Uuid;
541pub use validation::{validate_openapi_operation_security, validate_openapi_security, Validator};
542pub use verification::{
543    matches_verification_pattern, verify_at_least, verify_never, verify_requests, verify_sequence,
544    VerificationCount, VerificationRequest, VerificationResult,
545};
546#[cfg(feature = "voice")]
547pub use voice::{
548    ConversationContext, ConversationManager, ConversationState, GeneratedWorkspaceScenario,
549    HookTranspiler, ParsedCommand, ParsedWorkspaceScenario, VoiceCommandParser, VoiceSpecGenerator,
550    WorkspaceConfigSummary, WorkspaceScenarioGenerator,
551};
552#[cfg(feature = "workspace-mgmt")]
553#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
554pub use workspace::promotion_trait::PromotionService;
555#[cfg(feature = "workspace-mgmt")]
556#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
557pub use workspace::{EntityId, Folder, MockRequest, Workspace, WorkspaceConfig, WorkspaceRegistry};
558#[cfg(feature = "workspace-mgmt")]
559#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
560pub use workspace_import::{
561    create_workspace_from_curl, create_workspace_from_har, create_workspace_from_insomnia,
562    create_workspace_from_postman, import_postman_to_existing_workspace,
563    import_postman_to_workspace, WorkspaceImportConfig, WorkspaceImportResult,
564};
565#[cfg(feature = "workspace-mgmt")]
566#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
567pub use workspace_persistence::WorkspacePersistence;
568pub use ws_proxy::{WsProxyConfig, WsProxyHandler, WsProxyRule};
569// Note: ValidationError and ValidationResult from spec_parser conflict with schema_diff::ValidationError
570// Use qualified paths: spec_parser::ValidationError, spec_parser::ValidationResult
571
572/// Core configuration for MockForge
573#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
574#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
575#[serde(default)]
576pub struct Config {
577    /// Enable latency simulation
578    pub latency_enabled: bool,
579    /// Enable failure simulation
580    pub failures_enabled: bool,
581    /// Enable response overrides
582    pub overrides_enabled: bool,
583    /// Enable traffic shaping (bandwidth + burst loss)
584    pub traffic_shaping_enabled: bool,
585    /// Failure injection configuration
586    pub failure_config: Option<FailureConfig>,
587    /// Proxy configuration
588    pub proxy: Option<ProxyConfig>,
589    /// Default latency profile
590    pub default_latency: LatencyProfile,
591    /// Traffic shaping configuration
592    pub traffic_shaping: TrafficShapingConfig,
593    /// Random chaos configuration
594    pub chaos_random: Option<ChaosConfig>,
595    /// Maximum number of request logs to keep in memory (default: 1000)
596    /// Helps prevent unbounded memory growth from request logging
597    pub max_request_logs: usize,
598    /// Time travel configuration for temporal testing
599    pub time_travel: TimeTravelConfig,
600}
601
602/// Default configuration
603impl Default for Config {
604    fn default() -> Self {
605        Self {
606            latency_enabled: true,
607            failures_enabled: false,
608            overrides_enabled: true,
609            traffic_shaping_enabled: false,
610            failure_config: None,
611            proxy: None,
612            default_latency: LatencyProfile::default(),
613            traffic_shaping: TrafficShapingConfig::default(),
614            chaos_random: None,
615            max_request_logs: 1000, // Default: keep last 1000 requests
616            time_travel: TimeTravelConfig::default(),
617        }
618    }
619}
620
621impl Config {
622    /// Create a ChaosEngine from the chaos_random configuration if enabled
623    pub fn create_chaos_engine(&self) -> Option<ChaosEngine> {
624        self.chaos_random.as_ref().map(|config| ChaosEngine::new(config.clone()))
625    }
626
627    /// Check if random chaos mode is enabled
628    pub fn is_chaos_random_enabled(&self) -> bool {
629        self.chaos_random.as_ref().map(|c| c.enabled).unwrap_or(false)
630    }
631}
632
633#[cfg(test)]
634mod tests {
635    use super::*;
636
637    #[test]
638    fn test_config_default() {
639        let config = Config::default();
640        assert!(config.latency_enabled);
641        assert!(!config.failures_enabled);
642        assert!(config.overrides_enabled);
643        assert!(!config.traffic_shaping_enabled);
644        assert!(config.failure_config.is_none());
645        assert!(config.proxy.is_none());
646    }
647
648    #[test]
649    fn test_config_serialization() {
650        let config = Config::default();
651        let json = serde_json::to_string(&config).unwrap();
652        assert!(json.contains("latency_enabled"));
653        assert!(json.contains("failures_enabled"));
654    }
655
656    #[test]
657    fn test_config_deserialization() {
658        // Use default config and modify
659        let config = Config {
660            latency_enabled: false,
661            failures_enabled: true,
662            ..Default::default()
663        };
664
665        // Serialize and deserialize
666        let json = serde_json::to_string(&config).unwrap();
667        let deserialized: Config = serde_json::from_str(&json).unwrap();
668
669        assert!(!deserialized.latency_enabled);
670        assert!(deserialized.failures_enabled);
671        assert!(deserialized.overrides_enabled);
672    }
673
674    #[test]
675    fn test_config_with_custom_values() {
676        let config = Config {
677            latency_enabled: false,
678            failures_enabled: true,
679            ..Default::default()
680        };
681
682        assert!(!config.latency_enabled);
683        assert!(config.failures_enabled);
684    }
685}