Skip to main content

tilo_resource/
status.rs

1//! What an effect, or one of the resource's own actions, looks like to
2//! callers right now: unavailable while the engine is offline, labelled
3//! differently while recording, saying what it does on one row.
4
5use crate::ActionRef;
6use tilo_actions::{ActionKind, ActionParam, ActionSpec, Availability};
7
8/// What an effect, or one of the resource's own actions, looks like to
9/// callers right now, when it differs from its declaration: unavailable
10/// while the engine is offline, labelled "Stop recording" while recording.
11#[derive(Clone, Debug, PartialEq)]
12pub struct EffectStatus {
13    id: &'static str,
14    availability: Option<Availability>,
15    label: Option<String>,
16    /// What the effect says of itself on this entity right now, when the
17    /// entity's own state says it (what erasing this drive loses).
18    description: Option<String>,
19    /// What its caller types to confirm this invocation on this entity (the
20    /// drive's name), when the entity's state says it.
21    phrase: Option<String>,
22    /// One of the effect's parameters, narrowed to what this entity offers
23    /// for it now.
24    params: Vec<ParamStatus>,
25    /// The row or item resource the status is about, when it is about one
26    /// ([`Self::on`]) rather than the resource its view publishes.
27    item: Option<String>,
28    /// What the effect is on this entity alone: a page's reads take the
29    /// authority to operate a page that holds the person's sign-ins, and only
30    /// what any visitor has when it does not.
31    kind: Option<ActionKind>,
32}
33
34/// One of an effect's parameters as the entity offers it now: the values it
35/// takes here (a device's name in the nearby targets this window can see),
36/// what it means here, the bounds this entity's state sets.
37#[derive(Clone, Debug, PartialEq)]
38struct ParamStatus {
39    name: String,
40    /// Each accepted value with the words it reads by, when they differ from
41    /// the value itself.
42    choices: Option<Vec<(String, Option<String>)>>,
43    description: Option<String>,
44    schema: Option<serde_json::Value>,
45}
46
47impl ParamStatus {
48    fn apply(&self, param: &mut ActionParam) {
49        if let Some(description) = &self.description {
50            param.description = description.clone().into();
51        }
52        if let Some(schema) = &self.schema {
53            param.schema = Some(std::sync::Arc::new(schema.clone()));
54        }
55        // Choices last: each one's label is a schema annotation, kept beside
56        // the bounds the status sets.
57        if let Some(choices) = &self.choices {
58            if choices.iter().all(|(_, label)| label.is_none()) {
59                param.choices = choices
60                    .iter()
61                    .map(|(value, _)| value.clone().into())
62                    .collect();
63            } else {
64                *param =
65                    param
66                        .clone()
67                        .with_labelled_choices(choices.iter().map(|(value, label)| {
68                            (
69                                value.clone(),
70                                label.clone().unwrap_or_else(|| value.clone()),
71                            )
72                        }));
73            }
74        }
75    }
76}
77
78impl EffectStatus {
79    /// `effect` cannot be invoked now: `code` names why for programs,
80    /// `reason` for people.
81    pub fn unavailable<E, A>(
82        effect: ActionRef<E, A>,
83        code: impl Into<String>,
84        reason: impl Into<String>,
85    ) -> Self {
86        Self::unavailable_id(effect.id, code.into(), reason.into())
87    }
88
89    /// [`Self::unavailable`] once the effect's id and its words are read, so
90    /// every vocabulary's status is built by one function.
91    fn unavailable_id(id: &'static str, code: String, reason: String) -> Self {
92        Self {
93            id,
94            availability: Some(Availability::Unavailable { code, reason }),
95            label: None,
96            description: None,
97            phrase: None,
98            params: Vec::new(),
99            item: None,
100            kind: None,
101        }
102    }
103
104    /// `effect` says of itself what `description` says on this entity, and is
105    /// offered as declared otherwise.
106    pub fn described<E, A>(effect: ActionRef<E, A>, description: impl Into<String>) -> Self {
107        Self::described_id(effect.id, description.into())
108    }
109
110    /// [`Self::described`] once the effect's id and its words are read.
111    fn described_id(id: &'static str, description: String) -> Self {
112        Self {
113            id,
114            availability: None,
115            label: None,
116            description: Some(description),
117            phrase: None,
118            params: Vec::new(),
119            item: None,
120            kind: None,
121        }
122    }
123
124    /// `effect` is `kind` on this entity, offered as declared otherwise.
125    pub fn of_kind<E, A>(effect: ActionRef<E, A>, kind: ActionKind) -> Self {
126        Self::of_kind_id(effect.id, kind)
127    }
128
129    /// [`Self::of_kind`] once the effect's id is read.
130    fn of_kind_id(id: &'static str, kind: ActionKind) -> Self {
131        Self {
132            id,
133            availability: None,
134            label: None,
135            description: None,
136            phrase: None,
137            params: Vec::new(),
138            item: None,
139            kind: Some(kind),
140        }
141    }
142
143    /// `effect` is offered as `label` now.
144    pub fn labelled<E, A>(effect: ActionRef<E, A>, label: impl Into<String>) -> Self {
145        Self::labelled_id(effect.id, label.into())
146    }
147
148    /// [`Self::labelled`] once the effect's id and its words are read.
149    fn labelled_id(id: &'static str, label: String) -> Self {
150        Self {
151            id,
152            availability: None,
153            label: Some(label),
154            description: None,
155            phrase: None,
156            params: Vec::new(),
157            item: None,
158            kind: None,
159        }
160    }
161
162    /// The effect's parameter `param` accepts `choices` on this entity: the
163    /// apps that open this file, the devices nearby now.
164    #[must_use]
165    pub fn with_param_choices<P, V>(self, param: P, choices: impl IntoIterator<Item = V>) -> Self
166    where
167        P: Into<String>,
168        V: Into<String>,
169    {
170        self.with_labelled_param_choices(
171            param,
172            choices.into_iter().map(|choice| {
173                let choice = choice.into();
174                (choice.clone(), choice)
175            }),
176        )
177    }
178
179    /// [`Self::with_param_choices`], each choice with the words it reads by:
180    /// a nearby device's handle reads as the device's name.
181    #[must_use]
182    pub fn with_labelled_param_choices<P, V, L>(
183        mut self,
184        param: P,
185        choices: impl IntoIterator<Item = (V, L)>,
186    ) -> Self
187    where
188        P: Into<String>,
189        V: Into<String>,
190        L: Into<String>,
191    {
192        let choices: Vec<(String, Option<String>)> = choices
193            .into_iter()
194            .map(|(value, label)| {
195                let value = value.into();
196                let label = label.into();
197                (value.clone(), (label != value).then_some(label))
198            })
199            .collect();
200        self.param(param).choices = Some(choices);
201        self
202    }
203
204    /// The effect's parameter `param` means `description` on this entity.
205    #[must_use]
206    pub fn with_param_description<P: Into<String>>(
207        mut self,
208        param: P,
209        description: impl Into<String>,
210    ) -> Self {
211        self.param(param).description = Some(description.into());
212        self
213    }
214
215    /// The effect's parameter `param` is bounded by `schema` on this entity.
216    #[must_use]
217    pub fn with_param_schema<P: Into<String>>(
218        mut self,
219        param: P,
220        schema: serde_json::Value,
221    ) -> Self {
222        self.param(param).schema = Some(schema);
223        self
224    }
225
226    /// The status of `param` on this entity, added when the status does not
227    /// name it yet.
228    #[allow(
229        clippy::expect_used,
230        reason = "the parameter was just added when the search found none"
231    )]
232    fn param(&mut self, param: impl Into<String>) -> &mut ParamStatus {
233        let name = param.into();
234        if !self.params.iter().any(|held| held.name == name) {
235            self.params.push(ParamStatus {
236                name: name.clone(),
237                choices: None,
238                description: None,
239                schema: None,
240            });
241        }
242        self.params
243            .iter_mut()
244            .find(|held| held.name == name)
245            .expect("the parameter was just added when it was missing")
246    }
247
248    /// This status is about the item or row published as `item` rather than
249    /// the resource its view publishes: the effect is offered as the status
250    /// says on that entity's published actions alone (a process that is a
251    /// system service cannot be ended), served by
252    /// a publisher's row status.
253    #[must_use]
254    pub fn on(mut self, item: impl Into<String>) -> Self {
255        self.item = Some(item.into());
256        self
257    }
258
259    /// Offer the effect as `label` too.
260    #[must_use]
261    pub fn with_label(mut self, label: impl Into<String>) -> Self {
262        self.label = Some(label.into());
263        self
264    }
265
266    /// Say what the effect does on this entity right now, in the entity's
267    /// own words: what erasing this drive loses.
268    #[must_use]
269    pub fn with_description(mut self, description: impl Into<String>) -> Self {
270        self.description = Some(description.into());
271        self
272    }
273
274    /// Have the caller type `phrase` to confirm this invocation on this
275    /// entity: the name of what it erases.
276    #[must_use]
277    pub fn with_phrase(mut self, phrase: impl Into<String>) -> Self {
278        self.phrase = Some(phrase.into());
279        self
280    }
281
282    /// How the effect stands now, when the status narrows it.
283    #[must_use]
284    pub fn availability(&self) -> Option<&Availability> {
285        self.availability.as_ref()
286    }
287
288    /// What the effect says of itself on this entity, when the status says.
289    #[must_use]
290    pub fn description(&self) -> Option<&str> {
291        self.description.as_deref()
292    }
293
294    /// What its caller types to confirm it on this entity, when the status
295    /// asks for one.
296    #[must_use]
297    pub fn phrase(&self) -> Option<&str> {
298        self.phrase.as_deref()
299    }
300
301    /// The id of the action or effect this status is about.
302    #[must_use]
303    pub fn id(&self) -> &'static str {
304        self.id
305    }
306
307    /// The item or row this status is about, when it is about one rather
308    /// than the published resource.
309    #[must_use]
310    pub fn item(&self) -> Option<&str> {
311        self.item.as_deref()
312    }
313
314    /// Show `spec` as this status says it is right now.
315    pub fn overlay(&self, spec: &mut ActionSpec) {
316        if let Some(availability) = &self.availability {
317            spec.type_mut().contract.availability = availability.clone();
318        }
319        if let Some(label) = &self.label {
320            spec.type_mut().label.clone_from(label);
321        }
322        if let Some(description) = &self.description {
323            spec.type_mut().description = Some(description.clone());
324        }
325        if let Some(phrase) = &self.phrase {
326            spec.type_mut().contract.confirmation = tilo_actions::ConfirmationPolicy::Phrase {
327                phrase: phrase.clone(),
328            };
329        }
330        for param in &self.params {
331            spec.narrow_param(&param.name, |declared| param.apply(declared));
332        }
333        if let Some(kind) = self.kind {
334            spec.type_mut().contract.kind = kind;
335        }
336    }
337}
338
339/// Lay `statuses` over `resource`'s own actions, each by its id.
340pub fn apply_statuses(resource: &mut tilo_actions::ResourceSpec, statuses: &[EffectStatus]) {
341    for status in statuses {
342        for spec in resource
343            .actions
344            .iter_mut()
345            .filter(|spec| spec.id == status.id())
346        {
347            status.overlay(spec);
348        }
349    }
350}
351
352/// Lay what a publisher says of each row's effects over `rows`, the rows
353/// nested beneath them included.
354pub fn apply_row_statuses(
355    rows: &mut [tilo_actions::ResourceSpec],
356    statuses: &dyn Fn(&str) -> Vec<EffectStatus>,
357) {
358    for row in rows {
359        let said = statuses(row.id.as_str());
360        if !said.is_empty() {
361            apply_statuses(row, &said);
362        }
363        apply_row_statuses(&mut row.children, statuses);
364    }
365}
366
367#[cfg(test)]
368mod tests {
369    use super::EffectStatus;
370    use crate::Effect as _;
371
372    /// A send to one device: what a row's status narrows per entity.
373    #[derive(Clone, Debug, PartialEq, Eq, crate::Effect)]
374    #[effect(operation = "test.status.view", catalogue = "tests/locales")]
375    enum StatusEffect {
376        /// Send
377        #[effect(kind = "read")]
378        Send {
379            #[param("The device")]
380            target: String,
381            #[param("The port")]
382            port: i64,
383        },
384    }
385
386    #[test]
387    fn a_status_narrows_the_parameters_of_the_effect_it_is_about() {
388        let mut spec = StatusEffect::Send {
389            target: String::new(),
390            port: 0,
391        }
392        .bound_asking(&["target", "port"]);
393        EffectStatus::labelled(StatusEffect::SEND, "Send")
394            .with_labelled_param_choices("target", [("a", "Device A"), ("b", "Device B")])
395            .with_param_description("port", "The receiver's port")
396            .with_param_schema("port", serde_json::json!({"minimum": 1}))
397            .overlay(&mut spec);
398        let target = spec
399            .params()
400            .iter()
401            .find(|param| param.name == "target")
402            .expect("the target parameter");
403        assert_eq!(
404            target
405                .choices
406                .iter()
407                .map(ToString::to_string)
408                .collect::<Vec<_>>(),
409            vec!["a", "b"],
410            "only the devices this entity can send to are offered"
411        );
412        assert_eq!(target.choice_label("a"), Some("Device A"));
413        let port = spec
414            .params()
415            .iter()
416            .find(|param| param.name == "port")
417            .expect("the port parameter");
418        assert_eq!(&*port.description, "The receiver's port");
419        assert_eq!(
420            port.schema.as_deref(),
421            Some(&serde_json::json!({"minimum": 1})),
422            "the entity's state bounds what it accepts"
423        );
424    }
425
426    #[test]
427    fn a_status_leaves_the_parameters_it_does_not_name_as_declared() {
428        let mut spec = StatusEffect::Send {
429            target: String::new(),
430            port: 0,
431        }
432        .bound_asking(&["target", "port"]);
433        let declared = spec
434            .params()
435            .iter()
436            .find(|param| param.name == "port")
437            .expect("the port parameter")
438            .clone();
439        EffectStatus::labelled(StatusEffect::SEND, "Send")
440            .with_param_choices("missing", ["a"])
441            .overlay(&mut spec);
442        assert_eq!(
443            spec.params()
444                .iter()
445                .find(|param| param.name == "port")
446                .expect("the port parameter"),
447            &declared
448        );
449    }
450}