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;
#[cfg(not(target_arch = "wasm32"))]
pub type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
#[cfg(target_arch = "wasm32")]
pub type BoxFuture<T> = Pin<Box<dyn Future<Output = T>>>;
pub trait Runtime: MaybeSend {
fn spawn(&self, future: BoxFuture<()>);
fn sleep(&self, duration: Duration) -> BoxFuture<()>;
}
#[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 })
}
}
pub(super) struct Task {
abort: AbortHandle,
finished: Arc<AtomicBool>,
}
impl Task {
pub(super) fn abort(&self) {
self.abort.abort();
}
pub(super) fn is_finished(&self) -> bool {
self.finished.load(Ordering::Acquire)
}
}
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 {
let _ = Abortable::new(future, registration).await;
ended.store(true, Ordering::Release);
}));
Task { abort, finished }
}
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);
}
}