Skip to main content

velox_engine/async_rt/
manual.rs

1//! 确定性虚拟时钟与手动步进调度器 [`ManualScheduler`](同时实现 [`SchedulerBackend`] 与 [`AsyncDriver`])。
2//!
3//! 典型用途:
4//! - **零真睡、零时间抖动单元测试**:直接通过 [`ManualScheduler::advance`] 在 <1ms 内瞬间快进数分钟异步定时器;
5//! - **多调度器隔离验证**:证明同一套业务异步代码(`acx.spawn` / `cx.background_spawn` / `cx.timer`)可在不修改任何业务代码的前提下自由切换底层调度器。
6
7use core::cmp::Reverse;
8use core::future::Future;
9use core::pin::Pin;
10use core::sync::atomic::{AtomicBool, AtomicU64, Ordering};
11use core::task::{Context, Poll, Waker};
12use core::time::Duration;
13use std::collections::{BinaryHeap, VecDeque};
14use std::sync::{Arc, Mutex};
15use std::task::Wake;
16use std::vec::Vec;
17
18use crate::engine::VeloxEngine;
19
20use super::backend::{BoxFuture, SchedulerBackend, UiWakeSignal};
21use super::scheduler::{AsyncDriver, SchedulerCapabilities, SchedulerClock};
22use super::std_scheduler::Timer;
23
24struct ManualTimerEntry {
25    deadline_ms: u64,
26    seq: u64,
27    waker: Waker,
28}
29
30impl PartialEq for ManualTimerEntry {
31    fn eq(&self, other: &Self) -> bool {
32        self.deadline_ms == other.deadline_ms && self.seq == other.seq
33    }
34}
35
36impl Eq for ManualTimerEntry {}
37
38impl PartialOrd for ManualTimerEntry {
39    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
40        Some(self.cmp(other))
41    }
42}
43
44impl Ord for ManualTimerEntry {
45    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
46        self.deadline_ms
47            .cmp(&other.deadline_ms)
48            .then_with(|| self.seq.cmp(&other.seq))
49    }
50}
51
52struct ManualBgJob {
53    state: Arc<ManualState>,
54    future: Mutex<Option<BoxFuture<'static, ()>>>,
55    queued: AtomicBool,
56}
57
58impl ManualBgJob {
59    fn enqueue(self: &Arc<Self>) {
60        if !self.queued.swap(true, Ordering::AcqRel) {
61            let mut q = self
62                .state
63                .bg_queue
64                .lock()
65                .unwrap_or_else(|e| e.into_inner());
66            q.push_back(Arc::clone(self));
67            drop(q);
68            self.state.wake_signal.wake();
69        }
70    }
71
72    fn poll_once(self: &Arc<Self>) -> bool {
73        self.queued.store(false, Ordering::Release);
74        let mut fut = {
75            let mut slot = self.future.lock().unwrap_or_else(|e| e.into_inner());
76            let Some(f) = slot.take() else {
77                return false;
78            };
79            f
80        };
81        let waker = Waker::from(Arc::clone(self));
82        let mut cx = Context::from_waker(&waker);
83        match fut.as_mut().poll(&mut cx) {
84            Poll::Ready(()) => {}
85            Poll::Pending => {
86                let mut slot = self.future.lock().unwrap_or_else(|e| e.into_inner());
87                *slot = Some(fut);
88            }
89        }
90        true
91    }
92}
93
94impl Wake for ManualBgJob {
95    fn wake(self: Arc<Self>) {
96        self.enqueue();
97    }
98    fn wake_by_ref(self: &Arc<Self>) {
99        self.enqueue();
100    }
101}
102
103struct ManualState {
104    now_ms: AtomicU64,
105    timers: Mutex<(u64, BinaryHeap<Reverse<ManualTimerEntry>>)>,
106    bg_queue: Mutex<VecDeque<Arc<ManualBgJob>>>,
107    wake_signal: UiWakeSignal,
108}
109
110struct ManualTimerFuture {
111    state: Arc<ManualState>,
112    deadline_ms: u64,
113    registered: bool,
114}
115
116impl Unpin for ManualTimerFuture {}
117
118impl Future for ManualTimerFuture {
119    type Output = ();
120
121    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
122        let this = self.get_mut();
123        let now = this.state.now_ms.load(Ordering::Acquire);
124        if now >= this.deadline_ms {
125            return Poll::Ready(());
126        }
127        if !this.registered {
128            this.registered = true;
129            let mut guard = this.state.timers.lock().unwrap_or_else(|e| e.into_inner());
130            guard.0 = guard.0.wrapping_add(1);
131            let seq = guard.0;
132            guard.1.push(Reverse(ManualTimerEntry {
133                deadline_ms: this.deadline_ms,
134                seq,
135                waker: cx.waker().clone(),
136            }));
137        }
138        Poll::Pending
139    }
140}
141
142/// 确定性虚拟时钟与手动步进调度器(零真睡、零线程、100% 可复现)。
143#[derive(Clone)]
144pub struct ManualScheduler {
145    state: Arc<ManualState>,
146}
147
148impl ManualScheduler {
149    /// 创建一个从 `0ms` 开始计时的确定性调度器(返回 `Arc<Self>` 便于同时传给引擎与测试代码)。
150    pub fn new() -> Arc<Self> {
151        Arc::new(Self {
152            state: Arc::new(ManualState {
153                now_ms: AtomicU64::new(0),
154                timers: Mutex::new((0, BinaryHeap::new())),
155                bg_queue: Mutex::new(VecDeque::new()),
156                wake_signal: UiWakeSignal::new(),
157            }),
158        })
159    }
160
161    /// 返回当前虚拟单调时间戳(毫秒)。
162    #[inline]
163    pub fn current_ms(&self) -> u64 {
164        self.state.now_ms.load(Ordering::Acquire)
165    }
166
167    /// 返回当前虚拟单调时间戳(毫秒,`current_ms` 别名,避免同时导入多个调度 trait 时的调用二义性)。
168    #[inline]
169    pub fn now_ms(&self) -> u64 {
170        self.current_ms()
171    }
172
173    /// 将虚拟时钟向前推进 `duration`,并按截止时间先后顺序唤醒全部已到期定时器,返回唤醒数量。
174    pub fn advance(&self, duration: Duration) -> usize {
175        let delta_ms = duration.as_millis().min(u64::MAX as u128) as u64;
176        let target_ms = self
177            .state
178            .now_ms
179            .fetch_add(delta_ms, Ordering::AcqRel)
180            .saturating_add(delta_ms);
181
182        let due_wakers: Vec<Waker> = {
183            let mut guard = self.state.timers.lock().unwrap_or_else(|e| e.into_inner());
184            let mut out = Vec::new();
185            while let Some(Reverse(top)) = guard.1.peek() {
186                if top.deadline_ms <= target_ms {
187                    let Reverse(entry) = guard.1.pop().unwrap();
188                    out.push(entry.waker);
189                } else {
190                    break;
191                }
192            }
193            out
194        };
195
196        let count = due_wakers.len();
197        for waker in due_wakers {
198            waker.wake();
199        }
200        if count > 0 {
201            self.state.wake_signal.wake();
202        }
203        count
204    }
205
206    /// 排空当前已就绪的后台任务队列直至全部挂起或完成,返回实际 poll 的任务次数。
207    pub fn run_until_stalled(&self) -> usize {
208        let mut polls = 0usize;
209        for _ in 0..256 {
210            let batch: Vec<Arc<ManualBgJob>> = {
211                let mut q = self
212                    .state
213                    .bg_queue
214                    .lock()
215                    .unwrap_or_else(|e| e.into_inner());
216                q.drain(..).collect()
217            };
218            if batch.is_empty() {
219                break;
220            }
221            for job in batch {
222                if job.poll_once() {
223                    polls += 1;
224                }
225            }
226        }
227        polls
228    }
229
230    /// 交替驱动后台任务与 [`VeloxEngine`] 前景协程,直至两者均进入静默等待,返回推进轮数。
231    pub fn drive_engine(&self, engine: &mut VeloxEngine) -> usize {
232        let mut progress = 0usize;
233        for _ in 0..128 {
234            let bg = self.run_until_stalled();
235            let fg = usize::from(engine.poll_async_tasks());
236            if bg == 0 && fg == 0 {
237                break;
238            }
239            progress += bg + fg;
240        }
241        progress
242    }
243
244    /// 返回当前仍在等待虚拟时钟推进的定时器数量。
245    #[inline]
246    pub fn pending_timer_count(&self) -> usize {
247        self.state
248            .timers
249            .lock()
250            .unwrap_or_else(|e| e.into_inner())
251            .1
252            .len()
253    }
254
255    /// 返回当前排队待执行的后台任务数量。
256    #[inline]
257    pub fn pending_background_count(&self) -> usize {
258        self.state
259            .bg_queue
260            .lock()
261            .unwrap_or_else(|e| e.into_inner())
262            .len()
263    }
264
265    /// 获取关联的黏性唤醒信号句柄。
266    #[inline]
267    pub fn wake_signal(&self) -> &UiWakeSignal {
268        &self.state.wake_signal
269    }
270
271    /// 主动触发一次异步事件循环唤醒。
272    #[inline]
273    pub fn notify_event(&self) {
274        self.state.wake_signal.wake();
275    }
276}
277
278impl SchedulerBackend for ManualScheduler {
279    #[inline]
280    fn name(&self) -> &'static str {
281        "velox-manual"
282    }
283
284    #[inline]
285    fn capabilities(&self) -> SchedulerCapabilities {
286        SchedulerCapabilities {
287            name: self.name(),
288            supports_background_threads: false,
289            supports_dynamic_spawn: true,
290            deterministic_clock: true,
291        }
292    }
293
294    fn spawn_background(&self, fut: BoxFuture<'static, ()>) {
295        let job = Arc::new(ManualBgJob {
296            state: Arc::clone(&self.state),
297            future: Mutex::new(Some(fut)),
298            queued: AtomicBool::new(false),
299        });
300        job.enqueue();
301    }
302
303    fn timer(&self, duration: Duration) -> Timer {
304        let delta_ms = duration.as_millis().min(u64::MAX as u128) as u64;
305        let deadline_ms = self.current_ms().saturating_add(delta_ms);
306        Timer::from_future(std::boxed::Box::pin(ManualTimerFuture {
307            state: Arc::clone(&self.state),
308            deadline_ms,
309            registered: false,
310        }))
311    }
312
313    #[inline]
314    fn now_ms(&self) -> u64 {
315        self.current_ms()
316    }
317}
318
319impl SchedulerClock for ManualScheduler {
320    #[inline]
321    fn now_ms(&self) -> u64 {
322        self.current_ms()
323    }
324
325    #[inline]
326    fn sleep(&self, duration: Duration) -> impl Future<Output = ()> {
327        <Self as SchedulerBackend>::timer(self, duration)
328    }
329}
330
331impl AsyncDriver for ManualScheduler {
332    #[inline]
333    fn capabilities(&self) -> SchedulerCapabilities {
334        <Self as SchedulerBackend>::capabilities(self)
335    }
336
337    #[inline]
338    fn wait_for_event(&self) -> impl Future<Output = ()> {
339        self.state.wake_signal.wait()
340    }
341}