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//! NOTE: marked `ignore` (not `no_run`) — the example references types
26//! that moved out of `mockforge-core` during the workspace splits in
27//! commits 2ec7625a (openapi) and b75e243c (foundation):
28//! `OpenApiSpec`, `OpenApiRouteRegistry`, and `ValidationOptions` now
29//! live in `mockforge_openapi`; `LatencyProfile` is in
30//! `mockforge_foundation`. Until the example is rewritten using only
31//! symbols still re-exported from `mockforge_core`, marking it `ignore`
32//! keeps it visible as docs without breaking `cargo test --doc`.
33//!
34//! ```rust,ignore
35//! use mockforge_core::{
36//! Config, LatencyProfile, OpenApiRouteRegistry, OpenApiSpec, Result, ValidationOptions,
37//! };
38//!
39//! #[tokio::main]
40//! async fn main() -> Result<()> {
41//! // Load OpenAPI specification
42//! let spec = OpenApiSpec::from_file("api.json").await?;
43//!
44//! // Create route registry with validation
45//! let registry = OpenApiRouteRegistry::new_with_options(spec, ValidationOptions::default());
46//!
47//! // Configure core features
48//! let config = Config {
49//! latency_enabled: true,
50//! failures_enabled: false,
51//! default_latency: LatencyProfile::with_normal_distribution(400, 120.0),
52//! ..Default::default()
53//! };
54//!
55//! // Build your HTTP server with the registry
56//! // (See mockforge-http crate for router building)
57//!
58//! Ok(())
59//! }
60//! ```
61//!
62//! ### Request Chaining
63//!
64//! Chain multiple requests together with shared context:
65//!
66//! ```rust,no_run
67//! use mockforge_core::{
68//! ChainConfig, ChainDefinition, ChainLink, ChainRequest, RequestChainRegistry, Result,
69//! };
70//! use mockforge_core::request_chaining::RequestBody;
71//! use serde_json::json;
72//! use std::collections::HashMap;
73//!
74//! # async fn example() -> Result<()> {
75//! let registry = RequestChainRegistry::new(ChainConfig::default());
76//!
77//! // Define a chain: create user → add to group → verify membership
78//! let chain = ChainDefinition {
79//! id: "user_onboarding".to_string(),
80//! name: "User Onboarding".to_string(),
81//! description: Some("Create user → add to group".to_string()),
82//! config: ChainConfig {
83//! enabled: true,
84//! ..ChainConfig::default()
85//! },
86//! links: vec![
87//! ChainLink {
88//! request: ChainRequest {
89//! id: "create_user".to_string(),
90//! method: "POST".to_string(),
91//! url: "https://api.example.com/users".to_string(),
92//! headers: HashMap::new(),
93//! body: Some(RequestBody::json(json!({"name": "{{faker.name}}"}))),
94//! depends_on: Vec::new(),
95//! timeout_secs: None,
96//! expected_status: None,
97//! scripting: None,
98//! },
99//! extract: HashMap::from([("user_id".to_string(), "create_user.body.id".to_string())]),
100//! store_as: Some("create_user_response".to_string()),
101//! },
102//! ChainLink {
103//! request: ChainRequest {
104//! id: "add_to_group".to_string(),
105//! method: "POST".to_string(),
106//! url: "https://api.example.com/groups/{{user_id}}/members".to_string(),
107//! headers: HashMap::new(),
108//! body: None,
109//! depends_on: vec!["create_user".to_string()],
110//! timeout_secs: None,
111//! expected_status: None,
112//! scripting: None,
113//! },
114//! extract: HashMap::new(),
115//! store_as: None,
116//! },
117//! ],
118//! variables: HashMap::new(),
119//! tags: vec!["onboarding".to_string()],
120//! };
121//!
122//! registry.store().register_chain(chain).await?;
123//! # Ok(())
124//! # }
125//! ```
126//!
127//! ### Latency & Failure Injection
128//!
129//! Simulate realistic network conditions and errors:
130//!
131//! NOTE: also marked `ignore` for the same reason as the Quick Start
132//! example above — `LatencyProfile`, `FailureConfig`, and
133//! `create_failure_injector` no longer live in `mockforge_core` after
134//! the foundation/openapi extraction. Rewrite to use the actual hosting
135//! crates when this section is updated.
136//!
137//! ```rust,ignore
138//! use mockforge_core::{LatencyProfile, FailureConfig, create_failure_injector};
139//!
140//! // Configure latency simulation
141//! let latency = LatencyProfile::with_normal_distribution(400, 120.0)
142//! .with_min_ms(100)
143//! .with_max_ms(800);
144//!
145//! // Configure failure injection
146//! let failure_config = FailureConfig {
147//! global_error_rate: 0.05, // 5% of requests fail
148//! default_status_codes: vec![500, 502, 503],
149//! ..Default::default()
150//! };
151//!
152//! let injector = create_failure_injector(true, Some(failure_config));
153//! ```
154//!
155//! ## Key Modules
156//!
157//! ### OpenAPI Support
158//! - [`openapi`]: Parse and work with OpenAPI specifications
159//! - [`openapi_routes`]: Register routes from OpenAPI specs with validation
160//! - [`validation`]: Request/response validation against schemas
161//!
162//! ### Request Processing
163//! - [`routing`]: Route matching and registration
164//! - [`templating`]: Template variable expansion ({{uuid}}, {{now}}, etc.)
165//! - [`request_chaining`]: Multi-step request workflows
166//! - [`overrides`]: Dynamic request/response modifications
167//!
168//! ### Chaos Engineering
169//! - [`latency`]: Latency injection with configurable profiles
170//! - [`failure_injection`]: Simulate service failures and errors
171//! - [`traffic_shaping`]: Bandwidth limiting and packet loss
172//!
173//! ### Proxy & Hybrid
174//! - [`proxy`]: Forward requests to upstream services
175//! - [`ws_proxy`]: WebSocket proxy with message transformation
176//!
177//! ### Persistence & Import
178//! - [`workspace`]: Workspace management for organizing mocks
179//! - [`workspace_import`]: Import from Postman, Insomnia, cURL, HAR
180//! - [`record_replay`]: Record real requests and replay as fixtures
181//!
182//! ### Observability
183//! - [`request_logger`]: Centralized request logging
184//! - [`performance`]: Performance metrics and profiling
185//!
186//! ## Feature Flags
187//!
188//! This crate supports several optional features:
189//!
190//! - `openapi`: OpenAPI specification support (enabled by default)
191//! - `validation`: Request/response validation (enabled by default)
192//! - `templating`: Template expansion (enabled by default)
193//! - `chaos`: Chaos engineering features (enabled by default)
194//! - `proxy`: Proxy and hybrid mode (enabled by default)
195//! - `workspace`: Workspace management (enabled by default)
196//!
197//! ## Examples
198//!
199//! See the [examples directory](https://github.com/SaaSy-Solutions/mockforge/tree/main/examples)
200//! for complete working examples.
201//!
202//! ## Related Crates
203//!
204//! - [`mockforge-http`](https://docs.rs/mockforge-http): HTTP/REST mock server
205//! - [`mockforge-grpc`](https://docs.rs/mockforge-grpc): gRPC mock server
206//! - [`mockforge-ws`](https://docs.rs/mockforge-ws): WebSocket mock server
207//! - [`mockforge-graphql`](https://docs.rs/mockforge-graphql): GraphQL mock server
208//! - [`mockforge-plugin-core`](https://docs.rs/mockforge-plugin-core): Plugin development
209//! - [`mockforge-data`](https://docs.rs/mockforge-data): Synthetic data generation
210//!
211//! ## Documentation
212//!
213//! - [MockForge Book](https://docs.mockforge.dev/)
214//! - [API Reference](https://docs.rs/mockforge-core)
215//! - [GitHub Repository](https://github.com/SaaSy-Solutions/mockforge)
216
217#![allow(deprecated)]
218
219#[cfg(feature = "advanced")]
220pub mod ab_testing;
221/// `ai_contract_diff` lives in `mockforge_intelligence::ai_contract_diff`
222/// (Issue #562 phase 4). Re-exported here so existing
223/// `crate::ai_contract_diff::*` call sites inside core (`ai_studio` /
224/// `contract_diff_handler`, `request_capture`) and external
225/// `mockforge_core::ai_contract_diff::*` consumers (mockforge-http,
226/// mockforge-cli) keep compiling unchanged.
227pub use mockforge_intelligence::ai_contract_diff;
228#[cfg(feature = "ai")]
229#[deprecated(note = "Will be extracted to mockforge-intelligence crate")]
230pub mod ai_response;
231/// `ai_studio` lives in `mockforge_intelligence::ai_studio` (Issue #562
232/// phase 8 — the final AI cluster module). Re-exported here so existing
233/// `mockforge_core::ai_studio::*` call sites (mockforge-http handlers,
234/// mockforge-ui handlers) keep compiling unchanged. The whole-module move
235/// was unblocked by phases 5–7 extracting failure_analysis,
236/// contract_validation, reality, and voice (leaves).
237pub use mockforge_intelligence::ai_studio;
238/// Behavioral cloning of backends - learn from recorded traffic to create realistic mock behavior
239#[cfg(feature = "ai")]
240#[deprecated(note = "Will be extracted to mockforge-intelligence crate")]
241pub mod behavioral_cloning;
242#[cfg(feature = "advanced")]
243// behavioral_economics depends on priority_handler + core internals; staying in core.
244pub mod behavioral_economics;
245#[allow(dead_code)]
246pub(crate) mod cache;
247pub mod chain_execution;
248/// `chaos_utilities` moved to `mockforge_foundation::chaos_utilities`
249/// (Issue #562 phase 6) so `mockforge_intelligence::reality` can hold
250/// `ChaosConfig` fields without taking a dep on core. Re-exported here
251/// for backwards compat.
252pub use mockforge_foundation::chaos_utilities;
253#[cfg(feature = "advanced")]
254#[deprecated(note = "Will be extracted to mockforge-import crate")]
255pub mod codegen;
256/// Collection export utilities for exporting mock data in various formats
257#[allow(dead_code)]
258pub(crate) mod collection_export;
259pub mod conditions;
260pub mod config;
261/// Connection pooling for HTTP clients with health checks and idle management
262#[allow(dead_code)]
263pub(crate) mod connection_pool;
264/// Cross-protocol consistency engine for unified state across all protocols
265#[cfg(feature = "advanced")]
266pub mod consistency;
267#[cfg(feature = "contracts")]
268#[deprecated(note = "Will be extracted to mockforge-contracts crate")]
269/// Consumer-driven contracts for tracking usage and detecting consumer-specific breaking changes
270pub mod consumer_contracts;
271#[cfg(feature = "contracts")]
272/// Contract drift detection. Data types moved to mockforge-foundation
273/// (A13–A21); engines (DriftBudgetEngine, ThreatAnalyzer,
274/// ProtocolContractRegistry, WebSocket/MQTT/Kafka contract impls) stay
275/// here because they depend on OpenApiSpec and jsonschema validators.
276pub mod contract_drift;
277#[cfg(feature = "contracts")]
278/// `contract_validation` lives in `mockforge_intelligence::contract_validation`
279/// (Issue #562 phase 5). Re-exported here so existing
280/// `mockforge_core::contract_validation::*` call sites
281/// (mockforge-cli, in-core ai_studio) keep compiling unchanged.
282pub use mockforge_intelligence::contract_validation;
283/// Contract webhooks for notifying external systems about contract changes
284#[cfg(feature = "contracts")]
285#[allow(dead_code)]
286pub(crate) mod contract_webhooks;
287/// `custom_fixture` was promoted to [`mockforge_openapi::custom_fixture`];
288/// re-exported here for backwards compatibility.
289pub(crate) use mockforge_openapi::custom_fixture;
290/// Data source abstraction for loading test data from multiple sources
291pub mod data_source;
292/// Deceptive canary mode for routing team traffic to deceptive deploys
293pub mod deceptive_canary;
294/// Docker Compose integration for containerized mock deployments
295#[allow(dead_code)]
296pub(crate) mod docker_compose;
297#[cfg(feature = "contracts")]
298/// GitOps integration for drift budget violations. Depends on core
299/// incidents + contract_drift; stays in core.
300pub mod drift_gitops;
301// Encryption utility; stays in core (small, widely used).
302pub mod encryption;
303pub mod error;
304/// `failure_injection` was promoted to [`mockforge_foundation::failure_injection`];
305/// re-exported here for backwards compatibility.
306pub(crate) use mockforge_foundation::failure_injection;
307/// `failure_analysis` lives in `mockforge_intelligence::failure_analysis`
308/// (Issue #562 phase 5). Re-exported here so existing
309/// `mockforge_core::failure_analysis::*` call sites
310/// (mockforge-ui handlers, in-core workspace/request + ai_studio/debug_analyzer)
311/// keep compiling unchanged.
312pub use mockforge_intelligence::failure_analysis;
313pub mod fidelity;
314/// Generic fixture loading utilities shared across protocol crates
315pub mod fixture_store;
316pub mod generate_config;
317#[allow(dead_code)]
318pub(crate) mod generative_schema;
319#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
320pub mod git_watch;
321#[cfg(feature = "advanced")]
322pub mod graph;
323#[cfg(feature = "workspace-mgmt")]
324#[deprecated(note = "Will be extracted to mockforge-import crate")]
325pub mod import;
326#[cfg(feature = "contracts")]
327pub mod incidents;
328/// `latency` was promoted to [`mockforge_foundation::latency`]; re-exported
329/// here so the legacy `mockforge_core::latency::*` path continues to resolve.
330pub(crate) use mockforge_foundation::latency;
331/// `intelligent_behavior` lives in `mockforge_intelligence::intelligent_behavior`
332/// (Issue #562 phase 2). Re-exported here so existing
333/// `crate::intelligent_behavior::*` call sites inside core (voice, reality,
334/// graph, ai_contract_diff, ai_studio, contract_drift, failure_analysis) and
335/// external `mockforge_core::intelligent_behavior::*` consumers keep
336/// compiling without churn. Data types had already been promoted to
337/// `mockforge-foundation` (A12/A17); this PR moved the LLM-bound engines too.
338pub use mockforge_intelligence::intelligent_behavior;
339pub mod lifecycle;
340#[cfg(feature = "advanced")]
341// Config types moved to mockforge-foundation (A14);
342// MultiTenantWorkspaceRegistry + WorkspaceRouter stay here (hold Workspace).
343pub mod multi_tenant;
344pub mod network_profiles;
345/// OData function call URI rewrite middleware
346pub mod odata_rewrite;
347pub mod openapi;
348/// Core's concrete [`mockforge_openapi::response_rewriter::ResponseRewriter`]
349/// implementation wrapping core's `templating::expand_tokens` +
350/// [`overrides::Overrides`]. Used by the OpenAPI router internally; consumer
351/// code rarely constructs this directly.
352pub mod openapi_rewriter;
353/// `openapi_routes` was moved to [`mockforge_openapi::openapi_routes`];
354/// re-exported here so every existing
355/// `mockforge_core::openapi_routes::{OpenApiRouteRegistry, ValidationOptions,
356/// create_registry_from_file, create_registry_from_json, ...}` path
357/// keeps resolving.
358pub(crate) use mockforge_openapi::openapi_routes;
359pub mod output_control;
360pub mod overrides;
361pub mod performance;
362/// `pillar_tracking` and `pillars` were promoted to
363/// [`mockforge_foundation::pillar_tracking`] and
364/// [`mockforge_foundation::pillars`] (Issue #562 phase 4) so AI modules
365/// living in `mockforge-intelligence` can record pillar usage without
366/// taking a dep on `mockforge-core`. Re-exported here so existing
367/// `mockforge_core::pillar_tracking::*` and `mockforge_core::pillars::*`
368/// call sites (10+ files: ui, registry-server, scenarios, http, cli,
369/// ai_studio, voice, contract_validation, workspace) keep resolving.
370pub use mockforge_foundation::{pillar_tracking, pillars};
371/// PR generation lives in `mockforge_intelligence::pr_generation` (Issue #562
372/// phase 1); re-exported here so existing `crate::pr_generation::*` call sites
373/// and external users that imported `mockforge_core::pr_generation::*` keep
374/// compiling without churn.
375pub use mockforge_intelligence::pr_generation;
376pub mod priority_handler;
377pub mod protocol_abstraction;
378/// Protocol server lifecycle trait for uniform server startup and shutdown
379pub mod protocol_server;
380/// Proxy module — migrating to `mockforge-proxy` crate.
381/// Import from `mockforge_proxy` instead of `mockforge_core::proxy`.
382#[deprecated(note = "Use mockforge_proxy crate directly")]
383pub mod proxy;
384/// `reality` lives in `mockforge_intelligence::reality` (Issue #562 phase 6).
385/// Re-exported here so existing `mockforge_core::reality::*` call sites
386/// keep compiling unchanged. The `apply_to_config` inherent method moved
387/// to `mockforge_core::reality_apply::apply_reality_to_server_config`
388/// (it pokes at concrete `ServerConfig` sub-structs and belongs in core).
389pub use mockforge_intelligence::reality;
390pub mod reality_apply;
391#[cfg(feature = "advanced")]
392pub mod reality_continuum;
393pub mod record_replay;
394pub mod request_capture;
395pub mod request_chaining;
396/// `request_fingerprint` was promoted to [`mockforge_openapi::request_fingerprint`];
397/// re-exported here for backwards compatibility.
398pub(crate) use mockforge_openapi::request_fingerprint;
399pub mod request_logger;
400#[cfg(feature = "scripting")]
401pub(crate) mod request_scripting;
402// Route chaos has been moved to mockforge-route-chaos crate to avoid Send issues
403// Import directly from mockforge-route-chaos crate instead of re-exporting here
404// to avoid circular dependency (mockforge-route-chaos depends on mockforge-core for config types)
405#[allow(dead_code)]
406pub(crate) mod persona_lifecycle_time;
407pub mod routing;
408/// Runtime validation for SDKs (request/response validation at runtime)
409pub mod runtime_validation;
410/// Scenario Studio - Visual editor for co-editing business flows
411#[cfg(feature = "advanced")]
412pub mod scenario_studio;
413#[cfg(feature = "advanced")]
414pub mod scenarios;
415/// `schema_diff` was promoted to [`mockforge_foundation::schema_diff`] so that
416/// leaf crates can use its `ValidationError` + diff helpers without depending
417/// on `mockforge-core`. Re-exported here for backwards compatibility.
418pub(crate) use mockforge_foundation::schema_diff;
419pub mod security;
420pub mod server_utils;
421/// Time travel and snapshot functionality for saving and restoring system states
422#[cfg(feature = "advanced")]
423pub mod snapshots;
424/// Re-export of the extracted [`mockforge_openapi::spec_parser`] module.
425pub(crate) use mockforge_openapi::spec_parser;
426pub mod stateful_handler;
427// sync_watcher stays in core.
428pub mod sync_watcher;
429/// Template expansion utilities (Send-safe, isolated from templating module)
430pub mod template_expansion;
431/// Template library system for shared templates, versioning, and marketplace
432pub mod template_library;
433pub mod templating;
434#[cfg(feature = "advanced")]
435pub mod time_travel;
436#[cfg(feature = "advanced")]
437pub mod time_travel_handler;
438/// Shared TLS utilities for building rustls server and client configurations.
439pub mod tls;
440pub mod traffic_shaping;
441pub mod validation;
442pub mod verification;
443/// `voice` was split in Issue #562 phase 7. Six leaf files (command_parser,
444/// conversation, hook_transpiler, spec_generator, workspace_scenario_generator,
445/// mod) moved to `mockforge_intelligence::voice`. `voice_workspace` (formerly
446/// `voice::workspace_builder`) stays here because it depends on multi_tenant,
447/// scenarios, workspace, contract_drift, and reality_continuum — all core-only.
448/// The `voice` shim consolidates both halves so external callers see one API.
449#[cfg(feature = "voice")]
450pub mod voice;
451#[cfg(feature = "voice")]
452pub mod voice_workspace;
453#[cfg(feature = "workspace-mgmt")]
454// Workspace family (Workspace, WorkspaceConfig, WorkspaceRegistry, etc.) —
455// 11k+ LoC surface area. Staying in core; future extraction would need
456// its own dedicated planning.
457pub mod workspace;
458#[cfg(feature = "workspace-mgmt")]
459pub mod workspace_import;
460#[cfg(feature = "workspace-mgmt")]
461pub mod workspace_persistence;
462pub mod ws_proxy;
463
464#[cfg(feature = "advanced")]
465pub use ab_testing::{
466 apply_variant_to_response, select_variant, ABTestConfig, ABTestReport,
467 ABTestingMiddlewareState, MockVariant, VariantAllocation, VariantAnalytics, VariantComparison,
468 VariantManager, VariantSelectionStrategy,
469};
470#[cfg(feature = "ai")]
471#[deprecated(note = "Will be extracted to mockforge-intelligence crate")]
472pub use behavioral_cloning::{
473 AmplificationScope, BehavioralSequence, EdgeAmplificationConfig, EdgeAmplifier,
474 EndpointProbabilityModel, ErrorPattern, LatencyDistribution, PayloadVariation,
475 ProbabilisticModel, SequenceLearner, SequenceStep,
476};
477pub use chain_execution::{ChainExecutionEngine, ChainExecutionResult, ChainExecutionStatus};
478#[deprecated(note = "Use mockforge_chaos::core_chaos_utilities instead")]
479pub use chaos_utilities::{ChaosConfig, ChaosEngine, ChaosResult, ChaosStatistics};
480pub use conditions::{evaluate_condition, ConditionContext, ConditionError};
481pub use config::{
482 apply_env_overrides, load_config, load_config_with_fallback, save_config, ApiKeyConfig,
483 AuthConfig, ServerConfig,
484};
485#[cfg(feature = "advanced")]
486pub use consistency::{
487 ConsistencyEngine, EntityState, ProtocolState, SessionInfo, StateChangeEvent, UnifiedState,
488};
489pub(crate) use custom_fixture::CustomFixtureLoader;
490pub use data_source::{
491 DataSource, DataSourceConfig, DataSourceContent, DataSourceFactory, DataSourceManager,
492 DataSourceType, GitDataSource, HttpDataSource, LocalDataSource,
493};
494pub use deceptive_canary::{
495 CanaryRoutingStrategy, CanaryStats, DeceptiveCanaryConfig, DeceptiveCanaryRouter,
496 TeamIdentifiers,
497};
498pub use error::{Error, Result};
499pub use failure_analysis::{
500 ContributingFactor, FailureContext, FailureContextCollector, FailureNarrative,
501 FailureNarrativeGenerator, NarrativeFrame,
502};
503#[deprecated(note = "Use mockforge_chaos::core_failure_injection instead")]
504pub(crate) use failure_injection::FailureInjector;
505pub use fidelity::{FidelityCalculator, FidelityScore, SampleComparator, SchemaComparator};
506pub use generate_config::{
507 discover_config_file, load_generate_config, load_generate_config_with_fallback,
508 save_generate_config, BarrelType, GenerateConfig, GenerateOptions, InputConfig, OutputConfig,
509 PluginConfig,
510};
511#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
512pub use git_watch::{GitWatchConfig, GitWatchService};
513#[cfg(feature = "advanced")]
514pub use graph::{
515 builder::GraphBuilder, relationships, ClusterType, EdgeType, GraphCluster, GraphData,
516 GraphEdge, GraphNode, NodeType, Protocol as GraphProtocol,
517};
518pub(crate) use latency::LatencyProfile;
519pub use lifecycle::{
520 LifecycleHook, LifecycleHookRegistry, MockLifecycleEvent, RequestContext, ResponseContext,
521 ServerLifecycleEvent,
522};
523#[cfg(feature = "advanced")]
524pub use multi_tenant::{
525 MultiTenantConfig, MultiTenantWorkspaceRegistry, RoutingStrategy, TenantWorkspace,
526 WorkspaceContext, WorkspaceRouter, WorkspaceStats,
527};
528#[deprecated(note = "Use mockforge_chaos::core_network_profiles instead")]
529pub use network_profiles::{NetworkProfile, NetworkProfileCatalog};
530pub(crate) use openapi::OpenApiSpec;
531pub use output_control::{
532 apply_banner, apply_extension, apply_file_naming_template, build_file_naming_context,
533 process_generated_file, BarrelGenerator, FileNamingContext, GeneratedFile,
534};
535pub use overrides::{OverrideMode, OverrideRule, Overrides, PatchOp};
536pub use pillars::{Pillar, PillarMetadata};
537pub use priority_handler::{
538 CustomFixtureStep, FailureInjectionStep, GenerationResult, MockGenerator, MockResponse,
539 PriorityHttpHandler, PriorityRequest, PriorityResponse, PriorityStep, SimpleMockGenerator,
540};
541pub use protocol_abstraction::{
542 MessagePattern, MiddlewareAction, MiddlewareChain, Protocol, ProtocolMiddleware,
543 ProtocolRequest, ProtocolResponse, RequestMatcher, ResponseStatus, SpecOperation, SpecRegistry,
544 ValidationError as ProtocolValidationError, ValidationResult as ProtocolValidationResult,
545};
546#[deprecated(note = "Will be extracted to mockforge-proxy crate")]
547pub use proxy::{ProxyConfig, ProxyHandler, ProxyResponse};
548pub use reality::{PresetMetadata, RealityConfig, RealityEngine, RealityLevel, RealityPreset};
549#[cfg(feature = "advanced")]
550pub use reality_continuum::{
551 ContinuumConfig, ContinuumRule, MergeStrategy, RealityContinuumEngine, ResponseBlender,
552 TimeSchedule, TransitionCurve, TransitionMode,
553};
554pub use record_replay::{
555 clean_old_fixtures, list_fixtures, list_ready_fixtures, list_smoke_endpoints, RecordHandler,
556 RecordReplayHandler, RecordedRequest, ReplayHandler,
557};
558pub use request_chaining::{
559 ChainConfig, ChainContext, ChainDefinition, ChainExecutionContext, ChainLink, ChainRequest,
560 ChainResponse, ChainStore, ChainTemplatingContext, RequestChainRegistry,
561};
562pub(crate) use request_fingerprint::{RequestFingerprint, ResponsePriority, ResponseSource};
563pub use request_logger::{
564 create_grpc_log_entry, create_http_log_entry, create_http_log_entry_with_query,
565 create_websocket_log_entry, get_global_logger, init_global_logger, log_request_global,
566 CentralizedRequestLogger, RequestLogEntry,
567};
568// Route chaos types moved to mockforge-route-chaos crate
569// Import directly: use mockforge_route_chaos::{RouteChaosInjector, RouteFaultResponse, RouteMatcher};
570pub use routing::{HttpMethod, Route, RouteRegistry};
571pub use runtime_validation::{
572 RuntimeValidationError, RuntimeValidationResult, RuntimeValidatorConfig, SchemaMetadata,
573};
574#[cfg(feature = "advanced")]
575pub use scenario_studio::{
576 ConditionOperator, FlowCondition, FlowConnection, FlowDefinition, FlowExecutionResult,
577 FlowExecutor, FlowPosition, FlowStep, FlowStepResult, FlowType, FlowVariant, StepType,
578};
579#[cfg(feature = "advanced")]
580pub use scenarios::types::StepResult;
581#[cfg(feature = "advanced")]
582pub use scenarios::{
583 ScenarioDefinition, ScenarioExecutor, ScenarioParameter, ScenarioRegistry, ScenarioResult,
584 ScenarioStep,
585};
586pub use server_utils::errors::{json_error, json_success};
587pub use server_utils::{create_socket_addr, localhost_socket_addr, wildcard_socket_addr};
588#[cfg(feature = "advanced")]
589pub use snapshots::{SnapshotComponents, SnapshotManager, SnapshotManifest, SnapshotMetadata};
590pub use stateful_handler::{
591 ResourceIdExtract, StateInfo, StateResponse, StatefulConfig, StatefulResponse,
592 StatefulResponseHandler, TransitionTrigger,
593};
594#[cfg(feature = "workspace-mgmt")]
595pub use sync_watcher::{FileChange, SyncEvent, SyncService, SyncWatcher};
596pub use template_library::{
597 TemplateLibrary, TemplateLibraryEntry, TemplateLibraryManager, TemplateMarketplace,
598 TemplateMetadata, TemplateVersion,
599};
600pub use templating::{expand_str, expand_tokens};
601#[cfg(feature = "advanced")]
602pub use time_travel::{
603 cron::{CronJob, CronJobAction, CronScheduler},
604 get_global_clock, is_time_travel_enabled, now as time_travel_now, register_global_clock,
605 unregister_global_clock, RepeatConfig, ResponseScheduler, ScheduledResponse, TimeScenario,
606 TimeTravelConfig, TimeTravelManager, TimeTravelStatus, VirtualClock,
607};
608#[cfg(feature = "advanced")]
609pub use time_travel_handler::{
610 time_travel_middleware, ScheduledResponseWrapper, TimeTravelHandler,
611};
612#[deprecated(note = "Use mockforge_chaos::core_traffic_shaping instead")]
613pub use traffic_shaping::{BandwidthConfig, BurstLossConfig, TrafficShaper, TrafficShapingConfig};
614pub use uuid::Uuid;
615pub use validation::{validate_openapi_operation_security, validate_openapi_security, Validator};
616pub use verification::{
617 matches_verification_pattern, verify_at_least, verify_never, verify_requests, verify_sequence,
618 VerificationCount, VerificationRequest, VerificationResult,
619};
620#[cfg(feature = "voice")]
621pub use voice::{
622 ConversationContext, ConversationManager, ConversationState, GeneratedWorkspaceScenario,
623 HookTranspiler, ParsedCommand, ParsedWorkspaceScenario, VoiceCommandParser, VoiceSpecGenerator,
624 WorkspaceConfigSummary, WorkspaceScenarioGenerator,
625};
626#[cfg(feature = "workspace-mgmt")]
627pub use workspace::promotion_trait::PromotionService;
628#[cfg(feature = "workspace-mgmt")]
629pub use workspace::{EntityId, Folder, MockRequest, Workspace, WorkspaceConfig, WorkspaceRegistry};
630#[cfg(feature = "workspace-mgmt")]
631pub use workspace_import::{
632 create_workspace_from_curl, create_workspace_from_har, create_workspace_from_insomnia,
633 create_workspace_from_postman, import_postman_to_existing_workspace,
634 import_postman_to_workspace, WorkspaceImportConfig, WorkspaceImportResult,
635};
636#[cfg(feature = "workspace-mgmt")]
637pub use workspace_persistence::WorkspacePersistence;
638pub use ws_proxy::{WsProxyConfig, WsProxyHandler, WsProxyRule};
639// Note: ValidationError and ValidationResult from spec_parser conflict with schema_diff::ValidationError
640// Use qualified paths: spec_parser::ValidationError, spec_parser::ValidationResult
641
642// ── Organized module facades (R10) ───────────────────────────────────────────
643// These provide a namespaced access path for new code. Existing flat re-exports
644// above remain for backward compatibility. Prefer these for new imports.
645
646/// Routing, route matching, and OpenAPI route generation
647pub mod routes {
648 pub use crate::openapi::{
649 OpenApiOperation, OpenApiRoute, OpenApiSchema, OpenApiSecurityRequirement, OpenApiSpec,
650 };
651 pub use crate::openapi_routes::{
652 create_registry_from_file, create_registry_from_json, OpenApiRouteRegistry,
653 ValidationOptions,
654 };
655 pub use crate::routing::{HttpMethod, Route, RouteRegistry};
656}
657
658/// Middleware, protocol abstractions, and request processing
659pub mod middleware {
660 pub use crate::latency::LatencyInjector;
661 pub use crate::overrides::{OverrideMode, OverrideRule, Overrides, PatchOp};
662 pub use crate::protocol_abstraction::{
663 MessagePattern, MiddlewareAction, MiddlewareChain, Protocol, ProtocolMiddleware,
664 ProtocolRequest, ProtocolResponse, RequestMatcher, ResponseStatus, SpecOperation,
665 SpecRegistry,
666 };
667}
668
669/// Mock response generation and priority handling
670pub mod generation {
671 pub use crate::priority_handler::{
672 CustomFixtureStep, FailureInjectionStep, GenerationResult, MockGenerator, MockResponse,
673 PriorityHttpHandler, PriorityRequest, PriorityResponse, PriorityStep, SimpleMockGenerator,
674 };
675 pub use crate::stateful_handler::{StatefulConfig, StatefulResponse, StatefulResponseHandler};
676}
677
678/// Request/response validation
679pub mod validate {
680 pub use crate::runtime_validation::{
681 RuntimeValidationError, RuntimeValidationResult, RuntimeValidatorConfig, SchemaMetadata,
682 };
683 pub use crate::spec_parser::{GraphQLValidator, OpenApiValidator, SpecFormat};
684 pub use crate::validation::{
685 validate_openapi_operation_security, validate_openapi_security, Validator,
686 };
687 pub use crate::verification::{
688 matches_verification_pattern, verify_at_least, verify_never, verify_requests,
689 verify_sequence, VerificationCount, VerificationRequest, VerificationResult,
690 };
691}
692
693/// Fixture loading utilities
694pub mod fixtures {
695 pub use crate::custom_fixture::{CustomFixture, CustomFixtureLoader, NestedFixture};
696 pub use crate::fixture_store::{
697 load_fixtures_from_dir, FixtureFileFormat, FixtureFileGranularity, FixtureLoadErrorMode,
698 FixtureLoadOptions,
699 };
700 pub use crate::record_replay::{
701 RecordHandler, RecordReplayHandler, RecordedRequest, ReplayHandler,
702 };
703}
704
705/// Core configuration for MockForge
706#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
707#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
708#[serde(default)]
709pub struct Config {
710 /// Enable latency simulation
711 pub latency_enabled: bool,
712 /// Enable failure simulation
713 pub failures_enabled: bool,
714 /// Enable response overrides
715 pub overrides_enabled: bool,
716 /// Enable traffic shaping (bandwidth + burst loss)
717 pub traffic_shaping_enabled: bool,
718 /// Failure injection configuration
719 pub failure_config: Option<failure_injection::FailureConfig>,
720 /// Proxy configuration
721 pub proxy: Option<ProxyConfig>,
722 /// Default latency profile
723 pub default_latency: LatencyProfile,
724 /// Traffic shaping configuration
725 pub traffic_shaping: TrafficShapingConfig,
726 /// Random chaos configuration
727 pub chaos_random: Option<ChaosConfig>,
728 /// Maximum number of request logs to keep in memory (default: 1000)
729 /// Helps prevent unbounded memory growth from request logging
730 pub max_request_logs: usize,
731 /// Time travel configuration for temporal testing
732 pub time_travel: TimeTravelConfig,
733}
734
735/// Default configuration
736impl Default for Config {
737 fn default() -> Self {
738 Self {
739 latency_enabled: true,
740 failures_enabled: false,
741 overrides_enabled: true,
742 traffic_shaping_enabled: false,
743 failure_config: None,
744 proxy: None,
745 default_latency: LatencyProfile::default(),
746 traffic_shaping: TrafficShapingConfig::default(),
747 chaos_random: None,
748 max_request_logs: 1000, // Default: keep last 1000 requests
749 time_travel: TimeTravelConfig::default(),
750 }
751 }
752}
753
754impl Config {
755 /// Create a ChaosEngine from the chaos_random configuration if enabled
756 pub fn create_chaos_engine(&self) -> Option<ChaosEngine> {
757 self.chaos_random.as_ref().map(|config| ChaosEngine::new(config.clone()))
758 }
759
760 /// Check if random chaos mode is enabled
761 pub fn is_chaos_random_enabled(&self) -> bool {
762 self.chaos_random.as_ref().map(|c| c.enabled).unwrap_or(false)
763 }
764}
765
766#[cfg(test)]
767mod tests {
768 use super::*;
769
770 #[test]
771 fn test_config_default() {
772 let config = Config::default();
773 assert!(config.latency_enabled);
774 assert!(!config.failures_enabled);
775 assert!(config.overrides_enabled);
776 assert!(!config.traffic_shaping_enabled);
777 assert!(config.failure_config.is_none());
778 assert!(config.proxy.is_none());
779 }
780
781 #[test]
782 fn test_config_serialization() {
783 let config = Config::default();
784 let json = serde_json::to_string(&config).unwrap();
785 assert!(json.contains("latency_enabled"));
786 assert!(json.contains("failures_enabled"));
787 }
788
789 #[test]
790 fn test_config_deserialization() {
791 // Use default config and modify
792 let config = Config {
793 latency_enabled: false,
794 failures_enabled: true,
795 ..Default::default()
796 };
797
798 // Serialize and deserialize
799 let json = serde_json::to_string(&config).unwrap();
800 let deserialized: Config = serde_json::from_str(&json).unwrap();
801
802 assert!(!deserialized.latency_enabled);
803 assert!(deserialized.failures_enabled);
804 assert!(deserialized.overrides_enabled);
805 }
806
807 #[test]
808 fn test_config_with_custom_values() {
809 let config = Config {
810 latency_enabled: false,
811 failures_enabled: true,
812 ..Default::default()
813 };
814
815 assert!(!config.latency_enabled);
816 assert!(config.failures_enabled);
817 }
818}