Skip to main content

modem_contract/
documents.rs

1//! The management plane's payloads, as types.
2//!
3//! These existed as `serde_json::json!` literals until #37, and
4//! `registry/types.toml` named Rust paths for four of them —
5//! `modem_driver::mgmt::LinkState` and its siblings — that **had never
6//! existed**. Nothing caught it: `zenkey-build`'s type-table lint checks that
7//! every referenced type *name* resolves to a table entry, and never reads the
8//! `rust` field at all. So the registry already carried exactly the drift
9//! `@rpc/modem/describe` exists to prevent.
10//!
11//! Making the paths real is what lets the served schemas be derived from the
12//! thing that is actually serialized, rather than hand-written beside it. A
13//! second hand-maintained copy of six shapes, next to a first copy that has
14//! already drifted, would repeat the mistake in a bigger font.
15//!
16//! Two shapes here are deliberately *not* unified, and the tests below say so.
17
18use schemars::JsonSchema;
19use serde::{Deserialize, Serialize};
20
21/// Whether the medium can transmit and receive at once.
22///
23/// Defined here rather than by putting serde on [`modem_device::Duplex`]:
24/// `modem-device` is the data-path crate CI guards, and how a value is
25/// rendered on the management plane is not its business.
26#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
27#[serde(rename_all = "lowercase")]
28#[non_exhaustive]
29pub enum Duplex {
30    /// Transmit and receive are independent.
31    Full,
32    /// Transmitting blocks receiving and vice versa.
33    Half,
34}
35
36impl From<modem_device::Duplex> for Duplex {
37    fn from(d: modem_device::Duplex) -> Self {
38        match d {
39            modem_device::Duplex::Full => Self::Full,
40            modem_device::Duplex::Half => Self::Half,
41        }
42    }
43}
44
45/// What the medium behind a device can carry.
46#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
47pub struct Capabilities {
48    /// Largest SDU the medium will transmit, in bytes.
49    pub tx_max_sdu: u16,
50    /// Largest SDU the medium will deliver, in bytes.
51    pub rx_max_sdu: u16,
52    /// Whether the medium delivers in order and without loss.
53    pub reliable: bool,
54    /// Whether transmit and receive contend.
55    pub duplex: Duplex,
56    /// The largest `batch_size` Zenoh may be configured with.
57    ///
58    /// The number an operator cannot derive without knowing that Zenoh's
59    /// two-byte length prefix lives *inside* the batch.
60    pub max_batch_size: usize,
61}
62
63impl Capabilities {
64    /// From the medium's own declaration.
65    #[must_use]
66    pub fn of(caps: &modem_device::Capabilities) -> Self {
67        Self {
68            tx_max_sdu: caps.tx_max_sdu,
69            rx_max_sdu: caps.rx_max_sdu,
70            reliable: caps.reliable,
71            duplex: caps.duplex.into(),
72            max_batch_size: caps.tx_max_sdu as usize + modem_device::LENGTH_PREFIX,
73        }
74    }
75}
76
77/// One lane, in full.
78#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
79pub struct Lane {
80    /// The lane's own rendering: endpoint, reliability and rank.
81    pub lane: String,
82    /// Which remote it reaches. An addressing identifier, never a proof of
83    /// identity (invariant I5).
84    pub endpoint: String,
85    /// Whether it promises ordered, loss-free delivery.
86    pub reliable: bool,
87    /// Scheduling rank; lower is more urgent.
88    pub rank: u8,
89    /// Where its socket lives.
90    pub path: String,
91    /// Whether Zenoh is attached to it right now.
92    pub connected: bool,
93    /// Bytes Zenoh has written to this lane's socket that the driver has not
94    /// read yet (#151): which lane is backed up, where
95    /// `sched/lane_backlog_bytes` says only how much in all. Absent where
96    /// the driver cannot measure it.
97    #[serde(default, skip_serializing_if = "Option::is_none")]
98    pub backlog_bytes: Option<u64>,
99}
100
101impl Lane {
102    /// One lane, from the facts a driver has about it.
103    #[must_use]
104    pub fn of(
105        key: &modem_device::LaneKey,
106        path: &std::path::Path,
107        connected: bool,
108        backlog_bytes: Option<u64>,
109    ) -> Self {
110        Self {
111            lane: key.to_string(),
112            endpoint: key.endpoint.as_str().to_string(),
113            reliable: key.reliable,
114            rank: key.rank,
115            path: path.display().to_string(),
116            connected,
117            backlog_bytes,
118        }
119    }
120}
121
122/// One lane, as an endpoint document names it.
123///
124/// **Deliberately reduced**, and not an oversight. `state/modem/{device}/
125/// endpoint/{endpoint}` is the cardinality-64 subject and it is republished
126/// every `ttl_s/2` for ever; §4.6's whole argument is that those bytes are
127/// billed on a 2400 bit/s link. Carrying the full [`Lane`] here would multiply
128/// the largest refreshed document about fourfold to restate what
129/// `state/modem/device/{device}/sdu/link` already carries once.
130#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
131pub struct EndpointLane {
132    /// The lane's own rendering.
133    pub lane: String,
134    /// Whether Zenoh is attached to it right now.
135    pub connected: bool,
136}
137
138/// `state/modem/device/{device}/sdu/link` — what one device's medium is and what it carries.
139#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
140pub struct LinkState {
141    /// The local device.
142    pub device: String,
143    /// Seconds this document stays fresh. Refreshed at half this.
144    pub ttl_s: u64,
145    /// What the medium behind it can carry.
146    pub capabilities: Capabilities,
147    /// Every lane on the device.
148    pub lanes: Vec<Lane>,
149}
150
151impl LinkState {
152    /// The link document, from the facts: the device, its freshness bound,
153    /// what its medium can carry, and its lanes.
154    #[must_use]
155    pub fn of(
156        device: &str,
157        ttl_s: u64,
158        capabilities: &modem_device::Capabilities,
159        lanes: Vec<Lane>,
160    ) -> Self {
161        Self {
162            device: device.to_string(),
163            ttl_s,
164            capabilities: Capabilities::of(capabilities),
165            lanes,
166        }
167    }
168}
169
170/// `@rpc/modem/device/{device}/sdu/lanes` — the same facts, on demand.
171///
172/// Shares [`Capabilities`] with [`LinkState`] rather than carrying its own.
173/// Before #37 this document omitted `duplex`, which was an artefact of two
174/// `json!` literals typed months apart rather than a decision — there is no
175/// reason the lanes procedure should answer with a version of the medium's
176/// capabilities that leaves one out.
177#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
178pub struct LaneTable {
179    /// The local device.
180    pub device: String,
181    /// What the medium behind it can carry.
182    pub capabilities: Capabilities,
183    /// Every lane on the device.
184    pub lanes: Vec<Lane>,
185}
186
187impl LaneTable {
188    /// The lane table, from the same facts as [`LinkState`].
189    #[must_use]
190    pub fn of(device: &str, capabilities: &modem_device::Capabilities, lanes: Vec<Lane>) -> Self {
191        Self {
192            device: device.to_string(),
193            capabilities: Capabilities::of(capabilities),
194            lanes,
195        }
196    }
197}
198
199/// `state/modem/endpoint/{device}/{endpoint}` — one remote, and its lanes.
200#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
201pub struct EndpointState {
202    /// The medium's name for this remote. An addressing identifier, never a
203    /// proof of identity (invariant I5).
204    pub endpoint: String,
205    /// The local device that reaches it.
206    pub device: String,
207    /// The lanes toward it.
208    pub lanes: Vec<EndpointLane>,
209}
210
211impl EndpointState {
212    /// One remote's document: its lanes, reduced, from the device's lanes.
213    #[must_use]
214    pub fn of<'a>(
215        device: &str,
216        endpoint: &str,
217        lanes: impl IntoIterator<Item = (&'a modem_device::LaneKey, bool)>,
218    ) -> Self {
219        Self {
220            endpoint: endpoint.to_string(),
221            device: device.to_string(),
222            lanes: lanes
223                .into_iter()
224                .filter(|(key, _)| key.endpoint.as_str() == endpoint)
225                .map(|(key, connected)| EndpointLane {
226                    lane: key.to_string(),
227                    connected,
228                })
229                .collect(),
230        }
231    }
232}
233
234/// `state/modem/device/{device}/security` — properties, never a boolean.
235///
236/// Invariant I6, demonstrated rather than described. A device that provides
237/// no link security reports an empty guarantee set rather than omitting the
238/// subject or publishing a bare `encrypted: false`, which would say nothing
239/// about mode, scope, key management or peer authentication. A device, or a
240/// layer above it, that does provide something reports it through
241/// [`modem_device::Device::security`], and this document carries exactly
242/// that: what the device and its layers guarantee, hop by hop.
243///
244/// Note there is no `encrypted` field and cannot be one: serde emits what the
245/// type has. That is I6 enforced where it is enforceable, which is why the
246/// served schema does not additionally need to *forbid* it.
247#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
248pub struct SecurityState {
249    /// The local device.
250    pub device: String,
251    /// Who provides link security, if anyone.
252    pub provider: String,
253    /// What it covers.
254    pub scope: String,
255    /// The properties it guarantees, named individually.
256    pub guarantees: Vec<String>,
257    /// The principal the far side authenticated as, if any.
258    ///
259    /// Explicitly null rather than absent: I6 is about naming what is *not*
260    /// guaranteed, and omitting the field would be silence.
261    pub authenticated_principal: Option<String>,
262    /// Why the above reads as it does.
263    pub note: String,
264}
265
266impl SecurityState {
267    /// What the device reports (`Some`), or the statement that it reports
268    /// nothing (`None`): no link cryptography, said as properties.
269    #[must_use]
270    pub fn of(device: &str, props: Option<&modem_device::SecurityProperties>) -> Self {
271        match props {
272            None => Self {
273                device: device.to_string(),
274                provider: "none".into(),
275                scope: "none".into(),
276                guarantees: Vec::new(),
277                authenticated_principal: None,
278                note: "no link-layer cryptography on this device; any link security is \
279                       hop-by-hop, never end-to-end (architecture I6, §4.10)"
280                    .into(),
281            },
282            Some(p) => Self {
283                device: device.to_string(),
284                provider: p.provider.clone(),
285                scope: p.scope.as_str().to_string(),
286                guarantees: p
287                    .guarantees
288                    .iter()
289                    .map(|g| g.as_str().to_string())
290                    .collect(),
291                authenticated_principal: p.principal.clone(),
292                note: "hop-by-hop, as the device and its layers report it; never \
293                       end-to-end (architecture I6, §4.10)"
294                    .into(),
295            },
296        }
297    }
298}
299
300// ── Keyspace v2 documents (#120) ─────────────────────────────────────────────
301//
302// Declared with the registry break so the keys and their shapes settle once;
303// the producers that fill them arrived with #121 (`Oper`, `OperChange`) and arrive with #122
304// (`Identity`, `IdentityChange`, `Sensor`) and #128 (`Ack` from `persist`).
305// Until then a document that nobody produces is recorded in
306// `conditional.lock` with the issue that will produce it — declared, and
307// honest about being silent.
308
309/// `state/modem/device/{device}/oper` — RFC 2863's operational status, typed
310/// (#121). Only the states something produces are declared: `up`, `down`,
311/// `notPresent`, `unknown`; a coverage gap is `down` with `recoverable: true`,
312/// never `dormant`, because Linux's operstate defines dormant as L1 up.
313#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
314pub struct Oper {
315    /// The local device.
316    pub device: String,
317    /// `up` | `down` | `notPresent` | `unknown`.
318    pub status: String,
319    /// `up` | `down`: radio silence (EMCON) is `down` here and distinguishable
320    /// from a failure.
321    pub admin: String,
322    /// Why, in the device's words, when it is not `up`.
323    #[serde(default, skip_serializing_if = "Option::is_none")]
324    pub reason: Option<String>,
325    /// Whether the device expects to come back on its own — a coverage gap
326    /// does, a dead medium does not. This is what a supervisor reads before
327    /// deciding to restart (#96).
328    pub recoverable: bool,
329    /// Milliseconds since the epoch of the last status change, as the
330    /// device's clock had it.
331    #[serde(default, skip_serializing_if = "Option::is_none")]
332    pub last_change_ms: Option<u64>,
333    /// Seconds since this driver started: an ordering a wrong wall clock
334    /// cannot corrupt.
335    pub uptime_s: u64,
336    /// One id per driver start, so two events a second apart on either side
337    /// of a restart are told apart.
338    pub boot_id: String,
339    /// Whether the wall clock here is believed synchronised. A field unit may
340    /// have no RTC; `uptime_s` and `boot_id` are how a reader orders its
341    /// events anyway.
342    pub clock_synced: bool,
343}
344
345impl Oper {
346    /// The document, from what the device says and what the host knows.
347    ///
348    /// `uptime_s`, `boot_id` and `clock_synced` are the host's, not the
349    /// device's: they exist so a reader can order this node's events when
350    /// its wall clock is wrong, and one process has one boot.
351    #[must_use]
352    pub fn of(
353        device: &str,
354        status: &modem_device::OperStatus,
355        uptime_s: u64,
356        boot_id: &str,
357        clock_synced: bool,
358    ) -> Self {
359        Self {
360            device: device.to_string(),
361            status: status.status.as_str().to_string(),
362            admin: status.admin.as_str().to_string(),
363            reason: status.reason.clone(),
364            recoverable: status.recoverable,
365            last_change_ms: status
366                .since
367                .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
368                .map(|d| d.as_millis() as u64),
369            uptime_s,
370            boot_id: boot_id.to_string(),
371            clock_synced,
372        }
373    }
374}
375
376/// `state/modem/device/{device}/identity` — what the device is, with RFC
377/// 8348's field names (#122). Every field optional and `#[non_exhaustive]`:
378/// a device says what it knows. **Subscriber identifiers never appear here**
379/// — IMSI, ICCID, MSISDN identify a person's subscription, not equipment
380/// (invariant I5); the equipment identifier does, because the gateway keys
381/// its endpoints by it.
382#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
383#[non_exhaustive]
384pub struct Identity {
385    /// The local device.
386    pub device: String,
387    #[serde(default, skip_serializing_if = "Option::is_none")]
388    pub mfg_name: Option<String>,
389    #[serde(default, skip_serializing_if = "Option::is_none")]
390    pub model_name: Option<String>,
391    #[serde(default, skip_serializing_if = "Option::is_none")]
392    pub serial_num: Option<String>,
393    #[serde(default, skip_serializing_if = "Option::is_none")]
394    pub hardware_rev: Option<String>,
395    #[serde(default, skip_serializing_if = "Option::is_none")]
396    pub firmware_rev: Option<String>,
397    #[serde(default, skip_serializing_if = "Option::is_none")]
398    pub software_rev: Option<String>,
399    /// The bearer's equipment identifier — an IMEI. An addressing
400    /// identifier, never a proof of identity (I5).
401    #[serde(default, skip_serializing_if = "Option::is_none")]
402    pub imei: Option<String>,
403}
404
405impl Identity {
406    /// An identity that knows nothing but its name.
407    #[must_use]
408    pub fn unknown(device: &str) -> Self {
409        Self {
410            device: device.to_string(),
411            ..Self::default()
412        }
413    }
414
415    /// The document, from what the device says it is (#122).
416    #[must_use]
417    pub fn of(device: &str, id: &modem_device::Identity) -> Self {
418        Self {
419            device: device.to_string(),
420            mfg_name: id.mfg_name.clone(),
421            model_name: id.model_name.clone(),
422            serial_num: id.serial_num.clone(),
423            hardware_rev: id.hardware_rev.clone(),
424            firmware_rev: id.firmware_rev.clone(),
425            software_rev: id.software_rev.clone(),
426            imei: id.imei.clone(),
427        }
428    }
429}
430
431/// `state/modem/device/{device}/radio` — where a bearer stands with its
432/// network (#123): registration and access technology, for a device that
433/// registers with one. A point-to-point radio has none, and the subject is
434/// gated on `capability:registration` for it.
435#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
436pub struct RadioState {
437    /// The local device.
438    pub device: String,
439    /// `idle` | `home` | `searching` | `denied` | `roaming` | `unknown`.
440    pub registration: String,
441    /// ModemManager's spelling, lowercase: `lte`, `lte-cat-m`, `lte-nb-iot`,
442    /// `5gnr`, `iridium`, …
443    #[serde(default, skip_serializing_if = "Option::is_none")]
444    pub access_technology: Option<String>,
445}
446
447impl RadioState {
448    /// The document, from a report that carries a registration; `None` for
449    /// one that does not, which is the gate.
450    #[must_use]
451    pub fn of(device: &str, report: &modem_device::Report) -> Option<Self> {
452        let registration = report.registration?;
453        Some(Self {
454            device: device.to_string(),
455            registration: registration.as_str().to_string(),
456            access_technology: report.access_technology.map(|t| t.as_str().to_string()),
457        })
458    }
459}
460
461/// `state/modem/device/{device}/destination/{destination}` — one neighbour a
462/// netdev's radio reports it can reach (#137): a DLEP destination, with the
463/// radio's metrics for the link toward it.
464///
465/// **Not an endpoint** (architecture §4.6): an endpoint is a remote an
466/// operator configured lanes toward; this is what a radio discovered, and it
467/// comes and goes on its own, which is why the document is deleted when the
468/// radio reports it gone. A document field carries its unit in its name,
469/// because unlike a telemetry subject it has no registry `unit` to carry it.
470#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
471pub struct DestinationState {
472    /// The local device whose radio reports it.
473    pub device: String,
474    /// How the radio names it, as the key chunk spells it: for DLEP its MAC,
475    /// lowercase hex separated by hyphens. An addressing identifier, never a
476    /// proof of identity (invariant I5).
477    pub destination: String,
478    /// The addresses the radio says it has.
479    #[serde(default)]
480    pub addresses: Vec<String>,
481    #[serde(default, skip_serializing_if = "Option::is_none")]
482    pub rx_rate_bps: Option<u64>,
483    #[serde(default, skip_serializing_if = "Option::is_none")]
484    pub tx_rate_bps: Option<u64>,
485    #[serde(default, skip_serializing_if = "Option::is_none")]
486    pub rx_max_rate_bps: Option<u64>,
487    #[serde(default, skip_serializing_if = "Option::is_none")]
488    pub tx_max_rate_bps: Option<u64>,
489    #[serde(default, skip_serializing_if = "Option::is_none")]
490    pub latency_us: Option<u64>,
491    /// Percent.
492    #[serde(default, skip_serializing_if = "Option::is_none")]
493    pub resources_pct: Option<f64>,
494    /// Percent.
495    #[serde(default, skip_serializing_if = "Option::is_none")]
496    pub rx_quality_pct: Option<f64>,
497    /// Percent.
498    #[serde(default, skip_serializing_if = "Option::is_none")]
499    pub tx_quality_pct: Option<f64>,
500}
501
502impl DestinationState {
503    /// The document for one destination the device reported.
504    #[must_use]
505    pub fn of(device: &str, d: &modem_device::Destination) -> Self {
506        let pct = |m: Option<i32>| m.map(|m| f64::from(m) / 1_000.0);
507        Self {
508            device: device.to_string(),
509            destination: d.id.clone(),
510            addresses: d.addresses.iter().map(ToString::to_string).collect(),
511            rx_rate_bps: d.rx_rate,
512            tx_rate_bps: d.tx_rate,
513            rx_max_rate_bps: d.rx_max_rate,
514            tx_max_rate_bps: d.tx_max_rate,
515            latency_us: d.latency,
516            resources_pct: pct(d.resources),
517            rx_quality_pct: pct(d.rx_quality),
518            tx_quality_pct: pct(d.tx_quality),
519        }
520    }
521}
522
523/// `state/modem/sensor` — the producer's registration document (zenkey RFC 04
524/// §5): versions, and per device the `capability:` predicates that hold here
525/// (v1.41). The registry says which surfaces are conditional and on what;
526/// this says which conditions hold on *this* host, which is what lets a
527/// consumer read a gated subject's silence as honest (#122, #124).
528#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
529pub struct Sensor {
530    /// The crate version of the driver serving this.
531    pub version: String,
532    /// `git describe` of the build, when the build carried one.
533    #[serde(default, skip_serializing_if = "Option::is_none")]
534    pub build: Option<String>,
535    /// The zenkey the contract was compiled against.
536    pub zenkey: String,
537    /// Device chunk → the capability names that hold for it; the producer's
538    /// own, device-less capabilities under `"*"`.
539    #[serde(default)]
540    pub capabilities: std::collections::BTreeMap<String, Vec<String>>,
541    /// Device chunk → a hash of its effective configuration (#125), so a
542    /// fleet view spots divergence without reading every document.
543    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
544    pub config_hash: std::collections::BTreeMap<String, String>,
545}
546
547/// `events/modem/device/{device}/oper_change/{event_id}` — the operational
548/// status changed (#121): what the device says, or what the driver knows —
549/// a medium that failed a lane operation is `down` and not recoverable.
550#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
551pub struct OperChange {
552    /// The local device.
553    pub device: String,
554    /// The event's own id — the last chunk of its key.
555    pub event_id: String,
556    /// Milliseconds since the epoch, as the driver's clock had it.
557    pub at_ms: u64,
558    /// The status after the change: `up` | `down` | `notPresent` | `unknown`.
559    pub status: String,
560    /// Why, in the driver's or the device's words.
561    pub reason: String,
562    /// Transitions folded into this one under the rate floor — `1` when none
563    /// were (#121 damps a flapping interface, RFC 2863 §3.1.15).
564    pub occurrences: u64,
565}
566
567impl OperChange {
568    /// A transition to `status`, with the transitions folded into it.
569    #[must_use]
570    pub fn of(
571        device: &str,
572        event_id: String,
573        at_ms: u64,
574        status: &modem_device::OperStatus,
575        occurrences: u64,
576    ) -> Self {
577        Self {
578            device: device.to_string(),
579            event_id,
580            at_ms,
581            status: status.status.as_str().to_string(),
582            reason: status.reason.clone().unwrap_or_else(|| {
583                match status.status {
584                    modem_device::OperState::Up => "passing traffic",
585                    modem_device::OperState::Unknown => "the device has not said",
586                    _ => "",
587                }
588                .to_string()
589            }),
590            occurrences,
591        }
592    }
593}
594
595/// `events/modem/device/{device}/identity_change/{event_id}` — the device
596/// behind a name changed under a running driver (#122): a terminal swapped,
597/// or its firmware updated.
598#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
599pub struct IdentityChange {
600    /// The local device.
601    pub device: String,
602    /// The event's own id — the last chunk of its key.
603    pub event_id: String,
604    /// Milliseconds since the epoch, as the driver's clock had it.
605    pub at_ms: u64,
606    /// What it was.
607    pub before: Identity,
608    /// What it is.
609    pub after: Identity,
610    /// Changes folded into this one under the rate floor — `1` when none
611    /// were.
612    pub occurrences: u64,
613}
614
615impl IdentityChange {
616    /// The transition from `before` to `after`.
617    #[must_use]
618    pub fn of(
619        device: &str,
620        event_id: String,
621        at_ms: u64,
622        before: &modem_device::Identity,
623        after: &modem_device::Identity,
624        occurrences: u64,
625    ) -> Self {
626        Self {
627            device: device.to_string(),
628            event_id,
629            at_ms,
630            before: Identity::of(device, before),
631            after: Identity::of(device, after),
632            occurrences,
633        }
634    }
635}
636
637/// `@rpc/modem/device/{device}/action/{name}`'s body (#129): the action's
638/// arguments, with the configuration plane's value kinds.
639#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
640pub struct ActionRequest {
641    /// By name, as the action's spec declares them.
642    #[serde(default)]
643    pub arguments: std::collections::BTreeMap<String, zenkey::config::ParamValue>,
644}
645
646/// What an action did and what it cost (#129): the reply, so an operator
647/// sees the bill of an operation they asked for.
648#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
649pub struct ActionOutcome {
650    /// One line in the device's words.
651    pub detail: String,
652    /// What it cost, by unit: `{"sessions": 1, "messages_received": 2}`.
653    #[serde(default)]
654    pub cost: std::collections::BTreeMap<String, i64>,
655}
656
657impl ActionOutcome {
658    /// The document, from the device's outcome.
659    #[must_use]
660    pub fn of(outcome: &modem_device::action::ActionOutcome) -> Self {
661        Self {
662            detail: outcome.detail.clone(),
663            cost: outcome.cost.clone(),
664        }
665    }
666}
667
668/// `events/modem/device/{device}/action/{event_id}` — an operator action
669/// ran, or was refused (#129). Every invocation is one, so the record shows
670/// the decisions an operator made and the scripts that were refused rather
671/// than billed. The attribution is caller-claimed, never authentication (I5).
672#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
673pub struct ActionEvent {
674    /// The local device.
675    pub device: String,
676    /// The event's own id — the last chunk of its key.
677    pub event_id: String,
678    /// Milliseconds since the epoch, as the driver's clock had it.
679    pub at_ms: u64,
680    /// The action's name.
681    pub action: String,
682    /// Its arguments, as asked.
683    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
684    pub arguments: std::collections::BTreeMap<String, zenkey::config::ParamValue>,
685    /// `ok` | `refused` | `failed`.
686    pub outcome: String,
687    /// What it cost, when it ran.
688    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
689    pub cost: std::collections::BTreeMap<String, i64>,
690    /// The device's words, or why it was refused.
691    pub detail: String,
692    /// The caller's `?actor=`, as claimed.
693    #[serde(default, skip_serializing_if = "Option::is_none")]
694    pub actor: Option<String>,
695    /// The caller's `?request_id=`, as claimed.
696    #[serde(default, skip_serializing_if = "Option::is_none")]
697    pub request_id: Option<String>,
698}
699
700/// The reply of a write that has nothing to read back: `persist`'s.
701#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
702pub struct Ack {}
703
704#[cfg(test)]
705mod tests {
706    use super::*;
707
708    /// The document's field names, sorted.
709    ///
710    /// Sorted because that is all that is observable: `serde_json::Map` is
711    /// BTree-backed here (nothing in the graph enables `preserve_order`), so
712    /// declaration order never reaches the wire. Which fields exist is the
713    /// contract; the order they appear in is not.
714    fn keys(value: &serde_json::Value) -> Vec<String> {
715        let mut names: Vec<String> = value
716            .as_object()
717            .expect("an object")
718            .keys()
719            .cloned()
720            .collect();
721        names.sort();
722        names
723    }
724
725    #[test]
726    fn renaming_a_field_is_a_wire_break_not_a_refactor() {
727        // `registry.lock` pins type *names*; nothing pins their fields, and
728        // under RFC 08 §3 a rename is an incompatible payload change that needs
729        // a suffixed sibling rather than an edit. This is the thing that makes
730        // that reviewable.
731        let link = serde_json::to_value(LinkState {
732            device: "rf0".into(),
733            ttl_s: 60,
734            capabilities: Capabilities {
735                tx_max_sdu: 220,
736                rx_max_sdu: 220,
737                reliable: false,
738                duplex: Duplex::Half,
739                max_batch_size: 222,
740            },
741            lanes: Vec::new(),
742        })
743        .expect("serializes");
744        assert_eq!(keys(&link), ["capabilities", "device", "lanes", "ttl_s"]);
745        assert_eq!(
746            keys(&link["capabilities"]),
747            [
748                "duplex",
749                "max_batch_size",
750                "reliable",
751                "rx_max_sdu",
752                "tx_max_sdu"
753            ]
754        );
755
756        let security = serde_json::to_value(SecurityState::of("rf0", None)).expect("serializes");
757        assert_eq!(
758            keys(&security),
759            [
760                "authenticated_principal",
761                "device",
762                "guarantees",
763                "note",
764                "provider",
765                "scope"
766            ]
767        );
768        assert!(
769            security["authenticated_principal"].is_null(),
770            "I6 names the absence explicitly; omitting it would be silence"
771        );
772        assert!(
773            security.get("encrypted").is_none(),
774            "a bare boolean is exactly what I6 forbids"
775        );
776
777        // What a device that provides something reports, in the same keys.
778        let props = modem_device::SecurityProperties::new("test", modem_device::Scope::Hop)
779            .guarantee(modem_device::Guarantee::Integrity)
780            .guarantee(modem_device::Guarantee::AntiReplay);
781        let sealed =
782            serde_json::to_value(SecurityState::of("rf0", Some(&props))).expect("serializes");
783        assert_eq!(keys(&sealed), keys(&security));
784        assert_eq!(sealed["provider"], "test");
785        assert_eq!(sealed["scope"], "hop");
786        assert_eq!(
787            sealed["guarantees"],
788            serde_json::json!(["integrity", "anti-replay"])
789        );
790        assert!(sealed["authenticated_principal"].is_null());
791        assert!(sealed.get("encrypted").is_none());
792
793        let lane = serde_json::to_value(Lane::of(
794            &modem_device::LaneKey {
795                endpoint: modem_device::EndpointId::new("b"),
796                reliable: false,
797                rank: 0,
798            },
799            std::path::Path::new("/run/x"),
800            true,
801            Some(1024),
802        ))
803        .expect("serializes");
804        assert_eq!(
805            keys(&lane),
806            [
807                "backlog_bytes",
808                "connected",
809                "endpoint",
810                "lane",
811                "path",
812                "rank",
813                "reliable"
814            ]
815        );
816    }
817
818    #[test]
819    fn the_endpoint_document_stays_reduced() {
820        // Deliberate, and the one place it is written down where a future
821        // change has to read it. `endpoint/{device}/{endpoint}` is cardinality
822        // 64 and refreshed every ttl_s/2 for ever; carrying the full lane here
823        // would multiply the largest refreshed document about fourfold to
824        // restate what `sdu/link` already carries once, on a link where
825        // §4.6 measured the management plane at ~24% of the channel.
826        let lane = serde_json::to_value(EndpointLane {
827            lane: "peer-b/rel#0".into(),
828            connected: true,
829        })
830        .expect("serializes");
831        assert_eq!(keys(&lane), ["connected", "lane"]);
832    }
833
834    #[test]
835    fn the_lane_table_reports_duplex_like_the_link_document() {
836        // The divergence #37 removed: these two carry the same `Capabilities`
837        // now, so they cannot drift apart again without the type changing.
838        let caps = Capabilities {
839            tx_max_sdu: 340,
840            rx_max_sdu: 270,
841            reliable: true,
842            duplex: Duplex::Full,
843            max_batch_size: 342,
844        };
845        let table = serde_json::to_value(LaneTable {
846            device: "sat0".into(),
847            capabilities: caps,
848            lanes: Vec::new(),
849        })
850        .expect("serializes");
851        assert_eq!(table["capabilities"]["duplex"], "full");
852    }
853}
854
855/// `events/modem/device_fault/{event_id}` — the medium's own words.
856///
857/// The half of #51 that motivated it. Every `DeviceError` is the return value
858/// of a data-path call and there were exactly two consumers, both of which
859/// logged: so `+CME ERROR 3`, an SPI timeout, an MO status of "no network" —
860/// the one thing that says what is actually wrong — reached a `warn!` and was
861/// discarded. `detail` carries it verbatim.
862#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
863pub struct DeviceFault {
864    /// The local device.
865    pub device: String,
866    /// This event's own identifier, and the last chunk of its key.
867    pub event_id: String,
868    /// Milliseconds since the Unix epoch, as the publisher saw it.
869    pub at_ms: u64,
870    /// The lane it concerns, if it concerns one.
871    ///
872    /// Explicitly null rather than absent when it does not, for I6's reason
873    /// applied here: a reader must be able to tell "device-wide" from "the
874    /// publisher forgot".
875    pub lane: Option<String>,
876    /// `raised` or `cleared`.
877    ///
878    /// Edge-triggered: one of each, never a repeat while the condition lasts.
879    /// That is what makes `rate = "low"` a statement rather than a hope.
880    pub edge: String,
881    /// The medium's own words, verbatim.
882    pub detail: String,
883    /// Transitions this event stands for, including itself.
884    ///
885    /// Normally 1. Above that, the publisher was rate-limiting: the `events`
886    /// subject declares at most sixty an hour and a flapping radio can produce
887    /// more, so the extras are **summarised rather than dropped**. A reader
888    /// seeing 40 knows the plane did not simply lose 39 of them.
889    pub occurrences: u64,
890}
891
892impl DeviceFault {
893    /// One fault, as the events plane publishes it.
894    #[must_use]
895    pub fn of(
896        device: &str,
897        event_id: String,
898        at_ms: u64,
899        event: &modem_device::DeviceEvent,
900        occurrences: u64,
901    ) -> Self {
902        Self {
903            device: device.to_string(),
904            event_id,
905            at_ms,
906            lane: event.lane.as_ref().map(ToString::to_string),
907            edge: match event.edge {
908                modem_device::Edge::Raised => "raised".into(),
909                modem_device::Edge::Cleared => "cleared".into(),
910                // `Edge` is `#[non_exhaustive]`: a kind this build does not
911                // know is carried as its debug spelling rather than dropped,
912                // which is RFC 09 §5.1's O4 applied to a wire field.
913                other => format!("{other:?}").to_lowercase(),
914            },
915            detail: event.detail.clone(),
916            occurrences,
917        }
918    }
919}