Skip to main content

velox_engine/async_rt/
std_scheduler.rs

1//! 内置默认标准库调度器 [`NativeStdScheduler`]、统一定时器 [`Timer`]、可插拔 [`BackgroundExecutor`] 与轻量 [`block_on`]。
2//!
3//! 特点:
4//! - 零外部异步运行时依赖(纯标准库 `Future` / `Waker` / `Condvar` / `BinaryHeap`);
5//! - 后台线程池与单常驻最小堆定时器线程均惰性启动,未调用前 0 线程、0 内存占用,空闲 0% CPU;
6//! - [`BackgroundExecutor`] 持有 `Arc<dyn SchedulerBackend>`,并通过通用可取消包装自动为任意后端提供 RAII `Task::drop` 取消语义。
7
8use core::cmp::Reverse;
9use core::future::Future;
10use core::pin::{pin, Pin};
11use core::sync::atomic::{AtomicBool, Ordering};
12use core::task::{Context, Poll, Waker};
13use core::time::Duration;
14use std::boxed::Box;
15use std::collections::{BinaryHeap, VecDeque};
16use std::sync::{Arc, Condvar, Mutex, OnceLock};
17use std::task::Wake;
18use std::time::Instant;
19
20use super::backend::{BoxFuture, SchedulerBackend};
21use super::scheduler::SchedulerCapabilities;
22use super::task::{Task, TaskShared};
23
24/// 在当前线程阻塞驱动任意 [`Future`] 至完成(用于无头工具、CLI 演示与单元测试)。
25pub fn block_on<F: Future>(fut: F) -> F::Output {
26    struct ThreadWaker {
27        ready: Mutex<bool>,
28        cv: Condvar,
29    }
30    impl Wake for ThreadWaker {
31        fn wake(self: Arc<Self>) {
32            self.wake_by_ref();
33        }
34        fn wake_by_ref(self: &Arc<Self>) {
35            if let Ok(mut ready) = self.ready.lock() {
36                *ready = true;
37                self.cv.notify_one();
38            }
39        }
40    }
41
42    let signal = Arc::new(ThreadWaker {
43        ready: Mutex::new(false),
44        cv: Condvar::new(),
45    });
46    let waker = Waker::from(signal.clone());
47    let mut cx = Context::from_waker(&waker);
48    let mut fut = pin!(fut);
49
50    loop {
51        match fut.as_mut().poll(&mut cx) {
52            Poll::Ready(out) => return out,
53            Poll::Pending => {
54                if let Ok(mut ready) = signal.ready.lock() {
55                    while !*ready {
56                        ready = match signal.cv.wait(ready) {
57                            Ok(g) => g,
58                            Err(poisoned) => poisoned.into_inner(),
59                        };
60                    }
61                    *ready = false;
62                }
63            }
64        }
65    }
66}
67
68// ============================================================================
69// 全局单常驻线程最小堆定时器(NativeTimerDriver)
70// ============================================================================
71
72#[cfg(not(target_arch = "wasm32"))]
73struct TimerEntry {
74    deadline: Instant,
75    seq: u64,
76    waker: Waker,
77}
78
79#[cfg(not(target_arch = "wasm32"))]
80impl PartialEq for TimerEntry {
81    fn eq(&self, other: &Self) -> bool {
82        self.deadline == other.deadline && self.seq == other.seq
83    }
84}
85
86#[cfg(not(target_arch = "wasm32"))]
87impl Eq for TimerEntry {}
88
89#[cfg(not(target_arch = "wasm32"))]
90impl PartialOrd for TimerEntry {
91    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
92        Some(self.cmp(other))
93    }
94}
95
96#[cfg(not(target_arch = "wasm32"))]
97impl Ord for TimerEntry {
98    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
99        self.deadline
100            .cmp(&other.deadline)
101            .then_with(|| self.seq.cmp(&other.seq))
102    }
103}
104
105#[cfg(not(target_arch = "wasm32"))]
106struct TimerDriver {
107    state: Mutex<(u64, BinaryHeap<Reverse<TimerEntry>>)>,
108    cv: Condvar,
109}
110
111#[cfg(not(target_arch = "wasm32"))]
112static TIMER_DRIVER: OnceLock<Arc<TimerDriver>> = OnceLock::new();
113
114#[cfg(not(target_arch = "wasm32"))]
115fn timer_driver() -> &'static Arc<TimerDriver> {
116    TIMER_DRIVER.get_or_init(|| {
117        let driver = Arc::new(TimerDriver {
118            state: Mutex::new((0, BinaryHeap::new())),
119            cv: Condvar::new(),
120        });
121        let bg = Arc::clone(&driver);
122        let _ = std::thread::Builder::new()
123            .name(std::string::String::from("velox-async-timer"))
124            .stack_size(128 * 1024)
125            .spawn(move || loop {
126                let waker_to_fire = {
127                    let mut guard = bg.state.lock().unwrap_or_else(|e| e.into_inner());
128                    loop {
129                        let Some(Reverse(top)) = guard.1.peek() else {
130                            guard = bg.cv.wait(guard).unwrap_or_else(|e| e.into_inner());
131                            continue;
132                        };
133                        let now = Instant::now();
134                        if top.deadline <= now {
135                            let Reverse(entry) = guard.1.pop().unwrap();
136                            break entry.waker;
137                        }
138                        let wait_dur = top.deadline.saturating_duration_since(now);
139                        let (next_guard, _) = bg
140                            .cv
141                            .wait_timeout(guard, wait_dur)
142                            .unwrap_or_else(|e| e.into_inner());
143                        guard = next_guard;
144                    }
145                };
146                waker_to_fire.wake();
147            });
148        driver
149    })
150}
151
152struct NativeTimer {
153    deadline: Instant,
154    registered: bool,
155}
156
157impl NativeTimer {
158    #[inline]
159    fn after(duration: Duration) -> Self {
160        Self {
161            deadline: Instant::now() + duration,
162            registered: false,
163        }
164    }
165
166    fn poll_native(&mut self, cx: &mut Context<'_>) -> Poll<()> {
167        if Instant::now() >= self.deadline {
168            return Poll::Ready(());
169        }
170        #[cfg(not(target_arch = "wasm32"))]
171        {
172            if !self.registered {
173                self.registered = true;
174                let driver = timer_driver();
175                let mut guard = driver.state.lock().unwrap_or_else(|e| e.into_inner());
176                guard.0 = guard.0.wrapping_add(1);
177                let seq = guard.0;
178                let is_earlier = guard
179                    .1
180                    .peek()
181                    .map(|Reverse(top)| self.deadline < top.deadline)
182                    .unwrap_or(true);
183                guard.1.push(Reverse(TimerEntry {
184                    deadline: self.deadline,
185                    seq,
186                    waker: cx.waker().clone(),
187                }));
188                if is_earlier {
189                    driver.cv.notify_one();
190                }
191            }
192            Poll::Pending
193        }
194        #[cfg(target_arch = "wasm32")]
195        {
196            let _ = cx;
197            Poll::Ready(())
198        }
199    }
200}
201
202enum TimerInner {
203    /// 默认原生最小堆定时器(零额外 `Box` 堆分配快路径)。
204    Native(NativeTimer),
205    /// 可插拔第三方或确定性调度器提供的自定义定时器 Future。
206    Custom(BoxFuture<'static, ()>),
207}
208
209/// 跨调度器统一非阻塞异步定时器 [`Future`]。
210///
211/// - 使用默认 [`NativeStdScheduler`] 时走零 `Box` 快路径,由单常驻最小堆定时器线程驱动(空闲 0% CPU);
212/// - 注入自定义 [`SchedulerBackend`](如 [`ManualScheduler`](super::ManualScheduler) 或未来的 Tokio 适配器)时,
213///   自动透明切换至对应调度器的时钟实现,业务层无需修改任何代码。
214pub struct Timer {
215    inner: TimerInner,
216}
217
218impl Timer {
219    /// 创建一个使用默认内置原生时钟驱动的异步定时器。
220    #[inline]
221    pub fn after(duration: Duration) -> Self {
222        Self {
223            inner: TimerInner::Native(NativeTimer::after(duration)),
224        }
225    }
226
227    /// 将自定义调度器返回的任意 `Send + 'static` 定时 Future 包装为统一 [`Timer`]。
228    #[inline]
229    pub fn from_future(fut: BoxFuture<'static, ()>) -> Self {
230        Self {
231            inner: TimerInner::Custom(fut),
232        }
233    }
234}
235
236impl Unpin for Timer {}
237
238impl Future for Timer {
239    type Output = ();
240
241    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
242        match &mut self.get_mut().inner {
243            TimerInner::Native(native) => native.poll_native(cx),
244            TimerInner::Custom(custom) => custom.as_mut().poll(cx),
245        }
246    }
247}
248
249// ============================================================================
250// 内置原生后台工作线程池(NativeStdScheduler)
251// ============================================================================
252
253#[cfg(not(target_arch = "wasm32"))]
254struct BgJob {
255    future: Mutex<Option<BoxFuture<'static, ()>>>,
256    scheduled: AtomicBool,
257}
258
259#[cfg(not(target_arch = "wasm32"))]
260impl BgJob {
261    fn enqueue(self: &Arc<Self>) {
262        if !self.scheduled.swap(true, Ordering::AcqRel) {
263            let pool = bg_pool();
264            let mut q = pool.queue.lock().unwrap_or_else(|e| e.into_inner());
265            q.push_back(Arc::clone(self));
266            pool.cv.notify_one();
267        }
268    }
269
270    fn run(self: &Arc<Self>) {
271        self.scheduled.store(false, Ordering::Release);
272
273        // 先移出 Future 到局部栈再 poll,避免 Future 内部同步触发 wake 造成重入锁死锁
274        let mut fut = {
275            let mut slot = self.future.lock().unwrap_or_else(|e| e.into_inner());
276            let Some(f) = slot.take() else {
277                return;
278            };
279            f
280        };
281
282        let waker = Waker::from(Arc::clone(self));
283        let mut cx = Context::from_waker(&waker);
284        match fut.as_mut().poll(&mut cx) {
285            Poll::Ready(()) => {}
286            Poll::Pending => {
287                let mut slot = self.future.lock().unwrap_or_else(|e| e.into_inner());
288                *slot = Some(fut);
289            }
290        }
291    }
292}
293
294#[cfg(not(target_arch = "wasm32"))]
295impl Wake for BgJob {
296    fn wake(self: Arc<Self>) {
297        self.enqueue();
298    }
299    fn wake_by_ref(self: &Arc<Self>) {
300        self.enqueue();
301    }
302}
303
304#[cfg(not(target_arch = "wasm32"))]
305struct BackgroundPool {
306    queue: Mutex<VecDeque<Arc<BgJob>>>,
307    cv: Condvar,
308}
309
310#[cfg(not(target_arch = "wasm32"))]
311static BG_POOL: OnceLock<Arc<BackgroundPool>> = OnceLock::new();
312
313#[cfg(not(target_arch = "wasm32"))]
314fn bg_pool() -> &'static Arc<BackgroundPool> {
315    BG_POOL.get_or_init(|| {
316        let pool = Arc::new(BackgroundPool {
317            queue: Mutex::new(VecDeque::new()),
318            cv: Condvar::new(),
319        });
320        let worker_count = std::thread::available_parallelism()
321            .map(|n| n.get())
322            .unwrap_or(2)
323            .clamp(2, 4);
324        for idx in 0..worker_count {
325            let p = Arc::clone(&pool);
326            let _ = std::thread::Builder::new()
327                .name(std::format!("velox-bg-{idx}"))
328                .stack_size(256 * 1024)
329                .spawn(move || loop {
330                    let job = {
331                        let mut q = p.queue.lock().unwrap_or_else(|e| e.into_inner());
332                        while q.is_empty() {
333                            q = p.cv.wait(q).unwrap_or_else(|e| e.into_inner());
334                        }
335                        q.pop_front()
336                    };
337                    if let Some(job) = job {
338                        job.run();
339                    }
340                });
341        }
342        pool
343    })
344}
345
346/// Velox 内置默认标准库调度器后端(零外部依赖:常驻多线程池 + 单常驻最小堆定时器线程)。
347pub struct NativeStdScheduler {
348    epoch: Instant,
349}
350
351static GLOBAL_NATIVE_SCHEDULER: OnceLock<Arc<dyn SchedulerBackend>> = OnceLock::new();
352
353impl NativeStdScheduler {
354    /// 创建一个新的原生标准库调度器实例(共享惰性后台线程池与定时器线程)。
355    pub fn new() -> Self {
356        Self {
357            epoch: Instant::now(),
358        }
359    }
360
361    /// 获取进程级共享默认 [`NativeStdScheduler`] 后端引用(零重复分配)。
362    pub fn global() -> Arc<dyn SchedulerBackend> {
363        Arc::clone(GLOBAL_NATIVE_SCHEDULER.get_or_init(|| Arc::new(Self::new())))
364    }
365}
366
367impl Default for NativeStdScheduler {
368    fn default() -> Self {
369        Self::new()
370    }
371}
372
373impl SchedulerBackend for NativeStdScheduler {
374    #[inline]
375    fn name(&self) -> &'static str {
376        "velox-native-std"
377    }
378
379    #[inline]
380    fn capabilities(&self) -> SchedulerCapabilities {
381        SchedulerCapabilities {
382            name: self.name(),
383            supports_background_threads: cfg!(not(target_arch = "wasm32")),
384            supports_dynamic_spawn: true,
385            deterministic_clock: false,
386        }
387    }
388
389    fn spawn_background(&self, fut: BoxFuture<'static, ()>) {
390        #[cfg(not(target_arch = "wasm32"))]
391        {
392            let job = Arc::new(BgJob {
393                future: Mutex::new(Some(fut)),
394                scheduled: AtomicBool::new(false),
395            });
396            job.enqueue();
397        }
398        #[cfg(target_arch = "wasm32")]
399        {
400            block_on(fut);
401        }
402    }
403
404    #[inline]
405    fn timer(&self, duration: Duration) -> Timer {
406        Timer::after(duration)
407    }
408
409    #[inline]
410    fn now_ms(&self) -> u64 {
411        self.epoch.elapsed().as_millis().min(u64::MAX as u128) as u64
412    }
413}
414
415// ============================================================================
416// 通用可取消后台任务包装 + 可插拔 `BackgroundExecutor`
417// ============================================================================
418
419struct CancellableFuture<T, Fut> {
420    fut: Option<Pin<Box<Fut>>>,
421    shared: Arc<TaskShared<T>>,
422    cancel_waker: Arc<Mutex<Option<Waker>>>,
423}
424
425impl<T, Fut> Unpin for CancellableFuture<T, Fut> {}
426
427impl<T, Fut> Future for CancellableFuture<T, Fut>
428where
429    T: Send + 'static,
430    Fut: Future<Output = T> + Send + 'static,
431{
432    type Output = ();
433
434    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
435        let this = self.get_mut();
436        if this.shared.is_cancelled() {
437            this.fut = None;
438            let mut slot = this.cancel_waker.lock().unwrap_or_else(|e| e.into_inner());
439            *slot = None;
440            return Poll::Ready(());
441        }
442
443        {
444            let mut slot = this.cancel_waker.lock().unwrap_or_else(|e| e.into_inner());
445            let should_update = slot
446                .as_ref()
447                .map(|prev| !prev.will_wake(cx.waker()))
448                .unwrap_or(true);
449            if should_update {
450                *slot = Some(cx.waker().clone());
451            }
452        }
453
454        let Some(fut) = this.fut.as_mut() else {
455            return Poll::Ready(());
456        };
457
458        match fut.as_mut().poll(cx) {
459            Poll::Ready(output) => {
460                this.fut = None;
461                {
462                    let mut slot = this.cancel_waker.lock().unwrap_or_else(|e| e.into_inner());
463                    *slot = None;
464                }
465                if !this.shared.is_cancelled() {
466                    this.shared.complete(output);
467                }
468                Poll::Ready(())
469            }
470            Poll::Pending => {
471                if this.shared.is_cancelled() {
472                    this.fut = None;
473                    let mut slot = this.cancel_waker.lock().unwrap_or_else(|e| e.into_inner());
474                    *slot = None;
475                    return Poll::Ready(());
476                }
477                Poll::Pending
478            }
479        }
480    }
481}
482
483/// 可插拔后台异步执行器句柄(轻量 `Clone`,面向 CPU 密集型计算、阻塞 I/O 与跨调度器定时)。
484///
485/// 内部持有 `Arc<dyn SchedulerBackend>`:默认指向 [`NativeStdScheduler::global`],
486/// 也可通过 [`BackgroundExecutor::with_backend`] 或 [`crate::engine::VeloxEngine::with_scheduler`] 切换至任意外部调度器。
487#[derive(Clone)]
488pub struct BackgroundExecutor {
489    backend: Arc<dyn SchedulerBackend>,
490}
491
492impl Default for BackgroundExecutor {
493    #[inline]
494    fn default() -> Self {
495        Self::new()
496    }
497}
498
499impl core::fmt::Debug for BackgroundExecutor {
500    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
501        f.debug_struct("BackgroundExecutor")
502            .field("scheduler", &self.backend.name())
503            .finish()
504    }
505}
506
507impl BackgroundExecutor {
508    /// 创建一个绑定默认内置 [`NativeStdScheduler`] 的后台执行器句柄。
509    #[inline]
510    pub fn new() -> Self {
511        Self {
512            backend: NativeStdScheduler::global(),
513        }
514    }
515
516    /// 创建一个绑定指定 [`SchedulerBackend`] 的后台执行器句柄。
517    #[inline]
518    pub fn with_backend(backend: Arc<dyn SchedulerBackend>) -> Self {
519        Self { backend }
520    }
521
522    /// 获取底层 [`SchedulerBackend`] 引用。
523    #[inline]
524    pub fn backend(&self) -> &Arc<dyn SchedulerBackend> {
525        &self.backend
526    }
527
528    /// 返回当前绑定的调度器名称。
529    #[inline]
530    pub fn scheduler_name(&self) -> &'static str {
531        self.backend.name()
532    }
533
534    /// 返回当前绑定的调度器能力元信息。
535    #[inline]
536    pub fn capabilities(&self) -> SchedulerCapabilities {
537        self.backend.capabilities()
538    }
539
540    /// 返回当前调度器单调时钟(毫秒)。
541    #[inline]
542    pub fn now_ms(&self) -> u64 {
543        self.backend.now_ms()
544    }
545
546    /// 在所配置的后台调度器中派生 `Send + 'static` 异步任务并返回支持 RAII Drop 自动取消的 [`Task<T>`]。
547    pub fn spawn<T, Fut>(&self, fut: Fut) -> Task<T>
548    where
549        T: Send + 'static,
550        Fut: Future<Output = T> + Send + 'static,
551    {
552        let cancelled = Arc::new(AtomicBool::new(false));
553        let cancel_waker: Arc<Mutex<Option<Waker>>> = Arc::new(Mutex::new(None));
554        let cancel_waker_cb = Arc::clone(&cancel_waker);
555        let on_cancel: Arc<dyn Fn() + Send + Sync> = Arc::new(move || {
556            let waker = {
557                let mut slot = cancel_waker_cb.lock().unwrap_or_else(|e| e.into_inner());
558                slot.take()
559            };
560            if let Some(w) = waker {
561                w.wake();
562            }
563        });
564        let shared = TaskShared::new(cancelled, Some(on_cancel));
565        let wrapped = CancellableFuture {
566            fut: Some(Box::pin(fut)),
567            shared: Arc::clone(&shared),
568            cancel_waker,
569        };
570        self.backend.spawn_background(Box::pin(wrapped));
571        Task::from_shared(shared)
572    }
573
574    /// 创建由当前调度器时钟驱动的非阻塞异步定时器(与 GPUI `cx.background_executor().timer(dur)` 对齐)。
575    #[inline]
576    pub fn timer(&self, duration: Duration) -> Timer {
577        self.backend.timer(duration)
578    }
579}