mockforge-vbr 0.3.111

Virtual Backend Reality engine - stateful mock servers with persistent virtual databases
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
//! # 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 entity schemas
//! - Relationship modeling and constraint enforcement
//! - User session & auth emulation
//! - Time-based data evolution (data aging, expiring sessions)
//!
//! ## Example Usage
//!
//! ```no_run
//! use mockforge_vbr::{VbrEngine, VbrConfig};
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let config = VbrConfig::default()
//!     .with_storage_backend(mockforge_vbr::StorageBackend::Sqlite {
//!         path: "./data/vbr.db".into(),
//!     });
//!
//! let engine = VbrEngine::new(config).await?;
//! // Define entities and generate living API
//! # Ok(())
//! # }
//! ```

// Re-export error types from mockforge-core
pub use mockforge_core::{Error, Result};

use std::collections::HashMap;
use std::sync::Arc;

// Core modules
pub mod config;
pub mod database;
pub mod entities;
pub mod schema;

// Database and migration modules
pub mod constraints;
pub mod migration;

// API generation modules
pub mod api_generator;
pub mod handlers;

// Session and auth modules
pub mod auth;
pub mod session;

// Time-based features
pub mod aging;
pub mod mutation_rules;
pub mod scheduler;

// Integration module
pub mod integration;

// OpenAPI integration
pub mod openapi;

// Data seeding
pub mod seeding;

// ID generation
pub mod id_generation;

// Snapshots
pub mod snapshots;

// Re-export commonly used types
pub use config::{StorageBackend, VbrConfig};
pub use database::VirtualDatabase;
pub use entities::{Entity, EntityRegistry};
pub use mutation_rules::{
    ComparisonOperator, MutationOperation, MutationRule, MutationRuleManager, MutationTrigger,
};
pub use schema::{ManyToManyDefinition, VbrSchemaDefinition};
pub use snapshots::{SnapshotMetadata, TimeTravelSnapshotState};

/// Main VBR engine
pub struct VbrEngine {
    /// Configuration
    config: VbrConfig,
    /// Virtual database instance (stored in Arc for sharing)
    database: Arc<dyn VirtualDatabase + Send + Sync>,
    /// Entity registry
    registry: EntityRegistry,
}

impl VbrEngine {
    /// Create a new VBR engine with the given configuration
    pub async fn new(config: VbrConfig) -> Result<Self> {
        // Initialize virtual database (already in Arc)
        let database = database::create_database(&config.storage).await?;

        // Initialize entity registry
        let registry = EntityRegistry::new();

        Ok(Self {
            config,
            database,
            registry,
        })
    }

    /// Get the configuration
    pub fn config(&self) -> &VbrConfig {
        &self.config
    }

    /// Get the virtual database as Arc for sharing
    pub fn database_arc(&self) -> Arc<dyn VirtualDatabase + Send + Sync> {
        Arc::clone(&self.database)
    }

    /// Get a reference to the virtual database
    pub fn database(&self) -> &dyn VirtualDatabase {
        self.database.as_ref()
    }

    /// Get the entity registry
    pub fn registry(&self) -> &EntityRegistry {
        &self.registry
    }

    /// Get mutable access to the entity registry
    pub fn registry_mut(&mut self) -> &mut EntityRegistry {
        &mut self.registry
    }

    /// Create VBR engine from an OpenAPI specification
    ///
    /// This method automatically:
    /// - Parses the OpenAPI 3.x specification
    /// - Extracts entity schemas from `components/schemas`
    /// - Auto-detects primary keys and foreign keys
    /// - Registers all entities in the engine
    /// - Creates database tables for all entities
    ///
    /// # Arguments
    /// * `config` - VBR configuration
    /// * `openapi_content` - OpenAPI specification content (JSON or YAML)
    ///
    /// # Returns
    /// VBR engine with entities registered and database initialized
    pub async fn from_openapi(
        config: VbrConfig,
        openapi_content: &str,
    ) -> Result<(Self, openapi::OpenApiConversionResult)> {
        // Parse OpenAPI content (JSON or YAML)
        let json_value: serde_json::Value = if openapi_content.trim_start().starts_with('{') {
            serde_json::from_str(openapi_content)
                .map_err(|e| Error::internal(format!("Failed to parse OpenAPI JSON: {}", e)))?
        } else {
            serde_yaml::from_str(openapi_content)
                .map_err(|e| Error::internal(format!("Failed to parse OpenAPI YAML: {}", e)))?
        };

        // Load OpenAPI spec
        let spec = mockforge_core::openapi::OpenApiSpec::from_json(json_value)
            .map_err(|e| Error::internal(format!("Failed to load OpenAPI spec: {}", e)))?;

        // Validate spec
        spec.validate()
            .map_err(|e| Error::internal(format!("Invalid OpenAPI specification: {}", e)))?;

        // Convert OpenAPI to VBR entities
        let conversion_result = openapi::convert_openapi_to_vbr(&spec)?;

        // Create engine
        let mut engine = Self::new(config).await?;

        // Register entities and create database tables
        for (entity_name, vbr_schema) in &conversion_result.entities {
            let entity = Entity::new(entity_name.clone(), vbr_schema.clone());
            engine.registry_mut().register(entity.clone())?;

            // Create database table for this entity
            migration::create_table_for_entity(engine.database.as_ref(), &entity).await?;
        }

        Ok((engine, conversion_result))
    }

    /// Load VBR engine from an OpenAPI file
    ///
    /// # Arguments
    /// * `config` - VBR configuration
    /// * `file_path` - Path to OpenAPI specification file (JSON or YAML)
    ///
    /// # Returns
    /// VBR engine with entities registered and database initialized
    pub async fn from_openapi_file<P: AsRef<std::path::Path>>(
        config: VbrConfig,
        file_path: P,
    ) -> Result<(Self, openapi::OpenApiConversionResult)> {
        let content = tokio::fs::read_to_string(file_path.as_ref())
            .await
            .map_err(|e| Error::internal(format!("Failed to read OpenAPI file: {}", e)))?;

        Self::from_openapi(config, &content).await
    }

    /// Seed entity with data
    ///
    /// # Arguments
    /// * `entity_name` - Name of the entity to seed
    /// * `records` - Records to insert
    pub async fn seed_entity(
        &self,
        entity_name: &str,
        records: &[HashMap<String, serde_json::Value>],
    ) -> Result<usize> {
        seeding::seed_entity(self.database.as_ref(), &self.registry, entity_name, records).await
    }

    /// Seed all entities with data (respects dependencies)
    ///
    /// # Arguments
    /// * `seed_data` - Seed data organized by entity name
    pub async fn seed_all(&self, seed_data: &seeding::SeedData) -> Result<HashMap<String, usize>> {
        seeding::seed_all(self.database.as_ref(), &self.registry, seed_data).await
    }

    /// Load and seed from a file
    ///
    /// # Arguments
    /// * `file_path` - Path to seed file (JSON or YAML)
    pub async fn seed_from_file<P: AsRef<std::path::Path>>(
        &self,
        file_path: P,
    ) -> Result<HashMap<String, usize>> {
        let seed_data = seeding::load_seed_file(file_path).await?;
        self.seed_all(&seed_data).await
    }

    /// Clear all data from an entity
    ///
    /// # Arguments
    /// * `entity_name` - Name of the entity to clear
    pub async fn clear_entity(&self, entity_name: &str) -> Result<()> {
        seeding::clear_entity(self.database.as_ref(), &self.registry, entity_name).await
    }

    /// Clear all data from all entities
    pub async fn clear_all(&self) -> Result<()> {
        seeding::clear_all(self.database.as_ref(), &self.registry).await
    }

    /// Create a snapshot of the current database state
    ///
    /// # Arguments
    /// * `name` - Name for the snapshot
    /// * `description` - Optional description
    /// * `snapshots_dir` - Directory to store snapshots
    pub async fn create_snapshot<P: AsRef<std::path::Path>>(
        &self,
        name: &str,
        description: Option<String>,
        snapshots_dir: P,
    ) -> Result<SnapshotMetadata> {
        let manager = snapshots::SnapshotManager::new(snapshots_dir);
        manager
            .create_snapshot(name, description, self.database.as_ref(), &self.registry)
            .await
    }

    /// Create a snapshot with time travel state
    ///
    /// # Arguments
    /// * `name` - Name for the snapshot
    /// * `description` - Optional description
    /// * `snapshots_dir` - Directory to store snapshots
    /// * `include_time_travel` - Whether to include time travel state
    /// * `time_travel_state` - Optional time travel state to include
    pub async fn create_snapshot_with_time_travel<P: AsRef<std::path::Path>>(
        &self,
        name: &str,
        description: Option<String>,
        snapshots_dir: P,
        include_time_travel: bool,
        time_travel_state: Option<TimeTravelSnapshotState>,
    ) -> Result<SnapshotMetadata> {
        let manager = snapshots::SnapshotManager::new(snapshots_dir);
        manager
            .create_snapshot_with_time_travel(
                name,
                description,
                self.database.as_ref(),
                &self.registry,
                include_time_travel,
                time_travel_state,
            )
            .await
    }

    /// Restore a snapshot
    ///
    /// # Arguments
    /// * `name` - Name of the snapshot to restore
    /// * `snapshots_dir` - Directory where snapshots are stored
    pub async fn restore_snapshot<P: AsRef<std::path::Path>>(
        &self,
        name: &str,
        snapshots_dir: P,
    ) -> Result<()> {
        let manager = snapshots::SnapshotManager::new(snapshots_dir);
        manager.restore_snapshot(name, self.database.as_ref(), &self.registry).await
    }

    /// Restore a snapshot with time travel state
    ///
    /// # Arguments
    /// * `name` - Name of the snapshot to restore
    /// * `snapshots_dir` - Directory where snapshots are stored
    /// * `restore_time_travel` - Whether to restore time travel state
    /// * `time_travel_restore_callback` - Optional callback to restore time travel state
    pub async fn restore_snapshot_with_time_travel<P, F>(
        &self,
        name: &str,
        snapshots_dir: P,
        restore_time_travel: bool,
        time_travel_restore_callback: Option<F>,
    ) -> Result<()>
    where
        P: AsRef<std::path::Path>,
        F: FnOnce(TimeTravelSnapshotState) -> Result<()>,
    {
        let manager = snapshots::SnapshotManager::new(snapshots_dir);
        manager
            .restore_snapshot_with_time_travel(
                name,
                self.database.as_ref(),
                &self.registry,
                restore_time_travel,
                time_travel_restore_callback,
            )
            .await
    }

    /// List all snapshots
    ///
    /// # Arguments
    /// * `snapshots_dir` - Directory where snapshots are stored
    pub async fn list_snapshots<P: AsRef<std::path::Path>>(
        snapshots_dir: P,
    ) -> Result<Vec<SnapshotMetadata>> {
        let manager = snapshots::SnapshotManager::new(snapshots_dir);
        manager.list_snapshots().await
    }

    /// Delete a snapshot
    ///
    /// # Arguments
    /// * `name` - Name of the snapshot to delete
    /// * `snapshots_dir` - Directory where snapshots are stored
    pub async fn delete_snapshot<P: AsRef<std::path::Path>>(
        name: &str,
        snapshots_dir: P,
    ) -> Result<()> {
        let manager = snapshots::SnapshotManager::new(snapshots_dir);
        manager.delete_snapshot(name).await
    }

    /// Reset database to empty state
    pub async fn reset(&self) -> Result<()> {
        snapshots::reset_database(self.database.as_ref(), &self.registry).await
    }

    /// Export the complete database state as JSON
    ///
    /// This exports all entity data in a format suitable for snapshots.
    pub async fn export_state(&self) -> Result<serde_json::Value> {
        let mut state = serde_json::Map::new();
        let mut entities = serde_json::Map::new();

        for entity_name in self.registry.list() {
            if let Some(entity) = self.registry.get(&entity_name) {
                let table_name = entity.table_name();
                let query = format!("SELECT * FROM {}", table_name);
                let records = self.database.query(&query, &[]).await?;
                entities.insert(
                    entity_name.clone(),
                    serde_json::Value::Array(
                        records.into_iter().map(|r| serde_json::json!(r)).collect(),
                    ),
                );
            }
        }

        state.insert("entities".to_string(), serde_json::Value::Object(entities));
        state.insert(
            "storage_backend".to_string(),
            serde_json::Value::String(self.database.connection_info()),
        );
        state.insert(
            "exported_at".to_string(),
            serde_json::Value::String(chrono::Utc::now().to_rfc3339()),
        );

        Ok(serde_json::Value::Object(state))
    }

    /// Import database state from JSON
    ///
    /// This restores entity data from a previous snapshot export.
    pub async fn import_state(&self, state: serde_json::Value) -> Result<()> {
        // First, clear existing data
        self.reset().await?;

        // Extract entities from state
        let entities = state
            .get("entities")
            .and_then(|e| e.as_object())
            .ok_or_else(|| Error::internal("Invalid state format: missing entities"))?;

        // Import each entity
        for (entity_name, records_value) in entities {
            let records = records_value.as_array().ok_or_else(|| {
                Error::internal(format!("Invalid records for entity {}", entity_name))
            })?;

            if let Some(entity) = self.registry.get(entity_name) {
                let table_name = entity.table_name();

                for record in records {
                    let record_obj = record
                        .as_object()
                        .ok_or_else(|| Error::internal("Invalid record format"))?;

                    let fields: Vec<String> = record_obj.keys().cloned().collect();
                    let placeholders: Vec<String> =
                        (0..fields.len()).map(|_| "?".to_string()).collect();
                    let values: Vec<serde_json::Value> = fields
                        .iter()
                        .map(|f| record_obj.get(f).cloned().unwrap_or(serde_json::Value::Null))
                        .collect();

                    let query = format!(
                        "INSERT INTO {} ({}) VALUES ({})",
                        table_name,
                        fields.join(", "),
                        placeholders.join(", ")
                    );

                    self.database.execute(&query, &values).await?;
                }
            }
        }

        Ok(())
    }

    /// Get a summary of the current state
    pub async fn state_summary(&self) -> String {
        let mut total_records = 0usize;
        let entity_count = self.registry.list().len();

        for entity_name in self.registry.list() {
            if let Some(entity) = self.registry.get(&entity_name) {
                let table_name = entity.table_name();
                let count_query = format!("SELECT COUNT(*) as count FROM {}", table_name);
                if let Ok(results) = self.database.query(&count_query, &[]).await {
                    if let Some(count) =
                        results.first().and_then(|r| r.get("count")).and_then(|v| v.as_u64())
                    {
                        total_records += count as usize;
                    }
                }
            }
        }

        format!("{} entities, {} records", entity_count, total_records)
    }
}

// Implement ProtocolStateExporter trait for VbrEngine
use async_trait::async_trait;
use mockforge_core::snapshots::ProtocolStateExporter;

#[async_trait]
impl ProtocolStateExporter for VbrEngine {
    fn protocol_name(&self) -> &str {
        "vbr"
    }

    async fn export_state(&self) -> Result<serde_json::Value> {
        VbrEngine::export_state(self).await
    }

    async fn import_state(&self, state: serde_json::Value) -> Result<()> {
        VbrEngine::import_state(self, state).await
    }

    async fn state_summary(&self) -> String {
        VbrEngine::state_summary(self).await
    }
}

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

    #[tokio::test]
    async fn test_vbr_engine_creation() {
        // Use Memory backend for tests to avoid file system issues
        let config = VbrConfig::default().with_storage_backend(StorageBackend::Memory);
        let engine = VbrEngine::new(config).await;
        assert!(engine.is_ok());
    }
}