modem-device 0.3.0

The seam between the zenoh-modem driver and a physical or simulated medium
Documentation
//! Operator actions (#129): explicit, costed, never scheduled.
//!
//! Some operations are neither configuration nor observation — "check the
//! mailbox now", "re-register", "run a link test". YANG 1.1 calls them
//! actions (RFC 7950 §7.15): operations tied to a node, distinct from
//! configuration. The line they respect is the architecture's: a billed
//! mailbox poll is a tariff decision the operator makes (§4.11, #73), and a
//! policy inside the driver is what I1 forbids. An action is an operator
//! deciding, once, now. It is never a schedule the driver runs.
//!
//! **There is no `reset`, and there will not be one** (architecture §4.11):
//! recovery is a restart, of the device or of the daemon (#96). The driver's
//! `reopen` is an action like any here, run by an operator, once, now; it
//! rebuilds the device from its configuration and writes nothing to the
//! hardware that startup does not.

use std::collections::BTreeMap;
use std::fmt;

use crate::config::{ConfigValue, ParamSpec};

/// What an action costs, so an operator sees the bill of an operation they
/// asked for before asking.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum CostModel {
    /// Nothing an operator pays for.
    Free,
    /// Billed, in the unit named: a satellite session, a message.
    Billed {
        /// What one costs: `"session"`, `"message"`.
        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}"),
        }
    }
}

/// One action a device offers (#129).
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ActionSpec {
    /// The name the key spells: `device/{device}/action/{name}`.
    pub name: &'static str,
    /// One line for the operator reading the list cold.
    pub description: &'static str,
    /// Its arguments, with the configuration plane's kinds (#125).
    pub arguments: Vec<ParamSpec>,
    /// What it costs.
    pub cost: CostModel,
}

impl ActionSpec {
    /// An action with no arguments; add them with [`with`](Self::with).
    #[must_use]
    pub const fn new(name: &'static str, description: &'static str, cost: CostModel) -> Self {
        Self {
            name,
            description,
            arguments: Vec::new(),
            cost,
        }
    }

    /// Builder form of pushing an argument.
    #[must_use]
    pub fn with(mut self, argument: ParamSpec) -> Self {
        self.arguments.push(argument);
        self
    }

    /// One argument by name.
    #[must_use]
    pub fn argument(&self, name: &str) -> Option<&ParamSpec> {
        self.arguments.iter().find(|a| a.name == name)
    }

    /// Whether `arguments` are ones this action takes: every name declared,
    /// every value of its kind and within its bounds, the bound named.
    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(())
    }
}

/// What an action did, and what it cost (#129): the reply, and the record.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct ActionOutcome {
    /// One line in the device's words.
    pub detail: String,
    /// What it cost, by unit: `{"sessions": 1, "messages_received": 2}`.
    pub cost: BTreeMap<String, i64>,
}

impl ActionOutcome {
    /// An outcome with its detail; costs are added with [`cost`](Self::cost).
    #[must_use]
    pub fn new(detail: impl Into<String>) -> Self {
        Self {
            detail: detail.into(),
            cost: BTreeMap::new(),
        }
    }

    /// Record a cost.
    #[must_use]
    pub fn cost(mut self, what: impl Into<String>, n: i64) -> Self {
        self.cost.insert(what.into(), n);
        self
    }
}

/// Why an action did not run (#129).
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ActionError {
    /// No such action on this device.
    #[error("no action {0:?}; the device lists the actions it offers")]
    UnknownAction(String),
    /// An argument the action does not take, with the reason.
    #[error("{action}: {reason}")]
    Invalid { action: String, reason: String },
    /// The device refused or failed, in its own words.
    #[error("the device refused the action: {0}")]
    Device(String),
    /// Declared, and not runnable here yet.
    #[error("action {0:?} is not supported by this device")]
    Unsupported(String),
}

/// What a device offers an operator to do, now (#129).
///
/// Every invocation goes through the management plane's guards — the
/// concrete key, the startup allowlist, one at a time, the minimum interval
/// — before it reaches [`invoke`](Self::invoke), and every one is an event.
#[async_trait::async_trait]
pub trait Actions: Send + Sync {
    /// The actions this device offers, with their arguments and cost.
    fn specs(&self) -> Vec<ActionSpec>;

    /// Run one, now. Answers what it did and what it cost, or why not.
    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"
        );
    }
}