use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum Duplex {
Full,
Half,
}
impl From<modem_device::Duplex> for Duplex {
fn from(d: modem_device::Duplex) -> Self {
match d {
modem_device::Duplex::Full => Self::Full,
modem_device::Duplex::Half => Self::Half,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Capabilities {
pub tx_max_sdu: u16,
pub rx_max_sdu: u16,
pub reliable: bool,
pub duplex: Duplex,
pub max_batch_size: usize,
}
impl Capabilities {
#[must_use]
pub fn of(caps: &modem_device::Capabilities) -> Self {
Self {
tx_max_sdu: caps.tx_max_sdu,
rx_max_sdu: caps.rx_max_sdu,
reliable: caps.reliable,
duplex: caps.duplex.into(),
max_batch_size: caps.tx_max_sdu as usize + modem_device::LENGTH_PREFIX,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Lane {
pub lane: String,
pub endpoint: String,
pub reliable: bool,
pub rank: u8,
pub path: String,
pub connected: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub backlog_bytes: Option<u64>,
}
impl Lane {
#[must_use]
pub fn of(
key: &modem_device::LaneKey,
path: &std::path::Path,
connected: bool,
backlog_bytes: Option<u64>,
) -> Self {
Self {
lane: key.to_string(),
endpoint: key.endpoint.as_str().to_string(),
reliable: key.reliable,
rank: key.rank,
path: path.display().to_string(),
connected,
backlog_bytes,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct EndpointLane {
pub lane: String,
pub connected: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct LinkState {
pub device: String,
pub ttl_s: u64,
pub capabilities: Capabilities,
pub lanes: Vec<Lane>,
}
impl LinkState {
#[must_use]
pub fn of(
device: &str,
ttl_s: u64,
capabilities: &modem_device::Capabilities,
lanes: Vec<Lane>,
) -> Self {
Self {
device: device.to_string(),
ttl_s,
capabilities: Capabilities::of(capabilities),
lanes,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct LaneTable {
pub device: String,
pub capabilities: Capabilities,
pub lanes: Vec<Lane>,
}
impl LaneTable {
#[must_use]
pub fn of(device: &str, capabilities: &modem_device::Capabilities, lanes: Vec<Lane>) -> Self {
Self {
device: device.to_string(),
capabilities: Capabilities::of(capabilities),
lanes,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct EndpointState {
pub endpoint: String,
pub device: String,
pub lanes: Vec<EndpointLane>,
}
impl EndpointState {
#[must_use]
pub fn of<'a>(
device: &str,
endpoint: &str,
lanes: impl IntoIterator<Item = (&'a modem_device::LaneKey, bool)>,
) -> Self {
Self {
endpoint: endpoint.to_string(),
device: device.to_string(),
lanes: lanes
.into_iter()
.filter(|(key, _)| key.endpoint.as_str() == endpoint)
.map(|(key, connected)| EndpointLane {
lane: key.to_string(),
connected,
})
.collect(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct SecurityState {
pub device: String,
pub provider: String,
pub scope: String,
pub guarantees: Vec<String>,
pub authenticated_principal: Option<String>,
pub note: String,
}
impl SecurityState {
#[must_use]
pub fn of(device: &str, props: Option<&modem_device::SecurityProperties>) -> Self {
match props {
None => Self {
device: device.to_string(),
provider: "none".into(),
scope: "none".into(),
guarantees: Vec::new(),
authenticated_principal: None,
note: "no link-layer cryptography on this device; any link security is \
hop-by-hop, never end-to-end (architecture I6, §4.10)"
.into(),
},
Some(p) => Self {
device: device.to_string(),
provider: p.provider.clone(),
scope: p.scope.as_str().to_string(),
guarantees: p
.guarantees
.iter()
.map(|g| g.as_str().to_string())
.collect(),
authenticated_principal: p.principal.clone(),
note: "hop-by-hop, as the device and its layers report it; never \
end-to-end (architecture I6, §4.10)"
.into(),
},
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Oper {
pub device: String,
pub status: String,
pub admin: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
pub recoverable: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_change_ms: Option<u64>,
pub uptime_s: u64,
pub boot_id: String,
pub clock_synced: bool,
}
impl Oper {
#[must_use]
pub fn of(
device: &str,
status: &modem_device::OperStatus,
uptime_s: u64,
boot_id: &str,
clock_synced: bool,
) -> Self {
Self {
device: device.to_string(),
status: status.status.as_str().to_string(),
admin: status.admin.as_str().to_string(),
reason: status.reason.clone(),
recoverable: status.recoverable,
last_change_ms: status
.since
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_millis() as u64),
uptime_s,
boot_id: boot_id.to_string(),
clock_synced,
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct Identity {
pub device: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mfg_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub model_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub serial_num: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hardware_rev: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub firmware_rev: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub software_rev: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub imei: Option<String>,
}
impl Identity {
#[must_use]
pub fn unknown(device: &str) -> Self {
Self {
device: device.to_string(),
..Self::default()
}
}
#[must_use]
pub fn of(device: &str, id: &modem_device::Identity) -> Self {
Self {
device: device.to_string(),
mfg_name: id.mfg_name.clone(),
model_name: id.model_name.clone(),
serial_num: id.serial_num.clone(),
hardware_rev: id.hardware_rev.clone(),
firmware_rev: id.firmware_rev.clone(),
software_rev: id.software_rev.clone(),
imei: id.imei.clone(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct RadioState {
pub device: String,
pub registration: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub access_technology: Option<String>,
}
impl RadioState {
#[must_use]
pub fn of(device: &str, report: &modem_device::Report) -> Option<Self> {
let registration = report.registration?;
Some(Self {
device: device.to_string(),
registration: registration.as_str().to_string(),
access_technology: report.access_technology.map(|t| t.as_str().to_string()),
})
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct DestinationState {
pub device: String,
pub destination: String,
#[serde(default)]
pub addresses: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rx_rate_bps: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tx_rate_bps: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rx_max_rate_bps: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tx_max_rate_bps: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub latency_us: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resources_pct: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rx_quality_pct: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tx_quality_pct: Option<f64>,
}
impl DestinationState {
#[must_use]
pub fn of(device: &str, d: &modem_device::Destination) -> Self {
let pct = |m: Option<i32>| m.map(|m| f64::from(m) / 1_000.0);
Self {
device: device.to_string(),
destination: d.id.clone(),
addresses: d.addresses.iter().map(ToString::to_string).collect(),
rx_rate_bps: d.rx_rate,
tx_rate_bps: d.tx_rate,
rx_max_rate_bps: d.rx_max_rate,
tx_max_rate_bps: d.tx_max_rate,
latency_us: d.latency,
resources_pct: pct(d.resources),
rx_quality_pct: pct(d.rx_quality),
tx_quality_pct: pct(d.tx_quality),
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Sensor {
pub version: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub build: Option<String>,
pub zenkey: String,
#[serde(default)]
pub capabilities: std::collections::BTreeMap<String, Vec<String>>,
#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
pub config_hash: std::collections::BTreeMap<String, String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct OperChange {
pub device: String,
pub event_id: String,
pub at_ms: u64,
pub status: String,
pub reason: String,
pub occurrences: u64,
}
impl OperChange {
#[must_use]
pub fn of(
device: &str,
event_id: String,
at_ms: u64,
status: &modem_device::OperStatus,
occurrences: u64,
) -> Self {
Self {
device: device.to_string(),
event_id,
at_ms,
status: status.status.as_str().to_string(),
reason: status.reason.clone().unwrap_or_else(|| {
match status.status {
modem_device::OperState::Up => "passing traffic",
modem_device::OperState::Unknown => "the device has not said",
_ => "",
}
.to_string()
}),
occurrences,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct IdentityChange {
pub device: String,
pub event_id: String,
pub at_ms: u64,
pub before: Identity,
pub after: Identity,
pub occurrences: u64,
}
impl IdentityChange {
#[must_use]
pub fn of(
device: &str,
event_id: String,
at_ms: u64,
before: &modem_device::Identity,
after: &modem_device::Identity,
occurrences: u64,
) -> Self {
Self {
device: device.to_string(),
event_id,
at_ms,
before: Identity::of(device, before),
after: Identity::of(device, after),
occurrences,
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ActionRequest {
#[serde(default)]
pub arguments: std::collections::BTreeMap<String, zenkey::config::ParamValue>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ActionOutcome {
pub detail: String,
#[serde(default)]
pub cost: std::collections::BTreeMap<String, i64>,
}
impl ActionOutcome {
#[must_use]
pub fn of(outcome: &modem_device::action::ActionOutcome) -> Self {
Self {
detail: outcome.detail.clone(),
cost: outcome.cost.clone(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ActionEvent {
pub device: String,
pub event_id: String,
pub at_ms: u64,
pub action: String,
#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
pub arguments: std::collections::BTreeMap<String, zenkey::config::ParamValue>,
pub outcome: String,
#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
pub cost: std::collections::BTreeMap<String, i64>,
pub detail: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub actor: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub request_id: Option<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Ack {}
#[cfg(test)]
mod tests {
use super::*;
fn keys(value: &serde_json::Value) -> Vec<String> {
let mut names: Vec<String> = value
.as_object()
.expect("an object")
.keys()
.cloned()
.collect();
names.sort();
names
}
#[test]
fn renaming_a_field_is_a_wire_break_not_a_refactor() {
let link = serde_json::to_value(LinkState {
device: "rf0".into(),
ttl_s: 60,
capabilities: Capabilities {
tx_max_sdu: 220,
rx_max_sdu: 220,
reliable: false,
duplex: Duplex::Half,
max_batch_size: 222,
},
lanes: Vec::new(),
})
.expect("serializes");
assert_eq!(keys(&link), ["capabilities", "device", "lanes", "ttl_s"]);
assert_eq!(
keys(&link["capabilities"]),
[
"duplex",
"max_batch_size",
"reliable",
"rx_max_sdu",
"tx_max_sdu"
]
);
let security = serde_json::to_value(SecurityState::of("rf0", None)).expect("serializes");
assert_eq!(
keys(&security),
[
"authenticated_principal",
"device",
"guarantees",
"note",
"provider",
"scope"
]
);
assert!(
security["authenticated_principal"].is_null(),
"I6 names the absence explicitly; omitting it would be silence"
);
assert!(
security.get("encrypted").is_none(),
"a bare boolean is exactly what I6 forbids"
);
let props = modem_device::SecurityProperties::new("test", modem_device::Scope::Hop)
.guarantee(modem_device::Guarantee::Integrity)
.guarantee(modem_device::Guarantee::AntiReplay);
let sealed =
serde_json::to_value(SecurityState::of("rf0", Some(&props))).expect("serializes");
assert_eq!(keys(&sealed), keys(&security));
assert_eq!(sealed["provider"], "test");
assert_eq!(sealed["scope"], "hop");
assert_eq!(
sealed["guarantees"],
serde_json::json!(["integrity", "anti-replay"])
);
assert!(sealed["authenticated_principal"].is_null());
assert!(sealed.get("encrypted").is_none());
let lane = serde_json::to_value(Lane::of(
&modem_device::LaneKey {
endpoint: modem_device::EndpointId::new("b"),
reliable: false,
rank: 0,
},
std::path::Path::new("/run/x"),
true,
Some(1024),
))
.expect("serializes");
assert_eq!(
keys(&lane),
[
"backlog_bytes",
"connected",
"endpoint",
"lane",
"path",
"rank",
"reliable"
]
);
}
#[test]
fn the_endpoint_document_stays_reduced() {
let lane = serde_json::to_value(EndpointLane {
lane: "peer-b/rel#0".into(),
connected: true,
})
.expect("serializes");
assert_eq!(keys(&lane), ["connected", "lane"]);
}
#[test]
fn the_lane_table_reports_duplex_like_the_link_document() {
let caps = Capabilities {
tx_max_sdu: 340,
rx_max_sdu: 270,
reliable: true,
duplex: Duplex::Full,
max_batch_size: 342,
};
let table = serde_json::to_value(LaneTable {
device: "sat0".into(),
capabilities: caps,
lanes: Vec::new(),
})
.expect("serializes");
assert_eq!(table["capabilities"]["duplex"], "full");
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct DeviceFault {
pub device: String,
pub event_id: String,
pub at_ms: u64,
pub lane: Option<String>,
pub edge: String,
pub detail: String,
pub occurrences: u64,
}
impl DeviceFault {
#[must_use]
pub fn of(
device: &str,
event_id: String,
at_ms: u64,
event: &modem_device::DeviceEvent,
occurrences: u64,
) -> Self {
Self {
device: device.to_string(),
event_id,
at_ms,
lane: event.lane.as_ref().map(ToString::to_string),
edge: match event.edge {
modem_device::Edge::Raised => "raised".into(),
modem_device::Edge::Cleared => "cleared".into(),
other => format!("{other:?}").to_lowercase(),
},
detail: event.detail.clone(),
occurrences,
}
}
}