1use alloc::borrow::ToOwned;
34use alloc::format;
35use alloc::string::{String, ToString};
36use alloc::vec::Vec;
37
38use serde::Deserialize;
39
40use crate::message::{Message, MessageKind};
41use crate::types::common::{ReceptionStatus, ReceptionStatusValues};
42use crate::types::{Id, WireProfile};
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
46pub enum Strictness {
47 #[default]
49 Strict,
50 Lenient,
54}
55
56#[derive(Debug, Clone, PartialEq)]
58pub struct DecodeOptions {
59 pub strictness: Strictness,
61 pub profile: WireProfile,
63 pub max_bytes: usize,
65}
66
67impl Default for DecodeOptions {
68 fn default() -> Self {
69 Self {
70 strictness: Strictness::Strict,
71 profile: WireProfile::V1_0_0,
72 max_bytes: Self::DEFAULT_MAX_BYTES,
73 }
74 }
75}
76
77impl DecodeOptions {
78 pub const DEFAULT_MAX_BYTES: usize = 1024 * 1024;
81
82 #[must_use]
84 pub const fn profile(mut self, profile: WireProfile) -> Self {
85 self.profile = profile;
86 self
87 }
88
89 #[must_use]
91 pub const fn lenient(mut self) -> Self {
92 self.strictness = Strictness::Lenient;
93 self
94 }
95
96 #[must_use]
98 pub const fn max_bytes(mut self, bytes: usize) -> Self {
99 self.max_bytes = bytes;
100 self
101 }
102}
103
104#[derive(Debug, Clone, PartialEq, Eq, Default)]
109pub struct Peek {
110 pub message_type: Option<String>,
112 pub kind: Option<MessageKind>,
114 pub message_id: Option<Id>,
116 pub subject_message_id: Option<Id>,
118}
119
120impl Peek {
121 #[must_use]
126 pub fn subject(&self) -> Id {
127 self.message_id
128 .or(self.subject_message_id)
129 .unwrap_or(Id::NIL)
130 }
131}
132
133#[derive(Deserialize)]
134struct RawPeek<'a> {
135 #[serde(borrow, default)]
139 message_type: Option<alloc::borrow::Cow<'a, str>>,
140 #[serde(default)]
141 message_id: Option<String>,
142 #[serde(default)]
143 subject_message_id: Option<String>,
144}
145
146#[derive(Debug, Clone, PartialEq, thiserror::Error)]
148#[non_exhaustive]
149pub enum DecodeError {
150 #[error("message of {len} bytes exceeds the {max} byte limit")]
152 TooLarge {
153 len: usize,
155 max: usize,
157 },
158 #[error("not a JSON object: {reason}")]
160 NotJson {
161 reason: String,
163 },
164 #[error("no message_type")]
166 NoMessageType {
167 peek: Peek,
169 },
170 #[error("unknown message_type {message_type:?}")]
172 UnknownMessageType {
173 message_type: String,
175 peek: Peek,
177 },
178 #[error("{kind} does not exist in S2 JSON {profile}")]
180 NotInProfile {
181 kind: MessageKind,
183 profile: WireProfile,
185 peek: Peek,
187 },
188 #[error("{kind} does not match the schema: {reason}")]
191 Schema {
192 kind: MessageKind,
194 reason: String,
196 peek: Peek,
198 },
199 #[error("{kind} is not valid in S2 JSON {profile}: {reason}")]
201 ProfileMismatch {
202 kind: MessageKind,
204 profile: WireProfile,
206 reason: String,
208 peek: Peek,
210 },
211}
212
213impl DecodeError {
214 #[must_use]
216 pub fn peek(&self) -> Option<&Peek> {
217 match self {
218 DecodeError::TooLarge { .. } | DecodeError::NotJson { .. } => None,
219 DecodeError::NoMessageType { peek }
220 | DecodeError::UnknownMessageType { peek, .. }
221 | DecodeError::NotInProfile { peek, .. }
222 | DecodeError::Schema { peek, .. }
223 | DecodeError::ProfileMismatch { peek, .. } => Some(peek),
224 }
225 }
226
227 #[must_use]
233 pub fn status_value(&self) -> ReceptionStatusValues {
234 match self {
235 DecodeError::TooLarge { .. } | DecodeError::NotJson { .. } => {
237 ReceptionStatusValues::InvalidData
238 }
239 DecodeError::NoMessageType { peek } if peek.message_id.is_none() => {
240 ReceptionStatusValues::InvalidData
241 }
242 _ => ReceptionStatusValues::InvalidMessage,
244 }
245 }
246
247 #[must_use]
249 pub fn reception_status(&self) -> ReceptionStatus {
250 ReceptionStatus {
251 subject_message_id: self.peek().map_or(Id::NIL, Peek::subject),
252 status: self.status_value(),
253 diagnostic_label: Some(self.to_string()),
254 }
255 }
256}
257
258#[derive(Debug, Clone, PartialEq)]
260pub struct Decoded {
261 pub message: Message,
263 pub pruned: Vec<String>,
267}
268
269pub fn decode(text: &str) -> Result<Message, DecodeError> {
271 decode_with(text, &DecodeOptions::default()).map(|d| d.message)
272}
273
274pub fn decode_with(text: &str, options: &DecodeOptions) -> Result<Decoded, DecodeError> {
276 if text.len() > options.max_bytes {
277 return Err(DecodeError::TooLarge {
278 len: text.len(),
279 max: options.max_bytes,
280 });
281 }
282
283 let peek = peek(text)?;
284
285 let Some(message_type) = peek.message_type.clone() else {
286 return Err(DecodeError::NoMessageType { peek });
287 };
288 let Some(kind) = peek.kind else {
289 return Err(DecodeError::UnknownMessageType { message_type, peek });
290 };
291 if !kind.exists_in(options.profile) {
292 return Err(DecodeError::NotInProfile {
293 kind,
294 profile: options.profile,
295 peek,
296 });
297 }
298
299 let (message, pruned) = match options.strictness {
300 Strictness::Strict => {
301 let message =
302 serde_json::from_str::<Message>(text).map_err(|e| DecodeError::Schema {
303 kind,
304 reason: e.to_string(),
305 peek: peek.clone(),
306 })?;
307 (message, Vec::new())
308 }
309 Strictness::Lenient => {
310 let mut value = serde_json::from_str::<serde_json::Value>(text).map_err(|e| {
311 DecodeError::NotJson {
312 reason: e.to_string(),
313 }
314 })?;
315 let mut pruned = Vec::new();
316 crate::schema::prune_unknown(&mut value, kind.as_str(), &mut pruned);
317 let message =
318 serde_json::from_value::<Message>(value).map_err(|e| DecodeError::Schema {
319 kind,
320 reason: e.to_string(),
321 peek: peek.clone(),
322 })?;
323 (message, pruned)
324 }
325 };
326
327 check_profile(&message, options.profile, &peek)?;
328 Ok(Decoded { message, pruned })
329}
330
331pub fn peek(text: &str) -> Result<Peek, DecodeError> {
333 let raw: RawPeek = serde_json::from_str(text).map_err(|e| DecodeError::NotJson {
334 reason: e.to_string(),
335 })?;
336 Ok(Peek {
337 kind: raw.message_type.as_deref().and_then(MessageKind::from_wire),
338 message_type: raw.message_type.map(alloc::borrow::Cow::into_owned),
339 message_id: raw.message_id.as_deref().and_then(|s| Id::parse(s).ok()),
342 subject_message_id: raw
343 .subject_message_id
344 .as_deref()
345 .and_then(|s| Id::parse(s).ok()),
346 })
347}
348
349fn check_profile(message: &Message, profile: WireProfile, peek: &Peek) -> Result<(), DecodeError> {
351 if let Message::DdbcSystemDescription(d) = message {
352 let needs = profile.ddbc_system_description_carries_demand_rate();
353 match (needs, d.present_demand_rate.is_some()) {
354 (true, false) => {
355 return Err(DecodeError::ProfileMismatch {
356 kind: MessageKind::DdbcSystemDescription,
357 profile,
358 reason: "present_demand_rate is required in v0.0.2-beta".to_owned(),
359 peek: peek.clone(),
360 });
361 }
362 (false, true) => {
363 return Err(DecodeError::ProfileMismatch {
364 kind: MessageKind::DdbcSystemDescription,
365 profile,
366 reason: "present_demand_rate was removed in v1.0.0; \
367 send DDBC.PresentDemandStatus instead"
368 .to_owned(),
369 peek: peek.clone(),
370 });
371 }
372 _ => {}
373 }
374 }
375 Ok(())
376}
377
378#[must_use]
390pub fn encode(message: &Message) -> String {
391 serde_json::to_string(message).unwrap_or_else(|e| {
392 format!(r#"{{"message_type":"ReceptionStatus","subject_message_id":"00000000-0000-0000-0000-000000000000","status":"PERMANENT_ERROR","diagnostic_label":"s2-kit could not encode a message: {e}"}}"#)
395 })
396}
397
398#[must_use]
400pub fn encode_pretty(message: &Message) -> String {
401 serde_json::to_string_pretty(message).unwrap_or_else(|_| encode(message))
402}
403
404#[cfg(test)]
405mod tests {
406 use super::*;
407 use crate::types::{Timestamp, frbc};
408
409 const STORAGE_STATUS: &str =
410 r#"{"message_type":"FRBC.StorageStatus","message_id":"m1","present_fill_level":52.0}"#;
411
412 #[test]
413 fn a_good_message_decodes() {
414 let m = decode(STORAGE_STATUS).unwrap();
415 assert_eq!(m.kind(), MessageKind::FrbcStorageStatus);
416 assert_eq!(m.id(), Some(Id::new_const("m1")));
417 }
418
419 #[test]
420 fn encoding_is_canonical_and_round_trips() {
421 let m = decode(STORAGE_STATUS).unwrap();
422 assert_eq!(encode(&m), STORAGE_STATUS);
423 }
424
425 #[test]
426 fn broken_json_is_invalid_data_naming_nothing() {
427 let e = decode("{ not json").unwrap_err();
428 assert_eq!(e.status_value(), ReceptionStatusValues::InvalidData);
429 assert_eq!(e.reception_status().subject_message_id, Id::NIL);
430 }
431
432 #[test]
433 fn a_schema_violation_is_invalid_message_naming_the_right_id() {
434 let e = decode(r#"{"message_type":"FRBC.StorageStatus","message_id":"m1"}"#).unwrap_err();
436 assert_eq!(e.status_value(), ReceptionStatusValues::InvalidMessage);
437 let status = e.reception_status();
438 assert_eq!(status.subject_message_id, Id::new_const("m1"));
439 assert!(
440 status
441 .diagnostic_label
442 .unwrap()
443 .contains("present_fill_level")
444 );
445 }
446
447 #[test]
448 fn an_unknown_property_is_refused_in_strict_mode_and_pruned_in_lenient() {
449 let text = r#"{"message_type":"FRBC.StorageStatus","message_id":"m1","present_fill_level":52.0,"vendor":1}"#;
450 assert!(decode(text).is_err());
451
452 let decoded = decode_with(text, &DecodeOptions::default().lenient()).unwrap();
453 assert_eq!(decoded.pruned, alloc::vec!["/vendor".to_string()]);
454 assert_eq!(decoded.message.kind(), MessageKind::FrbcStorageStatus);
455 }
456
457 #[test]
458 fn no_message_type_is_reported_with_whatever_id_was_there() {
459 let e = decode(r#"{"message_id":"m1","present_fill_level":1.0}"#).unwrap_err();
460 assert_eq!(e.status_value(), ReceptionStatusValues::InvalidMessage);
463 assert_eq!(e.reception_status().subject_message_id, Id::new_const("m1"));
464
465 let e = decode(r#"{"present_fill_level":1.0}"#).unwrap_err();
467 assert_eq!(e.status_value(), ReceptionStatusValues::InvalidData);
468 assert_eq!(e.reception_status().subject_message_id, Id::NIL);
469 }
470
471 #[test]
472 fn a_message_type_written_with_json_escapes_still_decodes() {
473 let escaped = "{\"message_type\":\"FRBC\\u002EStorageStatus\",\
478 \"message_id\":\"m1\",\"present_fill_level\":52.0}";
479 let peeked = peek(escaped).unwrap();
480 assert_eq!(peeked.kind, Some(MessageKind::FrbcStorageStatus));
481 assert_eq!(peeked.message_type.as_deref(), Some("FRBC.StorageStatus"));
482 assert_eq!(peeked.message_id, Some(Id::new_const("m1")));
483
484 let message = decode(escaped).unwrap();
485 assert_eq!(message.kind(), MessageKind::FrbcStorageStatus);
486 assert_eq!(encode(&message), STORAGE_STATUS);
488 }
489
490 #[test]
491 fn an_unparseable_message_id_is_treated_as_no_id() {
492 let e = decode(r#"{"message_type":"FRBC.StorageStatus","message_id":"a b"}"#).unwrap_err();
494 assert_eq!(e.reception_status().subject_message_id, Id::NIL);
495 }
496
497 #[test]
498 fn an_unknown_message_type_is_named_in_the_diagnostic() {
499 let e = decode(r#"{"message_type":"FRBC.Surprise","message_id":"m1"}"#).unwrap_err();
500 assert!(matches!(e, DecodeError::UnknownMessageType { .. }));
501 assert!(e.to_string().contains("FRBC.Surprise"));
502 assert_eq!(e.reception_status().subject_message_id, Id::new_const("m1"));
503 }
504
505 #[test]
506 fn a_message_larger_than_the_cap_is_never_parsed() {
507 let big = alloc::format!(
508 r#"{{"message_type":"FRBC.StorageStatus","message_id":"m1","present_fill_level":{}}}"#,
509 "1".repeat(2000)
510 );
511 let options = DecodeOptions::default().max_bytes(512);
512 let e = decode_with(&big, &options).unwrap_err();
513 assert!(matches!(e, DecodeError::TooLarge { .. }));
514 assert_eq!(e.status_value(), ReceptionStatusValues::InvalidData);
515 }
516
517 #[test]
518 fn the_ddbc_difference_between_the_two_profiles_is_enforced() {
519 let beta = r#"{"message_type":"DDBC.SystemDescription","message_id":"m1",
520 "valid_from":"2019-08-24T14:15:22Z","actuators":[],
521 "present_demand_rate":{"start_of_range":0.0,"end_of_range":1.0},
522 "provides_average_demand_rate_forecast":false}"#;
523 let one_zero = r#"{"message_type":"DDBC.SystemDescription","message_id":"m1",
524 "valid_from":"2019-08-24T14:15:22Z","actuators":[],
525 "provides_average_demand_rate_forecast":false}"#;
526
527 assert!(
529 decode_with(
530 one_zero,
531 &DecodeOptions::default().profile(WireProfile::V1_0_0)
532 )
533 .is_ok()
534 );
535 assert!(
536 decode_with(
537 beta,
538 &DecodeOptions::default().profile(WireProfile::V0_0_2Beta)
539 )
540 .is_ok()
541 );
542 let e =
544 decode_with(beta, &DecodeOptions::default().profile(WireProfile::V1_0_0)).unwrap_err();
545 assert!(matches!(e, DecodeError::ProfileMismatch { .. }), "{e}");
546 let e = decode_with(
547 one_zero,
548 &DecodeOptions::default().profile(WireProfile::V0_0_2Beta),
549 )
550 .unwrap_err();
551 assert!(matches!(e, DecodeError::ProfileMismatch { .. }), "{e}");
552 }
553
554 #[test]
555 fn the_message_new_in_one_zero_is_refused_in_the_beta_profile() {
556 let text = r#"{"message_type":"DDBC.PresentDemandStatus","message_id":"m1",
557 "present_demand_rate":{"start_of_range":0.0,"end_of_range":1.0}}"#;
558 assert!(decode(text).is_ok());
559 let e = decode_with(
560 text,
561 &DecodeOptions::default().profile(WireProfile::V0_0_2Beta),
562 )
563 .unwrap_err();
564 assert!(matches!(e, DecodeError::NotInProfile { .. }), "{e}");
565 }
566
567 #[test]
568 fn a_reception_status_is_never_answered_but_still_peeks() {
569 let text = r#"{"message_type":"ReceptionStatus","subject_message_id":"m1","status":"OK"}"#;
570 let p = peek(text).unwrap();
571 assert_eq!(p.subject_message_id, Some(Id::new_const("m1")));
572 assert_eq!(p.message_id, None);
573 assert_eq!(p.subject(), Id::new_const("m1"));
574 let m = decode(text).unwrap();
575 assert_eq!(m.kind(), MessageKind::ReceptionStatus);
576 }
577
578 #[test]
579 fn pretty_encoding_still_parses() {
580 let m = Message::from(frbc::StorageStatus {
581 message_id: Id::new_const("m1"),
582 present_fill_level: 52.0,
583 });
584 let pretty = encode_pretty(&m);
585 assert!(pretty.contains('\n'));
586 assert_eq!(decode(&pretty).unwrap(), m);
587 }
588
589 #[test]
590 fn timestamps_survive_a_round_trip_unchanged() {
591 let text = r#"{"message_type":"PowerMeasurement","message_id":"m1","measurement_timestamp":"2019-08-24T14:15:22Z","values":[{"commodity_quantity":"ELECTRIC.POWER.L1","value":510.6}]}"#;
592 let m = decode(text).unwrap();
593 assert_eq!(encode(&m), text);
594 let _ = Timestamp::UNIX_EPOCH;
595 }
596}