Skip to content

Commit ca99636

Browse files
committed
Rust backend
1 parent a093f9c commit ca99636

File tree

9 files changed

+426
-11
lines changed

9 files changed

+426
-11
lines changed

.github/workflows/python-tests.yml

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,20 @@ on:
1010

1111
jobs:
1212
tests:
13-
name: "py${{ matrix.python-version }}-${{ matrix.os }}"
13+
name: "py${{ matrix.python-version }}-${{ matrix.os }}-${{ matrix.backend }}"
1414
runs-on: ${{ matrix.os }}
1515
strategy:
1616
matrix:
1717
python-version: ['3.10', '3.11', '3.12', '3.13', '3.14']
1818
os: [windows-latest, ubuntu-latest]
19+
backend: ['jsonschema']
20+
include:
21+
- python-version: '3.12'
22+
os: ubuntu-latest
23+
backend: 'jsonschema-rs'
24+
- python-version: '3.13'
25+
os: windows-latest
26+
backend: 'jsonschema-rs'
1927
fail-fast: false
2028
steps:
2129
- uses: actions/checkout@v4
@@ -49,9 +57,14 @@ jobs:
4957
- name: Install dependencies
5058
run: poetry install --all-extras
5159

60+
- name: Install jsonschema-rs
61+
if: matrix.backend != 'jsonschema'
62+
run: poetry run pip install ${{ matrix.backend }}
63+
5264
- name: Test
5365
env:
5466
PYTEST_ADDOPTS: "--color=yes"
67+
OPENAPI_SPEC_VALIDATOR_SCHEMA_VALIDATOR_BACKEND: ${{ matrix.backend }}
5568
run: poetry run pytest
5669

5770
- name: Static type check

README.rst

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,16 @@ Rules:
131131
* Set ``0`` to disable the resolved cache.
132132
* Invalid values (non-integer or negative) fall back to ``128``.
133133

134+
You can also choose schema validator backend:
135+
136+
.. code-block:: bash
137+
138+
OPENAPI_SPEC_VALIDATOR_SCHEMA_VALIDATOR_BACKEND=jsonschema-rs
139+
140+
Allowed values are ``auto`` (default), ``jsonschema``, and
141+
``jsonschema-rs``.
142+
Invalid values raise a warning and fall back to ``auto``.
143+
134144
Related projects
135145
################
136146

docs/cli.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,3 +73,7 @@ Performance note:
7373
You can tune resolved-path caching with
7474
``OPENAPI_SPEC_VALIDATOR_RESOLVED_CACHE_MAXSIZE``.
7575
Default is ``128``; set ``0`` to disable.
76+
77+
You can also select schema validator backend with
78+
``OPENAPI_SPEC_VALIDATOR_SCHEMA_VALIDATOR_BACKEND``
79+
(``auto``/``jsonschema``/``jsonschema-rs``).

docs/python.rst

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,3 +75,13 @@ Rules:
7575
* Default is ``128``.
7676
* Set ``0`` to disable the resolved cache.
7777
* Invalid values (non-integer or negative) fall back to ``128``.
78+
79+
Schema validator backend can be selected with:
80+
81+
.. code-block:: bash
82+
83+
OPENAPI_SPEC_VALIDATOR_SCHEMA_VALIDATOR_BACKEND=jsonschema-rs
84+
85+
Allowed values are ``auto`` (default), ``jsonschema``, and
86+
``jsonschema-rs``.
87+
Invalid values raise a warning and fall back to ``auto``.

openapi_spec_validator/schemas/__init__.py

Lines changed: 97 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,63 @@
11
"""OpenAIP spec validator schemas module."""
22

33
from functools import partial
4+
from typing import Any
45

56
from jsonschema.validators import Draft4Validator
67
from jsonschema.validators import Draft202012Validator
78
from lazy_object_proxy import Proxy
89

910
from openapi_spec_validator.schemas.utils import get_schema_content
11+
from openapi_spec_validator.settings import get_schema_validator_backend
1012

11-
__all__ = ["schema_v2", "schema_v3", "schema_v30", "schema_v31", "schema_v32"]
13+
_create_jsonschema_rs_validator_impl: Any = None
14+
15+
# Import jsonschema-rs adapters
16+
try:
17+
from openapi_spec_validator.schemas.jsonschema_rs_adapters import (
18+
create_validator as _create_jsonschema_rs_validator_impl,
19+
)
20+
from openapi_spec_validator.schemas.jsonschema_rs_adapters import (
21+
has_jsonschema_rs_validators,
22+
)
23+
24+
_USE_JSONSCHEMA_RS = has_jsonschema_rs_validators()
25+
except ImportError:
26+
_create_jsonschema_rs_validator_impl = None
27+
_USE_JSONSCHEMA_RS = False
28+
29+
def has_jsonschema_rs_validators() -> bool:
30+
return False
31+
32+
pass
33+
34+
35+
_BACKEND_MODE = get_schema_validator_backend()
36+
37+
if _BACKEND_MODE == "jsonschema":
38+
_USE_JSONSCHEMA_RS = False
39+
elif _BACKEND_MODE == "jsonschema-rs" and not _USE_JSONSCHEMA_RS:
40+
raise ImportError(
41+
"OPENAPI_SPEC_VALIDATOR_SCHEMA_VALIDATOR_BACKEND=jsonschema-rs "
42+
"is set but jsonschema-rs is not available. "
43+
"Install it with: pip install jsonschema-rs"
44+
)
45+
46+
47+
def get_validator_backend() -> str:
48+
if _USE_JSONSCHEMA_RS:
49+
return "rust (jsonschema-rs)"
50+
return "python (jsonschema)"
51+
52+
53+
__all__ = [
54+
"schema_v2",
55+
"schema_v3",
56+
"schema_v30",
57+
"schema_v31",
58+
"schema_v32",
59+
"get_validator_backend",
60+
]
1261

1362
get_schema_content_v2 = partial(get_schema_content, "2.0")
1463
get_schema_content_v30 = partial(get_schema_content, "3.0")
@@ -23,10 +72,53 @@
2372
# alias to the latest v3 version
2473
schema_v3 = schema_v32
2574

26-
get_openapi_v2_schema_validator = partial(Draft4Validator, schema_v2)
27-
get_openapi_v30_schema_validator = partial(Draft4Validator, schema_v30)
28-
get_openapi_v31_schema_validator = partial(Draft202012Validator, schema_v31)
29-
get_openapi_v32_schema_validator = partial(Draft202012Validator, schema_v32)
75+
76+
def _create_jsonschema_rs_schema_validator(
77+
schema: dict[str, Any],
78+
draft: str,
79+
) -> Any:
80+
if _create_jsonschema_rs_validator_impl is None:
81+
raise ImportError(
82+
"jsonschema-rs is not available. "
83+
"Install it with: pip install jsonschema-rs"
84+
)
85+
return _create_jsonschema_rs_validator_impl(schema, draft)
86+
87+
88+
# Validator factory functions with Rust/Python selection
89+
def get_openapi_v2_schema_validator() -> Any:
90+
"""Create OpenAPI 2.0 schema validator (Draft4)."""
91+
if _USE_JSONSCHEMA_RS:
92+
return _create_jsonschema_rs_schema_validator(dict(schema_v2), draft="draft4")
93+
return Draft4Validator(schema_v2)
94+
95+
96+
def get_openapi_v30_schema_validator() -> Any:
97+
"""Create OpenAPI 3.0 schema validator (Draft4)."""
98+
if _USE_JSONSCHEMA_RS:
99+
return _create_jsonschema_rs_schema_validator(dict(schema_v30), draft="draft4")
100+
return Draft4Validator(schema_v30)
101+
102+
103+
def get_openapi_v31_schema_validator() -> Any:
104+
"""Create OpenAPI 3.1 schema validator (Draft 2020-12)."""
105+
if _USE_JSONSCHEMA_RS:
106+
return _create_jsonschema_rs_schema_validator(
107+
dict(schema_v31),
108+
draft="draft202012",
109+
)
110+
return Draft202012Validator(schema_v31)
111+
112+
113+
def get_openapi_v32_schema_validator() -> Any:
114+
"""Create OpenAPI 3.2 schema validator (Draft 2020-12)."""
115+
if _USE_JSONSCHEMA_RS:
116+
return _create_jsonschema_rs_schema_validator(
117+
dict(schema_v32),
118+
draft="draft202012",
119+
)
120+
return Draft202012Validator(schema_v32)
121+
30122

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

0 commit comments

Comments
 (0)