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};
pub const DIALECT: &str = "https://json-schema.org/draft/2020-12/schema";
const DEFS: usize = 1_000;
const NESTING: usize = 128;
pub fn schema(catalog: &Catalog, ty: &Type) -> Result<Json, EncodeError> {
Writer::new(catalog, &[], Purpose::Document).document(ty)
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum Purpose {
Document,
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> {
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,
}
}
pub(crate) fn document(mut self, ty: &Type) -> Result<Json, EncodeError> {
let root = self.schema(ty)?;
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),
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)
}
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()))
}
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)
}
other => Json::Object(vec![
("allOf".to_owned(), Json::Array(vec![other])),
description,
]),
}
}
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")
}
fn constant(name: &str) -> Json {
Json::Object(vec![("const".into(), Json::String(name.to_owned()))])
}
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)),
])
}
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),
])
}
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
}