Skip to main content

n0_watcher/
lib.rs

1//! Watchable values.
2//!
3//! A [`Watchable`] exists to keep track of a value which may change over time.  It allows
4//! observers to be notified of changes to the value.  The aim is to always be aware of the
5//! **last** value, not to observe *every* value change.
6//!
7//! The reason for this is ergonomics and predictable resource usage: Requiring every
8//! intermediate value to be observable would mean that either the side that sets new values
9//! using [`Watchable::set`] would need to wait for all "receivers" of these intermediate
10//! values to catch up and thus be an async operation, or it would require the receivers
11//! to buffer intermediate values until they've been "received" on the [`Watcher`]s with
12//! an unlimited buffer size and thus potentially unlimited memory growth.
13//!
14//! # Example
15//!
16//! ```
17//! use n0_future::StreamExt;
18//! use n0_watcher::{Watchable, Watcher as _};
19//!
20//! #[tokio::main(flavor = "current_thread", start_paused = true)]
21//! async fn main() {
22//!     let watchable = Watchable::new(None);
23//!
24//!     // A task that waits for the watcher to be initialized to Some(value) before printing it
25//!     let mut watcher = watchable.watch();
26//!     tokio::spawn(async move {
27//!         let initialized_value = watcher.initialized().await;
28//!         println!("initialized: {initialized_value}");
29//!     });
30//!
31//!     // A task that prints every update to the watcher since the initial one:
32//!     let mut updates = watchable.watch().stream_updates_only();
33//!     tokio::spawn(async move {
34//!         while let Some(update) = updates.next().await {
35//!             println!("update: {update:?}");
36//!         }
37//!     });
38//!
39//!     // A task that prints the current value and then every update it can catch,
40//!     // but it also does something else which makes it very slow to pick up new
41//!     // values, so it'll skip some:
42//!     let mut current_and_updates = watchable.watch().stream();
43//!     tokio::spawn(async move {
44//!         while let Some(update) = current_and_updates.next().await {
45//!             println!("update2: {update:?}");
46//!             tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
47//!         }
48//!     });
49//!
50//!     for i in 0..20 {
51//!         println!("Setting watchable to {i}");
52//!         watchable.set(Some(i)).ok();
53//!         tokio::time::sleep(tokio::time::Duration::from_millis(250)).await;
54//!     }
55//! }
56//! ```
57//!
58//! # Similar but different
59//!
60//! - `async_channel`: This is a multi-producer, multi-consumer channel implementation.
61//!   Only at most one consumer will receive each "produced" value.
62//!   What we want is to have every "produced" value to be "broadcast" to every receiver.
63//! - `tokio::broadcast`: Also a multi-producer, multi-consumer channel implementation.
64//!   This is very similar to this crate (`tokio::broadcast::Sender` is like [`Watchable`]
65//!   and `tokio::broadcast::Receiver` is like [`Watcher`]), but you can't get the latest
66//!   value without `.await`ing on the receiver, and it'll internally store a queue of
67//!   intermediate values.
68//! - `tokio::watch`: Also a MPSC channel, and unlike `tokio::broadcast` only retains the
69//!   latest value. That module has pretty much the same purpose as this crate, but doesn't
70//!   implement a poll-based method of getting updates and doesn't implement combinators.
71//! - [`std::sync::RwLock`]: (wrapped in an [`std::sync::Arc`]) This allows you access
72//!   to the latest values, but might block while it's being set (but that could be short
73//!   enough not to matter for async rust purposes).
74//!   This doesn't allow you to be notified whenever a new value is written.
75//! - The `watchable` crate: We used to use this crate at n0, but we wanted to experiment
76//!   with different APIs and needed Wasm support.
77#[cfg(not(watcher_loom))]
78use std::sync;
79use std::{
80    future::Future,
81    pin::Pin,
82    sync::{Arc, RwLockReadGuard, Weak},
83    task::{self, ready, Poll, Waker},
84};
85
86#[cfg(watcher_loom)]
87use loom::sync;
88use n0_error::StackError;
89use sync::{Mutex, RwLock};
90
91/// A wrapper around a value that notifies [`Watcher`]s when the value is modified.
92///
93/// Only the most recent value is available to any observer, but the observer is guaranteed
94/// to be notified of the most recent value.
95#[derive(Debug, Default)]
96pub struct Watchable<T> {
97    shared: Arc<Shared<T>>,
98}
99
100impl<T> Clone for Watchable<T> {
101    fn clone(&self) -> Self {
102        Self {
103            shared: self.shared.clone(),
104        }
105    }
106}
107
108/// Abstracts over `Option<T>` and `Vec<T>`
109pub trait Nullable<T> {
110    /// Converts this value into an `Option`.
111    fn into_option(self) -> Option<T>;
112}
113
114impl<T> Nullable<T> for Option<T> {
115    fn into_option(self) -> Option<T> {
116        self
117    }
118}
119
120impl<T> Nullable<T> for Vec<T> {
121    fn into_option(mut self) -> Option<T> {
122        self.pop()
123    }
124}
125
126impl<T: Clone + Eq> Watchable<T> {
127    /// Creates a [`Watchable`] initialized to given value.
128    pub fn new(value: T) -> Self {
129        Self {
130            shared: Arc::new(Shared {
131                state: RwLock::new(State {
132                    value,
133                    epoch: INITIAL_EPOCH,
134                }),
135                wakers: Default::default(),
136            }),
137        }
138    }
139
140    /// Sets a new value.
141    ///
142    /// Returns `Ok(previous_value)` if the value was different from the one set, or
143    /// returns the provided value back as `Err(value)` if the value didn't change.
144    ///
145    /// Watchers are only notified if the value changed.
146    pub fn set(&self, value: T) -> Result<T, T> {
147        // We don't actually write when the value didn't change, but there's unfortunately
148        // no way to upgrade a read guard to a write guard, and locking as read first, then
149        // dropping and locking as write introduces a possible race condition.
150        let mut state = self.shared.state.write().expect("poisoned");
151
152        // Find out if the value changed
153        let changed = state.value != value;
154
155        let ret = if changed {
156            let old = std::mem::replace(&mut state.value, value);
157            state.epoch += 1;
158            Ok(old)
159        } else {
160            Err(value)
161        };
162        drop(state); // No need to write anymore
163
164        // Notify watchers
165        if changed {
166            for (_, (waker, _)) in self.shared.wakers.lock().expect("poisoned").drain() {
167                waker.wake();
168            }
169        }
170        ret
171    }
172
173    /// Creates a [`Direct`] [`Watcher`], allowing the value to be observed, but not modified.
174    pub fn watch(&self) -> Direct<T> {
175        Direct {
176            state: self.shared.state().clone(),
177            shared: Some(Arc::downgrade(&self.shared)),
178            waker_key: None,
179        }
180    }
181
182    /// Returns the currently stored value.
183    pub fn get(&self) -> T {
184        self.shared.get()
185    }
186
187    /// Returns true when there are any watchers actively listening on changes,
188    /// or false when all watchers have been dropped or none have been created yet.
189    pub fn has_watchers(&self) -> bool {
190        // `Watchable`s will increase the strong count
191        // `Direct`s watchers (which all watchers descend from) will increase the weak count
192        Arc::weak_count(&self.shared) != 0
193    }
194
195    #[cfg(test)]
196    fn debug_waker_counts(&self) -> Vec<u64> {
197        self.shared
198            .wakers
199            .lock()
200            .expect("poisoned")
201            .iter()
202            .map(|(_, (_, c))| *c)
203            .collect()
204    }
205}
206
207impl<T> Drop for Shared<T> {
208    fn drop(&mut self) {
209        let Ok(mut wakers) = self.wakers.lock() else {
210            return; // Poisoned waking?
211        };
212        // Wake all wakers once we drop Shared (this happens when
213        // the last `Watchable` is dropped).
214        // This allows us to notify `NextFut::poll`s and have that
215        // return `Disconnected`.
216        for (_, (waker, _)) in wakers.drain() {
217            waker.wake();
218        }
219    }
220}
221
222/// A handle to a value that's represented by one or more underlying [`Watchable`]s.
223///
224/// A [`Watcher`] can get the current value, and will be notified when the value changes.
225/// Only the most recent value is accessible, and if the threads with the underlying [`Watchable`]s
226/// change the value faster than the threads with the [`Watcher`] can keep up with, then
227/// it'll miss in-between values.
228/// When the thread changing the [`Watchable`] pauses updating, the [`Watcher`] will always
229/// end up reporting the most recent state eventually.
230///
231/// Watchers can be modified via [`Watcher::map`] to observe a value derived from the original
232/// value via a function.
233///
234/// Watchers can be combined via [`Watcher::or`] to allow observing multiple values at once and
235/// getting an update in case any of the values updates.
236///
237/// One of the underlying [`Watchable`]s might already be dropped. In that case,
238/// the watcher will be "disconnected" and return [`Err(Disconnected)`](Disconnected)
239/// on some function calls or, when turned into a stream, that stream will end.
240/// This property can also be checked with [`Watcher::is_connected`].
241pub trait Watcher: Clone {
242    /// The type of value that can change.
243    ///
244    /// We require `Clone`, because we need to be able to make
245    /// the values have a lifetime that's detached from the original [`Watchable`]'s
246    /// lifetime.
247    ///
248    /// We require `Eq`, to be able to check whether the value actually changed or
249    /// not, so we can notify or not notify accordingly.
250    type Value: Clone + Eq;
251
252    /// Updates the watcher to the latest value and returns that value.
253    ///
254    /// If any of the underlying [`Watchable`] values have been dropped, then this
255    /// might return an outdated value for that watchable, specifically, the latest
256    /// value that was fetched for that watchable, as opposed to the latest value
257    /// that was set on the watchable before it was dropped.
258    ///
259    /// The default implementation for this is simply
260    /// ```ignore
261    /// fn get(&mut self) -> Self::Value {
262    ///     self.update();
263    ///     self.peek().clone()
264    /// }
265    /// ```
266    fn get(&mut self) -> Self::Value {
267        self.update();
268        self.peek().clone()
269    }
270
271    /// Updates the watcher to the latest value and returns whether it changed.
272    ///
273    /// Watchers keep track of the "latest known" value they fetched.
274    /// This function updates that internal value by looking up the latest value
275    /// at the [`Watchable`]\(s\) that this watcher is linked to.
276    fn update(&mut self) -> bool;
277
278    /// Returns a reference to the value currently stored in the watcher.
279    ///
280    /// Watchers keep track of the "latest known" value they fetched.
281    /// Calling this won't update the latest value, unlike [`Watcher::get`] or
282    /// [`Watcher::update`].
283    ///
284    /// This can be useful if you want to avoid copying out the internal value
285    /// frequently like what [`Watcher::get`] will end up doing.
286    fn peek(&self) -> &Self::Value;
287
288    /// Whether this watcher is still connected to all of its underlying [`Watchable`]s.
289    ///
290    /// Returns false when any of the underlying watchables has been dropped.
291    fn is_connected(&self) -> bool;
292
293    /// Polls for the next value, or returns [`Disconnected`] if one of the underlying
294    /// [`Watchable`]s has been dropped.
295    fn poll_updated(&mut self, cx: &mut task::Context<'_>) -> Poll<Result<(), Disconnected>>;
296
297    /// Returns a future completing with `Ok(value)` once a new value is set, or with
298    /// [`Err(Disconnected)`](Disconnected) if the connected [`Watchable`] was dropped.
299    ///
300    /// # Cancel Safety
301    ///
302    /// The returned future is cancel-safe.
303    fn updated(&mut self) -> NextFut<'_, Self> {
304        NextFut { watcher: self }
305    }
306
307    /// Returns a future completing once the value is set to [`Some`] value.
308    ///
309    /// If the current value is [`Some`] value, this future will resolve immediately.
310    ///
311    /// This is a utility for the common case of storing an [`Option`] inside a
312    /// [`Watchable`].
313    ///
314    /// # Cancel Safety
315    ///
316    /// The returned future is cancel-safe.
317    fn initialized<T, W>(&mut self) -> InitializedFut<'_, T, W, Self>
318    where
319        W: Nullable<T> + Clone,
320        Self: Watcher<Value = W>,
321    {
322        InitializedFut {
323            initial: self.get().into_option(),
324            watcher: self,
325        }
326    }
327
328    /// Returns a stream which will yield the most recent values as items.
329    ///
330    /// The first item of the stream is the current value, so that this stream can be easily
331    /// used to operate on the most recent value.
332    ///
333    /// Note however, that only the last item is stored.  If the stream is not polled when an
334    /// item is available it can be replaced with another item by the time it is polled.
335    ///
336    /// This stream ends once the original [`Watchable`] has been dropped.
337    ///
338    /// # Cancel Safety
339    ///
340    /// The returned stream is cancel-safe.
341    fn stream(mut self) -> Stream<Self>
342    where
343        Self: Unpin,
344    {
345        Stream {
346            initial: Some(self.get()),
347            watcher: self,
348        }
349    }
350
351    /// Returns a stream which will yield the most recent values as items, starting from
352    /// the next unobserved future value.
353    ///
354    /// This means this stream will only yield values when the watched value changes,
355    /// the value stored at the time the stream is created is not yielded.
356    ///
357    /// Note however, that only the last item is stored.  If the stream is not polled when an
358    /// item is available it can be replaced with another item by the time it is polled.
359    ///
360    /// This stream ends once the original [`Watchable`] has been dropped.
361    ///
362    /// # Cancel Safety
363    ///
364    /// The returned stream is cancel-safe.
365    fn stream_updates_only(self) -> Stream<Self>
366    where
367        Self: Unpin,
368    {
369        Stream {
370            initial: None,
371            watcher: self,
372        }
373    }
374
375    /// Maps this watcher with a function that transforms the observed values.
376    ///
377    /// The returned watcher will only register updates, when the *mapped* value
378    /// observably changes.
379    fn map<T: Clone + Eq>(
380        mut self,
381        map: impl Fn(Self::Value) -> T + Send + Sync + 'static,
382    ) -> Map<Self, T> {
383        Map {
384            current: (map)(self.get()),
385            map: Arc::new(map),
386            watcher: self,
387        }
388    }
389
390    /// Returns a watcher that updates every time this or the other watcher
391    /// updates, and yields both watcher's items together when that happens.
392    fn or<W: Watcher>(self, other: W) -> Tuple<Self, W> {
393        Tuple::new(self, other)
394    }
395}
396
397/// The immediate, direct observer of a [`Watchable`] value.
398///
399/// This type is mainly used via the [`Watcher`] interface.
400#[derive(Debug)]
401pub struct Direct<T> {
402    state: State<T>,
403    /// The reference of state shared with the connected [`Watchable`].
404    ///
405    /// We wrap the Weak with an Option, so that we can set it to `None` once we
406    /// notice that Weak is not upgradable anymore for the first time.
407    /// This allows the weak pointer's allocation to be freed in case this makes
408    /// the weak count go to zero (even if Direct is still kept around).
409    shared: Option<Weak<Shared<T>>>,
410    /// The key we get when registering the waker.
411    ///
412    /// This allows us to tell `Shared` to remove our waker once we are
413    /// no longer interested in getting notified (i.e. on drop).
414    ///
415    /// Prevents leaking memory when constructing `Direct`s constantly, polling at
416    /// least once and then dropping them again.
417    waker_key: Option<slotmap::DefaultKey>,
418}
419
420impl<T: Clone> Clone for Direct<T> {
421    fn clone(&self) -> Self {
422        Self {
423            state: self.state.clone(),
424            shared: self.shared.clone(),
425            waker_key: None,
426        }
427    }
428}
429
430impl<T: Clone + Eq> Watcher for Direct<T> {
431    type Value = T;
432
433    fn update(&mut self) -> bool {
434        let Some(shared) = self.shared.as_ref().and_then(|weak| weak.upgrade()) else {
435            self.shared = None; // Weak won't be upgradable in the future, this way we can allow the allocation to be freed
436            return false;
437        };
438        let state = shared.state();
439        if state.epoch > self.state.epoch {
440            self.state = state.clone();
441            true
442        } else {
443            false
444        }
445    }
446
447    fn peek(&self) -> &Self::Value {
448        &self.state.value
449    }
450
451    fn is_connected(&self) -> bool {
452        self.shared
453            .as_ref()
454            .and_then(|weak| weak.upgrade())
455            .is_some()
456    }
457
458    fn poll_updated(&mut self, cx: &mut task::Context<'_>) -> Poll<Result<(), Disconnected>> {
459        let Some(shared) = self.shared.as_ref().and_then(|weak| weak.upgrade()) else {
460            self.shared = None; // Weak won't be upgradable in the future, this way we can allow the allocation to be freed
461            return Poll::Ready(Err(Disconnected));
462        };
463        self.state = ready!(shared.poll_updated(cx, self.state.epoch, &mut self.waker_key));
464        Poll::Ready(Ok(()))
465    }
466}
467
468impl<T> Drop for Direct<T> {
469    fn drop(&mut self) {
470        let Some(shared) = self.shared.take().and_then(|weak| weak.upgrade()) else {
471            return;
472        };
473        let Some(key) = self.waker_key.take() else {
474            return;
475        };
476        shared.remove_waker(key);
477    }
478}
479
480#[derive(Debug, Clone)]
481pub struct Tuple<S: Watcher, T: Watcher> {
482    inner: (S, T),
483    current: (S::Value, T::Value),
484}
485
486impl<S: Watcher, T: Watcher> Tuple<S, T> {
487    pub fn new(mut s: S, mut t: T) -> Self {
488        let current = (s.get(), t.get());
489        Self {
490            inner: (s, t),
491            current,
492        }
493    }
494}
495
496impl<S: Watcher, T: Watcher> Watcher for Tuple<S, T> {
497    type Value = (S::Value, T::Value);
498
499    fn update(&mut self) -> bool {
500        // We need to update all watchers! So don't early-return
501        let s_updated = self.inner.0.update();
502        let t_updated = self.inner.1.update();
503        let updated = s_updated || t_updated;
504        if updated {
505            self.current = (self.inner.0.peek().clone(), self.inner.1.peek().clone());
506        }
507        updated
508    }
509
510    fn peek(&self) -> &Self::Value {
511        &self.current
512    }
513
514    fn is_connected(&self) -> bool {
515        self.inner.0.is_connected() && self.inner.1.is_connected()
516    }
517
518    fn poll_updated(&mut self, cx: &mut task::Context<'_>) -> Poll<Result<(), Disconnected>> {
519        let poll_0 = self.inner.0.poll_updated(cx)?;
520        let poll_1 = self.inner.1.poll_updated(cx)?;
521        if poll_0.is_pending() && poll_1.is_pending() {
522            return Poll::Pending;
523        }
524        if poll_0.is_ready() {
525            self.current.0 = self.inner.0.peek().clone();
526        }
527        if poll_1.is_ready() {
528            self.current.1 = self.inner.1.peek().clone();
529        }
530        Poll::Ready(Ok(()))
531    }
532}
533
534#[derive(Debug, Clone)]
535pub struct Triple<S: Watcher, T: Watcher, U: Watcher> {
536    inner: (S, T, U),
537    current: (S::Value, T::Value, U::Value),
538}
539
540impl<S: Watcher, T: Watcher, U: Watcher> Triple<S, T, U> {
541    pub fn new(mut s: S, mut t: T, mut u: U) -> Self {
542        let current = (s.get(), t.get(), u.get());
543        Self {
544            inner: (s, t, u),
545            current,
546        }
547    }
548}
549
550impl<S: Watcher, T: Watcher, U: Watcher> Watcher for Triple<S, T, U> {
551    type Value = (S::Value, T::Value, U::Value);
552
553    fn update(&mut self) -> bool {
554        // We need to update all watchers! So don't early-return
555        let s_updated = self.inner.0.update();
556        let t_updated = self.inner.1.update();
557        let u_updated = self.inner.2.update();
558        let updated = s_updated || t_updated || u_updated;
559        if updated {
560            self.current = (
561                self.inner.0.peek().clone(),
562                self.inner.1.peek().clone(),
563                self.inner.2.peek().clone(),
564            );
565        }
566        updated
567    }
568
569    fn peek(&self) -> &Self::Value {
570        &self.current
571    }
572
573    fn is_connected(&self) -> bool {
574        self.inner.0.is_connected() && self.inner.1.is_connected() && self.inner.2.is_connected()
575    }
576
577    fn poll_updated(&mut self, cx: &mut task::Context<'_>) -> Poll<Result<(), Disconnected>> {
578        let poll_0 = self.inner.0.poll_updated(cx)?;
579        let poll_1 = self.inner.1.poll_updated(cx)?;
580        let poll_2 = self.inner.2.poll_updated(cx)?;
581
582        if poll_0.is_pending() && poll_1.is_pending() && poll_2.is_pending() {
583            return Poll::Pending;
584        }
585        if poll_0.is_ready() {
586            self.current.0 = self.inner.0.peek().clone();
587        }
588        if poll_1.is_ready() {
589            self.current.1 = self.inner.1.peek().clone();
590        }
591        if poll_2.is_ready() {
592            self.current.2 = self.inner.2.peek().clone();
593        }
594        Poll::Ready(Ok(()))
595    }
596}
597
598/// Combinator to join two watchers
599#[derive(Debug, Clone)]
600pub struct Join<T: Clone + Eq, W: Watcher<Value = T>> {
601    // invariant: watchers.len() == current.len()
602    watchers: Vec<W>,
603    current: Vec<T>,
604}
605
606impl<T: Clone + Eq, W: Watcher<Value = T>> Join<T, W> {
607    /// Joins a set of watchers into a single watcher
608    pub fn new(watchers: impl Iterator<Item = W>) -> Self {
609        let mut watchers: Vec<W> = watchers.into_iter().collect();
610
611        let mut current = Vec::with_capacity(watchers.len());
612        for watcher in &mut watchers {
613            current.push(watcher.get());
614        }
615        Self { watchers, current }
616    }
617}
618
619impl<T: Clone + Eq, W: Watcher<Value = T>> Watcher for Join<T, W> {
620    type Value = Vec<T>;
621
622    fn update(&mut self) -> bool {
623        let mut any_updated = false;
624        for (value, watcher) in self.current.iter_mut().zip(self.watchers.iter_mut()) {
625            if watcher.update() {
626                any_updated = true;
627                *value = watcher.peek().clone();
628            }
629        }
630        any_updated
631    }
632
633    fn peek(&self) -> &Self::Value {
634        &self.current
635    }
636
637    fn is_connected(&self) -> bool {
638        self.watchers.iter().all(|w| w.is_connected())
639    }
640
641    fn poll_updated(&mut self, cx: &mut task::Context<'_>) -> Poll<Result<(), Disconnected>> {
642        let mut any_updated = false;
643        for (value, watcher) in self.current.iter_mut().zip(self.watchers.iter_mut()) {
644            if watcher.poll_updated(cx)?.is_ready() {
645                any_updated = true;
646                *value = watcher.peek().clone();
647            }
648        }
649
650        if any_updated {
651            Poll::Ready(Ok(()))
652        } else {
653            Poll::Pending
654        }
655    }
656}
657
658/// Wraps a [`Watcher`] to allow observing a derived value.
659///
660/// See [`Watcher::map`].
661#[derive(derive_more::Debug, Clone)]
662pub struct Map<W: Watcher, T: Clone + Eq> {
663    #[debug("Arc<dyn Fn(W::Value) -> T>")]
664    map: Arc<dyn Fn(W::Value) -> T + Send + Sync + 'static>,
665    watcher: W,
666    current: T,
667}
668
669impl<W: Watcher, T: Clone + Eq> Watcher for Map<W, T> {
670    type Value = T;
671
672    fn update(&mut self) -> bool {
673        if self.watcher.update() {
674            let new = (self.map)(self.watcher.peek().clone());
675            if new != self.current {
676                self.current = new;
677                true
678            } else {
679                false
680            }
681        } else {
682            false
683        }
684    }
685
686    fn peek(&self) -> &Self::Value {
687        &self.current
688    }
689
690    fn is_connected(&self) -> bool {
691        self.watcher.is_connected()
692    }
693
694    fn poll_updated(&mut self, cx: &mut task::Context<'_>) -> Poll<Result<(), Disconnected>> {
695        loop {
696            ready!(self.watcher.poll_updated(cx)?);
697            let new = (self.map)(self.watcher.peek().clone());
698            if new != self.current {
699                self.current = new;
700                return Poll::Ready(Ok(()));
701            }
702        }
703    }
704}
705
706/// Future returning the next item after the current one in a [`Watcher`].
707///
708/// See [`Watcher::updated`].
709///
710/// # Cancel Safety
711///
712/// This future is cancel-safe.
713#[derive(Debug)]
714pub struct NextFut<'a, W: Watcher> {
715    watcher: &'a mut W,
716}
717
718impl<W: Watcher> Future for NextFut<'_, W> {
719    type Output = Result<W::Value, Disconnected>;
720
721    fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
722        ready!(self.watcher.poll_updated(cx))?;
723        Poll::Ready(Ok(self.watcher.peek().clone()))
724    }
725}
726
727/// Future returning the current or next value that's [`Some`] value.
728/// in a [`Watcher`].
729///
730/// See [`Watcher::initialized`].
731///
732/// # Cancel Safety
733///
734/// This Future is cancel-safe.
735#[derive(Debug)]
736pub struct InitializedFut<'a, T, V: Nullable<T> + Clone, W: Watcher<Value = V>> {
737    initial: Option<T>,
738    watcher: &'a mut W,
739}
740
741impl<T: Clone + Eq + Unpin, V: Nullable<T> + Clone, W: Watcher<Value = V> + Unpin> Future
742    for InitializedFut<'_, T, V, W>
743{
744    type Output = T;
745
746    fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
747        let mut this = self.as_mut();
748        if let Some(value) = this.initial.take() {
749            return Poll::Ready(value);
750        }
751        loop {
752            if ready!(this.watcher.poll_updated(cx)).is_err() {
753                // The value will never be initialized
754                return Poll::Pending;
755            };
756            let value = this.watcher.peek();
757            if let Some(value) = value.clone().into_option() {
758                return Poll::Ready(value);
759            }
760        }
761    }
762}
763
764/// A stream for a [`Watcher`]'s next values.
765///
766/// See [`Watcher::stream`] and [`Watcher::stream_updates_only`].
767///
768/// # Cancel Safety
769///
770/// This stream is cancel-safe.
771#[derive(Debug, Clone)]
772pub struct Stream<W: Watcher + Unpin> {
773    initial: Option<W::Value>,
774    watcher: W,
775}
776
777impl<W: Watcher + Unpin> n0_future::Stream for Stream<W>
778where
779    W::Value: Unpin,
780{
781    type Item = W::Value;
782
783    fn poll_next(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
784        if let Some(value) = self.as_mut().initial.take() {
785            return Poll::Ready(Some(value));
786        }
787        match self.as_mut().watcher.poll_updated(cx) {
788            Poll::Ready(Ok(())) => Poll::Ready(Some(self.as_ref().watcher.peek().clone())),
789            Poll::Ready(Err(Disconnected)) => Poll::Ready(None),
790            Poll::Pending => Poll::Pending,
791        }
792    }
793}
794
795/// The error for when a [`Watcher`] is disconnected from its underlying
796/// [`Watchable`] value, because of that watchable having been dropped.
797#[derive(StackError)]
798#[error("Watcher lost connection to underlying Watchable, it was dropped")]
799pub struct Disconnected;
800
801// Private:
802
803const INITIAL_EPOCH: u64 = 1;
804
805/// The shared state for a [`Watchable`].
806#[derive(Debug, Default)]
807struct Shared<T> {
808    /// The value to be watched and its current epoch.
809    state: RwLock<State<T>>,
810    /// Watcher wakers to be notified when this watchable is changed or dropped.
811    ///
812    /// We use a slotmap so we have a stable key we can store in the watcher for it to
813    /// remember which waker it previously inserted into the slot map.
814    /// We also store a u64 "reference count" of how many watchers have registered said
815    /// waker in the same task. This ensures we only remove the waker once the last
816    /// watcher from that task is dropped, while making sure that we don't register
817    /// wakers twice for the same task (saving memory).
818    wakers: Mutex<slotmap::DenseSlotMap<slotmap::DefaultKey, (Waker, u64)>>,
819}
820
821#[derive(Debug, Clone)]
822struct State<T> {
823    value: T,
824    epoch: u64,
825}
826
827impl<T: Default> Default for State<T> {
828    fn default() -> Self {
829        Self {
830            value: Default::default(),
831            epoch: INITIAL_EPOCH,
832        }
833    }
834}
835
836impl<T: Clone> Shared<T> {
837    fn get(&self) -> T {
838        self.state.read().expect("poisoned").value.clone()
839    }
840
841    fn state(&self) -> RwLockReadGuard<'_, State<T>> {
842        self.state.read().expect("poisoned")
843    }
844
845    fn poll_updated(
846        &self,
847        cx: &mut task::Context<'_>,
848        last_epoch: u64,
849        waker_key: &mut Option<slotmap::DefaultKey>,
850    ) -> Poll<State<T>> {
851        {
852            let state = self.state();
853
854            // We might get spurious wakeups due to e.g. a second-to-last Watchable being dropped.
855            // This makes sure we don't accidentally return an update that's not actually an update.
856            if last_epoch < state.epoch {
857                return Poll::Ready(state.clone());
858            }
859        }
860
861        self.add_waker(cx, waker_key);
862
863        #[cfg(watcher_loom)]
864        loom::thread::yield_now();
865
866        // We check for an update again to prevent races between putting in wakers and looking for updates.
867        {
868            let state = self.state();
869
870            if last_epoch < state.epoch {
871                return Poll::Ready(state.clone());
872            }
873        }
874
875        Poll::Pending
876    }
877
878    /// Adds the task's waker to this watchable.
879    ///
880    /// The waker will be woken when the watchable is dropped completely
881    /// or when the watcher is updated.
882    ///
883    /// Will set `waker_key` to the key used in the waker slotmap.
884    /// `add_waker` needs to know the currently set waker key in order to
885    /// figure out whether it needs to increase the internal waker count
886    /// or not.
887    fn add_waker(&self, cx: &mut task::Context<'_>, waker_key: &mut Option<slotmap::DefaultKey>) {
888        let mut wakers = self.wakers.lock().expect("poisoned");
889        for (key, (waker, count)) in wakers.iter_mut() {
890            if waker.will_wake(cx.waker()) {
891                if Some(key) != *waker_key {
892                    *count = count.saturating_add(1);
893                    if let Some(old_key) = waker_key.replace(key) {
894                        // This makes sure we clean up a potentially old waker we added previously.
895                        Self::dec_or_rem_waker(&mut wakers, old_key);
896                    }
897                }
898                return;
899            }
900        }
901        // There can be technical reasons why runtimes have `will_wake` false negatives
902        // (e.g. tokio root block_on wakers being on different CGUs in release mode) which
903        // means we add a new waker every poll. This makes sure we clean up wakers from the
904        // last poll call, if still present.
905        if let Some(old_key) = waker_key.take() {
906            Self::dec_or_rem_waker(&mut wakers, old_key);
907        }
908        *waker_key = Some(wakers.insert((cx.waker().clone(), 1)));
909    }
910}
911
912impl<T> Shared<T> {
913    /// Removes and optionally returns the waker that was added via [`Self::add_waker`] before.
914    fn remove_waker(&self, waker_key: slotmap::DefaultKey) {
915        let mut wakers = self.wakers.lock().expect("poisoned");
916        Self::dec_or_rem_waker(&mut wakers, waker_key);
917    }
918
919    /// Decrements the count of a waker entry, removing it when it reaches zero.
920    ///
921    /// Operates on an already-locked `wakers` guard to avoid re-entrant locking
922    /// from within [`Shared::add_waker`].
923    fn dec_or_rem_waker(
924        wakers: &mut slotmap::DenseSlotMap<slotmap::DefaultKey, (Waker, u64)>,
925        waker_key: slotmap::DefaultKey,
926    ) {
927        // We need to be careful to not use `remove` -> `insert` in favor of `get_mut`,
928        // because we care about the key the waker is stored under, as other watchers
929        // might still refer to the slot under that key.
930        if let Some((_, count)) = wakers.get_mut(waker_key) {
931            if *count <= 1 {
932                wakers.remove(waker_key);
933            } else {
934                *count -= 1;
935            }
936        }
937    }
938}
939
940#[cfg(test)]
941mod tests {
942
943    use n0_future::{future::poll_once, StreamExt};
944    use rand::{rng, RngExt};
945    use tokio::{
946        task::JoinSet,
947        time::{Duration, Instant},
948    };
949    use tokio_util::sync::CancellationToken;
950
951    use super::*;
952
953    #[tokio::test]
954    async fn test_watcher() {
955        let cancel = CancellationToken::new();
956        let watchable = Watchable::new(17);
957
958        assert_eq!(watchable.watch().stream().next().await.unwrap(), 17);
959
960        let start = Instant::now();
961        // spawn watchers
962        let mut tasks = JoinSet::new();
963        for i in 0..3 {
964            let mut watch = watchable.watch().stream();
965            let cancel = cancel.clone();
966            tasks.spawn(async move {
967                println!("[{i}] spawn");
968                let mut expected_value = 17;
969                loop {
970                    tokio::select! {
971                        biased;
972                        Some(value) = &mut watch.next() => {
973                            println!("{:?} [{i}] update: {value}", start.elapsed());
974                            assert_eq!(value, expected_value);
975                            if expected_value == 17 {
976                                expected_value = 0;
977                            } else {
978                                expected_value += 1;
979                            }
980                        },
981                        _ = cancel.cancelled() => {
982                            println!("{:?} [{i}] cancel", start.elapsed());
983                            assert_eq!(expected_value, 10);
984                            break;
985                        }
986                    }
987                }
988            });
989        }
990        for i in 0..3 {
991            let mut watch = watchable.watch().stream_updates_only();
992            let cancel = cancel.clone();
993            tasks.spawn(async move {
994                println!("[{i}] spawn");
995                let mut expected_value = 0;
996                loop {
997                    tokio::select! {
998                        biased;
999                        Some(value) = watch.next() => {
1000                            println!("{:?} [{i}] stream update: {value}", start.elapsed());
1001                            assert_eq!(value, expected_value);
1002                            expected_value += 1;
1003                        },
1004                        _ = cancel.cancelled() => {
1005                            println!("{:?} [{i}] cancel", start.elapsed());
1006                            assert_eq!(expected_value, 10);
1007                            break;
1008                        }
1009                        else => {
1010                            panic!("stream died");
1011                        }
1012                    }
1013                }
1014            });
1015        }
1016
1017        // set value
1018        for next_value in 0..10 {
1019            let sleep = Duration::from_nanos(rng().random_range(0..100_000_000));
1020            println!("{:?} sleep {sleep:?}", start.elapsed());
1021            tokio::time::sleep(sleep).await;
1022
1023            let changed = watchable.set(next_value);
1024            println!("{:?} set {next_value} changed={changed:?}", start.elapsed());
1025        }
1026
1027        println!("cancel");
1028        cancel.cancel();
1029        while let Some(res) = tasks.join_next().await {
1030            res.expect("task failed");
1031        }
1032    }
1033
1034    #[test]
1035    fn test_get() {
1036        let watchable = Watchable::new(None);
1037        assert!(watchable.get().is_none());
1038
1039        watchable.set(Some(1u8)).ok();
1040        assert_eq!(watchable.get(), Some(1u8));
1041    }
1042
1043    #[tokio::test]
1044    async fn test_initialize() {
1045        let watchable = Watchable::new(None);
1046
1047        let mut watcher = watchable.watch();
1048        let mut initialized = watcher.initialized();
1049
1050        let poll = poll_once(&mut initialized).await;
1051        assert!(poll.is_none());
1052
1053        watchable.set(Some(1u8)).ok();
1054
1055        let poll = poll_once(&mut initialized).await;
1056        assert_eq!(poll.unwrap(), 1u8);
1057    }
1058
1059    #[tokio::test]
1060    async fn test_initialize_already_init() {
1061        let watchable = Watchable::new(Some(1u8));
1062
1063        let mut watcher = watchable.watch();
1064        let mut initialized = watcher.initialized();
1065
1066        let poll = poll_once(&mut initialized).await;
1067        assert_eq!(poll.unwrap(), 1u8);
1068    }
1069
1070    #[test]
1071    fn test_initialized_always_resolves() {
1072        #[cfg(not(watcher_loom))]
1073        use std::thread;
1074
1075        #[cfg(watcher_loom)]
1076        use loom::thread;
1077
1078        let test_case = || {
1079            let watchable = Watchable::<Option<u8>>::new(None);
1080
1081            let mut watch = watchable.watch();
1082            let thread = thread::spawn(move || n0_future::future::block_on(watch.initialized()));
1083
1084            watchable.set(Some(42)).ok();
1085
1086            thread::yield_now();
1087
1088            let value: u8 = thread.join().unwrap();
1089
1090            assert_eq!(value, 42);
1091        };
1092
1093        #[cfg(watcher_loom)]
1094        loom::model(test_case);
1095        #[cfg(not(watcher_loom))]
1096        test_case();
1097    }
1098
1099    #[tokio::test(flavor = "multi_thread")]
1100    async fn test_update_cancel_safety() {
1101        let watchable = Watchable::new(0);
1102        let mut watch = watchable.watch();
1103        const MAX: usize = 100_000;
1104
1105        let handle = tokio::spawn(async move {
1106            let mut last_observed = 0;
1107
1108            while last_observed != MAX {
1109                tokio::select! {
1110                    val = watch.updated() => {
1111                        let Ok(val) = val else {
1112                            return;
1113                        };
1114
1115                        assert_ne!(val, last_observed, "never observe the same value twice, even with cancellation");
1116                        last_observed = val;
1117                    }
1118                    _ = tokio::time::sleep(Duration::from_micros(rng().random_range(0..10_000))) => {
1119                        // We cancel the other future and start over again
1120                        continue;
1121                    }
1122                }
1123            }
1124        });
1125
1126        for i in 1..=MAX {
1127            watchable.set(i).ok();
1128            if rng().random_bool(0.2) {
1129                tokio::task::yield_now().await;
1130            }
1131        }
1132
1133        tokio::time::timeout(Duration::from_secs(10), handle)
1134            .await
1135            .unwrap()
1136            .unwrap()
1137    }
1138
1139    #[tokio::test]
1140    async fn test_join_simple() {
1141        let a = Watchable::new(1u8);
1142        let b = Watchable::new(1u8);
1143
1144        let mut ab = Join::new([a.watch(), b.watch()].into_iter());
1145
1146        let stream = ab.clone().stream();
1147        let handle = tokio::task::spawn(async move { stream.take(5).collect::<Vec<_>>().await });
1148
1149        // get
1150        assert_eq!(ab.get(), vec![1, 1]);
1151        // set a
1152        a.set(2u8).unwrap();
1153        tokio::task::yield_now().await;
1154        assert_eq!(ab.get(), vec![2, 1]);
1155        // set b
1156        b.set(3u8).unwrap();
1157        tokio::task::yield_now().await;
1158        assert_eq!(ab.get(), vec![2, 3]);
1159
1160        a.set(3u8).unwrap();
1161        tokio::task::yield_now().await;
1162        b.set(4u8).unwrap();
1163        tokio::task::yield_now().await;
1164
1165        let values = tokio::time::timeout(Duration::from_secs(5), handle)
1166            .await
1167            .unwrap()
1168            .unwrap();
1169        assert_eq!(
1170            values,
1171            vec![vec![1, 1], vec![2, 1], vec![2, 3], vec![3, 3], vec![3, 4]]
1172        );
1173    }
1174
1175    #[tokio::test]
1176    async fn test_updated_then_disconnect_then_get() {
1177        let watchable = Watchable::new(10);
1178        let mut watcher = watchable.watch();
1179        assert_eq!(watchable.get(), 10);
1180        watchable.set(42).ok();
1181        assert_eq!(watcher.updated().await.unwrap(), 42);
1182        drop(watchable);
1183        assert_eq!(watcher.get(), 42);
1184    }
1185
1186    #[tokio::test(start_paused = true)]
1187    async fn test_update_wakeup_on_watchable_drop() {
1188        let watchable = Watchable::new(10);
1189        let mut watcher = watchable.watch();
1190
1191        let start = Instant::now();
1192        let (_, result) = tokio::time::timeout(Duration::from_secs(2), async move {
1193            tokio::join!(
1194                async move {
1195                    tokio::time::sleep(Duration::from_secs(1)).await;
1196                    drop(watchable);
1197                },
1198                async move { watcher.updated().await }
1199            )
1200        })
1201        .await
1202        .expect("watcher never updated");
1203        // We should've updated 1s after start, since that's when the watchable was dropped.
1204        // If this is 2s, then the watchable dropping didn't wake up the `Watcher::updated` future.
1205        assert_eq!(start.elapsed(), Duration::from_secs(1));
1206        assert!(result.is_err());
1207    }
1208
1209    #[tokio::test(start_paused = true)]
1210    async fn test_update_wakeup_always_a_change() {
1211        let watchable = Watchable::new(10);
1212        let mut watcher = watchable.watch();
1213
1214        let task = tokio::spawn(async move {
1215            let mut last_value = watcher.get();
1216            let mut values = Vec::new();
1217            while let Ok(value) = watcher.updated().await {
1218                values.push(value);
1219                if last_value == value {
1220                    return Err("value duplicated");
1221                }
1222                last_value = value;
1223            }
1224            Ok(values)
1225        });
1226
1227        // wait for the task to get set up and polled till pending for once
1228        tokio::time::sleep(Duration::from_millis(100)).await;
1229
1230        watchable.set(11).ok();
1231        tokio::time::sleep(Duration::from_millis(100)).await;
1232        let clone = watchable.clone();
1233        drop(clone); // this shouldn't trigger an update
1234        tokio::time::sleep(Duration::from_millis(100)).await;
1235        for i in 1..=10 {
1236            watchable.set(i + 11).ok();
1237            tokio::time::sleep(Duration::from_millis(100)).await;
1238        }
1239        drop(watchable);
1240
1241        let values = task
1242            .await
1243            .expect("task panicked")
1244            .expect("value duplicated");
1245        assert_eq!(values, vec![11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]);
1246    }
1247
1248    #[test]
1249    fn test_has_watchers() {
1250        let a = Watchable::new(1u8);
1251        assert!(!a.has_watchers());
1252        let b = a.clone();
1253        assert!(!a.has_watchers());
1254        assert!(!b.has_watchers());
1255
1256        let watcher = a.watch();
1257        assert!(a.has_watchers());
1258        assert!(b.has_watchers());
1259
1260        drop(watcher);
1261
1262        assert!(!a.has_watchers());
1263        assert!(!b.has_watchers());
1264    }
1265
1266    #[tokio::test]
1267    async fn test_three_watchers_basic() {
1268        let watchable = Watchable::new(1u8);
1269
1270        let mut w1 = watchable.watch();
1271        let mut w2 = watchable.watch();
1272        let mut w3 = watchable.watch();
1273
1274        // All see the initial value
1275
1276        assert_eq!(w1.get(), 1);
1277        assert_eq!(w2.get(), 1);
1278        assert_eq!(w3.get(), 1);
1279
1280        // Change  value
1281        watchable.set(42).unwrap();
1282
1283        // All watchers get notified
1284        assert_eq!(w1.updated().await.unwrap(), 42);
1285        assert_eq!(w2.updated().await.unwrap(), 42);
1286        assert_eq!(w3.updated().await.unwrap(), 42);
1287    }
1288
1289    #[tokio::test]
1290    async fn test_three_watchers_skip_intermediate() {
1291        let watchable = Watchable::new(0u8);
1292        let mut watcher = watchable.watch();
1293
1294        watchable.set(1).ok();
1295        watchable.set(2).ok();
1296        watchable.set(3).ok();
1297        watchable.set(4).ok();
1298
1299        let value = watcher.updated().await.unwrap();
1300
1301        assert_eq!(value, 4);
1302    }
1303
1304    #[tokio::test]
1305    async fn test_three_watchers_with_streams() {
1306        let watchable = Watchable::new(10u8);
1307
1308        let mut stream1 = watchable.watch().stream();
1309        let mut stream2 = watchable.watch().stream();
1310        let mut stream3 = watchable.watch().stream_updates_only();
1311
1312        assert_eq!(stream1.next().await.unwrap(), 10);
1313        assert_eq!(stream2.next().await.unwrap(), 10);
1314
1315        // Update the value
1316        watchable.set(20).ok();
1317
1318        // All streams see the update
1319        assert_eq!(stream1.next().await.unwrap(), 20);
1320        assert_eq!(stream2.next().await.unwrap(), 20);
1321        assert_eq!(stream3.next().await.unwrap(), 20);
1322    }
1323
1324    #[tokio::test]
1325    async fn test_three_watchers_independent() {
1326        let watchable = Watchable::new(0u8);
1327
1328        let mut fast_watcher = watchable.watch();
1329        let mut slow_watcher = watchable.watch();
1330        let mut lazy_watcher = watchable.watch();
1331
1332        watchable.set(1).ok();
1333        assert_eq!(fast_watcher.updated().await.unwrap(), 1);
1334
1335        // More updates happen
1336        watchable.set(2).ok();
1337        watchable.set(3).ok();
1338
1339        assert_eq!(slow_watcher.updated().await.unwrap(), 3);
1340        assert_eq!(lazy_watcher.get(), 3);
1341    }
1342
1343    #[tokio::test]
1344    async fn test_combine_three_watchers() {
1345        let a = Watchable::new(1u8);
1346        let b = Watchable::new(2u8);
1347        let c = Watchable::new(3u8);
1348
1349        let mut combined = Triple::new(a.watch(), b.watch(), c.watch());
1350
1351        assert_eq!(combined.get(), (1, 2, 3));
1352
1353        // Update one
1354        b.set(20).ok();
1355
1356        assert_eq!(combined.updated().await.unwrap(), (1, 20, 3));
1357
1358        c.set(30).ok();
1359        assert_eq!(combined.updated().await.unwrap(), (1, 20, 30));
1360    }
1361
1362    #[tokio::test]
1363    async fn test_three_watchers_disconnection() {
1364        let watchable = Watchable::new(5u8);
1365
1366        // All connected
1367        let mut w1 = watchable.watch();
1368        let mut w2 = watchable.watch();
1369        let mut w3 = watchable.watch();
1370
1371        // Drop the watchable
1372        drop(watchable);
1373
1374        // All become disconnected
1375        assert!(!w1.is_connected());
1376        assert!(!w2.is_connected());
1377        assert!(!w3.is_connected());
1378
1379        // Can still get last known value
1380        assert_eq!(w1.get(), 5);
1381        assert_eq!(w2.get(), 5);
1382
1383        // But updates fail
1384        assert!(w3.updated().await.is_err());
1385    }
1386
1387    #[tokio::test]
1388    async fn test_three_watchers_truly_concurrent() {
1389        use tokio::time::sleep;
1390        let watchable = Watchable::new(0u8);
1391
1392        // Spawn three READER tasks
1393        let mut reader_handles = vec![];
1394        for i in 0..3 {
1395            let mut watcher = watchable.watch();
1396            let handle = tokio::spawn(async move {
1397                let mut values = vec![];
1398                // Collect up to 5 updates
1399                for _ in 0..5 {
1400                    if let Ok(value) = watcher.updated().await {
1401                        values.push(value);
1402                    } else {
1403                        break;
1404                    }
1405                }
1406                (i, values)
1407            });
1408            reader_handles.push(handle);
1409        }
1410
1411        // Spawn three WRITER tasks that update concurrently
1412        let mut writer_handles = vec![];
1413        for i in 0..3 {
1414            let watchable_clone = watchable.clone();
1415            let handle = tokio::spawn(async move {
1416                for j in 0..5 {
1417                    let value = (i * 10) + j;
1418                    watchable_clone.set(value).ok();
1419                    sleep(Duration::from_millis(5)).await;
1420                }
1421            });
1422            writer_handles.push(handle);
1423        }
1424
1425        // Wait for writers to finish
1426        for handle in writer_handles {
1427            handle.await.unwrap();
1428        }
1429
1430        // Wait for readers and check results
1431        for handle in reader_handles {
1432            let (task_id, values) = handle.await.unwrap();
1433            println!("Reader {}: saw values {:?}", task_id, values);
1434            assert!(!values.is_empty());
1435        }
1436    }
1437
1438    #[tokio::test]
1439    async fn test_peek() {
1440        let a = Watchable::new(vec![1, 2, 3]);
1441        let mut wa = a.watch();
1442
1443        assert_eq!(wa.get(), vec![1, 2, 3]);
1444        assert_eq!(wa.peek(), &vec![1, 2, 3]);
1445
1446        let mut wa_map = wa.map(|a| a.into_iter().map(|a| a * 2).collect::<Vec<_>>());
1447
1448        assert_eq!(wa_map.get(), vec![2, 4, 6]);
1449        assert_eq!(wa_map.peek(), &vec![2, 4, 6]);
1450
1451        let mut wb = a.watch();
1452
1453        assert_eq!(wb.get(), vec![1, 2, 3]);
1454        assert_eq!(wb.peek(), &vec![1, 2, 3]);
1455
1456        let mut wb_map = wb.map(|a| a.into_iter().map(|a| a * 2).collect::<Vec<_>>());
1457
1458        assert_eq!(wb_map.get(), vec![2, 4, 6]);
1459        assert_eq!(wb_map.peek(), &vec![2, 4, 6]);
1460
1461        let mut w_join = Join::new([wa_map, wb_map].into_iter());
1462
1463        assert_eq!(w_join.get(), vec![vec![2, 4, 6], vec![2, 4, 6]]);
1464        assert_eq!(w_join.peek(), &vec![vec![2, 4, 6], vec![2, 4, 6]]);
1465    }
1466
1467    #[tokio::test]
1468    async fn test_update_updates_peek() {
1469        let value = Watchable::new(42);
1470        let mut watcher = value.watch();
1471
1472        assert_eq!(watcher.peek(), &42);
1473        assert!(!watcher.update());
1474
1475        value.set(50).ok();
1476
1477        assert_eq!(watcher.peek(), &42); // watcher wasn't updated yet
1478        assert!(watcher.update()); // Update returns true, because there was an update
1479        assert_eq!(watcher.peek(), &50);
1480        assert!(!watcher.update());
1481
1482        let mut watcher_map = watcher.clone().map(|v| v * 2);
1483
1484        assert_eq!(watcher_map.peek(), &100);
1485        assert!(!watcher_map.update());
1486
1487        value.set(10).ok();
1488
1489        assert_eq!(watcher_map.peek(), &100);
1490        assert!(watcher_map.update());
1491        assert_eq!(watcher_map.peek(), &20);
1492        assert!(!watcher_map.update());
1493
1494        let value2 = Watchable::new(0);
1495        let mut watcher_join = Join::new([watcher, value2.watch()].into_iter());
1496
1497        assert_eq!(watcher_join.peek(), &vec![10, 0]);
1498        assert!(!watcher_join.update());
1499
1500        value.set(0).ok();
1501        value2.set(1).ok();
1502
1503        assert_eq!(watcher_join.peek(), &vec![10, 0]);
1504        assert!(watcher_join.update());
1505        assert_eq!(watcher_join.peek(), &vec![0, 1]);
1506        assert!(!watcher_join.update());
1507    }
1508
1509    #[tokio::test]
1510    async fn test_get_updates_peek() {
1511        let value = Watchable::new(42);
1512        let mut watcher = value.watch();
1513
1514        assert_eq!(watcher.peek(), &42);
1515        assert!(!watcher.update());
1516
1517        value.set(50).ok();
1518
1519        assert_eq!(watcher.peek(), &42); // watcher wasn't updated yet
1520        assert_eq!(watcher.get(), 50); // Update returns true, because there was an update
1521        assert_eq!(watcher.peek(), &50);
1522        assert!(!watcher.update());
1523
1524        let mut watcher_map = watcher.clone().map(|v| v * 2);
1525
1526        assert_eq!(watcher_map.peek(), &100);
1527        assert!(!watcher_map.update());
1528
1529        value.set(10).ok();
1530
1531        assert_eq!(watcher_map.peek(), &100);
1532        assert_eq!(watcher_map.get(), 20);
1533        assert_eq!(watcher_map.peek(), &20);
1534        assert!(!watcher_map.update());
1535
1536        let value2 = Watchable::new(0);
1537        let mut watcher_join = Join::new([watcher, value2.watch()].into_iter());
1538
1539        assert_eq!(watcher_join.peek(), &vec![10, 0]);
1540        assert!(!watcher_join.update());
1541
1542        value.set(0).ok();
1543        value2.set(1).ok();
1544
1545        assert_eq!(watcher_join.peek(), &vec![10, 0]);
1546        assert_eq!(watcher_join.get(), vec![0, 1]);
1547        assert_eq!(watcher_join.peek(), &vec![0, 1]);
1548        assert!(!watcher_join.update());
1549    }
1550
1551    #[tokio::test]
1552    async fn test_ensure_wakers_bounded() {
1553        use tokio::time::{interval, Duration};
1554        let watchable = Watchable::new(0);
1555        let mut watcher = watchable.watch();
1556        let max_tick = 1000;
1557
1558        let handle = tokio::spawn(async move {
1559            let mut ticker = interval(Duration::from_nanos(1));
1560            let mut tick_no = 0;
1561            loop {
1562                tokio::select! {
1563                    _ = watcher.updated() => {}
1564                    _ = ticker.tick() => {
1565                        // We cancel the other future and start over again
1566                        tick_no += 1;
1567                        if tick_no > max_tick{
1568                            return
1569                        }
1570                    }
1571                }
1572                let num_wakers = watchable.shared.wakers.lock().unwrap().len();
1573                assert_eq!(num_wakers, 1);
1574            }
1575        });
1576
1577        tokio::time::timeout(Duration::from_secs(1), handle)
1578            .await
1579            .unwrap()
1580            .unwrap()
1581    }
1582
1583    #[tokio::test]
1584    async fn regression_completed_tasks_clean_up_wakers() {
1585        const N: usize = 100;
1586        let watchable = Watchable::new(0u64);
1587
1588        let mut tasks = JoinSet::new();
1589        for _ in 0..N {
1590            let mut w = watchable.watch();
1591            tasks.spawn(async move {
1592                // Register the `Direct` as a future in this tokio task by polling once,
1593                // but then end the task without waiting for wake.
1594                tokio::select! {
1595                    biased;
1596                    _ = w.updated() => {}
1597                    _ = std::future::ready(()) => {}
1598                }
1599            });
1600        }
1601        tasks.join_all().await;
1602
1603        // All N tasks completed and joined. The watchable should not store any wakers.
1604        // Calling `watchable.set(1)` would drain all wakers. In a previous version that
1605        // list was non-empty here and draining it would free memory.
1606        assert_eq!(watchable.debug_waker_counts(), vec![]);
1607    }
1608
1609    #[tokio::test(start_paused = true)]
1610    async fn regression_same_task_drop_one_watcher_during_poll() {
1611        struct SameTaskDropOneDirectDuringPoll {
1612            watcher_1: Option<Direct<u64>>,
1613            watcher_2: Direct<u64>,
1614        }
1615
1616        impl Future for SameTaskDropOneDirectDuringPoll {
1617            type Output = Result<(), Disconnected>;
1618
1619            fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
1620                // register a waker with both watchers
1621                if let Some(watcher) = &mut self.watcher_1 {
1622                    let _ = watcher.poll_updated(cx);
1623                }
1624                let res = self.watcher_2.poll_updated(cx);
1625                self.watcher_1 = None; // drop watcher 1
1626                res
1627            }
1628        }
1629
1630        let watcher = Watchable::new(0);
1631        let weird = SameTaskDropOneDirectDuringPoll {
1632            watcher_1: Some(watcher.watch()),
1633            watcher_2: watcher.watch(),
1634        };
1635        let task = tokio::spawn(weird);
1636        tokio::time::sleep(Duration::from_millis(100)).await;
1637        let _ = watcher.set(1);
1638        tokio::time::timeout(Duration::from_millis(100), task)
1639            .await
1640            .unwrap() // no panic
1641            .unwrap() // no timeout
1642            .unwrap(); // no watcher disconnect
1643    }
1644
1645    #[tokio::test]
1646    async fn regression_waker_count_stuck_on_double_poll() {
1647        let watchable = Watchable::new(0u64);
1648        let mut watcher = watchable.watch();
1649
1650        // poll the watcher twice
1651        tokio::select! {
1652            biased;
1653            _ = watcher.updated() => {}
1654            _ = std::future::ready(()) => {}
1655        }
1656        tokio::select! {
1657            biased;
1658            _ = watcher.updated() => {}
1659            _ = std::future::ready(()) => {}
1660        }
1661        drop(watcher);
1662
1663        assert_eq!(watchable.debug_waker_counts(), vec![]);
1664    }
1665
1666    #[tokio::test]
1667    async fn regression_waker_key_must_be_unchanged_on_remove() {
1668        let watchable = Watchable::new(0u64);
1669        let mut w1 = watchable.watch();
1670        let mut w2 = watchable.watch();
1671
1672        // register both watchers' wakers
1673        tokio::select! {
1674            biased;
1675            _ = w1.updated() => {}
1676            _ = w2.updated() => {}
1677            _ = std::future::ready(()) => {}
1678        }
1679        // we test the sum, because release and debug mode operate differently with tokio:
1680        // In release mode, `will_wake` returns false negatives causing us to have [1, 1] waker counts,
1681        // in debug mode, this doesn't happen, thus we're left with [2] as the waker counts.
1682        // The reason for the difference is related to tokio waker vtables being split across CGUs.
1683        assert_eq!(watchable.debug_waker_counts().iter().sum::<u64>(), 2);
1684        drop(w2); // unregister one watcher
1685        assert_eq!(watchable.debug_waker_counts().iter().sum::<u64>(), 1);
1686        // This used to add another count to the waker as
1687        // unregistering one watcher used to swap out the key
1688        // used for said waker.
1689        tokio::select! {
1690            biased;
1691            _ = w1.updated() => {}
1692            _ = std::future::ready(()) => {}
1693        }
1694        assert_eq!(watchable.debug_waker_counts().iter().sum::<u64>(), 1);
1695        drop(w1); // dropping the final waker should free the waker list
1696        assert_eq!(watchable.debug_waker_counts(), vec![]);
1697    }
1698}