rtci-stream-driver 0.6.1

A socket driver for a sans-I/O WebRTC engine (ICE-TCP, TURN over TCP and TLS, whole peer connections) on an async runtime of your choice
Documentation
//! A [`PeerDriver`] as a task of its own, driven through channels (feature `peer`): what an
//! application with its own threads or tasks uses instead of stepping the driver itself.
//!
//! [`task`] splits a driver into three parts:
//!
//! - [`PeerTask`], the loop: [`PeerTask::spawn`] runs it on the driver's runtime, or
//!   [`PeerTask::run`] is awaited where the application wants it (`Runtime::block_on` on an
//!   OS thread of its own, as reachmydevice's transport thread does);
//! - [`PeerHandle`] (cloneable), the commands: [`PeerHandle::call`] runs a closure on the
//!   driver inside the loop and hands back its result (signalling, data channels, media: the
//!   whole `RTCPeerConnection` API through [`PeerDriver::pc_mut`]), and
//!   [`PeerHandle::shutdown`] ends it in order ([`PeerDriver::shutdown`]). Each has a
//!   `_blocking` form for a thread outside any runtime;
//! - [`PeerEvents`], what the loop reports: the connection's events, the driver's own, and
//!   what the connection reads (RTP, RTCP, data channel messages), in order
//!   ([`PeerTaskEvent`]), with `recv` (async) and `recv_blocking`.
//!
//! The channels are `async-channel`'s: executor-agnostic, usable from tokio, smol, or a plain
//! thread. Events are unbounded (the loop never waits for the application); an application
//! that stops reading lets them pile up.
//!
//! ```text
//! let (task, handle, events) = rtci_stream_driver::task::task(driver);
//! let _join = task.spawn();
//! let offer = handle.call(|d| {
//!     let offer = d.pc_mut().create_offer(None)?;
//!     let now = d.runtime().now();
//!     d.pc_mut().set_local_description(now, offer.clone())?;
//!     Ok::<_, rtci::shared::error::Error>(offer)
//! }).await??;
//! while let Some(event) = events.recv().await { /* PeerTaskEvent::Connection(...), ... */ }
//! ```

use crate::peer::{PeerDriver, PeerDriverEvent};
use crate::runtime::JoinHandle;
use rtci::peer_connection::event::RTCPeerConnectionEvent;
use rtci::peer_connection::message::TaggedRTCMessage;
use rtci::sansio::Protocol;
use std::fmt;
use std::future::Future;
use std::task::Poll;
use std::time::Duration;

/// Something the loop reports ([`PeerEvents`]).
#[non_exhaustive]
pub enum PeerTaskEvent {
    /// An event of the connection (after the driver had its look: candidates to signal,
    /// negotiation needed, states, data channel events, ...).
    Connection(Box<RTCPeerConnectionEvent>),
    /// An event of the driver itself (mDNS, addresses changed, ...).
    Driver(PeerDriverEvent),
    /// What the connection read: RTP, RTCP, a data channel message.
    Message(TaggedRTCMessage),
    /// A step of the driver failed (a socket that could not be bound for a transport that
    /// needs one, a candidate the connection refused): the loop goes on.
    StepFailed(String),
    /// The loop ended (after [`PeerHandle::shutdown`], or when every handle was dropped).
    Ended,
}

impl fmt::Debug for PeerTaskEvent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Connection(event) => f.debug_tuple("Connection").field(event).finish(),
            Self::Driver(event) => f.debug_tuple("Driver").field(event).finish(),
            Self::Message(_) => f.write_str("Message(..)"),
            Self::StepFailed(e) => f.debug_tuple("StepFailed").field(e).finish(),
            Self::Ended => f.write_str("Ended"),
        }
    }
}

/// The loop ended: the command was not carried out.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TaskEnded;

impl fmt::Display for TaskEnded {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("the peer task has ended")
    }
}

impl std::error::Error for TaskEnded {}

type Call = Box<dyn FnOnce(&mut PeerDriver) + Send>;

enum Command {
    Call(Call),
    Shutdown(Duration, async_channel::Sender<()>),
}

/// The loop of a driver run as a task (see the [module documentation](self)).
pub struct PeerTask {
    driver: PeerDriver,
    commands: async_channel::Receiver<Command>,
    events: async_channel::Sender<PeerTaskEvent>,
    wait: Duration,
}

impl fmt::Debug for PeerTask {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PeerTask").finish_non_exhaustive()
    }
}

/// The commands of a driver run as a task: cloneable, usable from any thread.
#[derive(Clone)]
pub struct PeerHandle {
    commands: async_channel::Sender<Command>,
}

impl fmt::Debug for PeerHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PeerHandle").finish_non_exhaustive()
    }
}

/// What a driver run as a task reports, in order.
#[derive(Debug, Clone)]
pub struct PeerEvents {
    events: async_channel::Receiver<PeerTaskEvent>,
}

/// Splits `driver` into its loop, its commands and its events (see the
/// [module documentation](self)). The loop waits at most 20 ms per step when nothing happens
/// ([`PeerTask::with_step_wait`]).
pub fn task(driver: PeerDriver) -> (PeerTask, PeerHandle, PeerEvents) {
    let (commands_tx, commands) = async_channel::unbounded();
    let (events, events_rx) = async_channel::unbounded();
    (
        PeerTask {
            driver,
            commands,
            events,
            wait: Duration::from_millis(20),
        },
        PeerHandle {
            commands: commands_tx,
        },
        PeerEvents { events: events_rx },
    )
}

/// What ended one wait of the loop.
enum Woke {
    Stepped(rtci::shared::error::Result<()>),
    Command(Option<Command>),
}

impl PeerTask {
    /// The longest one step waits when nothing happens (the driver wakes earlier for its own
    /// timers, datagrams and commands).
    #[must_use]
    pub fn with_step_wait(mut self, wait: Duration) -> Self {
        self.wait = wait;
        self
    }

    /// Runs the loop on the driver's runtime.
    pub fn spawn(self) -> Box<dyn JoinHandle> {
        let runtime = self.driver.runtime().clone();
        runtime.spawn(Box::pin(async move {
            self.run().await;
        }))
    }

    /// Runs the loop until [`PeerHandle::shutdown`] or until every handle is dropped (the
    /// driver is then shut down with no linger). For an application that drives it itself
    /// (`Runtime::block_on` on a thread of its own).
    pub async fn run(mut self) {
        loop {
            let woke = {
                let mut step = std::pin::pin!(self.driver.step(self.wait));
                let mut command = std::pin::pin!(self.commands.recv());
                std::future::poll_fn(|cx| {
                    // Commands first: a step is cancel-safe (what it waits for stays queued).
                    if let Poll::Ready(command) = command.as_mut().poll(cx) {
                        return Poll::Ready(Woke::Command(command.ok()));
                    }
                    step.as_mut().poll(cx).map(Woke::Stepped)
                })
                .await
            };
            match woke {
                Woke::Stepped(Ok(())) => {}
                Woke::Stepped(Err(e)) => self.report(PeerTaskEvent::StepFailed(e.to_string())),
                Woke::Command(Some(Command::Call(call))) => {
                    call(&mut self.driver);
                    if let Err(e) = self.driver.flush() {
                        self.report(PeerTaskEvent::StepFailed(e.to_string()));
                    }
                }
                Woke::Command(Some(Command::Shutdown(linger, done))) => {
                    let _ = self.driver.shutdown(linger).await;
                    self.forward();
                    self.report(PeerTaskEvent::Ended);
                    let _ = done.try_send(());
                    return;
                }
                Woke::Command(None) => {
                    let _ = self.driver.shutdown(Duration::ZERO).await;
                    self.forward();
                    self.report(PeerTaskEvent::Ended);
                    return;
                }
            }
            self.forward();
        }
    }

    /// Hands what the driver and the connection have to the events channel.
    fn forward(&mut self) {
        while let Some(event) = self.driver.poll_event() {
            self.report(PeerTaskEvent::Connection(Box::new(event)));
        }
        while let Some(event) = self.driver.poll_driver_event() {
            self.report(PeerTaskEvent::Driver(event));
        }
        while let Some(message) = self.driver.pc_mut().poll_read() {
            self.report(PeerTaskEvent::Message(message));
        }
    }

    fn report(&self, event: PeerTaskEvent) {
        let _ = self.events.try_send(event);
    }
}

impl PeerHandle {
    fn send_call<R: Send + 'static>(
        &self,
        f: impl FnOnce(&mut PeerDriver) -> R + Send + 'static,
    ) -> Result<async_channel::Receiver<R>, TaskEnded> {
        let (tx, rx) = async_channel::bounded(1);
        let call: Call = Box::new(move |driver| {
            let _ = tx.try_send(f(driver));
        });
        self.commands
            .try_send(Command::Call(call))
            .map_err(|_| TaskEnded)?;
        Ok(rx)
    }

    /// Runs `f` on the driver inside the loop (which then flushes: what the connection wants
    /// to send leaves, and its events are reported) and gives back what it returned.
    ///
    /// # Errors
    ///
    /// The loop has ended.
    pub async fn call<R: Send + 'static>(
        &self,
        f: impl FnOnce(&mut PeerDriver) -> R + Send + 'static,
    ) -> Result<R, TaskEnded> {
        self.send_call(f)?.recv().await.map_err(|_| TaskEnded)
    }

    /// [`call`](Self::call) for a thread outside any async runtime: blocks until the loop has
    /// run `f`. Not to be called from inside the loop's own runtime thread (it would wait for
    /// itself).
    ///
    /// # Errors
    ///
    /// The loop has ended.
    pub fn call_blocking<R: Send + 'static>(
        &self,
        f: impl FnOnce(&mut PeerDriver) -> R + Send + 'static,
    ) -> Result<R, TaskEnded> {
        self.send_call(f)?.recv_blocking().map_err(|_| TaskEnded)
    }

    fn send_shutdown(&self, linger: Duration) -> Result<async_channel::Receiver<()>, TaskEnded> {
        let (tx, rx) = async_channel::bounded(1);
        self.commands
            .try_send(Command::Shutdown(linger, tx))
            .map_err(|_| TaskEnded)?;
        Ok(rx)
    }

    /// Ends the loop in order ([`PeerDriver::shutdown`] with `linger`: mDNS goodbyes, TURN
    /// releases) and waits until it has.
    ///
    /// # Errors
    ///
    /// The loop had ended already.
    pub async fn shutdown(&self, linger: Duration) -> Result<(), TaskEnded> {
        let done = self.send_shutdown(linger)?;
        let _ = done.recv().await;
        Ok(())
    }

    /// [`shutdown`](Self::shutdown) for a thread outside any async runtime (a SIGTERM
    /// handler's thread, say).
    ///
    /// # Errors
    ///
    /// The loop had ended already.
    pub fn shutdown_blocking(&self, linger: Duration) -> Result<(), TaskEnded> {
        let done = self.send_shutdown(linger)?;
        let _ = done.recv_blocking();
        Ok(())
    }
}

impl PeerEvents {
    /// The next event; `None` once the loop has ended and every event was read.
    pub async fn recv(&self) -> Option<PeerTaskEvent> {
        self.events.recv().await.ok()
    }

    /// [`recv`](Self::recv) for a thread outside any async runtime.
    pub fn recv_blocking(&self) -> Option<PeerTaskEvent> {
        self.events.recv_blocking().ok()
    }

    /// The next event if one is waiting.
    pub fn try_recv(&self) -> Option<PeerTaskEvent> {
        self.events.try_recv().ok()
    }
}