Compare commits
15 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2dd17f0b37 | |||
| cbda45e610 | |||
| 1085964c17 | |||
| 65971d9b93 | |||
| d938058d34 | |||
| 69ab6165bb | |||
| 03beada825 | |||
| efdd7528cc | |||
| 59395a33ac | |||
| 92c0a6fc0b | |||
| 7f66a4a35a | |||
| d37aadb0dd | |||
| d0ccc47d97 | |||
| 2d19bf100e | |||
| fb333c6cbb |
1
rustfmt.toml
Normal file
1
rustfmt.toml
Normal file
@ -0,0 +1 @@
|
|||||||
|
tab_spaces = 2
|
||||||
612
src/lib.rs
612
src/lib.rs
@ -2,16 +2,26 @@ use pgrx::*;
|
|||||||
|
|
||||||
pg_module_magic!();
|
pg_module_magic!();
|
||||||
|
|
||||||
use serde_json::{json, Value};
|
use boon::{CompileError, Compiler, ErrorKind, SchemaIndex, Schemas, ValidationError};
|
||||||
use std::{collections::HashMap, sync::RwLock};
|
|
||||||
use boon::{Compiler, Schemas, ValidationError, SchemaIndex, CompileError};
|
|
||||||
use lazy_static::lazy_static;
|
use lazy_static::lazy_static;
|
||||||
|
use serde_json::{json, Value};
|
||||||
|
use std::collections::hash_map::Entry;
|
||||||
|
use std::{collections::HashMap, sync::RwLock};
|
||||||
|
|
||||||
struct BoonCache {
|
struct BoonCache {
|
||||||
schemas: Schemas,
|
schemas: Schemas,
|
||||||
id_to_index: HashMap<String, SchemaIndex>,
|
id_to_index: HashMap<String, SchemaIndex>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Structure to hold error information without lifetimes
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct Error {
|
||||||
|
path: String,
|
||||||
|
code: String,
|
||||||
|
message: String,
|
||||||
|
cause: String,
|
||||||
|
}
|
||||||
|
|
||||||
lazy_static! {
|
lazy_static! {
|
||||||
static ref SCHEMA_CACHE: RwLock<BoonCache> = RwLock::new(BoonCache {
|
static ref SCHEMA_CACHE: RwLock<BoonCache> = RwLock::new(BoonCache {
|
||||||
schemas: Schemas::new(),
|
schemas: Schemas::new(),
|
||||||
@ -20,11 +30,17 @@ lazy_static! {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[pg_extern(strict)]
|
#[pg_extern(strict)]
|
||||||
fn cache_json_schema(schema_id: &str, schema: JsonB) -> JsonB {
|
fn cache_json_schema(schema_id: &str, schema: JsonB, strict: bool) -> JsonB {
|
||||||
let mut cache = SCHEMA_CACHE.write().unwrap();
|
let mut cache = SCHEMA_CACHE.write().unwrap();
|
||||||
let schema_value: Value = schema.0;
|
let mut schema_value: Value = schema.0;
|
||||||
let schema_path = format!("urn:{}", schema_id);
|
let schema_path = format!("urn:{}", schema_id);
|
||||||
|
|
||||||
|
// Apply strict validation to all objects in the schema if requested
|
||||||
|
if strict {
|
||||||
|
apply_strict_validation(&mut schema_value);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create the boon compiler and enable format assertions
|
||||||
let mut compiler = Compiler::new();
|
let mut compiler = Compiler::new();
|
||||||
compiler.enable_format_assertions();
|
compiler.enable_format_assertions();
|
||||||
|
|
||||||
@ -35,7 +51,7 @@ fn cache_json_schema(schema_id: &str, schema: JsonB) -> JsonB {
|
|||||||
"code": "SCHEMA_RESOURCE_ADD_FAILED",
|
"code": "SCHEMA_RESOURCE_ADD_FAILED",
|
||||||
"message": format!("Failed to add schema resource '{}'", schema_id),
|
"message": format!("Failed to add schema resource '{}'", schema_id),
|
||||||
"details": {
|
"details": {
|
||||||
"path": schema_path,
|
"schema": schema_id,
|
||||||
"cause": format!("{}", e)
|
"cause": format!("{}", e)
|
||||||
}
|
}
|
||||||
}]
|
}]
|
||||||
@ -54,9 +70,9 @@ fn cache_json_schema(schema_id: &str, schema: JsonB) -> JsonB {
|
|||||||
CompileError::ValidationError { url: _url, src } => {
|
CompileError::ValidationError { url: _url, src } => {
|
||||||
// Collect leaf errors from the meta-schema validation failure
|
// Collect leaf errors from the meta-schema validation failure
|
||||||
let mut error_list = Vec::new();
|
let mut error_list = Vec::new();
|
||||||
collect_validation_errors(src, &mut error_list);
|
collect_errors(src, &mut error_list);
|
||||||
// Filter and format errors properly - no instance for schema compilation
|
// Filter and format errors properly - no instance for schema compilation
|
||||||
format_drop_errors(error_list, &schema_value)
|
format_errors(error_list, &schema_value, schema_id)
|
||||||
}
|
}
|
||||||
_ => {
|
_ => {
|
||||||
// Other compilation errors
|
// Other compilation errors
|
||||||
@ -64,7 +80,7 @@ fn cache_json_schema(schema_id: &str, schema: JsonB) -> JsonB {
|
|||||||
"code": "SCHEMA_COMPILATION_FAILED",
|
"code": "SCHEMA_COMPILATION_FAILED",
|
||||||
"message": format!("Schema '{}' compilation failed", schema_id),
|
"message": format!("Schema '{}' compilation failed", schema_id),
|
||||||
"details": {
|
"details": {
|
||||||
"path": schema_path,
|
"schema": schema_id,
|
||||||
"cause": format!("{:?}", e)
|
"cause": format!("{:?}", e)
|
||||||
}
|
}
|
||||||
})]
|
})]
|
||||||
@ -75,10 +91,49 @@ fn cache_json_schema(schema_id: &str, schema: JsonB) -> JsonB {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Helper function to apply strict validation to a schema
|
||||||
|
//
|
||||||
|
// This recursively adds unevaluatedProperties: false to object-type schemas,
|
||||||
|
// but SKIPS schemas inside if/then/else to avoid breaking conditional validation.
|
||||||
|
fn apply_strict_validation(schema: &mut Value) {
|
||||||
|
apply_strict_validation_recursive(schema, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply_strict_validation_recursive(schema: &mut Value, inside_conditional: bool) {
|
||||||
|
match schema {
|
||||||
|
Value::Object(map) => {
|
||||||
|
// Skip adding strict validation if we're inside a conditional
|
||||||
|
if !inside_conditional {
|
||||||
|
// Add strict validation to object schemas only at top level
|
||||||
|
if let Some(Value::String(t)) = map.get("type") {
|
||||||
|
if t == "object" && !map.contains_key("unevaluatedProperties") && !map.contains_key("additionalProperties") {
|
||||||
|
// At top level, use unevaluatedProperties: false
|
||||||
|
// This considers all evaluated properties from all schemas
|
||||||
|
map.insert("unevaluatedProperties".to_string(), Value::Bool(false));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recurse into all properties
|
||||||
|
for (key, value) in map.iter_mut() {
|
||||||
|
// Mark when we're inside conditional branches
|
||||||
|
let in_conditional = inside_conditional || matches!(key.as_str(), "if" | "then" | "else");
|
||||||
|
apply_strict_validation_recursive(value, in_conditional);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Value::Array(arr) => {
|
||||||
|
// Recurse into array items
|
||||||
|
for item in arr.iter_mut() {
|
||||||
|
apply_strict_validation_recursive(item, inside_conditional);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[pg_extern(strict, parallel_safe)]
|
#[pg_extern(strict, parallel_safe)]
|
||||||
fn validate_json_schema(schema_id: &str, instance: JsonB) -> JsonB {
|
fn validate_json_schema(schema_id: &str, instance: JsonB) -> JsonB {
|
||||||
let cache = SCHEMA_CACHE.read().unwrap();
|
let cache = SCHEMA_CACHE.read().unwrap();
|
||||||
|
|
||||||
// Lookup uses the original schema_id
|
// Lookup uses the original schema_id
|
||||||
match cache.id_to_index.get(schema_id) {
|
match cache.id_to_index.get(schema_id) {
|
||||||
None => JsonB(json!({
|
None => JsonB(json!({
|
||||||
@ -86,6 +141,7 @@ fn validate_json_schema(schema_id: &str, instance: JsonB) -> JsonB {
|
|||||||
"code": "SCHEMA_NOT_FOUND",
|
"code": "SCHEMA_NOT_FOUND",
|
||||||
"message": format!("Schema '{}' not found in cache", schema_id),
|
"message": format!("Schema '{}' not found in cache", schema_id),
|
||||||
"details": {
|
"details": {
|
||||||
|
"schema": schema_id,
|
||||||
"cause": "Schema must be cached before validation"
|
"cause": "Schema must be cached before validation"
|
||||||
}
|
}
|
||||||
}]
|
}]
|
||||||
@ -96,10 +152,11 @@ fn validate_json_schema(schema_id: &str, instance: JsonB) -> JsonB {
|
|||||||
Ok(_) => JsonB(json!({ "response": "success" })),
|
Ok(_) => JsonB(json!({ "response": "success" })),
|
||||||
Err(validation_error) => {
|
Err(validation_error) => {
|
||||||
let mut error_list = Vec::new();
|
let mut error_list = Vec::new();
|
||||||
collect_validation_errors(&validation_error, &mut error_list);
|
collect_errors(&validation_error, &mut error_list);
|
||||||
let errors = format_drop_errors(error_list, &instance_value);
|
let errors = format_errors(error_list, &instance_value, schema_id);
|
||||||
|
// Filter out FALSE_SCHEMA errors if there are other validation errors
|
||||||
JsonB(json!({ "errors": errors }))
|
let filtered_errors = filter_false_schema_errors(errors);
|
||||||
|
JsonB(json!({ "errors": filtered_errors }))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -107,206 +164,370 @@ fn validate_json_schema(schema_id: &str, instance: JsonB) -> JsonB {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Recursively collects validation errors
|
// Recursively collects validation errors
|
||||||
fn collect_validation_errors(error: &ValidationError, errors_list: &mut Vec<(String, String, String)>) {
|
fn collect_errors(error: &ValidationError, errors_list: &mut Vec<Error>) {
|
||||||
// Check if this is a structural error that we should skip
|
// Check if this is a structural error that we should skip
|
||||||
let error_message = format!("{}", error.kind);
|
let is_structural = matches!(
|
||||||
let is_structural = error_message == "validation failed" ||
|
&error.kind,
|
||||||
error_message == "allOf failed" ||
|
ErrorKind::Group | ErrorKind::AllOf | ErrorKind::AnyOf | ErrorKind::Not | ErrorKind::OneOf(_)
|
||||||
error_message == "anyOf failed" ||
|
);
|
||||||
error_message == "not failed" ||
|
|
||||||
error_message.starts_with("oneOf failed");
|
|
||||||
|
|
||||||
if error.causes.is_empty() && !is_structural {
|
|
||||||
// This is a leaf error that's not structural
|
|
||||||
// Format just the error kind, not the whole validation error
|
|
||||||
let message = format!("{}", error.kind);
|
|
||||||
|
|
||||||
errors_list.push((
|
// Special handling for FalseSchema - if it has causes, use those instead
|
||||||
error.instance_location.to_string(),
|
if matches!(&error.kind, ErrorKind::FalseSchema) {
|
||||||
error.schema_url.to_string(),
|
if !error.causes.is_empty() {
|
||||||
message
|
// FalseSchema often wraps more specific errors in if/then conditionals
|
||||||
));
|
for cause in &error.causes {
|
||||||
|
collect_errors(cause, errors_list);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// If FalseSchema has no causes, it's likely from unevaluatedProperties
|
||||||
|
// We'll handle it as a leaf error below
|
||||||
|
}
|
||||||
|
|
||||||
|
if error.causes.is_empty() && !is_structural {
|
||||||
|
// Handle errors with multiple fields specially
|
||||||
|
match &error.kind {
|
||||||
|
ErrorKind::Required { want } => {
|
||||||
|
// Create a separate error for each missing required field
|
||||||
|
let base_path = error.instance_location.to_string();
|
||||||
|
for missing_field in want {
|
||||||
|
let field_path = if base_path.is_empty() {
|
||||||
|
format!("/{}", missing_field)
|
||||||
|
} else {
|
||||||
|
format!("{}/{}", base_path, missing_field)
|
||||||
|
};
|
||||||
|
|
||||||
|
errors_list.push(Error {
|
||||||
|
path: field_path,
|
||||||
|
code: "REQUIRED_FIELD_MISSING".to_string(),
|
||||||
|
message: format!("Required field '{}' is missing", missing_field),
|
||||||
|
cause: format!("property '{}' is required", missing_field),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ErrorKind::Dependency { prop, missing } | ErrorKind::DependentRequired { prop, missing } => {
|
||||||
|
// Create a separate error for each missing field
|
||||||
|
let base_path = error.instance_location.to_string();
|
||||||
|
for missing_field in missing {
|
||||||
|
let field_path = if base_path.is_empty() {
|
||||||
|
format!("/{}", missing_field)
|
||||||
|
} else {
|
||||||
|
format!("{}/{}", base_path, missing_field)
|
||||||
|
};
|
||||||
|
|
||||||
|
let (error_code, human_message) = match &error.kind {
|
||||||
|
ErrorKind::Dependency { .. } => (
|
||||||
|
"DEPENDENCY_FAILED".to_string(),
|
||||||
|
format!("Field '{}' is required when '{}' is present", missing_field, prop),
|
||||||
|
),
|
||||||
|
ErrorKind::DependentRequired { .. } => (
|
||||||
|
"DEPENDENT_REQUIRED_MISSING".to_string(),
|
||||||
|
format!("Field '{}' is required when '{}' is present", missing_field, prop),
|
||||||
|
),
|
||||||
|
_ => unreachable!(),
|
||||||
|
};
|
||||||
|
|
||||||
|
errors_list.push(Error {
|
||||||
|
path: field_path,
|
||||||
|
code: error_code,
|
||||||
|
message: human_message,
|
||||||
|
cause: format!("property '{}' required, if '{}' property exists", missing_field, prop),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ErrorKind::AdditionalProperties { got } => {
|
||||||
|
// Create a separate error for each additional property that's not allowed
|
||||||
|
let base_path = error.instance_location.to_string();
|
||||||
|
for extra_prop in got {
|
||||||
|
let field_path = if base_path.is_empty() {
|
||||||
|
format!("/{}", extra_prop)
|
||||||
|
} else {
|
||||||
|
format!("{}/{}", base_path, extra_prop)
|
||||||
|
};
|
||||||
|
|
||||||
|
errors_list.push(Error {
|
||||||
|
path: field_path,
|
||||||
|
code: "ADDITIONAL_PROPERTIES_NOT_ALLOWED".to_string(),
|
||||||
|
message: format!("Property '{}' is not allowed", extra_prop),
|
||||||
|
cause: format!("additionalProperty '{}' not allowed", extra_prop),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ErrorKind::Pattern { got, want } => {
|
||||||
|
// Special handling for pattern errors to include the pattern in the message
|
||||||
|
let display_value = if got.len() > 50 {
|
||||||
|
format!("{}...", &got[..50])
|
||||||
|
} else {
|
||||||
|
got.to_string()
|
||||||
|
};
|
||||||
|
|
||||||
|
errors_list.push(Error {
|
||||||
|
path: error.instance_location.to_string(),
|
||||||
|
code: "PATTERN_VIOLATED".to_string(),
|
||||||
|
message: format!("Value does not match pattern: {}", want),
|
||||||
|
cause: format!("'{}' does not match pattern {}", display_value, want),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
// Handle all other error types normally
|
||||||
|
let original_message = format!("{}", error.kind);
|
||||||
|
let (error_code, human_message) = convert_error_kind(&error.kind);
|
||||||
|
|
||||||
|
errors_list.push(Error {
|
||||||
|
path: error.instance_location.to_string(),
|
||||||
|
code: error_code,
|
||||||
|
message: human_message,
|
||||||
|
cause: original_message,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
// Recurse into causes
|
// Recurse into causes
|
||||||
for cause in &error.causes {
|
for cause in &error.causes {
|
||||||
collect_validation_errors(cause, errors_list);
|
collect_errors(cause, errors_list);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Convert ErrorKind to error code and human message
|
||||||
|
fn convert_error_kind(kind: &ErrorKind) -> (String, String) {
|
||||||
|
match kind {
|
||||||
|
ErrorKind::Type { .. } => (
|
||||||
|
"TYPE_MISMATCH".to_string(),
|
||||||
|
"Field type does not match the expected type".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::Required { .. } => (
|
||||||
|
"REQUIRED_FIELD_MISSING".to_string(),
|
||||||
|
"Required field is missing".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::DependentRequired { .. } => (
|
||||||
|
"DEPENDENT_REQUIRED_MISSING".to_string(),
|
||||||
|
"Dependent required fields are missing".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::Dependency { .. } => (
|
||||||
|
"DEPENDENCY_FAILED".to_string(),
|
||||||
|
"Dependency requirement not met".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::Enum { .. } => (
|
||||||
|
"ENUM_VIOLATED".to_string(),
|
||||||
|
"Value is not one of the allowed options".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::Const { .. } => (
|
||||||
|
"CONST_VIOLATED".to_string(),
|
||||||
|
"Value does not match the required constant".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::MinLength { .. } => (
|
||||||
|
"MIN_LENGTH_VIOLATED".to_string(),
|
||||||
|
"Field length is below the minimum required".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::MaxLength { .. } => (
|
||||||
|
"MAX_LENGTH_VIOLATED".to_string(),
|
||||||
|
"Field length exceeds the maximum allowed".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::Pattern { .. } => (
|
||||||
|
"PATTERN_VIOLATED".to_string(),
|
||||||
|
"Value does not match the required pattern".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::Minimum { .. } => (
|
||||||
|
"MINIMUM_VIOLATED".to_string(),
|
||||||
|
"Value is below the minimum allowed".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::Maximum { .. } => (
|
||||||
|
"MAXIMUM_VIOLATED".to_string(),
|
||||||
|
"Value exceeds the maximum allowed".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::ExclusiveMinimum { .. } => (
|
||||||
|
"EXCLUSIVE_MINIMUM_VIOLATED".to_string(),
|
||||||
|
"Value must be greater than the minimum".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::ExclusiveMaximum { .. } => (
|
||||||
|
"EXCLUSIVE_MAXIMUM_VIOLATED".to_string(),
|
||||||
|
"Value must be less than the maximum".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::MultipleOf { .. } => (
|
||||||
|
"MULTIPLE_OF_VIOLATED".to_string(),
|
||||||
|
"Value is not a multiple of the required factor".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::MinItems { .. } => (
|
||||||
|
"MIN_ITEMS_VIOLATED".to_string(),
|
||||||
|
"Array has fewer items than required".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::MaxItems { .. } => (
|
||||||
|
"MAX_ITEMS_VIOLATED".to_string(),
|
||||||
|
"Array has more items than allowed".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::UniqueItems { .. } => (
|
||||||
|
"UNIQUE_ITEMS_VIOLATED".to_string(),
|
||||||
|
"Array contains duplicate items".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::MinProperties { .. } => (
|
||||||
|
"MIN_PROPERTIES_VIOLATED".to_string(),
|
||||||
|
"Object has fewer properties than required".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::MaxProperties { .. } => (
|
||||||
|
"MAX_PROPERTIES_VIOLATED".to_string(),
|
||||||
|
"Object has more properties than allowed".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::AdditionalProperties { .. } => (
|
||||||
|
"ADDITIONAL_PROPERTIES_NOT_ALLOWED".to_string(),
|
||||||
|
"Object contains properties that are not allowed".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::AdditionalItems { .. } => (
|
||||||
|
"ADDITIONAL_ITEMS_NOT_ALLOWED".to_string(),
|
||||||
|
"Array contains additional items that are not allowed".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::Format { want, .. } => (
|
||||||
|
"FORMAT_INVALID".to_string(),
|
||||||
|
format!("Invalid {} format", want),
|
||||||
|
),
|
||||||
|
ErrorKind::PropertyName { .. } => (
|
||||||
|
"INVALID_PROPERTY_NAME".to_string(),
|
||||||
|
"Property name is invalid".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::Contains => (
|
||||||
|
"CONTAINS_FAILED".to_string(),
|
||||||
|
"No items match the required schema".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::MinContains { .. } => (
|
||||||
|
"MIN_CONTAINS_VIOLATED".to_string(),
|
||||||
|
"Too few items match the required schema".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::MaxContains { .. } => (
|
||||||
|
"MAX_CONTAINS_VIOLATED".to_string(),
|
||||||
|
"Too many items match the required schema".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::ContentEncoding { .. } => (
|
||||||
|
"CONTENT_ENCODING_INVALID".to_string(),
|
||||||
|
"Content encoding is invalid".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::ContentMediaType { .. } => (
|
||||||
|
"CONTENT_MEDIA_TYPE_INVALID".to_string(),
|
||||||
|
"Content media type is invalid".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::FalseSchema => (
|
||||||
|
"FALSE_SCHEMA".to_string(),
|
||||||
|
"Schema validation always fails".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::Not => (
|
||||||
|
"NOT_VIOLATED".to_string(),
|
||||||
|
"Value matched a schema it should not match".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::RefCycle { .. } => (
|
||||||
|
"REFERENCE_CYCLE".to_string(),
|
||||||
|
"Schema contains a reference cycle".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::Reference { .. } => (
|
||||||
|
"REFERENCE_FAILED".to_string(),
|
||||||
|
"Reference validation failed".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::Schema { .. } => (
|
||||||
|
"SCHEMA_FAILED".to_string(),
|
||||||
|
"Schema validation failed".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::ContentSchema => (
|
||||||
|
"CONTENT_SCHEMA_FAILED".to_string(),
|
||||||
|
"Content schema validation failed".to_string(),
|
||||||
|
),
|
||||||
|
// These shouldn't appear as leaf errors due to is_structural check
|
||||||
|
ErrorKind::Group => (
|
||||||
|
"VALIDATION_FAILED".to_string(),
|
||||||
|
"Validation failed".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::AllOf => (
|
||||||
|
"ALL_OF_VIOLATED".to_string(),
|
||||||
|
"Value does not match all required schemas".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::AnyOf => (
|
||||||
|
"ANY_OF_VIOLATED".to_string(),
|
||||||
|
"Value does not match any of the allowed schemas".to_string(),
|
||||||
|
),
|
||||||
|
ErrorKind::OneOf(_) => (
|
||||||
|
"ONE_OF_VIOLATED".to_string(),
|
||||||
|
"Value must match exactly one schema".to_string(),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Filter out FALSE_SCHEMA errors if there are other validation errors
|
||||||
|
fn filter_false_schema_errors(errors: Vec<Value>) -> Vec<Value> {
|
||||||
|
// Check if there are any non-FALSE_SCHEMA errors
|
||||||
|
let has_non_false_schema = errors.iter().any(|e| {
|
||||||
|
e.get("code")
|
||||||
|
.and_then(|c| c.as_str())
|
||||||
|
.map(|code| code != "FALSE_SCHEMA")
|
||||||
|
.unwrap_or(false)
|
||||||
|
});
|
||||||
|
|
||||||
|
if has_non_false_schema {
|
||||||
|
// Filter out FALSE_SCHEMA errors
|
||||||
|
errors.into_iter()
|
||||||
|
.filter(|e| {
|
||||||
|
e.get("code")
|
||||||
|
.and_then(|c| c.as_str())
|
||||||
|
.map(|code| code != "FALSE_SCHEMA")
|
||||||
|
.unwrap_or(true)
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
} else {
|
||||||
|
// Keep all errors (they're all FALSE_SCHEMA)
|
||||||
|
errors
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Formats errors according to DropError structure
|
// Formats errors according to DropError structure
|
||||||
fn format_drop_errors(raw_errors: Vec<(String, String, String)>, instance: &Value) -> Vec<Value> {
|
fn format_errors(errors: Vec<Error>, instance: &Value, schema_id: &str) -> Vec<Value> {
|
||||||
use std::collections::HashMap;
|
// Deduplicate by instance_path and format as DropError
|
||||||
use std::collections::hash_map::Entry;
|
let mut unique_errors: HashMap<String, Value> = HashMap::new();
|
||||||
|
for error in errors {
|
||||||
// We don't filter structural paths from instance paths anymore
|
if let Entry::Vacant(entry) = unique_errors.entry(error.path.clone()) {
|
||||||
// because instance paths shouldn't contain these segments anyway
|
// Extract the failing value from the instance
|
||||||
// The issue was likely with schema paths, not instance paths
|
let failing_value = extract_value_at_path(instance, &error.path);
|
||||||
let plausible_errors = raw_errors;
|
entry.insert(json!({
|
||||||
|
"code": error.code,
|
||||||
// 2. Deduplicate by instance_path and format as DropError
|
"message": error.message,
|
||||||
let mut unique_errors: HashMap<String, Value> = HashMap::new();
|
"details": {
|
||||||
for (instance_path, schema_path, message) in plausible_errors {
|
"path": error.path,
|
||||||
if let Entry::Vacant(entry) = unique_errors.entry(instance_path.clone()) {
|
"context": failing_value,
|
||||||
// Convert message to error code and make it human readable
|
"cause": error.cause,
|
||||||
let (code, human_message) = enhance_error_message(&message);
|
"schema": schema_id
|
||||||
|
}
|
||||||
// Extract the failing value from the instance
|
}));
|
||||||
let failing_value = extract_value_at_path(instance, &instance_path);
|
|
||||||
|
|
||||||
entry.insert(json!({
|
|
||||||
"code": code,
|
|
||||||
"message": human_message,
|
|
||||||
"details": {
|
|
||||||
"path": schema_path,
|
|
||||||
"context": json!({
|
|
||||||
"instance_path": instance_path,
|
|
||||||
"failing_value": failing_value
|
|
||||||
}),
|
|
||||||
"cause": message // Original error message
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
unique_errors.into_values().collect()
|
unique_errors.into_values().collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Helper function to extract value at a JSON pointer path
|
// Helper function to extract value at a JSON pointer path
|
||||||
fn extract_value_at_path(instance: &Value, path: &str) -> Value {
|
fn extract_value_at_path(instance: &Value, path: &str) -> Value {
|
||||||
let parts: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
|
let parts: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
|
||||||
let mut current = instance;
|
let mut current = instance;
|
||||||
|
|
||||||
for part in parts {
|
for part in parts {
|
||||||
match current {
|
match current {
|
||||||
Value::Object(map) => {
|
Value::Object(map) => {
|
||||||
if let Some(value) = map.get(part) {
|
if let Some(value) = map.get(part) {
|
||||||
current = value;
|
current = value;
|
||||||
} else {
|
} else {
|
||||||
return Value::Null;
|
return Value::Null;
|
||||||
}
|
|
||||||
}
|
|
||||||
Value::Array(arr) => {
|
|
||||||
if let Ok(index) = part.parse::<usize>() {
|
|
||||||
if let Some(value) = arr.get(index) {
|
|
||||||
current = value;
|
|
||||||
} else {
|
|
||||||
return Value::Null;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return Value::Null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => return Value::Null,
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
Value::Array(arr) => {
|
||||||
|
if let Ok(index) = part.parse::<usize>() {
|
||||||
|
if let Some(value) = arr.get(index) {
|
||||||
|
current = value;
|
||||||
|
} else {
|
||||||
|
return Value::Null;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return Value::Null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => return Value::Null,
|
||||||
}
|
}
|
||||||
|
}
|
||||||
current.clone()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Helper to convert validation messages to error codes and human-readable messages
|
current.clone()
|
||||||
fn enhance_error_message(message: &str) -> (String, String) {
|
|
||||||
// Match exact boon error message patterns
|
|
||||||
let trimmed = message.trim();
|
|
||||||
|
|
||||||
if trimmed.contains("value must be one of") {
|
|
||||||
("ENUM_VIOLATED".to_string(),
|
|
||||||
"Value is not one of the allowed options".to_string())
|
|
||||||
} else if trimmed.contains("length must be >=") && trimmed.contains("but got") {
|
|
||||||
("MIN_LENGTH_VIOLATED".to_string(),
|
|
||||||
"Field length is below the minimum required".to_string())
|
|
||||||
} else if trimmed.contains("length must be <=") && trimmed.contains("but got") {
|
|
||||||
("MAX_LENGTH_VIOLATED".to_string(),
|
|
||||||
"Field length exceeds the maximum allowed".to_string())
|
|
||||||
} else if trimmed.contains("must be >=") && trimmed.contains("but got") {
|
|
||||||
("MINIMUM_VIOLATED".to_string(),
|
|
||||||
"Value is below the minimum allowed".to_string())
|
|
||||||
} else if trimmed.contains("must be <=") && trimmed.contains("but got") {
|
|
||||||
("MAXIMUM_VIOLATED".to_string(),
|
|
||||||
"Value exceeds the maximum allowed".to_string())
|
|
||||||
} else if trimmed.contains("must be >") && trimmed.contains("but got") {
|
|
||||||
("EXCLUSIVE_MINIMUM_VIOLATED".to_string(),
|
|
||||||
"Value must be greater than the minimum".to_string())
|
|
||||||
} else if trimmed.contains("must be <") && trimmed.contains("but got") {
|
|
||||||
("EXCLUSIVE_MAXIMUM_VIOLATED".to_string(),
|
|
||||||
"Value must be less than the maximum".to_string())
|
|
||||||
} else if trimmed.contains("does not match pattern") {
|
|
||||||
("PATTERN_VIOLATED".to_string(),
|
|
||||||
"Value does not match the required pattern".to_string())
|
|
||||||
} else if trimmed.contains("missing properties") {
|
|
||||||
("REQUIRED_FIELD_MISSING".to_string(),
|
|
||||||
"Required field is missing".to_string())
|
|
||||||
} else if trimmed.contains("want") && trimmed.contains("but got") {
|
|
||||||
("TYPE_MISMATCH".to_string(),
|
|
||||||
"Field type does not match the expected type".to_string())
|
|
||||||
} else if trimmed.starts_with("value must be") && !trimmed.contains("one of") {
|
|
||||||
("CONST_VIOLATED".to_string(),
|
|
||||||
"Value does not match the required constant".to_string())
|
|
||||||
} else if trimmed.contains("is not valid") && trimmed.contains(":") {
|
|
||||||
("FORMAT_INVALID".to_string(),
|
|
||||||
extract_format_message(trimmed))
|
|
||||||
} else if trimmed.contains("items at") && trimmed.contains("are equal") {
|
|
||||||
("UNIQUE_ITEMS_VIOLATED".to_string(),
|
|
||||||
"Array contains duplicate items".to_string())
|
|
||||||
} else if trimmed.contains("additionalProperties") && trimmed.contains("not allowed") {
|
|
||||||
("ADDITIONAL_PROPERTIES_NOT_ALLOWED".to_string(),
|
|
||||||
"Object contains properties that are not allowed".to_string())
|
|
||||||
} else if trimmed.contains("is not multipleOf") {
|
|
||||||
("MULTIPLE_OF_VIOLATED".to_string(),
|
|
||||||
"Value is not a multiple of the required factor".to_string())
|
|
||||||
} else if trimmed.contains("minimum") && trimmed.contains("properties required") {
|
|
||||||
("MIN_PROPERTIES_VIOLATED".to_string(),
|
|
||||||
"Object has fewer properties than required".to_string())
|
|
||||||
} else if trimmed.contains("maximum") && trimmed.contains("properties required") {
|
|
||||||
("MAX_PROPERTIES_VIOLATED".to_string(),
|
|
||||||
"Object has more properties than allowed".to_string())
|
|
||||||
} else if trimmed.contains("minimum") && trimmed.contains("items required") {
|
|
||||||
("MIN_ITEMS_VIOLATED".to_string(),
|
|
||||||
"Array has fewer items than required".to_string())
|
|
||||||
} else if trimmed.contains("maximum") && trimmed.contains("items required") {
|
|
||||||
("MAX_ITEMS_VIOLATED".to_string(),
|
|
||||||
"Array has more items than allowed".to_string())
|
|
||||||
} else if trimmed == "false schema" {
|
|
||||||
("FALSE_SCHEMA".to_string(),
|
|
||||||
"Schema validation always fails".to_string())
|
|
||||||
} else if trimmed == "not failed" {
|
|
||||||
("NOT_VIOLATED".to_string(),
|
|
||||||
"Value matched a schema it should not match".to_string())
|
|
||||||
} else if trimmed == "allOf failed" {
|
|
||||||
("ALL_OF_VIOLATED".to_string(),
|
|
||||||
"Value does not match all required schemas".to_string())
|
|
||||||
} else if trimmed == "anyOf failed" {
|
|
||||||
("ANY_OF_VIOLATED".to_string(),
|
|
||||||
"Value does not match any of the allowed schemas".to_string())
|
|
||||||
} else if trimmed.contains("oneOf failed") {
|
|
||||||
("ONE_OF_VIOLATED".to_string(),
|
|
||||||
"Value must match exactly one schema".to_string())
|
|
||||||
} else if trimmed == "validation failed" {
|
|
||||||
("VALIDATION_FAILED".to_string(),
|
|
||||||
"Validation failed".to_string())
|
|
||||||
} else {
|
|
||||||
// For any unmatched patterns, try to provide a generic human-readable message
|
|
||||||
// while preserving the original error in details.cause
|
|
||||||
("VALIDATION_FAILED".to_string(),
|
|
||||||
"Validation failed".to_string())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// Extract a better format message
|
|
||||||
fn extract_format_message(message: &str) -> String {
|
|
||||||
if message.contains("date-time") {
|
|
||||||
"Invalid date-time format".to_string()
|
|
||||||
} else if message.contains("email") {
|
|
||||||
"Invalid email format".to_string()
|
|
||||||
} else if message.contains("uri") {
|
|
||||||
"Invalid URI format".to_string()
|
|
||||||
} else if message.contains("uuid") {
|
|
||||||
"Invalid UUID format".to_string()
|
|
||||||
} else {
|
|
||||||
"Invalid format".to_string()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[pg_extern(strict, parallel_safe)]
|
#[pg_extern(strict, parallel_safe)]
|
||||||
@ -347,7 +568,6 @@ pub mod pg_test {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
#[cfg(any(test, feature = "pg_test"))]
|
#[cfg(any(test, feature = "pg_test"))]
|
||||||
#[pg_schema]
|
#[pg_schema]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
|||||||
930
src/tests.rs
930
src/tests.rs
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user