modem-mgmt 0.2.0

The management plane of zenoh-modem as a library: serve every device on a host over Zenoh, for any driver that links the contract
Documentation
//! Operator actions (#129): `@rpc/modem/device/{device}/action/{name}`, and
//! the event every invocation is.
//!
//! An action is an operator deciding, once, now — never a schedule the
//! driver runs (I1; a billed mailbox poll is a tariff decision, #73). It
//! runs behind the same guards as a write (#126): the concrete key, a
//! startup allowlist (`[[device]] actions`), one at a time per device, and
//! a minimum interval per action (`action_interval_s`) so a looping script
//! is refused rather than billed. The reply reports what it cost, because an
//! operator must see the bill of an operation they asked for; the event
//! records the invocation, the refusal included.
//!
//! **Not provided: `reset`.** Architecture §4.11 stands: recovery is a
//! restart, and the supervisor's (#96).

use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use std::sync::atomic::AtomicU64;
use std::time::Duration;

use modem_contract::registry::modem::{Subject, key};
use modem_device::action::{ActionError, ActionSpec};
use modem_device::config::ConfigValue;
use tokio::time::Instant;
use zenkey::origin::LocalOrigin;
use zenoh::Session;

use crate::clock::{now_ms, ulid};
use crate::config::{Attribution, Bucket, Refusal};
use crate::oper::Source;

/// One device's actions, and the guards' state.
pub(crate) struct ActionState {
    pub(crate) device: String,
    source: Source,
    specs: Vec<ActionSpec>,
    /// The startup file's `actions`: what a remote caller may run.
    allow: BTreeSet<String>,
    /// The startup file's `action_interval_s`: the floor between two runs.
    intervals: BTreeMap<String, Duration>,
    last: std::sync::Mutex<BTreeMap<String, Instant>>,
    /// One at a time, per device.
    one: tokio::sync::Mutex<()>,
    /// Invocations not yet published, oldest first.
    events: tokio::sync::Mutex<Vec<serde_json::Value>>,
    changed: tokio::sync::Notify,
}

impl ActionState {
    /// For a node whose device offers actions; `None` for one that does
    /// not, whose procedure stays gated.
    pub(crate) fn of(
        device: &str,
        source: Source,
        allow: BTreeSet<String>,
        intervals: BTreeMap<String, Duration>,
    ) -> Option<Self> {
        let specs = source.action_specs()?;
        Some(Self {
            device: device.to_string(),
            source,
            specs,
            allow,
            intervals,
            last: std::sync::Mutex::new(BTreeMap::new()),
            one: tokio::sync::Mutex::new(()),
            events: tokio::sync::Mutex::new(Vec::new()),
            changed: tokio::sync::Notify::new(),
        })
    }

    /// The guards in order, then the device, then the record. `Ok` is the
    /// reply's JSON — the outcome, with what it cost.
    pub(crate) async fn invoke(
        &self,
        name: &str,
        arguments: BTreeMap<String, zenkey::config::ParamValue>,
        who: Attribution,
    ) -> Result<String, Refusal> {
        let arguments: BTreeMap<String, ConfigValue> = arguments
            .iter()
            .map(|(k, v)| (k.clone(), modem_contract::config::value_of(v)))
            .collect();
        let result = self.guarded(name, &arguments).await;
        let (outcome, cost, detail) = match &result {
            Ok(o) => ("ok", o.cost.clone(), o.detail.clone()),
            Err(r) if r.error == modem_contract::registry::modem::error::ACTION_REFUSED => {
                ("failed", BTreeMap::new(), r.message.clone())
            }
            Err(r) => ("refused", BTreeMap::new(), r.message.clone()),
        };
        let mut event = serde_json::json!({
            "device": self.device,
            "action": name,
            "outcome": outcome,
            "detail": detail,
        });
        if !arguments.is_empty() {
            event["arguments"] = serde_json::to_value(
                arguments
                    .iter()
                    .map(|(k, v)| (k.clone(), modem_contract::config::value(v)))
                    .collect::<BTreeMap<_, _>>(),
            )
            .unwrap_or(serde_json::Value::Null);
        }
        if !cost.is_empty() {
            event["cost"] = serde_json::to_value(&cost).unwrap_or(serde_json::Value::Null);
        }
        if let Some(a) = &who.actor {
            event["actor"] = serde_json::Value::String(a.clone());
        }
        if let Some(r) = &who.request_id {
            event["request_id"] = serde_json::Value::String(r.clone());
        }
        self.events.lock().await.push(event);
        self.changed.notify_waiters();
        result.and_then(|o| {
            serde_json::to_string(&super::ActionOutcome::of(&o)).map_err(|e| {
                Refusal::new(
                    "error/invalid-args",
                    format!("the outcome did not serialize: {e}"),
                )
            })
        })
    }

    async fn guarded(
        &self,
        name: &str,
        arguments: &BTreeMap<String, ConfigValue>,
    ) -> Result<modem_device::action::ActionOutcome, Refusal> {
        // The device lists what it offers; a name it does not is not found.
        let spec = self.specs.iter().find(|s| s.name == name).ok_or_else(|| {
            Refusal::new(
                "error/not-found",
                format!(
                    "device {:?} offers no action {name:?}; it offers {:?}",
                    self.device,
                    self.specs.iter().map(|s| s.name).collect::<Vec<_>>()
                ),
            )
        })?;
        // The startup allowlist.
        if !self.allow.contains(name) {
            return Err(Refusal::new(
                "error/gated",
                format!(
                    "action {name:?} is not remotely runnable on device {:?}: the startup \
                     file's `actions` names the ones that are",
                    self.device
                ),
            ));
        }
        // One at a time.
        let _one = self.one.lock().await;
        // The minimum interval: refused rather than billed.
        let now = Instant::now();
        if let Some(floor) = self.intervals.get(name)
            && let Some(last) = self.last.lock().expect("not poisoned").get(name)
            && now.duration_since(*last) < *floor
        {
            return Err(Refusal::new(
                "error/busy",
                format!(
                    "refused rather than billed: the last {name} on device {:?} was {} s ago \
                     and `action_interval_s` says {} s",
                    self.device,
                    now.duration_since(*last).as_secs(),
                    floor.as_secs()
                ),
            ));
        }
        // The arguments, against the spec.
        spec.check(arguments).map_err(|e| Refusal::of_action(&e))?;
        // The device.
        let outcome = self
            .source
            .invoke(name, arguments)
            .await
            .map_err(|e| Refusal::of_action(&e))?;
        self.last
            .lock()
            .expect("not poisoned")
            .insert(name.to_string(), now);
        tracing::info!(device = %self.device, action = name, cost = ?outcome.cost, "an operator action ran");
        Ok(outcome)
    }
}

impl Refusal {
    fn of_action(e: &ActionError) -> Self {
        use modem_contract::registry::modem::error;
        match e {
            ActionError::UnknownAction(_) => Self::new("error/not-found", e.to_string()),
            ActionError::Invalid { .. } => Self::new("error/invalid-args", e.to_string()),
            ActionError::Device(words) => Self::new(error::ACTION_REFUSED, words.clone()),
            _ => Self::new("error/unsupported", e.to_string()),
        }
    }
}

/// The events: every invocation, under the registry's `burst(600/h)`.
pub(super) async fn publish_loop(session: Session, origin: LocalOrigin, state: Arc<ActionState>) {
    let counter = AtomicU64::new(0);
    let mut bucket = Bucket::new(Instant::now());
    let mut folded: Option<serde_json::Value> = None;
    loop {
        let queued = std::mem::take(&mut *state.events.lock().await);
        let now = Instant::now();
        for mut event in folded.take().into_iter().chain(queued) {
            if bucket.take(now) {
                let event_id = ulid(&counter);
                event["event_id"] = serde_json::Value::String(event_id.clone());
                event["at_ms"] = serde_json::Value::from(now_ms());
                let subject = Subject::device_action(&state.device, &event_id);
                let _ = key(&origin, &subject);
                crate::events::publish(&session, &origin, &subject, &event, "action").await;
            } else {
                folded = Some(event);
            }
        }
        let wake = if folded.is_some() {
            bucket.next_at(now)
        } else {
            now + Duration::from_secs(3600)
        };
        tokio::select! {
            () = state.changed.notified() => {}
            () = tokio::time::sleep_until(wake) => {}
        }
    }
}