mgui-task 0.6.0

UI 线程本地异步任务执行器(无 wgpu/winit 依赖)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
//! UI 线程本地异步任务执行器
//!
//! 设计目标:
//! - **零第三方依赖**:只用 std Future/Waker(不引入 futures/smol);
//! - **!Send futures**:任务在 UI 线程轮询,可以捕获 `Rc`/`Signal` 等 UI 状态;
//! - **跨线程唤醒**:后台线程持有的 `Waker` 通过 `Arc<Mutex<ready>>` 入队,
//!   再调用 Runner 注入的 wake 回调(通常是 `EventLoopProxy::send_event`);
//! - **取消/panic 隔离**:`TaskHandle::cancel()` 立即移除任务;poll panic 被
//!   catch_unwind 捕获并记录,不影响其它任务与 UI 树。
//!
//! Runner 在 `user_event` / 每帧 redraw / `about_to_wait` 调用
//! [`TaskExecutor::poll_ready`] 驱动就绪任务;任务回调更新 Signal 后由 Runner
//! 标记重绘。

use std::cell::{Cell, RefCell};
use std::collections::{HashMap, VecDeque};
use std::future::Future;
use std::panic::AssertUnwindSafe;
use std::pin::Pin;
use std::rc::{Rc, Weak};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Wake, Waker};
use std::time::Duration;

type TaskId = u64;

/// 单次 `poll_ready` 最多轮询的任务数,防止自唤醒 future 独占 UI 线程。
const MAX_POLLS_PER_TURN: usize = 256;

struct TaskEntry {
    future: Pin<Box<dyn Future<Output = ()>>>,
    waker: Waker,
    cancelled: Rc<Cell<bool>>,
}

struct ExecutorInner {
    tasks: HashMap<TaskId, TaskEntry>,
    next_id: TaskId,
}

/// 唤醒回调:由 Runner 注入(通常是 `EventLoopProxy::send_event`)。
pub type WakeCallback = Arc<dyn Fn() + Send + Sync>;

/// UI 线程任务执行器(可 Clone;所有任务共享同一队列)
#[derive(Clone)]
pub struct TaskExecutor {
    inner: Rc<RefCell<ExecutorInner>>,
    /// 跨线程 waker 入队
    ready: Arc<Mutex<VecDeque<TaskId>>>,
    /// 唤醒事件循环(可在任意线程调用)
    wake: WakeCallback,
}

/// 任务句柄:drop 不会取消任务;需要取消显式调用 [`TaskHandle::cancel`]。
pub struct TaskHandle {
    id: TaskId,
    inner: Weak<RefCell<ExecutorInner>>,
    cancelled: Rc<Cell<bool>>,
}

impl TaskHandle {
    /// 取消任务并立即丢弃 future;完成回调不会再触发。
    pub fn cancel(&self) {
        self.cancelled.set(true);
        if let Some(inner) = self.inner.upgrade() {
            inner.borrow_mut().tasks.remove(&self.id);
        }
    }

    pub fn is_cancelled(&self) -> bool {
        self.cancelled.get()
    }
}

impl TaskExecutor {
    pub fn new(wake: WakeCallback) -> Self {
        Self {
            inner: Rc::new(RefCell::new(ExecutorInner { tasks: HashMap::new(), next_id: 0 })),
            ready: Arc::new(Mutex::new(VecDeque::new())),
            wake,
        }
    }

    /// 派生一个输出为 `()` 的本地任务。
    pub fn spawn<F>(&self, future: F) -> TaskHandle
    where
        F: Future<Output = ()> + 'static,
    {
        self.spawn_boxed(Box::pin(future))
    }

    /// 派生任务并在完成时于 UI 线程调用 `on_done`。
    ///
    /// 失败信息可直接通过 `Future<Output = Result<T, E>>` 交给回调处理。
    pub fn spawn_with<F, T, C>(&self, future: F, on_done: C) -> TaskHandle
    where
        F: Future<Output = T> + 'static,
        C: FnOnce(T) + 'static,
    {
        self.spawn(async move {
            let value = future.await;
            on_done(value);
        })
    }

    /// 派生阻塞工作到后台线程,完成后在 UI 线程调用 `on_done(Result<T, String>)`。
    ///
    /// 用于文件 IO / 图片解码等不能占用 UI 线程的工作;线程内 panic 会转成 Err。
    pub fn spawn_blocking<F, T, C>(&self, work: F, on_done: C) -> TaskHandle
    where
        F: FnOnce() -> Result<T, String> + Send + 'static,
        T: Send + 'static,
        C: FnOnce(Result<T, String>) + 'static,
    {
        let state = Arc::new(Mutex::new(BlockingState::<T> { value: None, waker: None }));
        let thread_state = Arc::clone(&state);
        let thread = std::thread::Builder::new().name("mgui-blocking".to_string()).spawn(move || {
            let result = std::panic::catch_unwind(AssertUnwindSafe(work))
                .unwrap_or_else(|payload| Err(format!("blocking task panicked: {}", panic_message(payload.as_ref()))));
            if let Ok(mut state) = thread_state.lock() {
                state.value = Some(result);
                if let Some(waker) = state.waker.take() {
                    drop(state);
                    waker.wake();
                }
            }
        });

        match thread {
            Ok(_) => self.spawn_with(BlockingFuture { state }, on_done),
            Err(e) => {
                // 线程创建失败:下一轮直接回报错误,任务不会永久挂起
                let message = format!("spawn blocking thread: {e}");
                self.spawn_with(async {}, move |_| on_done(Err(message)))
            }
        }
    }

    fn spawn_boxed(&self, future: Pin<Box<dyn Future<Output = ()>>>) -> TaskHandle {
        let id = {
            let mut inner = self.inner.borrow_mut();
            let id = inner.next_id;
            inner.next_id = inner.next_id.wrapping_add(1);
            id
        };

        let cancelled = Rc::new(Cell::new(false));
        let waker =
            Waker::from(Arc::new(TaskWake { id, ready: Arc::clone(&self.ready), wake: Arc::clone(&self.wake) }));

        self.inner.borrow_mut().tasks.insert(id, TaskEntry { future, waker, cancelled: Rc::clone(&cancelled) });
        if let Ok(mut ready) = self.ready.lock() {
            ready.push_back(id);
        }
        (self.wake)();

        TaskHandle { id, inner: Rc::downgrade(&self.inner), cancelled }
    }

    /// 轮询当前就绪队列;返回本轮实际 poll 的任务数。
    ///
    /// 在 UI 线程调用。任务在 poll 中新 spawn 的任务也会在同一轮处理
    /// (最多 MAX_POLLS_PER_TURN 个)。
    pub fn poll_ready(&self) -> usize {
        let mut polled = 0;
        for _ in 0..MAX_POLLS_PER_TURN {
            let id = match self.ready.lock() {
                Ok(mut ready) => ready.pop_front(),
                Err(_) => return polled,
            };
            let Some(id) = id else {
                return polled;
            };
            let Some(mut entry) = self.inner.borrow_mut().tasks.remove(&id) else {
                continue;
            };
            if entry.cancelled.get() {
                continue;
            }

            polled += 1;
            let waker = entry.waker.clone();
            let mut cx = Context::from_waker(&waker);
            let result = std::panic::catch_unwind(AssertUnwindSafe(|| entry.future.as_mut().poll(&mut cx)));
            match result {
                Ok(Poll::Ready(())) => {}
                Ok(Poll::Pending) => {
                    // 回调里可能已 cancel 自己:不再放回队列
                    if !entry.cancelled.get() {
                        self.inner.borrow_mut().tasks.insert(id, entry);
                    }
                }
                Err(payload) => {
                    log::error!(
                        target: "mgui_async",
                        "task {id} panicked: {}",
                        panic_message(payload.as_ref())
                    );
                }
            }
        }

        // 达到上限时不再立即 wake:剩余任务留给下一帧,避免自唤醒 future
        // 在单次事件循环里长时间独占 UI 线程(调用方会因 polled>0 请求重绘)。
        polled
    }

    pub fn len(&self) -> usize {
        self.inner.borrow().tasks.len()
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl std::fmt::Debug for TaskExecutor {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TaskExecutor").field("pending", &self.len()).finish_non_exhaustive()
    }
}

struct BlockingState<T> {
    value: Option<Result<T, String>>,
    waker: Option<Waker>,
}

struct BlockingFuture<T> {
    state: Arc<Mutex<BlockingState<T>>>,
}

impl<T> Future for BlockingFuture<T> {
    type Output = Result<T, String>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let mut state = match self.state.lock() {
            Ok(state) => state,
            Err(_) => return Poll::Ready(Err("blocking task state poisoned".to_string())),
        };
        if let Some(value) = state.value.take() {
            return Poll::Ready(value);
        }
        state.waker = Some(cx.waker().clone());
        Poll::Pending
    }
}

struct TaskWake {
    id: TaskId,
    ready: Arc<Mutex<VecDeque<TaskId>>>,
    wake: WakeCallback,
}

impl Wake for TaskWake {
    fn wake(self: Arc<Self>) {
        self.wake_by_ref();
    }

    fn wake_by_ref(self: &Arc<Self>) {
        if let Ok(mut ready) = self.ready.lock() {
            ready.push_back(self.id);
        }
        (self.wake)();
    }
}

fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
    if let Some(s) = payload.downcast_ref::<&str>() {
        (*s).to_string()
    } else if let Some(s) = payload.downcast_ref::<String>() {
        s.clone()
    } else {
        "unknown panic payload".to_string()
    }
}

// =================================================================
// 简易 sleep(后台线程定时;示例/测试用,大量定时器后续换 timer wheel)
// =================================================================

struct SleepState {
    done: bool,
    waker: Option<Waker>,
}

/// 在后台线程计时的 sleep future。
///
/// 每次 sleep 创建一个短生命周期线程,适合示例与小规模异步 IO 模拟;
/// 高频定时器场景后续应替换为集中式 timer wheel。
pub struct Sleep {
    duration: Duration,
    state: Arc<Mutex<SleepState>>,
    started: bool,
}

pub fn sleep(duration: Duration) -> Sleep {
    Sleep { duration, state: Arc::new(Mutex::new(SleepState { done: false, waker: None })), started: false }
}

impl Future for Sleep {
    type Output = ();

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
        let this = self.get_mut();
        let mut state = match this.state.lock() {
            Ok(state) => state,
            Err(_) => return Poll::Ready(()),
        };
        if state.done {
            return Poll::Ready(());
        }

        if !this.started {
            this.started = true;
            let sleep_state = Arc::clone(&this.state);
            let duration = this.duration;
            let spawned = std::thread::Builder::new().name("mgui-sleep".to_string()).spawn(move || {
                std::thread::sleep(duration);
                if let Ok(mut state) = sleep_state.lock() {
                    state.done = true;
                    if let Some(waker) = state.waker.take() {
                        drop(state);
                        waker.wake();
                    }
                }
            });
            if spawned.is_err() {
                // 线程创建失败:同步完成,避免任务永久挂起
                state.done = true;
                return Poll::Ready(());
            }
        }

        state.waker = Some(cx.waker().clone());
        Poll::Pending
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::time::Instant;

    fn noop_wake() -> WakeCallback {
        Arc::new(|| {})
    }

    #[test]
    fn ready_task_runs_and_calls_back() {
        let executor = TaskExecutor::new(noop_wake());
        let value = Rc::new(Cell::new(0));
        let out = Rc::clone(&value);
        let _handle = executor.spawn_with(async { 7 }, move |v| out.set(v));

        assert_eq!(executor.poll_ready(), 1);
        assert_eq!(value.get(), 7);
        assert!(executor.is_empty());
    }

    #[test]
    fn waker_requeues_pending_task() {
        struct WakeOnce(bool);
        impl Future for WakeOnce {
            type Output = ();
            fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
                if self.0 {
                    Poll::Ready(())
                } else {
                    self.0 = true;
                    cx.waker().wake_by_ref();
                    Poll::Pending
                }
            }
        }

        let executor = TaskExecutor::new(noop_wake());
        let done = Rc::new(Cell::new(false));
        let out = Rc::clone(&done);
        let _handle = executor.spawn_with(WakeOnce(false), move |_| out.set(true));

        assert_eq!(executor.poll_ready(), 2);
        assert!(done.get());
        assert!(executor.is_empty());
    }

    #[test]
    fn cancel_drops_task_without_callback() {
        struct Never;
        impl Future for Never {
            type Output = ();
            fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<()> {
                Poll::Pending
            }
        }

        let executor = TaskExecutor::new(noop_wake());
        let called = Rc::new(Cell::new(false));
        let out = Rc::clone(&called);
        let handle = executor.spawn_with(Never, move |_| out.set(true));

        handle.cancel();
        assert_eq!(executor.poll_ready(), 0);
        assert!(!called.get());
        assert!(executor.is_empty());
    }

    #[test]
    fn panic_isolated_from_other_tasks() {
        let executor = TaskExecutor::new(noop_wake());
        let done = Rc::new(Cell::new(false));
        let out = Rc::clone(&done);

        let _panicking = executor.spawn(async {
            panic!("intentional task panic");
        });
        let _healthy = executor.spawn_with(async {}, move |_| out.set(true));

        assert_eq!(executor.poll_ready(), 2);
        assert!(done.get(), "panic task 不得阻止其它任务完成");
        assert!(executor.is_empty());
    }

    #[test]
    fn sleep_completes_via_background_waker() {
        let executor = TaskExecutor::new(noop_wake());
        let done = Rc::new(Cell::new(false));
        let out = Rc::clone(&done);
        let _handle = executor.spawn_with(sleep(Duration::from_millis(20)), move |_| out.set(true));

        let start = Instant::now();
        while !done.get() && start.elapsed() < Duration::from_secs(2) {
            executor.poll_ready();
            std::thread::sleep(Duration::from_millis(2));
        }

        assert!(done.get(), "sleep 任务应在后台 waker 唤醒后完成");
        assert!(executor.is_empty());
    }

    #[test]
    fn spawn_during_poll_is_driven_same_turn() {
        let executor = TaskExecutor::new(noop_wake());
        let executor_for_task = executor.clone();
        let done = Rc::new(Cell::new(false));
        let out = Rc::clone(&done);

        let _outer = executor.spawn(async move {
            executor_for_task.spawn_with(async {}, move |_| out.set(true));
        });

        assert_eq!(executor.poll_ready(), 2);
        assert!(done.get());
        assert!(executor.is_empty());
    }

    #[test]
    fn spawn_blocking_returns_result_on_ui_thread() {
        let executor = TaskExecutor::new(noop_wake());
        let value = Rc::new(Cell::new(0));
        let out = Rc::clone(&value);
        let _handle = executor.spawn_blocking(|| Ok(42), move |result| out.set(result.unwrap_or_default()));

        let start = Instant::now();
        while value.get() == 0 && start.elapsed() < Duration::from_secs(2) {
            executor.poll_ready();
            std::thread::sleep(Duration::from_millis(2));
        }
        assert_eq!(value.get(), 42);
        assert!(executor.is_empty());
    }

    #[test]
    fn spawn_blocking_panic_becomes_error() {
        let executor = TaskExecutor::new(noop_wake());
        let failed = Rc::new(Cell::new(false));
        let out = Rc::clone(&failed);
        let _handle = executor.spawn_blocking(
            || -> Result<(), String> { panic!("blocking panic") },
            move |result| out.set(result.is_err()),
        );

        let start = Instant::now();
        while !failed.get() && start.elapsed() < Duration::from_secs(2) {
            executor.poll_ready();
            std::thread::sleep(Duration::from_millis(2));
        }
        assert!(failed.get());
    }

    #[test]
    fn wake_callback_invoked_for_cross_thread_spawn() {
        let woke = Arc::new(AtomicBool::new(false));
        let flag = Arc::clone(&woke);
        let executor = TaskExecutor::new(Arc::new(move || {
            flag.store(true, Ordering::SeqCst);
        }));

        let _handle = executor.spawn(async {});
        assert!(woke.load(Ordering::SeqCst), "spawn 应唤醒事件循环");
        executor.poll_ready();
    }
}