Skip to main content

flow_abi/
schema.rs

1//! A type's JSON Schema, draft 2020-12 (`abi.md`, *Schemas*).
2//!
3//! The schema is generated from the declarations and describes the encoding
4//! above; it adds no rule, and where JSON Schema cannot say what the encoding
5//! says — an integer's exact size, a set's order — the encoding decides.
6//!
7//! # Readings
8//!
9//! - A generic declaration has one `$defs` entry per list of arguments it is
10//!   used with, keyed by its identity with those arguments written after it:
11//!   `std@v1/result.Result<Int, Text>`. Types of one name declared in blocks
12//!   of one module are told apart by the `#n` their module gives them in
13//!   source order, `Point#2` for the second.
14//! - `Option` is written in place, not in `$defs`: inside a record it is its
15//!   payload's schema, and elsewhere a `oneOf` of `"None"` and `{"Some": ...}`.
16//! - A constructor's object form allows no other member, since decoding
17//!   refuses one; a record allows them, since a reply may carry extra fields.
18//! - A positional payload of several values and a tuple are arrays of exactly
19//!   their length; `Unit` is the empty array, and `Never` the schema `false`.
20//! - A host type is a `string`: the token.
21//! - A member's doc comment sits beside what it documents: a field's on its
22//!   property schema, a constructor's on its `oneOf` branch. A field whose
23//!   schema is `false` is written `{"allOf": [false]}` to carry one.
24
25use std::collections::{HashMap, VecDeque};
26use std::fmt::Write as _;
27
28use flow_types::{OptionCtor, Payload};
29
30use crate::catalog::{Catalog, StdForm};
31use crate::error::{EncodeError, EncodeErrorKind, Place};
32use crate::json::Json;
33use flow_types::{Body, DeclId, Type, Versions};
34
35/// The `$schema` this crate writes.
36pub const DIALECT: &str = "https://json-schema.org/draft/2020-12/schema";
37
38/// How many `$defs` entries one schema may have. A type whose
39/// declarations reach more argument lists than this is refused rather than
40/// written.
41const DEFS: usize = 1_000;
42
43/// The schema of `ty`, with each named type in `$defs` and every doc comment
44/// as a `description`.
45///
46/// # Errors
47///
48/// An [`EncodeError`] when `ty` has no schema, such as a function's, or
49/// names more declarations than a schema may define.
50pub fn schema(catalog: &Catalog, ty: &Type) -> Result<Json, EncodeError> {
51    Writer::new(catalog).document(ty)
52}
53
54struct Writer<'c> {
55    catalog: &'c Catalog,
56    keys: HashMap<(DeclId, Vec<Type>), String>,
57    defs: Vec<(String, Json)>,
58    pending: VecDeque<(usize, DeclId, Vec<Type>)>,
59}
60
61impl<'c> Writer<'c> {
62    fn new(catalog: &'c Catalog) -> Self {
63        Writer {
64            catalog,
65            keys: HashMap::new(),
66            defs: Vec::new(),
67            pending: VecDeque::new(),
68        }
69    }
70
71    /// The whole schema of `ty`: its own schema with `$schema` and, when it
72    /// names any declaration, `$defs`.
73    fn document(mut self, ty: &Type) -> Result<Json, EncodeError> {
74        let mut root = self.schema(ty)?;
75        // Each `$defs` entry is written after the one before it, so writing
76        // one that names another only queues it: however deep a chain of
77        // declarations runs, the writer's own stack does not.
78        while let Some((slot, decl, args)) = self.pending.pop_front() {
79            self.defs[slot].1 = self.body(decl, &args)?;
80        }
81        let mut members = vec![("$schema".to_owned(), Json::String(DIALECT.into()))];
82        match root {
83            Json::Object(ref mut own) => members.append(own),
84            // `true` and `false` schemas, which a `$defs` can't be added to.
85            other => members.push(("allOf".into(), Json::Array(vec![other]))),
86        }
87        if !self.defs.is_empty() {
88            members.push(("$defs".into(), Json::Object(self.defs)));
89        }
90        Ok(Json::Object(members))
91    }
92
93    fn schema(&mut self, ty: &Type) -> Result<Json, EncodeError> {
94        enum Visit<'a> {
95            Read(&'a Type),
96            Write { ty: &'a Type, start: usize },
97        }
98
99        let mut pending = vec![Visit::Read(ty)];
100        let mut schemas = Vec::new();
101        while let Some(visit) = pending.pop() {
102            let (ty, start) = match visit {
103                Visit::Read(ty) => {
104                    pending.push(Visit::Write {
105                        ty,
106                        start: schemas.len(),
107                    });
108                    match ty {
109                        Type::List(item) | Type::Set(item) | Type::Option(item) => {
110                            pending.push(Visit::Read(item));
111                        }
112                        Type::Dict(key, item) => {
113                            pending.push(Visit::Read(item));
114                            if *self.catalog.erase(key) != Type::Text {
115                                pending.push(Visit::Read(key));
116                            }
117                        }
118                        Type::Tuple(parts) => {
119                            pending.extend(parts.iter().rev().map(Visit::Read));
120                        }
121                        Type::Int
122                        | Type::Decimal
123                        | Type::Bool
124                        | Type::Text
125                        | Type::Bytes
126                        | Type::Duration
127                        | Type::Instant
128                        | Type::Unit
129                        | Type::Never
130                        | Type::Json
131                        | Type::Named(_, _)
132                        | Type::Param(_)
133                        | Type::Task(_)
134                        | Type::Function { .. }
135                        | Type::NotData => {}
136                    }
137                    continue;
138                }
139                Visit::Write { ty, start } => (ty, start),
140            };
141            let parts = schemas.split_off(start);
142            schemas.push(self.schema_node(ty, parts)?);
143        }
144        Ok(schemas.pop().expect("one root schema"))
145    }
146
147    fn schema_node(&mut self, ty: &Type, parts: Vec<Json>) -> Result<Json, EncodeError> {
148        let object = |members: Vec<(&str, Json)>| {
149            Json::Object(
150                members
151                    .into_iter()
152                    .map(|(key, value)| (key.to_owned(), value))
153                    .collect(),
154            )
155        };
156        let string = |text: &str| Json::String(text.to_owned());
157        let typed = |name: &str| object(vec![("type", string(name))]);
158        let mut parts = parts.into_iter();
159        let schema = match ty {
160            Type::Int => typed("integer"),
161            Type::Decimal => typed("number"),
162            Type::Bool => typed("boolean"),
163            Type::Text => typed("string"),
164            Type::Bytes => object(vec![
165                ("type", string("string")),
166                ("contentEncoding", string("base64")),
167            ]),
168            Type::Duration => object(vec![
169                ("type", string("string")),
170                ("format", string("duration")),
171            ]),
172            Type::Instant => object(vec![
173                ("type", string("string")),
174                ("format", string("date-time")),
175            ]),
176            Type::Unit => array(Vec::new()),
177            Type::Never => Json::Bool(false),
178            Type::Json => Json::Object(Vec::new()),
179            Type::List(_) => object(vec![
180                ("type", string("array")),
181                ("items", parts.next().expect("a list item schema")),
182            ]),
183            Type::Set(_) => object(vec![
184                ("type", string("array")),
185                ("items", parts.next().expect("a set item schema")),
186                ("uniqueItems", Json::Bool(true)),
187            ]),
188            Type::Dict(key, _) if *self.catalog.erase(key) == Type::Text => object(vec![
189                ("type", string("object")),
190                (
191                    "additionalProperties",
192                    parts.next().expect("a dictionary item schema"),
193                ),
194            ]),
195            Type::Dict(_, _) => object(vec![
196                ("type", string("array")),
197                ("items", array(parts.collect())),
198            ]),
199            Type::Option(_) => object(vec![(
200                "oneOf",
201                Json::Array(vec![
202                    constant(OptionCtor::None.name()),
203                    single(
204                        OptionCtor::Some.name(),
205                        parts.next().expect("an option item schema"),
206                    ),
207                ]),
208            )]),
209            Type::Tuple(_) => array(parts.collect()),
210            Type::Named(decl, args) => {
211                object(vec![("$ref", string(&self.reference(*decl, args)?))])
212            }
213            Type::Param(_) | Type::Task(_) | Type::Function { .. } | Type::NotData => {
214                return Err(EncodeError::new(
215                    &Place::default(),
216                    EncodeErrorKind::NoEncoding,
217                    "has a type with no encoding",
218                ));
219            }
220        };
221        Ok(schema)
222    }
223
224    /// The `$ref` to `decl` applied to `args`, queueing its `$defs` entry
225    /// the first time it is reached.
226    fn reference(&mut self, decl: DeclId, args: &[Type]) -> Result<String, EncodeError> {
227        let id = (decl, args.to_vec());
228        if let Some(key) = self.keys.get(&id) {
229            return Ok(pointer(key));
230        }
231        if self.keys.len() == DEFS {
232            return Err(too_large());
233        }
234        let written = self
235            .catalog
236            .written(&Type::Named(decl, args.to_vec()), Versions::Shown);
237        let key = written;
238        self.keys.insert(id, key.clone());
239        self.pending
240            .push_back((self.defs.len(), decl, args.to_vec()));
241        self.defs.push((key.clone(), Json::Null));
242        Ok(pointer(&key))
243    }
244
245    fn body(&mut self, decl: DeclId, args: &[Type]) -> Result<Json, EncodeError> {
246        let declared = self.catalog.decl(decl);
247        let member = |index: usize| declared.members.get(index);
248        let members: Vec<(String, Json)> = match &declared.body {
249            // A newtype's entry is its base's schema, with nothing of its
250            // own but its doc comment (`abi.md`, *Schemas*).
251            Body::Newtype(base) => {
252                let mut schema = self.schema(&base.subst(args))?;
253                // `url.Url` alone adds the format `uri`.
254                if StdForm::of(declared) == Some(StdForm::Url)
255                    && let Json::Object(members) = &mut schema
256                {
257                    members.push(("format".to_owned(), Json::String("uri".to_owned())));
258                }
259                return Ok(Self::described(schema, declared.doc.as_deref()));
260            }
261            Body::Record(shape, fields) => {
262                let fields: Vec<Type> = fields.iter().map(|field| field.subst(args)).collect();
263                let names: Vec<&str> = shape.fields().collect();
264                let docs: Vec<Option<&str>> = (0..names.len())
265                    .map(|index| member(index).and_then(|member| member.doc.as_deref()))
266                    .collect();
267                self.fields(&names, &fields, &docs)?
268            }
269            Body::Enum(shape, ctors) => {
270                let branches = ctors
271                    .iter()
272                    .enumerate()
273                    .map(|(index, parts)| {
274                        let ctor = shape
275                            .constructor(index)
276                            .expect("one payload per constructor");
277                        let parts: Vec<Type> = parts.iter().map(|part| part.subst(args)).collect();
278                        let doc = member(index).and_then(|member| member.doc.as_deref());
279                        let payload = match ctor.payload() {
280                            Payload::None => {
281                                return Ok(Self::described(constant(ctor.name()), doc));
282                            }
283                            Payload::Positional(1) => self.schema(&parts[0])?,
284                            Payload::Positional(_) => array(
285                                parts
286                                    .iter()
287                                    .map(|part| self.schema(part))
288                                    .collect::<Result<_, _>>()?,
289                            ),
290                            Payload::Named(names) => {
291                                let names: Vec<&str> = names.iter().map(|name| &**name).collect();
292                                let docs: Vec<Option<&str>> = (0..names.len())
293                                    .map(|field| {
294                                        member(index)
295                                            .and_then(|member| member.fields.get(field))
296                                            .and_then(Option::as_deref)
297                                    })
298                                    .collect();
299                                Json::Object(self.fields(&names, &parts, &docs)?)
300                            }
301                        };
302                        Ok(Self::described(single(ctor.name(), payload), doc))
303                    })
304                    .collect::<Result<_, EncodeError>>()?;
305                vec![("oneOf".into(), Json::Array(branches))]
306            }
307            Body::NonData => {
308                return Err(EncodeError::new(
309                    &Place::default(),
310                    EncodeErrorKind::NoEncoding,
311                    "has a type with no encoding",
312                ));
313            }
314            Body::Host => vec![("type".into(), Json::String("string".into()))],
315        };
316        Ok(Self::described(
317            Json::Object(members),
318            declared.doc.as_deref(),
319        ))
320    }
321
322    /// `schema` with `doc` as its `description`, when there is one and the
323    /// schema is written to be read.
324    fn described(mut schema: Json, doc: Option<&str>) -> Json {
325        let Some(doc) = doc else {
326            return schema;
327        };
328        let description = ("description".to_owned(), Json::String(doc.to_owned()));
329        match schema {
330            Json::Object(ref mut members) => {
331                members.push(description);
332                schema
333            }
334            // `false`, the one schema a field can have that is not an
335            // object.
336            other => Json::Object(vec![
337                ("allOf".to_owned(), Json::Array(vec![other])),
338                description,
339            ]),
340        }
341    }
342
343    /// An object schema's members for named fields: each field's schema, an
344    /// `Option` field's being its payload's, described by its doc comment in
345    /// `docs`, every other field required, and in a signature the names in
346    /// declaration order as `order`.
347    fn fields(
348        &mut self,
349        names: &[&str],
350        types: &[Type],
351        docs: &[Option<&str>],
352    ) -> Result<Vec<(String, Json)>, EncodeError> {
353        let mut properties = Vec::new();
354        let mut required = Vec::new();
355        for ((name, ty), doc) in names.iter().zip(types).zip(docs) {
356            // A field whose type erases to `Option<X>` is written as any
357            // `Option<X>` field is, not required and with `X`'s schema; for a
358            // newtype over one, the newtype's doc stands in for a missing
359            // field doc, since its `$defs` entry is not referred to here.
360            let catalog = self.catalog;
361            let (schema, doc) = if let Type::Option(item) = &*catalog.erase(ty) {
362                let own = match ty {
363                    Type::Named(decl, _) => catalog.decl(*decl).doc.as_deref(),
364                    _ => None,
365                };
366                (self.schema(item)?, doc.or(own))
367            } else {
368                required.push(Json::String((*name).to_owned()));
369                (self.schema(ty)?, *doc)
370            };
371            properties.push(((*name).to_owned(), Self::described(schema, doc)));
372        }
373        let members = vec![
374            ("type".to_owned(), Json::String("object".into())),
375            ("properties".to_owned(), Json::Object(properties)),
376            ("required".to_owned(), Json::Array(required)),
377        ];
378        Ok(members)
379    }
380}
381
382fn too_large() -> EncodeError {
383    EncodeError::new(
384        &Place::default(),
385        EncodeErrorKind::TooLarge,
386        "has a type too large to describe",
387    )
388}
389
390/// `{"const": name}`: a constructor with no payload.
391fn constant(name: &str) -> Json {
392    Json::Object(vec![("const".into(), Json::String(name.to_owned()))])
393}
394
395/// An object with exactly the one member `name`, holding `payload`.
396fn single(name: &str, payload: Json) -> Json {
397    Json::Object(vec![
398        ("type".into(), Json::String("object".into())),
399        (
400            "properties".into(),
401            Json::Object(vec![(name.to_owned(), payload)]),
402        ),
403        (
404            "required".into(),
405            Json::Array(vec![Json::String(name.to_owned())]),
406        ),
407        ("additionalProperties".into(), Json::Bool(false)),
408    ])
409}
410
411/// An array of exactly `parts`, in order.
412fn array(parts: Vec<Json>) -> Json {
413    let count = Json::Number(flow_value::Decimal::from(&flow_value::Int::from_count(
414        parts.len(),
415    )));
416    Json::Object(vec![
417        ("type".into(), Json::String("array".into())),
418        ("prefixItems".into(), Json::Array(parts)),
419        ("items".into(), Json::Bool(false)),
420        ("minItems".into(), count),
421    ])
422}
423
424/// The `$ref` naming the `$defs` entry `key`: a JSON Pointer in a URI
425/// fragment, with `~` and `/` escaped as the pointer requires and every
426/// character a fragment can't hold percent-encoded.
427pub(crate) fn pointer(key: &str) -> String {
428    let mut out = String::from("#/$defs/");
429    let escaped = key.replace('~', "~0").replace('/', "~1");
430    for byte in escaped.bytes() {
431        if byte.is_ascii_alphanumeric() || b"-._~!$&'()*+,;=:@/".contains(&byte) {
432            out.push(char::from(byte));
433        } else {
434            write!(out, "%{byte:02X}").expect("writing to a string");
435        }
436    }
437    out
438}