1use std::collections::BTreeMap;
18use std::fmt;
19
20use crate::config::{ConfigValue, ParamSpec};
21
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25#[non_exhaustive]
26pub enum CostModel {
27 Free,
29 Billed {
31 unit: &'static str,
33 },
34}
35
36impl fmt::Display for CostModel {
37 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38 match self {
39 Self::Free => f.write_str("free"),
40 Self::Billed { unit } => write!(f, "billed per {unit}"),
41 }
42 }
43}
44
45#[derive(Clone, Debug, PartialEq, Eq)]
47#[non_exhaustive]
48pub struct ActionSpec {
49 pub name: &'static str,
51 pub description: &'static str,
53 pub arguments: Vec<ParamSpec>,
55 pub cost: CostModel,
57}
58
59impl ActionSpec {
60 #[must_use]
62 pub const fn new(name: &'static str, description: &'static str, cost: CostModel) -> Self {
63 Self {
64 name,
65 description,
66 arguments: Vec::new(),
67 cost,
68 }
69 }
70
71 #[must_use]
73 pub fn with(mut self, argument: ParamSpec) -> Self {
74 self.arguments.push(argument);
75 self
76 }
77
78 #[must_use]
80 pub fn argument(&self, name: &str) -> Option<&ParamSpec> {
81 self.arguments.iter().find(|a| a.name == name)
82 }
83
84 pub fn check(&self, arguments: &BTreeMap<String, ConfigValue>) -> Result<(), ActionError> {
87 for (name, value) in arguments {
88 let spec = self.argument(name).ok_or_else(|| ActionError::Invalid {
89 action: self.name.to_string(),
90 reason: format!("no argument {name:?}"),
91 })?;
92 spec.check(value).map_err(|reason| ActionError::Invalid {
93 action: self.name.to_string(),
94 reason: format!("{name}: {reason}"),
95 })?;
96 }
97 Ok(())
98 }
99}
100
101#[derive(Clone, Debug, Default, PartialEq, Eq)]
103#[non_exhaustive]
104pub struct ActionOutcome {
105 pub detail: String,
107 pub cost: BTreeMap<String, i64>,
109}
110
111impl ActionOutcome {
112 #[must_use]
114 pub fn new(detail: impl Into<String>) -> Self {
115 Self {
116 detail: detail.into(),
117 cost: BTreeMap::new(),
118 }
119 }
120
121 #[must_use]
123 pub fn cost(mut self, what: impl Into<String>, n: i64) -> Self {
124 self.cost.insert(what.into(), n);
125 self
126 }
127}
128
129#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
131#[non_exhaustive]
132pub enum ActionError {
133 #[error("no action {0:?}; the device lists the actions it offers")]
135 UnknownAction(String),
136 #[error("{action}: {reason}")]
138 Invalid { action: String, reason: String },
139 #[error("the device refused the action: {0}")]
141 Device(String),
142 #[error("action {0:?} is not supported by this device")]
144 Unsupported(String),
145}
146
147#[async_trait::async_trait]
153pub trait Actions: Send + Sync {
154 fn specs(&self) -> Vec<ActionSpec>;
156
157 async fn invoke(
159 &self,
160 name: &str,
161 arguments: &BTreeMap<String, ConfigValue>,
162 ) -> Result<ActionOutcome, ActionError>;
163}
164
165#[cfg(test)]
166mod tests {
167 use super::*;
168 use crate::config::ParamKind;
169
170 #[test]
171 fn an_action_checks_its_arguments_by_name_kind_and_bound() {
172 let spec = ActionSpec::new("link_test", "", CostModel::Free).with(ParamSpec::new(
173 "seconds",
174 ParamKind::integer(Some(1), Some(60), Some("s")),
175 "",
176 ));
177 assert!(
178 spec.check(&[("seconds".to_string(), ConfigValue::Integer(10))].into())
179 .is_ok()
180 );
181 let err = spec
182 .check(&[("seconds".to_string(), ConfigValue::Integer(90))].into())
183 .expect_err("above the maximum");
184 assert!(
185 err.to_string().contains("above the maximum of 60 s"),
186 "{err}"
187 );
188 let err = spec
189 .check(&[("minutes".to_string(), ConfigValue::Integer(1))].into())
190 .expect_err("no such argument");
191 assert!(err.to_string().contains("no argument \"minutes\""), "{err}");
192 assert_eq!(
193 CostModel::Billed { unit: "session" }.to_string(),
194 "billed per session"
195 );
196 }
197}