Skip to main content

tuwunel_service/pusher/
notification.rs

1use std::{collections::BTreeMap, fmt::Debug};
2
3use futures::{StreamExt, future::join3, stream::select};
4use ruma::{EventId, OwnedEventId, RoomId, UserId, events::receipt::ReceiptThread};
5use serde::Serialize;
6use tuwunel_core::{
7	Error, Result, implement, trace,
8	utils::{
9		bytes::{escape_bytes, u64_from_bytes},
10		stream::{BroadbandExt, ReadyExt, TryIgnore},
11	},
12	warn,
13};
14use tuwunel_database::{
15	Deserialized, Ignore, IgnoreAll, Interfix, KeyBuf, deserialize_from_slice as deserialize_key,
16};
17use tuwunel_matrix::Event;
18
19/// Per-thread unread counts: `(notification, highlight)` keyed by thread root.
20type ThreadCounts = BTreeMap<OwnedEventId, (u64, u64)>;
21
22/// Per-thread last-read counts keyed by thread root.
23///
24/// Sync compares each count against its window to tell whether a thread's zero
25/// is news to the client.
26type ThreadLastReads = BTreeMap<OwnedEventId, u64>;
27
28/// Reset the room's main-timeline notification counts.
29///
30/// The last-read stamp gates sync output; callers dispatch the badge refresh
31/// after every reset.
32#[implement(super::Service)]
33#[tracing::instrument(level = "debug", skip(self))]
34pub async fn reset_notification_counts(&self, user_id: &UserId, room_id: &RoomId) {
35	let count = self.services.globals.next_count();
36
37	let userroom_id = (user_id, room_id);
38
39	self.reset_notification_count(room_id, user_id, userroom_id)
40		.await;
41
42	self.db
43		.userroomid_highlightcount
44		.put(userroom_id, 0_u64);
45
46	let roomuser_id = (room_id, user_id);
47	self.db
48		.roomuserid_lastnotificationread
49		.put(roomuser_id, *count);
50
51	let removed = self.clear_suppressed_room(user_id, room_id);
52	if removed > 0 {
53		trace!(?user_id, ?room_id, removed, "Cleared suppressed push events after read");
54	}
55}
56
57#[implement(super::Service)]
58async fn reset_notification_count<K>(&self, room_id: &RoomId, user_id: &UserId, key: K)
59where
60	K: Serialize + Debug + Send + Sync,
61{
62	// The increment path is a read-modify-write under this lock; an unlocked
63	// zero could land inside it and be overwritten by the stale sum.
64	let _lock = self
65		.notification_increment_mutex
66		.lock(&(room_id.to_owned(), user_id.to_owned()))
67		.await;
68
69	self.db
70		.userroomid_notificationcount
71		.put(key, 0_u64);
72}
73
74/// Reset counts for a single thread within a room.
75///
76/// The last-read stamp gates sync output.
77#[implement(super::Service)]
78#[tracing::instrument(level = "debug", skip(self))]
79pub async fn reset_thread_notification_counts(
80	&self,
81	user_id: &UserId,
82	room_id: &RoomId,
83	thread_root: &EventId,
84) {
85	let count = self.services.globals.next_count();
86
87	let userroom_thread = (user_id, room_id, thread_root);
88
89	self.reset_notification_count(room_id, user_id, userroom_thread)
90		.await;
91
92	self.db
93		.userroomid_highlightcount
94		.put(userroom_thread, 0_u64);
95
96	let roomuser_thread = (room_id, user_id, thread_root);
97	self.db
98		.roomuserid_lastnotificationread
99		.put(roomuser_thread, *count);
100}
101
102/// Clear all per-thread notification state for this user and room.
103///
104/// The `Interfix` prefix excludes the main row. The notification-count sweep
105/// runs under the increment mutex so a concurrent read-modify-write cannot
106/// resurrect a cleared row.
107#[implement(super::Service)]
108#[tracing::instrument(level = "debug", skip(self))]
109pub async fn clear_all_thread_notification_counts(&self, user_id: &UserId, room_id: &RoomId) {
110	let userroom_prefix = (user_id, room_id, Interfix);
111	let roomuser_prefix = (room_id, user_id, Interfix);
112
113	let highlights = self
114		.db
115		.userroomid_highlightcount
116		.del_prefix(&userroom_prefix);
117
118	let last_reads = self
119		.db
120		.roomuserid_lastnotificationread
121		.del_prefix(&roomuser_prefix);
122
123	let notifications = async {
124		let _lock = self
125			.notification_increment_mutex
126			.lock(&(room_id.to_owned(), user_id.to_owned()))
127			.await;
128
129		self.db
130			.userroomid_notificationcount
131			.del_prefix(&userroom_prefix)
132			.await;
133	};
134
135	join3(notifications, highlights, last_reads).await;
136}
137
138/// Dispatcher: route a receipt's `ReceiptThread` to the matching reset path.
139///
140/// `Unthreaded` clears all room and thread counts; `Main` clears only the
141/// main-timeline counts; `Thread(id)` clears just that thread unless the
142/// acknowledged event is the thread root. `None` denotes a non-receipt reset.
143#[implement(super::Service)]
144pub async fn reset_notification_counts_for_thread(
145	&self,
146	user_id: &UserId,
147	room_id: &RoomId,
148	acknowledged: Option<&EventId>,
149	thread: &ReceiptThread,
150) {
151	match thread {
152		| ReceiptThread::Thread(root) if acknowledged == Some(root) => {},
153		| ReceiptThread::Main =>
154			self.reset_notification_counts(user_id, room_id)
155				.await,
156		| ReceiptThread::Thread(root) =>
157			self.reset_thread_notification_counts(user_id, room_id, root)
158				.await,
159		| _ => {
160			self.reset_notification_counts(user_id, room_id)
161				.await;
162
163			self.clear_all_thread_notification_counts(user_id, room_id)
164				.await;
165		},
166	}
167}
168
169#[implement(super::Service)]
170#[tracing::instrument(level = "debug", skip(self), ret(level = "trace"))]
171pub async fn notification_count(&self, user_id: &UserId, room_id: &RoomId) -> u64 {
172	let key = (user_id, room_id);
173	self.db
174		.userroomid_notificationcount
175		.qry(&key)
176		.await
177		.deserialized()
178		.unwrap_or(0)
179}
180
181/// Return the user's account-wide unread notification count.
182///
183/// Joined main and thread rows contribute to a saturating total. A row whose
184/// key or count cannot be read is logged and contributes nothing.
185#[implement(super::Service)]
186#[tracing::instrument(level = "trace", skip(self), ret)]
187pub async fn global_notification_count(&self, user_id: &UserId) -> u64 {
188	self.db
189		.userroomid_notificationcount
190		.stream_prefix_raw(&(user_id, Interfix))
191		.ignore_err()
192		.ready_filter_map(|(key, count)| {
193			let count = u64_from_bytes(count)
194				.inspect_err(|error| warn_unreadable(key, error))
195				.ok()?;
196
197			count.gt(&0).then(|| (KeyBuf::from(key), count))
198		})
199		.broad_filter_map(async |(key, count)| {
200			let (_, room_id, _): (Ignore, &RoomId, IgnoreAll) = deserialize_key(&key)
201				.inspect_err(|error| warn_unreadable(&key, error))
202				.ok()?;
203
204			self.services
205				.state_cache
206				.is_joined(user_id, room_id)
207				.await
208				.then_some(count)
209		})
210		.ready_fold(0_u64, u64::saturating_add)
211		.await
212}
213
214fn warn_unreadable(key: &[u8], error: &Error) {
215	// Stock release builds strip `debug_warn!`, and nothing else would show this row.
216	warn!(key = %escape_bytes(key), %error, "Skipping unreadable notification count.");
217}
218
219#[implement(super::Service)]
220#[tracing::instrument(level = "debug", skip(self), ret(level = "trace"))]
221pub async fn highlight_count(&self, user_id: &UserId, room_id: &RoomId) -> u64 {
222	let key = (user_id, room_id);
223	self.db
224		.userroomid_highlightcount
225		.qry(&key)
226		.await
227		.deserialized()
228		.unwrap_or(0)
229}
230
231/// Per-thread `(notification, highlight)` counts for one room and user.
232/// `Interfix` excludes the legacy 2-tuple main row from the scan; only
233/// 3-tuple `(user, room, root)` rows match.
234#[implement(super::Service)]
235#[tracing::instrument(level = "debug", skip(self))]
236pub async fn thread_notification_counts(
237	&self,
238	user_id: &UserId,
239	room_id: &RoomId,
240) -> ThreadCounts {
241	let prefix = (user_id, room_id, Interfix);
242	let notifications = self
243		.db
244		.userroomid_notificationcount
245		.stream_prefix(&prefix)
246		.ignore_err()
247		.map(notification_kv);
248
249	let highlights = self
250		.db
251		.userroomid_highlightcount
252		.stream_prefix(&prefix)
253		.ignore_err()
254		.map(highlight_kv);
255
256	select(notifications, highlights)
257		.ready_fold(ThreadCounts::default(), merge_thread_count)
258		.await
259}
260
261fn notification_kv(
262	(key, notifications): ((&UserId, &RoomId, OwnedEventId), u64),
263) -> (OwnedEventId, (u64, u64)) {
264	(key.2, (notifications, 0))
265}
266
267fn highlight_kv(
268	(key, highlights): ((&UserId, &RoomId, OwnedEventId), u64),
269) -> (OwnedEventId, (u64, u64)) {
270	(key.2, (0, highlights))
271}
272
273fn merge_thread_count(
274	mut counts: ThreadCounts,
275	(root, (notifications, highlights)): (OwnedEventId, (u64, u64)),
276) -> ThreadCounts {
277	let entry = counts.entry(root).or_default();
278	entry.0 = entry.0.saturating_add(notifications);
279	entry.1 = entry.1.saturating_add(highlights);
280	counts
281}
282
283/// Whether the user has read past one notified event.
284///
285/// The room's main watermark covers every notification up to it, and a
286/// notification in a thread is also read once that thread's watermark passes
287/// it. `count` is the event's position, comparable with both.
288#[implement(super::Service)]
289#[tracing::instrument(
290	level = "debug",
291	skip(self, event),
292	fields(
293		event_id = %event.event_id(),
294	),
295)]
296pub async fn notification_read<E>(&self, user_id: &UserId, event: &E, count: u64) -> bool
297where
298	E: Event,
299{
300	let room_id = event.room_id();
301	let read_past = |last_read: Result<u64>| last_read.is_ok_and(|last_read| last_read >= count);
302
303	let main_read = self
304		.last_notification_read(user_id, room_id)
305		.await;
306
307	if read_past(main_read) {
308		return true;
309	}
310
311	let Some(thread_root) = self.services.threads.get_thread_id(event).await else {
312		return false;
313	};
314
315	let thread_read = self
316		.last_thread_notification_read(user_id, room_id, &thread_root)
317		.await;
318
319	read_past(thread_read)
320}
321
322#[implement(super::Service)]
323#[tracing::instrument(level = "debug", skip(self), ret(level = "trace"))]
324pub async fn last_notification_read(&self, user_id: &UserId, room_id: &RoomId) -> Result<u64> {
325	let key = (room_id, user_id);
326	self.db
327		.roomuserid_lastnotificationread
328		.qry(&key)
329		.await
330		.deserialized()
331}
332
333/// Read the last notification watermark for one thread.
334///
335/// Uses the same room, user and thread key as thread count resets.
336#[implement(super::Service)]
337#[tracing::instrument(level = "debug", skip(self), ret(level = "trace"))]
338pub async fn last_thread_notification_read(
339	&self,
340	user_id: &UserId,
341	room_id: &RoomId,
342	thread_root: &EventId,
343) -> Result<u64> {
344	let key = (room_id, user_id, thread_root);
345
346	self.db
347		.roomuserid_lastnotificationread
348		.qry(&key)
349		.await
350		.deserialized()
351}
352
353/// Per-thread last-read counts for one room and user. `Interfix` keeps the
354/// scan to 3-tuple `(room, user, root)` rows; the legacy 2-tuple main row
355/// is excluded by construction and lives behind `last_notification_read`.
356#[implement(super::Service)]
357#[tracing::instrument(level = "debug", skip(self))]
358pub async fn thread_last_notification_reads(
359	&self,
360	user_id: &UserId,
361	room_id: &RoomId,
362) -> ThreadLastReads {
363	let prefix = (room_id, user_id, Interfix);
364	self.db
365		.roomuserid_lastnotificationread
366		.stream_prefix(&prefix)
367		.ignore_err()
368		.map(|((_, _, root), count): ((Ignore, Ignore, OwnedEventId), u64)| (root, count))
369		.collect()
370		.await
371}
372
373#[implement(super::Service)]
374pub async fn delete_room_notification_read(&self, room_id: &RoomId) -> Result {
375	let key = (room_id, Interfix);
376	self.db
377		.roomuserid_lastnotificationread
378		.keys_prefix_raw(&key)
379		.ignore_err()
380		.ready_for_each(|key| {
381			trace!("Removing key: {key:?}");
382			self.db
383				.roomuserid_lastnotificationread
384				.remove(key);
385		})
386		.await;
387
388	Ok(())
389}