use serde::Serialize;
use serde_json::Value;
use crate::{
Code, ContentReport, Finding, Resolver, STRUCTURAL_DEPTH_MAX, ValidationResult, check_content,
schema::schema_findings,
semantic::{semantic_findings, semantic_warnings},
strict::strict_findings,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Mode {
#[default]
Lenient,
Strict,
}
#[derive(Debug, Clone, Serialize)]
pub struct FullReport {
pub validation: ValidationResult,
pub content: ContentReport,
}
impl FullReport {
#[must_use]
pub fn ok(&self) -> bool {
self.validation.ok() && self.content.ok()
}
}
#[must_use]
pub fn validate(descriptor: &Value, mode: Mode) -> ValidationResult {
if exceeds_structural_depth(descriptor) {
return ValidationResult {
findings: vec![structural_depth_finding()],
warnings: Vec::new(),
};
}
let mut findings = schema_findings(descriptor);
findings.extend(semantic_findings(descriptor));
if mode == Mode::Strict {
findings.extend(strict_findings(descriptor));
}
findings.sort();
findings.dedup();
ValidationResult {
findings,
warnings: semantic_warnings(descriptor),
}
}
fn exceeds_structural_depth(descriptor: &Value) -> bool {
let mut worklist = vec![(descriptor, 1usize)];
while let Some((value, depth)) = worklist.pop() {
if depth > STRUCTURAL_DEPTH_MAX {
return true;
}
match value {
Value::Array(items) => {
worklist.extend(items.iter().map(|item| (item, depth + 1)));
}
Value::Object(members) => {
worklist.extend(members.values().map(|member| (member, depth + 1)));
}
_ => {}
}
}
false
}
fn structural_depth_finding() -> Finding {
Finding {
code: Code::Akb011,
path: String::new(),
message: format!(
"descriptor nesting exceeds the structural depth limit of {STRUCTURAL_DEPTH_MAX}; \
it is not a well-formed OpenAKB descriptor"
),
}
}
pub async fn validate_with_content(
descriptor: &Value,
resolver: &dyn Resolver,
mode: Mode,
) -> FullReport {
FullReport {
validation: validate(descriptor, mode),
content: check_content(descriptor, resolver).await,
}
}