Skip to content

Commit

Permalink
refactor: Rework public API
Browse files Browse the repository at this point in the history
Signed-off-by: Dmitry Dygalo <[email protected]>
  • Loading branch information
Stranger6667 committed Sep 18, 2024
1 parent 3e83197 commit 74354df
Show file tree
Hide file tree
Showing 59 changed files with 586 additions and 543 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ jobs:
strategy:
fail-fast: false
matrix:
target: ["compile", "validation"]
target: ["builder", "validation"]
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/daily.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ jobs:
strategy:
fail-fast: false
matrix:
target: ["compile", "validation"]
target: ["builder", "validation"]
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
Expand Down
20 changes: 20 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,30 @@

## [Unreleased]

### Added
- New draft-specific modules for easier version-targeted validation:
- `jsonschema::draft4`
- `jsonschema::draft6`
- `jsonschema::draft7`
- `jsonschema::draft201909`
- `jsonschema::draft202012`
Each module provides `new()`, `is_valid()`, and `options()` functions.
- `jsonschema::options()` function as a shortcut for `jsonschema::Validator::options()`, that allows for customization of the validation process.

### Changed

- Make `Debug` implementation for `SchemaNode` opaque.

### Deprecated

- Rename `CompilationOptions` to `ValidationOptions` for clarity.
- Rename `JSONSchema` to `Validator` for clarity. [#424](https://github.com/Stranger6667/jsonschema-rs/issues/424)
- Rename `JSONPointer` to `JsonPointer` for consistency with naming conventions. [#424](https://github.com/Stranger6667/jsonschema-rs/issues/424)
- Rename `jsonschema::compile` to `jsonschema::validator_for`.
- Rename `CompilationOptions::compile` to `ValidationOptions::build`.

Old names are retained for backward compatibility but will be removed in a future release.

## [0.19.1] - 2024-09-15

### Fixed
Expand Down
10 changes: 5 additions & 5 deletions crates/benchmark-suite/benches/boon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@ use boon::{Compiler, Schemas};
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
use serde_json::Value;

fn bench_compile(c: &mut Criterion, name: &str, schema: &Value) {
fn bench_build(c: &mut Criterion, name: &str, schema: &Value) {
let mut compiler = Compiler::new();
compiler
.add_resource("schema.json", schema.clone())
.expect("Failed to add resource");
c.bench_function(&format!("boon/{}/compile", name), |b| {
c.bench_function(&format!("boon/{}/build", name), |b| {
b.iter(|| {
compiler
.compile("schema.json", &mut Schemas::new())
.expect("Failed to compile");
.expect("Failed to build");
})
});
}
Expand All @@ -25,7 +25,7 @@ fn bench_validate(c: &mut Criterion, name: &str, schema: &Value, instance: &Valu
.expect("Failed to add resource");
let id = compiler
.compile("schema.json", &mut schemas)
.expect("Failed to compile");
.expect("Failed to build");

c.bench_with_input(
BenchmarkId::new(name, "validate"),
Expand All @@ -37,7 +37,7 @@ fn bench_validate(c: &mut Criterion, name: &str, schema: &Value, instance: &Valu
fn run_benchmarks(c: &mut Criterion) {
for benchmark in Benchmark::iter() {
benchmark.run(&mut |name, schema, instances| {
bench_compile(c, name, schema);
bench_build(c, name, schema);
for instance in instances {
let name = format!("boon/{}/{}", name, instance.name);
bench_validate(c, &name, schema, &instance.data);
Expand Down
6 changes: 3 additions & 3 deletions crates/benchmark-suite/benches/jsonschema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ use benchmark::Benchmark;
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
use serde_json::Value;

fn bench_compile(c: &mut Criterion, name: &str, schema: &Value) {
c.bench_function(&format!("jsonschema/{}/compile", name), |b| {
fn bench_build(c: &mut Criterion, name: &str, schema: &Value) {
c.bench_function(&format!("jsonschema/{}/build", name), |b| {
b.iter(|| jsonschema::validator_for(schema).expect("Valid schema"))
});
}
Expand Down Expand Up @@ -37,7 +37,7 @@ fn bench_validate(c: &mut Criterion, name: &str, schema: &Value, instance: &Valu
fn run_benchmarks(c: &mut Criterion) {
for benchmark in Benchmark::iter() {
benchmark.run(&mut |name, schema, instances| {
bench_compile(c, name, schema);
bench_build(c, name, schema);
for instance in instances {
let name = format!("jsonschema/{}/{}", name, instance.name);
bench_is_valid(c, &name, schema, &instance.data);
Expand Down
6 changes: 3 additions & 3 deletions crates/benchmark-suite/benches/jsonschema_valid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
use jsonschema_valid::{schemas, Config};
use serde_json::Value;

fn bench_compile(c: &mut Criterion, name: &str, schema: &Value) {
c.bench_function(&format!("jsonschema_valid/{}/compile", name), |b| {
fn bench_build(c: &mut Criterion, name: &str, schema: &Value) {
c.bench_function(&format!("jsonschema_valid/{}/build", name), |b| {
b.iter(|| Config::from_schema(schema, Some(schemas::Draft::Draft7)).expect("Valid schema"))
});
}
Expand All @@ -28,7 +28,7 @@ fn run_benchmarks(c: &mut Criterion) {
for benchmark in Benchmark::iter() {
benchmark.run(&mut |name, schema, instances| {
if !UNSUPPORTED_BENCHMARKS.contains(&name) {
bench_compile(c, name, schema);
bench_build(c, name, schema);
for instance in instances {
let name = format!("jsonschema_valid/{}/{}", name, instance.name);
bench_validate(c, &name, schema, &instance.data);
Expand Down
6 changes: 3 additions & 3 deletions crates/benchmark-suite/benches/valico.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
use serde_json::Value;
use valico::json_schema;

fn bench_compile(c: &mut Criterion, name: &str, schema: &Value) {
c.bench_function(&format!("valico/{}/compile", name), |b| {
fn bench_build(c: &mut Criterion, name: &str, schema: &Value) {
c.bench_function(&format!("valico/{}/build", name), |b| {
b.iter(|| {
let mut scope = json_schema::Scope::new();
scope
Expand Down Expand Up @@ -36,7 +36,7 @@ fn run_benchmarks(c: &mut Criterion) {
for benchmark in Benchmark::iter() {
benchmark.run(&mut |name, schema, instances| {
if !UNSUPPORTED_BENCHMARKS.contains(&name) {
bench_compile(c, name, schema);
bench_build(c, name, schema);
for instance in instances {
let name = format!("valico/{}/{}", name, instance.name);
bench_validate(c, &name, schema, &instance.data);
Expand Down
36 changes: 18 additions & 18 deletions crates/jsonschema-py/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::{
panic::{self, AssertUnwindSafe},
};

use jsonschema::{paths::JSONPointer, Draft};
use jsonschema::{paths::JsonPointer, Draft};
use pyo3::{
exceptions::{self, PyValueError},
ffi::PyUnicode_AsUTF8AndSize,
Expand Down Expand Up @@ -90,7 +90,7 @@ fn into_py_err(py: Python<'_>, error: jsonschema::ValidationError<'_>) -> PyResu
))
}

fn into_path(py: Python<'_>, pointer: JSONPointer) -> PyResult<Py<PyList>> {
fn into_path(py: Python<'_>, pointer: JsonPointer) -> PyResult<Py<PyList>> {
let path = PyList::empty_bound(py);
for chunk in pointer {
match chunk {
Expand Down Expand Up @@ -125,7 +125,7 @@ thread_local! {
fn make_options(
draft: Option<u8>,
formats: Option<&Bound<'_, PyDict>>,
) -> PyResult<jsonschema::CompilationOptions> {
) -> PyResult<jsonschema::ValidationOptions> {
let mut options = jsonschema::options();
if let Some(raw_draft_version) = draft {
options.with_draft(get_draft(raw_draft_version)?);
Expand Down Expand Up @@ -166,7 +166,7 @@ fn make_options(

fn iter_on_error(
py: Python<'_>,
validator: &jsonschema::JSONSchema,
validator: &jsonschema::Validator,
instance: &Bound<'_, PyAny>,
) -> PyResult<ValidationErrorIter> {
let instance = ser::to_value(instance)?;
Expand All @@ -188,7 +188,7 @@ fn iter_on_error(

fn raise_on_error(
py: Python<'_>,
validator: &jsonschema::JSONSchema,
validator: &jsonschema::Validator,
instance: &Bound<'_, PyAny>,
) -> PyResult<()> {
let instance = ser::to_value(instance)?;
Expand Down Expand Up @@ -276,7 +276,7 @@ fn is_valid(
) -> PyResult<bool> {
let options = make_options(draft, formats)?;
let schema = ser::to_value(schema)?;
match options.compile(&schema) {
match options.build(&schema) {
Ok(validator) => {
let instance = ser::to_value(instance)?;
panic::catch_unwind(AssertUnwindSafe(|| Ok(validator.is_valid(&instance))))
Expand Down Expand Up @@ -310,7 +310,7 @@ fn validate(
) -> PyResult<()> {
let options = make_options(draft, formats)?;
let schema = ser::to_value(schema)?;
match options.compile(&schema) {
match options.build(&schema) {
Ok(validator) => raise_on_error(py, &validator, instance),
Err(error) => Err(into_py_err(py, error)?),
}
Expand Down Expand Up @@ -339,7 +339,7 @@ fn iter_errors(
) -> PyResult<ValidationErrorIter> {
let options = make_options(draft, formats)?;
let schema = ser::to_value(schema)?;
match options.compile(&schema) {
match options.build(&schema) {
Ok(validator) => iter_on_error(py, &validator, instance),
Err(error) => Err(into_py_err(py, error)?),
}
Expand All @@ -356,7 +356,7 @@ fn iter_errors(
/// By default Draft 7 will be used for compilation.
#[pyclass(module = "jsonschema_rs")]
struct JSONSchema {
schema: jsonschema::JSONSchema,
validator: jsonschema::Validator,
repr: String,
}

Expand Down Expand Up @@ -397,9 +397,9 @@ impl JSONSchema {
) -> PyResult<Self> {
let options = make_options(draft, formats)?;
let raw_schema = ser::to_value(schema)?;
match options.compile(&raw_schema) {
Ok(schema) => Ok(JSONSchema {
schema,
match options.build(&raw_schema) {
Ok(validator) => Ok(JSONSchema {
validator,
repr: get_schema_repr(&raw_schema),
}),
Err(error) => Err(into_py_err(py, error)?),
Expand Down Expand Up @@ -439,9 +439,9 @@ impl JSONSchema {
let raw_schema = serde_json::from_slice(slice)
.map_err(|error| PyValueError::new_err(format!("Invalid string: {}", error)))?;
let options = make_options(draft, formats)?;
match options.compile(&raw_schema) {
Ok(schema) => Ok(JSONSchema {
schema,
match options.build(&raw_schema) {
Ok(validator) => Ok(JSONSchema {
validator,
repr: get_schema_repr(&raw_schema),
}),
Err(error) => Err(into_py_err(py, error)?),
Expand All @@ -461,7 +461,7 @@ impl JSONSchema {
#[pyo3(text_signature = "(instance)")]
fn is_valid(&self, instance: &Bound<'_, PyAny>) -> PyResult<bool> {
let instance = ser::to_value(instance)?;
panic::catch_unwind(AssertUnwindSafe(|| Ok(self.schema.is_valid(&instance))))
panic::catch_unwind(AssertUnwindSafe(|| Ok(self.validator.is_valid(&instance))))
.map_err(handle_format_checked_panic)?
}

Expand All @@ -477,7 +477,7 @@ impl JSONSchema {
/// If the input instance is invalid, only the first occurred error is raised.
#[pyo3(text_signature = "(instance)")]
fn validate(&self, py: Python<'_>, instance: &Bound<'_, PyAny>) -> PyResult<()> {
raise_on_error(py, &self.schema, instance)
raise_on_error(py, &self.validator, instance)
}

/// iter_errors(instance)
Expand All @@ -494,7 +494,7 @@ impl JSONSchema {
py: Python<'_>,
instance: &Bound<'_, PyAny>,
) -> PyResult<ValidationErrorIter> {
iter_on_error(py, &self.schema, instance)
iter_on_error(py, &self.validator, instance)
}
fn __repr__(&self) -> String {
format!("<JSONSchema: {}>", self.repr)
Expand Down
6 changes: 3 additions & 3 deletions crates/jsonschema/benches/jsonschema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ use benchmark::Benchmark;
use codspeed_criterion_compat::{criterion_group, criterion_main, BenchmarkId, Criterion};
use serde_json::Value;

fn bench_compile(c: &mut Criterion, name: &str, schema: &Value) {
c.bench_function(&format!("{}/compile", name), |b| {
fn bench_build(c: &mut Criterion, name: &str, schema: &Value) {
c.bench_function(&format!("{}/build", name), |b| {
b.iter(|| jsonschema::validator_for(schema).expect("Valid schema"))
});
}
Expand Down Expand Up @@ -37,7 +37,7 @@ fn bench_validate(c: &mut Criterion, name: &str, schema: &Value, instance: &Valu
fn run_benchmarks(c: &mut Criterion) {
for benchmark in Benchmark::iter() {
benchmark.run(&mut |name, schema, instances| {
bench_compile(c, name, schema);
bench_build(c, name, schema);
for instance in instances {
let name = format!("{}/{}", name, instance.name);
bench_is_valid(c, &name, schema, &instance.data);
Expand Down
6 changes: 3 additions & 3 deletions crates/jsonschema/benches/keywords.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ use benchmark::run_keyword_benchmarks;
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
use serde_json::Value;

fn bench_keyword_compile(c: &mut Criterion, name: &str, schema: &Value) {
c.bench_function(&format!("keyword/{}/compile", name), |b| {
fn bench_keyword_build(c: &mut Criterion, name: &str, schema: &Value) {
c.bench_function(&format!("keyword/{}/build", name), |b| {
b.iter(|| jsonschema::validator_for(schema).expect("Valid schema"))
});
}
Expand Down Expand Up @@ -36,7 +36,7 @@ fn bench_keyword_validate(c: &mut Criterion, name: &str, schema: &Value, instanc

fn run_benchmarks(c: &mut Criterion) {
run_keyword_benchmarks(&mut |name, schema, instances| {
bench_keyword_compile(c, name, schema);
bench_keyword_build(c, name, schema);
for instance in instances {
let name = format!("jsonschema/{}/{}", name, instance.name);
bench_keyword_is_valid(c, &name, schema, &instance.data);
Expand Down
12 changes: 6 additions & 6 deletions crates/jsonschema/src/compilation/context.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use super::options::CompilationOptions;
use super::options::ValidationOptions;
use crate::{
compilation::DEFAULT_SCOPE,
paths::{JSONPointer, JsonPointerNode, PathChunkRef},
paths::{JsonPointer, JsonPointerNode, PathChunkRef},
resolver::Resolver,
schemas, Draft,
};
Expand All @@ -15,7 +15,7 @@ static DEFAULT_SCHEME: &str = "json-schema";
#[derive(Debug, Clone)]
pub(crate) struct CompilationContext<'a> {
base_uri: BaseUri<'a>,
pub(crate) config: Arc<CompilationOptions>,
pub(crate) config: Arc<ValidationOptions>,
pub(crate) resolver: Arc<Resolver>,
pub(crate) schema_path: JsonPointerNode<'a, 'a>,
}
Expand Down Expand Up @@ -77,7 +77,7 @@ impl<'a> From<&'a BaseUri<'a>> for Cow<'a, Url> {
impl<'a> CompilationContext<'a> {
pub(crate) const fn new(
scope: BaseUri<'a>,
config: Arc<CompilationOptions>,
config: Arc<ValidationOptions>,
resolver: Arc<Resolver>,
) -> Self {
CompilationContext {
Expand Down Expand Up @@ -144,13 +144,13 @@ impl<'a> CompilationContext<'a> {

/// Create a JSON Pointer from the current `schema_path` & a new chunk.
#[inline]
pub(crate) fn into_pointer(self) -> JSONPointer {
pub(crate) fn into_pointer(self) -> JsonPointer {
self.schema_path.into()
}

/// Create a JSON Pointer from the current `schema_path` & a new chunk.
#[inline]
pub(crate) fn as_pointer_with(&'a self, chunk: impl Into<PathChunkRef<'a>>) -> JSONPointer {
pub(crate) fn as_pointer_with(&'a self, chunk: impl Into<PathChunkRef<'a>>) -> JsonPointer {
self.schema_path.push(chunk).into()
}

Expand Down
Loading

0 comments on commit 74354df

Please sign in to comment.