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
//! A netdev's neighbours, as `state` (#137).
//!
//! `state/modem/device/{device}/destination/{destination}`: one document per
//! neighbour the device's radio reports, with the radio's metrics toward it.
//! A neighbour comes and goes on its own, so unlike the other state
//! documents the set of keys changes: a document is put when a destination
//! appears or changes, refreshed at half the TTL like every state document,
//! and **deleted** when the radio reports it gone, so a reader listing the
//! subtree sees the neighbour table rather than its history.
//!
//! The device is polled once a second, which is the resolution a neighbour
//! edge is published at; a poll that finds nothing changed puts nothing.

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

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

use modem_contract::documents::DestinationState;

/// How often the device's neighbour table is read.
const POLL: Duration = Duration::from_secs(1);

pub(super) async fn publish_loop(
    session: Session,
    origin: LocalOrigin,
    device: String,
    dev: Arc<dyn modem_device::Netdev>,
    ttl_s: u64,
) {
    let refresh = Duration::from_secs((ttl_s / 2).max(1));
    let bound = Subject::device_destination(&device, "x")
        .cardinality()
        .unwrap_or(64) as usize;
    let mut published: BTreeMap<String, (Key, DestinationState)> = BTreeMap::new();
    let mut last_refresh: Option<Instant> = None;
    let mut warned = false;
    loop {
        let due = last_refresh.is_none_or(|t| t.elapsed() >= refresh);
        let mut now = dev.destinations().unwrap_or_default();
        if now.len() > bound {
            // The registry's bound is a promise to every consumer; a radio
            // with more neighbours than it is told so, once, and the rest go
            // unpublished rather than the bound unkept.
            if !warned {
                tracing::warn!(
                    device = %device,
                    reported = now.len(),
                    bound,
                    "more destinations than the registry's cardinality; publishing the first"
                );
                warned = true;
            }
            now.truncate(bound);
        }
        let mut next = BTreeMap::new();
        for d in &now {
            let subject = Subject::device_destination(&device, &d.id);
            let k = key(&origin, &subject);
            let doc = DestinationState::of(&device, d);
            let changed = published.get(&d.id).is_none_or(|(_, old)| *old != doc);
            if changed || due {
                crate::state::put(&session, &k, &doc, subject.qos()).await;
            }
            next.insert(d.id.clone(), (k, doc));
        }
        for (id, (k, _)) in &published {
            if !next.contains_key(id)
                && let Err(e) = session.delete(k.as_keyexpr()).await
            {
                tracing::debug!(key = %k, error = %e, "destination delete failed");
            }
        }
        published = next;
        if due {
            last_refresh = Some(Instant::now());
        }
        tokio::time::sleep(POLL).await;
    }
}