| 1 | use crate::{PlatformDispatcher, RunnableMeta}; |
| 2 | use async_task::Runnable; |
| 3 | use chrono::{DateTime, Utc}; |
| 4 | use futures::channel::oneshot; |
| 5 | use scheduler::Instant; |
| 6 | use scheduler::{ |
| 7 | Clock, LocalExecutor, Priority, Scheduler, SessionId, Task, TestScheduler, Timer, |
| 8 | spawn_dedicated_thread, |
| 9 | }; |
| 10 | #[cfg(not(target_family = "wasm"))] |
| 11 | use std::task::{Context, Poll}; |
| 12 | use std::{ |
| 13 | any::Any, |
| 14 | future::Future, |
| 15 | pin::Pin, |
| 16 | sync::{ |
| 17 | Arc, |
| 18 | atomic::{AtomicU16, Ordering}, |
| 19 | }, |
| 20 | time::Duration, |
| 21 | }; |
| 22 | |
| 23 | /// A production implementation of [`Scheduler`] that wraps a [`PlatformDispatcher`]. |
| 24 | /// |
| 25 | /// This allows GPUI to use the scheduler crate's executor types with the platform's |
| 26 | /// native dispatch mechanisms (e.g., Grand Central Dispatch on macOS). |
| 27 | pub struct PlatformScheduler { |
| 28 | dispatcher: Arc<dyn PlatformDispatcher>, |
| 29 | clock: Arc<PlatformClock>, |
| 30 | next_session_id: AtomicU16, |
| 31 | #[cfg(feature = "profiler")] |
| 32 | foreground_runnables: crate::profiler::journal::ForegroundRunnableCounter, |
| 33 | } |
| 34 | |
| 35 | impl PlatformScheduler { |
| 36 | pub fn new(dispatcher: Arc<dyn PlatformDispatcher>) -> Self { |
| 37 | Self { |
| 38 | dispatcher: dispatcher.clone(), |
| 39 | clock: Arc::new(PlatformClock { dispatcher }), |
| 40 | next_session_id: AtomicU16::new(0), |
| 41 | #[cfg(feature = "profiler")] |
| 42 | foreground_runnables: crate::profiler::journal::foreground_runnable_counter(), |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | pub fn foreground_executor(self: &Arc<Self>) -> LocalExecutor { |
| 47 | let session_id = self.next_session_id(); |
| 48 | let scheduler = Arc::downgrade(self); |
| 49 | LocalExecutor::new(session_id, self.clone(), move |runnable| { |
| 50 | if let Some(scheduler) = scheduler.upgrade() { |
| 51 | scheduler.schedule_local(session_id, runnable); |
| 52 | } |
| 53 | }) |
| 54 | } |
| 55 | |
| 56 | fn next_session_id(&self) -> SessionId { |
| 57 | SessionId::new(self.next_session_id.fetch_add(1, Ordering::SeqCst)) |
| 58 | } |
| 59 | |
| 60 | #[cfg(feature = "profiler")] |
| 61 | pub(crate) fn foreground_runnable_counter( |
| 62 | &self, |
| 63 | ) -> crate::profiler::journal::ForegroundRunnableCounter { |
| 64 | self.foreground_runnables.clone() |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | impl Scheduler for PlatformScheduler { |
| 69 | #[cfg(not(target_family = "wasm"))] |
| 70 | fn block( |
| 71 | &self, |
| 72 | _session_id: Option<SessionId>, |
| 73 | mut future: Pin<&mut dyn Future<Output = ()>>, |
| 74 | timeout: Option<Duration>, |
| 75 | ) -> bool { |
| 76 | use waker_fn::waker_fn; |
| 77 | let deadline = timeout.map(|t| Instant::now() + t); |
| 78 | let parker = parking::Parker::new(); |
| 79 | let unparker = parker.unparker(); |
| 80 | let waker = waker_fn(move || { |
| 81 | unparker.unpark(); |
| 82 | }); |
| 83 | let mut cx = Context::from_waker(&waker); |
| 84 | if let Poll::Ready(()) = future.as_mut().poll(&mut cx) { |
| 85 | return true; |
| 86 | } |
| 87 | |
| 88 | let park_deadline = |deadline: Instant| { |
| 89 | // Timer expirations are only delivered every ~15.6 milliseconds by default on Windows. |
| 90 | // We increase the resolution during this wait so that short timeouts stay reasonably short. |
| 91 | let _timer_guard = self.dispatcher.increase_timer_resolution(); |
| 92 | parker.park_deadline(deadline) |
| 93 | }; |
| 94 | |
| 95 | loop { |
| 96 | match deadline { |
| 97 | Some(deadline) if !park_deadline(deadline) && deadline <= Instant::now() => { |
| 98 | return false; |
| 99 | } |
| 100 | Some(_) => (), |
| 101 | None => parker.park(), |
| 102 | } |
| 103 | if let Poll::Ready(()) = future.as_mut().poll(&mut cx) { |
| 104 | break true; |
| 105 | } |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | fn schedule_local(&self, _session_id: SessionId, runnable: Runnable<RunnableMeta>) { |
| 110 | #[cfg(feature = "profiler")] |
| 111 | self.foreground_runnables.queued(); |
| 112 | self.dispatcher |
| 113 | .dispatch_on_main_thread(runnable, Priority::default()); |
| 114 | } |
| 115 | |
| 116 | fn schedule_background_with_priority( |
| 117 | &self, |
| 118 | runnable: Runnable<RunnableMeta>, |
| 119 | priority: Priority, |
| 120 | ) { |
| 121 | self.dispatcher.dispatch(runnable, priority); |
| 122 | } |
| 123 | |
| 124 | fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>) { |
| 125 | self.dispatcher.spawn_realtime(f); |
| 126 | } |
| 127 | |
| 128 | #[track_caller] |
| 129 | fn timer(&self, duration: Duration) -> Timer { |
| 130 | let (tx, rx) = oneshot::channel(); |
| 131 | let dispatcher = self.dispatcher.clone(); |
| 132 | |
| 133 | // Create a runnable that will send the completion signal |
| 134 | let location = std::panic::Location::caller(); |
| 135 | let (runnable, _task) = async_task::Builder::new() |
| 136 | .metadata(RunnableMeta { |
| 137 | location, |
| 138 | spawned: scheduler::SpawnTime(Instant::now()), |
| 139 | }) |
| 140 | .spawn( |
| 141 | move |_| async move { |
| 142 | let _ = tx.send(()); |
| 143 | }, |
| 144 | move |runnable| { |
| 145 | dispatcher.dispatch_after(duration, runnable); |
| 146 | }, |
| 147 | ); |
| 148 | runnable.schedule(); |
| 149 | |
| 150 | Timer::new(rx) |
| 151 | } |
| 152 | |
| 153 | fn clock(&self) -> Arc<dyn Clock> { |
| 154 | self.clock.clone() |
| 155 | } |
| 156 | |
| 157 | fn spawn_dedicated( |
| 158 | self: Arc<Self>, |
| 159 | f: Box< |
| 160 | dyn FnOnce( |
| 161 | LocalExecutor, |
| 162 | ) |
| 163 | -> Pin<Box<dyn Future<Output = Box<dyn Any + Send + Sync>> + 'static>> |
| 164 | + Send |
| 165 | + 'static, |
| 166 | >, |
| 167 | ) -> Task<Box<dyn Any + Send + Sync>> { |
| 168 | let session_id = self.next_session_id(); |
| 169 | spawn_dedicated_thread(session_id, self, move |executor| f(executor)) |
| 170 | } |
| 171 | |
| 172 | fn as_test(&self) -> Option<&TestScheduler> { |
| 173 | None |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | /// A production clock that uses the platform dispatcher's time. |
| 178 | struct PlatformClock { |
| 179 | dispatcher: Arc<dyn PlatformDispatcher>, |
| 180 | } |
| 181 | |
| 182 | impl Clock for PlatformClock { |
| 183 | fn utc_now(&self) -> DateTime<Utc> { |
| 184 | Utc::now() |
| 185 | } |
| 186 | |
| 187 | fn now(&self) -> Instant { |
| 188 | self.dispatcher.now() |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | #[cfg(all(test, not(target_family = "wasm")))] |
| 193 | mod tests { |
| 194 | use super::*; |
| 195 | use crate::RunnableVariant; |
| 196 | use scheduler::BackgroundExecutor; |
| 197 | use std::time::Instant as StdInstant; |
| 198 | |
| 199 | // `spawn_dedicated` shouldn't touch the platform dispatcher at all; |
| 200 | // panicking on every method ensures the test catches it if it does. |
| 201 | struct SmokeDispatcher; |
| 202 | |
| 203 | impl PlatformDispatcher for SmokeDispatcher { |
| 204 | fn is_main_thread(&self) -> bool { |
| 205 | false |
| 206 | } |
| 207 | fn dispatch(&self, _runnable: RunnableVariant, _priority: Priority) { |
| 208 | panic!("SmokeDispatcher should not be asked to dispatch in this test"); |
| 209 | } |
| 210 | fn dispatch_on_main_thread(&self, _runnable: RunnableVariant, _priority: Priority) { |
| 211 | panic!("SmokeDispatcher does not implement a main thread"); |
| 212 | } |
| 213 | fn dispatch_after(&self, _duration: Duration, _runnable: RunnableVariant) { |
| 214 | panic!("SmokeDispatcher does not implement timers"); |
| 215 | } |
| 216 | fn spawn_realtime(&self, _f: Box<dyn FnOnce() + Send>) { |
| 217 | panic!("SmokeDispatcher does not implement realtime"); |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | #[test] |
| 222 | fn dedicated_executor_tasks_share_one_thread() { |
| 223 | let background = |
| 224 | BackgroundExecutor::new(Arc::new(PlatformScheduler::new(Arc::new(SmokeDispatcher)))); |
| 225 | let dedicated = scheduler::DedicatedExecutor::new(&background); |
| 226 | |
| 227 | let first = dedicated.spawn(async { std::thread::current().id() }); |
| 228 | let second = dedicated.spawn(async { std::thread::current().id() }); |
| 229 | |
| 230 | let first = futures::executor::block_on(first); |
| 231 | let second = futures::executor::block_on(second); |
| 232 | |
| 233 | assert_eq!(first, second, "tasks must share the dedicated thread"); |
| 234 | assert_ne!( |
| 235 | first, |
| 236 | std::thread::current().id(), |
| 237 | "dedicated tasks must not run on the spawning thread" |
| 238 | ); |
| 239 | } |
| 240 | |
| 241 | #[test] |
| 242 | fn spawn_dedicated_runs_on_a_real_separate_thread() { |
| 243 | let background = |
| 244 | BackgroundExecutor::new(Arc::new(PlatformScheduler::new(Arc::new(SmokeDispatcher)))); |
| 245 | let started = StdInstant::now(); |
| 246 | let task = background.spawn_dedicated(|_executor| async move { |
| 247 | // A genuine blocking syscall on the dedicated thread. If |
| 248 | // `spawn_dedicated` were running the future on any shared |
| 249 | // executor, this would stall that executor. |
| 250 | let thread_id_before = std::thread::current().id(); |
| 251 | std::thread::sleep(Duration::from_millis(50)); |
| 252 | let thread_id_after = std::thread::current().id(); |
| 253 | assert_eq!(thread_id_before, thread_id_after); |
| 254 | (thread_id_before, "slept") |
| 255 | }); |
| 256 | let (dedicated_thread_id, message) = futures::executor::block_on(task); |
| 257 | let elapsed = started.elapsed(); |
| 258 | assert_eq!(message, "slept"); |
| 259 | assert_ne!( |
| 260 | dedicated_thread_id, |
| 261 | std::thread::current().id(), |
| 262 | "dedicated future ran on the test thread" |
| 263 | ); |
| 264 | assert!( |
| 265 | elapsed >= Duration::from_millis(40), |
| 266 | "expected the dedicated thread to genuinely sleep, elapsed = {:?}", |
| 267 | elapsed |
| 268 | ); |
| 269 | } |
| 270 | |
| 271 | #[test] |
| 272 | fn spawn_dedicated_returns_not_send_future_output() { |
| 273 | // The whole point of `spawn_dedicated` is that the future can be |
| 274 | // `!Send`. Constructing one with `Rc<RefCell<_>>` ensures the |
| 275 | // signature actually permits it. |
| 276 | use std::cell::RefCell; |
| 277 | use std::rc::Rc; |
| 278 | |
| 279 | let background = |
| 280 | BackgroundExecutor::new(Arc::new(PlatformScheduler::new(Arc::new(SmokeDispatcher)))); |
| 281 | let task = background.spawn_dedicated(|_executor| async move { |
| 282 | let state = Rc::new(RefCell::new(0_i32)); |
| 283 | for _ in 0..3 { |
| 284 | *state.borrow_mut() += 1; |
| 285 | } |
| 286 | *state.borrow() |
| 287 | }); |
| 288 | let output = futures::executor::block_on(task); |
| 289 | assert_eq!(output, 3); |
| 290 | } |
| 291 | |
| 292 | #[test] |
| 293 | fn spawn_dedicated_dropping_task_cancels_future() { |
| 294 | use parking_lot::Mutex; |
| 295 | use std::sync::mpsc; |
| 296 | |
| 297 | let background = |
| 298 | BackgroundExecutor::new(Arc::new(PlatformScheduler::new(Arc::new(SmokeDispatcher)))); |
| 299 | |
| 300 | let (started_tx, started_rx) = mpsc::channel::<()>(); |
| 301 | let (after_park_tx, after_park_rx) = mpsc::channel::<()>(); |
| 302 | let observed_post_await_write = Arc::new(Mutex::new(false)); |
| 303 | |
| 304 | let task = { |
| 305 | let observed_post_await_write = observed_post_await_write.clone(); |
| 306 | background.spawn_dedicated(move |_executor| async move { |
| 307 | // Announce that the future is live on the dedicated thread. |
| 308 | started_tx |
| 309 | .send(()) |
| 310 | .expect("started signal must be received"); |
| 311 | // Park forever. Dropping the `Task` must cancel us here so |
| 312 | // the code below this `await` never runs. |
| 313 | futures::future::pending::<()>().await; |
| 314 | *observed_post_await_write.lock() = true; |
| 315 | after_park_tx |
| 316 | .send(()) |
| 317 | .expect("after-park signal must be received"); |
| 318 | }) |
| 319 | }; |
| 320 | |
| 321 | // Wait until the dedicated future is actually parked at the await. |
| 322 | started_rx |
| 323 | .recv_timeout(Duration::from_secs(2)) |
| 324 | .expect("dedicated future failed to start"); |
| 325 | |
| 326 | // Drop the root Task: this must cancel the future. |
| 327 | drop(task); |
| 328 | |
| 329 | // If cancellation works, the future never advances past `pending`, |
| 330 | // so this recv must time out. |
| 331 | assert!( |
| 332 | after_park_rx |
| 333 | .recv_timeout(Duration::from_millis(100)) |
| 334 | .is_err(), |
| 335 | "dedicated future advanced past the await after its Task was dropped" |
| 336 | ); |
| 337 | assert!( |
| 338 | !*observed_post_await_write.lock(), |
| 339 | "dedicated future ran code past the cancellation point" |
| 340 | ); |
| 341 | } |
| 342 | |
| 343 | #[test] |
| 344 | fn spawn_dedicated_thread_tears_down_after_work_completes() { |
| 345 | use std::sync::mpsc; |
| 346 | |
| 347 | // Fires from `Drop` so we observe teardown of the dedicated future's |
| 348 | // captured state on whichever thread runs its destructor. |
| 349 | struct DropSignal { |
| 350 | tx: Option<mpsc::Sender<std::thread::ThreadId>>, |
| 351 | } |
| 352 | impl Drop for DropSignal { |
| 353 | fn drop(&mut self) { |
| 354 | if let Some(tx) = self.tx.take() { |
| 355 | let _ = tx.send(std::thread::current().id()); |
| 356 | } |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | let background = |
| 361 | BackgroundExecutor::new(Arc::new(PlatformScheduler::new(Arc::new(SmokeDispatcher)))); |
| 362 | let (started_tx, started_rx) = mpsc::channel::<std::thread::ThreadId>(); |
| 363 | let (drop_tx, drop_rx) = mpsc::channel::<std::thread::ThreadId>(); |
| 364 | |
| 365 | let task = background.spawn_dedicated(move |_executor| async move { |
| 366 | // Captured by the future's state. When the future completes and |
| 367 | // its state is dropped on the dedicated thread, this guard's |
| 368 | // `Drop` fires and reports the thread id it ran on. |
| 369 | let _guard = DropSignal { tx: Some(drop_tx) }; |
| 370 | started_tx |
| 371 | .send(std::thread::current().id()) |
| 372 | .expect("started signal must be received"); |
| 373 | // Future returns immediately. The dedicated thread should then |
| 374 | // drop the future (firing _guard), exit the recv loop, and exit. |
| 375 | }); |
| 376 | |
| 377 | let dedicated_thread_id = started_rx |
| 378 | .recv_timeout(Duration::from_secs(2)) |
| 379 | .expect("dedicated future failed to start"); |
| 380 | assert_ne!( |
| 381 | dedicated_thread_id, |
| 382 | std::thread::current().id(), |
| 383 | "dedicated future ran on the test thread" |
| 384 | ); |
| 385 | |
| 386 | // Drive the root task to completion so its body finishes. |
| 387 | futures::executor::block_on(task); |
| 388 | |
| 389 | // The guard's drop runs from the dedicated thread as it tears down |
| 390 | // the future's captured state. If the executor/recv-loop were |
| 391 | // keeping the future alive past task completion, this would hang. |
| 392 | let drop_thread_id = drop_rx |
| 393 | .recv_timeout(Duration::from_secs(2)) |
| 394 | .expect("dedicated future's captured state was not dropped after task completion"); |
| 395 | assert_eq!( |
| 396 | drop_thread_id, dedicated_thread_id, |
| 397 | "dedicated future's captured state must be dropped on the dedicated thread, not elsewhere" |
| 398 | ); |
| 399 | } |
| 400 | |
| 401 | #[test] |
| 402 | fn spawn_dedicated_detached_child_outlives_root() { |
| 403 | use std::sync::mpsc; |
| 404 | |
| 405 | let background = |
| 406 | BackgroundExecutor::new(Arc::new(PlatformScheduler::new(Arc::new(SmokeDispatcher)))); |
| 407 | |
| 408 | // `gate_rx` lets the detached child park until the test explicitly |
| 409 | // releases it — after we've already observed the root completing. |
| 410 | let (gate_tx, gate_rx) = mpsc::channel::<()>(); |
| 411 | let (child_done_tx, child_done_rx) = mpsc::channel::<std::thread::ThreadId>(); |
| 412 | |
| 413 | let task = background.spawn_dedicated(move |executor| async move { |
| 414 | executor |
| 415 | .spawn(async move { |
| 416 | // Blocking on `recv` is normally wrong inside an |
| 417 | // executor, but the dedicated thread is exclusive to |
| 418 | // this session, so blocking the only future on it is |
| 419 | // fine — this is the property `spawn_dedicated` is |
| 420 | // designed to provide. |
| 421 | gate_rx |
| 422 | .recv() |
| 423 | .expect("gate sender dropped before child resumed"); |
| 424 | child_done_tx |
| 425 | .send(std::thread::current().id()) |
| 426 | .expect("child_done receiver dropped"); |
| 427 | }) |
| 428 | .detach(); |
| 429 | // Root finishes here. The detached child must keep the |
| 430 | // dedicated thread alive until it completes. |
| 431 | }); |
| 432 | |
| 433 | futures::executor::block_on(task); |
| 434 | |
| 435 | // Negative assertion: the child has not finished, because the gate |
| 436 | // hasn't been released yet. |
| 437 | assert!( |
| 438 | child_done_rx |
| 439 | .recv_timeout(Duration::from_millis(50)) |
| 440 | .is_err(), |
| 441 | "detached child finished before being released" |
| 442 | ); |
| 443 | |
| 444 | // Release the gate. The detached child should now complete on the |
| 445 | // dedicated thread. |
| 446 | gate_tx.send(()).expect("gate receiver dropped"); |
| 447 | |
| 448 | let child_thread_id = child_done_rx |
| 449 | .recv_timeout(Duration::from_secs(2)) |
| 450 | .expect("detached child failed to complete after gate was released"); |
| 451 | assert_ne!( |
| 452 | child_thread_id, |
| 453 | std::thread::current().id(), |
| 454 | "detached child ran on the test thread instead of the dedicated thread" |
| 455 | ); |
| 456 | } |
| 457 | } |