Skip to main content

qlog/
lib.rs

1// Copyright (C) 2019, Cloudflare, Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright notice,
9//       this list of conditions and the following disclaimer.
10//
11//     * Redistributions in binary form must reproduce the above copyright
12//       notice, this list of conditions and the following disclaimer in the
13//       documentation and/or other materials provided with the distribution.
14//
15// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
16// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
19// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26
27//! The qlog crate is an implementation of the qlog [main logging schema],
28//! [QUIC event definitions], and [HTTP/3 and QPACK event definitions].
29//! The crate provides a qlog data model that can be used for traces with
30//! events. It supports serialization and deserialization but defers logging IO
31//! choices to applications.
32//!
33//! Serialization operates in either a [buffered mode] or a [streaming mode].
34//!
35//! The crate uses Serde for conversion between Rust and JSON.
36//!
37//! [main logging schema]: https://datatracker.ietf.org/doc/html/draft-ietf-quic-qlog-main-schema
38//! [QUIC event definitions]:
39//! https://datatracker.ietf.org/doc/html/draft-ietf-quic-qlog-quic-events.html
40//! [HTTP/3 and QPACK event definitions]:
41//! https://datatracker.ietf.org/doc/html/draft-ietf-quic-qlog-h3-events.html
42//! [buffered mode]: #buffered-traces-with-standard-json
43//! [streaming mode]: #streaming-traces-with-json-seq
44//!
45//! Overview
46//! ---------------
47//! qlog is a hierarchical logging format, with a rough structure of:
48//!
49//! * Log
50//!   * Trace(s)
51//!     * Event(s)
52//!
53//! In practice, a single QUIC connection maps to a single Trace file with one
54//! or more Events. Applications can decide whether to combine Traces from
55//! different connections into the same Log.
56//!
57//! ## Buffered Traces with standard JSON
58//!
59//! A [`Trace`] is a single JSON object. It contains metadata such as the
60//! [`VantagePoint`] of capture and the [`Configuration`], and protocol event
61//! data in the [`Event`] array.
62//!
63//! JSON Traces allow applications to appends events to them before eventually
64//! being serialized as a complete JSON object.
65//!
66//! ### Creating a Trace
67//!
68//! ```
69//! let mut trace = qlog::Trace::new(
70//! #    Some("Example qlog trace".to_string()),
71//! #    Some("Example qlog trace description".to_string()),
72//! #    None,
73//! #    Some(qlog::VantagePoint {
74//! #        name: Some("Example client".to_string()),
75//! #        ty: qlog::VantagePointType::Client,
76//! #        flow: None,
77//! #    }),
78//! #    vec![qlog::events::QUIC_URI.to_string(), qlog::events::HTTP3_URI.to_string()],
79//! # );
80//! ```
81//!
82//! ### Adding events to a Trace
83//!
84//! Qlog [`Event`] objects are added to [`qlog::Trace.events`].
85//!
86//! The following example demonstrates how to log a qlog QUIC `packet_sent`
87//! event containing a single Crypto frame. It constructs the necessary elements
88//! of the [`Event`], then appends it to the trace with [`push_event()`].
89//!
90//! ```
91//! # let mut trace = qlog::Trace::new(
92//! #    Some("Example qlog trace".to_string()),
93//! #    Some("Example qlog trace description".to_string()),
94//! #    None,
95//! #    Some(qlog::VantagePoint {
96//! #        name: Some("Example client".to_string()),
97//! #        ty: qlog::VantagePointType::Client,
98//! #        flow: None,
99//! #    }),
100//! #    vec![qlog::events::QUIC_URI.to_string(), qlog::events::HTTP3_URI.to_string()],
101//! # );
102//!
103//! let scid = [0x7e, 0x37, 0xe4, 0xdc, 0xc6, 0x68, 0x2d, 0xa8];
104//! let dcid = [0x36, 0xce, 0x10, 0x4e, 0xee, 0x50, 0x10, 0x1c];
105//!
106//! let pkt_hdr = qlog::events::quic::PacketHeader::new(
107//!     qlog::events::quic::PacketType::Initial,
108//!     Some(0),          // packet_number
109//!     None,             // token
110//!     None,             // length
111//!     Some(0x00000001), // version
112//!     Some(&scid),
113//!     Some(&dcid),
114//! );
115//!
116//! let frames = vec![qlog::events::quic::QuicFrame::Crypto {
117//!     offset: 0,
118//!     raw: None,
119//! }];
120//!
121//! let raw = qlog::events::RawInfo {
122//!     length: Some(1251),
123//!     payload_length: Some(1224),
124//!     data: None,
125//! };
126//!
127//! let event_data =
128//!     qlog::events::EventData::QuicPacketSent(qlog::events::quic::PacketSent {
129//!         header: pkt_hdr,
130//!         frames: Some(frames.into()),
131//!         stateless_reset_token: None,
132//!         supported_versions: None,
133//!         raw: Some(raw),
134//!         datagram_id: None,
135//!         is_mtu_probe_packet: None,
136//!         send_at_time: None,
137//!         trigger: None,
138//!     });
139//!
140//! trace.push_event(qlog::events::Event::with_time(0.0, event_data));
141//! ```
142//!
143//! ### Serializing
144//!
145//! The qlog crate has only been tested with `serde_json`, however
146//! other serializer targets might work.
147//!
148//! For example, serializing the trace created above:
149//!
150//! ```
151//! # let mut trace = qlog::Trace::new(
152//! #    Some("Example qlog trace".to_string()),
153//! #    Some("Example qlog trace description".to_string()),
154//! #    None,
155//! #    Some(qlog::VantagePoint {
156//! #        name: Some("Example client".to_string()),
157//! #        ty: qlog::VantagePointType::Client,
158//! #        flow: None,
159//! #    }),
160//! #    vec![qlog::events::QUIC_URI.to_string(), qlog::events::HTTP3_URI.to_string()],
161//! # );
162//! serde_json::to_string_pretty(&trace).unwrap();
163//! ```
164//!
165//! which would generate the following:
166//!
167//! ```ignore
168//! {
169//!   "vantage_point": {
170//!     "name": "Example client",
171//!     "type": "client"
172//!   },
173//!   "title": "Example qlog trace",
174//!   "description": "Example qlog trace description",
175//!   "configuration": {
176//!     "time_offset": 0.0
177//!   },
178//!   "events": [
179//!     {
180//!       "time": 0.0,
181//!       "name": "quic:packet_sent",
182//!       "data": {
183//!         "header": {
184//!           "packet_type": "initial",
185//!           "packet_number": 0,
186//!           "version": "1",
187//!           "scil": 8,
188//!           "dcil": 8,
189//!           "scid": "7e37e4dcc6682da8",
190//!           "dcid": "36ce104eee50101c"
191//!         },
192//!         "raw": {
193//!           "length": 1251,
194//!           "payload_length": 1224
195//!         },
196//!         "frames": [
197//!           {
198//!             "frame_type": "crypto",
199//!             "offset": 0,
200//!             "length": 0
201//!           }
202//!         ]
203//!       }
204//!     }
205//!   ]
206//! }
207//! ```
208//!
209//! ## Streaming Traces with JSON-SEQ
210//!
211//! To help support streaming serialization of qlogs,
212//! draft-ietf-quic-qlog-main-schema-01 introduced support for RFC 7464 JSON
213//! Text Sequences (JSON-SEQ). The qlog crate supports this format and provides
214//! utilities that aid streaming.
215//!
216//! A [`TraceSeq`] contains metadata such as the [`VantagePoint`] of capture and
217//! the [`Configuration`]. However, protocol event data is handled as separate
218//! lines containing a record separator character, a serialized [`Event`], and a
219//! newline.
220//!
221//! ### Creating a TraceSeq
222//!
223//! ```
224//! let mut trace = qlog::TraceSeq::new(
225//!     Some("Example qlog trace".to_string()),
226//!     Some("Example qlog trace description".to_string()),
227//!     None,
228//!     Some(qlog::VantagePoint {
229//!         name: Some("Example client".to_string()),
230//!         ty: qlog::VantagePointType::Client,
231//!         flow: None,
232//!     }),
233//!     vec![
234//!         qlog::events::QUIC_URI.to_string(),
235//!         qlog::events::HTTP3_URI.to_string(),
236//!     ],
237//! );
238//! ```
239//!
240//! Create an object with the [`Write`] trait:
241//!
242//! ```
243//! let mut file = std::fs::File::create("foo.sqlog").unwrap();
244//! ```
245//!
246//! Create a [`QlogStreamer`] and start serialization to foo.sqlog
247//! using [`start_log()`]:
248//!
249//! ```
250//! # let mut trace = qlog::TraceSeq::new(
251//! #    Some("Example qlog trace".to_string()),
252//! #    Some("Example qlog trace description".to_string()),
253//! #    None,
254//! #    Some(qlog::VantagePoint {
255//! #        name: Some("Example client".to_string()),
256//! #        ty: qlog::VantagePointType::Client,
257//! #        flow: None,
258//! #    }),
259//! #    vec![qlog::events::QUIC_URI.to_string(), qlog::events::HTTP3_URI.to_string()],
260//! # );
261//! # let mut file = std::fs::File::create("foo.sqlog").unwrap();
262//! let mut streamer = qlog::streamer::QlogStreamer::new(
263//!     Some("Example qlog".to_string()),
264//!     Some("Example qlog description".to_string()),
265//!     std::time::Instant::now(),
266//!     trace,
267//!     qlog::events::EventImportance::Base,
268//!     qlog::streamer::EventTimePrecision::NanoSeconds,
269//!     Box::new(file),
270//! );
271//!
272//! streamer.start_log().ok();
273//! ```
274//!
275//! ### Adding events
276//!
277//! Once logging has started you can stream events. Events
278//! are written in one step using one of [`add_event()`],
279//! [`add_event_with_instant()`], [`add_event_now()`],
280//! [`add_event_data_with_instant()`], or [`add_event_data_now()`] :
281//!
282//! ```
283//! # let mut trace = qlog::TraceSeq::new(
284//! #    Some("Example qlog trace".to_string()),
285//! #    Some("Example qlog trace description".to_string()),
286//! #    None,
287//! #    Some(qlog::VantagePoint {
288//! #        name: Some("Example client".to_string()),
289//! #        ty: qlog::VantagePointType::Client,
290//! #        flow: None,
291//! #    }),
292//! #    vec![qlog::events::QUIC_URI.to_string(), qlog::events::HTTP3_URI.to_string()],
293//! # );
294//! # let mut file = std::fs::File::create("foo.qlog").unwrap();
295//! # let mut streamer = qlog::streamer::QlogStreamer::new(
296//! #     Some("Example qlog".to_string()),
297//! #     Some("Example qlog description".to_string()),
298//! #     std::time::Instant::now(),
299//! #     trace,
300//! #     qlog::events::EventImportance::Base,
301//! #     qlog::streamer::EventTimePrecision::NanoSeconds,
302//! #     Box::new(file),
303//! # );
304//!
305//! let scid = [0x7e, 0x37, 0xe4, 0xdc, 0xc6, 0x68, 0x2d, 0xa8];
306//! let dcid = [0x36, 0xce, 0x10, 0x4e, 0xee, 0x50, 0x10, 0x1c];
307//!
308//! let pkt_hdr = qlog::events::quic::PacketHeader::with_type(
309//!     qlog::events::quic::PacketType::OneRtt,
310//!     Some(0),
311//!     Some(0x00000001),
312//!     Some(&scid),
313//!     Some(&dcid),
314//! );
315//!
316//! let ping = qlog::events::quic::QuicFrame::Ping {
317//!     raw: None,
318//! };
319//!
320//! let raw = qlog::events::RawInfo {
321//!             length: None,
322//!             payload_length:
323//!             Some(1234), data: None
324//!           };
325//! let padding = qlog::events::quic::QuicFrame::Padding {
326//!     raw: Some(Box::new(raw)),
327//! };
328//!
329//! let event_data =
330//!     qlog::events::EventData::QuicPacketSent(qlog::events::quic::PacketSent {
331//!         header: pkt_hdr,
332//!         frames: Some(vec![ping, padding].into()),
333//!         stateless_reset_token: None,
334//!         supported_versions: None,
335//!         raw: None,
336//!         datagram_id: None,
337//!         is_mtu_probe_packet: None,
338//!         send_at_time: None,
339//!         trigger: None,
340//!     });
341//!
342//! let event = qlog::events::Event::with_time(0.0, event_data);
343//!
344//! streamer.add_event(event).ok();
345//! ```
346//!
347//! Once all events have been written, the log
348//! can be finalized with [`finish_log()`]:
349//!
350//! ```
351//! # let mut trace = qlog::TraceSeq::new(
352//! #    Some("Example qlog trace".to_string()),
353//! #    Some("Example qlog trace description".to_string()),
354//! #    None,
355//! #    Some(qlog::VantagePoint {
356//! #        name: Some("Example client".to_string()),
357//! #        ty: qlog::VantagePointType::Client,
358//! #        flow: None,
359//! #    }),
360//! #    vec![qlog::events::QUIC_URI.to_string(), qlog::events::HTTP3_URI.to_string()],
361//! # );
362//! # let mut file = std::fs::File::create("foo.qlog").unwrap();
363//! # let mut streamer = qlog::streamer::QlogStreamer::new(
364//! #     Some("Example qlog".to_string()),
365//! #     Some("Example qlog description".to_string()),
366//! #     std::time::Instant::now(),
367//! #     trace,
368//! #     qlog::events::EventImportance::Base,
369//! #     qlog::streamer::EventTimePrecision::NanoSeconds,
370//! #     Box::new(file),
371//! # );
372//! streamer.finish_log().ok();
373//! ```
374//!
375//! ### Serializing
376//!
377//! Serialization to JSON occurs as methods on the [`QlogStreamer`]
378//! are called. No additional steps are required.
379//!
380//! [`Trace`]: struct.Trace.html
381//! [`TraceSeq`]: struct.TraceSeq.html
382//! [`VantagePoint`]: struct.VantagePoint.html
383//! [`Configuration`]: struct.Configuration.html
384//! [`qlog::Trace.events`]: struct.Trace.html#structfield.events
385//! [`push_event()`]: struct.Trace.html#method.push_event
386//! [`QlogStreamer`]: struct.QlogStreamer.html
387//! [`Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
388//! [`start_log()`]: streamer/struct.QlogStreamer.html#method.start_log
389//! [`add_event()`]: streamer/struct.QlogStreamer.html#method.add_event
390//! [`add_event_with_instant()`]: streamer/struct.QlogStreamer.html#method.add_event_with_instant
391//! [`add_event_now()`]: streamer/struct.QlogStreamer.html#method.add_event_now
392//! [`add_event_data_with_instant()`]: streamer/struct.QlogStreamer.html#method.add_event_data_with_instant
393//! [`add_event_data_now()`]: streamer/struct.QlogStreamer.html#method.add_event_data_now
394//! [`finish_log()`]: streamer/struct.QlogStreamer.html#method.finish_log
395
396use std::time::SystemTime;
397
398use crate::events::quic::PacketHeader;
399use crate::events::Event;
400
401use serde::Deserialize;
402use serde::Serialize;
403
404/// A quiche qlog error.
405#[derive(Debug)]
406pub enum Error {
407    /// There is no more work to do.
408    Done,
409
410    /// The operation cannot be completed because it was attempted
411    /// in an invalid state.
412    InvalidState,
413
414    // Invalid Qlog format
415    InvalidFormat,
416
417    /// I/O error.
418    IoError(std::io::Error),
419}
420
421impl std::fmt::Display for Error {
422    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
423        write!(f, "{self:?}")
424    }
425}
426
427impl std::error::Error for Error {
428    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
429        None
430    }
431}
432
433impl std::convert::From<std::io::Error> for Error {
434    fn from(err: std::io::Error) -> Self {
435        Error::IoError(err)
436    }
437}
438
439pub const QLOGFILE_URI: &str = "urn:ietf:params:qlog:file:contained";
440pub const QLOGFILESEQ_URI: &str = "urn:ietf:params:qlog:file:sequential";
441
442pub type Bytes = String;
443pub type StatelessResetToken = Bytes;
444
445/// A specialized [`Result`] type for quiche qlog operations.
446///
447/// This type is used throughout the public API for any operation that
448/// can produce an error.
449///
450/// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
451pub type Result<T> = std::result::Result<T, Error>;
452
453#[serde_with::skip_serializing_none]
454#[derive(Serialize, Deserialize, Clone)]
455pub struct Qlog {
456    pub file_schema: String,
457    pub serialization_format: String,
458    pub title: Option<String>,
459    pub description: Option<String>,
460
461    pub traces: Vec<Trace>,
462}
463#[serde_with::skip_serializing_none]
464#[derive(Serialize, Deserialize, Clone, Debug)]
465pub struct QlogSeq {
466    pub file_schema: String,
467    pub serialization_format: String,
468    pub title: Option<String>,
469    pub description: Option<String>,
470
471    pub trace: TraceSeq,
472}
473
474#[derive(Clone, Copy)]
475pub enum ImportanceLogLevel {
476    Core  = 0,
477    Base  = 1,
478    Extra = 2,
479}
480
481// We now commence data definitions heavily styled on the QLOG
482// schema definition. Data is serialized using serde.
483#[serde_with::skip_serializing_none]
484#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
485pub struct Trace {
486    pub title: Option<String>,
487    pub description: Option<String>,
488    pub common_fields: Option<CommonFields>,
489    pub vantage_point: Option<VantagePoint>,
490    pub event_schemas: Vec<String>,
491
492    pub events: Vec<Event>,
493}
494
495/// Helper functions for using a qlog [Trace].
496impl Trace {
497    /// Creates a new qlog [Trace]
498    pub fn new(
499        title: Option<String>, description: Option<String>,
500        common_fields: Option<CommonFields>, vantage_point: Option<VantagePoint>,
501        event_schemas: Vec<String>,
502    ) -> Self {
503        Trace {
504            title,
505            description,
506            common_fields,
507            vantage_point,
508            event_schemas,
509            events: Vec::new(),
510        }
511    }
512
513    /// Append an [Event] to a [Trace]
514    pub fn push_event(&mut self, event: Event) {
515        self.events.push(event);
516    }
517}
518
519#[serde_with::skip_serializing_none]
520#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
521pub struct TraceSeq {
522    pub title: Option<String>,
523    pub description: Option<String>,
524    pub common_fields: Option<CommonFields>,
525    pub vantage_point: Option<VantagePoint>,
526    pub event_schemas: Vec<String>,
527}
528
529/// Helper functions for using a qlog [TraceSeq].
530impl TraceSeq {
531    /// Creates a new qlog [TraceSeq]
532    pub fn new(
533        title: Option<String>, description: Option<String>,
534        common_fields: Option<CommonFields>, vantage_point: Option<VantagePoint>,
535        event_schemas: Vec<String>,
536    ) -> Self {
537        TraceSeq {
538            title,
539            description,
540            common_fields,
541            vantage_point,
542            event_schemas,
543        }
544    }
545}
546
547#[serde_with::skip_serializing_none]
548#[derive(Serialize, Deserialize, Clone, Default, PartialEq, Eq, Debug)]
549pub struct VantagePoint {
550    pub name: Option<String>,
551
552    #[serde(rename = "type")]
553    pub ty: VantagePointType,
554
555    pub flow: Option<VantagePointType>,
556}
557
558#[derive(Serialize, Deserialize, Clone, Default, PartialEq, Eq, Debug)]
559#[serde(rename_all = "snake_case")]
560pub enum VantagePointType {
561    Client,
562    Server,
563    Network,
564    #[default]
565    Unknown,
566}
567
568#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug, Default)]
569#[serde(rename_all = "snake_case")]
570pub enum TimeFormat {
571    #[default]
572    RelativeToEpoch,
573    RelativeToPreviousEvent,
574}
575
576#[serde_with::skip_serializing_none]
577#[derive(Serialize, Deserialize, Clone, Default, PartialEq, Debug)]
578#[serde(rename_all = "snake_case")]
579pub struct ReferenceTime {
580    pub clock_type: String,
581    pub epoch: String,
582    pub wall_clock_time: Option<String>,
583}
584
585impl ReferenceTime {
586    /// Create a new `ReferenceTime` instance that uses a monotonic clock.
587    ///
588    /// If `wall_clock_time` is specified, it will be added as the optional
589    /// `wall_clock_time` field of `ReferenceTime`.
590    pub fn new_monotonic(wall_clock_time: Option<SystemTime>) -> Self {
591        let wall_clock_time =
592            wall_clock_time.map(|t| humantime::format_rfc3339(t).to_string());
593        ReferenceTime {
594            clock_type: "monotonic".to_string(),
595            // per draft-ietf-quic-qlog-main-schema-13 epoch must be "unknown"
596            // for monotonic clocks
597            epoch: "unknown".to_string(),
598            wall_clock_time,
599        }
600    }
601}
602
603#[serde_with::skip_serializing_none]
604#[derive(Serialize, Deserialize, Clone, Default, PartialEq, Debug)]
605pub struct CommonFields {
606    pub tuple: Option<String>,
607    pub group_id: Option<String>,
608    pub protocol_types: Option<Vec<String>>,
609
610    pub reference_time: ReferenceTime,
611    pub time_format: Option<TimeFormat>,
612}
613
614#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]
615#[serde(rename_all = "snake_case")]
616pub enum TokenType {
617    Retry,
618    Resumption,
619}
620
621#[serde_with::skip_serializing_none]
622#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Debug)]
623pub struct Token {
624    #[serde(rename(serialize = "type"))]
625    pub ty: Option<TokenType>,
626
627    pub details: Option<String>,
628
629    pub raw: Option<events::RawInfo>,
630}
631
632pub struct HexSlice<'a>(&'a [u8]);
633
634impl<'a> HexSlice<'a> {
635    pub fn new<T>(data: &'a T) -> HexSlice<'a>
636    where
637        T: ?Sized + AsRef<[u8]> + 'a,
638    {
639        HexSlice(data.as_ref())
640    }
641
642    pub fn maybe_string<T>(data: Option<&'a T>) -> Option<String>
643    where
644        T: ?Sized + AsRef<[u8]> + 'a,
645    {
646        data.map(|d| format!("{}", HexSlice::new(d)))
647    }
648}
649
650impl std::fmt::Display for HexSlice<'_> {
651    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
652        for byte in self.0 {
653            write!(f, "{byte:02x}")?;
654        }
655        Ok(())
656    }
657}
658
659pub mod events;
660pub mod reader;
661pub mod streamer;
662#[doc(hidden)]
663pub mod testing;
664
665#[cfg(test)]
666mod tests {
667    use std::time::Duration;
668    use std::time::UNIX_EPOCH;
669
670    use super::ReferenceTime;
671
672    #[test]
673    fn reference_time_new_monotonic_serialization() {
674        // 2024-01-15T10:30:00Z = 1705314600 seconds after UNIX epoch
675        let t = UNIX_EPOCH + Duration::from_secs(1_705_314_600);
676        let rt = ReferenceTime::new_monotonic(Some(t));
677        let map: serde_json::Map<String, serde_json::Value> =
678            serde_json::from_str(&serde_json::to_string(&rt).unwrap()).unwrap();
679
680        assert_eq!(map["clock_type"], "monotonic");
681        assert_eq!(map["epoch"], "unknown");
682        assert_eq!(map["wall_clock_time"], "2024-01-15T10:30:00Z");
683
684        let rt = ReferenceTime::new_monotonic(None);
685        let map: serde_json::Map<String, serde_json::Value> =
686            serde_json::from_str(&serde_json::to_string(&rt).unwrap()).unwrap();
687
688        assert_eq!(map["clock_type"], "monotonic");
689        assert_eq!(map["epoch"], "unknown");
690        assert!(!map.contains_key("wall_clock_time"));
691    }
692}