mockforge-core 0.3.114

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
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
//! Multi-spec loading and merging utilities
//!
//! This module provides functionality to load multiple OpenAPI specifications,
//! group them by version, detect conflicts, and merge them according to
//! configurable strategies.

use crate::openapi::spec::OpenApiSpec;
use crate::{Error, Result};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use tracing::{debug, info, warn};

/// Conflict resolution strategy for merging specs
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConflictStrategy {
    /// Fail fast on conflicts (default)
    Error,
    /// First file wins
    First,
    /// Last file wins
    Last,
}

impl From<&str> for ConflictStrategy {
    fn from(s: &str) -> Self {
        match s {
            "first" => ConflictStrategy::First,
            "last" => ConflictStrategy::Last,
            _ => ConflictStrategy::Error,
        }
    }
}

/// A detected conflict between specs
#[derive(Debug, Clone)]
pub enum Conflict {
    /// Route conflict: same METHOD + PATH in multiple files
    RouteConflict {
        /// HTTP method
        method: String,
        /// API path
        path: String,
        /// Files containing this route
        files: Vec<PathBuf>,
    },
    /// Component conflict: same key with different definitions
    ComponentConflict {
        /// Type of component (schemas, responses, etc.)
        component_type: String,
        /// Component key/name
        key: String,
        /// Files containing this component
        files: Vec<PathBuf>,
    },
}

/// Error type for merge conflicts
#[derive(Debug)]
pub enum MergeConflictError {
    /// Route conflict error
    RouteConflict {
        /// HTTP method
        method: String,
        /// API path
        path: String,
        /// Files containing this route
        files: Vec<PathBuf>,
    },
    /// Component conflict error
    ComponentConflict {
        /// Type of component (schemas, responses, etc.)
        component_type: String,
        /// Component key/name
        key: String,
        /// Files containing this component
        files: Vec<PathBuf>,
    },
    /// Multiple conflicts detected
    MultipleConflicts {
        /// All detected conflicts
        conflicts: Vec<Conflict>,
    },
}

impl std::fmt::Display for MergeConflictError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            MergeConflictError::MultipleConflicts { conflicts } => {
                writeln!(f, "Found {} spec conflict(s):\n", conflicts.len())?;
                for (i, conflict) in conflicts.iter().enumerate() {
                    match conflict {
                        Conflict::RouteConflict {
                            method,
                            path,
                            files,
                        } => {
                            writeln!(f, "  {}. {} {} defined in:", i + 1, method, path)?;
                            for file in files {
                                writeln!(f, "     - {}", file.display())?;
                            }
                        }
                        Conflict::ComponentConflict {
                            component_type,
                            key,
                            files,
                        } => {
                            writeln!(
                                f,
                                "  {}. components.{}.{} defined in:",
                                i + 1,
                                component_type,
                                key
                            )?;
                            for file in files {
                                writeln!(f, "     - {}", file.display())?;
                            }
                        }
                    }
                }
                writeln!(f)?;
                write!(
                    f,
                    "Resolution options:\n\
                     - Use --merge-conflicts=first to keep the first definition\n\
                     - Use --merge-conflicts=last to keep the last definition\n\
                     - Remove duplicate routes/components from conflicting spec files"
                )
            }
            MergeConflictError::RouteConflict {
                method,
                path,
                files,
            } => {
                write!(
                    f,
                    "Conflict: {} {} defined in {}",
                    method,
                    path,
                    files.iter().map(|p| p.display().to_string()).collect::<Vec<_>>().join(" and ")
                )
            }
            MergeConflictError::ComponentConflict {
                component_type,
                key,
                files,
            } => {
                write!(
                    f,
                    "Conflict: components.{}.{} defined differently in {}",
                    component_type,
                    key,
                    files.iter().map(|p| p.display().to_string()).collect::<Vec<_>>().join(" and ")
                )
            }
        }
    }
}

impl std::error::Error for MergeConflictError {}

/// Load all OpenAPI spec files from a directory
///
/// Discovers all `.json`, `.yaml`, `.yml` files recursively,
/// sorts them lexicographically for deterministic ordering,
/// and loads each spec.
pub async fn load_specs_from_directory(dir: &Path) -> Result<Vec<(PathBuf, OpenApiSpec)>> {
    use globwalk::GlobWalkerBuilder;

    info!("Discovering OpenAPI specs in directory: {}", dir.display());

    if !dir.exists() {
        return Err(Error::internal(format!("Directory does not exist: {}", dir.display())));
    }

    if !dir.is_dir() {
        return Err(Error::internal(format!("Path is not a directory: {}", dir.display())));
    }

    // Discover all spec files
    let mut spec_files = Vec::new();
    let walker = GlobWalkerBuilder::from_patterns(dir, &["**/*.json", "**/*.yaml", "**/*.yml"])
        .build()
        .map_err(|e| Error::internal(format!("Failed to walk directory: {}", e)))?;

    for entry in walker {
        let entry = entry.map_err(|e| Error::io_with_context("directory entry", e.to_string()))?;
        let path = entry.path();
        if path.is_file() {
            spec_files.push(path.to_path_buf());
        }
    }

    // Sort lexicographically for deterministic ordering
    spec_files.sort();

    if spec_files.is_empty() {
        warn!("No OpenAPI spec files found in directory: {}", dir.display());
        return Ok(Vec::new());
    }

    info!("Found {} spec files, loading...", spec_files.len());

    // Load each spec file
    let mut specs = Vec::new();
    for file_path in spec_files {
        match OpenApiSpec::from_file(&file_path).await {
            Ok(spec) => {
                debug!("Loaded spec from: {}", file_path.display());
                specs.push((file_path, spec));
            }
            Err(e) => {
                warn!("Failed to load spec from {}: {}", file_path.display(), e);
                // Continue with other files
            }
        }
    }

    info!("Successfully loaded {} specs from directory", specs.len());
    Ok(specs)
}

/// Load OpenAPI specs from a list of file paths
pub async fn load_specs_from_files(files: Vec<PathBuf>) -> Result<Vec<(PathBuf, OpenApiSpec)>> {
    info!("Loading {} OpenAPI spec files", files.len());

    let mut specs = Vec::new();
    for file_path in files {
        match OpenApiSpec::from_file(&file_path).await {
            Ok(spec) => {
                debug!("Loaded spec from: {}", file_path.display());
                specs.push((file_path, spec));
            }
            Err(e) => {
                return Err(Error::internal(format!(
                    "Failed to load spec from {}: {}",
                    file_path.display(),
                    e
                )));
            }
        }
    }

    info!("Successfully loaded {} specs", specs.len());
    Ok(specs)
}

/// Group specs by OpenAPI document version (the `openapi` field)
///
/// Returns a map from OpenAPI version (e.g., "3.0.0") to lists of (path, spec) tuples.
pub fn group_specs_by_openapi_version(
    specs: Vec<(PathBuf, OpenApiSpec)>,
) -> HashMap<String, Vec<(PathBuf, OpenApiSpec)>> {
    let mut groups: HashMap<String, Vec<(PathBuf, OpenApiSpec)>> = HashMap::new();

    for (path, spec) in specs {
        // Extract OpenAPI version from the spec
        let version = spec
            .raw_document
            .as_ref()
            .and_then(|doc| doc.get("openapi"))
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
            .unwrap_or_else(|| "unknown".to_string());

        groups.entry(version.clone()).or_default().push((path, spec));
    }

    info!("Grouped specs into {} OpenAPI version groups", groups.len());
    for (version, specs_in_group) in &groups {
        info!("  OpenAPI {}: {} specs", version, specs_in_group.len());
    }

    groups
}

/// Group specs by API version (the `info.version` field)
///
/// Returns a map from API version (e.g., "1.0", "2.0") to lists of (path, spec) tuples.
/// Specs without `info.version` are grouped under "unknown".
pub fn group_specs_by_api_version(
    specs: Vec<(PathBuf, OpenApiSpec)>,
) -> HashMap<String, Vec<(PathBuf, OpenApiSpec)>> {
    let mut groups: HashMap<String, Vec<(PathBuf, OpenApiSpec)>> = HashMap::new();

    for (path, spec) in specs {
        // Extract API version from info.version
        let api_version = spec
            .raw_document
            .as_ref()
            .and_then(|doc| doc.get("info"))
            .and_then(|info| info.get("version"))
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
            .unwrap_or_else(|| "unknown".to_string());

        groups.entry(api_version.clone()).or_default().push((path, spec));
    }

    info!("Grouped specs into {} API version groups", groups.len());
    for (version, specs_in_group) in &groups {
        info!("  API version {}: {} specs", version, specs_in_group.len());
    }

    groups
}

/// Detect conflicts between specs
///
/// Returns a list of all detected conflicts (route and component conflicts).
pub fn detect_conflicts(specs: &[(PathBuf, OpenApiSpec)]) -> Vec<Conflict> {
    let mut conflicts = Vec::new();

    // Detect route conflicts (same METHOD + PATH)
    let mut routes: HashMap<(String, String), Vec<PathBuf>> = HashMap::new();
    for (path, spec) in specs {
        for (route_path, path_item_ref) in &spec.spec.paths.paths {
            if let openapiv3::ReferenceOr::Item(path_item) = path_item_ref {
                // Check all HTTP methods
                let methods = vec![
                    ("GET", path_item.get.as_ref()),
                    ("POST", path_item.post.as_ref()),
                    ("PUT", path_item.put.as_ref()),
                    ("DELETE", path_item.delete.as_ref()),
                    ("PATCH", path_item.patch.as_ref()),
                    ("HEAD", path_item.head.as_ref()),
                    ("OPTIONS", path_item.options.as_ref()),
                ];

                for (method, operation) in methods {
                    if operation.is_some() {
                        let key = (method.to_string(), route_path.clone());
                        routes.entry(key).or_default().push(path.clone());
                    }
                }
            }
        }
    }

    // Find route conflicts (same route in multiple files)
    for ((method, route_path), files) in routes {
        if files.len() > 1 {
            conflicts.push(Conflict::RouteConflict {
                method,
                path: route_path,
                files,
            });
        }
    }

    // Detect component conflicts
    for component_type in &[
        "schemas",
        "parameters",
        "responses",
        "requestBodies",
        "headers",
        "examples",
        "links",
        "callbacks",
    ] {
        let mut components: HashMap<String, Vec<PathBuf>> = HashMap::new();

        for (path, spec) in specs {
            if let Some(components_obj) = spec
                .raw_document
                .as_ref()
                .and_then(|doc| doc.get("components"))
                .and_then(|c| c.get(component_type))
            {
                if let Some(components_map) = components_obj.as_object() {
                    for key in components_map.keys() {
                        components.entry(key.clone()).or_default().push(path.clone());
                    }
                }
            }
        }

        // Check for conflicts (same key in multiple files with potentially different definitions)
        for (key, files) in components {
            if files.len() > 1 {
                // Check if definitions are identical
                let mut definitions = Vec::new();
                for (file_path, spec) in specs {
                    if files.contains(file_path) {
                        if let Some(def) = spec
                            .raw_document
                            .as_ref()
                            .and_then(|doc| doc.get("components"))
                            .and_then(|c| c.get(component_type))
                            .and_then(|ct| ct.get(&key))
                        {
                            definitions.push((file_path.clone(), def.clone()));
                        }
                    }
                }

                // Check if all definitions are byte-for-byte identical
                let first_def = &definitions[0].1;
                let all_identical = definitions.iter().all(|(_, def)| {
                    serde_json::to_string(def).ok() == serde_json::to_string(first_def).ok()
                });

                if !all_identical {
                    conflicts.push(Conflict::ComponentConflict {
                        component_type: component_type.to_string(),
                        key,
                        files,
                    });
                }
            }
        }
    }

    conflicts
}

/// Merge multiple OpenAPI specs according to the conflict strategy
///
/// This function merges paths and components from all specs.
/// Conflicts are handled according to the provided strategy.
pub fn merge_specs(
    specs: Vec<(PathBuf, OpenApiSpec)>,
    conflict_strategy: ConflictStrategy,
) -> std::result::Result<OpenApiSpec, MergeConflictError> {
    if specs.is_empty() {
        return Err(MergeConflictError::ComponentConflict {
            component_type: "general".to_string(),
            key: "no_specs".to_string(),
            files: Vec::new(),
        });
    }

    if specs.len() == 1 {
        // No merging needed — safe because we just checked len() == 1
        return specs.into_iter().next().map(|(_, spec)| spec).ok_or_else(|| {
            MergeConflictError::ComponentConflict {
                component_type: "general".to_string(),
                key: "no_specs".to_string(),
                files: Vec::new(),
            }
        });
    }

    // Detect conflicts first
    let conflicts = detect_conflicts(&specs);

    // Handle conflicts based on strategy
    match conflict_strategy {
        ConflictStrategy::Error => {
            if !conflicts.is_empty() {
                // Return all conflicts as an error for comprehensive feedback
                return Err(MergeConflictError::MultipleConflicts {
                    conflicts: conflicts.clone(),
                });
            }
        }
        ConflictStrategy::First | ConflictStrategy::Last => {
            // Log warnings for conflicts
            for conflict in &conflicts {
                match conflict {
                    Conflict::RouteConflict {
                        method,
                        path,
                        files,
                    } => {
                        warn!(
                            "Route conflict: {} {} defined in multiple files: {:?}. Using {} definition.",
                            method, path, files,
                            if conflict_strategy == ConflictStrategy::First { "first" } else { "last" }
                        );
                    }
                    Conflict::ComponentConflict {
                        component_type,
                        key,
                        files,
                    } => {
                        warn!(
                            "Component conflict: components.{} defined in multiple files: {}. Using {} definition (strategy: {}).",
                            component_type, key, files.iter().map(|f| f.display().to_string()).collect::<Vec<_>>().join(", "),
                            if conflict_strategy == ConflictStrategy::First { "first" } else { "last" }
                        );
                    }
                }
            }
        }
    }

    // Collect file paths before processing (needed for error messages)
    let all_file_paths: Vec<PathBuf> = specs.iter().map(|(p, _)| p.clone()).collect();

    // Start with the first spec as the base
    let base_spec = specs.first().map(|(_, spec)| spec.clone()).ok_or_else(|| {
        MergeConflictError::ComponentConflict {
            component_type: "general".to_string(),
            key: "no_specs".to_string(),
            files: Vec::new(),
        }
    })?;
    let mut base_doc = base_spec
        .raw_document
        .as_ref()
        .cloned()
        .unwrap_or_else(|| serde_json::json!({}));

    // Skip the first spec (used as base) and merge the rest
    let specs_to_merge: Vec<&(PathBuf, OpenApiSpec)> = specs.iter().skip(1).collect();

    // Merge each subsequent spec
    for (_file_path, spec) in specs_to_merge {
        let spec_doc = spec.raw_document.as_ref().cloned().unwrap_or_else(|| serde_json::json!({}));

        // Merge paths
        if let Some(paths) = spec_doc.get("paths").and_then(|p| p.as_object()) {
            if base_doc.get("paths").is_none() {
                base_doc["paths"] = serde_json::json!({});
            }
            let base_paths = base_doc["paths"].as_object_mut().ok_or_else(|| {
                MergeConflictError::ComponentConflict {
                    component_type: "paths".to_string(),
                    key: "invalid_type".to_string(),
                    files: all_file_paths.clone(),
                }
            })?;
            for (path, path_item) in paths {
                if base_paths.contains_key(path) {
                    // Conflict - handle based on strategy
                    if conflict_strategy == ConflictStrategy::Last {
                        base_paths.insert(path.clone(), path_item.clone());
                    }
                    // For First and Error, we already handled it above
                } else {
                    base_paths.insert(path.clone(), path_item.clone());
                }
            }
        }

        // Merge components
        if let Some(components) = spec_doc.get("components").and_then(|c| c.as_object()) {
            if base_doc.get("components").is_none() {
                base_doc["components"] = serde_json::json!({});
            }
            let base_components = base_doc["components"].as_object_mut().ok_or_else(|| {
                MergeConflictError::ComponentConflict {
                    component_type: "components".to_string(),
                    key: "invalid_type".to_string(),
                    files: all_file_paths.clone(),
                }
            })?;
            for (component_type, component_obj) in components {
                if let Some(component_map) = component_obj.as_object() {
                    let base_component_map = base_components
                        .entry(component_type.clone())
                        .or_insert_with(|| serde_json::json!({}))
                        .as_object_mut()
                        .ok_or_else(|| MergeConflictError::ComponentConflict {
                            component_type: component_type.clone(),
                            key: "invalid_type".to_string(),
                            files: all_file_paths.clone(),
                        })?;

                    for (key, value) in component_map {
                        if let Some(existing) = base_component_map.get(key) {
                            // Check if identical
                            if serde_json::to_string(existing).ok()
                                != serde_json::to_string(value).ok()
                            {
                                // Different - handle based on strategy
                                if conflict_strategy == ConflictStrategy::Last {
                                    base_component_map.insert(key.clone(), value.clone());
                                }
                                // For First and Error, we already handled it above
                            }
                            // If identical, no action needed
                        } else {
                            base_component_map.insert(key.clone(), value.clone());
                        }
                    }
                }
            }
        }
    }

    // Re-parse the merged document
    let merged_spec: openapiv3::OpenAPI =
        serde_json::from_value(base_doc.clone()).map_err(|e| {
            MergeConflictError::ComponentConflict {
                component_type: "parsing".to_string(),
                key: format!("merge_error: {}", e),
                files: all_file_paths,
            }
        })?;

    Ok(OpenApiSpec {
        spec: merged_spec,
        file_path: None, // Merged spec has no single file path
        raw_document: Some(base_doc),
    })
}