Skip to main content

modem_device/
action.rs

1//! Operator actions (#129): explicit, costed, never scheduled.
2//!
3//! Some operations are neither configuration nor observation — "check the
4//! mailbox now", "re-register", "run a link test". YANG 1.1 calls them
5//! actions (RFC 7950 §7.15): operations tied to a node, distinct from
6//! configuration. The line they respect is the architecture's: a billed
7//! mailbox poll is a tariff decision the operator makes (§4.11, #73), and a
8//! policy inside the driver is what I1 forbids. An action is an operator
9//! deciding, once, now. It is never a schedule the driver runs.
10//!
11//! **There is no `reset`, and there will not be one** (architecture §4.11):
12//! recovery is a restart, of the device or of the daemon (#96). The driver's
13//! `reopen` is an action like any here, run by an operator, once, now; it
14//! rebuilds the device from its configuration and writes nothing to the
15//! hardware that startup does not.
16
17use std::collections::BTreeMap;
18use std::fmt;
19
20use crate::config::{ConfigValue, ParamSpec};
21
22/// What an action costs, so an operator sees the bill of an operation they
23/// asked for before asking.
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25#[non_exhaustive]
26pub enum CostModel {
27    /// Nothing an operator pays for.
28    Free,
29    /// Billed, in the unit named: a satellite session, a message.
30    Billed {
31        /// What one costs: `"session"`, `"message"`.
32        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/// One action a device offers (#129).
46#[derive(Clone, Debug, PartialEq, Eq)]
47#[non_exhaustive]
48pub struct ActionSpec {
49    /// The name the key spells: `device/{device}/action/{name}`.
50    pub name: &'static str,
51    /// One line for the operator reading the list cold.
52    pub description: &'static str,
53    /// Its arguments, with the configuration plane's kinds (#125).
54    pub arguments: Vec<ParamSpec>,
55    /// What it costs.
56    pub cost: CostModel,
57}
58
59impl ActionSpec {
60    /// An action with no arguments; add them with [`with`](Self::with).
61    #[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    /// Builder form of pushing an argument.
72    #[must_use]
73    pub fn with(mut self, argument: ParamSpec) -> Self {
74        self.arguments.push(argument);
75        self
76    }
77
78    /// One argument by name.
79    #[must_use]
80    pub fn argument(&self, name: &str) -> Option<&ParamSpec> {
81        self.arguments.iter().find(|a| a.name == name)
82    }
83
84    /// Whether `arguments` are ones this action takes: every name declared,
85    /// every value of its kind and within its bounds, the bound named.
86    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/// What an action did, and what it cost (#129): the reply, and the record.
102#[derive(Clone, Debug, Default, PartialEq, Eq)]
103#[non_exhaustive]
104pub struct ActionOutcome {
105    /// One line in the device's words.
106    pub detail: String,
107    /// What it cost, by unit: `{"sessions": 1, "messages_received": 2}`.
108    pub cost: BTreeMap<String, i64>,
109}
110
111impl ActionOutcome {
112    /// An outcome with its detail; costs are added with [`cost`](Self::cost).
113    #[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    /// Record a cost.
122    #[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/// Why an action did not run (#129).
130#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
131#[non_exhaustive]
132pub enum ActionError {
133    /// No such action on this device.
134    #[error("no action {0:?}; the device lists the actions it offers")]
135    UnknownAction(String),
136    /// An argument the action does not take, with the reason.
137    #[error("{action}: {reason}")]
138    Invalid { action: String, reason: String },
139    /// The device refused or failed, in its own words.
140    #[error("the device refused the action: {0}")]
141    Device(String),
142    /// Declared, and not runnable here yet.
143    #[error("action {0:?} is not supported by this device")]
144    Unsupported(String),
145}
146
147/// What a device offers an operator to do, now (#129).
148///
149/// Every invocation goes through the management plane's guards — the
150/// concrete key, the startup allowlist, one at a time, the minimum interval
151/// — before it reaches [`invoke`](Self::invoke), and every one is an event.
152#[async_trait::async_trait]
153pub trait Actions: Send + Sync {
154    /// The actions this device offers, with their arguments and cost.
155    fn specs(&self) -> Vec<ActionSpec>;
156
157    /// Run one, now. Answers what it did and what it cost, or why not.
158    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}