use std::collections::BTreeSet;
use serde_json::{Map, Value};
const MAX_SCHEMA_DEPTH: usize = 6;
#[derive(Debug, Clone)]
pub(crate) struct SchemaParam<'a> {
pub(crate) path: String,
pub(crate) name: String,
pub(crate) pointer_suffix: String,
pub(crate) schema: &'a Map<String, Value>,
pub(crate) is_required: bool,
}
pub(crate) fn collect_schema_params<'a>(root: &'a Map<String, Value>) -> Vec<SchemaParam<'a>> {
let mut out = Vec::new();
let mut visited_refs = BTreeSet::new();
walk_object(root, root, "", "", 0, &mut visited_refs, &mut out);
out
}
pub(crate) fn schema_is_string(schema: &Map<String, Value>) -> bool {
match schema.get("type") {
Some(Value::String(s)) => s == "string",
Some(Value::Array(arr)) => arr.iter().any(|v| v.as_str() == Some("string")),
_ => false,
}
}
pub(crate) fn schema_is_container(schema: &Map<String, Value>) -> bool {
let check = |s: &str| s == "object" || s == "array";
match schema.get("type") {
Some(Value::String(s)) => check(s),
Some(Value::Array(arr)) => arr.iter().filter_map(Value::as_str).any(check),
_ => schema.contains_key("properties") || schema.contains_key("items"),
}
}
pub(crate) fn has_description(schema: &Map<String, Value>) -> bool {
schema
.get("description")
.and_then(Value::as_str)
.is_some_and(|s| !s.trim().is_empty())
}
pub(crate) fn is_empty_output_schema(output_schema: &Map<String, Value>) -> bool {
let is_object = match output_schema.get("type") {
Some(Value::String(s)) => s == "object",
Some(Value::Array(arr)) => arr.iter().any(|v| v.as_str() == Some("object")),
None => output_schema.is_empty(),
_ => false,
};
if !is_object {
return false;
}
let has_props = output_schema
.get("properties")
.and_then(Value::as_object)
.is_some_and(|p| !p.is_empty());
let has_combinator = output_schema.contains_key("$ref")
|| output_schema.contains_key("oneOf")
|| output_schema.contains_key("anyOf")
|| output_schema.contains_key("allOf");
let has_typed_additional = output_schema
.get("additionalProperties")
.is_some_and(Value::is_object);
!has_props && !has_combinator && !has_typed_additional
}
fn walk_object<'a>(
root: &'a Map<String, Value>,
node: &'a Map<String, Value>,
path_prefix: &str,
ptr_prefix: &str,
depth: usize,
visited_refs: &mut BTreeSet<String>,
out: &mut Vec<SchemaParam<'a>>,
) {
if depth > MAX_SCHEMA_DEPTH {
return;
}
if let Some(ref_str) = node.get("$ref").and_then(Value::as_str) {
if visited_refs.insert(ref_str.to_string()) {
if let Some(target) = resolve_local_ref(root, ref_str) {
walk_object(
root,
target,
path_prefix,
ptr_prefix,
depth,
visited_refs,
out,
);
}
visited_refs.remove(ref_str);
}
return;
}
for combinator in ["allOf", "oneOf", "anyOf"] {
if let Some(branches) = node.get(combinator).and_then(Value::as_array) {
for (idx, branch) in branches.iter().enumerate() {
if let Some(obj) = branch.as_object() {
let branch_ptr = format!("{ptr_prefix}/{combinator}/{idx}");
walk_object(
root,
obj,
path_prefix,
&branch_ptr,
depth,
visited_refs,
out,
);
}
}
}
}
let required: BTreeSet<&str> = node
.get("required")
.and_then(Value::as_array)
.map(|arr| arr.iter().filter_map(Value::as_str).collect())
.unwrap_or_default();
let Some(props) = node.get("properties").and_then(Value::as_object) else {
return;
};
for (prop_name, prop_val) in props {
let Some(raw_obj) = prop_val.as_object() else {
continue;
};
let (resolved_obj, ref_key) = match raw_obj.get("$ref").and_then(Value::as_str) {
Some(ref_str) if !visited_refs.contains(ref_str) => {
match resolve_local_ref(root, ref_str) {
Some(target) => (target, Some(ref_str.to_string())),
None => (raw_obj, None),
}
}
_ => (raw_obj, None),
};
let effective_schema = if has_description(raw_obj) || ref_key.is_none() {
raw_obj
} else {
resolved_obj
};
let path = if path_prefix.is_empty() {
prop_name.clone()
} else {
format!("{path_prefix}.{prop_name}")
};
let ptr = format!("{ptr_prefix}/properties/{}", escape_ptr(prop_name));
out.push(SchemaParam {
path: path.clone(),
name: prop_name.clone(),
pointer_suffix: ptr.clone(),
schema: effective_schema,
is_required: required.contains(prop_name.as_str()),
});
if let Some(rk) = &ref_key {
visited_refs.insert(rk.clone());
}
if resolved_obj.contains_key("properties")
|| resolved_obj.contains_key("allOf")
|| resolved_obj.contains_key("oneOf")
|| resolved_obj.contains_key("anyOf")
{
walk_object(
root,
resolved_obj,
&path,
&ptr,
depth + 1,
visited_refs,
out,
);
}
if let Some(items_obj) = resolved_obj.get("items").and_then(Value::as_object) {
let item_path = format!("{path}[]");
let item_ptr = format!("{ptr}/items");
walk_object(
root,
items_obj,
&item_path,
&item_ptr,
depth + 1,
visited_refs,
out,
);
}
if let Some(rk) = ref_key {
visited_refs.remove(&rk);
}
}
}
fn resolve_local_ref<'a>(
root: &'a Map<String, Value>,
ref_str: &str,
) -> Option<&'a Map<String, Value>> {
let pointer = ref_str.strip_prefix('#')?;
if pointer.is_empty() {
return Some(root);
}
let trimmed = pointer.strip_prefix('/')?;
let mut current_map = root;
let mut parts = trimmed.split('/').peekable();
while let Some(raw_seg) = parts.next() {
let seg = raw_seg.replace("~1", "/").replace("~0", "~");
let next_val = current_map.get(&seg)?;
if parts.peek().is_none() {
return next_val.as_object();
}
current_map = next_val.as_object()?;
}
None
}
#[derive(Debug, Clone, Default)]
pub(crate) struct SchemaIntegrityReport {
pub(crate) root_not_object: bool,
pub(crate) root_combinator: Option<&'static str>,
pub(crate) broken_refs: Vec<String>,
pub(crate) dangling_required: Vec<(String, String)>,
pub(crate) invalid_constraints: Vec<(String, String)>,
pub(crate) max_nesting_depth: usize,
}
pub(crate) fn inspect_schema_integrity(root: &Map<String, Value>) -> SchemaIntegrityReport {
let mut report = SchemaIntegrityReport::default();
match root.get("type") {
Some(Value::String(s)) if s == "object" => {}
Some(Value::String(_)) | Some(Value::Array(_)) | Some(_) => {
report.root_not_object = true;
}
None => {
if !root.is_empty() {
report.root_not_object = true;
}
}
}
for comb in ["oneOf", "anyOf", "allOf"] {
if root.contains_key(comb) {
report.root_combinator = Some(comb);
break;
}
}
let mut visited_refs = BTreeSet::new();
inspect_node(root, root, "", "", 0, &mut visited_refs, &mut report);
report.broken_refs.sort();
report.broken_refs.dedup();
report
}
fn inspect_node(
root: &Map<String, Value>,
node: &Map<String, Value>,
path_prefix: &str,
ptr_prefix: &str,
depth: usize,
visited_refs: &mut BTreeSet<String>,
report: &mut SchemaIntegrityReport,
) {
if depth > report.max_nesting_depth {
report.max_nesting_depth = depth;
}
if depth > MAX_SCHEMA_DEPTH + 4 {
return;
}
if let Some(ref_str) = node.get("$ref").and_then(Value::as_str) {
if !ref_str.starts_with('#') {
report.broken_refs.push(ref_str.to_string());
return;
}
match resolve_local_ref(root, ref_str) {
Some(target) => {
if visited_refs.insert(ref_str.to_string()) {
inspect_node(
root,
target,
path_prefix,
ptr_prefix,
depth,
visited_refs,
report,
);
visited_refs.remove(ref_str);
}
}
None => {
report.broken_refs.push(ref_str.to_string());
}
}
return;
}
let label = if path_prefix.is_empty() {
"<root>"
} else {
path_prefix
};
if let Some(arr) = node.get("enum").and_then(Value::as_array) {
if arr.is_empty() {
report
.invalid_constraints
.push((label.to_string(), "empty `enum` array".into()));
}
}
if let (Some(min), Some(max)) = (
node.get("minimum").and_then(Value::as_f64),
node.get("maximum").and_then(Value::as_f64),
) {
if min > max {
report.invalid_constraints.push((
label.to_string(),
format!("minimum ({min}) > maximum ({max})"),
));
}
}
if let (Some(min), Some(max)) = (
node.get("minLength").and_then(Value::as_u64),
node.get("maxLength").and_then(Value::as_u64),
) {
if min > max {
report.invalid_constraints.push((
label.to_string(),
format!("minLength ({min}) > maxLength ({max})"),
));
}
}
if let (Some(min), Some(max)) = (
node.get("minItems").and_then(Value::as_u64),
node.get("maxItems").and_then(Value::as_u64),
) {
if min > max {
report.invalid_constraints.push((
label.to_string(),
format!("minItems ({min}) > maxItems ({max})"),
));
}
}
if let Some(req_arr) = node.get("required").and_then(Value::as_array) {
let props = node.get("properties").and_then(Value::as_object);
let has_combinator =
node.contains_key("allOf") || node.contains_key("oneOf") || node.contains_key("anyOf");
if !has_combinator {
for req in req_arr.iter().filter_map(Value::as_str) {
let declared = props.is_some_and(|m| m.contains_key(req));
if !declared {
report
.dangling_required
.push((ptr_prefix.to_string(), req.to_string()));
}
}
}
}
for combinator in ["allOf", "oneOf", "anyOf"] {
if let Some(branches) = node.get(combinator).and_then(Value::as_array) {
for (idx, branch) in branches.iter().enumerate() {
if let Some(obj) = branch.as_object() {
let branch_ptr = format!("{ptr_prefix}/{combinator}/{idx}");
inspect_node(
root,
obj,
path_prefix,
&branch_ptr,
depth,
visited_refs,
report,
);
}
}
}
}
if let Some(props) = node.get("properties").and_then(Value::as_object) {
for (prop_name, prop_val) in props {
if let Some(prop_obj) = prop_val.as_object() {
let next_path = if path_prefix.is_empty() {
prop_name.clone()
} else {
format!("{path_prefix}.{prop_name}")
};
let next_ptr = format!("{ptr_prefix}/properties/{}", escape_ptr(prop_name));
inspect_node(
root,
prop_obj,
&next_path,
&next_ptr,
depth + 1,
visited_refs,
report,
);
}
}
}
if let Some(items_obj) = node.get("items").and_then(Value::as_object) {
let item_path = if path_prefix.is_empty() {
"[]".to_string()
} else {
format!("{path_prefix}[]")
};
let item_ptr = format!("{ptr_prefix}/items");
inspect_node(
root,
items_obj,
&item_path,
&item_ptr,
depth + 1,
visited_refs,
report,
);
}
}
fn escape_ptr(segment: &str) -> String {
segment.replace('~', "~0").replace('/', "~1")
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
#[test]
fn walks_nested_objects_arrays_and_local_refs_safely() {
let schema = json!({
"type": "object",
"$defs": {
"DateRange": {
"type": "object",
"properties": {
"start_date": { "type": "string" }
}
},
"Cyclic": {
"type": "object",
"properties": {
"next": { "$ref": "#/$defs/Cyclic" }
}
}
},
"properties": {
"range": { "$ref": "#/$defs/DateRange", "description": "Filter window." },
"items": {
"type": "array",
"description": "Batch entries.",
"items": {
"type": "object",
"properties": {
"mode": { "type": "string" }
}
}
},
"node": { "$ref": "#/$defs/Cyclic", "description": "Recursive node." }
}
})
.as_object()
.unwrap()
.clone();
let params = collect_schema_params(&schema);
let paths: Vec<&str> = params.iter().map(|p| p.path.as_str()).collect();
assert!(paths.contains(&"range.start_date"));
assert!(paths.contains(&"items[].mode"));
}
#[test]
fn detects_empty_output_schema() {
let bare = json!({"type": "object"}).as_object().unwrap().clone();
let rich = json!({
"type": "object",
"properties": { "ok": { "type": "boolean" } }
})
.as_object()
.unwrap()
.clone();
assert!(is_empty_output_schema(&bare));
assert!(!is_empty_output_schema(&rich));
}
}