zwire 0.4.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
//! Top-K view publication shared by the thread-safe reactive collections.
//!
//! Each view mirrors its rows into an external [`SyncAtom`]. A refresh is an immutable
//! `(view version, rows)` pair captured under the index lock while the view is clean and handed
//! to [`sync_publish_external_versioned`] after the lock is released. That call compares the
//! version, checks for subscribers, and writes inside one arena critical section, so publishers
//! may race freely: the newest version wins, an older one is dropped instead of overwriting it,
//! and a subscriber that links before the write is always notified.

use alloc::sync::Arc;
use alloc::vec::Vec;
use core::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::OnceLock;

use zwire_collections::TopKViewId;
use zwire_core::internal::sync_publish_external_versioned;
use zwire_core::{SyncAtom, SyncAtomOptions, SyncScope};

/// A view refresh captured under the index lock and published after it is released.
pub(crate) type DirtyView<T> = (Arc<TopKView<T>>, u64, Vec<T>);

/// A registered Top-K view and the external atom that mirrors its rows.
pub(crate) struct TopKView<T: Send + Sync + 'static> {
    view_id: TopKViewId,
    atom: OnceLock<SyncAtom<Vec<T>>>,
    /// `on_watched` minus `on_unwatched` deliveries. A counter rather than a flag because
    /// hooks run outside the arena lock, so a resubscribe may deliver them out of order (the
    /// count then wraps through zero until the matching hook arrives).
    watchers: AtomicUsize,
    /// Highest view version stored in `atom`, advanced only together with the write.
    published: AtomicU64,
}

impl<T: Clone + PartialEq + Send + Sync + 'static> TopKView<T> {
    /// Creates the atom mirroring `view_id`, seeded with the `rows` of `version`.
    ///
    /// `refresh` returns the owning scope and the view's current `(version, rows)`, or `None`
    /// when the atom already [holds](Self::holds) them or the collection is gone. It runs
    /// outside every arena lock: on first subscription, and before each unwatched read.
    pub(crate) fn create<R>(
        scope: &SyncScope,
        view_id: TopKViewId,
        version: u64,
        rows: Vec<T>,
        refresh: R,
    ) -> Arc<Self>
    where
        R: Fn(&Self) -> Option<(SyncScope, u64, Vec<T>)> + Send + Sync + 'static,
    {
        let view = Arc::new(Self {
            view_id,
            atom: OnceLock::new(),
            watchers: AtomicUsize::new(0),
            published: AtomicU64::new(version),
        });
        let refresh = Arc::new(refresh);

        let watch_view = Arc::clone(&view);
        let watch_refresh = Arc::clone(&refresh);
        let unwatch_view = Arc::clone(&view);
        let atom = scope.atom_with_eq(
            rows,
            SyncAtomOptions::new()
                .on_watched(move || {
                    watch_view.watchers.fetch_add(1, Ordering::SeqCst);
                    watch_view.pull(&*watch_refresh, false);
                    None
                })
                .on_unwatched(move || {
                    unwatch_view.watchers.fetch_sub(1, Ordering::SeqCst);
                }),
        );
        let _ = view.atom.set(atom);

        let poll_view = Arc::clone(&view);
        scope.set_external_poller(atom, move || poll_view.pull(&*refresh, true));
        view
    }

    fn pull<R>(&self, refresh: &R, quiet: bool)
    where
        R: Fn(&Self) -> Option<(SyncScope, u64, Vec<T>)>,
    {
        if let Some((scope, version, rows)) = refresh(self) {
            self.publish(&scope, version, rows, quiet);
        }
    }

    /// Identifier of the mirrored view inside the collection's index.
    pub(crate) const fn view_id(&self) -> TopKViewId {
        self.view_id
    }

    /// The external atom holding the view's rows.
    pub(crate) fn atom(&self) -> SyncAtom<Vec<T>> {
        *self.atom.get().expect("view atom is set by `create`")
    }

    /// Whether writers must refresh this view eagerly.
    pub(crate) fn is_watched(&self) -> bool {
        self.watchers.load(Ordering::SeqCst) > 0
    }

    /// Whether the atom already stores `version` or a newer one.
    pub(crate) fn holds(&self, version: u64) -> bool {
        self.published.load(Ordering::Acquire) >= version
    }

    /// Publishes `rows` as `version` unless the atom already [holds](Self::holds) it.
    ///
    /// With `quiet`, a write that finds no subscriber is not reported as a commit and does not
    /// flush effects (unwatched pull-on-read refreshes and drop syncs).
    pub(crate) fn publish(&self, scope: &SyncScope, version: u64, rows: Vec<T>, quiet: bool) {
        sync_publish_external_versioned(scope, self.atom(), &self.published, version, rows, quiet);
    }
}