Skip to content

Commit 8b6b7c9

Browse files
committed
Rust backend
1 parent a093f9c commit 8b6b7c9

File tree

9 files changed

+408
-11
lines changed

9 files changed

+408
-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: ['auto']
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 != 'auto'
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: 94 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,60 @@
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+
get_validator_backend,
22+
)
23+
from openapi_spec_validator.schemas.jsonschema_rs_adapters import (
24+
has_jsonschema_rs_validators,
25+
)
26+
27+
_USE_JSONSCHEMA_RS = has_jsonschema_rs_validators()
28+
except ImportError:
29+
_create_jsonschema_rs_validator_impl = None
30+
_USE_JSONSCHEMA_RS = False
31+
32+
def has_jsonschema_rs_validators() -> bool:
33+
return False
34+
35+
def get_validator_backend() -> str:
36+
return "python (jsonschema)"
37+
38+
39+
_BACKEND_MODE = get_schema_validator_backend()
40+
41+
if _BACKEND_MODE == "jsonschema":
42+
_USE_JSONSCHEMA_RS = False
43+
elif _BACKEND_MODE == "jsonschema-rs" and not _USE_JSONSCHEMA_RS:
44+
raise ImportError(
45+
"OPENAPI_SPEC_VALIDATOR_SCHEMA_VALIDATOR_BACKEND=jsonschema-rs "
46+
"is set but jsonschema-rs is not available. "
47+
"Install it with: pip install jsonschema-rs"
48+
)
49+
50+
__all__ = [
51+
"schema_v2",
52+
"schema_v3",
53+
"schema_v30",
54+
"schema_v31",
55+
"schema_v32",
56+
"get_validator_backend",
57+
]
1258

1359
get_schema_content_v2 = partial(get_schema_content, "2.0")
1460
get_schema_content_v30 = partial(get_schema_content, "3.0")
@@ -23,10 +69,53 @@
2369
# alias to the latest v3 version
2470
schema_v3 = schema_v32
2571

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

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

0 commit comments

Comments
 (0)