Skip to main content

Crate ash_jsonschema

Crate ash_jsonschema 

Source
Expand description

§ash-jsonschema

Chain the keywords, call .build(), get a schema.

A typed builder for JSON Schema 2020-12. One dialect, deliberately: the latest standard is the only thing this crate emits, so there is no draft selector to thread through the API and no keyword that means one thing here and another there.

use ash_jsonschema::{Format, Schema, SchemaError};

let schema = Schema::object()
    .dialect()
    .id("https://example.com/schemas/user")
    .title("User")
    .required_property("id", Schema::string().format(Format::Uuid))
    .required_property("email", Schema::string().format(Format::Email))
    .property("age", Schema::integer().minimum(0).nullable())
    .property("tags", Schema::array().items(Schema::string()).unique_items(true))
    .additional_properties(false)
    .build()?;

println!("{}", schema.to_json_pretty());

§The shape of the API

Schema is both the output type and the entry point. Each constructor returns a builder that has already committed the type keyword:

The type is not decoration. The keywords of the core, metadata, and applicator vocabularies are available on every builder, but a type-specific assertion is only reachable from the builder it applies to — .min_length() exists on a string schema and nowhere else, so a keyword that a validator would silently ignore does not compile in the first place.

§Nesting

Only the outermost chain needs .build(). Every keyword that takes a subschema accepts impl Into<Schema>, which a builder satisfies directly — and so does a bare bool, since true and false are themselves schemas:

let schema = Schema::object()
    .property("nested", Schema::object().additional_properties(false))
    .property("anything", true)
    .build()
    .unwrap();

§.build() checks its work

The 2020-12 meta-schema — all eight of its documents — is vendored into the crate and parsed once into memory on first use. Nothing is fetched at runtime. build runs the document you just assembled against it and returns a SchemaError rather than a Schema if it does not hold up.

The check is a depth-first walk, so the root and every subschema beneath it are validated in turn, each in its own right — a nested builder needs no .build() of its own and is checked all the same. A Violation names the JSON Pointer of the offending subschema and the meta-schema rule it broke:

let error = Schema::object()
    .property("inner", Schema::string().anchor("not a valid anchor"))
    .build()
    .unwrap_err();

assert_eq!(error.first().location, "/properties/inner/$anchor");
assert_eq!(error.first().rule, "meta/core#/$defs/anchorString/pattern");

build_unchecked skips the check, and Schema::validate runs it on demand.

§Reading a schema back in

Schema::parse reads a document that already exists, and Schema::parse_checked reads and validates in one step. Keywords outside the dialect are kept in SchemaObject::extensions rather than dropped, so a document parsed and rendered back out is unchanged; keyword writes one from the builder side.

let schema = Schema::parse(r#"{"type":"object","properties":{"id":{"type":"string"}}}"#)
    .unwrap();

assert!(schema.property("id").is_some());
assert_eq!(schema.pointer("/properties/id/type"), Some(serde_json::json!("string")));

Schema::into_builder picks such a schema back up and resumes the chain on it; Schema::into_typed does the same under a type marker, reopening that type’s vocabulary.

§Rendering

Schema is serde::Serialize, so it drops into any serializer. to_json, to_json_pretty, and to_value are the shorthands. Output is deterministic: keywords render in the specification’s own grouping order, and properties, $defs, and the other named-subschema maps render in the order the builder calls declared them.

§$ref resolves against a Registry

Following a reference needs a base URI to resolve against and somewhere to look the result up. A Registry is that somewhere: schemas go in under the $id they declare, and references resolve across documents, not only within one.

let address = Schema::object()
    .id("https://example.com/schemas/address")
    .required_property("city", Schema::string())
    .build()?;

let user = Schema::object()
    .id("https://example.com/schemas/user")
    .required_property("address", Schema::reference("address"))
    .build()?;

let mut registry = Registry::new();
registry.insert(&address)?;
registry.insert(&user)?;

registry.check_references()?;

Nothing is fetched: a registry resolves against what it was given, so a reference to a document nobody inserted dangles rather than reaching the network.

§A schema is a source, not just an output

diff() compares two versions and says what the change breaks — separately for whoever writes the data and whoever reads it, since a change lands on those two in opposite directions:

let v1 = Schema::object().required_property("id", Schema::string()).build()?;
let v2 = Schema::object()
    .required_property("id", Schema::string())
    .required_property("email", Schema::string())
    .build()?;

let report = diff(&v1, &v2);
assert!(report.is_breaking_for(Role::Writer));
assert!(!report.is_breaking_for(Role::Reader));

bundle() collapses a set of schemas into one self-contained document, embedding each referenced document under $defs with its $id intact so the references that named it still resolve.

§Macros

object! writes properties and required from one list — the duplication object schemas otherwise force — and yields an ordinary builder:

let user = object! {
    required "id": Schema::string().format("uuid"),
    "age": Schema::integer().minimum(0),
}
.closed()
.build()?;

assert!(user.requires("id"));

defs! takes a block of definitions; one_of_tagged! writes the tagged union the dialect has no keyword for. They exist for shapes that repeat structure, not to shorten single keywords.

§Getting a copy out

Schema::export returns a detached copy, and Schema::export_at lifts a subschema out as a Schema rather than a bare serde_json::Value. Both are on FrozenSchema too, and export is on every builder — where it takes a copy without ending the chain.

§Validating instances

Behind the validation feature, on by default: the validator module answers the other question — does this JSON satisfy the schema?

let validator = Validator::new(&object! {
    required "id": Schema::string().min_length(1),
}.build()?)?;

assert!(validator.is_valid(&serde_json::json!({"id": "a1"})));

let outcome = validator.validate(&serde_json::json!({}), Mode::All);
assert_eq!(outcome.first().unwrap().message(), "`id` is required");

A validator’s schema is fixed for its life. Mode::All reports every error and Mode::FailFast stops at the first; both give an Outcome whose errors name where in the instance the problem is and which schema keyword rejected it.

§Output the specification defines

An Outcome is the specification’s output tree, not a shape of this crate’s invention. Outcome::output renders it as any of the four formats 2020-12 describes — Flag, Basic, Detailed, Verbose — and the result validates against https://json-schema.org/draft/2020-12/output/schema, so it can be read by tooling that knows the standard rather than this crate.

Nesting is what makes a branching schema debuggable: a failed anyOf says only “no alternative matched”, so the evaluator keeps why each alternative was rejected beneath it. Outcome::errors is the flat view of the same run, and Outcome::unit is the tree.

Validator::annotate collects what the annotation keywords — title, description, default, readOnly — attached to each location. Validator::validate does not, since the usual question is whether an instance is valid and it should not pay for an answer it will not read.

Coverage is every assertion and applicator of the dialect, including unevaluated* and $dynamicRef.

format is an annotation by default, as 2020-12 specifies. Asking for it — Validator::builder(&schema).assert_formats() — turns on checks for the temporal, address, and pointer formats, and .format(name, check) registers a rule of your own under any name. validator::tld answers whether a hostname’s suffix is shaped like a TLD, or (behind iana-tlds) is one that exists.

Turn the feature off — default-features = false — for a build that only writes and reads schemas. No dependency goes with it: regex-lite is needed either way, since the meta-schema check .build() runs asserts patterns of its own. What goes is the evaluator, about a fifth of the crate.

§What this crate does not do

It builds, reads, and checks against schemas. What it does not do is fetch — no $ref is retrieved over the network. The meta-schema check .build() runs constrains a schema’s shape — that $anchor is a plain name, that required holds unique strings, that minLength is not negative — and says nothing about whether the schema makes sense. A minLength above its maxLength, or a then without an if, is a legal 2020-12 document and builds without complaint.

References are followed only when asked: .build() does not resolve them, and a Registry does.

Re-exports§

pub use builder::AnyBuilder;
pub use builder::ArrayBuilder;
pub use builder::Builder;
pub use builder::NumericBuilder;
pub use builder::ObjectBuilder;
pub use builder::StringBuilder;
pub use builder::kind;
pub use bundle::BundleError;
pub use bundle::bundle;
pub use diff::Change;
pub use diff::ChangeKind;
pub use diff::Effect;
pub use diff::Report;
pub use diff::Role;
pub use diff::diff;
pub use diff::diff_resolved;
pub use error::ErrorKind;
pub use error::ParseError;
pub use error::SchemaError;
pub use error::Violation;
pub use format::Format;
pub use frozen::FrozenSchema;
pub use map::OrderedMap;
pub use meta::MetaSchema;
pub use registry::Reference;
pub use registry::Registry;
pub use registry::RegistryError;
pub use schema::DIALECT;
pub use schema::DIALECT_KEYWORDS;
pub use schema::Num;
pub use schema::Schema;
pub use schema::SchemaObject;
pub use schema::SchemaType;
pub use schema::TypeSet;
pub use schema::UnknownSchemaType;
pub use schema::is_dialect_keyword;
pub use validator::CompileError;
pub use validator::Mode;
pub use validator::Outcome;
pub use validator::OutputFormat;
pub use validator::Unit;
pub use validator::ValidationError;
pub use validator::Validator;

Modules§

builder
The builders.
bundle
Collapsing a set of schemas into one self-contained document.
diff
Comparing two versions of a schema, and saying what the change would break.
error
What meta-schema validation reports when a built schema is not a legal JSON Schema 2020-12 document.
format
The format keyword’s defined attributes.
frozen
A schema that cannot be modified after it is built.
macros
Macros for the shapes that are wordy to write out.
map
An insertion-ordered, string-keyed map.
meta
The JSON Schema 2020-12 meta-schema, embedded in the binary and parsed once.
prelude
The types a typical caller wants in scope.
registry
Resolving $ref — a set of schemas indexed by the URIs they declare.
schema
The schema document itself: Schema, the keyword bag SchemaObject it wraps, and the small value types the keywords are written in.
uri
Resolving one URI reference against another, RFC 3986 §5.
validator
Checking that an instance satisfies a schema.
walk
Where subschemas actually live in a schema document.

Macros§

defs
A set of named subschemas for $defs, applied to a schema.
object
An object schema, written the way its instances look.
one_of_tagged
A oneOf over object schemas discriminated by a constant property — the tagged union JSON Schema has no keyword for.
validator
Builds a Validator from a schema written inline, at the call site.

Functions§

validate_document
Checks an already-parsed JSON document against the embedded JSON Schema 2020-12 meta-schema.