1use crate::msg::ActorMsg;
11use std::sync::Arc;
12use tokio::sync::{broadcast, watch};
13
14#[derive(Debug, Clone)]
20pub struct Topic<T: ActorMsg + Sync> {
21 tx: broadcast::Sender<Arc<T>>,
22}
23
24impl<T: ActorMsg + Sync> Topic<T> {
25 pub fn new(capacity: usize) -> Self {
27 let (tx, _) = broadcast::channel(capacity.max(1));
28 Self { tx }
29 }
30
31 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 pub fn publish_shared(&self, msg: Arc<T>) -> usize {
44 self.tx.send(msg).unwrap_or(0)
45 }
46
47 pub fn subscribe(&self) -> Subscriber<T> {
49 Subscriber {
50 rx: self.tx.subscribe(),
51 lagged: 0,
52 closed: false,
53 }
54 }
55
56 pub fn subscriber_count(&self) -> usize {
58 self.tx.receiver_count()
59 }
60}
61
62pub struct Subscriber<T: ActorMsg + Sync> {
64 rx: broadcast::Receiver<Arc<T>>,
65 lagged: u64,
66 closed: bool,
70}
71
72impl<T: ActorMsg + Sync> Subscriber<T> {
73 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 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 pub fn is_closed(&self) -> bool {
118 self.closed
119 }
120
121 pub fn lagged_count(&self) -> u64 {
123 self.lagged
124 }
125}
126
127#[derive(Debug, Clone)]
132pub struct SnapshotTopic<S: ActorMsg + Sync> {
133 tx: watch::Sender<Arc<S>>,
134}
135
136impl<S: ActorMsg + Sync> SnapshotTopic<S> {
137 pub fn new(initial: S) -> Self {
139 Self {
140 tx: watch::channel(Arc::new(initial)).0,
141 }
142 }
143
144 pub fn update(&self, snapshot: S) -> usize {
149 self.update_shared(Arc::new(snapshot))
150 }
151
152 pub fn update_shared(&self, snapshot: Arc<S>) -> usize {
156 let _ = self.tx.send_replace(snapshot);
159 self.tx.receiver_count()
160 }
161
162 pub fn latest(&self) -> Arc<S> {
164 self.tx.borrow().clone()
165 }
166
167 pub fn subscribe(&self) -> SnapshotReader<S> {
169 SnapshotReader {
170 rx: self.tx.subscribe(),
171 }
172 }
173
174 pub fn subscriber_count(&self) -> usize {
176 self.tx.receiver_count()
177 }
178}
179
180pub struct SnapshotReader<S: ActorMsg + Sync> {
182 rx: watch::Receiver<Arc<S>>,
183}
184
185impl<S: ActorMsg + Sync> SnapshotReader<S> {
186 pub async fn changed(&mut self) -> bool {
188 self.rx.changed().await.is_ok()
189 }
190
191 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 #[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 let got = slow.recv().await.unwrap();
232 assert!(slow.lagged_count() > 0);
233 assert!(*got >= 6);
234 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 #[tokio::test]
258 async fn snapshot_update_without_subscribers_is_retained() {
259 let snap = SnapshotTopic::new(vec![1u8]);
260 assert_eq!(snap.update(vec![2u8]), 0, "无订阅者:返回 0(但仍须落库)");
262 assert_eq!(*snap.latest(), vec![2u8], "无订阅者的 update 必须落库");
263
264 let mut late = snap.subscribe();
266 assert_eq!(*late.get(), vec![2u8], "后加入订阅者不得看到过期快照");
267
268 drop(late);
270 assert_eq!(snap.update_shared(Arc::new(vec![3u8])), 0);
271 assert_eq!(*snap.latest(), vec![3u8], "订阅者断开后 update 必须落库");
272
273 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 #[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}