-
-
Notifications
You must be signed in to change notification settings - Fork 73
Jsonschema-rs backend #478
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| """Schema validator backend selection and factories.""" | ||
|
|
||
| from typing import Any | ||
|
|
||
| from openapi_spec_validator.schemas.backend.jsonschema import ( | ||
| create_validator as create_jsonschema_validator, | ||
| ) | ||
| from openapi_spec_validator.schemas.backend.jsonschema_rs import ( | ||
| create_validator as create_jsonschema_rs_validator, | ||
| ) | ||
| from openapi_spec_validator.schemas.backend.jsonschema_rs import ( | ||
| has_jsonschema_rs_validators, | ||
| ) | ||
| from openapi_spec_validator.settings import get_schema_validator_backend | ||
|
|
||
|
|
||
| def _use_jsonschema_rs() -> bool: | ||
| backend_mode = get_schema_validator_backend() | ||
| available = has_jsonschema_rs_validators() | ||
|
|
||
| if backend_mode == "jsonschema": | ||
| return False | ||
| if backend_mode == "jsonschema-rs": | ||
| if not available: | ||
| raise RuntimeError( | ||
| "OPENAPI_SPEC_VALIDATOR_SCHEMA_VALIDATOR_BACKEND=" | ||
| "jsonschema-rs is set but jsonschema-rs is not available. " | ||
| "Install it with: pip install jsonschema-rs" | ||
| ) | ||
| return True | ||
| return available | ||
|
|
||
|
|
||
| def get_validator_backend() -> str: | ||
| if _use_jsonschema_rs(): | ||
| return "jsonschema-rs" | ||
| return "jsonschema" | ||
|
|
||
|
|
||
| def get_validator_for(schema: dict[str, Any]) -> Any: | ||
| if _use_jsonschema_rs(): | ||
| return create_jsonschema_rs_validator(dict(schema)) | ||
| return create_jsonschema_validator(schema) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| from typing import Any | ||
|
|
||
| from jsonschema.validators import validator_for | ||
|
|
||
|
|
||
| def create_validator(schema: dict[str, Any]) -> Any: | ||
| validator_cls = validator_for(schema) | ||
| return validator_cls(schema) |
162 changes: 162 additions & 0 deletions
162
openapi_spec_validator/schemas/backend/jsonschema_rs.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,162 @@ | ||
| """ | ||
| jsonschema-rs adapter for openapi-spec-validator. | ||
|
|
||
| This module provides a compatibility layer between jsonschema-rs (Rust) | ||
| and the existing jsonschema (Python) validator interface. | ||
| """ | ||
|
|
||
| import importlib | ||
| from collections.abc import Iterator | ||
| from typing import TYPE_CHECKING | ||
| from typing import Any | ||
| from typing import cast | ||
|
|
||
| if TYPE_CHECKING: | ||
|
|
||
| class ValidationErrorBase(Exception): | ||
| def __init__(self, *args: Any, **kwargs: Any) -> None: ... | ||
|
|
||
| else: | ||
| from jsonschema.exceptions import ValidationError as ValidationErrorBase | ||
|
|
||
| # Try to import jsonschema-rs | ||
| jsonschema_rs: Any = None | ||
| try: | ||
| jsonschema_rs = importlib.import_module("jsonschema_rs") | ||
|
|
||
| HAS_JSONSCHEMA_RS = True | ||
| except ImportError: | ||
| HAS_JSONSCHEMA_RS = False | ||
|
|
||
|
|
||
| def _get_jsonschema_rs_module() -> Any: | ||
| if jsonschema_rs is None: | ||
| raise ImportError( | ||
| "jsonschema-rs is not installed. Install it with: " | ||
| "pip install jsonschema-rs" | ||
| ) | ||
| return jsonschema_rs | ||
|
|
||
|
|
||
| class JsonschemaRsValidatorError(ValidationErrorBase): | ||
| """ValidationError compatible with jsonschema, but originating from Rust validator.""" | ||
|
|
||
| pass | ||
|
|
||
|
|
||
| class JsonschemaRsValidatorWrapper: | ||
| """ | ||
| Wrapper that makes jsonschema-rs validator compatible with jsonschema interface. | ||
|
|
||
| This allows drop-in replacement while maintaining the same API surface. | ||
| """ | ||
|
|
||
| def __init__(self, schema: dict[str, Any], validator: Any): | ||
| """ | ||
| Initialize Rust validator wrapper. | ||
|
|
||
| Args: | ||
| schema: JSON Schema to validate against | ||
| cls: JSON Schema validator | ||
p1c2u marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| """ | ||
| if not HAS_JSONSCHEMA_RS: | ||
| raise ImportError( | ||
| "jsonschema-rs is not installed. Install it with: " | ||
| "pip install jsonschema-rs" | ||
| ) | ||
|
|
||
| self.schema = schema | ||
| self._rs_validator = validator | ||
|
|
||
| def iter_errors(self, instance: Any) -> Iterator[ValidationErrorBase]: | ||
| """ | ||
| Validate instance and yield errors in jsonschema format. | ||
|
|
||
| This method converts jsonschema-rs errors to jsonschema ValidationError | ||
| format for compatibility with existing code. | ||
| """ | ||
| for error in self._rs_validator.iter_errors(instance): | ||
| yield self._convert_rust_error(error, instance) | ||
|
|
||
| def validate(self, instance: Any) -> None: | ||
| """ | ||
| Validate instance and raise ValidationError if invalid. | ||
|
|
||
| Compatible with jsonschema Validator.validate() method. | ||
| """ | ||
| try: | ||
| self._rs_validator.validate(instance) | ||
| except _get_jsonschema_rs_module().ValidationError as e: | ||
| # Convert and raise as Python ValidationError | ||
| py_error = self._convert_rust_error_exception(e, instance) | ||
| raise py_error from e | ||
|
|
||
| def is_valid(self, instance: Any) -> bool: | ||
| """Check if instance is valid against schema.""" | ||
| return cast(bool, self._rs_validator.is_valid(instance)) | ||
|
|
||
| def _convert_rust_error( | ||
| self, rust_error: Any, instance: Any | ||
| ) -> ValidationErrorBase: | ||
| """ | ||
| Convert jsonschema-rs error format to jsonschema ValidationError. | ||
|
|
||
| jsonschema-rs error structure: | ||
| - message: str | ||
| - instance_path: list | ||
| - schema_path: list (if available) | ||
| """ | ||
| message = str(rust_error) | ||
|
|
||
| # Extract path information if available | ||
| # Note: jsonschema-rs error format may differ - adjust as needed | ||
| instance_path = getattr(rust_error, "instance_path", []) | ||
| schema_path = getattr(rust_error, "schema_path", []) | ||
|
|
||
| return JsonschemaRsValidatorError( | ||
| message=message, | ||
| path=list(instance_path) if instance_path else [], | ||
| schema_path=list(schema_path) if schema_path else [], | ||
| instance=instance, | ||
| schema=self.schema, | ||
| ) | ||
|
|
||
| def _convert_rust_error_exception( | ||
| self, rust_error: Any, instance: Any | ||
| ) -> ValidationErrorBase: | ||
| """Convert jsonschema-rs ValidationError exception to Python format.""" | ||
| message = str(rust_error) | ||
|
|
||
| return JsonschemaRsValidatorError( | ||
| message=message, | ||
| instance=instance, | ||
| schema=self.schema, | ||
| ) | ||
|
|
||
|
|
||
| def create_validator(schema: dict[str, Any]) -> JsonschemaRsValidatorWrapper: | ||
| """ | ||
| Factory function to create Rust-backed validator. | ||
|
|
||
| Args: | ||
| schema: JSON Schema to validate against | ||
|
|
||
| Returns: | ||
| JsonschemaRsValidatorWrapper instance | ||
| """ | ||
|
|
||
| # Create appropriate Rust validator based on draft | ||
| module = _get_jsonschema_rs_module() | ||
| validator_cls: Any = module.validator_cls_for(schema) | ||
|
|
||
| validator = validator_cls( | ||
| schema, | ||
| validate_formats=True, | ||
| ) | ||
p1c2u marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| return JsonschemaRsValidatorWrapper(schema, validator=validator) | ||
|
|
||
|
|
||
| # Convenience function to check if Rust validators are available | ||
| def has_jsonschema_rs_validators() -> bool: | ||
| """Check if jsonschema-rs is available.""" | ||
| return HAS_JSONSCHEMA_RS | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.