use crate::msg::ActorMsg;
use std::sync::Arc;
use tokio::sync::{broadcast, watch};
#[derive(Debug, Clone)]
pub struct Topic<T: ActorMsg + Sync> {
tx: broadcast::Sender<Arc<T>>,
}
impl<T: ActorMsg + Sync> Topic<T> {
pub fn new(capacity: usize) -> Self {
let (tx, _) = broadcast::channel(capacity.max(1));
Self { tx }
}
pub fn publish(&self, msg: T) -> usize {
if self.tx.receiver_count() == 0 {
return 0;
}
self.publish_shared(Arc::new(msg))
}
pub fn publish_shared(&self, msg: Arc<T>) -> usize {
self.tx.send(msg).unwrap_or(0)
}
pub fn subscribe(&self) -> Subscriber<T> {
Subscriber {
rx: self.tx.subscribe(),
lagged: 0,
closed: false,
}
}
pub fn subscriber_count(&self) -> usize {
self.tx.receiver_count()
}
}
pub struct Subscriber<T: ActorMsg + Sync> {
rx: broadcast::Receiver<Arc<T>>,
lagged: u64,
closed: bool,
}
impl<T: ActorMsg + Sync> Subscriber<T> {
pub async fn recv(&mut self) -> Option<Arc<T>> {
loop {
match self.rx.recv().await {
Ok(msg) => return Some(msg),
Err(broadcast::error::RecvError::Lagged(n)) => {
self.lagged += n;
tracing::debug!(skipped = n, "Topic 订阅者积压溢出,已跳到最新");
continue;
}
Err(broadcast::error::RecvError::Closed) => {
self.closed = true;
return None;
}
}
}
}
pub fn try_recv(&mut self) -> Option<Arc<T>> {
loop {
match self.rx.try_recv() {
Ok(msg) => return Some(msg),
Err(broadcast::error::TryRecvError::Lagged(n)) => {
self.lagged += n;
continue;
}
Err(broadcast::error::TryRecvError::Closed) => {
self.closed = true;
return None;
}
Err(broadcast::error::TryRecvError::Empty) => return None,
}
}
}
pub fn is_closed(&self) -> bool {
self.closed
}
pub fn lagged_count(&self) -> u64 {
self.lagged
}
}
#[derive(Debug, Clone)]
pub struct SnapshotTopic<S: ActorMsg + Sync> {
tx: watch::Sender<Arc<S>>,
}
impl<S: ActorMsg + Sync> SnapshotTopic<S> {
pub fn new(initial: S) -> Self {
Self {
tx: watch::channel(Arc::new(initial)).0,
}
}
pub fn update(&self, snapshot: S) -> usize {
self.update_shared(Arc::new(snapshot))
}
pub fn update_shared(&self, snapshot: Arc<S>) -> usize {
let _ = self.tx.send_replace(snapshot);
self.tx.receiver_count()
}
pub fn latest(&self) -> Arc<S> {
self.tx.borrow().clone()
}
pub fn subscribe(&self) -> SnapshotReader<S> {
SnapshotReader {
rx: self.tx.subscribe(),
}
}
pub fn subscriber_count(&self) -> usize {
self.tx.receiver_count()
}
}
pub struct SnapshotReader<S: ActorMsg + Sync> {
rx: watch::Receiver<Arc<S>>,
}
impl<S: ActorMsg + Sync> SnapshotReader<S> {
pub async fn changed(&mut self) -> bool {
self.rx.changed().await.is_ok()
}
pub fn get(&mut self) -> Arc<S> {
self.rx.borrow_and_update().clone()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn topic_fans_out_to_all_subscribers() {
let topic: Topic<u32> = Topic::new(8);
let mut a = topic.subscribe();
let mut b = topic.subscribe();
assert_eq!(topic.publish(42), 2);
assert_eq!(&*a.recv().await.unwrap(), &42);
assert_eq!(&*b.recv().await.unwrap(), &42);
}
#[test]
fn publish_without_subscribers_returns_zero() {
let topic: Topic<u32> = Topic::new(4);
assert_eq!(topic.publish(1), 0, "无订阅者:发布返回 0");
assert_eq!(
topic.publish_shared(Arc::new(2)),
0,
"已装箱路径同语义(调用方自行装箱)"
);
}
#[tokio::test]
async fn slow_reader_skips_to_latest() {
let topic: Topic<u32> = Topic::new(2);
let mut slow = topic.subscribe();
for i in 0..10 {
topic.publish(i);
}
let got = slow.recv().await.unwrap();
assert!(slow.lagged_count() > 0);
assert!(*got >= 6);
let mut fresh = topic.subscribe();
topic.publish(99);
assert_eq!(&*fresh.recv().await.unwrap(), &99);
}
#[tokio::test]
async fn snapshot_always_latest() {
let snap = SnapshotTopic::new(vec![1u8]);
let mut reader = snap.subscribe();
snap.update(vec![2u8]);
snap.update(vec![3u8]);
assert_eq!(*snap.latest(), vec![3u8]);
assert!(reader.changed().await);
assert_eq!(*reader.get(), vec![3u8]);
}
#[tokio::test]
async fn snapshot_update_without_subscribers_is_retained() {
let snap = SnapshotTopic::new(vec![1u8]);
assert_eq!(snap.update(vec![2u8]), 0, "无订阅者:返回 0(但仍须落库)");
assert_eq!(*snap.latest(), vec![2u8], "无订阅者的 update 必须落库");
let mut late = snap.subscribe();
assert_eq!(*late.get(), vec![2u8], "后加入订阅者不得看到过期快照");
drop(late);
assert_eq!(snap.update_shared(Arc::new(vec![3u8])), 0);
assert_eq!(*snap.latest(), vec![3u8], "订阅者断开后 update 必须落库");
let mut reader = snap.subscribe();
snap.update(vec![4u8]);
assert!(reader.changed().await);
assert_eq!(*reader.get(), vec![4u8]);
}
#[tokio::test]
async fn subscriber_distinguishes_empty_from_closed() {
let topic: Topic<u32> = Topic::new(4);
let mut sub = topic.subscribe();
assert!(sub.try_recv().is_none(), "空主题:非阻塞接收返回 None");
assert!(!sub.is_closed(), "空而未关闭:is_closed 必须为 false");
drop(topic);
assert!(sub.try_recv().is_none(), "已关闭:非阻塞接收返回 None");
assert!(sub.is_closed(), "发布者全部消失后必须可识别关闭");
assert!(sub.recv().await.is_none(), "异步接收同样返回 None");
assert!(sub.is_closed());
}
}