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 driver with no lanes serves the whole management plane (#119).
//!
//! The acceptance for splitting the plane out of the daemon: a second
//! implementor — here a host carrying one stub netdev, built without
//! `modem-driver` anywhere in its dependency graph — calls `serve` and gets
//! the full contract: presence, `introspect`, `describe`, and a `lanes` that
//! says honestly why it cannot answer.

use std::sync::Arc;

use fake_medium::StubNetdev;
use modem_mgmt::{Host, MgmtConfig, Node, PRODUCER, PROFILE};
use zenkey::V1Context;

const PATIENCE: std::time::Duration = std::time::Duration::from_secs(20);

async fn operator(endpoint: &str) -> zenoh::Session {
    let mut cfg = zenoh::Config::default();
    cfg.insert_json5("scouting/multicast/enabled", "false")
        .unwrap();
    cfg.insert_json5("connect/endpoints", &format!("[{endpoint:?}]"))
        .unwrap();
    zenoh::open(cfg).await.expect("operator session")
}

/// The first reply to a GET: `Ok(payload)` or `Err(error envelope)`.
async fn ask(session: &zenoh::Session, key: &str) -> Result<String, serde_json::Value> {
    let replies = session.get(key).await.expect("get");
    let r = tokio::time::timeout(PATIENCE, replies.recv_async())
        .await
        .expect("a reply within patience")
        .expect("the channel is live");
    match r.result() {
        Ok(s) => Ok(s.payload().try_to_string().unwrap().into_owned()),
        Err(e) => Err(serde_json::from_str(&e.payload().try_to_string().unwrap()).expect("json")),
    }
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_host_with_no_lane_code_serves_the_whole_contract() {
    let endpoint = "tcp/127.0.0.1:7640";
    let host =
        Arc::new(Host::new().with(Node::netdev("wwan0", Arc::new(StubNetdev::new("wwan0")))));
    let mgmt = modem_mgmt::serve(
        &MgmtConfig {
            listen: vec![endpoint.to_string()],
            ttl_s: 4,
            telemetry_interval_ms: 50,
            ..MgmtConfig::default()
        },
        host.clone(),
    )
    .await
    .expect("the plane comes up over a netdev alone");

    let op = operator(endpoint).await;
    let ctx = V1Context::for_producer(&PROFILE, PRODUCER).expect("context");

    // Presence: one producer, the host's.
    let alive = ctx.alive_key().as_str().to_string();
    let deadline = tokio::time::Instant::now() + PATIENCE;
    let mut seen = false;
    while tokio::time::Instant::now() < deadline && !seen {
        let replies = op
            .liveliness()
            .get(alive.as_str())
            .await
            .expect("liveliness");
        while let Ok(r) = replies.recv_async().await {
            seen |= r.result().is_ok();
        }
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
    }
    assert!(seen, "the netdev-only host never appeared on the roster");

    // The contract, verbatim, and its schemas.
    let toml = ask(&op, ctx.rpc_key(&["introspect"]).unwrap().as_str())
        .await
        .expect("introspect answers");
    assert_eq!(toml, modem_contract::registry::modem::REGISTRY_SOURCE);
    let describe = ask(&op, ctx.rpc_key(&["describe"]).unwrap().as_str())
        .await
        .expect("describe answers");
    assert_eq!(describe, modem_contract::schema::describe_json());

    // The one procedure this device cannot do, refused with the reason.
    let err = ask(
        &op,
        ctx.rpc_key(&["device", "wwan0", "sdu", "lanes"])
            .unwrap()
            .as_str(),
    )
    .await
    .expect_err("lanes on a netdev is an error envelope");
    assert_eq!(err["error"], "error/gated");
    assert!(
        err["message"]
            .as_str()
            .unwrap_or_default()
            .contains("capability:sdu"),
        "{err}"
    );

    mgmt.shutdown().await;
    host.shutdown().await;
}

/// The next sample on `sub`, as JSON, within `PATIENCE`.
async fn next_json(
    sub: &zenoh::pubsub::Subscriber<zenoh::handlers::FifoChannelHandler<zenoh::sample::Sample>>,
) -> serde_json::Value {
    let s = tokio::time::timeout(PATIENCE, sub.recv_async())
        .await
        .expect("a sample in time")
        .expect("live");
    serde_json::from_slice(&s.payload().to_bytes()).expect("json")
}

/// A netdev has a status too (#121), read from the device alone because no
/// lane driver stands between: `unknown` while the stub has no carrier to
/// read, and whatever it says once it says something — as a document, and
/// as one event for the transition.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_netdev_has_an_operational_status_of_its_own() {
    let endpoint = "tcp/127.0.0.1:7641";
    let stub = Arc::new(StubNetdev::new("wwan0"));
    let host = Arc::new(Host::new().with(Node::netdev("wwan0", stub.clone())));
    let mgmt = modem_mgmt::serve(
        &MgmtConfig {
            listen: vec![endpoint.to_string()],
            ttl_s: 4,
            telemetry_interval_ms: 50,
            ..MgmtConfig::default()
        },
        host.clone(),
    )
    .await
    .expect("the plane comes up over a netdev alone");

    let op = operator(endpoint).await;
    let ctx = V1Context::for_producer(&PROFILE, PRODUCER).expect("context");
    let oper_key = ctx
        .state_key(&["device", "wwan0", "oper"])
        .expect("state key")
        .as_str()
        .to_string();
    let docs = op
        .declare_subscriber(oper_key.as_str())
        .await
        .expect("subscriber");
    let events = op
        .declare_subscriber("v1/*/events/modem/device/wwan0/oper_change/**")
        .await
        .expect("subscriber");
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;

    let first = next_json(&docs).await;
    assert_eq!(first["device"], "wwan0");
    assert_eq!(
        first["status"], "unknown",
        "a stub has no carrier to read: {first}"
    );
    assert_eq!(
        first["recoverable"], true,
        "unknown is not a reason to restart"
    );

    stub.set_oper(modem_device::OperStatus::up());
    let deadline = tokio::time::Instant::now() + PATIENCE;
    let up = loop {
        let doc = next_json(&docs).await;
        if doc["status"] == "up" || tokio::time::Instant::now() > deadline {
            break doc;
        }
    };
    assert_eq!(up["status"], "up", "{up}");
    let event = next_json(&events).await;
    assert_eq!(event["status"], "up");
    assert_eq!(event["device"], "wwan0");
    assert_eq!(event["occurrences"], 1);

    // The registration document lists what it holds (#122, #130): the
    // kernel's counters and nothing of a lane driver's — and the
    // producer's own capabilities under `*`, none.
    let sensor_key = ctx.state_key(&["sensor"]).expect("state key");
    let sensors = op
        .declare_subscriber(sensor_key.as_str())
        .await
        .expect("subscriber");
    let sensor = next_json(&sensors).await;
    assert_eq!(
        sensor["capabilities"]["wwan0"],
        serde_json::json!(["netdev"]),
        "{sensor}"
    );
    assert_eq!(
        sensor["capabilities"]["*"],
        serde_json::json!([]),
        "{sensor}"
    );
    assert_eq!(sensor["zenkey"], modem_contract::ZENKEY_VERSION);

    // And an identity, once the device says what it is.
    stub.set_identity(
        modem_device::Identity::unknown()
            .mfg_name("Sierra Wireless")
            .model_name("EM7565"),
    );
    let identity_key = ctx
        .state_key(&["device", "wwan0", "identity"])
        .expect("state key");
    let identities = op
        .declare_subscriber(identity_key.as_str())
        .await
        .expect("subscriber");
    let deadline = tokio::time::Instant::now() + PATIENCE;
    let identity = loop {
        let doc = next_json(&identities).await;
        if doc["model_name"] == "EM7565" || tokio::time::Instant::now() > deadline {
            break doc;
        }
    };
    assert_eq!(identity["mfg_name"], "Sierra Wireless", "{identity}");
    assert_eq!(identity["model_name"], "EM7565", "{identity}");

    mgmt.shutdown().await;
    host.shutdown().await;
}

/// The structural half of the claim: this crate's dependency graph has no
/// lane code in it. Read from the manifest, so a dependency added later fails
/// here rather than silently making the IP driver link a scheduler.
#[test]
fn the_plane_does_not_depend_on_the_lane_driver() {
    let manifest = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/Cargo.toml"))
        .expect("Cargo.toml");
    assert!(
        !manifest.contains("modem-driver"),
        "modem-mgmt must not depend on modem-driver: the plane serves any driver (#119)"
    );
}