zwire 0.1.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
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 zwire_collections::{AcceptAll, Collection, 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::{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<RefCell<Collection<T, K, IdFn, Cmp, Flt>>>,
    views: Rc<RefCell<Vec<WatchedTopK>>>,
    cached_top_k: RefCell<BTreeMap<usize, Computed<Vec<T>>>>,
    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.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(RefCell::new(Collection::from_parts(
                get_id, compare, filter,
            ))),
            views: Rc::new(RefCell::new(Vec::new())),
            cached_top_k: RefCell::new(BTreeMap::new()),
            flush_token,
            flush_scheduled: Rc::new(Cell::new(false)),
        }
    }

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

    /// Returns `true` if the collection stores no items.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.inner.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.borrow().indexed_len()
    }

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

    /// Returns `true` if `id` exists in the collection.
    #[inline]
    pub fn contains_key(&self, id: &K) -> bool {
        self.inner.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.borrow().top_k(k)
    }

    /// 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.borrow_mut().watch_top_k(k);
        let initial = self.inner.borrow().view_cloned(view_id);
        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.prune_disposed_views();
        let view_id = self.inner.borrow_mut().watch_top_k_filtered(k, predicate);
        let initial = self.inner.borrow().view_cloned(view_id);
        self.build_top_k_signal(view_id, initial)
    }

    /// 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.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.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 = {
                let mut col = poll_inner.borrow_mut();
                let changed = col.sync_view(view_id);
                poll_dirty.set(false);
                if changed {
                    Some(col.view_cloned(view_id))
                } else {
                    None
                }
            };
            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 = {
                    let mut col = watch_inner.borrow_mut();
                    let changed = col.sync_view(view_id);
                    watch_dirty.set(false);
                    if changed {
                        Some(col.view_cloned(view_id))
                    } else {
                        None
                    }
                };
                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.inner.borrow_mut().upsert(item);
        self.notify_views();
    }

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

    /// 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
            .borrow()
            .get_with_revision(id)
            .map(|(item, revision)| (item.clone(), revision))
        else {
            return false;
        };
        let next = edit(current);
        {
            let mut collection = self.inner.borrow_mut();
            if collection.get_with_revision(id).map(|(_, rev)| rev) != Some(revision) {
                return false;
            }
            collection.update(id, |_| next);
        }
        self.notify_views();
        true
    }

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

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

    fn notify_views(&self) {
        self.prune_disposed_views();
        let dirty_watched: Vec<(TopKViewId, NodeId)> = {
            let col = self.inner.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<(NodeId, Vec<T>)> = {
                let mut col = self.inner.borrow_mut();
                dirty_watched
                    .into_iter()
                    .filter_map(|(vid, sid)| {
                        if col.sync_view(vid) {
                            Some((sid, col.view_cloned(vid)))
                        } else {
                            None
                        }
                    })
                    .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.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 updates: Vec<(NodeId, Vec<T>)> = {
                        let mut col = inner.borrow_mut();
                        let views_ref = views.borrow();
                        views_ref
                            .iter()
                            .filter_map(|v| {
                                v.dirty_notified.set(false);
                                if v.watched.get() && col.sync_view(v.view_id) {
                                    Some((v.signal_id, col.view_cloned(v.view_id)))
                                } else {
                                    None
                                }
                            })
                            .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);
    }
}