redseat-api 0.9.0

Rust client for Redseat media servers
Documentation
//! How the mirror runs its background work, behind [`Runtime`]: tokio
//! ([`TokioRuntime`]) on native targets; an app on another runtime, or in a browser,
//! gives its own.

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;

use futures_util::future::{AbortHandle, Abortable, Either, select};

use crate::transport::MaybeSend;

/// A boxed future, `Send` on native targets.
#[cfg(not(target_arch = "wasm32"))]
pub type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
/// A boxed future, `Send` on native targets.
#[cfg(target_arch = "wasm32")]
pub type BoxFuture<T> = Pin<Box<dyn Future<Output = T>>>;

/// What the mirror needs to run in the background: tasks and timers.
pub trait Runtime: MaybeSend {
    /// Runs `future` in the background until it ends. The mirror stops its own tasks,
    /// so nothing is returned. The future must not be polled inside this call: the
    /// mirror may hold a lock the future takes first.
    fn spawn(&self, future: BoxFuture<()>);

    /// A future that ends `duration` after it is first polled.
    fn sleep(&self, duration: Duration) -> BoxFuture<()>;
}

/// [`Runtime`] on tokio: tasks and timers of the runtime the caller is in.
#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug, Clone, Copy, Default)]
pub struct TokioRuntime;

#[cfg(not(target_arch = "wasm32"))]
impl Runtime for TokioRuntime {
    fn spawn(&self, future: BoxFuture<()>) {
        tokio::spawn(future);
    }

    fn sleep(&self, duration: Duration) -> BoxFuture<()> {
        Box::pin(async move { tokio::time::sleep(duration).await })
    }
}

/// [`Runtime`] on a given tokio runtime: its tasks start from any thread, in its
/// context or not.
#[cfg(not(target_arch = "wasm32"))]
impl Runtime for tokio::runtime::Handle {
    fn spawn(&self, future: BoxFuture<()>) {
        tokio::runtime::Handle::spawn(self, future);
    }

    /// The timer runs on the runtime, so the future can be awaited on any executor.
    /// Dropped early (a timeout that did not fire), it stops the timer.
    fn sleep(&self, duration: Duration) -> BoxFuture<()> {
        /// Stops the timer's task when the sleep is dropped.
        struct Timer(tokio::task::JoinHandle<()>);
        impl Drop for Timer {
            fn drop(&mut self) {
                self.0.abort();
            }
        }
        // Built inside the task: a sleep made on the caller's thread would need a tokio
        // runtime there, and would belong to it.
        let mut timer = Timer(tokio::runtime::Handle::spawn(self, async move {
            tokio::time::sleep(duration).await
        }));
        Box::pin(async move {
            let _ = (&mut timer.0).await;
        })
    }
}

/// Runs blocking `work` on the blocking threads of `runtime`, or of the caller's tokio
/// runtime when `runtime` is `None`; on the caller's thread outside both. A store
/// keeps the runtime it was made in, so it can be awaited from any executor.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) async fn blocking<T: Send + 'static>(
    runtime: Option<&tokio::runtime::Handle>,
    work: impl FnOnce() -> T + Send + 'static,
) -> std::result::Result<T, tokio::task::JoinError> {
    let runtime = (runtime.cloned()).or_else(|| tokio::runtime::Handle::try_current().ok());
    match runtime {
        Some(runtime) => runtime.spawn_blocking(work).await,
        None => Ok(work()),
    }
}

/// A background task of the mirror. Dropping it leaves the task running.
pub(crate) struct Task {
    abort: AbortHandle,
    finished: Arc<AtomicBool>,
}

impl Task {
    /// Stops the task at its next wait.
    pub(crate) fn abort(&self) {
        self.abort.abort();
    }

    /// Whether the task ended, by itself or stopped.
    pub(super) fn is_finished(&self) -> bool {
        self.finished.load(Ordering::Acquire)
    }
}

/// Runs `future` in the background as a task that can be stopped.
pub(crate) fn spawn(runtime: &dyn Runtime, future: BoxFuture<()>) -> Task {
    let (abort, registration) = AbortHandle::new_pair();
    let finished = Arc::new(AtomicBool::new(false));
    let ended = finished.clone();
    runtime.spawn(Box::pin(async move {
        // Stopped is an end like another.
        let _ = Abortable::new(future, registration).await;
        ended.store(true, Ordering::Release);
    }));
    Task { abort, finished }
}

/// The output of `future`, or `None` when it takes longer than `duration`.
pub(crate) async fn timeout<T>(
    runtime: &dyn Runtime,
    duration: Duration,
    future: impl Future<Output = T>,
) -> Option<T> {
    let future = std::pin::pin!(future);
    match select(future, runtime.sleep(duration)).await {
        Either::Left((output, _)) => Some(output),
        Either::Right(_) => None,
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;

    #[tokio::test]
    async fn a_stopped_task_ends_without_finishing_its_work() {
        let done = Arc::new(AtomicBool::new(false));
        let flag = done.clone();
        let task = spawn(
            &TokioRuntime,
            Box::pin(async move {
                TokioRuntime.sleep(Duration::from_millis(50)).await;
                flag.store(true, Ordering::Release);
            }),
        );
        assert!(!task.is_finished());
        task.abort();
        tokio::time::sleep(Duration::from_millis(100)).await;
        assert!(task.is_finished());
        assert!(!done.load(Ordering::Acquire));
    }

    #[tokio::test]
    async fn a_task_left_alone_finishes() {
        let task = spawn(&TokioRuntime, Box::pin(async {}));
        tokio::time::sleep(Duration::from_millis(20)).await;
        assert!(task.is_finished());
    }

    /// Runs `future` on this thread, outside any tokio runtime.
    pub(crate) fn block_on<T>(future: impl Future<Output = T>) -> T {
        struct Unpark(std::thread::Thread);
        impl std::task::Wake for Unpark {
            fn wake(self: Arc<Self>) {
                self.0.unpark();
            }
        }
        let waker = Arc::new(Unpark(std::thread::current())).into();
        let mut cx = std::task::Context::from_waker(&waker);
        let mut future = std::pin::pin!(future);
        loop {
            if let std::task::Poll::Ready(output) = future.as_mut().poll(&mut cx) {
                return output;
            }
            std::thread::park();
        }
    }

    #[test]
    fn a_handle_times_out_from_a_thread_outside_tokio() {
        let runtime = tokio::runtime::Runtime::new().unwrap();
        let handle = runtime.handle().clone();
        let slow = std::thread::spawn(move || {
            block_on(timeout(
                &handle,
                Duration::from_millis(10),
                std::future::pending::<()>(),
            ))
        })
        .join()
        .unwrap();
        assert_eq!(slow, None);
    }

    #[tokio::test]
    async fn timeout_gives_the_output_or_gives_up() {
        let fast = timeout(&TokioRuntime, Duration::from_secs(5), async { 7 }).await;
        assert_eq!(fast, Some(7));
        let slow = timeout(
            &TokioRuntime,
            Duration::from_millis(10),
            TokioRuntime.sleep(Duration::from_secs(5)),
        )
        .await;
        assert_eq!(slow, None);
    }
}