1use crate::ActionRef;
6use tilo_actions::{ActionKind, ActionParam, ActionSpec, Availability};
7
8#[derive(Clone, Debug, PartialEq)]
12pub struct EffectStatus {
13 id: &'static str,
14 availability: Option<Availability>,
15 label: Option<String>,
16 description: Option<String>,
19 phrase: Option<String>,
22 params: Vec<ParamStatus>,
25 item: Option<String>,
28 kind: Option<ActionKind>,
32}
33
34#[derive(Clone, Debug, PartialEq)]
38struct ParamStatus {
39 name: String,
40 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 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 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 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 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 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 pub fn of_kind<E, A>(effect: ActionRef<E, A>, kind: ActionKind) -> Self {
126 Self::of_kind_id(effect.id, kind)
127 }
128
129 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 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 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 #[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 #[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 #[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 #[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 #[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 #[must_use]
254 pub fn on(mut self, item: impl Into<String>) -> Self {
255 self.item = Some(item.into());
256 self
257 }
258
259 #[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 #[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 #[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 #[must_use]
284 pub fn availability(&self) -> Option<&Availability> {
285 self.availability.as_ref()
286 }
287
288 #[must_use]
290 pub fn description(&self) -> Option<&str> {
291 self.description.as_deref()
292 }
293
294 #[must_use]
297 pub fn phrase(&self) -> Option<&str> {
298 self.phrase.as_deref()
299 }
300
301 #[must_use]
303 pub fn id(&self) -> &'static str {
304 self.id
305 }
306
307 #[must_use]
310 pub fn item(&self) -> Option<&str> {
311 self.item.as_deref()
312 }
313
314 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(¶m.name, |declared| param.apply(declared));
332 }
333 if let Some(kind) = self.kind {
334 spec.type_mut().contract.kind = kind;
335 }
336 }
337}
338
339pub 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
352pub 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 #[derive(Clone, Debug, PartialEq, Eq, crate::Effect)]
374 #[effect(operation = "test.status.view", catalogue = "tests/locales")]
375 enum StatusEffect {
376 #[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}