modem-contract 0.3.0

The management-plane contract of zenoh-modem: the registry, its payload types and their schemas, compiled once for every driver that serves it
Documentation
//! What every payload on this producer's keyspace looks like (RFC 08 §7).
//!
//! `introspect` answers what this driver *serves*; `describe` answers what
//! those payloads *are*. Without it a generic tool can see that a sample claims
//! to be a `Counter` and cannot check that it is one — which `zenctl topic
//! echo` reports, per sample, as `not-validated: no schema served for this
//! type`.
//!
//! **The schemas are derived, not written.** Four of the six come straight from
//! the types `documents.rs` defines and `modem-mgmt` serializes, so they cannot
//! describe something other than what goes on the wire. RFC 08 §6.1 applies
//! here as much as anywhere: a description that lies is worse than one that is
//! absent, and the way to keep one honest is to not give it a second source of
//! truth to drift from. The two that *are* hand-written describe things this
//! crate does not own — a TOML blob and zenkey's own envelope — and neither has
//! a shape we could get wrong without noticing.

use std::sync::LazyLock;

use serde_json::json;
use zenkey::schema::{SchemaSet, TypeSchema};

use crate::documents::{
    Ack, ActionEvent, ActionOutcome, ActionRequest, DestinationState, DeviceFault, EndpointState,
    Identity, IdentityChange, LaneTable, LinkState, Oper, OperChange, RadioState, SecurityState,
    Sensor,
};

/// Every payload type this producer serves, described.
fn build() -> SchemaSet {
    SchemaSet::builder("zenoh-modem")
        // Every telemetry subject shares one type, and it is exactly this: a
        // non-negative integer. Monotonic-versus-gauge is a property of a
        // *series*, not a value — no single sample could satisfy or violate it,
        // so a keyword asserting it would be unfalsifiable, which is the failure
        // §6.1 exists to prevent. `queue_depth` says it is a gauge in its
        // registry description, where a reader can act on it. `unit` likewise
        // already exists on `[[subject]]` and reaches the wire; repeating it
        // here would only create a second place for it to drift.
        .json::<u64>("Counter")
        // A gauge is any integer: a dBm is negative (#120, #123).
        .json::<i64>("Gauge")
        .json::<f64>("Measure")
        .json::<LinkState>("LinkState")
        .json::<SecurityState>("SecurityState")
        .json::<EndpointState>("EndpointState")
        .json::<LaneTable>("LaneTable")
        .json::<Oper>("Oper")
        .json::<Identity>("Identity")
        .json::<RadioState>("RadioState")
        .json::<DestinationState>("DestinationState")
        .json::<Sensor>("Sensor")
        .json::<OperChange>("OperChange")
        .json::<DeviceFault>("DeviceFault")
        .json::<IdentityChange>("IdentityChange")
        .json::<Ack>("Ack")
        .json::<ActionRequest>("ActionRequest")
        .json::<ActionOutcome>("ActionOutcome")
        .json::<ActionEvent>("ActionEvent")
        // The configuration convention's shapes are zenkey's (RFC 05 §5.1,
        // v1.42), described from the same types every producer of the
        // convention serializes.
        .json::<zenkey::config::ConfigView>("ConfigView")
        .json::<zenkey::config::ConfigChange>("ConfigChange")
        .json::<zenkey::config::ControlRequest>("ControlRequest")
        .json::<zenkey::config::ConfigChangeEvent>("ConfigChangeEvent")
        // Not JSON at all: `introspect` replies with the registry TOML verbatim,
        // under `application/toml`. The schema describes the serde data model —
        // a string — and `contentMediaType` carries the one fact a generic tool
        // actually needs, which is *do not parse this as JSON*. Encoding is the
        // separate axis RFC 08 §7 names, and the registry declares it too.
        .entry(
            "RegistryToml",
            TypeSchema::json_schema(json!({
                "$schema": "https://json-schema.org/draft/2020-12/schema",
                "title": "RegistryToml",
                "description": "the producer's registry, verbatim, as TOML text",
                "type": "string",
                "contentMediaType": "application/toml",
            })),
        )
        // The describe reply itself. Hand-written because it describes zenkey's
        // envelope rather than one of ours, and that shape is fixed by RFC 08 §7
        // and by `SchemaSet::to_json`, not by this crate. Deliberately open
        // about `kind`: the vocabulary is extensible (json-schema, protobuf,
        // cdr, …), so pinning it to what we happen to emit would describe a
        // narrower contract than the convention has. `hash` is pinned, because
        // the RFC and every zenkey constructor agree it is sha256.
        .entry(
            "SchemaSet",
            TypeSchema::json_schema(json!({
                "$schema": "https://json-schema.org/draft/2020-12/schema",
                "title": "SchemaSet",
                "description": "RFC 08 §7's describe envelope",
                "type": "object",
                "required": ["schema_version", "app", "types"],
                "properties": {
                    "schema_version": { "type": "integer" },
                    "app": { "type": "string" },
                    "types": {
                        "type": "object",
                        "additionalProperties": {
                            "type": "object",
                            "required": ["kind", "hash"],
                            "properties": {
                                "kind": { "type": "string" },
                                "hash": {
                                    "type": "string",
                                    "pattern": "^sha256:[0-9a-f]{64}$"
                                }
                            }
                        }
                    }
                }
            })),
        )
        .build()
}

/// Built once, like `introspect`'s constant.
static SCHEMAS: LazyLock<SchemaSet> = LazyLock::new(build);

/// The pre-rendered `describe` reply.
static DESCRIBE_JSON: LazyLock<String> = LazyLock::new(|| SCHEMAS.to_json());

/// Every payload type this producer serves, described.
pub fn schema_set() -> &'static SchemaSet {
    &SCHEMAS
}

/// The `describe` reply, rendered once.
pub fn describe_json() -> &'static str {
    &DESCRIBE_JSON
}

/// RFC 08 §7's totality bound, checked before this driver claims to be alive.
///
/// Deliberately not `SchemaSetBuilder::build_verified`, which panics: a panic
/// inside a `LazyLock` inside a spawned queryable is the worst available place
/// for this to go wrong. RFC 08 §6.1 says an implementation must not report
/// `alive` while the declared set and the served set disagree, so this is called
/// on the way up and its failure is an ordinary startup error.
///
/// `TYPE_NAMES` is generated from the registry the build linted, so nothing here
/// is a hand-maintained list.
pub fn verify_total() -> anyhow::Result<()> {
    schema_set()
        .verify_covers(crate::registry::TYPE_NAMES)
        .map_err(|e| anyhow::anyhow!("{e}"))
}

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

    #[test]
    fn the_schema_set_is_total() {
        // RFC 08 §7's totality bound, against the generated list rather than a
        // list written here — which is the only version of this test that can
        // fail when someone adds a subject.
        verify_total().expect("every registry type must be described");
        assert_eq!(schema_set().app(), "zenoh-modem");
    }

    #[test]
    fn every_schema_is_a_valid_json_schema_document() {
        // Catches a malformed hand-written entry in milliseconds rather than
        // behind a twenty-second Zenoh test. The derived ones cannot really
        // fail this; the two hand-written ones are the reason it exists.
        for (name, schema) in schema_set().iter() {
            let document = schema
                .json_document()
                .unwrap_or_else(|| panic!("{name} has no JSON document"));
            jsonschema::validator_for(document)
                .unwrap_or_else(|e| panic!("{name} is not a valid JSON Schema: {e}"));
        }
    }

    #[test]
    fn the_describe_reply_parses_back() {
        // The reply is a string built once and handed out for ever; if it does
        // not round-trip, every consumer fails and nothing here would say why.
        let parsed = SchemaSet::parse(describe_json()).expect("the reply must parse");
        assert_eq!(parsed.len(), schema_set().len());
        assert_eq!(parsed.app(), "zenoh-modem");
    }
}