mockforge-core 0.3.115

Shared logic for MockForge - routing, validation, latency, proxy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
//! # MockForge Core
//!
//! Core functionality and shared logic for the MockForge mocking framework.
//!
//! This crate provides the foundational building blocks used across all MockForge protocols
//! (HTTP, WebSocket, gRPC, GraphQL). It can be used as a library to programmatically create
//! and manage mock servers, or to build custom mocking solutions.
//!
//! ## Overview
//!
//! MockForge Core includes:
//!
//! - **Routing & Validation**: OpenAPI-based route registration and request validation
//! - **Request/Response Processing**: Template expansion, data generation, and transformation
//! - **Chaos Engineering**: Latency injection, failure simulation, and traffic shaping
//! - **Proxy & Hybrid Mode**: Forward requests to real backends with intelligent fallback
//! - **Request Chaining**: Multi-step request workflows with context passing
//! - **Workspace Management**: Organize and persist mock configurations
//! - **Observability**: Request logging, metrics collection, and tracing
//!
//! ## Quick Start: Embedding MockForge
//!
//! ### Creating a Simple HTTP Mock Server
//!
//! ```rust,no_run
//! use mockforge_core::{
//!     Config, LatencyProfile, OpenApiRouteRegistry, OpenApiSpec, Result, ValidationOptions,
//! };
//!
//! #[tokio::main]
//! async fn main() -> Result<()> {
//!     // Load OpenAPI specification
//!     let spec = OpenApiSpec::from_file("api.json").await?;
//!
//!     // Create route registry with validation
//!     let registry = OpenApiRouteRegistry::new_with_options(spec, ValidationOptions::default());
//!
//!     // Configure core features
//!     let config = Config {
//!         latency_enabled: true,
//!         failures_enabled: false,
//!         default_latency: LatencyProfile::with_normal_distribution(400, 120.0),
//!         ..Default::default()
//!     };
//!
//!     // Build your HTTP server with the registry
//!     // (See mockforge-http crate for router building)
//!
//!     Ok(())
//! }
//! ```
//!
//! ### Request Chaining
//!
//! Chain multiple requests together with shared context:
//!
//! ```rust,no_run
//! use mockforge_core::{
//!     ChainConfig, ChainDefinition, ChainLink, ChainRequest, RequestChainRegistry, Result,
//! };
//! use mockforge_core::request_chaining::RequestBody;
//! use serde_json::json;
//! use std::collections::HashMap;
//!
//! # async fn example() -> Result<()> {
//! let registry = RequestChainRegistry::new(ChainConfig::default());
//!
//! // Define a chain: create user → add to group → verify membership
//! let chain = ChainDefinition {
//!     id: "user_onboarding".to_string(),
//!     name: "User Onboarding".to_string(),
//!     description: Some("Create user → add to group".to_string()),
//!     config: ChainConfig {
//!         enabled: true,
//!         ..ChainConfig::default()
//!     },
//!     links: vec![
//!         ChainLink {
//!             request: ChainRequest {
//!                 id: "create_user".to_string(),
//!                 method: "POST".to_string(),
//!                 url: "https://api.example.com/users".to_string(),
//!                 headers: HashMap::new(),
//!                 body: Some(RequestBody::json(json!({"name": "{{faker.name}}"}))),
//!                 depends_on: Vec::new(),
//!                 timeout_secs: None,
//!                 expected_status: None,
//!                 scripting: None,
//!             },
//!             extract: HashMap::from([("user_id".to_string(), "create_user.body.id".to_string())]),
//!             store_as: Some("create_user_response".to_string()),
//!         },
//!         ChainLink {
//!             request: ChainRequest {
//!                 id: "add_to_group".to_string(),
//!                 method: "POST".to_string(),
//!                 url: "https://api.example.com/groups/{{user_id}}/members".to_string(),
//!                 headers: HashMap::new(),
//!                 body: None,
//!                 depends_on: vec!["create_user".to_string()],
//!                 timeout_secs: None,
//!                 expected_status: None,
//!                 scripting: None,
//!             },
//!             extract: HashMap::new(),
//!             store_as: None,
//!         },
//!     ],
//!     variables: HashMap::new(),
//!     tags: vec!["onboarding".to_string()],
//! };
//!
//! registry.store().register_chain(chain).await?;
//! # Ok(())
//! # }
//! ```
//!
//! ### Latency & Failure Injection
//!
//! Simulate realistic network conditions and errors:
//!
//! ```rust,no_run
//! use mockforge_core::{LatencyProfile, FailureConfig, create_failure_injector};
//!
//! // Configure latency simulation
//! let latency = LatencyProfile::with_normal_distribution(400, 120.0)
//!     .with_min_ms(100)
//!     .with_max_ms(800);
//!
//! // Configure failure injection
//! let failure_config = FailureConfig {
//!     global_error_rate: 0.05, // 5% of requests fail
//!     default_status_codes: vec![500, 502, 503],
//!     ..Default::default()
//! };
//!
//! let injector = create_failure_injector(true, Some(failure_config));
//! ```
//!
//! ## Key Modules
//!
//! ### OpenAPI Support
//! - [`openapi`]: Parse and work with OpenAPI specifications
//! - [`openapi_routes`]: Register routes from OpenAPI specs with validation
//! - [`validation`]: Request/response validation against schemas
//!
//! ### Request Processing
//! - [`routing`]: Route matching and registration
//! - [`templating`]: Template variable expansion ({{uuid}}, {{now}}, etc.)
//! - [`request_chaining`]: Multi-step request workflows
//! - [`overrides`]: Dynamic request/response modifications
//!
//! ### Chaos Engineering
//! - [`latency`]: Latency injection with configurable profiles
//! - [`failure_injection`]: Simulate service failures and errors
//! - [`traffic_shaping`]: Bandwidth limiting and packet loss
//!
//! ### Proxy & Hybrid
//! - [`proxy`]: Forward requests to upstream services
//! - [`ws_proxy`]: WebSocket proxy with message transformation
//!
//! ### Persistence & Import
//! - [`workspace`]: Workspace management for organizing mocks
//! - [`workspace_import`]: Import from Postman, Insomnia, cURL, HAR
//! - [`record_replay`]: Record real requests and replay as fixtures
//!
//! ### Observability
//! - [`request_logger`]: Centralized request logging
//! - [`performance`]: Performance metrics and profiling
//!
//! ## Feature Flags
//!
//! This crate supports several optional features:
//!
//! - `openapi`: OpenAPI specification support (enabled by default)
//! - `validation`: Request/response validation (enabled by default)
//! - `templating`: Template expansion (enabled by default)
//! - `chaos`: Chaos engineering features (enabled by default)
//! - `proxy`: Proxy and hybrid mode (enabled by default)
//! - `workspace`: Workspace management (enabled by default)
//!
//! ## Examples
//!
//! See the [examples directory](https://github.com/SaaSy-Solutions/mockforge/tree/main/examples)
//! for complete working examples.
//!
//! ## Related Crates
//!
//! - [`mockforge-http`](https://docs.rs/mockforge-http): HTTP/REST mock server
//! - [`mockforge-grpc`](https://docs.rs/mockforge-grpc): gRPC mock server
//! - [`mockforge-ws`](https://docs.rs/mockforge-ws): WebSocket mock server
//! - [`mockforge-graphql`](https://docs.rs/mockforge-graphql): GraphQL mock server
//! - [`mockforge-plugin-core`](https://docs.rs/mockforge-plugin-core): Plugin development
//! - [`mockforge-data`](https://docs.rs/mockforge-data): Synthetic data generation
//!
//! ## Documentation
//!
//! - [MockForge Book](https://docs.mockforge.dev/)
//! - [API Reference](https://docs.rs/mockforge-core)
//! - [GitHub Repository](https://github.com/SaaSy-Solutions/mockforge)

#![allow(deprecated)]

#[cfg(feature = "advanced")]
pub mod ab_testing;
#[cfg(feature = "ai")]
#[deprecated(note = "Will be extracted to mockforge-intelligence crate")]
pub mod ai_contract_diff;
#[cfg(feature = "ai")]
#[deprecated(note = "Will be extracted to mockforge-intelligence crate")]
pub mod ai_response;
/// AI Studio - Unified AI Copilot for all AI-powered features
#[cfg(feature = "ai")]
#[deprecated(note = "Will be extracted to mockforge-intelligence crate")]
pub mod ai_studio;
/// Behavioral cloning of backends - learn from recorded traffic to create realistic mock behavior
#[cfg(feature = "ai")]
#[deprecated(note = "Will be extracted to mockforge-intelligence crate")]
pub mod behavioral_cloning;
#[cfg(feature = "advanced")]
#[deprecated(note = "Will be extracted to mockforge-intelligence crate")]
pub mod behavioral_economics;
#[allow(dead_code)]
pub(crate) mod cache;
pub mod chain_execution;
pub mod chaos_utilities;
#[cfg(feature = "advanced")]
#[deprecated(note = "Will be extracted to mockforge-import crate")]
pub mod codegen;
/// Collection export utilities for exporting mock data in various formats
#[allow(dead_code)]
pub(crate) mod collection_export;
pub mod conditions;
pub mod config;
/// Connection pooling for HTTP clients with health checks and idle management
#[allow(dead_code)]
pub(crate) mod connection_pool;
/// Cross-protocol consistency engine for unified state across all protocols
#[cfg(feature = "advanced")]
pub mod consistency;
#[cfg(feature = "contracts")]
#[deprecated(note = "Will be extracted to mockforge-contracts crate")]
/// Consumer-driven contracts for tracking usage and detecting consumer-specific breaking changes
pub mod consumer_contracts;
#[cfg(feature = "contracts")]
#[deprecated(note = "Will be extracted to mockforge-contracts crate")]
/// Contract validation for ensuring API contracts match specifications
pub mod contract_drift;
#[cfg(feature = "contracts")]
#[deprecated(note = "Will be extracted to mockforge-contracts crate")]
/// Contract validation for ensuring API contracts match specifications
pub mod contract_validation;
/// Contract webhooks for notifying external systems about contract changes
#[cfg(feature = "contracts")]
#[allow(dead_code)]
pub(crate) mod contract_webhooks;
pub mod custom_fixture;
/// Data source abstraction for loading test data from multiple sources
pub mod data_source;
/// Deceptive canary mode for routing team traffic to deceptive deploys
pub mod deceptive_canary;
/// Docker Compose integration for containerized mock deployments
#[allow(dead_code)]
pub(crate) mod docker_compose;
#[cfg(feature = "contracts")]
#[deprecated(note = "Will be extracted to mockforge-contracts crate")]
/// GitOps integration for drift budget violations
pub mod drift_gitops;
#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
pub mod encryption;
pub mod error;
pub mod failure_analysis;
pub mod failure_injection;
pub mod fidelity;
/// Generic fixture loading utilities shared across protocol crates
pub mod fixture_store;
pub mod generate_config;
#[allow(dead_code)]
pub(crate) mod generative_schema;
#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
pub mod git_watch;
#[cfg(feature = "advanced")]
pub mod graph;
#[cfg(feature = "workspace-mgmt")]
#[deprecated(note = "Will be extracted to mockforge-import crate")]
pub mod import;
#[cfg(feature = "contracts")]
pub mod incidents;
#[cfg(feature = "ai")]
#[deprecated(note = "Will be extracted to mockforge-intelligence crate")]
pub mod intelligent_behavior;
pub mod latency;
pub mod lifecycle;
#[cfg(feature = "advanced")]
#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
pub mod multi_tenant;
pub mod network_profiles;
/// OData function call URI rewrite middleware
pub mod odata_rewrite;
pub mod openapi;
pub mod openapi_routes;
pub mod output_control;
pub mod overrides;
pub mod performance;
/// Pillar usage tracking utilities
pub mod pillar_tracking;
/// Pillar metadata system for compile-time pillar tagging
pub mod pillars;
#[cfg(feature = "contracts")]
pub mod pr_generation;
pub mod priority_handler;
pub mod protocol_abstraction;
/// Protocol server lifecycle trait for uniform server startup and shutdown
pub mod protocol_server;
#[deprecated(note = "Will be extracted to mockforge-proxy crate")]
pub mod proxy;
pub mod reality;
#[cfg(feature = "advanced")]
pub mod reality_continuum;
pub mod record_replay;
pub mod request_capture;
pub mod request_chaining;
pub mod request_fingerprint;
pub mod request_logger;
#[cfg(feature = "scripting")]
pub(crate) mod request_scripting;
// Route chaos has been moved to mockforge-route-chaos crate to avoid Send issues
// Import directly from mockforge-route-chaos crate instead of re-exporting here
// to avoid circular dependency (mockforge-route-chaos depends on mockforge-core for config types)
#[allow(dead_code)]
pub(crate) mod persona_lifecycle_time;
pub mod routing;
/// Runtime validation for SDKs (request/response validation at runtime)
pub mod runtime_validation;
/// Scenario Studio - Visual editor for co-editing business flows
#[cfg(feature = "advanced")]
pub mod scenario_studio;
#[cfg(feature = "advanced")]
pub mod scenarios;
#[deprecated(note = "Will be extracted to mockforge-contracts crate")]
pub mod schema_diff;
pub mod security;
pub mod server_utils;
/// Time travel and snapshot functionality for saving and restoring system states
#[cfg(feature = "advanced")]
pub mod snapshots;
pub mod spec_parser;
pub mod stateful_handler;
#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
pub mod sync_watcher;
/// Template expansion utilities (Send-safe, isolated from templating module)
pub mod template_expansion;
/// Template library system for shared templates, versioning, and marketplace
pub mod template_library;
pub mod templating;
#[cfg(feature = "advanced")]
pub mod time_travel;
#[cfg(feature = "advanced")]
pub mod time_travel_handler;
/// Shared TLS utilities for building rustls server and client configurations.
pub mod tls;
pub mod traffic_shaping;
pub mod validation;
pub mod verification;
#[cfg(feature = "voice")]
pub mod voice;
#[cfg(feature = "workspace-mgmt")]
#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
pub mod workspace;
#[cfg(feature = "workspace-mgmt")]
#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
pub mod workspace_import;
#[cfg(feature = "workspace-mgmt")]
#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
pub mod workspace_persistence;
pub mod ws_proxy;

#[cfg(feature = "advanced")]
pub use ab_testing::{
    apply_variant_to_response, select_variant, ABTestConfig, ABTestReport,
    ABTestingMiddlewareState, MockVariant, VariantAllocation, VariantAnalytics, VariantComparison,
    VariantManager, VariantSelectionStrategy,
};
#[cfg(feature = "ai")]
#[deprecated(note = "Will be extracted to mockforge-intelligence crate")]
pub use behavioral_cloning::{
    AmplificationScope, BehavioralSequence, EdgeAmplificationConfig, EdgeAmplifier,
    EndpointProbabilityModel, ErrorPattern, LatencyDistribution, PayloadVariation,
    ProbabilisticModel, SequenceLearner, SequenceStep,
};
pub use chain_execution::{ChainExecutionEngine, ChainExecutionResult, ChainExecutionStatus};
#[deprecated(note = "Use mockforge_chaos::core_chaos_utilities instead")]
pub use chaos_utilities::{ChaosConfig, ChaosEngine, ChaosResult, ChaosStatistics};
pub use conditions::{evaluate_condition, ConditionContext, ConditionError};
pub use config::{
    apply_env_overrides, load_config, load_config_with_fallback, save_config, ApiKeyConfig,
    AuthConfig, ServerConfig,
};
#[cfg(feature = "advanced")]
pub use consistency::{
    ConsistencyEngine, EntityState, ProtocolState, SessionInfo, StateChangeEvent, UnifiedState,
};
pub use custom_fixture::{CustomFixture, CustomFixtureLoader, NestedFixture};
pub use data_source::{
    DataSource, DataSourceConfig, DataSourceContent, DataSourceFactory, DataSourceManager,
    DataSourceType, GitDataSource, HttpDataSource, LocalDataSource,
};
pub use deceptive_canary::{
    CanaryRoutingStrategy, CanaryStats, DeceptiveCanaryConfig, DeceptiveCanaryRouter,
    TeamIdentifiers,
};
pub use error::{Error, Result};
pub use failure_analysis::{
    ContributingFactor, FailureContext, FailureContextCollector, FailureNarrative,
    FailureNarrativeGenerator, NarrativeFrame,
};
#[deprecated(note = "Use mockforge_chaos::core_failure_injection instead")]
pub use failure_injection::{
    create_failure_injector, FailureConfig, FailureInjector, TagFailureConfig,
};
pub use fidelity::{FidelityCalculator, FidelityScore, SampleComparator, SchemaComparator};
pub use generate_config::{
    discover_config_file, load_generate_config, load_generate_config_with_fallback,
    save_generate_config, BarrelType, GenerateConfig, GenerateOptions, InputConfig, OutputConfig,
    PluginConfig,
};
#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
pub use git_watch::{GitWatchConfig, GitWatchService};
#[cfg(feature = "advanced")]
pub use graph::{
    builder::GraphBuilder, relationships, ClusterType, EdgeType, GraphCluster, GraphData,
    GraphEdge, GraphNode, NodeType, Protocol as GraphProtocol,
};
pub use latency::LatencyProfile;
pub use lifecycle::{
    LifecycleHook, LifecycleHookRegistry, MockLifecycleEvent, RequestContext, ResponseContext,
    ServerLifecycleEvent,
};
#[cfg(feature = "advanced")]
#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
pub use multi_tenant::{
    MultiTenantConfig, MultiTenantWorkspaceRegistry, RoutingStrategy, TenantWorkspace,
    WorkspaceContext, WorkspaceRouter, WorkspaceStats,
};
#[deprecated(note = "Use mockforge_chaos::core_network_profiles instead")]
pub use network_profiles::{NetworkProfile, NetworkProfileCatalog};
pub use openapi::{
    OpenApiOperation, OpenApiRoute, OpenApiSchema, OpenApiSecurityRequirement, OpenApiSpec,
};
pub use openapi_routes::{
    create_registry_from_file, create_registry_from_json, OpenApiRouteRegistry, ValidationOptions,
};
pub use output_control::{
    apply_banner, apply_extension, apply_file_naming_template, build_file_naming_context,
    process_generated_file, BarrelGenerator, FileNamingContext, GeneratedFile,
};
pub use overrides::{OverrideMode, OverrideRule, Overrides, PatchOp};
pub use pillars::{Pillar, PillarMetadata};
pub use priority_handler::{
    CustomFixtureStep, FailureInjectionStep, GenerationResult, MockGenerator, MockResponse,
    PriorityHttpHandler, PriorityRequest, PriorityResponse, PriorityStep, SimpleMockGenerator,
};
pub use protocol_abstraction::{
    MessagePattern, MiddlewareAction, MiddlewareChain, Protocol, ProtocolMiddleware,
    ProtocolRequest, ProtocolResponse, RequestMatcher, ResponseStatus, SpecOperation, SpecRegistry,
    ValidationError as ProtocolValidationError, ValidationResult as ProtocolValidationResult,
};
#[deprecated(note = "Will be extracted to mockforge-proxy crate")]
pub use proxy::{ProxyConfig, ProxyHandler, ProxyResponse};
pub use reality::{PresetMetadata, RealityConfig, RealityEngine, RealityLevel, RealityPreset};
#[cfg(feature = "advanced")]
pub use reality_continuum::{
    ContinuumConfig, ContinuumRule, MergeStrategy, RealityContinuumEngine, ResponseBlender,
    TimeSchedule, TransitionCurve, TransitionMode,
};
pub use record_replay::{
    clean_old_fixtures, list_fixtures, list_ready_fixtures, list_smoke_endpoints, RecordHandler,
    RecordReplayHandler, RecordedRequest, ReplayHandler,
};
pub use request_chaining::{
    ChainConfig, ChainContext, ChainDefinition, ChainExecutionContext, ChainLink, ChainRequest,
    ChainResponse, ChainStore, ChainTemplatingContext, RequestChainRegistry,
};
pub use request_fingerprint::{
    RequestFingerprint, RequestHandlerResult, ResponsePriority, ResponseSource,
};
pub use request_logger::{
    create_grpc_log_entry, create_http_log_entry, create_http_log_entry_with_query,
    create_websocket_log_entry, get_global_logger, init_global_logger, log_request_global,
    CentralizedRequestLogger, RequestLogEntry,
};
// Route chaos types moved to mockforge-route-chaos crate
// Import directly: use mockforge_route_chaos::{RouteChaosInjector, RouteFaultResponse, RouteMatcher};
pub use routing::{HttpMethod, Route, RouteRegistry};
pub use runtime_validation::{
    RuntimeValidationError, RuntimeValidationResult, RuntimeValidatorConfig, SchemaMetadata,
};
#[cfg(feature = "advanced")]
pub use scenario_studio::{
    ConditionOperator, FlowCondition, FlowConnection, FlowDefinition, FlowExecutionResult,
    FlowExecutor, FlowPosition, FlowStep, FlowStepResult, FlowType, FlowVariant, StepType,
};
#[cfg(feature = "advanced")]
pub use scenarios::types::StepResult;
#[cfg(feature = "advanced")]
pub use scenarios::{
    ScenarioDefinition, ScenarioExecutor, ScenarioParameter, ScenarioRegistry, ScenarioResult,
    ScenarioStep,
};
#[cfg(feature = "contracts")]
#[deprecated(note = "Will be extracted to mockforge-contracts crate")]
pub use schema_diff::{to_enhanced_422_json, validation_diff, ValidationError};
pub use server_utils::errors::{json_error, json_success};
pub use server_utils::{create_socket_addr, localhost_socket_addr, wildcard_socket_addr};
#[cfg(feature = "advanced")]
pub use snapshots::{SnapshotComponents, SnapshotManager, SnapshotManifest, SnapshotMetadata};
pub use spec_parser::{GraphQLValidator, OpenApiValidator, SpecFormat};
pub use stateful_handler::{
    ResourceIdExtract, StateInfo, StateResponse, StatefulConfig, StatefulResponse,
    StatefulResponseHandler, TransitionTrigger,
};
#[cfg(feature = "workspace-mgmt")]
#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
pub use sync_watcher::{FileChange, SyncEvent, SyncService, SyncWatcher};
pub use template_library::{
    TemplateLibrary, TemplateLibraryEntry, TemplateLibraryManager, TemplateMarketplace,
    TemplateMetadata, TemplateVersion,
};
pub use templating::{expand_str, expand_tokens};
#[cfg(feature = "advanced")]
pub use time_travel::{
    cron::{CronJob, CronJobAction, CronScheduler},
    get_global_clock, is_time_travel_enabled, now as time_travel_now, register_global_clock,
    unregister_global_clock, RepeatConfig, ResponseScheduler, ScheduledResponse, TimeScenario,
    TimeTravelConfig, TimeTravelManager, TimeTravelStatus, VirtualClock,
};
#[cfg(feature = "advanced")]
pub use time_travel_handler::{
    time_travel_middleware, ScheduledResponseWrapper, TimeTravelHandler,
};
#[deprecated(note = "Use mockforge_chaos::core_traffic_shaping instead")]
pub use traffic_shaping::{BandwidthConfig, BurstLossConfig, TrafficShaper, TrafficShapingConfig};
pub use uuid::Uuid;
pub use validation::{validate_openapi_operation_security, validate_openapi_security, Validator};
pub use verification::{
    matches_verification_pattern, verify_at_least, verify_never, verify_requests, verify_sequence,
    VerificationCount, VerificationRequest, VerificationResult,
};
#[cfg(feature = "voice")]
pub use voice::{
    ConversationContext, ConversationManager, ConversationState, GeneratedWorkspaceScenario,
    HookTranspiler, ParsedCommand, ParsedWorkspaceScenario, VoiceCommandParser, VoiceSpecGenerator,
    WorkspaceConfigSummary, WorkspaceScenarioGenerator,
};
#[cfg(feature = "workspace-mgmt")]
#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
pub use workspace::promotion_trait::PromotionService;
#[cfg(feature = "workspace-mgmt")]
#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
pub use workspace::{EntityId, Folder, MockRequest, Workspace, WorkspaceConfig, WorkspaceRegistry};
#[cfg(feature = "workspace-mgmt")]
#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
pub use workspace_import::{
    create_workspace_from_curl, create_workspace_from_har, create_workspace_from_insomnia,
    create_workspace_from_postman, import_postman_to_existing_workspace,
    import_postman_to_workspace, WorkspaceImportConfig, WorkspaceImportResult,
};
#[cfg(feature = "workspace-mgmt")]
#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
pub use workspace_persistence::WorkspacePersistence;
pub use ws_proxy::{WsProxyConfig, WsProxyHandler, WsProxyRule};
// Note: ValidationError and ValidationResult from spec_parser conflict with schema_diff::ValidationError
// Use qualified paths: spec_parser::ValidationError, spec_parser::ValidationResult

// ── Organized module facades (R10) ───────────────────────────────────────────
// These provide a namespaced access path for new code. Existing flat re-exports
// above remain for backward compatibility. Prefer these for new imports.

/// Routing, route matching, and OpenAPI route generation
pub mod routes {
    pub use crate::openapi::{
        OpenApiOperation, OpenApiRoute, OpenApiSchema, OpenApiSecurityRequirement, OpenApiSpec,
    };
    pub use crate::openapi_routes::{
        create_registry_from_file, create_registry_from_json, OpenApiRouteRegistry,
        ValidationOptions,
    };
    pub use crate::routing::{HttpMethod, Route, RouteRegistry};
}

/// Middleware, protocol abstractions, and request processing
pub mod middleware {
    pub use crate::latency::LatencyInjector;
    pub use crate::overrides::{OverrideMode, OverrideRule, Overrides, PatchOp};
    pub use crate::protocol_abstraction::{
        MessagePattern, MiddlewareAction, MiddlewareChain, Protocol, ProtocolMiddleware,
        ProtocolRequest, ProtocolResponse, RequestMatcher, ResponseStatus, SpecOperation,
        SpecRegistry,
    };
}

/// Mock response generation and priority handling
pub mod generation {
    pub use crate::priority_handler::{
        CustomFixtureStep, FailureInjectionStep, GenerationResult, MockGenerator, MockResponse,
        PriorityHttpHandler, PriorityRequest, PriorityResponse, PriorityStep, SimpleMockGenerator,
    };
    pub use crate::stateful_handler::{StatefulConfig, StatefulResponse, StatefulResponseHandler};
}

/// Request/response validation
pub mod validate {
    pub use crate::runtime_validation::{
        RuntimeValidationError, RuntimeValidationResult, RuntimeValidatorConfig, SchemaMetadata,
    };
    pub use crate::spec_parser::{GraphQLValidator, OpenApiValidator, SpecFormat};
    pub use crate::validation::{
        validate_openapi_operation_security, validate_openapi_security, Validator,
    };
    pub use crate::verification::{
        matches_verification_pattern, verify_at_least, verify_never, verify_requests,
        verify_sequence, VerificationCount, VerificationRequest, VerificationResult,
    };
}

/// Fixture loading utilities
pub mod fixtures {
    pub use crate::custom_fixture::{CustomFixture, CustomFixtureLoader, NestedFixture};
    pub use crate::fixture_store::{
        load_fixtures_from_dir, FixtureFileFormat, FixtureFileGranularity, FixtureLoadErrorMode,
        FixtureLoadOptions,
    };
    pub use crate::record_replay::{
        RecordHandler, RecordReplayHandler, RecordedRequest, ReplayHandler,
    };
}

/// Core configuration for MockForge
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(default)]
pub struct Config {
    /// Enable latency simulation
    pub latency_enabled: bool,
    /// Enable failure simulation
    pub failures_enabled: bool,
    /// Enable response overrides
    pub overrides_enabled: bool,
    /// Enable traffic shaping (bandwidth + burst loss)
    pub traffic_shaping_enabled: bool,
    /// Failure injection configuration
    pub failure_config: Option<FailureConfig>,
    /// Proxy configuration
    pub proxy: Option<ProxyConfig>,
    /// Default latency profile
    pub default_latency: LatencyProfile,
    /// Traffic shaping configuration
    pub traffic_shaping: TrafficShapingConfig,
    /// Random chaos configuration
    pub chaos_random: Option<ChaosConfig>,
    /// Maximum number of request logs to keep in memory (default: 1000)
    /// Helps prevent unbounded memory growth from request logging
    pub max_request_logs: usize,
    /// Time travel configuration for temporal testing
    pub time_travel: TimeTravelConfig,
}

/// Default configuration
impl Default for Config {
    fn default() -> Self {
        Self {
            latency_enabled: true,
            failures_enabled: false,
            overrides_enabled: true,
            traffic_shaping_enabled: false,
            failure_config: None,
            proxy: None,
            default_latency: LatencyProfile::default(),
            traffic_shaping: TrafficShapingConfig::default(),
            chaos_random: None,
            max_request_logs: 1000, // Default: keep last 1000 requests
            time_travel: TimeTravelConfig::default(),
        }
    }
}

impl Config {
    /// Create a ChaosEngine from the chaos_random configuration if enabled
    pub fn create_chaos_engine(&self) -> Option<ChaosEngine> {
        self.chaos_random.as_ref().map(|config| ChaosEngine::new(config.clone()))
    }

    /// Check if random chaos mode is enabled
    pub fn is_chaos_random_enabled(&self) -> bool {
        self.chaos_random.as_ref().map(|c| c.enabled).unwrap_or(false)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_config_default() {
        let config = Config::default();
        assert!(config.latency_enabled);
        assert!(!config.failures_enabled);
        assert!(config.overrides_enabled);
        assert!(!config.traffic_shaping_enabled);
        assert!(config.failure_config.is_none());
        assert!(config.proxy.is_none());
    }

    #[test]
    fn test_config_serialization() {
        let config = Config::default();
        let json = serde_json::to_string(&config).unwrap();
        assert!(json.contains("latency_enabled"));
        assert!(json.contains("failures_enabled"));
    }

    #[test]
    fn test_config_deserialization() {
        // Use default config and modify
        let config = Config {
            latency_enabled: false,
            failures_enabled: true,
            ..Default::default()
        };

        // Serialize and deserialize
        let json = serde_json::to_string(&config).unwrap();
        let deserialized: Config = serde_json::from_str(&json).unwrap();

        assert!(!deserialized.latency_enabled);
        assert!(deserialized.failures_enabled);
        assert!(deserialized.overrides_enabled);
    }

    #[test]
    fn test_config_with_custom_values() {
        let config = Config {
            latency_enabled: false,
            failures_enabled: true,
            ..Default::default()
        };

        assert!(!config.latency_enabled);
        assert!(config.failures_enabled);
    }
}