use alloc::borrow::ToOwned;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use serde::Deserialize;
use crate::message::{Message, MessageKind};
use crate::types::common::{ReceptionStatus, ReceptionStatusValues};
use crate::types::{Id, WireProfile};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Strictness {
#[default]
Strict,
Lenient,
}
#[derive(Debug, Clone, PartialEq)]
pub struct DecodeOptions {
pub strictness: Strictness,
pub profile: WireProfile,
pub max_bytes: usize,
}
impl Default for DecodeOptions {
fn default() -> Self {
Self {
strictness: Strictness::Strict,
profile: WireProfile::V1_0_0,
max_bytes: Self::DEFAULT_MAX_BYTES,
}
}
}
impl DecodeOptions {
pub const DEFAULT_MAX_BYTES: usize = 1024 * 1024;
#[must_use]
pub const fn profile(mut self, profile: WireProfile) -> Self {
self.profile = profile;
self
}
#[must_use]
pub const fn lenient(mut self) -> Self {
self.strictness = Strictness::Lenient;
self
}
#[must_use]
pub const fn max_bytes(mut self, bytes: usize) -> Self {
self.max_bytes = bytes;
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Peek {
pub message_type: Option<String>,
pub kind: Option<MessageKind>,
pub message_id: Option<Id>,
pub subject_message_id: Option<Id>,
}
impl Peek {
#[must_use]
pub fn subject(&self) -> Id {
self.message_id
.or(self.subject_message_id)
.unwrap_or(Id::NIL)
}
}
#[derive(Deserialize)]
struct RawPeek<'a> {
#[serde(borrow, default)]
message_type: Option<alloc::borrow::Cow<'a, str>>,
#[serde(default)]
message_id: Option<String>,
#[serde(default)]
subject_message_id: Option<String>,
}
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum DecodeError {
#[error("message of {len} bytes exceeds the {max} byte limit")]
TooLarge {
len: usize,
max: usize,
},
#[error("not a JSON object: {reason}")]
NotJson {
reason: String,
},
#[error("no message_type")]
NoMessageType {
peek: Peek,
},
#[error("unknown message_type {message_type:?}")]
UnknownMessageType {
message_type: String,
peek: Peek,
},
#[error("{kind} does not exist in S2 JSON {profile}")]
NotInProfile {
kind: MessageKind,
profile: WireProfile,
peek: Peek,
},
#[error("{kind} does not match the schema: {reason}")]
Schema {
kind: MessageKind,
reason: String,
peek: Peek,
},
#[error("{kind} is not valid in S2 JSON {profile}: {reason}")]
ProfileMismatch {
kind: MessageKind,
profile: WireProfile,
reason: String,
peek: Peek,
},
}
impl DecodeError {
#[must_use]
pub fn peek(&self) -> Option<&Peek> {
match self {
DecodeError::TooLarge { .. } | DecodeError::NotJson { .. } => None,
DecodeError::NoMessageType { peek }
| DecodeError::UnknownMessageType { peek, .. }
| DecodeError::NotInProfile { peek, .. }
| DecodeError::Schema { peek, .. }
| DecodeError::ProfileMismatch { peek, .. } => Some(peek),
}
}
#[must_use]
pub fn status_value(&self) -> ReceptionStatusValues {
match self {
DecodeError::TooLarge { .. } | DecodeError::NotJson { .. } => {
ReceptionStatusValues::InvalidData
}
DecodeError::NoMessageType { peek } if peek.message_id.is_none() => {
ReceptionStatusValues::InvalidData
}
_ => ReceptionStatusValues::InvalidMessage,
}
}
#[must_use]
pub fn reception_status(&self) -> ReceptionStatus {
ReceptionStatus {
subject_message_id: self.peek().map_or(Id::NIL, Peek::subject),
status: self.status_value(),
diagnostic_label: Some(self.to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Decoded {
pub message: Message,
pub pruned: Vec<String>,
}
pub fn decode(text: &str) -> Result<Message, DecodeError> {
decode_with(text, &DecodeOptions::default()).map(|d| d.message)
}
pub fn decode_with(text: &str, options: &DecodeOptions) -> Result<Decoded, DecodeError> {
if text.len() > options.max_bytes {
return Err(DecodeError::TooLarge {
len: text.len(),
max: options.max_bytes,
});
}
let peek = peek(text)?;
let Some(message_type) = peek.message_type.clone() else {
return Err(DecodeError::NoMessageType { peek });
};
let Some(kind) = peek.kind else {
return Err(DecodeError::UnknownMessageType { message_type, peek });
};
if !kind.exists_in(options.profile) {
return Err(DecodeError::NotInProfile {
kind,
profile: options.profile,
peek,
});
}
let (message, pruned) = match options.strictness {
Strictness::Strict => {
let message =
serde_json::from_str::<Message>(text).map_err(|e| DecodeError::Schema {
kind,
reason: e.to_string(),
peek: peek.clone(),
})?;
(message, Vec::new())
}
Strictness::Lenient => {
let mut value = serde_json::from_str::<serde_json::Value>(text).map_err(|e| {
DecodeError::NotJson {
reason: e.to_string(),
}
})?;
let mut pruned = Vec::new();
crate::schema::prune_unknown(&mut value, kind.as_str(), options.profile, &mut pruned);
let message =
serde_json::from_value::<Message>(value).map_err(|e| DecodeError::Schema {
kind,
reason: e.to_string(),
peek: peek.clone(),
})?;
(message, pruned)
}
};
check_profile(&message, options.profile, &peek)?;
Ok(Decoded { message, pruned })
}
pub fn peek(text: &str) -> Result<Peek, DecodeError> {
let raw: RawPeek = serde_json::from_str(text).map_err(|e| DecodeError::NotJson {
reason: e.to_string(),
})?;
Ok(Peek {
kind: raw.message_type.as_deref().and_then(MessageKind::from_wire),
message_type: raw.message_type.map(alloc::borrow::Cow::into_owned),
message_id: raw.message_id.as_deref().and_then(|s| Id::parse(s).ok()),
subject_message_id: raw
.subject_message_id
.as_deref()
.and_then(|s| Id::parse(s).ok()),
})
}
fn check_profile(message: &Message, profile: WireProfile, peek: &Peek) -> Result<(), DecodeError> {
if let Message::DdbcSystemDescription(d) = message {
let needs = profile.ddbc_system_description_carries_demand_rate();
match (needs, d.present_demand_rate.is_some()) {
(true, false) => {
return Err(DecodeError::ProfileMismatch {
kind: MessageKind::DdbcSystemDescription,
profile,
reason: "present_demand_rate is required in v0.0.2-beta".to_owned(),
peek: peek.clone(),
});
}
(false, true) => {
return Err(DecodeError::ProfileMismatch {
kind: MessageKind::DdbcSystemDescription,
profile,
reason: "present_demand_rate was removed in v1.0.0; \
send DDBC.PresentDemandStatus instead"
.to_owned(),
peek: peek.clone(),
});
}
_ => {}
}
}
Ok(())
}
#[must_use]
pub fn encode(message: &Message) -> String {
serde_json::to_string(message).unwrap_or_else(|e| {
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}"}}"#)
})
}
#[must_use]
pub fn encode_pretty(message: &Message) -> String {
serde_json::to_string_pretty(message).unwrap_or_else(|_| encode(message))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::{Timestamp, frbc};
const STORAGE_STATUS: &str =
r#"{"message_type":"FRBC.StorageStatus","message_id":"m1","present_fill_level":52.0}"#;
#[test]
fn a_good_message_decodes() {
let m = decode(STORAGE_STATUS).unwrap();
assert_eq!(m.kind(), MessageKind::FrbcStorageStatus);
assert_eq!(m.id(), Some(Id::new_const("m1")));
}
#[test]
fn encoding_is_canonical_and_round_trips() {
let m = decode(STORAGE_STATUS).unwrap();
assert_eq!(encode(&m), STORAGE_STATUS);
}
#[test]
fn broken_json_is_invalid_data_naming_nothing() {
let e = decode("{ not json").unwrap_err();
assert_eq!(e.status_value(), ReceptionStatusValues::InvalidData);
assert_eq!(e.reception_status().subject_message_id, Id::NIL);
}
#[test]
fn a_schema_violation_is_invalid_message_naming_the_right_id() {
let e = decode(r#"{"message_type":"FRBC.StorageStatus","message_id":"m1"}"#).unwrap_err();
assert_eq!(e.status_value(), ReceptionStatusValues::InvalidMessage);
let status = e.reception_status();
assert_eq!(status.subject_message_id, Id::new_const("m1"));
assert!(
status
.diagnostic_label
.unwrap()
.contains("present_fill_level")
);
}
#[test]
fn an_unknown_property_is_refused_in_strict_mode_and_pruned_in_lenient() {
let text = r#"{"message_type":"FRBC.StorageStatus","message_id":"m1","present_fill_level":52.0,"vendor":1}"#;
assert!(decode(text).is_err());
let decoded = decode_with(text, &DecodeOptions::default().lenient()).unwrap();
assert_eq!(decoded.pruned, alloc::vec!["/vendor".to_string()]);
assert_eq!(decoded.message.kind(), MessageKind::FrbcStorageStatus);
}
#[test]
fn no_message_type_is_reported_with_whatever_id_was_there() {
let e = decode(r#"{"message_id":"m1","present_fill_level":1.0}"#).unwrap_err();
assert_eq!(e.status_value(), ReceptionStatusValues::InvalidMessage);
assert_eq!(e.reception_status().subject_message_id, Id::new_const("m1"));
let e = decode(r#"{"present_fill_level":1.0}"#).unwrap_err();
assert_eq!(e.status_value(), ReceptionStatusValues::InvalidData);
assert_eq!(e.reception_status().subject_message_id, Id::NIL);
}
#[test]
fn a_message_type_written_with_json_escapes_still_decodes() {
let escaped = "{\"message_type\":\"FRBC\\u002EStorageStatus\",\
\"message_id\":\"m1\",\"present_fill_level\":52.0}";
let peeked = peek(escaped).unwrap();
assert_eq!(peeked.kind, Some(MessageKind::FrbcStorageStatus));
assert_eq!(peeked.message_type.as_deref(), Some("FRBC.StorageStatus"));
assert_eq!(peeked.message_id, Some(Id::new_const("m1")));
let message = decode(escaped).unwrap();
assert_eq!(message.kind(), MessageKind::FrbcStorageStatus);
assert_eq!(encode(&message), STORAGE_STATUS);
}
#[test]
fn an_unparseable_message_id_is_treated_as_no_id() {
let e = decode(r#"{"message_type":"FRBC.StorageStatus","message_id":"a b"}"#).unwrap_err();
assert_eq!(e.reception_status().subject_message_id, Id::NIL);
}
#[test]
fn an_unknown_message_type_is_named_in_the_diagnostic() {
let e = decode(r#"{"message_type":"FRBC.Surprise","message_id":"m1"}"#).unwrap_err();
assert!(matches!(e, DecodeError::UnknownMessageType { .. }));
assert!(e.to_string().contains("FRBC.Surprise"));
assert_eq!(e.reception_status().subject_message_id, Id::new_const("m1"));
}
#[test]
fn a_message_larger_than_the_cap_is_never_parsed() {
let big = alloc::format!(
r#"{{"message_type":"FRBC.StorageStatus","message_id":"m1","present_fill_level":{}}}"#,
"1".repeat(2000)
);
let options = DecodeOptions::default().max_bytes(512);
let e = decode_with(&big, &options).unwrap_err();
assert!(matches!(e, DecodeError::TooLarge { .. }));
assert_eq!(e.status_value(), ReceptionStatusValues::InvalidData);
}
#[test]
fn the_ddbc_difference_between_the_two_profiles_is_enforced() {
let beta = r#"{"message_type":"DDBC.SystemDescription","message_id":"m1",
"valid_from":"2019-08-24T14:15:22Z","actuators":[],
"present_demand_rate":{"start_of_range":0.0,"end_of_range":1.0},
"provides_average_demand_rate_forecast":false}"#;
let one_zero = r#"{"message_type":"DDBC.SystemDescription","message_id":"m1",
"valid_from":"2019-08-24T14:15:22Z","actuators":[],
"provides_average_demand_rate_forecast":false}"#;
assert!(
decode_with(
one_zero,
&DecodeOptions::default().profile(WireProfile::V1_0_0)
)
.is_ok()
);
assert!(
decode_with(
beta,
&DecodeOptions::default().profile(WireProfile::V0_0_2Beta)
)
.is_ok()
);
let e =
decode_with(beta, &DecodeOptions::default().profile(WireProfile::V1_0_0)).unwrap_err();
assert!(matches!(e, DecodeError::ProfileMismatch { .. }), "{e}");
let e = decode_with(
one_zero,
&DecodeOptions::default().profile(WireProfile::V0_0_2Beta),
)
.unwrap_err();
assert!(matches!(e, DecodeError::ProfileMismatch { .. }), "{e}");
}
#[test]
fn a_lenient_reader_on_the_beta_profile_still_reads_the_beta_shape() {
let beta = r#"{"message_type":"DDBC.SystemDescription","message_id":"m1",
"valid_from":"2019-08-24T14:15:22Z","actuators":[],
"present_demand_rate":{"start_of_range":0.0,"end_of_range":1.0},
"provides_average_demand_rate_forecast":false,"vendor":"x"}"#;
let options = DecodeOptions::default()
.profile(WireProfile::V0_0_2Beta)
.lenient();
let decoded = decode_with(beta, &options).expect("a conforming beta message");
assert_eq!(decoded.pruned, alloc::vec!["/vendor".to_string()]);
let Message::DdbcSystemDescription(d) = decoded.message else {
panic!("wrong kind")
};
assert!(d.present_demand_rate.is_some());
}
#[test]
fn the_message_new_in_one_zero_is_refused_in_the_beta_profile() {
let text = r#"{"message_type":"DDBC.PresentDemandStatus","message_id":"m1",
"present_demand_rate":{"start_of_range":0.0,"end_of_range":1.0}}"#;
assert!(decode(text).is_ok());
let e = decode_with(
text,
&DecodeOptions::default().profile(WireProfile::V0_0_2Beta),
)
.unwrap_err();
assert!(matches!(e, DecodeError::NotInProfile { .. }), "{e}");
}
#[test]
fn a_reception_status_is_never_answered_but_still_peeks() {
let text = r#"{"message_type":"ReceptionStatus","subject_message_id":"m1","status":"OK"}"#;
let p = peek(text).unwrap();
assert_eq!(p.subject_message_id, Some(Id::new_const("m1")));
assert_eq!(p.message_id, None);
assert_eq!(p.subject(), Id::new_const("m1"));
let m = decode(text).unwrap();
assert_eq!(m.kind(), MessageKind::ReceptionStatus);
}
#[test]
fn pretty_encoding_still_parses() {
let m = Message::from(frbc::StorageStatus {
message_id: Id::new_const("m1"),
present_fill_level: 52.0,
});
let pretty = encode_pretty(&m);
assert!(pretty.contains('\n'));
assert_eq!(decode(&pretty).unwrap(), m);
}
#[test]
fn timestamps_survive_a_round_trip_unchanged() {
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}]}"#;
let m = decode(text).unwrap();
assert_eq!(encode(&m), text);
let _ = Timestamp::UNIX_EPOCH;
}
}