Wipe `Notifier` `FutureState` when returning from a waiter.
[rust-lightning] / lightning / src / util / wakers.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Utilities which allow users to block on some future notification from LDK. These are
11 //! specifically used by [`ChannelManager`] to allow waiting until the [`ChannelManager`] needs to
12 //! be re-persisted.
13 //!
14 //! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
15
16 use alloc::sync::Arc;
17 use core::mem;
18 use crate::sync::{Condvar, Mutex, MutexGuard};
19
20 use crate::prelude::*;
21
22 #[cfg(any(test, feature = "std"))]
23 use std::time::{Duration, Instant};
24
25 use core::future::Future as StdFuture;
26 use core::task::{Context, Poll};
27 use core::pin::Pin;
28
29
30 /// Used to signal to one of many waiters that the condition they're waiting on has happened.
31 pub(crate) struct Notifier {
32         notify_pending: Mutex<(bool, Option<Arc<Mutex<FutureState>>>)>,
33         condvar: Condvar,
34 }
35
36 macro_rules! check_woken {
37         ($guard: expr, $retval: expr) => { {
38                 if $guard.0 {
39                         $guard.0 = false;
40                         if $guard.1.as_ref().map(|l| l.lock().unwrap().complete).unwrap_or(false) {
41                                 // If we're about to return as woken, and the future state is marked complete, wipe
42                                 // the future state and let the next future wait until we get a new notify.
43                                 $guard.1.take();
44                         }
45                         return $retval;
46                 }
47         } }
48 }
49
50 impl Notifier {
51         pub(crate) fn new() -> Self {
52                 Self {
53                         notify_pending: Mutex::new((false, None)),
54                         condvar: Condvar::new(),
55                 }
56         }
57
58         fn propagate_future_state_to_notify_flag(&self) -> MutexGuard<(bool, Option<Arc<Mutex<FutureState>>>)> {
59                 let mut lock = self.notify_pending.lock().unwrap();
60                 if let Some(existing_state) = &lock.1 {
61                         if existing_state.lock().unwrap().callbacks_made {
62                                 // If the existing `FutureState` has completed and actually made callbacks,
63                                 // consider the notification flag to have been cleared and reset the future state.
64                                 lock.1.take();
65                                 lock.0 = false;
66                         }
67                 }
68                 lock
69         }
70
71         pub(crate) fn wait(&self) {
72                 loop {
73                         let mut guard = self.propagate_future_state_to_notify_flag();
74                         check_woken!(guard, ());
75                         guard = self.condvar.wait(guard).unwrap();
76                         check_woken!(guard, ());
77                 }
78         }
79
80         #[cfg(any(test, feature = "std"))]
81         pub(crate) fn wait_timeout(&self, max_wait: Duration) -> bool {
82                 let current_time = Instant::now();
83                 loop {
84                         let mut guard = self.propagate_future_state_to_notify_flag();
85                         check_woken!(guard, true);
86                         guard = self.condvar.wait_timeout(guard, max_wait).unwrap().0;
87                         check_woken!(guard, true);
88                         // Due to spurious wakeups that can happen on `wait_timeout`, here we need to check if the
89                         // desired wait time has actually passed, and if not then restart the loop with a reduced wait
90                         // time. Note that this logic can be highly simplified through the use of
91                         // `Condvar::wait_while` and `Condvar::wait_timeout_while`, if and when our MSRV is raised to
92                         // 1.42.0.
93                         let elapsed = current_time.elapsed();
94                         if elapsed >= max_wait {
95                                 return false;
96                         }
97                         match max_wait.checked_sub(elapsed) {
98                                 None => return false,
99                                 Some(_) => continue
100                         }
101                 }
102         }
103
104         /// Wake waiters, tracking that wake needs to occur even if there are currently no waiters.
105         pub(crate) fn notify(&self) {
106                 let mut lock = self.notify_pending.lock().unwrap();
107                 if let Some(future_state) = &lock.1 {
108                         future_state.lock().unwrap().complete();
109                 }
110                 lock.0 = true;
111                 mem::drop(lock);
112                 self.condvar.notify_all();
113         }
114
115         /// Gets a [`Future`] that will get woken up with any waiters
116         pub(crate) fn get_future(&self) -> Future {
117                 let mut lock = self.propagate_future_state_to_notify_flag();
118                 if let Some(existing_state) = &lock.1 {
119                         Future { state: Arc::clone(&existing_state) }
120                 } else {
121                         let state = Arc::new(Mutex::new(FutureState {
122                                 callbacks: Vec::new(),
123                                 complete: lock.0,
124                                 callbacks_made: false,
125                         }));
126                         lock.1 = Some(Arc::clone(&state));
127                         Future { state }
128                 }
129         }
130
131         #[cfg(any(test, feature = "_test_utils"))]
132         pub fn notify_pending(&self) -> bool {
133                 self.notify_pending.lock().unwrap().0
134         }
135 }
136
137 /// A callback which is called when a [`Future`] completes.
138 ///
139 /// Note that this MUST NOT call back into LDK directly, it must instead schedule actions to be
140 /// taken later. Rust users should use the [`std::future::Future`] implementation for [`Future`]
141 /// instead.
142 ///
143 /// Note that the [`std::future::Future`] implementation may only work for runtimes which schedule
144 /// futures when they receive a wake, rather than immediately executing them.
145 pub trait FutureCallback : Send {
146         /// The method which is called.
147         fn call(&self);
148 }
149
150 impl<F: Fn() + Send> FutureCallback for F {
151         fn call(&self) { (self)(); }
152 }
153
154 pub(crate) struct FutureState {
155         callbacks: Vec<Box<dyn FutureCallback>>,
156         complete: bool,
157         callbacks_made: bool,
158 }
159
160 impl FutureState {
161         fn complete(&mut self) {
162                 for callback in self.callbacks.drain(..) {
163                         callback.call();
164                         self.callbacks_made = true;
165                 }
166                 self.complete = true;
167         }
168 }
169
170 /// A simple future which can complete once, and calls some callback(s) when it does so.
171 pub struct Future {
172         state: Arc<Mutex<FutureState>>,
173 }
174
175 impl Future {
176         /// Registers a callback to be called upon completion of this future. If the future has already
177         /// completed, the callback will be called immediately.
178         ///
179         /// (C-not exported) use the bindings-only `register_callback_fn` instead
180         pub fn register_callback(&self, callback: Box<dyn FutureCallback>) {
181                 let mut state = self.state.lock().unwrap();
182                 if state.complete {
183                         state.callbacks_made = true;
184                         mem::drop(state);
185                         callback.call();
186                 } else {
187                         state.callbacks.push(callback);
188                 }
189         }
190
191         // C bindings don't (currently) know how to map `Box<dyn Trait>`, and while it could add the
192         // following wrapper, doing it in the bindings is currently much more work than simply doing it
193         // here.
194         /// Registers a callback to be called upon completion of this future. If the future has already
195         /// completed, the callback will be called immediately.
196         #[cfg(c_bindings)]
197         pub fn register_callback_fn<F: 'static + FutureCallback>(&self, callback: F) {
198                 self.register_callback(Box::new(callback));
199         }
200 }
201
202 use core::task::Waker;
203 struct StdWaker(pub Waker);
204 impl FutureCallback for StdWaker {
205         fn call(&self) { self.0.wake_by_ref() }
206 }
207
208 /// (C-not exported) as Rust Futures aren't usable in language bindings.
209 impl<'a> StdFuture for Future {
210         type Output = ();
211
212         fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
213                 let mut state = self.state.lock().unwrap();
214                 if state.complete {
215                         Poll::Ready(())
216                 } else {
217                         let waker = cx.waker().clone();
218                         state.callbacks.push(Box::new(StdWaker(waker)));
219                         Poll::Pending
220                 }
221         }
222 }
223
224 #[cfg(test)]
225 mod tests {
226         use super::*;
227         use core::sync::atomic::{AtomicBool, Ordering};
228         use core::future::Future as FutureTrait;
229         use core::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
230
231         #[test]
232         fn notifier_pre_notified_future() {
233                 // Previously, if we generated a future after a `Notifier` had been notified, the future
234                 // would never complete. This tests this behavior, ensuring the future instead completes
235                 // immediately.
236                 let notifier = Notifier::new();
237                 notifier.notify();
238
239                 let callback = Arc::new(AtomicBool::new(false));
240                 let callback_ref = Arc::clone(&callback);
241                 notifier.get_future().register_callback(Box::new(move || assert!(!callback_ref.fetch_or(true, Ordering::SeqCst))));
242                 assert!(callback.load(Ordering::SeqCst));
243         }
244
245         #[test]
246         fn notifier_future_completes_wake() {
247                 // Previously, if we were only using the `Future` interface to learn when a `Notifier` has
248                 // been notified, we'd never mark the notifier as not-awaiting-notify. This caused the
249                 // `lightning-background-processor` to persist in a tight loop.
250                 let notifier = Notifier::new();
251
252                 // First check the simple case, ensuring if we get notified a new future isn't woken until
253                 // a second `notify`.
254                 let callback = Arc::new(AtomicBool::new(false));
255                 let callback_ref = Arc::clone(&callback);
256                 notifier.get_future().register_callback(Box::new(move || assert!(!callback_ref.fetch_or(true, Ordering::SeqCst))));
257                 assert!(!callback.load(Ordering::SeqCst));
258
259                 notifier.notify();
260                 assert!(callback.load(Ordering::SeqCst));
261
262                 let callback = Arc::new(AtomicBool::new(false));
263                 let callback_ref = Arc::clone(&callback);
264                 notifier.get_future().register_callback(Box::new(move || assert!(!callback_ref.fetch_or(true, Ordering::SeqCst))));
265                 assert!(!callback.load(Ordering::SeqCst));
266
267                 notifier.notify();
268                 assert!(callback.load(Ordering::SeqCst));
269
270                 // Then check the case where the future is fetched before the notification, but a callback
271                 // is only registered after the `notify`, ensuring that it is still sufficient to ensure we
272                 // don't get an instant-wake when we get a new future.
273                 let future = notifier.get_future();
274                 notifier.notify();
275
276                 let callback = Arc::new(AtomicBool::new(false));
277                 let callback_ref = Arc::clone(&callback);
278                 future.register_callback(Box::new(move || assert!(!callback_ref.fetch_or(true, Ordering::SeqCst))));
279                 assert!(callback.load(Ordering::SeqCst));
280
281                 let callback = Arc::new(AtomicBool::new(false));
282                 let callback_ref = Arc::clone(&callback);
283                 notifier.get_future().register_callback(Box::new(move || assert!(!callback_ref.fetch_or(true, Ordering::SeqCst))));
284                 assert!(!callback.load(Ordering::SeqCst));
285         }
286
287         #[test]
288         fn new_future_wipes_notify_bit() {
289                 // Previously, if we were only using the `Future` interface to learn when a `Notifier` has
290                 // been notified, we'd never mark the notifier as not-awaiting-notify if a `Future` is
291                 // fetched after the notify bit has been set.
292                 let notifier = Notifier::new();
293                 notifier.notify();
294
295                 let callback = Arc::new(AtomicBool::new(false));
296                 let callback_ref = Arc::clone(&callback);
297                 notifier.get_future().register_callback(Box::new(move || assert!(!callback_ref.fetch_or(true, Ordering::SeqCst))));
298                 assert!(callback.load(Ordering::SeqCst));
299
300                 let callback = Arc::new(AtomicBool::new(false));
301                 let callback_ref = Arc::clone(&callback);
302                 notifier.get_future().register_callback(Box::new(move || assert!(!callback_ref.fetch_or(true, Ordering::SeqCst))));
303                 assert!(!callback.load(Ordering::SeqCst));
304
305                 notifier.notify();
306                 assert!(callback.load(Ordering::SeqCst));
307         }
308
309         #[cfg(feature = "std")]
310         #[test]
311         fn test_wait_timeout() {
312                 use crate::sync::Arc;
313                 use std::thread;
314
315                 let persistence_notifier = Arc::new(Notifier::new());
316                 let thread_notifier = Arc::clone(&persistence_notifier);
317
318                 let exit_thread = Arc::new(AtomicBool::new(false));
319                 let exit_thread_clone = exit_thread.clone();
320                 thread::spawn(move || {
321                         loop {
322                                 let mut lock = thread_notifier.notify_pending.lock().unwrap();
323                                 lock.0 = true;
324                                 thread_notifier.condvar.notify_all();
325
326                                 if exit_thread_clone.load(Ordering::SeqCst) {
327                                         break
328                                 }
329                         }
330                 });
331
332                 // Check that we can block indefinitely until updates are available.
333                 let _ = persistence_notifier.wait();
334
335                 // Check that the Notifier will return after the given duration if updates are
336                 // available.
337                 loop {
338                         if persistence_notifier.wait_timeout(Duration::from_millis(100)) {
339                                 break
340                         }
341                 }
342
343                 exit_thread.store(true, Ordering::SeqCst);
344
345                 // Check that the Notifier will return after the given duration even if no updates
346                 // are available.
347                 loop {
348                         if !persistence_notifier.wait_timeout(Duration::from_millis(100)) {
349                                 break
350                         }
351                 }
352         }
353
354         #[test]
355         fn test_future_callbacks() {
356                 let future = Future {
357                         state: Arc::new(Mutex::new(FutureState {
358                                 callbacks: Vec::new(),
359                                 complete: false,
360                                 callbacks_made: false,
361                         }))
362                 };
363                 let callback = Arc::new(AtomicBool::new(false));
364                 let callback_ref = Arc::clone(&callback);
365                 future.register_callback(Box::new(move || assert!(!callback_ref.fetch_or(true, Ordering::SeqCst))));
366
367                 assert!(!callback.load(Ordering::SeqCst));
368                 future.state.lock().unwrap().complete();
369                 assert!(callback.load(Ordering::SeqCst));
370                 future.state.lock().unwrap().complete();
371         }
372
373         #[test]
374         fn test_pre_completed_future_callbacks() {
375                 let future = Future {
376                         state: Arc::new(Mutex::new(FutureState {
377                                 callbacks: Vec::new(),
378                                 complete: false,
379                                 callbacks_made: false,
380                         }))
381                 };
382                 future.state.lock().unwrap().complete();
383
384                 let callback = Arc::new(AtomicBool::new(false));
385                 let callback_ref = Arc::clone(&callback);
386                 future.register_callback(Box::new(move || assert!(!callback_ref.fetch_or(true, Ordering::SeqCst))));
387
388                 assert!(callback.load(Ordering::SeqCst));
389                 assert!(future.state.lock().unwrap().callbacks.is_empty());
390         }
391
392         // Rather annoyingly, there's no safe way in Rust std to construct a Waker despite it being
393         // totally possible to construct from a trait implementation (though somewhat less effecient
394         // compared to a raw VTable). Instead, we have to write out a lot of boilerplate to build a
395         // waker, which we do here with a trivial Arc<AtomicBool> data element to track woke-ness.
396         const WAKER_V_TABLE: RawWakerVTable = RawWakerVTable::new(waker_clone, wake, wake_by_ref, drop);
397         unsafe fn wake_by_ref(ptr: *const ()) { let p = ptr as *const Arc<AtomicBool>; assert!(!(*p).fetch_or(true, Ordering::SeqCst)); }
398         unsafe fn drop(ptr: *const ()) { let p = ptr as *mut Arc<AtomicBool>; let _freed = Box::from_raw(p); }
399         unsafe fn wake(ptr: *const ()) { wake_by_ref(ptr); drop(ptr); }
400         unsafe fn waker_clone(ptr: *const ()) -> RawWaker {
401                 let p = ptr as *const Arc<AtomicBool>;
402                 RawWaker::new(Box::into_raw(Box::new(Arc::clone(&*p))) as *const (), &WAKER_V_TABLE)
403         }
404
405         fn create_waker() -> (Arc<AtomicBool>, Waker) {
406                 let a = Arc::new(AtomicBool::new(false));
407                 let waker = unsafe { Waker::from_raw(waker_clone((&a as *const Arc<AtomicBool>) as *const ())) };
408                 (a, waker)
409         }
410
411         #[test]
412         fn test_future() {
413                 let mut future = Future {
414                         state: Arc::new(Mutex::new(FutureState {
415                                 callbacks: Vec::new(),
416                                 complete: false,
417                                 callbacks_made: false,
418                         }))
419                 };
420                 let mut second_future = Future { state: Arc::clone(&future.state) };
421
422                 let (woken, waker) = create_waker();
423                 assert_eq!(Pin::new(&mut future).poll(&mut Context::from_waker(&waker)), Poll::Pending);
424                 assert!(!woken.load(Ordering::SeqCst));
425
426                 let (second_woken, second_waker) = create_waker();
427                 assert_eq!(Pin::new(&mut second_future).poll(&mut Context::from_waker(&second_waker)), Poll::Pending);
428                 assert!(!second_woken.load(Ordering::SeqCst));
429
430                 future.state.lock().unwrap().complete();
431                 assert!(woken.load(Ordering::SeqCst));
432                 assert!(second_woken.load(Ordering::SeqCst));
433                 assert_eq!(Pin::new(&mut future).poll(&mut Context::from_waker(&waker)), Poll::Ready(()));
434                 assert_eq!(Pin::new(&mut second_future).poll(&mut Context::from_waker(&second_waker)), Poll::Ready(()));
435         }
436 }