Skip to main content

graphrt_core/
task.rs

1//! One tokio task type for many spawn sites.
2//!
3//! `tokio::spawn` and `tokio::task::spawn_blocking` are generic over the
4//! future / closure, and each type compiles its own task machinery (poll,
5//! harness, join handle: about 1.9 KiB per call site on x86_64). Stores run
6//! every operation on the blocking pool, so a store with 30 methods paid for 30
7//! task types. [`spawn`] and [`spawn_blocking`] erase the future / closure
8//! behind a box (one allocation, which a spawn makes anyway), so the machinery
9//! exists once for each.
10
11use std::any::Any;
12use std::future::Future;
13use std::marker::PhantomData;
14use std::pin::Pin;
15use std::task::{Context, Poll};
16
17type ErasedFuture = Pin<Box<dyn Future<Output = ()> + Send>>;
18
19/// Spawns `future` on the current runtime, like `tokio::spawn`.
20pub fn spawn(future: impl Future<Output = ()> + Send + 'static) -> tokio::task::JoinHandle<()> {
21    spawn_erased(Box::pin(future))
22}
23
24#[inline(never)]
25fn spawn_erased(future: ErasedFuture) -> tokio::task::JoinHandle<()> {
26    tokio::spawn(future)
27}
28
29type ErasedJob = Box<dyn FnOnce() -> Box<dyn Any + Send> + Send>;
30type ErasedOutput = Result<Box<dyn Any + Send>, tokio::task::JoinError>;
31
32/// Runs `job` on the blocking pool, like `tokio::task::spawn_blocking`.
33///
34/// Like an `async fn`, the job is handed to the pool when the returned future
35/// is first polled, not when it is created. The future resolves to the
36/// `JoinError` when the job panicked or the runtime shut down.
37pub fn spawn_blocking<T: Send + 'static>(job: impl FnOnce() -> T + Send + 'static) -> Blocking<T> {
38    let erased: ErasedJob = Box::new(move || Box::new(job()) as Box<dyn Any + Send>);
39    Blocking { job: ErasedBlocking { job: Some(erased), handle: None }, output: PhantomData }
40}
41
42/// The future of [`spawn_blocking`].
43///
44/// An `async fn` here was a state machine per job type around the join handle,
45/// inlined into every caller's own state machine; here the spawn and the poll
46/// are one non-generic function and only the downcast is per type (about
47/// 19 KiB less in the gateway core).
48#[must_use = "a blocking job runs only once its future is polled"]
49pub struct Blocking<T> {
50    job: ErasedBlocking,
51    output: PhantomData<fn() -> T>,
52}
53
54impl<T> std::fmt::Debug for Blocking<T> {
55    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56        f.debug_struct("Blocking").field("spawned", &self.job.handle.is_some()).finish_non_exhaustive()
57    }
58}
59
60struct ErasedBlocking {
61    job: Option<ErasedJob>,
62    handle: Option<tokio::task::JoinHandle<Box<dyn Any + Send>>>,
63}
64
65impl<T: 'static> Future for Blocking<T> {
66    type Output = Result<T, tokio::task::JoinError>;
67
68    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
69        let output = match poll_erased(&mut self.get_mut().job, cx) {
70            Poll::Ready(output) => output?,
71            Poll::Pending => return Poll::Pending,
72        };
73        // The erased job returns exactly a `T`, so the downcast cannot fail.
74        match output.downcast::<T>() {
75            Ok(value) => Poll::Ready(Ok(*value)),
76            Err(_) => unreachable!("blocking job returned another type"),
77        }
78    }
79}
80
81#[inline(never)]
82fn poll_erased(state: &mut ErasedBlocking, cx: &mut Context<'_>) -> Poll<ErasedOutput> {
83    if let Some(job) = state.job.take() {
84        state.handle = Some(tokio::task::spawn_blocking(job));
85    }
86    match &mut state.handle {
87        Some(handle) => Pin::new(handle).poll(cx),
88        // Not reached: the job was spawned just above or by an earlier poll.
89        None => Poll::Pending,
90    }
91}
92
93#[cfg(test)]
94mod tests {
95    #[tokio::test]
96    async fn returns_the_value_and_reports_panics() {
97        assert_eq!(super::spawn_blocking(|| 6 * 7).await.unwrap(), 42);
98        assert_eq!(super::spawn_blocking(|| String::from("x")).await.unwrap(), "x");
99        let panicked = super::spawn_blocking(|| -> u8 { std::panic::panic_any("boom") }).await;
100        assert!(panicked.unwrap_err().is_panic());
101        let (sender, receiver) = tokio::sync::oneshot::channel();
102        super::spawn(async move { sender.send(7).unwrap() }).await.unwrap();
103        assert_eq!(receiver.await.unwrap(), 7);
104    }
105
106    #[tokio::test]
107    async fn the_job_starts_when_first_polled() {
108        use std::sync::Arc;
109        use std::sync::atomic::{AtomicBool, Ordering};
110        let ran = Arc::new(AtomicBool::new(false));
111        let flag = ran.clone();
112        let job = super::spawn_blocking(move || flag.store(true, Ordering::SeqCst));
113        // Long enough for the blocking pool to have run a job spawned eagerly.
114        std::thread::sleep(std::time::Duration::from_millis(50));
115        assert!(!ran.load(Ordering::SeqCst), "the job ran before its future was polled");
116        job.await.unwrap();
117        assert!(ran.load(Ordering::SeqCst));
118    }
119}