1use std::collections::BTreeMap;
2
3use serde::Serialize;
4
5use super::{Contract, Error, Evidence, Expected, NodeId, Observed, Snapshot, Unit};
6
7#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
9#[serde(rename_all = "lowercase")]
10pub enum Outcome {
11 Matched,
13 Mismatch,
15 Unverified,
17}
18
19#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
21pub enum Attribute {
22 DataType,
24 ValueRank,
26 EngineeringUnits,
28}
29
30#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
32#[serde(untagged)]
33pub enum AttributeValue {
34 DataType(NodeId),
36 ValueRank(i32),
38 EngineeringUnits(Unit),
40}
41
42#[derive(Debug, Serialize)]
44#[serde(rename_all = "camelCase")]
45pub struct Finding {
46 pub name: String,
48 pub node: NodeId,
50 pub attribute: Attribute,
52 pub expected: AttributeValue,
54 pub before: Option<Evidence<AttributeValue>>,
56 pub after: Option<Evidence<AttributeValue>>,
58 pub before_outcome: Option<Outcome>,
62 pub outcome: Outcome,
64}
65
66#[derive(Debug, Default, Eq, PartialEq, Serialize)]
68pub struct Counts {
69 pub matched: usize,
71 pub mismatch: usize,
73 pub unverified: usize,
75}
76
77#[derive(Debug, Serialize)]
79#[serde(rename_all = "camelCase")]
80pub struct Report {
81 pub schema_version: u32,
83 pub baseline_provided: bool,
85 pub device: String,
87 pub application_uri: String,
89 pub principal: String,
91 pub decision: Outcome,
93 pub complete: bool,
95 pub counts: Counts,
97 pub findings: Vec<Finding>,
99}
100
101impl Report {
102 pub fn exit_code(&self) -> u8 {
104 match self.decision {
105 Outcome::Matched => 0,
106 Outcome::Mismatch => 2,
107 Outcome::Unverified => 3,
108 }
109 }
110}
111
112fn index<'a>(
113 contract: &Contract,
114 definitions: &BTreeMap<&str, &Expected>,
115 snapshot: &'a Snapshot,
116) -> Result<BTreeMap<&'a str, &'a Observed>, Error> {
117 let c = &contract.0;
118 let s = &snapshot.0;
119 for (field, expected, observed) in [
120 ("device", &c.device, &s.device),
121 ("applicationUri", &c.application_uri, &s.application_uri),
122 ("principal", &c.principal, &s.principal),
123 ] {
124 if expected != observed {
125 return Err(Error::new(format!("{field} differs from the contract")));
126 }
127 }
128 let mut index = BTreeMap::new();
129 for (i, row) in s.signals.iter().enumerate() {
130 let definition = definitions
131 .get(row.name.as_str())
132 .ok_or_else(|| Error::new(format!("signals[{i}].name is absent from the contract")))?;
133 if definition.node != row.node {
134 return Err(Error::new(format!(
135 "signals[{i}].node differs from the contract mapping"
136 )));
137 }
138 index.insert(row.name.as_str(), row);
139 }
140 Ok(index)
141}
142
143impl<T: Clone> Evidence<T> {
144 fn mapped(&self, f: impl FnOnce(T) -> AttributeValue) -> Evidence<AttributeValue> {
145 Evidence {
146 status: self.status,
147 value: self.value.clone().map(f),
148 }
149 }
150}
151
152fn evidence(row: Option<&&Observed>, attribute: Attribute) -> Option<Evidence<AttributeValue>> {
153 let signal = row?;
154 match attribute {
155 Attribute::DataType => signal
156 .data_type
157 .as_ref()
158 .map(|e| e.mapped(AttributeValue::DataType)),
159 Attribute::ValueRank => signal
160 .value_rank
161 .as_ref()
162 .map(|e| e.mapped(AttributeValue::ValueRank)),
163 Attribute::EngineeringUnits => signal
164 .engineering_units
165 .as_ref()
166 .map(|e| e.mapped(AttributeValue::EngineeringUnits)),
167 }
168}
169
170pub fn assess(contract: &Contract, snapshot: &Snapshot) -> Result<Report, Error> {
174 evaluate(contract, None, snapshot)
175}
176
177pub fn compare(contract: &Contract, before: &Snapshot, after: &Snapshot) -> Result<Report, Error> {
181 evaluate(contract, Some(before), after)
182}
183
184fn evaluate(
185 contract: &Contract,
186 baseline: Option<&Snapshot>,
187 snapshot: &Snapshot,
188) -> Result<Report, Error> {
189 let definitions: BTreeMap<_, _> = contract
190 .0
191 .signals
192 .iter()
193 .map(|s| (s.name.as_str(), s))
194 .collect();
195 let before = baseline
196 .map(|s| index(contract, &definitions, s))
197 .transpose()
198 .map_err(|e| e.at("before"))?;
199 let after = index(contract, &definitions, snapshot).map_err(|e| e.at("snapshot"))?;
200 let mut counts = Counts::default();
201 let mut findings = Vec::new();
202 for (name, signal) in definitions {
203 let prior_row = before.as_ref().and_then(|rows| rows.get(name));
204 let current_row = after.get(name);
205 let datatype = (
206 Attribute::DataType,
207 AttributeValue::DataType(signal.data_type.clone()),
208 );
209 let rank = signal
210 .value_rank
211 .map(|v| (Attribute::ValueRank, AttributeValue::ValueRank(v)));
212 let units = signal.engineering_units.clone().map(|unit| {
213 (
214 Attribute::EngineeringUnits,
215 AttributeValue::EngineeringUnits(unit),
216 )
217 });
218 for (attribute, expected) in std::iter::once(datatype).chain(rank).chain(units) {
219 let previous = evidence(prior_row, attribute);
220 let current = evidence(current_row, attribute);
221 let classify = |e: &Option<Evidence<AttributeValue>>| match e
222 .as_ref()
223 .and_then(|r| r.value.as_ref())
224 {
225 Some(AttributeValue::EngineeringUnits(unit)) if !unit.is_identified() => {
226 Outcome::Unverified
227 }
228 Some(value) if *value == expected => Outcome::Matched,
229 Some(_) => Outcome::Mismatch,
230 None => Outcome::Unverified,
231 };
232 let outcome = classify(¤t);
233 let before_outcome = baseline.map(|_| classify(&previous));
234 match outcome {
235 Outcome::Matched => counts.matched += 1,
236 Outcome::Mismatch => counts.mismatch += 1,
237 Outcome::Unverified => counts.unverified += 1,
238 }
239 findings.push(Finding {
240 name: name.to_owned(),
241 node: signal.node.clone(),
242 attribute,
243 expected,
244 before: previous,
245 before_outcome,
246 after: current,
247 outcome,
248 });
249 }
250 }
251 let decision = if counts.mismatch > 0 {
252 Outcome::Mismatch
253 } else if counts.unverified > 0 {
254 Outcome::Unverified
255 } else {
256 Outcome::Matched
257 };
258 Ok(Report {
259 schema_version: 2,
260 baseline_provided: baseline.is_some(),
261 device: contract.0.device.clone(),
262 application_uri: contract.0.application_uri.clone(),
263 principal: contract.0.principal.clone(),
264 complete: counts.unverified == 0,
265 counts,
266 decision,
267 findings,
268 })
269}
270
271impl Contract {
272 pub fn validate_capture(&self, snapshot: &Snapshot) -> Result<(), Error> {
279 let definitions = self
280 .0
281 .signals
282 .iter()
283 .map(|s| (s.name.as_str(), s))
284 .collect();
285 let observed = index(self, &definitions, snapshot)?;
286 if observed.len() != self.0.signals.len() {
287 return Err(Error::new(
288 "capture is missing one or more requested signals",
289 ));
290 }
291 for (i, expected) in self.0.signals.iter().enumerate() {
292 let signal = observed[expected.name.as_str()];
293 if signal.data_type.is_none()
294 && signal.value_rank.is_none()
295 && signal.engineering_units.is_none()
296 {
297 continue;
298 }
299 if signal.data_type.is_none() {
300 return Err(Error::new(format!(
301 "capture is missing DataType for contract signals[{i}]"
302 )));
303 }
304 if signal.value_rank.is_some() != expected.value_rank.is_some() {
305 return Err(Error::new(format!(
306 "capture ValueRank coverage differs from contract signals[{i}]"
307 )));
308 }
309 if signal.engineering_units.is_some() != expected.engineering_units.is_some() {
310 return Err(Error::new(format!(
311 "capture EngineeringUnits coverage differs from contract signals[{i}]"
312 )));
313 }
314 }
315 Ok(())
316 }
317}