use std::any::Any;
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, OnceLock, RwLock};
pub type ReceiverFuture = Pin<Box<dyn Future<Output = ()> + Send + 'static>>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ReceiverId(u64);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum M2mAction {
Add,
Remove,
Set,
Clear,
}
#[derive(Debug, Clone)]
pub struct M2mChangedContext {
pub action: M2mAction,
pub through: &'static str,
pub src_col: &'static str,
pub dst_col: &'static str,
pub src_pk: i64,
pub dst_pks: Vec<i64>,
}
type ReceiverEntry = (ReceiverId, Box<dyn Any + Send + Sync>);
type Bag = Vec<ReceiverEntry>;
fn registry() -> &'static RwLock<HashMap<(), Bag>> {
static REG: OnceLock<RwLock<HashMap<(), Bag>>> = OnceLock::new();
REG.get_or_init(|| RwLock::new(HashMap::new()))
}
fn next_id() -> ReceiverId {
static COUNTER: AtomicU64 = AtomicU64::new(1);
ReceiverId(COUNTER.fetch_add(1, Ordering::Relaxed))
}
fn insert_receiver<R: Any + Send + Sync>(receiver: R) -> ReceiverId {
let id = next_id();
let mut reg = registry().write().unwrap_or_else(|e| e.into_inner());
reg.entry(()).or_default().push((id, Box::new(receiver)));
id
}
fn remove_receiver(id: ReceiverId) -> bool {
let mut reg = registry().write().unwrap_or_else(|e| e.into_inner());
let Some(bag) = reg.get_mut(&()) else {
return false;
};
let before = bag.len();
bag.retain(|(rid, _)| *rid != id);
bag.len() != before
}
fn snapshot<R: Any + Send + Sync + Clone>() -> Vec<R> {
let reg = registry().read().unwrap_or_else(|e| e.into_inner());
let Some(bag) = reg.get(&()) else {
return Vec::new();
};
bag.iter()
.filter_map(|(_, b)| b.downcast_ref::<R>().cloned())
.collect()
}
type ChangedReceiver = Arc<dyn Fn(M2mChangedContext) -> ReceiverFuture + Send + Sync>;
pub fn connect_m2m_changed<F, Fut>(receiver: F) -> ReceiverId
where
F: Fn(M2mChangedContext) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
let boxed: ChangedReceiver = Arc::new(move |ctx| Box::pin(receiver(ctx)));
insert_receiver(boxed)
}
pub fn disconnect_m2m_changed(id: ReceiverId) -> bool {
remove_receiver(id)
}
pub async fn send_m2m_changed(ctx: M2mChangedContext) {
let receivers: Vec<ChangedReceiver> = snapshot();
for r in receivers {
r(ctx.clone()).await;
}
}
pub fn clear_all() {
registry()
.write()
.unwrap_or_else(|e| e.into_inner())
.clear();
}
#[must_use]
pub fn receiver_count() -> usize {
let reg = registry().read().unwrap_or_else(|e| e.into_inner());
reg.get(&()).map_or(0, Vec::len)
}