nami-core 0.4.0

A powerful, lightweight reactive framework.
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
//! # Watcher Management
//!
//! This module provides the infrastructure for managing reactive value watchers,
//! including metadata handling and notification systems.
//!
//! # When watcher would be called?
//!
//! > Watchers are called when the value may have changed.
//!
//! This means that even if the new value is equal to the old value, watchers may will still be called.
//!
//! # Why not only when value actually changed?
//!
//! Since we does not require `Eq` or `PartialEq` bounds on the watched values, so we cannot determine
//! whether the value actually changed or not.
//!
//! # So if upstream user calls `notify`, my watcher will always be called?
//!
//! The answer is: Maybe yes, maybe no.
//!
//! We preserve the freedom to discard notifications in certain scenarios, as a performance optimization.
//!
//! Also, you can use `nami::SignalExt::distinct` to create a distinct signal that only notifies when the value changes manually.

use alloc::{boxed::Box, collections::BTreeMap, rc::Rc, vec::Vec};
use core::{
    any::{Any, TypeId, type_name},
    cell::RefCell,
    fmt::Debug,
    num::NonZeroUsize,
};

use crate::observe::{self, Origin};

/// A type-erased container for metadata that can be associated with computation results.
///
/// `Metadata` allows attaching arbitrary typed information to computation results
/// and passing it through the computation pipeline.
#[derive(Debug, Default, Clone)]
pub struct Metadata(Box<MetadataInner>);

/// Internal implementation of the metadata storage system.
///
/// Uses a `BTreeMap` with `TypeId` as keys to store type-erased values.
#[derive(Debug, Default, Clone)]
struct MetadataInner(BTreeMap<TypeId, Rc<dyn Any>>);

impl MetadataInner {
    /// Attempts to retrieve a value of type `T` from the metadata store.
    ///
    /// Returns `None` if no value of the requested type is present.
    pub fn try_get<T: 'static + Clone>(&self) -> Option<T> {
        // Once `downcast_ref_unchecked` stabilized, we will use it here.
        self.0
            .get(&TypeId::of::<T>())
            .and_then(|value| value.downcast_ref::<T>())
            .cloned()
    }

    /// Inserts a value of type `T` into the metadata store.
    ///
    /// If a value of the same type already exists, it will be replaced.
    pub fn insert<T: 'static + Clone>(&mut self, value: T) {
        // Value are always cheap to clone, for example, `Animation` may only within one machine word.
        // However, we must erase the type, so we must make a choice between `Rc` and `Box`.
        // Here we choose `Rc` to allow cheap cloning when retrieving the value.
        self.0.insert(TypeId::of::<T>(), Rc::new(value));
    }
}

/// Type alias for a reference-counted watcher function.
pub type Watcher<T> = Rc<dyn Fn(Context<T>) + 'static>;

/// Context passed to watchers containing the value and associated metadata.
#[derive(Debug, Clone)]
pub struct Context<T> {
    /// The current value being watched.
    value: T,
    /// Associated metadata for this value change.
    metadata: Metadata,
}

impl<T> Context<T> {
    /// Creates a new context with the given value and metadata.
    pub const fn new(value: T, metadata: Metadata) -> Self {
        Self { value, metadata }
    }

    /// Adds additional metadata to this context.
    #[must_use]
    pub fn with<V: Clone + 'static>(mut self, value: V) -> Self {
        self.metadata = self.metadata.with(value);
        self
    }

    /// Consumes the context and returns the inner value.
    pub fn into_value(self) -> T {
        self.value
    }

    /// Returns a reference to the inner value.
    pub const fn value(&self) -> &T {
        &self.value
    }

    /// Returns a mutable reference to the inner value.
    pub const fn value_mut(&mut self) -> &mut T {
        &mut self.value
    }

    /// Returns a reference to the metadata.
    pub const fn metadata(&self) -> &Metadata {
        &self.metadata
    }

    /// Returns a mutable reference to the metadata.
    pub const fn metadata_mut(&mut self) -> &mut Metadata {
        &mut self.metadata
    }

    /// Maps the inner value to a new value.
    pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Context<U> {
        Context::new(f(self.value), self.metadata)
    }

    /// Returns a new context with a reference to the inner value.
    pub fn as_ref(&self) -> Context<&T> {
        Context::new(&self.value, self.metadata.clone())
    }

    /// Returns a new context with a mutable reference to the inner value.
    pub fn as_mut(&mut self) -> Context<&mut T> {
        Context::new(&mut self.value, self.metadata.clone())
    }

    /// Returns a new context with a reference to the dereferenced inner value.
    pub fn as_deref(&self) -> Context<&T::Target>
    where
        T: core::ops::Deref,
    {
        Context::new(&*self.value, self.metadata.clone())
    }

    /// Returns a new context with a mutable reference to the dereferenced inner value.
    pub fn as_deref_mut(&mut self) -> Context<&mut T::Target>
    where
        T: core::ops::DerefMut,
    {
        Context::new(&mut *self.value, self.metadata.clone())
    }
}

impl<T> From<T> for Context<T> {
    fn from(value: T) -> Self {
        Self::new(value, Metadata::new())
    }
}

/// A guard that ensures proper cleanup of watchers when dropped.
#[must_use]
pub trait WatcherGuard: 'static {}

impl<T: 'static> WatcherGuard for Option<T> {}

impl<T: WatcherGuard, E: WatcherGuard> WatcherGuard for Result<T, E> {}

impl WatcherGuard for () {}

impl<T1: WatcherGuard, T2: WatcherGuard> WatcherGuard for (T1, T2) {}

/// A utility struct that runs a cleanup function when dropped.
#[derive(Debug)]
pub struct OnDrop<F>(Option<F>)
where
    F: FnOnce();

impl<F> OnDrop<F>
where
    F: FnOnce() + 'static,
{
    /// Creates a new `OnDrop` that will call the function when dropped.
    pub const fn new(f: F) -> Self {
        Self(Some(f))
    }

    /// Attaches a cleanup function to a guard.
    ///
    /// `drop` (not `let _ =`) moves `guard` into the closure: a `move`
    /// closure whose body only does `let _ = guard` captures nothing,
    /// because disjoint closure captures (edition 2021) see no use of
    /// `guard` — it would stay owned by the caller and die when `attach`
    /// returns.
    #[allow(clippy::needless_pass_by_value)]
    pub fn attach(guard: impl WatcherGuard, f: F) -> impl WatcherGuard {
        OnDrop::new(move || {
            drop(guard);
            f();
        })
    }
}

impl<F> Drop for OnDrop<F>
where
    F: FnOnce(),
{
    fn drop(&mut self) {
        let Some(callback) = self.0.take() else {
            panic!("OnDrop::drop called with missing callback");
        };
        callback();
    }
}

/// Type alias for a boxed watcher guard.
pub type BoxWatcherGuard = Box<dyn WatcherGuard>;

impl<T: WatcherGuard + ?Sized> WatcherGuard for Box<T> {}
impl<T: WatcherGuard + ?Sized> WatcherGuard for Rc<T> {}

impl<F: FnOnce() + 'static> WatcherGuard for OnDrop<F> {}

impl Metadata {
    /// Creates a new, empty metadata container.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Gets a value of type `T` from the metadata.
    ///
    /// # Panics
    ///
    /// Panics if no value of type `T` is present in the metadata.
    #[must_use]
    pub fn get<T: 'static + Clone>(&self) -> T {
        self.try_get()
            .unwrap_or_else(|| panic!("Metadata::get missing value for requested type"))
    }

    /// Attempts to get a value of type `T` from the metadata.
    ///
    /// Returns `None` if no value of the requested type is present.
    #[must_use]
    pub fn try_get<T: 'static + Clone>(&self) -> Option<T> {
        self.0.try_get()
    }

    /// Adds a value to the metadata and returns the updated metadata.
    ///
    /// This method is chainable for fluent API usage.
    #[must_use]
    pub fn with<T: 'static + Clone>(mut self, value: T) -> Self {
        self.0.insert(value);
        self
    }

    /// Checks if the metadata container is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.0.is_empty()
    }
}

/// A unique identifier for registered watchers.
pub(crate) type WatcherId = NonZeroUsize;

/// Manages a collection of watchers for a specific computation type.
///
/// Provides functionality to register, notify, and cancel watchers.
#[derive(Debug)]
pub struct WatcherManager<T> {
    inner: Rc<RefCell<WatcherManagerInner<T>>>,
}

impl<T> Clone for WatcherManager<T> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
        }
    }
}

impl<T> Default for WatcherManager<T> {
    fn default() -> Self {
        Self {
            inner: Rc::default(),
        }
    }
}

impl<T: 'static> WatcherManager<T> {
    /// Creates a new, empty watcher manager with no provenance.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a watcher manager attributed to a state-owning signal node.
    ///
    /// State owners should use this rather than [`Self::new`] so development
    /// tooling can attribute subscriptions and notifications to the node and to
    /// the source location that created it. [`Origin`] is zero-sized unless the
    /// `observability` feature is enabled.
    #[must_use]
    pub fn with_origin(origin: Origin) -> Self {
        observe::on_create(origin);
        Self {
            inner: Rc::new(RefCell::new(WatcherManagerInner::with_origin(origin))),
        }
    }

    /// Checks if the manager has any registered watchers.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.inner.borrow().is_empty()
    }

    /// Registers a new watcher and returns its unique identifier.
    pub fn register(&self, watcher: impl Fn(Context<T>) + 'static) -> WatcherId {
        let (id, origin, subscribers) = {
            let mut inner = self.inner.borrow_mut();
            let id = inner.register(watcher);
            (id, inner.origin, inner.len())
        };
        observe::on_subscribe(origin, subscribers);
        id
    }

    /// Registers a watcher and returns a guard that will unregister it when dropped.
    pub fn register_as_guard(
        &self,
        watcher: impl Fn(Context<T>) + 'static,
    ) -> WatcherManagerGuard<T> {
        let id = self.register(watcher);
        let this = self.clone();
        WatcherManagerGuard { manager: this, id }
    }

    /// Notifies all registered watchers with a preconstructed context.
    pub fn notify(&self, ctx: &Context<T>)
    where
        T: Clone,
    {
        let (watchers, origin) = {
            let inner = self.inner.borrow();
            (inner.watchers_snapshot(), inner.origin)
        };

        if watchers.is_empty() {
            return;
        }

        observe::on_notify(origin, watchers.len());

        for watcher in watchers {
            watcher(ctx.clone());
        }
    }

    /// Cancels a previously registered watcher by its identifier.
    ///
    /// The removed watcher is dropped after the borrow on `inner` is
    /// released, because dropping its closure may re-enter this manager
    /// through a `WatcherManagerGuard` it owns.
    pub fn cancel(&self, id: WatcherId) {
        let (removed, origin, subscribers) = {
            let mut inner = self.inner.borrow_mut();
            let removed = inner.cancel(id);
            (removed, inner.origin, inner.len())
        };
        observe::on_unsubscribe(origin, subscribers);
        drop(removed);
    }
}

/// A guard that ensures a watcher is unregistered when dropped.
#[must_use]
#[derive(Debug)]
pub struct WatcherManagerGuard<T: 'static> {
    manager: WatcherManager<T>,
    id: WatcherId,
}

impl<T> WatcherGuard for WatcherManagerGuard<T> {}

impl<T: 'static> Drop for WatcherManagerGuard<T> {
    fn drop(&mut self) {
        self.manager.cancel(self.id);
    }
}

/// Internal implementation of the watcher manager.
///
/// Maintains the collection of watchers and handles identifier assignment.
struct WatcherManagerInner<T> {
    id: WatcherId,
    map: BTreeMap<WatcherId, Watcher<T>>,
    origin: Origin,
}

impl<T> Debug for WatcherManagerInner<T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(type_name::<Self>())
    }
}

impl<T> Default for WatcherManagerInner<T> {
    fn default() -> Self {
        Self {
            id: WatcherId::MIN,
            map: BTreeMap::new(),
            origin: Origin::unattributed(),
        }
    }
}

impl<T> Drop for WatcherManagerInner<T> {
    fn drop(&mut self) {
        observe::on_drop(self.origin);
    }
}

impl<T: 'static> WatcherManagerInner<T> {
    /// Creates an inner manager attributed to a signal node.
    fn with_origin(origin: Origin) -> Self {
        Self {
            id: WatcherId::MIN,
            map: BTreeMap::new(),
            origin,
        }
    }

    /// Checks if there are any registered watchers.
    pub fn is_empty(&self) -> bool {
        self.map.is_empty()
    }

    /// Number of currently registered watchers.
    fn len(&self) -> usize {
        self.map.len()
    }

    /// Assigns a new unique identifier for a watcher.
    const fn assign(&mut self) -> WatcherId {
        let id = self.id;
        self.id = match self.id.checked_add(1) {
            Some(id) => id,
            None => panic!("`id` grows beyond `usize::MAX`"),
        };
        id
    }

    /// Registers a watcher and returns its unique identifier.
    pub fn register(&mut self, watcher: impl Fn(Context<T>) + 'static) -> WatcherId {
        let id = self.assign();
        self.map.insert(id, Rc::new(watcher));
        id
    }

    /// Creates a snapshot of the current watchers for notification.
    fn watchers_snapshot(&self) -> Vec<Watcher<T>> {
        self.map.values().cloned().collect()
    }

    /// Cancels a watcher registration by its identifier.
    ///
    /// The removed watcher is handed back to the caller, which drops it only
    /// after the `RefCell` borrow on the manager has been released.
    pub fn cancel(&mut self, id: WatcherId) -> Option<Watcher<T>> {
        self.map.remove(&id)
    }
}

#[cfg(test)]
mod tests {
    use alloc::rc::Rc;
    use core::cell::Cell;

    use super::{Context, OnDrop, WatcherGuard, WatcherManager};

    /// A watcher whose closure owns a `WatcherManagerGuard` on the same
    /// manager re-enters `cancel` from the guard's `Drop` when the watcher is
    /// dropped, so removal must not run that destructor while `inner` is
    /// still borrowed.
    #[test]
    fn cancel_drops_removed_watcher_after_releasing_borrow() {
        let manager = WatcherManager::<i32>::new();
        let nested = manager.register_as_guard(|_| ());
        let owner = manager.register(move |_: Context<i32>| {
            let _owns_nested_guard = &nested;
        });
        manager.cancel(owner);
        assert!(manager.is_empty());
    }

    /// A `move` closure that only did `let _ = guard` would capture nothing
    /// under edition 2021's disjoint captures, so `attach` returned a guard
    /// whose payload had already died. `attach` must hold `guard` until the
    /// returned `OnDrop` itself drops (water-rs/hydrolysis#228).
    #[test]
    fn attach_holds_the_guard_until_the_result_drops() {
        struct Probe(Rc<Cell<bool>>);
        impl WatcherGuard for Probe {}
        impl Drop for Probe {
            fn drop(&mut self) {
                self.0.set(true);
            }
        }

        let dropped = Rc::new(Cell::new(false));
        let attached = OnDrop::attach(Probe(Rc::clone(&dropped)), || ());
        assert!(!dropped.get(), "attach dropped the guard early");
        drop(attached);
        assert!(dropped.get());
    }
}