roas 0.17.0

Rust OpenAPI Specification — parser, validator, and loader for OpenAPI v2.0 / v3.0.x / v3.1.x / v3.2.x
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
//! Structural merge helpers shared across versions.
//!
//! Generic over `V` and `T`, so each per-version impl block calls into
//! them with its own `V`. The dedup-policy decision (per-version files
//! stay duplicated except `reference.rs`) is preserved.
//!
//! All helpers in this module no-op when `ctx.errored` is already set,
//! so callers do not need to interleave `if ctx.errored { return; }`
//! checks between successive calls. The first helper to record a
//! `Resolution::Errored` flips the flag and every subsequent helper
//! returns early.
//!
//! Path traversal uses a `&mut String` stack: each helper pushes its
//! own segment before recording a conflict and truncates back when
//! it returns. The non-conflict path therefore performs zero String
//! allocations (the original implementation `format!`'d a fresh
//! `String` for every field of every node, conflict or not). The
//! [`push_segment`] / [`PathGuard`] pair encapsulates the RAII
//! push/truncate dance so call sites stay readable.

use std::collections::BTreeMap;

use crate::merge::{ConflictKind, MergeContext, MergeWithContext};

/// RAII guard that pushes a segment onto `path` on construction and
/// truncates it back to the original length on drop. Holding the
/// guard for the duration of a child call keeps the path valid for
/// any conflict recording that happens inside.
pub(crate) struct PathGuard<'a> {
    path: &'a mut String,
    original_len: usize,
}

impl<'a> PathGuard<'a> {
    pub(crate) fn new(path: &'a mut String, segment: &str) -> Self {
        let original_len = path.len();
        path.push_str(segment);
        PathGuard { path, original_len }
    }

    pub(crate) fn path_mut(&mut self) -> &mut String {
        self.path
    }
}

impl Drop for PathGuard<'_> {
    fn drop(&mut self) {
        self.path.truncate(self.original_len);
    }
}

/// Convenience for ad-hoc pushes that don't immediately go into a
/// helper that already does its own push (e.g. when recording a
/// conflict directly from a component impl).
#[inline]
pub(crate) fn with_segment<R>(
    path: &mut String,
    segment: &str,
    f: impl FnOnce(&mut String) -> R,
) -> R {
    let mut guard = PathGuard::new(path, segment);
    f(guard.path_mut())
}

/// Merge two bare `BTreeMap`s by key. Used by `Paths`, `Callback`,
/// `Components.<bag>` (each bag is `Option<BTreeMap<...>>` — wrap with
/// [`merge_opt_map`] for those).
pub(crate) fn merge_map<K, V>(
    base: &mut BTreeMap<K, V>,
    other: BTreeMap<K, V>,
    ctx: &mut MergeContext,
    path: &mut String,
    mut recurse: impl FnMut(&mut V, V, &mut MergeContext, &mut String),
    fmt_key: impl Fn(&K, &mut String),
) where
    K: Ord,
{
    if ctx.errored {
        return;
    }
    for (k, incoming) in other {
        if let Some(base_v) = base.get_mut(&k) {
            // Use the PathGuard so a panic inside `recurse` still
            // restores the buffer on unwind. Merge runs against owned
            // data and doesn't itself panic, but a buggy user-supplied
            // recurse callback could — and dropped guards keep the
            // module invariant ("path balanced at every return") intact.
            let mut guard = PathGuard::new(path, ".");
            fmt_key(&k, guard.path_mut());
            recurse(base_v, incoming, ctx, guard.path_mut());
            drop(guard);
            if ctx.errored {
                return;
            }
        } else {
            base.insert(k, incoming);
        }
    }
}

/// Merge two `Option<BTreeMap<K, V>>` (the common shape for
/// `Components.<bag>` and the dozens of optional-map sub-fields).
/// Pushes `segment` onto `path` only when there's something to do.
pub(crate) fn merge_opt_map<K, V>(
    base: &mut Option<BTreeMap<K, V>>,
    other: Option<BTreeMap<K, V>>,
    ctx: &mut MergeContext,
    path: &mut String,
    segment: &str,
    recurse: impl FnMut(&mut V, V, &mut MergeContext, &mut String),
    fmt_key: impl Fn(&K, &mut String),
) where
    K: Ord,
{
    if ctx.errored {
        return;
    }
    let Some(other) = other else { return };
    match base {
        Some(base_map) => {
            let mut guard = PathGuard::new(path, segment);
            merge_map(base_map, other, ctx, guard.path_mut(), recurse, fmt_key);
        }
        None => *base = Some(other),
    }
}

/// Merge an identity-keyed `Vec` (e.g. `tags` by name, `parameters` by
/// `(name, in)`). On collision the recursion callback decides what
/// happens; new keys are appended in incoming order.
pub(crate) fn merge_vec_by_key<V, K>(
    base: &mut Vec<V>,
    other: Vec<V>,
    ctx: &mut MergeContext,
    path: &mut String,
    key_of: impl Fn(&V) -> K,
    mut recurse: impl FnMut(&mut V, V, &mut MergeContext, &mut String),
    fmt_key: impl Fn(&K, &mut String),
) where
    K: Ord + Clone,
{
    if ctx.errored {
        return;
    }
    use std::collections::BTreeMap as Map;
    let mut index: Map<K, usize> = Map::new();
    for (i, v) in base.iter().enumerate() {
        index.insert(key_of(v), i);
    }
    for incoming in other {
        let k = key_of(&incoming);
        if let Some(&i) = index.get(&k) {
            // PathGuard restores the buffer even if `recurse` panics
            // — same panic-safety reasoning as `merge_map`.
            let mut guard = PathGuard::new(path, "[");
            fmt_key(&k, guard.path_mut());
            guard.path_mut().push(']');
            recurse(&mut base[i], incoming, ctx, guard.path_mut());
            drop(guard);
            if ctx.errored {
                return;
            }
        } else {
            index.insert(k, base.len());
            base.push(incoming);
        }
    }
}

/// Merge an optional identity-keyed vec, treating `None` like an
/// empty list on either side.
#[allow(clippy::too_many_arguments)] // 8 args; this is a structural plumbing helper.
pub(crate) fn merge_opt_vec_by_key<V, K>(
    base: &mut Option<Vec<V>>,
    other: Option<Vec<V>>,
    ctx: &mut MergeContext,
    path: &mut String,
    segment: &str,
    key_of: impl Fn(&V) -> K,
    recurse: impl FnMut(&mut V, V, &mut MergeContext, &mut String),
    fmt_key: impl Fn(&K, &mut String),
) where
    K: Ord + Clone,
{
    if ctx.errored {
        return;
    }
    let Some(other) = other else { return };
    match base {
        Some(base_v) => {
            let mut guard = PathGuard::new(path, segment);
            merge_vec_by_key(
                base_v,
                other,
                ctx,
                guard.path_mut(),
                key_of,
                recurse,
                fmt_key,
            );
        }
        None => *base = Some(other),
    }
}

/// Set-union an `Option<Vec<V>>` while preserving the base order
/// (incoming-only entries appended in incoming order). No conflict
/// is recorded — adding more tags / `required` entries is purely
/// additive.
///
/// Linear-scan dedup: `Vec::contains` against the grown base.
pub(crate) fn merge_opt_vec_set_union<V>(
    base: &mut Option<Vec<V>>,
    other: Option<Vec<V>>,
    ctx: &mut MergeContext,
    _path: &mut String,
    _segment: &str,
) where
    V: Eq,
{
    if ctx.errored {
        return;
    }
    let Some(other) = other else { return };
    match base {
        Some(base_v) => {
            for v in other {
                if !base_v.contains(&v) {
                    base_v.push(v);
                }
            }
        }
        None => *base = Some(other),
    }
}

/// Merge an optional scalar. `None × x` keeps `x`. `Some(a) × Some(b)`
/// where `a == b` is a no-op. Mismatching values run through the
/// three-mode policy.
///
/// `segment` is appended onto `path` only when a real conflict is
/// recorded — the non-conflict path never grows `path`.
pub(crate) fn merge_opt_scalar<V>(
    base: &mut Option<V>,
    other: Option<V>,
    ctx: &mut MergeContext,
    path: &mut String,
    segment: &str,
    kind: ConflictKind,
) where
    V: PartialEq,
{
    if ctx.errored {
        return;
    }
    match (base.as_mut(), other) {
        (_, None) => {}
        (None, Some(v)) => *base = Some(v),
        (Some(a), Some(b)) => {
            if *a != b {
                let take = with_segment(path, segment, |p| ctx.should_take_incoming(p, kind));
                if take {
                    *a = b;
                }
            }
        }
    }
}

/// Merge a required scalar (one that's always present, like
/// `info.title`). Same policy as [`merge_opt_scalar`] for the
/// `Some × Some` arm.
pub(crate) fn merge_required_scalar<V>(
    base: &mut V,
    other: V,
    ctx: &mut MergeContext,
    path: &mut String,
    segment: &str,
    kind: ConflictKind,
) where
    V: PartialEq,
{
    if ctx.errored {
        return;
    }
    if *base != other {
        let take = with_segment(path, segment, |p| ctx.should_take_incoming(p, kind));
        if take {
            *base = other;
        }
    }
}

/// Replace `base` with `other` only when `other` is non-empty.
/// Records [`ConflictKind::ListReplaced`] when an actual replacement
/// occurs. Used for `servers`, `security`, etc.
pub(crate) fn merge_replace_list_when_nonempty<V>(
    base: &mut Option<Vec<V>>,
    other: Option<Vec<V>>,
    ctx: &mut MergeContext,
    path: &mut String,
    segment: &str,
) {
    if ctx.errored {
        return;
    }
    use crate::merge::MergeOptions;
    let replace_when_empty = ctx.is_option(MergeOptions::ReplaceListsWhenEmpty);
    let Some(other) = other else { return };
    if other.is_empty() && !replace_when_empty {
        return;
    }
    match base {
        Some(b) if !b.is_empty() => {
            let take = with_segment(path, segment, |p| {
                ctx.should_take_incoming(p, ConflictKind::ListReplaced)
            });
            if take {
                *b = other;
            }
        }
        _ => *base = Some(other),
    }
}

/// Merge `Option<BTreeMap<String, serde_json::Value>>` extensions
/// per-key. Identical JSON values are no-ops; differing values go
/// through the policy.
pub(crate) fn merge_extensions(
    base: &mut Option<BTreeMap<String, serde_json::Value>>,
    other: Option<BTreeMap<String, serde_json::Value>>,
    ctx: &mut MergeContext,
    path: &mut String,
    segment: &str,
) {
    if ctx.errored {
        return;
    }
    let Some(other) = other else { return };
    let base_map = base.get_or_insert_with(BTreeMap::new);
    let mut guard = PathGuard::new(path, segment);
    for (k, incoming) in other {
        match base_map.get_mut(&k) {
            None => {
                base_map.insert(k, incoming);
            }
            Some(existing) => {
                if *existing != incoming {
                    let take = with_segment(guard.path_mut(), ".", |p| {
                        p.push_str(&k);
                        ctx.should_take_incoming(p, ConflictKind::ScalarOverridden)
                    });
                    if take {
                        *existing = incoming;
                    }
                }
            }
        }
        if ctx.errored {
            return;
        }
    }
}

/// Merge two `Option<S>` where `S: MergeWithContext`. Mirrors the
/// scalar shape but recurses on `Some × Some`.
pub(crate) fn merge_opt_struct<S>(
    base: &mut Option<S>,
    other: Option<S>,
    ctx: &mut MergeContext,
    path: &mut String,
    segment: &str,
) where
    S: MergeWithContext,
{
    if ctx.errored {
        return;
    }
    match (base.as_mut(), other) {
        (_, None) => {}
        (None, Some(v)) => *base = Some(v),
        (Some(a), Some(b)) => {
            let mut guard = PathGuard::new(path, segment);
            a.merge_with_context(b, ctx, guard.path_mut());
        }
    }
}

/// Record a collision where the documented contract says "base is
/// kept" — used by every per-version `Spec::merge_with_context` for
/// `info` / `openapi` (or `swagger` in v2) when `MergeInfo` is off.
/// Records `Resolution::Base` in the default / `BaseWins` modes
/// (reflecting what actually happened) and trips
/// `ErrorOnConflict` when set. Pushes `segment` onto `path` only
/// when actually recording, keeping the eager-allocation regression
/// off the non-conflict path.
pub(crate) fn record_kept_base_or_error(
    ctx: &mut MergeContext,
    path: &mut String,
    segment: &str,
    kind: ConflictKind,
) {
    use crate::merge::{MergeOptions, Resolution};
    let original_len = path.len();
    path.push_str(segment);
    if ctx.is_option(MergeOptions::ErrorOnConflict) {
        ctx.record(path.clone(), kind, Resolution::Errored);
        ctx.errored = true;
    } else {
        ctx.record(path.clone(), kind, Resolution::Base);
    }
    path.truncate(original_len);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::merge::{ConflictKind, MergeOptions};

    fn root_path() -> String {
        "#".to_owned()
    }

    #[test]
    fn merge_opt_scalar_none_incoming_no_op() {
        let mut base: Option<String> = Some("a".into());
        let mut ctx: MergeContext = MergeContext::new(MergeOptions::new());
        let mut path = root_path();
        merge_opt_scalar(
            &mut base,
            None,
            &mut ctx,
            &mut path,
            ".x",
            ConflictKind::ScalarOverridden,
        );
        assert_eq!(base.as_deref(), Some("a"));
        assert!(ctx.conflicts.is_empty());
        assert_eq!(path, "#", "path stack must be balanced");
    }

    #[test]
    fn merge_opt_scalar_none_base_takes_incoming() {
        let mut base: Option<String> = None;
        let mut ctx: MergeContext = MergeContext::new(MergeOptions::new());
        let mut path = root_path();
        merge_opt_scalar(
            &mut base,
            Some("b".into()),
            &mut ctx,
            &mut path,
            ".x",
            ConflictKind::ScalarOverridden,
        );
        assert_eq!(base.as_deref(), Some("b"));
        assert!(ctx.conflicts.is_empty());
    }

    #[test]
    fn merge_opt_scalar_same_value_no_conflict() {
        let mut base: Option<String> = Some("a".into());
        let mut ctx: MergeContext = MergeContext::new(MergeOptions::new());
        let mut path = root_path();
        merge_opt_scalar(
            &mut base,
            Some("a".into()),
            &mut ctx,
            &mut path,
            ".x",
            ConflictKind::ScalarOverridden,
        );
        assert_eq!(base.as_deref(), Some("a"));
        assert!(ctx.conflicts.is_empty());
    }

    #[test]
    fn merge_opt_scalar_differing_takes_incoming_by_default() {
        let mut base: Option<String> = Some("a".into());
        let mut ctx: MergeContext = MergeContext::new(MergeOptions::new());
        let mut path = root_path();
        merge_opt_scalar(
            &mut base,
            Some("b".into()),
            &mut ctx,
            &mut path,
            ".x",
            ConflictKind::ScalarOverridden,
        );
        assert_eq!(base.as_deref(), Some("b"));
        assert_eq!(ctx.conflicts.len(), 1);
        assert_eq!(ctx.conflicts[0].path, "#.x", "conflict path materialised");
        assert_eq!(path, "#", "path stack balanced after conflict");
    }

    #[test]
    fn merge_opt_vec_set_union_dedupes_and_preserves_base_order() {
        let mut base: Option<Vec<i32>> = Some(vec![1, 2]);
        let mut ctx: MergeContext = MergeContext::new(MergeOptions::new());
        let mut path = root_path();
        merge_opt_vec_set_union(&mut base, Some(vec![2, 3]), &mut ctx, &mut path, ".x");
        assert_eq!(base.unwrap(), vec![1, 2, 3]);
        assert!(ctx.conflicts.is_empty());
    }

    #[test]
    fn merge_extensions_new_key_inserts() {
        let mut base: Option<BTreeMap<String, serde_json::Value>> = Some({
            let mut m = BTreeMap::new();
            m.insert("x-a".into(), serde_json::json!(1));
            m
        });
        let mut other = BTreeMap::new();
        other.insert("x-b".into(), serde_json::json!(2));
        let mut ctx: MergeContext = MergeContext::new(MergeOptions::new());
        let mut path = root_path();
        merge_extensions(&mut base, Some(other), &mut ctx, &mut path, ".ext");
        let b = base.unwrap();
        assert_eq!(b.get("x-a"), Some(&serde_json::json!(1)));
        assert_eq!(b.get("x-b"), Some(&serde_json::json!(2)));
        assert_eq!(path, "#", "path balanced");
    }

    #[test]
    fn merge_replace_list_keeps_populated_base_when_incoming_empty() {
        let mut base: Option<Vec<i32>> = Some(vec![1, 2]);
        let mut ctx: MergeContext = MergeContext::new(MergeOptions::new());
        let mut path = root_path();
        merge_replace_list_when_nonempty(&mut base, Some(vec![]), &mut ctx, &mut path, ".servers");
        assert_eq!(base, Some(vec![1, 2]));
        assert!(ctx.conflicts.is_empty());
    }

    #[test]
    fn merge_replace_list_replaces_when_both_non_empty() {
        let mut base: Option<Vec<i32>> = Some(vec![1, 2]);
        let mut ctx: MergeContext = MergeContext::new(MergeOptions::new());
        let mut path = root_path();
        merge_replace_list_when_nonempty(
            &mut base,
            Some(vec![9, 10]),
            &mut ctx,
            &mut path,
            ".servers",
        );
        assert_eq!(base, Some(vec![9, 10]));
        assert_eq!(ctx.conflicts.len(), 1);
        assert_eq!(ctx.conflicts[0].kind, ConflictKind::ListReplaced);
        assert_eq!(ctx.conflicts[0].path, "#.servers");
    }

    #[test]
    fn path_guard_restores_path_on_drop() {
        let mut path = "#.foo".to_owned();
        {
            let mut guard = PathGuard::new(&mut path, ".bar");
            assert_eq!(guard.path_mut(), "#.foo.bar");
        }
        assert_eq!(path, "#.foo");
    }

    #[test]
    fn path_guard_restores_path_on_drop_with_nested_guards() {
        let mut path = "#".to_owned();
        {
            let mut g1 = PathGuard::new(&mut path, ".a");
            {
                let mut g2 = PathGuard::new(g1.path_mut(), ".b");
                assert_eq!(g2.path_mut(), "#.a.b");
            }
            assert_eq!(g1.path_mut(), "#.a");
        }
        assert_eq!(path, "#");
    }
}