1use crate::{AppContext, PlatformDispatcher};
2use futures::{channel::mpsc, pin_mut, FutureExt};
3use smol::prelude::*;
4use std::{
5 fmt::Debug,
6 marker::PhantomData,
7 mem,
8 pin::Pin,
9 rc::Rc,
10 sync::{
11 atomic::{AtomicBool, Ordering::SeqCst},
12 Arc,
13 },
14 task::{Context, Poll},
15 time::Duration,
16};
17use util::TryFutureExt;
18use waker_fn::waker_fn;
19
20#[derive(Clone)]
21pub struct BackgroundExecutor {
22 dispatcher: Arc<dyn PlatformDispatcher>,
23}
24
25#[derive(Clone)]
26pub struct ForegroundExecutor {
27 dispatcher: Arc<dyn PlatformDispatcher>,
28 not_send: PhantomData<Rc<()>>,
29}
30
31#[must_use]
32pub enum Task<T> {
33 Ready(Option<T>),
34 Spawned(async_task::Task<T>),
35}
36
37impl<T> Task<T> {
38 pub fn ready(val: T) -> Self {
39 Task::Ready(Some(val))
40 }
41
42 pub fn detach(self) {
43 match self {
44 Task::Ready(_) => {}
45 Task::Spawned(task) => task.detach(),
46 }
47 }
48}
49
50impl<E, T> Task<Result<T, E>>
51where
52 T: 'static + Send,
53 E: 'static + Send + Debug,
54{
55 pub fn detach_and_log_err(self, cx: &mut AppContext) {
56 cx.executor().spawn(self.log_err()).detach();
57 }
58}
59
60impl<T> Future for Task<T> {
61 type Output = T;
62
63 fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
64 match unsafe { self.get_unchecked_mut() } {
65 Task::Ready(val) => Poll::Ready(val.take().unwrap()),
66 Task::Spawned(task) => task.poll(cx),
67 }
68 }
69}
70
71impl BackgroundExecutor {
72 pub fn new(dispatcher: Arc<dyn PlatformDispatcher>) -> Self {
73 Self { dispatcher }
74 }
75
76 /// Enqueues the given closure to be run on any thread. The closure returns
77 /// a future which will be run to completion on any available thread.
78 pub fn spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
79 where
80 R: Send + 'static,
81 {
82 let dispatcher = self.dispatcher.clone();
83 let (runnable, task) =
84 async_task::spawn(future, move |runnable| dispatcher.dispatch(runnable));
85 runnable.schedule();
86 Task::Spawned(task)
87 }
88
89 pub fn block<R>(&self, future: impl Future<Output = R>) -> R {
90 pin_mut!(future);
91 let (parker, unparker) = parking::pair();
92 let awoken = Arc::new(AtomicBool::new(false));
93 let awoken2 = awoken.clone();
94
95 let waker = waker_fn(move || {
96 awoken2.store(true, SeqCst);
97 unparker.unpark();
98 });
99 let mut cx = std::task::Context::from_waker(&waker);
100
101 loop {
102 match future.as_mut().poll(&mut cx) {
103 Poll::Ready(result) => return result,
104 Poll::Pending => {
105 if !self.dispatcher.poll() {
106 if awoken.swap(false, SeqCst) {
107 continue;
108 }
109
110 #[cfg(any(test, feature = "test-support"))]
111 if let Some(test) = self.dispatcher.as_test() {
112 if !test.parking_allowed() {
113 let mut backtrace_message = String::new();
114 if let Some(backtrace) = test.waiting_backtrace() {
115 backtrace_message =
116 format!("\nbacktrace of waiting future:\n{:?}", backtrace);
117 }
118 panic!("parked with nothing left to run\n{:?}", backtrace_message)
119 }
120 }
121 parker.park();
122 }
123 }
124 }
125 }
126 }
127
128 pub fn block_with_timeout<R>(
129 &self,
130 duration: Duration,
131 future: impl Future<Output = R>,
132 ) -> Result<R, impl Future<Output = R>> {
133 let mut future = Box::pin(future.fuse());
134 if duration.is_zero() {
135 return Err(future);
136 }
137
138 let mut timer = self.timer(duration).fuse();
139 let timeout = async {
140 futures::select_biased! {
141 value = future => Ok(value),
142 _ = timer => Err(()),
143 }
144 };
145 match self.block(timeout) {
146 Ok(value) => Ok(value),
147 Err(_) => Err(future),
148 }
149 }
150
151 pub async fn scoped<'scope, F>(&self, scheduler: F)
152 where
153 F: FnOnce(&mut Scope<'scope>),
154 {
155 let mut scope = Scope::new(self.clone());
156 (scheduler)(&mut scope);
157 let spawned = mem::take(&mut scope.futures)
158 .into_iter()
159 .map(|f| self.spawn(f))
160 .collect::<Vec<_>>();
161 for task in spawned {
162 task.await;
163 }
164 }
165
166 pub fn timer(&self, duration: Duration) -> Task<()> {
167 let (runnable, task) = async_task::spawn(async move {}, {
168 let dispatcher = self.dispatcher.clone();
169 move |runnable| dispatcher.dispatch_after(duration, runnable)
170 });
171 runnable.schedule();
172 Task::Spawned(task)
173 }
174
175 #[cfg(any(test, feature = "test-support"))]
176 pub fn start_waiting(&self) {
177 self.dispatcher.as_test().unwrap().start_waiting();
178 }
179
180 #[cfg(any(test, feature = "test-support"))]
181 pub fn finish_waiting(&self) {
182 self.dispatcher.as_test().unwrap().finish_waiting();
183 }
184
185 #[cfg(any(test, feature = "test-support"))]
186 pub fn simulate_random_delay(&self) -> impl Future<Output = ()> {
187 self.spawn(self.dispatcher.as_test().unwrap().simulate_random_delay())
188 }
189
190 #[cfg(any(test, feature = "test-support"))]
191 pub fn advance_clock(&self, duration: Duration) {
192 self.dispatcher.as_test().unwrap().advance_clock(duration)
193 }
194
195 #[cfg(any(test, feature = "test-support"))]
196 pub fn run_until_parked(&self) {
197 self.dispatcher.as_test().unwrap().run_until_parked()
198 }
199
200 #[cfg(any(test, feature = "test-support"))]
201 pub fn allow_parking(&self) {
202 self.dispatcher.as_test().unwrap().allow_parking();
203 }
204
205 pub fn num_cpus(&self) -> usize {
206 num_cpus::get()
207 }
208
209 pub fn is_main_thread(&self) -> bool {
210 self.dispatcher.is_main_thread()
211 }
212}
213
214impl ForegroundExecutor {
215 pub fn new(dispatcher: Arc<dyn PlatformDispatcher>) -> Self {
216 Self {
217 dispatcher,
218 not_send: PhantomData,
219 }
220 }
221
222 /// Enqueues the given closure to be run on any thread. The closure returns
223 /// a future which will be run to completion on any available thread.
224 pub fn spawn<R>(&self, future: impl Future<Output = R> + 'static) -> Task<R>
225 where
226 R: 'static,
227 {
228 let dispatcher = self.dispatcher.clone();
229 let (runnable, task) = async_task::spawn_local(future, move |runnable| {
230 dispatcher.dispatch_on_main_thread(runnable)
231 });
232 runnable.schedule();
233 Task::Spawned(task)
234 }
235}
236
237pub struct Scope<'a> {
238 executor: BackgroundExecutor,
239 futures: Vec<Pin<Box<dyn Future<Output = ()> + Send + 'static>>>,
240 tx: Option<mpsc::Sender<()>>,
241 rx: mpsc::Receiver<()>,
242 lifetime: PhantomData<&'a ()>,
243}
244
245impl<'a> Scope<'a> {
246 fn new(executor: BackgroundExecutor) -> Self {
247 let (tx, rx) = mpsc::channel(1);
248 Self {
249 executor,
250 tx: Some(tx),
251 rx,
252 futures: Default::default(),
253 lifetime: PhantomData,
254 }
255 }
256
257 pub fn spawn<F>(&mut self, f: F)
258 where
259 F: Future<Output = ()> + Send + 'a,
260 {
261 let tx = self.tx.clone().unwrap();
262
263 // Safety: The 'a lifetime is guaranteed to outlive any of these futures because
264 // dropping this `Scope` blocks until all of the futures have resolved.
265 let f = unsafe {
266 mem::transmute::<
267 Pin<Box<dyn Future<Output = ()> + Send + 'a>>,
268 Pin<Box<dyn Future<Output = ()> + Send + 'static>>,
269 >(Box::pin(async move {
270 f.await;
271 drop(tx);
272 }))
273 };
274 self.futures.push(f);
275 }
276}
277
278impl<'a> Drop for Scope<'a> {
279 fn drop(&mut self) {
280 self.tx.take().unwrap();
281
282 // Wait until the channel is closed, which means that all of the spawned
283 // futures have resolved.
284 self.executor.block(self.rx.next());
285 }
286}