Skip to main content

wordval_actor/
topic.rs

1//! Topic —— 广播扇出与快照拉取(多机集群 HUD 场景)。
2//!
3//! 两种一写多读原语:
4//! - [`Topic<T>`]:事件广播(tokio::broadcast),每个订阅者独立游标;
5//!   慢读者积压溢出时**自动跳到最新**(只统计 lagged,不报错),
6//!   符合"宁可错过旧事件,不可阻塞生产者"的取舍。
7//! - [`SnapshotTopic<S>`]:覆盖式快照(watch + `Arc<S>`),读者永远
8//!   拿到最新状态,零拷贝共享同一份快照 —— 机队 HUD 刷新用。
9
10use crate::msg::ActorMsg;
11use std::sync::Arc;
12use tokio::sync::{broadcast, watch};
13
14// 注意:本模块所有类型的元素以 `Arc<T>` 跨线程共享(broadcast/watch 的
15// auto-trait 传播),因此 `T` 必须额外满足 `Sync` —— 这是 `ActorMsg`
16// 只要求 `Send` 之后仍需在此保留的收紧 bound,勿删。
17
18/// 广播主题 —— 创建者即发布者,可自由克隆共享给多个生产者。
19#[derive(Debug, Clone)]
20pub struct Topic<T: ActorMsg + Sync> {
21    tx: broadcast::Sender<Arc<T>>,
22}
23
24impl<T: ActorMsg + Sync> Topic<T> {
25    /// 以给定缓冲容量创建主题(溢出语义见模块注释)。
26    pub fn new(capacity: usize) -> Self {
27        let (tx, _) = broadcast::channel(capacity.max(1));
28        Self { tx }
29    }
30
31    /// 发布一条事件(内部 Arc 包装供各订阅者共享)。
32    ///
33    /// 返回当前活跃订阅者数量;无订阅者时消息直接丢弃、
34    /// 不做 Arc 包装(空转发布路径零分配)。
35    pub fn publish(&self, msg: T) -> usize {
36        if self.tx.receiver_count() == 0 {
37            return 0;
38        }
39        self.publish_shared(Arc::new(msg))
40    }
41
42    /// 发布已 Arc 包装的事件(多主题转发时避免重复装箱)。
43    pub fn publish_shared(&self, msg: Arc<T>) -> usize {
44        self.tx.send(msg).unwrap_or(0)
45    }
46
47    /// 新增订阅者,从当前游标开始接收。
48    pub fn subscribe(&self) -> Subscriber<T> {
49        Subscriber {
50            rx: self.tx.subscribe(),
51            lagged: 0,
52            closed: false,
53        }
54    }
55
56    /// 当前活跃订阅者数量。
57    pub fn subscriber_count(&self) -> usize {
58        self.tx.receiver_count()
59    }
60}
61
62/// 主题订阅者(独占游标,不可跨任务克隆使用)。
63pub struct Subscriber<T: ActorMsg + Sync> {
64    rx: broadcast::Receiver<Arc<T>>,
65    lagged: u64,
66    /// 已观察到主题关闭([`recv`](Self::recv) /
67    /// [`try_recv`](Self::try_recv) 返回 None 后置位)。
68    /// 惰性更新:仅在接收路径观测到 `Closed` 时置位,非实时探测。
69    closed: bool,
70}
71
72impl<T: ActorMsg + Sync> Subscriber<T> {
73    /// 异步接收下一条事件;溢出时自动跳帧后继续等待。
74    ///
75    /// 仅当主题所有发布者都已放弃(drop)且缓冲耗尽时返回 `None`
76    /// (此后 [`is_closed`](Self::is_closed) 为 true)。
77    pub async fn recv(&mut self) -> Option<Arc<T>> {
78        loop {
79            match self.rx.recv().await {
80                Ok(msg) => return Some(msg),
81                Err(broadcast::error::RecvError::Lagged(n)) => {
82                    self.lagged += n;
83                    tracing::debug!(skipped = n, "Topic 订阅者积压溢出,已跳到最新");
84                    continue;
85                }
86                Err(broadcast::error::RecvError::Closed) => {
87                    self.closed = true;
88                    return None;
89                }
90            }
91        }
92    }
93
94    /// 非阻塞接收(溢出同样跳帧处理)。
95    ///
96    /// 返回 `None` 有两种含义 —— 暂无消息(通道仍开放)或主题已关闭;
97    /// 以 [`is_closed`](Self::is_closed) 区分。
98    pub fn try_recv(&mut self) -> Option<Arc<T>> {
99        loop {
100            match self.rx.try_recv() {
101                Ok(msg) => return Some(msg),
102                Err(broadcast::error::TryRecvError::Lagged(n)) => {
103                    self.lagged += n;
104                    continue;
105                }
106                Err(broadcast::error::TryRecvError::Closed) => {
107                    self.closed = true;
108                    return None;
109                }
110                Err(broadcast::error::TryRecvError::Empty) => return None,
111            }
112        }
113    }
114
115    /// 主题是否已关闭(全部发布者已 drop)。由接收路径惰性置位:
116    /// 未调用过 `recv`/`try_recv` 或尚未观测到关闭时为 `false`。
117    pub fn is_closed(&self) -> bool {
118        self.closed
119    }
120
121    /// 累计因积压被跳过的消息数(HUD 诊断"丢帧计数")。
122    pub fn lagged_count(&self) -> u64 {
123        self.lagged
124    }
125}
126
127/// 快照主题 —— 覆盖式最新值 + `Arc` 零拷贝读。
128///
129/// 与 [`Topic`] 的区别:无事件序列语义,读者只关心"现在是什么样"
130/// (如全机队状态表),写入即覆盖,读取永不阻塞、永不积压。
131#[derive(Debug, Clone)]
132pub struct SnapshotTopic<S: ActorMsg + Sync> {
133    tx: watch::Sender<Arc<S>>,
134}
135
136impl<S: ActorMsg + Sync> SnapshotTopic<S> {
137    /// 以初始快照创建主题。
138    pub fn new(initial: S) -> Self {
139        Self {
140            tx: watch::channel(Arc::new(initial)).0,
141        }
142    }
143
144    /// 覆盖写入新快照,返回订阅者数量。
145    ///
146    /// 无订阅者时快照同样落库 —— 快照语义是"当前状态",与有无读者无关
147    /// (后加入的订阅者与 [`latest`](Self::latest) 都必须看到最新值)。
148    pub fn update(&self, snapshot: S) -> usize {
149        self.update_shared(Arc::new(snapshot))
150    }
151
152    /// 覆盖写入已 Arc 包装的快照,返回订阅者数量。
153    ///
154    /// 与 [`Topic::publish`] 的零订阅丢弃语义**不同**:快照必须落库。
155    pub fn update_shared(&self, snapshot: Arc<S>) -> usize {
156        // 必须 send_replace:watch::Sender::send 在 receiver_count()==0 时
157        // 返回 Err 且不存储值,会把零订阅期的更新静默丢掉。
158        let _ = self.tx.send_replace(snapshot);
159        self.tx.receiver_count()
160    }
161
162    /// 立即读取当前快照(无需订阅,Arc 克隆零拷贝)。
163    pub fn latest(&self) -> Arc<S> {
164        self.tx.borrow().clone()
165    }
166
167    /// 新增变更订阅者(持有快照游标,可 `changed().await` 等变更)。
168    pub fn subscribe(&self) -> SnapshotReader<S> {
169        SnapshotReader {
170            rx: self.tx.subscribe(),
171        }
172    }
173
174    /// 当前活跃订阅者数量。
175    pub fn subscriber_count(&self) -> usize {
176        self.tx.receiver_count()
177    }
178}
179
180/// 快照订阅者 —— 每次读取都拿"写后最新",中间版本自然跳过。
181pub struct SnapshotReader<S: ActorMsg + Sync> {
182    rx: watch::Receiver<Arc<S>>,
183}
184
185impl<S: ActorMsg + Sync> SnapshotReader<S> {
186    /// 等待下一次快照更新;所有写端 drop 后返回 false。
187    pub async fn changed(&mut self) -> bool {
188        self.rx.changed().await.is_ok()
189    }
190
191    /// 读取当前快照并标记已见。
192    pub fn get(&mut self) -> Arc<S> {
193        self.rx.borrow_and_update().clone()
194    }
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200
201    #[tokio::test]
202    async fn topic_fans_out_to_all_subscribers() {
203        let topic: Topic<u32> = Topic::new(8);
204        let mut a = topic.subscribe();
205        let mut b = topic.subscribe();
206        assert_eq!(topic.publish(42), 2);
207        assert_eq!(&*a.recv().await.unwrap(), &42);
208        assert_eq!(&*b.recv().await.unwrap(), &42);
209    }
210
211    /// 零订阅发布短路:返回 0(无接收方),不改变既有丢弃语义。
212    #[test]
213    fn publish_without_subscribers_returns_zero() {
214        let topic: Topic<u32> = Topic::new(4);
215        assert_eq!(topic.publish(1), 0, "无订阅者:发布返回 0");
216        assert_eq!(
217            topic.publish_shared(Arc::new(2)),
218            0,
219            "已装箱路径同语义(调用方自行装箱)"
220        );
221    }
222
223    #[tokio::test]
224    async fn slow_reader_skips_to_latest() {
225        let topic: Topic<u32> = Topic::new(2);
226        let mut slow = topic.subscribe();
227        for i in 0..10 {
228            topic.publish(i);
229        }
230        // 慢读者溢出:跳帧后仍能收到缓冲内最新消息,且 lagged 有统计
231        let got = slow.recv().await.unwrap();
232        assert!(slow.lagged_count() > 0);
233        assert!(*got >= 6);
234        // 新订阅者从当前游标起步,只收到后续发布
235        let mut fresh = topic.subscribe();
236        topic.publish(99);
237        assert_eq!(&*fresh.recv().await.unwrap(), &99);
238    }
239
240    #[tokio::test]
241    async fn snapshot_always_latest() {
242        let snap = SnapshotTopic::new(vec![1u8]);
243        let mut reader = snap.subscribe();
244        snap.update(vec![2u8]);
245        snap.update(vec![3u8]);
246        assert_eq!(*snap.latest(), vec![3u8]);
247        assert!(reader.changed().await);
248        assert_eq!(*reader.get(), vec![3u8]);
249    }
250
251    /// 回归:零订阅者时快照必须落库。
252    ///
253    /// 落库不得依赖订阅端存在(`watch::Sender::send` 在
254    /// `receiver_count()==0` 时返回 Err 且不存储值):零订阅期 /
255    /// 全部断开后的更新不得被静默丢弃,`latest()` 与后加入的
256    /// 订阅者都必须拿到最新快照。
257    #[tokio::test]
258    async fn snapshot_update_without_subscribers_is_retained() {
259        let snap = SnapshotTopic::new(vec![1u8]);
260        // 默认态即零订阅者
261        assert_eq!(snap.update(vec![2u8]), 0, "无订阅者:返回 0(但仍须落库)");
262        assert_eq!(*snap.latest(), vec![2u8], "无订阅者的 update 必须落库");
263
264        // 后加入的订阅者拿到当前最新快照,而非创建时的初始值
265        let mut late = snap.subscribe();
266        assert_eq!(*late.get(), vec![2u8], "后加入订阅者不得看到过期快照");
267
268        // 全部订阅者断开后同样必须落库
269        drop(late);
270        assert_eq!(snap.update_shared(Arc::new(vec![3u8])), 0);
271        assert_eq!(*snap.latest(), vec![3u8], "订阅者断开后 update 必须落库");
272
273        // 有订阅者时通知语义不变(回归覆盖)
274        let mut reader = snap.subscribe();
275        snap.update(vec![4u8]);
276        assert!(reader.changed().await);
277        assert_eq!(*reader.get(), vec![4u8]);
278    }
279
280    /// 空(未关闭)与关闭都可让 `try_recv` 返回 None;以 `is_closed` 区分。
281    #[tokio::test]
282    async fn subscriber_distinguishes_empty_from_closed() {
283        let topic: Topic<u32> = Topic::new(4);
284        let mut sub = topic.subscribe();
285        assert!(sub.try_recv().is_none(), "空主题:非阻塞接收返回 None");
286        assert!(!sub.is_closed(), "空而未关闭:is_closed 必须为 false");
287
288        drop(topic);
289        assert!(sub.try_recv().is_none(), "已关闭:非阻塞接收返回 None");
290        assert!(sub.is_closed(), "发布者全部消失后必须可识别关闭");
291        assert!(sub.recv().await.is_none(), "异步接收同样返回 None");
292        assert!(sub.is_closed());
293    }
294}