mockforge-core 0.3.113

Shared logic for MockForge - routing, validation, latency, proxy
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
//! Performance benchmarks for MockForge core functionality
//!
//! Run with: cargo bench --bench core_benchmarks
//!
//! ## Memory Benchmarks
//!
//! Memory profiling is included for operations that allocate significant memory:
//! - Large OpenAPI spec parsing
//! - Bulk data generation
//! - Deep template rendering

#![allow(missing_docs)]
//!
//! These benchmarks use smaller sample sizes to reduce overhead while still
//! providing meaningful memory usage insights.

use criterion::{black_box, criterion_group, criterion_main, Criterion};
use mockforge_core::openapi_routes::create_registry_from_json;
use mockforge_core::templating::expand_str;
use mockforge_core::validation::{validate_json_schema, ValidationResult, Validator};
use serde_json::json;

/// Benchmark template rendering with different payload sizes
fn bench_template_rendering(c: &mut Criterion) {
    let mut group = c.benchmark_group("template_rendering");

    // Simple template with recognized token ({{uuid}} is a built-in token)
    group.bench_function("simple", |b| {
        let template = "Hello {{uuid}}!";
        b.iter(|| expand_str(black_box(template)));
    });

    // Complex template with multiple variables
    group.bench_function("complex", |b| {
        let template = r#"
            User: {{user.name}}
            Email: {{user.email}}
            Age: {{user.age}}
            Address: {{user.address.street}}, {{user.address.city}}
        "#;
        b.iter(|| expand_str(black_box(template)));
    });

    // Template with arrays
    group.bench_function("arrays", |b| {
        let template = "{{#each items}}{{name}}: {{price}}\n{{/each}}";
        b.iter(|| expand_str(black_box(template)));
    });

    group.finish();
}

/// Benchmark JSON schema validation
fn bench_json_validation(c: &mut Criterion) {
    let mut group = c.benchmark_group("json_validation");

    // Simple schema - pre-compile validator to avoid recompilation overhead
    let simple_schema = json!({
        "type": "object",
        "properties": {
            "name": {"type": "string"}
        }
    });
    let simple_data = json!({"name": "test"});
    // Pre-compile validator once to measure actual validation performance
    let simple_validator = Validator::from_json_schema(&simple_schema).unwrap();

    group.bench_function("simple", |b| {
        b.iter(|| {
            // Use pre-compiled validator to avoid schema compilation overhead
            let result = match simple_validator.validate(black_box(&simple_data)) {
                Ok(_) => ValidationResult::success(),
                Err(e) => ValidationResult::failure(vec![e.to_string()]),
            };
            black_box(result)
        });
    });

    // Complex schema with nested objects - pre-compile validator
    let complex_schema = json!({
        "type": "object",
        "properties": {
            "user": {
                "type": "object",
                "properties": {
                    "name": {"type": "string", "minLength": 1},
                    "email": {"type": "string", "format": "email"},
                    "age": {"type": "integer", "minimum": 0, "maximum": 150}
                },
                "required": ["name", "email"]
            }
        },
        "required": ["user"]
    });
    let complex_data = json!({
        "user": {
            "name": "John Doe",
            "email": "john@example.com",
            "age": 30
        }
    });
    // Pre-compile validator once to measure actual validation performance
    let complex_validator = Validator::from_json_schema(&complex_schema).unwrap();

    group.bench_function("complex", |b| {
        b.iter(|| {
            // Use pre-compiled validator to avoid schema compilation overhead
            let result = match complex_validator.validate(black_box(&complex_data)) {
                Ok(_) => ValidationResult::success(),
                Err(e) => ValidationResult::failure(vec![e.to_string()]),
            };
            black_box(result)
        });
    });

    group.finish();
}

/// Benchmark OpenAPI spec parsing
fn bench_openapi_parsing(c: &mut Criterion) {
    let mut group = c.benchmark_group("openapi_parsing");

    // Small spec with few paths
    let small_spec = json!({
        "openapi": "3.0.0",
        "info": {
            "title": "Test API",
            "version": "1.0.0"
        },
        "paths": {
            "/users": {
                "get": {
                    "summary": "Get users",
                    "responses": {
                        "200": {
                            "description": "Success",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "type": "array",
                                        "items": {
                                            "type": "object",
                                            "properties": {
                                                "id": {"type": "integer"},
                                                "name": {"type": "string"}
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    });

    // Use iter_with_setup to avoid cloning in the hot loop
    // Clone is done once in setup, not on every iteration
    group.bench_function("small_spec", |b| {
        b.iter_with_setup(
            || small_spec.clone(),
            |spec| {
                let result = create_registry_from_json(black_box(spec));
                black_box(result)
            },
        );
    });

    // Medium spec with multiple paths
    let mut paths = serde_json::Map::new();
    for i in 0..10 {
        let path = format!("/resource{}", i);
        paths.insert(
            path,
            json!({
                "get": {
                    "summary": format!("Get resource {}", i),
                    "responses": {
                        "200": {
                            "description": "Success",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "type": "object",
                                        "properties": {
                                            "id": {"type": "integer"},
                                            "name": {"type": "string"}
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }),
        );
    }

    let medium_spec = json!({
        "openapi": "3.0.0",
        "info": {
            "title": "Test API",
            "version": "1.0.0"
        },
        "paths": paths
    });

    // Use iter_with_setup to avoid cloning in the hot loop
    // Clone is done once in setup, not on every iteration
    group.bench_function("medium_spec_10_paths", |b| {
        b.iter_with_setup(
            || medium_spec.clone(),
            |spec| {
                let result = create_registry_from_json(black_box(spec));
                black_box(result)
            },
        );
    });

    group.finish();
}

/// Benchmark data generation
fn bench_data_generation(c: &mut Criterion) {
    use mockforge_data::{DataConfig, DataGenerator, SchemaDefinition};
    use serde_json::json;

    let mut group = c.benchmark_group("data_generation");

    // Create a simple schema for benchmarking
    let schema = SchemaDefinition::from_json_schema(&json!({
        "type": "object",
        "properties": {
            "name": {"type": "string"},
            "email": {"type": "string"},
            "id": {"type": "string"}
        }
    }))
    .unwrap();

    let config = DataConfig {
        rows: 1,
        ..Default::default()
    };

    // Use iter_with_setup to create a fresh generator for each iteration
    // This ensures we're measuring actual data generation, not just reference checks
    group.bench_function("generate_single_record", |b| {
        b.iter_with_setup(
            || {
                // Setup: Create a new generator for each iteration
                DataGenerator::new(schema.clone(), config.clone()).unwrap()
            },
            |mut generator| {
                // Benchmark: Actually generate a single record
                let result = generator.generate_single().unwrap();
                black_box(result)
            },
        );
    });

    group.finish();
}

/// Benchmark encryption/decryption
fn bench_encryption(c: &mut Criterion) {
    use mockforge_core::encryption::{EncryptionAlgorithm, EncryptionKey};
    use rand::{rng, Rng};

    let mut group = c.benchmark_group("encryption");

    // Benchmark AES-256-GCM encryption/decryption
    group.bench_function("aes256_gcm", |b| {
        b.iter_with_setup(
            || {
                // Setup: Generate a random 32-byte key for AES-256-GCM
                let mut key_bytes = [0u8; 32];
                rng().fill(&mut key_bytes);
                EncryptionKey::new(EncryptionAlgorithm::Aes256Gcm, key_bytes.to_vec()).unwrap()
            },
            |key| {
                // Benchmark: Encrypt and decrypt a test string
                let plaintext = "benchmark test data for encryption performance testing";
                let encrypted = key.encrypt(plaintext, None).unwrap();
                let decrypted = key.decrypt(&encrypted, None).unwrap();
                black_box(decrypted)
            },
        );
    });

    // Benchmark ChaCha20-Poly1305 encryption/decryption
    group.bench_function("chacha20_poly1305", |b| {
        b.iter_with_setup(
            || {
                // Setup: Generate a random 32-byte key for ChaCha20-Poly1305
                let mut key_bytes = [0u8; 32];
                rng().fill(&mut key_bytes);
                EncryptionKey::new(EncryptionAlgorithm::ChaCha20Poly1305, key_bytes.to_vec())
                    .unwrap()
            },
            |key| {
                // Benchmark: Encrypt and decrypt a test string
                let plaintext = "benchmark test data for encryption performance testing";
                let encrypted = key.encrypt(plaintext, None).unwrap();
                let decrypted = key.decrypt(&encrypted, None).unwrap();
                black_box(decrypted)
            },
        );
    });

    group.finish();
}

/// Helper function to create a large OpenAPI spec for memory benchmarking
fn create_large_openapi_spec() -> serde_json::Value {
    let mut paths = serde_json::Map::new();

    // Create 100 paths with complex schemas to stress memory
    for i in 0..100 {
        let path = format!("/api/v1/resource_{}", i);
        paths.insert(path, json!({
            "get": {
                "summary": format!("Get resource {}", i),
                "parameters": [
                    {
                        "name": "id",
                        "in": "path",
                        "required": true,
                        "schema": {"type": "string"}
                    },
                    {
                        "name": "filter",
                        "in": "query",
                        "schema": {"type": "string"}
                    }
                ],
                "responses": {
                    "200": {
                        "description": "Success",
                        "content": {
                            "application/json": {
                                "schema": {
                                    "type": "object",
                                    "properties": {
                                        "id": {"type": "integer"},
                                        "name": {"type": "string"},
                                        "description": {"type": "string"},
                                        "metadata": {
                                            "type": "object",
                                            "properties": {
                                                "created_at": {"type": "string", "format": "date-time"},
                                                "updated_at": {"type": "string", "format": "date-time"},
                                                "tags": {
                                                    "type": "array",
                                                    "items": {"type": "string"}
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            },
            "post": {
                "summary": format!("Create resource {}", i),
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "type": "object",
                                "properties": {
                                    "name": {"type": "string"},
                                    "description": {"type": "string"}
                                },
                                "required": ["name"]
                            }
                        }
                    }
                },
                "responses": {
                    "201": {
                        "description": "Created",
                        "content": {
                            "application/json": {
                                "schema": {
                                    "type": "object",
                                    "properties": {
                                        "id": {"type": "integer"}
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }));
    }

    json!({
        "openapi": "3.0.0",
        "info": {
            "title": "Large Test API",
            "version": "1.0.0",
            "description": "A large API spec for memory benchmarking"
        },
        "paths": paths
    })
}

/// Benchmark memory usage for large operations
fn bench_memory_usage(c: &mut Criterion) {
    let mut group = c.benchmark_group("memory");
    group.sample_size(10);

    // Pre-create the large spec once to avoid variance from JSON construction
    // This ensures we're measuring parsing/route generation, not JSON creation
    let large_spec = create_large_openapi_spec();

    // Benchmark large OpenAPI spec parsing
    group.bench_function("large_spec_parsing", |b| {
        b.iter_with_setup(
            || large_spec.clone(), // Clone the pre-created spec (more predictable than recreating)
            |spec| {
                let result = create_registry_from_json(black_box(spec));
                black_box(result)
            },
        );
    });

    // Benchmark deep template rendering
    group.bench_function("deep_template_rendering", |b| {
        b.iter_with_setup(
            || {
                // Create a deeply nested template
                let mut template = String::from("{{#each items}}");
                for i in 0..10 {
                    template.push_str(&format!("  Level {}: {{{{level{}}}}}\n", i, i));
                    template.push_str("  {{#each nested}}");
                }
                for _ in 0..10 {
                    template.push_str("  {{/each}}");
                }
                template.push_str("{{/each}}");
                template
            },
            |template| {
                let result = expand_str(black_box(&template));
                black_box(result)
            },
        );
    });

    // Benchmark complex validation with large data
    group.bench_function("large_data_validation", |b| {
        b.iter_with_setup(
            || {
                let schema = json!({
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "id": {"type": "integer"},
                            "name": {"type": "string", "minLength": 1},
                            "email": {"type": "string", "format": "email"},
                            "metadata": {
                                "type": "object",
                                "properties": {
                                    "tags": {
                                        "type": "array",
                                        "items": {"type": "string"}
                                    }
                                }
                            }
                        },
                        "required": ["id", "name", "email"]
                    },
                    "minItems": 1
                });

                let mut data = Vec::new();
                for i in 0..100 {
                    data.push(json!({
                        "id": i,
                        "name": format!("User {}", i),
                        "email": format!("user{}@example.com", i),
                        "metadata": {
                            "tags": ["tag1", "tag2", "tag3"]
                        }
                    }));
                }

                (schema, json!(data))
            },
            |(schema, data)| {
                let result = validate_json_schema(black_box(&data), black_box(&schema));
                black_box(result)
            },
        );
    });

    group.finish();
}

// Benchmark group for core functionality
criterion_group!(
    benches,
    bench_template_rendering,
    bench_json_validation,
    bench_openapi_parsing,
    bench_data_generation,
    bench_encryption,
    bench_memory_usage
);
criterion_main!(benches);