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
//! Link and endpoint documents, published as `state` (the security document
//! is every device's, in `security.rs`).
//!
//! `state` is last-writer-wins and must be refreshed at or below half its TTL,
//! so that a reader can distinguish "unchanged" from "the publisher is gone"
//! (zenkey RFC 04 §1). These carry the `refreshed` profile for that reason.
//!
//! This is where the withdrawn ICD's capability negotiation ends up. Instead of
//! a HELLO exchange only the link could perform, the driver's capabilities are
//! a document anyone may read at any time — including after the fact, and
//! including from a tool that was not running when the driver started.

use std::sync::Arc;
use std::time::Duration;

use modem_contract::registry::modem::{Subject, key};
use zenkey::origin::LocalOrigin;
use zenkey::{Key, QosProfile};
use zenoh::Session;

use crate::plane::SduPlane;

/// Every subject this loop will ever publish on, resolved once.
///
/// Built by [`StateKeys::of`] on the way up rather than inside the loop, for
/// #42's reason applied to the other plane: a roster that calls this driver
/// alive is entitled to its `state` documents, so anything that could stop them
/// appearing belongs to startup rather than to a spawned task's silence.
///
/// The keys come from the generated registry — `Subject::link(device)` and its
/// siblings — rather than from chunk arrays spelled here. Two consequences
/// worth naming: the builder is infallible, because every piece of it was
/// validated when the registry was linted; and the `ttl_s` below is the
/// registry's own, not a second copy of it.
pub(super) struct StateKeys {
    link: (Subject, Key),
    /// One per distinct remote, paired with the endpoint name it describes.
    endpoints: Vec<(String, Subject, Key)>,
}

impl StateKeys {
    pub(super) fn of(origin: &LocalOrigin, plane: &dyn SduPlane) -> Self {
        let device = plane.device();
        let resolve = |subject: Subject| {
            let k = key(origin, &subject);
            (subject, k)
        };

        let mut endpoints = Vec::new();
        let mut seen = std::collections::BTreeSet::new();
        for lane in plane.lanes() {
            let name = lane.key.endpoint.as_str();
            if seen.insert(name.to_string()) {
                let (subject, k) = resolve(Subject::device_sdu_endpoint(device, name));
                endpoints.push((name.to_string(), subject, k));
            }
        }

        Self {
            link: resolve(Subject::device_sdu_link(device)),
            endpoints,
        }
    }
}

/// The `ttl_s` the registry declares for this producer's `state` subjects.
///
/// All three declare the same bound, and RFC 08 §5 requires every `state`
/// subject to declare one — zenkey-build refuses to generate a registry where
/// one does not — so reading it off any of them is reading the contract.
///
/// `expect` rather than a fallback, because a default here would be a second
/// opinion about the contract, silently used at exactly the moment the contract
/// had gone missing.
pub(super) fn declared_ttl_s() -> u64 {
    Subject::device_sdu_link("rf0")
        .ttl_s()
        .expect("a state subject declares ttl_s (RFC 08 §5), enforced at build time")
}

/// `ttl_s` is the value the documents advertise **and** the cadence they are
/// refreshed at, and the caller has already checked it does not exceed what
/// [`StateKeys::ttl_s`] declares — an operator may refresh faster than the
/// contract promises, never slower.
pub(super) async fn publish_loop(
    session: Session,
    keys: StateKeys,
    plane: Arc<dyn SduPlane>,
    ttl_s: u64,
) {
    let StateKeys {
        link: (link_subject, link_key),
        endpoints: endpoint_keys,
    } = keys;

    // Refresh at half the TTL so a reader never sees a document expire while
    // the producer is healthy.
    let interval = Duration::from_secs((ttl_s / 2).max(1));

    loop {
        // The QoS profile comes off each subject, which reads it from the
        // registry. It was `QosProfile::Refreshed` written here, which is the
        // same value and a second place for it to drift from the contract.
        let lanes = plane.lanes();
        put(
            &session,
            &link_key,
            &super::LinkState::of(
                plane.device(),
                ttl_s,
                &plane.capabilities(),
                lanes
                    .iter()
                    .map(|l| super::Lane::of(&l.key, &l.path, l.connected, l.backlog_bytes))
                    .collect(),
            ),
            link_subject.qos(),
        )
        .await;
        for (endpoint, subject, key) in &endpoint_keys {
            put(
                &session,
                key,
                &super::EndpointState::of(
                    plane.device(),
                    endpoint,
                    lanes.iter().map(|l| (&l.key, l.connected)),
                ),
                subject.qos(),
            )
            .await;
        }
        tokio::time::sleep(interval).await;
    }
}

pub(super) async fn put<T: serde::Serialize>(
    session: &Session,
    key: &zenkey::Key,
    doc: &T,
    qos: QosProfile,
) {
    let payload = match serde_json::to_string(doc) {
        Ok(p) => p,
        Err(e) => {
            tracing::error!(key = %key, error = %e, "state document did not serialize");
            return;
        }
    };
    if let Err(e) = session
        .put(key.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 = %key, error = %e, "state publication failed");
    }
}