zwire 0.2.0

Zero-dependency, no_std-compatible transactional reactive state engine: scoped push-pull arena, rebaseable optimistic layers + STM drafts, exact incremental Top-K collections, and open @zwire/core wire protocols
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
use alloc::boxed::Box;
use alloc::collections::BTreeMap;
use alloc::rc::Rc;
use alloc::vec::Vec;
use core::cell::{Cell, RefCell};
use core::cmp::Ordering;
use core::marker::PhantomData;
#[path = "reactive_index.rs"]
mod reactive_index;
use reactive_index::Index;

use zwire_collections::{AcceptAll, ItemFilter, TopKViewId};
use zwire_core::internal::{
    alloc_token, batch_depth, create_external_signal, emit_external, is_node_alive,
    propagate_external, remove_flush_hook, schedule_flush_hook, update_external_silent,
};
use zwire_core::{Atom, CleanupFn, Computed, NodeId, Scope};

struct WatchedTopK {
    view_id: TopKViewId,
    signal_id: NodeId,
    watched: Rc<Cell<bool>>,
    dirty_notified: Rc<Cell<bool>>,
}

/// Reactive bridge wrapping [`zwire_collections::Collection`] with [`zwire_core::Scope`].
///
/// Exposes [`Self::top_k_signal`] as a first-class `F_EXTERNAL` reactive [`Computed<Vec<T>>`]
/// with `O(1)` Top-K boundary pruning, batched single-pass materialization via core flush hooks,
/// and STM `Draft` compatibility.
pub struct ReactiveCollection<T, K, IdFn, Cmp, Flt = AcceptAll>
where
    T: Clone + PartialEq + 'static,
    K: Ord + Clone + 'static,
    IdFn: Fn(&T) -> K + 'static,
    Cmp: Fn(&T, &T) -> Ordering + 'static,
    Flt: ItemFilter<T> + 'static,
{
    scope: Scope,
    inner: Rc<Index<T, K>>,
    policy_type: PhantomData<(IdFn, Cmp, Flt)>,
    views: Rc<RefCell<Vec<WatchedTopK>>>,
    cached_top_k: RefCell<BTreeMap<usize, Computed<Vec<T>>>>,
    query_revision: Cell<Option<Atom<u64>>>,
    flush_token: u64,
    flush_scheduled: Rc<Cell<bool>>,
}

impl<T, K, IdFn, Cmp, Flt> core::fmt::Debug for ReactiveCollection<T, K, IdFn, Cmp, Flt>
where
    T: Clone + PartialEq + 'static,
    K: Ord + Clone + 'static,
    IdFn: Fn(&T) -> K + 'static,
    Cmp: Fn(&T, &T) -> Ordering + 'static,
    Flt: ItemFilter<T> + 'static,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let mut s = f.debug_struct("ReactiveCollection");
        if let Ok(inner) = self.inner.data.try_borrow() {
            s.field("len", &inner.len())
                .field("indexed_len", &inner.indexed_len())
                .field("version", &inner.version());
        } else {
            s.field("state", &"<borrowed>");
        }
        s.field("flush_scheduled", &self.flush_scheduled.get())
            .finish_non_exhaustive()
    }
}

impl<T, K, IdFn, Cmp> ReactiveCollection<T, K, IdFn, Cmp, AcceptAll>
where
    T: Clone + PartialEq + 'static,
    K: Ord + Clone + 'static,
    IdFn: Fn(&T) -> K + 'static,
    Cmp: Fn(&T, &T) -> Ordering + 'static,
{
    /// Creates an unfiltered reactive incremental collection bound to `scope`.
    pub fn new(scope: &Scope, get_id: IdFn, compare: Cmp) -> Self {
        Self::from_parts(scope, get_id, compare, AcceptAll)
    }
}

impl<T, K, IdFn, Cmp, Flt> ReactiveCollection<T, K, IdFn, Cmp, Flt>
where
    T: Clone + PartialEq + 'static,
    K: Ord + Clone + 'static,
    IdFn: Fn(&T) -> K + 'static,
    Cmp: Fn(&T, &T) -> Ordering + 'static,
    Flt: Fn(&T) -> bool + 'static,
{
    /// Creates a filtered reactive incremental collection bound to `scope`.
    pub fn with_filter(scope: &Scope, get_id: IdFn, compare: Cmp, filter: Flt) -> Self {
        Self::from_parts(scope, get_id, compare, filter)
    }
}

impl<T, K, IdFn, Cmp, Flt> ReactiveCollection<T, K, IdFn, Cmp, Flt>
where
    T: Clone + PartialEq + 'static,
    K: Ord + Clone + 'static,
    IdFn: Fn(&T) -> K + 'static,
    Cmp: Fn(&T, &T) -> Ordering + 'static,
    Flt: ItemFilter<T> + 'static,
{
    /// Creates a reactive incremental collection with any [`ItemFilter<T>`] implementation.
    pub fn from_parts(scope: &Scope, get_id: IdFn, compare: Cmp, filter: Flt) -> Self {
        let flush_token = alloc_token(scope);
        Self {
            scope: scope.clone(),
            inner: Rc::new(Index::new(get_id, compare, filter)),
            policy_type: PhantomData,
            views: Rc::new(RefCell::new(Vec::new())),
            cached_top_k: RefCell::new(BTreeMap::new()),
            query_revision: Cell::new(None),
            flush_token,
            flush_scheduled: Rc::new(Cell::new(false)),
        }
    }

    /// Total number of stored items.
    #[inline]
    pub fn len(&self) -> usize {
        self.inner.data.borrow().len()
    }

    /// Returns `true` if the collection stores no items.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.inner.data.borrow().is_empty()
    }

    /// Number of items currently passing the filter and present in the sorted block index.
    #[inline]
    pub fn indexed_len(&self) -> usize {
        self.inner.data.borrow().indexed_len()
    }

    /// Clones the stored item for `id`, if present.
    #[inline]
    pub fn get(&self, id: &K) -> Option<T> {
        self.inner.get(id)
    }

    /// Returns `true` if `id` exists in the collection.
    #[inline]
    pub fn contains_key(&self, id: &K) -> bool {
        self.inner.data.borrow().contains_key(id)
    }

    /// Returns a cloned snapshot of the current top `k` indexed items.
    #[inline]
    pub fn get_top_k(&self, k: usize) -> Vec<T> {
        self.inner.window(0, k)
    }

    /// Returns a sorted window, measured after filtering.
    pub fn get_range(&self, offset: usize, limit: usize) -> Vec<T> {
        self.inner.window(offset, limit)
    }

    /// Iterates over a detached snapshot in exact index order.
    pub fn iter_sorted(&self) -> alloc::vec::IntoIter<T> {
        self.get_range(0, usize::MAX).into_iter()
    }

    fn query<R>(&self, read: impl Fn(&Index<T, K>) -> R + 'static) -> Computed<R>
    where
        R: PartialEq + 'static,
    {
        let revision = self.query_revision.get().unwrap_or_else(|| {
            let revision = self.scope.atom(self.inner.data.borrow().version());
            self.query_revision.set(Some(revision));
            revision
        });
        let inner = Rc::clone(&self.inner);
        self.scope.computed(move |cx| {
            let _ = cx.get(revision);
            read(&inner)
        })
    }

    /// Tracks a sorted window and suppresses equal snapshots.
    pub fn range_signal(&self, offset: usize, limit: usize) -> Computed<Vec<T>> {
        self.query(move |col| col.window(offset, limit))
    }

    /// Tracks the number of stored rows.
    pub fn len_signal(&self) -> Computed<usize> {
        self.query(|index| index.data.borrow().len())
    }

    /// Tracks the number of indexed rows.
    pub fn indexed_len_signal(&self) -> Computed<usize> {
        self.query(|index| index.data.borrow().indexed_len())
    }

    /// Tracks one row, including insertions and deletions.
    pub fn get_signal(&self, id: K) -> Computed<Option<T>> {
        self.query(move |col| col.get(&id))
    }

    /// Tracks membership independently of the current index filter.
    pub fn has_signal(&self, id: K) -> Computed<bool> {
        self.query(move |col| col.data.borrow().contains_key(&id))
    }

    /// Rebuilds under a new comparator and filter. Returns false when a callback changed the
    /// collection while building the replacement.
    pub fn set_ordering(
        &self,
        compare: impl Fn(&T, &T) -> Ordering + 'static,
        filter: impl Fn(&T) -> bool + 'static,
    ) -> bool {
        if self.inner.reorder(compare, filter) {
            self.notify_views();
            true
        } else {
            false
        }
    }

    /// Creates (or returns a cached live) first-class reactive [`Computed<Vec<T>>`] tracking the
    /// exact top `k` items.
    ///
    /// Mutations strictly outside the K-th boundary skip materialization and propagation in `O(1)`.
    pub fn top_k_signal(&self, k: usize) -> Computed<Vec<T>> {
        self.prune_disposed_views();
        if let Some(&sig) = self.cached_top_k.borrow().get(&k)
            && is_node_alive(&self.scope, sig.id())
        {
            return sig;
        }
        let view_id = self.inner.data.borrow_mut().watch_top_k(k);
        let initial = self
            .inner
            .materialize(view_id, false)
            .expect("registered view");
        let sig = self.build_top_k_signal(view_id, initial);
        self.cached_top_k.borrow_mut().insert(k, sig);
        sig
    }

    /// Creates a first-class reactive [`Computed<Vec<T>>`] with an additional per-view predicate.
    pub fn top_k_filtered_signal<P>(&self, k: usize, predicate: P) -> Computed<Vec<T>>
    where
        P: Fn(&T) -> bool + 'static,
    {
        self.query(move |index| index.filtered(k, &predicate))
    }

    /// Unregisters a previously created Top-K signal view and disposes its reactive node in the
    /// owning [`Scope`].
    pub fn dispose_top_k_signal(&self, sig: Computed<Vec<T>>) -> bool {
        let target = sig.id();
        self.cached_top_k
            .borrow_mut()
            .retain(|_, cached| cached.id() != target);
        let removed_view = {
            let mut views = self.views.borrow_mut();
            views
                .iter()
                .position(|v| v.signal_id == target)
                .map(|idx| views.swap_remove(idx).view_id)
        };
        if let Some(view_id) = removed_view {
            self.inner.data.borrow_mut().unwatch_top_k(view_id);
        }
        let disposed = self.scope.dispose(sig);
        removed_view.is_some() || disposed
    }

    fn prune_disposed_views(&self) {
        let dead: Vec<TopKViewId> = {
            let mut views = self.views.borrow_mut();
            views
                .extract_if(.., |v| !is_node_alive(&self.scope, v.signal_id))
                .map(|v| v.view_id)
                .collect()
        };
        if !dead.is_empty() {
            let mut col = self.inner.data.borrow_mut();
            for vid in dead {
                col.unwatch_top_k(vid);
            }
            self.cached_top_k
                .borrow_mut()
                .retain(|_, sig| is_node_alive(&self.scope, sig.id()));
        }
    }

    fn build_top_k_signal(&self, view_id: TopKViewId, initial: Vec<T>) -> Computed<Vec<T>> {
        let watched = Rc::new(Cell::new(false));
        let dirty_notified = Rc::new(Cell::new(false));
        let signal_id_cell: Rc<Cell<Option<NodeId>>> = Rc::new(Cell::new(None));

        let poll_inner = Rc::clone(&self.inner);
        let poll_id = Rc::clone(&signal_id_cell);
        let poll_dirty = Rc::clone(&dirty_notified);
        let poll = Rc::new(move |sc: &Scope| {
            let Some(sid) = poll_id.get() else {
                return;
            };
            let maybe_next = poll_inner.materialize(view_id, true);
            poll_dirty.set(false);
            if let Some(next) = maybe_next {
                update_external_silent(sc, sid, next);
            }
        });

        let watch_inner = Rc::clone(&self.inner);
        let watch_flag = Rc::clone(&watched);
        let watch_dirty = Rc::clone(&dirty_notified);
        let watch_id = Rc::clone(&signal_id_cell);
        let weak_sc = self.scope.downgrade();
        let on_watched = Rc::new(move || -> Option<CleanupFn> {
            watch_flag.set(true);
            if let (Some(sid), Some(sc_watch)) = (watch_id.get(), weak_sc.upgrade()) {
                let maybe_next = watch_inner.materialize(view_id, true);
                watch_dirty.set(false);
                if let Some(next) = maybe_next {
                    update_external_silent(&sc_watch, sid, next);
                }
            }
            let unw = Rc::clone(&watch_flag);
            let unw_dirty = Rc::clone(&watch_dirty);
            Some(Box::new(move || {
                unw.set(false);
                unw_dirty.set(false);
            }))
        });

        let eq: Rc<dyn Fn(&Vec<T>, &Vec<T>) -> bool> = Rc::new(|a, b| a == b);
        let sig =
            create_external_signal(&self.scope, initial, Some(eq), poll, Some(on_watched), None);
        signal_id_cell.set(Some(sig.id()));

        self.views.borrow_mut().push(WatchedTopK {
            view_id,
            signal_id: sig.id(),
            watched,
            dirty_notified,
        });

        sig
    }

    /// Inserts or replaces an item and incrementally updates any affected watched Top-K signals.
    pub fn upsert(&self, item: T) {
        self.try_upsert(item);
    }

    /// Returns false if a reentrant policy callback changed the index during this edit.
    pub fn try_upsert(&self, item: T) -> bool {
        let version = self.inner.data.borrow().version();
        if !self.inner.put(item, None, version) {
            return false;
        }
        self.notify_views();
        true
    }

    /// Inserts or replaces a batch of items.
    pub fn upsert_many<I>(&self, items: I)
    where
        I: IntoIterator<Item = T>,
    {
        self.try_upsert_many(items);
    }

    /// Atomically applies all rows. A competing reentrant edit supersedes this batch.
    pub fn try_upsert_many(&self, items: impl IntoIterator<Item = T>) -> bool {
        let mut items: Vec<_> = items.into_iter().collect();
        if items.is_empty() {
            return true;
        }
        if items.len() == 1 {
            return self.try_upsert(items.pop().expect("one item"));
        }
        if !self.inner.bulk(items) {
            return false;
        }
        self.notify_views();
        true
    }

    /// Updates a snapshot of the item. Returns false if the key was absent or
    /// the callback replaced or deleted it before the edit could be applied.
    pub fn update(&self, id: &K, updater: impl FnOnce(&T) -> T) -> bool {
        self.edit(id, |current| updater(&current))
    }

    /// Mutates a detached copy with the same conflict semantics as [`Self::update`].
    pub fn mutate(&self, id: &K, mutator: impl FnOnce(&mut T)) -> bool {
        self.edit(id, |mut current| {
            mutator(&mut current);
            current
        })
    }

    fn edit(&self, id: &K, edit: impl FnOnce(T) -> T) -> bool {
        let Some((current, revision)) = self
            .inner
            .data
            .borrow()
            .get_with_revision(id)
            .map(|(row, rev)| (Rc::clone(&row.item), rev))
        else {
            return false;
        };
        let next = edit((*current).clone());
        let version = {
            let collection = self.inner.data.borrow();
            if collection.get_with_revision(id).map(|(_, rev)| rev) != Some(revision) {
                return false;
            }
            collection.version()
        };
        if self.inner.put(next, Some(id), version) {
            self.notify_views();
            true
        } else {
            false
        }
    }

    /// Deletes an item by key.
    pub fn delete(&self, id: &K) -> Option<T> {
        let removed = self.inner.data.borrow_mut().delete(id);
        let removed = removed.map(|row| Rc::unwrap_or_clone(row.item));
        if removed.is_some() {
            self.notify_views();
        }
        removed
    }

    /// Removes all items from the collection.
    pub fn clear(&self) {
        let was_empty = self.inner.data.borrow().is_empty();
        if !was_empty {
            self.inner.clear();
            self.notify_views();
        }
    }

    fn notify_views(&self) {
        if let Some(revision) = self.query_revision.get() {
            let version = self.inner.data.borrow().version();
            self.scope.batch(|| {
                self.scope.set(revision, version);
                self.notify_top_k();
            });
        } else {
            self.notify_top_k();
        }
    }

    fn notify_top_k(&self) {
        self.prune_disposed_views();
        let dirty_watched: Vec<(TopKViewId, NodeId)> = {
            let col = self.inner.data.borrow();
            let views = self.views.borrow();
            views
                .iter()
                .filter(|v| v.watched.get() && col.is_view_dirty(v.view_id))
                .map(|v| (v.view_id, v.signal_id))
                .collect()
        };

        if dirty_watched.is_empty() {
            return;
        }

        if batch_depth(&self.scope) == 0 {
            let updates: Vec<_> = dirty_watched
                .into_iter()
                .filter_map(|(vid, sid)| self.inner.materialize(vid, true).map(|rows| (sid, rows)))
                .collect();

            if updates.len() == 1 {
                let (sid, next) = updates.into_iter().next().expect("len == 1");
                emit_external(&self.scope, sid, next);
            } else if !updates.is_empty() {
                self.scope.batch(|| {
                    for (sid, next) in updates {
                        emit_external(&self.scope, sid, next);
                    }
                });
            }
            return;
        }

        // Inside an active batch: mark downstream pending once and coalesce materialization to
        // a single flush hook at batch end!
        let to_propagate: Vec<NodeId> = {
            let col = self.inner.data.borrow();
            let views = self.views.borrow();
            views
                .iter()
                .filter_map(|v| {
                    if v.watched.get() && !v.dirty_notified.get() && col.is_view_dirty(v.view_id) {
                        v.dirty_notified.set(true);
                        Some(v.signal_id)
                    } else {
                        None
                    }
                })
                .collect()
        };
        for sid in to_propagate {
            propagate_external(&self.scope, sid);
        }

        if !self.flush_scheduled.get() {
            self.flush_scheduled.set(true);
            let inner = Rc::clone(&self.inner);
            let views = Rc::clone(&self.views);
            let scheduled = Rc::clone(&self.flush_scheduled);
            let weak_sc = self.scope.downgrade();
            schedule_flush_hook(
                &self.scope,
                self.flush_token,
                Rc::new(move || {
                    scheduled.set(false);
                    let Some(sc) = weak_sc.upgrade() else {
                        return;
                    };
                    let watched: Vec<_> = {
                        let views = views.borrow();
                        views
                            .iter()
                            .filter_map(|v| {
                                v.dirty_notified.set(false);
                                v.watched.get().then_some((v.signal_id, v.view_id))
                            })
                            .collect()
                    };
                    let updates: Vec<_> = watched
                        .into_iter()
                        .filter_map(|(sid, vid)| {
                            inner.materialize(vid, true).map(|rows| (sid, rows))
                        })
                        .collect();
                    for (sid, next) in updates {
                        emit_external(&sc, sid, next);
                    }
                }),
            );
        }
    }
}

impl<T, K, IdFn, Cmp, Flt> Drop for ReactiveCollection<T, K, IdFn, Cmp, Flt>
where
    T: Clone + PartialEq + 'static,
    K: Ord + Clone + 'static,
    IdFn: Fn(&T) -> K + 'static,
    Cmp: Fn(&T, &T) -> Ordering + 'static,
    Flt: ItemFilter<T> + 'static,
{
    fn drop(&mut self) {
        remove_flush_hook(&self.scope, self.flush_token);
    }
}