modem-mgmt 0.3.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
//! Transitions, published as `events`.
//!
//! The third class, and the last one this producer was missing. `telemetry` is
//! superseded and `state` is last-writer-wins; both answer "how is it now" and
//! neither can answer "what happened". `events` is the class where **each one
//! matters** (zenkey RFC 04 §1.3), which is why a link change cannot ride the
//! other two: a radio that died and came back leaves no trace in a document
//! that only ever holds the current answer, and "the node went quiet at 11:04
//! because the medium closed" is exactly what an operator arrives too late to
//! see.
//!
//! Both shipped routers have denied `v1/*/events/modem/**` since before there
//! was anything to deny (#45 wrote the rule first on purpose). So this module
//! adds a producer to a rule that already existed, and changes no config.
//!
//! **Not a declared publisher.** Every key here ends in a fresh event id, so
//! interning buys nothing — there is no key to re-use. `telemetry.rs` argues
//! the opposite case for its own subjects and is right about them; the
//! difference is that its keys repeat and these do not.

use std::sync::Arc;
use std::sync::atomic::AtomicU64;

use zenkey::origin::LocalOrigin;
use zenoh::Session;

use crate::plane::SduPlane;
use modem_contract::registry::modem::{Subject, key};

use crate::clock::{now_ms, ulid};

const FAULT_FLOOR: std::time::Duration = std::time::Duration::from_secs(60);

/// The fault stream of an SDU device, published as `device_fault`.
///
/// Until #121 this loop also watched the driver's medium-health flag and
/// published the one transition it could make; the operational status has
/// its own loop now (`oper.rs`), fed by what the device says rather than by
/// a one-way boolean.
pub(super) async fn publish_loop(session: Session, origin: LocalOrigin, plane: Arc<dyn SduPlane>) {
    let device = plane.device().to_string();
    let counter = AtomicU64::new(0);
    let mut faults = plane.events();
    let mut last_fault: Option<tokio::time::Instant> = None;
    let mut suppressed: u64 = 0;

    loop {
        match faults.recv().await {
            Ok(event) => {
                let now = tokio::time::Instant::now();
                if last_fault.is_some_and(|t| now.duration_since(t) < FAULT_FLOOR) {
                    suppressed += 1;
                    continue;
                }
                last_fault = Some(now);
                let event_id = ulid(&counter);
                let subject = Subject::device_device_fault(&device, &event_id);
                let doc =
                    super::DeviceFault::of(&device, event_id, now_ms(), &event, suppressed + 1);
                suppressed = 0;
                publish(&session, &origin, &subject, &doc, "device_fault").await;
            }
            Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
            Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
                suppressed += n;
            }
        }
    }
}

pub(super) async fn publish_device_loop(
    session: Session,
    origin: LocalOrigin,
    device: String,
    dev: Arc<dyn modem_device::Device>,
) {
    let counter = AtomicU64::new(0);
    let mut last_fault: Option<tokio::time::Instant> = None;
    let mut suppressed: u64 = 0;
    loop {
        let event = match dev.next_event().await {
            Ok(e) => e,
            Err(e) => {
                tracing::warn!(device = %device, error = %e, "the device's event stream ended");
                return;
            }
        };
        let now = tokio::time::Instant::now();
        if last_fault.is_some_and(|t| now.duration_since(t) < FAULT_FLOOR) {
            suppressed += 1;
            continue;
        }
        last_fault = Some(now);
        let event_id = ulid(&counter);
        let subject = Subject::device_device_fault(&device, &event_id);
        let doc = super::DeviceFault::of(&device, event_id, now_ms(), &event, suppressed + 1);
        suppressed = 0;
        publish(&session, &origin, &subject, &doc, "device_fault").await;
    }
}

/// Put one event document on its own key.
///
/// Never blocks a data-path task: this loop is its own, so the `Transition`
/// profile's `CongestionControl::Block` cannot reach the scheduler. That is the
/// whole reason the driver raises events into a `broadcast` rather than
/// publishing them where they happen.
pub(super) async fn publish<T: serde::Serialize>(
    session: &Session,
    origin: &LocalOrigin,
    subject: &Subject,
    doc: &T,
    what: &str,
) {
    let payload = match serde_json::to_string(doc) {
        Ok(p) => p,
        Err(e) => {
            tracing::error!(error = %e, "the {what} event did not serialize");
            return;
        }
    };
    let qos = subject.qos();
    let k = key(origin, subject);
    if let Err(e) = session
        .put(k.as_keyexpr(), payload)
        .congestion_control(qos.congestion_control())
        .priority(qos.priority())
        .express(qos.express())
        .reliability(qos.reliability())
        .encoding(zenoh::bytes::Encoding::APPLICATION_JSON)
        .await
    {
        tracing::debug!(key = %k, error = %e, "{what} publication failed");
    } else {
        tracing::info!(key = %k, "published a {what} event");
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn an_id_survives_being_used_as_a_key_chunk() {
        // It is the last chunk of the event's key, so it has to pass zenkey's
        // chunk grammar unchanged — a slug that rewrote it would make the id in
        // the document differ from the id in the key.
        let c = AtomicU64::new(0);
        let id = ulid(&c);
        assert_eq!(zenkey::Chunk::slug(&id).as_str(), id);
    }

    /// zenkey 0.8 made the key slug injective (RFC 03 §2 v1.31): a value
    /// passes through only when it is charset-legal and does not start with
    /// `x-`; everything else is re-keyed under an `x-` prefix. The names this
    /// driver puts in keys — device names, endpoint names, IMEIs — were all
    /// pass-through before and after, so #116 moved no key; this pins the
    /// rule for the next name somebody chooses.
    #[test]
    fn a_device_or_endpoint_name_keys_as_itself_when_it_is_lowercase_alnum() {
        for name in ["rf0", "sat0", "peer-b", "300234010753370", "gw.eu-1"] {
            assert_eq!(zenkey::Chunk::slug(name).as_str(), name, "{name} moved");
        }
        // Not charset-legal, or reserved: re-keyed, and never colliding with
        // a legal name — which is the whole point of the injective rule.
        for name in ["RF0", "x-sat0", "sat 0", ""] {
            let slug = zenkey::Chunk::slug(name);
            assert!(
                slug.as_str().starts_with("x-"),
                "{name:?} -> {}",
                slug.as_str()
            );
            assert_eq!(zenkey::Chunk::unslug(&slug).as_deref(), Some(name));
        }
    }
}