Skip to main content

tilo_actions/
field_type.rs

1//! The type of a field or value, the same whichever language declared it.
2//!
3//! A Rust model derives it (`#[derive(Model)]`, `#[derive(JsonSchema)]`), the
4//! tilolang compiler emits it, and a [`Surface`](crate::surface::Surface)
5//! carries it for every stored field. Records, enums and unions with a name
6//! are declared once, in the surface's [`types`](crate::surface::Surface::types),
7//! and referred to by name, so each side renders the other's declarations
8//! (`tilolang describe` prints a native app's resources as tilolang) and
9//! names the other's types (`use so.tilo.chat as chat`).
10
11use serde::{Deserialize, Deserializer, Serialize};
12
13/// A field's or value's type. See the module docs.
14#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
15#[serde(rename_all = "snake_case")]
16pub enum FieldType {
17    /// A value this vocabulary does not describe: any JSON value.
18    #[default]
19    Any,
20    Text,
21    /// Text handed over once and kept nowhere: a password, a token, a one-time code. A
22    /// parameter's type, never a stored field's: what a record keeps of a call whose parameter is
23    /// one is its name alone ([`crate::ParamType::Secret`]).
24    Secret,
25    /// Formatted text that references resources (tilo-doc's rich text).
26    RichText,
27    Int,
28    Float,
29    Bool,
30    /// A calendar day, held as ISO text `YYYY-MM-DD`.
31    Date,
32    /// An instant, held as ISO-8601 text.
33    Time,
34    /// An account of some service, held as its URI (`mailto:jane@x.com`).
35    Identifier,
36    /// Who did something: a person or an agent. Surfaces kept before it was
37    /// named actor say `principal`, and changes written under them are still
38    /// decided with them.
39    #[serde(alias = "principal")]
40    Actor,
41    /// A reference to a resource of this kind; of any kind when empty.
42    Resource(String),
43    /// A record or enum declared in the surface's types.
44    Named(String),
45    /// Any JSON value: what an action answers with that no field shape describes
46    /// (a read's output, a parsed document).
47    Json,
48    /// A value or none.
49    Option(Box<FieldType>),
50    List(Box<FieldType>),
51    /// Distinct values.
52    Set(Box<FieldType>),
53    /// Ordered items, each under an id of its own.
54    Collection(Box<FieldType>),
55    /// Values under text keys.
56    Map(Box<FieldType>),
57    /// A value of any of these types, at least two.
58    Union(Vec<FieldType>),
59    /// The platform's reactions: changed only by the react and unreact
60    /// field edits, which store their invoker.
61    Reactions,
62    /// An outbox of these entries: what a change queues there reaches
63    /// outside the record once delivered.
64    Outbox(Box<FieldType>),
65    /// A length of time, held as its number of seconds. Not a stored
66    /// field's type: a field keeps a number the app reads in its own unit.
67    Duration,
68}
69
70impl FieldType {
71    /// Whether it describes no type: any value.
72    #[must_use]
73    pub const fn is_any(&self) -> bool {
74        matches!(self, Self::Any)
75    }
76
77    /// Whether it is an outbox.
78    #[must_use]
79    pub const fn is_outbox(&self) -> bool {
80        matches!(self, Self::Outbox(_))
81    }
82
83    /// Whether it is the platform's reactions.
84    #[must_use]
85    pub const fn is_reactions(&self) -> bool {
86        matches!(self, Self::Reactions)
87    }
88
89    /// The type of a field a surface written before this vocabulary
90    /// described by its Rust type's text (`Outbox<Upload>`,
91    /// `ui::tilo_resource::Reactions`): what receipt still tells from it.
92    #[must_use]
93    pub fn from_rust_text(text: &str) -> Self {
94        let head = text.split('<').next().unwrap_or_default().trim();
95        match head.rsplit("::").next() {
96            Some("Outbox") if text.contains('<') => Self::Outbox(Box::new(Self::Any)),
97            Some("Reactions") => Self::Reactions,
98            _ => Self::Any,
99        }
100    }
101
102    /// This type with the named types `renames` maps given their new names:
103    /// what a surface does when a record its fields already declared is
104    /// named again by a value an action answers with.
105    #[must_use]
106    pub fn renamed(&self, renames: &std::collections::BTreeMap<String, String>) -> Self {
107        let inner = |ty: &Self| Box::new(ty.renamed(renames));
108        match self {
109            Self::Named(name) => renames
110                .get(name)
111                .map_or_else(|| self.clone(), |name| Self::Named(name.clone())),
112            Self::Option(ty) => Self::Option(inner(ty)),
113            Self::List(ty) => Self::List(inner(ty)),
114            Self::Set(ty) => Self::Set(inner(ty)),
115            Self::Collection(ty) => Self::Collection(inner(ty)),
116            Self::Map(ty) => Self::Map(inner(ty)),
117            Self::Outbox(ty) => Self::Outbox(inner(ty)),
118            Self::Union(cases) => {
119                Self::Union(cases.iter().map(|case| case.renamed(renames)).collect())
120            }
121            other => other.clone(),
122        }
123    }
124
125    /// The type of a value of the JSON Schema `schema`, as far as the schema
126    /// tells: what a parameter published only as its schema takes.
127    #[must_use]
128    pub fn from_schema(schema: &serde_json::Value) -> Self {
129        use serde_json::Value;
130        let Some(node) = schema.as_object() else {
131            return Self::Any;
132        };
133        if let Some(kind) = node
134            .get(crate::params::RESOURCE_KIND_ANNOTATION)
135            .and_then(Value::as_str)
136        {
137            return Self::Resource(kind.to_owned());
138        }
139        for key in ["anyOf", "oneOf"] {
140            if let Some(alternatives) = node.get(key).and_then(Value::as_array) {
141                let is_null = |alternative: &Value| {
142                    alternative.get("type").and_then(Value::as_str) == Some("null")
143                };
144                let present: Vec<&Value> =
145                    alternatives.iter().filter(|item| !is_null(item)).collect();
146                if let [one] = present.as_slice()
147                    && present.len() < alternatives.len()
148                {
149                    return Self::Option(Box::new(Self::from_schema(one)));
150                }
151                return Self::Any;
152            }
153        }
154        let types: Vec<&str> = match node.get("type") {
155            Some(Value::String(one)) => vec![one.as_str()],
156            Some(Value::Array(many)) => many.iter().filter_map(Value::as_str).collect(),
157            _ => Vec::new(),
158        };
159        let nullable = types.contains(&"null");
160        let present: Vec<&str> = types.into_iter().filter(|ty| *ty != "null").collect();
161        let ty = match present.as_slice() {
162            ["string"] => match node.get("format").and_then(Value::as_str) {
163                Some("date") => Self::Date,
164                Some("date-time") => Self::Time,
165                Some("uri") => Self::Identifier,
166                _ => Self::Text,
167            },
168            ["integer"] => Self::Int,
169            ["number"] => Self::Float,
170            ["boolean"] => Self::Bool,
171            ["array"] => {
172                let item = node.get("items").map_or(Self::Any, Self::from_schema);
173                if node.get("uniqueItems").and_then(Value::as_bool) == Some(true) {
174                    Self::Set(Box::new(item))
175                } else {
176                    Self::List(Box::new(item))
177                }
178            }
179            ["object"] => match node.get("additionalProperties") {
180                Some(item @ Value::Object(_)) if node.get("properties").is_none() => {
181                    Self::Map(Box::new(Self::from_schema(item)))
182                }
183                _ => Self::Any,
184            },
185            _ => Self::Any,
186        };
187        if nullable && ty != Self::Any {
188            Self::Option(Box::new(ty))
189        } else {
190            ty
191        }
192    }
193}
194
195/// A field type as a surface file holds it: the vocabulary, or the Rust
196/// text a file written before it holds, read as [`FieldType::from_rust_text`].
197pub(crate) fn field_type_or_text<'de, D: Deserializer<'de>>(
198    deserializer: D,
199) -> Result<FieldType, D::Error> {
200    #[derive(Deserialize)]
201    #[serde(untagged)]
202    enum Written {
203        Typed(FieldType),
204        Text(String),
205    }
206    Ok(match Written::deserialize(deserializer)? {
207        Written::Typed(ty) => ty,
208        Written::Text(text) => FieldType::from_rust_text(&text),
209    })
210}
211
212/// A record or enum with a name, declared once in a surface's types.
213///
214/// An enum has cases; a record has fields and no cases.
215#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
216pub struct NamedType {
217    pub name: String,
218    #[serde(default, skip_serializing_if = "String::is_empty")]
219    pub doc: String,
220    #[serde(default, skip_serializing_if = "Vec::is_empty")]
221    pub fields: Vec<TypeField>,
222    #[serde(default, skip_serializing_if = "Vec::is_empty")]
223    pub cases: Vec<TypeCase>,
224    /// For an enum whose cases carry fields: the key its case's name is written under, beside
225    /// the fields (`{"state": "done", "provider": …}`). Without one, a case with fields is
226    /// written as an object of its one key, the case's name, holding its fields.
227    #[serde(default, skip_serializing_if = "Option::is_none")]
228    pub tag: Option<String>,
229}
230
231impl NamedType {
232    /// Whether it is an enum: it has cases.
233    #[must_use]
234    pub const fn is_enum(&self) -> bool {
235        !self.cases.is_empty()
236    }
237}
238
239/// A field of a named record or of an enum case.
240#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
241pub struct TypeField {
242    pub name: String,
243    #[serde(rename = "type", deserialize_with = "field_type_or_text")]
244    pub ty: FieldType,
245    #[serde(default, skip_serializing_if = "String::is_empty")]
246    pub title: String,
247}
248
249/// A case of a named enum, with the fields its value carries.
250#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
251pub struct TypeCase {
252    pub name: String,
253    /// How it reads, for people.
254    #[serde(default, skip_serializing_if = "String::is_empty")]
255    pub label: String,
256    #[serde(default, skip_serializing_if = "Vec::is_empty")]
257    pub fields: Vec<TypeField>,
258}
259
260/// The named types a surface declares, gathered while its fields' types are
261/// worked out: each declared once under one name, however often it is used.
262#[derive(Debug, Default)]
263pub struct TypeSet {
264    /// The declared types, with the identity (a Rust type's path) each was
265    /// declared for.
266    declared: Vec<(String, NamedType)>,
267}
268
269impl TypeSet {
270    #[must_use]
271    pub fn new() -> Self {
272        Self::default()
273    }
274
275    /// The type named `name` declared for `identity` (a Rust type's path),
276    /// its body made by `build` the first time it is asked for. A different
277    /// type wanting a name already taken is numbered (`Step2`).
278    pub fn named(
279        &mut self,
280        identity: &str,
281        name: &str,
282        build: impl FnOnce(&mut Self) -> NamedType,
283    ) -> FieldType {
284        if let Some((_, declared)) = self.declared.iter().find(|(id, _)| id == identity) {
285            return FieldType::Named(declared.name.clone());
286        }
287        let mut unique = name.to_owned();
288        let mut number = 2_u32;
289        while self.declared.iter().any(|(_, ty)| ty.name == unique) {
290            unique = format!("{name}{number}");
291            number = number.saturating_add(1);
292        }
293        // Declared before its body is built, so a type that holds itself
294        // refers to its own name.
295        let at = self.declared.len();
296        self.declared.push((
297            identity.to_owned(),
298            NamedType {
299                name: unique.clone(),
300                ..NamedType::default()
301            },
302        ));
303        let mut body = build(self);
304        body.name.clone_from(&unique);
305        if let Some((_, slot)) = self.declared.get_mut(at) {
306            *slot = body;
307        }
308        FieldType::Named(unique)
309    }
310
311    /// Write the enum `ty` names with its case's name under `tag`, beside the case's fields.
312    pub fn tag(&mut self, ty: &FieldType, tag: &str) {
313        let FieldType::Named(name) = ty else { return };
314        if let Some((_, declared)) = self.declared.iter_mut().find(|(_, ty)| ty.name == *name) {
315            declared.tag = Some(tag.to_owned());
316        }
317    }
318
319    /// The type declared as `name`, when one is.
320    #[must_use]
321    pub fn get(&self, name: &str) -> Option<&NamedType> {
322        self.declared
323            .iter()
324            .map(|(_, ty)| ty)
325            .find(|ty| ty.name == name)
326    }
327
328    /// The declared types, by name.
329    #[must_use]
330    pub fn into_types(self) -> Vec<NamedType> {
331        let mut types: Vec<NamedType> = self.declared.into_iter().map(|(_, ty)| ty).collect();
332        types.sort_by(|a, b| a.name.cmp(&b.name));
333        types
334    }
335}
336
337/// The words of a case or field name as people read them: `in_progress` is
338/// "In progress".
339#[must_use]
340pub fn label_of(name: &str) -> String {
341    let words = name.replace(['_', '-'], " ");
342    let mut chars = words.trim().chars();
343    chars.next().map_or_else(String::new, |first| {
344        first.to_uppercase().chain(chars).collect()
345    })
346}
347
348#[cfg(test)]
349mod tests {
350    use super::*;
351
352    tilo_test_env::scenario! {
353        fn a_field_type_reads_and_declares_its_schema;
354
355        phase a_type_reads_from_the_vocabulary_or_older_rust_text;
356        {
357            #[derive(Deserialize)]
358            struct Field {
359                #[serde(deserialize_with = "field_type_or_text")]
360                ty: FieldType,
361            }
362            let read = |json: &str| {
363                serde_json::from_str::<Field>(json).map_or(FieldType::Any, |field| field.ty)
364            };
365            assert_eq!(read(r#"{"ty": "text"}"#), FieldType::Text);
366            assert_eq!(
367                read(r#"{"ty": {"option": {"named": "Channel"}}}"#),
368                FieldType::Option(Box::new(FieldType::Named("Channel".into())))
369            );
370            assert_eq!(read(r#"{"ty": "String"}"#), FieldType::Any);
371            assert_eq!(
372                read(r#"{"ty": "ui::tilo_resource::Reactions"}"#),
373                FieldType::Reactions
374            );
375            assert!(read(r#"{"ty": "Outbox<Upload>"}"#).is_outbox());
376            assert_eq!(
377                read(r#"{"ty": {"option": "principal"}}"#),
378                FieldType::Option(Box::new(FieldType::Actor))
379            );
380        }
381
382        phase a_type_used_twice_is_declared_once_and_names_stay_unique;
383        {
384            let mut types = TypeSet::new();
385            let record = |name: &str| NamedType {
386                name: name.into(),
387                ..NamedType::default()
388            };
389            let first = types.named("a::Step", "Step", |_| record("Step"));
390            let again = types.named("a::Step", "Step", |_| unreachable!());
391            let other = types.named("b::Step", "Step", |_| record("Step"));
392            assert_eq!(first, again);
393            assert_eq!(other, FieldType::Named("Step2".into()));
394            let names: Vec<String> = types.into_types().into_iter().map(|ty| ty.name).collect();
395            assert_eq!(names, ["Step", "Step2"]);
396        }
397
398        phase a_schema_tells_what_it_can;
399        {
400            let ty = FieldType::from_schema(&serde_json::json!({"type": ["string", "null"]}));
401            assert_eq!(ty, FieldType::Option(Box::new(FieldType::Text)));
402            let ty = FieldType::from_schema(
403                &serde_json::json!({"type": "array", "items": {"type": "integer"}}),
404            );
405            assert_eq!(ty, FieldType::List(Box::new(FieldType::Int)));
406        }
407    }
408}