1mod draft;
49#[cfg(feature = "cems")]
50pub mod meter;
51mod report;
52
53use std::{collections::BTreeSet, fmt, io};
54
55use serde::{Deserialize, Deserializer, Serialize, de::DeserializeOwned};
56
57use crate::{Severity, status_severity};
58
59pub use crate::NodeId;
60pub use draft::draft_contract;
61pub use report::{Attribute, AttributeValue, Counts, Finding, Outcome, Report, assess, compare};
62use {SignalObservation as Observed, SignalRequirement as Expected};
63
64pub const MAX_DOCUMENT_BYTES: usize = 4 * 1024 * 1024;
66pub const MAX_SIGNALS: usize = 1024;
68
69#[derive(Clone, Debug)]
71pub struct Error(String);
72
73impl Error {
74 fn new(message: impl Into<String>) -> Self {
75 Self(message.into())
76 }
77
78 fn at(self, path: &str) -> Self {
79 Self(format!("{path}: {self}"))
80 }
81}
82
83impl fmt::Display for Error {
84 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85 f.write_str(&self.0)
86 }
87}
88
89impl std::error::Error for Error {}
90
91impl From<crate::NodeIdError> for Error {
92 fn from(error: crate::NodeIdError) -> Self {
93 Self::new(error.to_string())
94 }
95}
96
97#[derive(Debug, Serialize, Deserialize)]
98#[serde(rename_all = "camelCase", deny_unknown_fields)]
99struct Document<T> {
100 schema_version: u32,
101 device: String,
102 application_uri: String,
103 principal: String,
104 signals: Vec<T>,
105}
106
107#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
110#[serde(rename_all = "camelCase", deny_unknown_fields)]
111pub struct SignalRequirement {
112 pub name: String,
114 pub node: NodeId,
116 pub data_type: NodeId,
118 #[serde(
120 default,
121 skip_serializing_if = "Option::is_none",
122 deserialize_with = "present"
123 )]
124 pub value_rank: Option<i32>,
125 #[serde(
127 default,
128 skip_serializing_if = "Option::is_none",
129 deserialize_with = "present"
130 )]
131 pub engineering_units: Option<Unit>,
132}
133
134impl SignalRequirement {
135 pub fn new(name: impl Into<String>, node: NodeId, data_type: NodeId) -> Self {
137 Self {
138 name: name.into(),
139 node,
140 data_type,
141 value_rank: None,
142 engineering_units: None,
143 }
144 }
145}
146
147pub use crate::EngineeringUnit as Unit;
149
150impl Unit {
151 fn validate(&self) -> Result<(), Error> {
152 if self.namespace_uri.chars().any(char::is_control) {
153 return Err(Error::new("namespaceUri contains control characters"));
154 }
155 Ok(())
156 }
157}
158
159#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
161#[serde(deny_unknown_fields, bound(deserialize = "T: Deserialize<'de>"))]
162pub struct Evidence<T> {
163 pub status: u32,
165 #[serde(
167 default,
168 skip_serializing_if = "Option::is_none",
169 deserialize_with = "present"
170 )]
171 pub value: Option<T>,
172}
173
174fn present<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
177where
178 D: Deserializer<'de>,
179 T: Deserialize<'de>,
180{
181 T::deserialize(deserializer).map(Some)
182}
183
184#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
186#[serde(rename_all = "camelCase", deny_unknown_fields)]
187pub struct SignalObservation {
188 pub name: String,
190 pub node: NodeId,
192 #[serde(
194 default,
195 skip_serializing_if = "Option::is_none",
196 deserialize_with = "present"
197 )]
198 pub data_type: Option<Evidence<NodeId>>,
199 #[serde(
201 default,
202 skip_serializing_if = "Option::is_none",
203 deserialize_with = "present"
204 )]
205 pub value_rank: Option<Evidence<i32>>,
206 #[serde(
208 default,
209 skip_serializing_if = "Option::is_none",
210 deserialize_with = "present"
211 )]
212 pub engineering_units: Option<Evidence<Unit>>,
213}
214
215impl SignalObservation {
216 pub fn new(name: impl Into<String>, node: NodeId) -> Self {
218 Self {
219 name: name.into(),
220 node,
221 data_type: None,
222 value_rank: None,
223 engineering_units: None,
224 }
225 }
226}
227
228#[derive(Debug, Serialize)]
230#[serde(transparent)]
231pub struct Contract(Document<SignalRequirement>);
232
233impl Contract {
234 pub fn new(
249 device: impl Into<String>,
250 application_uri: impl Into<String>,
251 principal: impl Into<String>,
252 signals: Vec<SignalRequirement>,
253 ) -> Result<Self, Error> {
254 validate_contract(Document::new(device, application_uri, principal, signals)?)
255 }
256
257 pub fn device(&self) -> &str {
259 &self.0.device
260 }
261
262 pub fn application_uri(&self) -> &str {
264 &self.0.application_uri
265 }
266
267 pub fn principal(&self) -> &str {
269 &self.0.principal
270 }
271
272 pub fn signals(&self) -> &[SignalRequirement] {
274 &self.0.signals
275 }
276
277 pub fn signal_count(&self) -> usize {
279 self.0.signals.len()
280 }
281}
282
283#[derive(Debug, Serialize)]
285#[serde(transparent)]
286pub struct Snapshot(Document<SignalObservation>);
287
288impl Snapshot {
289 pub fn new(
291 device: impl Into<String>,
292 application_uri: impl Into<String>,
293 principal: impl Into<String>,
294 signals: Vec<SignalObservation>,
295 ) -> Result<Self, Error> {
296 validate_snapshot(Document::new(device, application_uri, principal, signals)?)
297 }
298
299 pub fn device(&self) -> &str {
301 &self.0.device
302 }
303
304 pub fn application_uri(&self) -> &str {
306 &self.0.application_uri
307 }
308
309 pub fn principal(&self) -> &str {
311 &self.0.principal
312 }
313
314 pub fn signals(&self) -> &[SignalObservation] {
316 &self.0.signals
317 }
318}
319
320#[cfg(feature = "client")]
323pub(crate) struct SnapshotCollector {
324 document: Document<SignalObservation>,
325 budget: ByteBudget,
326}
327
328#[cfg(feature = "client")]
329impl SnapshotCollector {
330 pub(crate) fn new(contract: &Contract) -> Result<Self, Error> {
331 let document = Document {
332 schema_version: 1,
333 device: contract.device().to_owned(),
334 application_uri: contract.application_uri().to_owned(),
335 principal: contract.principal().to_owned(),
336 signals: Vec::with_capacity(contract.signal_count()),
337 };
338 let mut budget = ByteBudget(MAX_DOCUMENT_BYTES - 1);
339 serde_json::to_writer(&mut budget, &document).map_err(|e| Error::new(e.to_string()))?;
340 Ok(Self { document, budget })
341 }
342
343 pub(crate) fn push(&mut self, row: SignalObservation) -> Result<(), Error> {
344 use io::Write;
345 if !self.document.signals.is_empty() {
346 self.budget
347 .write_all(b",")
348 .map_err(|e| Error::new(e.to_string()))?;
349 }
350 serde_json::to_writer(&mut self.budget, &row).map_err(|e| Error::new(e.to_string()))?;
351 self.document.signals.push(row);
352 Ok(())
353 }
354
355 pub(crate) fn finish(self, contract: &Contract) -> Result<Snapshot, Error> {
356 let snapshot = validate_snapshot(self.document)?;
357 contract.validate_capture(&snapshot)?;
358 Ok(snapshot)
359 }
360}
361
362struct ByteBudget(usize);
364
365impl io::Write for ByteBudget {
366 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
367 self.0 = self
368 .0
369 .checked_sub(bytes.len())
370 .ok_or_else(|| io::Error::other("document exceeds 4 MiB"))?;
371 Ok(bytes.len())
372 }
373
374 fn flush(&mut self) -> io::Result<()> {
375 Ok(())
376 }
377}
378
379impl<T: Serialize> Document<T> {
380 fn new(
381 device: impl Into<String>,
382 application_uri: impl Into<String>,
383 principal: impl Into<String>,
384 signals: Vec<T>,
385 ) -> Result<Self, Error> {
386 let doc = Self {
387 schema_version: 1,
388 device: device.into(),
389 application_uri: application_uri.into(),
390 principal: principal.into(),
391 signals,
392 };
393 validate_header(&doc)?;
394 serde_json::to_writer(ByteBudget(MAX_DOCUMENT_BYTES), &doc)
395 .map_err(|error| Error::new(error.to_string()))?;
396 Ok(doc)
397 }
398}
399
400fn parse<T: DeserializeOwned>(bytes: &[u8]) -> Result<Document<T>, Error> {
401 if bytes.len() > MAX_DOCUMENT_BYTES {
402 return Err(Error::new("document exceeds 4 MiB"));
403 }
404 let doc: Document<T> = serde_json::from_slice(bytes).map_err(|error| {
405 let message: String = error
408 .to_string()
409 .chars()
410 .take(180)
411 .flat_map(char::escape_debug)
412 .collect();
413 Error::new(format!(
414 "invalid JSON at line {}, column {}: {message}",
415 error.line(),
416 error.column()
417 ))
418 })?;
419 validate_header(&doc)?;
420 Ok(doc)
421}
422
423fn validate_header<T>(doc: &Document<T>) -> Result<(), Error> {
424 if doc.schema_version != 1 {
425 return Err(Error::new("unsupported schemaVersion (expected 1)"));
426 }
427 for (path, value) in [
428 ("device", &doc.device),
429 ("applicationUri", &doc.application_uri),
430 ("principal", &doc.principal),
431 ] {
432 validate_label(value).map_err(|e| e.at(path))?;
433 }
434 if doc.signals.len() > MAX_SIGNALS {
435 return Err(Error::new("signals exceeds 1024 entries"));
436 }
437 Ok(())
438}
439
440fn validate_label(label: &str) -> Result<(), Error> {
441 if label.trim().is_empty() || label.chars().any(char::is_control) {
442 return Err(Error::new(
443 "expected nonempty text without control characters",
444 ));
445 }
446 Ok(())
447}
448
449fn validate_rank(rank: i32) -> Result<(), Error> {
450 if rank < -3 {
451 return Err(Error::new("ValueRank must be -3 or greater"));
452 }
453 Ok(())
454}
455
456fn unique<'a>(items: impl Iterator<Item = (&'a str, &'a NodeId)>) -> Result<(), Error> {
457 let mut names = BTreeSet::new();
458 let mut nodes = BTreeSet::new();
459 for (i, (name, node)) in items.enumerate() {
460 if !names.insert(name) {
461 return Err(Error::new(format!(
462 "signals[{i}].name duplicates another signal name"
463 )));
464 }
465 if !nodes.insert(node) {
466 return Err(Error::new(format!(
467 "signals[{i}].node duplicates another node identity"
468 )));
469 }
470 }
471 Ok(())
472}
473
474pub fn parse_contract(bytes: &[u8]) -> Result<Contract, Error> {
476 validate_contract(parse(bytes)?)
477}
478
479fn validate_contract(doc: Document<SignalRequirement>) -> Result<Contract, Error> {
480 if doc.signals.is_empty() {
481 return Err(Error::new("contract must specify at least one signal"));
482 }
483 for (i, s) in doc.signals.iter().enumerate() {
484 validate_label(&s.name).map_err(|e| e.at(&format!("signals[{i}].name")))?;
485 if let Some(rank) = s.value_rank {
486 validate_rank(rank).map_err(|e| e.at(&format!("signals[{i}].valueRank")))?;
487 }
488 if let Some(unit) = &s.engineering_units {
489 let path = format!("signals[{i}].engineeringUnits");
490 unit.validate().map_err(|e| e.at(&path))?;
491 if !unit.is_identified() {
492 return Err(
493 Error::new("expected nonempty namespaceUri and unitId other than -1").at(&path),
494 );
495 }
496 }
497 }
498 unique(doc.signals.iter().map(|s| (s.name.as_str(), &s.node)))?;
499 Ok(Contract(doc))
500}
501
502fn validate_observation<T>(
503 evidence: &Evidence<T>,
504 validate: impl FnOnce(&T) -> Result<(), Error>,
505) -> Result<(), Error> {
506 let good = status_severity(evidence.status) == Severity::Good;
507 let result = match (good, evidence.value.as_ref()) {
508 (true, Some(value)) => validate(value),
509 (_, None) => Ok(()),
510 (false, Some(_)) => Err(Error::new("non-Good status requires omitting the value")),
511 };
512 result.map_err(|e| Error::new(format!("{e} (status 0x{:08X})", evidence.status)))
513}
514
515#[derive(Deserialize)]
518#[serde(rename_all = "camelCase", deny_unknown_fields)]
519struct WireObservation {
520 name: String,
521 node: NodeId,
522 #[serde(default, deserialize_with = "present")]
523 data_type: Option<Evidence<crate::identity::WireNode>>,
524 #[serde(default, deserialize_with = "present")]
525 value_rank: Option<Evidence<i32>>,
526 #[serde(default, deserialize_with = "present")]
527 engineering_units: Option<Evidence<Unit>>,
528}
529
530impl WireObservation {
531 fn into_observation(self, index: usize) -> Result<SignalObservation, Error> {
532 let data_type = self
533 .data_type
534 .map(|evidence| -> Result<_, Error> {
535 let value = evidence
536 .value
537 .map(NodeId::try_from)
538 .transpose()
539 .map_err(|err| {
540 Error::new(format!(
541 "signals[{index}].dataType: {err} (status 0x{:08X})",
542 evidence.status
543 ))
544 })?;
545 Ok(Evidence {
546 status: evidence.status,
547 value,
548 })
549 })
550 .transpose()?;
551 Ok(SignalObservation {
552 name: self.name,
553 node: self.node,
554 data_type,
555 value_rank: self.value_rank,
556 engineering_units: self.engineering_units,
557 })
558 }
559}
560
561pub fn parse_snapshot(bytes: &[u8]) -> Result<Snapshot, Error> {
563 let doc: Document<WireObservation> = parse(bytes)?;
564 let signals = doc
565 .signals
566 .into_iter()
567 .enumerate()
568 .map(|(index, row)| row.into_observation(index))
569 .collect::<Result<_, _>>()?;
570 validate_snapshot(Document {
571 schema_version: doc.schema_version,
572 device: doc.device,
573 application_uri: doc.application_uri,
574 principal: doc.principal,
575 signals,
576 })
577}
578
579fn validate_snapshot(doc: Document<SignalObservation>) -> Result<Snapshot, Error> {
580 for (i, s) in doc.signals.iter().enumerate() {
581 validate_label(&s.name).map_err(|e| e.at(&format!("signals[{i}].name")))?;
582 if let Some(evidence) = &s.data_type {
583 validate_observation(evidence, |_| Ok(()))
584 .map_err(|e| e.at(&format!("signals[{i}].dataType")))?;
585 }
586 if let Some(evidence) = &s.value_rank {
587 validate_observation(evidence, |n| validate_rank(*n))
588 .map_err(|e| e.at(&format!("signals[{i}].valueRank")))?;
589 }
590 if let Some(evidence) = &s.engineering_units {
591 validate_observation(evidence, |unit| unit.validate())
592 .map_err(|e| e.at(&format!("signals[{i}].engineeringUnits")))?;
593 }
594 }
595 unique(doc.signals.iter().map(|s| (s.name.as_str(), &s.node)))?;
596 Ok(Snapshot(doc))
597}