Skip to main content

tilo_actions/
surface.rs

1//! A resource kind's public surface as data: its verbs with their
2//! parameters, kinds and the value each answers with, and its fields with
3//! their schema. An app's `surface.toml` holds it (written by `tilolang
4//! surface` from the code), and it is what a receiver without the app knows
5//! about the app's changes, and what another language compiles its actions
6//! and types against.
7//!
8//! The file keeps what receipt and the storage check need. The labels,
9//! descriptions, field titles and owners the code reports are for people and
10//! history; `tilolang surface` leaves them out of the file, so they read as
11//! empty here.
12
13use serde::{Deserialize, Serialize};
14
15use crate::PathStep;
16pub use crate::field_type::{FieldType, NamedType, TypeCase, TypeField, TypeSet};
17use tilo_action_policy::ActionKind;
18
19#[allow(
20    clippy::trivially_copy_pass_by_ref,
21    reason = "serde's skip_serializing_if passes the field by reference"
22)]
23const fn is_false(value: &bool) -> bool {
24    !*value
25}
26
27/// The record unit, as footprints and unit indexes name it.
28pub const RESOURCE_UNIT: &str = "record";
29
30/// The verb of a change that writes a record's content directly, with no finer action: typing
31/// in a cell, a list splice made from the window. The framework stamps such a change with it.
32pub const TYPE_VERB: &str = "type";
33
34/// The verb of the framework's storage migration of a record (`tilo_resource::evolution`).
35pub const MIGRATE_VERB: &str = "migrate";
36
37/// The verbs the framework writes under on every record kind, which no app's action publishes:
38/// a direct content edit ([`TYPE_VERB`]) and a storage migration ([`MIGRATE_VERB`]).
39pub const CONTENT_VERBS: [&str; 2] = [TYPE_VERB, MIGRATE_VERB];
40
41/// The key under which a record of a reading that is a resource of its own (a Wi-Fi network in
42/// the network's reading) carries its address. Its type declares it as a field of that name,
43/// typed [`FieldType::Resource`] of the record's kind, and the kind's own surface lists the
44/// actions offered on it: a caller of another language calls them on that address, the way any
45/// caller does, so a row's `join` is its own action and never a root action taking its name.
46pub const ADDRESS_KEY: &str = "$address";
47
48/// The record kind in which the framework keeps each member's actions waiting
49/// for the part of a chain they go to (an app whose records are a chain's
50/// parts): one record per member, which an app keeping chains declares its
51/// members' own (`[resources] own`), so their waiting actions reach their own
52/// devices and nobody else's.
53pub const CHAIN_UNSENT_KIND: &str = "tilo.chain-unsent";
54
55/// The public surface of one resource kind. See the module docs.
56#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
57pub struct Surface {
58    pub kind: String,
59    pub label: String,
60    /// The storage version (`#[resource(version = N)]`).
61    pub version: u32,
62    /// A record of the person's own, kept in their store rather than the
63    /// workspace of the window showing it: one the app declares with itself
64    /// (its `ResourceApp::PERSON_RESOURCES`, as `PersonKind::profile`). Only
65    /// the kinds an app's surface marks so may it keep in, or read from, the
66    /// person's store.
67    #[serde(default, skip_serializing_if = "is_false")]
68    pub person: bool,
69    /// Who reads a record of the kind, when not every member of the workspace (core.md, "One set
70    /// of resources per workspace"): each record is sealed to exactly its readers' key group, and
71    /// the store works out who they are ([`ReaderRule`]). Absent for a kind every member reads.
72    #[serde(default, skip_serializing_if = "Option::is_none")]
73    pub readers: Option<ReaderRule>,
74    /// Absent from a surface file that lists none.
75    #[serde(default)]
76    pub verbs: Vec<VerbSurface>,
77    /// Every stored field, depth first; empty for a resource without a
78    /// model shape.
79    #[serde(default)]
80    pub fields: Vec<FieldSurface>,
81    /// The records and enums its fields' types name ([`FieldType::Named`]),
82    /// each declared once, by name.
83    #[serde(default, skip_serializing_if = "Vec::is_empty")]
84    pub types: Vec<NamedType>,
85    /// The actions that show something in a window of the app (its view
86    /// effects), on whatever resource of it they are invoked: a row the app
87    /// publishes for one person or item as much as the app itself. A closed
88    /// app asked for one is started with a window.
89    #[serde(default, skip_serializing_if = "Vec::is_empty")]
90    pub shows: Vec<String>,
91    /// When a resource of the kind is a live activity (a track playing, a timer running), and
92    /// the view that shows it then; `None` for a kind that never is.
93    #[serde(default, skip_serializing_if = "Option::is_none")]
94    pub live: Option<LiveSurface>,
95    /// Each of its fields is written by its own setter, `set-<field>`, and
96    /// by no field edit: the setters follow from the fields
97    /// ([`Self::with_setters`]), as a settings section publishes them.
98    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
99    pub setters: bool,
100}
101
102/// When a resource of a kind is live, as the resource index keeps it: what its type says
103/// (`live when state == .playing`) as filters over the fields the index holds, every one of
104/// which holds of a live resource.
105#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
106pub struct LiveSurface {
107    /// The store's filters (`collab_types::store::Filter`) as JSON: this crate does not know the
108    /// store's types, and the store reads them back when it declares the kind.
109    pub when: serde_json::Value,
110    /// The name of the view the shell shows a live resource with.
111    pub view: String,
112}
113
114pub use tilo_action_policy::ReaderRule;
115
116/// One verb.
117#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
118pub struct VerbSurface {
119    pub id: String,
120    /// The name the action API offers this action by, where that is not `id`: a tilolang app
121    /// offers its actions by the name its code declares (`new_note`), while a change of one
122    /// claims the id the declaration keeps (`qymo5lg2`), which is what a receiver holding the
123    /// surface decides it by. Empty where the two are the same, as for a native verb.
124    #[serde(default, skip_serializing_if = "String::is_empty")]
125    pub name: String,
126    #[serde(default, skip_serializing_if = "String::is_empty")]
127    pub label: String,
128    #[serde(default, skip_serializing_if = "Option::is_none")]
129    pub description: Option<String>,
130    pub kind: ActionKind,
131    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
132    pub destructive: bool,
133    /// It records a message someone received, so an incoming-message
134    /// trigger fires on its changes
135    /// ([`INCOMING_MESSAGE_TAG`](crate::INCOMING_MESSAGE_TAG)).
136    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
137    pub incoming_message: bool,
138    /// Left out of a surface file when it takes none.
139    #[serde(default)]
140    pub params: Vec<ParamSurface>,
141    /// What it answers its caller with, when it answers a value: a read
142    /// effect's fields, a verb's record. Absent when it answers nothing or a
143    /// job.
144    #[serde(default, skip_serializing_if = "Option::is_none")]
145    pub returns: Option<ReturnsSurface>,
146    /// The units it writes (`tilo_resource::footprint`), when more than the
147    /// record unit.
148    #[serde(default = "record_unit", skip_serializing_if = "only_resource")]
149    pub writes: Vec<String>,
150    /// The field it sits under in the tree (`#[action(field = "...")]`): a
151    /// comment verb under the comments it writes.
152    #[serde(default, skip_serializing_if = "Option::is_none")]
153    pub field: Option<String>,
154    /// The tags its declaration carries ([`crate::SECRET_ANSWER_TAG`]): what a host reading the
155    /// surface knows of the action without running the app.
156    #[serde(default, skip_serializing_if = "Vec::is_empty")]
157    pub tags: Vec<String>,
158}
159
160fn stored_value() -> String {
161    STORED_VALUE.to_owned()
162}
163
164impl VerbSurface {
165    /// The name the action API offers this action by: [`Self::name`], or [`Self::id`] where the
166    /// two are the same.
167    #[must_use]
168    pub fn offered(&self) -> &str {
169        if self.name.is_empty() {
170            &self.id
171        } else {
172            &self.name
173        }
174    }
175}
176
177/// How a field holding a plain value is stored.
178pub const STORED_VALUE: &str = "value";
179
180fn record_unit() -> Vec<String> {
181    vec![RESOURCE_UNIT.to_owned()]
182}
183
184fn only_resource(units: &[String]) -> bool {
185    units == [RESOURCE_UNIT]
186}
187
188/// One parameter of a verb.
189#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
190pub struct ParamSurface {
191    pub name: String,
192    pub required: bool,
193    /// Its JSON Schema, from its type.
194    #[serde(default, skip_serializing_if = "serde_json::Value::is_null")]
195    pub schema: serde_json::Value,
196    /// Its type ([`FieldType`]), its named records and enums declared in
197    /// the surface's types; left out of a file, and absent from one written
198    /// before parameters had it, when the schema says all there is.
199    #[serde(
200        rename = "type",
201        default,
202        skip_serializing_if = "FieldType::is_any",
203        deserialize_with = "crate::field_type::field_type_or_text"
204    )]
205    pub ty: FieldType,
206    /// The parameter this one is a field of on the wire: a parameter that is a plain record
207    /// of named fields is published as those fields, and a call's arguments for them travel
208    /// nested under its name again ([`nest_arguments`]).
209    #[serde(default, skip_serializing_if = "Option::is_none")]
210    pub within: Option<String>,
211}
212
213/// What an action answers its caller with: its JSON Schema, and its type
214/// ([`FieldType`]) with the records and enums it names declared in the
215/// surface's types.
216///
217/// A surface is what another language compiles against, so the value an
218/// action gives back has to be described as precisely as it takes: a script
219/// reads the fields of a PDF's form without opening the PDF.
220#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
221pub struct ReturnsSurface {
222    /// Its JSON Schema, from its type.
223    #[serde(default, skip_serializing_if = "serde_json::Value::is_null")]
224    pub schema: serde_json::Value,
225    /// Its type, left out when the schema says all there is (`any`).
226    #[serde(
227        rename = "type",
228        default,
229        skip_serializing_if = "FieldType::is_any",
230        deserialize_with = "crate::field_type::field_type_or_text"
231    )]
232    pub ty: FieldType,
233}
234
235/// The type a parameter is published as, from its wire type. A resource is a resource of the
236/// kind it names, or of any kind: code passes the value it has, never its id's text. An object
237/// or a list says nothing more than its schema does ([`FieldType::Any`]).
238#[must_use]
239pub fn param_type(param: &crate::ActionParam) -> FieldType {
240    use crate::ParamType;
241    match param.ty {
242        ParamType::Text | ParamType::DateTime => FieldType::Text,
243        ParamType::Secret => FieldType::Secret,
244        ParamType::Resource => {
245            FieldType::Resource(param.resource_kind().unwrap_or_default().to_owned())
246        }
247        ParamType::Integer => FieldType::Int,
248        ParamType::Number => FieldType::Float,
249        ParamType::Boolean => FieldType::Bool,
250        // A list or object whose schema says what it holds is typed by it, so code can give it
251        // (`List<Text>`); one that says nothing is any JSON value.
252        ParamType::Object | ParamType::Array => param
253            .schema
254            .as_deref()
255            .map_or(FieldType::Any, FieldType::from_schema),
256    }
257}
258
259/// `action` as a verb taking `params`: its id and kind, and whether it destroys. The words a
260/// person reads of it are the catalogue's, not the surface's.
261#[must_use]
262pub fn verb_of(action: &crate::ActionSpec, params: Vec<ParamSurface>) -> VerbSurface {
263    VerbSurface {
264        id: action.id.clone(),
265        name: String::new(),
266        label: String::new(),
267        description: None,
268        kind: action.contract.settled_kind(),
269        destructive: action.contract.risk == crate::RiskLevel::Destructive,
270        incoming_message: false,
271        params,
272        returns: result_of(&action.contract.result),
273        writes: record_unit(),
274        field: None,
275        tags: Vec::new(),
276    }
277}
278
279/// What an action answers, as its surface says it: a call the surface declares a result for
280/// reads it back in tilolang.
281fn result_of(result: &crate::ResultSpec) -> Option<ReturnsSurface> {
282    match result {
283        crate::ResultSpec::Json { schema } => Some(ReturnsSurface {
284            schema: schema.clone(),
285            ty: crate::field_type::FieldType::from_schema(schema),
286        }),
287        crate::ResultSpec::None | crate::ResultSpec::Resource { .. } | crate::ResultSpec::Job => {
288            None
289        }
290    }
291}
292
293/// The resource `spec` as a surface: its kind and a verb for each of its actions, each
294/// parameter typed by its wire type ([`param_type`]). What a provider publishing it at a fixed
295/// address is compiled against: it stores no fields, so its verbs are called at that address.
296#[must_use]
297pub fn of_resource(spec: &crate::ResourceSpec) -> Surface {
298    let verbs = spec
299        .actions
300        .iter()
301        .map(|action| {
302            let params = action
303                .params()
304                .iter()
305                .map(|param| ParamSurface {
306                    name: param.name.to_string(),
307                    required: param.required,
308                    schema: serde_json::Value::Null,
309                    ty: param_type(param),
310                    within: None,
311                })
312                .collect();
313            verb_of(action, params)
314        })
315        .collect();
316    Surface {
317        kind: spec.kind.clone(),
318        label: String::new(),
319        version: 0,
320        person: false,
321        readers: None,
322        verbs,
323        fields: Vec::new(),
324        types: Vec::new(),
325        shows: Vec::new(),
326        live: None,
327        setters: false,
328    }
329}
330
331/// The arguments of a call of `verb`, as `(name, value)`, with each argument of a parameter
332/// published as a field of another ([`ParamSurface::within`]) nested back under that
333/// parameter's name: what the action's API reads.
334#[must_use]
335pub fn nest_arguments(
336    verb: &VerbSurface,
337    arguments: Vec<(String, serde_json::Value)>,
338) -> serde_json::Map<String, serde_json::Value> {
339    let mut out = serde_json::Map::new();
340    for (name, value) in arguments {
341        let within = verb
342            .params
343            .iter()
344            .find(|param| param.name == name)
345            .and_then(|param| param.within.clone());
346        match within {
347            Some(outer) => {
348                let nested = out
349                    .entry(outer)
350                    .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
351                if let serde_json::Value::Object(fields) = nested {
352                    fields.insert(name, value);
353                }
354            }
355            None => {
356                out.insert(name, value);
357            }
358        }
359    }
360    out
361}
362
363/// One stored field.
364#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
365#[expect(
366    clippy::struct_excessive_bools,
367    reason = "each flag is one mark a committed surface file writes for the field, read on its own"
368)]
369pub struct FieldSurface {
370    /// Where it is: stored keys from the root, `*` for every item of a
371    /// collection (`snippets.*.title`).
372    pub path: String,
373    /// The record type it belongs to, kebab case.
374    #[serde(default, skip_serializing_if = "String::is_empty")]
375    pub owner: String,
376    #[serde(default, skip_serializing_if = "String::is_empty")]
377    pub title: String,
378    /// How it is stored: `value` (left out of a surface file), `record` or
379    /// `collection`.
380    #[serde(default = "stored_value")]
381    pub stored: String,
382    /// Its type ([`FieldType`]); a surface file written before the
383    /// vocabulary holds its Rust type's text, read as
384    /// [`FieldType::from_rust_text`].
385    #[serde(
386        rename = "type",
387        deserialize_with = "crate::field_type::field_type_or_text"
388    )]
389    pub ty: FieldType,
390    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
391    pub readonly: bool,
392    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
393    pub unit: bool,
394    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
395    pub label: bool,
396    /// Set only whole: a change inside it could weaken the person's security,
397    /// so its setter takes no edit inside it ([`Surface::with_setters`]).
398    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
399    pub whole: bool,
400    /// The schema of the field's own operations, for a type with its own
401    /// vocabulary (rich text).
402    #[serde(default, skip_serializing_if = "Option::is_none")]
403    pub ops: Option<serde_json::Value>,
404}
405
406/// The verb that sets the field `key` whole: `set-<key>`, in kebab case.
407#[must_use]
408pub fn setter_id(key: &str) -> String {
409    format!("set-{}", key.replace('_', "-"))
410}
411
412/// What a receiver without the app reads from its surface: each verb's kind
413/// and tree field, which paths offer field edits, and which storage units
414/// an action may write (`*` for any item).
415impl Surface {
416    /// This surface with a setter of each of its own fields that is not read
417    /// only and has no declared verb of the setter's id, as a settings section
418    /// publishes them: [`setter_id`], taking the field's whole new `value` (not
419    /// for a collection or a keyed map, which change item by item) and, unless
420    /// the field is set only [`FieldSurface::whole`], an `edit` inside it.
421    #[must_use]
422    pub fn with_setters(mut self) -> Self {
423        let setters: Vec<VerbSurface> = self
424            .fields
425            .iter()
426            .filter(|field| !field.readonly && !field.path.contains('.'))
427            .map(|field| (setter_id(&field.path), field))
428            .filter(|(id, _)| !self.verbs.iter().any(|verb| verb.id == *id))
429            .map(|(id, field)| {
430                let param = |name: &str, ty: FieldType| ParamSurface {
431                    name: name.to_owned(),
432                    required: false,
433                    schema: serde_json::Value::Null,
434                    ty,
435                    within: None,
436                };
437                let mut params = Vec::new();
438                if !matches!(field.stored.as_str(), "collection" | "keyed") {
439                    params.push(param("value", field.ty.clone()));
440                }
441                if !field.whole {
442                    params.push(param("edit", FieldType::Any));
443                }
444                VerbSurface {
445                    id,
446                    name: String::new(),
447                    label: format!("Set {}", field.path.replace('_', " ")),
448                    description: None,
449                    kind: ActionKind::Undoable,
450                    destructive: false,
451                    incoming_message: false,
452                    params,
453                    returns: None,
454                    writes: vec![RESOURCE_UNIT.to_owned()],
455                    field: None,
456                    tags: Vec::new(),
457                }
458            })
459            .collect();
460        self.verbs.extend(setters);
461        self
462    }
463
464    /// The named type `name` of [`Self::types`].
465    #[must_use]
466    pub fn named(&self, name: &str) -> Option<&NamedType> {
467        self.types.iter().find(|ty| ty.name == name)
468    }
469
470    /// The kind of the verb `action` and the field it sits under, or `None`
471    /// when the app publishes no such verb.
472    #[must_use]
473    pub fn verb(&self, action: &str) -> Option<(ActionKind, Option<String>)> {
474        self.verbs
475            .iter()
476            .find(|verb| verb.id == action)
477            .map(|verb| (verb.kind, verb.field.clone()))
478    }
479
480    /// The stored field a path (from the record's root) reaches: the
481    /// deepest one its steps name, items and keys as `*`.
482    fn field_at(&self, path: &[PathStep]) -> Option<&FieldSurface> {
483        let mut dotted = String::new();
484        let mut found = None;
485        for step in path {
486            let part = match step {
487                PathStep::Field(key) => key.as_str(),
488                PathStep::Item(_) | PathStep::Key(_) | PathStep::Cell(..) => "*",
489            };
490            if !dotted.is_empty() {
491                dotted.push('.');
492            }
493            dotted.push_str(part);
494            if let Some(field) = self.fields.iter().find(|field| field.path == dotted) {
495                found = Some(field);
496            }
497        }
498        found
499    }
500
501    /// Whether the field at `path` offers edits: stored, and neither it nor
502    /// a field above it read-only. Reactions are the exception: their only
503    /// edits record who invoked them, so they forge nothing a read-only
504    /// field protects, and the record refuses any other edit of them.
505    #[must_use]
506    pub fn editable(&self, path: &[PathStep]) -> bool {
507        let Some(field) = self.field_at(path) else {
508            return false;
509        };
510        if field.ty.is_reactions() {
511            return true;
512        }
513        !self.fields.iter().any(|candidate| {
514            candidate.readonly
515                && (field.path == candidate.path
516                    || field.path.starts_with(&format!("{}.", candidate.path)))
517        })
518    }
519
520    /// The storage unit a field edit at `path` writes: the field's unit, an
521    /// item of a unit collection, else the record (the empty path).
522    #[must_use]
523    pub fn edit_unit(&self, path: &[PathStep]) -> Vec<PathStep> {
524        let mut dotted = String::new();
525        let mut unit = Vec::new();
526        for (index, step) in path.iter().enumerate() {
527            let PathStep::Field(key) = step else {
528                if !dotted.is_empty() {
529                    dotted.push('.');
530                }
531                dotted.push('*');
532                continue;
533            };
534            if !dotted.is_empty() {
535                dotted.push('.');
536            }
537            dotted.push_str(key);
538            let Some(field) = self.fields.iter().find(|field| field.path == dotted) else {
539                continue;
540            };
541            if field.unit {
542                let through = if matches!(field.stored.as_str(), "collection" | "keyed") {
543                    index.saturating_add(2)
544                } else {
545                    index.saturating_add(1)
546                };
547                unit = path.iter().take(through).cloned().collect();
548            }
549        }
550        unit
551    }
552
553    /// The units the verb `action` may write, on the item `item` when it
554    /// acts on one: the record (the empty path), its item's unit, and the
555    /// units of the fields it declares, `*` for any item.
556    #[must_use]
557    pub fn footprint(&self, action: &str, item: Option<&str>) -> Vec<Vec<PathStep>> {
558        let Some(verb) = self.verbs.iter().find(|verb| verb.id == action) else {
559            return Vec::new();
560        };
561        verb.writes
562            .iter()
563            .map(|unit| {
564                if unit == RESOURCE_UNIT {
565                    return Vec::new();
566                }
567                match unit.strip_suffix(".*") {
568                    Some(field) => vec![
569                        PathStep::Field(field.to_owned()),
570                        PathStep::Item(item.unwrap_or("*").to_owned()),
571                    ],
572                    None => vec![PathStep::Field(unit.clone())],
573                }
574            })
575            .collect()
576    }
577}