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(), options.profile, &mut pruned);
321 let message =
322 serde_json::from_value::<Message>(value).map_err(|e| DecodeError::Schema {
323 kind,
324 reason: e.to_string(),
325 peek: peek.clone(),
326 })?;
327 (message, pruned)
328 }
329 };
330
331 check_profile(&message, options.profile, &peek)?;
332 Ok(Decoded { message, pruned })
333}
334
335pub fn peek(text: &str) -> Result<Peek, DecodeError> {
337 let raw: RawPeek = serde_json::from_str(text).map_err(|e| DecodeError::NotJson {
338 reason: e.to_string(),
339 })?;
340 Ok(Peek {
341 kind: raw.message_type.as_deref().and_then(MessageKind::from_wire),
342 message_type: raw.message_type.map(alloc::borrow::Cow::into_owned),
343 message_id: raw.message_id.as_deref().and_then(|s| Id::parse(s).ok()),
346 subject_message_id: raw
347 .subject_message_id
348 .as_deref()
349 .and_then(|s| Id::parse(s).ok()),
350 })
351}
352
353fn check_profile(message: &Message, profile: WireProfile, peek: &Peek) -> Result<(), DecodeError> {
355 if let Message::DdbcSystemDescription(d) = message {
356 let needs = profile.ddbc_system_description_carries_demand_rate();
357 match (needs, d.present_demand_rate.is_some()) {
358 (true, false) => {
359 return Err(DecodeError::ProfileMismatch {
360 kind: MessageKind::DdbcSystemDescription,
361 profile,
362 reason: "present_demand_rate is required in v0.0.2-beta".to_owned(),
363 peek: peek.clone(),
364 });
365 }
366 (false, true) => {
367 return Err(DecodeError::ProfileMismatch {
368 kind: MessageKind::DdbcSystemDescription,
369 profile,
370 reason: "present_demand_rate was removed in v1.0.0; \
371 send DDBC.PresentDemandStatus instead"
372 .to_owned(),
373 peek: peek.clone(),
374 });
375 }
376 _ => {}
377 }
378 }
379 Ok(())
380}
381
382#[must_use]
394pub fn encode(message: &Message) -> String {
395 serde_json::to_string(message).unwrap_or_else(|e| {
396 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}"}}"#)
399 })
400}
401
402#[must_use]
404pub fn encode_pretty(message: &Message) -> String {
405 serde_json::to_string_pretty(message).unwrap_or_else(|_| encode(message))
406}
407
408#[cfg(test)]
409mod tests {
410 use super::*;
411 use crate::types::{Timestamp, frbc};
412
413 const STORAGE_STATUS: &str =
414 r#"{"message_type":"FRBC.StorageStatus","message_id":"m1","present_fill_level":52.0}"#;
415
416 #[test]
417 fn a_good_message_decodes() {
418 let m = decode(STORAGE_STATUS).unwrap();
419 assert_eq!(m.kind(), MessageKind::FrbcStorageStatus);
420 assert_eq!(m.id(), Some(Id::new_const("m1")));
421 }
422
423 #[test]
424 fn encoding_is_canonical_and_round_trips() {
425 let m = decode(STORAGE_STATUS).unwrap();
426 assert_eq!(encode(&m), STORAGE_STATUS);
427 }
428
429 #[test]
430 fn broken_json_is_invalid_data_naming_nothing() {
431 let e = decode("{ not json").unwrap_err();
432 assert_eq!(e.status_value(), ReceptionStatusValues::InvalidData);
433 assert_eq!(e.reception_status().subject_message_id, Id::NIL);
434 }
435
436 #[test]
437 fn a_schema_violation_is_invalid_message_naming_the_right_id() {
438 let e = decode(r#"{"message_type":"FRBC.StorageStatus","message_id":"m1"}"#).unwrap_err();
440 assert_eq!(e.status_value(), ReceptionStatusValues::InvalidMessage);
441 let status = e.reception_status();
442 assert_eq!(status.subject_message_id, Id::new_const("m1"));
443 assert!(
444 status
445 .diagnostic_label
446 .unwrap()
447 .contains("present_fill_level")
448 );
449 }
450
451 #[test]
452 fn an_unknown_property_is_refused_in_strict_mode_and_pruned_in_lenient() {
453 let text = r#"{"message_type":"FRBC.StorageStatus","message_id":"m1","present_fill_level":52.0,"vendor":1}"#;
454 assert!(decode(text).is_err());
455
456 let decoded = decode_with(text, &DecodeOptions::default().lenient()).unwrap();
457 assert_eq!(decoded.pruned, alloc::vec!["/vendor".to_string()]);
458 assert_eq!(decoded.message.kind(), MessageKind::FrbcStorageStatus);
459 }
460
461 #[test]
462 fn no_message_type_is_reported_with_whatever_id_was_there() {
463 let e = decode(r#"{"message_id":"m1","present_fill_level":1.0}"#).unwrap_err();
464 assert_eq!(e.status_value(), ReceptionStatusValues::InvalidMessage);
467 assert_eq!(e.reception_status().subject_message_id, Id::new_const("m1"));
468
469 let e = decode(r#"{"present_fill_level":1.0}"#).unwrap_err();
471 assert_eq!(e.status_value(), ReceptionStatusValues::InvalidData);
472 assert_eq!(e.reception_status().subject_message_id, Id::NIL);
473 }
474
475 #[test]
476 fn a_message_type_written_with_json_escapes_still_decodes() {
477 let escaped = "{\"message_type\":\"FRBC\\u002EStorageStatus\",\
482 \"message_id\":\"m1\",\"present_fill_level\":52.0}";
483 let peeked = peek(escaped).unwrap();
484 assert_eq!(peeked.kind, Some(MessageKind::FrbcStorageStatus));
485 assert_eq!(peeked.message_type.as_deref(), Some("FRBC.StorageStatus"));
486 assert_eq!(peeked.message_id, Some(Id::new_const("m1")));
487
488 let message = decode(escaped).unwrap();
489 assert_eq!(message.kind(), MessageKind::FrbcStorageStatus);
490 assert_eq!(encode(&message), STORAGE_STATUS);
492 }
493
494 #[test]
495 fn an_unparseable_message_id_is_treated_as_no_id() {
496 let e = decode(r#"{"message_type":"FRBC.StorageStatus","message_id":"a b"}"#).unwrap_err();
498 assert_eq!(e.reception_status().subject_message_id, Id::NIL);
499 }
500
501 #[test]
502 fn an_unknown_message_type_is_named_in_the_diagnostic() {
503 let e = decode(r#"{"message_type":"FRBC.Surprise","message_id":"m1"}"#).unwrap_err();
504 assert!(matches!(e, DecodeError::UnknownMessageType { .. }));
505 assert!(e.to_string().contains("FRBC.Surprise"));
506 assert_eq!(e.reception_status().subject_message_id, Id::new_const("m1"));
507 }
508
509 #[test]
510 fn a_message_larger_than_the_cap_is_never_parsed() {
511 let big = alloc::format!(
512 r#"{{"message_type":"FRBC.StorageStatus","message_id":"m1","present_fill_level":{}}}"#,
513 "1".repeat(2000)
514 );
515 let options = DecodeOptions::default().max_bytes(512);
516 let e = decode_with(&big, &options).unwrap_err();
517 assert!(matches!(e, DecodeError::TooLarge { .. }));
518 assert_eq!(e.status_value(), ReceptionStatusValues::InvalidData);
519 }
520
521 #[test]
522 fn the_ddbc_difference_between_the_two_profiles_is_enforced() {
523 let beta = r#"{"message_type":"DDBC.SystemDescription","message_id":"m1",
524 "valid_from":"2019-08-24T14:15:22Z","actuators":[],
525 "present_demand_rate":{"start_of_range":0.0,"end_of_range":1.0},
526 "provides_average_demand_rate_forecast":false}"#;
527 let one_zero = r#"{"message_type":"DDBC.SystemDescription","message_id":"m1",
528 "valid_from":"2019-08-24T14:15:22Z","actuators":[],
529 "provides_average_demand_rate_forecast":false}"#;
530
531 assert!(
533 decode_with(
534 one_zero,
535 &DecodeOptions::default().profile(WireProfile::V1_0_0)
536 )
537 .is_ok()
538 );
539 assert!(
540 decode_with(
541 beta,
542 &DecodeOptions::default().profile(WireProfile::V0_0_2Beta)
543 )
544 .is_ok()
545 );
546 let e =
548 decode_with(beta, &DecodeOptions::default().profile(WireProfile::V1_0_0)).unwrap_err();
549 assert!(matches!(e, DecodeError::ProfileMismatch { .. }), "{e}");
550 let e = decode_with(
551 one_zero,
552 &DecodeOptions::default().profile(WireProfile::V0_0_2Beta),
553 )
554 .unwrap_err();
555 assert!(matches!(e, DecodeError::ProfileMismatch { .. }), "{e}");
556 }
557
558 #[test]
559 fn a_lenient_reader_on_the_beta_profile_still_reads_the_beta_shape() {
560 let beta = r#"{"message_type":"DDBC.SystemDescription","message_id":"m1",
566 "valid_from":"2019-08-24T14:15:22Z","actuators":[],
567 "present_demand_rate":{"start_of_range":0.0,"end_of_range":1.0},
568 "provides_average_demand_rate_forecast":false,"vendor":"x"}"#;
569 let options = DecodeOptions::default()
570 .profile(WireProfile::V0_0_2Beta)
571 .lenient();
572 let decoded = decode_with(beta, &options).expect("a conforming beta message");
573 assert_eq!(decoded.pruned, alloc::vec!["/vendor".to_string()]);
574 let Message::DdbcSystemDescription(d) = decoded.message else {
575 panic!("wrong kind")
576 };
577 assert!(d.present_demand_rate.is_some());
578 }
579
580 #[test]
581 fn the_message_new_in_one_zero_is_refused_in_the_beta_profile() {
582 let text = r#"{"message_type":"DDBC.PresentDemandStatus","message_id":"m1",
583 "present_demand_rate":{"start_of_range":0.0,"end_of_range":1.0}}"#;
584 assert!(decode(text).is_ok());
585 let e = decode_with(
586 text,
587 &DecodeOptions::default().profile(WireProfile::V0_0_2Beta),
588 )
589 .unwrap_err();
590 assert!(matches!(e, DecodeError::NotInProfile { .. }), "{e}");
591 }
592
593 #[test]
594 fn a_reception_status_is_never_answered_but_still_peeks() {
595 let text = r#"{"message_type":"ReceptionStatus","subject_message_id":"m1","status":"OK"}"#;
596 let p = peek(text).unwrap();
597 assert_eq!(p.subject_message_id, Some(Id::new_const("m1")));
598 assert_eq!(p.message_id, None);
599 assert_eq!(p.subject(), Id::new_const("m1"));
600 let m = decode(text).unwrap();
601 assert_eq!(m.kind(), MessageKind::ReceptionStatus);
602 }
603
604 #[test]
605 fn pretty_encoding_still_parses() {
606 let m = Message::from(frbc::StorageStatus {
607 message_id: Id::new_const("m1"),
608 present_fill_level: 52.0,
609 });
610 let pretty = encode_pretty(&m);
611 assert!(pretty.contains('\n'));
612 assert_eq!(decode(&pretty).unwrap(), m);
613 }
614
615 #[test]
616 fn timestamps_survive_a_round_trip_unchanged() {
617 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}]}"#;
618 let m = decode(text).unwrap();
619 assert_eq!(encode(&m), text);
620 let _ = Timestamp::UNIX_EPOCH;
621 }
622}