wordval-actor 1.0.5

Wordval actor system: high-performance message foundation for drone ground stations
Documentation
//! Topic —— 广播扇出与快照拉取(多机集群 HUD 场景)。
//!
//! 两种一写多读原语:
//! - [`Topic<T>`]:事件广播(tokio::broadcast),每个订阅者独立游标;
//!   慢读者积压溢出时**自动跳到最新**(只统计 lagged,不报错),
//!   符合"宁可错过旧事件,不可阻塞生产者"的取舍。
//! - [`SnapshotTopic<S>`]:覆盖式快照(watch + `Arc<S>`),读者永远
//!   拿到最新状态,零拷贝共享同一份快照 —— 机队 HUD 刷新用。

use crate::msg::ActorMsg;
use std::sync::Arc;
use tokio::sync::{broadcast, watch};

// 注意:本模块所有类型的元素以 `Arc<T>` 跨线程共享(broadcast/watch 的
// auto-trait 传播),因此 `T` 必须额外满足 `Sync` —— 这是 `ActorMsg`
// 只要求 `Send` 之后仍需在此保留的收紧 bound,勿删。

/// 广播主题 —— 创建者即发布者,可自由克隆共享给多个生产者。
#[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 }
    }

    /// 发布一条事件(内部 Arc 包装供各订阅者共享)。
    ///
    /// 返回当前活跃订阅者数量;无订阅者时消息直接丢弃、
    /// 不做 Arc 包装(空转发布路径零分配)。
    pub fn publish(&self, msg: T) -> usize {
        if self.tx.receiver_count() == 0 {
            return 0;
        }
        self.publish_shared(Arc::new(msg))
    }

    /// 发布已 Arc 包装的事件(多主题转发时避免重复装箱)。
    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,
    /// 已观察到主题关闭([`recv`](Self::recv) /
    /// [`try_recv`](Self::try_recv) 返回 None 后置位)。
    /// 惰性更新:仅在接收路径观测到 `Closed` 时置位,非实时探测。
    closed: bool,
}

impl<T: ActorMsg + Sync> Subscriber<T> {
    /// 异步接收下一条事件;溢出时自动跳帧后继续等待。
    ///
    /// 仅当主题所有发布者都已放弃(drop)且缓冲耗尽时返回 `None`
    /// (此后 [`is_closed`](Self::is_closed) 为 true)。
    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;
                }
            }
        }
    }

    /// 非阻塞接收(溢出同样跳帧处理)。
    ///
    /// 返回 `None` 有两种含义 —— 暂无消息(通道仍开放)或主题已关闭;
    /// 以 [`is_closed`](Self::is_closed) 区分。
    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,
            }
        }
    }

    /// 主题是否已关闭(全部发布者已 drop)。由接收路径惰性置位:
    /// 未调用过 `recv`/`try_recv` 或尚未观测到关闭时为 `false`。
    pub fn is_closed(&self) -> bool {
        self.closed
    }

    /// 累计因积压被跳过的消息数(HUD 诊断"丢帧计数")。
    pub fn lagged_count(&self) -> u64 {
        self.lagged
    }
}

/// 快照主题 —— 覆盖式最新值 + `Arc` 零拷贝读。
///
/// 与 [`Topic`] 的区别:无事件序列语义,读者只关心"现在是什么样"
/// (如全机队状态表),写入即覆盖,读取永不阻塞、永不积压。
#[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,
        }
    }

    /// 覆盖写入新快照,返回订阅者数量。
    ///
    /// 无订阅者时快照同样落库 —— 快照语义是"当前状态",与有无读者无关
    /// (后加入的订阅者与 [`latest`](Self::latest) 都必须看到最新值)。
    pub fn update(&self, snapshot: S) -> usize {
        self.update_shared(Arc::new(snapshot))
    }

    /// 覆盖写入已 Arc 包装的快照,返回订阅者数量。
    ///
    /// 与 [`Topic::publish`] 的零订阅丢弃语义**不同**:快照必须落库。
    pub fn update_shared(&self, snapshot: Arc<S>) -> usize {
        // 必须 send_replace:watch::Sender::send 在 receiver_count()==0 时
        // 返回 Err 且不存储值,会把零订阅期的更新静默丢掉。
        let _ = self.tx.send_replace(snapshot);
        self.tx.receiver_count()
    }

    /// 立即读取当前快照(无需订阅,Arc 克隆零拷贝)。
    pub fn latest(&self) -> Arc<S> {
        self.tx.borrow().clone()
    }

    /// 新增变更订阅者(持有快照游标,可 `changed().await` 等变更)。
    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> {
    /// 等待下一次快照更新;所有写端 drop 后返回 false。
    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);
    }

    /// 零订阅发布短路:返回 0(无接收方),不改变既有丢弃语义。
    #[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);
        }
        // 慢读者溢出:跳帧后仍能收到缓冲内最新消息,且 lagged 有统计
        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]);
    }

    /// 回归:零订阅者时快照必须落库。
    ///
    /// 落库不得依赖订阅端存在(`watch::Sender::send` 在
    /// `receiver_count()==0` 时返回 Err 且不存储值):零订阅期 /
    /// 全部断开后的更新不得被静默丢弃,`latest()` 与后加入的
    /// 订阅者都必须拿到最新快照。
    #[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]);
    }

    /// 空(未关闭)与关闭都可让 `try_recv` 返回 None;以 `is_closed` 区分。
    #[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());
    }
}