1use std::collections::{BTreeMap, BTreeSet};
35
36use base64::Engine as _;
37use prost::Message as _;
38use prost_reflect::{
39 Cardinality, DescriptorPool, EnumDescriptor, FieldDescriptor, Kind, MessageDescriptor,
40};
41use serde_json::{Map, Value};
42
43use crate::bundle::Bundle;
44use crate::canonical::canonical;
45use crate::contract::Contract;
46use crate::schema::{ArtifactData, jcs};
47
48#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
50pub enum Class {
51 Compatible,
52 Review,
53 Breaking,
54}
55
56impl Class {
57 #[must_use]
58 pub fn as_str(self) -> &'static str {
59 match self {
60 Self::Compatible => "compatible",
61 Self::Review => "review",
62 Self::Breaking => "breaking",
63 }
64 }
65}
66
67#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct Finding {
70 pub class: Class,
71 pub rule: &'static str,
73 pub at: String,
75 pub detail: String,
76}
77
78#[derive(Debug, Clone, Default, PartialEq, Eq)]
80pub struct Verdict {
81 pub findings: Vec<Finding>,
83 pub warnings: Vec<Finding>,
85}
86
87impl Verdict {
88 #[must_use]
90 pub fn class(&self) -> Class {
91 self.findings
92 .iter()
93 .map(|f| f.class)
94 .max()
95 .unwrap_or(Class::Compatible)
96 }
97 #[must_use]
99 pub fn warning_rules(&self) -> Vec<&'static str> {
100 let s: BTreeSet<&'static str> = self.warnings.iter().map(|w| w.rule).collect();
101 s.into_iter().collect()
102 }
103 fn push(&mut self, class: Class, rule: &'static str, at: &str, detail: impl Into<String>) {
104 if class == Class::Compatible {
105 return;
106 }
107 self.findings.push(Finding {
108 class,
109 rule,
110 at: at.to_owned(),
111 detail: detail.into(),
112 });
113 }
114 fn warn(&mut self, rule: &'static str, at: &str, detail: impl Into<String>) {
115 self.warnings.push(Finding {
116 class: Class::Compatible,
117 rule,
118 at: at.to_owned(),
119 detail: detail.into(),
120 });
121 }
122 fn extend(&mut self, other: Verdict) {
123 self.findings.extend(other.findings);
124 self.warnings.extend(other.warnings);
125 }
126}
127
128#[derive(Debug, Clone, PartialEq)]
130pub enum Schema {
131 Protobuf(Vec<u8>),
133 Json(Value),
135}
136
137#[derive(Debug, Clone, PartialEq)]
139pub struct Revision {
140 pub canonical: Value,
141 pub schemas: BTreeMap<String, Schema>,
142}
143
144impl Revision {
145 #[must_use]
147 pub fn of(c: &Contract) -> Self {
148 let schemas = c
149 .artifacts
150 .iter()
151 .map(|(id, a)| {
152 let s = match &a.data {
153 ArtifactData::Protobuf(b) => Schema::Protobuf(b.clone()),
154 ArtifactData::Json(v) => Schema::Json(v.clone()),
155 };
156 (id.clone(), s)
157 })
158 .collect();
159 Self {
160 canonical: canonical(c),
161 schemas,
162 }
163 }
164
165 #[must_use]
167 pub fn of_bundle(b: &Bundle) -> Self {
168 let schemas = b
169 .schemas
170 .iter()
171 .filter_map(|(id, e)| {
172 let data = e.get("data")?;
173 let s = match e.get("kind")?.as_str()? {
174 "protobuf" => Schema::Protobuf(
175 base64::engine::general_purpose::STANDARD
176 .decode(data.as_str()?)
177 .ok()?,
178 ),
179 "jsonschema" | "packed" => Schema::Json(data.clone()),
180 _ => return None,
181 };
182 Some((id.clone(), s))
183 })
184 .collect();
185 Self {
186 canonical: b.contract.clone(),
187 schemas,
188 }
189 }
190
191 fn resources(&self) -> BTreeMap<(String, String), &Value> {
192 self.canonical["resources"]
193 .as_array()
194 .into_iter()
195 .flatten()
196 .filter_map(|r| {
197 Some((
198 (
199 r["kind"].as_str()?.to_owned(),
200 r["template"].as_str()?.to_owned(),
201 ),
202 r,
203 ))
204 })
205 .collect()
206 }
207
208 fn json_by_stem(&self) -> BTreeMap<String, &Value> {
211 let names: BTreeMap<&str, &str> = self.canonical["schemas"]
212 .as_array()
213 .into_iter()
214 .flatten()
215 .filter(|s| s["kind"] == "jsonschema")
216 .filter_map(|s| Some((s["id"].as_str()?, s["name"].as_str()?)))
217 .collect();
218 self.schemas
219 .iter()
220 .filter_map(|(id, s)| match s {
221 Schema::Json(v) => Some((names.get(id.as_str())?.to_string(), v)),
222 Schema::Protobuf(_) => None,
223 })
224 .collect()
225 }
226}
227
228#[must_use]
230pub fn check_history(history: &[Revision], new: &Revision) -> Verdict {
231 let mut v = Verdict::default();
232 for old in history {
233 v.extend(compare(old, new));
234 }
235 v
236}
237
238#[must_use]
240pub fn compare(old: &Revision, new: &Revision) -> Verdict {
241 let mut v = Verdict::default();
242 if old.canonical["interface"] != new.canonical["interface"] {
243 v.push(
244 Class::Breaking,
245 "interface_changed",
246 "interface",
247 "the interface id differs",
248 );
249 return v;
250 }
251 if old.canonical["uses"] != new.canonical["uses"] {
252 v.push(
253 Class::Review,
254 "uses_changed",
255 "interface.uses",
256 "the profiles used changed",
257 );
258 }
259 let (ro, rn) = (old.resources(), new.resources());
260 for (key, o) in &ro {
261 let at = format!("resources.{:?}", key.1);
262 match rn.get(key) {
263 None => v.push(
264 Class::Breaking,
265 "resource_removed",
266 &at,
267 "removed; a deprecated resource stays until the next major",
268 ),
269 Some(n) => compare_resource(o, n, old, new, &at, &mut v),
270 }
271 }
272 for (key, n) in &rn {
273 if ro.contains_key(key) {
274 continue;
275 }
276 let at = format!("resources.{:?}", key.1);
277 if n["optional"] == Value::Bool(true) {
278 } else {
281 v.push(
282 Class::Breaking,
283 "required_resource_added",
284 &at,
285 "a required resource added: old providers lack it",
286 );
287 }
288 }
289 compare_requires(
290 &old.canonical["requires"],
291 &new.canonical["requires"],
292 &mut v,
293 );
294 v
295}
296
297fn s(v: &Value) -> &str {
298 v.as_str().unwrap_or("")
299}
300
301#[allow(clippy::too_many_lines)]
302fn compare_resource(o: &Value, n: &Value, ro: &Revision, rn: &Revision, at: &str, v: &mut Verdict) {
303 match (s(&o["token"]), s(&n["token"])) {
305 (a, b) if a == b => {}
306 ("stream", "@stream") | ("state", "@state") => {
307 v.push(
308 Class::Breaking,
309 "explicit_set",
310 at,
311 "leaves ambient selectors",
312 );
313 }
314 ("@stream", "stream") | ("@state", "state") => {
315 v.push(
316 Class::Review,
317 "explicit_cleared",
318 at,
319 "joins ambient selectors (link budgets)",
320 );
321 }
322 _ => v.push(
323 Class::Breaking,
324 "token_changed",
325 at,
326 "the kind token changed",
327 ),
328 }
329 if o["params"] != n["params"] {
330 v.push(
331 Class::Breaking,
332 "params_changed",
333 at,
334 "a parameter's type changed",
335 );
336 }
337 match (o["optional"].as_bool(), n["optional"].as_bool()) {
338 (Some(true), Some(false)) => {
339 v.push(
340 Class::Breaking,
341 "optional_to_required",
342 at,
343 "old implementers may not expose it",
344 );
345 }
346 (Some(false), Some(true)) => {
347 v.push(
348 Class::Breaking,
349 "required_to_optional",
350 at,
351 "old consumers rely on it",
352 );
353 }
354 _ => {}
355 }
356 for (field, rule) in [
357 ("cardinality", "cardinality_changed"),
358 ("epoch", "epoch_changed"),
359 ("gate", "gate_changed"),
360 ("annotations", "annotations_changed"),
361 ] {
362 if o[field] != n[field] {
363 v.push(Class::Review, rule, at, format!("`{field}` changed"));
364 }
365 }
366 if o["deprecated"] != n["deprecated"] && !n["deprecated"].is_null() && o["deprecated"].is_null()
367 {
368 } else if o["deprecated"] != n["deprecated"] {
370 v.push(
371 Class::Review,
372 "deprecated_changed",
373 at,
374 "`deprecated` changed",
375 );
376 }
377 if s(&o["kind"]) != s(&n["kind"]) {
378 v.push(
379 Class::Breaking,
380 "kind_changed",
381 at,
382 "the resource kind changed",
383 );
384 return;
385 }
386 if o["encoding"] != n["encoding"] {
387 v.push(
388 Class::Breaking,
389 "encoding_changed",
390 at,
391 "the payload encoding changed",
392 );
393 }
394 if s(&o["kind"]) == "operation" {
395 for (field, what) in [("request", Dir::Request), ("response", Dir::Response)] {
396 compare_type(
397 &o[field],
398 &n[field],
399 ro,
400 rn,
401 &format!("{at}.{field}"),
402 what,
403 v,
404 );
405 }
406 for (field, rule) in [
407 ("error", "error_type_changed"),
408 ("summary", "summary_type_changed"),
409 ] {
410 match (o[field].is_null(), n[field].is_null()) {
411 (true, true) => {}
412 (false, false) => compare_type(
413 &o[field],
414 &n[field],
415 ro,
416 rn,
417 &format!("{at}.{field}"),
418 Dir::Response,
419 v,
420 ),
421 _ => v.push(
422 Class::Review,
423 rule,
424 at,
425 format!("`{field}` added or removed"),
426 ),
427 }
428 }
429 if o["idempotent"] == Value::Bool(true) && n["idempotent"] == Value::Bool(false) {
430 v.push(
431 Class::Breaking,
432 "idempotent_cleared",
433 at,
434 "callers may retry it",
435 );
436 } else if o["idempotent"] != n["idempotent"] {
437 v.push(
438 Class::Review,
439 "idempotent_set",
440 at,
441 "new callers may retry old servers",
442 );
443 }
444 if s(&o["fanout"]) == "allowed" && s(&n["fanout"]) == "forbidden" {
445 v.push(
446 Class::Breaking,
447 "fanout_forbidden",
448 at,
449 "fan-out calls are refused",
450 );
451 }
452 if s(&o["replies"]) == "one" && s(&n["replies"]) == "many" {
453 v.push(
454 Class::Breaking,
455 "replies_many",
456 at,
457 "callers' consolidation drops replies",
458 );
459 }
460 for (field, rule) in [
461 ("serving", "serving_changed"),
462 ("timeout_ms", "timeout_changed"),
463 ("priority", "priority_changed"),
464 ] {
465 if o[field] != n[field] {
466 v.push(Class::Review, rule, at, format!("`{field}` changed"));
467 }
468 }
469 return;
470 }
471 compare_type(
472 &o["type"],
473 &n["type"],
474 ro,
475 rn,
476 &format!("{at}.type"),
477 Dir::Data,
478 v,
479 );
480 match (o["attachment"].is_null(), n["attachment"].is_null()) {
481 (true, true) => {}
482 (false, false) => compare_type(
483 &o["attachment"],
484 &n["attachment"],
485 ro,
486 rn,
487 &format!("{at}.attachment"),
488 Dir::Data,
489 v,
490 ),
491 _ => v.push(
492 Class::Review,
493 "attachment_changed",
494 at,
495 "an attachment added or removed",
496 ),
497 }
498 if o["attachment_encoding"] != n["attachment_encoding"]
499 && !o["attachment"].is_null()
500 && !n["attachment"].is_null()
501 {
502 v.push(
503 Class::Breaking,
504 "encoding_changed",
505 at,
506 "the attachment encoding changed",
507 );
508 }
509 if s(&o["reliability"]) == "reliable" && s(&n["reliability"]) == "best_effort" {
510 v.push(
511 Class::Review,
512 "reliability_lowered",
513 at,
514 "reliable → best_effort",
515 );
516 }
517 if o["congestion"] != n["congestion"] {
518 v.push(
519 Class::Review,
520 "congestion_changed",
521 at,
522 "drop ↔ block (it can stall the producer, or drop)",
523 );
524 }
525 for (field, rule) in [
526 ("priority", "priority_changed"),
527 ("express", "express_toggled"),
528 ("history", "history_changed"),
529 ("rate", "rate_changed"),
530 ("retention_s", "retention_changed"),
531 ] {
532 if o[field] != n[field] {
533 v.push(Class::Review, rule, at, format!("`{field}` changed"));
534 }
535 }
536 let fields = if o.get("frame").is_some() && n.get("frame").is_some() {
537 (field_names(ro, &o["type"]), field_names(rn, &n["type"]))
538 } else {
539 (None, None)
540 };
541 compare_frame(o.get("frame"), n.get("frame"), &fields, at, v);
542}
543
544fn field_names(r: &Revision, t: &Value) -> Option<Vec<String>> {
548 if s(&t["kind"]) != "packed" {
549 return None;
550 }
551 let doc = match r.schemas.get(s(&t["schema"]))? {
552 Schema::Json(doc) => doc,
553 Schema::Protobuf(_) => return None,
554 };
555 let layout = crate::packed::PackedDoc::read(doc)
556 .types
557 .remove(s(&t["name"]))
558 .flatten()?;
559 Some(
560 layout
561 .items
562 .iter()
563 .filter_map(|i| match i {
564 crate::packed::Item::Field(f) => Some(f.name.clone()),
565 crate::packed::Item::Marker => None,
566 })
567 .collect(),
568 )
569}
570
571fn compare_frame(
580 o: Option<&Value>,
581 n: Option<&Value>,
582 fields: &(Option<Vec<String>>, Option<Vec<String>>),
583 at: &str,
584 v: &mut Verdict,
585) {
586 let (o, n) = match (o, n) {
587 (None, None) => return,
588 (Some(o), Some(n)) => (o, n),
589 _ => {
590 v.push(
591 Class::Breaking,
592 "frame_toggled",
593 at,
594 "`frame` added or removed: a reader of the other revision reads none of its samples",
595 );
596 return;
597 }
598 };
599 if ["records", "step_ms", "jitter_ms"]
600 .iter()
601 .any(|k| o[*k] != n[*k])
602 {
603 v.push(
604 Class::Breaking,
605 "frame_changed",
606 at,
607 "`records`, `step_ms` or `jitter_ms` changed: the bits and the times move",
608 );
609 }
610 let deadbands_differ = match fields {
611 (Some(old), Some(new)) if old.len() == new.len() => old
612 .iter()
613 .zip(new)
614 .any(|(a, b)| o["deadband"].get(a.as_str()) != n["deadband"].get(b.as_str())),
615 _ => o["deadband"] != n["deadband"],
616 };
617 if deadbands_differ {
618 v.push(
619 Class::Breaking,
620 "deadband_changed",
621 at,
622 "a deadband added, removed or changed: what an omitted field holds moves",
623 );
624 }
625 if o["keyframe_every"] != n["keyframe_every"] {
626 v.push(
627 Class::Review,
628 "keyframe_changed",
629 at,
630 "`keyframe_every` changed: how long a reader waits to heal",
631 );
632 }
633}
634
635fn compare_requires(o: &Value, n: &Value, v: &mut Verdict) {
636 let empty = Map::new();
637 let (o, n) = (
638 o.as_object().unwrap_or(&empty),
639 n.as_object().unwrap_or(&empty),
640 );
641 for (role, ro) in o {
642 let at = format!("requires.{role}");
643 let Some(rn) = n.get(role) else {
644 continue;
646 };
647 if ro["interface"] != rn["interface"] || ro["cardinality"] != rn["cardinality"] {
648 v.push(
649 Class::Breaking,
650 "role_changed",
651 &at,
652 "the role's interface or cardinality changed",
653 );
654 }
655 if ro["optional"] == Value::Bool(true) && rn["optional"] == Value::Bool(false) {
656 v.push(
657 Class::Breaking,
658 "role_required",
659 &at,
660 "deployments must now bind it",
661 );
662 }
663 if ro["resources"] != rn["resources"] || ro["annotations"] != rn["annotations"] {
664 v.push(
665 Class::Review,
666 "role_resources_changed",
667 &at,
668 "what the role consumes changed",
669 );
670 }
671 }
672 for (role, rn) in n {
673 if !o.contains_key(role) && rn["optional"] != Value::Bool(true) {
674 v.push(
675 Class::Breaking,
676 "required_role_added",
677 &format!("requires.{role}"),
678 "deployments must bind it",
679 );
680 }
681 }
682}
683
684#[derive(Debug, Clone, Copy)]
687enum Dir {
688 Data,
689 Request,
690 Response,
691}
692
693fn compare_type(
694 o: &Value,
695 n: &Value,
696 ro: &Revision,
697 rn: &Revision,
698 at: &str,
699 _dir: Dir,
700 v: &mut Verdict,
701) {
702 match (s(&o["kind"]), s(&n["kind"])) {
703 ("raw", "raw") => {
704 if o["media_type"] != n["media_type"] {
705 v.push(
706 Class::Breaking,
707 "media_type_changed",
708 at,
709 "the raw media type changed",
710 );
711 } else if o["media_param"] != n["media_param"] {
712 v.push(
713 Class::Review,
714 "media_param_changed",
715 at,
716 "`media_param` changed",
717 );
718 }
719 }
720 ("protobuf", "protobuf") => {
721 let (Some(po), Some(pn)) = (pool(ro, &o["schema"]), pool(rn, &n["schema"])) else {
722 v.push(
723 Class::Review,
724 "schema_unreadable",
725 at,
726 "a descriptor set does not decode",
727 );
728 return;
729 };
730 match (
731 po.get_message_by_name(s(&o["name"])),
732 pn.get_message_by_name(s(&n["name"])),
733 ) {
734 (Some(mo), Some(mn)) => {
735 let mut seen = BTreeSet::new();
736 compare_messages(&mo, &mn, at, &mut seen, v);
737 }
738 _ => v.push(
739 Class::Review,
740 "schema_unreadable",
741 at,
742 "a message is missing from its descriptor set",
743 ),
744 }
745 }
746 ("jsonschema", "jsonschema") => {
747 let (Some(Schema::Json(doc_old)), Some(Schema::Json(doc_new))) = (
748 ro.schemas.get(s(&o["schema"])),
749 rn.schemas.get(s(&n["schema"])),
750 ) else {
751 v.push(
752 Class::Review,
753 "schema_unreadable",
754 at,
755 "a JSON Schema artifact is missing",
756 );
757 return;
758 };
759 let cx = JsonCx {
760 old_docs: ro.json_by_stem(),
761 new_docs: rn.json_by_stem(),
762 };
763 let so = doc_old["$defs"][s(&o["name"])].clone();
764 let sn = doc_new["$defs"][s(&n["name"])].clone();
765 let mut seen = BTreeSet::new();
766 cx.compare(&so, doc_old, &sn, doc_new, at, &mut seen, v);
767 }
768 ("packed", "packed") => {
769 let layout = |r: &Revision, t: &Value| match r.schemas.get(s(&t["schema"])) {
770 Some(Schema::Json(doc)) => crate::packed::PackedDoc::read(doc)
771 .types
772 .remove(s(&t["name"]))
773 .flatten(),
774 _ => None,
775 };
776 match (layout(ro, o), layout(rn, n)) {
777 (Some(lo), Some(ln)) => compare_packed(&lo, &ln, at, v),
778 _ => v.push(
779 Class::Review,
780 "schema_unreadable",
781 at,
782 "a packed artifact is missing, or does not lay out its type",
783 ),
784 }
785 }
786 _ => v.push(
787 Class::Breaking,
788 "type_kind_changed",
789 at,
790 "the schema kind changed",
791 ),
792 }
793}
794
795fn compare_packed(o: &crate::packed::Layout, n: &crate::packed::Layout, at: &str, v: &mut Verdict) {
799 use crate::packed::Item;
800 let (a, b) = (&o.items, &n.items);
801 for (i, (x, y)) in a.iter().zip(b).enumerate() {
802 let at = format!("{at}.fields[{i}]");
803 match (x, y) {
804 (Item::Marker, Item::Marker) => {}
805 (Item::Field(x), Item::Field(y)) => compare_packed_fields(x, y, &at, v),
806 _ => v.push(
807 Class::Breaking,
808 "fields_changed",
809 &at,
810 "a marker where the other revision has a field",
811 ),
812 }
813 }
814 if a.len() != b.len() {
815 let shorter = if a.len() < b.len() { a } else { b };
816 if !matches!(shorter.last(), Some(Item::Marker)) {
817 v.push(
818 Class::Breaking,
819 "fields_changed",
820 at,
821 "fields added or removed where no marker ends the shorter revision",
822 );
823 }
824 }
825}
826
827fn compare_packed_fields(
828 x: &crate::packed::Field,
829 y: &crate::packed::Field,
830 at: &str,
831 v: &mut Verdict,
832) {
833 use crate::packed::FieldKind as K;
834 if x.kind.as_str() != y.kind.as_str() {
835 v.push(
836 Class::Breaking,
837 "type_changed",
838 at,
839 format!("{} became {}", x.kind.as_str(), y.kind.as_str()),
840 );
841 return;
842 }
843 if x.name != y.name {
844 v.push(
845 Class::Review,
846 "field_renamed",
847 at,
848 format!("{:?} renamed {:?}", x.name, y.name),
849 );
850 }
851 if x.optional != y.optional {
852 v.push(
853 Class::Breaking,
854 "presence_changed",
855 at,
856 "`optional` toggled: the presence bit appears or goes",
857 );
858 }
859 let bound = |v: &mut Verdict| {
860 v.push(Class::Breaking, "bound_changed", at, "a bound moved");
861 };
862 let reserved = |v: &mut Verdict| {
863 v.push(
864 Class::Breaking,
865 "reserved_changed",
866 at,
867 "`reserved` changed: the codes move",
868 );
869 };
870 match (&x.kind, &y.kind) {
871 (
872 K::Int {
873 minimum: a0,
874 maximum: a1,
875 reserved: ra,
876 },
877 K::Int {
878 minimum: b0,
879 maximum: b1,
880 reserved: rb,
881 },
882 ) => {
883 if (a0, a1) != (b0, b1) {
884 bound(v);
885 }
886 if ra != rb {
887 reserved(v);
888 }
889 }
890 (
891 K::Fixed {
892 minimum: a0,
893 maximum: a1,
894 resolution: ar,
895 reserved: ra,
896 ..
897 },
898 K::Fixed {
899 minimum: b0,
900 maximum: b1,
901 resolution: br,
902 reserved: rb,
903 ..
904 },
905 ) => {
906 if (a0, a1) != (b0, b1) {
907 bound(v);
908 }
909 if ar != br {
910 v.push(
911 Class::Breaking,
912 "resolution_changed",
913 at,
914 format!("`resolution` {ar} became {br}"),
915 );
916 }
917 if ra != rb {
918 reserved(v);
919 }
920 }
921 (
922 K::Enum {
923 values: va,
924 escape: ea,
925 },
926 K::Enum {
927 values: vb,
928 escape: eb,
929 },
930 ) => {
931 if x.width != y.width {
932 v.push(
933 Class::Breaking,
934 "width_changed",
935 at,
936 format!("the enum's width {} became {}", x.width, y.width),
937 );
938 }
939 if ea != eb {
942 v.push(Class::Breaking, "enum_changed", at, "the escape toggled");
943 }
944 for (p, q) in va.iter().zip(vb) {
945 if p == q {
946 continue;
947 }
948 if vb.contains(p) || va.contains(q) {
949 v.push(
950 Class::Breaking,
951 "enum_changed",
952 at,
953 format!("{p:?} or {q:?} moved to another index"),
954 );
955 } else {
956 v.push(
957 Class::Review,
958 "enum_value_renamed",
959 at,
960 format!("{p:?} renamed {q:?}"),
961 );
962 }
963 }
964 match (vb.len().cmp(&va.len()), *ea && *eb) {
967 (std::cmp::Ordering::Equal, _) | (std::cmp::Ordering::Greater, true) => {}
968 (std::cmp::Ordering::Less, true) => v.push(
969 Class::Review,
970 "enum_value_removed",
971 at,
972 "a value removed: an old writer still writes it, and a new reader reads the escape",
973 ),
974 (_, false) => v.push(
975 Class::Breaking,
976 "enum_changed",
977 at,
978 "a value added or removed where no escape reads it",
979 ),
980 }
981 }
982 (K::Counter, K::Counter) | (K::Time { .. }, K::Time { .. }) if x.width != y.width => {
983 v.push(
984 Class::Breaking,
985 "width_changed",
986 at,
987 format!("the width {} became {}", x.width, y.width),
988 );
989 }
990 _ => {}
991 }
992}
993
994fn pool(r: &Revision, id: &Value) -> Option<DescriptorPool> {
995 match r.schemas.get(id.as_str()?)? {
996 Schema::Protobuf(b) => DescriptorPool::decode(b.as_slice()).ok(),
997 Schema::Json(_) => None,
998 }
999}
1000
1001fn reserved(m: &MessageDescriptor, number: u32) -> bool {
1002 m.reserved_ranges().any(|r| r.contains(&number))
1003}
1004
1005fn compare_messages(
1006 o: &MessageDescriptor,
1007 n: &MessageDescriptor,
1008 at: &str,
1009 seen: &mut BTreeSet<(String, String)>,
1010 v: &mut Verdict,
1011) {
1012 if !seen.insert((o.full_name().to_owned(), n.full_name().to_owned())) {
1013 return;
1014 }
1015 for fo in o.fields() {
1016 let fat = format!("{at}.{}", fo.name());
1017 match n.get_field(fo.number()) {
1018 Some(fnew) => {
1019 if fo.name() != fnew.name() {
1020 v.push(
1021 Class::Review,
1022 "field_renamed",
1023 &fat,
1024 format!("now {:?}", fnew.name()),
1025 );
1026 } else if fo.json_name() != fnew.json_name() {
1027 v.push(
1028 Class::Review,
1029 "json_name_changed",
1030 &fat,
1031 format!("now {:?}", fnew.json_name()),
1032 );
1033 }
1034 if fo.is_list() != fnew.is_list() || fo.is_map() != fnew.is_map() {
1035 v.push(
1036 Class::Breaking,
1037 "cardinality_changed",
1038 &fat,
1039 "repeated, map or singular changed",
1040 );
1041 continue;
1042 }
1043 if is_required(&fo) != is_required(&fnew) {
1044 v.push(
1045 Class::Breaking,
1046 "required_label_changed",
1047 &fat,
1048 "proto2 `required` toggled",
1049 );
1050 }
1051 let oneof = |f: &prost_reflect::FieldDescriptor| {
1052 f.containing_oneof()
1053 .filter(|o| !o.is_synthetic())
1054 .map(|o| o.name().to_owned())
1055 };
1056 if oneof(&fo) != oneof(&fnew) {
1057 v.push(
1058 Class::Breaking,
1059 "oneof_changed",
1060 &fat,
1061 "moved into or out of a oneof",
1062 );
1063 } else if fo.supports_presence() != fnew.supports_presence() && !fo.is_list() {
1064 v.push(
1065 Class::Review,
1066 "presence_changed",
1067 &fat,
1068 "explicit presence toggled",
1069 );
1070 }
1071 compare_kinds(&fo.kind(), &fnew.kind(), &fat, seen, v);
1072 }
1073 None => {
1074 if is_required(&fo) && n.get_field_by_name(fo.name()).is_none() {
1075 v.push(
1076 Class::Breaking,
1077 "required_field_removed",
1078 &fat,
1079 "a proto2 `required` field deleted: old readers refuse what new writers send",
1080 );
1081 }
1082 if let Some(moved) = n.get_field_by_name(fo.name()) {
1083 v.push(
1084 Class::Breaking,
1085 "renumbered",
1086 &fat,
1087 format!(
1088 "{} → {}: the data is dropped both ways",
1089 fo.number(),
1090 moved.number()
1091 ),
1092 );
1093 } else if !reserved(n, fo.number()) {
1094 v.warn(
1095 "field_deleted_unreserved",
1096 &fat,
1097 format!("field {} deleted without reserving its number", fo.number()),
1098 );
1099 }
1100 }
1101 }
1102 }
1103 for fnew in n.fields() {
1104 if o.get_field(fnew.number()).is_some() || o.get_field_by_name(fnew.name()).is_some() {
1105 continue;
1106 }
1107 if is_required(&fnew) {
1108 v.push(
1109 Class::Breaking,
1110 "required_field_added",
1111 &format!("{at}.{}", fnew.name()),
1112 "a proto2 `required` field added: new readers refuse what old writers send",
1113 );
1114 }
1115 if reserved(o, fnew.number()) {
1116 v.push(
1117 Class::Breaking,
1118 "reserved_reused",
1119 &format!("{at}.{}", fnew.name()),
1120 format!("number {} was reserved", fnew.number()),
1121 );
1122 }
1123 }
1124}
1125
1126fn is_required(f: &FieldDescriptor) -> bool {
1127 f.cardinality() == Cardinality::Required
1128}
1129
1130fn compare_kinds(
1131 o: &Kind,
1132 n: &Kind,
1133 at: &str,
1134 seen: &mut BTreeSet<(String, String)>,
1135 v: &mut Verdict,
1136) {
1137 match (o, n) {
1138 (Kind::Message(mo), Kind::Message(mn)) => compare_messages(mo, mn, at, seen, v),
1139 (Kind::Enum(eo), Kind::Enum(en)) => compare_enums(eo, en, at, v),
1140 (a, b) if std::mem::discriminant(a) == std::mem::discriminant(b) => {}
1141 _ => v.push(
1142 Class::Breaking,
1143 "type_changed",
1144 at,
1145 format!("{o:?} → {n:?}"),
1146 ),
1147 }
1148}
1149
1150fn compare_enums(o: &EnumDescriptor, n: &EnumDescriptor, at: &str, v: &mut Verdict) {
1151 for vo in o.values() {
1152 match n.get_value(vo.number()) {
1153 None => v.push(
1154 Class::Review,
1155 "enum_value_removed",
1156 at,
1157 format!("{} removed", vo.name()),
1158 ),
1159 Some(vn) if vn.name() != vo.name() => {
1160 v.push(
1161 Class::Review,
1162 "enum_value_renamed",
1163 at,
1164 format!("{} → {}", vo.name(), vn.name()),
1165 );
1166 }
1167 Some(_) => {}
1168 }
1169 }
1170 let closed = n.parent_file().syntax() == prost_reflect::Syntax::Proto2;
1171 if closed && n.values().any(|vn| o.get_value(vn.number()).is_none()) {
1172 v.push(
1173 Class::Review,
1174 "closed_enum_value_added",
1175 at,
1176 "a proto2 (closed) enum gained a value: old readers fall back to the default",
1177 );
1178 }
1179}
1180
1181struct JsonCx<'a> {
1184 old_docs: BTreeMap<String, &'a Value>,
1185 new_docs: BTreeMap<String, &'a Value>,
1186}
1187
1188const ANNOTATIONS: &[&str] = &[
1189 "$schema",
1190 "$id",
1191 "$comment",
1192 "title",
1193 "description",
1194 "default",
1195 "examples",
1196 "format",
1197 "deprecated",
1198 "readOnly",
1199 "writeOnly",
1200];
1201const BOUNDS: &[&str] = &[
1202 "minimum",
1203 "maximum",
1204 "exclusiveMinimum",
1205 "exclusiveMaximum",
1206 "minLength",
1207 "maxLength",
1208 "minItems",
1209 "maxItems",
1210];
1211
1212fn strip(v: &Value) -> Value {
1219 match v {
1220 Value::Object(m) => Value::Object(
1221 m.iter()
1222 .filter(|(k, _)| !ANNOTATIONS.contains(&k.as_str()))
1223 .map(|(k, x)| {
1224 let x = match (k.as_str(), x) {
1225 ("properties" | "$defs", Value::Object(subs)) => {
1226 Value::Object(subs.iter().map(|(n, s)| (n.clone(), strip(s))).collect())
1227 }
1228 (
1229 "prefixItems" | "oneOf" | "anyOf" | "items" | "additionalProperties",
1230 sub,
1231 ) => strip(sub),
1232 (_, x) => x.clone(),
1233 };
1234 (k.clone(), x)
1235 })
1236 .collect(),
1237 ),
1238 Value::Array(a) => Value::Array(a.iter().map(strip).collect()),
1239 x => x.clone(),
1240 }
1241}
1242
1243fn types(s: &Value) -> BTreeSet<String> {
1244 match &s["type"] {
1245 Value::String(t) => [t.clone()].into(),
1246 Value::Array(a) => a
1247 .iter()
1248 .filter_map(|t| t.as_str().map(str::to_owned))
1249 .collect(),
1250 _ => BTreeSet::new(),
1251 }
1252}
1253
1254fn is_null_schema(s: &Value) -> bool {
1257 s.as_object().is_some_and(|m| {
1258 m.keys()
1259 .all(|k| k == "type" || ANNOTATIONS.contains(&k.as_str()))
1260 }) && types(s) == BTreeSet::from(["null".to_owned()])
1261}
1262
1263pub fn nullable_reading<T>(
1278 s: &Value,
1279 follow: impl FnOnce(&Value) -> Option<(Value, T)>,
1280) -> Option<(Value, T)> {
1281 let m = s.as_object()?;
1282 if m.keys()
1283 .any(|k| k != "anyOf" && !ANNOTATIONS.contains(&k.as_str()))
1284 {
1285 return None;
1286 }
1287 let [a, b] = m.get("anyOf")?.as_array()?.as_slice() else {
1288 return None;
1289 };
1290 let branch = match (is_null_schema(a), is_null_schema(b)) {
1291 (true, false) => b,
1292 (false, true) => a,
1293 _ => return None,
1294 };
1295 let (mut read, beside) = follow(branch)?;
1296 let r = read.as_object_mut()?;
1297 let typed = match r.get("type") {
1298 Some(Value::String(_)) => true,
1299 Some(Value::Array(a)) => a.iter().all(Value::is_string),
1300 _ => false,
1301 };
1302 if !typed
1303 || ["const", "oneOf", "anyOf"]
1304 .iter()
1305 .any(|k| r.contains_key(*k))
1306 {
1307 return None;
1308 }
1309 let mut t = types(&Value::Object(r.clone()));
1310 t.insert("null".to_owned());
1311 r.insert(
1312 "type".to_owned(),
1313 Value::Array(t.into_iter().map(Value::from).collect()),
1314 );
1315 if let Some(Value::Array(e)) = r.get_mut("enum")
1316 && !e.contains(&Value::Null)
1317 {
1318 e.push(Value::Null);
1319 }
1320 Some((read, beside))
1321}
1322
1323fn values(e: Option<&Value>) -> Option<BTreeSet<Vec<u8>>> {
1325 e.map(|e| e.as_array().into_iter().flatten().map(jcs).collect())
1326}
1327
1328fn required(s: &Value) -> BTreeSet<String> {
1329 s["required"]
1330 .as_array()
1331 .into_iter()
1332 .flatten()
1333 .filter_map(|r| r.as_str().map(str::to_owned))
1334 .collect()
1335}
1336
1337impl<'a> JsonCx<'a> {
1338 fn deref(&self, s: &Value, doc: &'a Value, old: bool) -> Option<(Value, &'a Value)> {
1351 let mut cur = s.clone();
1352 let mut doc = doc;
1353 let mut beside: Vec<Map<String, Value>> = Vec::new();
1354 for _ in 0..32 {
1355 let Some(r) = cur.get("$ref").and_then(Value::as_str).map(str::to_owned) else {
1356 break;
1357 };
1358 if let Value::Object(m) = &cur {
1359 let sib: Map<String, Value> = m
1360 .iter()
1361 .filter(|(k, _)| !matches!(k.as_str(), "$ref" | "$defs"))
1362 .map(|(k, x)| (k.clone(), x.clone()))
1363 .collect();
1364 if !sib.is_empty() {
1365 beside.push(sib);
1366 }
1367 }
1368 let (file, ptr) = r.split_once('#').unwrap_or((r.as_str(), ""));
1369 if !file.is_empty() {
1370 let base = file.rsplit('/').next().unwrap_or(file);
1371 let stem = base.strip_suffix(".json").unwrap_or(base);
1372 let docs = if old { &self.old_docs } else { &self.new_docs };
1373 doc = docs.get(stem)?;
1374 }
1375 cur = doc.pointer(ptr)?.clone();
1376 }
1377 if !beside.is_empty() && cur != Value::Bool(false) {
1378 let mut merged = match cur {
1379 Value::Object(m) => m,
1380 _ => Map::new(),
1381 };
1382 for sib in beside.into_iter().rev() {
1383 merged.extend(sib);
1384 }
1385 cur = Value::Object(merged);
1386 }
1387 Some((cur, doc))
1388 }
1389
1390 fn nullable(&self, s: &Value, doc: &'a Value, old: bool) -> Option<(Value, &'a Value)> {
1393 nullable_reading(s, |branch| self.deref(branch, doc, old))
1394 }
1395
1396 fn written(
1403 &self,
1404 v: &Value,
1405 doc: &'a Value,
1406 old: bool,
1407 stack: &mut Vec<Vec<u8>>,
1408 ) -> Option<Value> {
1409 match v {
1410 Value::Array(a) => a.iter().map(|x| self.written(x, doc, old, stack)).collect(),
1411 Value::Object(m) if m.contains_key("$ref") => {
1412 let (target, tdoc) = self.deref(v, doc, old)?;
1413 let id = jcs(&target);
1414 if stack.contains(&id) {
1415 return Some(strip(v));
1416 }
1417 stack.push(id);
1418 let out = self.written(&target, tdoc, old, stack);
1419 stack.pop();
1420 out
1421 }
1422 Value::Object(m) => {
1423 let mut out = Map::new();
1424 for (k, x) in m {
1425 if ANNOTATIONS.contains(&k.as_str()) {
1426 continue;
1427 }
1428 let x = match (k.as_str(), x) {
1429 ("properties" | "$defs", Value::Object(subs)) => Value::Object(
1430 subs.iter()
1431 .map(|(n, s)| Some((n.clone(), self.written(s, doc, old, stack)?)))
1432 .collect::<Option<_>>()?,
1433 ),
1434 (
1435 "prefixItems" | "oneOf" | "anyOf" | "items" | "additionalProperties",
1436 sub,
1437 ) => self.written(sub, doc, old, stack)?,
1438 (_, x) => x.clone(),
1439 };
1440 out.insert(k.clone(), x);
1441 }
1442 Some(Value::Object(out))
1443 }
1444 x => Some(x.clone()),
1445 }
1446 }
1447
1448 #[allow(clippy::too_many_arguments)]
1449 fn compare(
1450 &self,
1451 so: &Value,
1452 doc_o: &'a Value,
1453 sn: &Value,
1454 doc_n: &'a Value,
1455 at: &str,
1456 seen: &mut BTreeSet<(String, String)>,
1457 v: &mut Verdict,
1458 ) {
1459 let key = (
1460 String::from_utf8(jcs(so)).unwrap_or_default(),
1461 String::from_utf8(jcs(sn)).unwrap_or_default(),
1462 );
1463 if !seen.insert(key) {
1464 return;
1465 }
1466 let (Some((o, doc_o)), Some((n, doc_n))) =
1467 (self.deref(so, doc_o, true), self.deref(sn, doc_n, false))
1468 else {
1469 v.push(
1470 Class::Review,
1471 "schema_unreadable",
1472 at,
1473 "a `$ref` resolves to nothing in its revision",
1474 );
1475 return;
1476 };
1477 let (ro, rn) = (
1481 self.nullable(&o, doc_o, true),
1482 self.nullable(&n, doc_n, false),
1483 );
1484 let other_anyof =
1485 |s: &Value, read: &Option<(Value, &Value)>| read.is_none() && s.get("anyOf").is_some();
1486 let as_written =
1487 (ro.is_some() && other_anyof(&n, &rn)) || (rn.is_some() && other_anyof(&o, &ro));
1488 let ((o, doc_o), (n, doc_n)) = if as_written {
1489 ((o, doc_o), (n, doc_n))
1490 } else {
1491 (ro.unwrap_or((o, doc_o)), rn.unwrap_or((n, doc_n)))
1492 };
1493 let (o, n) = (&o, &n);
1494 if o.is_boolean() || n.is_boolean() {
1497 if o != n {
1498 v.push(
1499 Class::Review,
1500 "boolean_schema_changed",
1501 at,
1502 "a boolean schema changed",
1503 );
1504 }
1505 return;
1506 }
1507 if types(o) != types(n) {
1508 v.push(
1509 Class::Breaking,
1510 "type_changed",
1511 at,
1512 format!("{:?} → {:?}", types(o), types(n)),
1513 );
1514 return;
1515 }
1516 for k in BOUNDS {
1517 if o.get(*k) != n.get(*k) {
1518 v.push(
1519 Class::Breaking,
1520 "bound_changed",
1521 at,
1522 format!("`{k}` changed"),
1523 );
1524 }
1525 }
1526 if values(o.get("enum")) != values(n.get("enum")) {
1527 v.push(
1528 Class::Breaking,
1529 "enum_changed",
1530 at,
1531 "a value added or removed",
1532 );
1533 }
1534 if o.get("const") != n.get("const") {
1535 v.push(Class::Breaking, "const_changed", at, "`const` changed");
1536 }
1537 for k in ["oneOf", "anyOf", "prefixItems"] {
1542 let written = |s: &Value, doc: &'a Value, old: bool| {
1543 s.get(k).map(|x| self.written(x, doc, old, &mut Vec::new()))
1544 };
1545 let (a, b) = match (written(o, doc_o, true), written(n, doc_n, false)) {
1546 (Some(None), _) | (_, Some(None)) => {
1547 v.push(
1548 Class::Review,
1549 "schema_unreadable",
1550 at,
1551 format!("a `$ref` inside `{k}` resolves to nothing in its revision"),
1552 );
1553 continue;
1554 }
1555 (a, b) => (a.flatten(), b.flatten()),
1556 };
1557 if a == b {
1558 continue;
1559 }
1560 let grown = k == "oneOf"
1561 && matches!((&a, &b), (Some(Value::Array(x)), Some(Value::Array(y))) if y.len() > x.len());
1562 if grown {
1563 v.push(
1564 Class::Breaking,
1565 "oneof_branch_added",
1566 at,
1567 "a `oneOf` branch added",
1568 );
1569 } else {
1570 v.push(
1571 Class::Review,
1572 "undecided_changed",
1573 at,
1574 format!("`{k}` changed"),
1575 );
1576 }
1577 }
1578 let empty = Map::new();
1580 let po = o
1581 .get("properties")
1582 .and_then(Value::as_object)
1583 .unwrap_or(&empty);
1584 let pn = n
1585 .get("properties")
1586 .and_then(Value::as_object)
1587 .unwrap_or(&empty);
1588 let (ro, rn) = (required(o), required(n));
1589 for (name, so) in po {
1590 let pat = format!("{at}.{name}");
1591 match pn.get(name) {
1592 Some(sn) => {
1593 if ro.contains(name) != rn.contains(name) {
1594 v.push(
1595 Class::Breaking,
1596 "required_changed",
1597 &pat,
1598 "optional ↔ required",
1599 );
1600 }
1601 self.compare(so, doc_o, sn, doc_n, &pat, seen, v);
1602 }
1603 None if ro.contains(name) => {
1604 v.push(
1605 Class::Breaking,
1606 "required_removed",
1607 &pat,
1608 "a required property removed",
1609 );
1610 }
1611 None => {}
1612 }
1613 }
1614 for name in pn.keys() {
1615 if !po.contains_key(name) && rn.contains(name) {
1616 v.push(
1617 Class::Breaking,
1618 "required_added",
1619 &format!("{at}.{name}"),
1620 "a required property added",
1621 );
1622 }
1623 }
1624 for name in ro.symmetric_difference(&rn) {
1627 if po.contains_key(name) || pn.contains_key(name) {
1628 continue;
1629 }
1630 let rule = if rn.contains(name) {
1631 "required_added"
1632 } else {
1633 "required_removed"
1634 };
1635 v.push(
1636 Class::Breaking,
1637 rule,
1638 &format!("{at}.{name}"),
1639 "a required name without a property",
1640 );
1641 }
1642 for k in ["items", "additionalProperties"] {
1647 match (o.get(k), n.get(k)) {
1648 (Some(a @ Value::Object(_)), Some(b @ Value::Object(_))) => {
1649 self.compare(a, doc_o, b, doc_n, &format!("{at}.{k}"), seen, v);
1650 }
1651 (Some(Value::Object(_)), _) | (_, Some(Value::Object(_))) => {
1652 v.push(
1653 Class::Review,
1654 "members_changed",
1655 at,
1656 format!("`{k}` gained or lost a schema"),
1657 );
1658 }
1659 _ => {}
1660 }
1661 }
1662 }
1663}
1664
1665#[must_use]
1669pub fn same_revision(a: &Revision, b: &Revision) -> bool {
1670 let named = |r: &Revision| -> Option<(Value, BTreeMap<String, Vec<u8>>)> {
1671 let mut by_name = BTreeMap::new();
1672 let mut ids = BTreeMap::new();
1673 for s in r.canonical["schemas"].as_array()? {
1674 let (id, name) = (s["id"].as_str()?, s["name"].as_str()?);
1675 let key = format!("{}:{name}", s["kind"].as_str()?);
1676 let bytes = match r.schemas.get(id)? {
1677 Schema::Protobuf(b) => normalize_fds(b)?,
1678 Schema::Json(v) => jcs(v),
1679 };
1680 by_name.insert(key.clone(), bytes);
1681 ids.insert(id.to_owned(), key);
1682 }
1683 let mut c = r.canonical.clone();
1684 c["schemas"] = Value::Null;
1685 replace_ids(&mut c, &ids);
1686 Some((c, by_name))
1687 };
1688 match (named(a), named(b)) {
1689 (Some(x), Some(y)) => x == y,
1690 _ => false,
1691 }
1692}
1693
1694fn replace_ids(v: &mut Value, ids: &BTreeMap<String, String>) {
1695 match v {
1696 Value::String(s) => {
1697 if let Some(k) = ids.get(s.as_str()) {
1698 *s = k.clone();
1699 }
1700 }
1701 Value::Array(a) => a.iter_mut().for_each(|x| replace_ids(x, ids)),
1702 Value::Object(m) => m.values_mut().for_each(|x| replace_ids(x, ids)),
1703 _ => {}
1704 }
1705}
1706
1707fn normalize_fds(bytes: &[u8]) -> Option<Vec<u8>> {
1710 let mut set = prost_types::FileDescriptorSet::decode(bytes).ok()?;
1711 for f in &mut set.file {
1712 f.source_code_info = None;
1713 for m in &mut f.message_type {
1714 normalize_message(m);
1715 }
1716 }
1717 Some(set.encode_to_vec())
1718}
1719
1720fn normalize_message(m: &mut prost_types::DescriptorProto) {
1721 for f in &mut m.field {
1722 if f.json_name.as_deref() == Some(default_json_name(f.name()).as_str()) {
1723 f.json_name = None;
1724 }
1725 }
1726 for n in &mut m.nested_type {
1727 normalize_message(n);
1728 }
1729}
1730
1731fn default_json_name(name: &str) -> String {
1734 let mut out = String::with_capacity(name.len());
1735 let mut up = false;
1736 for c in name.chars() {
1737 if c == '_' {
1738 up = true;
1739 } else if up {
1740 out.extend(c.to_uppercase());
1741 up = false;
1742 } else {
1743 out.push(c);
1744 }
1745 }
1746 out
1747}
1748
1749#[cfg(test)]
1750mod tests {
1751 use std::path::Path;
1752
1753 use serde_json::json;
1754
1755 use super::*;
1756 use crate::contract::load_str;
1757
1758 fn rev(dir: &Path, doc: &Value) -> Revision {
1761 std::fs::write(dir.join("t.json"), doc.to_string()).unwrap();
1762 let src = "[interface]\nname = \"m\"\nmajor = 1\nminor = 0\n[schemas]\njsonschema = [\"t.json\"]\n\
1763 [resources.s]\nkind = \"state\"\ntype = \"json:T\"\n";
1764 let l = load_str(src, dir, None);
1765 Revision::of(&l.contract.unwrap_or_else(|| panic!("{}", l.report)))
1766 }
1767
1768 fn class(old: &Value, new: &Value) -> &'static str {
1769 static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1770 let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1771 let dir = std::env::temp_dir().join(format!("zk2-compat-{}-{n}", std::process::id()));
1772 std::fs::create_dir_all(&dir).unwrap();
1773 let (o, n) = (rev(&dir, old), rev(&dir, new));
1774 std::fs::remove_dir_all(&dir).unwrap();
1775 compare(&o, &n).class().as_str()
1776 }
1777
1778 fn doc(t: &Value) -> Value {
1779 json!({"$defs": {"T": t, "U": {"type": "integer"}}})
1780 }
1781
1782 #[test]
1783 fn keywords_beside_a_ref_are_compared() {
1784 let a = doc(&json!({"type": "object", "properties": {"n": {"$ref": "#/$defs/U"}}}));
1785 let b = doc(
1786 &json!({"type": "object", "properties": {"n": {"$ref": "#/$defs/U", "maximum": 3}}}),
1787 );
1788 assert_eq!(class(&a, &b), "breaking");
1789 assert_eq!(class(&b, &b), "compatible");
1790 let inline =
1791 doc(&json!({"type": "object", "properties": {"n": {"type": "integer", "maximum": 3}}}));
1792 assert_eq!(class(&b, &inline), "compatible");
1793 }
1794
1795 #[test]
1796 fn boolean_schemas_are_review() {
1797 let t = |p: Value| doc(&json!({"type": "object", "properties": {"p": p}}));
1798 assert_eq!(class(&t(json!(true)), &t(json!(false))), "review");
1799 assert_eq!(class(&t(json!(true)), &t(json!({}))), "review");
1800 assert_eq!(class(&t(json!(false)), &t(json!(false))), "compatible");
1801 }
1802
1803 #[test]
1804 fn a_required_name_without_a_property_binds() {
1805 let t = |r: Value| doc(&json!({"type": "object", "required": r}));
1806 assert_eq!(class(&t(json!(["a"])), &t(json!([]))), "breaking");
1807 assert_eq!(class(&t(json!([])), &t(json!(["a"]))), "breaking");
1808 assert_eq!(class(&t(json!(["a"])), &t(json!(["a"]))), "compatible");
1809 }
1810
1811 #[test]
1815 fn a_ref_that_resolves_to_nothing_is_unreadable() {
1816 let dir = std::env::temp_dir().join(format!("zk2-compat-dangling-{}", std::process::id()));
1817 std::fs::create_dir_all(&dir).unwrap();
1818 let ok = doc(&json!({"type": "object", "properties": {"n": {"$ref": "#/$defs/U"}}}));
1819 let old = rev(&dir, &ok);
1820 std::fs::remove_dir_all(&dir).unwrap();
1821 for dangling in ["u.json#/$defs/U", "#/$defs/Gone"] {
1822 let mut new = old.clone();
1823 for s in new.schemas.values_mut() {
1824 if let Schema::Json(v) = s {
1825 v["$defs"]["T"]["properties"]["n"]["$ref"] = json!(dangling);
1826 }
1827 }
1828 let v = compare(&old, &new);
1829 assert_eq!(v.class().as_str(), "review", "{dangling}");
1830 assert!(
1831 v.findings.iter().all(|f| f.rule == "schema_unreadable"),
1832 "{dangling}: {:?}",
1833 v.findings
1834 );
1835 }
1836 }
1837
1838 #[test]
1839 fn property_names_inside_oneof_are_not_annotations() {
1840 let t = |ty: &str| {
1841 doc(&json!({"oneOf": [{"type": "object", "properties": {"title": {"type": ty}}}]}))
1842 };
1843 assert_eq!(class(&t("string"), &t("integer")), "review");
1844 let d = |text: &str| doc(&json!({"oneOf": [{"type": "string", "description": text}]}));
1845 assert_eq!(class(&d("a"), &d("b")), "compatible");
1846 }
1847
1848 fn with_p(schema: &Value, i: &Value, e: &Value) -> Value {
1851 json!({"$defs": {
1852 "T": {"type": "object", "properties": {"p": schema}},
1853 "I": i,
1854 "E": e,
1855 }})
1856 }
1857
1858 #[test]
1862 fn a_nullable_is_one_type_in_either_spelling() {
1863 let i =
1864 json!({"type": "object", "properties": {"x": {"type": "integer"}}, "required": ["x"]});
1865 let e = json!({"type": "string", "enum": ["a", "b"]});
1866 let t = |p: Value| with_p(&p, &i, &e);
1867 let nul = json!({"type": "null"});
1868 let ty = t(json!({"type": ["integer", "null"], "minimum": 0}));
1869 let any = t(json!({"anyOf": [{"type": "integer", "minimum": 0}, nul]}));
1870 let any_rev = t(json!({"anyOf": [nul, {"type": "integer", "minimum": 0}]}));
1871 assert_eq!(class(&ty, &any), "compatible");
1872 assert_eq!(class(&any, &ty), "compatible");
1873 assert_eq!(class(&any, &any_rev), "compatible");
1874 let num = t(json!({"anyOf": [{"type": "number", "minimum": 0}, nul]}));
1876 assert_eq!(class(&any, &num), "breaking");
1877 let looser =
1878 t(json!({"anyOf": [{"type": "integer", "minimum": 0, "description": "d"}, nul]}));
1879 assert_eq!(class(&any, &looser), "compatible");
1880 assert_eq!(
1882 class(&any, &t(json!({"type": "integer", "minimum": 0}))),
1883 "breaking"
1884 );
1885 let r = |i: &Value| with_p(&json!({"anyOf": [{"$ref": "#/$defs/I"}, nul]}), i, &e);
1887 let retyped =
1888 json!({"type": "object", "properties": {"x": {"type": "string"}}, "required": ["x"]});
1889 assert_eq!(class(&r(&i), &r(&retyped)), "breaking");
1890 let widened = json!({"type": "object", "properties": {"x": {"type": "integer"}, "y": {"type": "string"}}, "required": ["x"]});
1891 assert_eq!(class(&r(&i), &r(&widened)), "compatible");
1892 let er = t(json!({"anyOf": [{"$ref": "#/$defs/E"}, nul]}));
1894 let with_null = t(json!({"type": ["string", "null"], "enum": ["a", "b", null]}));
1895 let without = t(json!({"type": ["string", "null"], "enum": ["a", "b"]}));
1896 assert_eq!(class(&er, &with_null), "compatible");
1897 assert_eq!(class(&er, &without), "breaking");
1898 }
1899
1900 #[test]
1904 fn a_nullable_beside_another_anyof_stays_undecided() {
1905 let (i, e) = (json!({"type": "object"}), json!({"type": "string"}));
1906 let t = |p: Value| with_p(&p, &i, &e);
1907 let one = t(json!({"anyOf": [{"type": "integer"}]}));
1908 let two = t(json!({"anyOf": [{"type": "integer"}, {"type": "null"}]}));
1909 assert_eq!(class(&one, &two), "review");
1910 assert_eq!(class(&two, &one), "review");
1911 let konst = t(json!({"anyOf": [{"type": "string", "const": "k"}, {"type": "null"}]}));
1912 let konst2 = t(json!({"anyOf": [{"type": "string", "const": "j"}, {"type": "null"}]}));
1913 assert_eq!(class(&konst, &konst2), "review");
1914 }
1915
1916 #[test]
1920 fn a_ref_inside_an_undecided_keyword_is_followed() {
1921 let t = |body: Value| {
1922 json!({"$defs": {
1923 "T": {"oneOf": [{"type": "object", "properties": {"body": {"$ref": "#/$defs/B"}}}]},
1924 "B": body,
1925 }})
1926 };
1927 let b = json!({"type": "object", "properties": {"x": {"type": "integer"}}});
1928 let b2 = json!({"type": "object", "properties": {"x": {"type": "string"}}});
1929 assert_eq!(class(&t(b.clone()), &t(b.clone())), "compatible");
1930 assert_eq!(class(&t(b.clone()), &t(b2)), "review");
1931 let inline =
1932 json!({"$defs": {"T": {"oneOf": [{"type": "object", "properties": {"body": b}}]}}});
1933 assert_eq!(class(&t(b.clone()), &inline), "compatible");
1934 let tree = |ty: &str| {
1935 json!({"$defs": {"T": {"anyOf": [
1936 {"type": ty},
1937 {"type": "array", "items": {"$ref": "#/$defs/T"}},
1938 ]}}})
1939 };
1940 assert_eq!(class(&tree("integer"), &tree("integer")), "compatible");
1941 assert_eq!(class(&tree("integer"), &tree("string")), "review");
1942
1943 let dir = std::env::temp_dir().join(format!("zk2-compat-oneof-ref-{}", std::process::id()));
1944 std::fs::create_dir_all(&dir).unwrap();
1945 let old = rev(&dir, &t(json!({"type": "integer"})));
1946 std::fs::remove_dir_all(&dir).unwrap();
1947 let mut new = old.clone();
1948 for s in new.schemas.values_mut() {
1949 if let Schema::Json(v) = s {
1950 v["$defs"]["T"]["oneOf"][0]["properties"]["body"]["$ref"] = json!("#/$defs/Gone");
1951 }
1952 }
1953 let v = compare(&old, &new);
1954 assert_eq!(v.class().as_str(), "review");
1955 assert!(
1956 v.findings.iter().all(|f| f.rule == "schema_unreadable"),
1957 "{:?}",
1958 v.findings
1959 );
1960 }
1961
1962 #[test]
1965 fn a_packed_enum_reports_every_change() {
1966 let dir = std::env::temp_dir().join(format!("zk2-compat-packed-{}", std::process::id()));
1967 std::fs::create_dir_all(&dir).unwrap();
1968 let rev = |values: &[&str], escape: bool| {
1969 let doc = json!({"types": {"T": {"fields": [
1970 {"name": "m", "type": "enum", "values": values, "escape": escape, "width": 3}
1971 ]}}});
1972 std::fs::write(dir.join("t.json"), doc.to_string()).unwrap();
1973 let src = "[interface]\nname = \"m\"\nmajor = 1\nminor = 0\n[schemas]\npacked = [\"t.json\"]\n\
1974 [resources.s]\nkind = \"state\"\ntype = \"packed:T\"\n";
1975 let l = load_str(src, &dir, None);
1976 Revision::of(&l.contract.unwrap_or_else(|| panic!("{}", l.report)))
1977 };
1978 let old = rev(&["off", "on", "auto"], false);
1979 let new = rev(&["off", "up", "auto", "eco"], true);
1980 std::fs::remove_dir_all(&dir).unwrap();
1981 let v = compare(&old, &new);
1982 assert_eq!(v.class().as_str(), "breaking");
1983 let said: Vec<(&str, &str)> = v
1984 .findings
1985 .iter()
1986 .map(|f| (f.rule, f.detail.as_str()))
1987 .collect();
1988 assert!(
1989 said.contains(&("enum_changed", "the escape toggled")),
1990 "{said:?}"
1991 );
1992 assert!(
1993 said.contains(&("enum_value_renamed", "\"on\" renamed \"up\"")),
1994 "{said:?}"
1995 );
1996 assert!(
1997 said.iter()
1998 .any(|(r, d)| *r == "enum_changed" && d.contains("added or removed")),
1999 "{said:?}"
2000 );
2001 }
2002}