tuwunel_service/rooms/pdu_metadata/
relations.rs1use 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
31type Checked = Option<(PduCount, Pdu)>;
36
37pub struct RelationQuery<'a> {
41 pub(crate) shortroomid: ShortRoomId,
43
44 pub(crate) target: PduCount,
46
47 pub(crate) from: Option<PduCount>,
49
50 pub(crate) dir: Direction,
52
53 pub(crate) user_id: Option<&'a UserId>,
55
56 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 | _ => {}, }
75}
76
77#[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#[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 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#[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#[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#[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#[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#[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#[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#[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}