Skip to main content

soothfast_spec/
compat.rs

1//! Consumer compatibility: what changed, and whether it breaks anyone.
2//!
3//! Once a spec is generated it can no longer disagree with the code, so the
4//! question worth gating shifts: not "does this match?" but "did this break
5//! the people calling it?". Every generated dialect asks that same question,
6//! and the payload half of the answer is always a JSON Schema comparison, so
7//! it lives here rather than in any one dialect.
8//!
9//! Requiredness means opposite things in the two directions, which is the
10//! subtlety the whole module turns on:
11//!
12//! - **Request** (consumer → us): growing *stricter* breaks them. A newly
13//!   required field is breaking; dropping a requirement is not.
14//! - **Response** (us → consumer): providing *less* breaks them. A field that
15//!   stops being guaranteed is breaking; a new one is not.
16
17use std::collections::{BTreeMap, BTreeSet};
18
19use serde_json::Value;
20
21/// Whether a change can break an existing consumer.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
23pub enum Severity {
24    /// Safe to release: consumers written against the old spec still work.
25    Additive,
26    /// Breaks consumers written against the old spec.
27    Breaking,
28}
29
30/// One difference between two versions of a spec.
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct Change {
33    pub severity: Severity,
34    /// Where it happened, e.g. `POST /items requestBody.qty`.
35    pub at: String,
36    pub detail: String,
37}
38
39impl Change {
40    /// A change of `severity` at `at`, described by `detail`.
41    pub fn new(severity: Severity, at: impl Into<String>, detail: impl Into<String>) -> Self {
42        Change {
43            severity,
44            at: at.into(),
45            detail: detail.into(),
46        }
47    }
48}
49
50/// True when nothing in the diff would break an existing consumer.
51pub fn is_compatible(changes: &[Change]) -> bool {
52    !changes.iter().any(|c| c.severity == Severity::Breaking)
53}
54
55/// Order a diff for reporting: breaking first, then by location, so output is
56/// stable between runs.
57pub fn sort(changes: &mut [Change]) {
58    changes.sort_by(|a, b| {
59        b.severity
60            .cmp(&a.severity)
61            .then_with(|| a.at.cmp(&b.at))
62            .then_with(|| a.detail.cmp(&b.detail))
63    });
64}
65
66/// Which way the data flows, which decides what "required" costs.
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub enum Direction {
69    /// Consumer-authored data arriving at us.
70    Request,
71    /// Data we hand to a consumer.
72    Response,
73}
74
75/// Compares schemas belonging to two revisions of a document.
76///
77/// Both documents are held because a `$ref` only means anything relative to
78/// the document it came from: the same pointer can name different shapes on
79/// either side of the comparison.
80pub struct SchemaDiff<'a> {
81    old_doc: &'a Value,
82    new_doc: &'a Value,
83}
84
85impl<'a> SchemaDiff<'a> {
86    /// Compare schemas from `old_doc` against schemas from `new_doc`.
87    pub fn new(old_doc: &'a Value, new_doc: &'a Value) -> Self {
88        SchemaDiff { old_doc, new_doc }
89    }
90
91    /// Compare two schemas in a known data-flow direction, appending whatever
92    /// differs to `changes`.
93    pub fn compare(
94        &self,
95        changes: &mut Vec<Change>,
96        at: &str,
97        old: &Value,
98        new: &Value,
99        dir: Direction,
100    ) {
101        self.walk(changes, at, old, new, dir, &mut BTreeSet::new());
102    }
103
104    fn walk(
105        &self,
106        changes: &mut Vec<Change>,
107        at: &str,
108        old: &Value,
109        new: &Value,
110        dir: Direction,
111        seen: &mut BTreeSet<(String, String)>,
112    ) {
113        // Self-referential schemas would otherwise recurse forever.
114        let pair = (
115            old["$ref"].as_str().unwrap_or_default().to_string(),
116            new["$ref"].as_str().unwrap_or_default().to_string(),
117        );
118        if !pair.0.is_empty() || !pair.1.is_empty() {
119            if seen.contains(&pair) {
120                return;
121            }
122            seen.insert(pair);
123        }
124
125        let old = deref(self.old_doc, old);
126        let new = deref(self.new_doc, new);
127
128        let (ot, nt) = (&old["type"], &new["type"]);
129        if ot != nt && !(ot.is_null() && nt.is_null()) {
130            changes.push(Change::new(
131                Severity::Breaking,
132                at,
133                format!("type {} -> {}", render(ot), render(nt)),
134            ));
135            return; // Field-level diffs are meaningless once the type moved.
136        }
137
138        // Arrays: compare element schemas.
139        if ot == "array" {
140            self.walk(
141                changes,
142                &format!("{at}[]"),
143                &old["items"],
144                &new["items"],
145                dir,
146                seen,
147            );
148            return;
149        }
150
151        let empty = serde_json::Map::new();
152        let old_props = old["properties"].as_object().unwrap_or(&empty);
153        let new_props = new["properties"].as_object().unwrap_or(&empty);
154        let old_req = required_set(old);
155        let new_req = required_set(new);
156
157        let names: BTreeSet<&String> = old_props.keys().chain(new_props.keys()).collect();
158        for name in names {
159            let where_ = format!("{at}.{name}");
160            match (old_props.get(name), new_props.get(name)) {
161                (Some(_), None) => {
162                    // Losing a response field breaks readers; losing a request
163                    // field means data callers still send is now ignored.
164                    changes.push(Change::new(Severity::Breaking, where_, "property removed"));
165                }
166                (None, Some(_)) => {
167                    let newly_required = new_req.contains(name.as_str());
168                    let severity = match (dir, newly_required) {
169                        // A new required request field breaks every caller.
170                        (Direction::Request, true) => Severity::Breaking,
171                        _ => Severity::Additive,
172                    };
173                    changes.push(Change::new(severity, where_, "property added"));
174                }
175                (Some(o), Some(n)) => {
176                    match (
177                        old_req.contains(name.as_str()),
178                        new_req.contains(name.as_str()),
179                    ) {
180                        (false, true) if dir == Direction::Request => changes.push(Change::new(
181                            Severity::Breaking,
182                            &where_,
183                            "became required",
184                        )),
185                        (true, false) if dir == Direction::Response => changes.push(Change::new(
186                            Severity::Breaking,
187                            &where_,
188                            "no longer guaranteed",
189                        )),
190                        (false, true) => changes.push(Change::new(
191                            Severity::Additive,
192                            &where_,
193                            "became required",
194                        )),
195                        (true, false) => changes.push(Change::new(
196                            Severity::Additive,
197                            &where_,
198                            "became optional",
199                        )),
200                        _ => {}
201                    }
202                    self.walk(changes, &where_, o, n, dir, seen);
203                }
204                (None, None) => {}
205            }
206        }
207
208        compare_enum(changes, at, old, new);
209    }
210}
211
212/// A removed accepted value breaks callers that still send or expect it.
213fn compare_enum(changes: &mut Vec<Change>, at: &str, old: &Value, new: &Value) {
214    let values = |v: &Value| -> BTreeSet<String> {
215        let mut out = BTreeSet::new();
216        if let Some(c) = v.get("const") {
217            out.insert(render(c));
218        }
219        if let Some(list) = v["enum"].as_array() {
220            out.extend(list.iter().map(render));
221        }
222        out
223    };
224    let (o, n) = (values(old), values(new));
225    if o.is_empty() && n.is_empty() {
226        return;
227    }
228    for gone in o.difference(&n) {
229        changes.push(Change::new(
230            Severity::Breaking,
231            at,
232            format!("value {gone} no longer accepted"),
233        ));
234    }
235    for added in n.difference(&o) {
236        changes.push(Change::new(
237            Severity::Additive,
238            at,
239            format!("value {added} added"),
240        ));
241    }
242}
243
244/// Follow a local `$ref` to the schema it names, once.
245///
246/// Resolution is by JSON Pointer rather than by a fixed `components/schemas`
247/// prefix: dialects disagree on where shared schemas live (`#/$defs/X` inside
248/// one tool's schema, `#/components/schemas/X` at the document root), and the
249/// pointer already says which.
250pub fn deref<'a>(doc: &'a Value, schema: &'a Value) -> &'a Value {
251    let Some(pointer) = schema["$ref"].as_str() else {
252        return schema;
253    };
254    match resolve_pointer(doc, pointer) {
255        Some(target) => target,
256        None => schema,
257    }
258}
259
260/// Walk a `#/a/b/c` JSON Pointer from a document root.
261fn resolve_pointer<'a>(doc: &'a Value, pointer: &str) -> Option<&'a Value> {
262    let path = pointer.strip_prefix('#')?;
263    let mut node = doc;
264    for raw in path.split('/').skip(1) {
265        if raw.is_empty() {
266            continue;
267        }
268        let token = raw.replace("~1", "/").replace("~0", "~");
269        node = node.get(&token)?;
270    }
271    Some(node)
272}
273
274/// The `required` names of an object schema.
275pub fn required_set(schema: &Value) -> BTreeSet<&str> {
276    schema["required"]
277        .as_array()
278        .map(|a| a.iter().filter_map(|v| v.as_str()).collect())
279        .unwrap_or_default()
280}
281
282/// A JSON value as it should read inside a diff message.
283pub fn render(v: &Value) -> String {
284    match v {
285        Value::String(s) => s.clone(),
286        Value::Null => "none".into(),
287        other => other.to_string(),
288    }
289}
290
291/// Compare two maps of named entries, reporting bare presence changes and
292/// handing matched pairs to `both`.
293///
294/// Added and removed entries mean the same thing in every dialect — a tool, a
295/// channel, an operation or a field that appears or disappears — so only the
296/// wording and the severity of a *removal* differ between callers.
297pub fn compare_keys<F>(
298    changes: &mut Vec<Change>,
299    old: &BTreeMap<String, Value>,
300    new: &BTreeMap<String, Value>,
301    noun: &str,
302    mut both: F,
303) where
304    F: FnMut(&mut Vec<Change>, &str, &Value, &Value),
305{
306    let keys: BTreeSet<&String> = old.keys().chain(new.keys()).collect();
307    for key in keys {
308        match (old.get(key), new.get(key)) {
309            (Some(_), None) => changes.push(Change::new(
310                Severity::Breaking,
311                key.clone(),
312                format!("{noun} removed"),
313            )),
314            (None, Some(_)) => changes.push(Change::new(
315                Severity::Additive,
316                key.clone(),
317                format!("{noun} added"),
318            )),
319            (Some(o), Some(n)) => both(changes, key, o, n),
320            (None, None) => {}
321        }
322    }
323}
324
325#[cfg(test)]
326mod tests {
327    use super::*;
328    use serde_json::json;
329
330    fn diff_schemas(old: &Value, new: &Value, dir: Direction) -> Vec<Change> {
331        let empty = json!({});
332        let mut changes = Vec::new();
333        SchemaDiff::new(&empty, &empty).compare(&mut changes, "at", old, new, dir);
334        changes
335    }
336
337    #[test]
338    fn a_new_required_request_field_breaks_callers() {
339        let old = json!({ "type": "object", "properties": { "a": { "type": "string" } } });
340        let new = json!({ "type": "object",
341                          "properties": { "a": { "type": "string" }, "b": { "type": "string" } },
342                          "required": ["b"] });
343        let changes = diff_schemas(&old, &new, Direction::Request);
344        assert_eq!(changes[0].severity, Severity::Breaking);
345        assert_eq!(changes[0].at, "at.b");
346    }
347
348    #[test]
349    fn the_same_new_field_on_a_response_is_additive() {
350        let old = json!({ "type": "object", "properties": { "a": { "type": "string" } } });
351        let new = json!({ "type": "object",
352                          "properties": { "a": { "type": "string" }, "b": { "type": "string" } },
353                          "required": ["b"] });
354        let changes = diff_schemas(&old, &new, Direction::Response);
355        assert_eq!(changes[0].severity, Severity::Additive);
356    }
357
358    #[test]
359    fn a_response_field_that_stops_being_guaranteed_breaks_readers() {
360        let old = json!({ "type": "object", "properties": { "a": { "type": "string" } },
361                          "required": ["a"] });
362        let new = json!({ "type": "object", "properties": { "a": { "type": "string" } } });
363        let changes = diff_schemas(&old, &new, Direction::Response);
364        assert_eq!(changes[0].severity, Severity::Breaking);
365        assert_eq!(changes[0].detail, "no longer guaranteed");
366    }
367
368    #[test]
369    fn refs_resolve_through_a_json_pointer_wherever_defs_live() {
370        let old_doc = json!({ "$defs": { "Item": { "type": "object",
371                                                   "properties": { "id": { "type": "string" } } } } });
372        let new_doc = json!({ "$defs": { "Item": { "type": "object",
373                                                   "properties": { "id": { "type": "integer" } } } } });
374        let r = json!({ "$ref": "#/$defs/Item" });
375        let mut changes = Vec::new();
376        SchemaDiff::new(&old_doc, &new_doc).compare(
377            &mut changes,
378            "Item",
379            &r,
380            &r,
381            Direction::Response,
382        );
383        assert_eq!(changes.len(), 1, "got {changes:?}");
384        assert_eq!(changes[0].detail, "type string -> integer");
385    }
386
387    #[test]
388    fn a_ref_that_resolves_nowhere_is_left_as_written() {
389        let doc = json!({});
390        let schema = json!({ "$ref": "#/components/schemas/Gone" });
391        assert_eq!(deref(&doc, &schema), &schema);
392    }
393
394    #[test]
395    fn a_self_referential_schema_terminates() {
396        let doc = json!({ "$defs": { "Node": { "type": "object",
397                                               "properties": { "next": { "$ref": "#/$defs/Node" } } } } });
398        let r = json!({ "$ref": "#/$defs/Node" });
399        let mut changes = Vec::new();
400        SchemaDiff::new(&doc, &doc).compare(&mut changes, "Node", &r, &r, Direction::Response);
401        assert!(changes.is_empty(), "got {changes:?}");
402    }
403
404    #[test]
405    fn a_removed_enum_value_breaks_consumers() {
406        let old = json!({ "type": "string", "enum": ["a", "b"] });
407        let new = json!({ "type": "string", "enum": ["a"] });
408        let changes = diff_schemas(&old, &new, Direction::Response);
409        assert_eq!(changes[0].severity, Severity::Breaking);
410        assert!(changes[0].detail.contains('b'));
411    }
412
413    #[test]
414    fn breaking_changes_sort_ahead_of_additive_ones() {
415        let mut changes = vec![
416            Change::new(Severity::Additive, "z", "added"),
417            Change::new(Severity::Breaking, "a", "removed"),
418        ];
419        sort(&mut changes);
420        assert_eq!(changes[0].severity, Severity::Breaking);
421        assert!(!is_compatible(&changes));
422    }
423
424    #[test]
425    fn presence_changes_report_with_the_callers_noun() {
426        let old: BTreeMap<String, Value> = [("gone".to_string(), json!({}))].into();
427        let new: BTreeMap<String, Value> = [("fresh".to_string(), json!({}))].into();
428        let mut changes = Vec::new();
429        compare_keys(&mut changes, &old, &new, "tool", |_, _, _, _| {});
430        sort(&mut changes);
431        assert_eq!(changes[0].detail, "tool removed");
432        assert_eq!(changes[0].severity, Severity::Breaking);
433        assert_eq!(changes[1].detail, "tool added");
434    }
435}