Skip to main content

tuwunel_service/pusher/
append.rs

1use std::{collections::HashSet, sync::Arc};
2
3use futures::{
4	FutureExt, Stream, StreamExt,
5	future::{join, join4},
6};
7use ruma::{
8	EventId, RoomId, UserId,
9	api::client::push::{ProfileTag, Pusher, PusherKind},
10	events::{
11		AnySyncTimelineEvent, TimelineEventType,
12		invite_permission_config::InvitePermission,
13		room::{member::MembershipState, power_levels::RoomPowerLevels},
14	},
15	push::{Action, Actions, HighlightTweakValue, Tweak},
16	serde::Raw,
17};
18use serde::{Deserialize, Serialize};
19use tracing::Level;
20use tuwunel_core::{
21	Result, implement, trace,
22	utils::{
23		BoolExt, ReadyExt, future::TryExtExt, option::OptionExt, result::ErrLog,
24		stream::TryIgnore, time::now_millis,
25	},
26};
27use tuwunel_database::{Deserialized, Ignore, Interfix, Json, Map, deserialize_from_slice};
28use tuwunel_matrix::{
29	event::Event,
30	pdu::{Count, Pdu, PduId, RawPduId},
31};
32
33use super::{Evaluate, RelatedEvents};
34use crate::rooms::short::ShortRoomId;
35
36/// Compact metadata stored for each notified event.
37///
38/// The database key supplies the user and PDU count. The stored `ShortRoomId`
39/// combines with that count to reconstruct the event's `PduId`.
40#[derive(Clone, Debug, Deserialize, Serialize)]
41pub struct Notified {
42	/// Milliseconds time at which the event notification was sent.
43	pub ts: u64,
44
45	/// ShortRoomId
46	pub sroomid: ShortRoomId,
47
48	/// The profile tag of the rule that matched this event.
49	#[serde(skip_serializing_if = "Option::is_none")]
50	pub tag: Option<ProfileTag>,
51
52	/// Actions vector
53	pub actions: Actions,
54}
55
56/// The values of one appended event shared by every recipient of it.
57///
58/// Each is resolved once per event and read once per recipient, so grouping
59/// them keeps the per-recipient call from growing an argument per lookup.
60#[derive(Clone, Copy)]
61struct Appended<'a> {
62	pdu_id: &'a RawPduId,
63	pdu: &'a Pdu,
64	power_levels: Option<&'a RoomPowerLevels>,
65	serialized: &'a Raw<AnySyncTimelineEvent>,
66	thread_root: Option<&'a EventId>,
67	related_events: Option<&'a Arc<RelatedEvents>>,
68}
69
70/// Called by timeline append_pdu.
71#[implement(super::Service)]
72#[tracing::instrument(name = "append", level = "debug", skip_all)]
73pub(crate) async fn append_pdu(&self, pdu_id: RawPduId, pdu: &Pdu) -> Result {
74	let push_target = self
75		.services
76		.state_cache
77		.active_local_users_in_room(pdu.room_id())
78		.map(ToOwned::to_owned)
79		.ready_filter(|user| *user != pdu.sender())
80		.filter_map(async |recipient_user| {
81			self.services
82				.users
83				.user_is_ignored(pdu.sender(), &recipient_user)
84				.await
85				.is_false()
86				.then_some(recipient_user)
87		})
88		.collect::<HashSet<_>>();
89
90	let power_levels = self
91		.services
92		.state_accessor
93		.get_power_levels(pdu.room_id())
94		.ok();
95
96	// Send generality
97	let (mut push_target, power_levels) = join(push_target, power_levels).boxed().await;
98
99	if *pdu.kind() == TimelineEventType::RoomMember
100		&& let Some(Ok(target_user_id)) = pdu.state_key().map(UserId::parse)
101		&& self
102			.services
103			.users
104			.is_active_local(&target_user_id)
105			.await
106		&& self.invite_notifiable(pdu, &target_user_id).await
107	{
108		push_target.insert(target_user_id);
109	}
110
111	if push_target.is_empty() {
112		return Ok(());
113	}
114
115	let serialized = pdu.to_format();
116	let (thread_root, related_events) =
117		join(self.services.threads.get_thread_id(pdu), self.related_events(pdu)).await;
118
119	let appended = Appended {
120		pdu_id: &pdu_id,
121		pdu,
122		power_levels: power_levels.as_ref(),
123		serialized: &serialized,
124		thread_root: thread_root.as_deref(),
125		related_events: related_events.as_ref(),
126	};
127
128	let _cork = self.db.db.cork();
129	for user in &push_target {
130		self.append_pdu_for_user(user, appended).await;
131	}
132
133	Ok(())
134}
135
136/// MSC4155: whether an invite may notify the user it names.
137///
138/// Every other membership transition notifies as before; only an invite the
139/// recipient ignores or blocks is withheld, matching what sync serves them.
140#[implement(super::Service)]
141async fn invite_notifiable(&self, pdu: &Pdu, user_id: &UserId) -> bool {
142	#[derive(Deserialize)]
143	struct Membership {
144		membership: MembershipState,
145	}
146
147	let is_invite = pdu
148		.get_content()
149		.is_ok_and(|content: Membership| content.membership == MembershipState::Invite);
150
151	!is_invite
152		|| self
153			.services
154			.users
155			.invite_permission(pdu.sender(), user_id)
156			.await
157			.eq(&InvitePermission::Allow)
158}
159
160#[implement(super::Service)]
161async fn append_pdu_for_user(
162	&self,
163	user: &UserId,
164	Appended {
165		pdu_id,
166		pdu,
167		power_levels,
168		serialized,
169		thread_root,
170		related_events,
171	}: Appended<'_>,
172) {
173	let ruleset = self.ruleset(user).await;
174	let actions = self
175		.get_actions(Evaluate {
176			user,
177			ruleset: &ruleset,
178			power_levels,
179			pdu: serialized,
180			room_id: pdu.room_id(),
181			related_events,
182		})
183		.await;
184
185	let notify = actions.iter().any(Action::should_notify);
186
187	let highlight = actions.iter().any(|action| {
188		matches!(action, Action::SetTweak(Tweak::Highlight(HighlightTweakValue::Yes)))
189	});
190
191	trace!(
192		%user,
193		event_id = %pdu.event_id(),
194		actions = %actions.len(),
195		notify,
196		highlight,
197		"Push rules evaluated",
198	);
199
200	// Mutually-exclusive partition: each notify (and each highlight)
201	// lands in either the room-level or thread bucket, never both.
202	let main_notify = (notify && thread_root.is_none())
203		.then_async(|| self.increment_notificationcount(pdu.room_id(), user));
204
205	let main_highlight = (highlight && thread_root.is_none())
206		.then_async(|| self.increment_highlightcount(pdu.room_id(), user));
207
208	let thread_notify = thread_root
209		.filter(|_| notify)
210		.map_async(|root| self.increment_thread_notificationcount(pdu.room_id(), user, root));
211
212	let thread_highlight = thread_root
213		.filter(|_| highlight)
214		.map_async(|root| self.increment_thread_highlightcount(pdu.room_id(), user, root));
215
216	join4(main_notify, thread_notify, main_highlight, thread_highlight).await;
217
218	if notify || highlight {
219		let id: PduId = (*pdu_id).into();
220		let notified = Notified {
221			ts: now_millis(),
222			sroomid: id.shortroomid,
223			tag: None,
224			actions: actions.into(),
225		};
226
227		if matches!(id.count, Count::Normal(_)) {
228			self.db
229				.useridcount_notification
230				.put((user, id.count.into_unsigned()), Json(notified));
231		}
232	}
233
234	// Email is built from the recorded rows, so only a recorded notification wakes it.
235	let mailable = notify && matches!(PduId::from(*pdu_id).count, Count::Normal(_));
236
237	if notify || highlight || self.services.config.push.everything {
238		self.keyed_pushers(user)
239			.ready_for_each(|(pushkey, pusher)| {
240				self.dispatch_push(user, pdu_id, pushkey, pusher, mailable);
241			})
242			.await;
243	}
244}
245
246/// The user's pushers by pushkey, each `None` when it cannot be decoded.
247///
248/// The pushkey comes from the row's key, so a pusher that cannot be decoded is
249/// still known by it.
250#[implement(super::Service)]
251fn keyed_pushers<'a>(
252	&'a self,
253	user: &'a UserId,
254) -> impl Stream<Item = (&'a str, Option<Pusher>)> + Send + 'a {
255	let prefix = (user, Interfix);
256
257	self.db
258		.senderkey_pusher
259		.stream_prefix(&prefix)
260		.ignore_err()
261		.map(|((_, pushkey), pusher): ((Ignore, &str), &[u8])| {
262			(pushkey, deserialize_from_slice(pusher).ok())
263		})
264}
265
266/// Hands one appended event to one of the user's pushers, by kind.
267///
268/// An email pusher wakes the email worker when there is a recorded notification
269/// to mail, and an HTTP pusher queues a push. A pusher that cannot be decoded
270/// is queued a push too, and its delivery reports the fault.
271#[implement(super::Service)]
272fn dispatch_push(
273	&self,
274	user: &UserId,
275	pdu_id: &RawPduId,
276	pushkey: &str,
277	pusher: Option<Pusher>,
278	mailable: bool,
279) {
280	match pusher.map(|Pusher { ids, kind, .. }| (kind, ids.pushkey)) {
281		| None => self.queue_push(user, pdu_id, pushkey.to_owned()),
282		| Some((PusherKind::Email(_), _)) if mailable => self.wake_email(user, pushkey),
283		| Some((PusherKind::Http(_), pushkey)) => self.queue_push(user, pdu_id, pushkey),
284		| Some(_) => {},
285	}
286}
287
288#[implement(super::Service)]
289fn queue_push(&self, user: &UserId, pdu_id: &RawPduId, pushkey: String) {
290	self.services
291		.sending
292		.send_pdu_push(pdu_id, user, pushkey)
293		.log_err(Level::TRACE)
294		.ok();
295}
296
297#[implement(super::Service)]
298async fn increment_notificationcount(&self, room_id: &RoomId, user_id: &UserId) {
299	let db = &self.db.userroomid_notificationcount;
300	let key = (room_id.to_owned(), user_id.to_owned());
301	let _lock = self.notification_increment_mutex.lock(&key).await;
302
303	increment(db, (user_id, room_id)).await;
304}
305
306#[implement(super::Service)]
307async fn increment_highlightcount(&self, room_id: &RoomId, user_id: &UserId) {
308	let db = &self.db.userroomid_highlightcount;
309	let key = (room_id.to_owned(), user_id.to_owned());
310	let _lock = self.highlight_increment_mutex.lock(&key).await;
311
312	increment(db, (user_id, room_id)).await;
313}
314
315#[implement(super::Service)]
316async fn increment_thread_notificationcount(
317	&self,
318	room_id: &RoomId,
319	user_id: &UserId,
320	thread_root: &EventId,
321) {
322	let db = &self.db.userroomid_notificationcount;
323	let key = (room_id.to_owned(), user_id.to_owned());
324	let _lock = self.notification_increment_mutex.lock(&key).await;
325
326	increment_thread(db, (user_id, room_id, thread_root)).await;
327}
328
329#[implement(super::Service)]
330async fn increment_thread_highlightcount(
331	&self,
332	room_id: &RoomId,
333	user_id: &UserId,
334	thread_root: &EventId,
335) {
336	let db = &self.db.userroomid_highlightcount;
337	let key = (room_id.to_owned(), user_id.to_owned());
338	let _lock = self.highlight_increment_mutex.lock(&key).await;
339
340	increment_thread(db, (user_id, room_id, thread_root)).await;
341}
342
343async fn increment(db: &Arc<Map>, key: (&UserId, &RoomId)) {
344	let old: u64 = db.qry(&key).await.deserialized().unwrap_or(0);
345	let new = old.saturating_add(1);
346	db.put(key, new);
347}
348
349async fn increment_thread(db: &Arc<Map>, key: (&UserId, &RoomId, &EventId)) {
350	let old: u64 = db.qry(&key).await.deserialized().unwrap_or(0);
351	let new = old.saturating_add(1);
352	db.put(key, new);
353}