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 })
}
}
#[cfg(not(target_arch = "wasm32"))]
impl Runtime for tokio::runtime::Handle {
fn spawn(&self, future: BoxFuture<()>) {
tokio::runtime::Handle::spawn(self, future);
}
fn sleep(&self, duration: Duration) -> BoxFuture<()> {
struct Timer(tokio::task::JoinHandle<()>);
impl Drop for Timer {
fn drop(&mut self) {
self.0.abort();
}
}
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;
})
}
}
#[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()),
}
}
pub(crate) struct Task {
abort: AbortHandle,
finished: Arc<AtomicBool>,
}
impl Task {
pub(crate) fn abort(&self) {
self.abort.abort();
}
pub(super) fn is_finished(&self) -> bool {
self.finished.load(Ordering::Acquire)
}
}
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 {
let _ = Abortable::new(future, registration).await;
ended.store(true, Ordering::Release);
}));
Task { abort, finished }
}
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());
}
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);
}
}