use std::collections::{BTreeMap, BTreeSet};
use base64::Engine as _;
use prost::Message as _;
use prost_reflect::{
Cardinality, DescriptorPool, EnumDescriptor, FieldDescriptor, Kind, MessageDescriptor,
};
use serde_json::{Map, Value};
use crate::bundle::Bundle;
use crate::canonical::canonical;
use crate::contract::Contract;
use crate::schema::{ArtifactData, jcs};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Class {
Compatible,
Review,
Breaking,
}
impl Class {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Compatible => "compatible",
Self::Review => "review",
Self::Breaking => "breaking",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Finding {
pub class: Class,
pub rule: &'static str,
pub at: String,
pub detail: String,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Verdict {
pub findings: Vec<Finding>,
pub warnings: Vec<Finding>,
}
impl Verdict {
#[must_use]
pub fn class(&self) -> Class {
self.findings
.iter()
.map(|f| f.class)
.max()
.unwrap_or(Class::Compatible)
}
#[must_use]
pub fn warning_rules(&self) -> Vec<&'static str> {
let s: BTreeSet<&'static str> = self.warnings.iter().map(|w| w.rule).collect();
s.into_iter().collect()
}
fn push(&mut self, class: Class, rule: &'static str, at: &str, detail: impl Into<String>) {
if class == Class::Compatible {
return;
}
self.findings.push(Finding {
class,
rule,
at: at.to_owned(),
detail: detail.into(),
});
}
fn warn(&mut self, rule: &'static str, at: &str, detail: impl Into<String>) {
self.warnings.push(Finding {
class: Class::Compatible,
rule,
at: at.to_owned(),
detail: detail.into(),
});
}
fn extend(&mut self, other: Verdict) {
self.findings.extend(other.findings);
self.warnings.extend(other.warnings);
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Schema {
Protobuf(Vec<u8>),
Json(Value),
}
#[derive(Debug, Clone, PartialEq)]
pub struct Revision {
pub canonical: Value,
pub schemas: BTreeMap<String, Schema>,
}
impl Revision {
#[must_use]
pub fn of(c: &Contract) -> Self {
let schemas = c
.artifacts
.iter()
.map(|(id, a)| {
let s = match &a.data {
ArtifactData::Protobuf(b) => Schema::Protobuf(b.clone()),
ArtifactData::Json(v) => Schema::Json(v.clone()),
};
(id.clone(), s)
})
.collect();
Self {
canonical: canonical(c),
schemas,
}
}
#[must_use]
pub fn of_bundle(b: &Bundle) -> Self {
let schemas = b
.schemas
.iter()
.filter_map(|(id, e)| {
let data = e.get("data")?;
let s = match e.get("kind")?.as_str()? {
"protobuf" => Schema::Protobuf(
base64::engine::general_purpose::STANDARD
.decode(data.as_str()?)
.ok()?,
),
"jsonschema" | "packed" => Schema::Json(data.clone()),
_ => return None,
};
Some((id.clone(), s))
})
.collect();
Self {
canonical: b.contract.clone(),
schemas,
}
}
fn resources(&self) -> BTreeMap<(String, String), &Value> {
self.canonical["resources"]
.as_array()
.into_iter()
.flatten()
.filter_map(|r| {
Some((
(
r["kind"].as_str()?.to_owned(),
r["template"].as_str()?.to_owned(),
),
r,
))
})
.collect()
}
fn json_by_stem(&self) -> BTreeMap<String, &Value> {
let names: BTreeMap<&str, &str> = self.canonical["schemas"]
.as_array()
.into_iter()
.flatten()
.filter(|s| s["kind"] == "jsonschema")
.filter_map(|s| Some((s["id"].as_str()?, s["name"].as_str()?)))
.collect();
self.schemas
.iter()
.filter_map(|(id, s)| match s {
Schema::Json(v) => Some((names.get(id.as_str())?.to_string(), v)),
Schema::Protobuf(_) => None,
})
.collect()
}
}
#[must_use]
pub fn check_history(history: &[Revision], new: &Revision) -> Verdict {
let mut v = Verdict::default();
for old in history {
v.extend(compare(old, new));
}
v
}
#[must_use]
pub fn compare(old: &Revision, new: &Revision) -> Verdict {
let mut v = Verdict::default();
if old.canonical["interface"] != new.canonical["interface"] {
v.push(
Class::Breaking,
"interface_changed",
"interface",
"the interface id differs",
);
return v;
}
if old.canonical["uses"] != new.canonical["uses"] {
v.push(
Class::Review,
"uses_changed",
"interface.uses",
"the profiles used changed",
);
}
let (ro, rn) = (old.resources(), new.resources());
for (key, o) in &ro {
let at = format!("resources.{:?}", key.1);
match rn.get(key) {
None => v.push(
Class::Breaking,
"resource_removed",
&at,
"removed; a deprecated resource stays until the next major",
),
Some(n) => compare_resource(o, n, old, new, &at, &mut v),
}
}
for (key, n) in &rn {
if ro.contains_key(key) {
continue;
}
let at = format!("resources.{:?}", key.1);
if n["optional"] == Value::Bool(true) {
} else {
v.push(
Class::Breaking,
"required_resource_added",
&at,
"a required resource added: old providers lack it",
);
}
}
compare_requires(
&old.canonical["requires"],
&new.canonical["requires"],
&mut v,
);
v
}
fn s(v: &Value) -> &str {
v.as_str().unwrap_or("")
}
#[allow(clippy::too_many_lines)]
fn compare_resource(o: &Value, n: &Value, ro: &Revision, rn: &Revision, at: &str, v: &mut Verdict) {
match (s(&o["token"]), s(&n["token"])) {
(a, b) if a == b => {}
("stream", "@stream") | ("state", "@state") => {
v.push(
Class::Breaking,
"explicit_set",
at,
"leaves ambient selectors",
);
}
("@stream", "stream") | ("@state", "state") => {
v.push(
Class::Review,
"explicit_cleared",
at,
"joins ambient selectors (link budgets)",
);
}
_ => v.push(
Class::Breaking,
"token_changed",
at,
"the kind token changed",
),
}
if o["params"] != n["params"] {
v.push(
Class::Breaking,
"params_changed",
at,
"a parameter's type changed",
);
}
match (o["optional"].as_bool(), n["optional"].as_bool()) {
(Some(true), Some(false)) => {
v.push(
Class::Breaking,
"optional_to_required",
at,
"old implementers may not expose it",
);
}
(Some(false), Some(true)) => {
v.push(
Class::Breaking,
"required_to_optional",
at,
"old consumers rely on it",
);
}
_ => {}
}
for (field, rule) in [
("cardinality", "cardinality_changed"),
("epoch", "epoch_changed"),
("gate", "gate_changed"),
("annotations", "annotations_changed"),
] {
if o[field] != n[field] {
v.push(Class::Review, rule, at, format!("`{field}` changed"));
}
}
if o["deprecated"] != n["deprecated"] && !n["deprecated"].is_null() && o["deprecated"].is_null()
{
} else if o["deprecated"] != n["deprecated"] {
v.push(
Class::Review,
"deprecated_changed",
at,
"`deprecated` changed",
);
}
if s(&o["kind"]) != s(&n["kind"]) {
v.push(
Class::Breaking,
"kind_changed",
at,
"the resource kind changed",
);
return;
}
if o["encoding"] != n["encoding"] {
v.push(
Class::Breaking,
"encoding_changed",
at,
"the payload encoding changed",
);
}
if s(&o["kind"]) == "operation" {
for (field, what) in [("request", Dir::Request), ("response", Dir::Response)] {
compare_type(
&o[field],
&n[field],
ro,
rn,
&format!("{at}.{field}"),
what,
v,
);
}
for (field, rule) in [
("error", "error_type_changed"),
("summary", "summary_type_changed"),
] {
match (o[field].is_null(), n[field].is_null()) {
(true, true) => {}
(false, false) => compare_type(
&o[field],
&n[field],
ro,
rn,
&format!("{at}.{field}"),
Dir::Response,
v,
),
_ => v.push(
Class::Review,
rule,
at,
format!("`{field}` added or removed"),
),
}
}
if o["idempotent"] == Value::Bool(true) && n["idempotent"] == Value::Bool(false) {
v.push(
Class::Breaking,
"idempotent_cleared",
at,
"callers may retry it",
);
} else if o["idempotent"] != n["idempotent"] {
v.push(
Class::Review,
"idempotent_set",
at,
"new callers may retry old servers",
);
}
if s(&o["fanout"]) == "allowed" && s(&n["fanout"]) == "forbidden" {
v.push(
Class::Breaking,
"fanout_forbidden",
at,
"fan-out calls are refused",
);
}
if s(&o["replies"]) == "one" && s(&n["replies"]) == "many" {
v.push(
Class::Breaking,
"replies_many",
at,
"callers' consolidation drops replies",
);
}
for (field, rule) in [
("serving", "serving_changed"),
("timeout_ms", "timeout_changed"),
("priority", "priority_changed"),
] {
if o[field] != n[field] {
v.push(Class::Review, rule, at, format!("`{field}` changed"));
}
}
return;
}
compare_type(
&o["type"],
&n["type"],
ro,
rn,
&format!("{at}.type"),
Dir::Data,
v,
);
match (o["attachment"].is_null(), n["attachment"].is_null()) {
(true, true) => {}
(false, false) => compare_type(
&o["attachment"],
&n["attachment"],
ro,
rn,
&format!("{at}.attachment"),
Dir::Data,
v,
),
_ => v.push(
Class::Review,
"attachment_changed",
at,
"an attachment added or removed",
),
}
if o["attachment_encoding"] != n["attachment_encoding"]
&& !o["attachment"].is_null()
&& !n["attachment"].is_null()
{
v.push(
Class::Breaking,
"encoding_changed",
at,
"the attachment encoding changed",
);
}
if s(&o["reliability"]) == "reliable" && s(&n["reliability"]) == "best_effort" {
v.push(
Class::Review,
"reliability_lowered",
at,
"reliable → best_effort",
);
}
if o["congestion"] != n["congestion"] {
v.push(
Class::Review,
"congestion_changed",
at,
"drop ↔ block (it can stall the producer, or drop)",
);
}
for (field, rule) in [
("priority", "priority_changed"),
("express", "express_toggled"),
("history", "history_changed"),
("rate", "rate_changed"),
("retention_s", "retention_changed"),
] {
if o[field] != n[field] {
v.push(Class::Review, rule, at, format!("`{field}` changed"));
}
}
let fields = if o.get("frame").is_some() && n.get("frame").is_some() {
(field_names(ro, &o["type"]), field_names(rn, &n["type"]))
} else {
(None, None)
};
compare_frame(o.get("frame"), n.get("frame"), &fields, at, v);
}
fn field_names(r: &Revision, t: &Value) -> Option<Vec<String>> {
if s(&t["kind"]) != "packed" {
return None;
}
let doc = match r.schemas.get(s(&t["schema"]))? {
Schema::Json(doc) => doc,
Schema::Protobuf(_) => return None,
};
let layout = crate::packed::PackedDoc::read(doc)
.types
.remove(s(&t["name"]))
.flatten()?;
Some(
layout
.items
.iter()
.filter_map(|i| match i {
crate::packed::Item::Field(f) => Some(f.name.clone()),
crate::packed::Item::Marker => None,
})
.collect(),
)
}
fn compare_frame(
o: Option<&Value>,
n: Option<&Value>,
fields: &(Option<Vec<String>>, Option<Vec<String>>),
at: &str,
v: &mut Verdict,
) {
let (o, n) = match (o, n) {
(None, None) => return,
(Some(o), Some(n)) => (o, n),
_ => {
v.push(
Class::Breaking,
"frame_toggled",
at,
"`frame` added or removed: a reader of the other revision reads none of its samples",
);
return;
}
};
if ["records", "step_ms", "jitter_ms"]
.iter()
.any(|k| o[*k] != n[*k])
{
v.push(
Class::Breaking,
"frame_changed",
at,
"`records`, `step_ms` or `jitter_ms` changed: the bits and the times move",
);
}
let deadbands_differ = match fields {
(Some(old), Some(new)) if old.len() == new.len() => old
.iter()
.zip(new)
.any(|(a, b)| o["deadband"].get(a.as_str()) != n["deadband"].get(b.as_str())),
_ => o["deadband"] != n["deadband"],
};
if deadbands_differ {
v.push(
Class::Breaking,
"deadband_changed",
at,
"a deadband added, removed or changed: what an omitted field holds moves",
);
}
if o["keyframe_every"] != n["keyframe_every"] {
v.push(
Class::Review,
"keyframe_changed",
at,
"`keyframe_every` changed: how long a reader waits to heal",
);
}
}
fn compare_requires(o: &Value, n: &Value, v: &mut Verdict) {
let empty = Map::new();
let (o, n) = (
o.as_object().unwrap_or(&empty),
n.as_object().unwrap_or(&empty),
);
for (role, ro) in o {
let at = format!("requires.{role}");
let Some(rn) = n.get(role) else {
continue;
};
if ro["interface"] != rn["interface"] || ro["cardinality"] != rn["cardinality"] {
v.push(
Class::Breaking,
"role_changed",
&at,
"the role's interface or cardinality changed",
);
}
if ro["optional"] == Value::Bool(true) && rn["optional"] == Value::Bool(false) {
v.push(
Class::Breaking,
"role_required",
&at,
"deployments must now bind it",
);
}
if ro["resources"] != rn["resources"] || ro["annotations"] != rn["annotations"] {
v.push(
Class::Review,
"role_resources_changed",
&at,
"what the role consumes changed",
);
}
}
for (role, rn) in n {
if !o.contains_key(role) && rn["optional"] != Value::Bool(true) {
v.push(
Class::Breaking,
"required_role_added",
&format!("requires.{role}"),
"deployments must bind it",
);
}
}
}
#[derive(Debug, Clone, Copy)]
enum Dir {
Data,
Request,
Response,
}
fn compare_type(
o: &Value,
n: &Value,
ro: &Revision,
rn: &Revision,
at: &str,
_dir: Dir,
v: &mut Verdict,
) {
match (s(&o["kind"]), s(&n["kind"])) {
("raw", "raw") => {
if o["media_type"] != n["media_type"] {
v.push(
Class::Breaking,
"media_type_changed",
at,
"the raw media type changed",
);
} else if o["media_param"] != n["media_param"] {
v.push(
Class::Review,
"media_param_changed",
at,
"`media_param` changed",
);
}
}
("protobuf", "protobuf") => {
let (Some(po), Some(pn)) = (pool(ro, &o["schema"]), pool(rn, &n["schema"])) else {
v.push(
Class::Review,
"schema_unreadable",
at,
"a descriptor set does not decode",
);
return;
};
match (
po.get_message_by_name(s(&o["name"])),
pn.get_message_by_name(s(&n["name"])),
) {
(Some(mo), Some(mn)) => {
let mut seen = BTreeSet::new();
compare_messages(&mo, &mn, at, &mut seen, v);
}
_ => v.push(
Class::Review,
"schema_unreadable",
at,
"a message is missing from its descriptor set",
),
}
}
("jsonschema", "jsonschema") => {
let (Some(Schema::Json(doc_old)), Some(Schema::Json(doc_new))) = (
ro.schemas.get(s(&o["schema"])),
rn.schemas.get(s(&n["schema"])),
) else {
v.push(
Class::Review,
"schema_unreadable",
at,
"a JSON Schema artifact is missing",
);
return;
};
let cx = JsonCx {
old_docs: ro.json_by_stem(),
new_docs: rn.json_by_stem(),
};
let so = doc_old["$defs"][s(&o["name"])].clone();
let sn = doc_new["$defs"][s(&n["name"])].clone();
let mut seen = BTreeSet::new();
cx.compare(&so, doc_old, &sn, doc_new, at, &mut seen, v);
}
("packed", "packed") => {
let layout = |r: &Revision, t: &Value| match r.schemas.get(s(&t["schema"])) {
Some(Schema::Json(doc)) => crate::packed::PackedDoc::read(doc)
.types
.remove(s(&t["name"]))
.flatten(),
_ => None,
};
match (layout(ro, o), layout(rn, n)) {
(Some(lo), Some(ln)) => compare_packed(&lo, &ln, at, v),
_ => v.push(
Class::Review,
"schema_unreadable",
at,
"a packed artifact is missing, or does not lay out its type",
),
}
}
_ => v.push(
Class::Breaking,
"type_kind_changed",
at,
"the schema kind changed",
),
}
}
fn compare_packed(o: &crate::packed::Layout, n: &crate::packed::Layout, at: &str, v: &mut Verdict) {
use crate::packed::Item;
let (a, b) = (&o.items, &n.items);
for (i, (x, y)) in a.iter().zip(b).enumerate() {
let at = format!("{at}.fields[{i}]");
match (x, y) {
(Item::Marker, Item::Marker) => {}
(Item::Field(x), Item::Field(y)) => compare_packed_fields(x, y, &at, v),
_ => v.push(
Class::Breaking,
"fields_changed",
&at,
"a marker where the other revision has a field",
),
}
}
if a.len() != b.len() {
let shorter = if a.len() < b.len() { a } else { b };
if !matches!(shorter.last(), Some(Item::Marker)) {
v.push(
Class::Breaking,
"fields_changed",
at,
"fields added or removed where no marker ends the shorter revision",
);
}
}
}
fn compare_packed_fields(
x: &crate::packed::Field,
y: &crate::packed::Field,
at: &str,
v: &mut Verdict,
) {
use crate::packed::FieldKind as K;
if x.kind.as_str() != y.kind.as_str() {
v.push(
Class::Breaking,
"type_changed",
at,
format!("{} became {}", x.kind.as_str(), y.kind.as_str()),
);
return;
}
if x.name != y.name {
v.push(
Class::Review,
"field_renamed",
at,
format!("{:?} renamed {:?}", x.name, y.name),
);
}
if x.optional != y.optional {
v.push(
Class::Breaking,
"presence_changed",
at,
"`optional` toggled: the presence bit appears or goes",
);
}
let bound = |v: &mut Verdict| {
v.push(Class::Breaking, "bound_changed", at, "a bound moved");
};
let reserved = |v: &mut Verdict| {
v.push(
Class::Breaking,
"reserved_changed",
at,
"`reserved` changed: the codes move",
);
};
match (&x.kind, &y.kind) {
(
K::Int {
minimum: a0,
maximum: a1,
reserved: ra,
},
K::Int {
minimum: b0,
maximum: b1,
reserved: rb,
},
) => {
if (a0, a1) != (b0, b1) {
bound(v);
}
if ra != rb {
reserved(v);
}
}
(
K::Fixed {
minimum: a0,
maximum: a1,
resolution: ar,
reserved: ra,
..
},
K::Fixed {
minimum: b0,
maximum: b1,
resolution: br,
reserved: rb,
..
},
) => {
if (a0, a1) != (b0, b1) {
bound(v);
}
if ar != br {
v.push(
Class::Breaking,
"resolution_changed",
at,
format!("`resolution` {ar} became {br}"),
);
}
if ra != rb {
reserved(v);
}
}
(
K::Enum {
values: va,
escape: ea,
},
K::Enum {
values: vb,
escape: eb,
},
) => {
if x.width != y.width {
v.push(
Class::Breaking,
"width_changed",
at,
format!("the enum's width {} became {}", x.width, y.width),
);
}
if ea != eb {
v.push(Class::Breaking, "enum_changed", at, "the escape toggled");
}
for (p, q) in va.iter().zip(vb) {
if p == q {
continue;
}
if vb.contains(p) || va.contains(q) {
v.push(
Class::Breaking,
"enum_changed",
at,
format!("{p:?} or {q:?} moved to another index"),
);
} else {
v.push(
Class::Review,
"enum_value_renamed",
at,
format!("{p:?} renamed {q:?}"),
);
}
}
match (vb.len().cmp(&va.len()), *ea && *eb) {
(std::cmp::Ordering::Equal, _) | (std::cmp::Ordering::Greater, true) => {}
(std::cmp::Ordering::Less, true) => v.push(
Class::Review,
"enum_value_removed",
at,
"a value removed: an old writer still writes it, and a new reader reads the escape",
),
(_, false) => v.push(
Class::Breaking,
"enum_changed",
at,
"a value added or removed where no escape reads it",
),
}
}
(K::Counter, K::Counter) | (K::Time { .. }, K::Time { .. }) if x.width != y.width => {
v.push(
Class::Breaking,
"width_changed",
at,
format!("the width {} became {}", x.width, y.width),
);
}
_ => {}
}
}
fn pool(r: &Revision, id: &Value) -> Option<DescriptorPool> {
match r.schemas.get(id.as_str()?)? {
Schema::Protobuf(b) => DescriptorPool::decode(b.as_slice()).ok(),
Schema::Json(_) => None,
}
}
fn reserved(m: &MessageDescriptor, number: u32) -> bool {
m.reserved_ranges().any(|r| r.contains(&number))
}
fn compare_messages(
o: &MessageDescriptor,
n: &MessageDescriptor,
at: &str,
seen: &mut BTreeSet<(String, String)>,
v: &mut Verdict,
) {
if !seen.insert((o.full_name().to_owned(), n.full_name().to_owned())) {
return;
}
for fo in o.fields() {
let fat = format!("{at}.{}", fo.name());
match n.get_field(fo.number()) {
Some(fnew) => {
if fo.name() != fnew.name() {
v.push(
Class::Review,
"field_renamed",
&fat,
format!("now {:?}", fnew.name()),
);
} else if fo.json_name() != fnew.json_name() {
v.push(
Class::Review,
"json_name_changed",
&fat,
format!("now {:?}", fnew.json_name()),
);
}
if fo.is_list() != fnew.is_list() || fo.is_map() != fnew.is_map() {
v.push(
Class::Breaking,
"cardinality_changed",
&fat,
"repeated, map or singular changed",
);
continue;
}
if is_required(&fo) != is_required(&fnew) {
v.push(
Class::Breaking,
"required_label_changed",
&fat,
"proto2 `required` toggled",
);
}
let oneof = |f: &prost_reflect::FieldDescriptor| {
f.containing_oneof()
.filter(|o| !o.is_synthetic())
.map(|o| o.name().to_owned())
};
if oneof(&fo) != oneof(&fnew) {
v.push(
Class::Breaking,
"oneof_changed",
&fat,
"moved into or out of a oneof",
);
} else if fo.supports_presence() != fnew.supports_presence() && !fo.is_list() {
v.push(
Class::Review,
"presence_changed",
&fat,
"explicit presence toggled",
);
}
compare_kinds(&fo.kind(), &fnew.kind(), &fat, seen, v);
}
None => {
if is_required(&fo) && n.get_field_by_name(fo.name()).is_none() {
v.push(
Class::Breaking,
"required_field_removed",
&fat,
"a proto2 `required` field deleted: old readers refuse what new writers send",
);
}
if let Some(moved) = n.get_field_by_name(fo.name()) {
v.push(
Class::Breaking,
"renumbered",
&fat,
format!(
"{} → {}: the data is dropped both ways",
fo.number(),
moved.number()
),
);
} else if !reserved(n, fo.number()) {
v.warn(
"field_deleted_unreserved",
&fat,
format!("field {} deleted without reserving its number", fo.number()),
);
}
}
}
}
for fnew in n.fields() {
if o.get_field(fnew.number()).is_some() || o.get_field_by_name(fnew.name()).is_some() {
continue;
}
if is_required(&fnew) {
v.push(
Class::Breaking,
"required_field_added",
&format!("{at}.{}", fnew.name()),
"a proto2 `required` field added: new readers refuse what old writers send",
);
}
if reserved(o, fnew.number()) {
v.push(
Class::Breaking,
"reserved_reused",
&format!("{at}.{}", fnew.name()),
format!("number {} was reserved", fnew.number()),
);
}
}
}
fn is_required(f: &FieldDescriptor) -> bool {
f.cardinality() == Cardinality::Required
}
fn compare_kinds(
o: &Kind,
n: &Kind,
at: &str,
seen: &mut BTreeSet<(String, String)>,
v: &mut Verdict,
) {
match (o, n) {
(Kind::Message(mo), Kind::Message(mn)) => compare_messages(mo, mn, at, seen, v),
(Kind::Enum(eo), Kind::Enum(en)) => compare_enums(eo, en, at, v),
(a, b) if std::mem::discriminant(a) == std::mem::discriminant(b) => {}
_ => v.push(
Class::Breaking,
"type_changed",
at,
format!("{o:?} → {n:?}"),
),
}
}
fn compare_enums(o: &EnumDescriptor, n: &EnumDescriptor, at: &str, v: &mut Verdict) {
for vo in o.values() {
match n.get_value(vo.number()) {
None => v.push(
Class::Review,
"enum_value_removed",
at,
format!("{} removed", vo.name()),
),
Some(vn) if vn.name() != vo.name() => {
v.push(
Class::Review,
"enum_value_renamed",
at,
format!("{} → {}", vo.name(), vn.name()),
);
}
Some(_) => {}
}
}
let closed = n.parent_file().syntax() == prost_reflect::Syntax::Proto2;
if closed && n.values().any(|vn| o.get_value(vn.number()).is_none()) {
v.push(
Class::Review,
"closed_enum_value_added",
at,
"a proto2 (closed) enum gained a value: old readers fall back to the default",
);
}
}
struct JsonCx<'a> {
old_docs: BTreeMap<String, &'a Value>,
new_docs: BTreeMap<String, &'a Value>,
}
const ANNOTATIONS: &[&str] = &[
"$schema",
"$id",
"$comment",
"title",
"description",
"default",
"examples",
"format",
"deprecated",
"readOnly",
"writeOnly",
];
const BOUNDS: &[&str] = &[
"minimum",
"maximum",
"exclusiveMinimum",
"exclusiveMaximum",
"minLength",
"maxLength",
"minItems",
"maxItems",
];
fn strip(v: &Value) -> Value {
match v {
Value::Object(m) => Value::Object(
m.iter()
.filter(|(k, _)| !ANNOTATIONS.contains(&k.as_str()))
.map(|(k, x)| {
let x = match (k.as_str(), x) {
("properties" | "$defs", Value::Object(subs)) => {
Value::Object(subs.iter().map(|(n, s)| (n.clone(), strip(s))).collect())
}
(
"prefixItems" | "oneOf" | "anyOf" | "items" | "additionalProperties",
sub,
) => strip(sub),
(_, x) => x.clone(),
};
(k.clone(), x)
})
.collect(),
),
Value::Array(a) => Value::Array(a.iter().map(strip).collect()),
x => x.clone(),
}
}
fn types(s: &Value) -> BTreeSet<String> {
match &s["type"] {
Value::String(t) => [t.clone()].into(),
Value::Array(a) => a
.iter()
.filter_map(|t| t.as_str().map(str::to_owned))
.collect(),
_ => BTreeSet::new(),
}
}
fn is_null_schema(s: &Value) -> bool {
s.as_object().is_some_and(|m| {
m.keys()
.all(|k| k == "type" || ANNOTATIONS.contains(&k.as_str()))
}) && types(s) == BTreeSet::from(["null".to_owned()])
}
pub fn nullable_reading<T>(
s: &Value,
follow: impl FnOnce(&Value) -> Option<(Value, T)>,
) -> Option<(Value, T)> {
let m = s.as_object()?;
if m.keys()
.any(|k| k != "anyOf" && !ANNOTATIONS.contains(&k.as_str()))
{
return None;
}
let [a, b] = m.get("anyOf")?.as_array()?.as_slice() else {
return None;
};
let branch = match (is_null_schema(a), is_null_schema(b)) {
(true, false) => b,
(false, true) => a,
_ => return None,
};
let (mut read, beside) = follow(branch)?;
let r = read.as_object_mut()?;
let typed = match r.get("type") {
Some(Value::String(_)) => true,
Some(Value::Array(a)) => a.iter().all(Value::is_string),
_ => false,
};
if !typed
|| ["const", "oneOf", "anyOf"]
.iter()
.any(|k| r.contains_key(*k))
{
return None;
}
let mut t = types(&Value::Object(r.clone()));
t.insert("null".to_owned());
r.insert(
"type".to_owned(),
Value::Array(t.into_iter().map(Value::from).collect()),
);
if let Some(Value::Array(e)) = r.get_mut("enum")
&& !e.contains(&Value::Null)
{
e.push(Value::Null);
}
Some((read, beside))
}
fn values(e: Option<&Value>) -> Option<BTreeSet<Vec<u8>>> {
e.map(|e| e.as_array().into_iter().flatten().map(jcs).collect())
}
fn required(s: &Value) -> BTreeSet<String> {
s["required"]
.as_array()
.into_iter()
.flatten()
.filter_map(|r| r.as_str().map(str::to_owned))
.collect()
}
impl<'a> JsonCx<'a> {
fn deref(&self, s: &Value, doc: &'a Value, old: bool) -> Option<(Value, &'a Value)> {
let mut cur = s.clone();
let mut doc = doc;
let mut beside: Vec<Map<String, Value>> = Vec::new();
for _ in 0..32 {
let Some(r) = cur.get("$ref").and_then(Value::as_str).map(str::to_owned) else {
break;
};
if let Value::Object(m) = &cur {
let sib: Map<String, Value> = m
.iter()
.filter(|(k, _)| !matches!(k.as_str(), "$ref" | "$defs"))
.map(|(k, x)| (k.clone(), x.clone()))
.collect();
if !sib.is_empty() {
beside.push(sib);
}
}
let (file, ptr) = r.split_once('#').unwrap_or((r.as_str(), ""));
if !file.is_empty() {
let base = file.rsplit('/').next().unwrap_or(file);
let stem = base.strip_suffix(".json").unwrap_or(base);
let docs = if old { &self.old_docs } else { &self.new_docs };
doc = docs.get(stem)?;
}
cur = doc.pointer(ptr)?.clone();
}
if !beside.is_empty() && cur != Value::Bool(false) {
let mut merged = match cur {
Value::Object(m) => m,
_ => Map::new(),
};
for sib in beside.into_iter().rev() {
merged.extend(sib);
}
cur = Value::Object(merged);
}
Some((cur, doc))
}
fn nullable(&self, s: &Value, doc: &'a Value, old: bool) -> Option<(Value, &'a Value)> {
nullable_reading(s, |branch| self.deref(branch, doc, old))
}
fn written(
&self,
v: &Value,
doc: &'a Value,
old: bool,
stack: &mut Vec<Vec<u8>>,
) -> Option<Value> {
match v {
Value::Array(a) => a.iter().map(|x| self.written(x, doc, old, stack)).collect(),
Value::Object(m) if m.contains_key("$ref") => {
let (target, tdoc) = self.deref(v, doc, old)?;
let id = jcs(&target);
if stack.contains(&id) {
return Some(strip(v));
}
stack.push(id);
let out = self.written(&target, tdoc, old, stack);
stack.pop();
out
}
Value::Object(m) => {
let mut out = Map::new();
for (k, x) in m {
if ANNOTATIONS.contains(&k.as_str()) {
continue;
}
let x = match (k.as_str(), x) {
("properties" | "$defs", Value::Object(subs)) => Value::Object(
subs.iter()
.map(|(n, s)| Some((n.clone(), self.written(s, doc, old, stack)?)))
.collect::<Option<_>>()?,
),
(
"prefixItems" | "oneOf" | "anyOf" | "items" | "additionalProperties",
sub,
) => self.written(sub, doc, old, stack)?,
(_, x) => x.clone(),
};
out.insert(k.clone(), x);
}
Some(Value::Object(out))
}
x => Some(x.clone()),
}
}
#[allow(clippy::too_many_arguments)]
fn compare(
&self,
so: &Value,
doc_o: &'a Value,
sn: &Value,
doc_n: &'a Value,
at: &str,
seen: &mut BTreeSet<(String, String)>,
v: &mut Verdict,
) {
let key = (
String::from_utf8(jcs(so)).unwrap_or_default(),
String::from_utf8(jcs(sn)).unwrap_or_default(),
);
if !seen.insert(key) {
return;
}
let (Some((o, doc_o)), Some((n, doc_n))) =
(self.deref(so, doc_o, true), self.deref(sn, doc_n, false))
else {
v.push(
Class::Review,
"schema_unreadable",
at,
"a `$ref` resolves to nothing in its revision",
);
return;
};
let (ro, rn) = (
self.nullable(&o, doc_o, true),
self.nullable(&n, doc_n, false),
);
let other_anyof =
|s: &Value, read: &Option<(Value, &Value)>| read.is_none() && s.get("anyOf").is_some();
let as_written =
(ro.is_some() && other_anyof(&n, &rn)) || (rn.is_some() && other_anyof(&o, &ro));
let ((o, doc_o), (n, doc_n)) = if as_written {
((o, doc_o), (n, doc_n))
} else {
(ro.unwrap_or((o, doc_o)), rn.unwrap_or((n, doc_n)))
};
let (o, n) = (&o, &n);
if o.is_boolean() || n.is_boolean() {
if o != n {
v.push(
Class::Review,
"boolean_schema_changed",
at,
"a boolean schema changed",
);
}
return;
}
if types(o) != types(n) {
v.push(
Class::Breaking,
"type_changed",
at,
format!("{:?} → {:?}", types(o), types(n)),
);
return;
}
for k in BOUNDS {
if o.get(*k) != n.get(*k) {
v.push(
Class::Breaking,
"bound_changed",
at,
format!("`{k}` changed"),
);
}
}
if values(o.get("enum")) != values(n.get("enum")) {
v.push(
Class::Breaking,
"enum_changed",
at,
"a value added or removed",
);
}
if o.get("const") != n.get("const") {
v.push(Class::Breaking, "const_changed", at, "`const` changed");
}
for k in ["oneOf", "anyOf", "prefixItems"] {
let written = |s: &Value, doc: &'a Value, old: bool| {
s.get(k).map(|x| self.written(x, doc, old, &mut Vec::new()))
};
let (a, b) = match (written(o, doc_o, true), written(n, doc_n, false)) {
(Some(None), _) | (_, Some(None)) => {
v.push(
Class::Review,
"schema_unreadable",
at,
format!("a `$ref` inside `{k}` resolves to nothing in its revision"),
);
continue;
}
(a, b) => (a.flatten(), b.flatten()),
};
if a == b {
continue;
}
let grown = k == "oneOf"
&& matches!((&a, &b), (Some(Value::Array(x)), Some(Value::Array(y))) if y.len() > x.len());
if grown {
v.push(
Class::Breaking,
"oneof_branch_added",
at,
"a `oneOf` branch added",
);
} else {
v.push(
Class::Review,
"undecided_changed",
at,
format!("`{k}` changed"),
);
}
}
let empty = Map::new();
let po = o
.get("properties")
.and_then(Value::as_object)
.unwrap_or(&empty);
let pn = n
.get("properties")
.and_then(Value::as_object)
.unwrap_or(&empty);
let (ro, rn) = (required(o), required(n));
for (name, so) in po {
let pat = format!("{at}.{name}");
match pn.get(name) {
Some(sn) => {
if ro.contains(name) != rn.contains(name) {
v.push(
Class::Breaking,
"required_changed",
&pat,
"optional ↔ required",
);
}
self.compare(so, doc_o, sn, doc_n, &pat, seen, v);
}
None if ro.contains(name) => {
v.push(
Class::Breaking,
"required_removed",
&pat,
"a required property removed",
);
}
None => {}
}
}
for name in pn.keys() {
if !po.contains_key(name) && rn.contains(name) {
v.push(
Class::Breaking,
"required_added",
&format!("{at}.{name}"),
"a required property added",
);
}
}
for name in ro.symmetric_difference(&rn) {
if po.contains_key(name) || pn.contains_key(name) {
continue;
}
let rule = if rn.contains(name) {
"required_added"
} else {
"required_removed"
};
v.push(
Class::Breaking,
rule,
&format!("{at}.{name}"),
"a required name without a property",
);
}
for k in ["items", "additionalProperties"] {
match (o.get(k), n.get(k)) {
(Some(a @ Value::Object(_)), Some(b @ Value::Object(_))) => {
self.compare(a, doc_o, b, doc_n, &format!("{at}.{k}"), seen, v);
}
(Some(Value::Object(_)), _) | (_, Some(Value::Object(_))) => {
v.push(
Class::Review,
"members_changed",
at,
format!("`{k}` gained or lost a schema"),
);
}
_ => {}
}
}
}
}
#[must_use]
pub fn same_revision(a: &Revision, b: &Revision) -> bool {
let named = |r: &Revision| -> Option<(Value, BTreeMap<String, Vec<u8>>)> {
let mut by_name = BTreeMap::new();
let mut ids = BTreeMap::new();
for s in r.canonical["schemas"].as_array()? {
let (id, name) = (s["id"].as_str()?, s["name"].as_str()?);
let key = format!("{}:{name}", s["kind"].as_str()?);
let bytes = match r.schemas.get(id)? {
Schema::Protobuf(b) => normalize_fds(b)?,
Schema::Json(v) => jcs(v),
};
by_name.insert(key.clone(), bytes);
ids.insert(id.to_owned(), key);
}
let mut c = r.canonical.clone();
c["schemas"] = Value::Null;
replace_ids(&mut c, &ids);
Some((c, by_name))
};
match (named(a), named(b)) {
(Some(x), Some(y)) => x == y,
_ => false,
}
}
fn replace_ids(v: &mut Value, ids: &BTreeMap<String, String>) {
match v {
Value::String(s) => {
if let Some(k) = ids.get(s.as_str()) {
*s = k.clone();
}
}
Value::Array(a) => a.iter_mut().for_each(|x| replace_ids(x, ids)),
Value::Object(m) => m.values_mut().for_each(|x| replace_ids(x, ids)),
_ => {}
}
}
fn normalize_fds(bytes: &[u8]) -> Option<Vec<u8>> {
let mut set = prost_types::FileDescriptorSet::decode(bytes).ok()?;
for f in &mut set.file {
f.source_code_info = None;
for m in &mut f.message_type {
normalize_message(m);
}
}
Some(set.encode_to_vec())
}
fn normalize_message(m: &mut prost_types::DescriptorProto) {
for f in &mut m.field {
if f.json_name.as_deref() == Some(default_json_name(f.name()).as_str()) {
f.json_name = None;
}
}
for n in &mut m.nested_type {
normalize_message(n);
}
}
fn default_json_name(name: &str) -> String {
let mut out = String::with_capacity(name.len());
let mut up = false;
for c in name.chars() {
if c == '_' {
up = true;
} else if up {
out.extend(c.to_uppercase());
up = false;
} else {
out.push(c);
}
}
out
}
#[cfg(test)]
mod tests {
use std::path::Path;
use serde_json::json;
use super::*;
use crate::contract::load_str;
fn rev(dir: &Path, doc: &Value) -> Revision {
std::fs::write(dir.join("t.json"), doc.to_string()).unwrap();
let src = "[interface]\nname = \"m\"\nmajor = 1\nminor = 0\n[schemas]\njsonschema = [\"t.json\"]\n\
[resources.s]\nkind = \"state\"\ntype = \"json:T\"\n";
let l = load_str(src, dir, None);
Revision::of(&l.contract.unwrap_or_else(|| panic!("{}", l.report)))
}
fn class(old: &Value, new: &Value) -> &'static str {
static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("zk2-compat-{}-{n}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let (o, n) = (rev(&dir, old), rev(&dir, new));
std::fs::remove_dir_all(&dir).unwrap();
compare(&o, &n).class().as_str()
}
fn doc(t: &Value) -> Value {
json!({"$defs": {"T": t, "U": {"type": "integer"}}})
}
#[test]
fn keywords_beside_a_ref_are_compared() {
let a = doc(&json!({"type": "object", "properties": {"n": {"$ref": "#/$defs/U"}}}));
let b = doc(
&json!({"type": "object", "properties": {"n": {"$ref": "#/$defs/U", "maximum": 3}}}),
);
assert_eq!(class(&a, &b), "breaking");
assert_eq!(class(&b, &b), "compatible");
let inline =
doc(&json!({"type": "object", "properties": {"n": {"type": "integer", "maximum": 3}}}));
assert_eq!(class(&b, &inline), "compatible");
}
#[test]
fn boolean_schemas_are_review() {
let t = |p: Value| doc(&json!({"type": "object", "properties": {"p": p}}));
assert_eq!(class(&t(json!(true)), &t(json!(false))), "review");
assert_eq!(class(&t(json!(true)), &t(json!({}))), "review");
assert_eq!(class(&t(json!(false)), &t(json!(false))), "compatible");
}
#[test]
fn a_required_name_without_a_property_binds() {
let t = |r: Value| doc(&json!({"type": "object", "required": r}));
assert_eq!(class(&t(json!(["a"])), &t(json!([]))), "breaking");
assert_eq!(class(&t(json!([])), &t(json!(["a"]))), "breaking");
assert_eq!(class(&t(json!(["a"])), &t(json!(["a"]))), "compatible");
}
#[test]
fn a_ref_that_resolves_to_nothing_is_unreadable() {
let dir = std::env::temp_dir().join(format!("zk2-compat-dangling-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let ok = doc(&json!({"type": "object", "properties": {"n": {"$ref": "#/$defs/U"}}}));
let old = rev(&dir, &ok);
std::fs::remove_dir_all(&dir).unwrap();
for dangling in ["u.json#/$defs/U", "#/$defs/Gone"] {
let mut new = old.clone();
for s in new.schemas.values_mut() {
if let Schema::Json(v) = s {
v["$defs"]["T"]["properties"]["n"]["$ref"] = json!(dangling);
}
}
let v = compare(&old, &new);
assert_eq!(v.class().as_str(), "review", "{dangling}");
assert!(
v.findings.iter().all(|f| f.rule == "schema_unreadable"),
"{dangling}: {:?}",
v.findings
);
}
}
#[test]
fn property_names_inside_oneof_are_not_annotations() {
let t = |ty: &str| {
doc(&json!({"oneOf": [{"type": "object", "properties": {"title": {"type": ty}}}]}))
};
assert_eq!(class(&t("string"), &t("integer")), "review");
let d = |text: &str| doc(&json!({"oneOf": [{"type": "string", "description": text}]}));
assert_eq!(class(&d("a"), &d("b")), "compatible");
}
fn with_p(schema: &Value, i: &Value, e: &Value) -> Value {
json!({"$defs": {
"T": {"type": "object", "properties": {"p": schema}},
"I": i,
"E": e,
}})
}
#[test]
fn a_nullable_is_one_type_in_either_spelling() {
let i =
json!({"type": "object", "properties": {"x": {"type": "integer"}}, "required": ["x"]});
let e = json!({"type": "string", "enum": ["a", "b"]});
let t = |p: Value| with_p(&p, &i, &e);
let nul = json!({"type": "null"});
let ty = t(json!({"type": ["integer", "null"], "minimum": 0}));
let any = t(json!({"anyOf": [{"type": "integer", "minimum": 0}, nul]}));
let any_rev = t(json!({"anyOf": [nul, {"type": "integer", "minimum": 0}]}));
assert_eq!(class(&ty, &any), "compatible");
assert_eq!(class(&any, &ty), "compatible");
assert_eq!(class(&any, &any_rev), "compatible");
let num = t(json!({"anyOf": [{"type": "number", "minimum": 0}, nul]}));
assert_eq!(class(&any, &num), "breaking");
let looser =
t(json!({"anyOf": [{"type": "integer", "minimum": 0, "description": "d"}, nul]}));
assert_eq!(class(&any, &looser), "compatible");
assert_eq!(
class(&any, &t(json!({"type": "integer", "minimum": 0}))),
"breaking"
);
let r = |i: &Value| with_p(&json!({"anyOf": [{"$ref": "#/$defs/I"}, nul]}), i, &e);
let retyped =
json!({"type": "object", "properties": {"x": {"type": "string"}}, "required": ["x"]});
assert_eq!(class(&r(&i), &r(&retyped)), "breaking");
let widened = json!({"type": "object", "properties": {"x": {"type": "integer"}, "y": {"type": "string"}}, "required": ["x"]});
assert_eq!(class(&r(&i), &r(&widened)), "compatible");
let er = t(json!({"anyOf": [{"$ref": "#/$defs/E"}, nul]}));
let with_null = t(json!({"type": ["string", "null"], "enum": ["a", "b", null]}));
let without = t(json!({"type": ["string", "null"], "enum": ["a", "b"]}));
assert_eq!(class(&er, &with_null), "compatible");
assert_eq!(class(&er, &without), "breaking");
}
#[test]
fn a_nullable_beside_another_anyof_stays_undecided() {
let (i, e) = (json!({"type": "object"}), json!({"type": "string"}));
let t = |p: Value| with_p(&p, &i, &e);
let one = t(json!({"anyOf": [{"type": "integer"}]}));
let two = t(json!({"anyOf": [{"type": "integer"}, {"type": "null"}]}));
assert_eq!(class(&one, &two), "review");
assert_eq!(class(&two, &one), "review");
let konst = t(json!({"anyOf": [{"type": "string", "const": "k"}, {"type": "null"}]}));
let konst2 = t(json!({"anyOf": [{"type": "string", "const": "j"}, {"type": "null"}]}));
assert_eq!(class(&konst, &konst2), "review");
}
#[test]
fn a_ref_inside_an_undecided_keyword_is_followed() {
let t = |body: Value| {
json!({"$defs": {
"T": {"oneOf": [{"type": "object", "properties": {"body": {"$ref": "#/$defs/B"}}}]},
"B": body,
}})
};
let b = json!({"type": "object", "properties": {"x": {"type": "integer"}}});
let b2 = json!({"type": "object", "properties": {"x": {"type": "string"}}});
assert_eq!(class(&t(b.clone()), &t(b.clone())), "compatible");
assert_eq!(class(&t(b.clone()), &t(b2)), "review");
let inline =
json!({"$defs": {"T": {"oneOf": [{"type": "object", "properties": {"body": b}}]}}});
assert_eq!(class(&t(b.clone()), &inline), "compatible");
let tree = |ty: &str| {
json!({"$defs": {"T": {"anyOf": [
{"type": ty},
{"type": "array", "items": {"$ref": "#/$defs/T"}},
]}}})
};
assert_eq!(class(&tree("integer"), &tree("integer")), "compatible");
assert_eq!(class(&tree("integer"), &tree("string")), "review");
let dir = std::env::temp_dir().join(format!("zk2-compat-oneof-ref-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let old = rev(&dir, &t(json!({"type": "integer"})));
std::fs::remove_dir_all(&dir).unwrap();
let mut new = old.clone();
for s in new.schemas.values_mut() {
if let Schema::Json(v) = s {
v["$defs"]["T"]["oneOf"][0]["properties"]["body"]["$ref"] = json!("#/$defs/Gone");
}
}
let v = compare(&old, &new);
assert_eq!(v.class().as_str(), "review");
assert!(
v.findings.iter().all(|f| f.rule == "schema_unreadable"),
"{:?}",
v.findings
);
}
#[test]
fn a_packed_enum_reports_every_change() {
let dir = std::env::temp_dir().join(format!("zk2-compat-packed-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let rev = |values: &[&str], escape: bool| {
let doc = json!({"types": {"T": {"fields": [
{"name": "m", "type": "enum", "values": values, "escape": escape, "width": 3}
]}}});
std::fs::write(dir.join("t.json"), doc.to_string()).unwrap();
let src = "[interface]\nname = \"m\"\nmajor = 1\nminor = 0\n[schemas]\npacked = [\"t.json\"]\n\
[resources.s]\nkind = \"state\"\ntype = \"packed:T\"\n";
let l = load_str(src, &dir, None);
Revision::of(&l.contract.unwrap_or_else(|| panic!("{}", l.report)))
};
let old = rev(&["off", "on", "auto"], false);
let new = rev(&["off", "up", "auto", "eco"], true);
std::fs::remove_dir_all(&dir).unwrap();
let v = compare(&old, &new);
assert_eq!(v.class().as_str(), "breaking");
let said: Vec<(&str, &str)> = v
.findings
.iter()
.map(|f| (f.rule, f.detail.as_str()))
.collect();
assert!(
said.contains(&("enum_changed", "the escape toggled")),
"{said:?}"
);
assert!(
said.contains(&("enum_value_renamed", "\"on\" renamed \"up\"")),
"{said:?}"
);
assert!(
said.iter()
.any(|(r, d)| *r == "enum_changed" && d.contains("added or removed")),
"{said:?}"
);
}
}