mockforge-data 0.3.111

Data generator for MockForge - faker + RAG synthetic data engine
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
//! Data drift simulation for evolving mock data
//!
//! This module provides data drift simulation capabilities, allowing mock data to
//! evolve naturally over time or across requests (e.g., order statuses progressing,
//! customer data changing).

use crate::{Error, Result};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;

/// Drift strategy for data evolution
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum DriftStrategy {
    /// Linear drift - values change linearly over time
    Linear,
    /// Step-based drift - values change at discrete steps
    Stepped,
    /// State machine - values transition between defined states
    StateMachine,
    /// Random walk - values change randomly within bounds
    RandomWalk,
    /// Custom drift using a rule expression
    Custom(String),
}

/// Drift rule configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DriftRule {
    /// Field to apply drift to
    pub field: String,
    /// Drift strategy
    pub strategy: DriftStrategy,
    /// Parameters for the drift strategy
    pub params: HashMap<String, Value>,
    /// Rate of change (per request or per time unit)
    pub rate: f64,
    /// Minimum value (for numeric fields)
    pub min_value: Option<Value>,
    /// Maximum value (for numeric fields)
    pub max_value: Option<Value>,
    /// Possible states (for state machine)
    pub states: Option<Vec<String>>,
    /// Transition probabilities (for state machine)
    pub transitions: Option<HashMap<String, Vec<(String, f64)>>>,
}

impl DriftRule {
    /// Create a new drift rule
    pub fn new(field: String, strategy: DriftStrategy) -> Self {
        Self {
            field,
            strategy,
            params: HashMap::new(),
            rate: 1.0,
            min_value: None,
            max_value: None,
            states: None,
            transitions: None,
        }
    }

    /// Set rate of change
    pub fn with_rate(mut self, rate: f64) -> Self {
        self.rate = rate;
        self
    }

    /// Set value bounds
    pub fn with_bounds(mut self, min: Value, max: Value) -> Self {
        self.min_value = Some(min);
        self.max_value = Some(max);
        self
    }

    /// Set states for state machine
    pub fn with_states(mut self, states: Vec<String>) -> Self {
        self.states = Some(states);
        self
    }

    /// Set transitions for state machine
    pub fn with_transitions(mut self, transitions: HashMap<String, Vec<(String, f64)>>) -> Self {
        self.transitions = Some(transitions);
        self
    }

    /// Add a parameter
    pub fn with_param(mut self, key: String, value: Value) -> Self {
        self.params.insert(key, value);
        self
    }

    /// Validate the drift rule
    pub fn validate(&self) -> Result<()> {
        if self.field.is_empty() {
            return Err(Error::generic("Field name cannot be empty"));
        }

        if self.rate < 0.0 {
            return Err(Error::generic("Rate must be non-negative"));
        }

        if self.strategy == DriftStrategy::StateMachine
            && (self.states.is_none() || self.transitions.is_none())
        {
            return Err(Error::generic("State machine strategy requires states and transitions"));
        }

        Ok(())
    }
}

/// Data drift configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DataDriftConfig {
    /// Drift rules to apply
    pub rules: Vec<DriftRule>,
    /// Whether to enable time-based drift
    pub time_based: bool,
    /// Whether to enable request-based drift
    pub request_based: bool,
    /// Drift interval (seconds for time-based, requests for request-based)
    pub interval: u64,
    /// Random seed for reproducible drift
    pub seed: Option<u64>,
}

impl Default for DataDriftConfig {
    fn default() -> Self {
        Self {
            rules: Vec::new(),
            time_based: false,
            request_based: true,
            interval: 1,
            seed: None,
        }
    }
}

impl DataDriftConfig {
    /// Create a new data drift configuration
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a drift rule
    pub fn with_rule(mut self, rule: DriftRule) -> Self {
        self.rules.push(rule);
        self
    }

    /// Enable time-based drift
    pub fn with_time_based(mut self, interval_secs: u64) -> Self {
        self.time_based = true;
        self.interval = interval_secs;
        self
    }

    /// Enable request-based drift
    pub fn with_request_based(mut self, interval_requests: u64) -> Self {
        self.request_based = true;
        self.interval = interval_requests;
        self
    }

    /// Set random seed
    pub fn with_seed(mut self, seed: u64) -> Self {
        self.seed = Some(seed);
        self
    }

    /// Validate configuration
    pub fn validate(&self) -> Result<()> {
        for rule in &self.rules {
            rule.validate()?;
        }

        if self.interval == 0 {
            return Err(Error::generic("Interval must be greater than 0"));
        }

        Ok(())
    }
}

/// Data drift engine state
#[derive(Debug)]
struct DriftState {
    /// Current values for drifting fields
    values: HashMap<String, Value>,
    /// Request counter
    request_count: u64,
    /// Start time
    start_time: std::time::Instant,
    /// Random number generator
    rng: rand::rngs::StdRng,
}

/// Data drift engine
pub struct DataDriftEngine {
    /// Configuration
    config: DataDriftConfig,
    /// Current state
    state: Arc<RwLock<DriftState>>,
}

impl DataDriftEngine {
    /// Create a new data drift engine
    pub fn new(config: DataDriftConfig) -> Result<Self> {
        config.validate()?;

        use rand::SeedableRng;
        let rng = if let Some(seed) = config.seed {
            rand::rngs::StdRng::seed_from_u64(seed)
        } else {
            rand::rngs::StdRng::seed_from_u64(fastrand::u64(..))
        };

        let state = DriftState {
            values: HashMap::new(),
            request_count: 0,
            start_time: std::time::Instant::now(),
            rng,
        };

        Ok(Self {
            config,
            state: Arc::new(RwLock::new(state)),
        })
    }

    /// Apply drift to a value
    pub async fn apply_drift(&self, mut data: Value) -> Result<Value> {
        let mut state = self.state.write().await;
        state.request_count += 1;

        // Check if we should apply drift
        let should_drift = if self.config.time_based {
            let elapsed_secs = state.start_time.elapsed().as_secs();
            elapsed_secs % self.config.interval == 0
        } else if self.config.request_based {
            state.request_count % self.config.interval == 0
        } else {
            true // Always drift if no specific timing is configured
        };

        if !should_drift {
            return Ok(data);
        }

        // Apply each drift rule
        for rule in &self.config.rules {
            if let Some(obj) = data.as_object_mut() {
                if let Some(field_value) = obj.get(&rule.field) {
                    let new_value = self.apply_rule(rule, field_value.clone(), &mut state)?;
                    obj.insert(rule.field.clone(), new_value);
                }
            }
        }

        Ok(data)
    }

    /// Apply a single drift rule
    fn apply_rule(
        &self,
        rule: &DriftRule,
        current: Value,
        state: &mut DriftState,
    ) -> Result<Value> {
        use rand::Rng;

        match &rule.strategy {
            DriftStrategy::Linear => {
                // Linear drift for numeric values
                if let Some(num) = current.as_f64() {
                    let delta = rule.rate;
                    let mut new_val = num + delta;

                    // Apply bounds
                    if let Some(min) = &rule.min_value {
                        if let Some(min_num) = min.as_f64() {
                            new_val = new_val.max(min_num);
                        }
                    }
                    if let Some(max) = &rule.max_value {
                        if let Some(max_num) = max.as_f64() {
                            new_val = new_val.min(max_num);
                        }
                    }

                    Ok(Value::from(new_val))
                } else {
                    Ok(current)
                }
            }
            DriftStrategy::Stepped => {
                // Step-based drift
                if let Some(num) = current.as_i64() {
                    let step = rule.rate as i64;
                    let new_val = num + step;
                    Ok(Value::from(new_val))
                } else {
                    Ok(current)
                }
            }
            DriftStrategy::StateMachine => {
                // State machine transitions
                if let Some(current_state) = current.as_str() {
                    if let Some(transitions) = &rule.transitions {
                        if let Some(possible_transitions) = transitions.get(current_state) {
                            // Use weighted random selection
                            let random_val: f64 = state.rng.random();
                            let mut cumulative = 0.0;

                            for (next_state, probability) in possible_transitions {
                                cumulative += probability;
                                if random_val <= cumulative {
                                    return Ok(Value::String(next_state.clone()));
                                }
                            }
                        }
                    }
                }
                Ok(current)
            }
            DriftStrategy::RandomWalk => {
                // Random walk within bounds
                if let Some(num) = current.as_f64() {
                    let delta = state.rng.random_range(-rule.rate..=rule.rate);
                    let mut new_val = num + delta;

                    // Apply bounds
                    if let Some(min) = &rule.min_value {
                        if let Some(min_num) = min.as_f64() {
                            new_val = new_val.max(min_num);
                        }
                    }
                    if let Some(max) = &rule.max_value {
                        if let Some(max_num) = max.as_f64() {
                            new_val = new_val.min(max_num);
                        }
                    }

                    Ok(Value::from(new_val))
                } else {
                    Ok(current)
                }
            }
            DriftStrategy::Custom(expr) => {
                // Custom drift rules using simple expression evaluation
                // Supported expressions:
                //   "value + <n>" / "value - <n>" — add/subtract constant
                //   "value * <n>" — multiply by factor
                //   "value % <n>" — modulo
                //   "clamp(<min>, <max>)" — clamp current value to range
                //   "<literal>" — replace with literal string or number
                let expr = expr.trim();

                if let Some(num) = current.as_f64() {
                    // Try arithmetic expressions on numeric values
                    if let Some(rest) = expr.strip_prefix("value") {
                        let rest = rest.trim();
                        let result = if let Some(operand) = rest.strip_prefix('+') {
                            operand.trim().parse::<f64>().ok().map(|n| num + n)
                        } else if let Some(operand) = rest.strip_prefix('-') {
                            operand.trim().parse::<f64>().ok().map(|n| num - n)
                        } else if let Some(operand) = rest.strip_prefix('*') {
                            operand.trim().parse::<f64>().ok().map(|n| num * n)
                        } else if let Some(operand) = rest.strip_prefix('%') {
                            operand.trim().parse::<f64>().ok().map(|n| {
                                if n != 0.0 {
                                    num % n
                                } else {
                                    num
                                }
                            })
                        } else {
                            None
                        };

                        if let Some(mut new_val) = result {
                            // Apply bounds from the rule
                            if let Some(min) = &rule.min_value {
                                if let Some(min_num) = min.as_f64() {
                                    new_val = new_val.max(min_num);
                                }
                            }
                            if let Some(max) = &rule.max_value {
                                if let Some(max_num) = max.as_f64() {
                                    new_val = new_val.min(max_num);
                                }
                            }
                            return Ok(Value::from(new_val));
                        }
                    }

                    // Try clamp expression: "clamp(min, max)"
                    if let Some(inner) =
                        expr.strip_prefix("clamp(").and_then(|s| s.strip_suffix(')'))
                    {
                        let parts: Vec<&str> = inner.split(',').collect();
                        if parts.len() == 2 {
                            if let (Ok(min), Ok(max)) =
                                (parts[0].trim().parse::<f64>(), parts[1].trim().parse::<f64>())
                            {
                                return Ok(Value::from(num.clamp(min, max)));
                            }
                        }
                    }

                    // Try literal number replacement
                    if let Ok(literal) = expr.parse::<f64>() {
                        return Ok(Value::from(literal));
                    }
                }

                // For string values or unmatched expressions, try literal replacement
                if !expr.starts_with("value") && !expr.starts_with("clamp") {
                    // Try as a literal JSON value
                    if let Ok(parsed) = serde_json::from_str::<Value>(expr) {
                        return Ok(parsed);
                    }
                    // Otherwise treat as a literal string
                    return Ok(Value::String(expr.to_string()));
                }

                Ok(current)
            }
        }
    }

    /// Reset the drift state
    pub async fn reset(&self) {
        let mut state = self.state.write().await;
        state.values.clear();
        state.request_count = 0;
        state.start_time = std::time::Instant::now();
    }

    /// Get current request count
    pub async fn request_count(&self) -> u64 {
        self.state.read().await.request_count
    }

    /// Get elapsed time since start
    pub async fn elapsed_secs(&self) -> u64 {
        self.state.read().await.start_time.elapsed().as_secs()
    }

    /// Update configuration
    pub fn update_config(&mut self, config: DataDriftConfig) -> Result<()> {
        config.validate()?;
        self.config = config;
        Ok(())
    }

    /// Get current configuration
    pub fn config(&self) -> &DataDriftConfig {
        &self.config
    }
}

/// Pre-defined drift scenarios
pub mod scenarios {
    use super::*;

    /// Order status progression
    pub fn order_status_drift() -> DriftRule {
        let mut transitions = HashMap::new();
        transitions.insert(
            "pending".to_string(),
            vec![
                ("processing".to_string(), 0.7),
                ("cancelled".to_string(), 0.3),
            ],
        );
        transitions.insert(
            "processing".to_string(),
            vec![("shipped".to_string(), 0.9), ("cancelled".to_string(), 0.1)],
        );
        transitions.insert("shipped".to_string(), vec![("delivered".to_string(), 1.0)]);
        transitions.insert("delivered".to_string(), vec![]);
        transitions.insert("cancelled".to_string(), vec![]);

        DriftRule::new("status".to_string(), DriftStrategy::StateMachine)
            .with_states(vec![
                "pending".to_string(),
                "processing".to_string(),
                "shipped".to_string(),
                "delivered".to_string(),
                "cancelled".to_string(),
            ])
            .with_transitions(transitions)
    }

    /// Stock quantity depletion
    pub fn stock_depletion_drift() -> DriftRule {
        DriftRule::new("quantity".to_string(), DriftStrategy::Linear)
            .with_rate(-1.0)
            .with_bounds(Value::from(0), Value::from(1000))
    }

    /// Price fluctuation
    pub fn price_fluctuation_drift() -> DriftRule {
        DriftRule::new("price".to_string(), DriftStrategy::RandomWalk)
            .with_rate(0.5)
            .with_bounds(Value::from(0.0), Value::from(10000.0))
    }

    /// User activity score
    pub fn activity_score_drift() -> DriftRule {
        DriftRule::new("activity_score".to_string(), DriftStrategy::Linear)
            .with_rate(0.1)
            .with_bounds(Value::from(0.0), Value::from(100.0))
    }
}

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

    #[test]
    fn test_drift_strategy_serde() {
        let strategy = DriftStrategy::Linear;
        let serialized = serde_json::to_string(&strategy).unwrap();
        let deserialized: DriftStrategy = serde_json::from_str(&serialized).unwrap();
        assert_eq!(strategy, deserialized);
    }

    #[test]
    fn test_drift_rule_builder() {
        let rule = DriftRule::new("quantity".to_string(), DriftStrategy::Linear)
            .with_rate(1.5)
            .with_bounds(Value::from(0), Value::from(100));

        assert_eq!(rule.field, "quantity");
        assert_eq!(rule.strategy, DriftStrategy::Linear);
        assert_eq!(rule.rate, 1.5);
    }

    #[test]
    fn test_drift_rule_validate() {
        let rule = DriftRule::new("test".to_string(), DriftStrategy::Linear);
        assert!(rule.validate().is_ok());
    }

    #[test]
    fn test_drift_rule_validate_empty_field() {
        let rule = DriftRule::new("".to_string(), DriftStrategy::Linear);
        assert!(rule.validate().is_err());
    }

    #[test]
    fn test_drift_config_builder() {
        let rule = DriftRule::new("field".to_string(), DriftStrategy::Linear);
        let config = DataDriftConfig::new().with_rule(rule).with_request_based(10).with_seed(42);

        assert_eq!(config.rules.len(), 1);
        assert!(config.request_based);
        assert_eq!(config.interval, 10);
        assert_eq!(config.seed, Some(42));
    }

    #[tokio::test]
    async fn test_drift_engine_creation() {
        let config = DataDriftConfig::new();
        let result = DataDriftEngine::new(config);
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_drift_engine_reset() {
        let config = DataDriftConfig::new();
        let engine = DataDriftEngine::new(config).unwrap();
        engine.reset().await;
        assert_eq!(engine.request_count().await, 0);
    }

    #[test]
    fn test_order_status_drift_scenario() {
        let rule = scenarios::order_status_drift();
        assert_eq!(rule.field, "status");
        assert_eq!(rule.strategy, DriftStrategy::StateMachine);
    }

    #[test]
    fn test_stock_depletion_drift_scenario() {
        let rule = scenarios::stock_depletion_drift();
        assert_eq!(rule.field, "quantity");
        assert_eq!(rule.strategy, DriftStrategy::Linear);
        assert_eq!(rule.rate, -1.0);
    }
}