Skip to main content

s2_kit/
codec.rs

1//! Turning bytes into [`Message`]s, and back.
2//!
3//! # Two phases, so that every failure can still be answered
4//!
5//! S2 requires a `ReceptionStatus` for every message received, and the status has to
6//! name the message it is about. That is awkward for a message that failed to parse: the
7//! `subject_message_id` has to come from somewhere.
8//!
9//! So decoding happens in two phases. First a [`Peek`] pulls out `message_type`,
10//! `message_id` and `subject_message_id`, ignoring everything else and tolerating almost
11//! any malformation. Then the typed decode runs, refusing unknown properties. Whatever
12//! goes wrong, the error carries what the peek learned, and
13//! [`DecodeError::reception_status`] turns it into exactly the status the standard
14//! prescribes — `INVALID_DATA` for "not understood", `INVALID_MESSAGE` for "not
15//! according to schema" — naming the right message, or the nil identifier when there was
16//! nothing to name.
17//!
18//! ```
19//! use s2_kit::codec::{decode, DecodeError};
20//!
21//! let err = decode("{ not json").unwrap_err();
22//! let status = err.reception_status();
23//! assert_eq!(status.status, s2_kit::types::common::ReceptionStatusValues::InvalidData);
24//! assert_eq!(status.subject_message_id, s2_kit::types::Id::NIL);
25//! ```
26//!
27//! # Bounded before it is parsed
28//!
29//! `maxItems` does not bound a message meaningfully: a schema-legal
30//! `PPBC.PowerProfileDefinition` may hold a thousand containers of 288 sequences of 288
31//! elements. [`DecodeOptions::max_bytes`] is checked *before* the parser runs.
32
33use 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/// How much malformation a decoder tolerates.
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
46pub enum Strictness {
47    /// Refuse anything the schema does not define. What an endpoint should do.
48    #[default]
49    Strict,
50    /// Remove properties the schema does not define, report them, and carry on. What a
51    /// proxy or an analyzer should do: forwarding a peer's message with an unknown field
52    /// stripped is more useful than refusing to look at it.
53    Lenient,
54}
55
56/// Everything that shapes a decode.
57#[derive(Debug, Clone, PartialEq)]
58pub struct DecodeOptions {
59    /// Strict or lenient.
60    pub strictness: Strictness,
61    /// The wire profile to decode against.
62    pub profile: WireProfile,
63    /// The largest message that will be parsed at all.
64    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    /// One mebibyte. Large enough for any plausible S2 message, small enough that a peer
79    /// cannot exhaust memory with a single legal one.
80    pub const DEFAULT_MAX_BYTES: usize = 1024 * 1024;
81
82    /// Decode against a particular wire profile.
83    #[must_use]
84    pub const fn profile(mut self, profile: WireProfile) -> Self {
85        self.profile = profile;
86        self
87    }
88
89    /// Strip and report unknown properties instead of refusing the message.
90    #[must_use]
91    pub const fn lenient(mut self) -> Self {
92        self.strictness = Strictness::Lenient;
93        self
94    }
95
96    /// Change the size cap.
97    #[must_use]
98    pub const fn max_bytes(mut self, bytes: usize) -> Self {
99        self.max_bytes = bytes;
100        self
101    }
102}
103
104/// What a decode learned before trying to build a typed message.
105///
106/// Everything here is optional because everything here can be missing from a message
107/// that a peer should not have sent but did.
108#[derive(Debug, Clone, PartialEq, Eq, Default)]
109pub struct Peek {
110    /// The raw `message_type` string, if there was one.
111    pub message_type: Option<String>,
112    /// The message kind, if this crate knows that type.
113    pub kind: Option<MessageKind>,
114    /// The `message_id`, if there was one and it was a valid identifier.
115    pub message_id: Option<Id>,
116    /// The `subject_message_id`, for a `ReceptionStatus`.
117    pub subject_message_id: Option<Id>,
118}
119
120impl Peek {
121    /// The identifier a `ReceptionStatus` about this message should carry.
122    ///
123    /// The nil identifier when the message had none — which is what the ecosystem does,
124    /// and what `[s2-json #21]` is open about.
125    #[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    // `Cow`, not `&str`: a peer may write `"FRBC\u002EStorageStatus"`, and a borrowed
136    // `&str` cannot hold a string that needed unescaping — serde refuses it, turning a
137    // good message into `INVALID_DATA` naming nothing. Unescaped messages still borrow.
138    #[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/// Why a message could not be decoded.
147#[derive(Debug, Clone, PartialEq, thiserror::Error)]
148#[non_exhaustive]
149pub enum DecodeError {
150    /// Larger than [`DecodeOptions::max_bytes`], and so never parsed.
151    #[error("message of {len} bytes exceeds the {max} byte limit")]
152    TooLarge {
153        /// How big it was.
154        len: usize,
155        /// How big it was allowed to be.
156        max: usize,
157    },
158    /// Not JSON at all, or not a JSON object.
159    #[error("not a JSON object: {reason}")]
160    NotJson {
161        /// What the parser said.
162        reason: String,
163    },
164    /// No `message_type` property, so there is no way to know what it is.
165    #[error("no message_type")]
166    NoMessageType {
167        /// What the peek found, for the reception status.
168        peek: Peek,
169    },
170    /// A `message_type` this crate does not know.
171    #[error("unknown message_type {message_type:?}")]
172    UnknownMessageType {
173        /// The type that was given.
174        message_type: String,
175        /// What the peek found.
176        peek: Peek,
177    },
178    /// A message type that does not exist in the negotiated wire profile.
179    #[error("{kind} does not exist in S2 JSON {profile}")]
180    NotInProfile {
181        /// The message.
182        kind: MessageKind,
183        /// The profile that was being decoded against.
184        profile: WireProfile,
185        /// What the peek found.
186        peek: Peek,
187    },
188    /// The message does not match the schema: a missing field, a wrong type, an unknown
189    /// property in strict mode, or a value outside what the type can hold.
190    #[error("{kind} does not match the schema: {reason}")]
191    Schema {
192        /// Which message it claimed to be.
193        kind: MessageKind,
194        /// What serde said, which names the offending field.
195        reason: String,
196        /// What the peek found.
197        peek: Peek,
198    },
199    /// A field the negotiated profile requires is absent, or one it forbids is present.
200    #[error("{kind} is not valid in S2 JSON {profile}: {reason}")]
201    ProfileMismatch {
202        /// Which message.
203        kind: MessageKind,
204        /// The profile.
205        profile: WireProfile,
206        /// What is wrong.
207        reason: String,
208        /// What the peek found.
209        peek: Peek,
210    },
211}
212
213impl DecodeError {
214    /// What the peek learned, whatever went wrong afterwards.
215    #[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    /// The reception status the standard prescribes for this failure.
228    ///
229    /// `S2J schemas/ReceptionStatusValues` draws the line precisely: `INVALID_DATA` is
230    /// "Message not understood (e.g. not valid JSON, no message_id found)" and
231    /// `INVALID_MESSAGE` is "Message was not according to schema".
232    #[must_use]
233    pub fn status_value(&self) -> ReceptionStatusValues {
234        match self {
235            // Not understood at all.
236            DecodeError::TooLarge { .. } | DecodeError::NotJson { .. } => {
237                ReceptionStatusValues::InvalidData
238            }
239            DecodeError::NoMessageType { peek } if peek.message_id.is_none() => {
240                ReceptionStatusValues::InvalidData
241            }
242            // Understood enough to answer, but not according to schema.
243            _ => ReceptionStatusValues::InvalidMessage,
244        }
245    }
246
247    /// The complete `ReceptionStatus` to send back.
248    #[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/// What a successful decode produced.
259#[derive(Debug, Clone, PartialEq)]
260pub struct Decoded {
261    /// The message.
262    pub message: Message,
263    /// Properties the schema does not define, removed in [`Strictness::Lenient`].
264    ///
265    /// Always empty in strict mode, where an unknown property is an error instead.
266    pub pruned: Vec<String>,
267}
268
269/// Decode one S2 message, strictly, against S2 JSON v1.0.0.
270pub fn decode(text: &str) -> Result<Message, DecodeError> {
271    decode_with(text, &DecodeOptions::default()).map(|d| d.message)
272}
273
274/// Decode one S2 message.
275pub 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            // Against the *negotiated* profile: the property table is v1.0.0's, and
317            // `DDBC.SystemDescription.present_demand_rate` is required in `0.0.2-beta`
318            // and absent from v1.0.0. Pruning against the wrong one removes a required
319            // field and then refuses the message for missing it.
320            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
335/// Read the three fields a reception status needs, tolerating everything else.
336pub 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        // An identifier that does not match the pattern is no identifier: a reception
344        // status carrying it would be unparseable in its turn.
345        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
353/// The one place the two wire profiles differ.
354fn 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/// Encode one S2 message.
383///
384/// The output is canonical: properties in schema order, absent optionals omitted rather
385/// than written as `null`, timestamps in UTC with the fewest fractional digits that lose
386/// nothing. Re-encoding a message a proxy did not change is a no-op.
387///
388/// # Panics
389///
390/// Never, for any `Message` this crate can construct: the model contains no map with
391/// non-string keys and no type whose `Serialize` can fail. A non-finite `f64` would be
392/// the one way to reach a failure, and the builders and validator refuse those.
393#[must_use]
394pub fn encode(message: &Message) -> String {
395    serde_json::to_string(message).unwrap_or_else(|e| {
396        // Unreachable for a well-formed Message; returning a diagnostic beats panicking
397        // in a driver that is trying to answer a peer.
398        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/// Encode one S2 message with indentation, for logs and fixtures.
403#[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        // Right type, missing a required field.
439        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        // There was an id, so the peer can be told which message failed; the status is
465        // INVALID_MESSAGE rather than INVALID_DATA because we could name it.
466        assert_eq!(e.status_value(), ReceptionStatusValues::InvalidMessage);
467        assert_eq!(e.reception_status().subject_message_id, Id::new_const("m1"));
468
469        // With nothing to name, it is INVALID_DATA and the nil identifier.
470        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        // `\u002E` is a dot. JSON says these two documents carry the same string, and a
478        // peer is entitled to emit either — some JSON writers escape aggressively. A
479        // peek that borrowed the slice would answer "expected a borrowed string" and
480        // turn a perfectly good status into INVALID_DATA naming nothing.
481        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        // And it re-encodes canonically, which is the unescaped spelling.
491        assert_eq!(encode(&message), STORAGE_STATUS);
492    }
493
494    #[test]
495    fn an_unparseable_message_id_is_treated_as_no_id() {
496        // `a b` cannot be an S2 identifier, so it cannot be echoed in a reception status.
497        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        // Each is right in its own profile...
532        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        // ...and wrong in the other.
547        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        // The bug this pins: lenient pruning ran against the v1.0.0 property table, so
561        // it stripped `present_demand_rate` — which `0.0.2-beta` *requires* — and then
562        // `check_profile` refused the message for the field the pruner had just removed.
563        // An `Analyzer` on the beta profile could therefore not read a single conforming
564        // `DDBC.SystemDescription`, which is precisely the transcript it exists for.
565        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}