Skip to main content

tuwunel_service/rooms/pdu_metadata/
references.rs

1use futures::{Stream, StreamExt, TryFutureExt};
2use ruma::{EventId, OwnedEventId, RoomId};
3use tuwunel_core::{
4	Result, implement, trace,
5	utils::{
6		stream::{BroadbandExt, ReadyExt, TryIgnore, WidebandExt},
7		u64_from_u8,
8	},
9};
10use tuwunel_database::Interfix;
11use tuwunel_matrix::{Event, Pdu, PduId};
12
13use super::{
14	ExtractRoomId, Service,
15	typed_relations::{Tag, prefix},
16};
17
18/// Cap on the `m.reference` bundle chunk; /relations is the paginated fallback.
19const BUNDLE_MAX: usize = 100;
20
21/// MSC2675/MSC3267: the event ids of `parent`'s `m.reference` children, oldest
22/// first, from the typed index, capped at `BUNDLE_MAX`. Empty when
23/// `parent` is redacted or unreferenced. The ids come from the index value (the
24/// child shorteventid) without loading the children, so the chunk is filtered
25/// for neither ignored users nor history visibility. The ignored-user posture
26/// matches the /relations endpoint, which also does not filter relation
27/// children by ignored sender; the history-visibility posture matches the
28/// thread and edit bundles and is less strict than /relations, which does
29/// filter children by visibility.
30#[implement(Service)]
31#[tracing::instrument(skip_all, level = "trace")]
32pub(super) async fn references(&self, parent: &Pdu) -> Vec<OwnedEventId> {
33	if parent.is_redacted() {
34		return Vec::new();
35	}
36
37	let Ok(parent_id) = self
38		.services
39		.timeline
40		.get_pdu_id(parent.event_id())
41		.map_ok(PduId::from)
42		.await
43	else {
44		return Vec::new();
45	};
46
47	self.referenced_children(parent_id)
48		.take(BUNDLE_MAX)
49		.collect()
50		.await
51}
52
53#[implement(Service)]
54fn referenced_children(&self, parent_id: PduId) -> impl Stream<Item = OwnedEventId> + Send + '_ {
55	let prefix = prefix(parent_id.shortroomid, parent_id.count, Tag::Reference);
56	let seek = prefix.clone();
57
58	self.db
59		.relatesto_typed
60		.raw_stream_from(seek.as_slice())
61		.ignore_err()
62		.ready_take_while(move |(key, _)| key.starts_with(&prefix))
63		.map(|(_, val)| u64_from_u8(val))
64		.wide_filter_map(async |short| {
65			self.services
66				.short
67				.get_eventid_from_short(short)
68				.await
69				.ok()
70		})
71}
72
73#[implement(Service)]
74#[tracing::instrument(skip_all, level = "debug")]
75pub fn mark_as_referenced<'a, I>(&self, room_id: &RoomId, event_ids: I)
76where
77	I: Iterator<Item = &'a EventId>,
78{
79	for event_id in event_ids {
80		let key = (room_id, event_id);
81
82		self.db.referencedevents.put_raw(key, []);
83	}
84}
85
86#[implement(Service)]
87#[tracing::instrument(skip(self), level = "debug", ret)]
88pub async fn is_event_referenced(&self, room_id: &RoomId, event_id: &EventId) -> bool {
89	let key = (room_id, event_id);
90
91	self.db.referencedevents.qry(&key).await.is_ok()
92}
93
94#[implement(Service)]
95#[tracing::instrument(skip(self), level = "debug")]
96pub fn mark_event_soft_failed(&self, event_id: &EventId) {
97	self.db.softfailedeventids.insert(event_id, []);
98}
99
100#[implement(Service)]
101#[tracing::instrument(skip(self), level = "debug", ret)]
102pub async fn is_event_soft_failed(&self, event_id: &EventId) -> bool {
103	self.db
104		.softfailedeventids
105		.get(event_id)
106		.await
107		.is_ok()
108}
109
110/// Clears the soft-fail markers belonging to a room.
111///
112/// Markers are keyed by event alone, so each is matched to the room named by
113/// its stored event, accepted or outlier. Unreadable events keep their markers.
114#[implement(Service)]
115#[tracing::instrument(skip(self), level = "debug")]
116pub async fn delete_all_soft_failed_for_room(&self, room_id: &RoomId) {
117	self.soft_failed_event_ids()
118		.broad_filter_map(async |event_id| {
119			self.services
120				.timeline
121				.get(&event_id)
122				.await
123				.is_ok_and(|event: ExtractRoomId| event.room_id == room_id)
124				.then_some(event_id)
125		})
126		.ready_for_each(|event_id| self.clear_event_soft_failed(&event_id))
127		.await;
128}
129
130/// Streams owned event IDs with soft-fail markers.
131///
132/// Each ID is copied before the database cursor advances.
133#[implement(Service)]
134pub fn soft_failed_event_ids(&self) -> impl Stream<Item = OwnedEventId> + Send + '_ {
135	self.db
136		.softfailedeventids
137		.keys()
138		.ignore_err()
139		.map(|event_id: &EventId| event_id.to_owned())
140}
141
142/// Clears one event's soft-fail marker.
143///
144/// A later processing attempt can evaluate the event again.
145#[implement(Service)]
146pub fn clear_event_soft_failed(&self, event_id: &EventId) {
147	self.db.softfailedeventids.remove(event_id);
148}
149
150#[implement(Service)]
151#[tracing::instrument(skip(self), level = "debug")]
152pub async fn delete_all_referenced_for_room(&self, room_id: &RoomId) -> Result {
153	let prefix = (room_id, Interfix);
154
155	self.db
156		.referencedevents
157		.keys_prefix_raw(&prefix)
158		.ignore_err()
159		.ready_for_each(|key| {
160			trace!(?key, "Removing key");
161			self.db.referencedevents.remove(key);
162		})
163		.await;
164
165	Ok(())
166}