Skip to main content

scheduler/
scheduler.rs

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