|
| 1 | +""" |
| 2 | +jsonschema-rs adapter for openapi-spec-validator. |
| 3 | +
|
| 4 | +This module provides a compatibility layer between jsonschema-rs (Rust) |
| 5 | +and the existing jsonschema (Python) validator interface. |
| 6 | +""" |
| 7 | + |
| 8 | +import importlib |
| 9 | +from typing import TYPE_CHECKING |
| 10 | +from typing import Any |
| 11 | +from typing import Iterator |
| 12 | +from typing import cast |
| 13 | + |
| 14 | +if TYPE_CHECKING: |
| 15 | + |
| 16 | + class ValidationErrorBase(Exception): |
| 17 | + def __init__(self, *args: Any, **kwargs: Any) -> None: ... |
| 18 | + |
| 19 | +else: |
| 20 | + from jsonschema.exceptions import ValidationError as ValidationErrorBase |
| 21 | + |
| 22 | +# Try to import jsonschema-rs |
| 23 | +jsonschema_rs: Any = None |
| 24 | +try: |
| 25 | + jsonschema_rs = importlib.import_module("jsonschema_rs") |
| 26 | + |
| 27 | + HAS_JSONSCHEMA_RS = True |
| 28 | +except ImportError: |
| 29 | + HAS_JSONSCHEMA_RS = False |
| 30 | + |
| 31 | + |
| 32 | +def _get_jsonschema_rs_module() -> Any: |
| 33 | + if jsonschema_rs is None: |
| 34 | + raise ImportError( |
| 35 | + "jsonschema-rs is not installed. Install it with: " |
| 36 | + "pip install jsonschema-rs" |
| 37 | + ) |
| 38 | + return jsonschema_rs |
| 39 | + |
| 40 | + |
| 41 | +class RustValidatorError(ValidationErrorBase): |
| 42 | + """ValidationError compatible with jsonschema, but originating from Rust validator.""" |
| 43 | + |
| 44 | + pass |
| 45 | + |
| 46 | + |
| 47 | +class RustValidatorWrapper: |
| 48 | + """ |
| 49 | + Wrapper that makes jsonschema-rs validator compatible with jsonschema interface. |
| 50 | +
|
| 51 | + This allows drop-in replacement while maintaining the same API surface. |
| 52 | + """ |
| 53 | + |
| 54 | + def __init__(self, schema: dict[str, Any], validator: Any): |
| 55 | + """ |
| 56 | + Initialize Rust validator wrapper. |
| 57 | +
|
| 58 | + Args: |
| 59 | + schema: JSON Schema to validate against |
| 60 | + cls: JSON Schema validator |
| 61 | + """ |
| 62 | + if not HAS_JSONSCHEMA_RS: |
| 63 | + raise ImportError( |
| 64 | + "jsonschema-rs is not installed. Install it with: " |
| 65 | + "pip install jsonschema-rs" |
| 66 | + ) |
| 67 | + |
| 68 | + self.schema = schema |
| 69 | + self._rs_validator = validator |
| 70 | + |
| 71 | + def iter_errors(self, instance: Any) -> Iterator[ValidationErrorBase]: |
| 72 | + """ |
| 73 | + Validate instance and yield errors in jsonschema format. |
| 74 | +
|
| 75 | + This method converts jsonschema-rs errors to jsonschema ValidationError |
| 76 | + format for compatibility with existing code. |
| 77 | + """ |
| 78 | + for error in self._rs_validator.iter_errors(instance): |
| 79 | + yield self._convert_rust_error(error, instance) |
| 80 | + |
| 81 | + def validate(self, instance: Any) -> None: |
| 82 | + """ |
| 83 | + Validate instance and raise ValidationError if invalid. |
| 84 | +
|
| 85 | + Compatible with jsonschema Validator.validate() method. |
| 86 | + """ |
| 87 | + try: |
| 88 | + self._rs_validator.validate(instance) |
| 89 | + except _get_jsonschema_rs_module().ValidationError as e: |
| 90 | + # Convert and raise as Python ValidationError |
| 91 | + py_error = self._convert_rust_error_exception(e, instance) |
| 92 | + raise py_error from e |
| 93 | + |
| 94 | + def is_valid(self, instance: Any) -> bool: |
| 95 | + """Check if instance is valid against schema.""" |
| 96 | + return cast(bool, self._rs_validator.is_valid(instance)) |
| 97 | + |
| 98 | + def _convert_rust_error( |
| 99 | + self, rust_error: Any, instance: Any |
| 100 | + ) -> ValidationErrorBase: |
| 101 | + """ |
| 102 | + Convert jsonschema-rs error format to jsonschema ValidationError. |
| 103 | +
|
| 104 | + jsonschema-rs error structure: |
| 105 | + - message: str |
| 106 | + - instance_path: list |
| 107 | + - schema_path: list (if available) |
| 108 | + """ |
| 109 | + message = str(rust_error) |
| 110 | + |
| 111 | + # Extract path information if available |
| 112 | + # Note: jsonschema-rs error format may differ - adjust as needed |
| 113 | + instance_path = getattr(rust_error, "instance_path", []) |
| 114 | + schema_path = getattr(rust_error, "schema_path", []) |
| 115 | + |
| 116 | + return RustValidatorError( |
| 117 | + message=message, |
| 118 | + path=list(instance_path) if instance_path else [], |
| 119 | + schema_path=list(schema_path) if schema_path else [], |
| 120 | + instance=instance, |
| 121 | + schema=self.schema, |
| 122 | + ) |
| 123 | + |
| 124 | + def _convert_rust_error_exception( |
| 125 | + self, rust_error: Any, instance: Any |
| 126 | + ) -> ValidationErrorBase: |
| 127 | + """Convert jsonschema-rs ValidationError exception to Python format.""" |
| 128 | + message = str(rust_error) |
| 129 | + |
| 130 | + return RustValidatorError( |
| 131 | + message=message, |
| 132 | + instance=instance, |
| 133 | + schema=self.schema, |
| 134 | + ) |
| 135 | + |
| 136 | + |
| 137 | +def create_validator(schema: dict[str, Any]) -> RustValidatorWrapper: |
| 138 | + """ |
| 139 | + Factory function to create Rust-backed validator. |
| 140 | +
|
| 141 | + Args: |
| 142 | + schema: JSON Schema to validate against |
| 143 | +
|
| 144 | + Returns: |
| 145 | + RustValidatorWrapper instance |
| 146 | + """ |
| 147 | + |
| 148 | + # Create appropriate Rust validator based on draft |
| 149 | + module = _get_jsonschema_rs_module() |
| 150 | + validator_cls: Any = module.validator_cls_for(schema) |
| 151 | + |
| 152 | + validator = validator_cls( |
| 153 | + schema, |
| 154 | + validate_formats=True, |
| 155 | + ) |
| 156 | + return RustValidatorWrapper(schema, validator=validator) |
| 157 | + |
| 158 | + |
| 159 | +# Convenience function to check if Rust validators are available |
| 160 | +def has_jsonschema_rs_validators() -> bool: |
| 161 | + """Check if jsonschema-rs is available.""" |
| 162 | + return HAS_JSONSCHEMA_RS |
0 commit comments