1use std::collections::BTreeSet;
2
3use super::{
4 Client, MAX_NODES_PER_READ, NAMESPACE_ARRAY, ReadError, ReadMetadata, ReadSession,
5 SERVER_ARRAY, Sample, definition::decode_data_type, sample::Quality, ua,
6};
7use crate::{
8 NodeId,
9 commissioning::{
10 Contract, Error, Evidence, SignalObservation, SignalRequirement, Snapshot,
11 SnapshotCollector,
12 },
13};
14
15#[derive(Debug, thiserror::Error)]
17#[non_exhaustive]
18pub enum SnapshotReadError {
19 #[error("snapshot contract principal differs from the authenticated session")]
21 Principal,
22 #[error("snapshot contract ApplicationUri differs from the pinned server")]
24 ServerIdentity,
25 #[error("snapshot signals[{index}] selects a reserved session bootstrap node")]
27 BootstrapNode {
28 index: usize,
30 },
31 #[error("could not prepare the snapshot session: {0}")]
33 Session(#[source] ReadError),
34 #[error("snapshot signals[{index}]: {source}")]
36 Signal {
37 index: usize,
39 #[source]
41 source: ReadError,
42 },
43 #[error("snapshot signals[{index}]: compact snapshot and newline exceed 4 MiB")]
45 OutputLimit {
46 index: usize,
48 },
49 #[error("invalid snapshot evidence: {0}")]
51 Evidence(#[source] Error),
52}
53
54fn evidence<T>(sample: Sample<T>) -> Evidence<T> {
55 Evidence {
56 status: sample.status,
57 value: sample.value,
58 }
59}
60
61fn protected_signals<'a>(
62 contract: &'a Contract,
63 server_uri: &str,
64 principal: &str,
65) -> Result<BTreeSet<&'a NodeId>, SnapshotReadError> {
66 if contract.principal() != principal {
67 return Err(SnapshotReadError::Principal);
68 }
69 if contract.application_uri() != server_uri {
70 return Err(SnapshotReadError::ServerIdentity);
71 }
72 contract.validate_capture_nodes()?;
73 Ok(contract.signals().iter().map(|s| &s.node).collect())
74}
75
76impl Contract {
77 pub fn validate_capture_nodes(&self) -> Result<(), SnapshotReadError> {
80 for (index, signal) in self.signals().iter().enumerate() {
81 let node = &signal.node;
82 if node.namespace() == "http://opcfoundation.org/UA/"
83 && node
84 .identifier()
85 .strip_prefix("i=")
86 .and_then(|id| id.parse::<u32>().ok())
87 .is_some_and(|id| {
88 matches!(id, SERVER_ARRAY | NAMESPACE_ARRAY | MAX_NODES_PER_READ)
89 })
90 {
91 return Err(SnapshotReadError::BootstrapNode { index });
92 }
93 }
94 Ok(())
95 }
96}
97
98impl Client {
99 pub async fn read_snapshot(&self, contract: &Contract) -> Result<Snapshot, SnapshotReadError> {
116 let protected = protected_signals(contract, &self.server_uri, &self.principal)?;
117 let mut output = SnapshotCollector::new(contract).map_err(SnapshotReadError::Evidence)?;
118 let (mut session, metadata) = self
119 .read_session()
120 .await
121 .map_err(SnapshotReadError::Session)?;
122 for (index, signal) in contract.signals().iter().enumerate() {
123 let row = self
124 .snapshot_signal(&mut session, metadata, signal, &protected)
125 .await
126 .map_err(|source| SnapshotReadError::Signal { index, source })?;
127 output
128 .push(row)
129 .map_err(|_| SnapshotReadError::OutputLimit { index })?;
130 }
131 self.check_channel().map_err(SnapshotReadError::Session)?;
132 drop(session);
133 output.finish(contract).map_err(SnapshotReadError::Evidence)
134 }
135
136 async fn snapshot_signal(
137 &self,
138 session: &mut ReadSession,
139 metadata: &ReadMetadata,
140 signal: &SignalRequirement,
141 protected: &BTreeSet<&NodeId>,
142 ) -> Result<SignalObservation, ReadError> {
143 let mut row = SignalObservation::new(signal.name.clone(), signal.node.clone());
144 if !metadata
145 .namespaces
146 .by_uri
147 .contains_key(signal.node.namespace())
148 {
149 return Ok(row);
150 }
151 let quality = Quality::GoodSeverity;
152 let data_type = if signal.value_rank.is_some() {
153 let definition = self
154 .definition_locked(session, metadata, &signal.node, quality)
155 .await?;
156 row.value_rank = Some(evidence(definition.value_rank?));
157 definition.data_type?
158 } else {
159 let wire = metadata.namespaces.wire_node(&signal.node, 0)?;
160 let raw = self
161 .one_attribute(session, wire, ua::AttributeId::DataType)
162 .await?;
163 decode_data_type(&metadata.namespaces, &raw, quality)?
164 };
165 row.data_type = Some(evidence(data_type));
166 if signal.engineering_units.is_some() {
167 let unit = self
168 .units_locked(
169 session,
170 &metadata.namespaces,
171 &signal.node,
172 quality,
173 |property| !protected.contains(property),
174 )
175 .await?;
176 row.engineering_units = Some(evidence(unit.sample));
177 }
178 Ok(row)
179 }
180}
181
182#[cfg(test)]
183mod tests {
184 use super::*;
185 use crate::commissioning::{MAX_DOCUMENT_BYTES, Unit, parse_contract};
186
187 #[test]
188 fn reject_bootstrap_aliases_in_any_position_before_preparing_session() {
189 let base = parse_contract(include_bytes!("../../fixtures/meter/contract.json")).unwrap();
190 for id in ["i=002254", "i=002255", "i=11705"] {
191 let mut a = base.signals()[0].clone();
192 a.node = NodeId::new("urn:vendor", id).unwrap();
193 let mut b = a.clone();
194 b.name = "bootstrap".into();
195 b.node = NodeId::new("http://opcfoundation.org/UA/", id).unwrap();
196 let new = |rows| Contract::new("site", "urn:server", "anonymous", rows).unwrap();
197 let c = new(vec![a.clone()]);
198 assert!(
199 protected_signals(&c, "urn:server", "anonymous")
200 .unwrap()
201 .contains(&a.node)
202 );
203 let c = new(vec![a, b]);
204 assert!(matches!(
205 protected_signals(&c, "urn:server", "anonymous"),
206 Err(SnapshotReadError::BootstrapNode { index: 1 })
207 ));
208 assert!(matches!(
209 protected_signals(&c, "urn:other", "anonymous"),
210 Err(SnapshotReadError::ServerIdentity)
211 ));
212 }
213 }
214
215 #[test]
216 fn rows_just_fit_or_fail_including_escaped_text_separator_and_newline() {
217 let fixture = parse_contract(include_bytes!("../../fixtures/meter/contract.json")).unwrap();
218 let mut other = fixture.signals()[0].clone();
219 other.name = "other".into();
220 other.node = NodeId::new("urn:site", "s=Other").unwrap();
221 let c = Contract::new(
222 "site",
223 "urn:server",
224 "anonymous",
225 vec![fixture.signals()[0].clone(), other],
226 )
227 .unwrap();
228 let row = |i: usize, suffix: usize| {
229 let required = &c.signals()[i];
230 let mut row = SignalObservation::new(required.name.clone(), required.node.clone());
231 row.data_type = Some(Evidence {
232 status: 0,
233 value: Some(required.data_type.clone()),
234 });
235 row.value_rank = Some(Evidence {
236 status: 0,
237 value: Some(-1),
238 });
239 row.engineering_units = Some(Evidence {
240 status: 0,
241 value: Some(Unit {
242 namespace_uri: format!("urn:unit:\"温{}", "x".repeat(suffix)),
243 unit_id: 1,
244 }),
245 });
246 row
247 };
248 let baseline = Snapshot::new(
249 c.device(),
250 c.application_uri(),
251 c.principal(),
252 vec![row(0, 0), row(1, 0)],
253 )
254 .unwrap();
255 let room = MAX_DOCUMENT_BYTES - 1 - serde_json::to_vec(&baseline).unwrap().len();
256 let mut output = SnapshotCollector::new(&c).unwrap();
257 output.push(row(0, 0)).unwrap();
258 output.push(row(1, room)).unwrap();
259 let exact = output.finish(&c).unwrap();
260 assert_eq!(
261 serde_json::to_vec(&exact).unwrap().len() + 1,
262 MAX_DOCUMENT_BYTES
263 );
264 let mut output = SnapshotCollector::new(&c).unwrap();
265 output.push(row(0, 0)).unwrap();
266 assert!(output.push(row(1, room + 1)).is_err());
267 }
268}