zwire 0.3.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
//! Thread-safe incremental reactive collection backed by [`zwire_collections::Collection`]
//! (2-level Chunked Sorted Block Index with `O(1)` Top-K boundary pruning).
//!
//! User `update` callbacks and all [`SyncScope`] calls execute strictly outside the collection's
//! `RwLock` guards; pure index predicates (`id`, `cmp`, `filter`) run under the index lock
//! without ever acquiring [`SyncScope`]'s lock.
//!
//! Signals are refreshed with versioned publications (see `sync_top_k`): each Top-K view and
//! the range revision is published as an immutable `(version, value)` pair that the arena
//! accepts only if it is newer than what the signal already holds, so racing writers, unwatched
//! readers, and new subscribers can never regress a signal or miss a committed write.

use alloc::boxed::Box;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::cmp::Ordering;
use core::fmt;
use core::marker::PhantomData;
use core::sync::atomic::{AtomicU64, AtomicUsize, Ordering as AtomicOrdering};
use std::sync::{OnceLock, PoisonError, RwLock};

use zwire_collections::{AcceptAll, Collection, ItemFilter};
use zwire_core::internal::sync_publish_external_versioned;
use zwire_core::{SyncAtom, SyncAtomOptions, SyncComputed, SyncScope, WeakSyncScope};

use crate::sync_top_k::{DirtyView, TopKView};

type ArcIdFn<T, K> = Box<dyn Fn(&Arc<T>) -> K + Send + Sync>;
type ArcCmpFn<T> = Box<dyn Fn(&Arc<T>, &Arc<T>) -> Ordering + Send + Sync>;
type ArcFltFn<T> = Box<dyn Fn(&Arc<T>) -> bool + Send + Sync>;
type SyncIndex<T, K> = Collection<Arc<T>, K, ArcIdFn<T, K>, ArcCmpFn<T>, ArcFltFn<T>>;

struct SyncColState<T: Send + Sync + 'static, K: Send + Sync + 'static> {
    index: SyncIndex<T, K>,
    views: Vec<Arc<TopKView<T>>>,
}

/// Revision signal that invalidates [`SyncReactiveCollection::range_signal`] windows.
struct RevClock {
    atom: OnceLock<SyncAtom<u64>>,
    /// Number of committed index mutations, advanced under the index write lock.
    counter: AtomicU64,
    /// Highest revision stored in `atom`, advanced only together with the write.
    published: AtomicU64,
    /// `on_watched` minus `on_unwatched` deliveries for `atom`.
    watchers: AtomicUsize,
}

impl RevClock {
    /// Publishes `rev` unless the atom already stores it or a newer revision, and returns
    /// whether this call advanced the atom.
    fn publish(&self, scope: &SyncScope, rev: u64, quiet: bool) -> bool {
        self.atom.get().is_some_and(|&atom| {
            sync_publish_external_versioned(scope, atom, &self.published, rev, rev, quiet)
        })
    }
}

struct SyncColInner<T: Send + Sync + 'static, K: Send + Sync + 'static> {
    scope: WeakSyncScope,
    state: RwLock<SyncColState<T, K>>,
    rev: SyncAtom<u64>,
    clock: Arc<RevClock>,
}

impl<T: Send + Sync + 'static, K: Send + Sync + 'static> Drop for SyncColInner<T, K> {
    fn drop(&mut self) {
        if let Some(scope) = self.scope.upgrade() {
            scope.dispose(self.rev);
        }
    }
}

impl<T, K> SyncColInner<T, K>
where
    T: Clone + PartialEq + Send + Sync + 'static,
    K: Ord + Clone + Send + Sync + 'static,
{
    /// Returns the view's current `(version, rows)` unless its atom already holds them.
    fn pending_view(&self, view: &TopKView<T>) -> Option<(u64, Vec<T>)> {
        let id = view.view_id();
        {
            let state = self.state.read().unwrap_or_else(PoisonError::into_inner);
            let version = state.index.view_version(id)?;
            if !state.index.is_view_dirty(id) && view.holds(version) {
                return None;
            }
        }
        let mut state = self.state.write().unwrap_or_else(PoisonError::into_inner);
        state.index.sync_view(id);
        let version = state.index.view_version(id)?;
        (!view.holds(version)).then(|| (version, state.index.view_mapped(id, |r| (**r).clone())))
    }
}

struct ViewAtomGuard<
    T: Clone + PartialEq + Send + Sync + 'static,
    K: Ord + Clone + Send + Sync + 'static,
> {
    inner: Arc<SyncColInner<T, K>>,
    view: Arc<TopKView<T>>,
}

impl<T: Clone + PartialEq + Send + Sync + 'static, K: Ord + Clone + Send + Sync + 'static> Drop
    for ViewAtomGuard<T, K>
{
    fn drop(&mut self) {
        {
            let mut state = self
                .inner
                .state
                .write()
                .unwrap_or_else(PoisonError::into_inner);
            state.views.retain(|v| !Arc::ptr_eq(v, &self.view));
            state.index.unwatch_top_k(self.view.view_id());
        }
        if let Some(scope) = self.inner.scope.upgrade() {
            scope.dispose(self.view.atom());
        }
    }
}

/// Thread-safe incremental reactive collection backed by a 2-level Chunked Sorted Block Index
/// with `O(log N)` mutations and `O(1)` Top-K boundary pruning.
pub struct SyncReactiveCollection<T, K, Id, Cmp, Flt = AcceptAll>
where
    T: Send + Sync + 'static,
    K: Send + Sync + 'static,
{
    scope: SyncScope,
    inner: Arc<SyncColInner<T, K>>,
    _marker: PhantomData<(Id, Cmp, Flt)>,
}

impl<T, K, Id, Cmp, Flt> fmt::Debug for SyncReactiveCollection<T, K, Id, Cmp, Flt>
where
    T: Send + Sync + 'static,
    K: Send + Sync + 'static,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SyncReactiveCollection")
            .field("rev", &self.inner.rev.id())
            .finish_non_exhaustive()
    }
}

impl<T, K, Id, Cmp> SyncReactiveCollection<T, K, Id, Cmp>
where
    T: Clone + PartialEq + Send + Sync + 'static,
    K: Ord + Clone + Send + Sync + 'static,
    Id: Fn(&T) -> K + Send + Sync + 'static,
    Cmp: Fn(&T, &T) -> Ordering + Send + Sync + 'static,
{
    /// Creates a collection with every row indexed.
    pub fn new(scope: &SyncScope, id: Id, cmp: Cmp) -> Self {
        Self::with_filter(scope, id, cmp, AcceptAll)
    }
}

impl<T, K, Id, Cmp, Flt> SyncReactiveCollection<T, K, Id, Cmp, Flt>
where
    T: Clone + PartialEq + Send + Sync + 'static,
    K: Ord + Clone + Send + Sync + 'static,
    Id: Fn(&T) -> K + Send + Sync + 'static,
    Cmp: Fn(&T, &T) -> Ordering + Send + Sync + 'static,
    Flt: ItemFilter<T> + Send + Sync + 'static,
{
    /// Creates a filtered collection. Ties are broken by the extracted key.
    pub fn with_filter(scope: &SyncScope, id: Id, cmp: Cmp, filter: Flt) -> Self {
        let id_fn: ArcIdFn<T, K> = Box::new(move |item: &Arc<T>| id(item));
        let cmp_fn: ArcCmpFn<T> = Box::new(move |a: &Arc<T>, b: &Arc<T>| cmp(a, b));
        let flt_fn: ArcFltFn<T> = Box::new(move |item: &Arc<T>| filter.matches(item));
        let index = Collection::from_parts(id_fn, cmp_fn, flt_fn);

        let clock = Arc::new(RevClock {
            atom: OnceLock::new(),
            counter: AtomicU64::new(0),
            published: AtomicU64::new(0),
            watchers: AtomicUsize::new(0),
        });

        let watch_clock = Arc::clone(&clock);
        let watch_scope = scope.downgrade();
        let unwatch_clock = Arc::clone(&clock);
        let rev = scope.atom_with(
            0u64,
            SyncAtomOptions::new()
                .on_watched(move || {
                    watch_clock.watchers.fetch_add(1, AtomicOrdering::SeqCst);
                    let rev = watch_clock.counter.load(AtomicOrdering::SeqCst);
                    if let Some(sc) = watch_scope.upgrade() {
                        let _ = watch_clock.publish(&sc, rev, false);
                    }
                    None
                })
                .on_unwatched(move || {
                    unwatch_clock.watchers.fetch_sub(1, AtomicOrdering::SeqCst);
                }),
        );
        let _ = clock.atom.set(rev);

        let poll_clock = Arc::clone(&clock);
        let poll_scope = scope.downgrade();
        scope.set_external_poller(rev, move || {
            let rev = poll_clock.counter.load(AtomicOrdering::SeqCst);
            if poll_clock.published.load(AtomicOrdering::Acquire) < rev
                && let Some(sc) = poll_scope.upgrade()
            {
                let _ = poll_clock.publish(&sc, rev, true);
            }
        });

        let inner = Arc::new(SyncColInner {
            scope: scope.downgrade(),
            state: RwLock::new(SyncColState {
                index,
                views: Vec::new(),
            }),
            rev,
            clock,
        });

        Self {
            scope: scope.clone(),
            inner,
            _marker: PhantomData,
        }
    }

    /// Returns a zero-copy snapshot of an individual row.
    pub fn get(&self, key: &K) -> Option<Arc<T>> {
        let state = self
            .inner
            .state
            .read()
            .unwrap_or_else(PoisonError::into_inner);
        state.index.get(key).cloned()
    }

    /// Returns the total number of rows.
    pub fn len(&self) -> usize {
        self.inner
            .state
            .read()
            .unwrap_or_else(PoisonError::into_inner)
            .index
            .len()
    }

    /// Whether the collection has any rows.
    pub fn is_empty(&self) -> bool {
        self.inner
            .state
            .read()
            .unwrap_or_else(PoisonError::into_inner)
            .index
            .is_empty()
    }

    /// Returns the number of rows matching the index filter.
    pub fn indexed_len(&self) -> usize {
        self.inner
            .state
            .read()
            .unwrap_or_else(PoisonError::into_inner)
            .index
            .indexed_len()
    }

    /// Inserts or replaces a row.
    pub fn upsert(&self, item: T) {
        self.mutate(|index| {
            index.upsert(Arc::new(item));
            Some(())
        });
    }

    /// Atomically inserts or replaces a batch of rows.
    pub fn upsert_many(&self, items: impl IntoIterator<Item = T>) {
        let batch: Vec<Arc<T>> = items.into_iter().map(Arc::new).collect();
        if batch.is_empty() {
            return;
        }
        self.mutate(|index| {
            index.upsert_many(batch);
            Some(())
        });
    }

    /// Updates a detached snapshot and migrates changed keys. Returns `false` if the
    /// original row was removed or replaced before publication.
    pub fn update(&self, key: &K, f: impl FnOnce(&T) -> T) -> bool {
        let Some(original) = self.get(key) else {
            return false;
        };
        let next = Arc::new(f(&original));
        self.mutate(|index| {
            let unchanged = index
                .get(key)
                .is_some_and(|cur| Arc::ptr_eq(cur, &original));
            (unchanged && index.update(key, |_| next)).then_some(())
        })
        .is_some()
    }

    /// Deletes a row, returning the removed payload.
    pub fn delete(&self, key: &K) -> Option<Arc<T>> {
        self.mutate(|index| index.delete(key))
    }

    /// Clears all rows and the sorted index.
    pub fn clear(&self) {
        self.mutate(|index| {
            if index.is_empty() {
                return None;
            }
            index.clear();
            Some(())
        });
    }

    /// An exact, deterministically sorted Top-K signal with `O(1)` boundary pruning and
    /// equality cutoff.
    pub fn top_k_signal(&self, k: usize) -> SyncComputed<Vec<T>> {
        let (view_id, rows, version) = {
            let mut state = self
                .inner
                .state
                .write()
                .unwrap_or_else(PoisonError::into_inner);
            let view_id = state.index.watch_top_k(k);
            let rows = state.index.view_mapped(view_id, |r| (**r).clone());
            let version = state.index.view_version(view_id).unwrap_or(0);
            (view_id, rows, version)
        };

        let weak = Arc::downgrade(&self.inner);
        let view = TopKView::create(&self.scope, view_id, version, rows, move |view| {
            let inner = weak.upgrade()?;
            let scope = inner.scope.upgrade()?;
            let (version, rows) = inner.pending_view(view)?;
            Some((scope, version, rows))
        });
        self.inner
            .state
            .write()
            .unwrap_or_else(PoisonError::into_inner)
            .views
            .push(Arc::clone(&view));

        let guard = ViewAtomGuard {
            inner: Arc::clone(&self.inner),
            view,
        };
        self.scope.computed(move |cx| {
            let guard = &guard;
            cx.get(guard.view.atom())
        })
    }

    /// A sorted offset/limit window signal.
    pub fn range_signal(&self, offset: usize, limit: usize) -> SyncComputed<Vec<T>> {
        let inner = Arc::clone(&self.inner);
        self.scope.computed(move |cx| {
            let _ = cx.get(inner.rev);
            let state = inner.state.read().unwrap_or_else(PoisonError::into_inner);
            state
                .index
                .range(offset, limit)
                .into_iter()
                .map(|r| (**r).clone())
                .collect()
        })
    }

    /// Applies `mutate` under the index write lock. When it reports a change (`Some`), stamps
    /// the next revision under the same lock and publishes every affected signal after the
    /// lock is released.
    fn mutate<R>(&self, mutate: impl FnOnce(&mut SyncIndex<T, K>) -> Option<R>) -> Option<R> {
        let (out, rev, dirty) = {
            let mut state = self
                .inner
                .state
                .write()
                .unwrap_or_else(PoisonError::into_inner);
            let out = mutate(&mut state.index)?;
            let rev = self
                .inner
                .clock
                .counter
                .fetch_add(1, AtomicOrdering::SeqCst)
                + 1;
            (out, rev, collect_dirty_watched(&mut state))
        };
        for (view, version, rows) in dirty {
            view.publish(&self.scope, version, rows, false);
        }
        let clock = &self.inner.clock;
        let observed = self.scope.has_commit_observers();
        if observed || clock.watchers.load(AtomicOrdering::SeqCst) > 0 {
            let advanced = clock.publish(&self.scope, rev, false);
            if observed && !advanced {
                // A racing writer already published a newer revision, which also invalidates
                // every window for this write. Re-commit that revision unchanged so commit
                // observers still receive exactly one revision event per write.
                self.scope.update(self.inner.rev, |current| *current);
            }
        }
        Some(out)
    }
}

fn collect_dirty_watched<T, K>(state: &mut SyncColState<T, K>) -> Vec<DirtyView<T>>
where
    T: Clone + PartialEq + Send + Sync + 'static,
    K: Ord + Clone + Send + Sync + 'static,
{
    let mut dirty = Vec::new();
    for view in &state.views {
        let id = view.view_id();
        if view.is_watched() && state.index.sync_view(id) {
            let version = state.index.view_version(id).unwrap_or(0);
            let rows = state.index.view_mapped(id, |r| (**r).clone());
            dirty.push((Arc::clone(view), version, rows));
        }
    }
    dirty
}