Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b4d9628b05 | |||
| 635d31d723 | |||
| 08efcb92db | |||
| dad1216e1f |
13
.env
Normal file
13
.env
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
ENVIRONMENT=local
|
||||||
|
DATABASE_PASSWORD=2HwURf1Za7m5ZKtECAfQJGpni3832RV3
|
||||||
|
DATABASE_ROLE=agreego_admin
|
||||||
|
DATABASE_HOST=127.1.27.10
|
||||||
|
DATABASE_PORT=5432
|
||||||
|
POSTGRES_PASSWORD=xzIq5JT0xY3F+2m1GtnrKDdK29sNSXVVYZHPKJVh8pI=
|
||||||
|
DATABASE_NAME=agreego
|
||||||
|
DEV_DATABASE_NAME=agreego_dev
|
||||||
|
GITEA_TOKEN=3d70c23673517330623a5122998fb304e3c73f0a
|
||||||
|
MOOV_ACCOUNT_ID=69a0d2f6-77a2-4e26-934f-d869134f87d3
|
||||||
|
MOOV_PUBLIC_KEY=9OMhK5qGnh7Tmk2Z
|
||||||
|
MOOV_SECRET_KEY=DrRox7B-YWfO9IheiUUX7lGP8-7VY-Ni
|
||||||
|
MOOV_DOMAIN=http://localhost
|
||||||
646
src/lib.rs
646
src/lib.rs
@ -4,399 +4,427 @@ pg_module_magic!();
|
|||||||
|
|
||||||
use serde_json::{json, Value};
|
use serde_json::{json, Value};
|
||||||
use std::{collections::HashMap, sync::RwLock};
|
use std::{collections::HashMap, sync::RwLock};
|
||||||
use boon::{Compiler, Schemas, ValidationError, SchemaIndex};
|
use boon::{Compiler, Schemas, ValidationError, SchemaIndex, CompileError};
|
||||||
use lazy_static::lazy_static;
|
use lazy_static::lazy_static;
|
||||||
|
|
||||||
struct BoonCache {
|
struct BoonCache {
|
||||||
schemas: Schemas,
|
schemas: Schemas,
|
||||||
id_to_index: HashMap<String, SchemaIndex>,
|
id_to_index: HashMap<String, SchemaIndex>,
|
||||||
}
|
}
|
||||||
|
|
||||||
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(),
|
||||||
id_to_index: HashMap::new()
|
id_to_index: HashMap::new(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
#[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) -> JsonB {
|
||||||
let mut cache = SCHEMA_CACHE.write().unwrap();
|
let mut cache = SCHEMA_CACHE.write().unwrap();
|
||||||
let schema_value: Value = schema.0;
|
let schema_value: Value = schema.0;
|
||||||
|
|
||||||
let mut compiler = Compiler::new();
|
let mut compiler = Compiler::new();
|
||||||
compiler.enable_format_assertions();
|
compiler.enable_format_assertions();
|
||||||
|
|
||||||
let schema_url = format!("urn:jspg:{}", schema_id);
|
if let Err(e) = compiler.add_resource(schema_id, schema_value) {
|
||||||
|
return JsonB(json!({
|
||||||
|
"success": false,
|
||||||
|
"error": {
|
||||||
|
"kind": "SchemaResourceError",
|
||||||
|
"message": format!("Failed to add schema resource: {}", e),
|
||||||
|
"schema_id": schema_id
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
if let Err(e) = compiler.add_resource(&schema_url, schema_value) {
|
match compiler.compile(schema_id, &mut cache.schemas) {
|
||||||
return JsonB(json!({
|
Ok(sch_index) => {
|
||||||
"success": false,
|
cache.id_to_index.insert(schema_id.to_string(), sch_index);
|
||||||
"error": format!("Failed to add schema resource '{}': {}", schema_id, e)
|
JsonB(json!({ "success": true }))
|
||||||
}));
|
|
||||||
}
|
}
|
||||||
|
Err(e) => {
|
||||||
match compiler.compile(&schema_url, &mut cache.schemas) {
|
// Enhance error reporting by matching on the CompileError variant
|
||||||
Ok(sch_index) => {
|
let error_details = match &e {
|
||||||
cache.id_to_index.insert(schema_id.to_string(), sch_index);
|
CompileError::ValidationError { url, src } => {
|
||||||
JsonB(json!({
|
// Metaschema validation failed - provide more detail
|
||||||
"success": true,
|
json!({
|
||||||
"schema_id": schema_id,
|
"kind": "SchemaCompilationError",
|
||||||
"message": "Schema cached successfully."
|
"sub_kind": "ValidationError", // Explicitly state it's a metaschema validation error
|
||||||
}))
|
"message": format!("Schema failed validation against its metaschema: {}", src),
|
||||||
}
|
"schema_id": schema_id,
|
||||||
Err(e) => JsonB(json!({
|
"failed_at_url": url,
|
||||||
|
"validation_details": format!("{:?}", src), // Include full debug info of the validation error
|
||||||
|
})
|
||||||
|
}
|
||||||
|
// Handle other potential compilation errors
|
||||||
|
_ => {
|
||||||
|
let error_type = format!("{:?}", e).split('(').next().unwrap_or("Unknown").to_string();
|
||||||
|
json!({
|
||||||
|
"kind": "SchemaCompilationError",
|
||||||
|
"sub_kind": error_type, // e.g., "InvalidJsonPointer", "UnsupportedUrlScheme"
|
||||||
|
"message": format!("Schema compilation failed: {}", e),
|
||||||
|
"schema_id": schema_id,
|
||||||
|
"details": format!("{:?}", e), // Generic debug info
|
||||||
|
})
|
||||||
|
}
|
||||||
|
};
|
||||||
|
JsonB(json!({
|
||||||
"success": false,
|
"success": false,
|
||||||
"schema_id": schema_id,
|
"error": error_details
|
||||||
"error": format!("Schema compilation failed: {}", e)
|
}))
|
||||||
})),
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[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();
|
||||||
|
|
||||||
match cache.id_to_index.get(schema_id) {
|
match cache.id_to_index.get(schema_id) {
|
||||||
None => JsonB(json!({
|
None => JsonB(json!({
|
||||||
|
"success": false,
|
||||||
|
"error": {
|
||||||
|
"kind": "SchemaNotFound",
|
||||||
|
"message": format!("Schema with id '{}' not found in cache", schema_id)
|
||||||
|
}
|
||||||
|
})),
|
||||||
|
Some(sch_index) => {
|
||||||
|
let instance_value: Value = instance.0;
|
||||||
|
match cache.schemas.validate(&instance_value, *sch_index) {
|
||||||
|
Ok(_) => JsonB(json!({ "success": true })),
|
||||||
|
Err(validation_error) => {
|
||||||
|
let error = format_validation_error(&validation_error);
|
||||||
|
JsonB(json!({
|
||||||
"success": false,
|
"success": false,
|
||||||
"errors": [{
|
"error": error
|
||||||
"kind": "SchemaNotFound",
|
}))
|
||||||
"message": format!("Schema with id '{}' not found in cache", schema_id)
|
|
||||||
}]
|
|
||||||
})),
|
|
||||||
Some(sch_index) => {
|
|
||||||
let instance_value: Value = instance.0;
|
|
||||||
match cache.schemas.validate(&instance_value, *sch_index) {
|
|
||||||
Ok(_) => JsonB(json!({ "success": true })),
|
|
||||||
Err(validation_error) => {
|
|
||||||
let error_details = format_boon_errors(&validation_error);
|
|
||||||
JsonB(json!({
|
|
||||||
"success": false,
|
|
||||||
"errors": [error_details]
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn format_boon_errors(error: &ValidationError) -> Value {
|
fn format_validation_error(error: &ValidationError) -> Value {
|
||||||
json!({
|
json!({
|
||||||
"instance_path": error.instance_location.to_string(),
|
"instance_path": error.instance_location.to_string(),
|
||||||
"schema_path": error.schema_url.to_string(),
|
"schema_path": error.schema_url.to_string(),
|
||||||
"kind": format!("{:?}", error.kind),
|
"kind": format!("{:?}", error.kind),
|
||||||
"message": format!("{}", error),
|
"message": format!("{}", error),
|
||||||
"causes": error
|
"error": error
|
||||||
.causes
|
.causes
|
||||||
.iter()
|
.iter()
|
||||||
.map(format_boon_errors)
|
.map(format_validation_error)
|
||||||
.collect::<Vec<_>>()
|
.collect::<Vec<_>>()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[pg_extern(strict, parallel_safe)]
|
#[pg_extern(strict, parallel_safe)]
|
||||||
fn json_schema_cached(schema_id: &str) -> bool {
|
fn json_schema_cached(schema_id: &str) -> bool {
|
||||||
let cache = SCHEMA_CACHE.read().unwrap();
|
let cache = SCHEMA_CACHE.read().unwrap();
|
||||||
cache.id_to_index.contains_key(schema_id)
|
cache.id_to_index.contains_key(schema_id)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[pg_extern(strict)]
|
#[pg_extern(strict)]
|
||||||
fn clear_json_schemas() -> JsonB {
|
fn clear_json_schemas() {
|
||||||
let mut cache = SCHEMA_CACHE.write().unwrap();
|
let mut cache = SCHEMA_CACHE.write().unwrap();
|
||||||
*cache = BoonCache {
|
*cache = BoonCache {
|
||||||
schemas: Schemas::new(),
|
schemas: Schemas::new(),
|
||||||
id_to_index: HashMap::new()
|
id_to_index: HashMap::new(),
|
||||||
};
|
};
|
||||||
JsonB(json!({
|
|
||||||
"success": true,
|
|
||||||
"message": "Schema cache cleared."
|
|
||||||
}))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[pg_extern(strict, parallel_safe)]
|
#[pg_extern(strict, parallel_safe)]
|
||||||
fn show_json_schemas() -> JsonB {
|
fn show_json_schemas() -> Vec<String> {
|
||||||
let cache = SCHEMA_CACHE.read().unwrap();
|
let cache = SCHEMA_CACHE.read().unwrap();
|
||||||
let ids: Vec<&String> = cache.id_to_index.keys().collect();
|
let ids: Vec<String> = cache.id_to_index.keys().cloned().collect();
|
||||||
JsonB(json!({
|
ids
|
||||||
"cached_schema_ids": ids
|
|
||||||
}))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[pg_schema]
|
#[pg_schema]
|
||||||
#[cfg(any(test, feature = "pg_test"))]
|
#[cfg(any(test, feature = "pg_test"))]
|
||||||
mod tests {
|
mod tests {
|
||||||
use pgrx::*;
|
use pgrx::*;
|
||||||
use pgrx::pg_test;
|
use pgrx::pg_test;
|
||||||
use super::*;
|
use super::*;
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
|
|
||||||
fn jsonb(val: Value) -> JsonB {
|
fn jsonb(val: Value) -> JsonB {
|
||||||
JsonB(val)
|
JsonB(val)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn setup_test() {
|
fn setup_test() {
|
||||||
clear_json_schemas();
|
clear_json_schemas();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[pg_test]
|
#[pg_test]
|
||||||
fn test_cache_and_validate_json_schema() {
|
fn test_cache_and_validate_json_schema() {
|
||||||
setup_test();
|
setup_test();
|
||||||
let schema_id = "my_schema";
|
let schema_id = "my_schema";
|
||||||
let schema = json!({
|
let schema = json!({
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
"name": { "type": "string" },
|
"name": { "type": "string" },
|
||||||
"age": { "type": "integer", "minimum": 0 }
|
"age": { "type": "integer", "minimum": 0 }
|
||||||
},
|
},
|
||||||
"required": ["name", "age"]
|
"required": ["name", "age"]
|
||||||
});
|
});
|
||||||
let valid_instance = json!({ "name": "Alice", "age": 30 });
|
let valid_instance = json!({ "name": "Alice", "age": 30 });
|
||||||
let invalid_instance_type = json!({ "name": "Bob", "age": -5 });
|
let invalid_instance_type = json!({ "name": "Bob", "age": -5 });
|
||||||
let invalid_instance_missing = json!({ "name": "Charlie" });
|
let invalid_instance_missing = json!({ "name": "Charlie" });
|
||||||
|
|
||||||
let cache_result = cache_json_schema(schema_id, jsonb(schema.clone()));
|
let cache_result = cache_json_schema(schema_id, jsonb(schema.clone()));
|
||||||
assert!(cache_result.0["success"].as_bool().unwrap());
|
assert!(cache_result.0["success"].as_bool().unwrap());
|
||||||
|
|
||||||
let valid_result = validate_json_schema(schema_id, jsonb(valid_instance));
|
let valid_result = validate_json_schema(schema_id, jsonb(valid_instance));
|
||||||
assert!(valid_result.0["success"].as_bool().unwrap());
|
assert!(valid_result.0["success"].as_bool().unwrap());
|
||||||
|
|
||||||
let invalid_result_type = validate_json_schema(schema_id, jsonb(invalid_instance_type));
|
let invalid_result_type = validate_json_schema(schema_id, jsonb(invalid_instance_type));
|
||||||
assert!(!invalid_result_type.0["success"].as_bool().unwrap());
|
assert!(!invalid_result_type.0["success"].as_bool().unwrap());
|
||||||
|
|
||||||
// --- Assertions for invalid_result_type ---
|
let error_obj_type = invalid_result_type.0.get("error").expect("Expected top-level 'error' object");
|
||||||
|
let causes_age = error_obj_type.get("error").and_then(Value::as_array).expect("Expected nested 'error' array (causes)");
|
||||||
|
assert!(!causes_age.is_empty(), "Expected causes for invalid age");
|
||||||
|
let first_cause_age = &causes_age[0];
|
||||||
|
assert!(first_cause_age["kind"].as_str().unwrap().contains("Minimum"), "Kind '{}' should contain Minimum", first_cause_age["kind"]);
|
||||||
|
let msg = first_cause_age["message"].as_str().unwrap_or("");
|
||||||
|
assert!(msg.contains("must be >=0"), "Error message mismatch for age minimum: {}", msg);
|
||||||
|
|
||||||
// Get top-level errors
|
let invalid_result_missing = validate_json_schema(schema_id, jsonb(invalid_instance_missing));
|
||||||
let top_level_errors = invalid_result_type.0["errors"].as_array().expect("Top-level 'errors' should be an array");
|
assert!(!invalid_result_missing.0["success"].as_bool().unwrap());
|
||||||
assert_eq!(top_level_errors.len(), 1, "Should have exactly one top-level error for invalid type");
|
|
||||||
|
|
||||||
// Get the first (and only) top-level error
|
let error_obj_missing = invalid_result_missing.0.get("error").expect("Expected top-level 'error' object");
|
||||||
let top_level_error = top_level_errors.get(0).expect("Should get the first top-level error");
|
let causes_missing = error_obj_missing.get("error").and_then(Value::as_array).expect("Expected nested 'error' array (causes) for missing");
|
||||||
|
assert!(!causes_missing.is_empty(), "Expected causes for missing age");
|
||||||
|
let first_cause_missing = &causes_missing[0];
|
||||||
|
assert!(first_cause_missing["kind"].as_str().unwrap().contains("Required"));
|
||||||
|
let msg_missing = first_cause_missing["message"].as_str().unwrap_or("");
|
||||||
|
assert!(msg_missing.contains("missing properties 'age'"), "Error message mismatch for missing 'age': {}", msg_missing);
|
||||||
|
assert!(first_cause_missing["instance_path"] == "", "Expected empty instance path for missing field");
|
||||||
|
|
||||||
// Check top-level error kind
|
let non_existent_id = "non_existent_schema";
|
||||||
assert!(top_level_error.get("kind").and_then(Value::as_str).map_or(false, |k| k.starts_with("Schema { url:")),
|
let invalid_schema_result = validate_json_schema(non_existent_id, jsonb(json!({})));
|
||||||
"Incorrect kind for top-level error. Expected 'Schema {{ url:'. Error: {:?}. All errors: {:?}", top_level_error, top_level_errors);
|
assert!(!invalid_schema_result.0["success"].as_bool().unwrap());
|
||||||
|
let schema_not_found_error = invalid_schema_result.0
|
||||||
|
.get("error") // Top level error object
|
||||||
|
.expect("Expected top-level 'error' object for schema not found");
|
||||||
|
assert_eq!(schema_not_found_error["kind"], "SchemaNotFound");
|
||||||
|
assert!(schema_not_found_error["message"].as_str().unwrap().contains(non_existent_id));
|
||||||
|
}
|
||||||
|
|
||||||
// Get the 'causes' array from the top-level error
|
#[pg_test]
|
||||||
let causes_age = top_level_error.get("causes").and_then(Value::as_array).expect("Top-level error 'causes' should be an array");
|
fn test_validate_json_schema_not_cached() {
|
||||||
assert_eq!(causes_age.len(), 1, "Should have one cause for the age error");
|
setup_test();
|
||||||
|
let instance = json!({ "foo": "bar" });
|
||||||
|
let result = validate_json_schema("non_existent_schema", jsonb(instance));
|
||||||
|
assert!(!result.0["success"].as_bool().unwrap());
|
||||||
|
let error_obj = result.0.get("error").expect("Expected top-level 'error' object");
|
||||||
|
assert_eq!(error_obj["kind"], "SchemaNotFound");
|
||||||
|
assert!(error_obj["message"].as_str().unwrap().contains("non_existent_schema"));
|
||||||
|
}
|
||||||
|
|
||||||
// Get the actual age error from the 'causes' array
|
#[pg_test]
|
||||||
let age_error = causes_age.get(0).expect("Should have an error object in 'causes'");
|
fn test_cache_invalid_json_schema() {
|
||||||
assert_eq!(age_error.get("instance_path").and_then(Value::as_str), Some("/age"),
|
setup_test();
|
||||||
"Incorrect instance_path for age error. Error: {:?}. All errors: {:?}", age_error, top_level_errors);
|
let schema_id = "invalid_schema";
|
||||||
|
let invalid_schema_json = "{\"type\": \"string\" \"maxLength\": 5}";
|
||||||
|
let invalid_schema_value: Result<Value, _> = serde_json::from_str(invalid_schema_json);
|
||||||
|
assert!(invalid_schema_value.is_err(), "Test setup assumes invalid JSON string");
|
||||||
|
|
||||||
assert!(age_error.get("kind").and_then(Value::as_str).map_or(false, |k| k.starts_with("Minimum { got:")),
|
let schema_representing_invalid = json!({
|
||||||
"Incorrect kind prefix for age error. Expected 'Minimum {{ got:'. Error: {:?}. All errors: {:?}", age_error, top_level_errors);
|
"type": 123
|
||||||
|
});
|
||||||
|
|
||||||
let expected_prefix = "at '/age': must be >=0";
|
let result = cache_json_schema(schema_id, jsonb(schema_representing_invalid.clone()));
|
||||||
assert!(age_error.get("message")
|
assert!(!result.0["success"].as_bool().unwrap());
|
||||||
.and_then(Value::as_str)
|
let error_obj = result.0.get("error").expect("Expected top-level 'error' object for compilation failure");
|
||||||
.map_or(false, |m| m.starts_with(expected_prefix)),
|
assert_eq!(error_obj.get("kind").and_then(Value::as_str), Some("SchemaCompilationError"));
|
||||||
"Incorrect message prefix for age error. Expected prefix '{}'. Error: {:?}. All errors: {:?}",
|
assert_eq!(error_obj.get("sub_kind").and_then(Value::as_str), Some("ValidationError"), "Expected sub_kind 'ValidationError' for metaschema failure");
|
||||||
expected_prefix, age_error, top_level_errors);
|
assert!(error_obj.get("message").and_then(Value::as_str).is_some(), "Expected 'message' field in error object");
|
||||||
|
assert!(error_obj["message"].as_str().unwrap().contains("Schema failed validation against its metaschema"), "Error message mismatch");
|
||||||
|
assert_eq!(error_obj.get("schema_id").and_then(Value::as_str), Some(schema_id));
|
||||||
|
let failed_at_url = error_obj.get("failed_at_url").and_then(Value::as_str).expect("Expected 'failed_at_url' string");
|
||||||
|
assert!(failed_at_url.ends_with(&format!("{}#", schema_id)), "failed_at_url ('{}') should end with schema_id + '#' ('{}#')", failed_at_url, schema_id);
|
||||||
|
assert!(error_obj.get("validation_details").and_then(Value::as_str).is_some(), "Expected 'validation_details' field");
|
||||||
|
}
|
||||||
|
|
||||||
let invalid_result_missing = validate_json_schema(schema_id, jsonb(invalid_instance_missing));
|
#[pg_test]
|
||||||
assert!(!invalid_result_missing.0["success"].as_bool().unwrap(), "Validation should fail for missing required field");
|
fn test_validate_json_schema_detailed_validation_errors() {
|
||||||
|
setup_test();
|
||||||
|
let schema_id = "detailed_schema";
|
||||||
|
let schema = json!({
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"address": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"street": { "type": "string" },
|
||||||
|
"city": { "type": "string", "maxLength": 10 }
|
||||||
|
},
|
||||||
|
"required": ["street", "city"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["address"]
|
||||||
|
});
|
||||||
|
let invalid_instance = json!({
|
||||||
|
"address": {
|
||||||
|
"street": 123,
|
||||||
|
"city": "Supercalifragilisticexpialidocious"
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// --- Assertions for invalid_result_missing ---
|
assert!(cache_json_schema(schema_id, jsonb(schema.clone())).0["success"].as_bool().unwrap());
|
||||||
|
let result = validate_json_schema(schema_id, jsonb(invalid_instance));
|
||||||
|
assert!(!result.0["success"].as_bool().unwrap());
|
||||||
|
|
||||||
// Get top-level errors
|
let error_obj = result.0.get("error").expect("Expected top-level 'error' object");
|
||||||
let top_level_errors_missing = invalid_result_missing.0["errors"].as_array().expect("Errors should be an array for missing field");
|
let causes = error_obj.get("error").and_then(Value::as_array).expect("Expected nested 'error' array (causes)");
|
||||||
assert_eq!(top_level_errors_missing.len(), 1, "Should have one top-level error for missing field");
|
assert!(causes.len() >= 2, "Expected at least 2 detailed causes");
|
||||||
|
|
||||||
// Get the first (and only) top-level error
|
let street_error = causes.iter().find(|e| e["instance_path"] == "/address/street").expect("Missing street error");
|
||||||
let top_error_missing = top_level_errors_missing.get(0).expect("Should get the first top-level missing field error");
|
assert!(street_error["kind"].as_str().unwrap().contains("Type"), "Kind '{}' should contain Type", street_error["kind"]);
|
||||||
|
let street_msg = street_error["message"].as_str().unwrap_or("null");
|
||||||
|
assert!(street_msg.contains("want string, but got number"), "Street message mismatch: {}", street_msg);
|
||||||
|
|
||||||
// Check top-level error kind
|
let city_error = causes.iter().find(|e| e["instance_path"] == "/address/city").expect("Missing city error");
|
||||||
assert!(top_error_missing.get("kind").and_then(Value::as_str).map_or(false, |k| k.starts_with("Schema { url:")),
|
assert!(city_error["kind"].as_str().unwrap().contains("MaxLength"), "Kind '{}' should contain MaxLength", city_error["kind"]);
|
||||||
"Incorrect kind for missing field top-level error. Error: {:?}. All errors: {:?}", top_error_missing, top_level_errors_missing);
|
let city_msg = city_error["message"].as_str().unwrap_or("null");
|
||||||
|
assert!(city_msg.contains("length must be <=10"), "City message mismatch: {}", city_msg);
|
||||||
|
|
||||||
// Get the 'causes' array from the top-level error
|
assert_eq!(causes.len(), 2, "Expected exactly 2 errors (street type, city length)");
|
||||||
let causes_missing = top_error_missing.get("causes").and_then(Value::as_array).expect("Causes should be an array for missing field error");
|
}
|
||||||
assert_eq!(causes_missing.len(), 1, "Should have one cause for missing field");
|
|
||||||
|
|
||||||
// Get the actual missing field error from the 'causes' array
|
#[pg_test]
|
||||||
let missing_error = causes_missing.get(0).expect("Should have missing field error object in 'causes'");
|
fn test_validate_json_schema_oneof_validation_errors() {
|
||||||
|
setup_test();
|
||||||
|
let schema_id = "oneof_schema";
|
||||||
|
let schema = json!({
|
||||||
|
"oneOf": [
|
||||||
|
{
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"string_prop": { "type": "string", "maxLength": 5 }
|
||||||
|
},
|
||||||
|
"required": ["string_prop"]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"number_prop": { "type": "number", "minimum": 10 }
|
||||||
|
},
|
||||||
|
"required": ["number_prop"]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
// Assertions on the specific missing field error
|
cache_json_schema(schema_id, jsonb(schema));
|
||||||
assert_eq!(missing_error.get("instance_path").and_then(Value::as_str), Some(""),
|
|
||||||
"Incorrect instance_path for missing age error: {:?}", missing_error);
|
|
||||||
assert!(missing_error.get("kind").and_then(Value::as_str).map_or(false, |k| k.starts_with("Required { want: [\"age\"]")),
|
|
||||||
"Incorrect kind for missing age error. Expected prefix 'Required {{ want: [\"age\"] }}'. Error: {:?}", missing_error);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pg_test]
|
let invalid_string_instance = json!({ "string_prop": "toolongstring" });
|
||||||
fn test_validate_json_schema_not_cached() {
|
let result_invalid_string = validate_json_schema(schema_id, jsonb(invalid_string_instance));
|
||||||
setup_test();
|
assert!(!result_invalid_string.0["success"].as_bool().unwrap());
|
||||||
let instance = json!({ "foo": "bar" });
|
|
||||||
let result = validate_json_schema("non_existent_schema", jsonb(instance));
|
|
||||||
assert!(!result.0["success"].as_bool().unwrap());
|
|
||||||
let errors = result.0["errors"].as_array().unwrap();
|
|
||||||
assert_eq!(errors.len(), 1);
|
|
||||||
assert_eq!(errors[0]["kind"], json!("SchemaNotFound"));
|
|
||||||
assert!(errors[0]["message"].as_str().unwrap().contains("non_existent_schema"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pg_test]
|
let error_obj_string = result_invalid_string.0.get("error").expect("Expected top-level 'error' object");
|
||||||
fn test_cache_invalid_json_schema() {
|
assert!(error_obj_string["kind"].as_str().unwrap().contains("Schema"), "Top level kind '{}' should contain Schema for OneOf failure", error_obj_string["kind"]);
|
||||||
setup_test();
|
assert!(error_obj_string["message"].as_str().unwrap().contains("oneOf failed, none matched"), "OneOf message mismatch: {}", error_obj_string["message"]); // Final adjustment
|
||||||
let schema_id = "invalid_schema";
|
|
||||||
let invalid_schema_json = "{\"type\": \"string\" \"maxLength\": 5}";
|
|
||||||
let invalid_schema_value: Result<Value, _> = serde_json::from_str(invalid_schema_json);
|
|
||||||
assert!(invalid_schema_value.is_err(), "Test setup assumes invalid JSON string");
|
|
||||||
|
|
||||||
let schema_representing_invalid = json!({
|
let causes_string = error_obj_string.get("error").and_then(Value::as_array).expect("Expected nested 'error' array (causes)");
|
||||||
"type": 123
|
assert_eq!(causes_string.len(), 1, "Expected one cause for oneOf failure (string)");
|
||||||
});
|
|
||||||
|
|
||||||
let result = cache_json_schema(schema_id, jsonb(schema_representing_invalid.clone()));
|
let nested_causes_string = causes_string[0].get("error").and_then(Value::as_array).expect("Expected deeper nested causes for string oneOf");
|
||||||
assert!(!result.0["success"].as_bool().unwrap());
|
assert_eq!(nested_causes_string.len(), 2, "Expected two nested causes for string oneOf");
|
||||||
assert!(result.0["error"].as_str().unwrap().contains("Schema compilation failed"));
|
let string_schema_fail = nested_causes_string.iter().find(|c| c["schema_path"].as_str().unwrap().ends_with("/oneOf/0/properties/string_prop")).expect("Missing nested cause for string schema");
|
||||||
}
|
assert_eq!(string_schema_fail["instance_path"].as_str().unwrap(), "/string_prop", "Instance path should be /string_prop");
|
||||||
|
assert!(string_schema_fail["kind"].as_str().unwrap().contains("MaxLength"), "Nested string cause kind should be MaxLength");
|
||||||
|
let number_schema_fail = nested_causes_string.iter().find(|c| c["schema_path"].as_str().unwrap().ends_with("/oneOf/1")).expect("Missing nested cause for number schema");
|
||||||
|
assert_eq!(number_schema_fail["instance_path"].as_str().unwrap(), "", "Instance path for branch 2 type mismatch should be empty");
|
||||||
|
assert!(number_schema_fail["kind"].as_str().unwrap().contains("Required"), "Nested number cause kind should be Required");
|
||||||
|
|
||||||
#[pg_test]
|
let invalid_number_instance = json!({ "number_prop": 5 });
|
||||||
fn test_validate_json_schema_detailed_validation_errors() {
|
let result_invalid_number = validate_json_schema(schema_id, jsonb(invalid_number_instance));
|
||||||
setup_test();
|
assert!(!result_invalid_number.0["success"].as_bool().unwrap());
|
||||||
let schema_id = "detailed_schema";
|
|
||||||
let schema = json!({
|
|
||||||
"type": "object",
|
|
||||||
"properties": {
|
|
||||||
"address": {
|
|
||||||
"type": "object",
|
|
||||||
"properties": {
|
|
||||||
"street": { "type": "string" },
|
|
||||||
"city": { "type": "string", "maxLength": 10 }
|
|
||||||
},
|
|
||||||
"required": ["street", "city"]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"required": ["address"]
|
|
||||||
});
|
|
||||||
let invalid_instance = json!({
|
|
||||||
"address": {
|
|
||||||
"city": "San Francisco Bay Area"
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
assert!(cache_json_schema(schema_id, jsonb(schema.clone())).0["success"].as_bool().unwrap());
|
let error_obj_number = result_invalid_number.0.get("error").expect("Expected top-level 'error' object");
|
||||||
let result = validate_json_schema(schema_id, jsonb(invalid_instance));
|
assert!(error_obj_number["kind"].as_str().unwrap().contains("Schema"), "Top level kind '{}' should contain Schema for OneOf failure", error_obj_number["kind"]);
|
||||||
assert!(!result.0["success"].as_bool().unwrap());
|
assert!(error_obj_number["message"].as_str().unwrap().contains("oneOf failed, none matched"), "OneOf message mismatch: {}", error_obj_number["message"]); // Final adjustment
|
||||||
|
|
||||||
let errors = result.0["errors"].as_array().expect("Errors should be an array");
|
let causes_number = error_obj_number.get("error").and_then(Value::as_array).expect("Expected nested 'error' array (causes)");
|
||||||
let top_error = errors.get(0).expect("Expected at least one top-level error object");
|
assert_eq!(causes_number.len(), 1, "Expected one cause for oneOf failure (number)");
|
||||||
let causes = top_error.get("causes").and_then(Value::as_array).expect("Expected causes array");
|
let nested_causes_number = causes_number[0].get("error").and_then(Value::as_array).expect("Expected deeper nested causes for number oneOf");
|
||||||
|
assert_eq!(nested_causes_number.len(), 2, "Expected two nested causes for number oneOf");
|
||||||
|
let string_schema_fail_num = nested_causes_number.iter().find(|c| c["schema_path"].as_str().unwrap().ends_with("/oneOf/0")).expect("Missing nested cause for string schema (number case)");
|
||||||
|
assert_eq!(string_schema_fail_num["instance_path"].as_str().unwrap(), "", "Instance path for branch 1 type mismatch should be empty");
|
||||||
|
assert!(string_schema_fail_num["kind"].as_str().unwrap().contains("Required"), "Nested string cause kind should be Required (number case)");
|
||||||
|
let number_schema_fail_num = nested_causes_number.iter().find(|c| c["schema_path"].as_str().unwrap().ends_with("/oneOf/1/properties/number_prop")).expect("Missing nested cause for number schema (number case)");
|
||||||
|
assert_eq!(number_schema_fail_num["instance_path"].as_str().unwrap(), "/number_prop", "Instance path should be /number_prop (number case)");
|
||||||
|
assert!(number_schema_fail_num["kind"].as_str().unwrap().contains("Minimum"), "Nested number cause kind should be Minimum (number case)");
|
||||||
|
|
||||||
let has_required_street_error = causes.iter().any(|e|
|
let invalid_bool_instance = json!({ "other_prop": true });
|
||||||
e.get("instance_path").and_then(Value::as_str) == Some("/address") && // Check path inside cause
|
let result_invalid_bool = validate_json_schema(schema_id, jsonb(invalid_bool_instance));
|
||||||
e.get("kind").and_then(Value::as_str).unwrap_or("").starts_with("Required { want:") && // Check kind prefix
|
assert!(!result_invalid_bool.0["success"].as_bool().unwrap());
|
||||||
e.get("kind").and_then(Value::as_str).unwrap_or("").contains("street") // Ensure 'street' is mentioned
|
|
||||||
);
|
|
||||||
assert!(has_required_street_error, "Missing required 'street' error within causes. Actual errors: {:?}", errors);
|
|
||||||
|
|
||||||
let has_maxlength_city_error = causes.iter().any(|e| // Check within causes
|
let error_obj_bool = result_invalid_bool.0.get("error").expect("Expected top-level 'error' object");
|
||||||
e.get("instance_path").and_then(Value::as_str) == Some("/address/city") &&
|
assert!(error_obj_bool["kind"].as_str().unwrap().contains("Schema"), "Top level kind '{}' should contain Schema for OneOf failure", error_obj_bool["kind"]);
|
||||||
e.get("kind").and_then(Value::as_str).unwrap_or("").starts_with("MaxLength { got:") // Check kind prefix
|
assert!(error_obj_bool["message"].as_str().unwrap().contains("oneOf failed, none matched"), "OneOf message mismatch: {}", error_obj_bool["message"]); // Final adjustment
|
||||||
);
|
|
||||||
assert!(has_maxlength_city_error, "Missing maxLength 'city' error within causes. Actual errors: {:?}", errors);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pg_test]
|
let causes_bool = error_obj_bool.get("error").and_then(Value::as_array).expect("Expected nested 'error' array (causes)");
|
||||||
fn test_validate_json_schema_oneof_validation_errors() {
|
assert_eq!(causes_bool.len(), 1, "Expected one cause for oneOf failure (bool)");
|
||||||
setup_test();
|
let nested_causes_bool = causes_bool[0].get("error").and_then(Value::as_array).expect("Expected deeper nested causes for bool oneOf");
|
||||||
let schema_id = "oneof_schema";
|
assert_eq!(nested_causes_bool.len(), 2, "Expected two nested causes for bool oneOf");
|
||||||
let schema = json!({
|
let bool_fail_0 = nested_causes_bool.iter().find(|c| c["schema_path"].as_str().unwrap().ends_with("/oneOf/0")).expect("Missing nested cause for branch 0 type fail");
|
||||||
"type": "object",
|
assert_eq!(bool_fail_0["instance_path"].as_str().unwrap(), "", "Instance path for branch 0 type fail should be empty");
|
||||||
"properties": {
|
assert!(bool_fail_0["kind"].as_str().unwrap().contains("Required"), "Nested bool cause 0 kind should be Required");
|
||||||
"value": {
|
let bool_fail_1 = nested_causes_bool.iter().find(|c| c["schema_path"].as_str().unwrap().ends_with("/oneOf/1")).expect("Missing nested cause for branch 1 type fail");
|
||||||
"oneOf": [
|
assert_eq!(bool_fail_1["instance_path"].as_str().unwrap(), "", "Instance path for branch 1 type fail should be empty");
|
||||||
{ "type": "string", "minLength": 5 },
|
assert!(bool_fail_1["kind"].as_str().unwrap().contains("Required"), "Nested bool cause 1 kind should be Required");
|
||||||
{ "type": "number", "minimum": 10 }
|
}
|
||||||
]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"required": ["value"]
|
|
||||||
});
|
|
||||||
assert!(cache_json_schema(schema_id, jsonb(schema.clone())).0["success"].as_bool().unwrap());
|
|
||||||
|
|
||||||
let invalid_instance = json!({ "value": "abc" });
|
#[pg_test]
|
||||||
let result = validate_json_schema(schema_id, jsonb(invalid_instance));
|
fn test_clear_json_schemas() {
|
||||||
|
setup_test();
|
||||||
|
let schema_id = "schema_to_clear";
|
||||||
|
let schema = json!({ "type": "string" });
|
||||||
|
cache_json_schema(schema_id, jsonb(schema.clone()));
|
||||||
|
|
||||||
assert!(!result.0["success"].as_bool().unwrap());
|
let show_result1 = show_json_schemas();
|
||||||
|
assert!(show_result1.contains(&schema_id.to_string()));
|
||||||
|
|
||||||
let errors_val = result.0["errors"].as_array().expect("Errors should be an array");
|
clear_json_schemas();
|
||||||
let top_schema_error = errors_val.get(0).expect("Expected at least one top-level Schema error object");
|
|
||||||
let schema_error_causes = top_schema_error.get("causes").and_then(Value::as_array).expect("Expected causes array for Schema error");
|
|
||||||
|
|
||||||
let oneof_error = schema_error_causes.iter().find(|e| {
|
let show_result2 = show_json_schemas();
|
||||||
e.get("kind").and_then(Value::as_str) == Some("OneOf(None)") &&
|
assert!(show_result2.is_empty());
|
||||||
e.get("instance_path").and_then(Value::as_str) == Some("/value")
|
|
||||||
}).expect("Could not find the OneOf(None) error for /value within Schema causes");
|
|
||||||
|
|
||||||
let oneof_causes = oneof_error.get("causes").and_then(Value::as_array)
|
let instance = json!("test");
|
||||||
.expect("Expected causes array for OneOf error");
|
let validate_result = validate_json_schema(schema_id, jsonb(instance));
|
||||||
|
assert!(!validate_result.0["success"].as_bool().unwrap());
|
||||||
|
let error_obj = validate_result.0.get("error").expect("Expected top-level 'error' object");
|
||||||
|
assert_eq!(error_obj["kind"], "SchemaNotFound");
|
||||||
|
assert!(error_obj["message"].as_str().unwrap().contains(schema_id));
|
||||||
|
}
|
||||||
|
|
||||||
let has_minlength_error = oneof_causes.iter().any(|e| // Check within OneOf causes
|
#[pg_test]
|
||||||
e.get("instance_path").and_then(Value::as_str) == Some("/value") &&
|
fn test_show_json_schemas() {
|
||||||
e.get("kind").and_then(Value::as_str).unwrap_or("").starts_with("MinLength { got:") // Check kind prefix
|
setup_test();
|
||||||
);
|
let schema_id1 = "schema1";
|
||||||
assert!(has_minlength_error, "Missing MinLength error within OneOf causes. Actual errors: {:?}", errors_val);
|
let schema_id2 = "schema2";
|
||||||
|
let schema = json!({ "type": "boolean" });
|
||||||
|
|
||||||
let has_type_error = oneof_causes.iter().any(|e| // Check within OneOf causes
|
cache_json_schema(schema_id1, jsonb(schema.clone()));
|
||||||
e.get("instance_path").and_then(Value::as_str) == Some("/value") &&
|
cache_json_schema(schema_id2, jsonb(schema.clone()));
|
||||||
e.get("kind").and_then(Value::as_str).unwrap_or("").starts_with("Type { got: String, want: Types") // More specific kind check
|
|
||||||
);
|
|
||||||
assert!(has_type_error, "Missing Type error within OneOf causes. Actual errors: {:?}", errors_val);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pg_test]
|
let result = show_json_schemas();
|
||||||
fn test_clear_json_schemas() {
|
assert!(result.contains(&schema_id1.to_string()));
|
||||||
setup_test();
|
assert!(result.contains(&schema_id2.to_string()));
|
||||||
let schema_id = "schema_to_clear";
|
}
|
||||||
let schema = json!({ "type": "string" });
|
|
||||||
cache_json_schema(schema_id, jsonb(schema.clone()));
|
|
||||||
|
|
||||||
let show_result1 = show_json_schemas();
|
|
||||||
assert!(show_result1.0["cached_schema_ids"].as_array().unwrap().iter().any(|id| id.as_str() == Some(schema_id)));
|
|
||||||
|
|
||||||
let clear_result = clear_json_schemas();
|
|
||||||
assert!(clear_result.0["success"].as_bool().unwrap());
|
|
||||||
|
|
||||||
let show_result2 = show_json_schemas();
|
|
||||||
assert!(show_result2.0["cached_schema_ids"].as_array().unwrap().is_empty());
|
|
||||||
|
|
||||||
let instance = json!("test");
|
|
||||||
let validate_result = validate_json_schema(schema_id, jsonb(instance));
|
|
||||||
assert!(!validate_result.0["success"].as_bool().unwrap());
|
|
||||||
assert_eq!(validate_result.0["errors"].as_array().unwrap()[0]["kind"], json!("SchemaNotFound"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pg_test]
|
|
||||||
fn test_show_json_schemas() {
|
|
||||||
setup_test();
|
|
||||||
let schema_id1 = "schema1";
|
|
||||||
let schema_id2 = "schema2";
|
|
||||||
let schema = json!({ "type": "boolean" });
|
|
||||||
|
|
||||||
cache_json_schema(schema_id1, jsonb(schema.clone()));
|
|
||||||
cache_json_schema(schema_id2, jsonb(schema.clone()));
|
|
||||||
|
|
||||||
let result = show_json_schemas();
|
|
||||||
let ids = result.0["cached_schema_ids"].as_array().unwrap();
|
|
||||||
assert_eq!(ids.len(), 2);
|
|
||||||
assert!(ids.contains(&json!(schema_id1)));
|
|
||||||
assert!(ids.contains(&json!(schema_id2)));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
pub mod pg_test {
|
pub mod pg_test {
|
||||||
pub fn setup(_options: Vec<&str>) {
|
pub fn setup(_options: Vec<&str>) {
|
||||||
// perform one-off initialization when the pg_test framework starts
|
// perform one-off initialization when the pg_test framework starts
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn postgresql_conf_options() -> Vec<&'static str> {
|
pub fn postgresql_conf_options() -> Vec<&'static str> {
|
||||||
// return any postgresql.conf settings that are required for your tests
|
// return any postgresql.conf settings that are required for your tests
|
||||||
vec![]
|
vec![]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user