1use std::collections::BTreeSet;
26use std::fmt;
27use std::future::Future;
28use std::pin::{Pin, pin};
29use std::sync::{Arc, Mutex};
30use std::task::Poll;
31
32use crate::action::{ActionError, ActionOutcome, ActionSpec, Actions, CostModel};
33use crate::config::{
34 ConfigError, ConfigValue, Configure, Effective, ParamClass, ParamKind, ParamSpec, Schema,
35};
36use crate::{
37 Capabilities, Device, DeviceError, DeviceEvent, Duplex, Edge, EndpointId, Identity, LaneKey,
38 Medium, Metrics, Netdev, NetdevStats, OperStatus, Report, Sdu,
39};
40
41#[derive(Clone, Debug, PartialEq, Eq)]
43pub struct Failure {
44 pub check: &'static str,
46 pub detail: String,
48}
49
50impl Failure {
51 fn new(check: &'static str, detail: impl Into<String>) -> Self {
52 Self {
53 check,
54 detail: detail.into(),
55 }
56 }
57}
58
59impl fmt::Display for Failure {
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 write!(f, "{}: {}", self.check, self.detail)
62 }
63}
64
65pub fn assert_clean(what: &str, failures: &[Failure]) {
71 assert!(
72 failures.is_empty(),
73 "{what} fails {} conformance check(s):\n{}",
74 failures.len(),
75 failures
76 .iter()
77 .map(|f| format!(" - {f}"))
78 .collect::<Vec<_>>()
79 .join("\n")
80 );
81}
82
83pub const DEVICE_METHODS: [&str; 7] = [
88 "report",
89 "oper",
90 "identity",
91 "next_event",
92 "close",
93 "configuration",
94 "actions",
95];
96
97pub const MEDIUM_METHODS: [&str; 12] = [
101 "report",
102 "oper",
103 "identity",
104 "next_event",
105 "close",
106 "configuration",
107 "actions",
108 "capabilities",
109 "send",
110 "recv",
111 "metrics",
112 "configure_lanes",
113];
114
115pub const NETDEV_METHODS: [&str; 10] = [
117 "report",
118 "oper",
119 "identity",
120 "next_event",
121 "close",
122 "configuration",
123 "actions",
124 "interface",
125 "statistics",
126 "epoch",
127];
128
129struct Recording {
134 config: RecordedConfig,
135 actions: RecordedActions,
136 seen: Mutex<BTreeSet<&'static str>>,
137}
138
139impl Recording {
140 fn new() -> Self {
141 Self {
142 config: RecordedConfig,
143 actions: RecordedActions,
144 seen: Mutex::new(BTreeSet::new()),
145 }
146 }
147
148 fn mark(&self, method: &'static str) {
149 self.seen.lock().expect("not poisoned").insert(method);
150 }
151
152 fn seen(&self) -> BTreeSet<&'static str> {
153 self.seen.lock().expect("not poisoned").clone()
154 }
155
156 fn caps() -> Capabilities {
157 Capabilities {
158 tx_max_sdu: 218,
159 rx_max_sdu: 217,
160 duplex: Duplex::Half,
161 reliable: false,
162 }
163 }
164
165 fn report() -> Report {
166 Report::new().age_ms(17).retransmits(5)
167 }
168
169 fn oper() -> OperStatus {
170 OperStatus::down("recorded", true)
171 }
172
173 fn identity() -> Identity {
174 Identity::unknown().model_name("recorded")
175 }
176
177 fn lane() -> LaneKey {
178 LaneKey {
179 endpoint: EndpointId::new("b"),
180 reliable: false,
181 rank: 0,
182 }
183 }
184
185 fn stats() -> NetdevStats {
186 NetdevStats {
187 in_octets: Some(4242),
188 ..NetdevStats::default()
189 }
190 }
191}
192
193struct RecordedConfig;
194
195#[async_trait::async_trait]
196impl Configure for RecordedConfig {
197 fn schema(&self) -> Schema {
198 Schema::new()
199 }
200 fn effective(&self) -> Effective {
201 Effective::default()
202 }
203}
204
205struct RecordedActions;
206
207#[async_trait::async_trait]
208impl Actions for RecordedActions {
209 fn specs(&self) -> Vec<ActionSpec> {
210 vec![ActionSpec::new("recorded", "", CostModel::Free)]
211 }
212 async fn invoke(
213 &self,
214 _name: &str,
215 _arguments: &std::collections::BTreeMap<String, ConfigValue>,
216 ) -> Result<ActionOutcome, ActionError> {
217 Ok(ActionOutcome::new("recorded"))
218 }
219}
220
221#[async_trait::async_trait]
222impl Device for Recording {
223 fn report(&self) -> Report {
224 self.mark("report");
225 Self::report()
226 }
227 fn oper(&self) -> OperStatus {
228 self.mark("oper");
229 Self::oper()
230 }
231 fn identity(&self) -> Identity {
232 self.mark("identity");
233 Self::identity()
234 }
235 fn configuration(&self) -> Option<&dyn Configure> {
236 self.mark("configuration");
237 Some(&self.config)
238 }
239 fn actions(&self) -> Option<&dyn Actions> {
240 self.mark("actions");
241 Some(&self.actions)
242 }
243 async fn close(&self) -> Result<(), DeviceError> {
244 self.mark("close");
245 Ok(())
246 }
247 async fn next_event(&self) -> Result<DeviceEvent, DeviceError> {
248 self.mark("next_event");
249 Ok(DeviceEvent::raised("recorded"))
250 }
251}
252
253#[async_trait::async_trait]
254impl Medium for Recording {
255 fn capabilities(&self) -> Capabilities {
256 self.mark("capabilities");
257 Self::caps()
258 }
259 async fn send(&self, _lane: &LaneKey, _sdu: &[u8]) -> Result<(), DeviceError> {
260 self.mark("send");
261 Ok(())
262 }
263 async fn recv(&self) -> Result<(LaneKey, Sdu), DeviceError> {
264 self.mark("recv");
265 Ok((Self::lane(), vec![0xAB]))
266 }
267 fn metrics(&self) -> Metrics {
268 self.mark("metrics");
269 Metrics {
270 tx_sdus: 7,
271 ..Metrics::default()
272 }
273 }
274 async fn configure_lanes(&self, _lanes: &[LaneKey]) -> Result<(), DeviceError> {
275 self.mark("configure_lanes");
276 Ok(())
277 }
278}
279
280impl Netdev for Recording {
281 fn interface(&self) -> &'static str {
282 self.mark("interface");
283 "recorded0"
284 }
285 fn statistics(&self) -> NetdevStats {
286 self.mark("statistics");
287 Self::stats()
288 }
289 fn epoch(&self) -> u64 {
290 self.mark("epoch");
291 42
292 }
293}
294
295async fn device_calls(name: &str, dev: &dyn Device, out: &mut Vec<Failure>) {
298 let report = dev.report();
299 let oper = dev.oper();
300 let identity = dev.identity();
301 let configuration = dev.configuration().is_some();
302 let actions = dev.actions().is_some();
303 let event = dev.next_event().await;
304 if report != Recording::report() {
305 out.push(Failure::new(
306 "decorator-forwards",
307 format!("{name} rewrote report: {report:?}"),
308 ));
309 }
310 if oper != Recording::oper() {
311 out.push(Failure::new(
312 "decorator-forwards",
313 format!("{name} rewrote oper: {oper:?}"),
314 ));
315 }
316 if identity != Recording::identity() {
317 out.push(Failure::new(
318 "decorator-forwards",
319 format!("{name} rewrote identity: {identity:?}"),
320 ));
321 }
322 if !configuration {
323 out.push(Failure::new(
324 "decorator-forwards",
325 format!("{name} answers None for configuration: the wrapped device has a plane"),
326 ));
327 }
328 if !actions {
329 out.push(Failure::new(
330 "decorator-forwards",
331 format!("{name} answers None for actions: the wrapped device offers one"),
332 ));
333 }
334 if event.as_ref().ok() != Some(&DeviceEvent::raised("recorded")) {
335 out.push(Failure::new(
336 "decorator-forwards",
337 format!("{name} rewrote next_event: {event:?}"),
338 ));
339 }
340}
341
342fn missing(name: &str, methods: &[&'static str], inner: &Recording, out: &mut Vec<Failure>) {
343 let seen = inner.seen();
344 let missing: Vec<&str> = methods
345 .iter()
346 .copied()
347 .filter(|m| !seen.contains(m))
348 .collect();
349 if !missing.is_empty() {
350 out.push(Failure::new(
351 "decorator-forwards",
352 format!(
353 "{name} does not forward {missing:?}, so it answers for itself rather than for \
354 the device it wraps"
355 ),
356 ));
357 }
358}
359
360pub async fn device_decorator_forwards<F>(name: &str, wrap: F) -> Vec<Failure>
366where
367 F: FnOnce(Arc<dyn Device>) -> Arc<dyn Device>,
368{
369 let inner = Arc::new(Recording::new());
370 let dev = wrap(inner.clone() as Arc<dyn Device>);
371 let mut out = Vec::new();
372 device_calls(name, dev.as_ref(), &mut out).await;
373 if let Err(e) = dev.close().await {
374 out.push(Failure::new(
375 "decorator-forwards",
376 format!("{name} failed close: {e}"),
377 ));
378 }
379 missing(name, &DEVICE_METHODS, &inner, &mut out);
380 out
381}
382
383pub async fn medium_decorator_forwards<F>(name: &str, wrap: F) -> Vec<Failure>
385where
386 F: FnOnce(Arc<dyn Medium>) -> Arc<dyn Medium>,
387{
388 let inner = Arc::new(Recording::new());
389 let medium = wrap(inner.clone() as Arc<dyn Medium>);
390 let mut out = Vec::new();
391 device_calls(name, medium.as_ref(), &mut out).await;
392 let caps = medium.capabilities();
393 if caps != Recording::caps() {
394 out.push(Failure::new(
395 "decorator-forwards",
396 format!("{name} rewrote capabilities: {caps:?}"),
397 ));
398 }
399 if let Err(e) = medium.send(&Recording::lane(), b"payload").await {
400 out.push(Failure::new(
401 "decorator-forwards",
402 format!("{name} failed send: {e}"),
403 ));
404 }
405 match medium.recv().await {
406 Ok((_, sdu)) if sdu == vec![0xAB] => {}
407 other => out.push(Failure::new(
408 "decorator-forwards",
409 format!("{name} rewrote recv: {other:?}"),
410 )),
411 }
412 let metrics = medium.metrics();
413 if metrics.tx_sdus != 7 {
414 out.push(Failure::new(
415 "decorator-forwards",
416 format!("{name} rewrote metrics: {metrics:?}"),
417 ));
418 }
419 if let Err(e) = medium.configure_lanes(&[Recording::lane()]).await {
420 out.push(Failure::new(
421 "decorator-forwards",
422 format!("{name} failed configure_lanes: {e}"),
423 ));
424 }
425 if let Err(e) = medium.close().await {
426 out.push(Failure::new(
427 "decorator-forwards",
428 format!("{name} failed close: {e}"),
429 ));
430 }
431 missing(name, &MEDIUM_METHODS, &inner, &mut out);
432 out
433}
434
435pub async fn netdev_decorator_forwards<F>(name: &str, wrap: F) -> Vec<Failure>
437where
438 F: FnOnce(Arc<dyn Netdev>) -> Arc<dyn Netdev>,
439{
440 let inner = Arc::new(Recording::new());
441 let dev = wrap(inner.clone() as Arc<dyn Netdev>);
442 let mut out = Vec::new();
443 device_calls(name, dev.as_ref(), &mut out).await;
444 if dev.interface() != "recorded0" {
445 out.push(Failure::new(
446 "decorator-forwards",
447 format!("{name} rewrote interface: {:?}", dev.interface()),
448 ));
449 }
450 if dev.statistics() != Recording::stats() {
451 out.push(Failure::new(
452 "decorator-forwards",
453 format!("{name} rewrote statistics: {:?}", dev.statistics()),
454 ));
455 }
456 if dev.epoch() != 42 {
457 out.push(Failure::new(
458 "decorator-forwards",
459 format!("{name} rewrote epoch: {}", dev.epoch()),
460 ));
461 }
462 if let Err(e) = dev.close().await {
463 out.push(Failure::new(
464 "decorator-forwards",
465 format!("{name} failed close: {e}"),
466 ));
467 }
468 missing(name, &NETDEV_METHODS, &inner, &mut out);
469 out
470}
471
472#[must_use]
482pub fn core(dev: &dyn Device) -> Vec<Failure> {
483 let mut out = Vec::new();
484 let ageless = |mut r: Report| {
485 r.age_ms = None;
486 r
487 };
488 let (a, b) = (dev.report(), dev.report());
489 if ageless(a) != ageless(b) {
490 out.push(Failure::new(
491 "report-is-cached",
492 format!("two calls in a row disagree: {a:?} then {b:?}"),
493 ));
494 }
495 if ageless(a) != Report::default() && a.age_ms.is_none() {
496 out.push(Failure::new(
497 "report-says-its-age",
498 format!("the report carries a reading and no age_ms: {a:?}"),
499 ));
500 }
501 let (a, b) = (dev.oper(), dev.oper());
502 if a != b {
503 out.push(Failure::new(
504 "oper-is-cached",
505 format!("two calls in a row disagree: {a:?} then {b:?}"),
506 ));
507 }
508 let (a, b) = (dev.identity(), dev.identity());
509 if a != b {
510 out.push(Failure::new(
511 "identity-is-cached",
512 format!("two calls in a row disagree: {a:?} then {b:?}"),
513 ));
514 }
515 out
516}
517
518async fn until<T>(
520 fut: impl Future<Output = T>,
521 mut deadline: Pin<&mut impl Future<Output = ()>>,
522) -> Option<T> {
523 let mut fut = pin!(fut);
524 std::future::poll_fn(|cx| {
525 if let Poll::Ready(v) = fut.as_mut().poll(cx) {
526 return Poll::Ready(Some(v));
527 }
528 match deadline.as_mut().poll(cx) {
529 Poll::Ready(()) => Poll::Ready(None),
530 Poll::Pending => Poll::Pending,
531 }
532 })
533 .await
534}
535
536pub async fn events_are_edge_triggered(
546 dev: &dyn Device,
547 deadline: impl Future<Output = ()>,
548) -> Vec<Failure> {
549 let mut deadline = pin!(deadline);
550 let mut out = Vec::new();
551 let mut last: Vec<(Option<LaneKey>, DeviceEvent)> = Vec::new();
552 while let Some(Ok(ev)) = until(dev.next_event(), deadline.as_mut()).await {
554 if let Some((_, prev)) = last.iter().find(|(lane, _)| *lane == ev.lane)
555 && prev.edge == ev.edge
556 && prev.detail == ev.detail
557 {
558 out.push(Failure::new(
559 "events-are-edge-triggered",
560 format!(
561 "{:?} {:?} was reported twice in a row with no {:?} between: a condition \
562 is one event when it starts and one when it stops",
563 ev.edge,
564 ev.detail,
565 match ev.edge {
566 Edge::Raised => Edge::Cleared,
567 _ => Edge::Raised,
568 }
569 ),
570 ));
571 }
572 last.retain(|(lane, _)| *lane != ev.lane);
573 last.push((ev.lane.clone(), ev));
574 }
575 out
576}
577
578fn plain_chunk(s: &str) -> bool {
581 !s.is_empty()
582 && s.chars()
583 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-')
584}
585
586#[must_use]
593pub fn schema_is_valid(schema: &Schema) -> Vec<Failure> {
594 let mut out = Vec::new();
595 let mut groups = BTreeSet::new();
596 for g in &schema.groups {
597 if !plain_chunk(g.name) {
598 out.push(Failure::new(
599 "schema-is-valid",
600 format!(
601 "group {:?} is not a plain chunk (lowercase, digits, `_`, `-`): it is \
602 spelled in the write key",
603 g.name
604 ),
605 ));
606 }
607 if !groups.insert(g.name) {
608 out.push(Failure::new(
609 "schema-is-valid",
610 format!("group {:?} is declared twice", g.name),
611 ));
612 }
613 if g.description.trim().is_empty() {
614 out.push(Failure::new(
615 "schema-is-valid",
616 format!("group {:?} has no description", g.name),
617 ));
618 }
619 if g.parameters.is_empty() {
620 out.push(Failure::new(
621 "schema-is-valid",
622 format!("group {:?} declares no parameter", g.name),
623 ));
624 }
625 let mut names = BTreeSet::new();
626 for p in &g.parameters {
627 if !plain_chunk(p.name) {
628 out.push(Failure::new(
629 "schema-is-valid",
630 format!("{}/{:?} is not a plain chunk", g.name, p.name),
631 ));
632 }
633 if !names.insert(p.name) {
634 out.push(Failure::new(
635 "schema-is-valid",
636 format!("{}/{} is declared twice", g.name, p.name),
637 ));
638 }
639 if p.description.trim().is_empty() {
640 out.push(Failure::new(
641 "schema-is-valid",
642 format!("{}/{} has no description", g.name, p.name),
643 ));
644 }
645 if let ParamKind::Integer {
646 min: Some(min),
647 max: Some(max),
648 ..
649 } = p.kind
650 && min > max
651 {
652 out.push(Failure::new(
653 "schema-is-valid",
654 format!("{}/{}: min {min} is above max {max}", g.name, p.name),
655 ));
656 }
657 }
658 }
659 out
660}
661
662#[must_use]
666pub fn effective_within_schema(schema: &Schema, effective: &Effective) -> Vec<Failure> {
667 let mut out = Vec::new();
668 for (group, params) in effective {
669 for (name, value) in params {
670 if let Err(e) = schema.check(group, name, value) {
671 out.push(Failure::new(
672 "effective-within-schema",
673 format!("effective carries {group}/{name} = {value}: {e}"),
674 ));
675 }
676 }
677 }
678 out.extend(sensitive_absent(schema, effective));
679 out
680}
681
682fn sensitive_absent(schema: &Schema, effective: &Effective) -> Vec<Failure> {
683 let mut out = Vec::new();
684 for g in &schema.groups {
685 for p in g.parameters.iter().filter(|p| p.sensitive) {
686 if effective
687 .get(g.name)
688 .is_some_and(|values| values.contains_key(p.name))
689 {
690 out.push(Failure::new(
691 "sensitive-never-read-back",
692 format!(
693 "{}/{} is sensitive and effective carries a value for it",
694 g.name, p.name
695 ),
696 ));
697 }
698 }
699 }
700 out
701}
702
703fn other_value(spec: &ParamSpec, current: Option<&ConfigValue>) -> ConfigValue {
705 match (&spec.kind, current) {
706 (ParamKind::Bool, Some(ConfigValue::Bool(b))) => ConfigValue::Bool(!b),
707 (ParamKind::Bool, _) => ConfigValue::Bool(true),
708 (ParamKind::Integer { min, max, .. }, cur) => {
709 let cur = match cur {
710 Some(ConfigValue::Integer(i)) => *i,
711 _ => min.unwrap_or(0),
712 };
713 let up = cur.saturating_add(1);
714 if max.is_none_or(|m| up <= m) {
715 ConfigValue::Integer(up)
716 } else {
717 ConfigValue::Integer(cur.saturating_sub(1).max(min.unwrap_or(i64::MIN)))
718 }
719 }
720 (ParamKind::Text, Some(ConfigValue::Text(t))) => {
721 ConfigValue::Text(format!("{t}-conformance"))
722 }
723 (_, _) => ConfigValue::Text("conformance".into()),
724 }
725}
726
727pub async fn contract_refused(cfg: &dyn Configure) -> Vec<Failure> {
731 let mut out = Vec::new();
732 let schema = cfg.schema();
733 let effective = cfg.effective();
734 for g in schema
735 .groups
736 .iter()
737 .filter(|g| g.class == ParamClass::Contract)
738 {
739 let Some(p) = g.parameters.first() else {
740 continue;
741 };
742 let current = effective.get(g.name).and_then(|v| v.get(p.name));
743 let value = other_value(p, current);
744 let change = [(p.name.to_string(), value.clone())].into_iter().collect();
745 match cfg.apply(g.name, &change).await {
746 Err(ConfigError::Contract(_)) => {}
747 Ok(_) => out.push(Failure::new(
748 "contract-refused",
749 format!(
750 "contract group {:?} accepted {}={} at runtime; it is part of what the \
751 transport was started against and belongs in the startup file",
752 g.name, p.name, value
753 ),
754 )),
755 Err(e) => out.push(Failure::new(
756 "contract-refused",
757 format!(
758 "contract group {:?} was refused for another reason than the contract, so \
759 the caller is not told to restart: {e}",
760 g.name
761 ),
762 )),
763 }
764 }
765 out
766}
767
768pub async fn read_back_and_undo(cfg: &dyn Configure) -> Vec<Failure> {
777 let mut out = Vec::new();
778 let schema = cfg.schema();
779 for g in schema
780 .groups
781 .iter()
782 .filter(|g| g.class != ParamClass::Contract)
783 {
784 for p in g.parameters.iter().filter(|p| !p.sensitive) {
785 let before = cfg.effective();
786 let current = before.get(g.name).and_then(|v| v.get(p.name));
787 let value = other_value(p, current);
788 let change = [(p.name.to_string(), value.clone())].into_iter().collect();
789 let undo = match cfg.apply(g.name, &change).await {
790 Ok(undo) => undo,
791 Err(ConfigError::Unsupported(_)) => break,
792 Err(e) => {
793 out.push(Failure::new(
794 "read-back",
795 format!(
796 "the schema says {}/{} accepts {value}; the device refused it: {e}",
797 g.name, p.name
798 ),
799 ));
800 continue;
801 }
802 };
803 let after = cfg.effective();
804 let read_back = after.get(g.name).and_then(|v| v.get(p.name));
805 if read_back != Some(&value) {
806 out.push(Failure::new(
807 "read-back",
808 format!(
809 "after apply {}/{}={value}, effective says {}: a change is not done \
810 until it can be read back",
811 g.name,
812 p.name,
813 read_back.map_or("nothing".to_string(), ToString::to_string)
814 ),
815 ));
816 }
817 if let Err(e) = cfg.apply(g.name, &undo).await {
818 out.push(Failure::new(
819 "undo-restores",
820 format!("the undo for {}/{} was refused: {e}", g.name, p.name),
821 ));
822 continue;
823 }
824 let restored = cfg.effective();
825 if restored != before {
826 out.push(Failure::new(
827 "undo-restores",
828 format!(
829 "after apply {}/{}={value} and its undo {undo:?}, effective is not what \
830 it was: {restored:?} vs {before:?}",
831 g.name, p.name
832 ),
833 ));
834 }
835 }
836 }
837 out
838}
839
840pub async fn sensitive_never_read_back(dev: &dyn Device) -> Vec<Failure> {
848 let Some(cfg) = dev.configuration() else {
849 return Vec::new();
850 };
851 let schema = cfg.schema();
852 let mut out = sensitive_absent(&schema, &cfg.effective());
853 let marker = format!(
854 "conformance-{}",
855 std::time::SystemTime::now()
856 .duration_since(std::time::UNIX_EPOCH)
857 .map_or(0, |d| d.as_nanos())
858 );
859 for g in schema
860 .groups
861 .iter()
862 .filter(|g| g.class != ParamClass::Contract)
863 {
864 for p in g
865 .parameters
866 .iter()
867 .filter(|p| p.sensitive && p.kind == ParamKind::Text)
868 {
869 let change = [(p.name.to_string(), ConfigValue::Text(marker.clone()))]
870 .into_iter()
871 .collect();
872 let undo = match cfg.apply(g.name, &change).await {
873 Ok(undo) => undo,
874 Err(ConfigError::Unsupported(_)) => break,
875 Err(e) => {
876 out.push(Failure::new(
877 "sensitive-never-read-back",
878 format!(
879 "the schema says {}/{} takes text; the device refused it: {e}",
880 g.name, p.name
881 ),
882 ));
883 continue;
884 }
885 };
886 let effective = cfg.effective();
887 let leaks = [
888 ("effective", format!("{effective:?}")),
889 ("the schema", format!("{:?}", cfg.schema())),
890 ("the report", format!("{:?}", dev.report())),
891 ("oper", format!("{:?}", dev.oper())),
892 ("the identity", format!("{:?}", dev.identity())),
893 ];
894 for (what, text) in leaks {
895 if text.contains(&marker) {
896 out.push(Failure::new(
897 "sensitive-never-read-back",
898 format!(
899 "the value written to sensitive {}/{} appears in {what}: {text}",
900 g.name, p.name
901 ),
902 ));
903 }
904 }
905 if !undo.is_empty()
906 && let Err(e) = cfg.apply(g.name, &undo).await
907 {
908 out.push(Failure::new(
909 "sensitive-never-read-back",
910 format!("the undo for {}/{} was refused: {e}", g.name, p.name),
911 ));
912 }
913 }
914 }
915 out
916}
917
918pub async fn configuration(dev: &dyn Device) -> Vec<Failure> {
921 let Some(cfg) = dev.configuration() else {
922 return Vec::new();
923 };
924 let schema = cfg.schema();
925 let mut out = schema_is_valid(&schema);
926 out.extend(effective_within_schema(&schema, &cfg.effective()));
927 out.extend(contract_refused(cfg).await);
928 out.extend(read_back_and_undo(cfg).await);
929 out.extend(sensitive_never_read_back(dev).await);
930 out
931}
932
933type Counter = fn(&NetdevStats) -> Option<u64>;
937
938const COUNTERS: [(&str, Counter); 9] = [
940 ("in_octets", |s| s.in_octets),
941 ("out_octets", |s| s.out_octets),
942 ("in_errors", |s| s.in_errors),
943 ("out_errors", |s| s.out_errors),
944 ("in_discards", |s| s.in_discards),
945 ("out_discards", |s| s.out_discards),
946 ("in_multicast_pkts", |s| s.in_multicast_pkts),
947 ("in_pkts", |s| s.in_pkts),
948 ("out_pkts", |s| s.out_pkts),
949];
950
951pub async fn netdev<Fut>(
959 dev: &dyn Netdev,
960 samples: usize,
961 mut tick: impl FnMut() -> Fut,
962) -> Vec<Failure>
963where
964 Fut: Future<Output = ()>,
965{
966 let mut out = Vec::new();
967 if dev.interface().trim().is_empty() {
968 out.push(Failure::new(
969 "netdev-is-named",
970 "interface() is empty: a netdev is named as the kernel spells it",
971 ));
972 }
973 let mut prev = (dev.epoch(), dev.statistics());
974 for _ in 0..samples {
975 tick().await;
976 let now = (dev.epoch(), dev.statistics());
977 if now.0 == prev.0 {
978 for (name, read) in COUNTERS {
979 if let (Some(a), Some(b)) = (read(&prev.1), read(&now.1))
980 && b < a
981 {
982 out.push(Failure::new(
983 "counters-never-decrease",
984 format!(
985 "{name} went from {a} to {b} within epoch {}: a counter that resets \
986 moves the epoch",
987 now.0
988 ),
989 ));
990 }
991 }
992 }
993 prev = now;
994 }
995 out
996}
997
998pub async fn device(dev: &dyn Device, event_deadline: impl Future<Output = ()>) -> Vec<Failure> {
1001 let mut out = core(dev);
1002 out.extend(events_are_edge_triggered(dev, event_deadline).await);
1003 out.extend(configuration(dev).await);
1004 out
1005}
1006
1007#[cfg(test)]
1008mod tests {
1009 use std::collections::BTreeMap;
1012 use std::sync::atomic::{AtomicU64, Ordering};
1013 use std::time::Duration;
1014
1015 use super::*;
1016 use crate::config::{ConfigGroup, Undo};
1017
1018 fn checks(failures: &[Failure]) -> Vec<&'static str> {
1019 failures.iter().map(|f| f.check).collect()
1020 }
1021
1022 fn detail(failures: &[Failure], check: &str) -> String {
1023 failures
1024 .iter()
1025 .filter(|f| f.check == check)
1026 .map(|f| f.detail.clone())
1027 .collect::<Vec<_>>()
1028 .join("\n")
1029 }
1030
1031 struct ForgetsOper(Arc<dyn Device>);
1035
1036 #[async_trait::async_trait]
1037 impl Device for ForgetsOper {
1038 fn report(&self) -> Report {
1039 self.0.report()
1040 }
1041 fn identity(&self) -> Identity {
1042 self.0.identity()
1043 }
1044 fn configuration(&self) -> Option<&dyn Configure> {
1045 self.0.configuration()
1046 }
1047 fn actions(&self) -> Option<&dyn Actions> {
1048 self.0.actions()
1049 }
1050 async fn close(&self) -> Result<(), DeviceError> {
1051 self.0.close().await
1052 }
1053 async fn next_event(&self) -> Result<DeviceEvent, DeviceError> {
1054 self.0.next_event().await
1055 }
1056 }
1057
1058 struct ForgetsMetrics(Arc<dyn Medium>);
1060
1061 #[async_trait::async_trait]
1062 impl Device for ForgetsMetrics {
1063 fn report(&self) -> Report {
1064 self.0.report()
1065 }
1066 fn oper(&self) -> OperStatus {
1067 self.0.oper()
1068 }
1069 fn identity(&self) -> Identity {
1070 self.0.identity()
1071 }
1072 fn configuration(&self) -> Option<&dyn Configure> {
1073 self.0.configuration()
1074 }
1075 fn actions(&self) -> Option<&dyn Actions> {
1076 self.0.actions()
1077 }
1078 async fn close(&self) -> Result<(), DeviceError> {
1079 self.0.close().await
1080 }
1081 async fn next_event(&self) -> Result<DeviceEvent, DeviceError> {
1082 self.0.next_event().await
1083 }
1084 }
1085
1086 #[async_trait::async_trait]
1087 impl Medium for ForgetsMetrics {
1088 fn capabilities(&self) -> Capabilities {
1089 self.0.capabilities()
1090 }
1091 async fn send(&self, lane: &LaneKey, sdu: &[u8]) -> Result<(), DeviceError> {
1092 self.0.send(lane, sdu).await
1093 }
1094 async fn recv(&self) -> Result<(LaneKey, Sdu), DeviceError> {
1095 self.0.recv().await
1096 }
1097 fn metrics(&self) -> Metrics {
1098 Metrics::default()
1099 }
1100 async fn configure_lanes(&self, lanes: &[LaneKey]) -> Result<(), DeviceError> {
1101 self.0.configure_lanes(lanes).await
1102 }
1103 }
1104
1105 struct ForgetsEpoch(Arc<dyn Netdev>);
1107
1108 #[async_trait::async_trait]
1109 impl Device for ForgetsEpoch {
1110 fn report(&self) -> Report {
1111 self.0.report()
1112 }
1113 fn oper(&self) -> OperStatus {
1114 self.0.oper()
1115 }
1116 fn identity(&self) -> Identity {
1117 self.0.identity()
1118 }
1119 fn configuration(&self) -> Option<&dyn Configure> {
1120 self.0.configuration()
1121 }
1122 fn actions(&self) -> Option<&dyn Actions> {
1123 self.0.actions()
1124 }
1125 async fn close(&self) -> Result<(), DeviceError> {
1126 self.0.close().await
1127 }
1128 async fn next_event(&self) -> Result<DeviceEvent, DeviceError> {
1129 self.0.next_event().await
1130 }
1131 }
1132
1133 impl Netdev for ForgetsEpoch {
1134 fn interface(&self) -> &str {
1135 self.0.interface()
1136 }
1137 fn statistics(&self) -> NetdevStats {
1138 self.0.statistics()
1139 }
1140 }
1141
1142 #[tokio::test]
1143 async fn a_decorator_that_forgets_a_method_is_named_with_the_method() {
1144 let f =
1145 device_decorator_forwards("ForgetsOper", |inner| Arc::new(ForgetsOper(inner))).await;
1146 assert_eq!(checks(&f), ["decorator-forwards", "decorator-forwards"]);
1147 let d = detail(&f, "decorator-forwards");
1148 assert!(
1149 d.contains("rewrote oper") && d.contains("[\"oper\"]"),
1150 "{d}"
1151 );
1152
1153 let f =
1154 medium_decorator_forwards("ForgetsMetrics", |inner| Arc::new(ForgetsMetrics(inner)))
1155 .await;
1156 assert!(
1157 detail(&f, "decorator-forwards").contains("[\"metrics\"]"),
1158 "{f:?}"
1159 );
1160
1161 let f =
1162 netdev_decorator_forwards("ForgetsEpoch", |inner| Arc::new(ForgetsEpoch(inner))).await;
1163 assert!(
1164 detail(&f, "decorator-forwards").contains("[\"epoch\"]"),
1165 "{f:?}"
1166 );
1167
1168 assert!(
1170 device_decorator_forwards("id", |inner| inner)
1171 .await
1172 .is_empty()
1173 );
1174 assert!(
1175 medium_decorator_forwards("id", |inner| inner)
1176 .await
1177 .is_empty()
1178 );
1179 assert!(
1180 netdev_decorator_forwards("id", |inner| inner)
1181 .await
1182 .is_empty()
1183 );
1184 }
1185
1186 struct Flickers(AtomicU64);
1190
1191 impl Device for Flickers {
1192 fn oper(&self) -> OperStatus {
1193 if self.0.fetch_add(1, Ordering::Relaxed).is_multiple_of(2) {
1194 OperStatus::up()
1195 } else {
1196 OperStatus::unknown()
1197 }
1198 }
1199 }
1200
1201 struct Ageless;
1203
1204 impl Device for Ageless {
1205 fn report(&self) -> Report {
1206 Report::new().rssi(-70_000)
1207 }
1208 }
1209
1210 #[test]
1211 fn a_status_that_changes_between_two_calls_and_a_reading_without_an_age_are_findings() {
1212 assert_eq!(
1213 checks(&core(&Flickers(AtomicU64::new(0)))),
1214 ["oper-is-cached"]
1215 );
1216 assert_eq!(checks(&core(&Ageless)), ["report-says-its-age"]);
1217 assert!(core(&Recording::new()).is_empty());
1218 }
1219
1220 struct Repeats {
1224 script: Vec<DeviceEvent>,
1225 at: AtomicU64,
1226 }
1227
1228 #[async_trait::async_trait]
1229 impl Device for Repeats {
1230 async fn next_event(&self) -> Result<DeviceEvent, DeviceError> {
1231 #[allow(clippy::cast_possible_truncation)]
1232 let i = self.at.fetch_add(1, Ordering::Relaxed) as usize;
1233 match self.script.get(i) {
1234 Some(ev) => Ok(ev.clone()),
1235 None => std::future::pending().await,
1236 }
1237 }
1238 }
1239
1240 #[tokio::test(start_paused = true)]
1241 async fn a_condition_reported_twice_without_the_opposite_edge_is_a_finding() {
1242 let nags = Repeats {
1243 script: vec![
1244 DeviceEvent::raised("+CME ERROR 3"),
1245 DeviceEvent::raised("+CME ERROR 3"),
1246 DeviceEvent::cleared("+CME ERROR 3"),
1247 ],
1248 at: AtomicU64::new(0),
1249 };
1250 let f = events_are_edge_triggered(&nags, tokio::time::sleep(Duration::from_secs(1))).await;
1251 assert_eq!(checks(&f), ["events-are-edge-triggered"]);
1252 assert!(f[0].detail.contains("twice in a row"), "{f:?}");
1253
1254 let edgy = Repeats {
1257 script: vec![
1258 DeviceEvent::raised("no carrier"),
1259 DeviceEvent::cleared("carrier"),
1260 DeviceEvent::raised("no carrier"),
1261 DeviceEvent::raised("registration lost"),
1262 ],
1263 at: AtomicU64::new(0),
1264 };
1265 assert!(
1266 events_are_edge_triggered(&edgy, tokio::time::sleep(Duration::from_secs(1)))
1267 .await
1268 .is_empty()
1269 );
1270 }
1271
1272 #[derive(Clone, Copy, Default)]
1275 #[allow(clippy::struct_excessive_bools)] struct Faults {
1277 nods: bool,
1279 forgets_undo: bool,
1281 bends: bool,
1283 leaks: bool,
1285 echoes: bool,
1287 off_schema: bool,
1289 bad_schema: bool,
1291 }
1292
1293 struct Knobs {
1296 faults: Faults,
1297 state: Mutex<BTreeMap<&'static str, ConfigValue>>,
1298 }
1299
1300 impl Knobs {
1301 fn new(faults: Faults) -> Self {
1302 Self {
1303 faults,
1304 state: Mutex::new(
1305 [
1306 ("level", ConfigValue::Integer(3)),
1307 ("label", ConfigValue::Text("lab".into())),
1308 ("pin", ConfigValue::Text("0000".into())),
1309 ("baud", ConfigValue::Integer(9600)),
1310 ]
1311 .into_iter()
1312 .collect(),
1313 ),
1314 }
1315 }
1316
1317 fn get(&self, name: &str) -> ConfigValue {
1318 self.state.lock().expect("not poisoned")[name].clone()
1319 }
1320 }
1321
1322 impl Device for Knobs {
1323 fn identity(&self) -> Identity {
1324 if self.faults.echoes {
1325 Identity::unknown().serial_num(self.get("pin").to_string())
1326 } else {
1327 Identity::unknown()
1328 }
1329 }
1330 fn configuration(&self) -> Option<&dyn Configure> {
1331 Some(self)
1332 }
1333 }
1334
1335 #[async_trait::async_trait]
1336 impl Configure for Knobs {
1337 fn schema(&self) -> Schema {
1338 let mut s = Schema::new()
1339 .with(
1340 ConfigGroup::new("tune", ParamClass::Hot, "tuning")
1341 .with(ParamSpec::new(
1342 "level",
1343 ParamKind::integer(Some(0), Some(10), None),
1344 "a level",
1345 ))
1346 .with(ParamSpec::new("label", ParamKind::Text, "a label")),
1347 )
1348 .with(
1349 ConfigGroup::new("auth", ParamClass::Hot, "the PIN")
1350 .with(ParamSpec::new("pin", ParamKind::Text, "the SIM PIN").sensitive()),
1351 )
1352 .with(
1353 ConfigGroup::new("port", ParamClass::Contract, "the port").with(
1354 ParamSpec::new(
1355 "baud",
1356 ParamKind::integer(Some(1200), Some(115_200), Some("bit/s")),
1357 "the rate",
1358 ),
1359 ),
1360 );
1361 if self.faults.bad_schema {
1362 s = s.with(ConfigGroup::new("tune", ParamClass::Hot, "again").with(
1363 ParamSpec::new("x", ParamKind::integer(Some(10), Some(1), None), "crossed"),
1364 ));
1365 }
1366 s
1367 }
1368
1369 fn effective(&self) -> Effective {
1370 let mut tune: BTreeMap<String, ConfigValue> = [
1371 ("level".to_string(), self.get("level")),
1372 ("label".to_string(), self.get("label")),
1373 ]
1374 .into_iter()
1375 .collect();
1376 if self.faults.off_schema {
1377 tune.insert("bogus".into(), ConfigValue::Bool(true));
1378 }
1379 let mut auth = BTreeMap::new();
1380 if self.faults.leaks {
1381 auth.insert("pin".to_string(), self.get("pin"));
1382 }
1383 [
1384 ("tune".to_string(), tune),
1385 ("auth".to_string(), auth),
1386 (
1387 "port".to_string(),
1388 [("baud".to_string(), self.get("baud"))]
1389 .into_iter()
1390 .collect(),
1391 ),
1392 ]
1393 .into_iter()
1394 .collect()
1395 }
1396
1397 async fn apply(
1398 &self,
1399 group: &str,
1400 values: &BTreeMap<String, ConfigValue>,
1401 ) -> Result<Undo, ConfigError> {
1402 if group == "port" && !self.faults.bends {
1403 return Err(ConfigError::Contract(group.into()));
1404 }
1405 let mut state = self.state.lock().expect("not poisoned");
1406 let mut undo = Undo::new();
1407 for (name, v) in values {
1408 let key: &'static str = match name.as_str() {
1409 "level" => "level",
1410 "label" => "label",
1411 "pin" => "pin",
1412 "baud" => "baud",
1413 other => {
1414 return Err(ConfigError::UnknownParameter {
1415 group: group.into(),
1416 name: other.into(),
1417 });
1418 }
1419 };
1420 if !self.faults.forgets_undo {
1421 undo.insert(name.clone(), state[key].clone());
1422 }
1423 if !self.faults.nods {
1424 state.insert(key, v.clone());
1425 }
1426 }
1427 Ok(undo)
1428 }
1429 }
1430
1431 #[tokio::test]
1432 async fn each_configuration_fault_is_found_and_a_device_without_one_passes() {
1433 assert!(
1434 configuration(&Knobs::new(Faults::default()))
1435 .await
1436 .is_empty()
1437 );
1438
1439 let cases: [(&str, Faults, &str, &str); 7] = [
1440 (
1441 "nods",
1442 Faults {
1443 nods: true,
1444 ..Faults::default()
1445 },
1446 "read-back",
1447 "not done until it can be read back",
1448 ),
1449 (
1450 "forgets_undo",
1451 Faults {
1452 forgets_undo: true,
1453 ..Faults::default()
1454 },
1455 "undo-restores",
1456 "not what it was",
1457 ),
1458 (
1459 "bends",
1460 Faults {
1461 bends: true,
1462 ..Faults::default()
1463 },
1464 "contract-refused",
1465 "accepted",
1466 ),
1467 (
1468 "leaks",
1469 Faults {
1470 leaks: true,
1471 ..Faults::default()
1472 },
1473 "sensitive-never-read-back",
1474 "effective",
1475 ),
1476 (
1477 "echoes",
1478 Faults {
1479 echoes: true,
1480 ..Faults::default()
1481 },
1482 "sensitive-never-read-back",
1483 "the identity",
1484 ),
1485 (
1486 "off_schema",
1487 Faults {
1488 off_schema: true,
1489 ..Faults::default()
1490 },
1491 "effective-within-schema",
1492 "tune/bogus",
1493 ),
1494 (
1495 "bad_schema",
1496 Faults {
1497 bad_schema: true,
1498 ..Faults::default()
1499 },
1500 "schema-is-valid",
1501 "declared twice",
1502 ),
1503 ];
1504 for (name, faults, check, words) in cases {
1505 let f = configuration(&Knobs::new(faults)).await;
1506 let d = detail(&f, check);
1507 assert!(
1508 !d.is_empty() && d.contains(words),
1509 "{name}: expected {check} saying {words:?}; got {f:?}"
1510 );
1511 }
1512 let f = schema_is_valid(
1514 &Knobs::new(Faults {
1515 bad_schema: true,
1516 ..Faults::default()
1517 })
1518 .schema(),
1519 );
1520 assert!(
1521 detail(&f, "schema-is-valid").contains("min 10 is above max 1"),
1522 "{f:?}"
1523 );
1524 }
1525
1526 struct Rewinds {
1530 honest: bool,
1531 reads: AtomicU64,
1532 }
1533
1534 impl Device for Rewinds {}
1535
1536 impl Netdev for Rewinds {
1537 fn interface(&self) -> &'static str {
1538 "wwan0"
1539 }
1540 fn statistics(&self) -> NetdevStats {
1541 let n = self.reads.fetch_add(1, Ordering::Relaxed);
1542 NetdevStats {
1543 in_octets: Some(if n < 2 { 1_000 } else { 10 }),
1544 ..NetdevStats::default()
1545 }
1546 }
1547 fn epoch(&self) -> u64 {
1548 u64::from(self.honest && self.reads.load(Ordering::Relaxed) >= 2)
1549 }
1550 }
1551
1552 #[tokio::test]
1553 async fn a_counter_that_goes_backwards_without_moving_the_epoch_is_a_finding() {
1554 let f = netdev(
1555 &Rewinds {
1556 honest: false,
1557 reads: AtomicU64::new(0),
1558 },
1559 3,
1560 || async {},
1561 )
1562 .await;
1563 assert_eq!(checks(&f), ["counters-never-decrease"]);
1564 assert!(
1565 f[0].detail.contains("in_octets went from 1000 to 10"),
1566 "{f:?}"
1567 );
1568
1569 let f = netdev(
1570 &Rewinds {
1571 honest: true,
1572 reads: AtomicU64::new(0),
1573 },
1574 3,
1575 || async {},
1576 )
1577 .await;
1578 assert!(f.is_empty(), "{f:?}");
1579 }
1580}