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)]
pub struct PreMigrateContext {
pub source: &'static str,
}
#[derive(Debug, Clone)]
pub struct PostMigrateContext {
pub source: &'static str,
pub applied: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum SignalKind {
PreMigrate,
PostMigrate,
}
type ReceiverEntry = (ReceiverId, Box<dyn Any + Send + Sync>);
type Bag = Vec<ReceiverEntry>;
fn registry() -> &'static RwLock<HashMap<SignalKind, Bag>> {
static REG: OnceLock<RwLock<HashMap<SignalKind, 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>(kind: SignalKind, receiver: R) -> ReceiverId {
let id = next_id();
let mut reg = registry().write().unwrap_or_else(|e| e.into_inner());
reg.entry(kind).or_default().push((id, Box::new(receiver)));
id
}
fn remove_receiver(kind: SignalKind, id: ReceiverId) -> bool {
let mut reg = registry().write().unwrap_or_else(|e| e.into_inner());
let Some(bag) = reg.get_mut(&kind) else {
return false;
};
let before = bag.len();
bag.retain(|(rid, _)| *rid != id);
bag.len() != before
}
fn snapshot<R: Any + Send + Sync + Clone>(kind: SignalKind) -> Vec<R> {
let reg = registry().read().unwrap_or_else(|e| e.into_inner());
let Some(bag) = reg.get(&kind) else {
return Vec::new();
};
bag.iter()
.filter_map(|(_, b)| b.downcast_ref::<R>().cloned())
.collect()
}
type PreReceiver = Arc<dyn Fn(PreMigrateContext) -> ReceiverFuture + Send + Sync>;
type PostReceiver = Arc<dyn Fn(PostMigrateContext) -> ReceiverFuture + Send + Sync>;
pub fn connect_pre_migrate<F, Fut>(receiver: F) -> ReceiverId
where
F: Fn(PreMigrateContext) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
let boxed: PreReceiver = Arc::new(move |ctx| Box::pin(receiver(ctx)));
insert_receiver(SignalKind::PreMigrate, boxed)
}
pub fn disconnect_pre_migrate(id: ReceiverId) -> bool {
remove_receiver(SignalKind::PreMigrate, id)
}
pub async fn send_pre_migrate(ctx: PreMigrateContext) {
let receivers: Vec<PreReceiver> = snapshot(SignalKind::PreMigrate);
for r in receivers {
r(ctx.clone()).await;
}
}
pub fn connect_post_migrate<F, Fut>(receiver: F) -> ReceiverId
where
F: Fn(PostMigrateContext) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
let boxed: PostReceiver = Arc::new(move |ctx| Box::pin(receiver(ctx)));
insert_receiver(SignalKind::PostMigrate, boxed)
}
pub fn disconnect_post_migrate(id: ReceiverId) -> bool {
remove_receiver(SignalKind::PostMigrate, id)
}
pub async fn send_post_migrate(ctx: PostMigrateContext) {
let receivers: Vec<PostReceiver> = snapshot(SignalKind::PostMigrate);
for r in receivers {
r(ctx.clone()).await;
}
}
pub fn clear_all() {
registry()
.write()
.unwrap_or_else(|e| e.into_inner())
.clear();
}
pub fn receiver_count() -> usize {
let reg = registry().read().unwrap_or_else(|e| e.into_inner());
[SignalKind::PreMigrate, SignalKind::PostMigrate]
.iter()
.map(|kind| reg.get(kind).map_or(0, Vec::len))
.sum()
}