whisker-runtime 0.18.0

Host-independent Whisker runtime: reactivity, retained elements, layout, and frames.
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
//! Single-threaded async task host.
//!
//! Whisker runs UI on a Host-owned UI thread. To let user code write plain
//! `async fn` without pulling in Tokio, each [`RuntimeContext`](crate::RuntimeContext)
//! owns a [`futures_executor::LocalPool`] that is activated and polled
//! cooperatively from the Host's frame callback.
//!
//! - [`spawn_local`] queues a `Future<Output = ()>` for execution on
//!   the next runtime drive.
//! - [`run_until_stalled`] (crate-internal) drains pending tasks
//!   until they're all blocked on something. `RuntimeInstance` calls this
//!   between reactive flushes.
//! - [`run_blocking`] runs a *synchronous* closure on a fresh worker
//!   thread and returns a `Future<Output = T>` that resolves on the
//!   UI runtime once the closure finishes. Used by [`resource`] and
//!   directly by user code that needs to call sync IO (`ureq`,
//!   filesystem, …) from inside an `async fn`.
//!
//! ## Threading model
//!
//! The local pool is single-threaded and active only while its runtime context
//! is entered, so spawned futures need not be `Send`. The `Waker` side is
//! `Send + Sync`: it captures the instance's any-thread Host wake handle and
//! never polls UI code on the waking thread.
//!
//! [`resource`]: crate::reactive::resource()

use std::cell::RefCell;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use futures_executor::{LocalPool, LocalSpawner};
use futures_util::task::{ArcWake, LocalSpawnExt, waker_ref};

thread_local! {
    static TASKS: RefCell<TaskState> = RefCell::new(TaskState::new());
}

pub(crate) struct TaskState {
    // Kept behind its own RefCell so polling the pool does not mutably
    // borrow the whole TaskState. A running task may legitimately call
    // `spawn_local`; that only needs the independent spawner.
    pool: RefCell<LocalPool>,
    spawner: LocalSpawner,
}

impl TaskState {
    pub(crate) fn new() -> Self {
        let pool = LocalPool::new();
        let spawner = pool.spawner();
        Self {
            pool: RefCell::new(pool),
            spawner,
        }
    }
}

pub(crate) fn swap_state(state: &mut TaskState) {
    TASKS.with_borrow_mut(|active| std::mem::swap(active, state));
}

/// The "request a main-loop drive" hook invoked by a task's [`Waker`]
/// when it is woken from ANY thread.
///
/// # Why this exists
///
/// `LocalPool`'s built-in waker only re-queues the task into the pool's
/// ready-queue; it does not poke the native main loop. The pool is
/// re-polled only from the driver's `tick_frame` →
/// [`run_until_stalled`], so a task awaiting a future that completes on
/// a FOREIGN thread (a tokio runtime thread, a `std::thread` worker)
/// would be re-queued and never re-polled — hanging for as long as
/// vsync stays parked. Every spawned future is therefore polled through
/// a [`DriveWaker`] that forwards to the pool's inner waker AND calls
/// this hook.
///
/// In production the hook is [`request_main_loop_drive`]. Tests can
/// override it via [`set_drive_hook`] to observe wakes without a full
/// main-loop harness.
type DriveHook = fn();

static DRIVE_HOOK: std::sync::Mutex<DriveHook> = std::sync::Mutex::new(request_main_loop_drive);

/// Production drive hook: ask the host to run another drive of the
/// runtime (which calls [`run_until_stalled`]).
///
/// The Host callback is any-thread-safe and coalesces the request onto its UI
/// event loop. The re-queued task is picked up by the in-flight drain or the
/// next scheduled frame.
fn request_main_loop_drive() {
    crate::runtime_wake::wake_runtime();
}

/// Install a custom drive hook. Returns the previous hook so callers
/// (tests) can restore it.
#[doc(hidden)]
pub fn set_drive_hook(hook: DriveHook) -> DriveHook {
    let mut guard = DRIVE_HOOK.lock().unwrap_or_else(|e| e.into_inner());
    std::mem::replace(&mut *guard, hook)
}

fn invoke_drive_hook() {
    let hook = *DRIVE_HOOK.lock().unwrap_or_else(|e| e.into_inner());
    hook();
}

/// A `Waker` that bridges a foreign-thread wake to Whisker's main
/// loop.
///
/// Holds the pool's own inner `Waker` for the task, so waking still
/// re-queues it into `LocalPool`'s ready-queue and the stock
/// same-thread / self-wake behaviour is preserved; then calls the drive
/// hook so the main loop actually re-polls. Safe from any thread — the
/// inner waker is `Send + Sync` and the Host wake contract is any-thread-safe.
struct DriveWaker {
    inner: std::task::Waker,
    wake: Option<crate::runtime_wake::RuntimeWakeHandle>,
}

impl ArcWake for DriveWaker {
    fn wake_by_ref(arc_self: &Arc<Self>) {
        arc_self.inner.wake_by_ref();
        if let Some(wake) = &arc_self.wake {
            wake.wake();
        } else {
            invoke_drive_hook();
        }
    }
}

/// Wraps a spawned future so that it is always polled with a
/// [`DriveWaker`]-composed `Context`.
///
/// `LocalPool` polls this wrapper with ITS waker (`cx.waker()`); the
/// user future is polled with a `DriveWaker` built around that one, so
/// whatever waker the user future stashes — and later wakes, possibly
/// from a foreign thread — is the drive-bridging one rather than the
/// bare pool waker.
struct DriveBridged<F: 'static> {
    future: crate::lifetime::Scoped<TaskFuture<F>>,
}

struct TaskFuture<F> {
    future: Pin<Box<F>>,
    wake_on_cancel: Option<std::task::Waker>,
}

impl<F> Drop for TaskFuture<F> {
    fn drop(&mut self) {
        if let Some(waker) = self.wake_on_cancel.take() {
            waker.wake();
        }
    }
}

impl<F: Future<Output = ()> + 'static> Future for DriveBridged<F> {
    type Output = ();
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
        let drive_waker = Arc::new(DriveWaker {
            inner: cx.waker().clone(),
            wake: crate::runtime_wake::current_wake_handle(),
        });
        let waker = waker_ref(&drive_waker);
        let mut cx = Context::from_waker(&waker);
        self.future
            .with_mut(|task| {
                task.wake_on_cancel = Some(cx.waker().clone());
                let result = task.future.as_mut().poll(&mut cx);
                if result.is_ready() {
                    task.wake_on_cancel = None;
                }
                result
            })
            .unwrap_or(Poll::Ready(()))
    }
}

/// Queue `future` for execution on Whisker's task pool.
///
/// The future is polled on the Host UI thread by the next drive after
/// either:
/// - [`crate::runtime_wake::wake_runtime`] fires (the future's `Waker`
///   was woken from anywhere), or
/// - any other reactive activity drove a tick to begin with.
///
/// The future is not required to be `Send` — Whisker's task pool is
/// strictly single-threaded.
///
/// Returns nothing because once spawned a task is owned by the pool;
/// its registering Owner cancels it on disposal. Use [`run_blocking`] when you want
/// a typed result back into an `async fn` body.
///
/// # Panics
///
/// Panics outside an entered Runtime, during shutdown, or when the current Owner is closing.
pub fn spawn_local<F>(future: F)
where
    F: Future<Output = ()> + 'static,
{
    let _ = spawn_cancelable(future);
}

pub(crate) fn spawn_cancelable<F>(future: F) -> crate::lifetime::Cancellation
where
    F: Future<Output = ()> + 'static,
{
    crate::reactive::error::invariant!(
        crate::runtime_dispatcher().is_some(),
        "spawn_local requires an entered Runtime"
    );
    let future = crate::lifetime::Scoped::new(TaskFuture {
        future: Box::pin(future),
        wake_on_cancel: None,
    });
    let cancellation = future.cancellation();
    TASKS.with(|tasks| {
        tasks
            .borrow()
            .spawner
            .spawn_local(DriveBridged { future })
            .expect("whisker tasks: local pool is shut down");
    });
    crate::runtime_wake::wake_runtime();
    cancellation
}

/// Drain pending tasks until they're all pending on external events.
///
/// The driver's tick callback wires this in alongside the reactive
/// flush. Calling it from user code is OK but pointless — the
/// runtime already drives it every tick.
pub fn run_until_stalled() {
    TASKS.with(|tasks| {
        tasks.borrow().pool.borrow_mut().run_until_stalled();
    });
}

/// Offload a synchronous closure to a fresh worker thread and return
/// a future that resolves once the closure completes.
///
/// Use this from inside an `async fn` (or `resource`'s fetcher) when
/// you need to call blocking sync IO (`ureq`, `std::fs`, a sync DB
/// driver) without freezing the Host UI thread. Sending the result wakes the
/// task's internal drive-aware waker, which
/// requests the correct runtime instance from any thread; the future itself
/// remains polled only on the Host UI thread.
///
/// `T` must be `Send + 'static` so it can cross the thread boundary.
/// `F` must be `Send + 'static` for the same reason.
///
/// ```ignore
/// resource(|| async move {
///     let body = run_blocking(|| {
///         ureq::get("https://example.com").call()
///             .map_err(|e| e.to_string())?
///             .into_string()
///             .map_err(|e| e.to_string())
///     }).await?;
///     parse(body)
/// })
/// ```
pub fn run_blocking<F, T>(closure: F) -> impl Future<Output = T>
where
    F: FnOnce() -> T + Send + 'static,
    T: Send + 'static,
{
    let (tx, rx) = futures_channel::oneshot::channel::<T>();
    std::thread::spawn(move || {
        let value = closure();
        // `send` fails only when the awaiting half was dropped because its
        // owner was disposed mid-fetch. Waking is any-thread safe; polling
        // still happens only when the Host next enters this runtime context.
        let _ = tx.send(value);
    });
    BlockingResult { rx }
}

/// Adapter so `run_blocking`'s return type doesn't leak
/// `futures_channel::oneshot::Receiver`. Pollable as a
/// `Future<Output = T>`; if the sender is dropped (owner disposed
/// mid-fetch) the future parks forever rather than panicking, and the
/// awaiting task is collected when its enclosing owner cascade fires.
struct BlockingResult<T> {
    rx: futures_channel::oneshot::Receiver<T>,
}

impl<T> Future for BlockingResult<T> {
    type Output = T;
    fn poll(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<T> {
        use std::task::Poll;
        match std::pin::Pin::new(&mut self.rx).poll(cx) {
            Poll::Ready(Ok(v)) => Poll::Ready(v),
            // A worker panic leaves no result; owner cancellation still drops this receiver.
            Poll::Ready(Err(_)) => Poll::Pending,
            Poll::Pending => Poll::Pending,
        }
    }
}

/// (Test only) reset the executor — drops all queued tasks. Use
/// between unit tests that exercise the pool so leftover work
/// doesn't bleed across.
#[doc(hidden)]
pub fn __reset_for_tests() {
    clear();
}

pub(crate) fn clear() {
    let removed = TASKS.with_borrow_mut(|tasks| std::mem::replace(tasks, TaskState::new()));
    drop(removed);
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::Cell;
    use std::rc::Rc;
    use std::sync::MutexGuard;

    fn lock<'a>() -> MutexGuard<'a, ()> {
        crate::runtime_wake::host_test_lock()
    }

    fn reset_all() {
        __reset_for_tests();
        crate::runtime_wake::__reset_for_tests();
    }

    #[test]
    fn spawn_local_does_not_block_poll_at_call_time() {
        let runtime = crate::RuntimeContext::new(crate::RuntimeWakeHandle::new(|| {}));
        runtime.enter(|| {
            let _g = lock();
            reset_all();
            let flag = Rc::new(Cell::new(false));
            let f = flag.clone();
            spawn_local(async move {
                f.set(true);
            });
            assert!(!flag.get(), "spawn should not poll synchronously");
            run_until_stalled();
            assert!(flag.get(), "tick should drive the task to completion");
        });
    }

    #[test]
    fn run_until_stalled_drains_multiple_independent_tasks() {
        let runtime = crate::RuntimeContext::new(crate::RuntimeWakeHandle::new(|| {}));
        runtime.enter(|| {
            let _g = lock();
            reset_all();
            let counter = Rc::new(Cell::new(0));
            for _ in 0..5 {
                let c = counter.clone();
                spawn_local(async move {
                    c.set(c.get() + 1);
                });
            }
            run_until_stalled();
            assert_eq!(counter.get(), 5);
        });
    }

    #[test]
    fn running_task_can_spawn_another_local_task() {
        let runtime = crate::RuntimeContext::new(crate::RuntimeWakeHandle::new(|| {}));
        runtime.enter(|| {
            let _g = lock();
            reset_all();
            let phase = Rc::new(Cell::new(0));
            let outer_phase = phase.clone();
            spawn_local(async move {
                outer_phase.set(1);
                let inner_phase = outer_phase.clone();
                spawn_local(async move {
                    inner_phase.set(2);
                });
            });

            run_until_stalled();

            assert_eq!(phase.get(), 2);
        });
    }

    /// Future that returns Pending on its first poll (re-waking
    /// itself), Ready on the second.
    struct Yielder {
        phase: Rc<Cell<i32>>,
        polled_once: bool,
    }
    impl Future for Yielder {
        type Output = ();
        fn poll(
            mut self: std::pin::Pin<&mut Self>,
            cx: &mut std::task::Context<'_>,
        ) -> std::task::Poll<()> {
            if !self.polled_once {
                self.polled_once = true;
                self.phase.set(1);
                cx.waker().wake_by_ref();
                std::task::Poll::Pending
            } else {
                self.phase.set(2);
                std::task::Poll::Ready(())
            }
        }
    }

    #[test]
    fn run_until_stalled_resumes_self_woken_tasks_within_one_call() {
        let runtime = crate::RuntimeContext::new(crate::RuntimeWakeHandle::new(|| {}));
        runtime.enter(|| {
            let _g = lock();
            reset_all();
            let phase = Rc::new(Cell::new(0));
            let phase_for_task = phase.clone();
            spawn_local(async move {
                Yielder {
                    phase: phase_for_task,
                    polled_once: false,
                }
                .await;
            });
            run_until_stalled();
            assert_eq!(phase.get(), 2);
        });
    }

    #[test]
    fn run_blocking_returns_value_from_worker_thread() {
        let runtime = crate::RuntimeContext::new(crate::RuntimeWakeHandle::new(|| {}));
        runtime.enter(|| {
            let _g = lock();
            reset_all();

            let got: Rc<RefCell<Option<i32>>> = Rc::new(RefCell::new(None));
            let got_for_task = got.clone();
            spawn_local(async move {
                let v = run_blocking(|| 42_i32).await;
                *got_for_task.borrow_mut() = Some(v);
            });

            // The worker may not have scheduled yet, so poll-loop with a
            // cap until the value lands.
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
            while got.borrow().is_none() && std::time::Instant::now() < deadline {
                run_until_stalled();
                std::thread::sleep(std::time::Duration::from_millis(5));
            }
            assert_eq!(*got.borrow(), Some(42));
        });
    }

    #[test]
    fn run_blocking_completion_does_not_require_legacy_dispatcher() {
        let runtime = crate::RuntimeContext::new(crate::RuntimeWakeHandle::new(|| {}));
        runtime.enter(|| {
            let _g = lock();
            reset_all();
            let polled = Rc::new(Cell::new(false));
            let polled_for_task = polled.clone();
            spawn_local(async move {
                let _v: () = run_blocking(|| {}).await;
                polled_for_task.set(true);
            });
            for _ in 0..20 {
                run_until_stalled();
                std::thread::sleep(std::time::Duration::from_millis(5));
            }
            assert!(
                polled.get(),
                "the result channel and task waker must work through the Host wake callback"
            );
        });
    }

    /// A future that parks on its first poll, stashing its `Waker` in a
    /// shared slot, and resolves once an external (foreign-thread)
    /// signal has been set. Models awaiting an I/O completion that is
    /// resolved off the main thread (e.g. a tokio runtime thread).
    struct ForeignSignal {
        done: Arc<std::sync::atomic::AtomicBool>,
        waker_slot: Arc<std::sync::Mutex<Option<std::task::Waker>>>,
    }
    impl Future for ForeignSignal {
        type Output = ();
        fn poll(
            self: std::pin::Pin<&mut Self>,
            cx: &mut std::task::Context<'_>,
        ) -> std::task::Poll<()> {
            if self.done.load(std::sync::atomic::Ordering::SeqCst) {
                std::task::Poll::Ready(())
            } else {
                // Stash the (drive-bridging) waker so a foreign thread
                // can wake us later.
                *self.waker_slot.lock().unwrap() = Some(cx.waker().clone());
                std::task::Poll::Pending
            }
        }
    }

    #[test]
    fn foreign_thread_wake_invokes_drive_hook_and_resumes_task() {
        let runtime = crate::RuntimeContext::new(crate::RuntimeWakeHandle::new(|| {}));
        runtime.enter(|| {
            use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
            let _g = lock();
            reset_all();

            // The test hook counts pokes; the re-poll the real DRIVE
            // callback would do is done explicitly below.
            static DRIVE_POKES: AtomicUsize = AtomicUsize::new(0);
            DRIVE_POKES.store(0, Ordering::SeqCst);
            fn test_hook() {
                DRIVE_POKES.fetch_add(1, Ordering::SeqCst);
            }
            let prev = set_drive_hook(test_hook);

            let done = Arc::new(AtomicBool::new(false));
            let waker_slot: Arc<std::sync::Mutex<Option<std::task::Waker>>> =
                Arc::new(std::sync::Mutex::new(None));
            let completed = Rc::new(Cell::new(false));

            let done_for_task = done.clone();
            let slot_for_task = waker_slot.clone();
            let completed_for_task = completed.clone();
            spawn_local(async move {
                ForeignSignal {
                    done: done_for_task,
                    waker_slot: slot_for_task,
                }
                .await;
                completed_for_task.set(true);
            });

            run_until_stalled();
            assert!(!completed.get(), "task should be parked awaiting signal");
            assert!(
                waker_slot.lock().unwrap().is_some(),
                "task must have stashed its waker on the first poll"
            );

            // Complete the future from a SEPARATE std::thread — the
            // foreign-thread wake this test exists for.
            let done_for_thread = done.clone();
            let slot_for_thread = waker_slot.clone();
            let handle = std::thread::spawn(move || {
                done_for_thread.store(true, Ordering::SeqCst);
                let waker = slot_for_thread.lock().unwrap().take().unwrap();
                waker.wake();
            });
            handle.join().unwrap();

            assert!(
                DRIVE_POKES.load(Ordering::SeqCst) >= 1,
                "foreign-thread wake must invoke the drive hook so the main \
             loop re-polls the pool (issue #7)"
            );

            // Stand in for the DRIVE callback the hook would have triggered.
            run_until_stalled();
            assert!(
                completed.get(),
                "task must resume and complete after the foreign-thread wake \
             drove a re-poll"
            );

            set_drive_hook(prev);
        });
    }

    #[test]
    fn reset_clears_pending_tasks() {
        let runtime = crate::RuntimeContext::new(crate::RuntimeWakeHandle::new(|| {}));
        runtime.enter(|| {
            let _g = lock();
            reset_all();
            let counter = Rc::new(Cell::new(0));
            let c = counter.clone();
            spawn_local(async move {
                c.set(c.get() + 1);
            });
            __reset_for_tests();
            run_until_stalled();
            assert_eq!(counter.get(), 0, "reset should drop pending tasks");
        });
    }

    #[test]
    fn spawn_local_after_reset_uses_fresh_spawner() {
        let runtime = crate::RuntimeContext::new(crate::RuntimeWakeHandle::new(|| {}));
        runtime.enter(|| {
            // `__reset_for_tests` must rebuild SPAWNER from the fresh POOL,
            // or later `spawn_local` calls enqueue onto the dead one.
            let _g = lock();
            reset_all();
            __reset_for_tests();
            let flag = Rc::new(Cell::new(false));
            let f = flag.clone();
            spawn_local(async move {
                f.set(true);
            });
            run_until_stalled();
            assert!(
                flag.get(),
                "spawner must be re-bound to the new pool after reset"
            );
        });
    }
}