Skip to main content

tilo_resource/
vocabulary.rs

1//! A resource type's actions with the type erased.
2//!
3//! What the framework publishes for a resource — its declared actions,
4//! `apply`, `group`, field edits, item resources and their schemas — is the
5//! same for every resource, apart from a few facts and functions of the
6//! type: its kind and label, its declarations, how a JSON value or a field
7//! edit becomes one of its actions. A [`Vocabulary`] gathers those once per
8//! type and a [`Built`] carries one of its actions without its type, so the
9//! publishing code is compiled once rather than once per resource of every
10//! app.
11
12use std::any::{Any, TypeId};
13use std::cell::RefCell;
14use std::collections::HashMap;
15use std::rc::Rc;
16use std::sync::Arc;
17
18use tilo_actions::{
19    ActionArgs, ActionError, ActionNeed, ActionParam, ActionSpec, EncodedAction, ResourceViewSpec,
20    RiskLevel,
21};
22
23use crate::action::ActionKind;
24use crate::collection::Id;
25use crate::path::Edit;
26use crate::resource::Resource;
27use crate::shape::Shape;
28
29/// One action of some resource, built and not yet encoded.
30pub struct Built(Box<dyn AnyAction>);
31
32/// What the framework does with a built action, whatever its type.
33trait AnyAction {
34    fn stamp(&mut self, now_ms: i64);
35    fn action_type(&self) -> &'static str;
36    fn write_json(&self, out: &mut Vec<u8>) -> Result<(), serde_json::Error>;
37    fn need(&self) -> ActionNeed;
38    fn risk(&self) -> RiskLevel;
39    fn undoable(&self) -> bool;
40    fn by_app(&self) -> bool;
41    fn into_any(self: Box<Self>) -> Box<dyn Any>;
42}
43
44struct Typed<R: Resource>(R::Action);
45
46impl<R: Resource> AnyAction for Typed<R> {
47    fn stamp(&mut self, now_ms: i64) {
48        R::stamp(&mut self.0, now_ms);
49    }
50
51    fn action_type(&self) -> &'static str {
52        R::ACTION_TYPE
53    }
54
55    fn write_json(&self, out: &mut Vec<u8>) -> Result<(), serde_json::Error> {
56        serde_json::to_writer(out, &self.0)
57    }
58
59    fn need(&self) -> ActionNeed {
60        crate::resource::need_of::<R>(&self.0)
61    }
62
63    fn risk(&self) -> RiskLevel {
64        tilo_actions::Action::risk(&self.0)
65    }
66
67    fn undoable(&self) -> bool {
68        tilo_actions::undo_takes_back(
69            tilo_actions::Action::action_kind(&self.0),
70            tilo_actions::Action::change_kind(&self.0),
71            tilo_actions::Action::irreversible(&self.0),
72        )
73    }
74
75    fn by_app(&self) -> bool {
76        R::by_app(&self.0)
77    }
78
79    fn into_any(self: Box<Self>) -> Box<dyn Any> {
80        Box::new(self.0)
81    }
82}
83
84impl Built {
85    #[must_use]
86    pub fn of<R: Resource>(action: R::Action) -> Self {
87        Self(Box::new(Typed::<R>(action)))
88    }
89
90    /// Stamp the origin's clock on it ([`Resource::stamp`]).
91    pub fn stamp(&mut self, now_ms: i64) {
92        self.0.stamp(now_ms);
93    }
94
95    /// What it is, for the grants deciding it ([`crate::need_of`]).
96    #[must_use]
97    pub fn need(&self) -> ActionNeed {
98        self.0.need()
99    }
100
101    /// Its consequence class.
102    #[must_use]
103    pub fn risk(&self) -> RiskLevel {
104        self.0.risk()
105    }
106
107    /// Whether Undo takes it back: a person's change of the document alone.
108    #[must_use]
109    pub fn undoable(&self) -> bool {
110        self.0.undoable()
111    }
112
113    /// Whether only the app's own code applies it
114    /// ([`Resource::by_app`]): no caller's value is one.
115    #[must_use]
116    pub fn by_app(&self) -> bool {
117        self.0.by_app()
118    }
119
120    /// Encoded under its resource's registry type id.
121    ///
122    /// # Errors
123    /// Returns [`ActionError::Encode`] when the action does not serialize.
124    pub fn encode(&self) -> Result<EncodedAction, ActionError> {
125        let mut payload = Vec::with_capacity(128);
126        self.0
127            .write_json(&mut payload)
128            .map_err(ActionError::Encode)?;
129        Ok(EncodedAction {
130            type_id: self.0.action_type().to_owned(),
131            payload,
132        })
133    }
134
135    /// Its JSON form, appended to `out`.
136    pub(crate) fn write_json(&self, out: &mut Vec<u8>) -> Result<(), serde_json::Error> {
137        self.0.write_json(out)
138    }
139
140    /// The action as the type of the resource `R` it was built for; `None`
141    /// when it is another resource's.
142    #[must_use]
143    pub fn into_action<R: Resource>(self) -> Option<R::Action> {
144        self.0
145            .into_any()
146            .downcast::<R::Action>()
147            .ok()
148            .map(|action| *action)
149    }
150}
151
152/// Builds a resource's action from arguments already bound against the
153/// declaration's parameters. `now_ms` is the origin's clock, captured once so
154/// replay is deterministic.
155pub type Builds = Arc<dyn Fn(&ActionArgs, i64) -> Result<Built, String> + Send + Sync>;
156
157/// One mutation offered by name, of whichever resource: what
158/// [`ActionDecl`](crate::ActionDecl) holds for its resource type.
159#[derive(Clone)]
160pub struct Declaration {
161    pub id: &'static str,
162    /// What a person reads it by, in the language it was declared in.
163    pub label: String,
164    /// The declared word [`Self::label`] is the source text of, read in the
165    /// person's language each time the action is published.
166    pub word: Option<crate::label::Word>,
167    /// The other words people use for the action
168    /// ([`tilo_actions::ActionSpec::keywords`]).
169    pub keywords: Vec<String>,
170    /// The action's own picture, by its Lucide name
171    /// ([`tilo_actions::ActionSpec::icon`]).
172    pub icon: Option<String>,
173    /// What the action did, in the app's own words
174    /// (`did = "renamed"`): the past-tense form a record of what was done
175    /// reads ([`tilo_actions::ActionSpec::did`]).
176    pub did: Option<String>,
177    pub description: Option<String>,
178    pub params: Vec<ActionParam>,
179    /// What the action is able to do. See [`tilo_actions::ActionContract::kind`].
180    pub kind: ActionKind,
181    /// Whether one invocation's kind is decided by its arguments, `kind`
182    /// being the least it is: every check asks the action built from them.
183    pub by_arguments: bool,
184    /// The one field it writes, if only one. See [`Resource::field_of`].
185    pub field: Option<&'static str>,
186    pub destructive: bool,
187    /// What the action answers its caller with, beside the change: the state
188    /// it left, as the declaring resource's surface reports it.
189    pub result: Option<tilo_actions::ResultSpec>,
190    /// Contract tags its callers read: a precondition on the invoker's view
191    /// (`ContextRequirement`), a text that may arrive in parts.
192    pub tags: Vec<String>,
193    /// The prompt of an action whose one input is content another action
194    /// produced (an image to place), carried by its callers rather than
195    /// typed: the build reads its content hash as the
196    /// [`PROMPTED_PARAM`](tilo_actions::PROMPTED_PARAM) argument.
197    pub content: Option<String>,
198    /// A bound edit that refines the resource's declared action of the same
199    /// id: it builds the same action from the same arguments, and also
200    /// places its invoker (the caret an append leaves its writer at).
201    /// See [`bind_declaration`](crate::bind_declaration).
202    pub refines: bool,
203    /// The kind of step it takes, as it declares it
204    /// ([`tilo_actions::StepKind`]), published with its contract.
205    pub step: Option<tilo_actions::StepKind>,
206    /// The collection of its resource it adds to, when it is a create whose
207    /// declaration names one (`writes = issues`): what the step makes, so a
208    /// surface says that collection's own noun ("Creating an issue in Issues").
209    pub creates: Option<&'static str>,
210    /// The collection whose item it acts on, when it is an item verb
211    /// (`#[action(item = issues)]`): published on the resource itself, it
212    /// says it needs an item ([`tilo_actions::ActionContract::item`]), and
213    /// each item offers it with the item bound.
214    pub item: Option<&'static str>,
215    /// The units the action writes ([`crate::footprint`]): `record`, an
216    /// item's unit, declared fields'.
217    pub writes: Vec<String>,
218    /// The kind of resource it is declared on ([`Resource::KIND`]).
219    pub resource: &'static str,
220    /// The registry type id the action it builds replays under
221    /// ([`Resource::ACTION_TYPE`]).
222    pub action_type: &'static str,
223    pub build: Builds,
224    /// The resource's own published action this one invokes, and the
225    /// arguments it fixes of it: a bound field edit is the resource's field
226    /// edit of that edit, a bound verb that verb with its bound values. What
227    /// another provider keeping the resource runs it as.
228    pub invokes: Option<(String, serde_json::Map<String, serde_json::Value>)>,
229    /// The type of each parameter the code declares by its Rust type
230    /// ([`JsonSchema::field_type`](crate::JsonSchema::field_type)), by name:
231    /// what the surface publishes of it. A parameter without one is
232    /// published as its schema says.
233    pub param_types: Vec<(&'static str, ParamFieldType)>,
234    /// For a flattened parameter, its record's fields and their types, by
235    /// name: the verb's own parameters even though the code declares one.
236    pub flat_types: Option<crate::surface::FlatTypes>,
237    /// The type of the value it answers with, when the code declares one
238    /// ([`JsonSchema::field_type`](crate::JsonSchema::field_type)): what the
239    /// surface publishes of its result.
240    pub result_type: Option<ParamFieldType>,
241}
242
243/// How a parameter's [`FieldType`](crate::FieldType) is worked out,
244/// declaring the records and enums it names.
245pub type ParamFieldType = crate::surface::FieldTypeOf;
246
247impl AsRef<Self> for Declaration {
248    fn as_ref(&self) -> &Self {
249        self
250    }
251}
252
253impl Declaration {
254    /// What a person reads it by now, in their language.
255    #[must_use]
256    pub fn shown_label(&self) -> String {
257        self.word
258            .as_ref()
259            .map_or_else(|| self.label.clone(), crate::label::Word::read)
260    }
261
262    /// Its parameters, each called what the person reads it by where its
263    /// catalogue has a word for it ([`crate::label::titled`]).
264    #[must_use]
265    pub fn shown_params(&self) -> Vec<ActionParam> {
266        match &self.word {
267            Some(word) => crate::label::titled(word, self.resource, self.params.clone()),
268            None => self.params.clone(),
269        }
270    }
271
272    /// The declaration `id` of the resource `vocabulary`, labelled `label`,
273    /// taking `params`, built by `build`.
274    pub(crate) fn new(
275        vocabulary: &Vocabulary,
276        id: &'static str,
277        label: String,
278        params: Vec<ActionParam>,
279        build: Builds,
280    ) -> Self {
281        Self {
282            id,
283            label,
284            word: None,
285            keywords: Vec::new(),
286            icon: None,
287            did: None,
288            description: None,
289            params,
290            kind: ActionKind::Undoable,
291            by_arguments: false,
292            field: None,
293            destructive: false,
294            result: None,
295            tags: Vec::new(),
296            content: None,
297            refines: false,
298            step: None,
299            creates: None,
300            item: None,
301            writes: vec![crate::footprint::RESOURCE_UNIT.to_owned()],
302            resource: vocabulary.kind,
303            action_type: vocabulary.action_type,
304            build,
305            invokes: None,
306            param_types: Vec::new(),
307            flat_types: None,
308            result_type: None,
309        }
310    }
311}
312
313/// What the framework's publishing code needs of one resource type, as
314/// plain values and functions. See the [module docs](self).
315pub struct Vocabulary {
316    /// [`Resource::KIND`].
317    pub kind: &'static str,
318    /// [`Resource::APP_ID`].
319    pub app: &'static str,
320    /// [`Resource::LABEL`].
321    pub label: &'static str,
322    /// [`Resource::CATALOGUE`].
323    pub catalogue: Option<&'static crate::label::Catalogue>,
324    /// [`Resource::ACTION_TYPE`].
325    pub action_type: &'static str,
326    /// [`Resource::EDITS`].
327    pub edits: bool,
328    /// [`Resource::READERS`].
329    pub readers: &'static str,
330    /// [`Resource::RESOURCE_TABLE`].
331    pub(crate) resource_table: Option<&'static crate::table::ModelTable>,
332    pub(crate) type_id: fn() -> TypeId,
333    pub(crate) shape: fn() -> Option<Shape>,
334    pub(crate) op_schemas: fn() -> Vec<(String, serde_json::Value)>,
335    pub(crate) action_schema: fn() -> Option<serde_json::Value>,
336    pub(crate) least_need: fn() -> ActionNeed,
337    /// Builds every declaration afresh; read them through
338    /// [`Vocabulary::declarations`], which keeps them.
339    pub(crate) declare: fn() -> Vec<Declaration>,
340    pub(crate) item_effects: fn(&str, &Id) -> Vec<ActionSpec>,
341    pub(crate) item_views: fn(&str, &Id) -> Vec<ResourceViewSpec>,
342    /// An action from its JSON form (serde's), unstamped.
343    pub(crate) read: fn(serde_json::Value) -> Result<Built, String>,
344    /// The action a field edit is ([`Resource::edit_action`]), unstamped.
345    pub(crate) edit: fn(Edit<()>) -> Option<Built>,
346}
347
348impl Vocabulary {
349    /// The field edit `edit` a caller sent, its path read from the record's
350    /// root ([`Edit::past_resource_name`]): the record answers to the last
351    /// part of its kind and to its label.
352    pub(crate) fn rooted_edit(&self, edit: Edit<()>) -> Result<Edit<()>, String> {
353        let Some(shape) = (self.shape)() else {
354            return Ok(edit);
355        };
356        let kind = self.kind.rsplit('.').next().unwrap_or(self.kind);
357        edit.past_resource_name(shape, &[kind, self.label])
358    }
359
360    /// Every declaration of the resource. They depend on its type alone, so
361    /// each thread builds them once per generation of app code
362    /// ([`reset_type_schemas`](crate::reset_type_schemas)) and answers the
363    /// same list after: publishing, binding a verb or reading an action no
364    /// longer rebuilds every verb's parameters and builder.
365    #[must_use]
366    pub fn declarations(&self) -> Rc<[Declaration]> {
367        type Kept = (u64, HashMap<TypeId, Rc<[Declaration]>>);
368        thread_local! {
369            static KEPT: RefCell<Kept> = RefCell::new((0, HashMap::new()));
370        }
371        let epoch = crate::resource::type_epoch();
372        let key = (self.type_id)();
373        let found = KEPT.with(|kept| {
374            let kept = kept.borrow();
375            if kept.0 == epoch {
376                kept.1.get(&key).cloned()
377            } else {
378                None
379            }
380        });
381        if let Some(found) = found {
382            return found;
383        }
384        // Built outside the borrow: a declaration may read another
385        // resource's vocabulary.
386        let built: Rc<[Declaration]> = (self.declare)().into();
387        KEPT.with(|kept| {
388            let mut kept = kept.borrow_mut();
389            if kept.0 != epoch {
390                *kept = (epoch, HashMap::new());
391            }
392            kept.1.insert(key, Rc::clone(&built));
393        });
394        built
395    }
396}
397
398fn declarations<R: Resource>() -> Vec<Declaration> {
399    let mut out = Vec::new();
400    for decl in R::declarations() {
401        out.push(decl.into_declaration());
402    }
403    out
404}
405
406fn read<R: Resource>(value: serde_json::Value) -> Result<Built, String> {
407    match serde_json::from_value::<R::Action>(value) {
408        Ok(action) => Ok(Built::of::<R>(action)),
409        Err(error) => Err(error.to_string()),
410    }
411}
412
413fn edit<R: Resource>(edit: Edit<()>) -> Option<Built> {
414    R::edit_action(edit.retyped()).map(Built::of::<R>)
415}
416
417struct VocabularyOf<R>(std::marker::PhantomData<R>);
418
419/// The least permission any of the resource's actions needs, as publishing it
420/// states it; a model build applies actions and publishes nothing.
421#[cfg(tilo_model_guest)]
422fn least_need_default() -> ActionNeed {
423    tilo_actions::ActionContract::default().need()
424}
425
426#[cfg(tilo_model_guest)]
427fn empty_op_schemas() -> Vec<(String, serde_json::Value)> {
428    Vec::new()
429}
430
431#[cfg(tilo_model_guest)]
432fn no_item_effects(_: &str, _: &Id) -> Vec<ActionSpec> {
433    Vec::new()
434}
435
436#[cfg(tilo_model_guest)]
437fn no_item_views(_: &str, _: &Id) -> Vec<ResourceViewSpec> {
438    Vec::new()
439}
440
441impl<R: Resource> VocabularyOf<R> {
442    const VOCABULARY: Vocabulary = Vocabulary {
443        kind: R::KIND,
444        app: R::APP_ID,
445        label: R::LABEL,
446        // What a model build leaves out is what a device applying an action
447        // never reads: the words of the resource's catalogue, the effects its
448        // items offer and the views they open, the schemas of its operations,
449        // and the least permission its actions need. Publishing them is the
450        // app's own work, so those bytes stay in the app.
451        #[cfg(tilo_model_guest)]
452        catalogue: None,
453        #[cfg(not(tilo_model_guest))]
454        catalogue: R::CATALOGUE,
455        action_type: R::ACTION_TYPE,
456        edits: R::EDITS,
457        readers: R::READERS,
458        resource_table: R::RESOURCE_TABLE,
459        type_id: TypeId::of::<R>,
460        shape: R::shape,
461        #[cfg(tilo_model_guest)]
462        op_schemas: empty_op_schemas,
463        #[cfg(not(tilo_model_guest))]
464        op_schemas: R::op_schemas,
465        action_schema: R::action_schema,
466        #[cfg(tilo_model_guest)]
467        least_need: least_need_default,
468        #[cfg(not(tilo_model_guest))]
469        least_need: R::least_need,
470        declare: declarations::<R>,
471        #[cfg(tilo_model_guest)]
472        item_effects: no_item_effects,
473        #[cfg(not(tilo_model_guest))]
474        item_effects: R::item_effects,
475        #[cfg(tilo_model_guest)]
476        item_views: no_item_views,
477        #[cfg(not(tilo_model_guest))]
478        item_views: R::item_views,
479        read: read::<R>,
480        edit: edit::<R>,
481    };
482}
483
484#[must_use]
485pub fn vocabulary<R: Resource>() -> &'static Vocabulary {
486    &VocabularyOf::<R>::VOCABULARY
487}