1mod decimal;
9mod object;
10mod trust_report;
11mod types;
12mod validation;
13
14pub use trust_report::{TrustReport, TrustSummary};
15pub use types::*;
16use validation::{enforce_collection_budget, known_source, require, validate_payload};
17
18use object::Node;
19use semver::Version;
20use serde::{
21 de::{self, DeserializeOwned, DeserializeSeed, MapAccess, SeqAccess, Visitor},
22 Deserialize, Deserializer, Serialize,
23};
24use serde_json::value::RawValue;
25use std::{collections::BTreeMap, fmt};
26
27pub const MAX_MESSAGE_BYTES: usize = 256 * 1024;
29
30#[derive(Clone, Copy, Debug)]
32pub struct DecodeLimits {
33 pub bytes: usize,
34 pub depth: usize,
35 pub entries_per_container: usize,
36}
37impl Default for DecodeLimits {
38 fn default() -> Self {
39 Self {
40 bytes: MAX_MESSAGE_BYTES,
41 depth: 32,
42 entries_per_container: 256,
43 }
44 }
45}
46
47#[derive(thiserror::Error, PartialEq, Eq)]
48pub enum WireError {
49 #[error("message exceeds the configured byte limit")]
50 TooLarge,
51 #[error("invalid JSON, duplicate key, or container limit exceeded")]
52 InvalidJson,
53 #[error("invalid CLS.EEDI field: {0}")]
54 Field(&'static str),
55 #[error("CLS.EEDI protocol violation: {0}")]
56 Protocol(&'static str),
57 #[error("incompatible CLS.EEDI major version")]
58 UnsupportedMajor { id: String, kind: Kind },
59}
60impl fmt::Debug for WireError {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 fmt::Display::fmt(self, f)
64 }
65}
66
67#[derive(Clone, PartialEq, Eq)]
69pub struct ReplyHint {
70 pub id: String,
71 pub kind: Kind,
72 pub error_number: u64,
73}
74impl fmt::Debug for ReplyHint {
75 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76 f.debug_struct("ReplyHint")
77 .field("kind", &self.kind)
78 .field("error_number", &self.error_number)
79 .finish_non_exhaustive()
80 }
81}
82#[derive(Debug, thiserror::Error)]
83#[error("{error}")]
84pub struct DecodeFailure {
85 pub error: WireError,
86 pub reply: Option<ReplyHint>,
87}
88impl From<WireError> for DecodeFailure {
89 fn from(error: WireError) -> Self {
90 Self { error, reply: None }
91 }
92}
93impl WireError {
94 fn ack_code(&self) -> u64 {
95 match self {
96 Self::UnsupportedMajor { .. } | Self::Protocol(_) => 2,
97 _ => 1,
98 }
99 }
100}
101
102#[derive(Clone, PartialEq, Eq)]
103pub struct Message {
104 pub id: String,
105 pub source: String,
106 pub relation: Option<String>,
107 pub protocol: Version,
108 pub payload: Payload,
109}
110impl fmt::Debug for Message {
111 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112 f.debug_struct("Message")
113 .field("kind", &self.payload.kind())
114 .finish_non_exhaustive()
115 }
116}
117
118#[derive(Deserialize)]
119struct Envelope {
120 #[serde(rename = "type")]
121 kind: Kind,
122 id: String,
123 #[serde(
124 default,
125 skip_serializing_if = "Option::is_none",
126 deserialize_with = "present"
127 )]
128 relation: Option<String>,
129}
130
131impl Message {
132 pub fn new(
134 id: impl Into<String>,
135 source: impl Into<String>,
136 payload: impl Into<Payload>,
137 ) -> Self {
138 Self {
139 id: id.into(),
140 source: source.into(),
141 protocol: Version::new(1, 2, 0),
142 relation: None,
143 payload: payload.into(),
144 }
145 }
146 #[must_use]
147 pub fn related_to(mut self, id: impl Into<String>) -> Self {
148 self.relation = Some(id.into());
149 self
150 }
151 pub fn decode(bytes: &[u8]) -> Result<Self, WireError> {
154 Self::decode_with(bytes, DecodeLimits::default())
155 }
156 pub fn decode_with(bytes: &[u8], limits: DecodeLimits) -> Result<Self, WireError> {
157 Self::decode_bounded(bytes, limits).map_err(|failure| failure.error)
158 }
159 pub fn decode_for_reply(bytes: &[u8]) -> Result<Self, DecodeFailure> {
165 Self::decode_bounded(bytes, DecodeLimits::default())
166 }
167 fn decode_bounded(bytes: &[u8], limits: DecodeLimits) -> Result<Self, DecodeFailure> {
168 if bytes.len() > limits.bytes {
169 return Err(WireError::TooLarge.into());
170 }
171 let mut deserializer = serde_json::Deserializer::from_slice(bytes);
172 let root = deserializer
173 .deserialize_map(CheckedJson {
174 limits: &limits,
175 depth: 0,
176 })
177 .map_err(|_| WireError::InvalidJson)?;
178 deserializer.end().map_err(|_| WireError::InvalidJson)?;
179 let Node::Object(mut fields) = root else {
180 return Err(WireError::Field("envelope").into());
181 };
182 let data = fields.remove("data").unwrap_or(Node::Null);
183 let source = fields.remove("source");
184 let specversion = fields.remove("specversion");
185 let mut envelope: Envelope = typed(Node::Object(fields), "envelope")?;
186 Self::from_envelope(&mut envelope, source, specversion, data).map_err(|error| {
187 let kind = envelope.kind;
188 let eligible = match (&error, kind) {
189 (_, Kind::Ack) => false,
190 (WireError::UnsupportedMajor { .. }, _) => true,
192 (_, Kind::Read) => true,
193 (_, Kind::Control) => envelope.relation.is_none(),
194 _ => false,
195 };
196 let reply = eligible.then(|| ReplyHint {
197 id: envelope.id,
198 kind,
199 error_number: error.ack_code(),
200 });
201 DecodeFailure { error, reply }
202 })
203 }
204 fn from_envelope(
205 envelope: &mut Envelope,
206 source: Option<Node>,
207 specversion: Option<Node>,
208 data: Node,
209 ) -> Result<Self, WireError> {
210 let Some(Node::String(source)) = source else {
211 return Err(WireError::Field("source"));
212 };
213 match specversion.as_ref().and_then(Node::as_str) {
214 Some("1.0") => {}
215 Some(_) => return Err(WireError::Protocol("specversion")),
216 None => return Err(WireError::Field("specversion")),
217 }
218 let Node::Object(mut data) = data else {
219 return Err(WireError::Field("data"));
220 };
221 let protocol = parse_version(data.remove("protocol"))?;
222 if protocol.major != 1 {
223 return Err(WireError::UnsupportedMajor {
224 id: envelope.id.clone(),
225 kind: envelope.kind,
226 });
227 }
228 if envelope.kind == Kind::State {
231 if let Some(Node::Array(meters)) = data.get_mut("measurements") {
232 meters.retain(|m| match m {
233 Node::Object(m) => m
234 .get("source")
235 .and_then(Node::as_str)
236 .is_none_or(known_source),
237 _ => true,
238 });
239 }
240 }
241 if matches!(envelope.kind, Kind::Control | Kind::State) {
242 reject_misplaced_directions(&data)?;
243 }
244 let data = Node::Object(data);
245 let mut payload = match envelope.kind {
246 Kind::Control => Payload::Control(typed(data, "control")?),
247 Kind::Ack => Payload::Ack(typed(data, "ack")?),
248 Kind::State => {
249 let mut state: State = typed(data, "state")?;
250 if let Some(items) = &mut state.supported_eebus_use_cases {
251 items.retain(|s| matches!(s.as_str(), "lpc" | "lpp" | "mgcp" | "mpc"));
252 }
253 Payload::State(state)
254 }
255 Kind::Read => Payload::Read(typed(data, "read")?),
256 Kind::LocalDeviceStatus => {
257 Payload::LocalDeviceStatus(typed(data, "localDeviceStatus")?)
258 }
259 };
260 let notify = match &mut payload {
261 Payload::Control(c) => c.notify.as_mut(),
262 Payload::State(s) => s.notify.as_mut(),
263 _ => None,
264 };
265 if let Some(sources) = notify.and_then(|n| n.source.as_mut()) {
266 sources.retain(|s| known_source(s));
267 }
268 validate_payload(&payload, envelope.relation.is_some())?;
269 Ok(Self {
270 id: std::mem::take(&mut envelope.id),
271 source,
272 relation: envelope.relation.take(),
273 protocol,
274 payload,
275 })
276 }
277
278 pub fn encode(&self) -> Result<Vec<u8>, WireError> {
280 enforce_collection_budget(&self.payload, DecodeLimits::default().entries_per_container)?;
281 self.validate()?;
282 #[derive(Serialize)]
283 struct OutboundData<'a> {
284 protocol: String,
285 #[serde(flatten)]
286 body: &'a Payload,
287 }
288 #[derive(Serialize)]
289 struct Outbound<'a> {
290 #[serde(rename = "type")]
291 kind: Kind,
292 id: &'a str,
293 source: &'a str,
294 specversion: &'static str,
295 #[serde(skip_serializing_if = "Option::is_none")]
296 relation: Option<&'a str>,
297 data: OutboundData<'a>,
298 }
299 let envelope = Outbound {
300 kind: self.payload.kind(),
301 id: &self.id,
302 source: &self.source,
303 specversion: "1.0",
304 relation: self.relation.as_deref(),
305 data: OutboundData {
306 protocol: self.protocol.to_string(),
307 body: &self.payload,
308 },
309 };
310 let mut output = BoundedOutput(Vec::new());
311 serde_json::to_writer(&mut output, &envelope).map_err(|e| {
312 if e.is_io() {
313 WireError::TooLarge
314 } else {
315 WireError::Field("data")
316 }
317 })?;
318 Ok(output.0)
319 }
320 pub fn validate(&self) -> Result<(), WireError> {
321 if self.protocol.major != 1 {
322 return Err(WireError::UnsupportedMajor {
323 id: self.id.clone(),
324 kind: self.payload.kind(),
325 });
326 }
327 require(self.protocol.to_string().len() <= 256, "protocol")?;
328 validate_payload(&self.payload, self.relation.is_some())
329 }
330}
331
332struct BoundedOutput(Vec<u8>);
333impl std::io::Write for BoundedOutput {
334 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
335 if buf.len() > MAX_MESSAGE_BYTES - self.0.len() {
336 return Err(std::io::Error::other("message limit"));
337 }
338 self.0.extend_from_slice(buf);
339 Ok(buf.len())
340 }
341 fn flush(&mut self) -> std::io::Result<()> {
342 Ok(())
343 }
344}
345
346fn typed<T: DeserializeOwned>(node: Node, field: &'static str) -> Result<T, WireError> {
347 T::deserialize(node).map_err(|_| WireError::Field(field))
348}
349fn reject_misplaced_directions(data: &BTreeMap<String, Node>) -> Result<(), WireError> {
352 for (property, error) in [
353 ("limits", "limits direction outside power.active"),
354 ("failsafes", "failsafes direction outside power.active"),
355 ] {
356 let Some(Node::Object(outer)) = data.get(property) else {
357 continue;
358 };
359 let power = match outer.get("power") {
360 Some(Node::Object(power)) => Some(power),
361 _ => None,
362 };
363 let misplaced = [Some(outer), power]
364 .into_iter()
365 .flatten()
366 .any(|level| level.contains_key("consumption") || level.contains_key("production"));
367 require(!misplaced, error)?;
368 }
369 Ok(())
370}
371fn parse_version(value: Option<Node>) -> Result<Version, WireError> {
372 value
373 .as_ref()
374 .and_then(Node::as_str)
375 .filter(|s| s.len() <= 256)
376 .and_then(|s| Version::parse(s).ok())
377 .ok_or(WireError::Field("protocol"))
378}
379#[derive(Clone, Copy)]
382struct CheckedJson<'a> {
383 limits: &'a DecodeLimits,
384 depth: usize,
385}
386impl<'de> DeserializeSeed<'de> for CheckedJson<'_> {
387 type Value = Node;
388 fn deserialize<D: Deserializer<'de>>(self, d: D) -> Result<Node, D::Error> {
389 if self.depth > self.limits.depth.min(96) {
390 return Err(de::Error::custom("nesting limit"));
391 }
392 let raw = <&RawValue>::deserialize(d)?;
394 let token = raw.get();
395 let mut parser = serde_json::Deserializer::from_str(token);
396 match token.as_bytes()[0] {
397 b'{' => parser.deserialize_map(self),
398 b'[' => parser.deserialize_seq(self),
399 b'"' => String::deserialize(&mut parser).map(Node::String),
400 b't' => Ok(Node::Bool(true)),
401 b'f' => Ok(Node::Bool(false)),
402 b'n' => Ok(Node::Null),
403 _ => Ok(decimal::number(token)),
404 }
405 .map_err(de::Error::custom)
406 }
407}
408impl<'de> Visitor<'de> for CheckedJson<'_> {
409 type Value = Node;
410 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
411 f.write_str("a bounded JSON container")
412 }
413
414 fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Node, A::Error> {
415 let child = Self {
416 depth: self.depth + 1,
417 ..self
418 };
419 let mut items = Vec::new();
420 while items.len() < self.limits.entries_per_container {
421 match seq.next_element_seed(child)? {
422 Some(item) => items.push(item),
423 None => return Ok(Node::Array(items)),
424 }
425 }
426 if seq.next_element::<de::IgnoredAny>()?.is_some() {
427 return Err(de::Error::custom("array limit"));
428 }
429 Ok(Node::Array(items))
430 }
431 fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Node, A::Error> {
432 let child = Self {
433 depth: self.depth + 1,
434 ..self
435 };
436 let mut items = BTreeMap::new();
437 while let Some(key) = map.next_key::<String>()? {
438 if items.len() == self.limits.entries_per_container || items.contains_key(&key) {
439 return Err(de::Error::custom("duplicate key or object limit"));
440 }
441 items.insert(key, map.next_value_seed(child)?);
442 }
443 Ok(Node::Object(items))
444 }
445}