Skip to main content

scheduler/
scheduler.rs

1// Modified by Longbridge for gpui-fast.
2mod clock;
3mod executor;
4mod fast;
5mod test_scheduler;
6#[cfg(test)]
7mod tests;
8
9pub use clock::*;
10pub use executor::*;
11pub use test_scheduler::*;
12
13static TEST_SCHEDULER_CREATED: std::sync::atomic::AtomicBool =
14    std::sync::atomic::AtomicBool::new(false);
15
16/// Whether this process has created a [`TestScheduler`].
17///
18/// Test harnesses create one before the test body runs, and applications never
19/// do. Code with no executor at hand, such as expensive data-structure invariant
20/// checks, can use this to run only in test processes. Code that has an
21/// executor should prefer [`BackgroundExecutor::is_test`], which is correct per
22/// executor.
23pub fn test_scheduler_created() -> bool {
24    TEST_SCHEDULER_CREATED.load(std::sync::atomic::Ordering::Relaxed)
25}
26
27use async_task::Runnable;
28use futures::channel::oneshot;
29use std::{
30    any::Any,
31    future::Future,
32    panic::Location,
33    pin::Pin,
34    sync::Arc,
35    task::{Context, Poll},
36    time::Duration,
37};
38
39/// Task priority for background tasks.
40///
41/// Higher priority tasks are more likely to be scheduled before lower priority tasks,
42/// but this is not a strict guarantee - the scheduler may interleave tasks of different
43/// priorities to prevent starvation.
44#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
45#[repr(u8)]
46pub enum Priority {
47    /// Realtime priority
48    ///
49    /// Spawning a task with this priority will spin it off on a separate thread dedicated just to that task. Only use for audio.
50    RealtimeAudio,
51    /// High priority - use for tasks critical to user experience/responsiveness.
52    High,
53    /// Medium priority - suitable for most use cases.
54    #[default]
55    Medium,
56    /// Low priority - use for background work that can be deprioritized.
57    Low,
58}
59
60impl Priority {
61    /// Returns the relative probability weight for this priority level.
62    /// Used by schedulers to determine task selection probability.
63    pub const fn weight(self) -> u32 {
64        match self {
65            Priority::High => 60,
66            Priority::Medium => 30,
67            Priority::Low => 10,
68            // realtime priorities are not considered for probability scheduling
69            Priority::RealtimeAudio => 0,
70        }
71    }
72}
73
74#[derive(Clone, Copy, Debug)]
75pub struct SpawnTime(pub Instant);
76
77/// Metadata attached to runnables for debugging and profiling.
78#[derive(Clone, Debug)]
79pub struct RunnableMeta {
80    /// The source location where the task was spawned.
81    pub location: &'static Location<'static>,
82    /// The moment the task was spawned.
83    pub spawned: SpawnTime,
84}
85
86impl RunnableMeta {
87    #[track_caller]
88    pub fn new_with_callers_location() -> Self {
89        Self {
90            location: core::panic::Location::caller(),
91            spawned: SpawnTime(Instant::now()),
92        }
93    }
94}
95
96pub trait Scheduler: Send + Sync {
97    /// Block until the given future completes or timeout occurs.
98    ///
99    /// Returns `true` if the future completed, `false` if it timed out.
100    /// The future is passed as a pinned mutable reference so the caller
101    /// retains ownership and can continue polling or return it on timeout.
102    #[cfg(not(target_family = "wasm"))]
103    fn block(
104        &self,
105        session_id: Option<SessionId>,
106        future: Pin<&mut dyn Future<Output = ()>>,
107        timeout: Option<Duration>,
108    ) -> bool;
109
110    /// Schedule a runnable on the local (session-pinned) queue for `session_id`.
111    /// Runnables scheduled here run in order on whichever thread drains the
112    /// session — the main thread for ordinary sessions, or a dedicated OS
113    /// thread for sessions created via `spawn_dedicated_thread`.
114    fn schedule_local(&self, session_id: SessionId, runnable: Runnable<RunnableMeta>);
115
116    /// Schedule a background task with the given priority.
117    fn schedule_background_with_priority(
118        &self,
119        runnable: Runnable<RunnableMeta>,
120        priority: Priority,
121    );
122
123    /// Spawn a closure on a dedicated realtime thread for audio processing.
124    fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>);
125
126    /// Schedule a background task with default (medium) priority.
127    fn schedule_background(&self, runnable: Runnable<RunnableMeta>) {
128        self.schedule_background_with_priority(runnable, Priority::default());
129    }
130
131    #[track_caller]
132    fn timer(&self, timeout: Duration) -> Timer;
133    fn clock(&self) -> Arc<dyn Clock>;
134
135    /// Spawn a closure on a fresh session pinned to its own [`LocalExecutor`].
136    ///
137    /// `PlatformScheduler` runs the closure on a new OS thread (see
138    /// [`spawn_dedicated_thread`]). `TestScheduler` runs it on the test
139    /// scheduler's loop alongside everything else so determinism under
140    /// `TestScheduler::many` is preserved.
141    ///
142    /// This is the dyn-safe entry point: the closure's output is type-erased
143    /// as `Box<dyn Any + Send + Sync>` so the trait stays object-safe.
144    /// Callers typically reach for the type-safe wrappers on
145    /// [`LocalExecutor::spawn_dedicated`] and
146    /// [`BackgroundExecutor::spawn_dedicated`], which compose this method
147    /// with [`Task::downcast`] to recover the closure's concrete return type.
148    fn spawn_dedicated(
149        self: Arc<Self>,
150        f: Box<
151            dyn FnOnce(
152                    LocalExecutor,
153                )
154                    -> Pin<Box<dyn Future<Output = Box<dyn Any + Send + Sync>> + 'static>>
155                + Send
156                + 'static,
157        >,
158    ) -> Task<Box<dyn Any + Send + Sync>>;
159
160    fn as_test(&self) -> Option<&TestScheduler> {
161        None
162    }
163}
164
165/// Spawn work on a fresh OS thread that's exclusive to the returned task and
166/// anything spawned on the executor it provides. Blocking syscalls inside that
167/// work don't disturb any other executor in the process.
168///
169/// `f` is called on the dedicated thread with a [`LocalExecutor`] pinned
170/// to it. The future `f` returns may freely be `!Send`. The returned `Task`
171/// resolves to that future's output: dropping it cancels the root, but
172/// detached children keep running until they finish. The thread shuts down
173/// once the executor and every task on it are gone.
174///
175/// This function never blocks: the returned task starts as an asynchronous
176/// rendezvous that resolves to the root task's handle once the dedicated
177/// thread has spawned it, and behaves like that handle from then on. That
178/// makes it safe to call from threads that must not block, such as the web
179/// main thread. On wasm targets the thread is a web worker and requires the
180/// `wasm-threads` cargo feature (and a shared-memory build); without it this
181/// panics. Spawning a worker is far more expensive than an OS thread —
182/// module instantiation plus a fresh function table — so on the web treat a
183/// dedicated session as a long-lived place to send work, not a per-job
184/// convenience.
185///
186/// The caller is responsible for supplying a `session_id` that's distinct from
187/// every other live session on `scheduler`. Concrete schedulers typically wrap
188/// this in an inherent method that allocates the id from their own counter.
189pub fn spawn_dedicated_thread<F, Fut>(
190    session_id: SessionId,
191    scheduler: Arc<dyn Scheduler>,
192    f: F,
193) -> Task<Fut::Output>
194where
195    F: FnOnce(LocalExecutor) -> Fut + Send + 'static,
196    Fut: Future + 'static,
197    Fut::Output: Send + 'static,
198{
199    let (task, delivery) = Task::rendezvous();
200    let thread_body = move || {
201        let (runnable_sender, runnable_receiver) = flume::unbounded::<Runnable<RunnableMeta>>();
202        let dispatch = move |runnable: Runnable<RunnableMeta>| {
203            let _ = runnable_sender.send(runnable);
204        };
205        let executor = LocalExecutor::new(session_id, scheduler, dispatch);
206        let root_task = executor.spawn(f(executor.clone()));
207        // If the caller already dropped or detached the rendezvous task,
208        // delivery applies that disposition to the root task here.
209        delivery.deliver(root_task);
210        // After this drop, every strong reference to the runnable sender
211        // lives inside a spawned task or a user-held executor clone. The
212        // recv loop exits once all of those are gone.
213        drop(executor);
214
215        while let Ok(runnable) = runnable_receiver.recv() {
216            runnable.run();
217        }
218    };
219    spawn_dedicated_os_thread(session_id, thread_body);
220    task
221}
222
223fn spawn_dedicated_os_thread(session_id: SessionId, thread_body: impl FnOnce() + Send + 'static) {
224    let thread_name = format!("spawn_dedicated session {:?}", session_id);
225    #[cfg(not(target_family = "wasm"))]
226    std::thread::Builder::new()
227        .name(thread_name)
228        .spawn(thread_body)
229        .expect("failed to spawn dedicated thread");
230    #[cfg(all(target_family = "wasm", feature = "wasm-threads"))]
231    wasm_thread::Builder::new()
232        .name(thread_name)
233        .spawn(thread_body)
234        .expect("failed to spawn dedicated thread");
235    #[cfg(all(target_family = "wasm", not(feature = "wasm-threads")))]
236    {
237        let _ = (thread_name, thread_body);
238        panic!("spawn_dedicated on wasm requires the scheduler crate's `wasm-threads` feature");
239    }
240}
241
242#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
243pub struct SessionId(u16);
244
245impl SessionId {
246    pub fn new(id: u16) -> Self {
247        SessionId(id)
248    }
249}
250
251pub struct Timer(oneshot::Receiver<()>);
252
253impl Timer {
254    pub fn new(rx: oneshot::Receiver<()>) -> Self {
255        Timer(rx)
256    }
257}
258
259impl Future for Timer {
260    type Output = ();
261
262    fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<()> {
263        match Pin::new(&mut self.0).poll(cx) {
264            Poll::Ready(_) => Poll::Ready(()),
265            Poll::Pending => Poll::Pending,
266        }
267    }
268}