1use std::any::Any;
14use std::marker::PhantomData;
15
16use crossbeam_channel::{Receiver, TryRecvError};
17use futures_util::future::BoxFuture;
18
19pub type ErasedBlockingResult = Box<dyn Any + Send>;
21
22pub type BoxedBlockingWork = Box<dyn FnOnce() -> ErasedBlockingResult + Send + 'static>;
24
25pub trait AsyncSpawner: Send + Sync {
32 fn spawn_supervised(
34 &self,
35 label: &'static str,
36 task: BoxFuture<'static, ()>,
37 ) -> Result<(), SpawnError>;
38
39 fn spawn_blocking_erased(
41 &self,
42 label: &'static str,
43 work: BoxedBlockingWork,
44 ) -> Result<Receiver<ErasedBlockingResult>, SpawnError>;
45
46 fn request_cancel(&self);
48
49 fn is_cancelled(&self) -> bool;
51
52 fn shutdown(&self) -> BoxFuture<'static, ()>;
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum SpawnError {
58 Unsupported,
60 ShuttingDown,
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub enum BlockingTryRecvError {
66 Empty,
67 Disconnected,
68 TypeMismatch,
69}
70
71pub struct BlockingTaskReceiver<T> {
73 inner: Receiver<ErasedBlockingResult>,
74 marker: PhantomData<T>,
75}
76
77impl<T> BlockingTaskReceiver<T> {
78 pub fn new(inner: Receiver<ErasedBlockingResult>) -> Self {
79 Self {
80 inner,
81 marker: PhantomData,
82 }
83 }
84}
85
86impl<T> BlockingTaskReceiver<T>
87where
88 T: Send + 'static,
89{
90 pub fn try_recv(&self) -> Result<T, BlockingTryRecvError> {
91 match self.inner.try_recv() {
92 Ok(value) => value
93 .downcast::<T>()
94 .map(|typed| *typed)
95 .map_err(|_| BlockingTryRecvError::TypeMismatch),
96 Err(TryRecvError::Empty) => Err(BlockingTryRecvError::Empty),
97 Err(TryRecvError::Disconnected) => Err(BlockingTryRecvError::Disconnected),
98 }
99 }
100}
101
102pub fn spawn_blocking<T, F>(
105 spawner: &dyn AsyncSpawner,
106 label: &'static str,
107 work: F,
108) -> Result<BlockingTaskReceiver<T>, SpawnError>
109where
110 T: Send + 'static,
111 F: FnOnce() -> T + Send + 'static,
112{
113 let rx = spawner.spawn_blocking_erased(label, Box::new(move || Box::new(work())))?;
114 Ok(BlockingTaskReceiver::new(rx))
115}
116
117#[cfg(test)]
118mod tests {
119 use std::sync::Arc;
120 use std::sync::atomic::{AtomicBool, Ordering};
121
122 use crossbeam_channel::bounded;
123
124 use super::{
125 AsyncSpawner, BlockingTaskReceiver, BlockingTryRecvError, BoxedBlockingWork, SpawnError,
126 spawn_blocking,
127 };
128
129 #[derive(Default)]
130 struct MockAsyncSpawner {
131 cancelled: Arc<AtomicBool>,
132 }
133
134 impl AsyncSpawner for MockAsyncSpawner {
135 fn spawn_supervised(
136 &self,
137 _label: &'static str,
138 _task: futures_util::future::BoxFuture<'static, ()>,
139 ) -> Result<(), SpawnError> {
140 if self.cancelled.load(Ordering::SeqCst) {
141 return Err(SpawnError::ShuttingDown);
142 }
143 Ok(())
144 }
145
146 fn spawn_blocking_erased(
147 &self,
148 _label: &'static str,
149 work: BoxedBlockingWork,
150 ) -> Result<crossbeam_channel::Receiver<super::ErasedBlockingResult>, SpawnError> {
151 if self.cancelled.load(Ordering::SeqCst) {
152 return Err(SpawnError::ShuttingDown);
153 }
154 let (tx, rx) = bounded(1);
155 let _ = tx.send(work());
156 Ok(rx)
157 }
158
159 fn request_cancel(&self) {
160 self.cancelled.store(true, Ordering::SeqCst);
161 }
162
163 fn is_cancelled(&self) -> bool {
164 self.cancelled.load(Ordering::SeqCst)
165 }
166
167 fn shutdown(&self) -> futures_util::future::BoxFuture<'static, ()> {
168 let cancelled = Arc::clone(&self.cancelled);
169 Box::pin(async move {
170 cancelled.store(true, Ordering::SeqCst);
171 })
172 }
173 }
174
175 #[test]
176 fn spawn_blocking_returns_typed_value() {
177 let spawner = MockAsyncSpawner::default();
178 let rx = spawn_blocking(&spawner, "test_blocking", || 42usize)
179 .expect("spawn_blocking should succeed");
180
181 assert_eq!(rx.try_recv(), Ok(42));
182 }
183
184 #[test]
185 fn blocking_task_receiver_reports_type_mismatch() {
186 let (tx, rx) = bounded(1);
187 tx.send(Box::new("wrong-type".to_string()) as super::ErasedBlockingResult)
188 .expect("send should succeed");
189 let rx = BlockingTaskReceiver::<usize>::new(rx);
190
191 assert_eq!(rx.try_recv(), Err(BlockingTryRecvError::TypeMismatch));
192 }
193
194 #[test]
195 fn spawn_blocking_rejects_new_work_after_cancel() {
196 let spawner = MockAsyncSpawner::default();
197 spawner.request_cancel();
198
199 let result = spawn_blocking(&spawner, "test_blocking", || 42usize);
200
201 assert!(matches!(result, Err(SpawnError::ShuttingDown)));
202 }
203}