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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
//! The management plane's payloads, as types.
//!
//! These existed as `serde_json::json!` literals until #37, and
//! `registry/types.toml` named Rust paths for four of them —
//! `modem_driver::mgmt::LinkState` and its siblings — that **had never
//! existed**. Nothing caught it: `zenkey-build`'s type-table lint checks that
//! every referenced type *name* resolves to a table entry, and never reads the
//! `rust` field at all. So the registry already carried exactly the drift
//! `@rpc/modem/describe` exists to prevent.
//!
//! Making the paths real is what lets the served schemas be derived from the
//! thing that is actually serialized, rather than hand-written beside it. A
//! second hand-maintained copy of six shapes, next to a first copy that has
//! already drifted, would repeat the mistake in a bigger font.
//!
//! Two shapes here are deliberately *not* unified, and the tests below say so.

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

/// Whether the medium can transmit and receive at once.
///
/// Defined here rather than by putting serde on [`modem_device::Duplex`]:
/// `modem-device` is the data-path crate CI guards, and how a value is
/// rendered on the management plane is not its business.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum Duplex {
    /// Transmit and receive are independent.
    Full,
    /// Transmitting blocks receiving and vice versa.
    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,
        }
    }
}

/// What the medium behind a device can carry.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Capabilities {
    /// Largest SDU the medium will transmit, in bytes.
    pub tx_max_sdu: u16,
    /// Largest SDU the medium will deliver, in bytes.
    pub rx_max_sdu: u16,
    /// Whether the medium delivers in order and without loss.
    pub reliable: bool,
    /// Whether transmit and receive contend.
    pub duplex: Duplex,
    /// The largest `batch_size` Zenoh may be configured with.
    ///
    /// The number an operator cannot derive without knowing that Zenoh's
    /// two-byte length prefix lives *inside* the batch.
    pub max_batch_size: usize,
}

impl Capabilities {
    /// From the medium's own declaration.
    #[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,
        }
    }
}

/// One lane, in full.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Lane {
    /// The lane's own rendering: endpoint, reliability and rank.
    pub lane: String,
    /// Which remote it reaches. An addressing identifier, never a proof of
    /// identity (invariant I5).
    pub endpoint: String,
    /// Whether it promises ordered, loss-free delivery.
    pub reliable: bool,
    /// Scheduling rank; lower is more urgent.
    pub rank: u8,
    /// Where its socket lives.
    pub path: String,
    /// Whether Zenoh is attached to it right now.
    pub connected: bool,
    /// Bytes Zenoh has written to this lane's socket that the driver has not
    /// read yet (#151): which lane is backed up, where
    /// `sched/lane_backlog_bytes` says only how much in all. Absent where
    /// the driver cannot measure it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub backlog_bytes: Option<u64>,
}

impl Lane {
    /// One lane, from the facts a driver has about it.
    #[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,
        }
    }
}

/// One lane, as an endpoint document names it.
///
/// **Deliberately reduced**, and not an oversight. `state/modem/{device}/
/// endpoint/{endpoint}` is the cardinality-64 subject and it is republished
/// every `ttl_s/2` for ever; §4.6's whole argument is that those bytes are
/// billed on a 2400 bit/s link. Carrying the full [`Lane`] here would multiply
/// the largest refreshed document about fourfold to restate what
/// `state/modem/device/{device}/sdu/link` already carries once.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct EndpointLane {
    /// The lane's own rendering.
    pub lane: String,
    /// Whether Zenoh is attached to it right now.
    pub connected: bool,
}

/// `state/modem/device/{device}/sdu/link` — what one device's medium is and what it carries.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct LinkState {
    /// The local device.
    pub device: String,
    /// Seconds this document stays fresh. Refreshed at half this.
    pub ttl_s: u64,
    /// What the medium behind it can carry.
    pub capabilities: Capabilities,
    /// Every lane on the device.
    pub lanes: Vec<Lane>,
}

impl LinkState {
    /// The link document, from the facts: the device, its freshness bound,
    /// what its medium can carry, and its lanes.
    #[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,
        }
    }
}

/// `@rpc/modem/device/{device}/sdu/lanes` — the same facts, on demand.
///
/// Shares [`Capabilities`] with [`LinkState`] rather than carrying its own.
/// Before #37 this document omitted `duplex`, which was an artefact of two
/// `json!` literals typed months apart rather than a decision — there is no
/// reason the lanes procedure should answer with a version of the medium's
/// capabilities that leaves one out.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct LaneTable {
    /// The local device.
    pub device: String,
    /// What the medium behind it can carry.
    pub capabilities: Capabilities,
    /// Every lane on the device.
    pub lanes: Vec<Lane>,
}

impl LaneTable {
    /// The lane table, from the same facts as [`LinkState`].
    #[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,
        }
    }
}

/// `state/modem/endpoint/{device}/{endpoint}` — one remote, and its lanes.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct EndpointState {
    /// The medium's name for this remote. An addressing identifier, never a
    /// proof of identity (invariant I5).
    pub endpoint: String,
    /// The local device that reaches it.
    pub device: String,
    /// The lanes toward it.
    pub lanes: Vec<EndpointLane>,
}

impl EndpointState {
    /// One remote's document: its lanes, reduced, from the device's lanes.
    #[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(),
        }
    }
}

/// `state/modem/device/{device}/security` — properties, never a boolean.
///
/// Invariant I6, demonstrated rather than described. A device that provides
/// no link security reports an empty guarantee set rather than omitting the
/// subject or publishing a bare `encrypted: false`, which would say nothing
/// about mode, scope, key management or peer authentication. A device, or a
/// layer above it, that does provide something reports it through
/// [`modem_device::Device::security`], and this document carries exactly
/// that: what the device and its layers guarantee, hop by hop.
///
/// Note there is no `encrypted` field and cannot be one: serde emits what the
/// type has. That is I6 enforced where it is enforceable, which is why the
/// served schema does not additionally need to *forbid* it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct SecurityState {
    /// The local device.
    pub device: String,
    /// Who provides link security, if anyone.
    pub provider: String,
    /// What it covers.
    pub scope: String,
    /// The properties it guarantees, named individually.
    pub guarantees: Vec<String>,
    /// The principal the far side authenticated as, if any.
    ///
    /// Explicitly null rather than absent: I6 is about naming what is *not*
    /// guaranteed, and omitting the field would be silence.
    pub authenticated_principal: Option<String>,
    /// Why the above reads as it does.
    pub note: String,
}

impl SecurityState {
    /// What the device reports (`Some`), or the statement that it reports
    /// nothing (`None`): no link cryptography, said as properties.
    #[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(),
            },
        }
    }
}

// ── Keyspace v2 documents (#120) ─────────────────────────────────────────────
//
// Declared with the registry break so the keys and their shapes settle once;
// the producers that fill them arrived with #121 (`Oper`, `OperChange`) and arrive with #122
// (`Identity`, `IdentityChange`, `Sensor`) and #128 (`Ack` from `persist`).
// Until then a document that nobody produces is recorded in
// `conditional.lock` with the issue that will produce it — declared, and
// honest about being silent.

/// `state/modem/device/{device}/oper` — RFC 2863's operational status, typed
/// (#121). Only the states something produces are declared: `up`, `down`,
/// `notPresent`, `unknown`; a coverage gap is `down` with `recoverable: true`,
/// never `dormant`, because Linux's operstate defines dormant as L1 up.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Oper {
    /// The local device.
    pub device: String,
    /// `up` | `down` | `notPresent` | `unknown`.
    pub status: String,
    /// `up` | `down`: radio silence (EMCON) is `down` here and distinguishable
    /// from a failure.
    pub admin: String,
    /// Why, in the device's words, when it is not `up`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    /// Whether the device expects to come back on its own — a coverage gap
    /// does, a dead medium does not. This is what a supervisor reads before
    /// deciding to restart (#96).
    pub recoverable: bool,
    /// Milliseconds since the epoch of the last status change, as the
    /// device's clock had it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_change_ms: Option<u64>,
    /// Seconds since this driver started: an ordering a wrong wall clock
    /// cannot corrupt.
    pub uptime_s: u64,
    /// One id per driver start, so two events a second apart on either side
    /// of a restart are told apart.
    pub boot_id: String,
    /// Whether the wall clock here is believed synchronised. A field unit may
    /// have no RTC; `uptime_s` and `boot_id` are how a reader orders its
    /// events anyway.
    pub clock_synced: bool,
}

impl Oper {
    /// The document, from what the device says and what the host knows.
    ///
    /// `uptime_s`, `boot_id` and `clock_synced` are the host's, not the
    /// device's: they exist so a reader can order this node's events when
    /// its wall clock is wrong, and one process has one boot.
    #[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,
        }
    }
}

/// `state/modem/device/{device}/identity` — what the device is, with RFC
/// 8348's field names (#122). Every field optional and `#[non_exhaustive]`:
/// a device says what it knows. **Subscriber identifiers never appear here**
/// — IMSI, ICCID, MSISDN identify a person's subscription, not equipment
/// (invariant I5); the equipment identifier does, because the gateway keys
/// its endpoints by it.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct Identity {
    /// The local device.
    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>,
    /// The bearer's equipment identifier — an IMEI. An addressing
    /// identifier, never a proof of identity (I5).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub imei: Option<String>,
}

impl Identity {
    /// An identity that knows nothing but its name.
    #[must_use]
    pub fn unknown(device: &str) -> Self {
        Self {
            device: device.to_string(),
            ..Self::default()
        }
    }

    /// The document, from what the device says it is (#122).
    #[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(),
        }
    }
}

/// `state/modem/device/{device}/radio` — where a bearer stands with its
/// network (#123): registration and access technology, for a device that
/// registers with one. A point-to-point radio has none, and the subject is
/// gated on `capability:registration` for it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct RadioState {
    /// The local device.
    pub device: String,
    /// `idle` | `home` | `searching` | `denied` | `roaming` | `unknown`.
    pub registration: String,
    /// ModemManager's spelling, lowercase: `lte`, `lte-cat-m`, `lte-nb-iot`,
    /// `5gnr`, `iridium`, …
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub access_technology: Option<String>,
}

impl RadioState {
    /// The document, from a report that carries a registration; `None` for
    /// one that does not, which is the gate.
    #[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()),
        })
    }
}

/// `state/modem/device/{device}/destination/{destination}` — one neighbour a
/// netdev's radio reports it can reach (#137): a DLEP destination, with the
/// radio's metrics for the link toward it.
///
/// **Not an endpoint** (architecture §4.6): an endpoint is a remote an
/// operator configured lanes toward; this is what a radio discovered, and it
/// comes and goes on its own, which is why the document is deleted when the
/// radio reports it gone. A document field carries its unit in its name,
/// because unlike a telemetry subject it has no registry `unit` to carry it.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct DestinationState {
    /// The local device whose radio reports it.
    pub device: String,
    /// How the radio names it, as the key chunk spells it: for DLEP its MAC,
    /// lowercase hex separated by hyphens. An addressing identifier, never a
    /// proof of identity (invariant I5).
    pub destination: String,
    /// The addresses the radio says it has.
    #[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>,
    /// Percent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resources_pct: Option<f64>,
    /// Percent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rx_quality_pct: Option<f64>,
    /// Percent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tx_quality_pct: Option<f64>,
}

impl DestinationState {
    /// The document for one destination the device reported.
    #[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),
        }
    }
}

/// `state/modem/sensor` — the producer's registration document (zenkey RFC 04
/// §5): versions, and per device the `capability:` predicates that hold here
/// (v1.41). The registry says which surfaces are conditional and on what;
/// this says which conditions hold on *this* host, which is what lets a
/// consumer read a gated subject's silence as honest (#122, #124).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Sensor {
    /// The crate version of the driver serving this.
    pub version: String,
    /// `git describe` of the build, when the build carried one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub build: Option<String>,
    /// The zenkey the contract was compiled against.
    pub zenkey: String,
    /// Device chunk → the capability names that hold for it; the producer's
    /// own, device-less capabilities under `"*"`.
    #[serde(default)]
    pub capabilities: std::collections::BTreeMap<String, Vec<String>>,
    /// Device chunk → a hash of its effective configuration (#125), so a
    /// fleet view spots divergence without reading every document.
    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
    pub config_hash: std::collections::BTreeMap<String, String>,
}

/// `events/modem/device/{device}/oper_change/{event_id}` — the operational
/// status changed (#121): what the device says, or what the driver knows —
/// a medium that failed a lane operation is `down` and not recoverable.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct OperChange {
    /// The local device.
    pub device: String,
    /// The event's own id — the last chunk of its key.
    pub event_id: String,
    /// Milliseconds since the epoch, as the driver's clock had it.
    pub at_ms: u64,
    /// The status after the change: `up` | `down` | `notPresent` | `unknown`.
    pub status: String,
    /// Why, in the driver's or the device's words.
    pub reason: String,
    /// Transitions folded into this one under the rate floor — `1` when none
    /// were (#121 damps a flapping interface, RFC 2863 §3.1.15).
    pub occurrences: u64,
}

impl OperChange {
    /// A transition to `status`, with the transitions folded into it.
    #[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,
        }
    }
}

/// `events/modem/device/{device}/identity_change/{event_id}` — the device
/// behind a name changed under a running driver (#122): a terminal swapped,
/// or its firmware updated.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct IdentityChange {
    /// The local device.
    pub device: String,
    /// The event's own id — the last chunk of its key.
    pub event_id: String,
    /// Milliseconds since the epoch, as the driver's clock had it.
    pub at_ms: u64,
    /// What it was.
    pub before: Identity,
    /// What it is.
    pub after: Identity,
    /// Changes folded into this one under the rate floor — `1` when none
    /// were.
    pub occurrences: u64,
}

impl IdentityChange {
    /// The transition from `before` to `after`.
    #[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,
        }
    }
}

/// `@rpc/modem/device/{device}/action/{name}`'s body (#129): the action's
/// arguments, with the configuration plane's value kinds.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ActionRequest {
    /// By name, as the action's spec declares them.
    #[serde(default)]
    pub arguments: std::collections::BTreeMap<String, zenkey::config::ParamValue>,
}

/// What an action did and what it cost (#129): the reply, so an operator
/// sees the bill of an operation they asked for.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ActionOutcome {
    /// One line in the device's words.
    pub detail: String,
    /// What it cost, by unit: `{"sessions": 1, "messages_received": 2}`.
    #[serde(default)]
    pub cost: std::collections::BTreeMap<String, i64>,
}

impl ActionOutcome {
    /// The document, from the device's outcome.
    #[must_use]
    pub fn of(outcome: &modem_device::action::ActionOutcome) -> Self {
        Self {
            detail: outcome.detail.clone(),
            cost: outcome.cost.clone(),
        }
    }
}

/// `events/modem/device/{device}/action/{event_id}` — an operator action
/// ran, or was refused (#129). Every invocation is one, so the record shows
/// the decisions an operator made and the scripts that were refused rather
/// than billed. The attribution is caller-claimed, never authentication (I5).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ActionEvent {
    /// The local device.
    pub device: String,
    /// The event's own id — the last chunk of its key.
    pub event_id: String,
    /// Milliseconds since the epoch, as the driver's clock had it.
    pub at_ms: u64,
    /// The action's name.
    pub action: String,
    /// Its arguments, as asked.
    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
    pub arguments: std::collections::BTreeMap<String, zenkey::config::ParamValue>,
    /// `ok` | `refused` | `failed`.
    pub outcome: String,
    /// What it cost, when it ran.
    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
    pub cost: std::collections::BTreeMap<String, i64>,
    /// The device's words, or why it was refused.
    pub detail: String,
    /// The caller's `?actor=`, as claimed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub actor: Option<String>,
    /// The caller's `?request_id=`, as claimed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub request_id: Option<String>,
}

/// The reply of a write that has nothing to read back: `persist`'s.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Ack {}

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

    /// The document's field names, sorted.
    ///
    /// Sorted because that is all that is observable: `serde_json::Map` is
    /// BTree-backed here (nothing in the graph enables `preserve_order`), so
    /// declaration order never reaches the wire. Which fields exist is the
    /// contract; the order they appear in is not.
    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() {
        // `registry.lock` pins type *names*; nothing pins their fields, and
        // under RFC 08 §3 a rename is an incompatible payload change that needs
        // a suffixed sibling rather than an edit. This is the thing that makes
        // that reviewable.
        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"
        );

        // What a device that provides something reports, in the same keys.
        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() {
        // Deliberate, and the one place it is written down where a future
        // change has to read it. `endpoint/{device}/{endpoint}` is cardinality
        // 64 and refreshed every ttl_s/2 for ever; carrying the full lane here
        // would multiply the largest refreshed document about fourfold to
        // restate what `sdu/link` already carries once, on a link where
        // §4.6 measured the management plane at ~24% of the channel.
        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() {
        // The divergence #37 removed: these two carry the same `Capabilities`
        // now, so they cannot drift apart again without the type changing.
        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");
    }
}

/// `events/modem/device_fault/{event_id}` — the medium's own words.
///
/// The half of #51 that motivated it. Every `DeviceError` is the return value
/// of a data-path call and there were exactly two consumers, both of which
/// logged: so `+CME ERROR 3`, an SPI timeout, an MO status of "no network" —
/// the one thing that says what is actually wrong — reached a `warn!` and was
/// discarded. `detail` carries it verbatim.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct DeviceFault {
    /// The local device.
    pub device: String,
    /// This event's own identifier, and the last chunk of its key.
    pub event_id: String,
    /// Milliseconds since the Unix epoch, as the publisher saw it.
    pub at_ms: u64,
    /// The lane it concerns, if it concerns one.
    ///
    /// Explicitly null rather than absent when it does not, for I6's reason
    /// applied here: a reader must be able to tell "device-wide" from "the
    /// publisher forgot".
    pub lane: Option<String>,
    /// `raised` or `cleared`.
    ///
    /// Edge-triggered: one of each, never a repeat while the condition lasts.
    /// That is what makes `rate = "low"` a statement rather than a hope.
    pub edge: String,
    /// The medium's own words, verbatim.
    pub detail: String,
    /// Transitions this event stands for, including itself.
    ///
    /// Normally 1. Above that, the publisher was rate-limiting: the `events`
    /// subject declares at most sixty an hour and a flapping radio can produce
    /// more, so the extras are **summarised rather than dropped**. A reader
    /// seeing 40 knows the plane did not simply lose 39 of them.
    pub occurrences: u64,
}

impl DeviceFault {
    /// One fault, as the events plane publishes it.
    #[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(),
                // `Edge` is `#[non_exhaustive]`: a kind this build does not
                // know is carried as its debug spelling rather than dropped,
                // which is RFC 09 §5.1's O4 applied to a wire field.
                other => format!("{other:?}").to_lowercase(),
            },
            detail: event.detail.clone(),
            occurrences,
        }
    }
}