Skip to main content

rtci_stream_driver/
task.rs

1//! A [`PeerDriver`] as a task of its own, driven through channels (feature `peer`): what an
2//! application with its own threads or tasks uses instead of stepping the driver itself.
3//!
4//! [`task`] splits a driver into three parts:
5//!
6//! - [`PeerTask`], the loop: [`PeerTask::spawn`] runs it on the driver's runtime, or
7//!   [`PeerTask::run`] is awaited where the application wants it (`Runtime::block_on` on an
8//!   OS thread of its own, as reachmydevice's transport thread does);
9//! - [`PeerHandle`] (cloneable), the commands: [`PeerHandle::call`] runs a closure on the
10//!   driver inside the loop and hands back its result (signalling, data channels, media: the
11//!   whole `RTCPeerConnection` API through [`PeerDriver::pc_mut`]), and
12//!   [`PeerHandle::shutdown`] ends it in order ([`PeerDriver::shutdown`]). Each has a
13//!   `_blocking` form for a thread outside any runtime;
14//! - [`PeerEvents`], what the loop reports: the connection's events, the driver's own, and
15//!   what the connection reads (RTP, RTCP, data channel messages), in order
16//!   ([`PeerTaskEvent`]), with `recv` (async) and `recv_blocking`.
17//!
18//! The channels are `async-channel`'s: executor-agnostic, usable from tokio, smol, or a plain
19//! thread. Events are unbounded (the loop never waits for the application); an application
20//! that stops reading lets them pile up.
21//!
22//! ```text
23//! let (task, handle, events) = rtci_stream_driver::task::task(driver);
24//! let _join = task.spawn();
25//! let offer = handle.call(|d| {
26//!     let offer = d.pc_mut().create_offer(None)?;
27//!     let now = d.runtime().now();
28//!     d.pc_mut().set_local_description(now, offer.clone())?;
29//!     Ok::<_, rtci::shared::error::Error>(offer)
30//! }).await??;
31//! while let Some(event) = events.recv().await { /* PeerTaskEvent::Connection(...), ... */ }
32//! ```
33
34use crate::peer::{PeerDriver, PeerDriverEvent};
35use crate::runtime::JoinHandle;
36use rtci::peer_connection::event::RTCPeerConnectionEvent;
37use rtci::peer_connection::message::TaggedRTCMessage;
38use rtci::sansio::Protocol;
39use std::fmt;
40use std::future::Future;
41use std::task::Poll;
42use std::time::Duration;
43
44/// Something the loop reports ([`PeerEvents`]).
45#[non_exhaustive]
46pub enum PeerTaskEvent {
47    /// An event of the connection (after the driver had its look: candidates to signal,
48    /// negotiation needed, states, data channel events, ...).
49    Connection(Box<RTCPeerConnectionEvent>),
50    /// An event of the driver itself (mDNS, addresses changed, ...).
51    Driver(PeerDriverEvent),
52    /// What the connection read: RTP, RTCP, a data channel message.
53    Message(TaggedRTCMessage),
54    /// A step of the driver failed (a socket that could not be bound for a transport that
55    /// needs one, a candidate the connection refused): the loop goes on.
56    StepFailed(String),
57    /// The loop ended (after [`PeerHandle::shutdown`], or when every handle was dropped).
58    Ended,
59}
60
61impl fmt::Debug for PeerTaskEvent {
62    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63        match self {
64            Self::Connection(event) => f.debug_tuple("Connection").field(event).finish(),
65            Self::Driver(event) => f.debug_tuple("Driver").field(event).finish(),
66            Self::Message(_) => f.write_str("Message(..)"),
67            Self::StepFailed(e) => f.debug_tuple("StepFailed").field(e).finish(),
68            Self::Ended => f.write_str("Ended"),
69        }
70    }
71}
72
73/// The loop ended: the command was not carried out.
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub struct TaskEnded;
76
77impl fmt::Display for TaskEnded {
78    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79        f.write_str("the peer task has ended")
80    }
81}
82
83impl std::error::Error for TaskEnded {}
84
85type Call = Box<dyn FnOnce(&mut PeerDriver) + Send>;
86
87enum Command {
88    Call(Call),
89    Shutdown(Duration, async_channel::Sender<()>),
90}
91
92/// The loop of a driver run as a task (see the [module documentation](self)).
93pub struct PeerTask {
94    driver: PeerDriver,
95    commands: async_channel::Receiver<Command>,
96    events: async_channel::Sender<PeerTaskEvent>,
97    wait: Duration,
98}
99
100impl fmt::Debug for PeerTask {
101    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102        f.debug_struct("PeerTask").finish_non_exhaustive()
103    }
104}
105
106/// The commands of a driver run as a task: cloneable, usable from any thread.
107#[derive(Clone)]
108pub struct PeerHandle {
109    commands: async_channel::Sender<Command>,
110}
111
112impl fmt::Debug for PeerHandle {
113    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114        f.debug_struct("PeerHandle").finish_non_exhaustive()
115    }
116}
117
118/// What a driver run as a task reports, in order.
119#[derive(Debug, Clone)]
120pub struct PeerEvents {
121    events: async_channel::Receiver<PeerTaskEvent>,
122}
123
124/// Splits `driver` into its loop, its commands and its events (see the
125/// [module documentation](self)). The loop waits at most 20 ms per step when nothing happens
126/// ([`PeerTask::with_step_wait`]).
127pub fn task(driver: PeerDriver) -> (PeerTask, PeerHandle, PeerEvents) {
128    let (commands_tx, commands) = async_channel::unbounded();
129    let (events, events_rx) = async_channel::unbounded();
130    (
131        PeerTask {
132            driver,
133            commands,
134            events,
135            wait: Duration::from_millis(20),
136        },
137        PeerHandle {
138            commands: commands_tx,
139        },
140        PeerEvents { events: events_rx },
141    )
142}
143
144/// What ended one wait of the loop.
145enum Woke {
146    Stepped(rtci::shared::error::Result<()>),
147    Command(Option<Command>),
148}
149
150impl PeerTask {
151    /// The longest one step waits when nothing happens (the driver wakes earlier for its own
152    /// timers, datagrams and commands).
153    #[must_use]
154    pub fn with_step_wait(mut self, wait: Duration) -> Self {
155        self.wait = wait;
156        self
157    }
158
159    /// Runs the loop on the driver's runtime.
160    pub fn spawn(self) -> Box<dyn JoinHandle> {
161        let runtime = self.driver.runtime().clone();
162        runtime.spawn(Box::pin(async move {
163            self.run().await;
164        }))
165    }
166
167    /// Runs the loop until [`PeerHandle::shutdown`] or until every handle is dropped (the
168    /// driver is then shut down with no linger). For an application that drives it itself
169    /// (`Runtime::block_on` on a thread of its own).
170    pub async fn run(mut self) {
171        loop {
172            let woke = {
173                let mut step = std::pin::pin!(self.driver.step(self.wait));
174                let mut command = std::pin::pin!(self.commands.recv());
175                std::future::poll_fn(|cx| {
176                    // Commands first: a step is cancel-safe (what it waits for stays queued).
177                    if let Poll::Ready(command) = command.as_mut().poll(cx) {
178                        return Poll::Ready(Woke::Command(command.ok()));
179                    }
180                    step.as_mut().poll(cx).map(Woke::Stepped)
181                })
182                .await
183            };
184            match woke {
185                Woke::Stepped(Ok(())) => {}
186                Woke::Stepped(Err(e)) => self.report(PeerTaskEvent::StepFailed(e.to_string())),
187                Woke::Command(Some(Command::Call(call))) => {
188                    call(&mut self.driver);
189                    if let Err(e) = self.driver.flush() {
190                        self.report(PeerTaskEvent::StepFailed(e.to_string()));
191                    }
192                }
193                Woke::Command(Some(Command::Shutdown(linger, done))) => {
194                    let _ = self.driver.shutdown(linger).await;
195                    self.forward();
196                    self.report(PeerTaskEvent::Ended);
197                    let _ = done.try_send(());
198                    return;
199                }
200                Woke::Command(None) => {
201                    let _ = self.driver.shutdown(Duration::ZERO).await;
202                    self.forward();
203                    self.report(PeerTaskEvent::Ended);
204                    return;
205                }
206            }
207            self.forward();
208        }
209    }
210
211    /// Hands what the driver and the connection have to the events channel.
212    fn forward(&mut self) {
213        while let Some(event) = self.driver.poll_event() {
214            self.report(PeerTaskEvent::Connection(Box::new(event)));
215        }
216        while let Some(event) = self.driver.poll_driver_event() {
217            self.report(PeerTaskEvent::Driver(event));
218        }
219        while let Some(message) = self.driver.pc_mut().poll_read() {
220            self.report(PeerTaskEvent::Message(message));
221        }
222    }
223
224    fn report(&self, event: PeerTaskEvent) {
225        let _ = self.events.try_send(event);
226    }
227}
228
229impl PeerHandle {
230    fn send_call<R: Send + 'static>(
231        &self,
232        f: impl FnOnce(&mut PeerDriver) -> R + Send + 'static,
233    ) -> Result<async_channel::Receiver<R>, TaskEnded> {
234        let (tx, rx) = async_channel::bounded(1);
235        let call: Call = Box::new(move |driver| {
236            let _ = tx.try_send(f(driver));
237        });
238        self.commands
239            .try_send(Command::Call(call))
240            .map_err(|_| TaskEnded)?;
241        Ok(rx)
242    }
243
244    /// Runs `f` on the driver inside the loop (which then flushes: what the connection wants
245    /// to send leaves, and its events are reported) and gives back what it returned.
246    ///
247    /// # Errors
248    ///
249    /// The loop has ended.
250    pub async fn call<R: Send + 'static>(
251        &self,
252        f: impl FnOnce(&mut PeerDriver) -> R + Send + 'static,
253    ) -> Result<R, TaskEnded> {
254        self.send_call(f)?.recv().await.map_err(|_| TaskEnded)
255    }
256
257    /// [`call`](Self::call) for a thread outside any async runtime: blocks until the loop has
258    /// run `f`. Not to be called from inside the loop's own runtime thread (it would wait for
259    /// itself).
260    ///
261    /// # Errors
262    ///
263    /// The loop has ended.
264    pub fn call_blocking<R: Send + 'static>(
265        &self,
266        f: impl FnOnce(&mut PeerDriver) -> R + Send + 'static,
267    ) -> Result<R, TaskEnded> {
268        self.send_call(f)?.recv_blocking().map_err(|_| TaskEnded)
269    }
270
271    fn send_shutdown(&self, linger: Duration) -> Result<async_channel::Receiver<()>, TaskEnded> {
272        let (tx, rx) = async_channel::bounded(1);
273        self.commands
274            .try_send(Command::Shutdown(linger, tx))
275            .map_err(|_| TaskEnded)?;
276        Ok(rx)
277    }
278
279    /// Ends the loop in order ([`PeerDriver::shutdown`] with `linger`: mDNS goodbyes, TURN
280    /// releases) and waits until it has.
281    ///
282    /// # Errors
283    ///
284    /// The loop had ended already.
285    pub async fn shutdown(&self, linger: Duration) -> Result<(), TaskEnded> {
286        let done = self.send_shutdown(linger)?;
287        let _ = done.recv().await;
288        Ok(())
289    }
290
291    /// [`shutdown`](Self::shutdown) for a thread outside any async runtime (a SIGTERM
292    /// handler's thread, say).
293    ///
294    /// # Errors
295    ///
296    /// The loop had ended already.
297    pub fn shutdown_blocking(&self, linger: Duration) -> Result<(), TaskEnded> {
298        let done = self.send_shutdown(linger)?;
299        let _ = done.recv_blocking();
300        Ok(())
301    }
302}
303
304impl PeerEvents {
305    /// The next event; `None` once the loop has ended and every event was read.
306    pub async fn recv(&self) -> Option<PeerTaskEvent> {
307        self.events.recv().await.ok()
308    }
309
310    /// [`recv`](Self::recv) for a thread outside any async runtime.
311    pub fn recv_blocking(&self) -> Option<PeerTaskEvent> {
312        self.events.recv_blocking().ok()
313    }
314
315    /// The next event if one is waiting.
316    pub fn try_recv(&self) -> Option<PeerTaskEvent> {
317        self.events.try_recv().ok()
318    }
319}