use serde::{Deserialize, Deserializer, Serialize};
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FieldType {
#[default]
Any,
Text,
Secret,
RichText,
Int,
Float,
Bool,
Date,
Time,
Identifier,
#[serde(alias = "principal")]
Actor,
Resource(String),
Named(String),
Json,
Option(Box<FieldType>),
List(Box<FieldType>),
Set(Box<FieldType>),
Collection(Box<FieldType>),
Map(Box<FieldType>),
Union(Vec<FieldType>),
Reactions,
Outbox(Box<FieldType>),
Duration,
}
impl FieldType {
#[must_use]
pub const fn is_any(&self) -> bool {
matches!(self, Self::Any)
}
#[must_use]
pub const fn is_outbox(&self) -> bool {
matches!(self, Self::Outbox(_))
}
#[must_use]
pub const fn is_reactions(&self) -> bool {
matches!(self, Self::Reactions)
}
#[must_use]
pub fn from_rust_text(text: &str) -> Self {
let head = text.split('<').next().unwrap_or_default().trim();
match head.rsplit("::").next() {
Some("Outbox") if text.contains('<') => Self::Outbox(Box::new(Self::Any)),
Some("Reactions") => Self::Reactions,
_ => Self::Any,
}
}
#[must_use]
pub fn renamed(&self, renames: &std::collections::BTreeMap<String, String>) -> Self {
let inner = |ty: &Self| Box::new(ty.renamed(renames));
match self {
Self::Named(name) => renames
.get(name)
.map_or_else(|| self.clone(), |name| Self::Named(name.clone())),
Self::Option(ty) => Self::Option(inner(ty)),
Self::List(ty) => Self::List(inner(ty)),
Self::Set(ty) => Self::Set(inner(ty)),
Self::Collection(ty) => Self::Collection(inner(ty)),
Self::Map(ty) => Self::Map(inner(ty)),
Self::Outbox(ty) => Self::Outbox(inner(ty)),
Self::Union(cases) => {
Self::Union(cases.iter().map(|case| case.renamed(renames)).collect())
}
other => other.clone(),
}
}
#[must_use]
pub fn from_schema(schema: &serde_json::Value) -> Self {
use serde_json::Value;
let Some(node) = schema.as_object() else {
return Self::Any;
};
if let Some(kind) = node
.get(crate::params::RESOURCE_KIND_ANNOTATION)
.and_then(Value::as_str)
{
return Self::Resource(kind.to_owned());
}
for key in ["anyOf", "oneOf"] {
if let Some(alternatives) = node.get(key).and_then(Value::as_array) {
let is_null = |alternative: &Value| {
alternative.get("type").and_then(Value::as_str) == Some("null")
};
let present: Vec<&Value> =
alternatives.iter().filter(|item| !is_null(item)).collect();
if let [one] = present.as_slice()
&& present.len() < alternatives.len()
{
return Self::Option(Box::new(Self::from_schema(one)));
}
return Self::Any;
}
}
let types: Vec<&str> = match node.get("type") {
Some(Value::String(one)) => vec![one.as_str()],
Some(Value::Array(many)) => many.iter().filter_map(Value::as_str).collect(),
_ => Vec::new(),
};
let nullable = types.contains(&"null");
let present: Vec<&str> = types.into_iter().filter(|ty| *ty != "null").collect();
let ty = match present.as_slice() {
["string"] => match node.get("format").and_then(Value::as_str) {
Some("date") => Self::Date,
Some("date-time") => Self::Time,
Some("uri") => Self::Identifier,
_ => Self::Text,
},
["integer"] => Self::Int,
["number"] => Self::Float,
["boolean"] => Self::Bool,
["array"] => {
let item = node.get("items").map_or(Self::Any, Self::from_schema);
if node.get("uniqueItems").and_then(Value::as_bool) == Some(true) {
Self::Set(Box::new(item))
} else {
Self::List(Box::new(item))
}
}
["object"] => match node.get("additionalProperties") {
Some(item @ Value::Object(_)) if node.get("properties").is_none() => {
Self::Map(Box::new(Self::from_schema(item)))
}
_ => Self::Any,
},
_ => Self::Any,
};
if nullable && ty != Self::Any {
Self::Option(Box::new(ty))
} else {
ty
}
}
}
pub(crate) fn field_type_or_text<'de, D: Deserializer<'de>>(
deserializer: D,
) -> Result<FieldType, D::Error> {
#[derive(Deserialize)]
#[serde(untagged)]
enum Written {
Typed(FieldType),
Text(String),
}
Ok(match Written::deserialize(deserializer)? {
Written::Typed(ty) => ty,
Written::Text(text) => FieldType::from_rust_text(&text),
})
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct NamedType {
pub name: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub doc: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub fields: Vec<TypeField>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub cases: Vec<TypeCase>,
}
impl NamedType {
#[must_use]
pub const fn is_enum(&self) -> bool {
!self.cases.is_empty()
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TypeField {
pub name: String,
#[serde(rename = "type", deserialize_with = "field_type_or_text")]
pub ty: FieldType,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub title: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TypeCase {
pub name: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub label: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub fields: Vec<TypeField>,
}
#[derive(Debug, Default)]
pub struct TypeSet {
declared: Vec<(String, NamedType)>,
}
impl TypeSet {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn named(
&mut self,
identity: &str,
name: &str,
build: impl FnOnce(&mut Self) -> NamedType,
) -> FieldType {
if let Some((_, declared)) = self.declared.iter().find(|(id, _)| id == identity) {
return FieldType::Named(declared.name.clone());
}
let mut unique = name.to_owned();
let mut number = 2_u32;
while self.declared.iter().any(|(_, ty)| ty.name == unique) {
unique = format!("{name}{number}");
number = number.saturating_add(1);
}
let at = self.declared.len();
self.declared.push((
identity.to_owned(),
NamedType {
name: unique.clone(),
..NamedType::default()
},
));
let mut body = build(self);
body.name.clone_from(&unique);
if let Some((_, slot)) = self.declared.get_mut(at) {
*slot = body;
}
FieldType::Named(unique)
}
#[must_use]
pub fn get(&self, name: &str) -> Option<&NamedType> {
self.declared
.iter()
.map(|(_, ty)| ty)
.find(|ty| ty.name == name)
}
#[must_use]
pub fn into_types(self) -> Vec<NamedType> {
let mut types: Vec<NamedType> = self.declared.into_iter().map(|(_, ty)| ty).collect();
types.sort_by(|a, b| a.name.cmp(&b.name));
types
}
}
#[must_use]
pub fn label_of(name: &str) -> String {
let words = name.replace(['_', '-'], " ");
let mut chars = words.trim().chars();
chars.next().map_or_else(String::new, |first| {
first.to_uppercase().chain(chars).collect()
})
}
#[cfg(test)]
mod tests {
use super::*;
tilo_test_env::scenario! {
fn a_field_type_reads_and_declares_its_schema;
phase a_type_reads_from_the_vocabulary_or_older_rust_text;
{
#[derive(Deserialize)]
struct Field {
#[serde(deserialize_with = "field_type_or_text")]
ty: FieldType,
}
let read = |json: &str| {
serde_json::from_str::<Field>(json).map_or(FieldType::Any, |field| field.ty)
};
assert_eq!(read(r#"{"ty": "text"}"#), FieldType::Text);
assert_eq!(
read(r#"{"ty": {"option": {"named": "Channel"}}}"#),
FieldType::Option(Box::new(FieldType::Named("Channel".into())))
);
assert_eq!(read(r#"{"ty": "String"}"#), FieldType::Any);
assert_eq!(
read(r#"{"ty": "ui::tilo_resource::Reactions"}"#),
FieldType::Reactions
);
assert!(read(r#"{"ty": "Outbox<Upload>"}"#).is_outbox());
assert_eq!(
read(r#"{"ty": {"option": "principal"}}"#),
FieldType::Option(Box::new(FieldType::Actor))
);
}
phase a_type_used_twice_is_declared_once_and_names_stay_unique;
{
let mut types = TypeSet::new();
let record = |name: &str| NamedType {
name: name.into(),
..NamedType::default()
};
let first = types.named("a::Step", "Step", |_| record("Step"));
let again = types.named("a::Step", "Step", |_| unreachable!());
let other = types.named("b::Step", "Step", |_| record("Step"));
assert_eq!(first, again);
assert_eq!(other, FieldType::Named("Step2".into()));
let names: Vec<String> = types.into_types().into_iter().map(|ty| ty.name).collect();
assert_eq!(names, ["Step", "Step2"]);
}
phase a_schema_tells_what_it_can;
{
let ty = FieldType::from_schema(&serde_json::json!({"type": ["string", "null"]}));
assert_eq!(ty, FieldType::Option(Box::new(FieldType::Text)));
let ty = FieldType::from_schema(
&serde_json::json!({"type": "array", "items": {"type": "integer"}}),
);
assert_eq!(ty, FieldType::List(Box::new(FieldType::Int)));
}
}
}