forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

notify_hub.rs204 lines, 6.7 KiBHistoryRawDownload
1//! Live unread counts for the bell. [`NotifyHub`] keeps one `watch` channel per signed-in user who
2//! has an open `GET /notifications/stream`. A write that changes a user's inbox publishes the new
3//! count, and each open stream of that user sends it. Nothing polls: a stream waits on its channel.
4//! The hub is in-process only, so a second server process would not see the change.
5//!
6//! A channel with no receivers left is removed, so the map holds only users who are connected.
7
8use std::collections::HashMap;
9use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
10
11use tokio::sync::watch;
12
13use crate::live::Topic;
14use crate::state::AppState;
15
16/// The users with an open stream, each with the channel that carries its unread count.
17pub struct NotifyHub {
18 users: Mutex<HashMap<String, watch::Sender<u64>>>,
19 /// Set once on server shutdown. Every open stream ends when it sees this.
20 closing: watch::Sender<bool>,
21}
22
23impl NotifyHub {
24 pub fn new() -> Self {
25 Self {
26 users: Mutex::new(HashMap::new()),
27 closing: watch::channel(false).0,
28 }
29 }
30
31 fn users(&self) -> MutexGuard<'_, HashMap<String, watch::Sender<u64>>> {
32 self.users.lock().unwrap_or_else(PoisonError::into_inner)
33 }
34
35 /// Opens a subscription to the counts published for `user_id`. The first count is not sent
36 /// here: the caller reads it from the store after subscribing, so a change in between is
37 /// seen by the subscription and sent again rather than lost.
38 pub fn subscribe(self: &Arc<Self>, user_id: &str) -> Subscription {
39 let rx = self
40 .users()
41 .entry(user_id.to_owned())
42 .or_insert_with(|| watch::channel(0).0)
43 .subscribe();
44 Subscription {
45 rx: Some(rx),
46 closing: self.closing.subscribe(),
47 hub: Arc::clone(self),
48 user_id: user_id.to_owned(),
49 }
50 }
51
52 /// True when `user_id` has an open stream. A write skips the count query for anyone else.
53 pub fn is_watched(&self, user_id: &str) -> bool {
54 self.users()
55 .get(user_id)
56 .is_some_and(|tx| tx.receiver_count() > 0)
57 }
58
59 /// Sends `count` to every open stream of `user_id`. Drops the channel when none is left.
60 pub fn publish(&self, user_id: &str, count: u64) {
61 let mut users = self.users();
62 let Some(tx) = users.get(user_id) else {
63 return;
64 };
65 if tx.receiver_count() == 0 {
66 users.remove(user_id);
67 return;
68 }
69 tx.send_replace(count);
70 }
71
72 /// Ends every open stream. Called once when the server shuts down.
73 pub fn close(&self) {
74 self.closing.send_replace(true);
75 }
76
77 /// Removes the user's channel once its last subscription is gone.
78 fn release(&self, user_id: &str) {
79 let mut users = self.users();
80 if users
81 .get(user_id)
82 .is_some_and(|tx| tx.receiver_count() == 0)
83 {
84 users.remove(user_id);
85 }
86 }
87}
88
89/// One open stream's view of its user's count. Dropping it releases the user's channel when no
90/// other stream of that user is open.
91pub struct Subscription {
92 /// Taken in `drop` before the hub is told, so the hub counts this receiver as gone.
93 rx: Option<watch::Receiver<u64>>,
94 closing: watch::Receiver<bool>,
95 hub: Arc<NotifyHub>,
96 user_id: String,
97}
98
99impl Subscription {
100 /// Waits for the next published count. `None` once the hub is closing (server shutdown).
101 pub async fn next_count(&mut self) -> Option<u64> {
102 loop {
103 if *self.closing.borrow() {
104 return None;
105 }
106 let rx = self.rx.as_mut()?;
107 tokio::select! {
108 changed = rx.changed() => {
109 changed.ok()?;
110 return Some(*rx.borrow_and_update());
111 }
112 changed = self.closing.changed() => {
113 changed.ok()?;
114 }
115 }
116 }
117 }
118}
119
120impl Drop for Subscription {
121 fn drop(&mut self) {
122 self.rx = None;
123 self.hub.release(&self.user_id);
124 }
125}
126
127/// Publishes `user_id`'s current unread count to that user's open streams, and wakes the inbox
128/// page's live stream. Call it after a write that changes the inbox. Skips the count query when
129/// nobody is listening. Never fails: problems are logged.
130pub async fn publish_unread(state: &AppState, user_id: &str) {
131 state.live.bump(&Topic::Inbox(user_id.to_owned()));
132 if !state.notify_hub.is_watched(user_id) {
133 return;
134 }
135 match state.store.unread_count(user_id).await {
136 Ok(count) => state.notify_hub.publish(user_id, count),
137 Err(e) => tracing::error!(error = %e, user_id, "notify: unread count failed"),
138 }
139}
140
141#[cfg(test)]
142mod tests {
143 use std::time::Duration;
144
145 use super::*;
146
147 #[tokio::test]
148 async fn publish_reaches_the_subscriber_of_that_user_only() {
149 let hub = Arc::new(NotifyHub::new());
150 let mut tahinli = hub.subscribe("tahinli");
151 let mut bob = hub.subscribe("bob");
152
153 hub.publish("tahinli", 3);
154 assert_eq!(tahinli.next_count().await, Some(3));
155
156 // Bob heard nothing: his wait times out.
157 let quiet = tokio::time::timeout(Duration::from_millis(50), bob.next_count()).await;
158 assert!(quiet.is_err());
159 }
160
161 #[tokio::test]
162 async fn publish_without_subscribers_is_a_no_op_and_nothing_is_kept() {
163 let hub = Arc::new(NotifyHub::new());
164 assert!(!hub.is_watched("tahinli"));
165 hub.publish("tahinli", 1);
166 assert!(!hub.is_watched("tahinli"));
167 assert!(hub.users().is_empty());
168 }
169
170 #[tokio::test]
171 async fn the_channel_is_released_when_the_last_subscription_drops() {
172 let hub = Arc::new(NotifyHub::new());
173 let first = hub.subscribe("tahinli");
174 let second = hub.subscribe("tahinli");
175 assert!(hub.is_watched("tahinli"));
176
177 drop(first);
178 assert!(hub.is_watched("tahinli"));
179
180 drop(second);
181 assert!(!hub.is_watched("tahinli"));
182 assert!(hub.users().is_empty());
183 }
184
185 #[tokio::test]
186 async fn every_open_stream_of_a_user_gets_the_count() {
187 let hub = Arc::new(NotifyHub::new());
188 let mut tab_one = hub.subscribe("tahinli");
189 let mut tab_two = hub.subscribe("tahinli");
190
191 hub.publish("tahinli", 5);
192 assert_eq!(tab_one.next_count().await, Some(5));
193 assert_eq!(tab_two.next_count().await, Some(5));
194 }
195
196 #[tokio::test]
197 async fn close_ends_every_subscription() {
198 let hub = Arc::new(NotifyHub::new());
199 let mut sub = hub.subscribe("tahinli");
200
201 hub.close();
202 assert_eq!(sub.next_count().await, None);
203 }
204}