mockforge-vbr 0.3.106

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
//! Entity management and registry
//!
//! This module provides entity definition, management, and registry functionality
//! for tracking all entities in the VBR engine.

use crate::database::VirtualDatabase;
use crate::schema::VbrSchemaDefinition;
use crate::{Error, Result};
use mockforge_core::intelligent_behavior::rules::StateMachine;
use std::collections::HashMap;
use tracing::warn;

/// Entity definition
#[derive(Debug, Clone)]
pub struct Entity {
    /// Entity name
    pub name: String,

    /// Schema definition
    pub schema: VbrSchemaDefinition,

    /// Table name (derived from entity name)
    pub table_name: String,

    /// Optional state machine for this entity
    ///
    /// If set, the entity can participate in state machine transitions.
    /// The state machine defines valid state transitions and lifecycle management.
    pub state_machine: Option<StateMachine>,
}

impl Entity {
    /// Create a new entity
    pub fn new(name: String, schema: VbrSchemaDefinition) -> Self {
        let table_name = name.to_lowercase() + "s"; // Simple pluralization
        Self {
            name,
            schema,
            table_name,
            state_machine: None,
        }
    }

    /// Create a new entity with a state machine
    pub fn with_state_machine(
        name: String,
        schema: VbrSchemaDefinition,
        state_machine: StateMachine,
    ) -> Self {
        let table_name = name.to_lowercase() + "s";
        Self {
            name,
            schema,
            table_name,
            state_machine: Some(state_machine),
        }
    }

    /// Set the state machine for this entity
    pub fn set_state_machine(&mut self, state_machine: StateMachine) {
        self.state_machine = Some(state_machine);
    }

    /// Get the state machine for this entity
    pub fn state_machine(&self) -> Option<&StateMachine> {
        self.state_machine.as_ref()
    }

    /// Check if this entity has a state machine
    pub fn has_state_machine(&self) -> bool {
        self.state_machine.is_some()
    }

    /// Apply a state transition to an entity record
    ///
    /// Updates the entity's state field in the database based on the state machine transition.
    /// The state field name is typically derived from the state machine's resource_type
    /// (e.g., "status" for "Order" resource type).
    ///
    /// This method should be called after validating that the transition is allowed
    /// by the state machine.
    pub async fn apply_state_transition(
        &self,
        database: &dyn VirtualDatabase,
        record_id: &str,
        new_state: &str,
        state_field_name: Option<&str>,
    ) -> Result<()> {
        // Determine state field name:
        // 1. Use the explicitly passed name if provided
        // 2. Look for a matching field in the schema (e.g., "order_status" for resource_type "Order")
        // 3. Fall back to "status"
        let derived_field;
        let field_name = if let Some(name) = state_field_name {
            name
        } else if let Some(ref sm) = self.state_machine {
            // Derive candidate field name: "Order" -> "order_status"
            let candidate = format!("{}_status", sm.resource_type.to_ascii_lowercase());
            // Check if the derived field exists in the schema
            if self.schema.base.fields.iter().any(|f| f.name == candidate) {
                derived_field = candidate;
                &derived_field
            } else {
                "status"
            }
        } else {
            "status"
        };

        // Check if the field exists in the schema
        let field_exists = self.schema.base.fields.iter().any(|f| f.name == field_name);

        if !field_exists {
            // If field doesn't exist, we'll still try to update it
            // (it might be a dynamic field or added later)
            warn!(
                "State field '{}' not found in entity schema, attempting update anyway",
                field_name
            );
        }

        // Update the state field in the database
        let query = format!("UPDATE {} SET {} = ? WHERE id = ?", self.table_name, field_name);

        database
            .execute(
                &query,
                &[
                    serde_json::Value::String(new_state.to_string()),
                    serde_json::Value::String(record_id.to_string()),
                ],
            )
            .await
            .map_err(|e| Error::internal(format!("Failed to update entity state: {}", e)))?;

        Ok(())
    }

    /// Get the current state of an entity record
    ///
    /// Reads the state field from the database for a specific record.
    pub async fn get_current_state(
        &self,
        database: &dyn VirtualDatabase,
        record_id: &str,
        state_field_name: Option<&str>,
    ) -> Result<Option<String>> {
        let field_name = state_field_name.unwrap_or("status");

        let query = format!("SELECT {} FROM {} WHERE id = ?", field_name, self.table_name);

        let results = database
            .query(&query, &[serde_json::Value::String(record_id.to_string())])
            .await
            .map_err(|e| Error::internal(format!("Failed to query entity state: {}", e)))?;

        if let Some(row) = results.first() {
            if let Some(value) = row.get(field_name) {
                if let Some(state) = value.as_str() {
                    return Ok(Some(state.to_string()));
                }
            }
        }

        Ok(None)
    }

    /// Check if a state transition is allowed for an entity record
    ///
    /// Validates that the transition from the current state to the new state
    /// is allowed by the entity's state machine.
    pub async fn can_transition(
        &self,
        database: &dyn VirtualDatabase,
        record_id: &str,
        to_state: &str,
        state_field_name: Option<&str>,
    ) -> Result<bool> {
        let state_machine = self
            .state_machine
            .as_ref()
            .ok_or_else(|| Error::internal("Entity does not have a state machine configured"))?;

        // Get current state
        let current_state = self
            .get_current_state(database, record_id, state_field_name)
            .await?
            .ok_or_else(|| {
                Error::internal(format!("Record '{}' not found or has no state", record_id))
            })?;

        // Check if transition is allowed
        Ok(state_machine.can_transition(&current_state, to_state))
    }

    /// Get the entity name
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the table name
    pub fn table_name(&self) -> &str {
        &self.table_name
    }
}

/// Entity registry for managing all entities
#[derive(Clone)]
pub struct EntityRegistry {
    /// Registered entities by name
    entities: HashMap<String, Entity>,
}

impl EntityRegistry {
    /// Create a new entity registry
    pub fn new() -> Self {
        Self {
            entities: HashMap::new(),
        }
    }

    /// Register an entity
    pub fn register(&mut self, entity: Entity) -> Result<()> {
        let name = entity.name.clone();
        if self.entities.contains_key(&name) {
            return Err(Error::internal(format!("Entity '{}' already registered", name)));
        }
        self.entities.insert(name, entity);
        Ok(())
    }

    /// Get an entity by name
    pub fn get(&self, name: &str) -> Option<&Entity> {
        self.entities.get(name)
    }

    /// Get all entity names
    pub fn list(&self) -> Vec<String> {
        self.entities.keys().cloned().collect()
    }

    /// Check if an entity exists
    pub fn exists(&self, name: &str) -> bool {
        self.entities.contains_key(name)
    }

    /// Remove an entity
    pub fn remove(&mut self, name: &str) -> Result<()> {
        self.entities
            .remove(name)
            .ok_or_else(|| Error::internal(format!("Entity '{}' not found", name)))?;
        Ok(())
    }
}

impl Default for EntityRegistry {
    fn default() -> Self {
        Self::new()
    }
}

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

    fn create_test_schema(name: &str) -> VbrSchemaDefinition {
        let base_schema = SchemaDefinition::new(name.to_string());
        VbrSchemaDefinition::new(base_schema)
    }

    // Entity tests
    #[test]
    fn test_entity_creation() {
        let base_schema = SchemaDefinition::new("User".to_string());
        let vbr_schema = VbrSchemaDefinition::new(base_schema);
        let entity = Entity::new("User".to_string(), vbr_schema);

        assert_eq!(entity.name(), "User");
        assert_eq!(entity.table_name(), "users");
    }

    #[test]
    fn test_entity_table_name_pluralization() {
        let entity = Entity::new("Order".to_string(), create_test_schema("Order"));
        assert_eq!(entity.table_name(), "orders");

        let entity2 = Entity::new("Product".to_string(), create_test_schema("Product"));
        assert_eq!(entity2.table_name(), "products");
    }

    #[test]
    fn test_entity_table_name_lowercase() {
        let entity = Entity::new("UserProfile".to_string(), create_test_schema("UserProfile"));
        assert_eq!(entity.table_name(), "userprofiles");
    }

    #[test]
    fn test_entity_no_state_machine() {
        let entity = Entity::new("Item".to_string(), create_test_schema("Item"));
        assert!(!entity.has_state_machine());
        assert!(entity.state_machine().is_none());
    }

    #[test]
    fn test_entity_clone() {
        let entity = Entity::new("Test".to_string(), create_test_schema("Test"));
        let cloned = entity.clone();
        assert_eq!(entity.name(), cloned.name());
        assert_eq!(entity.table_name(), cloned.table_name());
    }

    #[test]
    fn test_entity_debug() {
        let entity = Entity::new("DebugEntity".to_string(), create_test_schema("DebugEntity"));
        let debug = format!("{:?}", entity);
        assert!(debug.contains("Entity"));
        assert!(debug.contains("DebugEntity"));
    }

    #[test]
    fn test_entity_name_getter() {
        let entity = Entity::new("Customer".to_string(), create_test_schema("Customer"));
        assert_eq!(entity.name(), "Customer");
        assert_eq!(entity.name, "Customer");
    }

    // EntityRegistry tests
    #[test]
    fn test_entity_registry() {
        let mut registry = EntityRegistry::new();

        let base_schema = SchemaDefinition::new("User".to_string());
        let vbr_schema = VbrSchemaDefinition::new(base_schema);
        let entity = Entity::new("User".to_string(), vbr_schema);

        assert!(registry.register(entity).is_ok());
        assert!(registry.exists("User"));
        assert!(registry.get("User").is_some());
    }

    #[test]
    fn test_entity_registry_duplicate() {
        let mut registry = EntityRegistry::new();

        let base_schema1 = SchemaDefinition::new("User".to_string());
        let vbr_schema1 = VbrSchemaDefinition::new(base_schema1);
        let entity1 = Entity::new("User".to_string(), vbr_schema1);

        let base_schema2 = SchemaDefinition::new("User".to_string());
        let vbr_schema2 = VbrSchemaDefinition::new(base_schema2);
        let entity2 = Entity::new("User".to_string(), vbr_schema2);

        assert!(registry.register(entity1).is_ok());
        assert!(registry.register(entity2).is_err());
    }

    #[test]
    fn test_entity_registry_default() {
        let registry = EntityRegistry::default();
        assert!(registry.list().is_empty());
    }

    #[test]
    fn test_entity_registry_new() {
        let registry = EntityRegistry::new();
        assert!(registry.list().is_empty());
        assert!(!registry.exists("Anything"));
    }

    #[test]
    fn test_entity_registry_get_nonexistent() {
        let registry = EntityRegistry::new();
        assert!(registry.get("NonExistent").is_none());
    }

    #[test]
    fn test_entity_registry_list() {
        let mut registry = EntityRegistry::new();

        registry
            .register(Entity::new("User".to_string(), create_test_schema("User")))
            .unwrap();
        registry
            .register(Entity::new("Order".to_string(), create_test_schema("Order")))
            .unwrap();
        registry
            .register(Entity::new("Product".to_string(), create_test_schema("Product")))
            .unwrap();

        let list = registry.list();
        assert_eq!(list.len(), 3);
        assert!(list.contains(&"User".to_string()));
        assert!(list.contains(&"Order".to_string()));
        assert!(list.contains(&"Product".to_string()));
    }

    #[test]
    fn test_entity_registry_exists() {
        let mut registry = EntityRegistry::new();
        registry
            .register(Entity::new("User".to_string(), create_test_schema("User")))
            .unwrap();

        assert!(registry.exists("User"));
        assert!(!registry.exists("Order"));
        assert!(!registry.exists("user")); // Case sensitive
    }

    #[test]
    fn test_entity_registry_remove() {
        let mut registry = EntityRegistry::new();
        registry
            .register(Entity::new("User".to_string(), create_test_schema("User")))
            .unwrap();

        assert!(registry.exists("User"));
        assert!(registry.remove("User").is_ok());
        assert!(!registry.exists("User"));
    }

    #[test]
    fn test_entity_registry_remove_nonexistent() {
        let mut registry = EntityRegistry::new();
        let result = registry.remove("NonExistent");
        assert!(result.is_err());
    }

    #[test]
    fn test_entity_registry_clone() {
        let mut registry = EntityRegistry::new();
        registry
            .register(Entity::new("User".to_string(), create_test_schema("User")))
            .unwrap();

        let cloned = registry.clone();
        assert!(cloned.exists("User"));
        assert_eq!(cloned.list().len(), 1);
    }

    #[test]
    fn test_entity_registry_multiple_operations() {
        let mut registry = EntityRegistry::new();

        // Register multiple entities
        registry
            .register(Entity::new("A".to_string(), create_test_schema("A")))
            .unwrap();
        registry
            .register(Entity::new("B".to_string(), create_test_schema("B")))
            .unwrap();

        // Verify
        assert_eq!(registry.list().len(), 2);
        assert!(registry.exists("A"));
        assert!(registry.exists("B"));

        // Remove one
        registry.remove("A").unwrap();
        assert_eq!(registry.list().len(), 1);
        assert!(!registry.exists("A"));
        assert!(registry.exists("B"));

        // Add another
        registry
            .register(Entity::new("C".to_string(), create_test_schema("C")))
            .unwrap();
        assert_eq!(registry.list().len(), 2);
    }

    #[test]
    fn test_entity_registry_get_returns_reference() {
        let mut registry = EntityRegistry::new();
        registry
            .register(Entity::new("User".to_string(), create_test_schema("User")))
            .unwrap();

        let entity = registry.get("User").unwrap();
        assert_eq!(entity.name(), "User");
        assert_eq!(entity.table_name(), "users");
    }
}