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