use alloc::boxed::Box;
use alloc::collections::BTreeMap;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::fmt;
use core::marker::PhantomData;
use std::sync::{PoisonError, RwLock};
use zwire_collections::{AcceptAll, ItemFilter, KeyedCollection, TopKViewId};
use zwire_core::{SyncAtom, SyncScope, SyncSignal, WeakSyncScope};
use crate::sync_top_k::{DirtyView, TopKView};
type ArcIdFn<T, K> = Box<dyn Fn(&Arc<T>) -> K + Send + Sync>;
type ArcSkFn<T, S> = Box<dyn Fn(&Arc<T>) -> S + Send + Sync>;
type ArcFltFn<T> = Box<dyn Fn(&Arc<T>) -> bool + Send + Sync>;
type SyncPureIndex<T, K, S> =
KeyedCollection<Arc<T>, K, S, ArcIdFn<T, K>, ArcSkFn<T, S>, ArcFltFn<T>>;
struct SyncPureState<T, K, S>
where
T: Send + Sync + 'static,
K: Send + Sync + 'static,
S: Send + Sync + 'static,
{
index: SyncPureIndex<T, K, S>,
views: Vec<Arc<TopKView<T>>>,
cached_top_k: BTreeMap<usize, SyncAtom<Vec<T>>>,
}
struct SyncPureInner<T, K, S>
where
T: Send + Sync + 'static,
K: Send + Sync + 'static,
S: Send + Sync + 'static,
{
scope: WeakSyncScope,
state: RwLock<SyncPureState<T, K, S>>,
}
impl<T, K, S> SyncPureInner<T, K, S>
where
T: Clone + PartialEq + Send + Sync + 'static,
K: Ord + Clone + Send + Sync + 'static,
S: Ord + Copy + Send + Sync + 'static,
{
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())))
}
}
pub struct SyncPureReactiveCollection<T, K, S, IdFn, SkFn, Flt = AcceptAll>
where
T: Clone + PartialEq + Send + Sync + 'static,
K: Ord + Clone + Send + Sync + 'static,
S: Ord + Copy + Send + Sync + 'static,
IdFn: Fn(&T) -> K + Send + Sync + 'static,
SkFn: Fn(&T) -> S + Send + Sync + 'static,
Flt: ItemFilter<T> + Send + Sync + 'static,
{
scope: SyncScope,
id: Arc<IdFn>,
inner: Arc<SyncPureInner<T, K, S>>,
_marker: PhantomData<(SkFn, Flt)>,
}
impl<T, K, S, IdFn, SkFn, Flt> fmt::Debug for SyncPureReactiveCollection<T, K, S, IdFn, SkFn, Flt>
where
T: Clone + PartialEq + Send + Sync + 'static,
K: Ord + Clone + Send + Sync + 'static,
S: Ord + Copy + Send + Sync + 'static,
IdFn: Fn(&T) -> K + Send + Sync + 'static,
SkFn: Fn(&T) -> S + Send + Sync + 'static,
Flt: ItemFilter<T> + Send + Sync + 'static,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut s = f.debug_struct("SyncPureReactiveCollection");
if let Ok(state) = self.inner.state.try_read() {
s.field("len", &state.index.len())
.field("indexed_len", &state.index.indexed_len())
.field("version", &state.index.version());
} else {
s.field("state", &"<locked>");
}
s.finish_non_exhaustive()
}
}
impl<T, K, S, IdFn, SkFn> SyncPureReactiveCollection<T, K, S, IdFn, SkFn, AcceptAll>
where
T: Clone + PartialEq + Send + Sync + 'static,
K: Ord + Clone + Send + Sync + 'static,
S: Ord + Copy + Send + Sync + 'static,
IdFn: Fn(&T) -> K + Send + Sync + 'static,
SkFn: Fn(&T) -> S + Send + Sync + 'static,
{
pub fn new(scope: &SyncScope, get_id: IdFn, sort_key: SkFn) -> Self {
Self::from_parts(scope, get_id, sort_key, AcceptAll)
}
}
impl<T, K, S, IdFn, SkFn, Flt> SyncPureReactiveCollection<T, K, S, IdFn, SkFn, Flt>
where
T: Clone + PartialEq + Send + Sync + 'static,
K: Ord + Clone + Send + Sync + 'static,
S: Ord + Copy + Send + Sync + 'static,
IdFn: Fn(&T) -> K + Send + Sync + 'static,
SkFn: Fn(&T) -> S + Send + Sync + 'static,
Flt: Fn(&T) -> bool + Send + Sync + 'static,
{
pub fn with_filter(scope: &SyncScope, get_id: IdFn, sort_key: SkFn, filter: Flt) -> Self {
Self::from_parts(scope, get_id, sort_key, filter)
}
}
impl<T, K, S, IdFn, SkFn, Flt> SyncPureReactiveCollection<T, K, S, IdFn, SkFn, Flt>
where
T: Clone + PartialEq + Send + Sync + 'static,
K: Ord + Clone + Send + Sync + 'static,
S: Ord + Copy + Send + Sync + 'static,
IdFn: Fn(&T) -> K + Send + Sync + 'static,
SkFn: Fn(&T) -> S + Send + Sync + 'static,
Flt: ItemFilter<T> + Send + Sync + 'static,
{
pub fn from_parts(scope: &SyncScope, get_id: IdFn, sort_key: SkFn, filter: Flt) -> Self {
let id = Arc::new(get_id);
let id_for_col = Arc::clone(&id);
let id_fn: ArcIdFn<T, K> = Box::new(move |item: &Arc<T>| id_for_col(item));
let sk_fn: ArcSkFn<T, S> = Box::new(move |item: &Arc<T>| sort_key(item));
let flt_fn: ArcFltFn<T> = Box::new(move |item: &Arc<T>| filter.matches(item));
let index = KeyedCollection::from_parts(id_fn, sk_fn, flt_fn);
Self {
scope: scope.clone(),
id,
inner: Arc::new(SyncPureInner {
scope: scope.downgrade(),
state: RwLock::new(SyncPureState {
index,
views: Vec::new(),
cached_top_k: BTreeMap::new(),
}),
}),
_marker: PhantomData,
}
}
#[inline]
pub fn len(&self) -> usize {
self.inner
.state
.read()
.unwrap_or_else(PoisonError::into_inner)
.index
.len()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.inner
.state
.read()
.unwrap_or_else(PoisonError::into_inner)
.index
.is_empty()
}
#[inline]
pub fn indexed_len(&self) -> usize {
self.inner
.state
.read()
.unwrap_or_else(PoisonError::into_inner)
.index
.indexed_len()
}
#[inline]
pub fn get(&self, id: &K) -> Option<Arc<T>> {
self.inner
.state
.read()
.unwrap_or_else(PoisonError::into_inner)
.index
.get(id)
.cloned()
}
#[inline]
pub fn contains_key(&self, id: &K) -> bool {
self.inner
.state
.read()
.unwrap_or_else(PoisonError::into_inner)
.index
.contains_key(id)
}
#[inline]
pub fn get_top_k(&self, k: usize) -> Vec<T> {
let state = self
.inner
.state
.read()
.unwrap_or_else(PoisonError::into_inner);
state
.index
.top_k_refs(k)
.into_iter()
.map(|r| (**r).clone())
.collect()
}
pub fn upsert(&self, item: T) {
self.mutate(|index| {
index.upsert(Arc::new(item));
Some(())
});
}
pub fn upsert_many<I>(&self, items: I)
where
I: 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(())
});
}
pub fn update(&self, id: &K, f: impl FnOnce(&T) -> T) -> bool {
let Some(original) = self.get(id) else {
return false;
};
let next = Arc::new(f(&original));
let next_id = (self.id)(&next);
self.mutate(|index| {
if !index.get(id).is_some_and(|cur| Arc::ptr_eq(cur, &original)) {
return None;
}
let displaced = if &next_id == id {
None
} else {
index.delete(id)
};
index.upsert(next);
Some(displaced)
})
.is_some()
}
pub fn delete(&self, id: &K) -> Option<Arc<T>> {
self.mutate(|index| index.delete(id))
}
pub fn clear(&self) {
self.mutate(|index| {
if index.is_empty() {
return None;
}
index.clear();
Some(())
});
}
pub fn top_k_signal(&self, k: usize) -> SyncSignal<Vec<T>> {
self.prune_disposed_views();
loop {
let cached = {
let state = self
.inner
.state
.read()
.unwrap_or_else(PoisonError::into_inner);
state.cached_top_k.get(&k).copied()
};
if let Some(atom) = cached
&& self.scope.contains_node(atom.id())
{
return atom.as_signal();
}
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))
});
let view_atom = view.atom();
let existing = {
let mut state = self
.inner
.state
.write()
.unwrap_or_else(PoisonError::into_inner);
if let Some(&prev) = state.cached_top_k.get(&k) {
state.index.unwatch_top_k(view_id);
Some(prev)
} else {
state.views.push(view);
state.cached_top_k.insert(k, view_atom);
None
}
};
if let Some(prev) = existing {
self.scope.dispose(view_atom);
if self.scope.contains_node(prev.id()) {
return prev.as_signal();
}
self.prune_disposed_views();
continue;
}
return view_atom.as_signal();
}
}
pub fn dispose_top_k_signal(&self, sig: SyncSignal<Vec<T>>) -> bool {
let target = sig.id();
let removed_view = {
let mut state = self
.inner
.state
.write()
.unwrap_or_else(PoisonError::into_inner);
state.cached_top_k.retain(|_, atom| atom.id() != target);
let removed = state
.views
.iter()
.position(|v| v.atom().id() == target)
.map(|idx| state.views.swap_remove(idx).view_id());
if let Some(view_id) = removed {
state.index.unwatch_top_k(view_id);
}
removed
};
let disposed = self.scope.dispose(sig);
removed_view.is_some() || disposed
}
fn prune_disposed_views(&self) {
let candidate_ids: Vec<zwire_core::NodeId> = {
let state = self
.inner
.state
.read()
.unwrap_or_else(PoisonError::into_inner);
state.views.iter().map(|v| v.atom().id()).collect()
};
let dead_ids: Vec<zwire_core::NodeId> = candidate_ids
.into_iter()
.filter(|&id| !self.scope.contains_node(id))
.collect();
if dead_ids.is_empty() {
return;
}
let mut state = self
.inner
.state
.write()
.unwrap_or_else(PoisonError::into_inner);
let removed: Vec<TopKViewId> = state
.views
.extract_if(.., |v| dead_ids.contains(&v.atom().id()))
.map(|v| v.view_id())
.collect();
for vid in removed {
state.index.unwatch_top_k(vid);
}
state
.cached_top_k
.retain(|_, atom| !dead_ids.contains(&atom.id()));
}
fn mutate<R>(
&self,
mutate: impl FnOnce(&mut SyncPureIndex<T, K, S>) -> Option<R>,
) -> Option<R> {
let (out, dirty) = {
let mut state = self
.inner
.state
.write()
.unwrap_or_else(PoisonError::into_inner);
let out = mutate(&mut state.index)?;
(out, collect_dirty_watched(&mut state))
};
for (view, version, rows) in dirty {
view.publish(&self.scope, version, rows, false);
}
Some(out)
}
}
impl<T, K, S, IdFn, SkFn, Flt> Drop for SyncPureReactiveCollection<T, K, S, IdFn, SkFn, Flt>
where
T: Clone + PartialEq + Send + Sync + 'static,
K: Ord + Clone + Send + Sync + 'static,
S: Ord + Copy + Send + Sync + 'static,
IdFn: Fn(&T) -> K + Send + Sync + 'static,
SkFn: Fn(&T) -> S + Send + Sync + 'static,
Flt: ItemFilter<T> + Send + Sync + 'static,
{
fn drop(&mut self) {
let pending: Vec<DirtyView<T>> = {
let mut state = self
.inner
.state
.write()
.unwrap_or_else(PoisonError::into_inner);
let state = &mut *state;
let mut out = Vec::new();
for view in &state.views {
let id = view.view_id();
state.index.sync_view(id);
let version = state.index.view_version(id).unwrap_or(0);
if !view.holds(version) {
let rows = state.index.view_mapped(id, |r| (**r).clone());
out.push((Arc::clone(view), version, rows));
}
}
out
};
for (view, version, rows) in pending {
view.publish(&self.scope, version, rows, true);
}
}
}
fn collect_dirty_watched<T, K, S>(state: &mut SyncPureState<T, K, S>) -> Vec<DirtyView<T>>
where
T: Clone + PartialEq + Send + Sync + 'static,
K: Ord + Clone + Send + Sync + 'static,
S: Ord + Copy + 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
}