use std::collections::BTreeMap;
use std::fmt;
use crate::config::{ConfigValue, ParamSpec};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum CostModel {
Free,
Billed {
unit: &'static str,
},
}
impl fmt::Display for CostModel {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Free => f.write_str("free"),
Self::Billed { unit } => write!(f, "billed per {unit}"),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ActionSpec {
pub name: &'static str,
pub description: &'static str,
pub arguments: Vec<ParamSpec>,
pub cost: CostModel,
}
impl ActionSpec {
#[must_use]
pub const fn new(name: &'static str, description: &'static str, cost: CostModel) -> Self {
Self {
name,
description,
arguments: Vec::new(),
cost,
}
}
#[must_use]
pub fn with(mut self, argument: ParamSpec) -> Self {
self.arguments.push(argument);
self
}
#[must_use]
pub fn argument(&self, name: &str) -> Option<&ParamSpec> {
self.arguments.iter().find(|a| a.name == name)
}
pub fn check(&self, arguments: &BTreeMap<String, ConfigValue>) -> Result<(), ActionError> {
for (name, value) in arguments {
let spec = self.argument(name).ok_or_else(|| ActionError::Invalid {
action: self.name.to_string(),
reason: format!("no argument {name:?}"),
})?;
spec.check(value).map_err(|reason| ActionError::Invalid {
action: self.name.to_string(),
reason: format!("{name}: {reason}"),
})?;
}
Ok(())
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct ActionOutcome {
pub detail: String,
pub cost: BTreeMap<String, i64>,
}
impl ActionOutcome {
#[must_use]
pub fn new(detail: impl Into<String>) -> Self {
Self {
detail: detail.into(),
cost: BTreeMap::new(),
}
}
#[must_use]
pub fn cost(mut self, what: impl Into<String>, n: i64) -> Self {
self.cost.insert(what.into(), n);
self
}
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ActionError {
#[error("no action {0:?}; the device lists the actions it offers")]
UnknownAction(String),
#[error("{action}: {reason}")]
Invalid { action: String, reason: String },
#[error("the device refused the action: {0}")]
Device(String),
#[error("action {0:?} is not supported by this device")]
Unsupported(String),
}
#[async_trait::async_trait]
pub trait Actions: Send + Sync {
fn specs(&self) -> Vec<ActionSpec>;
async fn invoke(
&self,
name: &str,
arguments: &BTreeMap<String, ConfigValue>,
) -> Result<ActionOutcome, ActionError>;
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::ParamKind;
#[test]
fn an_action_checks_its_arguments_by_name_kind_and_bound() {
let spec = ActionSpec::new("link_test", "", CostModel::Free).with(ParamSpec::new(
"seconds",
ParamKind::integer(Some(1), Some(60), Some("s")),
"",
));
assert!(
spec.check(&[("seconds".to_string(), ConfigValue::Integer(10))].into())
.is_ok()
);
let err = spec
.check(&[("seconds".to_string(), ConfigValue::Integer(90))].into())
.expect_err("above the maximum");
assert!(
err.to_string().contains("above the maximum of 60 s"),
"{err}"
);
let err = spec
.check(&[("minutes".to_string(), ConfigValue::Integer(1))].into())
.expect_err("no such argument");
assert!(err.to_string().contains("no argument \"minutes\""), "{err}");
assert_eq!(
CostModel::Billed { unit: "session" }.to_string(),
"billed per session"
);
}
}