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
//! The wire-level half of the conformance kit (#131): a running management
//! plane, probed as an operator's tool would.
//!
//! `modem_device::conformance` holds a device to its traits; this holds a
//! host to the contract — what the registry declares against what is
//! served, the gate on every procedure a device lacks a plane for, and the
//! write path that zenkey#222's `conform` deliberately never probes. A
//! wildcard write is safe to send because the correct answer is a refusal.
//!
//! Every probe reads *every* reply to a query, not the first, with
//! consolidation off: a second queryable answering `ok` beside the plane's
//! refusal is exactly the fault a caller would be fooled by, one reply would
//! hide it, and zenoh's default consolidation folds two `ok`s on one key
//! into the latest.
//!
//! Every subscriber the kit declares is dropped when its probe ends. A
//! subscriber nobody drains fills its channel — forty-two samples a tick do
//! it in a second — and a full channel holds the link the plane's replies
//! come back on, which reads as the plane having gone silent. A suite that
//! keeps its own subscriber past its use sees the same.
use std::collections::BTreeSet;
use std::time::Duration;
use serde_json::Value;
use zenkey::V1Context;
use zenoh::Session;
pub use modem_device::conformance::{Failure, assert_clean};
use crate::Host;
use crate::oper::Source;
/// The kit's handle on a running plane: an operator session that reaches
/// it, the producer context, and the host it serves (for what each device
/// declares and what the startup file lets a remote writer change).
pub struct Wire<'a> {
session: &'a Session,
ctx: &'a V1Context,
host: &'a Host,
patience: Duration,
window: Duration,
}
impl<'a> Wire<'a> {
/// Twenty seconds for a reply, three for a window of telemetry.
#[must_use]
pub fn new(session: &'a Session, ctx: &'a V1Context, host: &'a Host) -> Self {
Self {
session,
ctx,
host,
patience: Duration::from_secs(20),
window: Duration::from_secs(3),
}
}
/// How long one reply or sample may take.
#[must_use]
pub fn with_patience(mut self, patience: Duration) -> Self {
self.patience = patience;
self
}
/// How long telemetry is watched, and how long an event that must not
/// come is waited for. Several telemetry intervals.
#[must_use]
pub fn with_window(mut self, window: Duration) -> Self {
self.window = window;
self
}
fn fail(check: &'static str, detail: impl Into<String>) -> Failure {
Failure {
check,
detail: detail.into(),
}
}
/// Every reply to one query, as text: `Ok(payload)` or `Err(envelope)`.
/// The first within `patience`, the rest within a short grace.
///
/// Consolidation off, on purpose: with it, two `ok` replies on one key
/// collapse to the latest, and the impostor this kit exists to see is
/// exactly the one that would be folded away.
async fn replies_text(
&self,
check: &'static str,
key: &str,
body: Option<&Value>,
) -> Result<Vec<Result<String, String>>, Failure> {
let mut get = self
.session
.get(key)
.consolidation(zenoh::query::ConsolidationMode::None);
if let Some(body) = body {
get = get
.payload(body.to_string())
.encoding(zenoh::bytes::Encoding::APPLICATION_JSON);
}
let replies = get
.await
.map_err(|e| Self::fail(check, format!("{key}: the query failed: {e}")))?;
let mut out = Vec::new();
let mut wait = self.patience;
// The first reply within `patience`, the rest within a grace; a
// closed channel or the grace running out ends the collection.
while let Ok(Ok(r)) = tokio::time::timeout(wait, replies.recv_async()).await {
let text =
|b: &zenoh::bytes::ZBytes| b.try_to_string().unwrap_or_default().into_owned();
out.push(match r.result() {
Ok(s) => Ok(text(s.payload())),
Err(e) => Err(text(e.payload())),
});
wait = Duration::from_millis(300);
}
if out.is_empty() {
return Err(Self::fail(
check,
format!("{key}: no reply within {:?}", self.patience),
));
}
Ok(out)
}
/// Every reply to one query, each parsed as JSON: a payload or an
/// error envelope. One that is not JSON is a failure naming it.
async fn replies(
&self,
check: &'static str,
key: &str,
body: Option<&Value>,
) -> Result<Vec<Result<Value, Value>>, Failure> {
let mut out = Vec::new();
for r in self.replies_text(check, key, body).await? {
out.push(match r {
Ok(t) => Ok(serde_json::from_str::<Value>(&t).map_err(|e| {
Self::fail(
check,
format!("{key}: a reply that is not JSON ({e}): {t:?}"),
)
})?),
Err(t) => Err(serde_json::from_str::<Value>(&t).map_err(|e| {
Self::fail(
check,
format!("{key}: an error reply that is not JSON ({e}): {t:?}"),
)
})?),
});
}
Ok(out)
}
/// The one reply an operator expects, or a failure naming the others.
async fn one(
&self,
check: &'static str,
key: &str,
body: Option<&Value>,
) -> Result<Result<Value, Value>, Failure> {
let mut replies = self.replies(check, key, body).await?;
if replies.len() != 1 {
return Err(Self::fail(
check,
format!(
"{key}: {} replies where one queryable should answer: {replies:?}",
replies.len()
),
));
}
Ok(replies.remove(0))
}
fn rpc_key(&self, chunks: &[&str]) -> Result<String, Failure> {
self.ctx
.rpc_key(chunks)
.map(|k| k.as_str().to_string())
.map_err(|e| Self::fail("wire", format!("{chunks:?} is not an rpc key: {e}")))
}
/// The contract as served, parsed.
async fn served_slice(&self, check: &'static str) -> Result<zenkey::RegistrySlice, Failure> {
let key = self.rpc_key(&["introspect"])?;
let mut replies = self.replies_text(check, &key, None).await?;
if replies.len() != 1 {
return Err(Self::fail(
check,
format!("{key}: {} replies where one should answer", replies.len()),
));
}
match replies.remove(0) {
Ok(toml) => zenkey::parse_slice(&toml).map_err(|e| {
Self::fail(
check,
format!("introspect served a slice that does not parse: {e}"),
)
}),
Err(envelope) => Err(Self::fail(
check,
format!("introspect answered an error: {envelope}"),
)),
}
}
/// The registration document, from the wire: what each device holds.
async fn sensor(&self, check: &'static str) -> Result<Value, Failure> {
let key = self
.ctx
.state_key(&["sensor"])
.map_err(|e| Self::fail(check, format!("no sensor key: {e}")))?;
let sub = self
.session
.declare_subscriber(key.as_str())
.await
.map_err(|e| Self::fail(check, format!("{key}: subscribe failed: {e}")))?;
let s = tokio::time::timeout(self.patience, sub.recv_async())
.await
.map_err(|_| {
Self::fail(
check,
format!("{key}: no registration document within {:?}", self.patience),
)
})?
.map_err(|_| Self::fail(check, format!("{key}: the subscriber closed")))?;
serde_json::from_slice(&s.payload().to_bytes())
.map_err(|e| Self::fail(check, format!("{key}: not JSON: {e}")))
}
fn holds(sensor: &Value, device: &str) -> BTreeSet<String> {
sensor["capabilities"][device]
.as_array()
.map(|a| {
a.iter()
.filter_map(|v| v.as_str().map(str::to_string))
.collect()
})
.unwrap_or_default()
}
/// Whether every `capability:` predicate in `when` holds for a device.
fn gate_open(when: Option<&[zenkey::Predicate]>, holds: &BTreeSet<String>) -> bool {
when.is_none_or(|preds| {
preds.iter().all(|p| {
p.token()
.strip_prefix("capability:")
.is_some_and(|c| holds.contains(c))
})
})
}
/// Declared minus gated equals served, per device (#124, RFC 08 §6.1):
/// over one `window` of telemetry, each device publishes exactly the
/// subjects whose gates the registration document says are open, and
/// every payload is a number.
pub async fn declared_minus_gated_equals_served(&self) -> Vec<Failure> {
const CHECK: &str = "declared-minus-gated-equals-served";
let prefix = self.ctx.telemetry_prefix().as_str().to_string();
let sub = match self
.session
.declare_subscriber(format!("{prefix}/**").as_str())
.await
{
Ok(s) => s,
Err(e) => return vec![Self::fail(CHECK, format!("subscribe failed: {e}"))],
};
let mut out = Vec::new();
let mut published: BTreeSet<String> = BTreeSet::new();
let until = tokio::time::Instant::now() + self.window;
while let Ok(Ok(s)) = tokio::time::timeout_at(until, sub.recv_async()).await {
let key = s.key_expr().as_str().to_string();
let Some(rest) = key
.strip_prefix(prefix.as_str())
.and_then(|k| k.strip_prefix('/'))
else {
continue;
};
let text = s.payload().try_to_string().unwrap_or_default().into_owned();
if text.parse::<f64>().is_err() {
out.push(Self::fail(
CHECK,
format!("{key} carried {text:?}, not a number"),
));
}
published.insert(rest.to_string());
}
let sensor = match self.sensor(CHECK).await {
Ok(s) => s,
Err(f) => return vec![f],
};
let slice = match self.served_slice(CHECK).await {
Ok(s) => s,
Err(f) => return vec![f],
};
for node in self.host.nodes() {
let device = node.name();
if sensor["capabilities"].get(device).is_none() {
out.push(Self::fail(
CHECK,
format!("the registration document does not list {device}: {sensor}"),
));
continue;
}
let holds = Self::holds(&sensor, device);
let expected: BTreeSet<String> = slice
.subjects_in(zenkey::Class::Telemetry)
.filter(|s| Self::gate_open(s.when.as_deref(), &holds))
.map(|s| s.path.replace("{device}", device))
.collect();
let got: BTreeSet<String> = published
.iter()
.filter(|p| p.starts_with(&format!("device/{device}/")))
.cloned()
.collect();
if got != expected {
let silent: Vec<_> = expected.difference(&got).collect();
let extra: Vec<_> = got.difference(&expected).collect();
out.push(Self::fail(
CHECK,
format!(
"{device} holds {holds:?}; declared and not served in {:?}: {silent:?}; \
served and not declared for it: {extra:?}",
self.window
),
));
}
}
out
}
/// Every procedure gated on a capability a device lacks answers
/// `error/gated` naming the predicate (RFC 08 §6.1) — and nothing else
/// answers at all.
pub async fn gated_procedures_answer_gated(&self) -> Vec<Failure> {
const CHECK: &str = "gated-procedures-answer-gated";
let sensor = match self.sensor(CHECK).await {
Ok(s) => s,
Err(f) => return vec![f],
};
let slice = match self.served_slice(CHECK).await {
Ok(s) => s,
Err(f) => return vec![f],
};
let mut out = Vec::new();
for node in self.host.nodes() {
let device = node.name();
let holds = Self::holds(&sensor, device);
for proc_ in slice.procedures.iter().filter(|p| p.when.is_some()) {
let Some(when) = proc_.when.as_deref() else {
continue;
};
if Self::gate_open(Some(when), &holds) {
continue;
}
let Some(closed) = when.iter().find(|p| {
!p.token()
.strip_prefix("capability:")
.is_some_and(|c| holds.contains(c))
}) else {
continue;
};
let chunks: Vec<String> = proc_
.path
.split('/')
.map(|c| match c {
"{device}" => device.to_string(),
c if c.starts_with('{') => "conformance".to_string(),
c => c.to_string(),
})
.collect();
let chunks: Vec<&str> = chunks.iter().map(String::as_str).collect();
let key = match self.rpc_key(&chunks) {
Ok(k) => k,
Err(f) => {
out.push(f);
continue;
}
};
let replies = match self
.replies(CHECK, &key, Some(&serde_json::json!({})))
.await
{
Ok(r) => r,
Err(f) => {
out.push(f);
continue;
}
};
for reply in replies {
match reply {
Err(env)
if env["error"] == "error/gated"
&& env["message"]
.as_str()
.is_some_and(|m| m.contains(&closed.token())) => {}
Err(env) => out.push(Self::fail(
CHECK,
format!(
"{key}: {device} lacks {}; the reply is {env}, not error/gated \
naming it",
closed.token()
),
)),
Ok(payload) => out.push(Self::fail(
CHECK,
format!(
"{key}: {device} lacks {}; something answered {payload} instead \
of error/gated",
closed.token()
),
)),
}
}
}
}
out
}
/// The current read-back of a device's configuration.
async fn view(&self, check: &'static str, device: &str) -> Result<Value, Failure> {
let key = self.rpc_key(&["config", device])?;
match self.one(check, &key, None).await? {
Ok(v) => Ok(v),
Err(env) => Err(Self::fail(check, format!("{key}: the read answered {env}"))),
}
}
/// The write path, on every device with a configuration plane and a
/// group the startup file lets a remote writer change:
///
/// - a wildcard `set` is refused (`error/fanout-forbidden`) by every
/// reply;
/// - a stale `expected_revision` is refused naming the revision;
/// - `dry_run` answers a read-back at the same revision, changes nothing,
/// and raises no `config_change`;
/// - a value written to a sensitive parameter appears in no reply, no
/// echo and no event.
///
/// The sensitive probe writes a marker the device keeps: run it against
/// a test double, which is what a suite does.
pub async fn write_path(&self) -> Vec<Failure> {
const CHECK: &str = "write-path";
let mut out = Vec::new();
for node in self.host.nodes() {
let device = node.name();
let Some(schema) = Source::of(node).schema() else {
continue;
};
let writable: Vec<_> = schema
.groups
.iter()
.filter(|g| {
g.class != modem_device::config::ParamClass::Contract
&& node.writable().contains(g.name)
})
.collect();
let Some((group, param)) = writable.iter().find_map(|g| {
g.parameters
.iter()
.find(|p| !p.sensitive)
.map(|p| (g.name, p))
}) else {
continue;
};
let before = match self.view(CHECK, device).await {
Ok(v) => v,
Err(f) => {
out.push(f);
continue;
}
};
let revision = before["revision"].as_u64().unwrap_or(0);
let current = before["groups"]
.as_array()
.and_then(|gs| gs.iter().find(|g| g["name"] == group))
.and_then(|g| g["parameters"].as_array())
.and_then(|ps| ps.iter().find(|p| p["name"] == param.name))
.map(|p| p["value"].clone());
let value = other_value(param, current.as_ref());
let set_key = match self.rpc_key(&["config", device, group, "set"]) {
Ok(k) => k,
Err(f) => {
out.push(f);
continue;
}
};
let values = serde_json::json!({ param.name: value });
// A wildcard write.
let wild = set_key.replace(&format!("/{device}/"), "/*/");
match self
.replies(CHECK, &wild, Some(&serde_json::json!({ "values": values })))
.await
{
Ok(replies) => {
for r in replies {
match r {
Err(env) if env["error"] == "error/fanout-forbidden" => {}
other => out.push(Self::fail(
CHECK,
format!(
"{wild}: a wildcard write must be refused by every reply \
(error/fanout-forbidden); got {other:?}"
),
)),
}
}
}
Err(f) => out.push(f),
}
// A stale revision.
let stale = revision + 1000;
match self
.replies(
CHECK,
&set_key,
Some(&serde_json::json!({ "values": values, "expected_revision": stale })),
)
.await
{
Ok(replies) => {
for r in replies {
match r {
Err(env)
if env["error"] == "error/invalid-args"
&& env["message"]
.as_str()
.is_some_and(|m| m.contains(&stale.to_string())) => {}
other => out.push(Self::fail(
CHECK,
format!(
"{set_key}: expected_revision {stale} against revision \
{revision} must be refused naming it; got {other:?}"
),
)),
}
}
}
Err(f) => out.push(f),
}
// A dry run.
let events_key = format!("v1/*/events/modem/device/{device}/config_change/**");
let events = match self.session.declare_subscriber(events_key.as_str()).await {
Ok(s) => s,
Err(e) => {
out.push(Self::fail(
CHECK,
format!("{events_key}: subscribe failed: {e}"),
));
continue;
}
};
match self
.replies(
CHECK,
&set_key,
Some(&serde_json::json!({ "values": values, "dry_run": true })),
)
.await
{
Ok(replies) => {
for r in replies {
match r {
Ok(view)
if view["revision"] == revision && view["groups"].is_array() => {}
other => out.push(Self::fail(
CHECK,
format!(
"{set_key}: a dry run answers the read-back it would \
produce, at the unchanged revision {revision}; got {other:?}"
),
)),
}
}
}
Err(f) => out.push(f),
}
match self.view(CHECK, device).await {
Ok(after) if after == before => {}
Ok(after) => out.push(Self::fail(
CHECK,
format!("{set_key}: a dry run changed the read-back: {after} vs {before}"),
)),
Err(f) => out.push(f),
}
if let Ok(Ok(s)) = tokio::time::timeout(self.window, events.recv_async()).await {
out.push(Self::fail(
CHECK,
format!(
"{set_key}: a dry run raised a config_change event: {}",
s.payload().try_to_string().unwrap_or_default()
),
));
}
// A sensitive value.
let Some((sgroup, sparam)) = writable.iter().find_map(|g| {
g.parameters
.iter()
.find(|p| p.sensitive && p.kind == modem_device::config::ParamKind::Text)
.map(|p| (g.name, p))
}) else {
continue;
};
let marker = format!(
"conformance-{}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_nanos())
);
let echo_key = match self.ctx.state_key(&["config", device]) {
Ok(k) => k.as_str().to_string(),
Err(e) => {
out.push(Self::fail(CHECK, format!("no config state key: {e}")));
continue;
}
};
let echo = match self.session.declare_subscriber(echo_key.as_str()).await {
Ok(s) => s,
Err(e) => {
out.push(Self::fail(
CHECK,
format!("{echo_key}: subscribe failed: {e}"),
));
continue;
}
};
let set_key = match self.rpc_key(&["config", device, sgroup, "set"]) {
Ok(k) => k,
Err(f) => {
out.push(f);
continue;
}
};
let body = serde_json::json!({ "values": { sparam.name: marker } });
match self.replies(CHECK, &set_key, Some(&body)).await {
Ok(replies) => {
for r in replies {
let text = match &r {
Ok(v) | Err(v) => v.to_string(),
};
if text.contains(&marker) {
out.push(Self::fail(
CHECK,
format!(
"{set_key}: the value written to sensitive {sgroup}/{} \
appears in the reply: {text}",
sparam.name
),
));
}
if let Err(env) = &r
&& env["error"] != "error/unsupported"
{
out.push(Self::fail(
CHECK,
format!(
"{set_key}: the schema says {sgroup}/{} takes text; the \
write was refused: {env}",
sparam.name
),
));
}
}
}
Err(f) => out.push(f),
}
for (what, sub, key) in [
("the echo", &echo, &echo_key),
("the event", &events, &events_key),
] {
match tokio::time::timeout(self.patience, sub.recv_async()).await {
Ok(Ok(s)) => {
let text = s.payload().try_to_string().unwrap_or_default().into_owned();
if text.contains(&marker) {
out.push(Self::fail(
CHECK,
format!(
"{key}: the value written to sensitive {sgroup}/{} appears \
in {what}: {text}",
sparam.name
),
));
}
}
_ => out.push(Self::fail(
CHECK,
format!(
"{key}: no {what} followed the write to {sgroup}/{} within {:?}",
sparam.name, self.patience
),
)),
}
}
match self.view(CHECK, device).await {
Ok(view) if view.to_string().contains(&marker) => out.push(Self::fail(
CHECK,
format!(
"the value written to sensitive {sgroup}/{} appears in the read-back: \
{view}",
sparam.name
),
)),
Ok(_) => {}
Err(f) => out.push(f),
}
}
out
}
/// The three wire checks.
pub async fn all(&self) -> Vec<Failure> {
let mut out = self.declared_minus_gated_equals_served().await;
out.extend(self.gated_procedures_answer_gated().await);
out.extend(self.write_path().await);
out
}
}
/// A value the parameter accepts that differs from what the read-back shows.
fn other_value(spec: &modem_device::config::ParamSpec, current: Option<&Value>) -> Value {
use modem_device::config::ParamKind;
match &spec.kind {
ParamKind::Bool => Value::Bool(!current.and_then(Value::as_bool).unwrap_or(false)),
ParamKind::Integer { min, max, .. } => {
let cur = current
.and_then(Value::as_i64)
.unwrap_or_else(|| min.unwrap_or(0));
let up = cur.saturating_add(1);
if max.is_none_or(|m| up <= m) {
Value::from(up)
} else {
Value::from(cur.saturating_sub(1).max(min.unwrap_or(i64::MIN)))
}
}
_ => Value::String(format!(
"{}-conformance",
current.and_then(Value::as_str).unwrap_or("")
)),
}
}