iroh_quinn_proto/connection/
qlog.rs

1//! Implements support for emitting qlog events.
2//!
3//! This uses the [`qlog`] crate to emit qlog events. The n0-qlog crate, and thus this
4//! implementation, is currently based on [draft-ietf-quic-qlog-main-schema-13] an
5//! [draft-ietf-quic-qlog-quic-events-12].
6//!
7//! [draft-ietf-quic-qlog-main-schema-13]: https://www.ietf.org/archive/id/draft-ietf-quic-qlog-main-schema-13.html
8//! [draft-ietf-quic-qlog-quic-events-12]: https://www.ietf.org/archive/id/draft-ietf-quic-qlog-quic-events-12.html
9
10// Function bodies in this module are regularly cfg'd out
11#![allow(unused_variables)]
12
13#[cfg(not(feature = "qlog"))]
14use std::marker::PhantomData;
15#[cfg(feature = "qlog")]
16use std::sync::{Arc, Mutex};
17use std::{
18    net::{IpAddr, SocketAddr},
19    time::Duration,
20};
21
22#[cfg(feature = "qlog")]
23use qlog::{
24    CommonFields, HexSlice, TokenType, VantagePoint,
25    events::{
26        ApplicationError, ConnectionClosedFrameError, Event, EventData, RawInfo, TupleEndpointInfo,
27        quic::{
28            self, AckedRanges, AddressDiscoveryRole, ConnectionStarted, ErrorSpace, PacketHeader,
29            PacketLost, PacketLostTrigger, PacketReceived, PacketSent, PacketType,
30            ParametersRestored, ParametersSet, PreferredAddress, QlogTimerType, QuicFrame,
31            StreamType, TimerEventType, TimerType, TimerUpdated, TransportInitiator, TupleAssigned,
32        },
33    },
34    streamer::QlogStreamer,
35};
36#[cfg(feature = "qlog")]
37use tracing::warn;
38
39use crate::{
40    Connection, ConnectionId, FourTuple, Frame, Instant, PathId,
41    connection::{PathData, SentPacket, timer::Timer},
42    frame::EncodableFrame,
43    packet::{Header, SpaceId},
44    transport_parameters::TransportParameters,
45};
46#[cfg(feature = "qlog")]
47use crate::{
48    QlogConfig, Side, TransportErrorCode,
49    connection::timer::{ConnTimer, PathTimer},
50    frame,
51};
52
53/// Shareable handle to a single qlog output stream
54#[cfg(feature = "qlog")]
55#[derive(Clone)]
56pub(crate) struct QlogStream(Arc<Mutex<QlogStreamer>>);
57
58#[cfg(feature = "qlog")]
59impl QlogStream {
60    pub(crate) fn new(
61        config: QlogConfig,
62        initial_dst_cid: ConnectionId,
63        side: Side,
64        now: Instant,
65    ) -> Result<Self, qlog::Error> {
66        let vantage_point = VantagePoint {
67            name: None,
68            ty: match side {
69                Side::Client => qlog::VantagePointType::Client,
70                Side::Server => qlog::VantagePointType::Server,
71            },
72            flow: None,
73        };
74
75        let common_fields = CommonFields {
76            group_id: Some(initial_dst_cid.to_string()),
77            ..Default::default()
78        };
79
80        let trace = qlog::TraceSeq::new(
81            config.title.clone(),
82            config.description.clone(),
83            Some(common_fields),
84            Some(vantage_point),
85            vec![],
86        );
87
88        let start_time = config.start_time.unwrap_or(now);
89
90        let mut streamer = QlogStreamer::new(
91            config.title,
92            config.description,
93            start_time,
94            trace,
95            qlog::events::EventImportance::Extra,
96            config.writer,
97        );
98
99        streamer.start_log()?;
100        Ok(Self(Arc::new(Mutex::new(streamer))))
101    }
102
103    fn emit_event(&self, event: EventData, now: Instant) {
104        self.emit_event_with_tuple_id(event, now, None);
105    }
106
107    fn emit_event_with_tuple_id(
108        &self,
109        event: EventData,
110        now: Instant,
111        network_path: Option<String>,
112    ) {
113        // Time will be overwritten by `add_event_with_instant`
114        let mut event = Event::with_time(0.0, event);
115        event.tuple = network_path;
116        let mut qlog_streamer = self.0.lock().unwrap();
117        if let Err(e) = qlog_streamer.add_event_with_instant(event, now) {
118            warn!("could not emit qlog event: {e}");
119        }
120    }
121}
122
123/// A [`QlogStream`] that may be either dynamically disabled or compiled out entirely
124#[derive(Clone, Default)]
125pub(crate) struct QlogSink {
126    #[cfg(feature = "qlog")]
127    stream: Option<QlogStream>,
128}
129
130impl QlogSink {
131    #[cfg(feature = "qlog")]
132    pub(crate) fn new(
133        config: QlogConfig,
134        initial_dst_cid: ConnectionId,
135        side: Side,
136        now: Instant,
137    ) -> Self {
138        let stream = QlogStream::new(config, initial_dst_cid, side, now)
139            .inspect_err(|err| warn!("failed to initialize qlog streamer: {err}"))
140            .ok();
141        Self { stream }
142    }
143
144    pub(crate) fn emit_connection_started(
145        &self,
146        now: Instant,
147        loc_cid: ConnectionId,
148        rem_cid: ConnectionId,
149        remote: SocketAddr,
150        local_ip: Option<IpAddr>,
151        transport_params: &TransportParameters,
152    ) {
153        #[cfg(feature = "qlog")]
154        {
155            let Some(stream) = self.stream.as_ref() else {
156                return;
157            };
158            stream.emit_event(
159                EventData::ConnectionStarted(ConnectionStarted {
160                    local: tuple_endpoint_info(local_ip, None, Some(loc_cid)),
161                    remote: tuple_endpoint_info(
162                        Some(remote.ip()),
163                        Some(remote.port()),
164                        Some(rem_cid),
165                    ),
166                }),
167                now,
168            );
169
170            let params = transport_params.to_qlog(TransportInitiator::Local);
171            let event = EventData::ParametersSet(params);
172            stream.emit_event(event, now);
173        }
174    }
175
176    pub(super) fn emit_recovery_metrics(&self, path_id: PathId, path: &mut PathData, now: Instant) {
177        #[cfg(feature = "qlog")]
178        {
179            let Some(stream) = self.stream.as_ref() else {
180                return;
181            };
182
183            let Some(metrics) = path.qlog_recovery_metrics(path_id) else {
184                return;
185            };
186
187            stream.emit_event(EventData::MetricsUpdated(metrics), now);
188        }
189    }
190
191    pub(super) fn emit_packet_lost(
192        &self,
193        pn: u64,
194        info: &SentPacket,
195        loss_delay: Duration,
196        space: SpaceId,
197        now: Instant,
198    ) {
199        #[cfg(feature = "qlog")]
200        {
201            let Some(stream) = self.stream.as_ref() else {
202                return;
203            };
204
205            let event = PacketLost {
206                header: Some(PacketHeader {
207                    packet_number: Some(pn),
208                    packet_type: packet_type(space, false),
209                    length: Some(info.size),
210                    ..Default::default()
211                }),
212                frames: None,
213                trigger: Some(
214                    match info.time_sent.saturating_duration_since(now) >= loss_delay {
215                        true => PacketLostTrigger::TimeThreshold,
216                        false => PacketLostTrigger::ReorderingThreshold,
217                    },
218                ),
219                is_mtu_probe_packet: None,
220            };
221
222            stream.emit_event(EventData::PacketLost(event), now);
223        }
224    }
225
226    pub(super) fn emit_peer_transport_params_restored(&self, conn: &Connection, now: Instant) {
227        #[cfg(feature = "qlog")]
228        {
229            let Some(stream) = self.stream.as_ref() else {
230                return;
231            };
232            let params = conn.peer_params.to_qlog_restored();
233            let event = EventData::ParametersRestored(params);
234            stream.emit_event(event, now);
235        }
236    }
237
238    pub(super) fn emit_peer_transport_params_received(&self, conn: &Connection, now: Instant) {
239        #[cfg(feature = "qlog")]
240        {
241            let Some(stream) = self.stream.as_ref() else {
242                return;
243            };
244            let params = conn.peer_params.to_qlog(TransportInitiator::Remote);
245            let event = EventData::ParametersSet(params);
246            stream.emit_event(event, now);
247        }
248    }
249
250    pub(super) fn emit_tuple_assigned(&self, path_id: PathId, tuple: FourTuple, now: Instant) {
251        #[cfg(feature = "qlog")]
252        {
253            let Some(stream) = self.stream.as_ref() else {
254                return;
255            };
256            let tuple_id = fmt_tuple_id(path_id.as_u32() as u64);
257            let event = TupleAssigned {
258                tuple_id,
259                tuple_local: tuple
260                    .local_ip
261                    .map(|local_ip| tuple_endpoint_info(Some(local_ip), None, None)),
262                tuple_remote: Some(tuple_endpoint_info(
263                    Some(tuple.remote.ip()),
264                    Some(tuple.remote.port()),
265                    None,
266                )),
267            };
268
269            stream.emit_event(EventData::TupleAssigned(event), now);
270        }
271    }
272
273    pub(super) fn emit_packet_sent(&self, packet: QlogSentPacket, now: Instant) {
274        #[cfg(feature = "qlog")]
275        {
276            let Some(stream) = self.stream.as_ref() else {
277                return;
278            };
279            let tuple_id = packet.inner.header.path_id.map(fmt_tuple_id);
280            stream.emit_event_with_tuple_id(EventData::PacketSent(packet.inner), now, tuple_id);
281        }
282    }
283
284    pub(super) fn emit_packet_received(&self, packet: QlogRecvPacket, now: Instant) {
285        #[cfg(feature = "qlog")]
286        {
287            let Some(stream) = self.stream.as_ref() else {
288                return;
289            };
290            let mut packet = packet;
291            packet.emit_padding();
292            let tuple_id = packet.inner.header.path_id.map(fmt_tuple_id);
293            let event = packet.inner;
294            stream.emit_event_with_tuple_id(EventData::PacketReceived(event), now, tuple_id);
295        }
296    }
297
298    /// Emits a timer event.
299    ///
300    /// This function is not public: Instead, create a [`QlogSinkWithTime`] via [`Self::with_time`] and use
301    /// its `emit_timer_` methods.
302    #[cfg(feature = "qlog")]
303    fn emit_timer(&self, timer: Timer, op: TimerOp, now: Instant) {
304        let Some(stream) = self.stream.as_ref() else {
305            return;
306        };
307
308        let timer_type: Option<TimerType> = match timer {
309            Timer::Conn(conn_timer) => match conn_timer {
310                ConnTimer::Idle => Some(QlogTimerType::IdleTimeout.into()),
311                ConnTimer::Close => Some(TimerType::custom("close")),
312                ConnTimer::KeyDiscard => Some(TimerType::custom("key_discard")),
313                ConnTimer::KeepAlive => Some(TimerType::custom("keep_alive")),
314                ConnTimer::PushNewCid => Some(TimerType::custom("push_new_cid")),
315            },
316            Timer::PerPath(_, path_timer) => match path_timer {
317                PathTimer::LossDetection => Some(QlogTimerType::LossTimeout.into()),
318                PathTimer::PathIdle => Some(TimerType::custom("path_idle")),
319                PathTimer::PathValidation => Some(QlogTimerType::PathValidation.into()),
320                PathTimer::PathChallengeLost => Some(TimerType::custom("path_challenge_lost")),
321                PathTimer::PathOpen => Some(TimerType::custom("path_open")),
322                PathTimer::PathKeepAlive => Some(TimerType::custom("path_keep_alive")),
323                PathTimer::Pacing => Some(TimerType::custom("pacing")),
324                PathTimer::MaxAckDelay => Some(QlogTimerType::Ack.into()),
325                PathTimer::DiscardPath => Some(TimerType::custom("discard_path")),
326            },
327        };
328
329        let Some(timer_type) = timer_type else {
330            return;
331        };
332
333        let delta = match op {
334            TimerOp::Set(instant) => instant
335                .checked_duration_since(now)
336                .map(|dur| dur.as_secs_f32() * 1000.),
337            _ => None,
338        };
339        let path_id = match timer {
340            Timer::Conn(_) => None,
341            Timer::PerPath(path_id, _) => Some(path_id.as_u32() as u64),
342        };
343
344        let event_type = match op {
345            TimerOp::Set(_) => TimerEventType::Set,
346            TimerOp::Expire => TimerEventType::Expired,
347            TimerOp::Cancelled => TimerEventType::Cancelled,
348        };
349
350        let event = TimerUpdated {
351            path_id,
352            timer_type: Some(timer_type),
353            timer_id: None,
354            packet_number_space: None,
355            event_type,
356            delta,
357        };
358        stream.emit_event(EventData::TimerUpdated(event), now);
359    }
360
361    /// Returns a [`QlogSinkWithTime`] that passes along a `now` timestamp.
362    ///
363    /// This may be used if you want to pass a [`QlogSink`] downwards together with the current
364    /// `now` timestamp, to not have to pass the latter separately as an additional argument just
365    /// for qlog support.
366    pub(super) fn with_time(&self, now: Instant) -> QlogSinkWithTime<'_> {
367        #[cfg(feature = "qlog")]
368        let s = QlogSinkWithTime { sink: self, now };
369        #[cfg(not(feature = "qlog"))]
370        let s = QlogSinkWithTime {
371            _phantom: PhantomData,
372        };
373        s
374    }
375}
376
377/// A [`QlogSink`] with a `now` timestamp.
378#[derive(Clone)]
379pub(super) struct QlogSinkWithTime<'a> {
380    #[cfg(feature = "qlog")]
381    sink: &'a QlogSink,
382    #[cfg(feature = "qlog")]
383    now: Instant,
384    #[cfg(not(feature = "qlog"))]
385    _phantom: PhantomData<&'a ()>,
386}
387
388impl<'a> QlogSinkWithTime<'a> {
389    pub(super) fn emit_timer_stop(&self, timer: Timer) {
390        #[cfg(feature = "qlog")]
391        self.sink.emit_timer(timer, TimerOp::Cancelled, self.now)
392    }
393
394    pub(super) fn emit_timer_set(&self, timer: Timer, expire_at: Instant) {
395        #[cfg(feature = "qlog")]
396        self.sink
397            .emit_timer(timer, TimerOp::Set(expire_at), self.now)
398    }
399
400    pub(super) fn emit_timer_expire(&self, timer: Timer) {
401        #[cfg(feature = "qlog")]
402        self.sink.emit_timer(timer, TimerOp::Expire, self.now)
403    }
404}
405
406#[cfg(feature = "qlog")]
407enum TimerOp {
408    Set(Instant),
409    Expire,
410    Cancelled,
411}
412
413/// Info about a sent packet. Zero-sized struct if `qlog` feature is not enabled.
414#[derive(Default)]
415pub(crate) struct QlogSentPacket {
416    #[cfg(feature = "qlog")]
417    inner: PacketSent,
418}
419
420impl QlogSentPacket {
421    /// Sets data from the packet header.
422    pub(crate) fn header(
423        &mut self,
424        header: &Header,
425        pn: Option<u64>,
426        space: SpaceId,
427        is_0rtt: bool,
428        path_id: PathId,
429    ) {
430        #[cfg(feature = "qlog")]
431        {
432            self.inner.header.scid = header.src_cid().map(stringify_cid);
433            self.inner.header.dcid = Some(stringify_cid(header.dst_cid()));
434            self.inner.header.packet_number = pn;
435            self.inner.header.packet_type = packet_type(space, is_0rtt);
436            self.inner.header.path_id = Some(path_id.as_u32() as u64);
437        }
438    }
439
440    /// Adds a PADDING frame.
441    ///
442    /// This is a no-op if the `qlog` feature is not enabled.
443    pub(crate) fn frame_padding(&mut self, count: usize) {
444        #[cfg(feature = "qlog")]
445        self.frame_raw(QuicFrame::Padding {
446            raw: Some(RawInfo {
447                length: Some(count as u64),
448                payload_length: Some(count as u64),
449                data: None,
450            }),
451        });
452    }
453
454    /// Adds a frame by pushing a [`QuicFrame`].
455    ///
456    /// This function is only available if the `qlog` feature is enabled, because constructing a [`QuicFrame`] may involve
457    /// calculations which shouldn't be performed if the `qlog` feature is disabled.
458    #[cfg(feature = "qlog")]
459    fn frame_raw(&mut self, frame: QuicFrame) {
460        self.inner.frames.get_or_insert_default().push(frame);
461    }
462
463    /// Finalizes the packet by setting the final packet length (after encryption).
464    pub(super) fn finalize(&mut self, len: usize) {
465        #[cfg(feature = "qlog")]
466        {
467            self.inner.header.length = Some(len as u16);
468        }
469    }
470
471    pub(crate) fn record<'a>(&mut self, frame: &EncodableFrame<'a>) {
472        #[cfg(feature = "qlog")]
473        self.frame_raw(frame.to_qlog());
474    }
475}
476
477/// Info about a received packet. Zero-sized struct if `qlog` feature is not enabled.
478pub(crate) struct QlogRecvPacket {
479    #[cfg(feature = "qlog")]
480    inner: PacketReceived,
481    #[cfg(feature = "qlog")]
482    padding: usize,
483}
484
485impl QlogRecvPacket {
486    /// Creates a new [`QlogRecvPacket`]. Noop if `qlog` feature is not enabled.
487    ///
488    /// `len` is the packet's full length (before decryption).
489    pub(crate) fn new(len: usize) -> Self {
490        #[cfg(not(feature = "qlog"))]
491        let this = Self {};
492
493        #[cfg(feature = "qlog")]
494        let this = {
495            let mut this = Self {
496                inner: Default::default(),
497                padding: 0,
498            };
499            this.inner.header.length = Some(len as u16);
500            this
501        };
502
503        this
504    }
505
506    /// Adds info from the packet header.
507    pub(crate) fn header(&mut self, header: &Header, pn: Option<u64>, path_id: PathId) {
508        #[cfg(feature = "qlog")]
509        {
510            let is_0rtt = !header.is_1rtt();
511            self.inner.header.scid = header.src_cid().map(stringify_cid);
512            self.inner.header.dcid = Some(stringify_cid(header.dst_cid()));
513            self.inner.header.packet_number = pn;
514            self.inner.header.packet_type = packet_type(header.space(), is_0rtt);
515            self.inner.header.path_id = Some(path_id.as_u32() as u64);
516        }
517    }
518
519    /// Adds a frame.
520    pub(crate) fn frame(&mut self, frame: &Frame) {
521        #[cfg(feature = "qlog")]
522        {
523            if matches!(frame, crate::Frame::Padding) {
524                self.padding += 1;
525            } else {
526                self.emit_padding();
527                self.inner
528                    .frames
529                    .get_or_insert_default()
530                    .push(frame.to_qlog())
531            }
532        }
533    }
534
535    #[cfg(feature = "qlog")]
536    fn emit_padding(&mut self) {
537        if self.padding > 0 {
538            self.inner
539                .frames
540                .get_or_insert_default()
541                .push(QuicFrame::Padding {
542                    raw: Some(RawInfo {
543                        length: Some(self.padding as u64),
544                        payload_length: Some(self.padding as u64),
545                        data: None,
546                    }),
547                });
548            self.padding = 0;
549        }
550    }
551}
552
553/* Frame conversions to qlog */
554#[cfg(feature = "qlog")]
555pub(crate) trait ToQlog {
556    fn to_qlog(&self) -> QuicFrame;
557}
558
559#[cfg(feature = "qlog")]
560impl<'a> ToQlog for frame::AckEncoder<'a> {
561    fn to_qlog(&self) -> QuicFrame {
562        QuicFrame::Ack {
563            ack_delay: Some(self.delay as f32),
564            acked_ranges: Some(AckedRanges::Double(
565                self.ranges
566                    .iter()
567                    .map(|range| (range.start, range.end))
568                    .collect(),
569            )),
570            ect1: self.ecn.map(|e| e.ect1),
571            ect0: self.ecn.map(|e| e.ect0),
572            ce: self.ecn.map(|e| e.ce),
573            raw: None,
574        }
575    }
576}
577
578#[cfg(feature = "qlog")]
579impl ToQlog for frame::AckFrequency {
580    fn to_qlog(&self) -> QuicFrame {
581        QuicFrame::AckFrequency {
582            sequence_number: self.sequence.into_inner(),
583            ack_eliciting_threshold: self.ack_eliciting_threshold.into_inner(),
584            requested_max_ack_delay: self.request_max_ack_delay.into_inner(),
585            reordering_threshold: self.reordering_threshold.into_inner(),
586            raw: None,
587        }
588    }
589}
590
591#[cfg(feature = "qlog")]
592impl ToQlog for frame::AddAddress {
593    fn to_qlog(&self) -> QuicFrame {
594        QuicFrame::AddAddress {
595            sequence_number: self.seq_no.into_inner(),
596            ip_v4: match self.ip {
597                IpAddr::V4(ipv4_addr) => Some(ipv4_addr.to_string()),
598                IpAddr::V6(ipv6_addr) => None,
599            },
600            ip_v6: match self.ip {
601                IpAddr::V4(ipv4_addr) => None,
602                IpAddr::V6(ipv6_addr) => Some(ipv6_addr.to_string()),
603            },
604            port: self.port,
605        }
606    }
607}
608
609#[cfg(feature = "qlog")]
610impl ToQlog for frame::CloseEncoder<'_> {
611    fn to_qlog(&self) -> QuicFrame {
612        self.close.to_qlog()
613    }
614}
615
616#[cfg(feature = "qlog")]
617impl ToQlog for frame::Close {
618    fn to_qlog(&self) -> QuicFrame {
619        match self {
620            Self::Connection(f) => {
621                let (error, error_code) = transport_error(f.error_code);
622                let error = error.map(|transport_error| {
623                    ConnectionClosedFrameError::TransportError(transport_error)
624                });
625                QuicFrame::ConnectionClose {
626                    error_space: Some(ErrorSpace::TransportError),
627                    error,
628                    error_code,
629                    reason: String::from_utf8(f.reason.to_vec()).ok(),
630                    reason_bytes: None,
631                    trigger_frame_type: None,
632                }
633            }
634            Self::Application(f) => QuicFrame::ConnectionClose {
635                error_space: Some(ErrorSpace::ApplicationError),
636                error: None,
637                error_code: Some(f.error_code.into_inner()),
638                reason: String::from_utf8(f.reason.to_vec()).ok(),
639                reason_bytes: None,
640                trigger_frame_type: None,
641            },
642        }
643    }
644}
645
646#[cfg(feature = "qlog")]
647impl ToQlog for frame::Crypto {
648    fn to_qlog(&self) -> QuicFrame {
649        QuicFrame::Crypto {
650            offset: self.offset,
651            raw: Some(RawInfo {
652                length: Some(self.data.len() as u64),
653                ..Default::default()
654            }),
655        }
656    }
657}
658
659#[cfg(feature = "qlog")]
660impl ToQlog for frame::Datagram {
661    fn to_qlog(&self) -> QuicFrame {
662        QuicFrame::Datagram {
663            raw: Some(RawInfo {
664                length: Some(self.data.len() as u64),
665                ..Default::default()
666            }),
667        }
668    }
669}
670
671#[cfg(feature = "qlog")]
672impl ToQlog for frame::HandshakeDone {
673    fn to_qlog(&self) -> QuicFrame {
674        QuicFrame::HandshakeDone { raw: None }
675    }
676}
677
678#[cfg(feature = "qlog")]
679impl ToQlog for frame::ImmediateAck {
680    fn to_qlog(&self) -> QuicFrame {
681        QuicFrame::ImmediateAck { raw: None }
682    }
683}
684
685#[cfg(feature = "qlog")]
686impl ToQlog for frame::MaxData {
687    fn to_qlog(&self) -> QuicFrame {
688        QuicFrame::MaxData {
689            maximum: self.0.into(),
690            raw: None,
691        }
692    }
693}
694
695#[cfg(feature = "qlog")]
696impl ToQlog for frame::MaxPathId {
697    fn to_qlog(&self) -> QuicFrame {
698        QuicFrame::MaxPathId {
699            maximum_path_id: self.0.as_u32().into(),
700            raw: None,
701        }
702    }
703}
704
705#[cfg(feature = "qlog")]
706impl ToQlog for frame::MaxStreamData {
707    fn to_qlog(&self) -> QuicFrame {
708        QuicFrame::MaxStreamData {
709            stream_id: self.id.into(),
710            maximum: self.offset,
711            raw: None,
712        }
713    }
714}
715
716#[cfg(feature = "qlog")]
717impl ToQlog for frame::MaxStreams {
718    fn to_qlog(&self) -> QuicFrame {
719        QuicFrame::MaxStreams {
720            maximum: self.count,
721            stream_type: self.dir.into(),
722            raw: None,
723        }
724    }
725}
726
727#[cfg(feature = "qlog")]
728impl ToQlog for frame::NewConnectionId {
729    fn to_qlog(&self) -> QuicFrame {
730        QuicFrame::NewConnectionId {
731            sequence_number: self.sequence,
732            retire_prior_to: self.retire_prior_to,
733            connection_id_length: Some(self.id.len() as u8),
734            connection_id: self.id.to_string(),
735            stateless_reset_token: Some(self.reset_token.to_string()),
736            raw: None,
737        }
738    }
739}
740
741#[cfg(feature = "qlog")]
742impl ToQlog for frame::NewToken {
743    fn to_qlog(&self) -> QuicFrame {
744        QuicFrame::NewToken {
745            token: qlog::Token {
746                ty: Some(TokenType::Retry),
747                raw: Some(RawInfo {
748                    data: HexSlice::maybe_string(Some(&self.token)),
749                    length: Some(self.token.len() as u64),
750                    payload_length: None,
751                }),
752                details: None,
753            },
754            raw: None,
755        }
756    }
757}
758
759#[cfg(feature = "qlog")]
760impl ToQlog for frame::ObservedAddr {
761    fn to_qlog(&self) -> QuicFrame {
762        QuicFrame::ObservedAddress {
763            sequence_number: self.seq_no.into_inner(),
764            ip_v4: match self.ip {
765                IpAddr::V4(ipv4_addr) => Some(ipv4_addr.to_string()),
766                IpAddr::V6(ipv6_addr) => None,
767            },
768            ip_v6: match self.ip {
769                IpAddr::V4(ipv4_addr) => None,
770                IpAddr::V6(ipv6_addr) => Some(ipv6_addr.to_string()),
771            },
772            port: self.port,
773            raw: None,
774        }
775    }
776}
777
778#[cfg(feature = "qlog")]
779impl ToQlog for frame::PathAbandon {
780    fn to_qlog(&self) -> QuicFrame {
781        QuicFrame::PathAbandon {
782            path_id: self.path_id.as_u32().into(),
783            error_code: self.error_code.into(),
784            raw: None,
785        }
786    }
787}
788
789#[cfg(feature = "qlog")]
790impl ToQlog for frame::PathAckEncoder<'_> {
791    fn to_qlog(&self) -> QuicFrame {
792        QuicFrame::PathAck {
793            path_id: self.path_id.as_u32() as u64,
794            ack_delay: Some(self.delay as f32),
795            acked_ranges: Some(AckedRanges::Double(
796                self.ranges
797                    .iter()
798                    .map(|range| (range.start, range.end))
799                    .collect(),
800            )),
801            ect1: self.ecn.map(|e| e.ect1),
802            ect0: self.ecn.map(|e| e.ect0),
803            ce: self.ecn.map(|e| e.ce),
804            raw: None,
805        }
806    }
807}
808
809#[cfg(feature = "qlog")]
810impl ToQlog for frame::PathChallenge {
811    #[cfg(feature = "qlog")]
812    fn to_qlog(&self) -> QuicFrame {
813        QuicFrame::PathChallenge {
814            data: Some(self.to_string()),
815            raw: None,
816        }
817    }
818}
819
820#[cfg(feature = "qlog")]
821impl ToQlog for frame::PathCidsBlocked {
822    fn to_qlog(&self) -> QuicFrame {
823        QuicFrame::PathCidsBlocked {
824            path_id: self.path_id.as_u32().into(),
825            next_sequence_number: self.next_seq.into(),
826            raw: None,
827        }
828    }
829}
830
831#[cfg(feature = "qlog")]
832impl ToQlog for frame::PathResponse {
833    fn to_qlog(&self) -> QuicFrame {
834        QuicFrame::PathResponse {
835            data: Some(self.to_string()),
836            raw: None,
837        }
838    }
839}
840
841#[cfg(feature = "qlog")]
842impl ToQlog for frame::ReachOut {
843    fn to_qlog(&self) -> QuicFrame {
844        QuicFrame::ReachOut {
845            round: self.round.into_inner(),
846            ip_v4: match self.ip {
847                IpAddr::V4(ipv4_addr) => Some(ipv4_addr.to_string()),
848                IpAddr::V6(ipv6_addr) => None,
849            },
850            ip_v6: match self.ip {
851                IpAddr::V4(ipv4_addr) => None,
852                IpAddr::V6(ipv6_addr) => Some(ipv6_addr.to_string()),
853            },
854            port: self.port,
855        }
856    }
857}
858
859#[cfg(feature = "qlog")]
860impl ToQlog for frame::Ping {
861    fn to_qlog(&self) -> QuicFrame {
862        QuicFrame::Ping { raw: None }
863    }
864}
865
866#[cfg(feature = "qlog")]
867impl ToQlog for frame::PathStatusAvailable {
868    fn to_qlog(&self) -> QuicFrame {
869        QuicFrame::PathStatusAvailable {
870            path_id: self.path_id.as_u32().into(),
871            path_status_sequence_number: self.status_seq_no.into(),
872            raw: None,
873        }
874    }
875}
876
877#[cfg(feature = "qlog")]
878impl ToQlog for frame::PathStatusBackup {
879    fn to_qlog(&self) -> QuicFrame {
880        QuicFrame::PathStatusBackup {
881            path_id: self.path_id.as_u32().into(),
882            path_status_sequence_number: self.status_seq_no.into(),
883            raw: None,
884        }
885    }
886}
887
888#[cfg(feature = "qlog")]
889impl ToQlog for frame::PathsBlocked {
890    fn to_qlog(&self) -> QuicFrame {
891        QuicFrame::PathsBlocked {
892            maximum_path_id: self.0.as_u32().into(),
893            raw: None,
894        }
895    }
896}
897
898#[cfg(feature = "qlog")]
899impl ToQlog for frame::ResetStream {
900    fn to_qlog(&self) -> QuicFrame {
901        QuicFrame::ResetStream {
902            stream_id: self.id.into(),
903            error_code: Some(self.error_code.into_inner()),
904            final_size: self.final_offset.into(),
905            error: ApplicationError::Unknown,
906            raw: None,
907        }
908    }
909}
910
911#[cfg(feature = "qlog")]
912impl ToQlog for frame::StopSending {
913    fn to_qlog(&self) -> QuicFrame {
914        QuicFrame::StopSending {
915            stream_id: self.id.into(),
916            error_code: Some(self.error_code.into_inner()),
917            error: ApplicationError::Unknown,
918            raw: None,
919        }
920    }
921}
922
923#[cfg(feature = "qlog")]
924impl ToQlog for frame::RetireConnectionId {
925    fn to_qlog(&self) -> QuicFrame {
926        QuicFrame::RetireConnectionId {
927            sequence_number: self.sequence,
928            raw: None,
929        }
930    }
931}
932
933#[cfg(feature = "qlog")]
934impl ToQlog for frame::RemoveAddress {
935    fn to_qlog(&self) -> QuicFrame {
936        QuicFrame::RemoveAddress {
937            sequence_number: self.seq_no.into_inner(),
938        }
939    }
940}
941
942#[cfg(feature = "qlog")]
943impl ToQlog for frame::StreamMetaEncoder {
944    fn to_qlog(&self) -> QuicFrame {
945        let meta = &self.meta;
946        QuicFrame::Stream {
947            stream_id: meta.id.into(),
948            offset: Some(meta.offsets.start),
949            fin: Some(meta.fin),
950            raw: Some(RawInfo {
951                length: Some(meta.offsets.end - meta.offsets.start),
952                ..Default::default()
953            }),
954        }
955    }
956}
957
958#[cfg(feature = "qlog")]
959impl Frame {
960    /// Converts a [`crate::Frame`] into a [`QuicFrame`].
961    pub(crate) fn to_qlog(&self) -> QuicFrame {
962        match self {
963            Self::Padding => QuicFrame::Padding {
964                raw: Some(RawInfo {
965                    length: None,
966                    payload_length: Some(1),
967                    data: None,
968                }),
969            },
970            Self::Ping => frame::Ping.to_qlog(),
971            Self::Ack(f) => QuicFrame::Ack {
972                ack_delay: Some(f.delay as f32),
973                acked_ranges: Some(AckedRanges::Double(
974                    f.iter()
975                        .map(|range| (*range.start(), *range.end()))
976                        .collect(),
977                )),
978                ect1: f.ecn.as_ref().map(|e| e.ect1),
979                ect0: f.ecn.as_ref().map(|e| e.ect0),
980                ce: f.ecn.as_ref().map(|e| e.ce),
981                raw: None,
982            },
983            Self::ResetStream(f) => f.to_qlog(),
984            Self::StopSending(f) => f.to_qlog(),
985            Self::Crypto(f) => f.to_qlog(),
986            Self::NewToken(f) => f.to_qlog(),
987            Self::Stream(s) => QuicFrame::Stream {
988                stream_id: s.id.into(),
989                offset: Some(s.offset),
990                fin: Some(s.fin),
991                raw: Some(RawInfo {
992                    length: Some(s.data.len() as u64),
993                    ..Default::default()
994                }),
995            },
996            Self::MaxData(v) => v.to_qlog(),
997            Self::MaxStreamData(f) => f.to_qlog(),
998            Self::MaxStreams(f) => f.to_qlog(),
999            Self::DataBlocked { offset } => QuicFrame::DataBlocked {
1000                limit: *offset,
1001                raw: None,
1002            },
1003            Self::StreamDataBlocked { id, offset } => QuicFrame::StreamDataBlocked {
1004                stream_id: (*id).into(),
1005                limit: *offset,
1006                raw: None,
1007            },
1008            Self::StreamsBlocked { dir, limit } => QuicFrame::StreamsBlocked {
1009                stream_type: (*dir).into(),
1010                limit: *limit,
1011                raw: None,
1012            },
1013            Self::NewConnectionId(f) => f.to_qlog(),
1014            Self::RetireConnectionId(f) => f.to_qlog(),
1015            Self::PathChallenge(f) => f.to_qlog(),
1016            Self::PathResponse(f) => f.to_qlog(),
1017            Self::Close(close) => close.to_qlog(),
1018            Self::Datagram(d) => d.to_qlog(),
1019            Self::HandshakeDone => frame::HandshakeDone.to_qlog(),
1020            Self::PathAck(ack) => QuicFrame::PathAck {
1021                path_id: ack.path_id.as_u32().into(),
1022                ack_delay: Some(ack.delay as f32),
1023                ect1: ack.ecn.as_ref().map(|e| e.ect1),
1024                ect0: ack.ecn.as_ref().map(|e| e.ect0),
1025                ce: ack.ecn.as_ref().map(|e| e.ce),
1026                raw: None,
1027                acked_ranges: Some(AckedRanges::Double(
1028                    ack.into_iter()
1029                        .map(|range| (*range.start(), *range.end()))
1030                        .collect(),
1031                )),
1032            },
1033            Self::PathAbandon(frame) => frame.to_qlog(),
1034            Self::PathStatusAvailable(frame) => frame.to_qlog(),
1035            Self::PathStatusBackup(frame) => frame.to_qlog(),
1036            Self::PathsBlocked(frame) => frame.to_qlog(),
1037            Self::PathCidsBlocked(frame) => frame.to_qlog(),
1038            Self::MaxPathId(f) => f.to_qlog(),
1039            Self::AckFrequency(f) => f.to_qlog(),
1040            Self::ImmediateAck => frame::ImmediateAck.to_qlog(),
1041            Self::ObservedAddr(f) => f.to_qlog(),
1042            Self::AddAddress(f) => f.to_qlog(),
1043            Self::ReachOut(f) => f.to_qlog(),
1044            Self::RemoveAddress(f) => f.to_qlog(),
1045        }
1046    }
1047}
1048
1049#[cfg(feature = "qlog")]
1050impl From<crate::Dir> for StreamType {
1051    fn from(value: crate::Dir) -> Self {
1052        match value {
1053            crate::Dir::Bi => Self::Bidirectional,
1054            crate::Dir::Uni => Self::Unidirectional,
1055        }
1056    }
1057}
1058
1059#[cfg(feature = "qlog")]
1060fn packet_type(space: SpaceId, is_0rtt: bool) -> PacketType {
1061    match space {
1062        SpaceId::Initial => PacketType::Initial,
1063        SpaceId::Handshake => PacketType::Handshake,
1064        SpaceId::Data if is_0rtt => PacketType::ZeroRtt,
1065        SpaceId::Data => PacketType::OneRtt,
1066    }
1067}
1068
1069#[cfg(feature = "qlog")]
1070fn stringify_cid(cid: ConnectionId) -> String {
1071    format!("{cid}")
1072}
1073
1074#[cfg(feature = "qlog")]
1075fn tuple_endpoint_info(
1076    ip: Option<IpAddr>,
1077    port: Option<u16>,
1078    cid: Option<ConnectionId>,
1079) -> TupleEndpointInfo {
1080    let (ip_v4, port_v4, ip_v6, port_v6) = match ip {
1081        Some(addr) => match addr {
1082            IpAddr::V4(ipv4_addr) => (Some(ipv4_addr.to_string()), port, None, None),
1083            IpAddr::V6(ipv6_addr) => (None, None, Some(ipv6_addr.to_string()), port),
1084        },
1085        None => (None, None, None, None),
1086    };
1087    TupleEndpointInfo {
1088        ip_v4,
1089        port_v4,
1090        ip_v6,
1091        port_v6,
1092        connection_ids: cid.map(|cid| vec![cid.to_string()]),
1093    }
1094}
1095
1096#[cfg(feature = "qlog")]
1097fn transport_error(code: TransportErrorCode) -> (Option<quic::TransportError>, Option<u64>) {
1098    let transport_error = match code {
1099        TransportErrorCode::NO_ERROR => Some(quic::TransportError::NoError),
1100        TransportErrorCode::INTERNAL_ERROR => Some(quic::TransportError::InternalError),
1101        TransportErrorCode::CONNECTION_REFUSED => Some(quic::TransportError::ConnectionRefused),
1102        TransportErrorCode::FLOW_CONTROL_ERROR => Some(quic::TransportError::FlowControlError),
1103        TransportErrorCode::STREAM_LIMIT_ERROR => Some(quic::TransportError::StreamLimitError),
1104        TransportErrorCode::STREAM_STATE_ERROR => Some(quic::TransportError::StreamStateError),
1105        TransportErrorCode::FINAL_SIZE_ERROR => Some(quic::TransportError::FinalSizeError),
1106        TransportErrorCode::FRAME_ENCODING_ERROR => Some(quic::TransportError::FrameEncodingError),
1107        TransportErrorCode::TRANSPORT_PARAMETER_ERROR => {
1108            Some(quic::TransportError::TransportParameterError)
1109        }
1110        TransportErrorCode::CONNECTION_ID_LIMIT_ERROR => {
1111            Some(quic::TransportError::ConnectionIdLimitError)
1112        }
1113        TransportErrorCode::PROTOCOL_VIOLATION => Some(quic::TransportError::ProtocolViolation),
1114        TransportErrorCode::INVALID_TOKEN => Some(quic::TransportError::InvalidToken),
1115        TransportErrorCode::APPLICATION_ERROR => Some(quic::TransportError::ApplicationError),
1116        TransportErrorCode::CRYPTO_BUFFER_EXCEEDED => {
1117            Some(quic::TransportError::CryptoBufferExceeded)
1118        }
1119        TransportErrorCode::KEY_UPDATE_ERROR => Some(quic::TransportError::KeyUpdateError),
1120        TransportErrorCode::AEAD_LIMIT_REACHED => Some(quic::TransportError::AeadLimitReached),
1121        TransportErrorCode::NO_VIABLE_PATH => Some(quic::TransportError::NoViablePath),
1122        // multipath
1123        TransportErrorCode::APPLICATION_ABANDON_PATH => {
1124            Some(quic::TransportError::ApplicationAbandonPath)
1125        }
1126        TransportErrorCode::PATH_RESOURCE_LIMIT_REACHED => {
1127            Some(quic::TransportError::PathResourceLimitReached)
1128        }
1129        TransportErrorCode::PATH_UNSTABLE_OR_POOR => Some(quic::TransportError::PathUnstableOrPoor),
1130        TransportErrorCode::NO_CID_AVAILABLE_FOR_PATH => {
1131            Some(quic::TransportError::NoCidsAvailableForPath)
1132        }
1133        _ => None,
1134    };
1135    let code = match transport_error {
1136        None => Some(code.into()),
1137        Some(_) => None,
1138    };
1139    (transport_error, code)
1140}
1141
1142#[cfg(feature = "qlog")]
1143fn fmt_tuple_id(path_id: u64) -> String {
1144    format!("p{path_id}")
1145}
1146
1147#[cfg(feature = "qlog")]
1148impl TransportParameters {
1149    fn to_qlog(self, initiator: TransportInitiator) -> ParametersSet {
1150        ParametersSet {
1151            initiator: Some(initiator),
1152            resumption_allowed: None,
1153            early_data_enabled: None,
1154            tls_cipher: None,
1155            original_destination_connection_id: self
1156                .original_dst_cid
1157                .as_ref()
1158                .map(ToString::to_string),
1159            initial_source_connection_id: self.initial_src_cid.as_ref().map(ToString::to_string),
1160            retry_source_connection_id: self.retry_src_cid.as_ref().map(ToString::to_string),
1161            stateless_reset_token: self.stateless_reset_token.as_ref().map(ToString::to_string),
1162            disable_active_migration: Some(self.disable_active_migration),
1163            max_idle_timeout: Some(self.max_idle_timeout.into()),
1164            max_udp_payload_size: Some(self.max_udp_payload_size.into()),
1165            ack_delay_exponent: Some(self.ack_delay_exponent.into()),
1166            max_ack_delay: Some(self.max_ack_delay.into()),
1167            active_connection_id_limit: Some(self.active_connection_id_limit.into()),
1168            initial_max_data: Some(self.initial_max_data.into()),
1169            initial_max_stream_data_bidi_local: Some(
1170                self.initial_max_stream_data_bidi_local.into(),
1171            ),
1172            initial_max_stream_data_bidi_remote: Some(
1173                self.initial_max_stream_data_bidi_remote.into(),
1174            ),
1175            initial_max_stream_data_uni: Some(self.initial_max_stream_data_uni.into()),
1176            initial_max_streams_bidi: Some(self.initial_max_streams_bidi.into()),
1177            initial_max_streams_uni: Some(self.initial_max_streams_uni.into()),
1178            preferred_address: self.preferred_address.as_ref().map(Into::into),
1179            min_ack_delay: self.min_ack_delay.map(Into::into),
1180            address_discovery: self.address_discovery_role.to_qlog(),
1181            initial_max_path_id: self.initial_max_path_id.map(|p| p.as_u32() as u64),
1182            max_remote_nat_traversal_addresses: self
1183                .max_remote_nat_traversal_addresses
1184                .map(|v| u64::from(v.get())),
1185            max_datagram_frame_size: self.max_datagram_frame_size.map(Into::into),
1186            grease_quic_bit: Some(self.grease_quic_bit),
1187            unknown_parameters: Default::default(),
1188        }
1189    }
1190
1191    fn to_qlog_restored(self) -> ParametersRestored {
1192        ParametersRestored {
1193            disable_active_migration: Some(self.disable_active_migration),
1194            max_idle_timeout: Some(self.max_idle_timeout.into()),
1195            max_udp_payload_size: Some(self.max_udp_payload_size.into()),
1196            active_connection_id_limit: Some(self.active_connection_id_limit.into()),
1197            initial_max_data: Some(self.initial_max_data.into()),
1198            initial_max_stream_data_bidi_local: Some(
1199                self.initial_max_stream_data_bidi_local.into(),
1200            ),
1201            initial_max_stream_data_bidi_remote: Some(
1202                self.initial_max_stream_data_bidi_remote.into(),
1203            ),
1204            initial_max_stream_data_uni: Some(self.initial_max_stream_data_uni.into()),
1205            initial_max_streams_bidi: Some(self.initial_max_streams_bidi.into()),
1206            initial_max_streams_uni: Some(self.initial_max_streams_uni.into()),
1207            max_datagram_frame_size: self.max_datagram_frame_size.map(Into::into),
1208            grease_quic_bit: Some(self.grease_quic_bit),
1209        }
1210    }
1211}
1212
1213#[cfg(feature = "qlog")]
1214impl From<&crate::transport_parameters::PreferredAddress> for PreferredAddress {
1215    fn from(value: &crate::transport_parameters::PreferredAddress) -> Self {
1216        let port_v4 = value.address_v4.map(|addr| addr.port()).unwrap_or_default();
1217        let port_v6 = value.address_v6.map(|addr| addr.port()).unwrap_or_default();
1218        let ip_v4 = value
1219            .address_v4
1220            .map(|addr| addr.ip().to_string())
1221            .unwrap_or_default();
1222        let ip_v6 = value
1223            .address_v6
1224            .map(|addr| addr.ip().to_string())
1225            .unwrap_or_default();
1226        let connection_id = value.connection_id.to_string();
1227        let stateless_reset_token = value.stateless_reset_token.to_string();
1228
1229        Self {
1230            ip_v4,
1231            ip_v6,
1232            port_v4,
1233            port_v6,
1234            connection_id,
1235            stateless_reset_token,
1236        }
1237    }
1238}
1239
1240#[cfg(feature = "qlog")]
1241impl crate::address_discovery::Role {
1242    fn to_qlog(self) -> Option<AddressDiscoveryRole> {
1243        match self {
1244            Self::SendOnly => Some(AddressDiscoveryRole::SendOnly),
1245            Self::ReceiveOnly => Some(AddressDiscoveryRole::ReceiveOnly),
1246            Self::Both => Some(AddressDiscoveryRole::Both),
1247            Self::Disabled => None,
1248        }
1249    }
1250}