flow-abi 0.1.0

The value encoding at the host boundary: type-directed JSON encoding and decoding, the canonical form and its hash, JSON Schemas, and Tool declaration fingerprints.
Documentation
//! A type's JSON Schema, draft 2020-12 (`abi.md`, *Schemas*).
//!
//! The schema is generated from the declarations and describes the encoding
//! above; it adds no rule, and where JSON Schema cannot say what the encoding
//! says — an integer's exact size, a set's order — the encoding decides.
//!
//! # Readings
//!
//! - A generic declaration has one `$defs` entry per list of arguments it is
//!   used with, keyed by its identity with those arguments written after it:
//!   `std@v1/result.Result<Int, Text>`. Two declarations that write the same
//!   key — local types of one name in one file — are told apart by a `#2`,
//!   `#3`, ... suffix in the order they are reached.
//! - `Option` is written in place, not in `$defs`: inside a record it is its
//!   payload's schema, and elsewhere a `oneOf` of `"None"` and `{"Some": ...}`.
//! - A constructor's object form allows no other member, since decoding
//!   refuses one; a record allows them, since a reply may carry extra fields.
//! - A positional payload of several values and a tuple are arrays of exactly
//!   their length; `Unit` is the empty array, and `Never` the schema `false`.
//! - A host type is a `string`: the token.
//! - A member's doc comment sits beside what it documents: a field's on its
//!   property schema, a constructor's on its `oneOf` branch. A field whose
//!   schema is `false` is written `{"allOf": [false]}` to carry one.

use std::collections::{HashMap, VecDeque};
use std::fmt::Write as _;

use flow_value::Payload;

use crate::error::{EncodeError, Path};
use crate::json::Json;
use crate::types::{Body, Catalog, DeclId, Type};

/// The `$schema` this crate writes.
pub const DIALECT: &str = "https://json-schema.org/draft/2020-12/schema";

/// How many `$defs` entries one schema may have. A type whose generic
/// declarations reach more argument lists than this — only one that applies
/// itself to ever larger arguments can — is refused rather than written.
const DEFS: usize = 1_000;

/// How deeply one type written in a schema may nest. Only a declaration that
/// applies itself to ever larger arguments reaches it.
const NESTING: usize = 128;

/// The schema of `ty`, with each named type in `$defs` and every doc comment
/// as a `description`.
pub fn schema(catalog: &Catalog, ty: &Type) -> Result<Json, EncodeError> {
    Writer::new(catalog, &[], Purpose::Document).document(ty)
}

/// What a schema is written for.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum Purpose {
    /// To be read: doc comments become descriptions, and `$defs` keys are
    /// identities.
    Document,
    /// To be hashed into a fingerprint, which a doc comment or a new
    /// repository version must not move: no description, and `$defs` keys
    /// are identities without the version.
    Signature,
}

pub(crate) struct Writer<'c> {
    catalog: &'c Catalog,
    params: &'c [String],
    purpose: Purpose,
    keys: HashMap<(DeclId, Vec<Type>), String>,
    taken: HashMap<String, usize>,
    defs: Vec<(String, Json)>,
    pending: VecDeque<(usize, DeclId, Vec<Type>)>,
    nesting: usize,
}

impl<'c> Writer<'c> {
    /// A writer for types whose [`Type::Param`]s are named by `params`.
    pub(crate) fn new(catalog: &'c Catalog, params: &'c [String], purpose: Purpose) -> Self {
        Writer {
            catalog,
            params,
            purpose,
            keys: HashMap::new(),
            taken: HashMap::new(),
            defs: Vec::new(),
            pending: VecDeque::new(),
            nesting: 0,
        }
    }

    /// The whole schema of `ty`: its own schema with `$schema` and, when it
    /// names any declaration, `$defs`.
    pub(crate) fn document(mut self, ty: &Type) -> Result<Json, EncodeError> {
        let root = self.schema(ty)?;
        // Each `$defs` entry is written after the one before it, so writing
        // one that names another only queues it: however deep a chain of
        // declarations runs, the writer's own stack does not.
        while let Some((slot, decl, args)) = self.pending.pop_front() {
            self.defs[slot].1 = self.body(decl, &args)?;
        }
        let mut members = vec![("$schema".to_owned(), Json::String(DIALECT.into()))];
        match root {
            Json::Object(own) => members.extend(own),
            // `true` and `false` schemas, which a `$defs` can't be added to.
            other => members.push(("allOf".into(), Json::Array(vec![other]))),
        }
        if !self.defs.is_empty() {
            members.push(("$defs".into(), Json::Object(self.defs)));
        }
        Ok(Json::Object(members))
    }

    fn schema(&mut self, ty: &Type) -> Result<Json, EncodeError> {
        if self.nesting == NESTING {
            return Err(too_large());
        }
        self.nesting += 1;
        let schema = self.nested(ty);
        self.nesting -= 1;
        schema
    }

    fn nested(&mut self, ty: &Type) -> Result<Json, EncodeError> {
        let object = |members: Vec<(&str, Json)>| {
            Json::Object(
                members
                    .into_iter()
                    .map(|(key, value)| (key.to_owned(), value))
                    .collect(),
            )
        };
        let string = |text: &str| Json::String(text.to_owned());
        let typed = |name: &str| object(vec![("type", string(name))]);
        let schema = match ty {
            Type::Int => typed("integer"),
            Type::Decimal => typed("number"),
            Type::Bool => typed("boolean"),
            Type::Text => typed("string"),
            Type::Bytes => object(vec![
                ("type", string("string")),
                ("contentEncoding", string("base64")),
            ]),
            Type::Duration => object(vec![
                ("type", string("string")),
                ("format", string("duration")),
            ]),
            Type::Instant => object(vec![
                ("type", string("string")),
                ("format", string("date-time")),
            ]),
            Type::Unit => array(Vec::new()),
            Type::Never => Json::Bool(false),
            Type::Json => Json::Object(Vec::new()),
            Type::List(item) => object(vec![
                ("type", string("array")),
                ("items", self.schema(item)?),
            ]),
            Type::Set(item) => object(vec![
                ("type", string("array")),
                ("items", self.schema(item)?),
                ("uniqueItems", Json::Bool(true)),
            ]),
            Type::Dict(key, item) if **key == Type::Text => object(vec![
                ("type", string("object")),
                ("additionalProperties", self.schema(item)?),
            ]),
            Type::Dict(key, item) => object(vec![
                ("type", string("array")),
                ("items", array(vec![self.schema(key)?, self.schema(item)?])),
            ]),
            Type::Option(item) => object(vec![(
                "oneOf",
                Json::Array(vec![constant("None"), single("Some", self.schema(item)?)]),
            )]),
            Type::Tuple(parts) => array(
                parts
                    .iter()
                    .map(|part| self.schema(part))
                    .collect::<Result<_, _>>()?,
            ),
            Type::Named(decl, args) => {
                object(vec![("$ref", string(&self.reference(*decl, args)?))])
            }
            Type::Param(index) => {
                let name = self.params.get(*index as usize).ok_or_else(|| {
                    EncodeError::new(&Path::default(), "names a type parameter it does not have")
                })?;
                object(vec![("$param", string(name))])
            }
            Type::Task(_) | Type::Function { .. } | Type::NotData => {
                return Err(EncodeError::new(
                    &Path::default(),
                    "has a type with no encoding",
                ));
            }
        };
        Ok(schema)
    }

    /// The `$ref` to `decl` applied to `args`, queueing its `$defs` entry
    /// the first time it is reached.
    fn reference(&mut self, decl: DeclId, args: &[Type]) -> Result<String, EncodeError> {
        let id = (decl, args.to_vec());
        if let Some(key) = self.keys.get(&id) {
            return Ok(pointer(key));
        }
        if self.keys.len() == DEFS {
            return Err(too_large());
        }
        let written = self.catalog.written(
            &Type::Named(decl, args.to_vec()),
            self.purpose == Purpose::Document,
        );
        let count = self.taken.entry(written.clone()).or_insert(0);
        *count += 1;
        let key = if *count == 1 {
            written
        } else {
            format!("{written}#{count}")
        };
        self.keys.insert(id, key.clone());
        self.pending
            .push_back((self.defs.len(), decl, args.to_vec()));
        self.defs.push((key.clone(), Json::Null));
        Ok(pointer(&key))
    }

    fn body(&mut self, decl: DeclId, args: &[Type]) -> Result<Json, EncodeError> {
        let named = self.catalog.decl(decl);
        let member = |index: usize| named.members.get(index);
        let members: Vec<(String, Json)> = match &named.body {
            Body::Record(shape, fields) => {
                let fields: Vec<Type> = fields.iter().map(|field| field.subst(args)).collect();
                let names: Vec<&str> = shape.fields().collect();
                let docs: Vec<Option<&str>> = (0..names.len())
                    .map(|index| member(index).and_then(|member| member.doc.as_deref()))
                    .collect();
                self.fields(&names, &fields, &docs)?
            }
            Body::Enum(shape, ctors) => {
                let branches = ctors
                    .iter()
                    .enumerate()
                    .map(|(index, parts)| {
                        let ctor = shape
                            .constructor(index)
                            .expect("one payload per constructor");
                        let parts: Vec<Type> = parts.iter().map(|part| part.subst(args)).collect();
                        let doc = member(index).and_then(|member| member.doc.as_deref());
                        let payload = match ctor.payload() {
                            Payload::None => return Ok(self.described(constant(ctor.name()), doc)),
                            Payload::Positional(1) => self.schema(&parts[0])?,
                            Payload::Positional(_) => array(
                                parts
                                    .iter()
                                    .map(|part| self.schema(part))
                                    .collect::<Result<_, _>>()?,
                            ),
                            Payload::Named(names) => {
                                let names: Vec<&str> = names.iter().map(|name| &**name).collect();
                                let docs: Vec<Option<&str>> = (0..names.len())
                                    .map(|field| {
                                        member(index)
                                            .and_then(|member| member.fields.get(field))
                                            .and_then(Option::as_deref)
                                    })
                                    .collect();
                                Json::Object(self.fields(&names, &parts, &docs)?)
                            }
                        };
                        Ok(self.described(single(ctor.name(), payload), doc))
                    })
                    .collect::<Result<_, EncodeError>>()?;
                vec![("oneOf".into(), Json::Array(branches))]
            }
            Body::NonData => {
                return Err(EncodeError::new(
                    &Path::default(),
                    "has a type with no encoding",
                ));
            }
            Body::Host => vec![("type".into(), Json::String("string".into()))],
        };
        Ok(self.described(Json::Object(members), named.doc.as_deref()))
    }

    /// `schema` with `doc` as its `description`, when there is one and the
    /// schema is written to be read.
    fn described(&self, schema: Json, doc: Option<&str>) -> Json {
        let Some(doc) = doc.filter(|_| self.purpose == Purpose::Document) else {
            return schema;
        };
        let description = ("description".to_owned(), Json::String(doc.to_owned()));
        match schema {
            Json::Object(mut members) => {
                members.push(description);
                Json::Object(members)
            }
            // `false`, the one schema a field can have that is not an
            // object.
            other => Json::Object(vec![
                ("allOf".to_owned(), Json::Array(vec![other])),
                description,
            ]),
        }
    }

    /// An object schema's members for named fields: each field's schema, an
    /// `Option` field's being its payload's, described by its doc comment in
    /// `docs`, and every other field required.
    fn fields(
        &mut self,
        names: &[&str],
        types: &[Type],
        docs: &[Option<&str>],
    ) -> Result<Vec<(String, Json)>, EncodeError> {
        let mut properties = Vec::new();
        let mut required = Vec::new();
        for ((name, ty), doc) in names.iter().zip(types).zip(docs) {
            let schema = if let Type::Option(item) = ty {
                self.schema(item)?
            } else {
                required.push(Json::String((*name).to_owned()));
                self.schema(ty)?
            };
            properties.push(((*name).to_owned(), self.described(schema, *doc)));
        }
        Ok(vec![
            ("type".to_owned(), Json::String("object".into())),
            ("properties".to_owned(), Json::Object(properties)),
            ("required".to_owned(), Json::Array(required)),
        ])
    }
}

fn too_large() -> EncodeError {
    EncodeError::new(&Path::default(), "has a type too large to describe")
}

/// `{"const": name}`: a constructor with no payload.
fn constant(name: &str) -> Json {
    Json::Object(vec![("const".into(), Json::String(name.to_owned()))])
}

/// An object with exactly the one member `name`, holding `payload`.
fn single(name: &str, payload: Json) -> Json {
    Json::Object(vec![
        ("type".into(), Json::String("object".into())),
        (
            "properties".into(),
            Json::Object(vec![(name.to_owned(), payload)]),
        ),
        (
            "required".into(),
            Json::Array(vec![Json::String(name.to_owned())]),
        ),
        ("additionalProperties".into(), Json::Bool(false)),
    ])
}

/// An array of exactly `parts`, in order.
fn array(parts: Vec<Json>) -> Json {
    let count = Json::Number(flow_value::Decimal::from(&flow_value::Int::from_count(
        parts.len(),
    )));
    Json::Object(vec![
        ("type".into(), Json::String("array".into())),
        ("prefixItems".into(), Json::Array(parts)),
        ("items".into(), Json::Bool(false)),
        ("minItems".into(), count),
    ])
}

/// The `$ref` naming the `$defs` entry `key`: a JSON Pointer in a URI
/// fragment, with `~` and `/` escaped as the pointer requires and every
/// character a fragment can't hold percent-encoded.
fn pointer(key: &str) -> String {
    let mut out = String::from("#/$defs/");
    let escaped = key.replace('~', "~0").replace('/', "~1");
    for byte in escaped.bytes() {
        if byte.is_ascii_alphanumeric() || b"-._~!$&'()*+,;=:@/".contains(&byte) {
            out.push(char::from(byte));
        } else {
            write!(out, "%{byte:02X}").expect("writing to a string");
        }
    }
    out
}