nami_core/watcher.rs
1//! # Watcher Management
2//!
3//! This module provides the infrastructure for managing reactive value watchers,
4//! including metadata handling and notification systems.
5//!
6//! # When watcher would be called?
7//!
8//! > Watchers are called when the value may have changed.
9//!
10//! This means that even if the new value is equal to the old value, watchers may will still be called.
11//!
12//! # Why not only when value actually changed?
13//!
14//! Since we does not require `Eq` or `PartialEq` bounds on the watched values, so we cannot determine
15//! whether the value actually changed or not.
16//!
17//! # So if upstream user calls `notify`, my watcher will always be called?
18//!
19//! The answer is: Maybe yes, maybe no.
20//!
21//! We preserve the freedom to discard notifications in certain scenarios, as a performance optimization.
22//!
23//! Also, you can use `nami::SignalExt::distinct` to create a distinct signal that only notifies when the value changes manually.
24
25use alloc::{boxed::Box, collections::VecDeque, rc::Rc, vec::Vec};
26use core::{
27 any::{Any, TypeId, type_name},
28 cell::RefCell,
29 fmt::Debug,
30 num::NonZeroUsize,
31};
32
33use crate::observe::{self, Origin};
34
35/// A type-erased container for metadata that can be associated with computation results.
36///
37/// `Metadata` allows attaching arbitrary typed information to computation results
38/// and passing it through the computation pipeline.
39///
40/// It holds at most a handful of entries (typically none, sometimes an
41/// animation), so it is a boxed slice searched linearly: an empty `Metadata`
42/// does not allocate, and cloning an empty one is free.
43#[derive(Debug, Default, Clone)]
44pub struct Metadata(Box<[(TypeId, Rc<dyn Any>)]>);
45
46/// Type alias for a reference-counted watcher function.
47pub type Watcher<T> = Rc<dyn Fn(Context<T>) + 'static>;
48
49/// Context passed to watchers containing the value and associated metadata.
50#[derive(Debug, Clone)]
51pub struct Context<T> {
52 /// The current value being watched.
53 value: T,
54 /// Associated metadata for this value change.
55 metadata: Metadata,
56}
57
58impl<T> Context<T> {
59 /// Creates a new context with the given value and metadata.
60 pub const fn new(value: T, metadata: Metadata) -> Self {
61 Self { value, metadata }
62 }
63
64 /// Adds additional metadata to this context.
65 #[must_use]
66 pub fn with<V: Clone + 'static>(mut self, value: V) -> Self {
67 self.metadata = self.metadata.with(value);
68 self
69 }
70
71 /// Consumes the context and returns the inner value.
72 pub fn into_value(self) -> T {
73 self.value
74 }
75
76 /// Consumes the context and returns the value and the metadata.
77 ///
78 /// Useful to re-wrap a borrow of the value with the same metadata, without
79 /// cloning it: `Context::new(&value[..], metadata)`.
80 pub fn into_parts(self) -> (T, Metadata) {
81 (self.value, self.metadata)
82 }
83
84 /// Returns a reference to the inner value.
85 pub const fn value(&self) -> &T {
86 &self.value
87 }
88
89 /// Returns a mutable reference to the inner value.
90 pub const fn value_mut(&mut self) -> &mut T {
91 &mut self.value
92 }
93
94 /// Returns a reference to the metadata.
95 pub const fn metadata(&self) -> &Metadata {
96 &self.metadata
97 }
98
99 /// Returns a mutable reference to the metadata.
100 pub const fn metadata_mut(&mut self) -> &mut Metadata {
101 &mut self.metadata
102 }
103
104 /// Maps the inner value to a new value.
105 pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Context<U> {
106 Context::new(f(self.value), self.metadata)
107 }
108
109 /// Returns a new context with a reference to the inner value.
110 pub fn as_ref(&self) -> Context<&T> {
111 Context::new(&self.value, self.metadata.clone())
112 }
113
114 /// Returns a new context with a mutable reference to the inner value.
115 pub fn as_mut(&mut self) -> Context<&mut T> {
116 Context::new(&mut self.value, self.metadata.clone())
117 }
118
119 /// Returns a new context with a reference to the dereferenced inner value.
120 pub fn as_deref(&self) -> Context<&T::Target>
121 where
122 T: core::ops::Deref,
123 {
124 Context::new(&*self.value, self.metadata.clone())
125 }
126
127 /// Returns a new context with a mutable reference to the dereferenced inner value.
128 pub fn as_deref_mut(&mut self) -> Context<&mut T::Target>
129 where
130 T: core::ops::DerefMut,
131 {
132 Context::new(&mut *self.value, self.metadata.clone())
133 }
134}
135
136impl<T> From<T> for Context<T> {
137 fn from(value: T) -> Self {
138 Self::new(value, Metadata::new())
139 }
140}
141
142/// A guard that ensures proper cleanup of watchers when dropped.
143#[must_use]
144pub trait WatcherGuard: 'static {}
145
146impl<T: 'static> WatcherGuard for Option<T> {}
147
148impl<T: WatcherGuard, E: WatcherGuard> WatcherGuard for Result<T, E> {}
149
150impl WatcherGuard for () {}
151
152impl<T1: WatcherGuard, T2: WatcherGuard> WatcherGuard for (T1, T2) {}
153
154/// A utility struct that runs a cleanup function when dropped.
155#[derive(Debug)]
156pub struct OnDrop<F>(Option<F>)
157where
158 F: FnOnce();
159
160impl<F> OnDrop<F>
161where
162 F: FnOnce() + 'static,
163{
164 /// Creates a new `OnDrop` that will call the function when dropped.
165 pub const fn new(f: F) -> Self {
166 Self(Some(f))
167 }
168
169 /// Attaches a cleanup function to a guard.
170 ///
171 /// `drop` (not `let _ =`) moves `guard` into the closure: a `move`
172 /// closure whose body only does `let _ = guard` captures nothing,
173 /// because disjoint closure captures (edition 2021) see no use of
174 /// `guard` — it would stay owned by the caller and die when `attach`
175 /// returns.
176 #[allow(clippy::needless_pass_by_value)]
177 pub fn attach(guard: impl WatcherGuard, f: F) -> impl WatcherGuard {
178 OnDrop::new(move || {
179 drop(guard);
180 f();
181 })
182 }
183}
184
185impl<F> Drop for OnDrop<F>
186where
187 F: FnOnce(),
188{
189 fn drop(&mut self) {
190 let Some(callback) = self.0.take() else {
191 panic!("OnDrop::drop called with missing callback");
192 };
193 callback();
194 }
195}
196
197/// Type alias for a boxed watcher guard.
198pub type BoxWatcherGuard = Box<dyn WatcherGuard>;
199
200impl<T: WatcherGuard + ?Sized> WatcherGuard for Box<T> {}
201impl<T: WatcherGuard + ?Sized> WatcherGuard for Rc<T> {}
202
203impl<F: FnOnce() + 'static> WatcherGuard for OnDrop<F> {}
204
205impl Metadata {
206 /// Creates a new, empty metadata container.
207 #[must_use]
208 pub fn new() -> Self {
209 Self::default()
210 }
211
212 /// Gets a value of type `T` from the metadata.
213 ///
214 /// # Panics
215 ///
216 /// Panics if no value of type `T` is present in the metadata.
217 #[must_use]
218 pub fn get<T: 'static + Clone>(&self) -> T {
219 self.try_get()
220 .unwrap_or_else(|| panic!("Metadata::get missing value for requested type"))
221 }
222
223 /// Attempts to get a value of type `T` from the metadata.
224 ///
225 /// Returns `None` if no value of the requested type is present.
226 #[must_use]
227 pub fn try_get<T: 'static + Clone>(&self) -> Option<T> {
228 let id = TypeId::of::<T>();
229 self.0
230 .iter()
231 .find(|(key, _)| *key == id)
232 .and_then(|(_, value)| value.downcast_ref::<T>())
233 .cloned()
234 }
235
236 /// Adds a value to the metadata and returns the updated metadata.
237 ///
238 /// A value of the same type that is already present is replaced.
239 /// This method is chainable for fluent API usage.
240 #[must_use]
241 pub fn with<T: 'static + Clone>(self, value: T) -> Self {
242 // Values are cheap to clone (an `Animation` is a few words), but the
243 // type must be erased; `Rc` keeps retrieval a refcount bump.
244 self.with_erased(TypeId::of::<T>(), Rc::new(value))
245 }
246
247 /// Merges `other` into `self`, returning the union: a value already
248 /// present under the same type is replaced by `other`'s.
249 ///
250 /// Deferred notifications (such as a batched `List` change) compose
251 /// their metadata this way, so the single notification they finally
252 /// send carries what the individual ones would have.
253 #[must_use]
254 pub fn merge(self, other: Self) -> Self {
255 if self.is_empty() {
256 return other;
257 }
258 other
259 .0
260 .into_iter()
261 .fold(self, |merged, (id, value)| merged.with_erased(id, value))
262 }
263
264 /// Stores the erased `value` under `id`, replacing a value already
265 /// present under it.
266 fn with_erased(mut self, id: TypeId, value: Rc<dyn Any>) -> Self {
267 if let Some(slot) = self.0.iter_mut().find(|(key, _)| *key == id) {
268 slot.1 = value;
269 return self;
270 }
271 let mut entries = Vec::from(self.0);
272 entries.push((id, value));
273 self.0 = entries.into_boxed_slice();
274 self
275 }
276
277 /// Checks if the metadata container is empty.
278 #[must_use]
279 pub fn is_empty(&self) -> bool {
280 self.0.is_empty()
281 }
282}
283
284/// A unique identifier for registered watchers.
285pub type WatcherId = NonZeroUsize;
286
287/// The registered callbacks of a [`WatcherRegistry`], in registration order.
288///
289/// Shared copy-on-write: a notification holds one of these while it runs, so
290/// registering or cancelling during a notification rebuilds the list for the
291/// next round instead of changing the one being delivered.
292type Entries<W> = Rc<Vec<(WatcherId, Rc<W>)>>;
293
294/// A copy-on-write list of callbacks, the storage behind every watcher list
295/// in nami.
296///
297/// `W` is the callback type, usually a `dyn Fn(..)`. [`WatcherManager`] is the
298/// registry for `Fn(Context<T>)` watchers; collections use it with their own
299/// callback signature.
300///
301/// Notifying takes a refcount on the current list instead of collecting it,
302/// so the notify path does not allocate. Watchers registered or cancelled
303/// during a notification do not affect that notification, and a notification
304/// raised by a watcher while one is in progress is queued and delivered
305/// afterwards (see [`Self::notify_with`]), so every watcher sees changes in
306/// the order they happened.
307pub struct WatcherRegistry<W: ?Sized> {
308 inner: Rc<RefCell<RegistryInner<W>>>,
309}
310
311impl<W: ?Sized> Debug for WatcherRegistry<W> {
312 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
313 f.write_str(type_name::<Self>())
314 }
315}
316
317impl<W: ?Sized> Clone for WatcherRegistry<W> {
318 fn clone(&self) -> Self {
319 Self {
320 inner: self.inner.clone(),
321 }
322 }
323}
324
325impl<W: ?Sized> Default for WatcherRegistry<W> {
326 fn default() -> Self {
327 Self::with_origin_unobserved(Origin::unattributed())
328 }
329}
330
331impl<W: ?Sized + 'static> WatcherRegistry<W> {
332 /// Creates an empty registry with no provenance.
333 #[must_use]
334 pub fn new() -> Self {
335 Self::default()
336 }
337
338 /// Creates a registry attributed to a state-owning signal node.
339 ///
340 /// State owners should use this rather than [`Self::new`] so development
341 /// tooling can attribute subscriptions and notifications to the node and to
342 /// the source location that created it. [`Origin`] is zero-sized unless the
343 /// `observability` feature is enabled.
344 #[must_use]
345 pub fn with_origin(origin: Origin) -> Self {
346 observe::on_create(origin);
347 Self::with_origin_unobserved(origin)
348 }
349
350 /// Checks if the registry has any registered watchers.
351 #[must_use]
352 pub fn is_empty(&self) -> bool {
353 self.inner.borrow().entries.is_empty()
354 }
355
356 /// Number of currently registered watchers.
357 #[must_use]
358 pub fn len(&self) -> usize {
359 self.inner.borrow().entries.len()
360 }
361
362 /// Adds `watcher` and returns its identifier.
363 pub fn insert(&self, watcher: Rc<W>) -> WatcherId {
364 let (id, origin, subscribers) = {
365 let mut inner = self.inner.borrow_mut();
366 let id = inner.assign();
367 Rc::make_mut(&mut inner.entries).push((id, watcher));
368 (id, inner.origin, inner.entries.len())
369 };
370 observe::on_subscribe(origin, subscribers);
371 id
372 }
373
374 /// Adds `watcher` and returns a guard that removes it when dropped.
375 pub fn insert_as_guard(&self, watcher: Rc<W>) -> RegistryGuard<W> {
376 let id = self.insert(watcher);
377 RegistryGuard {
378 registry: self.clone(),
379 id,
380 }
381 }
382
383 /// Cancels a previously registered watcher by its identifier.
384 ///
385 /// The removed watcher is dropped after the borrow on `inner` is
386 /// released, because dropping its closure may re-enter this registry
387 /// through a guard it owns.
388 pub fn cancel(&self, id: WatcherId) {
389 let (removed, origin, subscribers) = {
390 let mut inner = self.inner.borrow_mut();
391 // Ids are assigned in increasing order and entries are only ever
392 // appended, so the list stays sorted by id.
393 let removed = match inner.entries.binary_search_by_key(&id, |(id, _)| *id) {
394 Ok(position) => Some(Rc::make_mut(&mut inner.entries).remove(position)),
395 Err(_) => None,
396 };
397 (removed, inner.origin, inner.entries.len())
398 };
399 observe::on_unsubscribe(origin, subscribers);
400 drop(removed);
401 }
402
403 /// Calls `call` once per registered watcher with a clone of `value`; the
404 /// last watcher receives `value` itself, so a single watcher costs no
405 /// clone at all.
406 ///
407 /// The watcher list is the one registered when the call starts: watchers
408 /// added or cancelled by a callback take effect from the next delivery.
409 ///
410 /// # Reentrancy
411 ///
412 /// A `notify_with` call that arrives while the same registry is already
413 /// delivering — a watcher notifying the signal it watches — does not
414 /// run a nested round. Its delivery is queued, and the outermost
415 /// `notify_with` drains the queue after its own round finishes: every
416 /// watcher sees the running round's value before the queued one.
417 /// Queued deliveries run in the order they arrived, each to the
418 /// watchers that were registered when it was raised and are still
419 /// registered when it runs: a watcher added meanwhile has already read
420 /// the state the queued notification describes, and one cancelled
421 /// meanwhile must not be called at all. A delivery queued while
422 /// draining joins the same loop, so reentrant notification never
423 /// recurses at any depth.
424 ///
425 /// The queue owns a deferred delivery until its turn, which is why
426 /// `value` and `call` must be `'static`; it allocates only when a
427 /// notification is actually deferred.
428 pub fn notify_with<A: Clone + 'static>(&self, value: A, mut call: impl FnMut(&W, A) + 'static) {
429 let (entries, origin) = {
430 let mut inner = self.inner.borrow_mut();
431 // The snapshot comes first: a mutable borrow of `inner.queue`
432 // would keep all of `inner` borrowed through `DerefMut`.
433 let entries = Rc::clone(&inner.entries);
434 let origin = inner.origin;
435 if let Some(queue) = &mut inner.queue {
436 // A round is in progress: queue this delivery behind it
437 // instead of nesting a second round inside the first. The
438 // recipients are the watchers registered right now, so the
439 // current entries list rides along (a refcount, not a copy).
440 queue.push_back((
441 entries,
442 Box::new(move |watcher| call(watcher, value.clone())),
443 ));
444 return;
445 }
446 inner.queue = Some(VecDeque::new());
447 (entries, origin)
448 };
449 // Takes `queue` back to `None` on any exit — a panicking watcher
450 // included — and drops what is still queued with it, so the registry
451 // is never stuck in "delivering".
452 let _scope = DeliveryScope(&self.inner);
453
454 let Some(((_, last), rest)) = entries.split_last() else {
455 return;
456 };
457 observe::on_notify(origin, entries.len());
458 for (_, watcher) in rest {
459 call(watcher, value.clone());
460 }
461 call(last, value);
462
463 // Deliver what watchers queued, oldest first; deliveries queued
464 // while draining join the same loop. A queued delivery goes to the
465 // watchers registered when it was raised that are still registered
466 // — both lists are sorted by id, so membership is a binary search.
467 loop {
468 let queued = {
469 let mut inner = self.inner.borrow_mut();
470 // `queue` stays `Some` until `_scope` drops.
471 let Some(queue) = inner.queue.as_mut() else {
472 break;
473 };
474 queue.pop_front()
475 };
476 let Some((raised, mut delivery)) = queued else {
477 break;
478 };
479 let (current, origin) = {
480 let inner = self.inner.borrow();
481 (Rc::clone(&inner.entries), inner.origin)
482 };
483 let still_registered =
484 |id: &WatcherId| current.binary_search_by_key(id, |(id, _)| *id).is_ok();
485 let recipients = raised.iter().filter(|(id, _)| still_registered(id)).count();
486 if recipients == 0 {
487 continue;
488 }
489 observe::on_notify(origin, recipients);
490 for (_, watcher) in raised.iter().filter(|(id, _)| still_registered(id)) {
491 delivery(watcher);
492 }
493 }
494 }
495}
496
497impl<W: ?Sized> WatcherRegistry<W> {
498 /// Builds the registry without reporting its creation to observers.
499 fn with_origin_unobserved(origin: Origin) -> Self {
500 Self {
501 inner: Rc::new(RefCell::new(RegistryInner {
502 next: WatcherId::MIN,
503 entries: Rc::new(Vec::new()),
504 origin,
505 queue: None,
506 })),
507 }
508 }
509}
510
511/// A guard that removes a watcher from its [`WatcherRegistry`] when dropped.
512#[must_use]
513pub struct RegistryGuard<W: ?Sized + 'static> {
514 registry: WatcherRegistry<W>,
515 id: WatcherId,
516}
517
518impl<W: ?Sized> Debug for RegistryGuard<W> {
519 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
520 f.debug_struct("RegistryGuard")
521 .field("registry", &self.registry)
522 .field("id", &self.id)
523 .finish()
524 }
525}
526
527impl<W: ?Sized + 'static> WatcherGuard for RegistryGuard<W> {}
528
529impl<W: ?Sized + 'static> Drop for RegistryGuard<W> {
530 fn drop(&mut self) {
531 self.registry.cancel(self.id);
532 }
533}
534
535/// Manages the `Fn(Context<T>)` watchers of a signal.
536pub type WatcherManager<T> = WatcherRegistry<dyn Fn(Context<T>)>;
537
538/// A guard that ensures a watcher is unregistered from its
539/// [`WatcherManager`] when dropped.
540pub type WatcherManagerGuard<T> = RegistryGuard<dyn Fn(Context<T>)>;
541
542impl<T: 'static> WatcherRegistry<dyn Fn(Context<T>)> {
543 /// Registers a new watcher and returns its unique identifier.
544 pub fn register(&self, watcher: impl Fn(Context<T>) + 'static) -> WatcherId {
545 self.insert(Rc::new(watcher))
546 }
547
548 /// Registers a watcher and returns a guard that will unregister it when dropped.
549 pub fn register_as_guard(
550 &self,
551 watcher: impl Fn(Context<T>) + 'static,
552 ) -> WatcherManagerGuard<T> {
553 self.insert_as_guard(Rc::new(watcher))
554 }
555
556 /// Notifies all registered watchers with a clone of `ctx`.
557 ///
558 /// Prefer [`Self::notify_owned`] when the context is not needed
559 /// afterwards: it saves one clone.
560 pub fn notify(&self, ctx: &Context<T>)
561 where
562 T: Clone,
563 {
564 if self.is_empty() {
565 return;
566 }
567 self.notify_owned(ctx.clone());
568 }
569
570 /// Notifies all registered watchers, moving `ctx` into the last one.
571 pub fn notify_owned(&self, ctx: Context<T>)
572 where
573 T: Clone,
574 {
575 self.notify_with(ctx, |watcher, ctx| watcher(ctx));
576 }
577}
578
579/// A notification that arrived while its registry was already delivering.
580/// Owns the value and the caller's `call`, cloning the value for each
581/// watcher it is invoked for.
582type QueuedDelivery<W> = Box<dyn FnMut(&W)>;
583
584/// Internal state of a [`WatcherRegistry`].
585struct RegistryInner<W: ?Sized> {
586 next: WatcherId,
587 entries: Entries<W>,
588 origin: Origin,
589 /// `Some` while a `notify_*` call is delivering: notifications that
590 /// arrive then are appended here and drained once the round in progress
591 /// finishes, oldest first. Each entry keeps the watcher list that was
592 /// registered when the notification was raised (a refcount, not a
593 /// copy). The `VecDeque` allocates on its first push, so a registry
594 /// that is never notified re-entrantly allocates nothing.
595 queue: Option<VecDeque<(Entries<W>, QueuedDelivery<W>)>>,
596}
597
598/// Ends a registry's "delivering" state on drop. A watcher that panics
599/// unwinds through this guard, so the registry is never left stuck; the
600/// still-queued deliveries are dropped along with the state.
601struct DeliveryScope<'a, W: ?Sized>(&'a RefCell<RegistryInner<W>>);
602
603impl<W: ?Sized> Drop for DeliveryScope<'_, W> {
604 fn drop(&mut self) {
605 // A queued delivery can own a guard on this registry; drop them
606 // only after the borrow is released.
607 let queue = self.0.borrow_mut().queue.take();
608 drop(queue);
609 }
610}
611
612impl<W: ?Sized> Drop for RegistryInner<W> {
613 fn drop(&mut self) {
614 observe::on_drop(self.origin);
615 }
616}
617
618impl<W: ?Sized> RegistryInner<W> {
619 /// Assigns a new unique identifier for a watcher.
620 const fn assign(&mut self) -> WatcherId {
621 let id = self.next;
622 self.next = match self.next.checked_add(1) {
623 Some(id) => id,
624 None => panic!("`id` grows beyond `usize::MAX`"),
625 };
626 id
627 }
628}
629
630#[cfg(test)]
631mod tests {
632 use alloc::{rc::Rc, vec, vec::Vec};
633 use core::cell::{Cell, RefCell};
634
635 use super::{Context, OnDrop, WatcherGuard, WatcherManager};
636
637 /// A watcher whose closure owns a `WatcherManagerGuard` on the same
638 /// manager re-enters `cancel` from the guard's `Drop` when the watcher is
639 /// dropped, so removal must not run that destructor while `inner` is
640 /// still borrowed.
641 #[test]
642 fn cancel_drops_removed_watcher_after_releasing_borrow() {
643 let manager = WatcherManager::<i32>::new();
644 let nested = manager.register_as_guard(|_| ());
645 let owner = manager.register(move |_: Context<i32>| {
646 let _owns_nested_guard = &nested;
647 });
648 manager.cancel(owner);
649 assert!(manager.is_empty());
650 }
651
652 /// A `move` closure that only did `let _ = guard` would capture nothing
653 /// under edition 2021's disjoint captures, so `attach` returned a guard
654 /// whose payload had already died. `attach` must hold `guard` until the
655 /// returned `OnDrop` itself drops (water-rs/hydrolysis#228).
656 #[test]
657 fn attach_holds_the_guard_until_the_result_drops() {
658 struct Probe(Rc<Cell<bool>>);
659 impl WatcherGuard for Probe {}
660 impl Drop for Probe {
661 fn drop(&mut self) {
662 self.0.set(true);
663 }
664 }
665
666 let dropped = Rc::new(Cell::new(false));
667 let attached = OnDrop::attach(Probe(Rc::clone(&dropped)), || ());
668 assert!(!dropped.get(), "attach dropped the guard early");
669 drop(attached);
670 assert!(dropped.get());
671 }
672
673 /// A notification raised while a round is delivering is queued and
674 /// drained after it, so every watcher sees the changes in the order
675 /// they were made (water-rs/nami#51).
676 #[test]
677 fn reentrant_notify_is_queued_until_the_round_finishes() {
678 let manager = WatcherManager::<i32>::new();
679 let seen_first = Rc::new(RefCell::new(Vec::new()));
680 let seen_second = Rc::new(RefCell::new(Vec::new()));
681 let fired = Rc::new(Cell::new(false));
682
683 manager.register({
684 let manager = manager.clone();
685 let seen = Rc::clone(&seen_first);
686 let fired = Rc::clone(&fired);
687 move |context: Context<i32>| {
688 let value = context.into_value();
689 seen.borrow_mut().push(value);
690 if value == 1 && !fired.replace(true) {
691 manager.notify_owned(Context::from(2));
692 }
693 }
694 });
695 manager.register({
696 let seen = Rc::clone(&seen_second);
697 move |context: Context<i32>| seen.borrow_mut().push(context.into_value())
698 });
699
700 manager.notify_owned(Context::from(1));
701
702 assert_eq!(*seen_first.borrow(), vec![1, 2]);
703 assert_eq!(*seen_second.borrow(), vec![1, 2]);
704 }
705
706 /// A watcher registered while a round is delivering — but after a
707 /// notification was raised — misses the queued delivery too: by the
708 /// time it registered it could already read the state that notification
709 /// describes.
710 #[test]
711 fn a_watcher_registered_mid_round_misses_queued_deliveries() {
712 let manager = WatcherManager::<i32>::new();
713 let seen_late = Rc::new(RefCell::new(Vec::new()));
714 let done = Rc::new(Cell::new(false));
715
716 manager.register({
717 let manager = manager.clone();
718 let seen_late = Rc::clone(&seen_late);
719 let done = Rc::clone(&done);
720 move |_context: Context<i32>| {
721 if done.replace(true) {
722 return;
723 }
724 // Raised before the late watcher registers: it must not see
725 // this delivery.
726 manager.notify_owned(Context::from(2));
727 manager.register({
728 let seen_late = Rc::clone(&seen_late);
729 move |context: Context<i32>| {
730 seen_late.borrow_mut().push(context.into_value());
731 }
732 });
733 }
734 });
735
736 manager.notify_owned(Context::from(1));
737 assert!(
738 seen_late.borrow().is_empty(),
739 "the late watcher must miss the delivery raised before it registered"
740 );
741
742 manager.notify_owned(Context::from(3));
743 assert_eq!(
744 *seen_late.borrow(),
745 vec![3],
746 "the late watcher takes effect from the next notification"
747 );
748 }
749
750 /// A watcher cancelled by an earlier watcher after a notification was
751 /// raised but before its queued delivery runs does not receive it.
752 #[test]
753 fn a_watcher_cancelled_mid_round_misses_queued_deliveries() {
754 let manager = WatcherManager::<i32>::new();
755 let done = Rc::new(Cell::new(false));
756 let cancelled_id = Rc::new(RefCell::new(None));
757 let seen_cancelled = Rc::new(RefCell::new(Vec::new()));
758 let seen_later = Rc::new(RefCell::new(Vec::new()));
759
760 manager.register({
761 let manager = manager.clone();
762 let done = Rc::clone(&done);
763 let cancelled_id = Rc::clone(&cancelled_id);
764 move |context: Context<i32>| {
765 if *context.value() == 1 && !done.replace(true) {
766 // Raised while the cancelled watcher is still
767 // registered; cancelled before the delivery runs.
768 manager.notify_owned(Context::from(2));
769 if let Some(id) = cancelled_id.borrow_mut().take() {
770 manager.cancel(id);
771 }
772 }
773 }
774 });
775 let second = manager.register({
776 let seen = Rc::clone(&seen_cancelled);
777 move |context: Context<i32>| seen.borrow_mut().push(context.into_value())
778 });
779 *cancelled_id.borrow_mut() = Some(second);
780 manager.register({
781 let seen = Rc::clone(&seen_later);
782 move |context: Context<i32>| seen.borrow_mut().push(context.into_value())
783 });
784
785 manager.notify_owned(Context::from(1));
786
787 assert_eq!(
788 *seen_cancelled.borrow(),
789 vec![1],
790 "round 1's snapshot still reached it; the queued delivery did not"
791 );
792 assert_eq!(*seen_later.borrow(), vec![1, 2]);
793 }
794}