redseat-api 0.7.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 })
    }
}

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

impl Task {
    /// Stops the task at its next wait.
    pub(super) 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(super) 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(super) 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)]
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());
    }

    #[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);
    }
}