Wado

WEP: Jade — JSON Schema for Wado

Context

The first consumer of Jade is an HTTP framework in the style of FastAPI. A handler takes and returns typed values, the framework decodes the request body into the handler's argument, and it publishes an OpenAPI document that describes every body. OpenAPI 3.1 describes a body with JSON Schema Draft 2020-12, so the framework needs one schema per Wado type. Every value the server writes has to validate against it, and every document that validates has to decode, or the published API and the served one drift apart.

"JSON Schema" names four separate capabilities, and keeping them apart is the first design step:

Capability Input → output Rust prior art Go prior art
A Schema document model + I/O JSON Schema document ⇄ typed tree schemars::schema invopop/jsonschema Schema
B Type → schema derivation Wado type → schema document schemars invopop/jsonschema (struct-tag reflection)
C Schema → value validation (schema, JSON document) → result the jsonschema crate santhosh-tekuri/jsonschema
D Schema → Wado type codegen .json schema → generated .wado typify go-jsonschema

A framework that starts from typed handlers needs B. The others serve programs that start from a schema someone else wrote.

Wado already has the pieces these ecosystems add after the fact:

What changed since the first version

The first version of this WEP took the options of a Kiln generator as its first consumer. Those options now cross the generator boundary as a typed WIT value, so they need no schema. It also proposed a Constrained trait for a value's permitted range. Nothing enforced that trait at a boundary, and Jade could not implement Deserialize for a type it does not own. Refined types replace it.

Decision

Name

Jade: JSON Assertion and Definition Engine. Assertion is C, definition is A, B and D, and the engine is the runtime and the generator together. It is a short natural noun, as Gale, Kiln, Grog, Marl and Loam are. The package is wado-lang:jade.

One package, four layers

Jade is a library and, for D, a Kiln generator, in one package, as Grog is. Each layer is usable on its own, and no layer depends on one above it:

D  codegen      .json schema → .wado types        (Kiln generator)
C  validation   (Schema, document) → result
B  derivation   JsonSchema: T → Schema             (library code over Reflect*)
A  model        Schema  (written through core:serde to core:json)

Nothing of JSON Schema is in the compiler or the standard library.

Layer A — the schema model

A schema is true, false or an object, so Schema is a variant of Bool(bool) and Object(SchemaObject). SchemaObject is a typed struct with one field per Draft 2020-12 keyword, written through core:serde to core:json. An absent keyword is left out of the output rather than written as null. core:serde has no way to omit a field by its value, so SchemaObject writes itself with a hand-written Serialize. A keyword the draft does not define is kept as written, in extra.

The model is typed rather than a tree of core:value::Value. A Value tree is slow to build and to walk, and the schemas B emits are known keyword by keyword.

Schema::parse reads a schema from JSON text. A keyword whose value breaks the draft's rule for it is an error at its JSON Pointer.

The document model

Jade reads two kinds of JSON without decoding them into a Wado type: a schema's text, and an instance C validates. Both are read into a Document. A Document holds its values in flat arrays in document order, one array per field, so reading one allocates a few arrays rather than one object per value. A Node is a value inside it. Its equality is JSON Schema's: 1 equals 1.0, and an object's members compare whatever their order. The keywords that hold any JSON value (default, enum, const and examples) hold a Document.

A Document is read through core:json's lexer, so it settles what RFC 8259 leaves open as core:json does. A repeated key and a lone surrogate are errors.

Layer B — deriving a schema from a type

pub trait JsonSchema with () {
    fn json_schema(gen: &mut SchemaGenerator) -> Schema;
}

impl SchemaGenerator {
    pub fn new() -> SchemaGenerator;       // definitions under `#/$defs/`
    pub fn openapi() -> SchemaGenerator;   // under `#/components/schemas/`
    pub fn define(&mut self, name: String, build: fn(&mut SchemaGenerator) -> Schema) -> Schema;
}

pub fn schema_for<T: JsonSchema>() -> Schema;   // a standalone document

The trait has no receiver, so a schema is built from the type alone. SchemaGenerator collects the definitions a schema refers to and decides where they live. define emits a named composite once as a definition and answers a $ref to it at each use. It records the name before building, which is also how a recursive type such as struct Node { next: Option<Node> } ends. A composite whose name is empty, such as an anonymous struct, is built inline. The name is Reflect::decl_name(), so the trait needs no schema_name of its own.

One blanket per kind

Jade derives JsonSchema with one blanket impl per reflection kind, as core:serde derives Serialize:

impl<T: ReflectStruct<FieldTypes = [..F], FieldInputs = [..F]>, ..F: JsonSchema> JsonSchema for T { … }
impl<V: ReflectVariant<CasePayloads = [..P]>, ..P: JsonSchema> JsonSchema for V { … }
impl<E: ReflectEnum<Members = [..M]>, ..M> JsonSchema for E { … }
impl<L: ReflectFlags<Members = [..M]>, ..M> JsonSchema for L { … }
impl<R: ReflectRefined<Base = B, …>, B: JsonSchema, …> JsonSchema for R { … }

The struct blanket pins FieldInputs, as serde's do, so a closed struct (one with a field narrower than the struct) derives no schema, just as it derives no Serialize. Its author writes both (Reflect Derivation).

A newtype inherits its base's impl, as it inherits every trait. The leaves are Jade's own impls: the primitives, String, the byte types, Option, List, TreeSet, HashSet, TreeMap, HashMap, Result and the tuples. So are the standard library types whose Serialize is hand-written: core:temporal's types, core:uri's Uri, core:url's Url and core:uuid's Uuid. Each is a string.

A leaf takes a format only when every text its type writes meets that format, read strictly, and Jade writes no format name the specification does not define. So Uri takes uri-reference and Uuid takes uuid, while the core:temporal types take none: an Instant or a PlainDate may carry an expanded year that RFC 3339 rejects, a Duration such as P1Y2D or PT0.5S falls outside RFC 3339 Appendix A's grammar, and the other types write a time without an offset or with a time zone annotation. research-format.md records what the specifications and implementations say.

Each of these leaves also names its Wado type in x-wado-format, in Symbol Notation: {"type": "string", "x-wado-format": "core:temporal#Instant"}. JSON Schema reserves the x- prefix for annotations, which other tools ignore and which must not affect evaluation. So C never asserts it, and D reads it before format to choose the type it generates.

Total Reflection's match type would fold the blankets into one body. The blankets are what exists today.

The schema follows the wire form

Each kind maps to the shape core:json writes (Serialization). The derived Deserialize reads that shape and sometimes more, such as a number spelled as a string. A document that matches the schema decodes, except for the text a leaf asserts nothing about (known gap):

Wado JSON Schema
bool boolean
i8…i32, u8…u32 integer, bounded by the type's range
i64, u64 integer in the type's range and within ±(2^53 − 1), or a decimal string in the type's range
i128, u128 a decimal string in the type's range
the float types number
char string of one code point
String string
ByteList, ByteArray, ByteSlice string with contentEncoding: "base64url", unpadded
the core:temporal types string with x-wado-format
Uri string with format: "uri-reference" and x-wado-format
Uuid string with format: "uuid" and x-wado-format
Url string with x-wado-format
() null
Option<T> anyOf of T's schema and null
List<T> array of T
TreeSet<T>, HashSet<T> array of T with uniqueItems
TreeMap<String, V>, HashMap<String, V> object whose additionalProperties is V's schema
a tuple array with prefixItems, and minItems and maxItems both its arity
struct object: properties under the wire names, required, each field's default
enum string with enum of the wire names
flags array of the member wire names, with uniqueItems
variant oneOf: a unit case as a const string, a payload case as an object of that one property
variant with #[wire(tag)] oneOf of objects whose tag property is the case's const wire name
newtype its base's schema
refined type its base's schema, with the keywords its clauses carry

A decimal string's range is a pattern anchored by ^ and $, since a regular expression states any integer range exactly and JSON Schema does not anchor one itself. The pattern uses plain groups and [0-9] alone, the subset every engine reads alike. An Option takes anyOf rather than oneOf, because in Option<Option<T>> both branches accept null.

A tuple bounds its length on both sides: items: false alone admits a shorter array, which the decoder rejects. A payload case's object takes maxProperties: 1, since the decoder rejects a second key there too.

A field is required when it declares no default. A field with a default takes the default keyword, its default value written as core:json writes it, or none where JSON cannot hold the value, such as NaN. A bare Option<T> field is required and may be null; an Option<T> = null field is optional.

A derived Deserialize skips a key that names no field. The derived schema therefore leaves additionalProperties unset rather than false, so a client may send a field that a newer server reads and this one ignores.

Refined types become assertion keywords

A refined type's value clauses carry its keywords. Jade reads them through ReflectRefined and its own Keywords trait, which it implements for the standard library's clause types: a range becomes minimum and maximum, or exclusiveMaximum for an exclusive one. Length { min, max } becomes minLength and maxLength only if it counts code points, as those keywords do; what it counts is a known gap of Refined Types. A clause type that implements Keywords in its own package reaches the schema the same way.

type UserName = String contract Length { min: 1, max: 64 };
type Age = i32 contract 0..=150;

#[wire(name_policy = "camelCase")]
struct CreateUser {
    /// The user's login name.
    user_name: UserName,       // {"type": "string", "minLength": 1, "maxLength": 64}
    age: Age = Age::from(0),   // {"type": "integer", "minimum": 0, "maximum": 150,
                               //  "default": 0}; not required
}

What B still waits for

None of them blocks the rest of B.

Use from a framework

A handler's signature is not reflectable, but its function type is enough. A route registration bounds the handler's argument and result, and inference settles both from the handler:

fn post<Req: JsonSchema + Deserialize, Res: JsonSchema + Serialize, effect E>(
    &mut self, path: String, handler: fn(Req) -> Res with E,
) { … }

app.post("/users", create_user);   // Req = CreateUser, Res = User

The framework decodes a request body with the derived Deserialize, which enforces every refined field through try_from. A failed clause is a DeserializeError with the path to the field, which the framework answers with a client error. It never traps.

Layer C — validating a document

C checks a JSON document against a schema it did not derive, such as a third party's. Its commitments stand from the first version:

let validator = Validator::compile(&Schema::parse(text)?)?;   // SchemaError
validator.validate(&doc.root())                               // Result<(), List<ValidationError>>

compile lays the subschemas out in one table, indexed by their $id, their anchors and their JSON Pointer under each resource that holds them, and points every $ref at an index. A schema without an $id takes an internal base URI, which resolves relative references as any other base does. validate reports every keyword the instance fails, but under anyOf, oneOf, not and if only the keyword itself, since a failing branch is not an error.

A $ref or $dynamicRef that comes back to a subschema at the value it left, without stepping into the instance, would recurse forever. The specification leaves such a schema undefined, and validate reports the reference that closes the cycle as failing.

multipleOf divides the shortest decimals that read back as the two numbers, so 0.3 is a multiple of 0.1, as written, though not in binary floating point.

pattern and patternProperties use lib:re, which reads ECMA-262 patterns in Unicode mode and rejects what it cannot match in linear time, such as a backreference or a lookbehind.

Layer D — generating Wado types from a schema

D is a Kiln generator, and its output imports Jade as its runtime, as Grog's does. The consumer names Jade twice, under [build-dependencies] and [dependencies], for the reason Grog gives.

use { CreateUser } from "./create-user.schema.json" with {
    generator: { module: "lib:jade" },
};

An object becomes a struct, a string enum an enum, a oneOf of tagged objects a variant, $defs sibling declarations, and $ref a reference to one. A schema carrying assertion keywords becomes a refined type with the matching clauses, so B applied to D's output gives back the keywords D read. A string with an x-wado-format D can resolve becomes the type it names, which takes precedence over format.

No attribute of Jade's own

A package cannot own a compiler-recognized attribute, and Jade needs none. The wire names come from #[wire(…)], which the decoder reads too. A permitted range comes from a refined type. A description comes from a doc comment.

Roadmap

Known gaps

A hand-written Serialize the schema does not see

A type whose Serialize or Deserialize is hand-written, and whose members are visible, takes the structural blanket. Its schema then describes its fields, not its wire form.

A clause Jade cannot read

A condition clause carries nothing to read, and a clause type with no Keywords impl carries nothing Jade knows. Either way the ReflectRefined blanket does not apply, and the refined type meets JsonSchema through its base's impl, as Refined Types lets it. The schema then accepts values the decoder rejects, and nothing reports it.

One error per request

DeserializeError reports the first failure. A framework that answers with every failure in the body, as FastAPI does, has nothing that collects them.

A text type's schema admits what the type cannot read

A leaf whose type is text, such as Instant or Url, asserts only string, with a standard format only where one fits strictly. x-wado-format names the type but asserts nothing. A document whose string the type cannot read, such as "yesterday" for an Instant, matches the schema but does not decode. Bytes are the same: contentEncoding: "base64url" is an annotation, so "!" matches a ByteList's schema.

A map whose key is not a string

TreeMap<i32, V> is written as an object whose keys spell integers. JSON Schema states that through propertyNames, and the mapping table does not cover it yet.

Other drafts and output formats

A Draft 7 or OpenAPI 3.0 schema, with nullable and definitions, has no reader. C's errors are a flat list rather than the specification's standard output units.