Expand description
§MockForge WebSocket
WebSocket mocking library for MockForge with replay, proxy, and AI-powered event generation.
This crate provides comprehensive WebSocket mocking capabilities, including:
- Replay Mode: Script and replay WebSocket message sequences
- Interactive Mode: Dynamic responses based on client messages
- AI Event Streams: Generate narrative-driven event sequences
- Proxy Mode: Forward messages to real WebSocket backends
- JSONPath Matching: Sophisticated message matching with JSONPath queries
§Overview
MockForge WebSocket supports multiple operational modes:
§1. Replay Mode
Play back pre-recorded WebSocket interactions from JSONL files with template expansion.
§2. Proxy Mode
Forward WebSocket messages to upstream servers with optional message transformation.
§3. AI Event Generation
Generate realistic event streams using LLMs based on narrative descriptions.
§Quick Start
§Basic WebSocket Server
use mockforge_ws::router;
use std::net::SocketAddr;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Create WebSocket router
let app = router();
// Start server
let addr: SocketAddr = "0.0.0.0:3001".parse()?;
let listener = tokio::net::TcpListener::bind(addr).await?;
axum::serve(listener, app).await?;
Ok(())
}
§With Latency Simulation
use mockforge_ws::router_with_latency;
use mockforge_core::latency::{FaultConfig, LatencyInjector};
use mockforge_core::LatencyProfile;
let latency = LatencyProfile::with_normal_distribution(250, 75.0)
.with_min_ms(100)
.with_max_ms(500);
let injector = LatencyInjector::new(latency, FaultConfig::default());
let app = router_with_latency(injector);
§With Proxy Support
use mockforge_ws::router_with_proxy;
use mockforge_core::{WsProxyHandler, WsProxyConfig};
let proxy_config = WsProxyConfig {
upstream_url: "wss://api.example.com/ws".to_string(),
..Default::default()
};
let proxy = WsProxyHandler::new(proxy_config);
let app = router_with_proxy(proxy);
§AI Event Generation
Generate realistic event streams from narrative descriptions:
use mockforge_ws::{AiEventGenerator, WebSocketAiConfig};
use mockforge_data::replay_augmentation::{scenarios, ReplayMode};
let ai_config = WebSocketAiConfig {
enabled: true,
replay: Some(scenarios::stock_market_scenario()),
max_events: Some(30),
event_rate: Some(1.5),
};
let generator = AiEventGenerator::new(ai_config.replay.clone().unwrap())?;
let _events = generator; // use the generator with `stream_events` in your handler
§Replay File Format
WebSocket replay files use JSON Lines (JSONL) format:
{"ts":0,"dir":"out","text":"HELLO {{uuid}}","waitFor":"^CLIENT_READY$"}
{"ts":10,"dir":"out","text":"{\"type\":\"welcome\",\"sessionId\":\"{{uuid}}\"}"}
{"ts":20,"dir":"out","text":"{\"data\":{{randInt 1 100}}}","waitFor":"^ACK$"}
Fields:
ts
: Timestamp in millisecondsdir
: Direction (“in” = received, “out” = sent)text
: Message content (supports template expansion)waitFor
: Optional regex/JSONPath pattern to wait for
§JSONPath Message Matching
Match messages using JSONPath queries:
{"waitFor": "$.type", "text": "Type received"}
{"waitFor": "$.user.id", "text": "User authenticated"}
{"waitFor": "$.order.status", "text": "Order updated"}
§Key Modules
ai_event_generator
: AI-powered event stream generationws_tracing
: Distributed tracing integration
§Examples
See the examples directory for complete working examples.
§Related Crates
mockforge-core
: Core mocking functionalitymockforge-data
: Synthetic data generation
§Documentation
Re-exports§
pub use ai_event_generator::AiEventGenerator;
pub use ai_event_generator::WebSocketAiConfig;
pub use ws_tracing::create_ws_connection_span;
pub use ws_tracing::create_ws_message_span;
pub use ws_tracing::record_ws_connection_success;
pub use ws_tracing::record_ws_error;
pub use ws_tracing::record_ws_message_success;
Modules§
- ai_
event_ generator - AI-powered WebSocket event generation
- ws_
tracing - Distributed tracing for WebSocket connections
Functions§
- router
- Build the WebSocket router (exposed for tests and embedding)
- router_
with_ latency - Build the WebSocket router with latency injector state
- router_
with_ proxy - Build the WebSocket router with proxy handler
- start_
with_ latency - Start WebSocket server with latency simulation