MockForge Virtual Backend Reality (VBR) Engine
The VBR engine creates stateful mock servers with persistent virtual databases, auto-generated CRUD APIs, relationship constraints, session management, and time-based data evolution.
Overview
VBR acts like a mini real backend with:
- Persistent virtual database (SQLite, JSON, in-memory options)
- CRUD APIs auto-generated from OpenAPI specifications or entity schemas
- Relationship modeling (1:N, N:N) with constraint enforcement
- Configurable data seeding from JSON/YAML files or programmatic API
- Enhanced ID generation (pattern-based, realistic Stripe-style IDs)
- State snapshots and resets for environment management
- User session & auth emulation
- Time-based data evolution (data aging, expiring sessions)
Quick Start
Installation
The VBR engine is included in MockForge. No additional installation needed.
Basic Usage
# Create an entity
# Start a VBR server
Programmatic Usage
use ;
use ;
use VbrSchemaDefinition;
use ;
use HashMap;
async
Features
1. Virtual Database
VBR supports multiple storage backends:
- SQLite (default): Persistent, production-like database
- JSON: Human-readable file storage
- Memory: Fast, no persistence (for testing)
use ;
// SQLite backend
let config = default
.with_storage_backend;
// JSON backend
let config = default
.with_storage_backend;
// In-memory backend
let config = default
.with_storage_backend;
2. Entity Definition
Define entities with schemas, relationships, and constraints:
use ;
let order_schema = VbrSchemaDefinition ;
3. Auto-Generated CRUD APIs
Once entities are registered, CRUD endpoints are automatically generated:
GET /vbr-api/{entity}- List all entities (with pagination, filtering, sorting)GET /vbr-api/{entity}/{id}- Get entity by IDPOST /vbr-api/{entity}- Create new entityPUT /vbr-api/{entity}/{id}- Update entity (full replacement)PATCH /vbr-api/{entity}/{id}- Partial update entityDELETE /vbr-api/{entity}/{id}- Delete entity
Example:
# Create a user
# Get user by ID
# List all users with pagination
# Update user
# Delete user
4. Relationship Endpoints
Traverse relationships automatically:
GET /vbr-api/{entity}/{id}/{relationship}- Get related entities
Example:
# Get all orders for a user (one-to-many)
# Get the user for an order (many-to-one)
5. Session Management
Enable session-scoped data for isolated per-session databases:
use ;
use SessionDataManager;
let session_manager = new;
let session_data_manager = new;
// Each session gets its own isolated database
let session_db = session_data_manager.get_session_database.await?;
6. Data Aging
Automatically clean up expired data:
use ;
let mut aging_manager = new;
aging_manager.add_rule;
// Run cleanup (typically done in background)
let cleaned = aging_manager.cleanup_expired.await?;
7. Authentication
Virtual user management and JWT token generation:
use VbrAuthService;
let auth_service = new;
// Create a user
let user = auth_service.create_default_user.await?;
// Authenticate
let user = auth_service.authenticate.await?;
// Generate JWT token
let token = auth_service.generate_token?;
// Validate token
let user = auth_service.validate_token?;
CLI Commands
Create Entity
# Create entity from fields
# Create entity from schema file
# Save to file
Serve VBR API
# Start with in-memory storage
# Start with SQLite
# Start with JSON storage
# Enable session-scoped data
Manage Entities
# List all entities
# Show entity details
Integration with mockforge-http
To integrate VBR routes into the main MockForge HTTP server:
use integrate_vbr_routes;
use Router;
let app = new; // Your existing router
let context = HandlerContext ;
let app = integrate_vbr_routes?;
Configuration
VBR can be configured via VbrConfig:
use ;
let config = default
.with_storage_backend
.with_session_timeout // 2 hours
.with_session_scoped_data
.with_data_aging
.with_cleanup_interval; // 1 hour
New Features
OpenAPI Integration
Automatically generate VBR entities from OpenAPI 3.x specifications:
use ;
let config = default;
let = from_openapi_file.await?;
println!;
The engine automatically:
- Extracts schemas from
components/schemas - Detects primary keys (fields named "id", "uuid")
- Detects foreign keys (fields ending in "_id")
- Generates CRUD endpoints for each entity
Many-to-Many Relationships
Define many-to-many relationships with junction tables:
use ManyToManyDefinition;
let user_role_m2m = new
.with_junction_table;
let role_schema = new
.with_many_to_many;
Access via: GET /api/users/{id}/roles or GET /api/roles/{id}/users
Data Seeding
Seed your database from JSON/YAML files:
// From file
engine.seed_from_file.await?;
// Programmatically
let mut seed_data = new;
seed_data.insert;
engine.seed_all.await?;
Seed file format:
Enhanced ID Generation
Generate realistic IDs with patterns:
// Pattern-based: "USR-000001", "ORD-{timestamp}", "TXN-{random:12}"
.with_auto_generation
// Realistic Stripe-style: "cus_abc123def456"
.with_auto_generation
State Snapshots
Create and restore database snapshots:
// Create snapshot
let metadata = engine.create_snapshot.await?;
// Restore snapshot
engine.restore_snapshot.await?;
// List snapshots
let snapshots = list_snapshots.await?;
// Reset database
engine.reset.await?;
Examples
See the following files for comprehensive examples:
tests/tests/vbr_integration.rs- Basic CRUD operations, relationships, paginationtests/tests/vbr_new_features.rs- OpenAPI, seeding, snapshots, ID generationexamples/vbr_openapi_example.rs- Creating engine from OpenAPI specexamples/vbr_seeding_example.rs- Data seeding from files
Architecture
Components
- VirtualDatabase: Abstraction over storage backends
- EntityRegistry: Manages entity definitions
- MigrationManager: Generates SQL schemas from entities
- ConstraintValidator: Enforces foreign keys and constraints
- HandlerContext: Shared state for HTTP handlers
- SessionDataManager: Per-session database isolation
- AgingManager: Time-based data cleanup
- VbrAuthService: User authentication and JWT tokens
Request Flow
HTTP Request → Handler → HandlerContext → VirtualDatabase → Storage Backend
↓
EntityRegistry (validate schema)
↓
ConstraintValidator (check constraints)
Best Practices
- Use SQLite for production-like testing: Provides realistic database behavior
- Use Memory for fast tests: No I/O overhead, perfect for unit tests
- Define relationships explicitly: Foreign keys enable relationship traversal
- Enable data aging for realistic behavior: Simulates data lifecycle
- Use session-scoped data for multi-user scenarios: Each session gets isolated data
Limitations
- Currently supports SQLite, JSON, and in-memory storage only
- JWT authentication requires the
jwtfeature flag (fallback available) - Full archive functionality requires manual archive table creation
- Complex queries (JOINs across multiple tables) not yet supported
Contributing
VBR is part of the MockForge project. See the main CONTRIBUTING.md for guidelines.
License
Licensed under MIT OR Apache-2.0, same as MockForge.