use std::collections::BTreeMap;
use serde::Serialize;
use super::{Contract, Error, Evidence, Expected, NodeId, Observed, Snapshot, Unit};
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Outcome {
Matched,
Mismatch,
Unverified,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
pub enum Attribute {
DataType,
ValueRank,
EngineeringUnits,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum AttributeValue {
DataType(NodeId),
ValueRank(i32),
EngineeringUnits(Unit),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Finding {
pub name: String,
pub node: NodeId,
pub attribute: Attribute,
pub expected: AttributeValue,
pub before: Option<Evidence<AttributeValue>>,
pub after: Option<Evidence<AttributeValue>>,
pub before_outcome: Option<Outcome>,
pub outcome: Outcome,
}
#[derive(Debug, Default, Eq, PartialEq, Serialize)]
pub struct Counts {
pub matched: usize,
pub mismatch: usize,
pub unverified: usize,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Report {
pub schema_version: u32,
pub baseline_provided: bool,
pub device: String,
pub application_uri: String,
pub principal: String,
pub decision: Outcome,
pub complete: bool,
pub counts: Counts,
pub findings: Vec<Finding>,
}
impl Report {
pub fn exit_code(&self) -> u8 {
match self.decision {
Outcome::Matched => 0,
Outcome::Mismatch => 2,
Outcome::Unverified => 3,
}
}
}
fn index<'a>(
contract: &Contract,
definitions: &BTreeMap<&str, &Expected>,
snapshot: &'a Snapshot,
) -> Result<BTreeMap<&'a str, &'a Observed>, Error> {
let c = &contract.0;
let s = &snapshot.0;
for (field, expected, observed) in [
("device", &c.device, &s.device),
("applicationUri", &c.application_uri, &s.application_uri),
("principal", &c.principal, &s.principal),
] {
if expected != observed {
return Err(Error::new(format!("{field} differs from the contract")));
}
}
let mut index = BTreeMap::new();
for (i, row) in s.signals.iter().enumerate() {
let definition = definitions
.get(row.name.as_str())
.ok_or_else(|| Error::new(format!("signals[{i}].name is absent from the contract")))?;
if definition.node != row.node {
return Err(Error::new(format!(
"signals[{i}].node differs from the contract mapping"
)));
}
index.insert(row.name.as_str(), row);
}
Ok(index)
}
impl<T: Clone> Evidence<T> {
fn mapped(&self, f: impl FnOnce(T) -> AttributeValue) -> Evidence<AttributeValue> {
Evidence {
status: self.status,
value: self.value.clone().map(f),
}
}
}
fn evidence(row: Option<&&Observed>, attribute: Attribute) -> Option<Evidence<AttributeValue>> {
let signal = row?;
match attribute {
Attribute::DataType => signal
.data_type
.as_ref()
.map(|e| e.mapped(AttributeValue::DataType)),
Attribute::ValueRank => signal
.value_rank
.as_ref()
.map(|e| e.mapped(AttributeValue::ValueRank)),
Attribute::EngineeringUnits => signal
.engineering_units
.as_ref()
.map(|e| e.mapped(AttributeValue::EngineeringUnits)),
}
}
pub fn assess(contract: &Contract, snapshot: &Snapshot) -> Result<Report, Error> {
evaluate(contract, None, snapshot)
}
pub fn compare(contract: &Contract, before: &Snapshot, after: &Snapshot) -> Result<Report, Error> {
evaluate(contract, Some(before), after)
}
fn evaluate(
contract: &Contract,
baseline: Option<&Snapshot>,
snapshot: &Snapshot,
) -> Result<Report, Error> {
let definitions: BTreeMap<_, _> = contract
.0
.signals
.iter()
.map(|s| (s.name.as_str(), s))
.collect();
let before = baseline
.map(|s| index(contract, &definitions, s))
.transpose()
.map_err(|e| e.at("before"))?;
let after = index(contract, &definitions, snapshot).map_err(|e| e.at("snapshot"))?;
let mut counts = Counts::default();
let mut findings = Vec::new();
for (name, signal) in definitions {
let prior_row = before.as_ref().and_then(|rows| rows.get(name));
let current_row = after.get(name);
let datatype = (
Attribute::DataType,
AttributeValue::DataType(signal.data_type.clone()),
);
let rank = signal
.value_rank
.map(|v| (Attribute::ValueRank, AttributeValue::ValueRank(v)));
let units = signal.engineering_units.clone().map(|unit| {
(
Attribute::EngineeringUnits,
AttributeValue::EngineeringUnits(unit),
)
});
for (attribute, expected) in std::iter::once(datatype).chain(rank).chain(units) {
let previous = evidence(prior_row, attribute);
let current = evidence(current_row, attribute);
let classify = |e: &Option<Evidence<AttributeValue>>| match e
.as_ref()
.and_then(|r| r.value.as_ref())
{
Some(AttributeValue::EngineeringUnits(unit)) if !unit.is_identified() => {
Outcome::Unverified
}
Some(value) if *value == expected => Outcome::Matched,
Some(_) => Outcome::Mismatch,
None => Outcome::Unverified,
};
let outcome = classify(¤t);
let before_outcome = baseline.map(|_| classify(&previous));
match outcome {
Outcome::Matched => counts.matched += 1,
Outcome::Mismatch => counts.mismatch += 1,
Outcome::Unverified => counts.unverified += 1,
}
findings.push(Finding {
name: name.to_owned(),
node: signal.node.clone(),
attribute,
expected,
before: previous,
before_outcome,
after: current,
outcome,
});
}
}
let decision = if counts.mismatch > 0 {
Outcome::Mismatch
} else if counts.unverified > 0 {
Outcome::Unverified
} else {
Outcome::Matched
};
Ok(Report {
schema_version: 2,
baseline_provided: baseline.is_some(),
device: contract.0.device.clone(),
application_uri: contract.0.application_uri.clone(),
principal: contract.0.principal.clone(),
complete: counts.unverified == 0,
counts,
decision,
findings,
})
}
impl Contract {
pub fn validate_capture(&self, snapshot: &Snapshot) -> Result<(), Error> {
let definitions = self
.0
.signals
.iter()
.map(|s| (s.name.as_str(), s))
.collect();
let observed = index(self, &definitions, snapshot)?;
if observed.len() != self.0.signals.len() {
return Err(Error::new(
"capture is missing one or more requested signals",
));
}
for (i, expected) in self.0.signals.iter().enumerate() {
let signal = observed[expected.name.as_str()];
if signal.data_type.is_none()
&& signal.value_rank.is_none()
&& signal.engineering_units.is_none()
{
continue;
}
if signal.data_type.is_none() {
return Err(Error::new(format!(
"capture is missing DataType for contract signals[{i}]"
)));
}
if signal.value_rank.is_some() != expected.value_rank.is_some() {
return Err(Error::new(format!(
"capture ValueRank coverage differs from contract signals[{i}]"
)));
}
if signal.engineering_units.is_some() != expected.engineering_units.is_some() {
return Err(Error::new(format!(
"capture EngineeringUnits coverage differs from contract signals[{i}]"
)));
}
}
Ok(())
}
}