Skip to main content

rtc/peer_connection/handler/
mod.rs

1pub(crate) mod datachannel;
2pub(crate) mod demuxer;
3pub(crate) mod dtls;
4pub(crate) mod endpoint;
5pub(crate) mod ice;
6pub(crate) mod interceptor;
7pub(crate) mod sctp;
8pub(crate) mod srtp;
9
10use crate::peer_connection::RTCPeerConnection;
11use crate::peer_connection::event::RTCPeerConnectionEvent;
12use crate::peer_connection::event::{RTCEventInternal, TaggedRTCEvent};
13use crate::peer_connection::handler::datachannel::{DataChannelHandler, DataChannelHandlerContext};
14use crate::peer_connection::handler::demuxer::{DemuxerHandler, DemuxerHandlerContext};
15use crate::peer_connection::handler::dtls::{DtlsHandler, DtlsHandlerContext};
16use crate::peer_connection::handler::endpoint::{EndpointHandler, EndpointHandlerContext};
17use crate::peer_connection::handler::ice::{IceHandler, IceHandlerContext};
18use crate::peer_connection::handler::interceptor::{InterceptorHandler, InterceptorHandlerContext};
19use crate::peer_connection::handler::sctp::{SctpHandler, SctpHandlerContext};
20use crate::peer_connection::handler::srtp::{SrtpHandler, SrtpHandlerContext};
21use crate::peer_connection::message::{
22    RTCMessage, TaggedRTCMessage,
23    internal::{
24        ApplicationMessage, DTLSMessage, DataChannelEvent, RTCMessageInternal, RTPMessage,
25        TaggedRTCMessageInternal,
26    },
27};
28use crate::peer_connection::state::peer_connection_state::RTCPeerConnectionState;
29use crate::peer_connection::state::signaling_state::RTCSignalingState;
30use crate::statistics::accumulator::RTCStatsAccumulator;
31use ::interceptor::Packet;
32use log::warn;
33use shared::TaggedBytesMut;
34use shared::error::{Error, flatten_errs};
35use std::collections::VecDeque;
36use std::time::Instant;
37
38/// Forward handler list - invokes callback with handler list
39macro_rules! forward_handlers {
40    ($callback:ident!($($args:tt)*)) => {
41        $callback!(
42            $($args)*,
43            [
44                get_demuxer_handler,
45                get_ice_handler,
46                get_dtls_handler,
47                get_sctp_handler,
48                get_datachannel_handler,
49                get_srtp_handler,
50                get_interceptor_handler,
51                get_endpoint_handler
52            ]
53        )
54    };
55}
56
57/// Reverse handler list - invokes callback with handler list
58macro_rules! reverse_handlers {
59    ($callback:ident!($($args:tt)*)) => {
60        $callback!(
61            $($args)*,
62            [
63                get_endpoint_handler,
64                get_interceptor_handler,
65                get_srtp_handler,
66                get_datachannel_handler,
67                get_sctp_handler,
68                get_dtls_handler,
69                get_ice_handler,
70                get_demuxer_handler
71            ]
72        )
73    };
74}
75
76/// Helper macro that processes a list of handlers with code blocks
77macro_rules! process_handler_list {
78    (call_macro: process_handler!($self:expr, $handler:ident, $code:block), [$($getter:ident),+]) => {{
79        $(
80            {
81                let mut $handler = $self.$getter();
82                $code
83            }
84        )+
85    }};
86}
87
88/// Unified macro to iterate over handlers with code blocks
89macro_rules! for_each_handler {
90    // Forward order: execute code block for each handler
91    (forward: $macro:ident!($($args:tt)*)) => {
92        forward_handlers!(process_handler_list!(call_macro: $macro!($($args)*)))
93    };
94
95    // Reverse order: execute code block for each handler
96    (reverse: $macro:ident!($($args:tt)*)) => {
97        reverse_handlers!(process_handler_list!(call_macro: $macro!($($args)*)))
98    };
99}
100
101pub(crate) struct PipelineContext {
102    // Handler contexts
103    pub(crate) demuxer_handler_context: DemuxerHandlerContext,
104    pub(crate) ice_handler_context: IceHandlerContext,
105    pub(crate) dtls_handler_context: DtlsHandlerContext,
106    pub(crate) sctp_handler_context: SctpHandlerContext,
107    pub(crate) datachannel_handler_context: DataChannelHandlerContext,
108    pub(crate) srtp_handler_context: SrtpHandlerContext,
109    pub(crate) interceptor_handler_context: InterceptorHandlerContext,
110    pub(crate) endpoint_handler_context: EndpointHandlerContext,
111
112    // Pipeline
113    /// Media (RTP/RTCP) ready for the application.
114    ///
115    /// Split from data-channel output deliberately. Back-pressure is applied by *not draining
116    /// a queue* — that is what grows [`Self::data_read_outs`], bounds the SCTP drain,
117    /// lowers `a_rwnd` and throttles the peer. While both kinds shared one queue, a caller
118    /// applying that back-pressure necessarily stopped draining media too, so a slow
119    /// data-channel consumer froze video on the same connection for as long as it stalled —
120    /// video that arrives over SRTP and is subject to none of SCTP's flow control.
121    pub(crate) media_read_outs: VecDeque<TaggedRTCMessage>,
122    /// Data-channel messages ready for the application.
123    ///
124    /// Its length *is* the back-pressure signal the SCTP handler bounds against, so a caller
125    /// that declines to drain it throttles the peer — and nothing else. No counter to keep in
126    /// step with it: the queue is the count.
127    pub(crate) data_read_outs: VecDeque<TaggedRTCMessage>,
128    pub(crate) write_outs: VecDeque<TaggedBytesMut>,
129    pub(crate) event_outs: VecDeque<RTCPeerConnectionEvent>,
130
131    // Statistics accumulator
132    pub(crate) stats: RTCStatsAccumulator,
133
134    /// The newest instant the pipeline has been given, through a datagram, a write or a timeout.
135    ///
136    /// `close()` takes no time of its own, and this crate reads no clock, so the `close_notify`
137    /// it sends is stamped with this.
138    pub(crate) now: Instant,
139}
140
141impl PipelineContext {
142    fn observe(&mut self, now: Instant) {
143        self.now = self.now.max(now);
144    }
145}
146
147impl RTCPeerConnection {
148    /*
149     Pipeline Flow (Read Path):
150     Raw Bytes -> Demuxer -> ICE -> DTLS -> SCTP -> DataChannel -> SRTP -> Interceptor -> Endpoint -> Application
151
152     Pipeline Flow (Write Path):
153     Application -> Endpoint -> Interceptor -> SRTP -> DataChannel -> SCTP -> DTLS -> ICE -> Demuxer -> Raw Bytes
154    */
155
156    pub(crate) fn get_demuxer_handler(&mut self) -> DemuxerHandler<'_> {
157        DemuxerHandler::new(
158            &mut self.pipeline_context.demuxer_handler_context,
159            &mut self.pipeline_context.stats,
160        )
161    }
162
163    pub(crate) fn get_ice_handler(&mut self) -> IceHandler<'_> {
164        IceHandler::new(
165            &mut self.pipeline_context.ice_handler_context,
166            &mut self.pipeline_context.stats,
167        )
168    }
169
170    pub(crate) fn get_dtls_handler(&mut self) -> DtlsHandler<'_> {
171        DtlsHandler::new(
172            &mut self.pipeline_context.dtls_handler_context,
173            &mut self.pipeline_context.stats,
174        )
175    }
176
177    /// Next media (RTP/RTCP) message for the application, if any.
178    ///
179    /// Never affected by data-channel back-pressure. Media arrives over SRTP and is subject to
180    /// none of SCTP's flow control, so a caller throttling a slow data-channel consumer must
181    /// still be able to deliver video — draining this is how.
182    ///
183    /// Most callers should use [`poll_read`](sansio::Protocol::poll_read), which interleaves
184    /// media and data-channel messages by the instant each was observed. Reach for this split
185    /// pair only to drain one kind without the other.
186    #[doc(hidden)]
187    pub fn poll_media_read(&mut self) -> Option<TaggedRTCMessage> {
188        self.pipeline_context.media_read_outs.pop_front()
189    }
190
191    /// Next data-channel message for the application, if any.
192    ///
193    /// **Declining to call this is how back-pressure is applied.** Undrained messages leave
194    /// bytes in SCTP's reassembly queue, which lowers the receiver-window credit advertised in
195    /// every SACK, which tells the peer to slow down. Stop calling it while the application is
196    /// behind, resume when it catches up.
197    ///
198    /// Most callers should use [`poll_read`](sansio::Protocol::poll_read), which interleaves
199    /// media and data-channel messages by the instant each was observed; declining to call
200    /// *that* applies the same back-pressure. Reach for this split pair only to drain one kind
201    /// without the other.
202    #[doc(hidden)]
203    pub fn poll_data_read(&mut self) -> Option<TaggedRTCMessage> {
204        self.pipeline_context.data_read_outs.pop_front()
205    }
206
207    pub(crate) fn get_sctp_handler(&mut self) -> SctpHandler<'_> {
208        // The SCTP handler bounds how much it pulls out of the reassembly queues against what
209        // the application has not yet consumed. That backlog lives here, not in the handler's
210        // own `read_outs` — the pipeline empties that within a single `handle_read` — and it
211        // is data-channel output only, so unrelated media cannot throttle SCTP.
212        let downstream_backlog = self.pipeline_context.data_read_outs.len();
213        SctpHandler::new(
214            &mut self.pipeline_context.sctp_handler_context,
215            downstream_backlog,
216        )
217    }
218
219    pub(crate) fn get_datachannel_handler(&mut self) -> DataChannelHandler<'_> {
220        // Read the Copy values before `&mut self.data_channels` borrows self mutably. The
221        // handler needs the DTLS role to give stream ids the parity RFC 8832 §6 requires, and
222        // the negotiated stream count to bound them.
223        let dtls_role = self.dtls_transport().role();
224        let max_channels = self.sctp_transport().max_channels();
225        DataChannelHandler::new(
226            &mut self.pipeline_context.datachannel_handler_context,
227            &mut self.data_channels,
228            &mut self.pipeline_context.stats,
229            self.setting_engine.data_channel.dcep_handshake_timeout,
230            dtls_role,
231            max_channels,
232        )
233    }
234
235    pub(crate) fn get_srtp_handler(&mut self) -> SrtpHandler<'_> {
236        SrtpHandler::new(&mut self.pipeline_context.srtp_handler_context)
237    }
238
239    pub(crate) fn get_interceptor_handler(&mut self) -> InterceptorHandler<'_> {
240        InterceptorHandler::new(
241            &mut self.pipeline_context.interceptor_handler_context,
242            &mut self.rtp_transceivers,
243            &self.media_engine,
244            &mut self.interceptor,
245            &mut self.pipeline_context.stats,
246        )
247    }
248
249    pub(crate) fn get_endpoint_handler(&mut self) -> EndpointHandler<'_> {
250        EndpointHandler::new(
251            &mut self.pipeline_context.endpoint_handler_context,
252            &mut self.rtp_transceivers,
253            &mut self.pipeline_context.stats,
254        )
255    }
256
257    /// Runs every handler's pending writes down the pipeline into `write_outs`, where
258    /// [`poll_write`](sansio::Protocol::poll_write) hands them out.
259    fn flush_writes(&mut self) {
260        use sansio::Protocol;
261
262        let mut intermediate_wouts = VecDeque::new();
263
264        for_each_handler!(reverse: process_handler!(self, handler, {
265            while let Some(msg) = intermediate_wouts.pop_front() {
266                if let Err(err) = handler.handle_write(msg) {
267                    warn!("{}.handle_write got error: {}", handler.name(), err);
268                }
269            }
270            while let Some(msg) = handler.poll_write() {
271                intermediate_wouts.push_back(msg);
272            }
273        }));
274
275        // Final poll write out to pipeline's write out
276        while let Some(msg) = intermediate_wouts.pop_front() {
277            if let RTCMessageInternal::Raw(message) = msg.message {
278                self.pipeline_context.write_outs.push_back(TaggedBytesMut {
279                    now: msg.now,
280                    transport: msg.transport,
281                    message,
282                });
283            }
284        }
285    }
286
287    fn pump_reads(&mut self, msg: Option<TaggedRTCMessageInternal>) {
288        let mut intermediate_routs = VecDeque::<TaggedRTCMessageInternal>::new();
289
290        if let Some(msg) = msg {
291            intermediate_routs.push_back(msg);
292        }
293
294        use sansio::Protocol;
295        for_each_handler!(forward: process_handler!(self, handler, {
296            while let Some(msg) = intermediate_routs.pop_front() {
297                if let Err(err) = handler.handle_read(msg) {
298                    warn!("{}.handle_read got error: {}", handler.name(), err);
299                }
300            }
301            while let Some(msg) = handler.poll_read() {
302                intermediate_routs.push_back(msg);
303            }
304        }));
305
306        // Finally, put intermediate_routs into RTCPeerConnection's routs
307        while let Some(msg) = intermediate_routs.pop_front() {
308            let rtc_message = match msg.message {
309                RTCMessageInternal::Dtls(DTLSMessage::DataChannel(application_message)) => {
310                    if let DataChannelEvent::Message(data_channel_message) =
311                        application_message.data_channel_event
312                    {
313                        Some(RTCMessage::DataChannelMessage(
314                            application_message.data_channel_id,
315                            data_channel_message,
316                        ))
317                    } else {
318                        None
319                    }
320                }
321                RTCMessageInternal::Rtp(RTPMessage::TrackPacket(track_packet)) => {
322                    match track_packet.packet {
323                        Packet::Rtp(packet) => {
324                            Some(RTCMessage::RtpPacket(track_packet.track_id, packet))
325                        }
326                        Packet::Rtcp(packet) => {
327                            Some(RTCMessage::RtcpPacket(track_packet.track_id, packet))
328                        }
329                        _ => None,
330                    }
331                }
332                _ => None,
333            };
334
335            if let Some(rtc_message) = rtc_message {
336                // The instant travels with the message: the application learns when the packet
337                // was observed at the socket, not when it happened to drain it.
338                let tagged = TaggedRTCMessage {
339                    now: msg.now,
340                    message: rtc_message,
341                };
342                // Routed by kind, so a caller can decline data-channel output — the only way
343                // to apply SCTP back-pressure — without also declining media.
344                match &tagged.message {
345                    RTCMessage::DataChannelMessage(..) => {
346                        self.pipeline_context.data_read_outs.push_back(tagged)
347                    }
348                    _ => self.pipeline_context.media_read_outs.push_back(tagged),
349                }
350            }
351        }
352    }
353
354    /// Returns whether any handler raised an event during the sweep.
355    fn pump_events(&mut self) -> bool {
356        let mut intermediate_eouts = VecDeque::new();
357        let mut raised = false;
358
359        use sansio::Protocol;
360
361        for_each_handler!(forward: process_handler!(self, handler, {
362            while let Some(evt) = intermediate_eouts.pop_front() {
363                if let Err(err) = handler.handle_event(evt) {
364                    warn!("{}.handle_event got error: {}", handler.name(), err);
365                }
366            }
367            while let Some(msg) = handler.poll_event() {
368                raised = true;
369                intermediate_eouts.push_back(msg);
370            }
371        }));
372
373        // Finally, put intermediate_eouts into RTCPeerConnection's eouts
374        while let Some(evt_internal) = intermediate_eouts.pop_front() {
375            match &evt_internal.event {
376                RTCEventInternal::RTCPeerConnectionEvent(
377                    RTCPeerConnectionEvent::OnIceConnectionStateChangeEvent(_),
378                )
379                | RTCEventInternal::DTLSHandshakeComplete(_, _)
380                | RTCEventInternal::DTLSClosed => {
381                    self.update_connection_state(false);
382                }
383                _ => {}
384            };
385
386            if let RTCEventInternal::RTCPeerConnectionEvent(evt) = evt_internal.event {
387                self.pipeline_context.event_outs.push_back(evt);
388            }
389        }
390
391        raised
392    }
393}
394
395impl sansio::Protocol<TaggedBytesMut, TaggedRTCMessage, TaggedRTCEvent> for RTCPeerConnection {
396    type Rout = TaggedRTCMessage;
397    type Wout = TaggedBytesMut;
398    type Eout = RTCPeerConnectionEvent;
399    type Error = Error;
400    type Time = Instant;
401
402    fn handle_read(&mut self, msg: TaggedBytesMut) -> Result<(), Self::Error> {
403        self.pipeline_context.observe(msg.now);
404        let msg = TaggedRTCMessageInternal {
405            now: msg.now,
406            transport: msg.transport,
407            message: RTCMessageInternal::Raw(msg.message),
408        };
409        self.pump_reads(Some(msg));
410        Ok(())
411    }
412
413    fn poll_read(&mut self) -> Option<Self::Rout> {
414        self.pump_reads(None);
415
416        if let (Some(data), Some(media)) = (
417            self.pipeline_context.data_read_outs.front(),
418            self.pipeline_context.media_read_outs.front(),
419        ) {
420            if data.now <= media.now {
421                self.pipeline_context.data_read_outs.pop_front()
422            } else {
423                self.pipeline_context.media_read_outs.pop_front()
424            }
425        } else if self.pipeline_context.data_read_outs.front().is_some() {
426            self.pipeline_context.data_read_outs.pop_front()
427        } else {
428            self.pipeline_context.media_read_outs.pop_front()
429        }
430    }
431
432    fn handle_write(&mut self, msg: TaggedRTCMessage) -> Result<(), Self::Error> {
433        let now = msg.now;
434        self.pipeline_context.observe(now);
435        let rtc_message_internal = match msg.message {
436            RTCMessage::DataChannelMessage(data_channel_id, data_channel_message) => {
437                RTCMessageInternal::Dtls(DTLSMessage::DataChannel(ApplicationMessage {
438                    data_channel_id,
439                    data_channel_event: DataChannelEvent::Message(data_channel_message),
440                }))
441            }
442            RTCMessage::RtpPacket(_track_id, rtp_packet) => {
443                RTCMessageInternal::Rtp(RTPMessage::Packet(Packet::Rtp(rtp_packet)))
444            }
445            RTCMessage::RtcpPacket(_track_id, rtcp_packet) => {
446                RTCMessageInternal::Rtp(RTPMessage::Packet(Packet::Rtcp(rtcp_packet)))
447            }
448        };
449
450        // Only endpoint can handle user write message
451        let mut endpoint_handler = self.get_endpoint_handler();
452        endpoint_handler.handle_write(TaggedRTCMessageInternal {
453            now,
454            transport: Default::default(),
455            message: rtc_message_internal,
456        })
457    }
458
459    fn poll_write(&mut self) -> Option<Self::Wout> {
460        self.flush_writes();
461        self.pipeline_context.write_outs.pop_front()
462    }
463
464    fn handle_event(&mut self, evt: TaggedRTCEvent) -> Result<(), Self::Error> {
465        // `RTCEvent` is `pub enum RTCEvent {}` — uninhabited, reserved for future use — so no
466        // caller can construct one and this arm is unreachable. Diverging on the empty match
467        // keeps that fact in the type system, and avoids inventing an instant to wrap the
468        // event with when there is none to be had. C3-03 replaces this with `evt.now` once
469        // the public channel carries a timestamp.
470        match evt.event {}
471    }
472
473    fn poll_event(&mut self) -> Option<Self::Eout> {
474        // Drain the backlog before sweeping the pipeline again: anything a sweep adds lands
475        // behind it anyway, and the sweep runs once the backlog is empty.
476        if let Some(evt) = self.pipeline_context.event_outs.pop_front() {
477            return Some(evt);
478        }
479
480        // Handling an event can queue read messages, like the open of a negotiated data channel
481        // on `SCTPHandshakeComplete`. Deliver them, and the events they raise, now rather than
482        // on the next incoming packet.
483        if self.pump_events() {
484            self.pump_reads(None);
485            self.pump_events();
486        }
487
488        self.pipeline_context.event_outs.pop_front()
489    }
490
491    fn handle_timeout(&mut self, now: Instant) -> Result<(), Self::Error> {
492        self.pipeline_context.observe(now);
493        for_each_handler!(forward: process_handler!(self, handler, {
494            handler.handle_timeout(now)?;
495        }));
496        Ok(())
497    }
498
499    fn poll_timeout(&mut self) -> Option<Instant> {
500        let mut eto: Option<Instant> = None;
501        for_each_handler!(forward: process_handler!(self, handler, {
502            if let Some(next) = handler.poll_timeout() {
503                eto = Some(eto.map_or(next, |curr| std::cmp::min(curr, next)));
504            }
505        }));
506        eto
507    }
508
509    fn close(&mut self) -> Result<(), Self::Error> {
510        // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #1)
511        if self.peer_connection_state == RTCPeerConnectionState::Closed {
512            return Ok(());
513        }
514
515        // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #3)
516        self.signaling_state = RTCSignalingState::Closed;
517
518        // Tell the peer before tearing anything down, so it can close at once instead of waiting
519        // for its ICE consent checks to time out (rtc#255). During this flush the SCTP handler
520        // sends the data it still holds and then an ABORT for each association (W3C close():
521        // "tear down the underlying SCTP association by sending an SCTP ABORT chunk"), and the
522        // DTLS handler queues a close_notify behind them, so nothing pending is dropped or sent
523        // after it. They are routed now because closing the ICE handler below forgets the
524        // selected candidate pair every outbound packet is addressed with; the packets wait in
525        // `write_outs` for the caller's next `poll_write`.
526        let now = self.pipeline_context.now;
527        self.get_sctp_handler().request_abort();
528        self.get_dtls_handler().request_close(now);
529        self.flush_writes();
530
531        // Try closing everything and collect the errors
532        // Shutdown strategy:
533        // 1. All Conn close by closing their underlying Conn.
534        // 2. A Mux stops this chain. It won't close the underlying
535        //    Conn if one of the endpoints is closed down. To
536        //    continue the chain the Mux has to be closed.
537        for_each_handler!(forward: process_handler!(self, handler, {
538            handler.close()?;
539        }));
540
541        let close_errs: Vec<Error> = vec![];
542
543        /* TODO:
544        if let Err(err) = self.interceptor.close().await {
545            close_errs.push(Error::new(format!("interceptor: {err}")));
546        }
547
548        // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #4)
549        {
550            let mut rtp_transceivers = self.internal.rtp_transceivers.lock().await;
551            for t in &*rtp_transceivers {
552                if let Err(err) = t.stop().await {
553                    close_errs.push(Error::new(format!("rtp_transceivers: {err}")));
554                }
555            }
556            rtp_transceivers.clear();
557        }
558
559        // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #5)
560        {
561            let mut data_channels = self.internal.sctp_transport.data_channels.lock().await;
562            for d in &*data_channels {
563                if let Err(err) = d.close().await {
564                    close_errs.push(Error::new(format!("data_channels: {err}")));
565                }
566            }
567            data_channels.clear();
568        }
569
570        // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #6)
571        if let Err(err) = self.internal.sctp_transport.stop().await {
572            close_errs.push(Error::new(format!("sctp_transport: {err}")));
573        }
574
575        // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #7)
576        if let Err(err) = self.internal.dtls_transport.stop().await {
577            close_errs.push(Error::new(format!("dtls_transport: {err}")));
578        }
579
580        // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #8, #9, #10)
581        if let Err(err) = self.internal.ice_transport.stop().await {
582            close_errs.push(Error::new(format!("ice_transport: {err}")));
583        }
584         */
585
586        self.update_connection_state(true);
587
588        flatten_errs(close_errs)
589    }
590}
591
592#[cfg(test)]
593mod handler_test {
594    use super::*;
595    use crate::data_channel::message::RTCDataChannelMessage;
596    use crate::peer_connection::RTCPeerConnectionBuilder;
597    use crate::peer_connection::event::RTCDataChannelEvent;
598    use bytes::BytesMut;
599    use sansio::Protocol;
600    use shared::{TransportContext, TransportProtocol};
601    use std::net::Ipv4Addr;
602    use std::time::Duration;
603
604    /// Media must be drainable while data-channel output is held back.
605    ///
606    /// That is the whole point of the split: back-pressure is applied by declining to drain
607    /// the data-channel queue, and while both kinds shared one queue that also stopped media.
608    /// A slow signalling channel froze video on the same connection for as long as it stalled.
609    #[test]
610    fn media_drains_while_data_channel_output_is_held_back() {
611        let base = Instant::now();
612        let mut pc = RTCPeerConnectionBuilder::new()
613            .build(base)
614            .expect("build peer connection");
615
616        // Media outnumbering data, the shape of a real SFU connection.
617        for i in 0..10 {
618            let message = if i % 5 == 0 {
619                RTCMessage::DataChannelMessage(0, RTCDataChannelMessage::default())
620            } else {
621                RTCMessage::RtpPacket(Default::default(), ::rtp::packet::Packet::default())
622            };
623            let tagged = TaggedRTCMessage { now: base, message };
624            match tagged.message {
625                RTCMessage::DataChannelMessage(..) => {
626                    pc.pipeline_context.data_read_outs.push_back(tagged)
627                }
628                _ => pc.pipeline_context.media_read_outs.push_back(tagged),
629            }
630        }
631
632        // Drain media only — as a caller applying data-channel back-pressure would.
633        let mut media = 0;
634        while let Some(msg) = pc.poll_media_read() {
635            assert!(
636                !matches!(msg.message, RTCMessage::DataChannelMessage(..)),
637                "poll_media_read must never yield data-channel output"
638            );
639            media += 1;
640        }
641
642        assert_eq!(
643            media, 8,
644            "all media must be deliverable while data is held back"
645        );
646        assert_eq!(
647            pc.pipeline_context.data_read_outs.len(),
648            2,
649            "held-back data-channel output must stay queued — its length is the signal the \
650             SCTP drain is bounded against, so losing it would drop the back-pressure"
651        );
652
653        // And releasing it hands over exactly what was held.
654        let mut data = 0;
655        while let Some(msg) = pc.poll_data_read() {
656            assert!(matches!(msg.message, RTCMessage::DataChannelMessage(..)));
657            data += 1;
658        }
659        assert_eq!(data, 2);
660    }
661
662    /// `poll_read` still yields both kinds, so the callers that predate the split — 58 files
663    /// across tests and examples — behave exactly as before.
664    #[test]
665    fn poll_read_still_yields_both_kinds() {
666        let base = Instant::now();
667        let mut pc = RTCPeerConnectionBuilder::new()
668            .build(base)
669            .expect("build peer connection");
670
671        pc.pipeline_context
672            .data_read_outs
673            .push_back(TaggedRTCMessage {
674                now: base,
675                message: RTCMessage::DataChannelMessage(0, RTCDataChannelMessage::default()),
676            });
677        pc.pipeline_context
678            .media_read_outs
679            .push_back(TaggedRTCMessage {
680                now: base,
681                message: RTCMessage::RtpPacket(
682                    Default::default(),
683                    ::rtp::packet::Packet::default(),
684                ),
685            });
686
687        let mut kinds = vec![];
688        while let Some(msg) = pc.poll_read() {
689            kinds.push(matches!(msg.message, RTCMessage::DataChannelMessage(..)));
690        }
691        assert_eq!(kinds.len(), 2, "poll_read must still drain everything");
692        assert!(kinds.contains(&true) && kinds.contains(&false));
693    }
694
695    /// The instant the application supplies on `handle_write` is the one the core stamps the
696    /// resulting internal message with — not a reading the core took for itself. Before C3-03
697    /// the public `Win` was a bare `RTCMessage`, so this entry point had no time source and
698    /// stamped `Instant::now()`.
699    #[test]
700    fn handle_write_stamps_from_the_caller_not_the_clock() {
701        let base = Instant::now();
702        let t = |secs| base + Duration::from_secs(secs);
703
704        let mut pc = RTCPeerConnectionBuilder::new()
705            .build(t(0))
706            .expect("a default peer connection builds");
707
708        pc.handle_write(TaggedRTCMessage {
709            now: t(5),
710            message: RTCMessage::DataChannelMessage(
711                1,
712                RTCDataChannelMessage {
713                    is_string: true,
714                    data: BytesMut::from(&b"hello"[..]),
715                },
716            ),
717        })
718        .expect("handle_write queues the message");
719
720        let queued = pc
721            .pipeline_context
722            .endpoint_handler_context
723            .write_outs
724            .front()
725            .expect("the message reaches the endpoint handler");
726
727        assert_eq!(
728            queued.now,
729            t(5),
730            "the internal message carries the caller's instant, not an ambient reading"
731        );
732        assert_ne!(queued.now, t(0), "and not the construction instant either");
733    }
734
735    /// The open of a negotiated data channel is queued as a read message while
736    /// `SCTPHandshakeComplete` is being handled, i.e. inside `poll_event`. That same `poll_event`
737    /// call must return the `OnOpen`: the async `webrtc` driver drains events until `poll_event`
738    /// returns `None` and then waits for the next packet or timer.
739    #[test]
740    fn negotiated_channel_opens_within_the_same_poll_event() {
741        use crate::data_channel::RTCDataChannelInit;
742        use crate::peer_connection::event::TaggedRTCEventInternal;
743        use crate::peer_connection::transport::RTCDtlsRole;
744
745        let base = Instant::now();
746        let mut pc = RTCPeerConnectionBuilder::new()
747            .build(base)
748            .expect("a default peer connection builds");
749        let id = pc
750            .create_data_channel(
751                "negotiated",
752                Some(RTCDataChannelInit {
753                    negotiated: Some(1),
754                    ..Default::default()
755                }),
756            )
757            .expect("a negotiated data channel is created")
758            .id();
759
760        // Drain what creating the channel raised (`OnNegotiationNeeded`): an unrelated event
761        // returned alongside would keep the loop below polling and hide a stuck open.
762        while pc.poll_event().is_some() {}
763
764        // Resolved by the DTLS handshake, which precedes the association.
765        pc.dtls_transport_mut().dtls_role = RTCDtlsRole::Client;
766
767        // What the SCTP handler emits once the association is up.
768        pc.pipeline_context
769            .sctp_handler_context
770            .event_outs
771            .push_back(TaggedRTCEventInternal {
772                now: base,
773                event: RTCEventInternal::SCTPHandshakeComplete(0),
774            });
775
776        let mut opened = false;
777        while let Some(event) = pc.poll_event() {
778            if matches!(
779                event,
780                RTCPeerConnectionEvent::OnDataChannel(RTCDataChannelEvent::OnOpen(opened_id)) if opened_id == id
781            ) {
782                opened = true;
783            }
784        }
785        assert!(
786            opened,
787            "the open must not wait for the next incoming packet"
788        );
789    }
790
791    /// Check that messages in the `read_out` queues don't get stuck until the next incoming packet triggers `handle_read`.
792    #[test]
793    fn pump_read_outs() {
794        let base = Instant::now();
795        let t = |secs| base + Duration::from_secs(secs);
796
797        let mut pc = RTCPeerConnectionBuilder::new()
798            .build(t(0))
799            .expect("a default peer connection builds");
800
801        // drop a message into the data channel handler read outs, like DataChannel::emit_data_channel_opened() does
802        pc.pipeline_context
803            .datachannel_handler_context
804            .read_outs
805            .push_back(TaggedRTCMessageInternal {
806                now: t(5),
807                transport: TransportContext {
808                    local_addr: (Ipv4Addr::LOCALHOST, 0).into(),
809                    peer_addr: (Ipv4Addr::LOCALHOST, 0).into(),
810                    transport_protocol: TransportProtocol::UDP,
811                    ecn: None,
812                },
813                message: RTCMessageInternal::Dtls(DTLSMessage::DataChannel(ApplicationMessage {
814                    data_channel_id: 42,
815                    data_channel_event: DataChannelEvent::Open,
816                })),
817            });
818
819        // call `poll_read` to pump the read outs
820        let msg = pc.poll_read();
821        assert!(
822            msg.is_none(),
823            "The message should be consumed by the enpoint handler"
824        );
825
826        // we should get a channel opened event
827        let event = pc.poll_event().expect("should have an event");
828        assert!(matches!(
829            event,
830            RTCPeerConnectionEvent::OnDataChannel(RTCDataChannelEvent::OnOpen(42))
831        ));
832    }
833}