use std::fmt;
use std::future::Future;
use futures::channel::oneshot;
use crate::bound::MaybeSend;
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
#[error("no async runtime is current on this thread")]
pub struct RuntimeUnavailable;
pub struct Unscheduled<F>(pub(crate) F);
impl<F> Unscheduled<F> {
pub fn into_inner(self) -> F {
self.0
}
}
impl<F> fmt::Debug for Unscheduled<F> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("Unscheduled(..)")
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
#[error("detached task ended before publishing its result")]
pub struct Abandoned;
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
pub enum DetachedError {
#[error(transparent)]
Unavailable(#[from] RuntimeUnavailable),
#[error(transparent)]
Abandoned(#[from] Abandoned),
}
#[derive(Clone, Debug)]
pub struct Spawner {
#[cfg(not(all(feature = "browser", target_family = "wasm")))]
handle: tokio::runtime::Handle,
}
impl Spawner {
#[cfg(not(all(feature = "browser", target_family = "wasm")))]
pub fn current() -> Result<Self, RuntimeUnavailable> {
tokio::runtime::Handle::try_current()
.map(|handle| Self { handle })
.map_err(|_| RuntimeUnavailable)
}
#[cfg(all(feature = "browser", target_family = "wasm"))]
pub fn current() -> Result<Self, RuntimeUnavailable> {
Ok(Self {})
}
#[cfg(not(all(feature = "browser", target_family = "wasm")))]
pub fn spawn<F>(&self, future: F)
where F: Future<Output = ()> + MaybeSend + 'static {
drop(self.handle.spawn(future));
}
#[cfg(all(feature = "browser", target_family = "wasm"))]
pub fn spawn<F>(&self, future: F)
where F: Future<Output = ()> + MaybeSend + 'static {
wasm_bindgen_futures::spawn_local(future);
}
pub fn run_detached<F, T>(
&self,
future: F,
) -> impl Future<Output = Result<T, Abandoned>> + MaybeSend + 'static
where
F: Future<Output = T> + MaybeSend + 'static,
T: MaybeSend + 'static,
{
let (sender, receiver) = oneshot::channel();
self.spawn(async move {
let _ = sender.send(future.await);
});
async move { receiver.await.map_err(|_| Abandoned) }
}
}
pub fn spawn_detached<F>(future: F) -> Result<(), Unscheduled<F>>
where F: Future<Output = ()> + MaybeSend + 'static {
match Spawner::current() {
Ok(spawner) => {
spawner.spawn(future);
Ok(())
}
Err(RuntimeUnavailable) => Err(Unscheduled(future)),
}
}
pub fn run_detached<F, T>(
future: F,
) -> impl Future<Output = Result<T, DetachedError>> + MaybeSend + 'static
where
F: Future<Output = T> + MaybeSend + 'static,
T: MaybeSend + 'static,
{
let output = Spawner::current().map(|spawner| spawner.run_detached(future));
async move { Ok(output?.await?) }
}
#[cfg(not(all(feature = "browser", target_family = "wasm")))]
pub fn run_blocking<F, T>(
operation: F,
) -> impl Future<Output = Result<T, DetachedError>> + Send + 'static
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,
{
let joined = tokio::runtime::Handle::try_current()
.map(|handle| handle.spawn_blocking(operation))
.map_err(|_| RuntimeUnavailable);
async move { Ok(joined?.await.map_err(|_| Abandoned)?) }
}
#[cfg(all(test, not(target_family = "wasm")))]
mod tests {
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Notify;
use super::run_blocking;
use super::run_detached;
use super::spawn_detached;
use super::Abandoned;
use super::DetachedError;
use super::RuntimeUnavailable;
use super::Spawner;
#[test]
fn test_spawner_outside_a_runtime_is_unavailable() {
assert_eq!(Spawner::current().err(), Some(RuntimeUnavailable));
}
#[test]
fn test_unscheduled_future_is_handed_back_unpolled() {
let polled = Arc::new(AtomicBool::new(false));
let witness = Arc::clone(&polled);
let unscheduled = spawn_detached(async move { witness.store(true, Ordering::SeqCst) })
.expect_err("no runtime is current outside Tokio");
assert!(!polled.load(Ordering::SeqCst));
futures::executor::block_on(unscheduled.into_inner());
assert!(polled.load(Ordering::SeqCst));
}
#[test]
fn test_run_detached_outside_a_runtime_is_unavailable() {
let result = futures::executor::block_on(run_detached(async {}));
assert_eq!(result, Err(DetachedError::Unavailable(RuntimeUnavailable)));
}
#[test]
fn test_spawner_keeps_its_executor_on_a_runtime_less_thread() {
let runtime = tokio::runtime::Runtime::new().expect("test runtime");
let spawner = runtime
.block_on(async { Spawner::current() })
.expect("current");
let done = Arc::new(Notify::new());
let signal = Arc::clone(&done);
std::thread::spawn(move || spawner.spawn(async move { signal.notify_one() }))
.join()
.expect("spawning thread");
runtime.block_on(done.notified());
}
#[tokio::test]
async fn test_cancelling_waiter_does_not_cancel_owned_detached_work() {
let started = Arc::new(Notify::new());
let release = Arc::new(Notify::new());
let completed = Arc::new(Notify::new());
let waiter = {
let started = Arc::clone(&started);
let release = Arc::clone(&release);
let completed = Arc::clone(&completed);
tokio::spawn(run_detached(async move {
started.notify_one();
release.notified().await;
completed.notify_one();
}))
};
started.notified().await;
waiter.abort();
let _ = waiter.await;
release.notify_one();
tokio::time::timeout(Duration::from_secs(1), completed.notified())
.await
.expect("owned detached work must outlive its cancelled waiter");
}
#[tokio::test]
async fn test_work_starts_at_the_call_not_at_the_first_poll() {
let completed = Arc::new(Notify::new());
let signal = Arc::clone(&completed);
drop(run_detached(async move { signal.notify_one() }));
tokio::time::timeout(Duration::from_secs(1), completed.notified())
.await
.expect("work handed to the executor must run although its waiter was never polled");
}
#[test]
fn test_spawner_after_runtime_shutdown_drops_work_and_reports_abandoned() {
let runtime = tokio::runtime::Runtime::new().expect("test runtime");
let spawner = runtime
.block_on(async { Spawner::current() })
.expect("current");
drop(runtime);
let polled = Arc::new(AtomicBool::new(false));
let witness = Arc::clone(&polled);
spawner.spawn(async move { witness.store(true, Ordering::SeqCst) });
let result = futures::executor::block_on(spawner.run_detached(async {}));
assert!(!polled.load(Ordering::SeqCst));
assert_eq!(result, Err(Abandoned));
}
#[tokio::test]
async fn test_panicking_detached_work_is_abandoned() {
let result: Result<(), DetachedError> = run_detached(async {
panic!("injected detached task failure");
})
.await;
assert_eq!(result, Err(DetachedError::Abandoned(Abandoned)));
}
#[test]
fn test_run_blocking_outside_a_runtime_is_unavailable() {
let result = futures::executor::block_on(run_blocking(|| ()));
assert_eq!(result, Err(DetachedError::Unavailable(RuntimeUnavailable)));
}
#[tokio::test]
async fn test_dropping_the_waiter_does_not_cancel_blocking_work() {
let (sender, receiver) = std::sync::mpsc::channel();
drop(run_blocking(move || sender.send(()).expect("receiver alive")));
tokio::task::spawn_blocking(move || receiver.recv_timeout(Duration::from_secs(10)))
.await
.expect("waiting thread")
.expect("blocking work must run although its waiter was dropped");
}
#[tokio::test]
async fn test_panicking_blocking_work_is_abandoned() {
let result: Result<(), DetachedError> =
run_blocking(|| panic!("injected blocking failure")).await;
assert_eq!(result, Err(DetachedError::Abandoned(Abandoned)));
}
}