mrapids 0.1.31

Your OpenAPI, but executable
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
# Implementation Guide: Reference-Aware Parsing

## Technical Deep Dive

This guide provides implementation details for developers working with the reference-aware parsing system.

## Core Problem: Serde Untagged Enum Limitation

### The Issue

Serde's `#[serde(untagged)]` attribute attempts to deserialize into each variant in order. When encountering a mixed array like:

```json
[
  { "name": "limit", "in": "query" },
  { "$ref": "#/components/parameters/page" }
]
```

Serde tries to deserialize the second element as a Parameter object, fails (missing "name" field), and reports an error before trying the Reference variant.

### Why Two-Pass Parsing?

1. **First Pass**: Parse as generic Value (always succeeds)
2. **Second Pass**: Inspect each value and route to appropriate type

This approach gives us full control over the deserialization logic.

## Implementation Patterns

### 1. Generic Reference Conversion

```rust
/// Pattern for converting any type that might be a reference
fn convert_value_to_ref_or<T, F>(value: &Value, convert_fn: F) -> Result<ReferenceOr<T>>
where
    T: Clone,
    F: FnOnce(&Value) -> Result<T>,
{
    // Check for $ref first
    if let Some(reference) = value.get("$ref").and_then(|v| v.as_str()) {
        Ok(ReferenceOr::Reference {
            reference: reference.to_string(),
        })
    } else {
        // Attempt conversion to concrete type
        Ok(ReferenceOr::Item(convert_fn(value)?))
    }
}
```

### 2. Array Conversion Pattern

```rust
/// Convert array of potentially mixed references/items
fn convert_array_to_reference_or_parameters(arr: &Vec<Value>) -> Vec<ReferenceOr<Parameter>> {
    arr.iter()
        .filter_map(|v| {
            match convert_value_to_ref_or(v, |val| {
                serde_json::from_value::<Parameter>(val.clone())
                    .context("Failed to parse parameter")
            }) {
                Ok(ref_or_param) => Some(ref_or_param),
                Err(e) => {
                    eprintln!("Warning: Failed to parse parameter: {}", e);
                    None
                }
            }
        })
        .collect()
}
```

### 3. Map Conversion Pattern

```rust
/// Convert HashMap of potentially mixed references/items
fn convert_map_to_reference_or<T, F>(
    map: &serde_json::Map<String, Value>,
    converter: F,
) -> HashMap<String, ReferenceOr<T>>
where
    F: Fn(&Value) -> Result<T>,
    T: Clone,
{
    let mut result = HashMap::new();
    for (key, value) in map {
        match convert_value_to_ref_or(value, |v| converter(v)) {
            Ok(ref_or_item) => {
                result.insert(key.clone(), ref_or_item);
            }
            Err(e) => {
                eprintln!("Warning: Failed to convert {} - {}", key, e);
            }
        }
    }
    result
}
```

## Reference Resolution Strategy

### 1. Caching Architecture

```rust
pub struct SpecResolver {
    components: Option<Components>,
    // Type-specific caches
    parameter_cache: HashMap<String, Parameter>,
    schema_cache: HashMap<String, Schema>,
    response_cache: HashMap<String, Response>,
    request_body_cache: HashMap<String, RequestBody>,
}
```

Benefits:
- Avoids repeated lookups
- Handles circular references gracefully
- Improves performance for large specs

### 2. Resolution Pattern

```rust
pub fn resolve_parameter(&mut self, item: &ReferenceOr<Parameter>) -> Result<Parameter> {
    match item {
        ReferenceOr::Item(p) => Ok(p.clone()),
        ReferenceOr::Reference { reference } => {
            // 1. Check cache first
            if let Some(cached) = self.parameter_cache.get(reference) {
                return Ok(cached.clone());
            }
            
            // 2. Parse reference path
            let param_name = reference.strip_prefix("#/components/parameters/")
                .ok_or_else(|| anyhow::anyhow!("Invalid parameter reference: {}", reference))?;
            
            // 3. Look up in components
            let components = self.components.as_ref()
                .ok_or_else(|| anyhow::anyhow!("No components section found"))?;
            
            // 4. Get the parameter (might itself be a reference)
            let param_ref = components.parameters.as_ref()
                .and_then(|params| params.get(param_name))
                .ok_or_else(|| anyhow::anyhow!("Parameter not found: {}", param_name))?;
            
            // 5. Recursively resolve if needed
            let resolved = match param_ref {
                ReferenceOr::Item(p) => p.clone(),
                ReferenceOr::Reference { .. } => {
                    // Clone to avoid borrow conflicts
                    let param_ref_clone = param_ref.clone();
                    self.resolve_parameter(&param_ref_clone)?
                }
            };
            
            // 6. Cache the result
            self.parameter_cache.insert(reference.clone(), resolved.clone());
            Ok(resolved)
        }
    }
}
```

### 3. Handling Borrow Checker Conflicts

When resolving nested references, we might need to access `self.components` multiple times. Solution:

```rust
// Clone the reference to avoid borrow conflict
let param_ref_clone = param_ref.clone();
// Drop temporary borrows
let _ = components;
let _ = parameters;
// Now we can call self.resolve_parameter again
self.resolve_parameter(&param_ref_clone)?
```

## Flattening Implementation

### 1. Recursive Value Flattening

```rust
fn flatten_value(value: &mut Value, resolver: &mut SpecResolver, path: &mut Vec<String>) -> Result<()> {
    match value {
        Value::Object(map) => {
            // Check if this is a reference object
            if let Some(Value::String(ref_str)) = map.get("$ref") {
                let ref_str = ref_str.clone();
                
                // Resolve the reference
                let resolved = resolve_reference(&ref_str, resolver)?;
                
                // Replace the entire object with resolved value
                *value = resolved;
                
                // Continue flattening the resolved value
                flatten_value(value, resolver, path)?;
            } else {
                // Recursively flatten all values in the object
                for (key, val) in map.iter_mut() {
                    path.push(key.clone());
                    flatten_value(val, resolver, path)?;
                    path.pop();
                }
            }
        }
        Value::Array(arr) => {
            // Recursively flatten all values in the array
            for (i, val) in arr.iter_mut().enumerate() {
                path.push(format!("[{}]", i));
                flatten_value(val, resolver, path)?;
                path.pop();
            }
        }
        _ => {} // Primitive values don't need flattening
    }
    
    Ok(())
}
```

### 2. Reference Resolution for Flattening

```rust
fn resolve_reference(reference: &str, resolver: &mut SpecResolver) -> Result<Value> {
    // Parse the reference path
    if let Some(path) = reference.strip_prefix("#/components/") {
        let parts: Vec<&str> = path.split('/').collect();
        let component_type = parts[0];
        let component_name = parts[1];
        
        // Resolve based on component type
        match component_type {
            "parameters" => {
                let param_ref = ReferenceOr::Reference { reference: reference.to_string() };
                let param = resolver.resolve_parameter(&param_ref)?;
                serde_json::to_value(param).context("Failed to serialize parameter")
            }
            "schemas" => {
                let schema_ref = ReferenceOr::Reference { reference: reference.to_string() };
                let schema = resolver.resolve_schema(&schema_ref)?;
                serde_json::to_value(schema).context("Failed to serialize schema")
            }
            // ... handle other types
            _ => Err(anyhow::anyhow!("Unsupported component type: {}", component_type))
        }
    } else {
        Err(anyhow::anyhow!("Only local references (#/components/...) are currently supported"))
    }
}
```

## Validation Implementation

### 1. Validation Result Structure

```rust
pub struct ValidationResult {
    pub errors: Vec<ValidationError>,
    pub warnings: Vec<ValidationError>,
}

pub struct ValidationError {
    pub path: String,    // JSONPath-like location
    pub message: String, // Human-readable error
}
```

### 2. Path Parameter Validation

```rust
fn extract_path_parameters(path: &str) -> HashSet<String> {
    let mut params = HashSet::new();
    let mut in_param = false;
    let mut current_param = String::new();
    
    for ch in path.chars() {
        if ch == '{' {
            in_param = true;
            current_param.clear();
        } else if ch == '}' {
            if in_param {
                params.insert(current_param.clone());
                in_param = false;
            }
        } else if in_param {
            current_param.push(ch);
        }
    }
    
    params
}
```

### 3. Reference Tracking for Unused Detection

```rust
// Track all referenced components during validation
let mut referenced_params = HashSet::new();
let mut referenced_schemas = HashSet::new();

// When encountering a reference:
if reference.starts_with("#/components/parameters/") {
    let param_name = reference.trim_start_matches("#/components/parameters/");
    referenced_params.insert(param_name.to_string());
}

// After validation, check for unused:
for param_name in params.keys() {
    if !referenced_params.contains(param_name) {
        result.add_warning(
            &format!("components.parameters.{}", param_name),
            "Parameter is defined but never used"
        );
    }
}
```

## Error Handling Best Practices

### 1. Context-Rich Errors

```rust
let content = fs::read_to_string(&cmd.spec)
    .map_err(|e| anyhow::anyhow!("Cannot read spec file: {}", e))?;

let raw_value: serde_yaml::Value = serde_yaml::from_str(content)
    .context("Failed to parse OpenAPI spec as YAML")?;
```

### 2. Graceful Degradation

```rust
// In conversion functions, log warnings but continue
match convert_value_to_ref_or(value, |v| converter(v)) {
    Ok(ref_or_item) => {
        result.insert(key.clone(), ref_or_item);
    }
    Err(e) => {
        eprintln!("Warning: Failed to convert {} - {}", key, e);
        // Continue processing other items
    }
}
```

### 3. User-Friendly Output

```rust
// Provide actionable error messages
if param.location == "path" && param.required != Some(true) {
    result.add_error(
        &format!("{}.parameters[{}]", path, i),
        &format!("Path parameter '{}' must be required", param.name)
    );
}
```

## Performance Considerations

1. **Caching**: All resolved references are cached to avoid repeated lookups
2. **Lazy Evaluation**: Components are only parsed when needed
3. **Early Returns**: Cache checks happen before any parsing
4. **Minimal Cloning**: Use references where possible, clone only when necessary

## Testing Strategies

### 1. Unit Tests for Conversion Functions

```rust
#[test]
fn test_convert_value_to_ref_or() {
    // Test reference
    let ref_value = json!({"$ref": "#/components/parameters/limit"});
    let result = convert_value_to_ref_or(&ref_value, |_| unreachable!()).unwrap();
    assert!(matches!(result, ReferenceOr::Reference { .. }));
    
    // Test inline item
    let item_value = json!({"name": "limit", "in": "query"});
    let result = convert_value_to_ref_or(&item_value, |v| {
        serde_json::from_value::<Parameter>(v.clone())
    }).unwrap();
    assert!(matches!(result, ReferenceOr::Item(_)));
}
```

### 2. Integration Tests with Real Specs

```rust
#[test]
fn test_github_api_spec() {
    let content = fs::read_to_string("tests/fixtures/github-api.yaml").unwrap();
    let result = parse_openapi_v3(&content);
    assert!(result.is_ok());
    let spec = result.unwrap();
    assert!(spec.operations.len() > 700);
}
```

### 3. Validation Tests

```rust
#[test]
fn test_validation_catches_errors() {
    let invalid_spec = r#"
    openapi: 3.0.0
    info:
      title: ""
      version: 1.0.0
    paths:
      /users: {}
    "#;
    
    let doc: OpenAPIDocument = serde_yaml::from_str(invalid_spec).unwrap();
    let result = validate_openapi(&doc);
    
    assert!(!result.is_valid());
    assert!(result.errors.iter().any(|e| e.message.contains("Title cannot be empty")));
}
```

## Debugging Tips

1. **Enable Debug Output**: Temporarily uncomment `eprintln!` statements
2. **Use JSON Output**: `mrapids validate spec.yaml -f json` for structured errors
3. **Test Incrementally**: Use small test specs before large ones
4. **Check Caches**: Add debug prints to see what's being cached
5. **Path Tracking**: The `path` parameter in recursive functions helps locate issues

## Common Pitfalls and Solutions

1. **Borrow Checker Issues**: Clone references when needed for recursive calls
2. **Missing Null Checks**: Always check Option values before unwrapping
3. **Reference Format**: Ensure references start with `#/components/`
4. **Array Indices**: Remember arrays can contain references at any position
5. **Error Propagation**: Use `?` operator consistently for clean error handling

## Future Extension Points

1. **External References**: Add HTTP client for remote refs
2. **Circular Detection**: Implement visited set in resolver
3. **Custom Validators**: Plugin system for domain-specific validation
4. **Performance Metrics**: Add timing information for large specs
5. **Streaming Parser**: For extremely large specifications