Skip to main content

tilo_resource/
surface.rs

1//! A resource's public surface as data (`tilo_actions::surface`), read from
2//! its declarations and stored shape. `tilolang surface` writes it to the
3//! app's `surface.toml` and compiled `surface.json`, and `tilolang check` compares it with the code, so a
4//! rename or an incompatible storage change shows up in review, and it is
5//! what the OS knows about an app that is not running and what another
6//! language compiles its actions and types against.
7
8pub use tilo_actions::surface::{
9    CONTENT_VERBS, FieldSurface, FieldType, MIGRATE_VERB, NamedType, ParamSurface, ReturnsSurface,
10    Surface, TYPE_VERB, TypeCase, TypeField, TypeSet, VerbSurface,
11};
12
13pub mod file;
14
15use crate::resource::Resource;
16use crate::shape::Shape;
17use crate::vocabulary::{Declaration, vocabulary};
18
19/// A flattened parameter's record fields and their published types, by name, as the code
20/// declares them.
21pub type FlatTypes = fn(&mut TypeSet) -> Vec<(String, FieldType)>;
22
23/// The published parameters of an action, each typed by its Rust type when
24/// the code declares one and by its schema otherwise.
25fn params_of(
26    params: &[tilo_actions::ActionParam],
27    param_types: &[(&'static str, FieldTypeOf)],
28    flat_types: Option<FlatTypes>,
29    types: &mut TypeSet,
30) -> Vec<ParamSurface> {
31    // A flattened parameter is published as its record's own fields: their
32    // types are the ones the code declares, so a nested argument that is an
33    // enum names that enum rather than "any".
34    let flat: Vec<(String, FieldType)> = flat_types.map_or_else(Vec::new, |flat| flat(types));
35    params
36        .iter()
37        .map(|param| {
38            let schema = param
39                .schema
40                .as_deref()
41                .cloned()
42                .unwrap_or(serde_json::Value::Null);
43            let declared = param_types
44                .iter()
45                .find(|(name, _)| *name == param.name.as_ref());
46            let ty = if param.ty == tilo_actions::ParamType::Secret {
47                // What it takes is handed over once and kept nowhere, whatever Rust type holds it.
48                FieldType::Secret
49            } else {
50                match declared {
51                    Some((_, ty)) => ty(types),
52                    None => flat
53                        .iter()
54                        .find(|(name, _)| name == param.name.as_ref())
55                        .map_or_else(|| FieldType::from_schema(&schema), |(_, ty)| ty.clone()),
56                }
57            };
58            ParamSurface {
59                name: param.name.to_string(),
60                required: param.required,
61                schema,
62                ty,
63                within: None,
64            }
65        })
66        .collect()
67}
68
69/// The value an action answers with, from its result: a JSON value's schema
70/// and its type, typed by `declared` when the code declares one.
71fn returns_of(
72    result: Option<&tilo_actions::ResultSpec>,
73    declared: Option<FieldTypeOf>,
74    types: &mut TypeSet,
75) -> Option<ReturnsSurface> {
76    let tilo_actions::ResultSpec::Json { schema } = result? else {
77        return None;
78    };
79    Some(ReturnsSurface {
80        schema: schema.clone(),
81        ty: declared.map_or_else(|| FieldType::from_schema(schema), |ty| ty(types)),
82    })
83}
84
85fn verb_of(decl: &Declaration, types: &mut TypeSet) -> VerbSurface {
86    VerbSurface {
87        id: decl.id.to_owned(),
88        name: String::new(),
89        label: decl.shown_label(),
90        description: decl.description.clone(),
91        kind: decl.kind,
92        destructive: decl.destructive,
93        incoming_message: decl
94            .tags
95            .iter()
96            .any(|tag| tag == tilo_actions::INCOMING_MESSAGE_TAG),
97        params: params_of(&decl.params, &decl.param_types, decl.flat_types, types),
98        returns: returns_of(decl.result.as_ref(), decl.result_type, types),
99        writes: decl.writes.clone(),
100        field: decl.field.map(str::to_owned),
101        tags: Vec::new(),
102    }
103}
104
105/// A verb the framework writes under on a record of `shape`: its id, and the units of the
106/// record a change of it may write. It takes no parameters and answers nothing.
107fn framework_verb(id: &str, writes: Vec<String>) -> VerbSurface {
108    VerbSurface {
109        id: id.to_owned(),
110        name: String::new(),
111        label: String::new(),
112        description: None,
113        kind: crate::ActionKind::Undoable,
114        destructive: false,
115        incoming_message: false,
116        params: Vec::new(),
117        returns: None,
118        writes,
119        field: None,
120        tags: Vec::new(),
121    }
122}
123
124/// The units a change of `shape` may write: the record itself, and each field kept as its own
125/// storage unit (`tilo_resource::footprint`), a unit collection by any of its items.
126fn units_of(shape: Shape) -> Vec<String> {
127    let mut units = vec![tilo_actions::surface::RESOURCE_UNIT.to_owned()];
128    if let Shape::Record(fields) = shape {
129        for field in fields.iter().filter(|field| field.unit) {
130            let unit = match field.shape {
131                Shape::Collection(_) | Shape::Keyed(_) => format!("{}.*", field.key),
132                _ => field.key.to_owned(),
133            };
134            if !units.contains(&unit) {
135                units.push(unit);
136            }
137        }
138    }
139    units
140}
141
142/// Whether `shape` holds something a person changes directly, with no finer action: a field
143/// that is not read-only, beneath fields that are not either. A record whose every field is
144/// read-only changes only by its verbs.
145fn edits_content(shape: Shape) -> bool {
146    match shape {
147        Shape::Record(fields) => fields
148            .iter()
149            .any(|field| !field.readonly && edits_content(field.shape)),
150        Shape::Collection(_) | Shape::Keyed(_) | Shape::Map(_) | Shape::Value => true,
151    }
152}
153
154fn stored(shape: Shape) -> &'static str {
155    match shape {
156        // A map is published as the value it is written as.
157        Shape::Value | Shape::Map(_) => "value",
158        Shape::Record(_) => "record",
159        Shape::Collection(_) => "collection",
160        Shape::Keyed(_) => "keyed",
161    }
162}
163
164fn fields_of(shape: Shape, prefix: &str, types: &mut TypeSet, out: &mut Vec<FieldSurface>) {
165    let (fields, item) = match shape {
166        Shape::Record(fields) => (fields, false),
167        Shape::Collection(item) | Shape::Keyed(item) => {
168            fields_of(*item, &format!("{prefix}*."), types, out);
169            return;
170        }
171        Shape::Value | Shape::Map(_) => return,
172    };
173    let _ = item;
174    for field in fields {
175        let path = format!("{prefix}{}", field.key);
176        out.push(FieldSurface {
177            path: path.clone(),
178            owner: field.owner.to_owned(),
179            title: field.title.to_owned(),
180            stored: stored(field.shape).to_owned(),
181            ty: (field.field_type)(types),
182            readonly: field.readonly,
183            unit: field.unit,
184            label: field.label,
185            whole: false,
186            ops: None,
187        });
188        fields_of(field.shape, &format!("{path}."), types, out);
189    }
190}
191
192/// The surface of `R`, from its declarations and stored shape.
193#[must_use]
194pub fn surface_of<R: Resource>() -> Surface {
195    surface_in(vocabulary::<R>(), R::VERSION, R::MIGRATES)
196}
197
198/// [`surface_of`] the resource `vocabulary`, stored at `version`, with migrations when
199/// `migrates` says the type registers one.
200fn surface_in(vocabulary: &crate::Vocabulary, version: u32, migrates: bool) -> Surface {
201    let mut fields = Vec::new();
202    let mut types = TypeSet::new();
203    let shape = (vocabulary.shape)();
204    if let Some(shape) = shape {
205        fields_of(shape, "", &mut types, &mut fields);
206    }
207    for (path, schema) in (vocabulary.op_schemas)() {
208        if let Some(field) = fields.iter_mut().find(|field| field.path == path) {
209            field.ops = Some(schema);
210        }
211    }
212    let mut verbs = Vec::new();
213    for decl in vocabulary.declarations().iter() {
214        verbs.push(verb_of(decl, &mut types));
215    }
216    // The content the framework writes itself: direct edits with no finer action, and the
217    // migrations a record's type registers. A kind whose every field is read-only has neither.
218    if let Some(shape) = shape {
219        if edits_content(shape) {
220            verbs.push(framework_verb(TYPE_VERB, units_of(shape)));
221        }
222        if migrates {
223            verbs.push(framework_verb(MIGRATE_VERB, units_of(shape)));
224        }
225    }
226    Surface {
227        kind: vocabulary.kind.to_owned(),
228        label: vocabulary.label.to_owned(),
229        version,
230        person: false,
231        readers: reader_rule(vocabulary.readers),
232        verbs,
233        fields,
234        types: types.into_types(),
235        shows: Vec::new(),
236        live: None,
237        setters: false,
238    }
239}
240
241/// The rule `#[resource(readers = "...")]` wrote, which the macro checked:
242/// `None` for a kind every member reads.
243fn reader_rule(readers: &str) -> Option<tilo_actions::surface::ReaderRule> {
244    tilo_actions::surface::ReaderRule::parse(readers)
245}
246
247/// The surface of a resource a service publishes outside any record (the
248/// sound, the network, the battery): its fields are its reading `R`, as the
249/// service serialises it, each read-only since only the service's effects
250/// change it, and its verbs are the effects `E` it offers on it. What a
251/// view of another language reads and presses of it, typed as the service
252/// declares it.
253#[must_use]
254pub fn reading_surface<R: crate::JsonSchema, E: crate::Effect>(kind: &str, label: &str) -> Surface {
255    let mut types = TypeSet::new();
256    let root = R::field_type(&mut types);
257    let verbs: Vec<VerbSurface> = E::declarations()
258        .iter()
259        .map(|decl| effect_verb(decl, &mut types))
260        .collect();
261    let mut declared = types.into_types();
262    // The reading's own record is the resource itself: its fields are the
263    // resource's, and only the records it holds stay named types.
264    let own = match &root {
265        FieldType::Named(name) => declared
266            .iter()
267            .position(|ty| ty.name == *name && !ty.is_enum())
268            .map(|at| declared.remove(at)),
269        _ => None,
270    };
271    let fields = own
272        .map(|own| {
273            own.fields
274                .into_iter()
275                .map(|field| FieldSurface {
276                    path: field.name,
277                    owner: String::new(),
278                    title: field.title,
279                    stored: "value".to_owned(),
280                    ty: field.ty,
281                    readonly: true,
282                    unit: false,
283                    label: false,
284                    whole: false,
285                    ops: None,
286                })
287                .collect()
288        })
289        .unwrap_or_default();
290    Surface {
291        kind: kind.to_owned(),
292        label: label.to_owned(),
293        version: 1,
294        person: false,
295        readers: None,
296        verbs,
297        fields,
298        types: declared,
299        shows: Vec::new(),
300        live: None,
301        setters: false,
302    }
303}
304
305/// The surface of the row type `R`, whose rows a reading carries with their
306/// addresses ([`crate::Handle`]): its kind, its name, and the effects `E` it
307/// offers on each row, called on the row's address. Its fields are the
308/// record the reading declares for it, so it lists none of its own.
309#[must_use]
310pub fn row_surface<R: crate::words::RowType, E: crate::Effect>() -> Surface {
311    let mut types = TypeSet::new();
312    let verbs = E::declarations()
313        .iter()
314        .map(|decl| effect_verb(decl, &mut types))
315        .collect();
316    Surface {
317        kind: R::KIND.to_owned(),
318        label: R::LABEL.to_owned(),
319        version: 1,
320        person: false,
321        readers: None,
322        verbs,
323        fields: Vec::new(),
324        types: types.into_types(),
325        shows: Vec::new(),
326        live: None,
327        setters: false,
328    }
329}
330
331/// An effect's declaration as a verb of the surface: its id, words,
332/// parameters and the value it answers with, each typed by its schema.
333#[must_use]
334pub fn effect_verb(decl: &crate::EffectDecl, types: &mut TypeSet) -> VerbSurface {
335    VerbSurface {
336        id: decl.id.to_owned(),
337        name: String::new(),
338        label: decl.label.read(),
339        description: (!decl.description.is_empty()).then(|| decl.description.to_owned()),
340        kind: decl.action_kind,
341        destructive: decl.risk == tilo_actions::RiskLevel::Destructive,
342        incoming_message: false,
343        params: params_of(&decl.params, &decl.param_types, None, types),
344        returns: decl.result.map(|result| ReturnsSurface {
345            schema: (result.schema)(),
346            ty: result.ty.map_or_else(|| FieldType::Any, |ty| ty(types)),
347        }),
348        writes: vec!["record".to_owned()],
349        field: None,
350        tags: Vec::new(),
351    }
352}
353
354/// The ids of an app's effects that show something in its window
355/// (`#[effect(view)]`): what its surface declares it [`Surface::shows`].
356#[must_use]
357pub fn view_effects(rows: &[crate::effect::EffectRow]) -> Vec<String> {
358    let mut shows: Vec<String> = rows
359        .iter()
360        .filter(|row| row.kind == tilo_actions::OperationKind::View)
361        .map(|row| row.id.to_owned())
362        .collect();
363    shows.sort();
364    shows.dedup();
365    shows
366}
367
368/// An app's effects as actions a caller of another language reads: every one
369/// that only reads (`kind = "read"`) and that is offered on the app's own
370/// resource, answering with the value it declares. An effect offered on a row
371/// of a declared type is one of them: the resource's action, its parameter
372/// naming the row it acts on. What its window shows (a view's zoom, its caret)
373/// is no action of the catalogue, and neither is one offered on an item of the
374/// resource's collection: that is published on the item itself.
375#[must_use]
376pub fn effect_verbs(rows: &[crate::effect::EffectRow], types: &mut TypeSet) -> Vec<VerbSurface> {
377    rows.iter()
378        .filter(|row| row.kind != tilo_actions::OperationKind::View)
379        .filter(|row| row.action_kind == crate::ActionKind::Read)
380        .filter(|row| !row.row)
381        .filter(|row| {
382            !row.items
383                .iter()
384                .any(|target| matches!(target, crate::effect::EffectTarget::Field(_)))
385        })
386        .map(|row| effect_verb(&crate::EffectDecl::of_row(row), types))
387        .collect()
388}
389
390/// The type of a record of `shape` named `name` (the Rust type `identity`):
391/// what `#[derive(Model)]` publishes for a struct, its fields read from its
392/// shape.
393#[doc(hidden)]
394pub fn resource_type(
395    types: &mut TypeSet,
396    identity: &str,
397    name: &str,
398    doc: &str,
399    shape: Shape,
400) -> FieldType {
401    types.named(identity, name, |types| NamedType {
402        name: name.to_owned(),
403        doc: doc.to_owned(),
404        fields: shape
405            .fields()
406            .iter()
407            .map(|field| TypeField {
408                name: field.key.to_owned(),
409                ty: (field.field_type)(types),
410                title: field.title.to_owned(),
411            })
412            .collect(),
413        cases: Vec::new(),
414    })
415}
416
417/// How a value's [`FieldType`] is worked out, declaring the records and
418/// enums it names: a type's `field_type`.
419pub type FieldTypeOf = fn(&mut TypeSet) -> FieldType;
420
421/// The type of a record named `name` (the Rust type `identity`) with the
422/// fields `fields`, their names and types: what `#[derive(JsonSchema)]`
423/// publishes for a struct.
424#[doc(hidden)]
425pub fn resource_of(
426    types: &mut TypeSet,
427    identity: &str,
428    name: &str,
429    doc: &str,
430    fields: &[(&str, FieldTypeOf)],
431) -> FieldType {
432    types.named(identity, name, |types| NamedType {
433        name: name.to_owned(),
434        doc: doc.to_owned(),
435        fields: fields
436            .iter()
437            .map(|(field, ty)| TypeField {
438                name: (*field).to_owned(),
439                ty: ty(types),
440                title: String::new(),
441            })
442            .collect(),
443        cases: Vec::new(),
444    })
445}
446
447/// One case of an enum as a derive lists it: its stored name, how it reads
448/// (empty: its name in words), and its fields' keys with their types.
449#[doc(hidden)]
450pub type CaseOf<'a> = (&'a str, &'a str, &'a [(&'a str, FieldTypeOf)]);
451
452/// The type of an enum named `name` (the Rust type `identity`) with the
453/// cases `cases`: what `#[derive(Model)]` and `#[derive(JsonSchema)]`
454/// publish for an enum.
455#[doc(hidden)]
456pub fn enum_type(
457    types: &mut TypeSet,
458    identity: &str,
459    name: &str,
460    doc: &str,
461    cases: &[CaseOf<'_>],
462) -> FieldType {
463    types.named(identity, name, |types| NamedType {
464        name: name.to_owned(),
465        doc: doc.to_owned(),
466        fields: Vec::new(),
467        cases: cases
468            .iter()
469            .map(|(case, label, fields)| TypeCase {
470                name: (*case).to_owned(),
471                label: if label.is_empty() {
472                    tilo_actions::field_type::label_of(case)
473                } else {
474                    (*label).trim_end_matches('.').to_owned()
475                },
476                fields: fields
477                    .iter()
478                    .map(|(field, ty)| TypeField {
479                        name: (*field).to_owned(),
480                        ty: ty(types),
481                        title: String::new(),
482                    })
483                    .collect(),
484            })
485            .collect(),
486    })
487}