Skip to main content

saluki_common/sync/
live.rs

1//! Live views of a shared value.
2//!
3//! [`channel`] creates a [`LivePublisher`] and a [`LiveSource`] that share one root value. The publisher replaces the
4//! root and notifies views. The source reads the root and creates [`Live`] views of parts of it. Each view caches a
5//! snapshot of its selected value and refreshes it only when [`Live::changed`] processes a notification.
6//!
7//! ```
8//! use saluki_common::sync::live;
9//!
10//! # #[tokio::main(flavor = "current_thread")]
11//! # async fn main() {
12//! struct Root {
13//!     enabled: bool,
14//! }
15//!
16//! let (mut publisher, source) = live::channel(Root { enabled: false });
17//! let mut enabled = source.live(|root| &root.enabled);
18//! publisher.publish(Root { enabled: true });
19//!
20//! // An existing view keeps its snapshot until `changed` processes the update; a new view reads the latest root.
21//! assert!(!*enabled);
22//! assert!(*source.live(|root| &root.enabled));
23//!
24//! assert!(enabled.changed().await);
25//! assert!(*enabled);
26//! # }
27//! ```
28
29use std::fmt;
30use std::ops::Deref;
31use std::sync::Arc;
32
33use arc_swap::ArcSwap;
34use futures::stream::{self, Stream};
35use tokio::sync::watch;
36
37/// Borrowed access to the source's projected value, hiding the source type.
38///
39/// Calling a source must call its callback exactly once.
40// Borrowed projections let nested views clone only their selected `T`, not the shared source.
41type Source<T> = Arc<dyn Fn(&mut dyn FnMut(&T)) + Send + Sync>;
42
43/// Creates a publisher and a source that share `initial` as their root value.
44pub fn channel<S>(initial: S) -> (LivePublisher<S>, LiveSource<S>)
45where
46    S: Send + Sync + 'static,
47{
48    let cell = Arc::new(ArcSwap::from_pointee(initial));
49    let (tick, tick_rx) = watch::channel(());
50    let publisher = LivePublisher {
51        cell: Arc::clone(&cell),
52        tick,
53    };
54    (publisher, LiveSource { cell, tick: tick_rx })
55}
56
57/// The handle that replaces a channel's root value.
58///
59/// Each channel has one publisher: it isn't `Clone`, and publishing takes `&mut self`. Dropping it closes the channel.
60/// Neither of these compiles:
61///
62/// ```compile_fail,E0599
63/// let (publisher, _source) = saluki_common::sync::live::channel(0_u32);
64/// let _second = publisher.clone();
65/// ```
66///
67/// ```compile_fail,E0596
68/// fn publish(publisher: &saluki_common::sync::live::LivePublisher<u32>) {
69///     publisher.publish(1);
70/// }
71/// ```
72pub struct LivePublisher<S> {
73    cell: Arc<ArcSwap<S>>,
74    tick: watch::Sender<()>,
75}
76
77impl<S> LivePublisher<S> {
78    /// Replaces the root value with `next` and notifies the views.
79    ///
80    /// This method does not validate `next`. New views read the current root; existing views refresh through
81    /// [`Live::changed`]. A later publication can replace `next` before a view reads it.
82    ///
83    /// # Panics
84    ///
85    /// If this releases the last reference to the previous root, a panic in its destructor propagates. The views are
86    /// notified of `next` first.
87    pub fn publish(&mut self, next: S) {
88        let next = Arc::new(next);
89        // Not `ArcSwap::store`: it drops the previous root, whose destructor could panic before the notification.
90        let previous = self.cell.swap(next);
91        self.tick.send_replace(());
92        drop(previous);
93    }
94}
95
96/// A read-only handle to a channel's root value, used to load it and to create views of it.
97///
98/// A source doesn't keep the channel open. After the publisher drops, it still reads the final root.
99pub struct LiveSource<S> {
100    cell: Arc<ArcSwap<S>>,
101
102    // Never polled: each new view takes a clone.
103    tick: watch::Receiver<()>,
104}
105
106impl<S> LiveSource<S> {
107    /// Returns an `Arc` holding the current root value.
108    ///
109    /// It keeps this version alive across later publications, even after the channel's handles are dropped.
110    pub fn load(&self) -> Arc<S> {
111        self.cell.load_full()
112    }
113}
114
115impl<S> LiveSource<S>
116where
117    S: Send + Sync + 'static,
118{
119    /// Creates a view of the value selected by `project`, starting from the current root.
120    ///
121    /// `project` borrows part of the root; the view clones that selected value into its snapshot. The view retains access
122    /// to the source and can outlive this handle.
123    pub fn live<T>(&self, project: impl for<'a> Fn(&'a S) -> &'a T + Send + Sync + 'static) -> Live<T>
124    where
125        T: Clone + PartialEq + 'static,
126    {
127        // Mark before reading the snapshot, so a concurrent publish is either in the snapshot or still unseen.
128        let mut tick = self.tick.clone();
129        tick.mark_unchanged();
130
131        let cell = Arc::clone(&self.cell);
132        let source: Source<T> = Arc::new(move |f: &mut dyn FnMut(&T)| {
133            let guard = cell.load();
134            f(project(&guard));
135        });
136        Live::from_source(source, tick)
137    }
138}
139
140impl<S> Clone for LiveSource<S> {
141    fn clone(&self) -> Self {
142        Self {
143            cell: Arc::clone(&self.cell),
144            tick: self.tick.clone(),
145        }
146    }
147}
148
149/// A typed view of one projection of a shared value.
150///
151/// Consumers use the same API for fixed values and for dynamic views created by [`LiveSource::live`]. `Deref` returns
152/// this view's cached snapshot, not a fresh source read. Only [`changed`](Self::changed) refreshes the snapshot; source
153/// updates alone do not.
154///
155/// Cloning copies the snapshot and the record of which notifications this view has processed. Each view then
156/// processes updates independently.
157pub struct Live<T> {
158    inner: Inner<T>,
159}
160
161enum Inner<T> {
162    Fixed(T),
163    Dynamic {
164        source: Source<T>,
165
166        // Notifications carry no value and may include changes outside this view's projection.
167        tick: watch::Receiver<()>,
168
169        snapshot: T,
170    },
171}
172
173impl<T: Clone + PartialEq + 'static> Live<T> {
174    fn from_source(source: Source<T>, tick: watch::Receiver<()>) -> Self {
175        let mut snapshot = None;
176        source(&mut |value| snapshot = Some(value.clone()));
177        let snapshot = snapshot.expect("a source always passes its current value to the callback");
178        Self {
179            inner: Inner::Dynamic { source, tick, snapshot },
180        }
181    }
182
183    /// Creates a view with a value that never changes.
184    pub fn new_fixed(value: T) -> Self {
185        Self {
186            inner: Inner::Fixed(value),
187        }
188    }
189
190    /// Returns `true` if this view's value never changes.
191    ///
192    /// A fixed view never yields from [`changed`](Self::changed), so callers can treat its current value as a constant.
193    pub fn is_fixed(&self) -> bool {
194        matches!(self.inner, Inner::Fixed(_))
195    }
196
197    /// Waits until the selected value differs from this view's snapshot, then updates the snapshot and returns it.
198    ///
199    /// Notifications trigger a source read; equal values leave the call pending. The returned value matches the snapshot
200    /// exposed by `Deref`. Several publications can produce one observed change, skipping intermediate values.
201    ///
202    /// Fixed views stay pending forever. When the publisher drops, dynamic views process any unseen notification, then
203    /// stay pending forever. Callers can therefore use `select!` without handling closure.
204    pub async fn changed(&mut self) -> T {
205        match &mut self.inner {
206            Inner::Fixed(_) => std::future::pending::<T>().await,
207            Inner::Dynamic { source, tick, snapshot } => loop {
208                if tick.changed().await.is_err() {
209                    std::future::pending::<()>().await;
210                }
211                let mut changed = false;
212                source(&mut |latest| {
213                    if *latest != *snapshot {
214                        *snapshot = latest.clone();
215                        changed = true;
216                    }
217                });
218                if changed {
219                    return snapshot.clone();
220                }
221            },
222        }
223    }
224
225    /// Converts this view into a stream of its changes.
226    ///
227    /// Each item comes from [`changed`](Self::changed): the stream skips the current snapshot but can yield a change
228    /// pending before conversion. Intermediate values may be skipped. The stream never ends, even for fixed views or
229    /// after the publisher drops.
230    pub fn into_stream(self) -> impl Stream<Item = T> + Send + 'static
231    where
232        T: Send,
233    {
234        stream::unfold(self, |mut live| async move {
235            let value = live.changed().await;
236            Some((value, live))
237        })
238    }
239
240    /// Creates a child view by selecting part of this view's value with `f`.
241    ///
242    /// A dynamic child shares the source, but has its own snapshot and processes notifications independently.
243    /// Its initial snapshot reads the source, not this view's snapshot, so it may be newer. The child can outlive its
244    /// parent. A fixed child is projected once and remains fixed.
245    pub fn project<U>(&self, f: impl for<'a> Fn(&'a T) -> &'a U + Send + Sync + 'static) -> Live<U>
246    where
247        U: Clone + PartialEq + 'static,
248    {
249        match &self.inner {
250            Inner::Fixed(value) => Live::new_fixed(f(value).clone()),
251            Inner::Dynamic { source, tick, .. } => {
252                let parent = Arc::clone(source);
253                let source: Source<U> = Arc::new(move |g: &mut dyn FnMut(&U)| parent(&mut |value| g(f(value))));
254                Live::from_source(source, tick.clone())
255            }
256        }
257    }
258
259    /// Creates a child view by computing an owned value with `f`.
260    ///
261    /// Unlike [`project`](Self::project), `f` returns an owned value rather than a reference. A dynamic child reads the
262    /// source, not this view's cached snapshot, and processes updates independently. It calls `f` when created and
263    /// whenever it or its children read the source. [`changed`](Self::changed) compares mapped values and stays pending
264    /// when they are equal. A fixed child is mapped once and remains fixed.
265    pub fn map<U>(&self, f: impl Fn(&T) -> U + Send + Sync + 'static) -> Live<U>
266    where
267        U: Clone + PartialEq + 'static,
268    {
269        match &self.inner {
270            Inner::Fixed(value) => Live::new_fixed(f(value)),
271            Inner::Dynamic { source, tick, .. } => {
272                let parent = Arc::clone(source);
273                let source: Source<U> = Arc::new(move |g: &mut dyn FnMut(&U)| parent(&mut |value| g(&f(value))));
274                Live::from_source(source, tick.clone())
275            }
276        }
277    }
278}
279
280impl<T> Deref for Live<T> {
281    type Target = T;
282    fn deref(&self) -> &T {
283        match &self.inner {
284            Inner::Fixed(value) => value,
285            Inner::Dynamic { snapshot, .. } => snapshot,
286        }
287    }
288}
289
290impl<T: Clone> Clone for Live<T> {
291    fn clone(&self) -> Self {
292        let inner = match &self.inner {
293            Inner::Fixed(value) => Inner::Fixed(value.clone()),
294            Inner::Dynamic { source, tick, snapshot } => Inner::Dynamic {
295                source: Arc::clone(source),
296                tick: tick.clone(),
297                snapshot: snapshot.clone(),
298            },
299        };
300        Self { inner }
301    }
302}
303
304impl<T: fmt::Debug> fmt::Debug for Live<T> {
305    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
306        match &self.inner {
307            Inner::Fixed(value) => f.debug_tuple("Live::Fixed").field(value).finish(),
308            Inner::Dynamic { snapshot, .. } => f
309                .debug_struct("Live::Dynamic")
310                .field("snapshot", snapshot)
311                .finish_non_exhaustive(),
312        }
313    }
314}
315
316#[cfg(test)]
317mod tests {
318    use std::cell::Cell;
319    use std::panic::{catch_unwind, AssertUnwindSafe};
320    use std::sync::atomic::{AtomicUsize, Ordering};
321    use std::sync::{mpsc, Arc, Barrier};
322    use std::thread;
323    use std::time::Duration;
324
325    use tokio_test::{assert_pending, assert_ready, task::spawn};
326
327    use super::{channel, Live, LivePublisher, LiveSource};
328
329    #[derive(Clone, Debug, Default, PartialEq)]
330    struct Root {
331        selected: Selected,
332        unrelated: u32,
333    }
334
335    #[derive(Clone, Debug, Default, PartialEq)]
336    struct Selected {
337        value: u32,
338        sibling: u32,
339    }
340
341    /// A channel whose tests publish edits of the current root.
342    struct Shared {
343        publisher: LivePublisher<Root>,
344        source: LiveSource<Root>,
345    }
346
347    impl Shared {
348        fn new() -> Self {
349            let (publisher, source) = channel(Root::default());
350            Self { publisher, source }
351        }
352
353        fn update(&mut self, f: impl FnOnce(&mut Root)) {
354            let mut next = Root::clone(&self.source.load());
355            f(&mut next);
356            self.publisher.publish(next);
357        }
358    }
359
360    fn assert_send_sync<S>(_: &S)
361    where
362        S: Send + Sync,
363    {
364    }
365
366    #[test]
367    fn fixed_view_never_changes() {
368        let mut view = Live::new_fixed(true);
369        let mut changed = spawn(view.changed());
370        assert_pending!(changed.poll());
371        drop(changed);
372        assert!(*view);
373    }
374
375    #[test]
376    fn fixed_live_stream_never_yields_or_ends() {
377        let mut values = spawn(Live::new_fixed(true).into_stream());
378        assert_pending!(values.poll_next());
379    }
380
381    #[test]
382    fn fixed_child_holds_the_projected_value_and_never_changes() {
383        let parent = Live::new_fixed(Selected { value: 1, sibling: 2 });
384        let mut child = parent.project(|selected| &selected.sibling);
385        assert_eq!(*child, 2);
386        assert_pending!(spawn(child.changed()).poll());
387    }
388
389    #[test]
390    fn dynamic_view_keeps_its_snapshot_until_changed_processes_the_update() {
391        let mut shared = Shared::new();
392        let mut view = shared.source.live(|root| &root.selected.value);
393
394        shared.update(|root| root.selected.value = 1);
395        assert_eq!(*view, 0);
396
397        assert_eq!(assert_ready!(spawn(view.changed()).poll()), 1);
398        assert_eq!(*view, 1);
399    }
400
401    #[test]
402    fn project_follows_the_selected_child_while_the_parent_snapshot_stays_unchanged() {
403        let mut shared = Shared::new();
404        let parent = shared.source.live(|root| root);
405        let mut child = parent
406            .project(|root| &root.selected)
407            .project(|selected| &selected.value);
408
409        shared.update(|root| root.selected.value = 1);
410
411        assert_eq!(assert_ready!(spawn(child.changed()).poll()), 1);
412        assert_eq!(*child, 1);
413        assert_eq!(*parent, Root::default());
414    }
415
416    #[test]
417    fn project_reads_the_source_for_the_child_initial_snapshot() {
418        let mut shared = Shared::new();
419        let parent = shared.source.live(|root| &root.selected);
420
421        shared.update(|root| root.selected.value = 1);
422        let child = parent.project(|selected| &selected.value);
423
424        assert_eq!(*child, 1);
425        assert_eq!(parent.value, 0);
426    }
427
428    #[test]
429    fn projected_view_ignores_unrelated_and_unchanged_values() {
430        let mut shared = Shared::new();
431        let mut child = shared
432            .source
433            .live(|root| &root.selected)
434            .project(|selected| &selected.value);
435        let mut changed = spawn(child.changed());
436        assert_pending!(changed.poll());
437
438        shared.update(|root| root.unrelated = 1);
439        assert!(changed.is_woken());
440        assert_pending!(changed.poll());
441
442        shared.update(|root| root.selected.sibling = 1);
443        assert!(changed.is_woken());
444        assert_pending!(changed.poll());
445
446        shared.update(|root| root.selected.value = 0);
447        assert!(changed.is_woken());
448        assert_pending!(changed.poll());
449
450        shared.update(|root| root.selected.value = 2);
451        assert_eq!(assert_ready!(changed.poll()), 2);
452    }
453
454    #[test]
455    fn projected_stream_ignores_unrelated_and_unchanged_values() {
456        let mut shared = Shared::new();
457        let child = shared
458            .source
459            .live(|root| &root.selected)
460            .project(|selected| &selected.value);
461        let mut values = spawn(child.into_stream());
462
463        shared.update(|root| root.unrelated = 1);
464        assert_pending!(values.poll_next());
465
466        shared.update(|root| root.selected.value = 0);
467        assert!(values.is_woken());
468        assert_pending!(values.poll_next());
469
470        shared.update(|root| root.selected.value = 3);
471        assert_eq!(assert_ready!(values.poll_next()), Some(3));
472        assert_pending!(values.poll_next());
473    }
474
475    #[test]
476    fn stream_starts_with_the_next_change_not_the_current_snapshot() {
477        let mut shared = Shared::new();
478        shared.update(|root| root.selected.value = 1);
479        let mut values = spawn(shared.source.live(|root| &root.selected.value).into_stream());
480
481        assert_pending!(values.poll_next());
482
483        shared.update(|root| root.selected.value = 2);
484        assert_eq!(assert_ready!(values.poll_next()), Some(2));
485    }
486
487    #[test]
488    fn stream_yields_an_update_pending_before_conversion() {
489        let mut shared = Shared::new();
490        let view = shared.source.live(|root| &root.selected.value);
491
492        shared.update(|root| root.selected.value = 1);
493        let mut values = spawn(view.into_stream());
494
495        assert_eq!(assert_ready!(values.poll_next()), Some(1));
496        assert_pending!(values.poll_next());
497    }
498
499    #[test]
500    fn stream_coalesces_unprocessed_updates_to_the_latest_value() {
501        let mut shared = Shared::new();
502        let mut values = spawn(shared.source.live(|root| &root.selected.value).into_stream());
503
504        shared.update(|root| root.selected.value = 1);
505        shared.update(|root| root.selected.value = 2);
506
507        assert_eq!(assert_ready!(values.poll_next()), Some(2));
508        assert_pending!(values.poll_next());
509    }
510
511    #[test]
512    fn fixed_map_maps_once_and_never_changes() {
513        let calls = Arc::new(AtomicUsize::new(0));
514        let counter = Arc::clone(&calls);
515        let parent = Live::new_fixed(Selected { value: 1, sibling: 2 });
516        let mut child = parent.map(move |selected| {
517            counter.fetch_add(1, Ordering::Relaxed);
518            selected.value + selected.sibling
519        });
520
521        assert_eq!(*child, 3);
522        assert_pending!(spawn(child.changed()).poll());
523        let _ = child.clone();
524        assert_eq!(calls.load(Ordering::Relaxed), 1);
525    }
526
527    #[test]
528    fn mapped_view_ignores_changes_outside_the_map_and_equal_mapped_values() {
529        let mut shared = Shared::new();
530        let mut child = shared
531            .source
532            .live(|root| &root.selected)
533            .map(|selected| selected.value % 2 == 1);
534        assert!(!*child);
535        let mut changed = spawn(child.changed());
536        assert_pending!(changed.poll());
537
538        shared.update(|root| root.unrelated = 1);
539        assert!(changed.is_woken());
540        assert_pending!(changed.poll());
541
542        shared.update(|root| root.selected.value = 2);
543        assert!(changed.is_woken());
544        assert_pending!(changed.poll());
545
546        shared.update(|root| root.selected.value = 3);
547        assert!(assert_ready!(changed.poll()));
548        drop(changed);
549        assert!(*child);
550    }
551
552    #[test]
553    fn map_composes_with_project_in_both_orders() {
554        let mut shared = Shared::new();
555        let parent = shared.source.live(|root| root);
556        let mut project_then_map = parent
557            .project(|root| &root.selected)
558            .map(|selected| selected.value * 10);
559        let mut map_then_project = parent
560            .map(|root| root.selected.clone())
561            .project(|selected| &selected.value);
562
563        shared.update(|root| root.selected.sibling = 1);
564        assert_pending!(spawn(project_then_map.changed()).poll());
565        assert_pending!(spawn(map_then_project.changed()).poll());
566
567        shared.update(|root| root.selected.value = 2);
568        assert_eq!(assert_ready!(spawn(project_then_map.changed()).poll()), 20);
569        assert_eq!(assert_ready!(spawn(map_then_project.changed()).poll()), 2);
570        assert_eq!(*parent, Root::default());
571    }
572
573    #[test]
574    fn map_reads_the_source_for_the_child_initial_snapshot() {
575        let mut shared = Shared::new();
576        let parent = shared.source.live(|root| &root.selected);
577
578        shared.update(|root| root.selected.value = 1);
579        let child = parent.map(|selected| selected.value + 1);
580
581        assert_eq!(*child, 2);
582        assert_eq!(parent.value, 0);
583    }
584
585    #[test]
586    fn mapped_stream_suppresses_equal_mapped_values_and_yields_changes() {
587        let mut shared = Shared::new();
588        let child = shared.source.live(|root| &root.selected.value).map(|value| *value / 10);
589        let mut values = spawn(child.into_stream());
590        assert_pending!(values.poll_next());
591
592        shared.update(|root| root.selected.value = 9);
593        assert!(values.is_woken());
594        assert_pending!(values.poll_next());
595
596        shared.update(|root| root.selected.value = 15);
597        assert_eq!(assert_ready!(values.poll_next()), Some(1));
598        assert_pending!(values.poll_next());
599    }
600
601    #[test]
602    fn mapped_clones_have_their_own_snapshot_and_notification_cursor() {
603        let mut shared = Shared::new();
604        let mut original = shared.source.live(|root| &root.selected.value).map(|value| *value + 1);
605        let mut clone = original.clone();
606
607        shared.update(|root| root.selected.value = 1);
608        assert_eq!(assert_ready!(spawn(original.changed()).poll()), 2);
609        assert_eq!(*clone, 1);
610
611        assert_eq!(assert_ready!(spawn(clone.changed()).poll()), 2);
612        assert_pending!(spawn(original.changed()).poll());
613    }
614
615    #[test]
616    fn dynamic_view_and_stream_park_after_the_publisher_drops() {
617        let shared = Shared::new();
618        let mut view = shared.source.live(|root| &root.selected.value);
619        let mut values = spawn(shared.source.live(|root| &root.selected.value).into_stream());
620        drop(shared);
621
622        assert_pending!(spawn(view.changed()).poll());
623        assert_pending!(values.poll_next());
624        assert_eq!(*view, 0);
625    }
626
627    #[test]
628    fn clone_has_its_own_snapshot_and_notification_cursor() {
629        let mut shared = Shared::new();
630        let mut original = shared.source.live(|root| &root.selected.value);
631        let mut clone = original.clone();
632
633        shared.update(|root| root.selected.value = 1);
634        assert_eq!(assert_ready!(spawn(original.changed()).poll()), 1);
635        assert_eq!(*clone, 0);
636
637        assert_eq!(assert_ready!(spawn(clone.changed()).poll()), 1);
638        assert_pending!(spawn(original.changed()).poll());
639    }
640
641    #[test]
642    fn debug_shows_the_kind_and_value() {
643        let shared = Shared::new();
644        assert_eq!(format!("{:?}", Live::new_fixed(1)), "Live::Fixed(1)");
645        assert_eq!(
646            format!("{:?}", shared.source.live(|root| &root.selected.value)),
647            "Live::Dynamic { snapshot: 0, .. }"
648        );
649    }
650
651    #[test]
652    fn stream_is_send_and_static_for_a_send_value_that_is_not_sync() {
653        fn assert_send_static<S>(_: &S)
654        where
655            S: Send + 'static,
656        {
657        }
658
659        assert_send_static(&Live::new_fixed(Cell::new(1)).into_stream());
660    }
661
662    #[test]
663    fn source_clones_and_publishes_a_root_that_is_neither_clone_nor_partial_eq() {
664        struct Opaque {
665            value: u32,
666        }
667
668        let (mut publisher, source) = channel(Opaque { value: 0 });
669        let clone = source.clone();
670        assert_send_sync(&clone);
671        let mut view = clone.live(|root| &root.value);
672
673        publisher.publish(Opaque { value: 1 });
674
675        assert_eq!(source.load().value, 1);
676        assert_eq!(assert_ready!(spawn(view.changed()).poll()), 1);
677    }
678
679    #[test]
680    fn publishing_without_views_or_receivers_replaces_the_root() {
681        let mut shared = Shared::new();
682        shared.update(|root| root.selected.value = 1);
683        assert_eq!(shared.source.load().selected.value, 1);
684        assert_eq!(*shared.source.live(|root| &root.selected.value), 1);
685
686        // With no source left, the channel has no receivers.
687        let Shared { mut publisher, source } = shared;
688        drop(source);
689        publisher.publish(Root::default());
690    }
691
692    #[test]
693    fn a_view_created_after_a_publish_starts_from_it_without_reprocessing_its_notification() {
694        let mut shared = Shared::new();
695        shared.update(|root| root.selected.value = 1);
696
697        let reads = Arc::new(AtomicUsize::new(0));
698        let counter = Arc::clone(&reads);
699        let mut view = shared.source.live(move |root| {
700            counter.fetch_add(1, Ordering::Relaxed);
701            &root.selected.value
702        });
703        assert_eq!(*view, 1);
704
705        let mut changed = spawn(view.changed());
706        assert_pending!(changed.poll());
707        assert_eq!(
708            reads.load(Ordering::Relaxed),
709            1,
710            "only the initial snapshot reads the source"
711        );
712
713        shared.update(|root| root.selected.value = 2);
714        assert_eq!(assert_ready!(changed.poll()), 2);
715    }
716
717    #[test]
718    fn a_publication_during_view_creation_remains_unseen_by_the_new_view() {
719        let (mut publisher, source) = channel(0_u32);
720        let (loaded_tx, loaded_rx) = mpsc::channel();
721        let finish_projection = Arc::new(Barrier::new(2));
722        let release = Arc::clone(&finish_projection);
723        let creating = thread::spawn(move || {
724            source.live(move |value| {
725                if *value == 0 {
726                    // Hold the initial root while another thread publishes its replacement.
727                    loaded_tx.send(()).unwrap();
728                    release.wait();
729                }
730                value
731            })
732        });
733
734        loaded_rx.recv_timeout(Duration::from_secs(5)).unwrap();
735        publisher.publish(1);
736        finish_projection.wait();
737        let mut view = creating.join().unwrap();
738
739        assert_eq!(*view, 0);
740        assert_eq!(assert_ready!(spawn(view.changed()).poll()), 1);
741    }
742
743    #[test]
744    fn a_panicking_old_root_destructor_runs_after_the_new_root_is_notified() {
745        struct PanicsOnDrop {
746            value: u32,
747            panics: bool,
748        }
749
750        impl Drop for PanicsOnDrop {
751            fn drop(&mut self) {
752                if self.panics {
753                    panic!("old root destructor");
754                }
755            }
756        }
757
758        let (mut publisher, source) = channel(PanicsOnDrop { value: 0, panics: true });
759        let mut view = source.live(|root| &root.value);
760
761        let published = catch_unwind(AssertUnwindSafe(|| {
762            publisher.publish(PanicsOnDrop {
763                value: 1,
764                panics: false,
765            })
766        }));
767
768        assert!(published.is_err(), "publishing drops the old root");
769        assert_eq!(assert_ready!(spawn(view.changed()).poll()), 1);
770        assert_eq!(source.load().value, 1);
771    }
772
773    #[test]
774    fn after_the_publisher_drops_views_process_an_unseen_update_then_stay_pending() {
775        let mut shared = Shared::new();
776        let mut view = shared.source.live(|root| &root.selected.value);
777        let mut values = spawn(shared.source.live(|root| &root.selected.value).into_stream());
778        shared.update(|root| root.selected.value = 1);
779        let Shared { publisher, source } = shared;
780        drop(publisher);
781
782        assert_eq!(assert_ready!(spawn(view.changed()).poll()), 1);
783        assert_pending!(spawn(view.changed()).poll());
784        assert_eq!(assert_ready!(values.poll_next()), Some(1));
785        assert_pending!(values.poll_next());
786
787        let mut late = source.live(|root| &root.selected.value);
788        assert_eq!(*late, 1);
789        assert_pending!(spawn(late.changed()).poll());
790        assert_eq!(source.load().selected.value, 1);
791    }
792
793    #[test]
794    fn mapped_view_is_send_and_sync() {
795        let shared = Shared::new();
796        assert_send_sync(&shared.source.live(|root| &root.selected).map(|selected| selected.value));
797    }
798}