1use crate::{App, PlatformDispatcher};
2use async_task::Runnable;
3use futures::channel::mpsc;
4use smol::prelude::*;
5use std::mem::ManuallyDrop;
6use std::panic::Location;
7use std::thread::{self, ThreadId};
8use std::{
9 fmt::Debug,
10 marker::PhantomData,
11 mem,
12 num::NonZeroUsize,
13 pin::Pin,
14 rc::Rc,
15 sync::{
16 Arc,
17 atomic::{AtomicUsize, Ordering::SeqCst},
18 },
19 task::{Context, Poll},
20 time::{Duration, Instant},
21};
22use util::TryFutureExt;
23use waker_fn::waker_fn;
24
25#[cfg(any(test, feature = "test-support"))]
26use rand::rngs::StdRng;
27
28/// A pointer to the executor that is currently running,
29/// for spawning background tasks.
30#[derive(Clone)]
31pub struct BackgroundExecutor {
32 #[doc(hidden)]
33 pub dispatcher: Arc<dyn PlatformDispatcher>,
34}
35
36/// A pointer to the executor that is currently running,
37/// for spawning tasks on the main thread.
38///
39/// This is intentionally `!Send` via the `not_send` marker field. This is because
40/// `ForegroundExecutor::spawn` does not require `Send` but checks at runtime that the future is
41/// only polled from the same thread it was spawned from. These checks would fail when spawning
42/// foreground tasks from from background threads.
43#[derive(Clone)]
44pub struct ForegroundExecutor {
45 #[doc(hidden)]
46 pub dispatcher: Arc<dyn PlatformDispatcher>,
47 not_send: PhantomData<Rc<()>>,
48}
49
50/// Task is a primitive that allows work to happen in the background.
51///
52/// It implements [`Future`] so you can `.await` on it.
53///
54/// If you drop a task it will be cancelled immediately. Calling [`Task::detach`] allows
55/// the task to continue running, but with no way to return a value.
56#[must_use]
57#[derive(Debug)]
58pub struct Task<T>(TaskState<T>);
59
60#[derive(Debug)]
61enum TaskState<T> {
62 /// A task that is ready to return a value
63 Ready(Option<T>),
64
65 /// A task that is currently running.
66 Spawned(async_task::Task<T>),
67}
68
69impl<T> Task<T> {
70 /// Creates a new task that will resolve with the value
71 pub fn ready(val: T) -> Self {
72 Task(TaskState::Ready(Some(val)))
73 }
74
75 /// Detaching a task runs it to completion in the background
76 pub fn detach(self) {
77 match self {
78 Task(TaskState::Ready(_)) => {}
79 Task(TaskState::Spawned(task)) => task.detach(),
80 }
81 }
82}
83
84impl<E, T> Task<Result<T, E>>
85where
86 T: 'static,
87 E: 'static + Debug,
88{
89 /// Run the task to completion in the background and log any
90 /// errors that occur.
91 #[track_caller]
92 pub fn detach_and_log_err(self, cx: &App) {
93 let location = core::panic::Location::caller();
94 cx.foreground_executor()
95 .spawn(self.log_tracked_err(*location))
96 .detach();
97 }
98}
99
100impl<T> Future for Task<T> {
101 type Output = T;
102
103 fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
104 match unsafe { self.get_unchecked_mut() } {
105 Task(TaskState::Ready(val)) => Poll::Ready(val.take().unwrap()),
106 Task(TaskState::Spawned(task)) => task.poll(cx),
107 }
108 }
109}
110
111/// A task label is an opaque identifier that you can use to
112/// refer to a task in tests.
113#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
114pub struct TaskLabel(NonZeroUsize);
115
116impl Default for TaskLabel {
117 fn default() -> Self {
118 Self::new()
119 }
120}
121
122impl TaskLabel {
123 /// Construct a new task label.
124 pub fn new() -> Self {
125 static NEXT_TASK_LABEL: AtomicUsize = AtomicUsize::new(1);
126 Self(NEXT_TASK_LABEL.fetch_add(1, SeqCst).try_into().unwrap())
127 }
128}
129
130type AnyLocalFuture<R> = Pin<Box<dyn 'static + Future<Output = R>>>;
131
132type AnyFuture<R> = Pin<Box<dyn 'static + Send + Future<Output = R>>>;
133
134/// BackgroundExecutor lets you run things on background threads.
135/// In production this is a thread pool with no ordering guarantees.
136/// In tests this is simulated by running tasks one by one in a deterministic
137/// (but arbitrary) order controlled by the `SEED` environment variable.
138impl BackgroundExecutor {
139 #[doc(hidden)]
140 pub fn new(dispatcher: Arc<dyn PlatformDispatcher>) -> Self {
141 Self { dispatcher }
142 }
143
144 /// Enqueues the given future to be run to completion on a background thread.
145 pub fn spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
146 where
147 R: Send + 'static,
148 {
149 self.spawn_internal::<R>(Box::pin(future), None)
150 }
151
152 /// Enqueues the given future to be run to completion on a background thread.
153 /// The given label can be used to control the priority of the task in tests.
154 pub fn spawn_labeled<R>(
155 &self,
156 label: TaskLabel,
157 future: impl Future<Output = R> + Send + 'static,
158 ) -> Task<R>
159 where
160 R: Send + 'static,
161 {
162 self.spawn_internal::<R>(Box::pin(future), Some(label))
163 }
164
165 fn spawn_internal<R: Send + 'static>(
166 &self,
167 future: AnyFuture<R>,
168 label: Option<TaskLabel>,
169 ) -> Task<R> {
170 let dispatcher = self.dispatcher.clone();
171 let (runnable, task) = async_task::spawn(tracy_client::fiber!(future), move |runnable| {
172 dispatcher.dispatch(runnable, label)
173 });
174 runnable.schedule();
175 Task(TaskState::Spawned(task))
176 }
177
178 /// Used by the test harness to run an async test in a synchronous fashion.
179 #[cfg(any(test, feature = "test-support"))]
180 #[track_caller]
181 pub fn block_test<R>(&self, future: impl Future<Output = R>) -> R {
182 if let Ok(value) = self.block_internal(false, future, None) {
183 value
184 } else {
185 unreachable!()
186 }
187 }
188
189 /// Block the current thread until the given future resolves.
190 /// Consider using `block_with_timeout` instead.
191 pub fn block<R>(&self, future: impl Future<Output = R>) -> R {
192 if let Ok(value) = self.block_internal(true, future, None) {
193 value
194 } else {
195 unreachable!()
196 }
197 }
198
199 #[cfg(not(any(test, feature = "test-support")))]
200 pub(crate) fn block_internal<Fut: Future>(
201 &self,
202 _background_only: bool,
203 future: Fut,
204 timeout: Option<Duration>,
205 ) -> Result<Fut::Output, impl Future<Output = Fut::Output> + use<Fut>> {
206 use std::time::Instant;
207
208 let mut future = Box::pin(future);
209 if timeout == Some(Duration::ZERO) {
210 return Err(future);
211 }
212 let deadline = timeout.map(|timeout| Instant::now() + timeout);
213
214 let unparker = self.dispatcher.unparker();
215 let waker = waker_fn(move || {
216 unparker.unpark();
217 });
218 let mut cx = std::task::Context::from_waker(&waker);
219
220 loop {
221 match future.as_mut().poll(&mut cx) {
222 Poll::Ready(result) => return Ok(result),
223 Poll::Pending => {
224 let timeout =
225 deadline.map(|deadline| deadline.saturating_duration_since(Instant::now()));
226 if !self.dispatcher.park(timeout)
227 && deadline.is_some_and(|deadline| deadline < Instant::now())
228 {
229 return Err(future);
230 }
231 }
232 }
233 }
234 }
235
236 #[cfg(any(test, feature = "test-support"))]
237 #[track_caller]
238 pub(crate) fn block_internal<Fut: Future>(
239 &self,
240 background_only: bool,
241 future: Fut,
242 timeout: Option<Duration>,
243 ) -> Result<Fut::Output, impl Future<Output = Fut::Output> + use<Fut>> {
244 use std::sync::atomic::AtomicBool;
245
246 let mut future = Box::pin(future);
247 if timeout == Some(Duration::ZERO) {
248 return Err(future);
249 }
250 let Some(dispatcher) = self.dispatcher.as_test() else {
251 return Err(future);
252 };
253
254 let mut max_ticks = if timeout.is_some() {
255 dispatcher.gen_block_on_ticks()
256 } else {
257 usize::MAX
258 };
259 let unparker = self.dispatcher.unparker();
260 let awoken = Arc::new(AtomicBool::new(false));
261 let waker = waker_fn({
262 let awoken = awoken.clone();
263 move || {
264 awoken.store(true, SeqCst);
265 unparker.unpark();
266 }
267 });
268 let mut cx = std::task::Context::from_waker(&waker);
269
270 loop {
271 match future.as_mut().poll(&mut cx) {
272 Poll::Ready(result) => return Ok(result),
273 Poll::Pending => {
274 if max_ticks == 0 {
275 return Err(future);
276 }
277 max_ticks -= 1;
278
279 if !dispatcher.tick(background_only) {
280 if awoken.swap(false, SeqCst) {
281 continue;
282 }
283
284 if !dispatcher.parking_allowed() {
285 if dispatcher.advance_clock_to_next_delayed() {
286 continue;
287 }
288 let mut backtrace_message = String::new();
289 let mut waiting_message = String::new();
290 if let Some(backtrace) = dispatcher.waiting_backtrace() {
291 backtrace_message =
292 format!("\nbacktrace of waiting future:\n{:?}", backtrace);
293 }
294 if let Some(waiting_hint) = dispatcher.waiting_hint() {
295 waiting_message = format!("\n waiting on: {}\n", waiting_hint);
296 }
297 panic!(
298 "parked with nothing left to run{waiting_message}{backtrace_message}",
299 )
300 }
301 self.dispatcher.park(None);
302 }
303 }
304 }
305 }
306 }
307
308 /// Block the current thread until the given future resolves
309 /// or `duration` has elapsed.
310 pub fn block_with_timeout<Fut: Future>(
311 &self,
312 duration: Duration,
313 future: Fut,
314 ) -> Result<Fut::Output, impl Future<Output = Fut::Output> + use<Fut>> {
315 self.block_internal(true, future, Some(duration))
316 }
317
318 /// Scoped lets you start a number of tasks and waits
319 /// for all of them to complete before returning.
320 pub async fn scoped<'scope, F>(&self, scheduler: F)
321 where
322 F: FnOnce(&mut Scope<'scope>),
323 {
324 let mut scope = Scope::new(self.clone());
325 (scheduler)(&mut scope);
326 let spawned = mem::take(&mut scope.futures)
327 .into_iter()
328 .map(|f| self.spawn(f))
329 .collect::<Vec<_>>();
330 for task in spawned {
331 task.await;
332 }
333 }
334
335 /// Get the current time.
336 ///
337 /// Calling this instead of `std::time::Instant::now` allows the use
338 /// of fake timers in tests.
339 pub fn now(&self) -> Instant {
340 self.dispatcher.now()
341 }
342
343 /// Returns a task that will complete after the given duration.
344 /// Depending on other concurrent tasks the elapsed duration may be longer
345 /// than requested.
346 pub fn timer(&self, duration: Duration) -> Task<()> {
347 if duration.is_zero() {
348 return Task::ready(());
349 }
350 let (runnable, task) = async_task::spawn(async move {}, {
351 let dispatcher = self.dispatcher.clone();
352 move |runnable| dispatcher.dispatch_after(duration, runnable)
353 });
354 runnable.schedule();
355 Task(TaskState::Spawned(task))
356 }
357
358 /// in tests, start_waiting lets you indicate which task is waiting (for debugging only)
359 #[cfg(any(test, feature = "test-support"))]
360 pub fn start_waiting(&self) {
361 self.dispatcher.as_test().unwrap().start_waiting();
362 }
363
364 /// in tests, removes the debugging data added by start_waiting
365 #[cfg(any(test, feature = "test-support"))]
366 pub fn finish_waiting(&self) {
367 self.dispatcher.as_test().unwrap().finish_waiting();
368 }
369
370 /// in tests, run an arbitrary number of tasks (determined by the SEED environment variable)
371 #[cfg(any(test, feature = "test-support"))]
372 pub fn simulate_random_delay(&self) -> impl Future<Output = ()> + use<> {
373 self.dispatcher.as_test().unwrap().simulate_random_delay()
374 }
375
376 /// in tests, indicate that a given task from `spawn_labeled` should run after everything else
377 #[cfg(any(test, feature = "test-support"))]
378 pub fn deprioritize(&self, task_label: TaskLabel) {
379 self.dispatcher.as_test().unwrap().deprioritize(task_label)
380 }
381
382 /// in tests, move time forward. This does not run any tasks, but does make `timer`s ready.
383 #[cfg(any(test, feature = "test-support"))]
384 pub fn advance_clock(&self, duration: Duration) {
385 self.dispatcher.as_test().unwrap().advance_clock(duration)
386 }
387
388 /// in tests, run one task.
389 #[cfg(any(test, feature = "test-support"))]
390 pub fn tick(&self) -> bool {
391 self.dispatcher.as_test().unwrap().tick(false)
392 }
393
394 /// in tests, run all tasks that are ready to run. If after doing so
395 /// the test still has outstanding tasks, this will panic. (See also [`Self::allow_parking`])
396 #[cfg(any(test, feature = "test-support"))]
397 pub fn run_until_parked(&self) {
398 self.dispatcher.as_test().unwrap().run_until_parked()
399 }
400
401 /// in tests, prevents `run_until_parked` from panicking if there are outstanding tasks.
402 /// This is useful when you are integrating other (non-GPUI) futures, like disk access, that
403 /// do take real async time to run.
404 #[cfg(any(test, feature = "test-support"))]
405 pub fn allow_parking(&self) {
406 self.dispatcher.as_test().unwrap().allow_parking();
407 }
408
409 /// undoes the effect of [`Self::allow_parking`].
410 #[cfg(any(test, feature = "test-support"))]
411 pub fn forbid_parking(&self) {
412 self.dispatcher.as_test().unwrap().forbid_parking();
413 }
414
415 /// adds detail to the "parked with nothing let to run" message.
416 #[cfg(any(test, feature = "test-support"))]
417 pub fn set_waiting_hint(&self, msg: Option<String>) {
418 self.dispatcher.as_test().unwrap().set_waiting_hint(msg);
419 }
420
421 /// in tests, returns the rng used by the dispatcher and seeded by the `SEED` environment variable
422 #[cfg(any(test, feature = "test-support"))]
423 pub fn rng(&self) -> StdRng {
424 self.dispatcher.as_test().unwrap().rng()
425 }
426
427 /// How many CPUs are available to the dispatcher.
428 pub fn num_cpus(&self) -> usize {
429 #[cfg(any(test, feature = "test-support"))]
430 return 4;
431
432 #[cfg(not(any(test, feature = "test-support")))]
433 return num_cpus::get();
434 }
435
436 /// Whether we're on the main thread.
437 pub fn is_main_thread(&self) -> bool {
438 self.dispatcher.is_main_thread()
439 }
440
441 #[cfg(any(test, feature = "test-support"))]
442 /// in tests, control the number of ticks that `block_with_timeout` will run before timing out.
443 pub fn set_block_on_ticks(&self, range: std::ops::RangeInclusive<usize>) {
444 self.dispatcher.as_test().unwrap().set_block_on_ticks(range);
445 }
446}
447
448/// ForegroundExecutor runs things on the main thread.
449impl ForegroundExecutor {
450 /// Creates a new ForegroundExecutor from the given PlatformDispatcher.
451 pub fn new(dispatcher: Arc<dyn PlatformDispatcher>) -> Self {
452 Self {
453 dispatcher,
454 not_send: PhantomData,
455 }
456 }
457
458 /// Enqueues the given Task to run on the main thread at some point in the future.
459 #[track_caller]
460 pub fn spawn<R>(&self, future: impl Future<Output = R> + 'static) -> Task<R>
461 where
462 R: 'static,
463 {
464 let dispatcher = self.dispatcher.clone();
465
466 #[track_caller]
467 fn inner<R: 'static>(
468 dispatcher: Arc<dyn PlatformDispatcher>,
469 future: AnyLocalFuture<R>,
470 ) -> Task<R> {
471 let (runnable, task) = spawn_local_with_source_location(future, move |runnable| {
472 dispatcher.dispatch_on_main_thread(runnable)
473 });
474 runnable.schedule();
475 Task(TaskState::Spawned(task))
476 }
477 inner::<R>(dispatcher, Box::pin(future))
478 }
479}
480
481/// Variant of `async_task::spawn_local` that includes the source location of the spawn in panics.
482///
483/// Copy-modified from:
484/// <https://github.com/smol-rs/async-task/blob/ca9dbe1db9c422fd765847fa91306e30a6bb58a9/src/runnable.rs#L405>
485#[track_caller]
486fn spawn_local_with_source_location<Fut, S>(
487 future: Fut,
488 schedule: S,
489) -> (Runnable<()>, async_task::Task<Fut::Output, ()>)
490where
491 Fut: Future + 'static,
492 Fut::Output: 'static,
493 S: async_task::Schedule<()> + Send + Sync + 'static,
494{
495 #[inline]
496 fn thread_id() -> ThreadId {
497 std::thread_local! {
498 static ID: ThreadId = thread::current().id();
499 }
500 ID.try_with(|id| *id)
501 .unwrap_or_else(|_| thread::current().id())
502 }
503
504 struct Checked<F> {
505 id: ThreadId,
506 inner: ManuallyDrop<F>,
507 location: &'static Location<'static>,
508 }
509
510 impl<F> Drop for Checked<F> {
511 fn drop(&mut self) {
512 assert!(
513 self.id == thread_id(),
514 "local task dropped by a thread that didn't spawn it. Task spawned at {}",
515 self.location
516 );
517 unsafe {
518 ManuallyDrop::drop(&mut self.inner);
519 }
520 }
521 }
522
523 impl<F: Future> Future for Checked<F> {
524 type Output = F::Output;
525
526 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
527 assert!(
528 self.id == thread_id(),
529 "local task polled by a thread that didn't spawn it. Task spawned at {}",
530 self.location
531 );
532 unsafe { self.map_unchecked_mut(|c| &mut *c.inner).poll(cx) }
533 }
534 }
535
536 // Wrap the future into one that checks which thread it's on.
537 let future = Checked {
538 id: thread_id(),
539 inner: ManuallyDrop::new(future),
540 location: Location::caller(),
541 };
542
543 unsafe { async_task::spawn_unchecked(future, schedule) }
544}
545
546/// Scope manages a set of tasks that are enqueued and waited on together. See [`BackgroundExecutor::scoped`].
547pub struct Scope<'a> {
548 executor: BackgroundExecutor,
549 futures: Vec<Pin<Box<dyn Future<Output = ()> + Send + 'static>>>,
550 tx: Option<mpsc::Sender<()>>,
551 rx: mpsc::Receiver<()>,
552 lifetime: PhantomData<&'a ()>,
553}
554
555impl<'a> Scope<'a> {
556 fn new(executor: BackgroundExecutor) -> Self {
557 let (tx, rx) = mpsc::channel(1);
558 Self {
559 executor,
560 tx: Some(tx),
561 rx,
562 futures: Default::default(),
563 lifetime: PhantomData,
564 }
565 }
566
567 /// How many CPUs are available to the dispatcher.
568 pub fn num_cpus(&self) -> usize {
569 self.executor.num_cpus()
570 }
571
572 /// Spawn a future into this scope.
573 pub fn spawn<F>(&mut self, f: F)
574 where
575 F: Future<Output = ()> + Send + 'a,
576 {
577 let tx = self.tx.clone().unwrap();
578
579 // SAFETY: The 'a lifetime is guaranteed to outlive any of these futures because
580 // dropping this `Scope` blocks until all of the futures have resolved.
581 let f = unsafe {
582 mem::transmute::<
583 Pin<Box<dyn Future<Output = ()> + Send + 'a>>,
584 Pin<Box<dyn Future<Output = ()> + Send + 'static>>,
585 >(Box::pin(async move {
586 f.await;
587 drop(tx);
588 }))
589 };
590 self.futures.push(f);
591 }
592}
593
594impl Drop for Scope<'_> {
595 fn drop(&mut self) {
596 self.tx.take().unwrap();
597
598 // Wait until the channel is closed, which means that all of the spawned
599 // futures have resolved.
600 self.executor.block(self.rx.next());
601 }
602}