watchable 1.1.2

A watchable RwLock-like type that is compatible with both multi-threaded and async code.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
#![doc = include_str!(".crate-docs.md")]
#![forbid(unsafe_code)]
#![warn(
    clippy::cargo,
    missing_docs,
    // clippy::missing_docs_in_private_items,
    clippy::pedantic,
    future_incompatible,
    rust_2018_idioms,
)]
#![allow(clippy::option_if_let_else, clippy::module_name_repetitions)]

use std::{
    ops::{Deref, DerefMut},
    pin::Pin,
    sync::{
        atomic::{AtomicUsize, Ordering},
        Arc,
    },
    task::Poll,
    time::{Duration, Instant},
};

use event_listener::{Event, EventListener};
use futures_util::{FutureExt, Stream};
use parking_lot::{RwLock, RwLockReadGuard, RwLockUpgradableReadGuard, RwLockWriteGuard};

/// A watchable wrapper for a value.
#[derive(Default, Debug)]
pub struct Watchable<T> {
    data: Arc<Data<T>>,
}

impl<T> Clone for Watchable<T> {
    fn clone(&self) -> Self {
        self.data.watchables.fetch_add(1, Ordering::AcqRel);
        Self {
            data: self.data.clone(),
        }
    }
}

impl<T> Drop for Watchable<T> {
    fn drop(&mut self) {
        if self.data.watchables.fetch_sub(1, Ordering::AcqRel) == 1 {
            // Last watchable
            self.shutdown();
        }
    }
}

impl<T> Watchable<T> {
    /// Returns a new instance with the initial value provided.
    pub fn new(initial_value: T) -> Self {
        Self {
            data: Arc::new(Data {
                value: RwLock::new(initial_value),
                changed: RwLock::new(Some(Event::new())),
                version: AtomicUsize::new(0),
                watchers: AtomicUsize::new(0),
                watchables: AtomicUsize::new(1),
            }),
        }
    }

    /// Returns a new watcher that can monitor for changes to the contained
    /// value.
    pub fn watch(&self) -> Watcher<T> {
        self.data.watchers.fetch_add(1, Ordering::AcqRel);
        Watcher {
            version: AtomicUsize::new(self.data.current_version()),
            watched: self.data.clone(),
        }
    }

    /// Replaces the current value contained and notifies all watching
    /// [`Watcher`]s. Returns the previously stored value.
    pub fn replace(&self, new_value: T) -> T {
        let mut stored = self.data.value.write();
        let mut old_value = new_value;
        std::mem::swap(&mut *stored, &mut old_value);
        self.data.increment_version();
        old_value
    }

    /// Updates the current value, if it is different from the contained value.
    /// Returns `Ok(previous_value)` if `new_value != previous_value`, otherwise
    /// returns `Err(new_value)`.
    ///
    /// # Errors
    ///
    /// Returns `Err(new_value)` if the currently stored value is equal to `new_value`.
    pub fn update(&self, new_value: T) -> Result<T, T>
    where
        T: PartialEq,
    {
        let stored = self.data.value.upgradable_read();
        if *stored == new_value {
            Err(new_value)
        } else {
            let mut stored = RwLockUpgradableReadGuard::upgrade(stored);
            let mut old_value = new_value;
            std::mem::swap(&mut *stored, &mut old_value);
            self.data.increment_version();
            Ok(old_value)
        }
    }

    /// Returns a write guard that allows updating the value. If the inner value
    /// is accessed through [`DerefMut::deref_mut()`], all [`Watcher`]s will be
    /// notified when the returned guard is dropped.
    ///
    /// [`WatchableWriteGuard`] holds an exclusive lock. No other threads will
    /// be able to read or write the contained value until the guard is dropped.
    pub fn write(&self) -> WatchableWriteGuard<'_, T> {
        WatchableWriteGuard {
            watchable: self,
            guard: self.data.value.write(),
            accessed_mut: false,
        }
    }

    /// Returns a guard which can be used to access the value held within the
    /// variable. This guard does not block other threads from reading the
    /// value.
    pub fn read(&self) -> WatchableReadGuard<'_, T> {
        WatchableReadGuard(self.data.value.read())
    }

    /// Returns the currently contained value.
    #[must_use]
    pub fn get(&self) -> T
    where
        T: Clone,
    {
        self.data.value.read().clone()
    }

    /// Returns the number of [`Watcher`]s for this value.
    #[must_use]
    pub fn watchers(&self) -> usize {
        self.data.watchers.load(Ordering::Acquire)
    }

    /// Returns true if there are any [`Watcher`]s for this value.
    #[must_use]
    pub fn has_watchers(&self) -> bool {
        self.watchers() > 0
    }

    /// Disconnects all [`Watcher`]s.
    ///
    /// All future value updates will not be observed by the watchers, but the
    /// last value will still be readable before the watcher signals that it is
    /// disconnected.
    pub fn shutdown(&self) {
        let mut changed = self.data.changed.write();
        if let Some(changed) = changed.take() {
            changed.notify(usize::MAX);
        }
    }
}

impl<T> Data<T> {
    fn current_version(&self) -> usize {
        self.version.load(Ordering::Acquire)
    }

    fn increment_version(&self) {
        self.version.fetch_add(1, Ordering::AcqRel);
        let changed = self.changed.read();
        if let Some(changed) = changed.as_ref() {
            changed.notify(usize::MAX);
        }
    }
}

/// A read guard that allows reading the currently stored value in a
/// [`Watchable`]. No values can be stored within the source [`Watchable`] while
/// this guard exists.
///
/// The inner value is accessible through [`Deref`].
#[must_use]
pub struct WatchableReadGuard<'a, T>(RwLockReadGuard<'a, T>);

impl<'a, T> Deref for WatchableReadGuard<'a, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// A write guard that allows updating the currently stored value in a
/// [`Watchable`].
///
/// The inner value is readable through [`Deref`], and modifiable through
/// [`DerefMut`]. Any usage of [`DerefMut`] will cause all [`Watcher`]s to be
/// notified of an updated value when the guard is dropped.
///
/// [`WatchableWriteGuard`] is an exclusive guard. No other threads will be
/// able to read or write the contained value until the guard is dropped.
#[must_use]
pub struct WatchableWriteGuard<'a, T> {
    watchable: &'a Watchable<T>,
    accessed_mut: bool,
    guard: RwLockWriteGuard<'a, T>,
}

impl<'a, T> Deref for WatchableWriteGuard<'a, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.guard
    }
}

impl<'a, T> DerefMut for WatchableWriteGuard<'a, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.accessed_mut = true;
        &mut self.guard
    }
}

impl<'a, T> Drop for WatchableWriteGuard<'a, T> {
    fn drop(&mut self) {
        if self.accessed_mut {
            self.watchable.data.increment_version();
        }
    }
}

#[derive(Debug)]
struct Data<T> {
    changed: RwLock<Option<Event>>,
    version: AtomicUsize,
    watchers: AtomicUsize,
    watchables: AtomicUsize,
    value: RwLock<T>,
}

impl<T> Default for Data<T>
where
    T: Default,
{
    fn default() -> Self {
        Self {
            changed: RwLock::new(Some(Event::new())),
            version: AtomicUsize::new(0),
            watchers: AtomicUsize::new(0),
            watchables: AtomicUsize::new(1),
            value: RwLock::default(),
        }
    }
}

/// An observer of a [`Watchable`] value.
///
/// ## Cloning behavior
///
/// Cloning a watcher also clones the current watching state. If the watcher
/// hasn't read the value currently stored, the cloned instance will also
/// consider the current value unread.
#[derive(Debug)]
#[must_use]
pub struct Watcher<T> {
    version: AtomicUsize,
    watched: Arc<Data<T>>,
}

impl<T> Drop for Watcher<T> {
    fn drop(&mut self) {
        self.watched.watchers.fetch_sub(1, Ordering::AcqRel);
    }
}

impl<T> Clone for Watcher<T> {
    fn clone(&self) -> Self {
        Self {
            version: AtomicUsize::new(self.version.load(Ordering::Relaxed)),
            watched: self.watched.clone(),
        }
    }
}

#[derive(Debug)]
enum CreateListenerError {
    NewValueAvailable,
    Disconnected,
}

/// A watch operation failed because all [`Watchable`] instances have been
/// dropped.
#[derive(Debug, thiserror::Error, Eq, PartialEq)]
#[error("all watchable instances have been dropped")]
pub struct Disconnected;

/// A watch operation with a timeout failed.
#[derive(Debug, thiserror::Error, Eq, PartialEq)]
pub enum TimeoutError {
    /// A watch operation failed because all [`Watchable`] instances have been
    /// dropped.
    #[error("all watchable instances have been dropped")]
    Disconnected,
    /// No new values were written before the timeout elapsed
    #[error("no new values were written before the timeout elapsed")]
    Timeout,
}

impl<T> Watcher<T> {
    fn create_listener_if_needed(&self) -> Result<Pin<Box<EventListener>>, CreateListenerError> {
        let changed = self.watched.changed.read();
        match (changed.as_ref(), self.is_current()) {
            (_, false) => Err(CreateListenerError::NewValueAvailable),
            (None, _) => Err(CreateListenerError::Disconnected),
            (Some(changed), true) => {
                let listener = changed.listen();

                // Between now and creating the listener, an update may have
                // come in, so we need to check again before returning the
                // listener.
                if self.is_current() {
                    Ok(listener)
                } else {
                    Err(CreateListenerError::NewValueAvailable)
                }
            }
        }
    }

    /// Returns true if the latest value has been read from this instance.
    #[must_use]
    pub fn is_current(&self) -> bool {
        self.version.load(Ordering::Relaxed) == self.watched.current_version()
    }

    /// Updates this instance's state to reflect that it has read the currently
    /// stored value. The next call to a watch call will block until the next
    /// value is stored.
    ///
    /// Returns true if the internal state was updated, and false if no changes
    /// were necessary.
    pub fn mark_read(&self) -> bool {
        let current_version = self.watched.current_version();
        let mut stored_version = self.version.load(Ordering::Acquire);
        while stored_version < current_version {
            match self.version.compare_exchange(
                stored_version,
                current_version,
                Ordering::Release,
                Ordering::Acquire,
            ) {
                Ok(_) => return true,
                Err(new_stored) => stored_version = new_stored,
            }
        }
        false
    }

    /// Watches for a new value to be stored in the source [`Watchable`]. If the
    /// current value hasn't been accessed through [`Self::read()`] or marked
    /// read with [`Self::mark_read()`], this call will block the calling
    /// thread until a new value has been published.
    ///
    /// # Errors
    ///
    /// Returns [`Disconnected`] if all instances of [`Watchable`] have been
    /// dropped and the current value has been read.
    pub fn watch(&self) -> Result<(), Disconnected> {
        loop {
            match self.create_listener_if_needed() {
                Ok(mut listener) => {
                    listener.as_mut().wait();
                    if !self.is_current() {
                        break;
                    }
                }
                Err(CreateListenerError::Disconnected) => return Err(Disconnected),
                Err(CreateListenerError::NewValueAvailable) => break,
            }
        }

        Ok(())
    }

    /// Watches for a new value to be stored in the source [`Watchable`]. If the
    /// current value hasn't been accessed through [`Self::read()`] or marked
    /// read with [`Self::mark_read()`], this call will block the calling
    /// thread until a new value has been published or until `duration` has
    /// elapsed.
    ///
    /// # Errors
    ///
    /// - [`TimeoutError::Disconnected`]: All instances of [`Watchable`] have
    /// been dropped and the current value has been read.
    /// - [`TimeoutError::Timeout`]: A timeout occurred before a new value was
    /// written.
    pub fn watch_timeout(&self, duration: Duration) -> Result<(), TimeoutError> {
        self.watch_until(Instant::now() + duration)
    }

    /// Watches for a new value to be stored in the source [`Watchable`]. If the
    /// current value hasn't been accessed through [`Self::read()`] or marked
    /// read with [`Self::mark_read()`], this call will block the calling
    /// thread until a new value has been published or until `deadline`.
    ///
    /// # Errors
    ///
    /// - [`TimeoutError::Disconnected`]: All instances of [`Watchable`] have
    /// been dropped and the current value has been read.
    /// - [`TimeoutError::Timeout`]: A timeout occurred before a new value was
    /// written.
    pub fn watch_until(&self, deadline: Instant) -> Result<(), TimeoutError> {
        loop {
            match self.create_listener_if_needed() {
                Ok(mut listener) => {
                    if listener.as_mut().wait_deadline(deadline).is_some() {
                        if !self.is_current() {
                            break;
                        } else if Instant::now() < deadline {
                            // Spurious wake-up
                        }
                    } else {
                        return Err(TimeoutError::Timeout);
                    }
                }
                Err(CreateListenerError::Disconnected) => return Err(TimeoutError::Disconnected),
                Err(CreateListenerError::NewValueAvailable) => break,
            }
        }

        Ok(())
    }

    /// Watches for a new value to be stored in the source [`Watchable`]. If the
    /// current value hasn't been accessed through [`Self::read()`] or marked
    /// read with [`Self::mark_read()`], the async task will block until
    /// a new value has been published.
    ///
    /// # Errors
    ///
    /// Returns [`Disconnected`] if all instances of [`Watchable`] have been
    /// dropped and the current value has been read.
    pub async fn watch_async(&self) -> Result<(), Disconnected> {
        loop {
            match self.create_listener_if_needed() {
                Ok(listener) => {
                    listener.await;
                    if !self.is_current() {
                        break;
                    }
                }
                Err(CreateListenerError::Disconnected) => return Err(Disconnected),
                Err(CreateListenerError::NewValueAvailable) => break,
            }
        }
        Ok(())
    }

    /// Returns a read guard that allows reading the currently stored value.
    /// This function does not consider the value read, and the next call to a
    /// watch function will be unaffected.
    pub fn peek(&self) -> WatchableReadGuard<'_, T> {
        let guard = self.watched.value.read();
        WatchableReadGuard(guard)
    }

    /// Returns a read guard that allows reading the currently stored value.
    /// This function marks the stored value as read, ensuring that the next
    /// call to a watch function will block until the a new value has been
    /// published.
    pub fn read(&self) -> WatchableReadGuard<'_, T> {
        let guard = self.watched.value.read();
        self.version
            .store(self.watched.current_version(), Ordering::Relaxed);
        WatchableReadGuard(guard)
    }

    /// Returns the currently contained value. This function marks the stored
    /// value as read, ensuring that the next call to a watch function will
    /// block until the a new value has been published.
    #[must_use]
    pub fn get(&self) -> T
    where
        T: Clone,
    {
        self.read().clone()
    }

    /// Watches for a new value to be stored in the source [`Watchable`] and
    /// returns a clone of it. If the current value hasn't been accessed through
    /// [`Self::read()`] or marked read with [`Self::mark_read()`], this call
    /// will block the calling thread until a new value has been published.
    ///
    /// # Errors
    ///
    /// Returns [`Disconnected`] if all instances of [`Watchable`] have been
    /// dropped and the current value has been read.
    pub fn next_value(&self) -> Result<T, Disconnected>
    where
        T: Clone,
    {
        self.watch().map(|()| self.read().clone())
    }

    /// Watches for a new value to be stored in the source [`Watchable`] and
    /// returns a clone of it. If the current value hasn't been accessed through
    /// [`Self::read()`] or marked read with [`Self::mark_read()`], this call
    /// will asynchronously wait for a new value to be published.
    ///
    /// The async task is safe to be cancelled without losing track of the last
    /// read value.
    ///
    /// # Errors
    ///
    /// Returns [`Disconnected`] if all instances of [`Watchable`] have been
    /// dropped and the current value has been read.
    pub async fn next_value_async(&self) -> Result<T, Disconnected>
    where
        T: Clone,
    {
        self.watch_async().await.map(|()| self.read().clone())
    }

    /// Returns this watcher in a type that implements [`Stream`].
    pub fn into_stream(self) -> WatcherStream<T> {
        WatcherStream {
            watcher: self,
            listener: None,
        }
    }
}

impl<T> Iterator for Watcher<T>
where
    T: Clone,
{
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        self.next_value().ok()
    }
}

/// Asynchronous iterator for a [`Watcher`]. Implements [`Stream`].
#[derive(Debug)]
#[must_use]
pub struct WatcherStream<T> {
    watcher: Watcher<T>,
    listener: Option<Pin<Box<EventListener>>>,
}

impl<T> WatcherStream<T> {
    /// Returns the wrapped [`Watcher`].
    pub fn into_inner(self) -> Watcher<T> {
        self.watcher
    }
}

impl<T> Stream for WatcherStream<T>
where
    T: Clone,
{
    type Item = T;

    fn poll_next(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> Poll<Option<Self::Item>> {
        // If we have a listener or we have already read the current value, we
        // need to poll the listener as a future first.
        loop {
            match self
                .listener
                .take()
                .ok_or(CreateListenerError::Disconnected)
                .or_else(|_| self.watcher.create_listener_if_needed())
            {
                Ok(mut listener) => {
                    match listener.poll_unpin(cx) {
                        Poll::Ready(()) => {
                            if !self.watcher.is_current() {
                                break;
                            }

                            // A new value is available. Fall through.
                        }
                        Poll::Pending => {
                            // The listener wasn't ready, store it again.
                            self.listener = Some(listener);
                            return Poll::Pending;
                        }
                    }
                }
                Err(CreateListenerError::NewValueAvailable) => break,
                Err(CreateListenerError::Disconnected) => return Poll::Ready(None),
            }
        }

        Poll::Ready(Some(self.watcher.read().clone()))
    }
}

#[test]
fn basics() {
    let watchable = Watchable::new(1_u32);
    assert!(!watchable.has_watchers());
    let watcher1 = watchable.watch();
    let watcher2 = watchable.watch();
    assert!(!watcher1.mark_read());

    assert_eq!(watchable.watchers(), 2);
    assert_eq!(watchable.replace(2), 1);
    // A call to watch should not block since the value has already been sent
    watcher1.watch().unwrap();
    // Peek shouldn't cause the watcher to block.
    assert_eq!(*watcher1.peek(), 2);
    watcher1.watch().unwrap();
    // Reading should switch the state back to needing to block, which we'll
    // test in an other unit test
    assert_eq!(*watcher1.read(), 2);
    assert!(!watcher1.mark_read());
    drop(watcher1);
    assert_eq!(watchable.watchers(), 1);

    // Now, despite watcher1 having updated, watcher2 should have independent state
    assert!(watcher2.mark_read());
    assert_eq!(*watcher2.read(), 2);
    drop(watcher2);
    assert_eq!(watchable.watchers(), 0);
}

#[test]
fn accessing_values() {
    let watchable = Watchable::new(String::from("hello"));
    assert_eq!(watchable.get(), "hello");
    assert_eq!(&*watchable.read(), "hello");
    assert_eq!(&*watchable.write(), "hello");

    let watcher = watchable.watch();
    assert_eq!(watcher.get(), "hello");
    assert_eq!(&*watcher.read(), "hello");
}

#[test]
#[allow(clippy::redundant_clone)]
fn clones() {
    let watchable = Watchable::default();
    let cloned_watchable = watchable.clone();
    let watcher1 = watchable.watch();
    let watcher2 = watcher1.clone();

    watchable.replace(1);
    assert_eq!(watcher1.next_value().unwrap(), 1);
    assert_eq!(watcher2.next_value().unwrap(), 1);
    cloned_watchable.replace(2);
    assert_eq!(watcher1.next_value().unwrap(), 2);
    assert_eq!(watcher2.next_value().unwrap(), 2);
}

#[test]
fn drop_watchable() {
    let watchable = Watchable::default();
    assert!(!watchable.has_watchers());
    let watcher = watchable.watch();

    watchable.replace(1_u32);
    assert_eq!(watcher.next_value().unwrap(), 1);

    drop(watchable);
    assert!(matches!(watcher.next_value().unwrap_err(), Disconnected));
}

#[test]
fn drop_watchable_timeouts() {
    let watchable = Watchable::new(0_u8);
    assert!(!watchable.has_watchers());
    let watcher = watchable.watch();
    let start = Instant::now();
    let wait_timeout_thread = std::thread::spawn(move || {
        assert!(matches!(
            watcher.watch_timeout(Duration::from_secs(15)).unwrap_err(),
            TimeoutError::Disconnected
        ));
    });
    let watcher = watchable.watch();
    let wait_until_thread = std::thread::spawn(move || {
        assert!(matches!(
            watcher
                .watch_until(Instant::now().checked_add(Duration::from_secs(15)).unwrap())
                .unwrap_err(),
            TimeoutError::Disconnected
        ));
    });

    // Give time for the threads to spawn.
    std::thread::sleep(Duration::from_millis(100));
    drop(watchable);

    wait_timeout_thread.join().unwrap();
    wait_until_thread.join().unwrap();

    let elapsed = Instant::now().checked_duration_since(start).unwrap();
    assert!(elapsed.as_secs() < 1);
}

#[test]
fn timeouts() {
    let watchable = Watchable::new(1_u32);
    let watcher = watchable.watch();
    let start = Instant::now();
    assert!(matches!(
        watcher.watch_timeout(Duration::from_millis(100)),
        Err(TimeoutError::Timeout)
    ));
    assert!(matches!(
        watcher.watch_until(Instant::now() + Duration::from_millis(100)),
        Err(TimeoutError::Timeout)
    ));
    let elapsed = Instant::now().checked_duration_since(start).unwrap();
    // We don't control the delay logic, so to ensure this test is stable, we're
    // comparing against a duration slightly less than 200 ms even though in
    // theory that shouldn't be possible.
    assert!(elapsed.as_millis() >= 180);

    // Test that watch_timeout/until return true when a new event is available
    watchable.replace(2);
    watcher.watch_timeout(Duration::from_secs(1)).unwrap();
    watchable.replace(3);
    watcher
        .watch_until(Instant::now() + Duration::from_secs(1))
        .unwrap();
}

#[test]
fn deref_publish() {
    let watchable = Watchable::new(1_u32);
    let watcher = watchable.watch();
    // Reading the value (Deref) shouldn't publish a new value
    {
        let write_guard = watchable.write();
        assert_eq!(*write_guard, 1);
    }
    assert!(!watcher.mark_read());
    // Writing a value (DerefMut) should publish a new value
    {
        let mut write_guard = watchable.write();
        *write_guard = 2;
    }
    assert!(watcher.mark_read());
}

#[test]
fn blocking_tests() {
    let watchable = Watchable::new(1_u32);
    let watcher = watchable.watch();
    let (sender, receiver) = std::sync::mpsc::sync_channel(1);
    let worker_thread = std::thread::spawn(move || {
        watcher.watch().unwrap();
        assert_eq!(*watcher.read(), 2);
        sender.send(()).unwrap();
        watcher.watch().unwrap();
        *watcher.read()
    });

    watchable.replace(2);
    // Wait for the thread to perform its read.
    receiver.recv().unwrap();
    assert!(watchable.update(42).is_ok());
    assert!(watchable.update(42).is_err());

    assert_eq!(worker_thread.join().unwrap(), 42);
}

#[test]
fn iterator_test() {
    let watchable = Watchable::new(1_u32);
    let watcher = watchable.watch();
    let worker_thread = std::thread::spawn(move || {
        let mut last_value = watcher.next_value().unwrap();
        for value in watcher {
            assert_ne!(last_value, value);
            println!("Received {value}");
            last_value = value;
        }
        assert_eq!(last_value, 1000);
    });

    for i in 1..=1000 {
        watchable.replace(i);
    }
    drop(watchable);
    worker_thread.join().unwrap();
}

#[cfg(test)]
#[tokio::test(flavor = "multi_thread")]
async fn stream_test() {
    use futures_util::StreamExt;

    let watchable = Watchable::default();
    let watcher = watchable.watch();
    let worker_thread = tokio::task::spawn(async move {
        let mut last_value = watcher.next_value_async().await.unwrap();
        let mut stream = watcher.into_stream();
        while let Some(value) = stream.next().await {
            assert_ne!(last_value, value);
            println!("Received {value}");
            last_value = value;
        }
        assert_eq!(last_value, 1000);

        // Ensure it's safe to call next again with no blocking and no panics.
        assert!(stream.next().await.is_none());

        // Convert back to a normal watcher and check that the state still
        // matches.
        let watcher = stream.into_inner();
        assert!(!watcher.mark_read());
    });

    for i in 1..=1000 {
        watchable.replace(i);
        if i % 100 == 0 {
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    }

    // Allow the stream to end
    drop(watchable);

    // Wait for the task to finish.
    worker_thread.await.unwrap();
}

#[test]
fn stress_test() {
    let watchable = Watchable::new(1_u32);
    let mut workers = Vec::new();
    for _ in 1..=10 {
        let watcher = watchable.watch();
        workers.push(std::thread::spawn(move || {
            let mut last_value = *watcher.read();
            while watcher.watch().is_ok() {
                let current_value = *watcher.read();
                assert_ne!(last_value, current_value);
                last_value = current_value;
            }
            assert_eq!(last_value, 10000);
        }));
    }

    for i in 1..=10000 {
        let _ = watchable.update(i);
    }
    drop(watchable);

    for worker in workers {
        worker.join().unwrap();
    }
}

#[cfg(test)]
#[tokio::test(flavor = "multi_thread")]
async fn stress_test_async() {
    let watchable = Watchable::new(1_u32);
    let mut workers = Vec::new();
    for _ in 1..=64 {
        let watcher = watchable.watch();
        workers.push(tokio::task::spawn(async move {
            let mut last_value = *watcher.read();
            loop {
                watcher.watch_async().await.unwrap();
                let current_value = *watcher.read();
                assert_ne!(last_value, current_value);
                if current_value == 10000 {
                    break;
                }
                last_value = current_value;
            }
        }));
    }

    tokio::task::spawn_blocking(move || {
        for i in 1..=10000 {
            let _ = watchable.update(i);
        }
    })
    .await
    .unwrap();

    for worker in workers {
        worker.await.unwrap();
    }
}

#[test]
fn shutdown() {
    let watchable = Watchable::new(0);
    let watcher = watchable.watch();

    // Set a new value, then shutdown
    watchable.replace(1);
    watchable.shutdown();

    // The value should still be accessible
    assert_eq!(watcher.next_value().expect("initial value missing"), 1);
    watcher
        .next_value()
        .expect_err("watcher should be disconnected");
}