Skip to main content

tuwunel_service/rooms/pdu_metadata/
relations.rs

1use futures::{
2	Stream, StreamExt, TryFutureExt, TryStreamExt,
3	future::{
4		Either::{Left, Right},
5		ready,
6	},
7};
8use ruma::{
9	EventId, OwnedUserId, UserId,
10	api::Direction,
11	events::{reaction::ReactionEventContent, relation::RelationType},
12};
13use tuwunel_core::{
14	Result,
15	arrayvec::ArrayVec,
16	implement, is_equal_to,
17	utils::{
18		result::NotFound,
19		stream::{ReadyExt, TryIgnore, TryReadyExt, TryWidebandExt},
20		u64_from_u8,
21	},
22};
23use tuwunel_database::keyval::Key;
24use tuwunel_matrix::{Event, Pdu, PduCount, PduId, RawPduId, event::RelationTypeEqual};
25
26use super::Service;
27use crate::{integrity::undecodable_as, rooms::short::ShortRoomId};
28
29type StartKey = ArrayVec<u8, 16>;
30
31/// One row of a checked relation walk.
32///
33/// It is a related event at its position, or `None` for an index key too short
34/// to hold a position or for a related event whose row does not decode.
35type Checked = Option<(PduCount, Pdu)>;
36
37/// Parameters controlling a relation-row query.
38///
39/// The row limit applies before event loading and filtering.
40pub struct RelationQuery<'a> {
41	/// Numeric room identifier containing the relation rows.
42	pub(crate) shortroomid: ShortRoomId,
43
44	/// Event position targeted by each relation row.
45	pub(crate) target: PduCount,
46
47	/// Optional exclusive cursor for the first relation row.
48	pub(crate) from: Option<PduCount>,
49
50	/// Direction in which relation rows are visited.
51	pub(crate) dir: Direction,
52
53	/// Requesting user, used to filter the unsigned fields private to a sender.
54	pub(crate) user_id: Option<&'a UserId>,
55
56	/// Maximum number of raw relation rows to visit.
57	pub(crate) limit: usize,
58}
59
60#[implement(Service)]
61#[tracing::instrument(skip(self, from, to), level = "debug")]
62pub fn add_relation(&self, from: PduCount, to: PduCount) {
63	const BUFSIZE: usize = size_of::<u64>() * 2;
64
65	match (from, to) {
66		| (PduCount::Normal(from), PduCount::Normal(to)) => {
67			let key: &[u64] = &[to, from];
68
69			self.db
70				.tofrom_relation
71				.aput_raw::<BUFSIZE, _, _>(key, []);
72		},
73		| _ => {}, // TODO: Relations with backfilled pdus
74	}
75}
76
77/// Query relations of an event to determine if matching any of the trailing
78/// arguments. When all criteria are None the mere presence of a relation causes
79/// this function to return true.
80#[implement(Service)]
81pub async fn event_has_relation(
82	&self,
83	event_id: &EventId,
84	user_id: Option<&UserId>,
85	rel_type: Option<&RelationType>,
86	key: Option<&str>,
87) -> bool {
88	let Ok(pdu_id) = self.services.timeline.get_pdu_id(event_id).await else {
89		return false;
90	};
91
92	self.has_relation(pdu_id.into(), user_id, rel_type, key)
93		.await
94}
95
96/// Query relations of an event by PduId to determine if matching any of the
97/// trailing arguments. When all criteria are None the mere presence of a
98/// relation causes this function to return true.
99#[implement(Service)]
100pub async fn has_relation(
101	&self,
102	target: PduId,
103	user_id: Option<&UserId>,
104	rel_type: Option<&RelationType>,
105	key: Option<&str>,
106) -> bool {
107	self.get_relations(target.shortroomid, target.count, None, Direction::Forward, None)
108		.ready_filter(|(_, pdu)| user_id.is_none_or(is_equal_to!(pdu.sender())))
109		.ready_filter(|(_, pdu)| {
110			debug_assert!(
111				key.is_none() || rel_type.is_none_or(is_equal_to!(&RelationType::Annotation)),
112				"key argument only applies to Annotation type relations."
113			);
114
115			// When key is supplied we don't need to double-parse the content here and
116			// below.
117			key.is_some() || rel_type.is_none_or(|rel_type| rel_type.relation_type_equal(&pdu))
118		})
119		.ready_filter(|(_, pdu)| {
120			key.is_none_or(|key| {
121				pdu.get_content()
122					.map(|content: ReactionEventContent| content.relates_to.key == key)
123					.unwrap_or(false)
124			})
125		})
126		.ready_any(|_| true)
127		.await
128}
129
130/// MSC3440 `related_by_*`: whether any event relates to `target` with a
131/// `rel_type` in `rel_types` and a `sender` in `senders`. An empty list is
132/// unconstrained on that axis; a single relating event must satisfy both.
133#[implement(Service)]
134pub async fn has_incoming_relation(
135	&self,
136	target: PduId,
137	senders: &[OwnedUserId],
138	rel_types: &[RelationType],
139) -> bool {
140	self.get_relations(target.shortroomid, target.count, None, Direction::Forward, None)
141		.ready_any(|(_, pdu)| {
142			let sender_matches =
143				senders.is_empty() || senders.iter().any(is_equal_to!(pdu.sender()));
144
145			let rel_type_matches = rel_types.is_empty()
146				|| rel_types
147					.iter()
148					.any(|rel_type| rel_type.relation_type_equal(&pdu));
149
150			sender_matches && rel_type_matches
151		})
152		.await
153}
154
155#[implement(Service)]
156pub fn get_relations<'a>(
157	&'a self,
158	shortroomid: ShortRoomId,
159	target: PduCount,
160	from: Option<PduCount>,
161	dir: Direction,
162	user_id: Option<&'a UserId>,
163) -> impl Stream<Item = (PduCount, Pdu)> + Send + '_ {
164	self.try_get_relations(shortroomid, target, from, dir, user_id)
165		.ignore_err()
166}
167
168/// Walks related events in the requested direction, preserving read failures.
169///
170/// Missing children are skipped; other load and transaction-ID errors are yielded.
171#[implement(Service)]
172pub fn try_get_relations<'a>(
173	&'a self,
174	shortroomid: ShortRoomId,
175	target: PduCount,
176	from: Option<PduCount>,
177	dir: Direction,
178	user_id: Option<&'a UserId>,
179) -> impl Stream<Item = Result<(PduCount, Pdu)>> + Send + '_ {
180	self.try_get_relations_limited(RelationQuery {
181		shortroomid,
182		target,
183		from,
184		dir,
185		user_id,
186		limit: usize::MAX,
187	})
188}
189
190/// Walks at most `limit` relation rows, preserving read failures.
191///
192/// The limit counts missing children before event loading and filtering.
193#[implement(Service)]
194pub fn try_get_relations_limited<'a>(
195	&'a self,
196	RelationQuery {
197		shortroomid,
198		target,
199		from,
200		dir,
201		user_id,
202		limit,
203	}: RelationQuery<'a>,
204) -> impl Stream<Item = Result<(PduCount, Pdu)>> + Send + '_ {
205	self.relation_counts(target, from, dir, limit)
206		.wide_and_then(move |count| self.related_pdu(user_id, shortroomid, count))
207		.ready_try_filter_map(Ok)
208}
209
210/// Walks the positions of at most `limit` events related to a target.
211///
212/// `from` is exclusive, and without one the walk starts at the end `dir` leads
213/// away from. A position is yielded whether or not its event is still stored,
214/// so `limit` counts index rows rather than loaded events.
215#[implement(Service)]
216pub fn relation_counts(
217	&self,
218	target: PduCount,
219	from: Option<PduCount>,
220	dir: Direction,
221	limit: usize,
222) -> impl Stream<Item = Result<PduCount>> + Send + '_ {
223	self.relation_keys(target, from, dir)
224		.take(limit)
225		.map_ok(|to_from| u64_from_u8(&to_from[8..16]))
226		.map_ok(PduCount::from_unsigned)
227}
228
229/// Walks every event related to a target, reading each index key fallibly.
230///
231/// It walks as [`Service::try_get_relations_limited`] does from the end `dir`
232/// leads away from, with no limit, except that a key under the target too short
233/// to hold a position comes back as `None` where that walk panics, and so does a
234/// child whose row a release build cannot decode. Missing children are skipped,
235/// and storage errors are yielded.
236#[implement(Service)]
237pub fn try_get_relations_checked(
238	&self,
239	shortroomid: ShortRoomId,
240	target: PduCount,
241	dir: Direction,
242) -> impl Stream<Item = Result<Checked>> + Send + '_ {
243	self.relation_keys(target, None, dir)
244		.map_ok(|to_from| {
245			to_from
246				.get(8..16)
247				.map(u64_from_u8)
248				.map(PduCount::from_unsigned)
249		})
250		.wide_and_then(move |count| match count {
251			| None => Left(ready(Ok(Some(None)))),
252			| Some(count) => Right(
253				self.related_pdu_checked(shortroomid, count)
254					.map_ok(|related| related.map(Some))
255					.or_else(|error| ready(undecodable_as(error, Some(None)))),
256			),
257		})
258		.ready_try_filter_map(Ok)
259}
260
261/// Loads a related event as `related_pdu` does for no user, decoding its row as
262/// a release build does.
263///
264/// A debug build of that function panics on a row holding a further record after
265/// the event's, beyond one trailing separator.
266#[implement(Service)]
267async fn related_pdu_checked(
268	&self,
269	shortroomid: ShortRoomId,
270	count: PduCount,
271) -> Result<Option<(PduCount, Pdu)>> {
272	let pdu_id: RawPduId = PduId { shortroomid, count }.into();
273
274	let pdu = self
275		.services
276		.timeline
277		.get_from_id_checked(&pdu_id)
278		.await
279		.optional()?
280		.map(|pdu: Pdu| (count, pdu.without_private_unless_sender(None)));
281
282	Ok(pdu)
283}
284
285/// Walks the index keys of the events related to a target.
286///
287/// `from` is exclusive, and without one the walk starts at the end `dir` leads
288/// away from. Each key begins with the target's count.
289#[implement(Service)]
290fn relation_keys(
291	&self,
292	target: PduCount,
293	from: Option<PduCount>,
294	dir: Direction,
295) -> impl Stream<Item = Result<Key<'_>>> + Send + '_ {
296	let target = target.to_be_bytes();
297	let from = from
298		.map(|from| from.saturating_inc(dir))
299		.unwrap_or_else(|| match dir {
300			| Direction::Backward => PduCount::max(),
301			| Direction::Forward => PduCount::default(),
302		})
303		.to_be_bytes();
304
305	let start: StartKey = target.into_iter().chain(from).collect();
306	let start = start.as_slice();
307
308	match dir {
309		| Direction::Backward => self
310			.db
311			.tofrom_relation
312			.rev_raw_keys_from(start)
313			.left_stream(),
314
315		| Direction::Forward => self
316			.db
317			.tofrom_relation
318			.raw_keys_from(start)
319			.right_stream(),
320	}
321	.ready_try_take_while(move |key| Ok(key.starts_with(&target)))
322}
323
324#[implement(Service)]
325async fn related_pdu(
326	&self,
327	user_id: Option<&UserId>,
328	shortroomid: ShortRoomId,
329	count: PduCount,
330) -> Result<Option<(PduCount, Pdu)>> {
331	let pdu_id: RawPduId = PduId { shortroomid, count }.into();
332
333	let pdu = self
334		.services
335		.timeline
336		.get_pdu_from_id(&pdu_id)
337		.await
338		.optional()?
339		.map(|pdu| (count, pdu.without_private_unless_sender(user_id)));
340
341	Ok(pdu)
342}