Skip to main content

ntex_util/
task.rs

1//! Task wake-up and scheduling utilities.
2use std::{cell::Cell, fmt, task::Waker};
3
4/// A single-threaded synchronization primitive for task wake-up.
5///
6/// Sometimes the task interested in a given event will change over time.
7/// A `LocalWaker` can coordinate notifications with the consumer
8/// potentially "updating" the underlying task to wake up. This is useful in
9/// scenarios where a computation completes in another task and wants to
10/// notify the consumer, but the consumer is in the process of being migrated to
11/// a new logical task.
12///
13/// Consumers should call `register` before checking the result of a computation
14/// and producers should call `wake` after producing the computation (this
15/// differs from the usual `thread::park` pattern). It is also permitted for
16/// `wake` to be called **before** `register`. This results in a no-op.
17///
18/// A single `LocalWaker` may be reused for any number of calls to `register` or
19/// `wake`.
20///
21/// The slot and its owned local handle must remain on their acquiring thread.
22/// Use [`take`](Self::take) to transfer a registered standard waker instead.
23///
24/// ```compile_fail
25/// fn assert_send<T: Send>() {}
26/// assert_send::<ntex_util::task::LocalWaker>();
27/// ```
28///
29/// ```compile_fail
30/// fn assert_sync<T: Sync>() {}
31/// assert_sync::<ntex_util::task::LocalWaker>();
32/// ```
33#[derive(Default)]
34pub struct LocalWaker {
35    waker: Cell<Option<ntex_rt::LocalWaker>>,
36}
37
38#[cfg(target_pointer_width = "64")]
39const _: () = assert!(size_of::<LocalWaker>() == 16);
40
41impl LocalWaker {
42    /// Creates an empty `LocalWaker`.
43    pub fn new() -> Self {
44        LocalWaker::with(None)
45    }
46
47    /// Creates a `LocalWaker` with an optional initial waker.
48    pub fn with(waker: Option<Waker>) -> Self {
49        LocalWaker {
50            waker: Cell::new(waker.map(ntex_rt::LocalWaker::from)),
51        }
52    }
53
54    #[inline]
55    /// Registers the waker to be notified on calls to `wake`.
56    ///
57    /// Returns `true` if a waker was already registered.
58    ///
59    /// If cloning the replacement panics, the previous registration is retained
60    /// unless the clone callback itself changes the slot.
61    pub fn register(&self, waker: &Waker) -> bool {
62        let prev = self.waker.take();
63        let registered = prev.is_some();
64        let same = prev.as_ref().is_some_and(|prev| prev.will_wake(waker));
65        self.waker.set(prev);
66        if !same {
67            // Clone and drop callbacks may reenter the slot. Keep the old
68            // registration until cloning succeeds, then publish before dropping.
69            let next = ntex_rt::LocalWaker::from_waker(waker);
70            drop(self.waker.replace(Some(next)));
71        }
72        registered
73    }
74
75    /// Registers `waker` in the slot returned by `slot`, like [`register`](Self::register).
76    ///
77    /// Waker clone and drop callbacks may reenter the owner of the slot and
78    /// move or mutate it. `slot` is called again after every callback, so it
79    /// must derive a fresh reference from the owner each time. No reference
80    /// to the slot is kept while a callback runs.
81    pub(crate) fn register_in<'a>(slot: impl Fn() -> &'a LocalWaker, waker: &Waker) -> bool {
82        let prev = slot().waker.take();
83        let registered = prev.is_some();
84        let same = prev.as_ref().is_some_and(|prev| prev.will_wake(waker));
85        slot().waker.set(prev);
86        if !same {
87            let next = ntex_rt::LocalWaker::from_waker(waker);
88            let prev = slot().waker.replace(Some(next));
89            drop(prev);
90        }
91        registered
92    }
93
94    #[inline]
95    /// Calls `wake` on the last `Waker` passed to `register`.
96    ///
97    /// The waker is consumed, so a later `wake` does nothing until `register`
98    /// is called again. If no waker is registered, this does nothing.
99    pub fn wake(&self) {
100        if let Some(waker) = self.take_local() {
101            waker.wake();
102        }
103    }
104
105    #[inline]
106    /// Calls `wake` on the last `Waker` passed to `register`.
107    ///
108    /// Returns `false` if no waker is registered. Like [`wake`](Self::wake),
109    /// this consumes the registered waker.
110    pub fn wake_checked(&self) -> bool {
111        if let Some(waker) = self.take_local() {
112            waker.wake();
113            true
114        } else {
115            false
116        }
117    }
118
119    /// Returns the last `Waker` passed to `register`, so that the user can wake it.
120    ///
121    /// This empties the slot and converts the owned handle into a thread-safe
122    /// standard waker without cloning. If no waker is registered, returns `None`.
123    /// Use [`take_local`](Self::take_local) to retain native local operations.
124    pub fn take(&self) -> Option<Waker> {
125        self.take_local().map(ntex_rt::LocalWaker::into_waker)
126    }
127
128    /// Takes the registered wake handle, leaving the slot empty.
129    ///
130    /// The returned handle retains native local operations and cannot be sent
131    /// to another thread. If no waker is registered, returns `None`.
132    #[inline]
133    pub fn take_local(&self) -> Option<ntex_rt::LocalWaker> {
134        self.waker.take()
135    }
136
137    #[doc(hidden)]
138    /// Returns `true` if a waker is registered.
139    pub fn is_set(&self) -> bool {
140        let waker = self.waker.take();
141        let set = waker.is_some();
142        self.waker.set(waker);
143        set
144    }
145}
146
147/// Cloning creates an empty `LocalWaker`; the registered waker is not copied.
148impl Clone for LocalWaker {
149    fn clone(&self) -> Self {
150        LocalWaker::new()
151    }
152}
153
154impl fmt::Debug for LocalWaker {
155    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156        write!(f, "LocalWaker")
157    }
158}
159
160/// Yields execution back to the current runtime.
161pub async fn yield_to() {
162    use std::{future::Future, pin::Pin, task::Context, task::Poll};
163
164    struct Yield {
165        completed: bool,
166    }
167
168    impl Future for Yield {
169        type Output = ();
170
171        fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
172            if self.completed {
173                return Poll::Ready(());
174            }
175
176            self.completed = true;
177            cx.waker().wake_by_ref();
178
179            Poll::Pending
180        }
181    }
182
183    Yield { completed: false }.await;
184}
185
186#[cfg(test)]
187mod test {
188    use super::*;
189
190    /// STATEMENT: `yield_to` returns `Pending` once and wakes its own task, then completes on
191    /// the next poll.
192    ///
193    /// HOW:
194    /// - Poll `yield_to` by hand with a waker that counts wake-ups.
195    /// - Expect `Pending` and one wake-up on the first poll.
196    /// - Expect `Ready` and no further wake-up on the second poll.
197    #[test]
198    fn yield_test() {
199        use std::sync::{Arc, atomic::AtomicUsize, atomic::Ordering};
200        use std::{future::Future, pin::pin, task::Context, task::Wake, task::Waker};
201
202        struct Counter(AtomicUsize);
203        impl Wake for Counter {
204            fn wake(self: Arc<Self>) {
205                self.0.fetch_add(1, Ordering::Relaxed);
206            }
207        }
208
209        let counter = Arc::new(Counter(AtomicUsize::new(0)));
210        let waker = Waker::from(counter.clone());
211        let mut cx = Context::from_waker(&waker);
212        let mut fut = pin!(yield_to());
213
214        assert!(fut.as_mut().poll(&mut cx).is_pending());
215        assert_eq!(counter.0.load(Ordering::Relaxed), 1);
216        assert!(fut.as_mut().poll(&mut cx).is_ready());
217        assert_eq!(counter.0.load(Ordering::Relaxed), 1);
218    }
219
220    /// STATEMENT: Local and standard slot wake paths reschedule the current task.
221    ///
222    /// HOW:
223    /// - Register and wake through the slot, a taken local waker, and a taken standard waker.
224    /// - Require a fourth poll to finish and verify the slot is empty afterward.
225    #[ntex::test]
226    async fn local_slot_wakes_current_task() {
227        crate::spawn(async {
228            let slot = LocalWaker::new();
229            let mut polls = 0;
230            std::future::poll_fn(|cx| {
231                polls += 1;
232                if polls == 4 {
233                    return std::task::Poll::Ready(());
234                }
235                assert!(!slot.register(cx.waker()));
236                match polls {
237                    1 => slot.wake(),
238                    2 => slot.take_local().unwrap().wake(),
239                    _ => slot.take().unwrap().wake(),
240                }
241                std::task::Poll::Pending
242            })
243            .await;
244            assert!(!slot.is_set());
245        })
246        .await
247        .unwrap();
248    }
249}
250
251/// Wakers whose callbacks run one-shot hooks, for reentrancy tests.
252#[cfg(test)]
253pub(crate) mod hooks {
254    use std::cell::Cell;
255    use std::task::{RawWaker, RawWakerVTable, Waker};
256    use std::thread::LocalKey;
257
258    pub(crate) type Hook = Cell<Option<Box<dyn FnOnce()>>>;
259
260    // Waker callbacks may run on any thread; local test closures stay in TLS.
261    thread_local! {
262        pub(crate) static ON_CLONE: Hook = Cell::new(None);
263        pub(crate) static ON_DROP: Hook = Cell::new(None);
264        pub(crate) static ON_WAKE: Hook = Cell::new(None);
265    }
266
267    fn run_hook(key: &'static LocalKey<Hook>) {
268        if let Some(hook) = key.with(Cell::take) {
269            hook();
270        }
271    }
272
273    /// Returns a waker that runs the pending `ON_CLONE`, `ON_WAKE` or `ON_DROP` hook.
274    pub(crate) fn hook_waker() -> Waker {
275        static HOOK_VTABLE: RawWakerVTable = RawWakerVTable::new(
276            |p| {
277                run_hook(&ON_CLONE);
278                RawWaker::new(p, &HOOK_VTABLE)
279            },
280            |_| run_hook(&ON_WAKE),
281            |_| run_hook(&ON_WAKE),
282            |_| run_hook(&ON_DROP),
283        );
284        // SAFETY: Callbacks ignore the null data pointer and access only their calling thread's TLS.
285        unsafe { Waker::from_raw(RawWaker::new(std::ptr::null(), &HOOK_VTABLE)) }
286    }
287
288    /// Wake counter for wakers created by [`counted_waker`].
289    #[derive(Default)]
290    pub(crate) struct WakeCount(pub(crate) std::sync::atomic::AtomicUsize);
291
292    impl std::task::Wake for WakeCount {
293        fn wake(self: std::sync::Arc<Self>) {
294            self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
295        }
296    }
297
298    impl WakeCount {
299        pub(crate) fn get(&self) -> usize {
300            self.0.load(std::sync::atomic::Ordering::Relaxed)
301        }
302    }
303
304    /// Returns a distinct waker and the counter of its wake-ups.
305    pub(crate) fn counted_waker() -> (std::sync::Arc<WakeCount>, Waker) {
306        let count = std::sync::Arc::new(WakeCount::default());
307        (count.clone(), Waker::from(count))
308    }
309}
310
311#[cfg(test)]
312mod tests {
313    use std::panic::{AssertUnwindSafe, catch_unwind};
314    use std::rc::Rc;
315    use std::sync::Arc;
316    use std::sync::atomic::{AtomicUsize, Ordering};
317    use std::task::{RawWaker, RawWakerVTable, Wake};
318
319    use super::hooks::{ON_CLONE, ON_DROP, ON_WAKE, hook_waker};
320    use super::*;
321
322    static CLONES: AtomicUsize = AtomicUsize::new(0);
323
324    static VTABLE: RawWakerVTable = RawWakerVTable::new(
325        |p| {
326            CLONES.fetch_add(1, Ordering::Relaxed);
327            RawWaker::new(p, &VTABLE)
328        },
329        |_| {},
330        |_| {},
331        |_| {},
332    );
333
334    #[derive(Default)]
335    struct WakeCounter(AtomicUsize);
336
337    impl Wake for WakeCounter {
338        fn wake(self: Arc<Self>) {
339            self.0.fetch_add(1, Ordering::Relaxed);
340        }
341    }
342
343    fn counted_waker() -> (Arc<WakeCounter>, Waker) {
344        let count = Arc::new(WakeCounter::default());
345        let waker = Waker::from(count.clone());
346        (count, waker)
347    }
348
349    /// STATEMENT: Registering an equivalent waker avoids cloning it again.
350    ///
351    /// HOW:
352    /// - Repeatedly register one raw waker, then replace it with a distinct one.
353    /// - Check clone counts and verify the taken waker matches the replacement.
354    #[test]
355    fn test_register_same_waker() {
356        static A: u8 = 0;
357        static B: u8 = 0;
358        // SAFETY: The static vtable never dereferences the static data and uses only atomic shared state.
359        let a = unsafe { Waker::from_raw(RawWaker::new((&raw const A).cast(), &VTABLE)) };
360        // SAFETY: The same thread-safe vtable ignores this distinct static data pointer.
361        let b = unsafe { Waker::from_raw(RawWaker::new((&raw const B).cast(), &VTABLE)) };
362
363        let w = LocalWaker::new();
364        assert!(!w.register(&a));
365        assert!(w.register(&a));
366        assert!(w.register(&a));
367        assert_eq!(CLONES.load(Ordering::Relaxed), 1);
368
369        assert!(w.register(&b));
370        assert_eq!(CLONES.load(Ordering::Relaxed), 2);
371        assert!(w.take().unwrap().will_wake(&b));
372    }
373
374    /// STATEMENT: Cloning a `LocalWaker` creates an empty slot without clearing the original.
375    ///
376    /// HOW:
377    /// - Clone a registered slot and verify only the original remains set.
378    /// - Check waking the empty clone returns false and inspect the original's debug output.
379    #[test]
380    fn local_waker_clone_is_empty() {
381        let waker = LocalWaker::new();
382        waker.register(std::task::Waker::noop());
383        assert!(waker.is_set());
384        let cloned = waker.clone();
385        assert!(!cloned.is_set());
386        assert!(!cloned.wake_checked());
387        assert!(waker.is_set());
388        assert_eq!(format!("{waker:?}"), "LocalWaker");
389    }
390
391    /// STATEMENT: Owning waker conversions and wake operations consume the slot without cloning.
392    ///
393    /// HOW:
394    /// - Install a clone hook that panics and exercise four owning wake paths.
395    /// - Verify four wakes, empty slots, and an unused clone hook.
396    #[test]
397    fn owning_conversions_and_wakes_do_not_clone() {
398        ON_CLONE.set(Some(Box::new(|| panic!("unexpected clone"))));
399        let calls = Rc::new(Cell::new(0));
400        for path in 0..4 {
401            let calls = calls.clone();
402            ON_WAKE.set(Some(Box::new(move || calls.set(calls.get() + 1))));
403            let slot = LocalWaker::with(Some(hook_waker()));
404            match path {
405                0 => slot.take().unwrap().wake(),
406                1 => slot.take_local().unwrap().wake(),
407                2 => slot.wake(),
408                _ => assert!(slot.wake_checked()),
409            }
410            assert!(slot.take().is_none());
411            assert!(slot.take_local().is_none());
412            assert!(!slot.wake_checked());
413        }
414        assert_eq!(calls.get(), 4);
415        assert!(ON_CLONE.with(Cell::take).is_some());
416    }
417
418    /// STATEMENT: A replacement-waker clone panic preserves the previous registration.
419    ///
420    /// HOW:
421    /// - Register a counted waker, then catch a replacement's clone panic.
422    /// - Wake the slot and verify the original waker receives exactly one wake.
423    #[test]
424    fn clone_panic_preserves_registration() {
425        let (calls, original) = counted_waker();
426        let slot = LocalWaker::with(Some(original));
427        let replacement = hook_waker();
428        ON_CLONE.set(Some(Box::new(|| panic!("clone"))));
429        assert!(catch_unwind(AssertUnwindSafe(|| slot.register(&replacement))).is_err());
430        assert!(slot.wake_checked());
431        assert_eq!(calls.0.load(Ordering::Relaxed), 1);
432    }
433
434    /// STATEMENT: Reentrant clone callbacks retain nested registration when replacement unwinds.
435    ///
436    /// HOW:
437    /// - During replacement cloning, wake the previous waker and register a nested one.
438    /// - Exercise normal and panicking callbacks and check which registration survives.
439    #[test]
440    fn clone_reentry_preserves_nested_changes_on_unwind() {
441        for panic in [false, true] {
442            let (previous_calls, previous) = counted_waker();
443            let (nested_calls, nested) = counted_waker();
444            let slot = Rc::new(LocalWaker::with(Some(previous)));
445            let callback_slot = slot.clone();
446            ON_CLONE.set(Some(Box::new(move || {
447                assert!(callback_slot.wake_checked());
448                assert!(!callback_slot.register(&nested));
449                assert!(!panic, "clone");
450            })));
451            let replacement = hook_waker();
452            let result = catch_unwind(AssertUnwindSafe(|| slot.register(&replacement)));
453            if panic {
454                assert!(result.is_err());
455            } else {
456                assert!(result.unwrap());
457            }
458            assert_eq!(previous_calls.0.load(Ordering::Relaxed), 1);
459            assert!(slot.wake_checked());
460            assert_eq!(nested_calls.0.load(Ordering::Relaxed), usize::from(panic));
461        }
462    }
463
464    /// STATEMENT: Reentrant drop callbacks can replace a newly registered waker even when they panic.
465    ///
466    /// HOW:
467    /// - Drop the old waker during replacement and have its callback wake and replace the new one.
468    /// - Check replacement and nested wake counts with and without callback unwind.
469    #[test]
470    fn replaced_drop_reentry_and_unwind() {
471        for panic in [false, true] {
472            let (replacement_calls, replacement) = counted_waker();
473            let (nested_calls, nested) = counted_waker();
474            let slot = Rc::new(LocalWaker::with(Some(hook_waker())));
475            let callback_slot = slot.clone();
476            ON_DROP.set(Some(Box::new(move || {
477                assert!(callback_slot.wake_checked());
478                assert!(!callback_slot.register(&nested));
479                assert!(!panic, "drop");
480            })));
481            let result = catch_unwind(AssertUnwindSafe(|| slot.register(&replacement)));
482            if panic {
483                assert!(result.is_err());
484            } else {
485                assert!(result.unwrap());
486            }
487            assert_eq!(replacement_calls.0.load(Ordering::Relaxed), 1);
488            assert!(slot.wake_checked());
489            assert_eq!(nested_calls.0.load(Ordering::Relaxed), 1);
490        }
491    }
492
493    /// STATEMENT: Wake callbacks see an empty slot and can register a surviving replacement.
494    ///
495    /// HOW:
496    /// - Exercise checked and unchecked wakes with callbacks that register a nested waker.
497    /// - Repeat with panics and verify the nested registration still receives one wake.
498    #[test]
499    fn wake_reentry_and_unwind() {
500        for panic in [false, true] {
501            for checked in [false, true] {
502                let (calls, nested) = counted_waker();
503                let slot = Rc::new(LocalWaker::with(Some(hook_waker())));
504                let callback_slot = slot.clone();
505                ON_WAKE.set(Some(Box::new(move || {
506                    assert!(!callback_slot.is_set());
507                    assert!(!callback_slot.register(&nested));
508                    assert!(!panic, "wake");
509                })));
510                let result = catch_unwind(AssertUnwindSafe(|| {
511                    if checked {
512                        assert!(slot.wake_checked());
513                    } else {
514                        slot.wake();
515                    }
516                }));
517                assert_eq!(result.is_err(), panic);
518                assert!(slot.wake_checked());
519                assert_eq!(calls.0.load(Ordering::Relaxed), 1);
520            }
521        }
522    }
523
524    /// STATEMENT: Native task wakers support local and cross-thread delivery and remain safe after shutdown.
525    ///
526    /// HOW:
527    /// - Poll a native runtime task, wake it locally and from another thread, and count three polls.
528    /// - Drop the runtime and check task completion, released task state, and one final consumed wake.
529    #[test]
530    fn native_slot_delivery_and_shutdown() {
531        #[derive(Debug)]
532        struct NoopNotify;
533
534        impl ntex_rt::Notify for NoopNotify {
535            fn notify(&self) -> std::io::Result<()> {
536                Ok(())
537            }
538        }
539
540        let rt = ntex_rt::Runtime::new(Box::new(NoopNotify));
541        let slot = Rc::new(LocalWaker::new());
542        let polls = Rc::new(Cell::new(0));
543        let (task_slot, task_polls) = (slot.clone(), polls.clone());
544        let task = rt.spawn(std::future::poll_fn(move |cx| {
545            task_polls.set(task_polls.get() + 1);
546            task_slot.register(cx.waker());
547            std::task::Poll::<()>::Pending
548        }));
549        rt.poll();
550        slot.take_local().unwrap().wake();
551        rt.poll();
552        let standard = slot.take().unwrap();
553        std::thread::spawn(move || standard.wake()).join().unwrap();
554        rt.poll();
555        assert_eq!(polls.get(), 3);
556        assert_eq!(Rc::strong_count(&slot), 2);
557        drop(rt);
558        assert!(task.is_finished());
559        assert_eq!(Rc::strong_count(&slot), 1);
560        assert!(slot.wake_checked());
561        assert!(!slot.wake_checked());
562    }
563}